llex.c 17 KB

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