llex.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /*
  2. ** $Id: llex.c,v 2.80 2014/07/18 13:36:14 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(unsigned char, token));
  59. return (lisprint(token)) ? luaO_pushfstring(ls->L, LUA_QL("%c"), token) :
  60. luaO_pushfstring(ls->L, "char(%d)", 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, LUA_QS, 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, LUA_QS, 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. luaX_syntaxerror(ls, "chunk has too many lines");
  126. }
  127. void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
  128. int firstchar) {
  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_new(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. #if !defined(getlocaledecpoint)
  177. #define getlocaledecpoint() (localeconv()->decimal_point[0])
  178. #endif
  179. #define buff2num(b,o) (luaO_str2num(luaZ_buffer(b), o) != 0)
  180. /*
  181. ** in case of format error, try to change decimal point separator to
  182. ** the one defined in the current locale and check again
  183. */
  184. static void trydecpoint (LexState *ls, TValue *o) {
  185. char old = ls->decpoint;
  186. ls->decpoint = getlocaledecpoint();
  187. buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
  188. if (!buff2num(ls->buff, o)) {
  189. /* format error with correct decimal point: no more options */
  190. buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
  191. lexerror(ls, "malformed number", TK_FLT);
  192. }
  193. }
  194. /* LUA_NUMBER */
  195. /*
  196. ** this function is quite liberal in what it accepts, as 'luaO_str2num'
  197. ** will reject ill-formed numerals.
  198. */
  199. static int read_numeral (LexState *ls, SemInfo *seminfo) {
  200. TValue obj;
  201. const char *expo = "Ee";
  202. int first = ls->current;
  203. lua_assert(lisdigit(ls->current));
  204. save_and_next(ls);
  205. if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */
  206. expo = "Pp";
  207. for (;;) {
  208. if (check_next2(ls, expo)) /* exponent part? */
  209. check_next2(ls, "-+"); /* optional exponent sign */
  210. if (lisxdigit(ls->current))
  211. save_and_next(ls);
  212. else if (ls->current == '.')
  213. save_and_next(ls);
  214. else break;
  215. }
  216. save(ls, '\0');
  217. buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */
  218. if (!buff2num(ls->buff, &obj)) /* format error? */
  219. trydecpoint(ls, &obj); /* try to update decimal point separator */
  220. if (ttisinteger(&obj)) {
  221. seminfo->i = ivalue(&obj);
  222. return TK_INT;
  223. }
  224. else {
  225. lua_assert(ttisfloat(&obj));
  226. seminfo->r = fltvalue(&obj);
  227. return TK_FLT;
  228. }
  229. }
  230. /*
  231. ** skip a sequence '[=*[' or ']=*]' and return its number of '='s or
  232. ** -1 if sequence is malformed
  233. */
  234. static int skip_sep (LexState *ls) {
  235. int count = 0;
  236. int s = ls->current;
  237. lua_assert(s == '[' || s == ']');
  238. save_and_next(ls);
  239. while (ls->current == '=') {
  240. save_and_next(ls);
  241. count++;
  242. }
  243. return (ls->current == s) ? count : (-count) - 1;
  244. }
  245. static void read_long_string (LexState *ls, SemInfo *seminfo, int 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) + (2 + sep),
  280. luaZ_bufflen(ls->buff) - 2*(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. static unsigned long readutf8esc (LexState *ls) {
  301. unsigned long r;
  302. int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */
  303. save_and_next(ls); /* skip 'u' */
  304. esccheck(ls, ls->current == '{', "missing '{'");
  305. r = gethexa(ls); /* must have at least one digit */
  306. while ((save_and_next(ls), lisxdigit(ls->current))) {
  307. i++;
  308. r = (r << 4) + luaO_hexavalue(ls->current);
  309. esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large");
  310. }
  311. esccheck(ls, ls->current == '}', "missing '}'");
  312. next(ls); /* skip '}' */
  313. luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */
  314. return r;
  315. }
  316. static void utf8esc (LexState *ls) {
  317. char buff[UTF8BUFFSZ];
  318. int n = luaO_utf8esc(buff, readutf8esc(ls));
  319. for (; n > 0; n--) /* add 'buff' to string */
  320. save(ls, buff[UTF8BUFFSZ - n]);
  321. }
  322. static int readdecesc (LexState *ls) {
  323. int i;
  324. int r = 0; /* result accumulator */
  325. for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
  326. r = 10*r + ls->current - '0';
  327. save_and_next(ls);
  328. }
  329. esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
  330. luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */
  331. return r;
  332. }
  333. static void read_string (LexState *ls, int del, SemInfo *seminfo) {
  334. save_and_next(ls); /* keep delimiter (for error messages) */
  335. while (ls->current != del) {
  336. switch (ls->current) {
  337. case EOZ:
  338. lexerror(ls, "unfinished string", TK_EOS);
  339. break; /* to avoid warnings */
  340. case '\n':
  341. case '\r':
  342. lexerror(ls, "unfinished string", TK_STRING);
  343. break; /* to avoid warnings */
  344. case '\\': { /* escape sequences */
  345. int c; /* final character to be saved */
  346. save_and_next(ls); /* keep '\\' for error messages */
  347. switch (ls->current) {
  348. case 'a': c = '\a'; goto read_save;
  349. case 'b': c = '\b'; goto read_save;
  350. case 'f': c = '\f'; goto read_save;
  351. case 'n': c = '\n'; goto read_save;
  352. case 'r': c = '\r'; goto read_save;
  353. case 't': c = '\t'; goto read_save;
  354. case 'v': c = '\v'; goto read_save;
  355. case 'x': c = readhexaesc(ls); goto read_save;
  356. case 'u': utf8esc(ls); goto no_save;
  357. case '\n': case '\r':
  358. inclinenumber(ls); c = '\n'; goto only_save;
  359. case '\\': case '\"': case '\'':
  360. c = ls->current; goto read_save;
  361. case EOZ: goto no_save; /* will raise an error next loop */
  362. case 'z': { /* zap following span of spaces */
  363. luaZ_buffremove(ls->buff, 1); /* remove '\\' */
  364. next(ls); /* skip the 'z' */
  365. while (lisspace(ls->current)) {
  366. if (currIsNewline(ls)) inclinenumber(ls);
  367. else next(ls);
  368. }
  369. goto no_save;
  370. }
  371. default: {
  372. esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
  373. c = readdecesc(ls); /* digital escape \ddd */
  374. goto only_save;
  375. }
  376. }
  377. read_save:
  378. next(ls);
  379. /* go through */
  380. only_save:
  381. luaZ_buffremove(ls->buff, 1); /* remove '\\' */
  382. save(ls, c);
  383. /* go through */
  384. no_save: break;
  385. }
  386. default:
  387. save_and_next(ls);
  388. }
  389. }
  390. save_and_next(ls); /* skip delimiter */
  391. seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
  392. luaZ_bufflen(ls->buff) - 2);
  393. }
  394. static int llex (LexState *ls, SemInfo *seminfo) {
  395. luaZ_resetbuffer(ls->buff);
  396. for (;;) {
  397. switch (ls->current) {
  398. case '\n': case '\r': { /* line breaks */
  399. inclinenumber(ls);
  400. break;
  401. }
  402. case ' ': case '\f': case '\t': case '\v': { /* spaces */
  403. next(ls);
  404. break;
  405. }
  406. case '-': { /* '-' or '--' (comment) */
  407. next(ls);
  408. if (ls->current != '-') return '-';
  409. /* else is a comment */
  410. next(ls);
  411. if (ls->current == '[') { /* long comment? */
  412. int sep = skip_sep(ls);
  413. luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */
  414. if (sep >= 0) {
  415. read_long_string(ls, NULL, sep); /* skip long comment */
  416. luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
  417. break;
  418. }
  419. }
  420. /* else short comment */
  421. while (!currIsNewline(ls) && ls->current != EOZ)
  422. next(ls); /* skip until end of line (or end of file) */
  423. break;
  424. }
  425. case '[': { /* long string or simply '[' */
  426. int sep = skip_sep(ls);
  427. if (sep >= 0) {
  428. read_long_string(ls, seminfo, sep);
  429. return TK_STRING;
  430. }
  431. else if (sep == -1) return '[';
  432. else lexerror(ls, "invalid long string delimiter", TK_STRING);
  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. }