llex.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 it
  94. ** will not be collected until the end of the compilation; by that time
  95. ** it should be anchored somewhere. It also internalizes long strings,
  96. ** ensuring there is only one copy of each unique string. The table
  97. ** here is used as a set: the string enters as the key, while its value
  98. ** is irrelevant. We use the string itself as the value only because it
  99. ** is a TValue readily available. Later, the code generation can change
  100. ** this value.
  101. */
  102. TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
  103. lua_State *L = ls->L;
  104. TString *ts = luaS_newlstr(L, str, l); /* create new string */
  105. const TValue *o = luaH_getstr(ls->h, ts);
  106. if (!ttisnil(o)) /* string already present? */
  107. ts = keystrval(nodefromval(o)); /* get saved copy */
  108. else { /* not in use yet */
  109. TValue *stv = s2v(L->top.p++); /* reserve stack space for string */
  110. setsvalue(L, stv, ts); /* temporarily anchor the string */
  111. luaH_finishset(L, ls->h, stv, o, 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. }
  116. return ts;
  117. }
  118. /*
  119. ** increment line number and skips newline sequence (any of
  120. ** \n, \r, \n\r, or \r\n)
  121. */
  122. static void inclinenumber (LexState *ls) {
  123. int old = ls->current;
  124. lua_assert(currIsNewline(ls));
  125. next(ls); /* skip '\n' or '\r' */
  126. if (currIsNewline(ls) && ls->current != old)
  127. next(ls); /* skip '\n\r' or '\r\n' */
  128. if (++ls->linenumber >= MAX_INT)
  129. lexerror(ls, "chunk has too many lines", 0);
  130. }
  131. void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
  132. int firstchar) {
  133. ls->t.token = 0;
  134. ls->L = L;
  135. ls->current = firstchar;
  136. ls->lookahead.token = TK_EOS; /* no look-ahead token */
  137. ls->z = z;
  138. ls->fs = NULL;
  139. ls->linenumber = 1;
  140. ls->lastline = 1;
  141. ls->source = source;
  142. ls->envn = luaS_newliteral(L, LUA_ENV); /* get env name */
  143. luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
  144. }
  145. /*
  146. ** =======================================================
  147. ** LEXICAL ANALYZER
  148. ** =======================================================
  149. */
  150. static int check_next1 (LexState *ls, int c) {
  151. if (ls->current == c) {
  152. next(ls);
  153. return 1;
  154. }
  155. else return 0;
  156. }
  157. /*
  158. ** Check whether current char is in set 'set' (with two chars) and
  159. ** saves it
  160. */
  161. static int check_next2 (LexState *ls, const char *set) {
  162. lua_assert(set[2] == '\0');
  163. if (ls->current == set[0] || ls->current == set[1]) {
  164. save_and_next(ls);
  165. return 1;
  166. }
  167. else return 0;
  168. }
  169. /* LUA_NUMBER */
  170. /*
  171. ** This function is quite liberal in what it accepts, as 'luaO_str2num'
  172. ** will reject ill-formed numerals. Roughly, it accepts the following
  173. ** pattern:
  174. **
  175. ** %d(%x|%.|([Ee][+-]?))* | 0[Xx](%x|%.|([Pp][+-]?))*
  176. **
  177. ** The only tricky part is to accept [+-] only after a valid exponent
  178. ** mark, to avoid reading '3-4' or '0xe+1' as a single number.
  179. **
  180. ** The caller might have already read an initial dot.
  181. */
  182. static int read_numeral (LexState *ls, SemInfo *seminfo) {
  183. TValue obj;
  184. const char *expo = "Ee";
  185. int first = ls->current;
  186. lua_assert(lisdigit(ls->current));
  187. save_and_next(ls);
  188. if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */
  189. expo = "Pp";
  190. for (;;) {
  191. if (check_next2(ls, expo)) /* exponent mark? */
  192. check_next2(ls, "-+"); /* optional exponent sign */
  193. else if (lisxdigit(ls->current) || ls->current == '.') /* '%x|%.' */
  194. save_and_next(ls);
  195. else break;
  196. }
  197. if (lislalpha(ls->current)) /* is numeral touching a letter? */
  198. save_and_next(ls); /* force an error */
  199. save(ls, '\0');
  200. if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */
  201. lexerror(ls, "malformed number", TK_FLT);
  202. if (ttisinteger(&obj)) {
  203. seminfo->i = ivalue(&obj);
  204. return TK_INT;
  205. }
  206. else {
  207. lua_assert(ttisfloat(&obj));
  208. seminfo->r = fltvalue(&obj);
  209. return TK_FLT;
  210. }
  211. }
  212. /*
  213. ** read a sequence '[=*[' or ']=*]', leaving the last bracket. If
  214. ** sequence is well formed, return its number of '='s + 2; otherwise,
  215. ** return 1 if it is a single bracket (no '='s and no 2nd bracket);
  216. ** otherwise (an unfinished '[==...') return 0.
  217. */
  218. static size_t skip_sep (LexState *ls) {
  219. size_t count = 0;
  220. int s = ls->current;
  221. lua_assert(s == '[' || s == ']');
  222. save_and_next(ls);
  223. while (ls->current == '=') {
  224. save_and_next(ls);
  225. count++;
  226. }
  227. return (ls->current == s) ? count + 2
  228. : (count == 0) ? 1
  229. : 0;
  230. }
  231. static void read_long_string (LexState *ls, SemInfo *seminfo, size_t sep) {
  232. int line = ls->linenumber; /* initial line (for error message) */
  233. save_and_next(ls); /* skip 2nd '[' */
  234. if (currIsNewline(ls)) /* string starts with a newline? */
  235. inclinenumber(ls); /* skip it */
  236. for (;;) {
  237. switch (ls->current) {
  238. case EOZ: { /* error */
  239. const char *what = (seminfo ? "string" : "comment");
  240. const char *msg = luaO_pushfstring(ls->L,
  241. "unfinished long %s (starting at line %d)", what, line);
  242. lexerror(ls, msg, TK_EOS);
  243. break; /* to avoid warnings */
  244. }
  245. case ']': {
  246. if (skip_sep(ls) == sep) {
  247. save_and_next(ls); /* skip 2nd ']' */
  248. goto endloop;
  249. }
  250. break;
  251. }
  252. case '\n': case '\r': {
  253. save(ls, '\n');
  254. inclinenumber(ls);
  255. if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */
  256. break;
  257. }
  258. default: {
  259. if (seminfo) save_and_next(ls);
  260. else next(ls);
  261. }
  262. }
  263. } endloop:
  264. if (seminfo)
  265. seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + sep,
  266. luaZ_bufflen(ls->buff) - 2 * sep);
  267. }
  268. static void esccheck (LexState *ls, int c, const char *msg) {
  269. if (!c) {
  270. if (ls->current != EOZ)
  271. save_and_next(ls); /* add current to buffer for error message */
  272. lexerror(ls, msg, TK_STRING);
  273. }
  274. }
  275. static int gethexa (LexState *ls) {
  276. save_and_next(ls);
  277. esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected");
  278. return luaO_hexavalue(ls->current);
  279. }
  280. static int readhexaesc (LexState *ls) {
  281. int r = gethexa(ls);
  282. r = (r << 4) + gethexa(ls);
  283. luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */
  284. return r;
  285. }
  286. static unsigned long readutf8esc (LexState *ls) {
  287. unsigned long r;
  288. int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */
  289. save_and_next(ls); /* skip 'u' */
  290. esccheck(ls, ls->current == '{', "missing '{'");
  291. r = gethexa(ls); /* must have at least one digit */
  292. while (cast_void(save_and_next(ls)), lisxdigit(ls->current)) {
  293. i++;
  294. esccheck(ls, r <= (0x7FFFFFFFu >> 4), "UTF-8 value too large");
  295. r = (r << 4) + luaO_hexavalue(ls->current);
  296. }
  297. esccheck(ls, ls->current == '}', "missing '}'");
  298. next(ls); /* skip '}' */
  299. luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */
  300. return r;
  301. }
  302. static void utf8esc (LexState *ls) {
  303. char buff[UTF8BUFFSZ];
  304. int n = luaO_utf8esc(buff, readutf8esc(ls));
  305. for (; n > 0; n--) /* add 'buff' to string */
  306. save(ls, buff[UTF8BUFFSZ - n]);
  307. }
  308. static int readdecesc (LexState *ls) {
  309. int i;
  310. int r = 0; /* result accumulator */
  311. for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
  312. r = 10*r + ls->current - '0';
  313. save_and_next(ls);
  314. }
  315. esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
  316. luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */
  317. return r;
  318. }
  319. static void read_string (LexState *ls, int del, SemInfo *seminfo) {
  320. save_and_next(ls); /* keep delimiter (for error messages) */
  321. while (ls->current != del) {
  322. switch (ls->current) {
  323. case EOZ:
  324. lexerror(ls, "unfinished string", TK_EOS);
  325. break; /* to avoid warnings */
  326. case '\n':
  327. case '\r':
  328. lexerror(ls, "unfinished string", TK_STRING);
  329. break; /* to avoid warnings */
  330. case '\\': { /* escape sequences */
  331. int c; /* final character to be saved */
  332. save_and_next(ls); /* keep '\\' for error messages */
  333. switch (ls->current) {
  334. case 'a': c = '\a'; goto read_save;
  335. case 'b': c = '\b'; goto read_save;
  336. case 'f': c = '\f'; goto read_save;
  337. case 'n': c = '\n'; goto read_save;
  338. case 'r': c = '\r'; goto read_save;
  339. case 't': c = '\t'; goto read_save;
  340. case 'v': c = '\v'; goto read_save;
  341. case 'x': c = readhexaesc(ls); goto read_save;
  342. case 'u': utf8esc(ls); goto no_save;
  343. case '\n': case '\r':
  344. inclinenumber(ls); c = '\n'; goto only_save;
  345. case '\\': case '\"': case '\'':
  346. c = ls->current; goto read_save;
  347. case EOZ: goto no_save; /* will raise an error next loop */
  348. case 'z': { /* zap following span of spaces */
  349. luaZ_buffremove(ls->buff, 1); /* remove '\\' */
  350. next(ls); /* skip the 'z' */
  351. while (lisspace(ls->current)) {
  352. if (currIsNewline(ls)) inclinenumber(ls);
  353. else next(ls);
  354. }
  355. goto no_save;
  356. }
  357. default: {
  358. esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
  359. c = readdecesc(ls); /* digital escape '\ddd' */
  360. goto only_save;
  361. }
  362. }
  363. read_save:
  364. next(ls);
  365. /* go through */
  366. only_save:
  367. luaZ_buffremove(ls->buff, 1); /* remove '\\' */
  368. save(ls, c);
  369. /* go through */
  370. no_save: break;
  371. }
  372. default:
  373. save_and_next(ls);
  374. }
  375. }
  376. save_and_next(ls); /* skip delimiter */
  377. seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
  378. luaZ_bufflen(ls->buff) - 2);
  379. }
  380. static int llex (LexState *ls, SemInfo *seminfo) {
  381. luaZ_resetbuffer(ls->buff);
  382. for (;;) {
  383. switch (ls->current) {
  384. case '\n': case '\r': { /* line breaks */
  385. inclinenumber(ls);
  386. break;
  387. }
  388. case ' ': case '\f': case '\t': case '\v': { /* spaces */
  389. next(ls);
  390. break;
  391. }
  392. case '-': { /* '-' or '--' (comment) */
  393. next(ls);
  394. if (ls->current != '-') return '-';
  395. /* else is a comment */
  396. next(ls);
  397. if (ls->current == '[') { /* long comment? */
  398. size_t sep = skip_sep(ls);
  399. luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */
  400. if (sep >= 2) {
  401. read_long_string(ls, NULL, sep); /* skip long comment */
  402. luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
  403. break;
  404. }
  405. }
  406. /* else short comment */
  407. while (!currIsNewline(ls) && ls->current != EOZ)
  408. next(ls); /* skip until end of line (or end of file) */
  409. break;
  410. }
  411. case '[': { /* long string or simply '[' */
  412. size_t sep = skip_sep(ls);
  413. if (sep >= 2) {
  414. read_long_string(ls, seminfo, sep);
  415. return TK_STRING;
  416. }
  417. else if (sep == 0) /* '[=...' missing second bracket? */
  418. lexerror(ls, "invalid long string delimiter", TK_STRING);
  419. return '[';
  420. }
  421. case '=': {
  422. next(ls);
  423. if (check_next1(ls, '=')) return TK_EQ; /* '==' */
  424. else return '=';
  425. }
  426. case '<': {
  427. next(ls);
  428. if (check_next1(ls, '=')) return TK_LE; /* '<=' */
  429. else if (check_next1(ls, '<')) return TK_SHL; /* '<<' */
  430. else return '<';
  431. }
  432. case '>': {
  433. next(ls);
  434. if (check_next1(ls, '=')) return TK_GE; /* '>=' */
  435. else if (check_next1(ls, '>')) return TK_SHR; /* '>>' */
  436. else return '>';
  437. }
  438. case '/': {
  439. next(ls);
  440. if (check_next1(ls, '/')) return TK_IDIV; /* '//' */
  441. else return '/';
  442. }
  443. case '~': {
  444. next(ls);
  445. if (check_next1(ls, '=')) return TK_NE; /* '~=' */
  446. else return '~';
  447. }
  448. case ':': {
  449. next(ls);
  450. if (check_next1(ls, ':')) return TK_DBCOLON; /* '::' */
  451. else return ':';
  452. }
  453. case '"': case '\'': { /* short literal strings */
  454. read_string(ls, ls->current, seminfo);
  455. return TK_STRING;
  456. }
  457. case '.': { /* '.', '..', '...', or number */
  458. save_and_next(ls);
  459. if (check_next1(ls, '.')) {
  460. if (check_next1(ls, '.'))
  461. return TK_DOTS; /* '...' */
  462. else return TK_CONCAT; /* '..' */
  463. }
  464. else if (!lisdigit(ls->current)) return '.';
  465. else return read_numeral(ls, seminfo);
  466. }
  467. case '0': case '1': case '2': case '3': case '4':
  468. case '5': case '6': case '7': case '8': case '9': {
  469. return read_numeral(ls, seminfo);
  470. }
  471. case EOZ: {
  472. return TK_EOS;
  473. }
  474. default: {
  475. if (lislalpha(ls->current)) { /* identifier or reserved word? */
  476. TString *ts;
  477. do {
  478. save_and_next(ls);
  479. } while (lislalnum(ls->current));
  480. ts = luaX_newstring(ls, luaZ_buffer(ls->buff),
  481. luaZ_bufflen(ls->buff));
  482. seminfo->ts = ts;
  483. if (isreserved(ts)) /* reserved word? */
  484. return ts->extra - 1 + FIRST_RESERVED;
  485. else {
  486. return TK_NAME;
  487. }
  488. }
  489. else { /* single-char tokens ('+', '*', '%', '{', '}', ...) */
  490. int c = ls->current;
  491. next(ls);
  492. return c;
  493. }
  494. }
  495. }
  496. }
  497. }
  498. void luaX_next (LexState *ls) {
  499. ls->lastline = ls->linenumber;
  500. if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
  501. ls->t = ls->lookahead; /* use this one */
  502. ls->lookahead.token = TK_EOS; /* and discharge it */
  503. }
  504. else
  505. ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */
  506. }
  507. int luaX_lookahead (LexState *ls) {
  508. lua_assert(ls->lookahead.token == TK_EOS);
  509. ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);
  510. return ls->lookahead.token;
  511. }