]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/lex.c
Melchior FRANZ:
[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 // Parse a hex nibble
140 static int hexc(char c, struct Parser* p, int index)
141 {
142     if(c >= '0' && c <= '9') return c - '0';
143     if(c >= 'A' && c <= 'F') return c - 'A' + 10;
144     if(c >= 'a' && c <= 'f') return c - 'a' + 10;
145     error(p, "bad hex constant", index);
146     return 0;
147 }
148
149 // Escape and returns a single backslashed expression in a single
150 // quoted string.  Trivial, just escape \' and leave everything else
151 // alone.
152 static void sqEscape(char* buf, int len, int index, struct Parser* p,
153                      char* cOut, int* eatenOut)
154 {
155     if(len < 2) error(p, "unterminated string", index);
156     if(buf[1] == '\'') {
157         *cOut = '\'';
158         *eatenOut = 2;
159     } else {
160         *cOut = '\\';
161         *eatenOut = 1;
162     }
163 }
164
165 // Ditto, but more complicated for double quotes.
166 static void dqEscape(char* buf, int len, int index, struct Parser* p,
167                      char* cOut, int* eatenOut)
168 {
169     if(len < 2) error(p, "unterminated string", index);
170     *eatenOut = 2;
171     switch(buf[1]) {
172     case '"': *cOut = '"'; break;
173     case 'r': *cOut = '\r'; break;
174     case 'n': *cOut = '\n'; break;
175     case 't': *cOut = '\t'; break;
176     case '\\': *cOut = '\\'; break;
177     case 'x':
178         if(len < 4) error(p, "unterminated string", index);
179         *cOut = (char)((hexc(buf[2], p, index)<<4) | hexc(buf[3], p, index));
180         *eatenOut = 4;
181         break;
182     default:
183         // Unhandled, put the backslash back
184         *cOut = '\\';
185         *eatenOut = 1;
186     }
187 }
188
189 // Read in a string literal
190 static int lexStringLiteral(struct Parser* p, int index, int singleQuote)
191 {
192     int i, j, len, iteration;
193     char* out = 0;
194     char* buf = p->buf;
195     char endMark = singleQuote ? '\'' : '"';
196
197     for(iteration = 0; iteration<2; iteration++) {
198         i = index+1;
199         j = len = 0;
200         while(i < p->len) {
201             char c = buf[i];
202             int eaten = 1;
203             if(c == endMark)
204                 break;
205             if(c == '\\') {
206                 if(singleQuote) sqEscape(buf+i, p->len-i, i, p, &c, &eaten);
207                 else            dqEscape(buf+i, p->len-i, i, p, &c, &eaten);
208             }
209             if(iteration == 1) out[j++] = c;
210             i += eaten;
211             len++;
212         }
213         // Finished stage one -- allocate the buffer for stage two
214         if(iteration == 0) out = naParseAlloc(p, len);
215     }
216     newToken(p, index, TOK_LITERAL, out, len, 0);
217     return i+1;
218 }
219
220 static int lexNumLiteral(struct Parser* p, int index)
221 {
222     int len = p->len, i = index;
223     unsigned char* buf = p->buf;
224     double d;
225
226     while(i<len && buf[i] >= '0' && buf[i] <= '9') i++;
227     if(i<len && buf[i] == '.') {
228         i++;
229         while(i<len && buf[i] >= '0' && buf[i] <= '9') i++;
230     }
231     if(i<len && (buf[i] == 'e' || buf[i] == 'E')) {
232         i++;
233         if(i<len
234            && (buf[i] == '-' || buf[i] == '+')
235            && (i+1<len && buf[i+1] >= '0' && buf[i+1] <= '9')) i++;
236         while(i<len && buf[i] >= '0' && buf[i] <= '9') i++;
237     }
238     naStr_parsenum(p->buf + index, i - index, &d);
239     newToken(p, index, TOK_LITERAL, 0, 0, d);
240     return i;
241 }
242
243 static int trySymbol(struct Parser* p, int start)
244 {
245     int i = start;
246     while((i < p->len) &&
247           ((p->buf[i] == '_') ||
248            (p->buf[i] >= 'A' && p->buf[i] <= 'Z') ||
249            (p->buf[i] >= 'a' && p->buf[i] <= 'z') ||
250            (p->buf[i] >= '0' && p->buf[i] <= '9')))
251     { i++; }
252     return i-start;
253 }
254
255 // Returns the length of lexeme l if the buffer prefix matches, or
256 // else zero.
257 static int matchLexeme(char* buf, int len, char* l)
258 {
259     int i;
260     for(i=0; i<len; i++) {
261         if(l[i] == 0)      return i;
262         if(l[i] != buf[i]) return 0;
263     }
264     // Ran out of buffer.  This is still OK if we're also at the end
265     // of the lexeme.
266     if(l[i] == 0) return i;
267     return 0;
268 }
269
270 // This is dumb and algorithmically slow.  It would be much more
271 // elegant to sort and binary search the lexeme list, but that's a lot
272 // more code and this really isn't very slow in practice; it checks
273 // every byte of every lexeme for each input byte.  There are less
274 // than 100 bytes of lexemes in the grammar.  Returns the number of
275 // bytes in the lexeme read (or zero if none was recognized)
276 static int tryLexemes(struct Parser* p, int index, int* lexemeOut)
277 {
278     int i, n, best, bestIndex=-1;
279     char* start = p->buf + index;
280     int len = p->len - index;
281
282     n = sizeof(LEXEMES) / sizeof(struct Lexeme);
283     best = 0;
284     for(i=0; i<n; i++) {
285         int l = matchLexeme(start, len, LEXEMES[i].str);
286         if(l > best) {
287             best = l;
288             bestIndex = i;
289         }
290     }
291     if(best > 0) *lexemeOut = bestIndex;
292     return best;
293 }
294
295 void naLex(struct Parser* p)
296 {
297     int i = 0;
298     findLines(p);
299     while(i<p->len) {
300         char c = p->buf[i];
301
302         // Whitespace, comments and string literals have obvious
303         // markers and can be handled by a switch:
304         int handled = 1;
305         switch(c) {
306         case ' ': case '\t': case '\n': case '\r': case '\f': case '\v':
307             i++;
308             break;
309         case '#':
310             i = lineEnd(p, getLine(p, i));
311             break;
312         case '\'': case '"':
313             i = lexStringLiteral(p, i, (c=='"' ? 0 : 1));
314             break;
315         default:
316             if(c >= '0' && c <= '9') i = lexNumLiteral(p, i);
317             else                     handled = 0;
318         }
319
320         // Lexemes and symbols are a little more complicated.  Pick
321         // the longest one that matches.  Since some lexemes look like
322         // symbols (e.g. "or") they need a higher precedence, but we
323         // don't want a lexeme match to clobber the beginning of a
324         // symbol (e.g. "orchid").  If neither match, we have a bad
325         // character in the mix.
326         if(!handled) {
327             int symlen=0, lexlen=0, lexeme;
328             lexlen = tryLexemes(p, i, &lexeme);
329             if((c>='A' && c<='Z') || (c>='a' && c<='z') || (c=='_'))
330                 symlen = trySymbol(p, i);
331             if(lexlen && lexlen >= symlen) {
332                 newToken(p, i, LEXEMES[lexeme].tok, 0, 0, 0);
333                 i += lexlen;
334             } else if(symlen) {
335                 newToken(p, i, TOK_SYMBOL, p->buf+i, symlen, 0);
336                 i += symlen;
337             } else {
338                 error(p, "illegal character", i);
339             }
340         }
341     }
342 }