llex.c 16 KB

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