llex.c 17 KB

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