llex.c 16 KB

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