llex.c 16 KB

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