llex.c 17 KB

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