lparser.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. /*
  2. ** $Id: lparser.c,v 1.109 2000/08/15 13:18:28 roberto Exp roberto $
  3. ** LL(1) Parser and code generator for Lua
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include "lua.h"
  9. #include "lcode.h"
  10. #include "lfunc.h"
  11. #include "llex.h"
  12. #include "lmem.h"
  13. #include "lobject.h"
  14. #include "lopcodes.h"
  15. #include "lparser.h"
  16. #include "lstate.h"
  17. #include "lstring.h"
  18. /*
  19. ** Constructors descriptor:
  20. ** `n' indicates number of elements, and `k' signals whether
  21. ** it is a list constructor (k = 0) or a record constructor (k = 1)
  22. ** or empty (k = ';' or '}')
  23. */
  24. typedef struct Constdesc {
  25. int n;
  26. int k;
  27. } Constdesc;
  28. typedef struct Breaklabel {
  29. struct Breaklabel *previous; /* chain */
  30. int breaklist;
  31. int stacklevel;
  32. } Breaklabel;
  33. /*
  34. ** prototypes for recursive non-terminal functions
  35. */
  36. static void body (LexState *ls, int needself, int line);
  37. static void chunk (LexState *ls);
  38. static void constructor (LexState *ls);
  39. static void expr (LexState *ls, expdesc *v);
  40. static void exp1 (LexState *ls);
  41. static void next (LexState *ls) {
  42. ls->lastline = ls->linenumber;
  43. if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
  44. ls->t = ls->lookahead; /* use this one */
  45. ls->lookahead.token = TK_EOS; /* and discharge it */
  46. }
  47. else
  48. ls->t.token = luaX_lex(ls); /* read next token */
  49. }
  50. static void lookahead (LexState *ls) {
  51. LUA_ASSERT(ls->lookahead.token == TK_EOS, "two look-aheads");
  52. ls->lookahead.token = luaX_lex(ls);
  53. }
  54. static void error_expected (LexState *ls, int token) {
  55. char buff[100], t[TOKEN_LEN];
  56. luaX_token2str(token, t);
  57. sprintf(buff, "`%.20s' expected", t);
  58. luaK_error(ls, buff);
  59. }
  60. static void check (LexState *ls, int c) {
  61. if (ls->t.token != c)
  62. error_expected(ls, c);
  63. next(ls);
  64. }
  65. static void check_condition (LexState *ls, int c, const char *msg) {
  66. if (!c) luaK_error(ls, msg);
  67. }
  68. static int optional (LexState *ls, int c) {
  69. if (ls->t.token == c) {
  70. next(ls);
  71. return 1;
  72. }
  73. else return 0;
  74. }
  75. static void check_match (LexState *ls, int what, int who, int where) {
  76. if (ls->t.token != what) {
  77. if (where == ls->linenumber)
  78. error_expected(ls, what);
  79. else {
  80. char buff[100];
  81. char t_what[TOKEN_LEN], t_who[TOKEN_LEN];
  82. luaX_token2str(what, t_what);
  83. luaX_token2str(who, t_who);
  84. sprintf(buff, "`%.20s' expected (to close `%.20s' at line %d)",
  85. t_what, t_who, where);
  86. luaK_error(ls, buff);
  87. }
  88. }
  89. next(ls);
  90. }
  91. static int string_constant (FuncState *fs, TString *s) {
  92. Proto *f = fs->f;
  93. int c = s->u.s.constindex;
  94. if (c >= f->nkstr || f->kstr[c] != s) {
  95. luaM_growvector(fs->L, f->kstr, f->nkstr, 1, TString *,
  96. "constant table overflow", MAXARG_U);
  97. c = f->nkstr++;
  98. f->kstr[c] = s;
  99. s->u.s.constindex = c; /* hint for next time */
  100. }
  101. return c;
  102. }
  103. static void code_string (LexState *ls, TString *s) {
  104. luaK_kstr(ls, string_constant(ls->fs, s));
  105. }
  106. static TString *str_checkname (LexState *ls) {
  107. TString *ts;
  108. check_condition(ls, (ls->t.token == TK_NAME), "<name> expected");
  109. ts = ls->t.seminfo.ts;
  110. next(ls);
  111. return ts;
  112. }
  113. static int checkname (LexState *ls) {
  114. return string_constant(ls->fs, str_checkname(ls));
  115. }
  116. static int luaI_registerlocalvar (LexState *ls, TString *varname) {
  117. Proto *f = ls->fs->f;
  118. luaM_growvector(ls->L, f->locvars, f->nlocvars, 1, LocVar, "", MAX_INT);
  119. f->locvars[f->nlocvars].varname = varname;
  120. return f->nlocvars++;
  121. }
  122. static void new_localvar (LexState *ls, TString *name, int n) {
  123. FuncState *fs = ls->fs;
  124. luaX_checklimit(ls, fs->nactloc+n+1, MAXLOCALS, "local variables");
  125. fs->actloc[fs->nactloc+n] = luaI_registerlocalvar(ls, name);
  126. }
  127. static void adjustlocalvars (LexState *ls, int nvars) {
  128. FuncState *fs = ls->fs;
  129. while (nvars--)
  130. fs->f->locvars[fs->actloc[fs->nactloc++]].startpc = fs->pc;
  131. }
  132. static void removelocalvars (LexState *ls, int nvars) {
  133. FuncState *fs = ls->fs;
  134. while (nvars--)
  135. fs->f->locvars[fs->actloc[--fs->nactloc]].endpc = fs->pc;
  136. }
  137. static void new_localvarstr (LexState *ls, const char *name, int n) {
  138. new_localvar(ls, luaS_newfixed(ls->L, name), n);
  139. }
  140. static int search_local (LexState *ls, TString *n, expdesc *var) {
  141. FuncState *fs;
  142. int level = 0;
  143. for (fs=ls->fs; fs; fs=fs->prev) {
  144. int i;
  145. for (i=fs->nactloc-1; i >= 0; i--) {
  146. if (n == fs->f->locvars[fs->actloc[i]].varname) {
  147. var->k = VLOCAL;
  148. var->u.index = i;
  149. return level;
  150. }
  151. }
  152. level++; /* `var' not found; check outer level */
  153. }
  154. var->k = VGLOBAL; /* not found in any level; must be global */
  155. return -1;
  156. }
  157. static void singlevar (LexState *ls, TString *n, expdesc *var) {
  158. int level = search_local(ls, n, var);
  159. if (level >= 1) /* neither local (0) nor global (-1)? */
  160. luaX_syntaxerror(ls, "cannot access a variable in outer scope", n->str);
  161. else if (level == -1) /* global? */
  162. var->u.index = string_constant(ls->fs, n);
  163. }
  164. static int indexupvalue (LexState *ls, expdesc *v) {
  165. FuncState *fs = ls->fs;
  166. int i;
  167. for (i=0; i<fs->nupvalues; i++) {
  168. if (fs->upvalues[i].k == v->k && fs->upvalues[i].u.index == v->u.index)
  169. return i;
  170. }
  171. /* new one */
  172. luaX_checklimit(ls, fs->nupvalues+1, MAXUPVALUES, "upvalues");
  173. fs->upvalues[fs->nupvalues] = *v;
  174. return fs->nupvalues++;
  175. }
  176. static void pushupvalue (LexState *ls, TString *n) {
  177. FuncState *fs = ls->fs;
  178. expdesc v;
  179. int level = search_local(ls, n, &v);
  180. if (level == -1) { /* global? */
  181. if (fs->prev == NULL)
  182. luaX_syntaxerror(ls, "cannot access upvalue in main", n->str);
  183. v.u.index = string_constant(fs->prev, n);
  184. }
  185. else if (level != 1)
  186. luaX_syntaxerror(ls,
  187. "upvalue must be global or local to immediately outer scope", n->str);
  188. luaK_code1(fs, OP_PUSHUPVALUE, indexupvalue(ls, &v));
  189. }
  190. static void adjust_mult_assign (LexState *ls, int nvars, int nexps) {
  191. FuncState *fs = ls->fs;
  192. int diff = nexps - nvars;
  193. if (nexps > 0 && luaK_lastisopen(fs)) { /* list ends in a function call */
  194. diff--; /* do not count function call itself */
  195. if (diff <= 0) { /* more variables than values? */
  196. luaK_setcallreturns(fs, -diff); /* function call provide extra values */
  197. diff = 0; /* no more difference */
  198. }
  199. else /* more values than variables */
  200. luaK_setcallreturns(fs, 0); /* call should provide no value */
  201. }
  202. /* push or pop eventual difference between list lengths */
  203. luaK_adjuststack(fs, diff);
  204. }
  205. static void code_params (LexState *ls, int nparams, int dots) {
  206. FuncState *fs = ls->fs;
  207. adjustlocalvars(ls, nparams);
  208. luaX_checklimit(ls, fs->nactloc, MAXPARAMS, "parameters");
  209. fs->f->numparams = fs->nactloc; /* `self' could be there already */
  210. fs->f->is_vararg = dots;
  211. if (dots) {
  212. new_localvarstr(ls, "arg", 0);
  213. adjustlocalvars(ls, 1);
  214. }
  215. luaK_deltastack(fs, fs->nactloc); /* count parameters in the stack */
  216. }
  217. static void enterbreak (FuncState *fs, Breaklabel *bl) {
  218. bl->stacklevel = fs->stacklevel;
  219. bl->breaklist = NO_JUMP;
  220. bl->previous = fs->bl;
  221. fs->bl = bl;
  222. }
  223. static void leavebreak (FuncState *fs, Breaklabel *bl) {
  224. fs->bl = bl->previous;
  225. LUA_ASSERT(bl->stacklevel == fs->stacklevel, "wrong levels");
  226. luaK_patchlist(fs, bl->breaklist, luaK_getlabel(fs));
  227. }
  228. static void pushclosure (LexState *ls, FuncState *func) {
  229. FuncState *fs = ls->fs;
  230. Proto *f = fs->f;
  231. int i;
  232. for (i=0; i<func->nupvalues; i++)
  233. luaK_tostack(ls, &func->upvalues[i], 1);
  234. luaM_growvector(ls->L, f->kproto, f->nkproto, 1, Proto *,
  235. "constant table overflow", MAXARG_A);
  236. f->kproto[f->nkproto++] = func->f;
  237. luaK_code2(fs, OP_CLOSURE, f->nkproto-1, func->nupvalues);
  238. }
  239. static void open_func (LexState *ls, FuncState *fs) {
  240. Proto *f = luaF_newproto(ls->L);
  241. fs->prev = ls->fs; /* linked list of funcstates */
  242. fs->ls = ls;
  243. fs->L = ls->L;
  244. ls->fs = fs;
  245. fs->stacklevel = 0;
  246. fs->nactloc = 0;
  247. fs->nupvalues = 0;
  248. fs->bl = NULL;
  249. fs->f = f;
  250. f->source = ls->source;
  251. fs->pc = 0;
  252. fs->lasttarget = 0;
  253. fs->nlineinfo = 0;
  254. fs->lastline = 0;
  255. fs->jlt = NO_JUMP;
  256. f->code = NULL;
  257. f->maxstacksize = 0;
  258. f->numparams = 0; /* default for main chunk */
  259. f->is_vararg = 0; /* default for main chunk */
  260. }
  261. static void close_func (LexState *ls) {
  262. lua_State *L = ls->L;
  263. FuncState *fs = ls->fs;
  264. Proto *f = fs->f;
  265. luaK_code0(fs, OP_END);
  266. luaK_getlabel(fs); /* close eventual list of pending jumps */
  267. luaM_reallocvector(L, f->code, fs->pc, Instruction);
  268. luaM_reallocvector(L, f->kstr, f->nkstr, TString *);
  269. luaM_reallocvector(L, f->knum, f->nknum, Number);
  270. luaM_reallocvector(L, f->kproto, f->nkproto, Proto *);
  271. removelocalvars(ls, fs->nactloc);
  272. luaM_reallocvector(L, f->locvars, f->nlocvars, LocVar);
  273. luaM_reallocvector(L, f->lineinfo, fs->nlineinfo+1, int);
  274. f->lineinfo[fs->nlineinfo] = MAX_INT; /* end flag */
  275. ls->fs = fs->prev;
  276. LUA_ASSERT(fs->bl == NULL, "wrong list end");
  277. }
  278. Proto *luaY_parser (lua_State *L, ZIO *z) {
  279. struct LexState lexstate;
  280. struct FuncState funcstate;
  281. luaX_setinput(L, &lexstate, z, luaS_new(L, zname(z)));
  282. open_func(&lexstate, &funcstate);
  283. next(&lexstate); /* read first token */
  284. chunk(&lexstate);
  285. check_condition(&lexstate, (lexstate.t.token == TK_EOS), "<eof> expected");
  286. close_func(&lexstate);
  287. LUA_ASSERT(funcstate.prev == NULL, "wrong list end");
  288. LUA_ASSERT(funcstate.nupvalues == 0, "no upvalues in main");
  289. return funcstate.f;
  290. }
  291. /*============================================================*/
  292. /* GRAMMAR RULES */
  293. /*============================================================*/
  294. static int explist1 (LexState *ls) {
  295. /* explist1 -> expr { ',' expr } */
  296. int n = 1; /* at least one expression */
  297. expdesc v;
  298. expr(ls, &v);
  299. while (ls->t.token == ',') {
  300. luaK_tostack(ls, &v, 1); /* gets only 1 value from previous expression */
  301. next(ls); /* skip comma */
  302. expr(ls, &v);
  303. n++;
  304. }
  305. luaK_tostack(ls, &v, 0); /* keep open number of values of last expression */
  306. return n;
  307. }
  308. static void funcargs (LexState *ls, int slf) {
  309. FuncState *fs = ls->fs;
  310. int slevel = fs->stacklevel - slf - 1; /* where is func in the stack */
  311. switch (ls->t.token) {
  312. case '(': { /* funcargs -> '(' [ explist1 ] ')' */
  313. int line = ls->linenumber;
  314. int nargs = 0;
  315. next(ls);
  316. if (ls->t.token != ')') /* arg list not empty? */
  317. nargs = explist1(ls);
  318. check_match(ls, ')', '(', line);
  319. #ifdef LUA_COMPAT_ARGRET
  320. if (nargs > 0) /* arg list is not empty? */
  321. luaK_setcallreturns(fs, 1); /* last call returns only 1 value */
  322. #else
  323. UNUSED(nargs); /* to avoid warnings */
  324. #endif
  325. break;
  326. }
  327. case '{': { /* funcargs -> constructor */
  328. constructor(ls);
  329. break;
  330. }
  331. case TK_STRING: { /* funcargs -> STRING */
  332. code_string(ls, ls->t.seminfo.ts); /* must use `seminfo' before `next' */
  333. next(ls);
  334. break;
  335. }
  336. default: {
  337. luaK_error(ls, "function arguments expected");
  338. break;
  339. }
  340. }
  341. fs->stacklevel = slevel; /* call will remove function and arguments */
  342. luaK_code2(fs, OP_CALL, slevel, MULT_RET);
  343. }
  344. static void var_or_func_tail (LexState *ls, expdesc *v) {
  345. for (;;) {
  346. switch (ls->t.token) {
  347. case '.': { /* var_or_func_tail -> '.' NAME */
  348. next(ls);
  349. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  350. luaK_kstr(ls, checkname(ls));
  351. v->k = VINDEXED;
  352. break;
  353. }
  354. case '[': { /* var_or_func_tail -> '[' exp1 ']' */
  355. next(ls);
  356. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  357. v->k = VINDEXED;
  358. exp1(ls);
  359. check(ls, ']');
  360. break;
  361. }
  362. case ':': { /* var_or_func_tail -> ':' NAME funcargs */
  363. int name;
  364. next(ls);
  365. name = checkname(ls);
  366. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  367. luaK_code1(ls->fs, OP_PUSHSELF, name);
  368. funcargs(ls, 1);
  369. v->k = VEXP;
  370. v->u.l.t = v->u.l.f = NO_JUMP;
  371. break;
  372. }
  373. case '(': case TK_STRING: case '{': { /* var_or_func_tail -> funcargs */
  374. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  375. funcargs(ls, 0);
  376. v->k = VEXP;
  377. v->u.l.t = v->u.l.f = NO_JUMP;
  378. break;
  379. }
  380. default: return; /* should be follow... */
  381. }
  382. }
  383. }
  384. static void var_or_func (LexState *ls, expdesc *v) {
  385. /* var_or_func -> ['%'] NAME var_or_func_tail */
  386. if (optional(ls, '%')) { /* upvalue? */
  387. pushupvalue(ls, str_checkname(ls));
  388. v->k = VEXP;
  389. v->u.l.t = v->u.l.f = NO_JUMP;
  390. }
  391. else /* variable name */
  392. singlevar(ls, str_checkname(ls), v);
  393. var_or_func_tail(ls, v);
  394. }
  395. /*
  396. ** {======================================================================
  397. ** Rules for Constructors
  398. ** =======================================================================
  399. */
  400. static void recfield (LexState *ls) {
  401. /* recfield -> (NAME | '['exp1']') = exp1 */
  402. switch (ls->t.token) {
  403. case TK_NAME: {
  404. luaK_kstr(ls, checkname(ls));
  405. break;
  406. }
  407. case '[': {
  408. next(ls);
  409. exp1(ls);
  410. check(ls, ']');
  411. break;
  412. }
  413. default: luaK_error(ls, "<name> or `[' expected");
  414. }
  415. check(ls, '=');
  416. exp1(ls);
  417. }
  418. static int recfields (LexState *ls) {
  419. /* recfields -> recfield { ',' recfield } [','] */
  420. FuncState *fs = ls->fs;
  421. int n = 1; /* at least one element */
  422. recfield(ls);
  423. while (ls->t.token == ',') {
  424. next(ls);
  425. if (ls->t.token == ';' || ls->t.token == '}')
  426. break;
  427. recfield(ls);
  428. n++;
  429. if (n%RFIELDS_PER_FLUSH == 0)
  430. luaK_code1(fs, OP_SETMAP, RFIELDS_PER_FLUSH);
  431. }
  432. luaK_code1(fs, OP_SETMAP, n%RFIELDS_PER_FLUSH);
  433. return n;
  434. }
  435. static int listfields (LexState *ls) {
  436. /* listfields -> exp1 { ',' exp1 } [','] */
  437. FuncState *fs = ls->fs;
  438. int n = 1; /* at least one element */
  439. exp1(ls);
  440. while (ls->t.token == ',') {
  441. next(ls);
  442. if (ls->t.token == ';' || ls->t.token == '}')
  443. break;
  444. exp1(ls);
  445. n++;
  446. luaX_checklimit(ls, n/LFIELDS_PER_FLUSH, MAXARG_A,
  447. "`item groups' in a list initializer");
  448. if (n%LFIELDS_PER_FLUSH == 0)
  449. luaK_code2(fs, OP_SETLIST, n/LFIELDS_PER_FLUSH - 1, LFIELDS_PER_FLUSH);
  450. }
  451. luaK_code2(fs, OP_SETLIST, n/LFIELDS_PER_FLUSH, n%LFIELDS_PER_FLUSH);
  452. return n;
  453. }
  454. static void constructor_part (LexState *ls, Constdesc *cd) {
  455. switch (ls->t.token) {
  456. case ';': case '}': { /* constructor_part -> empty */
  457. cd->n = 0;
  458. cd->k = ls->t.token;
  459. break;
  460. }
  461. case TK_NAME: { /* may be listfields or recfields */
  462. lookahead(ls);
  463. if (ls->lookahead.token != '=') /* expression? */
  464. goto case_default;
  465. /* else go through to recfields */
  466. }
  467. case '[': { /* constructor_part -> recfields */
  468. cd->n = recfields(ls);
  469. cd->k = 1; /* record */
  470. break;
  471. }
  472. default: { /* constructor_part -> listfields */
  473. case_default:
  474. cd->n = listfields(ls);
  475. cd->k = 0; /* list */
  476. break;
  477. }
  478. }
  479. }
  480. static void constructor (LexState *ls) {
  481. /* constructor -> '{' constructor_part [';' constructor_part] '}' */
  482. FuncState *fs = ls->fs;
  483. int line = ls->linenumber;
  484. int pc = luaK_code1(fs, OP_CREATETABLE, 0);
  485. int nelems;
  486. Constdesc cd;
  487. check(ls, '{');
  488. constructor_part(ls, &cd);
  489. nelems = cd.n;
  490. if (optional(ls, ';')) {
  491. Constdesc other_cd;
  492. constructor_part(ls, &other_cd);
  493. check_condition(ls, (cd.k != other_cd.k), "invalid constructor syntax");
  494. nelems += other_cd.n;
  495. }
  496. check_match(ls, '}', '{', line);
  497. luaX_checklimit(ls, nelems, MAXARG_U, "elements in a table constructor");
  498. SETARG_U(fs->f->code[pc], nelems); /* set initial table size */
  499. }
  500. /* }====================================================================== */
  501. /*
  502. ** {======================================================================
  503. ** Expression parsing
  504. ** =======================================================================
  505. */
  506. static void simpleexp (LexState *ls, expdesc *v) {
  507. FuncState *fs = ls->fs;
  508. switch (ls->t.token) {
  509. case TK_NUMBER: { /* simpleexp -> NUMBER */
  510. Number r = ls->t.seminfo.r;
  511. next(ls);
  512. luaK_number(fs, r);
  513. break;
  514. }
  515. case TK_STRING: { /* simpleexp -> STRING */
  516. code_string(ls, ls->t.seminfo.ts); /* must use `seminfo' before `next' */
  517. next(ls);
  518. break;
  519. }
  520. case TK_NIL: { /* simpleexp -> NIL */
  521. luaK_adjuststack(fs, -1);
  522. next(ls);
  523. break;
  524. }
  525. case '{': { /* simpleexp -> constructor */
  526. constructor(ls);
  527. break;
  528. }
  529. case TK_FUNCTION: { /* simpleexp -> FUNCTION body */
  530. next(ls);
  531. body(ls, 0, ls->linenumber);
  532. break;
  533. }
  534. case '(': { /* simpleexp -> '(' expr ')' */
  535. next(ls);
  536. expr(ls, v);
  537. check(ls, ')');
  538. return;
  539. }
  540. case TK_NAME: case '%': {
  541. var_or_func(ls, v);
  542. return;
  543. }
  544. default: {
  545. luaK_error(ls, "<expression> expected");
  546. return;
  547. }
  548. }
  549. v->k = VEXP;
  550. v->u.l.t = v->u.l.f = NO_JUMP;
  551. }
  552. static void exp1 (LexState *ls) {
  553. expdesc v;
  554. expr(ls, &v);
  555. luaK_tostack(ls, &v, 1);
  556. }
  557. static UnOpr getunopr (int op) {
  558. switch (op) {
  559. case TK_NOT: return OPR_NOT;
  560. case '-': return OPR_MINUS;
  561. default: return OPR_NOUNOPR;
  562. }
  563. }
  564. static BinOpr getbinopr (int op) {
  565. switch (op) {
  566. case '+': return OPR_ADD;
  567. case '-': return OPR_SUB;
  568. case '*': return OPR_MULT;
  569. case '/': return OPR_DIV;
  570. case '^': return OPR_POW;
  571. case TK_CONCAT: return OPR_CONCAT;
  572. case TK_NE: return OPR_NE;
  573. case TK_EQ: return OPR_EQ;
  574. case '<': return OPR_LT;
  575. case TK_LE: return OPR_LE;
  576. case '>': return OPR_GT;
  577. case TK_GE: return OPR_GE;
  578. case TK_AND: return OPR_AND;
  579. case TK_OR: return OPR_OR;
  580. default: return OPR_NOBINOPR;
  581. }
  582. }
  583. static const struct {
  584. char left; /* left priority for each binary operator */
  585. char right; /* right priority */
  586. } priority[] = { /* ORDER OPR */
  587. {5, 5}, {5, 5}, {6, 6}, {6, 6}, /* arithmetic */
  588. {9, 8}, {4, 3}, /* power and concat (right associative) */
  589. {2, 2}, {2, 2}, /* equality */
  590. {2, 2}, {2, 2}, {2, 2}, {2, 2}, /* order */
  591. {1, 1}, {1, 1} /* logical */
  592. };
  593. #define UNARY_PRIORITY 7 /* priority for unary operators */
  594. /*
  595. ** subexpr -> (simplexep | unop subexpr) { binop subexpr }
  596. ** where `binop' is any binary operator with a priority higher than `limit'
  597. */
  598. static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
  599. BinOpr op;
  600. UnOpr uop = getunopr(ls->t.token);
  601. if (uop != OPR_NOUNOPR) {
  602. next(ls);
  603. subexpr(ls, v, UNARY_PRIORITY);
  604. luaK_prefix(ls, uop, v);
  605. }
  606. else simpleexp(ls, v);
  607. /* expand while operators have priorities higher than `limit' */
  608. op = getbinopr(ls->t.token);
  609. while (op != OPR_NOBINOPR && priority[op].left > limit) {
  610. expdesc v2;
  611. BinOpr nextop;
  612. next(ls);
  613. luaK_infix(ls, op, v);
  614. /* read sub-expression with higher priority */
  615. nextop = subexpr(ls, &v2, priority[op].right);
  616. luaK_posfix(ls, op, v, &v2);
  617. op = nextop;
  618. }
  619. return op; /* return first untreated operator */
  620. }
  621. static void expr (LexState *ls, expdesc *v) {
  622. subexpr(ls, v, -1);
  623. }
  624. /* }==================================================================== */
  625. /*
  626. ** {======================================================================
  627. ** Rules for Statements
  628. ** =======================================================================
  629. */
  630. static int block_follow (int token) {
  631. switch (token) {
  632. case TK_ELSE: case TK_ELSEIF: case TK_END:
  633. case TK_UNTIL: case TK_EOS:
  634. return 1;
  635. default: return 0;
  636. }
  637. }
  638. static void block (LexState *ls) {
  639. /* block -> chunk */
  640. FuncState *fs = ls->fs;
  641. int nactloc = fs->nactloc;
  642. chunk(ls);
  643. luaK_adjuststack(fs, fs->nactloc - nactloc); /* remove local variables */
  644. removelocalvars(ls, fs->nactloc - nactloc);
  645. }
  646. static int assignment (LexState *ls, expdesc *v, int nvars) {
  647. int left = 0; /* number of values left in the stack after assignment */
  648. luaX_checklimit(ls, nvars, MAXVARSLH, "variables in a multiple assignment");
  649. if (ls->t.token == ',') { /* assignment -> ',' NAME assignment */
  650. expdesc nv;
  651. next(ls);
  652. var_or_func(ls, &nv);
  653. check_condition(ls, (nv.k != VEXP), "syntax error");
  654. left = assignment(ls, &nv, nvars+1);
  655. }
  656. else { /* assignment -> '=' explist1 */
  657. int nexps;
  658. check(ls, '=');
  659. nexps = explist1(ls);
  660. adjust_mult_assign(ls, nvars, nexps);
  661. }
  662. if (v->k != VINDEXED)
  663. luaK_storevar(ls, v);
  664. else { /* there may be garbage between table-index and value */
  665. luaK_code2(ls->fs, OP_SETTABLE, left+nvars+2, 1);
  666. left += 2;
  667. }
  668. return left;
  669. }
  670. static void cond (LexState *ls, expdesc *v) {
  671. /* cond -> exp */
  672. expr(ls, v); /* read condition */
  673. luaK_goiftrue(ls->fs, v, 0);
  674. }
  675. static void whilestat (LexState *ls, int line) {
  676. /* whilestat -> WHILE cond DO block END */
  677. FuncState *fs = ls->fs;
  678. int while_init = luaK_getlabel(fs);
  679. expdesc v;
  680. Breaklabel bl;
  681. enterbreak(fs, &bl);
  682. next(ls);
  683. cond(ls, &v);
  684. check(ls, TK_DO);
  685. block(ls);
  686. luaK_patchlist(fs, luaK_jump(fs), while_init);
  687. luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
  688. check_match(ls, TK_END, TK_WHILE, line);
  689. leavebreak(fs, &bl);
  690. }
  691. static void repeatstat (LexState *ls, int line) {
  692. /* repeatstat -> REPEAT block UNTIL cond */
  693. FuncState *fs = ls->fs;
  694. int repeat_init = luaK_getlabel(fs);
  695. expdesc v;
  696. Breaklabel bl;
  697. enterbreak(fs, &bl);
  698. next(ls);
  699. block(ls);
  700. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  701. cond(ls, &v);
  702. luaK_patchlist(fs, v.u.l.f, repeat_init);
  703. leavebreak(fs, &bl);
  704. }
  705. static void forbody (LexState *ls, int nvar, OpCode prepfor, OpCode loopfor) {
  706. /* forbody -> DO block END */
  707. FuncState *fs = ls->fs;
  708. int prep = luaK_code1(fs, prepfor, NO_JUMP);
  709. int blockinit = luaK_getlabel(fs);
  710. check(ls, TK_DO);
  711. adjustlocalvars(ls, nvar); /* scope for control variables */
  712. block(ls);
  713. luaK_patchlist(fs, prep, luaK_getlabel(fs));
  714. luaK_patchlist(fs, luaK_code1(fs, loopfor, NO_JUMP), blockinit);
  715. removelocalvars(ls, nvar);
  716. }
  717. static void fornum (LexState *ls, TString *varname) {
  718. /* fornum -> NAME = exp1,exp1[,exp1] forbody */
  719. FuncState *fs = ls->fs;
  720. check(ls, '=');
  721. exp1(ls); /* initial value */
  722. check(ls, ',');
  723. exp1(ls); /* limit */
  724. if (optional(ls, ','))
  725. exp1(ls); /* optional step */
  726. else
  727. luaK_code1(fs, OP_PUSHINT, 1); /* default step */
  728. new_localvar(ls, varname, 0);
  729. new_localvarstr(ls, "*limit*", 1);
  730. new_localvarstr(ls, "*step*", 2);
  731. forbody(ls, 3, OP_FORPREP, OP_FORLOOP);
  732. }
  733. static void forlist (LexState *ls, TString *indexname) {
  734. /* forlist -> NAME,NAME IN exp1 forbody */
  735. TString *valname;
  736. check(ls, ',');
  737. valname = str_checkname(ls);
  738. /* next test is dirty, but avoids `in' being a reserved word */
  739. check_condition(ls,
  740. (ls->t.token == TK_NAME && ls->t.seminfo.ts == luaS_new(ls->L, "in")),
  741. "`in' expected");
  742. next(ls); /* skip `in' */
  743. exp1(ls); /* table */
  744. new_localvarstr(ls, "*table*", 0);
  745. new_localvarstr(ls, "*counter*", 1);
  746. new_localvar(ls, indexname, 2);
  747. new_localvar(ls, valname, 3);
  748. forbody(ls, 4, OP_LFORPREP, OP_LFORLOOP);
  749. }
  750. static void forstat (LexState *ls, int line) {
  751. /* forstat -> fornum | forlist */
  752. FuncState *fs = ls->fs;
  753. TString *varname;
  754. Breaklabel bl;
  755. enterbreak(fs, &bl);
  756. next(ls); /* skip `for' */
  757. varname = str_checkname(ls); /* first variable name */
  758. switch (ls->t.token) {
  759. case '=': fornum(ls, varname); break;
  760. case ',': forlist(ls, varname); break;
  761. default: luaK_error(ls, "`=' or `,' expected");
  762. }
  763. check_match(ls, TK_END, TK_FOR, line);
  764. leavebreak(fs, &bl);
  765. }
  766. static void test_then_block (LexState *ls, expdesc *v) {
  767. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  768. next(ls); /* skip IF or ELSEIF */
  769. cond(ls, v);
  770. check(ls, TK_THEN);
  771. block(ls); /* `then' part */
  772. }
  773. static void ifstat (LexState *ls, int line) {
  774. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  775. FuncState *fs = ls->fs;
  776. expdesc v;
  777. int escapelist = NO_JUMP;
  778. test_then_block(ls, &v); /* IF cond THEN block */
  779. while (ls->t.token == TK_ELSEIF) {
  780. luaK_concat(fs, &escapelist, luaK_jump(fs));
  781. luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
  782. test_then_block(ls, &v); /* ELSEIF cond THEN block */
  783. }
  784. if (ls->t.token == TK_ELSE) {
  785. luaK_concat(fs, &escapelist, luaK_jump(fs));
  786. luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
  787. next(ls); /* skip ELSE */
  788. block(ls); /* `else' part */
  789. }
  790. else
  791. luaK_concat(fs, &escapelist, v.u.l.f);
  792. luaK_patchlist(fs, escapelist, luaK_getlabel(fs));
  793. check_match(ls, TK_END, TK_IF, line);
  794. }
  795. static void localstat (LexState *ls) {
  796. /* stat -> LOCAL NAME {',' NAME} ['=' explist1] */
  797. int nvars = 0;
  798. int nexps;
  799. do {
  800. next(ls); /* skip LOCAL or ',' */
  801. new_localvar(ls, str_checkname(ls), nvars++);
  802. } while (ls->t.token == ',');
  803. if (optional(ls, '='))
  804. nexps = explist1(ls);
  805. else
  806. nexps = 0;
  807. adjust_mult_assign(ls, nvars, nexps);
  808. adjustlocalvars(ls, nvars);
  809. }
  810. static int funcname (LexState *ls, expdesc *v) {
  811. /* funcname -> NAME [':' NAME | '.' NAME] */
  812. int needself = 0;
  813. singlevar(ls, str_checkname(ls), v);
  814. if (ls->t.token == ':' || ls->t.token == '.') {
  815. needself = (ls->t.token == ':');
  816. next(ls);
  817. luaK_tostack(ls, v, 1);
  818. luaK_kstr(ls, checkname(ls));
  819. v->k = VINDEXED;
  820. }
  821. return needself;
  822. }
  823. static void funcstat (LexState *ls, int line) {
  824. /* funcstat -> FUNCTION funcname body */
  825. int needself;
  826. expdesc v;
  827. next(ls); /* skip FUNCTION */
  828. needself = funcname(ls, &v);
  829. body(ls, needself, line);
  830. luaK_storevar(ls, &v);
  831. }
  832. static void namestat (LexState *ls) {
  833. /* stat -> func | ['%'] NAME assignment */
  834. FuncState *fs = ls->fs;
  835. expdesc v;
  836. var_or_func(ls, &v);
  837. if (v.k == VEXP) { /* stat -> func */
  838. check_condition(ls, luaK_lastisopen(fs), "syntax error"); /* an upvalue? */
  839. luaK_setcallreturns(fs, 0); /* call statement uses no results */
  840. }
  841. else { /* stat -> ['%'] NAME assignment */
  842. int left = assignment(ls, &v, 1);
  843. luaK_adjuststack(fs, left); /* remove eventual garbage left on stack */
  844. }
  845. }
  846. static void retstat (LexState *ls) {
  847. /* stat -> RETURN explist */
  848. FuncState *fs = ls->fs;
  849. next(ls); /* skip RETURN */
  850. if (!block_follow(ls->t.token))
  851. explist1(ls); /* optional return values */
  852. luaK_code1(fs, OP_RETURN, ls->fs->nactloc);
  853. fs->stacklevel = fs->nactloc; /* removes all temp values */
  854. }
  855. static void breakstat (LexState *ls) {
  856. /* stat -> BREAK [NAME] */
  857. FuncState *fs = ls->fs;
  858. int currentlevel = fs->stacklevel;
  859. Breaklabel *bl = fs->bl;
  860. if (!bl)
  861. luaK_error(ls, "no loop to break");
  862. next(ls); /* skip BREAK */
  863. luaK_adjuststack(fs, currentlevel - bl->stacklevel);
  864. luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
  865. /* correct stack for compiler and symbolic execution */
  866. luaK_adjuststack(fs, bl->stacklevel - currentlevel);
  867. }
  868. static int stat (LexState *ls) {
  869. int line = ls->linenumber; /* may be needed for error messages */
  870. switch (ls->t.token) {
  871. case TK_IF: { /* stat -> ifstat */
  872. ifstat(ls, line);
  873. return 0;
  874. }
  875. case TK_WHILE: { /* stat -> whilestat */
  876. whilestat(ls, line);
  877. return 0;
  878. }
  879. case TK_DO: { /* stat -> DO block END */
  880. next(ls); /* skip DO */
  881. block(ls);
  882. check_match(ls, TK_END, TK_DO, line);
  883. return 0;
  884. }
  885. case TK_FOR: { /* stat -> forstat */
  886. forstat(ls, line);
  887. return 0;
  888. }
  889. case TK_REPEAT: { /* stat -> repeatstat */
  890. repeatstat(ls, line);
  891. return 0;
  892. }
  893. case TK_FUNCTION: { /* stat -> funcstat */
  894. funcstat(ls, line);
  895. return 0;
  896. }
  897. case TK_LOCAL: { /* stat -> localstat */
  898. localstat(ls);
  899. return 0;
  900. }
  901. case TK_NAME: case '%': { /* stat -> namestat */
  902. namestat(ls);
  903. return 0;
  904. }
  905. case TK_RETURN: { /* stat -> retstat */
  906. retstat(ls);
  907. return 1; /* must be last statement */
  908. }
  909. case TK_BREAK: { /* stat -> breakstat */
  910. breakstat(ls);
  911. return 1; /* must be last statement */
  912. }
  913. default: {
  914. luaK_error(ls, "<statement> expected");
  915. return 0; /* to avoid warnings */
  916. }
  917. }
  918. }
  919. static void parlist (LexState *ls) {
  920. /* parlist -> [ param { ',' param } ] */
  921. int nparams = 0;
  922. int dots = 0;
  923. if (ls->t.token != ')') { /* is `parlist' not empty? */
  924. do {
  925. switch (ls->t.token) {
  926. case TK_DOTS: next(ls); dots = 1; break;
  927. case TK_NAME: new_localvar(ls, str_checkname(ls), nparams++); break;
  928. default: luaK_error(ls, "<name> or `...' expected");
  929. }
  930. } while (!dots && optional(ls, ','));
  931. }
  932. code_params(ls, nparams, dots);
  933. }
  934. static void body (LexState *ls, int needself, int line) {
  935. /* body -> '(' parlist ')' chunk END */
  936. FuncState new_fs;
  937. open_func(ls, &new_fs);
  938. new_fs.f->lineDefined = line;
  939. check(ls, '(');
  940. if (needself) {
  941. new_localvarstr(ls, "self", 0);
  942. adjustlocalvars(ls, 1);
  943. }
  944. parlist(ls);
  945. check(ls, ')');
  946. chunk(ls);
  947. check_match(ls, TK_END, TK_FUNCTION, line);
  948. close_func(ls);
  949. pushclosure(ls, &new_fs);
  950. }
  951. /* }====================================================================== */
  952. static void chunk (LexState *ls) {
  953. /* chunk -> { stat [';'] } */
  954. int islast = 0;
  955. while (!islast && !block_follow(ls->t.token)) {
  956. islast = stat(ls);
  957. optional(ls, ';');
  958. LUA_ASSERT(ls->fs->stacklevel == ls->fs->nactloc,
  959. "stack size != # local vars");
  960. }
  961. }