FreeBSD: Lock vnode in zfs_ioctl()
[zfs.git] / module / lua / lparser.c
blobf3a1f772486b52ffa27b4ae76102fe8084b72948
1 /*
2 ** $Id: lparser.c,v 2.130.1.1 2013/04/12 18:48:47 roberto Exp $
3 ** Lua Parser
4 ** See Copyright Notice in lua.h
5 */
7 #define lparser_c
8 #define LUA_CORE
10 #include <sys/lua/lua.h>
12 #include "lcode.h"
13 #include "ldebug.h"
14 #include "ldo.h"
15 #include "lfunc.h"
16 #include "llex.h"
17 #include "lmem.h"
18 #include "lobject.h"
19 #include "lopcodes.h"
20 #include "lparser.h"
21 #include "lstate.h"
22 #include "lstring.h"
23 #include "ltable.h"
27 /* maximum number of local variables per function (must be smaller
28 than 250, due to the bytecode format) */
29 #define MAXVARS 200
32 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
37 ** nodes for block list (list of active blocks)
39 typedef struct BlockCnt {
40 struct BlockCnt *previous; /* chain */
41 short firstlabel; /* index of first label in this block */
42 short firstgoto; /* index of first pending goto in this block */
43 lu_byte nactvar; /* # active locals outside the block */
44 lu_byte upval; /* true if some variable in the block is an upvalue */
45 lu_byte isloop; /* true if `block' is a loop */
46 } BlockCnt;
51 ** prototypes for recursive non-terminal functions
53 static void statement (LexState *ls);
54 static void expr (LexState *ls, expdesc *v);
57 static void anchor_token (LexState *ls) {
58 /* last token from outer function must be EOS */
59 lua_assert(ls->fs != NULL || ls->t.token == TK_EOS);
60 if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
61 TString *ts = ls->t.seminfo.ts;
62 luaX_newstring(ls, getstr(ts), ts->tsv.len);
67 /* semantic error */
68 static l_noret semerror (LexState *ls, const char *msg) {
69 ls->t.token = 0; /* remove 'near to' from final message */
70 luaX_syntaxerror(ls, msg);
74 static l_noret error_expected (LexState *ls, int token) {
75 luaX_syntaxerror(ls,
76 luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
80 static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
81 lua_State *L = fs->ls->L;
82 const char *msg;
83 int line = fs->f->linedefined;
84 const char *where = (line == 0)
85 ? "main function"
86 : luaO_pushfstring(L, "function at line %d", line);
87 msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
88 what, limit, where);
89 luaX_syntaxerror(fs->ls, msg);
93 static void checklimit (FuncState *fs, int v, int l, const char *what) {
94 if (v > l) errorlimit(fs, l, what);
98 static int testnext (LexState *ls, int c) {
99 if (ls->t.token == c) {
100 luaX_next(ls);
101 return 1;
103 else return 0;
107 static void check (LexState *ls, int c) {
108 if (ls->t.token != c)
109 error_expected(ls, c);
113 static void checknext (LexState *ls, int c) {
114 check(ls, c);
115 luaX_next(ls);
119 #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
123 static void check_match (LexState *ls, int what, int who, int where) {
124 if (!testnext(ls, what)) {
125 if (where == ls->linenumber)
126 error_expected(ls, what);
127 else {
128 luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
129 "%s expected (to close %s at line %d)",
130 luaX_token2str(ls, what), luaX_token2str(ls, who), where));
136 static TString *str_checkname (LexState *ls) {
137 TString *ts;
138 check(ls, TK_NAME);
139 ts = ls->t.seminfo.ts;
140 luaX_next(ls);
141 return ts;
145 static void init_exp (expdesc *e, expkind k, int i) {
146 e->f = e->t = NO_JUMP;
147 e->k = k;
148 e->u.info = i;
152 static void codestring (LexState *ls, expdesc *e, TString *s) {
153 init_exp(e, VK, luaK_stringK(ls->fs, s));
157 static void checkname (LexState *ls, expdesc *e) {
158 codestring(ls, e, str_checkname(ls));
162 static int registerlocalvar (LexState *ls, TString *varname) {
163 FuncState *fs = ls->fs;
164 Proto *f = fs->f;
165 int oldsize = f->sizelocvars;
166 luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
167 LocVar, SHRT_MAX, "local variables");
168 while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
169 f->locvars[fs->nlocvars].varname = varname;
170 luaC_objbarrier(ls->L, f, varname);
171 return fs->nlocvars++;
175 static void new_localvar (LexState *ls, TString *name) {
176 FuncState *fs = ls->fs;
177 Dyndata *dyd = ls->dyd;
178 int reg = registerlocalvar(ls, name);
179 checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
180 MAXVARS, "local variables");
181 luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,
182 dyd->actvar.size, Vardesc, MAX_INT, "local variables");
183 dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg);
187 static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) {
188 new_localvar(ls, luaX_newstring(ls, name, sz));
191 #define new_localvarliteral(ls,v) \
192 new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1)
195 static LocVar *getlocvar (FuncState *fs, int i) {
196 int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
197 lua_assert(idx < fs->nlocvars);
198 return &fs->f->locvars[idx];
202 static void adjustlocalvars (LexState *ls, int nvars) {
203 FuncState *fs = ls->fs;
204 fs->nactvar = cast_byte(fs->nactvar + nvars);
205 for (; nvars; nvars--) {
206 getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;
211 static void removevars (FuncState *fs, int tolevel) {
212 fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
213 while (fs->nactvar > tolevel)
214 getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
218 static int searchupvalue (FuncState *fs, TString *name) {
219 int i;
220 Upvaldesc *up = fs->f->upvalues;
221 for (i = 0; i < fs->nups; i++) {
222 if (luaS_eqstr(up[i].name, name)) return i;
224 return -1; /* not found */
228 static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
229 Proto *f = fs->f;
230 int oldsize = f->sizeupvalues;
231 checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
232 luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
233 Upvaldesc, MAXUPVAL, "upvalues");
234 while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL;
235 f->upvalues[fs->nups].instack = (v->k == VLOCAL);
236 f->upvalues[fs->nups].idx = cast_byte(v->u.info);
237 f->upvalues[fs->nups].name = name;
238 luaC_objbarrier(fs->ls->L, f, name);
239 return fs->nups++;
243 static int searchvar (FuncState *fs, TString *n) {
244 int i;
245 for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
246 if (luaS_eqstr(n, getlocvar(fs, i)->varname))
247 return i;
249 return -1; /* not found */
254 Mark block where variable at given level was defined
255 (to emit close instructions later).
257 static void markupval (FuncState *fs, int level) {
258 BlockCnt *bl = fs->bl;
259 while (bl->nactvar > level) bl = bl->previous;
260 bl->upval = 1;
265 Find variable with given name 'n'. If it is an upvalue, add this
266 upvalue into all intermediate functions.
268 static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
269 if (fs == NULL) /* no more levels? */
270 return VVOID; /* default is global */
271 else {
272 int v = searchvar(fs, n); /* look up locals at current level */
273 if (v >= 0) { /* found? */
274 init_exp(var, VLOCAL, v); /* variable is local */
275 if (!base)
276 markupval(fs, v); /* local will be used as an upval */
277 return VLOCAL;
279 else { /* not found as local at current level; try upvalues */
280 int idx = searchupvalue(fs, n); /* try existing upvalues */
281 if (idx < 0) { /* not found? */
282 if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */
283 return VVOID; /* not found; is a global */
284 /* else was LOCAL or UPVAL */
285 idx = newupvalue(fs, n, var); /* will be a new upvalue */
287 init_exp(var, VUPVAL, idx);
288 return VUPVAL;
294 static void singlevar (LexState *ls, expdesc *var) {
295 TString *varname = str_checkname(ls);
296 FuncState *fs = ls->fs;
297 if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */
298 expdesc key;
299 singlevaraux(fs, ls->envn, var, 1); /* get environment variable */
300 lua_assert(var->k == VLOCAL || var->k == VUPVAL);
301 codestring(ls, &key, varname); /* key is variable name */
302 luaK_indexed(fs, var, &key); /* env[varname] */
307 static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
308 FuncState *fs = ls->fs;
309 int extra = nvars - nexps;
310 if (hasmultret(e->k)) {
311 extra++; /* includes call itself */
312 if (extra < 0) extra = 0;
313 luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
314 if (extra > 1) luaK_reserveregs(fs, extra-1);
316 else {
317 if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */
318 if (extra > 0) {
319 int reg = fs->freereg;
320 luaK_reserveregs(fs, extra);
321 luaK_nil(fs, reg, extra);
327 static void enterlevel (LexState *ls) {
328 lua_State *L = ls->L;
329 ++L->nCcalls;
330 checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels");
334 #define leavelevel(ls) ((ls)->L->nCcalls--)
337 static void closegoto (LexState *ls, int g, Labeldesc *label) {
338 int i;
339 FuncState *fs = ls->fs;
340 Labellist *gl = &ls->dyd->gt;
341 Labeldesc *gt = &gl->arr[g];
342 lua_assert(luaS_eqstr(gt->name, label->name));
343 if (gt->nactvar < label->nactvar) {
344 TString *vname = getlocvar(fs, gt->nactvar)->varname;
345 const char *msg = luaO_pushfstring(ls->L,
346 "<goto %s> at line %d jumps into the scope of local " LUA_QS,
347 getstr(gt->name), gt->line, getstr(vname));
348 semerror(ls, msg);
350 luaK_patchlist(fs, gt->pc, label->pc);
351 /* remove goto from pending list */
352 for (i = g; i < gl->n - 1; i++)
353 gl->arr[i] = gl->arr[i + 1];
354 gl->n--;
359 ** try to close a goto with existing labels; this solves backward jumps
361 static int findlabel (LexState *ls, int g) {
362 int i;
363 BlockCnt *bl = ls->fs->bl;
364 Dyndata *dyd = ls->dyd;
365 Labeldesc *gt = &dyd->gt.arr[g];
366 /* check labels in current block for a match */
367 for (i = bl->firstlabel; i < dyd->label.n; i++) {
368 Labeldesc *lb = &dyd->label.arr[i];
369 if (luaS_eqstr(lb->name, gt->name)) { /* correct label? */
370 if (gt->nactvar > lb->nactvar &&
371 (bl->upval || dyd->label.n > bl->firstlabel))
372 luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
373 closegoto(ls, g, lb); /* close it */
374 return 1;
377 return 0; /* label not found; cannot close goto */
381 static int newlabelentry (LexState *ls, Labellist *l, TString *name,
382 int line, int pc) {
383 int n = l->n;
384 luaM_growvector(ls->L, l->arr, n, l->size,
385 Labeldesc, SHRT_MAX, "labels/gotos");
386 l->arr[n].name = name;
387 l->arr[n].line = line;
388 l->arr[n].nactvar = ls->fs->nactvar;
389 l->arr[n].pc = pc;
390 l->n++;
391 return n;
396 ** check whether new label 'lb' matches any pending gotos in current
397 ** block; solves forward jumps
399 static void findgotos (LexState *ls, Labeldesc *lb) {
400 Labellist *gl = &ls->dyd->gt;
401 int i = ls->fs->bl->firstgoto;
402 while (i < gl->n) {
403 if (luaS_eqstr(gl->arr[i].name, lb->name))
404 closegoto(ls, i, lb);
405 else
406 i++;
412 ** "export" pending gotos to outer level, to check them against
413 ** outer labels; if the block being exited has upvalues, and
414 ** the goto exits the scope of any variable (which can be the
415 ** upvalue), close those variables being exited.
417 static void movegotosout (FuncState *fs, BlockCnt *bl) {
418 int i = bl->firstgoto;
419 Labellist *gl = &fs->ls->dyd->gt;
420 /* correct pending gotos to current block and try to close it
421 with visible labels */
422 while (i < gl->n) {
423 Labeldesc *gt = &gl->arr[i];
424 if (gt->nactvar > bl->nactvar) {
425 if (bl->upval)
426 luaK_patchclose(fs, gt->pc, bl->nactvar);
427 gt->nactvar = bl->nactvar;
429 if (!findlabel(fs->ls, i))
430 i++; /* move to next one */
435 static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
436 bl->isloop = isloop;
437 bl->nactvar = fs->nactvar;
438 bl->firstlabel = fs->ls->dyd->label.n;
439 bl->firstgoto = fs->ls->dyd->gt.n;
440 bl->upval = 0;
441 bl->previous = fs->bl;
442 fs->bl = bl;
443 lua_assert(fs->freereg == fs->nactvar);
448 ** create a label named "break" to resolve break statements
450 static void breaklabel (LexState *ls) {
451 TString *n = luaS_new(ls->L, "break");
452 int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);
453 findgotos(ls, &ls->dyd->label.arr[l]);
457 ** generates an error for an undefined 'goto'; choose appropriate
458 ** message when label name is a reserved word (which can only be 'break')
460 static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
461 const char *msg = isreserved(gt->name)
462 ? "<%s> at line %d not inside a loop"
463 : "no visible label " LUA_QS " for <goto> at line %d";
464 msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
465 semerror(ls, msg);
469 static void leaveblock (FuncState *fs) {
470 BlockCnt *bl = fs->bl;
471 LexState *ls = fs->ls;
472 if (bl->previous && bl->upval) {
473 /* create a 'jump to here' to close upvalues */
474 int j = luaK_jump(fs);
475 luaK_patchclose(fs, j, bl->nactvar);
476 luaK_patchtohere(fs, j);
478 if (bl->isloop)
479 breaklabel(ls); /* close pending breaks */
480 fs->bl = bl->previous;
481 removevars(fs, bl->nactvar);
482 lua_assert(bl->nactvar == fs->nactvar);
483 fs->freereg = fs->nactvar; /* free registers */
484 ls->dyd->label.n = bl->firstlabel; /* remove local labels */
485 if (bl->previous) /* inner block? */
486 movegotosout(fs, bl); /* update pending gotos to outer block */
487 else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */
488 undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
493 ** adds a new prototype into list of prototypes
495 static Proto *addprototype (LexState *ls) {
496 Proto *clp;
497 lua_State *L = ls->L;
498 FuncState *fs = ls->fs;
499 Proto *f = fs->f; /* prototype of current function */
500 if (fs->np >= f->sizep) {
501 int oldsize = f->sizep;
502 luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
503 while (oldsize < f->sizep) f->p[oldsize++] = NULL;
505 f->p[fs->np++] = clp = luaF_newproto(L);
506 luaC_objbarrier(L, f, clp);
507 return clp;
512 ** codes instruction to create new closure in parent function.
513 ** The OP_CLOSURE instruction must use the last available register,
514 ** so that, if it invokes the GC, the GC knows which registers
515 ** are in use at that time.
517 static void codeclosure (LexState *ls, expdesc *v) {
518 FuncState *fs = ls->fs->prev;
519 init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
520 luaK_exp2nextreg(fs, v); /* fix it at the last register */
524 static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
525 lua_State *L = ls->L;
526 Proto *f;
527 fs->prev = ls->fs; /* linked list of funcstates */
528 fs->ls = ls;
529 ls->fs = fs;
530 fs->pc = 0;
531 fs->lasttarget = 0;
532 fs->jpc = NO_JUMP;
533 fs->freereg = 0;
534 fs->nk = 0;
535 fs->np = 0;
536 fs->nups = 0;
537 fs->nlocvars = 0;
538 fs->nactvar = 0;
539 fs->firstlocal = ls->dyd->actvar.n;
540 fs->bl = NULL;
541 f = fs->f;
542 f->source = ls->source;
543 f->maxstacksize = 2; /* registers 0/1 are always valid */
544 fs->h = luaH_new(L);
545 /* anchor table of constants (to avoid being collected) */
546 sethvalue2s(L, L->top, fs->h);
547 incr_top(L);
548 enterblock(fs, bl, 0);
552 static void close_func (LexState *ls) {
553 lua_State *L = ls->L;
554 FuncState *fs = ls->fs;
555 Proto *f = fs->f;
556 luaK_ret(fs, 0, 0); /* final return */
557 leaveblock(fs);
558 luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
559 f->sizecode = fs->pc;
560 luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
561 f->sizelineinfo = fs->pc;
562 luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
563 f->sizek = fs->nk;
564 luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
565 f->sizep = fs->np;
566 luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
567 f->sizelocvars = fs->nlocvars;
568 luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
569 f->sizeupvalues = fs->nups;
570 lua_assert(fs->bl == NULL);
571 ls->fs = fs->prev;
572 /* last token read was anchored in defunct function; must re-anchor it */
573 anchor_token(ls);
574 L->top--; /* pop table of constants */
575 luaC_checkGC(L);
580 /*============================================================*/
581 /* GRAMMAR RULES */
582 /*============================================================*/
586 ** check whether current token is in the follow set of a block.
587 ** 'until' closes syntactical blocks, but do not close scope,
588 ** so it handled in separate.
590 static int block_follow (LexState *ls, int withuntil) {
591 switch (ls->t.token) {
592 case TK_ELSE: case TK_ELSEIF:
593 case TK_END: case TK_EOS:
594 return 1;
595 case TK_UNTIL: return withuntil;
596 default: return 0;
602 * by inlining statlist() and test_then_block() we cut back the
603 * native stack usage per nested C call from 272 bytes to 152
604 * which allows us to stay within budget for 8K kernel stacks
606 __attribute__((always_inline)) inline
607 static void statlist (LexState *ls) {
608 /* statlist -> { stat [`;'] } */
609 while (!block_follow(ls, 1)) {
610 if (ls->t.token == TK_RETURN) {
611 statement(ls);
612 return; /* 'return' must be last statement */
614 statement(ls);
619 static void fieldsel (LexState *ls, expdesc *v) {
620 /* fieldsel -> ['.' | ':'] NAME */
621 FuncState *fs = ls->fs;
622 expdesc key;
623 luaK_exp2anyregup(fs, v);
624 luaX_next(ls); /* skip the dot or colon */
625 checkname(ls, &key);
626 luaK_indexed(fs, v, &key);
630 static void yindex (LexState *ls, expdesc *v) {
631 /* index -> '[' expr ']' */
632 luaX_next(ls); /* skip the '[' */
633 expr(ls, v);
634 luaK_exp2val(ls->fs, v);
635 checknext(ls, ']');
640 ** {======================================================================
641 ** Rules for Constructors
642 ** =======================================================================
646 struct ConsControl {
647 expdesc v; /* last list item read */
648 expdesc *t; /* table descriptor */
649 int nh; /* total number of `record' elements */
650 int na; /* total number of array elements */
651 int tostore; /* number of array elements pending to be stored */
655 static void recfield (LexState *ls, struct ConsControl *cc) {
656 /* recfield -> (NAME | `['exp1`]') = exp1 */
657 FuncState *fs = ls->fs;
658 int reg = ls->fs->freereg;
659 expdesc key, val;
660 int rkkey;
661 if (ls->t.token == TK_NAME) {
662 checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
663 checkname(ls, &key);
665 else /* ls->t.token == '[' */
666 yindex(ls, &key);
667 cc->nh++;
668 checknext(ls, '=');
669 rkkey = luaK_exp2RK(fs, &key);
670 expr(ls, &val);
671 luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val));
672 fs->freereg = reg; /* free registers */
676 static void closelistfield (FuncState *fs, struct ConsControl *cc) {
677 if (cc->v.k == VVOID) return; /* there is no list item */
678 luaK_exp2nextreg(fs, &cc->v);
679 cc->v.k = VVOID;
680 if (cc->tostore == LFIELDS_PER_FLUSH) {
681 luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
682 cc->tostore = 0; /* no more items pending */
687 static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
688 if (cc->tostore == 0) return;
689 if (hasmultret(cc->v.k)) {
690 luaK_setmultret(fs, &cc->v);
691 luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
692 cc->na--; /* do not count last expression (unknown number of elements) */
694 else {
695 if (cc->v.k != VVOID)
696 luaK_exp2nextreg(fs, &cc->v);
697 luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
702 static void listfield (LexState *ls, struct ConsControl *cc) {
703 /* listfield -> exp */
704 expr(ls, &cc->v);
705 checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
706 cc->na++;
707 cc->tostore++;
711 static void field (LexState *ls, struct ConsControl *cc) {
712 /* field -> listfield | recfield */
713 switch(ls->t.token) {
714 case TK_NAME: { /* may be 'listfield' or 'recfield' */
715 if (luaX_lookahead(ls) != '=') /* expression? */
716 listfield(ls, cc);
717 else
718 recfield(ls, cc);
719 break;
721 case '[': {
722 recfield(ls, cc);
723 break;
725 default: {
726 listfield(ls, cc);
727 break;
733 static void constructor (LexState *ls, expdesc *t) {
734 /* constructor -> '{' [ field { sep field } [sep] ] '}'
735 sep -> ',' | ';' */
736 FuncState *fs = ls->fs;
737 int line = ls->linenumber;
738 int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
739 struct ConsControl cc;
740 cc.na = cc.nh = cc.tostore = 0;
741 cc.t = t;
742 init_exp(t, VRELOCABLE, pc);
743 init_exp(&cc.v, VVOID, 0); /* no value (yet) */
744 luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */
745 checknext(ls, '{');
746 do {
747 lua_assert(cc.v.k == VVOID || cc.tostore > 0);
748 if (ls->t.token == '}') break;
749 closelistfield(fs, &cc);
750 field(ls, &cc);
751 } while (testnext(ls, ',') || testnext(ls, ';'));
752 check_match(ls, '}', '{', line);
753 lastlistfield(fs, &cc);
754 SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
755 SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
758 /* }====================================================================== */
762 static void parlist (LexState *ls) {
763 /* parlist -> [ param { `,' param } ] */
764 FuncState *fs = ls->fs;
765 Proto *f = fs->f;
766 int nparams = 0;
767 f->is_vararg = 0;
768 if (ls->t.token != ')') { /* is `parlist' not empty? */
769 do {
770 switch (ls->t.token) {
771 case TK_NAME: { /* param -> NAME */
772 new_localvar(ls, str_checkname(ls));
773 nparams++;
774 break;
776 case TK_DOTS: { /* param -> `...' */
777 luaX_next(ls);
778 f->is_vararg = 1;
779 break;
781 default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
783 } while (!f->is_vararg && testnext(ls, ','));
785 adjustlocalvars(ls, nparams);
786 f->numparams = cast_byte(fs->nactvar);
787 luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
791 static void body (LexState *ls, expdesc *e, int ismethod, int line) {
792 /* body -> `(' parlist `)' block END */
793 FuncState new_fs;
794 BlockCnt bl;
795 new_fs.f = addprototype(ls);
796 new_fs.f->linedefined = line;
797 open_func(ls, &new_fs, &bl);
798 checknext(ls, '(');
799 if (ismethod) {
800 new_localvarliteral(ls, "self"); /* create 'self' parameter */
801 adjustlocalvars(ls, 1);
803 parlist(ls);
804 checknext(ls, ')');
805 statlist(ls);
806 new_fs.f->lastlinedefined = ls->linenumber;
807 check_match(ls, TK_END, TK_FUNCTION, line);
808 codeclosure(ls, e);
809 close_func(ls);
813 static int explist (LexState *ls, expdesc *v) {
814 /* explist -> expr { `,' expr } */
815 int n = 1; /* at least one expression */
816 expr(ls, v);
817 while (testnext(ls, ',')) {
818 luaK_exp2nextreg(ls->fs, v);
819 expr(ls, v);
820 n++;
822 return n;
826 static void funcargs (LexState *ls, expdesc *f, int line) {
827 FuncState *fs = ls->fs;
828 expdesc args;
829 int base, nparams;
830 switch (ls->t.token) {
831 case '(': { /* funcargs -> `(' [ explist ] `)' */
832 luaX_next(ls);
833 if (ls->t.token == ')') /* arg list is empty? */
834 args.k = VVOID;
835 else {
836 explist(ls, &args);
837 luaK_setmultret(fs, &args);
839 check_match(ls, ')', '(', line);
840 break;
842 case '{': { /* funcargs -> constructor */
843 constructor(ls, &args);
844 break;
846 case TK_STRING: { /* funcargs -> STRING */
847 codestring(ls, &args, ls->t.seminfo.ts);
848 luaX_next(ls); /* must use `seminfo' before `next' */
849 break;
851 default: {
852 luaX_syntaxerror(ls, "function arguments expected");
855 lua_assert(f->k == VNONRELOC);
856 base = f->u.info; /* base register for call */
857 if (hasmultret(args.k))
858 nparams = LUA_MULTRET; /* open call */
859 else {
860 if (args.k != VVOID)
861 luaK_exp2nextreg(fs, &args); /* close last argument */
862 nparams = fs->freereg - (base+1);
864 init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
865 luaK_fixline(fs, line);
866 fs->freereg = base+1; /* call remove function and arguments and leaves
867 (unless changed) one result */
874 ** {======================================================================
875 ** Expression parsing
876 ** =======================================================================
880 static void primaryexp (LexState *ls, expdesc *v) {
881 /* primaryexp -> NAME | '(' expr ')' */
882 switch (ls->t.token) {
883 case '(': {
884 int line = ls->linenumber;
885 luaX_next(ls);
886 expr(ls, v);
887 check_match(ls, ')', '(', line);
888 luaK_dischargevars(ls->fs, v);
889 return;
891 case TK_NAME: {
892 singlevar(ls, v);
893 return;
895 default: {
896 luaX_syntaxerror(ls, "unexpected symbol");
902 static void suffixedexp (LexState *ls, expdesc *v) {
903 /* suffixedexp ->
904 primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
905 FuncState *fs = ls->fs;
906 int line = ls->linenumber;
907 primaryexp(ls, v);
908 for (;;) {
909 switch (ls->t.token) {
910 case '.': { /* fieldsel */
911 fieldsel(ls, v);
912 break;
914 case '[': { /* `[' exp1 `]' */
915 expdesc key;
916 luaK_exp2anyregup(fs, v);
917 yindex(ls, &key);
918 luaK_indexed(fs, v, &key);
919 break;
921 case ':': { /* `:' NAME funcargs */
922 expdesc key;
923 luaX_next(ls);
924 checkname(ls, &key);
925 luaK_self(fs, v, &key);
926 funcargs(ls, v, line);
927 break;
929 case '(': case TK_STRING: case '{': { /* funcargs */
930 luaK_exp2nextreg(fs, v);
931 funcargs(ls, v, line);
932 break;
934 default: return;
940 static void simpleexp (LexState *ls, expdesc *v) {
941 /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
942 constructor | FUNCTION body | suffixedexp */
943 switch (ls->t.token) {
944 case TK_NUMBER: {
945 init_exp(v, VKNUM, 0);
946 v->u.nval = ls->t.seminfo.r;
947 break;
949 case TK_STRING: {
950 codestring(ls, v, ls->t.seminfo.ts);
951 break;
953 case TK_NIL: {
954 init_exp(v, VNIL, 0);
955 break;
957 case TK_TRUE: {
958 init_exp(v, VTRUE, 0);
959 break;
961 case TK_FALSE: {
962 init_exp(v, VFALSE, 0);
963 break;
965 case TK_DOTS: { /* vararg */
966 FuncState *fs = ls->fs;
967 check_condition(ls, fs->f->is_vararg,
968 "cannot use " LUA_QL("...") " outside a vararg function");
969 init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
970 break;
972 case '{': { /* constructor */
973 constructor(ls, v);
974 return;
976 case TK_FUNCTION: {
977 luaX_next(ls);
978 body(ls, v, 0, ls->linenumber);
979 return;
981 default: {
982 suffixedexp(ls, v);
983 return;
986 luaX_next(ls);
990 static UnOpr getunopr (int op) {
991 switch (op) {
992 case TK_NOT: return OPR_NOT;
993 case '-': return OPR_MINUS;
994 case '#': return OPR_LEN;
995 default: return OPR_NOUNOPR;
1000 static BinOpr getbinopr (int op) {
1001 switch (op) {
1002 case '+': return OPR_ADD;
1003 case '-': return OPR_SUB;
1004 case '*': return OPR_MUL;
1005 case '/': return OPR_DIV;
1006 case '%': return OPR_MOD;
1007 case '^': return OPR_POW;
1008 case TK_CONCAT: return OPR_CONCAT;
1009 case TK_NE: return OPR_NE;
1010 case TK_EQ: return OPR_EQ;
1011 case '<': return OPR_LT;
1012 case TK_LE: return OPR_LE;
1013 case '>': return OPR_GT;
1014 case TK_GE: return OPR_GE;
1015 case TK_AND: return OPR_AND;
1016 case TK_OR: return OPR_OR;
1017 default: return OPR_NOBINOPR;
1022 static const struct {
1023 lu_byte left; /* left priority for each binary operator */
1024 lu_byte right; /* right priority */
1025 } priority[] = { /* ORDER OPR */
1026 {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `*' `/' `%' */
1027 {10, 9}, {5, 4}, /* ^, .. (right associative) */
1028 {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
1029 {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
1030 {2, 2}, {1, 1} /* and, or */
1033 #define UNARY_PRIORITY 8 /* priority for unary operators */
1037 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1038 ** where `binop' is any binary operator with a priority higher than `limit'
1040 static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
1041 BinOpr op;
1042 UnOpr uop;
1043 enterlevel(ls);
1044 uop = getunopr(ls->t.token);
1045 if (uop != OPR_NOUNOPR) {
1046 int line = ls->linenumber;
1047 luaX_next(ls);
1048 subexpr(ls, v, UNARY_PRIORITY);
1049 luaK_prefix(ls->fs, uop, v, line);
1051 else simpleexp(ls, v);
1052 /* expand while operators have priorities higher than `limit' */
1053 op = getbinopr(ls->t.token);
1054 while (op != OPR_NOBINOPR && priority[op].left > limit) {
1055 expdesc v2;
1056 BinOpr nextop;
1057 int line = ls->linenumber;
1058 luaX_next(ls);
1059 luaK_infix(ls->fs, op, v);
1060 /* read sub-expression with higher priority */
1061 nextop = subexpr(ls, &v2, priority[op].right);
1062 luaK_posfix(ls->fs, op, v, &v2, line);
1063 op = nextop;
1065 leavelevel(ls);
1066 return op; /* return first untreated operator */
1070 static void expr (LexState *ls, expdesc *v) {
1071 subexpr(ls, v, 0);
1074 /* }==================================================================== */
1079 ** {======================================================================
1080 ** Rules for Statements
1081 ** =======================================================================
1085 static void block (LexState *ls) {
1086 /* block -> statlist */
1087 FuncState *fs = ls->fs;
1088 BlockCnt bl;
1089 enterblock(fs, &bl, 0);
1090 statlist(ls);
1091 leaveblock(fs);
1096 ** structure to chain all variables in the left-hand side of an
1097 ** assignment
1099 struct LHS_assign {
1100 struct LHS_assign *prev;
1101 expdesc v; /* variable (global, local, upvalue, or indexed) */
1106 ** check whether, in an assignment to an upvalue/local variable, the
1107 ** upvalue/local variable is begin used in a previous assignment to a
1108 ** table. If so, save original upvalue/local value in a safe place and
1109 ** use this safe copy in the previous assignment.
1111 static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
1112 FuncState *fs = ls->fs;
1113 int extra = fs->freereg; /* eventual position to save local variable */
1114 int conflict = 0;
1115 for (; lh; lh = lh->prev) { /* check all previous assignments */
1116 if (lh->v.k == VINDEXED) { /* assigning to a table? */
1117 /* table is the upvalue/local being assigned now? */
1118 if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {
1119 conflict = 1;
1120 lh->v.u.ind.vt = VLOCAL;
1121 lh->v.u.ind.t = extra; /* previous assignment will use safe copy */
1123 /* index is the local being assigned? (index cannot be upvalue) */
1124 if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {
1125 conflict = 1;
1126 lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
1130 if (conflict) {
1131 /* copy upvalue/local value to a temporary (in position 'extra') */
1132 OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
1133 luaK_codeABC(fs, op, extra, v->u.info, 0);
1134 luaK_reserveregs(fs, 1);
1139 static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
1140 expdesc e;
1141 check_condition(ls, vkisvar(lh->v.k), "syntax error");
1142 if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */
1143 struct LHS_assign nv;
1144 nv.prev = lh;
1145 suffixedexp(ls, &nv.v);
1146 if (nv.v.k != VINDEXED)
1147 check_conflict(ls, lh, &nv.v);
1148 checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,
1149 "C levels");
1150 assignment(ls, &nv, nvars+1);
1152 else { /* assignment -> `=' explist */
1153 int nexps;
1154 checknext(ls, '=');
1155 nexps = explist(ls, &e);
1156 if (nexps != nvars) {
1157 adjust_assign(ls, nvars, nexps, &e);
1158 if (nexps > nvars)
1159 ls->fs->freereg -= nexps - nvars; /* remove extra values */
1161 else {
1162 luaK_setoneret(ls->fs, &e); /* close last expression */
1163 luaK_storevar(ls->fs, &lh->v, &e);
1164 return; /* avoid default */
1167 init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
1168 luaK_storevar(ls->fs, &lh->v, &e);
1172 static int cond (LexState *ls) {
1173 /* cond -> exp */
1174 expdesc v;
1175 expr(ls, &v); /* read condition */
1176 if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
1177 luaK_goiftrue(ls->fs, &v);
1178 return v.f;
1182 static void gotostat (LexState *ls, int pc) {
1183 int line = ls->linenumber;
1184 TString *label;
1185 int g;
1186 if (testnext(ls, TK_GOTO))
1187 label = str_checkname(ls);
1188 else {
1189 luaX_next(ls); /* skip break */
1190 label = luaS_new(ls->L, "break");
1192 g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);
1193 findlabel(ls, g); /* close it if label already defined */
1197 /* check for repeated labels on the same block */
1198 static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
1199 int i;
1200 for (i = fs->bl->firstlabel; i < ll->n; i++) {
1201 if (luaS_eqstr(label, ll->arr[i].name)) {
1202 const char *msg = luaO_pushfstring(fs->ls->L,
1203 "label " LUA_QS " already defined on line %d",
1204 getstr(label), ll->arr[i].line);
1205 semerror(fs->ls, msg);
1211 /* skip no-op statements */
1212 static void skipnoopstat (LexState *ls) {
1213 while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
1214 statement(ls);
1218 static void labelstat (LexState *ls, TString *label, int line) {
1219 /* label -> '::' NAME '::' */
1220 FuncState *fs = ls->fs;
1221 Labellist *ll = &ls->dyd->label;
1222 int l; /* index of new label being created */
1223 checkrepeated(fs, ll, label); /* check for repeated labels */
1224 checknext(ls, TK_DBCOLON); /* skip double colon */
1225 /* create new entry for this label */
1226 l = newlabelentry(ls, ll, label, line, fs->pc);
1227 skipnoopstat(ls); /* skip other no-op statements */
1228 if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */
1229 /* assume that locals are already out of scope */
1230 ll->arr[l].nactvar = fs->bl->nactvar;
1232 findgotos(ls, &ll->arr[l]);
1236 static void whilestat (LexState *ls, int line) {
1237 /* whilestat -> WHILE cond DO block END */
1238 FuncState *fs = ls->fs;
1239 int whileinit;
1240 int condexit;
1241 BlockCnt bl;
1242 luaX_next(ls); /* skip WHILE */
1243 whileinit = luaK_getlabel(fs);
1244 condexit = cond(ls);
1245 enterblock(fs, &bl, 1);
1246 checknext(ls, TK_DO);
1247 block(ls);
1248 luaK_jumpto(fs, whileinit);
1249 check_match(ls, TK_END, TK_WHILE, line);
1250 leaveblock(fs);
1251 luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
1255 static void repeatstat (LexState *ls, int line) {
1256 /* repeatstat -> REPEAT block UNTIL cond */
1257 int condexit;
1258 FuncState *fs = ls->fs;
1259 int repeat_init = luaK_getlabel(fs);
1260 BlockCnt bl1, bl2;
1261 enterblock(fs, &bl1, 1); /* loop block */
1262 enterblock(fs, &bl2, 0); /* scope block */
1263 luaX_next(ls); /* skip REPEAT */
1264 statlist(ls);
1265 check_match(ls, TK_UNTIL, TK_REPEAT, line);
1266 condexit = cond(ls); /* read condition (inside scope block) */
1267 if (bl2.upval) /* upvalues? */
1268 luaK_patchclose(fs, condexit, bl2.nactvar);
1269 leaveblock(fs); /* finish scope */
1270 luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
1271 leaveblock(fs); /* finish loop */
1275 static int exp1 (LexState *ls) {
1276 expdesc e;
1277 int reg;
1278 expr(ls, &e);
1279 luaK_exp2nextreg(ls->fs, &e);
1280 lua_assert(e.k == VNONRELOC);
1281 reg = e.u.info;
1282 return reg;
1286 static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1287 /* forbody -> DO block */
1288 BlockCnt bl;
1289 FuncState *fs = ls->fs;
1290 int prep, endfor;
1291 adjustlocalvars(ls, 3); /* control variables */
1292 checknext(ls, TK_DO);
1293 prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1294 enterblock(fs, &bl, 0); /* scope for declared variables */
1295 adjustlocalvars(ls, nvars);
1296 luaK_reserveregs(fs, nvars);
1297 block(ls);
1298 leaveblock(fs); /* end of scope for declared variables */
1299 luaK_patchtohere(fs, prep);
1300 if (isnum) /* numeric for? */
1301 endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
1302 else { /* generic for */
1303 luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
1304 luaK_fixline(fs, line);
1305 endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
1307 luaK_patchlist(fs, endfor, prep + 1);
1308 luaK_fixline(fs, line);
1312 static void fornum (LexState *ls, TString *varname, int line) {
1313 /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1314 FuncState *fs = ls->fs;
1315 int base = fs->freereg;
1316 new_localvarliteral(ls, "(for index)");
1317 new_localvarliteral(ls, "(for limit)");
1318 new_localvarliteral(ls, "(for step)");
1319 new_localvar(ls, varname);
1320 checknext(ls, '=');
1321 exp1(ls); /* initial value */
1322 checknext(ls, ',');
1323 exp1(ls); /* limit */
1324 if (testnext(ls, ','))
1325 exp1(ls); /* optional step */
1326 else { /* default step = 1 */
1327 luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1));
1328 luaK_reserveregs(fs, 1);
1330 forbody(ls, base, line, 1, 1);
1334 static void forlist (LexState *ls, TString *indexname) {
1335 /* forlist -> NAME {,NAME} IN explist forbody */
1336 FuncState *fs = ls->fs;
1337 expdesc e;
1338 int nvars = 4; /* gen, state, control, plus at least one declared var */
1339 int line;
1340 int base = fs->freereg;
1341 /* create control variables */
1342 new_localvarliteral(ls, "(for generator)");
1343 new_localvarliteral(ls, "(for state)");
1344 new_localvarliteral(ls, "(for control)");
1345 /* create declared variables */
1346 new_localvar(ls, indexname);
1347 while (testnext(ls, ',')) {
1348 new_localvar(ls, str_checkname(ls));
1349 nvars++;
1351 checknext(ls, TK_IN);
1352 line = ls->linenumber;
1353 adjust_assign(ls, 3, explist(ls, &e), &e);
1354 luaK_checkstack(fs, 3); /* extra space to call generator */
1355 forbody(ls, base, line, nvars - 3, 0);
1359 static void forstat (LexState *ls, int line) {
1360 /* forstat -> FOR (fornum | forlist) END */
1361 FuncState *fs = ls->fs;
1362 TString *varname;
1363 BlockCnt bl;
1364 enterblock(fs, &bl, 1); /* scope for loop and control variables */
1365 luaX_next(ls); /* skip `for' */
1366 varname = str_checkname(ls); /* first variable name */
1367 switch (ls->t.token) {
1368 case '=': fornum(ls, varname, line); break;
1369 case ',': case TK_IN: forlist(ls, varname); break;
1370 default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
1372 check_match(ls, TK_END, TK_FOR, line);
1373 leaveblock(fs); /* loop scope (`break' jumps to this point) */
1377 __attribute__((always_inline)) inline
1378 static void test_then_block (LexState *ls, int *escapelist) {
1379 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1380 BlockCnt bl;
1381 FuncState *fs = ls->fs;
1382 expdesc v;
1383 int jf; /* instruction to skip 'then' code (if condition is false) */
1384 luaX_next(ls); /* skip IF or ELSEIF */
1385 expr(ls, &v); /* read condition */
1386 checknext(ls, TK_THEN);
1387 if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
1388 luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */
1389 enterblock(fs, &bl, 0); /* must enter block before 'goto' */
1390 gotostat(ls, v.t); /* handle goto/break */
1391 skipnoopstat(ls); /* skip other no-op statements */
1392 if (block_follow(ls, 0)) { /* 'goto' is the entire block? */
1393 leaveblock(fs);
1394 return; /* and that is it */
1396 else /* must skip over 'then' part if condition is false */
1397 jf = luaK_jump(fs);
1399 else { /* regular case (not goto/break) */
1400 luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */
1401 enterblock(fs, &bl, 0);
1402 jf = v.f;
1404 statlist(ls); /* `then' part */
1405 leaveblock(fs);
1406 if (ls->t.token == TK_ELSE ||
1407 ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
1408 luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
1409 luaK_patchtohere(fs, jf);
1413 static void ifstat (LexState *ls, int line) {
1414 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1415 FuncState *fs = ls->fs;
1416 int escapelist = NO_JUMP; /* exit list for finished parts */
1417 test_then_block(ls, &escapelist); /* IF cond THEN block */
1418 while (ls->t.token == TK_ELSEIF)
1419 test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
1420 if (testnext(ls, TK_ELSE))
1421 block(ls); /* `else' part */
1422 check_match(ls, TK_END, TK_IF, line);
1423 luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
1427 static void localfunc (LexState *ls) {
1428 expdesc b;
1429 FuncState *fs = ls->fs;
1430 new_localvar(ls, str_checkname(ls)); /* new local variable */
1431 adjustlocalvars(ls, 1); /* enter its scope */
1432 body(ls, &b, 0, ls->linenumber); /* function created in next register */
1433 /* debug information will only see the variable after this point! */
1434 getlocvar(fs, b.u.info)->startpc = fs->pc;
1438 static void localstat (LexState *ls) {
1439 /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
1440 int nvars = 0;
1441 int nexps;
1442 expdesc e;
1443 do {
1444 new_localvar(ls, str_checkname(ls));
1445 nvars++;
1446 } while (testnext(ls, ','));
1447 if (testnext(ls, '='))
1448 nexps = explist(ls, &e);
1449 else {
1450 e.k = VVOID;
1451 nexps = 0;
1453 adjust_assign(ls, nvars, nexps, &e);
1454 adjustlocalvars(ls, nvars);
1458 static int funcname (LexState *ls, expdesc *v) {
1459 /* funcname -> NAME {fieldsel} [`:' NAME] */
1460 int ismethod = 0;
1461 singlevar(ls, v);
1462 while (ls->t.token == '.')
1463 fieldsel(ls, v);
1464 if (ls->t.token == ':') {
1465 ismethod = 1;
1466 fieldsel(ls, v);
1468 return ismethod;
1472 static void funcstat (LexState *ls, int line) {
1473 /* funcstat -> FUNCTION funcname body */
1474 int ismethod;
1475 expdesc v, b;
1476 luaX_next(ls); /* skip FUNCTION */
1477 ismethod = funcname(ls, &v);
1478 body(ls, &b, ismethod, line);
1479 luaK_storevar(ls->fs, &v, &b);
1480 luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
1484 static void exprstat (LexState *ls) {
1485 /* stat -> func | assignment */
1486 FuncState *fs = ls->fs;
1487 struct LHS_assign v;
1488 suffixedexp(ls, &v.v);
1489 if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
1490 v.prev = NULL;
1491 assignment(ls, &v, 1);
1493 else { /* stat -> func */
1494 check_condition(ls, v.v.k == VCALL, "syntax error");
1495 SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
1500 static void retstat (LexState *ls) {
1501 /* stat -> RETURN [explist] [';'] */
1502 FuncState *fs = ls->fs;
1503 expdesc e;
1504 int first, nret; /* registers with returned values */
1505 if (block_follow(ls, 1) || ls->t.token == ';')
1506 first = nret = 0; /* return no values */
1507 else {
1508 nret = explist(ls, &e); /* optional return values */
1509 if (hasmultret(e.k)) {
1510 luaK_setmultret(fs, &e);
1511 if (e.k == VCALL && nret == 1) { /* tail call? */
1512 SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1513 lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1515 first = fs->nactvar;
1516 nret = LUA_MULTRET; /* return all values */
1518 else {
1519 if (nret == 1) /* only one single value? */
1520 first = luaK_exp2anyreg(fs, &e);
1521 else {
1522 luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
1523 first = fs->nactvar; /* return all `active' values */
1524 lua_assert(nret == fs->freereg - first);
1528 luaK_ret(fs, first, nret);
1529 (void) testnext(ls, ';'); /* skip optional semicolon */
1533 static void statement (LexState *ls) {
1534 int line = ls->linenumber; /* may be needed for error messages */
1535 enterlevel(ls);
1536 switch (ls->t.token) {
1537 case ';': { /* stat -> ';' (empty statement) */
1538 luaX_next(ls); /* skip ';' */
1539 break;
1541 case TK_IF: { /* stat -> ifstat */
1542 ifstat(ls, line);
1543 break;
1545 case TK_WHILE: { /* stat -> whilestat */
1546 whilestat(ls, line);
1547 break;
1549 case TK_DO: { /* stat -> DO block END */
1550 luaX_next(ls); /* skip DO */
1551 block(ls);
1552 check_match(ls, TK_END, TK_DO, line);
1553 break;
1555 case TK_FOR: { /* stat -> forstat */
1556 forstat(ls, line);
1557 break;
1559 case TK_REPEAT: { /* stat -> repeatstat */
1560 repeatstat(ls, line);
1561 break;
1563 case TK_FUNCTION: { /* stat -> funcstat */
1564 funcstat(ls, line);
1565 break;
1567 case TK_LOCAL: { /* stat -> localstat */
1568 luaX_next(ls); /* skip LOCAL */
1569 if (testnext(ls, TK_FUNCTION)) /* local function? */
1570 localfunc(ls);
1571 else
1572 localstat(ls);
1573 break;
1575 case TK_DBCOLON: { /* stat -> label */
1576 luaX_next(ls); /* skip double colon */
1577 labelstat(ls, str_checkname(ls), line);
1578 break;
1580 case TK_RETURN: { /* stat -> retstat */
1581 luaX_next(ls); /* skip RETURN */
1582 retstat(ls);
1583 break;
1585 case TK_BREAK: /* stat -> breakstat */
1586 case TK_GOTO: { /* stat -> 'goto' NAME */
1587 gotostat(ls, luaK_jump(ls->fs));
1588 break;
1590 default: { /* stat -> func | assignment */
1591 exprstat(ls);
1592 break;
1595 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1596 ls->fs->freereg >= ls->fs->nactvar);
1597 ls->fs->freereg = ls->fs->nactvar; /* free registers */
1598 leavelevel(ls);
1601 /* }====================================================================== */
1605 ** compiles the main function, which is a regular vararg function with an
1606 ** upvalue named LUA_ENV
1608 static void mainfunc (LexState *ls, FuncState *fs) {
1609 BlockCnt bl;
1610 expdesc v;
1611 open_func(ls, fs, &bl);
1612 fs->f->is_vararg = 1; /* main function is always vararg */
1613 init_exp(&v, VLOCAL, 0); /* create and... */
1614 newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */
1615 luaX_next(ls); /* read first token */
1616 statlist(ls); /* parse main body */
1617 check(ls, TK_EOS);
1618 close_func(ls);
1622 Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1623 Dyndata *dyd, const char *name, int firstchar) {
1624 LexState lexstate;
1625 FuncState funcstate;
1626 Closure *cl = luaF_newLclosure(L, 1); /* create main closure */
1627 /* anchor closure (to avoid being collected) */
1628 setclLvalue(L, L->top, cl);
1629 incr_top(L);
1630 funcstate.f = cl->l.p = luaF_newproto(L);
1631 funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
1632 lexstate.buff = buff;
1633 lexstate.dyd = dyd;
1634 dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
1635 luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
1636 mainfunc(&lexstate, &funcstate);
1637 lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
1638 /* all scopes should be correctly finished */
1639 lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
1640 return cl; /* it's on the stack too */