]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/lex.c
The previous update (and, embarassingly, the "nasal 1.0" release I
[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     {"...", TOK_ELLIPSIS},
45     {"?", TOK_QUESTION},
46     {"var", TOK_VAR},
47     {"+=", TOK_PLUSEQ},
48     {"-=", TOK_MINUSEQ},
49     {"*=", TOK_MULEQ},
50     {"/=", TOK_DIVEQ},
51     {"~=", TOK_CATEQ},
52     {"forindex", TOK_FORINDEX},
53 };
54
55 // Build a table of where each line ending is
56 static int* findLines(struct Parser* p)
57 {
58     char* buf = p->buf;
59     int sz = p->len/10 + 16;
60     int* lines = naParseAlloc(p, (sizeof(int) * sz));
61     int i, j, n=0;
62
63     for(i=0; i<p->len; i++) {
64         // Not a line ending at all
65         if(buf[i] != '\n' && buf[i] != '\r')
66             continue;
67
68         // Skip over the \r of a \r\n pair.
69         if(buf[i] == '\r' && (i+1)<p->len && buf[i+1] == '\n') {
70             continue;
71         }
72         // Reallocate if necessary
73         if(n == sz) {
74             int* nl;
75             sz *= 2;
76             nl = naParseAlloc(p, sizeof(int) * sz);
77             for(j=0; j<n; j++) nl[j] = lines[j];
78             lines = nl;
79         }
80         lines[n++] = i;
81     }
82     p->lines = lines;
83     p->nLines = n;
84     return lines;
85 }
86
87 // What line number is the index on?
88 static int getLine(struct Parser* p, int index)
89 {
90     int i;
91     for(i=0; i<p->nLines; i++)
92         if(p->lines[i] > index)
93             return (p->firstLine-1) + i+1;
94     return (p->firstLine-1) + p->nLines+1;
95 }
96
97 static void error(struct Parser* p, char* msg, int index)
98 {
99     naParseError(p, msg, getLine(p, index));
100 }
101
102 // End index (the newline character) of the given line
103 static int lineEnd(struct Parser* p, int line)
104 {
105     if(line > p->nLines) return p->len;
106     return p->lines[line-1];
107 }
108
109 static void newToken(struct Parser* p, int pos, int type,
110                      char* str, int slen, double num)
111 {
112     struct Token* tok;
113
114     tok = naParseAlloc(p, sizeof(struct Token));
115     tok->type = type;
116     tok->line = getLine(p, pos);
117     tok->str = str;
118     tok->strlen = slen;
119     tok->num = num;
120     tok->parent = &p->tree;
121     tok->next = 0;
122     tok->prev = p->tree.lastChild;
123     tok->children = 0;
124     tok->lastChild = 0;
125
126     // Context sensitivity hack: a "-" following a binary operator of
127     // higher precedence (MUL and DIV, basically) must be a unary
128     // negation.  Needed to get precedence right in the parser for
129     // expressiong like "a * -2"
130     if(type == TOK_MINUS && tok->prev)
131         if(tok->prev->type == TOK_MUL || tok->prev->type == TOK_DIV)
132             tok->type = type = TOK_NEG;
133
134     if(!p->tree.children) p->tree.children = tok;
135     if(p->tree.lastChild) p->tree.lastChild->next = tok;
136     p->tree.lastChild = tok;
137 }
138
139 static int hex(char c)
140 {
141     if(c >= '0' && c <= '9') return c - '0';
142     if(c >= 'A' && c <= 'F') return c - 'A' + 10;
143     if(c >= 'a' && c <= 'f') return c - 'a' + 10;
144     return -1;
145 }
146
147 static int hexc(char c, struct Parser* p, int index)
148 {
149     int n = hex(c);
150     if(n < 0) error(p, "bad hex constant", index);
151     return n;
152 }
153
154 // Escape and returns a single backslashed expression in a single
155 // quoted string.  Trivial, just escape \' and leave everything else
156 // alone.
157 static void sqEscape(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     if(buf[1] == '\'') {
162         *cOut = '\'';
163         *eatenOut = 2;
164     } else {
165         *cOut = '\\';
166         *eatenOut = 1;
167     }
168 }
169
170 // Ditto, but more complicated for double quotes.
171 static void dqEscape(char* buf, int len, int index, struct Parser* p,
172                      char* cOut, int* eatenOut)
173 {
174     if(len < 2) error(p, "unterminated string", index);
175     *eatenOut = 2;
176     switch(buf[1]) {
177     case '"': *cOut = '"'; break;
178     case 'r': *cOut = '\r'; break;
179     case 'n': *cOut = '\n'; break;
180     case 't': *cOut = '\t'; break;
181     case '\\': *cOut = '\\'; break;
182     case 'x':
183         if(len < 4) error(p, "unterminated string", index);
184         *cOut = (char)((hexc(buf[2], p, index)<<4) | hexc(buf[3], p, index));
185         *eatenOut = 4;
186         break;
187     default:
188         // Unhandled, put the backslash back
189         *cOut = '\\';
190         *eatenOut = 1;
191     }
192 }
193
194 // FIXME: should handle UTF8 too
195 static void charLiteral(struct Parser* p, int index, char* s, int len)
196 {
197     if(len != 1) error(p, "character constant not single character", index);
198     newToken(p, index, TOK_LITERAL, 0, 0, *s);
199 }
200
201 // Read in a string literal
202 static int lexStringLiteral(struct Parser* p, int index, char q)
203 {
204     int i, j, len, iteration;
205     char* out = 0;
206     char* buf = p->buf;
207
208     for(iteration = 0; iteration<2; iteration++) {
209         i = index+1;
210         j = len = 0;
211         while(i < p->len) {
212             char c = buf[i];
213             int eaten = 1;
214             if(c == q) break;
215             if(c == '\\') {
216                 if(q == '\'') sqEscape(buf+i, p->len-i, i, p, &c, &eaten);
217                 else          dqEscape(buf+i, p->len-i, i, p, &c, &eaten);
218             }
219             if(iteration == 1) out[j++] = c;
220             i += eaten;
221             len++;
222         }
223         // Finished stage one -- allocate the buffer for stage two
224         if(iteration == 0) out = naParseAlloc(p, len);
225     }
226     if(q == '`') charLiteral(p, index, out, len);
227     else         newToken(p, index, TOK_LITERAL, out, len, 0);
228     return i+1;
229 }
230
231 static int lexHexLiteral(struct Parser* p, int index)
232 {
233     int nib, i = index;
234     double d = 0;
235     while(i < p->len && (nib = hex(p->buf[i])) >= 0) {
236         d = d*16 + nib;
237         i++;
238     }
239     newToken(p, index, TOK_LITERAL, 0, 0, d);
240     return i;
241 }
242
243 static int lexNumLiteral(struct Parser* p, int index)
244 {
245     int len = p->len, i = index;
246     unsigned char* buf = (unsigned char*)p->buf;
247     double d;
248
249     if(i+1<len && buf[i+1] == 'x') return lexHexLiteral(p, index+2);
250
251     while(i<len && buf[i] >= '0' && buf[i] <= '9') i++;
252     if(i<len && buf[i] == '.') {
253         i++;
254         while(i<len && buf[i] >= '0' && buf[i] <= '9') i++;
255     }
256     if(i<len && (buf[i] == 'e' || buf[i] == 'E')) {
257         i++;
258         if(i<len
259            && (buf[i] == '-' || buf[i] == '+')
260            && (i+1<len && buf[i+1] >= '0' && buf[i+1] <= '9')) i++;
261         while(i<len && buf[i] >= '0' && buf[i] <= '9') i++;
262     }
263     naStr_parsenum(p->buf + index, i - index, &d);
264     newToken(p, index, TOK_LITERAL, 0, 0, d);
265     return i;
266 }
267
268 static int trySymbol(struct Parser* p, int start)
269 {
270     int i = start;
271     while((i < p->len) &&
272           ((p->buf[i] == '_') ||
273            (p->buf[i] >= 'A' && p->buf[i] <= 'Z') ||
274            (p->buf[i] >= 'a' && p->buf[i] <= 'z') ||
275            (p->buf[i] >= '0' && p->buf[i] <= '9')))
276     { i++; }
277     return i-start;
278 }
279
280 // Returns the length of lexeme l if the buffer prefix matches, or
281 // else zero.
282 static int matchLexeme(char* buf, int len, char* l)
283 {
284     int i;
285     for(i=0; i<len; i++) {
286         if(l[i] == 0)      return i;
287         if(l[i] != buf[i]) return 0;
288     }
289     // Ran out of buffer.  This is still OK if we're also at the end
290     // of the lexeme.
291     if(l[i] == 0) return i;
292     return 0;
293 }
294
295 // This is dumb and algorithmically slow.  It would be much more
296 // elegant to sort and binary search the lexeme list, but that's a lot
297 // more code and this really isn't very slow in practice; it checks
298 // every byte of every lexeme for each input byte.  There are less
299 // than 100 bytes of lexemes in the grammar.  Returns the number of
300 // bytes in the lexeme read (or zero if none was recognized)
301 static int tryLexemes(struct Parser* p, int index, int* lexemeOut)
302 {
303     int i, n, best, bestIndex=-1;
304     char* start = p->buf + index;
305     int len = p->len - index;
306
307     n = sizeof(LEXEMES) / sizeof(struct Lexeme);
308     best = 0;
309     for(i=0; i<n; i++) {
310         int l = matchLexeme(start, len, LEXEMES[i].str);
311         if(l > best) {
312             best = l;
313             bestIndex = i;
314         }
315     }
316     if(best > 0) *lexemeOut = bestIndex;
317     return best;
318 }
319
320 void naLex(struct Parser* p)
321 {
322     int i = 0;
323     findLines(p);
324     while(i<p->len) {
325         char c = p->buf[i];
326
327         // Whitespace, comments and string literals have obvious
328         // markers and can be handled by a switch:
329         int handled = 1;
330         switch(c) {
331         case ' ': case '\t': case '\n': case '\r': case '\f': case '\v':
332             i++;
333             break;
334         case '#':
335             i = lineEnd(p, getLine(p, i));
336             break;
337         case '\'': case '"': case '`':
338             i = lexStringLiteral(p, i, c);
339             break;
340         default:
341             if(c >= '0' && c <= '9') i = lexNumLiteral(p, i);
342             else handled = 0;
343         }
344
345         // Lexemes and symbols are a little more complicated.  Pick
346         // the longest one that matches.  Since some lexemes look like
347         // symbols (e.g. "or") they need a higher precedence, but we
348         // don't want a lexeme match to clobber the beginning of a
349         // symbol (e.g. "orchid").  If neither match, we have a bad
350         // character in the mix.
351         if(!handled) {
352             int symlen=0, lexlen=0, lexeme=-1;
353             lexlen = tryLexemes(p, i, &lexeme);
354             if((c>='A' && c<='Z') || (c>='a' && c<='z') || (c=='_'))
355                 symlen = trySymbol(p, i);
356             if(lexlen && lexlen >= symlen) {
357                 newToken(p, i, LEXEMES[lexeme].tok, 0, 0, 0);
358                 i += lexlen;
359             } else if(symlen) {
360                 newToken(p, i, TOK_SYMBOL, p->buf+i, symlen, 0);
361                 i += symlen;
362             } else {
363                 error(p, "illegal character", i);
364             }
365         }
366     }
367 }