llex.c 17 KB

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