3 ** $Id: lparser.c,v 2.130.1.1 2013/04/12 18:48:47 roberto Exp $
5 ** See Copyright Notice in lua.h
11 #include <sys/lua/lua.h>
28 /* maximum number of local variables per function (must be smaller
29 than 250, due to the bytecode format) */
33 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
38 ** nodes for block list (list of active blocks)
40 typedef struct BlockCnt {
41 struct BlockCnt *previous; /* chain */
42 short firstlabel; /* index of first label in this block */
43 short firstgoto; /* index of first pending goto in this block */
44 lu_byte nactvar; /* # active locals outside the block */
45 lu_byte upval; /* true if some variable in the block is an upvalue */
46 lu_byte isloop; /* true if `block' is a loop */
52 ** prototypes for recursive non-terminal functions
54 static void statement (LexState *ls);
55 static void expr (LexState *ls, expdesc *v);
58 static void anchor_token (LexState *ls) {
59 /* last token from outer function must be EOS */
60 lua_assert(ls->fs != NULL || ls->t.token == TK_EOS);
61 if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
62 TString *ts = ls->t.seminfo.ts;
63 luaX_newstring(ls, getstr(ts), ts->tsv.len);
69 static l_noret semerror (LexState *ls, const char *msg) {
70 ls->t.token = 0; /* remove 'near to' from final message */
71 luaX_syntaxerror(ls, msg);
75 static l_noret error_expected (LexState *ls, int token) {
77 luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
81 static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
82 lua_State *L = fs->ls->L;
84 int line = fs->f->linedefined;
85 const char *where = (line == 0)
87 : luaO_pushfstring(L, "function at line %d", line);
88 msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
90 luaX_syntaxerror(fs->ls, msg);
94 static void checklimit (FuncState *fs, int v, int l, const char *what) {
95 if (v > l) errorlimit(fs, l, what);
99 static int testnext (LexState *ls, int c) {
100 if (ls->t.token == c) {
108 static void check (LexState *ls, int c) {
109 if (ls->t.token != c)
110 error_expected(ls, c);
114 static void checknext (LexState *ls, int c) {
120 #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
124 static void check_match (LexState *ls, int what, int who, int where) {
125 if (!testnext(ls, what)) {
126 if (where == ls->linenumber)
127 error_expected(ls, what);
129 luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
130 "%s expected (to close %s at line %d)",
131 luaX_token2str(ls, what), luaX_token2str(ls, who), where));
137 static TString *str_checkname (LexState *ls) {
140 ts = ls->t.seminfo.ts;
146 static void init_exp (expdesc *e, expkind k, int i) {
147 e->f = e->t = NO_JUMP;
153 static void codestring (LexState *ls, expdesc *e, TString *s) {
154 init_exp(e, VK, luaK_stringK(ls->fs, s));
158 static void checkname (LexState *ls, expdesc *e) {
159 codestring(ls, e, str_checkname(ls));
163 static int registerlocalvar (LexState *ls, TString *varname) {
164 FuncState *fs = ls->fs;
166 int oldsize = f->sizelocvars;
167 luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
168 LocVar, SHRT_MAX, "local variables");
169 while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
170 f->locvars[fs->nlocvars].varname = varname;
171 luaC_objbarrier(ls->L, f, varname);
172 return fs->nlocvars++;
176 static void new_localvar (LexState *ls, TString *name) {
177 FuncState *fs = ls->fs;
178 Dyndata *dyd = ls->dyd;
179 int reg = registerlocalvar(ls, name);
180 checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
181 MAXVARS, "local variables");
182 luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,
183 dyd->actvar.size, Vardesc, MAX_INT, "local variables");
184 dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg);
188 static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) {
189 new_localvar(ls, luaX_newstring(ls, name, sz));
192 #define new_localvarliteral(ls,v) \
193 new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1)
196 static LocVar *getlocvar (FuncState *fs, int i) {
197 int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
198 lua_assert(idx < fs->nlocvars);
199 return &fs->f->locvars[idx];
203 static void adjustlocalvars (LexState *ls, int nvars) {
204 FuncState *fs = ls->fs;
205 fs->nactvar = cast_byte(fs->nactvar + nvars);
206 for (; nvars; nvars--) {
207 getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;
212 static void removevars (FuncState *fs, int tolevel) {
213 fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
214 while (fs->nactvar > tolevel)
215 getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
219 static int searchupvalue (FuncState *fs, TString *name) {
221 Upvaldesc *up = fs->f->upvalues;
222 for (i = 0; i < fs->nups; i++) {
223 if (luaS_eqstr(up[i].name, name)) return i;
225 return -1; /* not found */
229 static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
231 int oldsize = f->sizeupvalues;
232 checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
233 luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
234 Upvaldesc, MAXUPVAL, "upvalues");
235 while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL;
236 f->upvalues[fs->nups].instack = (v->k == VLOCAL);
237 f->upvalues[fs->nups].idx = cast_byte(v->u.info);
238 f->upvalues[fs->nups].name = name;
239 luaC_objbarrier(fs->ls->L, f, name);
244 static int searchvar (FuncState *fs, TString *n) {
246 for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
247 if (luaS_eqstr(n, getlocvar(fs, i)->varname))
250 return -1; /* not found */
255 Mark block where variable at given level was defined
256 (to emit close instructions later).
258 static void markupval (FuncState *fs, int level) {
259 BlockCnt *bl = fs->bl;
260 while (bl->nactvar > level) bl = bl->previous;
266 Find variable with given name 'n'. If it is an upvalue, add this
267 upvalue into all intermediate functions.
269 static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
270 if (fs == NULL) /* no more levels? */
271 return VVOID; /* default is global */
273 int v = searchvar(fs, n); /* look up locals at current level */
274 if (v >= 0) { /* found? */
275 init_exp(var, VLOCAL, v); /* variable is local */
277 markupval(fs, v); /* local will be used as an upval */
280 else { /* not found as local at current level; try upvalues */
281 int idx = searchupvalue(fs, n); /* try existing upvalues */
282 if (idx < 0) { /* not found? */
283 if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */
284 return VVOID; /* not found; is a global */
285 /* else was LOCAL or UPVAL */
286 idx = newupvalue(fs, n, var); /* will be a new upvalue */
288 init_exp(var, VUPVAL, idx);
295 static void singlevar (LexState *ls, expdesc *var) {
296 TString *varname = str_checkname(ls);
297 FuncState *fs = ls->fs;
298 if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */
300 singlevaraux(fs, ls->envn, var, 1); /* get environment variable */
301 lua_assert(var->k == VLOCAL || var->k == VUPVAL);
302 codestring(ls, &key, varname); /* key is variable name */
303 luaK_indexed(fs, var, &key); /* env[varname] */
308 static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
309 FuncState *fs = ls->fs;
310 int extra = nvars - nexps;
311 if (hasmultret(e->k)) {
312 extra++; /* includes call itself */
313 if (extra < 0) extra = 0;
314 luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
315 if (extra > 1) luaK_reserveregs(fs, extra-1);
318 if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */
320 int reg = fs->freereg;
321 luaK_reserveregs(fs, extra);
322 luaK_nil(fs, reg, extra);
328 static void enterlevel (LexState *ls) {
329 lua_State *L = ls->L;
331 checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels");
335 #define leavelevel(ls) ((ls)->L->nCcalls--)
338 static void closegoto (LexState *ls, int g, Labeldesc *label) {
340 FuncState *fs = ls->fs;
341 Labellist *gl = &ls->dyd->gt;
342 Labeldesc *gt = &gl->arr[g];
343 lua_assert(luaS_eqstr(gt->name, label->name));
344 if (gt->nactvar < label->nactvar) {
345 TString *vname = getlocvar(fs, gt->nactvar)->varname;
346 const char *msg = luaO_pushfstring(ls->L,
347 "<goto %s> at line %d jumps into the scope of local " LUA_QS,
348 getstr(gt->name), gt->line, getstr(vname));
351 luaK_patchlist(fs, gt->pc, label->pc);
352 /* remove goto from pending list */
353 for (i = g; i < gl->n - 1; i++)
354 gl->arr[i] = gl->arr[i + 1];
360 ** try to close a goto with existing labels; this solves backward jumps
362 static int findlabel (LexState *ls, int g) {
364 BlockCnt *bl = ls->fs->bl;
365 Dyndata *dyd = ls->dyd;
366 Labeldesc *gt = &dyd->gt.arr[g];
367 /* check labels in current block for a match */
368 for (i = bl->firstlabel; i < dyd->label.n; i++) {
369 Labeldesc *lb = &dyd->label.arr[i];
370 if (luaS_eqstr(lb->name, gt->name)) { /* correct label? */
371 if (gt->nactvar > lb->nactvar &&
372 (bl->upval || dyd->label.n > bl->firstlabel))
373 luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
374 closegoto(ls, g, lb); /* close it */
378 return 0; /* label not found; cannot close goto */
382 static int newlabelentry (LexState *ls, Labellist *l, TString *name,
385 luaM_growvector(ls->L, l->arr, n, l->size,
386 Labeldesc, SHRT_MAX, "labels/gotos");
387 l->arr[n].name = name;
388 l->arr[n].line = line;
389 l->arr[n].nactvar = ls->fs->nactvar;
397 ** check whether new label 'lb' matches any pending gotos in current
398 ** block; solves forward jumps
400 static void findgotos (LexState *ls, Labeldesc *lb) {
401 Labellist *gl = &ls->dyd->gt;
402 int i = ls->fs->bl->firstgoto;
404 if (luaS_eqstr(gl->arr[i].name, lb->name))
405 closegoto(ls, i, lb);
413 ** "export" pending gotos to outer level, to check them against
414 ** outer labels; if the block being exited has upvalues, and
415 ** the goto exits the scope of any variable (which can be the
416 ** upvalue), close those variables being exited.
418 static void movegotosout (FuncState *fs, BlockCnt *bl) {
419 int i = bl->firstgoto;
420 Labellist *gl = &fs->ls->dyd->gt;
421 /* correct pending gotos to current block and try to close it
422 with visible labels */
424 Labeldesc *gt = &gl->arr[i];
425 if (gt->nactvar > bl->nactvar) {
427 luaK_patchclose(fs, gt->pc, bl->nactvar);
428 gt->nactvar = bl->nactvar;
430 if (!findlabel(fs->ls, i))
431 i++; /* move to next one */
436 static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
438 bl->nactvar = fs->nactvar;
439 bl->firstlabel = fs->ls->dyd->label.n;
440 bl->firstgoto = fs->ls->dyd->gt.n;
442 bl->previous = fs->bl;
444 lua_assert(fs->freereg == fs->nactvar);
449 ** create a label named "break" to resolve break statements
451 static void breaklabel (LexState *ls) {
452 TString *n = luaS_new(ls->L, "break");
453 int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);
454 findgotos(ls, &ls->dyd->label.arr[l]);
458 ** generates an error for an undefined 'goto'; choose appropriate
459 ** message when label name is a reserved word (which can only be 'break')
461 static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
462 const char *msg = isreserved(gt->name)
463 ? "<%s> at line %d not inside a loop"
464 : "no visible label " LUA_QS " for <goto> at line %d";
465 msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
470 static void leaveblock (FuncState *fs) {
471 BlockCnt *bl = fs->bl;
472 LexState *ls = fs->ls;
473 if (bl->previous && bl->upval) {
474 /* create a 'jump to here' to close upvalues */
475 int j = luaK_jump(fs);
476 luaK_patchclose(fs, j, bl->nactvar);
477 luaK_patchtohere(fs, j);
480 breaklabel(ls); /* close pending breaks */
481 fs->bl = bl->previous;
482 removevars(fs, bl->nactvar);
483 lua_assert(bl->nactvar == fs->nactvar);
484 fs->freereg = fs->nactvar; /* free registers */
485 ls->dyd->label.n = bl->firstlabel; /* remove local labels */
486 if (bl->previous) /* inner block? */
487 movegotosout(fs, bl); /* update pending gotos to outer block */
488 else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */
489 undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
494 ** adds a new prototype into list of prototypes
496 static Proto *addprototype (LexState *ls) {
498 lua_State *L = ls->L;
499 FuncState *fs = ls->fs;
500 Proto *f = fs->f; /* prototype of current function */
501 if (fs->np >= f->sizep) {
502 int oldsize = f->sizep;
503 luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
504 while (oldsize < f->sizep) f->p[oldsize++] = NULL;
506 f->p[fs->np++] = clp = luaF_newproto(L);
507 luaC_objbarrier(L, f, clp);
513 ** codes instruction to create new closure in parent function.
514 ** The OP_CLOSURE instruction must use the last available register,
515 ** so that, if it invokes the GC, the GC knows which registers
516 ** are in use at that time.
518 static void codeclosure (LexState *ls, expdesc *v) {
519 FuncState *fs = ls->fs->prev;
520 init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
521 luaK_exp2nextreg(fs, v); /* fix it at the last register */
525 static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
526 lua_State *L = ls->L;
528 fs->prev = ls->fs; /* linked list of funcstates */
540 fs->firstlocal = ls->dyd->actvar.n;
543 f->source = ls->source;
544 f->maxstacksize = 2; /* registers 0/1 are always valid */
546 /* anchor table of constants (to avoid being collected) */
547 sethvalue2s(L, L->top, fs->h);
549 enterblock(fs, bl, 0);
553 static void close_func (LexState *ls) {
554 lua_State *L = ls->L;
555 FuncState *fs = ls->fs;
557 luaK_ret(fs, 0, 0); /* final return */
559 luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
560 f->sizecode = fs->pc;
561 luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
562 f->sizelineinfo = fs->pc;
563 luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
565 luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
567 luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
568 f->sizelocvars = fs->nlocvars;
569 luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
570 f->sizeupvalues = fs->nups;
571 lua_assert(fs->bl == NULL);
573 /* last token read was anchored in defunct function; must re-anchor it */
575 L->top--; /* pop table of constants */
581 /*============================================================*/
583 /*============================================================*/
587 ** check whether current token is in the follow set of a block.
588 ** 'until' closes syntactical blocks, but do not close scope,
589 ** so it handled in separate.
591 static int block_follow (LexState *ls, int withuntil) {
592 switch (ls->t.token) {
593 case TK_ELSE: case TK_ELSEIF:
594 case TK_END: case TK_EOS:
596 case TK_UNTIL: return withuntil;
603 * by inlining statlist() and test_then_block() we cut back the
604 * native stack usage per nested C call from 272 bytes to 152
605 * which allows us to stay within budget for 8K kernel stacks
607 __attribute__((always_inline)) inline
608 static void statlist (LexState *ls) {
609 /* statlist -> { stat [`;'] } */
610 while (!block_follow(ls, 1)) {
611 if (ls->t.token == TK_RETURN) {
613 return; /* 'return' must be last statement */
620 static void fieldsel (LexState *ls, expdesc *v) {
621 /* fieldsel -> ['.' | ':'] NAME */
622 FuncState *fs = ls->fs;
624 luaK_exp2anyregup(fs, v);
625 luaX_next(ls); /* skip the dot or colon */
627 luaK_indexed(fs, v, &key);
631 static void yindex (LexState *ls, expdesc *v) {
632 /* index -> '[' expr ']' */
633 luaX_next(ls); /* skip the '[' */
635 luaK_exp2val(ls->fs, v);
641 ** {======================================================================
642 ** Rules for Constructors
643 ** =======================================================================
648 expdesc v; /* last list item read */
649 expdesc *t; /* table descriptor */
650 int nh; /* total number of `record' elements */
651 int na; /* total number of array elements */
652 int tostore; /* number of array elements pending to be stored */
656 static void recfield (LexState *ls, struct ConsControl *cc) {
657 /* recfield -> (NAME | `['exp1`]') = exp1 */
658 FuncState *fs = ls->fs;
659 int reg = ls->fs->freereg;
662 if (ls->t.token == TK_NAME) {
663 checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
666 else /* ls->t.token == '[' */
670 rkkey = luaK_exp2RK(fs, &key);
672 luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val));
673 fs->freereg = reg; /* free registers */
677 static void closelistfield (FuncState *fs, struct ConsControl *cc) {
678 if (cc->v.k == VVOID) return; /* there is no list item */
679 luaK_exp2nextreg(fs, &cc->v);
681 if (cc->tostore == LFIELDS_PER_FLUSH) {
682 luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
683 cc->tostore = 0; /* no more items pending */
688 static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
689 if (cc->tostore == 0) return;
690 if (hasmultret(cc->v.k)) {
691 luaK_setmultret(fs, &cc->v);
692 luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
693 cc->na--; /* do not count last expression (unknown number of elements) */
696 if (cc->v.k != VVOID)
697 luaK_exp2nextreg(fs, &cc->v);
698 luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
703 static void listfield (LexState *ls, struct ConsControl *cc) {
704 /* listfield -> exp */
706 checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
712 static void field (LexState *ls, struct ConsControl *cc) {
713 /* field -> listfield | recfield */
714 switch(ls->t.token) {
715 case TK_NAME: { /* may be 'listfield' or 'recfield' */
716 if (luaX_lookahead(ls) != '=') /* expression? */
734 static void constructor (LexState *ls, expdesc *t) {
735 /* constructor -> '{' [ field { sep field } [sep] ] '}'
737 FuncState *fs = ls->fs;
738 int line = ls->linenumber;
739 int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
740 struct ConsControl cc;
741 cc.na = cc.nh = cc.tostore = 0;
743 init_exp(t, VRELOCABLE, pc);
744 init_exp(&cc.v, VVOID, 0); /* no value (yet) */
745 luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */
748 lua_assert(cc.v.k == VVOID || cc.tostore > 0);
749 if (ls->t.token == '}') break;
750 closelistfield(fs, &cc);
752 } while (testnext(ls, ',') || testnext(ls, ';'));
753 check_match(ls, '}', '{', line);
754 lastlistfield(fs, &cc);
755 SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
756 SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
759 /* }====================================================================== */
763 static void parlist (LexState *ls) {
764 /* parlist -> [ param { `,' param } ] */
765 FuncState *fs = ls->fs;
769 if (ls->t.token != ')') { /* is `parlist' not empty? */
771 switch (ls->t.token) {
772 case TK_NAME: { /* param -> NAME */
773 new_localvar(ls, str_checkname(ls));
777 case TK_DOTS: { /* param -> `...' */
782 default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
784 } while (!f->is_vararg && testnext(ls, ','));
786 adjustlocalvars(ls, nparams);
787 f->numparams = cast_byte(fs->nactvar);
788 luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
792 static void body (LexState *ls, expdesc *e, int ismethod, int line) {
793 /* body -> `(' parlist `)' block END */
796 new_fs.f = addprototype(ls);
797 new_fs.f->linedefined = line;
798 open_func(ls, &new_fs, &bl);
801 new_localvarliteral(ls, "self"); /* create 'self' parameter */
802 adjustlocalvars(ls, 1);
807 new_fs.f->lastlinedefined = ls->linenumber;
808 check_match(ls, TK_END, TK_FUNCTION, line);
814 static int explist (LexState *ls, expdesc *v) {
815 /* explist -> expr { `,' expr } */
816 int n = 1; /* at least one expression */
818 while (testnext(ls, ',')) {
819 luaK_exp2nextreg(ls->fs, v);
827 static void funcargs (LexState *ls, expdesc *f, int line) {
828 FuncState *fs = ls->fs;
831 switch (ls->t.token) {
832 case '(': { /* funcargs -> `(' [ explist ] `)' */
834 if (ls->t.token == ')') /* arg list is empty? */
838 luaK_setmultret(fs, &args);
840 check_match(ls, ')', '(', line);
843 case '{': { /* funcargs -> constructor */
844 constructor(ls, &args);
847 case TK_STRING: { /* funcargs -> STRING */
848 codestring(ls, &args, ls->t.seminfo.ts);
849 luaX_next(ls); /* must use `seminfo' before `next' */
853 luaX_syntaxerror(ls, "function arguments expected");
856 lua_assert(f->k == VNONRELOC);
857 base = f->u.info; /* base register for call */
858 if (hasmultret(args.k))
859 nparams = LUA_MULTRET; /* open call */
862 luaK_exp2nextreg(fs, &args); /* close last argument */
863 nparams = fs->freereg - (base+1);
865 init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
866 luaK_fixline(fs, line);
867 fs->freereg = base+1; /* call remove function and arguments and leaves
868 (unless changed) one result */
875 ** {======================================================================
876 ** Expression parsing
877 ** =======================================================================
881 static void primaryexp (LexState *ls, expdesc *v) {
882 /* primaryexp -> NAME | '(' expr ')' */
883 switch (ls->t.token) {
885 int line = ls->linenumber;
888 check_match(ls, ')', '(', line);
889 luaK_dischargevars(ls->fs, v);
897 luaX_syntaxerror(ls, "unexpected symbol");
903 static void suffixedexp (LexState *ls, expdesc *v) {
905 primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
906 FuncState *fs = ls->fs;
907 int line = ls->linenumber;
910 switch (ls->t.token) {
911 case '.': { /* fieldsel */
915 case '[': { /* `[' exp1 `]' */
917 luaK_exp2anyregup(fs, v);
919 luaK_indexed(fs, v, &key);
922 case ':': { /* `:' NAME funcargs */
926 luaK_self(fs, v, &key);
927 funcargs(ls, v, line);
930 case '(': case TK_STRING: case '{': { /* funcargs */
931 luaK_exp2nextreg(fs, v);
932 funcargs(ls, v, line);
941 static void simpleexp (LexState *ls, expdesc *v) {
942 /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
943 constructor | FUNCTION body | suffixedexp */
944 switch (ls->t.token) {
946 init_exp(v, VKNUM, 0);
947 v->u.nval = ls->t.seminfo.r;
951 codestring(ls, v, ls->t.seminfo.ts);
955 init_exp(v, VNIL, 0);
959 init_exp(v, VTRUE, 0);
963 init_exp(v, VFALSE, 0);
966 case TK_DOTS: { /* vararg */
967 FuncState *fs = ls->fs;
968 check_condition(ls, fs->f->is_vararg,
969 "cannot use " LUA_QL("...") " outside a vararg function");
970 init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
973 case '{': { /* constructor */
979 body(ls, v, 0, ls->linenumber);
991 static UnOpr getunopr (int op) {
993 case TK_NOT: return OPR_NOT;
994 case '-': return OPR_MINUS;
995 case '#': return OPR_LEN;
996 default: return OPR_NOUNOPR;
1001 static BinOpr getbinopr (int op) {
1003 case '+': return OPR_ADD;
1004 case '-': return OPR_SUB;
1005 case '*': return OPR_MUL;
1006 case '/': return OPR_DIV;
1007 case '%': return OPR_MOD;
1008 case '^': return OPR_POW;
1009 case TK_CONCAT: return OPR_CONCAT;
1010 case TK_NE: return OPR_NE;
1011 case TK_EQ: return OPR_EQ;
1012 case '<': return OPR_LT;
1013 case TK_LE: return OPR_LE;
1014 case '>': return OPR_GT;
1015 case TK_GE: return OPR_GE;
1016 case TK_AND: return OPR_AND;
1017 case TK_OR: return OPR_OR;
1018 default: return OPR_NOBINOPR;
1023 static const struct {
1024 lu_byte left; /* left priority for each binary operator */
1025 lu_byte right; /* right priority */
1026 } priority[] = { /* ORDER OPR */
1027 {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `*' `/' `%' */
1028 {10, 9}, {5, 4}, /* ^, .. (right associative) */
1029 {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
1030 {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
1031 {2, 2}, {1, 1} /* and, or */
1034 #define UNARY_PRIORITY 8 /* priority for unary operators */
1038 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1039 ** where `binop' is any binary operator with a priority higher than `limit'
1041 static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
1045 uop = getunopr(ls->t.token);
1046 if (uop != OPR_NOUNOPR) {
1047 int line = ls->linenumber;
1049 subexpr(ls, v, UNARY_PRIORITY);
1050 luaK_prefix(ls->fs, uop, v, line);
1052 else simpleexp(ls, v);
1053 /* expand while operators have priorities higher than `limit' */
1054 op = getbinopr(ls->t.token);
1055 while (op != OPR_NOBINOPR && priority[op].left > limit) {
1058 int line = ls->linenumber;
1060 luaK_infix(ls->fs, op, v);
1061 /* read sub-expression with higher priority */
1062 nextop = subexpr(ls, &v2, priority[op].right);
1063 luaK_posfix(ls->fs, op, v, &v2, line);
1067 return op; /* return first untreated operator */
1071 static void expr (LexState *ls, expdesc *v) {
1075 /* }==================================================================== */
1080 ** {======================================================================
1081 ** Rules for Statements
1082 ** =======================================================================
1086 static void block (LexState *ls) {
1087 /* block -> statlist */
1088 FuncState *fs = ls->fs;
1090 enterblock(fs, &bl, 0);
1097 ** structure to chain all variables in the left-hand side of an
1101 struct LHS_assign *prev;
1102 expdesc v; /* variable (global, local, upvalue, or indexed) */
1107 ** check whether, in an assignment to an upvalue/local variable, the
1108 ** upvalue/local variable is begin used in a previous assignment to a
1109 ** table. If so, save original upvalue/local value in a safe place and
1110 ** use this safe copy in the previous assignment.
1112 static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
1113 FuncState *fs = ls->fs;
1114 int extra = fs->freereg; /* eventual position to save local variable */
1116 for (; lh; lh = lh->prev) { /* check all previous assignments */
1117 if (lh->v.k == VINDEXED) { /* assigning to a table? */
1118 /* table is the upvalue/local being assigned now? */
1119 if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {
1121 lh->v.u.ind.vt = VLOCAL;
1122 lh->v.u.ind.t = extra; /* previous assignment will use safe copy */
1124 /* index is the local being assigned? (index cannot be upvalue) */
1125 if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {
1127 lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
1132 /* copy upvalue/local value to a temporary (in position 'extra') */
1133 OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
1134 luaK_codeABC(fs, op, extra, v->u.info, 0);
1135 luaK_reserveregs(fs, 1);
1140 static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
1142 check_condition(ls, vkisvar(lh->v.k), "syntax error");
1143 if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */
1144 struct LHS_assign nv;
1146 suffixedexp(ls, &nv.v);
1147 if (nv.v.k != VINDEXED)
1148 check_conflict(ls, lh, &nv.v);
1149 checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,
1151 assignment(ls, &nv, nvars+1);
1153 else { /* assignment -> `=' explist */
1156 nexps = explist(ls, &e);
1157 if (nexps != nvars) {
1158 adjust_assign(ls, nvars, nexps, &e);
1160 ls->fs->freereg -= nexps - nvars; /* remove extra values */
1163 luaK_setoneret(ls->fs, &e); /* close last expression */
1164 luaK_storevar(ls->fs, &lh->v, &e);
1165 return; /* avoid default */
1168 init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
1169 luaK_storevar(ls->fs, &lh->v, &e);
1173 static int cond (LexState *ls) {
1176 expr(ls, &v); /* read condition */
1177 if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
1178 luaK_goiftrue(ls->fs, &v);
1183 static void gotostat (LexState *ls, int pc) {
1184 int line = ls->linenumber;
1187 if (testnext(ls, TK_GOTO))
1188 label = str_checkname(ls);
1190 luaX_next(ls); /* skip break */
1191 label = luaS_new(ls->L, "break");
1193 g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);
1194 findlabel(ls, g); /* close it if label already defined */
1198 /* check for repeated labels on the same block */
1199 static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
1201 for (i = fs->bl->firstlabel; i < ll->n; i++) {
1202 if (luaS_eqstr(label, ll->arr[i].name)) {
1203 const char *msg = luaO_pushfstring(fs->ls->L,
1204 "label " LUA_QS " already defined on line %d",
1205 getstr(label), ll->arr[i].line);
1206 semerror(fs->ls, msg);
1212 /* skip no-op statements */
1213 static void skipnoopstat (LexState *ls) {
1214 while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
1219 static void labelstat (LexState *ls, TString *label, int line) {
1220 /* label -> '::' NAME '::' */
1221 FuncState *fs = ls->fs;
1222 Labellist *ll = &ls->dyd->label;
1223 int l; /* index of new label being created */
1224 checkrepeated(fs, ll, label); /* check for repeated labels */
1225 checknext(ls, TK_DBCOLON); /* skip double colon */
1226 /* create new entry for this label */
1227 l = newlabelentry(ls, ll, label, line, fs->pc);
1228 skipnoopstat(ls); /* skip other no-op statements */
1229 if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */
1230 /* assume that locals are already out of scope */
1231 ll->arr[l].nactvar = fs->bl->nactvar;
1233 findgotos(ls, &ll->arr[l]);
1237 static void whilestat (LexState *ls, int line) {
1238 /* whilestat -> WHILE cond DO block END */
1239 FuncState *fs = ls->fs;
1243 luaX_next(ls); /* skip WHILE */
1244 whileinit = luaK_getlabel(fs);
1245 condexit = cond(ls);
1246 enterblock(fs, &bl, 1);
1247 checknext(ls, TK_DO);
1249 luaK_jumpto(fs, whileinit);
1250 check_match(ls, TK_END, TK_WHILE, line);
1252 luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
1256 static void repeatstat (LexState *ls, int line) {
1257 /* repeatstat -> REPEAT block UNTIL cond */
1259 FuncState *fs = ls->fs;
1260 int repeat_init = luaK_getlabel(fs);
1262 enterblock(fs, &bl1, 1); /* loop block */
1263 enterblock(fs, &bl2, 0); /* scope block */
1264 luaX_next(ls); /* skip REPEAT */
1266 check_match(ls, TK_UNTIL, TK_REPEAT, line);
1267 condexit = cond(ls); /* read condition (inside scope block) */
1268 if (bl2.upval) /* upvalues? */
1269 luaK_patchclose(fs, condexit, bl2.nactvar);
1270 leaveblock(fs); /* finish scope */
1271 luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
1272 leaveblock(fs); /* finish loop */
1276 static int exp1 (LexState *ls) {
1280 luaK_exp2nextreg(ls->fs, &e);
1281 lua_assert(e.k == VNONRELOC);
1287 static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1288 /* forbody -> DO block */
1290 FuncState *fs = ls->fs;
1292 adjustlocalvars(ls, 3); /* control variables */
1293 checknext(ls, TK_DO);
1294 prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1295 enterblock(fs, &bl, 0); /* scope for declared variables */
1296 adjustlocalvars(ls, nvars);
1297 luaK_reserveregs(fs, nvars);
1299 leaveblock(fs); /* end of scope for declared variables */
1300 luaK_patchtohere(fs, prep);
1301 if (isnum) /* numeric for? */
1302 endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
1303 else { /* generic for */
1304 luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
1305 luaK_fixline(fs, line);
1306 endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
1308 luaK_patchlist(fs, endfor, prep + 1);
1309 luaK_fixline(fs, line);
1313 static void fornum (LexState *ls, TString *varname, int line) {
1314 /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1315 FuncState *fs = ls->fs;
1316 int base = fs->freereg;
1317 new_localvarliteral(ls, "(for index)");
1318 new_localvarliteral(ls, "(for limit)");
1319 new_localvarliteral(ls, "(for step)");
1320 new_localvar(ls, varname);
1322 exp1(ls); /* initial value */
1324 exp1(ls); /* limit */
1325 if (testnext(ls, ','))
1326 exp1(ls); /* optional step */
1327 else { /* default step = 1 */
1328 luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1));
1329 luaK_reserveregs(fs, 1);
1331 forbody(ls, base, line, 1, 1);
1335 static void forlist (LexState *ls, TString *indexname) {
1336 /* forlist -> NAME {,NAME} IN explist forbody */
1337 FuncState *fs = ls->fs;
1339 int nvars = 4; /* gen, state, control, plus at least one declared var */
1341 int base = fs->freereg;
1342 /* create control variables */
1343 new_localvarliteral(ls, "(for generator)");
1344 new_localvarliteral(ls, "(for state)");
1345 new_localvarliteral(ls, "(for control)");
1346 /* create declared variables */
1347 new_localvar(ls, indexname);
1348 while (testnext(ls, ',')) {
1349 new_localvar(ls, str_checkname(ls));
1352 checknext(ls, TK_IN);
1353 line = ls->linenumber;
1354 adjust_assign(ls, 3, explist(ls, &e), &e);
1355 luaK_checkstack(fs, 3); /* extra space to call generator */
1356 forbody(ls, base, line, nvars - 3, 0);
1360 static void forstat (LexState *ls, int line) {
1361 /* forstat -> FOR (fornum | forlist) END */
1362 FuncState *fs = ls->fs;
1365 enterblock(fs, &bl, 1); /* scope for loop and control variables */
1366 luaX_next(ls); /* skip `for' */
1367 varname = str_checkname(ls); /* first variable name */
1368 switch (ls->t.token) {
1369 case '=': fornum(ls, varname, line); break;
1370 case ',': case TK_IN: forlist(ls, varname); break;
1371 default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
1373 check_match(ls, TK_END, TK_FOR, line);
1374 leaveblock(fs); /* loop scope (`break' jumps to this point) */
1378 __attribute__((always_inline)) inline
1379 static void test_then_block (LexState *ls, int *escapelist) {
1380 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1382 FuncState *fs = ls->fs;
1384 int jf; /* instruction to skip 'then' code (if condition is false) */
1385 luaX_next(ls); /* skip IF or ELSEIF */
1386 expr(ls, &v); /* read condition */
1387 checknext(ls, TK_THEN);
1388 if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
1389 luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */
1390 enterblock(fs, &bl, 0); /* must enter block before 'goto' */
1391 gotostat(ls, v.t); /* handle goto/break */
1392 skipnoopstat(ls); /* skip other no-op statements */
1393 if (block_follow(ls, 0)) { /* 'goto' is the entire block? */
1395 return; /* and that is it */
1397 else /* must skip over 'then' part if condition is false */
1400 else { /* regular case (not goto/break) */
1401 luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */
1402 enterblock(fs, &bl, 0);
1405 statlist(ls); /* `then' part */
1407 if (ls->t.token == TK_ELSE ||
1408 ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
1409 luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
1410 luaK_patchtohere(fs, jf);
1414 static void ifstat (LexState *ls, int line) {
1415 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1416 FuncState *fs = ls->fs;
1417 int escapelist = NO_JUMP; /* exit list for finished parts */
1418 test_then_block(ls, &escapelist); /* IF cond THEN block */
1419 while (ls->t.token == TK_ELSEIF)
1420 test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
1421 if (testnext(ls, TK_ELSE))
1422 block(ls); /* `else' part */
1423 check_match(ls, TK_END, TK_IF, line);
1424 luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
1428 static void localfunc (LexState *ls) {
1430 FuncState *fs = ls->fs;
1431 new_localvar(ls, str_checkname(ls)); /* new local variable */
1432 adjustlocalvars(ls, 1); /* enter its scope */
1433 body(ls, &b, 0, ls->linenumber); /* function created in next register */
1434 /* debug information will only see the variable after this point! */
1435 getlocvar(fs, b.u.info)->startpc = fs->pc;
1439 static void localstat (LexState *ls) {
1440 /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
1445 new_localvar(ls, str_checkname(ls));
1447 } while (testnext(ls, ','));
1448 if (testnext(ls, '='))
1449 nexps = explist(ls, &e);
1454 adjust_assign(ls, nvars, nexps, &e);
1455 adjustlocalvars(ls, nvars);
1459 static int funcname (LexState *ls, expdesc *v) {
1460 /* funcname -> NAME {fieldsel} [`:' NAME] */
1463 while (ls->t.token == '.')
1465 if (ls->t.token == ':') {
1473 static void funcstat (LexState *ls, int line) {
1474 /* funcstat -> FUNCTION funcname body */
1477 luaX_next(ls); /* skip FUNCTION */
1478 ismethod = funcname(ls, &v);
1479 body(ls, &b, ismethod, line);
1480 luaK_storevar(ls->fs, &v, &b);
1481 luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
1485 static void exprstat (LexState *ls) {
1486 /* stat -> func | assignment */
1487 FuncState *fs = ls->fs;
1488 struct LHS_assign v;
1489 suffixedexp(ls, &v.v);
1490 if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
1492 assignment(ls, &v, 1);
1494 else { /* stat -> func */
1495 check_condition(ls, v.v.k == VCALL, "syntax error");
1496 SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
1501 static void retstat (LexState *ls) {
1502 /* stat -> RETURN [explist] [';'] */
1503 FuncState *fs = ls->fs;
1505 int first, nret; /* registers with returned values */
1506 if (block_follow(ls, 1) || ls->t.token == ';')
1507 first = nret = 0; /* return no values */
1509 nret = explist(ls, &e); /* optional return values */
1510 if (hasmultret(e.k)) {
1511 luaK_setmultret(fs, &e);
1512 if (e.k == VCALL && nret == 1) { /* tail call? */
1513 SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1514 lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1516 first = fs->nactvar;
1517 nret = LUA_MULTRET; /* return all values */
1520 if (nret == 1) /* only one single value? */
1521 first = luaK_exp2anyreg(fs, &e);
1523 luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
1524 first = fs->nactvar; /* return all `active' values */
1525 lua_assert(nret == fs->freereg - first);
1529 luaK_ret(fs, first, nret);
1530 (void) testnext(ls, ';'); /* skip optional semicolon */
1534 static void statement (LexState *ls) {
1535 int line = ls->linenumber; /* may be needed for error messages */
1537 switch (ls->t.token) {
1538 case ';': { /* stat -> ';' (empty statement) */
1539 luaX_next(ls); /* skip ';' */
1542 case TK_IF: { /* stat -> ifstat */
1546 case TK_WHILE: { /* stat -> whilestat */
1547 whilestat(ls, line);
1550 case TK_DO: { /* stat -> DO block END */
1551 luaX_next(ls); /* skip DO */
1553 check_match(ls, TK_END, TK_DO, line);
1556 case TK_FOR: { /* stat -> forstat */
1560 case TK_REPEAT: { /* stat -> repeatstat */
1561 repeatstat(ls, line);
1564 case TK_FUNCTION: { /* stat -> funcstat */
1568 case TK_LOCAL: { /* stat -> localstat */
1569 luaX_next(ls); /* skip LOCAL */
1570 if (testnext(ls, TK_FUNCTION)) /* local function? */
1576 case TK_DBCOLON: { /* stat -> label */
1577 luaX_next(ls); /* skip double colon */
1578 labelstat(ls, str_checkname(ls), line);
1581 case TK_RETURN: { /* stat -> retstat */
1582 luaX_next(ls); /* skip RETURN */
1586 case TK_BREAK: /* stat -> breakstat */
1587 case TK_GOTO: { /* stat -> 'goto' NAME */
1588 gotostat(ls, luaK_jump(ls->fs));
1591 default: { /* stat -> func | assignment */
1596 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1597 ls->fs->freereg >= ls->fs->nactvar);
1598 ls->fs->freereg = ls->fs->nactvar; /* free registers */
1602 /* }====================================================================== */
1606 ** compiles the main function, which is a regular vararg function with an
1607 ** upvalue named LUA_ENV
1609 static void mainfunc (LexState *ls, FuncState *fs) {
1612 open_func(ls, fs, &bl);
1613 fs->f->is_vararg = 1; /* main function is always vararg */
1614 init_exp(&v, VLOCAL, 0); /* create and... */
1615 newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */
1616 luaX_next(ls); /* read first token */
1617 statlist(ls); /* parse main body */
1623 Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1624 Dyndata *dyd, const char *name, int firstchar) {
1626 FuncState funcstate;
1627 Closure *cl = luaF_newLclosure(L, 1); /* create main closure */
1628 /* anchor closure (to avoid being collected) */
1629 setclLvalue(L, L->top, cl);
1631 funcstate.f = cl->l.p = luaF_newproto(L);
1632 funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
1633 lexstate.buff = buff;
1635 dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
1636 luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
1637 mainfunc(&lexstate, &funcstate);
1638 lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
1639 /* all scopes should be correctly finished */
1640 lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
1641 return cl; /* it's on the stack too */