2
0

llex.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. static unsigned long readutf8esc (LexState *ls) {
  293. unsigned long r;
  294. int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */
  295. save_and_next(ls); /* skip 'u' */
  296. esccheck(ls, ls->current == '{', "missing '{'");
  297. r = cast_ulong(gethexa(ls)); /* must have at least one digit */
  298. while (cast_void(save_and_next(ls)), lisxdigit(ls->current)) {
  299. i++;
  300. esccheck(ls, r <= (0x7FFFFFFFu >> 4), "UTF-8 value too large");
  301. r = (r << 4) + luaO_hexavalue(ls->current);
  302. }
  303. esccheck(ls, ls->current == '}', "missing '}'");
  304. next(ls); /* skip '}' */
  305. luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */
  306. return r;
  307. }
  308. static void utf8esc (LexState *ls) {
  309. char buff[UTF8BUFFSZ];
  310. int n = luaO_utf8esc(buff, readutf8esc(ls));
  311. for (; n > 0; n--) /* add 'buff' to string */
  312. save(ls, buff[UTF8BUFFSZ - n]);
  313. }
  314. static int readdecesc (LexState *ls) {
  315. int i;
  316. int r = 0; /* result accumulator */
  317. for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
  318. r = 10*r + ls->current - '0';
  319. save_and_next(ls);
  320. }
  321. esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
  322. luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */
  323. return r;
  324. }
  325. static void read_string (LexState *ls, int del, SemInfo *seminfo) {
  326. save_and_next(ls); /* keep delimiter (for error messages) */
  327. while (ls->current != del) {
  328. switch (ls->current) {
  329. case EOZ:
  330. lexerror(ls, "unfinished string", TK_EOS);
  331. break; /* to avoid warnings */
  332. case '\n':
  333. case '\r':
  334. lexerror(ls, "unfinished string", TK_STRING);
  335. break; /* to avoid warnings */
  336. case '\\': { /* escape sequences */
  337. int c; /* final character to be saved */
  338. save_and_next(ls); /* keep '\\' for error messages */
  339. switch (ls->current) {
  340. case 'a': c = '\a'; goto read_save;
  341. case 'b': c = '\b'; goto read_save;
  342. case 'f': c = '\f'; goto read_save;
  343. case 'n': c = '\n'; goto read_save;
  344. case 'r': c = '\r'; goto read_save;
  345. case 't': c = '\t'; goto read_save;
  346. case 'v': c = '\v'; goto read_save;
  347. case 'x': c = readhexaesc(ls); goto read_save;
  348. case 'u': utf8esc(ls); goto no_save;
  349. case '\n': case '\r':
  350. inclinenumber(ls); c = '\n'; goto only_save;
  351. case '\\': case '\"': case '\'':
  352. c = ls->current; goto read_save;
  353. case EOZ: goto no_save; /* will raise an error next loop */
  354. case 'z': { /* zap following span of spaces */
  355. luaZ_buffremove(ls->buff, 1); /* remove '\\' */
  356. next(ls); /* skip the 'z' */
  357. while (lisspace(ls->current)) {
  358. if (currIsNewline(ls)) inclinenumber(ls);
  359. else next(ls);
  360. }
  361. goto no_save;
  362. }
  363. default: {
  364. esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
  365. c = readdecesc(ls); /* digital escape '\ddd' */
  366. goto only_save;
  367. }
  368. }
  369. read_save:
  370. next(ls);
  371. /* go through */
  372. only_save:
  373. luaZ_buffremove(ls->buff, 1); /* remove '\\' */
  374. save(ls, c);
  375. /* go through */
  376. no_save: break;
  377. }
  378. default:
  379. save_and_next(ls);
  380. }
  381. }
  382. save_and_next(ls); /* skip delimiter */
  383. seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
  384. luaZ_bufflen(ls->buff) - 2);
  385. }
  386. static int llex (LexState *ls, SemInfo *seminfo) {
  387. luaZ_resetbuffer(ls->buff);
  388. for (;;) {
  389. switch (ls->current) {
  390. case '\n': case '\r': { /* line breaks */
  391. inclinenumber(ls);
  392. break;
  393. }
  394. case ' ': case '\f': case '\t': case '\v': { /* spaces */
  395. next(ls);
  396. break;
  397. }
  398. case '-': { /* '-' or '--' (comment) */
  399. next(ls);
  400. if (ls->current != '-') return '-';
  401. /* else is a comment */
  402. next(ls);
  403. if (ls->current == '[') { /* long comment? */
  404. size_t sep = skip_sep(ls);
  405. luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */
  406. if (sep >= 2) {
  407. read_long_string(ls, NULL, sep); /* skip long comment */
  408. luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
  409. break;
  410. }
  411. }
  412. /* else short comment */
  413. while (!currIsNewline(ls) && ls->current != EOZ)
  414. next(ls); /* skip until end of line (or end of file) */
  415. break;
  416. }
  417. case '[': { /* long string or simply '[' */
  418. size_t sep = skip_sep(ls);
  419. if (sep >= 2) {
  420. read_long_string(ls, seminfo, sep);
  421. return TK_STRING;
  422. }
  423. else if (sep == 0) /* '[=...' missing second bracket? */
  424. lexerror(ls, "invalid long string delimiter", TK_STRING);
  425. return '[';
  426. }
  427. case '=': {
  428. next(ls);
  429. if (check_next1(ls, '=')) return TK_EQ; /* '==' */
  430. else return '=';
  431. }
  432. case '<': {
  433. next(ls);
  434. if (check_next1(ls, '=')) return TK_LE; /* '<=' */
  435. else if (check_next1(ls, '<')) return TK_SHL; /* '<<' */
  436. else return '<';
  437. }
  438. case '>': {
  439. next(ls);
  440. if (check_next1(ls, '=')) return TK_GE; /* '>=' */
  441. else if (check_next1(ls, '>')) return TK_SHR; /* '>>' */
  442. else return '>';
  443. }
  444. case '/': {
  445. next(ls);
  446. if (check_next1(ls, '/')) return TK_IDIV; /* '//' */
  447. else return '/';
  448. }
  449. case '~': {
  450. next(ls);
  451. if (check_next1(ls, '=')) return TK_NE; /* '~=' */
  452. else return '~';
  453. }
  454. case ':': {
  455. next(ls);
  456. if (check_next1(ls, ':')) return TK_DBCOLON; /* '::' */
  457. else return ':';
  458. }
  459. case '"': case '\'': { /* short literal strings */
  460. read_string(ls, ls->current, seminfo);
  461. return TK_STRING;
  462. }
  463. case '.': { /* '.', '..', '...', or number */
  464. save_and_next(ls);
  465. if (check_next1(ls, '.')) {
  466. if (check_next1(ls, '.'))
  467. return TK_DOTS; /* '...' */
  468. else return TK_CONCAT; /* '..' */
  469. }
  470. else if (!lisdigit(ls->current)) return '.';
  471. else return read_numeral(ls, seminfo);
  472. }
  473. case '0': case '1': case '2': case '3': case '4':
  474. case '5': case '6': case '7': case '8': case '9': {
  475. return read_numeral(ls, seminfo);
  476. }
  477. case EOZ: {
  478. return TK_EOS;
  479. }
  480. default: {
  481. if (lislalpha(ls->current)) { /* identifier or reserved word? */
  482. TString *ts;
  483. do {
  484. save_and_next(ls);
  485. } while (lislalnum(ls->current));
  486. /* find or create string */
  487. ts = luaS_newlstr(ls->L, luaZ_buffer(ls->buff),
  488. luaZ_bufflen(ls->buff));
  489. if (isreserved(ts)) /* reserved word? */
  490. return ts->extra - 1 + FIRST_RESERVED;
  491. else {
  492. seminfo->ts = anchorstr(ls, ts);
  493. return TK_NAME;
  494. }
  495. }
  496. else { /* single-char tokens ('+', '*', '%', '{', '}', ...) */
  497. int c = ls->current;
  498. next(ls);
  499. return c;
  500. }
  501. }
  502. }
  503. }
  504. }
  505. void luaX_next (LexState *ls) {
  506. ls->lastline = ls->linenumber;
  507. if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
  508. ls->t = ls->lookahead; /* use this one */
  509. ls->lookahead.token = TK_EOS; /* and discharge it */
  510. }
  511. else
  512. ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */
  513. }
  514. int luaX_lookahead (LexState *ls) {
  515. lua_assert(ls->lookahead.token == TK_EOS);
  516. ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);
  517. return ls->lookahead.token;
  518. }