llex.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /*
  2. ** $Id: llex.c,v 2.83 2014/10/17 16:28:21 roberto Exp roberto $
  3. ** Lexical Analyzer
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <locale.h>
  7. #include <string.h>
  8. #define llex_c
  9. #define LUA_CORE
  10. #include "lua.h"
  11. #include "lctype.h"
  12. #include "ldo.h"
  13. #include "lgc.h"
  14. #include "llex.h"
  15. #include "lobject.h"
  16. #include "lparser.h"
  17. #include "lstate.h"
  18. #include "lstring.h"
  19. #include "ltable.h"
  20. #include "lzio.h"
  21. #define next(ls) (ls->current = zgetc(ls->z))
  22. #define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r')
  23. /* ORDER RESERVED */
  24. static const char *const luaX_tokens [] = {
  25. "and", "break", "do", "else", "elseif",
  26. "end", "false", "for", "function", "goto", "if",
  27. "in", "local", "nil", "not", "or", "repeat",
  28. "return", "then", "true", "until", "while",
  29. "//", "..", "...", "==", ">=", "<=", "~=",
  30. "<<", ">>", "::", "<eof>",
  31. "<number>", "<number>", "<name>", "<string>"
  32. };
  33. #define save_and_next(ls) (save(ls, ls->current), next(ls))
  34. static l_noret lexerror (LexState *ls, const char *msg, int token);
  35. static void save (LexState *ls, int c) {
  36. Mbuffer *b = ls->buff;
  37. if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {
  38. size_t newsize;
  39. if (luaZ_sizebuffer(b) >= MAX_SIZE/2)
  40. lexerror(ls, "lexical element too long", 0);
  41. newsize = luaZ_sizebuffer(b) * 2;
  42. luaZ_resizebuffer(ls->L, b, newsize);
  43. }
  44. b->buffer[luaZ_bufflen(b)++] = cast(char, c);
  45. }
  46. void luaX_init (lua_State *L) {
  47. int i;
  48. TString *e = luaS_new(L, LUA_ENV); /* create env name */
  49. luaC_fix(L, obj2gco(e)); /* never collect this name */
  50. for (i=0; i<NUM_RESERVED; i++) {
  51. TString *ts = luaS_new(L, luaX_tokens[i]);
  52. luaC_fix(L, obj2gco(ts)); /* reserved words are never collected */
  53. ts->extra = cast_byte(i+1); /* reserved word */
  54. }
  55. }
  56. const char *luaX_token2str (LexState *ls, int token) {
  57. if (token < FIRST_RESERVED) { /* single-byte symbols? */
  58. lua_assert(token == cast_uchar(token));
  59. return luaO_pushfstring(ls->L, "'%c'", token);
  60. }
  61. else {
  62. const char *s = luaX_tokens[token - FIRST_RESERVED];
  63. if (token < TK_EOS) /* fixed format (symbols and reserved words)? */
  64. return luaO_pushfstring(ls->L, "'%s'", s);
  65. else /* names, strings, and numerals */
  66. return s;
  67. }
  68. }
  69. static const char *txtToken (LexState *ls, int token) {
  70. switch (token) {
  71. case TK_NAME: case TK_STRING:
  72. case TK_FLT: case TK_INT:
  73. save(ls, '\0');
  74. return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff));
  75. default:
  76. return luaX_token2str(ls, token);
  77. }
  78. }
  79. static l_noret lexerror (LexState *ls, const char *msg, int token) {
  80. char buff[LUA_IDSIZE];
  81. luaO_chunkid(buff, getstr(ls->source), LUA_IDSIZE);
  82. msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg);
  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. luaX_syntaxerror(ls, "chunk has too many lines");
  125. }
  126. void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
  127. int firstchar) {
  128. ls->decpoint = '.';
  129. ls->L = L;
  130. ls->current = firstchar;
  131. ls->lookahead.token = TK_EOS; /* no look-ahead token */
  132. ls->z = z;
  133. ls->fs = NULL;
  134. ls->linenumber = 1;
  135. ls->lastline = 1;
  136. ls->source = source;
  137. ls->envn = luaS_new(L, LUA_ENV); /* get env name */
  138. luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
  139. }
  140. /*
  141. ** =======================================================
  142. ** LEXICAL ANALYZER
  143. ** =======================================================
  144. */
  145. static int check_next1 (LexState *ls, int c) {
  146. if (ls->current == c) {
  147. next(ls);
  148. return 1;
  149. }
  150. else return 0;
  151. }
  152. /*
  153. ** Check whether current char is in set 'set' (with two chars) and
  154. ** saves it
  155. */
  156. static int check_next2 (LexState *ls, const char *set) {
  157. lua_assert(set[2] == '\0');
  158. if (ls->current == set[0] || ls->current == set[1]) {
  159. save_and_next(ls);
  160. return 1;
  161. }
  162. else return 0;
  163. }
  164. /*
  165. ** change all characters 'from' in buffer to 'to'
  166. */
  167. static void buffreplace (LexState *ls, char from, char to) {
  168. if (from != to) {
  169. size_t n = luaZ_bufflen(ls->buff);
  170. char *p = luaZ_buffer(ls->buff);
  171. while (n--)
  172. if (p[n] == from) p[n] = to;
  173. }
  174. }
  175. #if !defined(l_getlocaledecpoint)
  176. #define l_getlocaledecpoint() (localeconv()->decimal_point[0])
  177. #endif
  178. #define buff2num(b,o) (luaO_str2num(luaZ_buffer(b), o) != 0)
  179. /*
  180. ** in case of format error, try to change decimal point separator to
  181. ** the one defined in the current locale and check again
  182. */
  183. static void trydecpoint (LexState *ls, TValue *o) {
  184. char old = ls->decpoint;
  185. ls->decpoint = l_getlocaledecpoint();
  186. buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
  187. if (!buff2num(ls->buff, o)) {
  188. /* format error with correct decimal point: no more options */
  189. buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
  190. lexerror(ls, "malformed number", TK_FLT);
  191. }
  192. }
  193. /* LUA_NUMBER */
  194. /*
  195. ** this function is quite liberal in what it accepts, as 'luaO_str2num'
  196. ** will reject ill-formed numerals.
  197. */
  198. static int read_numeral (LexState *ls, SemInfo *seminfo) {
  199. TValue obj;
  200. const char *expo = "Ee";
  201. int first = ls->current;
  202. lua_assert(lisdigit(ls->current));
  203. save_and_next(ls);
  204. if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */
  205. expo = "Pp";
  206. for (;;) {
  207. if (check_next2(ls, expo)) /* exponent part? */
  208. check_next2(ls, "-+"); /* optional exponent sign */
  209. if (lisxdigit(ls->current))
  210. save_and_next(ls);
  211. else if (ls->current == '.')
  212. save_and_next(ls);
  213. else break;
  214. }
  215. save(ls, '\0');
  216. buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */
  217. if (!buff2num(ls->buff, &obj)) /* format error? */
  218. trydecpoint(ls, &obj); /* try to update decimal point separator */
  219. if (ttisinteger(&obj)) {
  220. seminfo->i = ivalue(&obj);
  221. return TK_INT;
  222. }
  223. else {
  224. lua_assert(ttisfloat(&obj));
  225. seminfo->r = fltvalue(&obj);
  226. return TK_FLT;
  227. }
  228. }
  229. /*
  230. ** skip a sequence '[=*[' or ']=*]' and return its number of '='s or
  231. ** -1 if sequence is malformed
  232. */
  233. static int skip_sep (LexState *ls) {
  234. int count = 0;
  235. int s = ls->current;
  236. lua_assert(s == '[' || s == ']');
  237. save_and_next(ls);
  238. while (ls->current == '=') {
  239. save_and_next(ls);
  240. count++;
  241. }
  242. return (ls->current == s) ? count : (-count) - 1;
  243. }
  244. static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
  245. int line = ls->linenumber; /* initial line (for error message) */
  246. save_and_next(ls); /* skip 2nd `[' */
  247. if (currIsNewline(ls)) /* string starts with a newline? */
  248. inclinenumber(ls); /* skip it */
  249. for (;;) {
  250. switch (ls->current) {
  251. case EOZ: { /* error */
  252. const char *what = (seminfo ? "string" : "comment");
  253. const char *msg = luaO_pushfstring(ls->L,
  254. "unfinished long %s (starting at line %d)", what, line);
  255. lexerror(ls, msg, TK_EOS);
  256. break; /* to avoid warnings */
  257. }
  258. case ']': {
  259. if (skip_sep(ls) == sep) {
  260. save_and_next(ls); /* skip 2nd `]' */
  261. goto endloop;
  262. }
  263. break;
  264. }
  265. case '\n': case '\r': {
  266. save(ls, '\n');
  267. inclinenumber(ls);
  268. if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */
  269. break;
  270. }
  271. default: {
  272. if (seminfo) save_and_next(ls);
  273. else next(ls);
  274. }
  275. }
  276. } endloop:
  277. if (seminfo)
  278. seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep),
  279. luaZ_bufflen(ls->buff) - 2*(2 + sep));
  280. }
  281. static void esccheck (LexState *ls, int c, const char *msg) {
  282. if (!c) {
  283. if (ls->current != EOZ)
  284. save_and_next(ls); /* add current to buffer for error message */
  285. lexerror(ls, msg, TK_STRING);
  286. }
  287. }
  288. static int gethexa (LexState *ls) {
  289. save_and_next(ls);
  290. esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected");
  291. return luaO_hexavalue(ls->current);
  292. }
  293. static int readhexaesc (LexState *ls) {
  294. int r = gethexa(ls);
  295. r = (r << 4) + gethexa(ls);
  296. luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */
  297. return r;
  298. }
  299. static unsigned long readutf8esc (LexState *ls) {
  300. unsigned long r;
  301. int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */
  302. save_and_next(ls); /* skip 'u' */
  303. esccheck(ls, ls->current == '{', "missing '{'");
  304. r = gethexa(ls); /* must have at least one digit */
  305. while ((save_and_next(ls), lisxdigit(ls->current))) {
  306. i++;
  307. r = (r << 4) + luaO_hexavalue(ls->current);
  308. esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large");
  309. }
  310. esccheck(ls, ls->current == '}', "missing '}'");
  311. next(ls); /* skip '}' */
  312. luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */
  313. return r;
  314. }
  315. static void utf8esc (LexState *ls) {
  316. char buff[UTF8BUFFSZ];
  317. int n = luaO_utf8esc(buff, readutf8esc(ls));
  318. for (; n > 0; n--) /* add 'buff' to string */
  319. save(ls, buff[UTF8BUFFSZ - n]);
  320. }
  321. static int readdecesc (LexState *ls) {
  322. int i;
  323. int r = 0; /* result accumulator */
  324. for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
  325. r = 10*r + ls->current - '0';
  326. save_and_next(ls);
  327. }
  328. esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
  329. luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */
  330. return r;
  331. }
  332. static void read_string (LexState *ls, int del, SemInfo *seminfo) {
  333. save_and_next(ls); /* keep delimiter (for error messages) */
  334. while (ls->current != del) {
  335. switch (ls->current) {
  336. case EOZ:
  337. lexerror(ls, "unfinished string", TK_EOS);
  338. break; /* to avoid warnings */
  339. case '\n':
  340. case '\r':
  341. lexerror(ls, "unfinished string", TK_STRING);
  342. break; /* to avoid warnings */
  343. case '\\': { /* escape sequences */
  344. int c; /* final character to be saved */
  345. save_and_next(ls); /* keep '\\' for error messages */
  346. switch (ls->current) {
  347. case 'a': c = '\a'; goto read_save;
  348. case 'b': c = '\b'; goto read_save;
  349. case 'f': c = '\f'; goto read_save;
  350. case 'n': c = '\n'; goto read_save;
  351. case 'r': c = '\r'; goto read_save;
  352. case 't': c = '\t'; goto read_save;
  353. case 'v': c = '\v'; goto read_save;
  354. case 'x': c = readhexaesc(ls); goto read_save;
  355. case 'u': utf8esc(ls); goto no_save;
  356. case '\n': case '\r':
  357. inclinenumber(ls); c = '\n'; goto only_save;
  358. case '\\': case '\"': case '\'':
  359. c = ls->current; goto read_save;
  360. case EOZ: goto no_save; /* will raise an error next loop */
  361. case 'z': { /* zap following span of spaces */
  362. luaZ_buffremove(ls->buff, 1); /* remove '\\' */
  363. next(ls); /* skip the 'z' */
  364. while (lisspace(ls->current)) {
  365. if (currIsNewline(ls)) inclinenumber(ls);
  366. else next(ls);
  367. }
  368. goto no_save;
  369. }
  370. default: {
  371. esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
  372. c = readdecesc(ls); /* digital escape \ddd */
  373. goto only_save;
  374. }
  375. }
  376. read_save:
  377. next(ls);
  378. /* go through */
  379. only_save:
  380. luaZ_buffremove(ls->buff, 1); /* remove '\\' */
  381. save(ls, c);
  382. /* go through */
  383. no_save: break;
  384. }
  385. default:
  386. save_and_next(ls);
  387. }
  388. }
  389. save_and_next(ls); /* skip delimiter */
  390. seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
  391. luaZ_bufflen(ls->buff) - 2);
  392. }
  393. static int llex (LexState *ls, SemInfo *seminfo) {
  394. luaZ_resetbuffer(ls->buff);
  395. for (;;) {
  396. switch (ls->current) {
  397. case '\n': case '\r': { /* line breaks */
  398. inclinenumber(ls);
  399. break;
  400. }
  401. case ' ': case '\f': case '\t': case '\v': { /* spaces */
  402. next(ls);
  403. break;
  404. }
  405. case '-': { /* '-' or '--' (comment) */
  406. next(ls);
  407. if (ls->current != '-') return '-';
  408. /* else is a comment */
  409. next(ls);
  410. if (ls->current == '[') { /* long comment? */
  411. int sep = skip_sep(ls);
  412. luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */
  413. if (sep >= 0) {
  414. read_long_string(ls, NULL, sep); /* skip long comment */
  415. luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
  416. break;
  417. }
  418. }
  419. /* else short comment */
  420. while (!currIsNewline(ls) && ls->current != EOZ)
  421. next(ls); /* skip until end of line (or end of file) */
  422. break;
  423. }
  424. case '[': { /* long string or simply '[' */
  425. int sep = skip_sep(ls);
  426. if (sep >= 0) {
  427. read_long_string(ls, seminfo, sep);
  428. return TK_STRING;
  429. }
  430. else if (sep == -1) return '[';
  431. else lexerror(ls, "invalid long string delimiter", TK_STRING);
  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. }