2
0

llex.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /*
  2. ** $Id: llex.c,v 2.91 2015/03/28 19:14:47 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_newliteral(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_newliteral(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. #define buff2num(b,o) (luaO_str2num(luaZ_buffer(b), o) != 0)
  178. /*
  179. ** in case of format error, try to change decimal point separator to
  180. ** the one defined in the current locale and check again
  181. */
  182. static void trydecpoint (LexState *ls, TValue *o) {
  183. char old = ls->decpoint;
  184. ls->decpoint = lua_getlocaledecpoint();
  185. buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
  186. if (!buff2num(ls->buff, o)) {
  187. /* format error with correct decimal point: no more options */
  188. buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
  189. lexerror(ls, "malformed number", TK_FLT);
  190. }
  191. }
  192. /* LUA_NUMBER */
  193. /*
  194. ** this function is quite liberal in what it accepts, as 'luaO_str2num'
  195. ** will reject ill-formed numerals.
  196. */
  197. static int read_numeral (LexState *ls, SemInfo *seminfo) {
  198. TValue obj;
  199. const char *expo = "Ee";
  200. int first = ls->current;
  201. lua_assert(lisdigit(ls->current));
  202. save_and_next(ls);
  203. if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */
  204. expo = "Pp";
  205. for (;;) {
  206. if (check_next2(ls, expo)) /* exponent part? */
  207. check_next2(ls, "-+"); /* optional exponent sign */
  208. if (lisxdigit(ls->current))
  209. save_and_next(ls);
  210. else if (ls->current == '.')
  211. save_and_next(ls);
  212. else break;
  213. }
  214. save(ls, '\0');
  215. buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */
  216. if (!buff2num(ls->buff, &obj)) /* format error? */
  217. trydecpoint(ls, &obj); /* try to update decimal point separator */
  218. if (ttisinteger(&obj)) {
  219. seminfo->i = ivalue(&obj);
  220. return TK_INT;
  221. }
  222. else {
  223. lua_assert(ttisfloat(&obj));
  224. seminfo->r = fltvalue(&obj);
  225. return TK_FLT;
  226. }
  227. }
  228. /*
  229. ** skip a sequence '[=*[' or ']=*]'; if sequence is wellformed, return
  230. ** its number of '='s; otherwise, return a negative number (-1 iff there
  231. ** are no '='s after initial bracket)
  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) /* '[=...' missing second bracket */
  431. lexerror(ls, "invalid long string delimiter", TK_STRING);
  432. return '[';
  433. }
  434. case '=': {
  435. next(ls);
  436. if (check_next1(ls, '=')) return TK_EQ;
  437. else return '=';
  438. }
  439. case '<': {
  440. next(ls);
  441. if (check_next1(ls, '=')) return TK_LE;
  442. else if (check_next1(ls, '<')) return TK_SHL;
  443. else return '<';
  444. }
  445. case '>': {
  446. next(ls);
  447. if (check_next1(ls, '=')) return TK_GE;
  448. else if (check_next1(ls, '>')) return TK_SHR;
  449. else return '>';
  450. }
  451. case '/': {
  452. next(ls);
  453. if (check_next1(ls, '/')) return TK_IDIV;
  454. else return '/';
  455. }
  456. case '~': {
  457. next(ls);
  458. if (check_next1(ls, '=')) return TK_NE;
  459. else return '~';
  460. }
  461. case ':': {
  462. next(ls);
  463. if (check_next1(ls, ':')) return TK_DBCOLON;
  464. else return ':';
  465. }
  466. case '"': case '\'': { /* short literal strings */
  467. read_string(ls, ls->current, seminfo);
  468. return TK_STRING;
  469. }
  470. case '.': { /* '.', '..', '...', or number */
  471. save_and_next(ls);
  472. if (check_next1(ls, '.')) {
  473. if (check_next1(ls, '.'))
  474. return TK_DOTS; /* '...' */
  475. else return TK_CONCAT; /* '..' */
  476. }
  477. else if (!lisdigit(ls->current)) return '.';
  478. else return read_numeral(ls, seminfo);
  479. }
  480. case '0': case '1': case '2': case '3': case '4':
  481. case '5': case '6': case '7': case '8': case '9': {
  482. return read_numeral(ls, seminfo);
  483. }
  484. case EOZ: {
  485. return TK_EOS;
  486. }
  487. default: {
  488. if (lislalpha(ls->current)) { /* identifier or reserved word? */
  489. TString *ts;
  490. do {
  491. save_and_next(ls);
  492. } while (lislalnum(ls->current));
  493. ts = luaX_newstring(ls, luaZ_buffer(ls->buff),
  494. luaZ_bufflen(ls->buff));
  495. seminfo->ts = ts;
  496. if (isreserved(ts)) /* reserved word? */
  497. return ts->extra - 1 + FIRST_RESERVED;
  498. else {
  499. return TK_NAME;
  500. }
  501. }
  502. else { /* single-char tokens (+ - / ...) */
  503. int c = ls->current;
  504. next(ls);
  505. return c;
  506. }
  507. }
  508. }
  509. }
  510. }
  511. void luaX_next (LexState *ls) {
  512. ls->lastline = ls->linenumber;
  513. if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
  514. ls->t = ls->lookahead; /* use this one */
  515. ls->lookahead.token = TK_EOS; /* and discharge it */
  516. }
  517. else
  518. ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */
  519. }
  520. int luaX_lookahead (LexState *ls) {
  521. lua_assert(ls->lookahead.token == TK_EOS);
  522. ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);
  523. return ls->lookahead.token;
  524. }