xref: /netbsd-src/external/mit/lua/dist/src/llex.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: llex.c,v 1.11 2017/04/26 13:17:33 mbalmer Exp $	*/
2 
3 /*
4 ** Id: llex.c,v 2.96 2016/05/02 14:02:12 roberto Exp
5 ** Lexical Analyzer
6 ** See Copyright Notice in lua.h
7 */
8 
9 #define llex_c
10 #define LUA_CORE
11 
12 #include "lprefix.h"
13 
14 
15 #ifndef _KERNEL
16 #include <locale.h>
17 #include <string.h>
18 #endif /* _KERNEL */
19 
20 #include "lua.h"
21 
22 #include "lctype.h"
23 #include "ldebug.h"
24 #include "ldo.h"
25 #include "lgc.h"
26 #include "llex.h"
27 #include "lobject.h"
28 #include "lparser.h"
29 #include "lstate.h"
30 #include "lstring.h"
31 #include "ltable.h"
32 #include "lzio.h"
33 
34 
35 
36 #define next(ls) (ls->current = zgetc(ls->z))
37 
38 
39 
40 #define currIsNewline(ls)	(ls->current == '\n' || ls->current == '\r')
41 
42 
43 /* ORDER RESERVED */
44 static const char *const luaX_tokens [] = {
45     "and", "break", "do", "else", "elseif",
46     "end", "false", "for", "function", "goto", "if",
47     "in", "local", "nil", "not", "or", "repeat",
48     "return", "then", "true", "until", "while",
49     "//", "..", "...", "==", ">=", "<=", "~=",
50     "<<", ">>", "::", "<eof>",
51     "<number>", "<integer>", "<name>", "<string>"
52 };
53 
54 
55 #define save_and_next(ls) (save(ls, ls->current), next(ls))
56 
57 
58 static l_noret lexerror (LexState *ls, const char *msg, int token);
59 
60 
61 static void save (LexState *ls, int c) {
62   Mbuffer *b = ls->buff;
63   if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {
64     size_t newsize;
65     if (luaZ_sizebuffer(b) >= MAX_SIZE/2)
66       lexerror(ls, "lexical element too long", 0);
67     newsize = luaZ_sizebuffer(b) * 2;
68     luaZ_resizebuffer(ls->L, b, newsize);
69   }
70   b->buffer[luaZ_bufflen(b)++] = cast(char, c);
71 }
72 
73 
74 void luaX_init (lua_State *L) {
75   int i;
76   TString *e = luaS_newliteral(L, LUA_ENV);  /* create env name */
77   luaC_fix(L, obj2gco(e));  /* never collect this name */
78   for (i=0; i<NUM_RESERVED; i++) {
79     TString *ts = luaS_new(L, luaX_tokens[i]);
80     luaC_fix(L, obj2gco(ts));  /* reserved words are never collected */
81     ts->extra = cast_byte(i+1);  /* reserved word */
82   }
83 }
84 
85 
86 const char *luaX_token2str (LexState *ls, int token) {
87   if (token < FIRST_RESERVED) {  /* single-byte symbols? */
88     lua_assert(token == cast_uchar(token));
89     return luaO_pushfstring(ls->L, "'%c'", token);
90   }
91   else {
92     const char *s = luaX_tokens[token - FIRST_RESERVED];
93     if (token < TK_EOS)  /* fixed format (symbols and reserved words)? */
94       return luaO_pushfstring(ls->L, "'%s'", s);
95     else  /* names, strings, and numerals */
96       return s;
97   }
98 }
99 
100 
101 static const char *txtToken (LexState *ls, int token) {
102   switch (token) {
103     case TK_NAME: case TK_STRING:
104 #ifndef _KERNEL
105     case TK_FLT: case TK_INT:
106 #else /* _KERNEL */
107     case TK_INT:
108 #endif /* _KERNEL */
109       save(ls, '\0');
110       return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff));
111     default:
112       return luaX_token2str(ls, token);
113   }
114 }
115 
116 
117 static l_noret lexerror (LexState *ls, const char *msg, int token) {
118   msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber);
119   if (token)
120     luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token));
121   luaD_throw(ls->L, LUA_ERRSYNTAX);
122 }
123 
124 
125 l_noret luaX_syntaxerror (LexState *ls, const char *msg) {
126   lexerror(ls, msg, ls->t.token);
127 }
128 
129 
130 /*
131 ** creates a new string and anchors it in scanner's table so that
132 ** it will not be collected until the end of the compilation
133 ** (by that time it should be anchored somewhere)
134 */
135 TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
136   lua_State *L = ls->L;
137   TValue *o;  /* entry for 'str' */
138   TString *ts = luaS_newlstr(L, str, l);  /* create new string */
139   setsvalue2s(L, L->top++, ts);  /* temporarily anchor it in stack */
140   o = luaH_set(L, ls->h, L->top - 1);
141   if (ttisnil(o)) {  /* not in use yet? */
142     /* boolean value does not need GC barrier;
143        table has no metatable, so it does not need to invalidate cache */
144     setbvalue(o, 1);  /* t[string] = true */
145     luaC_checkGC(L);
146   }
147   else {  /* string already present */
148     ts = tsvalue(keyfromval(o));  /* re-use value previously stored */
149   }
150   L->top--;  /* remove string from stack */
151   return ts;
152 }
153 
154 
155 /*
156 ** increment line number and skips newline sequence (any of
157 ** \n, \r, \n\r, or \r\n)
158 */
159 static void inclinenumber (LexState *ls) {
160   int old = ls->current;
161   lua_assert(currIsNewline(ls));
162   next(ls);  /* skip '\n' or '\r' */
163   if (currIsNewline(ls) && ls->current != old)
164     next(ls);  /* skip '\n\r' or '\r\n' */
165   if (++ls->linenumber >= MAX_INT)
166     lexerror(ls, "chunk has too many lines", 0);
167 }
168 
169 
170 void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
171                     int firstchar) {
172   ls->t.token = 0;
173   ls->L = L;
174   ls->current = firstchar;
175   ls->lookahead.token = TK_EOS;  /* no look-ahead token */
176   ls->z = z;
177   ls->fs = NULL;
178   ls->linenumber = 1;
179   ls->lastline = 1;
180   ls->source = source;
181   ls->envn = luaS_newliteral(L, LUA_ENV);  /* get env name */
182   luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER);  /* initialize buffer */
183 }
184 
185 
186 
187 /*
188 ** =======================================================
189 ** LEXICAL ANALYZER
190 ** =======================================================
191 */
192 
193 
194 static int check_next1 (LexState *ls, int c) {
195   if (ls->current == c) {
196     next(ls);
197     return 1;
198   }
199   else return 0;
200 }
201 
202 
203 /*
204 ** Check whether current char is in set 'set' (with two chars) and
205 ** saves it
206 */
207 static int check_next2 (LexState *ls, const char *set) {
208   lua_assert(set[2] == '\0');
209   if (ls->current == set[0] || ls->current == set[1]) {
210     save_and_next(ls);
211     return 1;
212   }
213   else return 0;
214 }
215 
216 
217 #ifndef _KERNEL
218 /* LUA_NUMBER */
219 /*
220 ** this function is quite liberal in what it accepts, as 'luaO_str2num'
221 ** will reject ill-formed numerals.
222 */
223 static int read_numeral (LexState *ls, SemInfo *seminfo) {
224   TValue obj;
225   const char *expo = "Ee";
226   int first = ls->current;
227   lua_assert(lisdigit(ls->current));
228   save_and_next(ls);
229   if (first == '0' && check_next2(ls, "xX"))  /* hexadecimal? */
230     expo = "Pp";
231   for (;;) {
232     if (check_next2(ls, expo))  /* exponent part? */
233       check_next2(ls, "-+");  /* optional exponent sign */
234     if (lisxdigit(ls->current))
235       save_and_next(ls);
236     else if (ls->current == '.')
237       save_and_next(ls);
238     else break;
239   }
240   save(ls, '\0');
241   if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0)  /* format error? */
242     lexerror(ls, "malformed number", TK_FLT);
243   if (ttisinteger(&obj)) {
244     seminfo->i = ivalue(&obj);
245     return TK_INT;
246   }
247   else {
248     lua_assert(ttisfloat(&obj));
249     seminfo->r = fltvalue(&obj);
250     return TK_FLT;
251   }
252 }
253 
254 #else /* _KERNEL */
255 
256 static int read_numeral (LexState *ls, SemInfo *seminfo) {
257   TValue obj;
258   int first = ls->current;
259   lua_assert(lisdigit(ls->current));
260   save_and_next(ls);
261   if (first == '0')
262     check_next2(ls, "xX");  /* hexadecimal? */
263   for (;;) {
264     if (lisxdigit(ls->current))
265       save_and_next(ls);
266     else break;
267   }
268   save(ls, '\0');
269   if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0)  /* format error? */
270     lexerror(ls, "malformed number", TK_INT);
271   lua_assert(ttisinteger(&obj));
272   seminfo->i = ivalue(&obj);
273   return TK_INT;
274 }
275 #endif /* _KERNEL */
276 
277 /*
278 ** skip a sequence '[=*[' or ']=*]'; if sequence is well formed, return
279 ** its number of '='s; otherwise, return a negative number (-1 iff there
280 ** are no '='s after initial bracket)
281 */
282 static int skip_sep (LexState *ls) {
283   int count = 0;
284   int s = ls->current;
285   lua_assert(s == '[' || s == ']');
286   save_and_next(ls);
287   while (ls->current == '=') {
288     save_and_next(ls);
289     count++;
290   }
291   return (ls->current == s) ? count : (-count) - 1;
292 }
293 
294 
295 static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
296   int line = ls->linenumber;  /* initial line (for error message) */
297   save_and_next(ls);  /* skip 2nd '[' */
298   if (currIsNewline(ls))  /* string starts with a newline? */
299     inclinenumber(ls);  /* skip it */
300   for (;;) {
301     switch (ls->current) {
302       case EOZ: {  /* error */
303         const char *what = (seminfo ? "string" : "comment");
304         const char *msg = luaO_pushfstring(ls->L,
305                      "unfinished long %s (starting at line %d)", what, line);
306         lexerror(ls, msg, TK_EOS);
307         break;  /* to avoid warnings */
308       }
309       case ']': {
310         if (skip_sep(ls) == sep) {
311           save_and_next(ls);  /* skip 2nd ']' */
312           goto endloop;
313         }
314         break;
315       }
316       case '\n': case '\r': {
317         save(ls, '\n');
318         inclinenumber(ls);
319         if (!seminfo) luaZ_resetbuffer(ls->buff);  /* avoid wasting space */
320         break;
321       }
322       default: {
323         if (seminfo) save_and_next(ls);
324         else next(ls);
325       }
326     }
327   } endloop:
328   if (seminfo)
329     seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep),
330                                      luaZ_bufflen(ls->buff) - 2*(2 + sep));
331 }
332 
333 
334 static void esccheck (LexState *ls, int c, const char *msg) {
335   if (!c) {
336     if (ls->current != EOZ)
337       save_and_next(ls);  /* add current to buffer for error message */
338     lexerror(ls, msg, TK_STRING);
339   }
340 }
341 
342 
343 static int gethexa (LexState *ls) {
344   save_and_next(ls);
345   esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected");
346   return luaO_hexavalue(ls->current);
347 }
348 
349 
350 static int readhexaesc (LexState *ls) {
351   int r = gethexa(ls);
352   r = (r << 4) + gethexa(ls);
353   luaZ_buffremove(ls->buff, 2);  /* remove saved chars from buffer */
354   return r;
355 }
356 
357 
358 static unsigned long readutf8esc (LexState *ls) {
359   unsigned long r;
360   int i = 4;  /* chars to be removed: '\', 'u', '{', and first digit */
361   save_and_next(ls);  /* skip 'u' */
362   esccheck(ls, ls->current == '{', "missing '{'");
363   r = gethexa(ls);  /* must have at least one digit */
364   while ((save_and_next(ls), lisxdigit(ls->current))) {
365     i++;
366     r = (r << 4) + luaO_hexavalue(ls->current);
367     esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large");
368   }
369   esccheck(ls, ls->current == '}', "missing '}'");
370   next(ls);  /* skip '}' */
371   luaZ_buffremove(ls->buff, i);  /* remove saved chars from buffer */
372   return r;
373 }
374 
375 
376 static void utf8esc (LexState *ls) {
377   char buff[UTF8BUFFSZ];
378   int n = luaO_utf8esc(buff, readutf8esc(ls));
379   for (; n > 0; n--)  /* add 'buff' to string */
380     save(ls, buff[UTF8BUFFSZ - n]);
381 }
382 
383 
384 static int readdecesc (LexState *ls) {
385   int i;
386   int r = 0;  /* result accumulator */
387   for (i = 0; i < 3 && lisdigit(ls->current); i++) {  /* read up to 3 digits */
388     r = 10*r + ls->current - '0';
389     save_and_next(ls);
390   }
391   esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
392   luaZ_buffremove(ls->buff, i);  /* remove read digits from buffer */
393   return r;
394 }
395 
396 
397 static void read_string (LexState *ls, int del, SemInfo *seminfo) {
398   save_and_next(ls);  /* keep delimiter (for error messages) */
399   while (ls->current != del) {
400     switch (ls->current) {
401       case EOZ:
402         lexerror(ls, "unfinished string", TK_EOS);
403         break;  /* to avoid warnings */
404       case '\n':
405       case '\r':
406         lexerror(ls, "unfinished string", TK_STRING);
407         break;  /* to avoid warnings */
408       case '\\': {  /* escape sequences */
409         int c;  /* final character to be saved */
410         save_and_next(ls);  /* keep '\\' for error messages */
411         switch (ls->current) {
412           case 'a': c = '\a'; goto read_save;
413           case 'b': c = '\b'; goto read_save;
414           case 'f': c = '\f'; goto read_save;
415           case 'n': c = '\n'; goto read_save;
416           case 'r': c = '\r'; goto read_save;
417           case 't': c = '\t'; goto read_save;
418           case 'v': c = '\v'; goto read_save;
419           case 'x': c = readhexaesc(ls); goto read_save;
420           case 'u': utf8esc(ls);  goto no_save;
421           case '\n': case '\r':
422             inclinenumber(ls); c = '\n'; goto only_save;
423           case '\\': case '\"': case '\'':
424             c = ls->current; goto read_save;
425           case EOZ: goto no_save;  /* will raise an error next loop */
426           case 'z': {  /* zap following span of spaces */
427             luaZ_buffremove(ls->buff, 1);  /* remove '\\' */
428             next(ls);  /* skip the 'z' */
429             while (lisspace(ls->current)) {
430               if (currIsNewline(ls)) inclinenumber(ls);
431               else next(ls);
432             }
433             goto no_save;
434           }
435           default: {
436             esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
437             c = readdecesc(ls);  /* digital escape '\ddd' */
438             goto only_save;
439           }
440         }
441        read_save:
442          next(ls);
443          /* go through */
444        only_save:
445          luaZ_buffremove(ls->buff, 1);  /* remove '\\' */
446          save(ls, c);
447          /* go through */
448        no_save: break;
449       }
450       default:
451         save_and_next(ls);
452     }
453   }
454   save_and_next(ls);  /* skip delimiter */
455   seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
456                                    luaZ_bufflen(ls->buff) - 2);
457 }
458 
459 
460 static int llex (LexState *ls, SemInfo *seminfo) {
461   luaZ_resetbuffer(ls->buff);
462   for (;;) {
463     switch (ls->current) {
464       case '\n': case '\r': {  /* line breaks */
465         inclinenumber(ls);
466         break;
467       }
468       case ' ': case '\f': case '\t': case '\v': {  /* spaces */
469         next(ls);
470         break;
471       }
472       case '-': {  /* '-' or '--' (comment) */
473         next(ls);
474         if (ls->current != '-') return '-';
475         /* else is a comment */
476         next(ls);
477         if (ls->current == '[') {  /* long comment? */
478           int sep = skip_sep(ls);
479           luaZ_resetbuffer(ls->buff);  /* 'skip_sep' may dirty the buffer */
480           if (sep >= 0) {
481             read_long_string(ls, NULL, sep);  /* skip long comment */
482             luaZ_resetbuffer(ls->buff);  /* previous call may dirty the buff. */
483             break;
484           }
485         }
486         /* else short comment */
487         while (!currIsNewline(ls) && ls->current != EOZ)
488           next(ls);  /* skip until end of line (or end of file) */
489         break;
490       }
491       case '[': {  /* long string or simply '[' */
492         int sep = skip_sep(ls);
493         if (sep >= 0) {
494           read_long_string(ls, seminfo, sep);
495           return TK_STRING;
496         }
497         else if (sep != -1)  /* '[=...' missing second bracket */
498           lexerror(ls, "invalid long string delimiter", TK_STRING);
499         return '[';
500       }
501       case '=': {
502         next(ls);
503         if (check_next1(ls, '=')) return TK_EQ;
504         else return '=';
505       }
506       case '<': {
507         next(ls);
508         if (check_next1(ls, '=')) return TK_LE;
509         else if (check_next1(ls, '<')) return TK_SHL;
510         else return '<';
511       }
512       case '>': {
513         next(ls);
514         if (check_next1(ls, '=')) return TK_GE;
515         else if (check_next1(ls, '>')) return TK_SHR;
516         else return '>';
517       }
518       case '/': {
519         next(ls);
520         if (check_next1(ls, '/')) return TK_IDIV;
521         else return '/';
522       }
523       case '~': {
524         next(ls);
525         if (check_next1(ls, '=')) return TK_NE;
526         else return '~';
527       }
528       case ':': {
529         next(ls);
530         if (check_next1(ls, ':')) return TK_DBCOLON;
531         else return ':';
532       }
533       case '"': case '\'': {  /* short literal strings */
534         read_string(ls, ls->current, seminfo);
535         return TK_STRING;
536       }
537       case '.': {  /* '.', '..', '...', or number */
538         save_and_next(ls);
539         if (check_next1(ls, '.')) {
540           if (check_next1(ls, '.'))
541             return TK_DOTS;   /* '...' */
542           else return TK_CONCAT;   /* '..' */
543         }
544 #ifndef _KERNEL
545         else if (!lisdigit(ls->current)) return '.';
546         else return read_numeral(ls, seminfo);
547 #else /* _KERNEL */
548         else return '.';
549 #endif /* _KERNEL */
550       }
551       case '0': case '1': case '2': case '3': case '4':
552       case '5': case '6': case '7': case '8': case '9': {
553         return read_numeral(ls, seminfo);
554       }
555       case EOZ: {
556         return TK_EOS;
557       }
558       default: {
559         if (lislalpha(ls->current)) {  /* identifier or reserved word? */
560           TString *ts;
561           do {
562             save_and_next(ls);
563           } while (lislalnum(ls->current));
564           ts = luaX_newstring(ls, luaZ_buffer(ls->buff),
565                                   luaZ_bufflen(ls->buff));
566           seminfo->ts = ts;
567           if (isreserved(ts))  /* reserved word? */
568             return ts->extra - 1 + FIRST_RESERVED;
569           else {
570             return TK_NAME;
571           }
572         }
573         else {  /* single-char tokens (+ - / ...) */
574           int c = ls->current;
575           next(ls);
576           return c;
577         }
578       }
579     }
580   }
581 }
582 
583 
584 void luaX_next (LexState *ls) {
585   ls->lastline = ls->linenumber;
586   if (ls->lookahead.token != TK_EOS) {  /* is there a look-ahead token? */
587     ls->t = ls->lookahead;  /* use this one */
588     ls->lookahead.token = TK_EOS;  /* and discharge it */
589   }
590   else
591     ls->t.token = llex(ls, &ls->t.seminfo);  /* read next token */
592 }
593 
594 
595 int luaX_lookahead (LexState *ls) {
596   lua_assert(ls->lookahead.token == TK_EOS);
597   ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);
598   return ls->lookahead.token;
599 }
600 
601