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