]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/lex.c
Clamp pitch values rather than just dumping an error message.
[simgear.git] / simgear / nasal / lex.c
1 #include "parse.h"
2
3 // Static table of recognized lexemes in the language
4 struct Lexeme {
5     char* str;
6     int   tok;
7 } LEXEMES[] = {
8     {"and", TOK_AND},
9     {"or",  TOK_OR},
10     {"!",   TOK_NOT},
11     {"(", TOK_LPAR},
12     {")", TOK_RPAR},
13     {"[", TOK_LBRA},
14     {"]", TOK_RBRA},
15     {"{", TOK_LCURL},
16     {"}", TOK_RCURL},
17     {"*", TOK_MUL},
18     {"+", TOK_PLUS},
19     {"-", TOK_MINUS},
20     {"/", TOK_DIV},
21     {"~", TOK_CAT},
22     {":", TOK_COLON},
23     {".", TOK_DOT},
24     {",", TOK_COMMA},
25     {";", TOK_SEMI},
26     {"=", TOK_ASSIGN},
27     {"<",  TOK_LT},
28     {"<=", TOK_LTE},
29     {"==", TOK_EQ},
30     {"!=", TOK_NEQ},
31     {">",  TOK_GT},
32     {">=", TOK_GTE},
33     {"nil", TOK_NIL},
34     {"if",    TOK_IF},
35     {"elsif", TOK_ELSIF},
36     {"else",  TOK_ELSE},
37     {"for",     TOK_FOR},
38     {"foreach", TOK_FOREACH},
39     {"while",   TOK_WHILE},
40     {"return",   TOK_RETURN},
41     {"break",    TOK_BREAK},
42     {"continue", TOK_CONTINUE},
43     {"func", TOK_FUNC}
44 };
45
46 // Build a table of where each line ending is
47 static int* findLines(struct Parser* p)
48 {
49     char* buf = p->buf;
50     int sz = p->len/10 + 16;
51     int* lines = naParseAlloc(p, (sizeof(int) * sz));
52     int i, j, n=0;
53
54     for(i=0; i<p->len; i++) {
55         // Not a line ending at all
56         if(buf[i] != '\n' && buf[i] != '\r')
57             continue;
58
59         // Skip over the \r of a \r\n pair.
60         if(buf[i] == '\r' && (i+1)<p->len && buf[i+1] == '\n') {
61             continue;
62         }
63         // Reallocate if necessary
64         if(n == sz) {
65             int* nl;
66             sz *= 2;
67             nl = naParseAlloc(p, sizeof(int) * sz);
68             for(j=0; j<n; j++) nl[j] = lines[j];
69             lines = nl;
70         }
71         lines[n++] = i;
72     }
73     p->lines = lines;
74     p->nLines = n;
75     return lines;
76 }
77
78 // What line number is the index on?
79 static int getLine(struct Parser* p, int index)
80 {
81     int i;
82     for(i=0; i<p->nLines; i++)
83         if(p->lines[i] > index)
84             return (p->firstLine-1) + i+1;
85     return (p->firstLine-1) + p->nLines+1;
86 }
87
88 static void error(struct Parser* p, char* msg, int index)
89 {
90     naParseError(p, msg, getLine(p, index));
91 }
92
93 // End index (the newline character) of the given line
94 static int lineEnd(struct Parser* p, int line)
95 {
96     if(line > p->nLines) return p->len;
97     return p->lines[line-1];
98 }
99
100 static void newToken(struct Parser* p, int pos, int type,
101                      char* str, int slen, double num)
102 {
103     struct Token* tok;
104
105     tok = naParseAlloc(p, sizeof(struct Token));
106     tok->type = type;
107     tok->line = getLine(p, pos);
108     tok->str = str;
109     tok->strlen = slen;
110     tok->num = num;
111     tok->parent = &p->tree;
112     tok->next = 0;
113     tok->prev = p->tree.lastChild;
114     tok->children = 0;
115     tok->lastChild = 0;
116
117     // Context sensitivity hack: a "-" following a binary operator of
118     // higher precedence (MUL and DIV, basically) must be a unary
119     // negation.  Needed to get precedence right in the parser for
120     // expressiong like "a * -2"
121     if(type == TOK_MINUS && tok->prev)
122         if(tok->prev->type == TOK_MUL || tok->prev->type == TOK_DIV)
123             tok->type = type = TOK_NEG;
124
125     if(!p->tree.children) p->tree.children = tok;
126     if(p->tree.lastChild) p->tree.lastChild->next = tok;
127     p->tree.lastChild = tok;
128 }
129
130 // Parse a hex nibble
131 static int hexc(char c, struct Parser* p, int index)
132 {
133     if(c >= '0' && c <= '9') return c - '0';
134     if(c >= 'A' && c <= 'F') return c - 'A' + 10;
135     if(c >= 'a' && c <= 'f') return c - 'a' + 10;
136     error(p, "bad hex constant", index);
137     return 0;
138 }
139
140 // Escape and returns a single backslashed expression in a single
141 // quoted string.  Trivial, just escape \' and leave everything else
142 // alone.
143 static void sqEscape(char* buf, int len, int index, struct Parser* p,
144                      char* cOut, int* eatenOut)
145 {
146     if(len < 2) error(p, "unterminated string", index);
147     if(buf[1] == '\'') {
148         *cOut = '\'';
149         *eatenOut = 2;
150     } else {
151         *cOut = '\\';
152         *eatenOut = 1;
153     }
154 }
155
156 // Ditto, but more complicated for double quotes.
157 static void dqEscape(char* buf, int len, int index, struct Parser* p,
158                      char* cOut, int* eatenOut)
159 {
160     if(len < 2) error(p, "unterminated string", index);
161     *eatenOut = 2;
162     switch(buf[1]) {
163     case '"': *cOut = '"'; break;
164     case 'r': *cOut = '\r'; break;
165     case 'n': *cOut = '\n'; break;
166     case 't': *cOut = '\t'; break;
167     case '\\': *cOut = '\\'; break;
168     case 'x':
169         if(len < 4) error(p, "unterminated string", index);
170         *cOut = (char)((hexc(buf[2], p, index)<<4) | hexc(buf[3], p, index));
171         *eatenOut = 4;
172         break;
173     default:
174         // Unhandled, put the backslash back
175         *cOut = '\\';
176         *eatenOut = 1;
177     }
178 }
179
180 // Read in a string literal
181 static int lexStringLiteral(struct Parser* p, int index, int singleQuote)
182 {
183     int i, j, len, iteration;
184     char* out = 0;
185     char* buf = p->buf;
186     char endMark = singleQuote ? '\'' : '"';
187
188     for(iteration = 0; iteration<2; iteration++) {
189         i = index+1;
190         j = len = 0;
191         while(i < p->len) {
192             char c = buf[i];
193             int eaten = 1;
194             if(c == endMark)
195                 break;
196             if(c == '\\') {
197                 if(singleQuote) sqEscape(buf+i, p->len-i, i, p, &c, &eaten);
198                 else            dqEscape(buf+i, p->len-i, i, p, &c, &eaten);
199             }
200             if(iteration == 1) out[j++] = c;
201             i += eaten;
202             len++;
203         }
204         // Finished stage one -- allocate the buffer for stage two
205         if(iteration == 0) out = naParseAlloc(p, len);
206     }
207     newToken(p, index, TOK_LITERAL, out, len, 0);
208     return i+1;
209 }
210
211 static int lexNumLiteral(struct Parser* p, int index)
212 {
213     int len = p->len, i = index;
214     unsigned char* buf = p->buf;
215     double d;
216
217     while(i<len && buf[i] >= '0' && buf[i] <= '9') i++;
218     if(i<len && buf[i] == '.') {
219         i++;
220         while(i<len && buf[i] >= '0' && buf[i] <= '9') i++;
221     }
222     if(i<len && (buf[i] == 'e' || buf[i] == 'E')) {
223         i++;
224         if(i<len
225            && (buf[i] == '-' || buf[i] == '+')
226            && (i+1<len && buf[i+1] >= '0' && buf[i+1] <= '9')) i++;
227         while(i<len && buf[i] >= '0' && buf[i] <= '9') i++;
228     }
229     naStr_parsenum(p->buf + index, i - index, &d);
230     newToken(p, index, TOK_LITERAL, 0, 0, d);
231     return i;
232 }
233
234 static int trySymbol(struct Parser* p, int start)
235 {
236     int i = start;
237     while((i < p->len) &&
238           ((p->buf[i] == '_') ||
239            (p->buf[i] >= 'A' && p->buf[i] <= 'Z') ||
240            (p->buf[i] >= 'a' && p->buf[i] <= 'z') ||
241            (p->buf[i] >= '0' && p->buf[i] <= '9')))
242     { i++; }
243     return i-start;
244 }
245
246 // Returns the length of lexeme l if the buffer prefix matches, or
247 // else zero.
248 static int matchLexeme(char* buf, int len, char* l)
249 {
250     int i;
251     for(i=0; i<len; i++) {
252         if(l[i] == 0)      return i;
253         if(l[i] != buf[i]) return 0;
254     }
255     // Ran out of buffer.  This is still OK if we're also at the end
256     // of the lexeme.
257     if(l[i] == 0) return i;
258     return 0;
259 }
260
261 // This is dumb and algorithmically slow.  It would be much more
262 // elegant to sort and binary search the lexeme list, but that's a lot
263 // more code and this really isn't very slow in practice; it checks
264 // every byte of every lexeme for each input byte.  There are less
265 // than 100 bytes of lexemes in the grammar.  Returns the number of
266 // bytes in the lexeme read (or zero if none was recognized)
267 static int tryLexemes(struct Parser* p, int index, int* lexemeOut)
268 {
269     int i, n, best, bestIndex=-1;
270     char* start = p->buf + index;
271     int len = p->len - index;
272
273     n = sizeof(LEXEMES) / sizeof(struct Lexeme);
274     best = 0;
275     for(i=0; i<n; i++) {
276         int l = matchLexeme(start, len, LEXEMES[i].str);
277         if(l > best) {
278             best = l;
279             bestIndex = i;
280         }
281     }
282     if(best > 0) *lexemeOut = bestIndex;
283     return best;
284 }
285
286 void naLex(struct Parser* p)
287 {
288     int i = 0;
289     findLines(p);
290     while(i<p->len) {
291         char c = p->buf[i];
292
293         // Whitespace, comments and string literals have obvious
294         // markers and can be handled by a switch:
295         int handled = 1;
296         switch(c) {
297         case ' ': case '\t': case '\n': case '\r': case '\f': case '\v':
298             i++;
299             break;
300         case '#':
301             i = lineEnd(p, getLine(p, i));
302             break;
303         case '\'': case '"':
304             i = lexStringLiteral(p, i, (c=='"' ? 0 : 1));
305             break;
306         default:
307             if(c >= '0' && c <= '9') i = lexNumLiteral(p, i);
308             else                     handled = 0;
309         }
310
311         // Lexemes and symbols are a little more complicated.  Pick
312         // the longest one that matches.  Since some lexemes look like
313         // symbols (e.g. "or") they need a higher precedence, but we
314         // don't want a lexeme match to clobber the beginning of a
315         // symbol (e.g. "orchid").  If neither match, we have a bad
316         // character in the mix.
317         if(!handled) {
318             int symlen=0, lexlen=0, lexeme;
319             lexlen = tryLexemes(p, i, &lexeme);
320             if((c>='A' && c<='Z') || (c>='a' && c<='z') || (c=='_'))
321                 symlen = trySymbol(p, i);
322             if(lexlen && lexlen >= symlen) {
323                 newToken(p, i, LEXEMES[lexeme].tok, 0, 0, 0);
324                 i += lexlen;
325             } else if(symlen) {
326                 newToken(p, i, TOK_SYMBOL, p->buf+i, symlen, 0);
327                 i += symlen;
328             } else {
329                 error(p, "illegal character", i);
330             }
331         }
332     }
333 }