interplane.Get Omega
Read in your language

lua

[Ported from github.com/lua/lua] Cast in 'rl_readline_name'

Brought by drakestapleton

branch master Branches Tags History

lua / llex.c

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