llex.c 17 KB

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