llex.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. /*
  2. ** $Id: llex.c,v 2.75 2014/04/30 16:48:44 roberto Exp roberto $
  3. ** Lexical Analyzer
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <locale.h>
  7. #include <string.h>
  8. #define llex_c
  9. #define LUA_CORE
  10. #include "lua.h"
  11. #include "lctype.h"
  12. #include "ldo.h"
  13. #include "lgc.h"
  14. #include "llex.h"
  15. #include "lobject.h"
  16. #include "lparser.h"
  17. #include "lstate.h"
  18. #include "lstring.h"
  19. #include "ltable.h"
  20. #include "lzio.h"
  21. #define next(ls) (ls->current = zgetc(ls->z))
  22. #define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r')
  23. /* ORDER RESERVED */
  24. static const char *const luaX_tokens [] = {
  25. "and", "break", "do", "else", "elseif",
  26. "end", "false", "for", "function", "goto", "if",
  27. "in", "local", "nil", "not", "or", "repeat",
  28. "return", "then", "true", "until", "while",
  29. "//", "..", "...", "==", ">=", "<=", "~=",
  30. "<<", ">>", "::", "<eof>",
  31. "<number>", "<number>", "<name>", "<string>"
  32. };
  33. #define save_and_next(ls) (save(ls, ls->current), next(ls))
  34. static l_noret lexerror (LexState *ls, const char *msg, int token);
  35. static void save (LexState *ls, int c) {
  36. Mbuffer *b = ls->buff;
  37. if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {
  38. size_t newsize;
  39. if (luaZ_sizebuffer(b) >= MAX_SIZE/2)
  40. lexerror(ls, "lexical element too long", 0);
  41. newsize = luaZ_sizebuffer(b) * 2;
  42. luaZ_resizebuffer(ls->L, b, newsize);
  43. }
  44. b->buffer[luaZ_bufflen(b)++] = cast(char, c);
  45. }
  46. void luaX_init (lua_State *L) {
  47. int i;
  48. TString *e = luaS_new(L, LUA_ENV); /* create env name */
  49. luaC_fix(L, obj2gco(e)); /* never collect this name */
  50. for (i=0; i<NUM_RESERVED; i++) {
  51. TString *ts = luaS_new(L, luaX_tokens[i]);
  52. luaC_fix(L, obj2gco(ts)); /* reserved words are never collected */
  53. ts->tsv.extra = cast_byte(i+1); /* reserved word */
  54. }
  55. }
  56. const char *luaX_token2str (LexState *ls, int token) {
  57. if (token < FIRST_RESERVED) { /* single-byte symbols? */
  58. lua_assert(token == cast(unsigned char, token));
  59. return (lisprint(token)) ? luaO_pushfstring(ls->L, LUA_QL("%c"), token) :
  60. luaO_pushfstring(ls->L, "char(%d)", token);
  61. }
  62. else {
  63. const char *s = luaX_tokens[token - FIRST_RESERVED];
  64. if (token < TK_EOS) /* fixed format (symbols and reserved words)? */
  65. return luaO_pushfstring(ls->L, LUA_QS, s);
  66. else /* names, strings, and numerals */
  67. return s;
  68. }
  69. }
  70. static const char *txtToken (LexState *ls, int token) {
  71. switch (token) {
  72. case TK_NAME: case TK_STRING:
  73. case TK_FLT: case TK_INT:
  74. save(ls, '\0');
  75. return luaO_pushfstring(ls->L, LUA_QS, luaZ_buffer(ls->buff));
  76. default:
  77. return luaX_token2str(ls, token);
  78. }
  79. }
  80. static l_noret lexerror (LexState *ls, const char *msg, int token) {
  81. char buff[LUA_IDSIZE];
  82. luaO_chunkid(buff, getstr(ls->source), LUA_IDSIZE);
  83. msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg);
  84. if (token)
  85. luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token));
  86. luaD_throw(ls->L, LUA_ERRSYNTAX);
  87. }
  88. l_noret luaX_syntaxerror (LexState *ls, const char *msg) {
  89. lexerror(ls, msg, ls->t.token);
  90. }
  91. /*
  92. ** creates a new string and anchors it in scanner's table so that
  93. ** it will not be collected until the end of the compilation
  94. ** (by that time it should be anchored somewhere)
  95. */
  96. TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
  97. lua_State *L = ls->L;
  98. TValue *o; /* entry for `str' */
  99. TString *ts = luaS_newlstr(L, str, l); /* create new string */
  100. setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */
  101. o = luaH_set(L, ls->h, L->top - 1);
  102. if (ttisnil(o)) { /* not in use yet? */
  103. /* boolean value does not need GC barrier;
  104. table has no metatable, so it does not need to invalidate cache */
  105. setbvalue(o, 1); /* t[string] = true */
  106. luaC_checkGC(L);
  107. }
  108. else { /* string already present */
  109. ts = rawtsvalue(keyfromval(o)); /* re-use value previously stored */
  110. }
  111. L->top--; /* remove string from stack */
  112. return ts;
  113. }
  114. /*
  115. ** increment line number and skips newline sequence (any of
  116. ** \n, \r, \n\r, or \r\n)
  117. */
  118. static void inclinenumber (LexState *ls) {
  119. int old = ls->current;
  120. lua_assert(currIsNewline(ls));
  121. next(ls); /* skip `\n' or `\r' */
  122. if (currIsNewline(ls) && ls->current != old)
  123. next(ls); /* skip `\n\r' or `\r\n' */
  124. if (++ls->linenumber >= MAX_INT)
  125. luaX_syntaxerror(ls, "chunk has too many lines");
  126. }
  127. void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
  128. int firstchar) {
  129. ls->decpoint = '.';
  130. ls->L = L;
  131. ls->current = firstchar;
  132. ls->lookahead.token = TK_EOS; /* no look-ahead token */
  133. ls->z = z;
  134. ls->fs = NULL;
  135. ls->linenumber = 1;
  136. ls->lastline = 1;
  137. ls->source = source;
  138. ls->envn = luaS_new(L, LUA_ENV); /* get env name */
  139. luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
  140. }
  141. /*
  142. ** =======================================================
  143. ** LEXICAL ANALYZER
  144. ** =======================================================
  145. */
  146. static int check_next (LexState *ls, const char *set) {
  147. if (ls->current == '\0' || !strchr(set, ls->current))
  148. return 0;
  149. save_and_next(ls);
  150. return 1;
  151. }
  152. /*
  153. ** change all characters 'from' in buffer to 'to'
  154. */
  155. static void buffreplace (LexState *ls, char from, char to) {
  156. if (from != to) {
  157. size_t n = luaZ_bufflen(ls->buff);
  158. char *p = luaZ_buffer(ls->buff);
  159. while (n--)
  160. if (p[n] == from) p[n] = to;
  161. }
  162. }
  163. #if !defined(getlocaledecpoint)
  164. #define getlocaledecpoint() (localeconv()->decimal_point[0])
  165. #endif
  166. #define buff2num(b,o) (luaO_str2num(luaZ_buffer(b), o) != 0)
  167. /*
  168. ** in case of format error, try to change decimal point separator to
  169. ** the one defined in the current locale and check again
  170. */
  171. static void trydecpoint (LexState *ls, TValue *o) {
  172. char old = ls->decpoint;
  173. ls->decpoint = getlocaledecpoint();
  174. buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
  175. if (!buff2num(ls->buff, o)) {
  176. /* format error with correct decimal point: no more options */
  177. buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
  178. lexerror(ls, "malformed number", TK_FLT);
  179. }
  180. }
  181. /* LUA_NUMBER */
  182. /*
  183. ** this function is quite liberal in what it accepts, as 'luaO_str2num'
  184. ** will reject ill-formed numerals.
  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_next(ls, "Xx")) /* hexadecimal? */
  193. expo = "Pp";
  194. for (;;) {
  195. if (check_next(ls, expo)) /* exponent part? */
  196. check_next(ls, "+-"); /* optional exponent sign */
  197. if (lisxdigit(ls->current))
  198. save_and_next(ls);
  199. else if (ls->current == '.')
  200. save_and_next(ls);
  201. else break;
  202. }
  203. save(ls, '\0');
  204. buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */
  205. if (!buff2num(ls->buff, &obj)) /* format error? */
  206. trydecpoint(ls, &obj); /* try to update decimal point separator */
  207. if (ttisinteger(&obj)) {
  208. seminfo->i = ivalue(&obj);
  209. return TK_INT;
  210. }
  211. else {
  212. lua_assert(ttisfloat(&obj));
  213. seminfo->r = fltvalue(&obj);
  214. return TK_FLT;
  215. }
  216. }
  217. /*
  218. ** skip a sequence '[=*[' or ']=*]' and return its number of '='s or
  219. ** -1 if sequence is malformed
  220. */
  221. static int skip_sep (LexState *ls) {
  222. int count = 0;
  223. int s = ls->current;
  224. lua_assert(s == '[' || s == ']');
  225. save_and_next(ls);
  226. while (ls->current == '=') {
  227. save_and_next(ls);
  228. count++;
  229. }
  230. return (ls->current == s) ? count : (-count) - 1;
  231. }
  232. static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
  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:
  239. lexerror(ls, (seminfo) ? "unfinished long string" :
  240. "unfinished long comment", TK_EOS);
  241. break; /* to avoid warnings */
  242. case ']': {
  243. if (skip_sep(ls) == sep) {
  244. save_and_next(ls); /* skip 2nd `]' */
  245. goto endloop;
  246. }
  247. break;
  248. }
  249. case '\n': case '\r': {
  250. save(ls, '\n');
  251. inclinenumber(ls);
  252. if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */
  253. break;
  254. }
  255. default: {
  256. if (seminfo) save_and_next(ls);
  257. else next(ls);
  258. }
  259. }
  260. } endloop:
  261. if (seminfo)
  262. seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep),
  263. luaZ_bufflen(ls->buff) - 2*(2 + sep));
  264. }
  265. static void esccheck (LexState *ls, int c, const char *msg) {
  266. if (!c) {
  267. if (ls->current != EOZ)
  268. save_and_next(ls); /* add current to buffer for error message */
  269. lexerror(ls, msg, TK_STRING);
  270. }
  271. }
  272. static int gethexa (LexState *ls) {
  273. save_and_next(ls);
  274. esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected");
  275. return luaO_hexavalue(ls->current);
  276. }
  277. static int readhexaesc (LexState *ls) {
  278. int r = gethexa(ls);
  279. r = (r << 4) + gethexa(ls);
  280. luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */
  281. return r;
  282. }
  283. static unsigned int readutf8esc (LexState *ls) {
  284. unsigned int r;
  285. int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */
  286. save_and_next(ls); /* skip 'u' */
  287. esccheck(ls, ls->current == '{', "missing '{'");
  288. r = gethexa(ls); /* must have at least one digit */
  289. while ((save_and_next(ls), lisxdigit(ls->current))) {
  290. i++;
  291. r = (r << 4) + luaO_hexavalue(ls->current);
  292. esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large");
  293. }
  294. esccheck(ls, ls->current == '}', "missing '}'");
  295. next(ls); /* skip '}' */
  296. luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */
  297. return r;
  298. }
  299. static void utf8esc (LexState *ls) {
  300. char buff[UTF8BUFFSZ];
  301. int n = luaO_utf8esc(buff, readutf8esc(ls));
  302. for (; n > 0; n--) /* add 'buff' to string */
  303. save(ls, buff[UTF8BUFFSZ - n]);
  304. }
  305. static int readdecesc (LexState *ls) {
  306. int i;
  307. int r = 0; /* result accumulator */
  308. for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
  309. r = 10*r + ls->current - '0';
  310. save_and_next(ls);
  311. }
  312. esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
  313. luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */
  314. return r;
  315. }
  316. static void read_string (LexState *ls, int del, SemInfo *seminfo) {
  317. save_and_next(ls); /* keep delimiter (for error messages) */
  318. while (ls->current != del) {
  319. switch (ls->current) {
  320. case EOZ:
  321. lexerror(ls, "unfinished string", TK_EOS);
  322. break; /* to avoid warnings */
  323. case '\n':
  324. case '\r':
  325. lexerror(ls, "unfinished string", TK_STRING);
  326. break; /* to avoid warnings */
  327. case '\\': { /* escape sequences */
  328. int c; /* final character to be saved */
  329. save_and_next(ls); /* keep '\\' for error messages */
  330. switch (ls->current) {
  331. case 'a': c = '\a'; goto read_save;
  332. case 'b': c = '\b'; goto read_save;
  333. case 'f': c = '\f'; goto read_save;
  334. case 'n': c = '\n'; goto read_save;
  335. case 'r': c = '\r'; goto read_save;
  336. case 't': c = '\t'; goto read_save;
  337. case 'v': c = '\v'; goto read_save;
  338. case 'x': c = readhexaesc(ls); goto read_save;
  339. case 'u': utf8esc(ls); goto no_save;
  340. case '\n': case '\r':
  341. inclinenumber(ls); c = '\n'; goto only_save;
  342. case '\\': case '\"': case '\'':
  343. c = ls->current; goto read_save;
  344. case EOZ: goto no_save; /* will raise an error next loop */
  345. case 'z': { /* zap following span of spaces */
  346. luaZ_buffremove(ls->buff, 1); /* remove '\\' */
  347. next(ls); /* skip the 'z' */
  348. while (lisspace(ls->current)) {
  349. if (currIsNewline(ls)) inclinenumber(ls);
  350. else next(ls);
  351. }
  352. goto no_save;
  353. }
  354. default: {
  355. esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
  356. c = readdecesc(ls); /* digital escape \ddd */
  357. goto only_save;
  358. }
  359. }
  360. read_save:
  361. next(ls);
  362. /* go through */
  363. only_save:
  364. luaZ_buffremove(ls->buff, 1); /* remove '\\' */
  365. save(ls, c);
  366. /* go through */
  367. no_save: break;
  368. }
  369. default:
  370. save_and_next(ls);
  371. }
  372. }
  373. save_and_next(ls); /* skip delimiter */
  374. seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
  375. luaZ_bufflen(ls->buff) - 2);
  376. }
  377. static int llex (LexState *ls, SemInfo *seminfo) {
  378. luaZ_resetbuffer(ls->buff);
  379. for (;;) {
  380. switch (ls->current) {
  381. case '\n': case '\r': { /* line breaks */
  382. inclinenumber(ls);
  383. break;
  384. }
  385. case ' ': case '\f': case '\t': case '\v': { /* spaces */
  386. next(ls);
  387. break;
  388. }
  389. case '-': { /* '-' or '--' (comment) */
  390. next(ls);
  391. if (ls->current != '-') return '-';
  392. /* else is a comment */
  393. next(ls);
  394. if (ls->current == '[') { /* long comment? */
  395. int sep = skip_sep(ls);
  396. luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */
  397. if (sep >= 0) {
  398. read_long_string(ls, NULL, sep); /* skip long comment */
  399. luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
  400. break;
  401. }
  402. }
  403. /* else short comment */
  404. while (!currIsNewline(ls) && ls->current != EOZ)
  405. next(ls); /* skip until end of line (or end of file) */
  406. break;
  407. }
  408. case '[': { /* long string or simply '[' */
  409. int sep = skip_sep(ls);
  410. if (sep >= 0) {
  411. read_long_string(ls, seminfo, sep);
  412. return TK_STRING;
  413. }
  414. else if (sep == -1) return '[';
  415. else lexerror(ls, "invalid long string delimiter", TK_STRING);
  416. }
  417. case '=': {
  418. next(ls);
  419. if (ls->current != '=') return '=';
  420. else { next(ls); return TK_EQ; }
  421. }
  422. case '<': {
  423. next(ls);
  424. if (ls->current == '=') { next(ls); return TK_LE; }
  425. if (ls->current == '<') { next(ls); return TK_SHL; }
  426. return '<';
  427. }
  428. case '>': {
  429. next(ls);
  430. if (ls->current == '=') { next(ls); return TK_GE; }
  431. if (ls->current == '>') { next(ls); return TK_SHR; }
  432. return '>';
  433. }
  434. case '/': {
  435. next(ls);
  436. if (ls->current != '/') return '/';
  437. else { next(ls); return TK_IDIV; }
  438. }
  439. case '~': {
  440. next(ls);
  441. if (ls->current != '=') return '~';
  442. else { next(ls); return TK_NE; }
  443. }
  444. case ':': {
  445. next(ls);
  446. if (ls->current != ':') return ':';
  447. else { next(ls); return TK_DBCOLON; }
  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_next(ls, ".")) {
  456. if (check_next(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->tsv.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. }