llex.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. /*
  2. ** $Id: llex.c,v 2.69 2013/08/30 16:01:37 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. size_t n = luaZ_bufflen(ls->buff);
  157. char *p = luaZ_buffer(ls->buff);
  158. while (n--)
  159. if (p[n] == from) p[n] = to;
  160. }
  161. #if !defined(getlocaledecpoint)
  162. #define getlocaledecpoint() (localeconv()->decimal_point[0])
  163. #endif
  164. #define buff2d(b,e) luaO_str2d(luaZ_buffer(b), luaZ_bufflen(b) - 1, e)
  165. /*
  166. ** in case of format error, try to change decimal point separator to
  167. ** the one defined in the current locale and check again
  168. */
  169. static void trydecpoint (LexState *ls, SemInfo *seminfo) {
  170. char old = ls->decpoint;
  171. ls->decpoint = getlocaledecpoint();
  172. buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
  173. if (!buff2d(ls->buff, &seminfo->r)) {
  174. /* format error with correct decimal point: no more options */
  175. buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
  176. lexerror(ls, "malformed number", TK_FLT);
  177. }
  178. }
  179. /* LUA_NUMBER */
  180. /*
  181. ** this function is quite liberal in what it accepts, as 'luaO_str2d'
  182. ** will reject ill-formed numerals. 'isf' means the numeral is not
  183. ** an integer (it has a dot or an exponent).
  184. */
  185. static int read_numeral (LexState *ls, SemInfo *seminfo, int isf) {
  186. const char *expo = "Ee";
  187. int first = ls->current;
  188. lua_assert(lisdigit(ls->current));
  189. save_and_next(ls);
  190. if (first == '0' && check_next(ls, "Xx")) /* hexadecimal? */
  191. expo = "Pp";
  192. for (;;) {
  193. if (check_next(ls, expo)) { /* exponent part? */
  194. check_next(ls, "+-"); /* optional exponent sign */
  195. isf = 1;
  196. }
  197. if (lisxdigit(ls->current))
  198. save_and_next(ls);
  199. else if (ls->current == '.') {
  200. save_and_next(ls);
  201. isf = 1;
  202. }
  203. else break;
  204. }
  205. save(ls, '\0');
  206. if (!isf) {
  207. if (!luaO_str2int(luaZ_buffer(ls->buff), luaZ_bufflen(ls->buff) - 1,
  208. &seminfo->i))
  209. lexerror(ls, "malformed number", TK_INT);
  210. return TK_INT;
  211. }
  212. else {
  213. buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */
  214. if (!buff2d(ls->buff, &seminfo->r)) /* format error? */
  215. trydecpoint(ls, seminfo); /* try to update decimal point separator */
  216. return TK_FLT;
  217. }
  218. }
  219. /*
  220. ** skip a sequence '[=*[' or ']=*]' and return its number of '='s or
  221. ** -1 if sequence is malformed
  222. */
  223. static int skip_sep (LexState *ls) {
  224. int count = 0;
  225. int s = ls->current;
  226. lua_assert(s == '[' || s == ']');
  227. save_and_next(ls);
  228. while (ls->current == '=') {
  229. save_and_next(ls);
  230. count++;
  231. }
  232. return (ls->current == s) ? count : (-count) - 1;
  233. }
  234. static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
  235. save_and_next(ls); /* skip 2nd `[' */
  236. if (currIsNewline(ls)) /* string starts with a newline? */
  237. inclinenumber(ls); /* skip it */
  238. for (;;) {
  239. switch (ls->current) {
  240. case EOZ:
  241. lexerror(ls, (seminfo) ? "unfinished long string" :
  242. "unfinished long comment", TK_EOS);
  243. break; /* to avoid warnings */
  244. case ']': {
  245. if (skip_sep(ls) == sep) {
  246. save_and_next(ls); /* skip 2nd `]' */
  247. goto endloop;
  248. }
  249. break;
  250. }
  251. case '\n': case '\r': {
  252. save(ls, '\n');
  253. inclinenumber(ls);
  254. if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */
  255. break;
  256. }
  257. default: {
  258. if (seminfo) save_and_next(ls);
  259. else next(ls);
  260. }
  261. }
  262. } endloop:
  263. if (seminfo)
  264. seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep),
  265. luaZ_bufflen(ls->buff) - 2*(2 + sep));
  266. }
  267. static void escerror (LexState *ls, int *c, int n, const char *msg) {
  268. int i;
  269. luaZ_resetbuffer(ls->buff); /* prepare error message */
  270. save(ls, '\\');
  271. for (i = 0; i < n && c[i] != EOZ; i++)
  272. save(ls, c[i]);
  273. lexerror(ls, msg, TK_STRING);
  274. }
  275. static int readhexaesc (LexState *ls) {
  276. int c[3], i; /* keep input for error message */
  277. int r = 0; /* result accumulator */
  278. c[0] = 'x'; /* for error message */
  279. for (i = 1; i < 3; i++) { /* read two hexadecimal digits */
  280. c[i] = next(ls);
  281. if (!lisxdigit(c[i]))
  282. escerror(ls, c, i + 1, "hexadecimal digit expected");
  283. r = (r << 4) + luaO_hexavalue(c[i]);
  284. }
  285. return r;
  286. }
  287. static int readdecesc (LexState *ls) {
  288. int c[3], i;
  289. int r = 0; /* result accumulator */
  290. for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
  291. c[i] = ls->current;
  292. r = 10*r + c[i] - '0';
  293. next(ls);
  294. }
  295. if (r > UCHAR_MAX)
  296. escerror(ls, c, i, "decimal escape too large");
  297. return r;
  298. }
  299. static void read_string (LexState *ls, int del, SemInfo *seminfo) {
  300. save_and_next(ls); /* keep delimiter (for error messages) */
  301. while (ls->current != del) {
  302. switch (ls->current) {
  303. case EOZ:
  304. lexerror(ls, "unfinished string", TK_EOS);
  305. break; /* to avoid warnings */
  306. case '\n':
  307. case '\r':
  308. lexerror(ls, "unfinished string", TK_STRING);
  309. break; /* to avoid warnings */
  310. case '\\': { /* escape sequences */
  311. int c; /* final character to be saved */
  312. next(ls); /* do not save the `\' */
  313. switch (ls->current) {
  314. case 'a': c = '\a'; goto read_save;
  315. case 'b': c = '\b'; goto read_save;
  316. case 'f': c = '\f'; goto read_save;
  317. case 'n': c = '\n'; goto read_save;
  318. case 'r': c = '\r'; goto read_save;
  319. case 't': c = '\t'; goto read_save;
  320. case 'v': c = '\v'; goto read_save;
  321. case 'x': c = readhexaesc(ls); goto read_save;
  322. case '\n': case '\r':
  323. inclinenumber(ls); c = '\n'; goto only_save;
  324. case '\\': case '\"': case '\'':
  325. c = ls->current; goto read_save;
  326. case EOZ: goto no_save; /* will raise an error next loop */
  327. case 'z': { /* zap following span of spaces */
  328. next(ls); /* skip the 'z' */
  329. while (lisspace(ls->current)) {
  330. if (currIsNewline(ls)) inclinenumber(ls);
  331. else next(ls);
  332. }
  333. goto no_save;
  334. }
  335. default: {
  336. if (!lisdigit(ls->current))
  337. escerror(ls, &ls->current, 1, "invalid escape sequence");
  338. /* digital escape \ddd */
  339. c = readdecesc(ls);
  340. goto only_save;
  341. }
  342. }
  343. read_save: next(ls); /* read next character */
  344. only_save: save(ls, c); /* save 'c' */
  345. no_save: break;
  346. }
  347. default:
  348. save_and_next(ls);
  349. }
  350. }
  351. save_and_next(ls); /* skip delimiter */
  352. seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
  353. luaZ_bufflen(ls->buff) - 2);
  354. }
  355. static int llex (LexState *ls, SemInfo *seminfo) {
  356. luaZ_resetbuffer(ls->buff);
  357. for (;;) {
  358. switch (ls->current) {
  359. case '\n': case '\r': { /* line breaks */
  360. inclinenumber(ls);
  361. break;
  362. }
  363. case ' ': case '\f': case '\t': case '\v': { /* spaces */
  364. next(ls);
  365. break;
  366. }
  367. case '-': { /* '-' or '--' (comment) */
  368. next(ls);
  369. if (ls->current != '-') return '-';
  370. /* else is a comment */
  371. next(ls);
  372. if (ls->current == '[') { /* long comment? */
  373. int sep = skip_sep(ls);
  374. luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */
  375. if (sep >= 0) {
  376. read_long_string(ls, NULL, sep); /* skip long comment */
  377. luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
  378. break;
  379. }
  380. }
  381. /* else short comment */
  382. while (!currIsNewline(ls) && ls->current != EOZ)
  383. next(ls); /* skip until end of line (or end of file) */
  384. break;
  385. }
  386. case '[': { /* long string or simply '[' */
  387. int sep = skip_sep(ls);
  388. if (sep >= 0) {
  389. read_long_string(ls, seminfo, sep);
  390. return TK_STRING;
  391. }
  392. else if (sep == -1) return '[';
  393. else lexerror(ls, "invalid long string delimiter", TK_STRING);
  394. }
  395. case '=': {
  396. next(ls);
  397. if (ls->current != '=') return '=';
  398. else { next(ls); return TK_EQ; }
  399. }
  400. case '<': {
  401. next(ls);
  402. if (ls->current == '=') { next(ls); return TK_LE; }
  403. if (ls->current == '<') { next(ls); return TK_SHL; }
  404. return '<';
  405. }
  406. case '>': {
  407. next(ls);
  408. if (ls->current == '=') { next(ls); return TK_GE; }
  409. if (ls->current == '>') { next(ls); return TK_SHR; }
  410. return '>';
  411. }
  412. case '/': {
  413. next(ls);
  414. if (ls->current != '/') return '/';
  415. else { next(ls); return TK_IDIV; }
  416. }
  417. case '~': {
  418. next(ls);
  419. if (ls->current != '=') return '~';
  420. else { next(ls); return TK_NE; }
  421. }
  422. case ':': {
  423. next(ls);
  424. if (ls->current != ':') return ':';
  425. else { next(ls); return TK_DBCOLON; }
  426. }
  427. case '"': case '\'': { /* short literal strings */
  428. read_string(ls, ls->current, seminfo);
  429. return TK_STRING;
  430. }
  431. case '.': { /* '.', '..', '...', or number */
  432. save_and_next(ls);
  433. if (check_next(ls, ".")) {
  434. if (check_next(ls, "."))
  435. return TK_DOTS; /* '...' */
  436. else return TK_CONCAT; /* '..' */
  437. }
  438. else if (!lisdigit(ls->current)) return '.';
  439. else return read_numeral(ls, seminfo, 1);
  440. }
  441. case '0': case '1': case '2': case '3': case '4':
  442. case '5': case '6': case '7': case '8': case '9': {
  443. return read_numeral(ls, seminfo, 0);
  444. }
  445. case EOZ: {
  446. return TK_EOS;
  447. }
  448. default: {
  449. if (lislalpha(ls->current)) { /* identifier or reserved word? */
  450. TString *ts;
  451. do {
  452. save_and_next(ls);
  453. } while (lislalnum(ls->current));
  454. ts = luaX_newstring(ls, luaZ_buffer(ls->buff),
  455. luaZ_bufflen(ls->buff));
  456. seminfo->ts = ts;
  457. if (isreserved(ts)) /* reserved word? */
  458. return ts->tsv.extra - 1 + FIRST_RESERVED;
  459. else {
  460. return TK_NAME;
  461. }
  462. }
  463. else { /* single-char tokens (+ - / ...) */
  464. int c = ls->current;
  465. next(ls);
  466. return c;
  467. }
  468. }
  469. }
  470. }
  471. }
  472. void luaX_next (LexState *ls) {
  473. ls->lastline = ls->linenumber;
  474. if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
  475. ls->t = ls->lookahead; /* use this one */
  476. ls->lookahead.token = TK_EOS; /* and discharge it */
  477. }
  478. else
  479. ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */
  480. }
  481. int luaX_lookahead (LexState *ls) {
  482. lua_assert(ls->lookahead.token == TK_EOS);
  483. ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);
  484. return ls->lookahead.token;
  485. }