xref: /netbsd-src/external/mit/lua/dist/src/lparser.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: lparser.c,v 1.11 2018/08/04 17:30:01 alnsn Exp $	*/
2 
3 /*
4 ** Id: lparser.c,v 2.155.1.2 2017/04/29 18:11:40 roberto Exp
5 ** Lua Parser
6 ** See Copyright Notice in lua.h
7 */
8 
9 #define lparser_c
10 #define LUA_CORE
11 
12 #include "lprefix.h"
13 
14 
15 #ifndef _KERNEL
16 #include <string.h>
17 #endif /* _KERNEL */
18 
19 #include "lua.h"
20 
21 #include "lcode.h"
22 #include "ldebug.h"
23 #include "ldo.h"
24 #include "lfunc.h"
25 #include "llex.h"
26 #include "lmem.h"
27 #include "lobject.h"
28 #include "lopcodes.h"
29 #include "lparser.h"
30 #include "lstate.h"
31 #include "lstring.h"
32 #include "ltable.h"
33 
34 
35 
36 /* maximum number of local variables per function (must be smaller
37    than 250, due to the bytecode format) */
38 #define MAXVARS		200
39 
40 
41 #define hasmultret(k)		((k) == VCALL || (k) == VVARARG)
42 
43 
44 /* because all strings are unified by the scanner, the parser
45    can use pointer equality for string equality */
46 #define eqstr(a,b)	((a) == (b))
47 
48 
49 /*
50 ** nodes for block list (list of active blocks)
51 */
52 typedef struct BlockCnt {
53   struct BlockCnt *previous;  /* chain */
54   int firstlabel;  /* index of first label in this block */
55   int firstgoto;  /* index of first pending goto in this block */
56   lu_byte nactvar;  /* # active locals outside the block */
57   lu_byte upval;  /* true if some variable in the block is an upvalue */
58   lu_byte isloop;  /* true if 'block' is a loop */
59 } BlockCnt;
60 
61 
62 
63 /*
64 ** prototypes for recursive non-terminal functions
65 */
66 static void statement (LexState *ls);
67 static void expr (LexState *ls, expdesc *v);
68 
69 
70 /* semantic error */
71 static l_noret semerror (LexState *ls, const char *msg) {
72   ls->t.token = 0;  /* remove "near <token>" from final message */
73   luaX_syntaxerror(ls, msg);
74 }
75 
76 
77 static l_noret error_expected (LexState *ls, int token) {
78   luaX_syntaxerror(ls,
79       luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
80 }
81 
82 
83 static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
84   lua_State *L = fs->ls->L;
85   const char *msg;
86   int line = fs->f->linedefined;
87   const char *where = (line == 0)
88                       ? "main function"
89                       : luaO_pushfstring(L, "function at line %d", line);
90   msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
91                              what, limit, where);
92   luaX_syntaxerror(fs->ls, msg);
93 }
94 
95 
96 static void checklimit (FuncState *fs, int v, int l, const char *what) {
97   if (v > l) errorlimit(fs, l, what);
98 }
99 
100 
101 static int testnext (LexState *ls, int c) {
102   if (ls->t.token == c) {
103     luaX_next(ls);
104     return 1;
105   }
106   else return 0;
107 }
108 
109 
110 static void check (LexState *ls, int c) {
111   if (ls->t.token != c)
112     error_expected(ls, c);
113 }
114 
115 
116 static void checknext (LexState *ls, int c) {
117   check(ls, c);
118   luaX_next(ls);
119 }
120 
121 
122 #define check_condition(ls,c,msg)	{ if (!(c)) luaX_syntaxerror(ls, msg); }
123 
124 
125 
126 static void check_match (LexState *ls, int what, int who, int where) {
127   if (!testnext(ls, what)) {
128     if (where == ls->linenumber)
129       error_expected(ls, what);
130     else {
131       luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
132              "%s expected (to close %s at line %d)",
133               luaX_token2str(ls, what), luaX_token2str(ls, who), where));
134     }
135   }
136 }
137 
138 
139 static TString *str_checkname (LexState *ls) {
140   TString *ts;
141   check(ls, TK_NAME);
142   ts = ls->t.seminfo.ts;
143   luaX_next(ls);
144   return ts;
145 }
146 
147 
148 static void init_exp (expdesc *e, expkind k, int i) {
149   e->f = e->t = NO_JUMP;
150   e->k = k;
151   e->u.info = i;
152 }
153 
154 
155 static void codestring (LexState *ls, expdesc *e, TString *s) {
156   init_exp(e, VK, luaK_stringK(ls->fs, s));
157 }
158 
159 
160 static void checkname (LexState *ls, expdesc *e) {
161   codestring(ls, e, str_checkname(ls));
162 }
163 
164 
165 static int registerlocalvar (LexState *ls, TString *varname) {
166   FuncState *fs = ls->fs;
167   Proto *f = fs->f;
168   int oldsize = f->sizelocvars;
169   luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
170                   LocVar, SHRT_MAX, "local variables");
171   while (oldsize < f->sizelocvars)
172     f->locvars[oldsize++].varname = NULL;
173   f->locvars[fs->nlocvars].varname = varname;
174   luaC_objbarrier(ls->L, f, varname);
175   return fs->nlocvars++;
176 }
177 
178 
179 static void new_localvar (LexState *ls, TString *name) {
180   FuncState *fs = ls->fs;
181   Dyndata *dyd = ls->dyd;
182   int reg = registerlocalvar(ls, name);
183   checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
184                   MAXVARS, "local variables");
185   luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,
186                   dyd->actvar.size, Vardesc, MAX_INT, "local variables");
187   dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg);
188 }
189 
190 
191 static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) {
192   new_localvar(ls, luaX_newstring(ls, name, sz));
193 }
194 
195 #define new_localvarliteral(ls,v) \
196 	new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1)
197 
198 
199 static LocVar *getlocvar (FuncState *fs, int i) {
200   int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
201   lua_assert(idx < fs->nlocvars);
202   return &fs->f->locvars[idx];
203 }
204 
205 
206 static void adjustlocalvars (LexState *ls, int nvars) {
207   FuncState *fs = ls->fs;
208   fs->nactvar = cast_byte(fs->nactvar + nvars);
209   for (; nvars; nvars--) {
210     getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;
211   }
212 }
213 
214 
215 static void removevars (FuncState *fs, int tolevel) {
216   fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
217   while (fs->nactvar > tolevel)
218     getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
219 }
220 
221 
222 static int searchupvalue (FuncState *fs, TString *name) {
223   int i;
224   Upvaldesc *up = fs->f->upvalues;
225   for (i = 0; i < fs->nups; i++) {
226     if (eqstr(up[i].name, name)) return i;
227   }
228   return -1;  /* not found */
229 }
230 
231 
232 static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
233   Proto *f = fs->f;
234   int oldsize = f->sizeupvalues;
235   checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
236   luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
237                   Upvaldesc, MAXUPVAL, "upvalues");
238   while (oldsize < f->sizeupvalues)
239     f->upvalues[oldsize++].name = NULL;
240   f->upvalues[fs->nups].instack = (v->k == VLOCAL);
241   f->upvalues[fs->nups].idx = cast_byte(v->u.info);
242   f->upvalues[fs->nups].name = name;
243   luaC_objbarrier(fs->ls->L, f, name);
244   return fs->nups++;
245 }
246 
247 
248 static int searchvar (FuncState *fs, TString *n) {
249   int i;
250   for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
251     if (eqstr(n, getlocvar(fs, i)->varname))
252       return i;
253   }
254   return -1;  /* not found */
255 }
256 
257 
258 /*
259   Mark block where variable at given level was defined
260   (to emit close instructions later).
261 */
262 static void markupval (FuncState *fs, int level) {
263   BlockCnt *bl = fs->bl;
264   while (bl->nactvar > level)
265     bl = bl->previous;
266   bl->upval = 1;
267 }
268 
269 
270 /*
271   Find variable with given name 'n'. If it is an upvalue, add this
272   upvalue into all intermediate functions.
273 */
274 static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
275   if (fs == NULL)  /* no more levels? */
276     init_exp(var, VVOID, 0);  /* default is global */
277   else {
278     int v = searchvar(fs, n);  /* look up locals at current level */
279     if (v >= 0) {  /* found? */
280       init_exp(var, VLOCAL, v);  /* variable is local */
281       if (!base)
282         markupval(fs, v);  /* local will be used as an upval */
283     }
284     else {  /* not found as local at current level; try upvalues */
285       int idx = searchupvalue(fs, n);  /* try existing upvalues */
286       if (idx < 0) {  /* not found? */
287         singlevaraux(fs->prev, n, var, 0);  /* try upper levels */
288         if (var->k == VVOID)  /* not found? */
289           return;  /* it is a global */
290         /* else was LOCAL or UPVAL */
291         idx  = newupvalue(fs, n, var);  /* will be a new upvalue */
292       }
293       init_exp(var, VUPVAL, idx);  /* new or old upvalue */
294     }
295   }
296 }
297 
298 
299 static void singlevar (LexState *ls, expdesc *var) {
300   TString *varname = str_checkname(ls);
301   FuncState *fs = ls->fs;
302   singlevaraux(fs, varname, var, 1);
303   if (var->k == VVOID) {  /* global name? */
304     expdesc key;
305     singlevaraux(fs, ls->envn, var, 1);  /* get environment variable */
306     lua_assert(var->k != VVOID);  /* this one must exist */
307     codestring(ls, &key, varname);  /* key is variable name */
308     luaK_indexed(fs, var, &key);  /* env[varname] */
309   }
310 }
311 
312 
313 static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
314   FuncState *fs = ls->fs;
315   int extra = nvars - nexps;
316   if (hasmultret(e->k)) {
317     extra++;  /* includes call itself */
318     if (extra < 0) extra = 0;
319     luaK_setreturns(fs, e, extra);  /* last exp. provides the difference */
320     if (extra > 1) luaK_reserveregs(fs, extra-1);
321   }
322   else {
323     if (e->k != VVOID) luaK_exp2nextreg(fs, e);  /* close last expression */
324     if (extra > 0) {
325       int reg = fs->freereg;
326       luaK_reserveregs(fs, extra);
327       luaK_nil(fs, reg, extra);
328     }
329   }
330   if (nexps > nvars)
331     ls->fs->freereg -= nexps - nvars;  /* remove extra values */
332 }
333 
334 
335 static void enterlevel (LexState *ls) {
336   lua_State *L = ls->L;
337   ++L->nCcalls;
338   checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels");
339 }
340 
341 
342 #define leavelevel(ls)	((ls)->L->nCcalls--)
343 
344 
345 static void closegoto (LexState *ls, int g, Labeldesc *label) {
346   int i;
347   FuncState *fs = ls->fs;
348   Labellist *gl = &ls->dyd->gt;
349   Labeldesc *gt = &gl->arr[g];
350   lua_assert(eqstr(gt->name, label->name));
351   if (gt->nactvar < label->nactvar) {
352     TString *vname = getlocvar(fs, gt->nactvar)->varname;
353     const char *msg = luaO_pushfstring(ls->L,
354       "<goto %s> at line %d jumps into the scope of local '%s'",
355       getstr(gt->name), gt->line, getstr(vname));
356     semerror(ls, msg);
357   }
358   luaK_patchlist(fs, gt->pc, label->pc);
359   /* remove goto from pending list */
360   for (i = g; i < gl->n - 1; i++)
361     gl->arr[i] = gl->arr[i + 1];
362   gl->n--;
363 }
364 
365 
366 /*
367 ** try to close a goto with existing labels; this solves backward jumps
368 */
369 static int findlabel (LexState *ls, int g) {
370   int i;
371   BlockCnt *bl = ls->fs->bl;
372   Dyndata *dyd = ls->dyd;
373   Labeldesc *gt = &dyd->gt.arr[g];
374   /* check labels in current block for a match */
375   for (i = bl->firstlabel; i < dyd->label.n; i++) {
376     Labeldesc *lb = &dyd->label.arr[i];
377     if (eqstr(lb->name, gt->name)) {  /* correct label? */
378       if (gt->nactvar > lb->nactvar &&
379           (bl->upval || dyd->label.n > bl->firstlabel))
380         luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
381       closegoto(ls, g, lb);  /* close it */
382       return 1;
383     }
384   }
385   return 0;  /* label not found; cannot close goto */
386 }
387 
388 
389 static int newlabelentry (LexState *ls, Labellist *l, TString *name,
390                           int line, int pc) {
391   int n = l->n;
392   luaM_growvector(ls->L, l->arr, n, l->size,
393                   Labeldesc, SHRT_MAX, "labels/gotos");
394   l->arr[n].name = name;
395   l->arr[n].line = line;
396   l->arr[n].nactvar = ls->fs->nactvar;
397   l->arr[n].pc = pc;
398   l->n = n + 1;
399   return n;
400 }
401 
402 
403 /*
404 ** check whether new label 'lb' matches any pending gotos in current
405 ** block; solves forward jumps
406 */
407 static void findgotos (LexState *ls, Labeldesc *lb) {
408   Labellist *gl = &ls->dyd->gt;
409   int i = ls->fs->bl->firstgoto;
410   while (i < gl->n) {
411     if (eqstr(gl->arr[i].name, lb->name))
412       closegoto(ls, i, lb);
413     else
414       i++;
415   }
416 }
417 
418 
419 /*
420 ** export pending gotos to outer level, to check them against
421 ** outer labels; if the block being exited has upvalues, and
422 ** the goto exits the scope of any variable (which can be the
423 ** upvalue), close those variables being exited.
424 */
425 static void movegotosout (FuncState *fs, BlockCnt *bl) {
426   int i = bl->firstgoto;
427   Labellist *gl = &fs->ls->dyd->gt;
428   /* correct pending gotos to current block and try to close it
429      with visible labels */
430   while (i < gl->n) {
431     Labeldesc *gt = &gl->arr[i];
432     if (gt->nactvar > bl->nactvar) {
433       if (bl->upval)
434         luaK_patchclose(fs, gt->pc, bl->nactvar);
435       gt->nactvar = bl->nactvar;
436     }
437     if (!findlabel(fs->ls, i))
438       i++;  /* move to next one */
439   }
440 }
441 
442 
443 static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
444   bl->isloop = isloop;
445   bl->nactvar = fs->nactvar;
446   bl->firstlabel = fs->ls->dyd->label.n;
447   bl->firstgoto = fs->ls->dyd->gt.n;
448   bl->upval = 0;
449   bl->previous = fs->bl;
450   fs->bl = bl;
451   lua_assert(fs->freereg == fs->nactvar);
452 }
453 
454 
455 /*
456 ** create a label named 'break' to resolve break statements
457 */
458 static void breaklabel (LexState *ls) {
459   TString *n = luaS_new(ls->L, "break");
460   int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);
461   findgotos(ls, &ls->dyd->label.arr[l]);
462 }
463 
464 /*
465 ** generates an error for an undefined 'goto'; choose appropriate
466 ** message when label name is a reserved word (which can only be 'break')
467 */
468 static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
469   const char *msg = isreserved(gt->name)
470                     ? "<%s> at line %d not inside a loop"
471                     : "no visible label '%s' for <goto> at line %d";
472   msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
473   semerror(ls, msg);
474 }
475 
476 
477 static void leaveblock (FuncState *fs) {
478   BlockCnt *bl = fs->bl;
479   LexState *ls = fs->ls;
480   if (bl->previous && bl->upval) {
481     /* create a 'jump to here' to close upvalues */
482     int j = luaK_jump(fs);
483     luaK_patchclose(fs, j, bl->nactvar);
484     luaK_patchtohere(fs, j);
485   }
486   if (bl->isloop)
487     breaklabel(ls);  /* close pending breaks */
488   fs->bl = bl->previous;
489   removevars(fs, bl->nactvar);
490   lua_assert(bl->nactvar == fs->nactvar);
491   fs->freereg = fs->nactvar;  /* free registers */
492   ls->dyd->label.n = bl->firstlabel;  /* remove local labels */
493   if (bl->previous)  /* inner block? */
494     movegotosout(fs, bl);  /* update pending gotos to outer block */
495   else if (bl->firstgoto < ls->dyd->gt.n)  /* pending gotos in outer block? */
496     undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]);  /* error */
497 }
498 
499 
500 /*
501 ** adds a new prototype into list of prototypes
502 */
503 static Proto *addprototype (LexState *ls) {
504   Proto *clp;
505   lua_State *L = ls->L;
506   FuncState *fs = ls->fs;
507   Proto *f = fs->f;  /* prototype of current function */
508   if (fs->np >= f->sizep) {
509     int oldsize = f->sizep;
510     luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
511     while (oldsize < f->sizep)
512       f->p[oldsize++] = NULL;
513   }
514   f->p[fs->np++] = clp = luaF_newproto(L);
515   luaC_objbarrier(L, f, clp);
516   return clp;
517 }
518 
519 
520 /*
521 ** codes instruction to create new closure in parent function.
522 ** The OP_CLOSURE instruction must use the last available register,
523 ** so that, if it invokes the GC, the GC knows which registers
524 ** are in use at that time.
525 */
526 static void codeclosure (LexState *ls, expdesc *v) {
527   FuncState *fs = ls->fs->prev;
528   init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
529   luaK_exp2nextreg(fs, v);  /* fix it at the last register */
530 }
531 
532 
533 static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
534   Proto *f;
535   fs->prev = ls->fs;  /* linked list of funcstates */
536   fs->ls = ls;
537   ls->fs = fs;
538   fs->pc = 0;
539   fs->lasttarget = 0;
540   fs->jpc = NO_JUMP;
541   fs->freereg = 0;
542   fs->nk = 0;
543   fs->np = 0;
544   fs->nups = 0;
545   fs->nlocvars = 0;
546   fs->nactvar = 0;
547   fs->firstlocal = ls->dyd->actvar.n;
548   fs->bl = NULL;
549   f = fs->f;
550   f->source = ls->source;
551   f->maxstacksize = 2;  /* registers 0/1 are always valid */
552   enterblock(fs, bl, 0);
553 }
554 
555 
556 static void close_func (LexState *ls) {
557   lua_State *L = ls->L;
558   FuncState *fs = ls->fs;
559   Proto *f = fs->f;
560   luaK_ret(fs, 0, 0);  /* final return */
561   leaveblock(fs);
562   luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
563   f->sizecode = fs->pc;
564   luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
565   f->sizelineinfo = fs->pc;
566   luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
567   f->sizek = fs->nk;
568   luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
569   f->sizep = fs->np;
570   luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
571   f->sizelocvars = fs->nlocvars;
572   luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
573   f->sizeupvalues = fs->nups;
574   lua_assert(fs->bl == NULL);
575   ls->fs = fs->prev;
576   luaC_checkGC(L);
577 }
578 
579 
580 
581 /*============================================================*/
582 /* GRAMMAR RULES */
583 /*============================================================*/
584 
585 
586 /*
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 is handled in separate.
590 */
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:
595       return 1;
596     case TK_UNTIL: return withuntil;
597     default: return 0;
598   }
599 }
600 
601 
602 static void statlist (LexState *ls) {
603   /* statlist -> { stat [';'] } */
604   while (!block_follow(ls, 1)) {
605     if (ls->t.token == TK_RETURN) {
606       statement(ls);
607       return;  /* 'return' must be last statement */
608     }
609     statement(ls);
610   }
611 }
612 
613 
614 static void fieldsel (LexState *ls, expdesc *v) {
615   /* fieldsel -> ['.' | ':'] NAME */
616   FuncState *fs = ls->fs;
617   expdesc key;
618   luaK_exp2anyregup(fs, v);
619   luaX_next(ls);  /* skip the dot or colon */
620   checkname(ls, &key);
621   luaK_indexed(fs, v, &key);
622 }
623 
624 
625 static void yindex (LexState *ls, expdesc *v) {
626   /* index -> '[' expr ']' */
627   luaX_next(ls);  /* skip the '[' */
628   expr(ls, v);
629   luaK_exp2val(ls->fs, v);
630   checknext(ls, ']');
631 }
632 
633 
634 /*
635 ** {======================================================================
636 ** Rules for Constructors
637 ** =======================================================================
638 */
639 
640 
641 struct ConsControl {
642   expdesc v;  /* last list item read */
643   expdesc *t;  /* table descriptor */
644   int nh;  /* total number of 'record' elements */
645   int na;  /* total number of array elements */
646   int tostore;  /* number of array elements pending to be stored */
647 };
648 
649 
650 static void recfield (LexState *ls, struct ConsControl *cc) {
651   /* recfield -> (NAME | '['exp1']') = exp1 */
652   FuncState *fs = ls->fs;
653   int reg = ls->fs->freereg;
654   expdesc key, val;
655   int rkkey;
656   if (ls->t.token == TK_NAME) {
657     checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
658     checkname(ls, &key);
659   }
660   else  /* ls->t.token == '[' */
661     yindex(ls, &key);
662   cc->nh++;
663   checknext(ls, '=');
664   rkkey = luaK_exp2RK(fs, &key);
665   expr(ls, &val);
666   luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val));
667   fs->freereg = reg;  /* free registers */
668 }
669 
670 
671 static void closelistfield (FuncState *fs, struct ConsControl *cc) {
672   if (cc->v.k == VVOID) return;  /* there is no list item */
673   luaK_exp2nextreg(fs, &cc->v);
674   cc->v.k = VVOID;
675   if (cc->tostore == LFIELDS_PER_FLUSH) {
676     luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);  /* flush */
677     cc->tostore = 0;  /* no more items pending */
678   }
679 }
680 
681 
682 static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
683   if (cc->tostore == 0) return;
684   if (hasmultret(cc->v.k)) {
685     luaK_setmultret(fs, &cc->v);
686     luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
687     cc->na--;  /* do not count last expression (unknown number of elements) */
688   }
689   else {
690     if (cc->v.k != VVOID)
691       luaK_exp2nextreg(fs, &cc->v);
692     luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
693   }
694 }
695 
696 
697 static void listfield (LexState *ls, struct ConsControl *cc) {
698   /* listfield -> exp */
699   expr(ls, &cc->v);
700   checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
701   cc->na++;
702   cc->tostore++;
703 }
704 
705 
706 static void field (LexState *ls, struct ConsControl *cc) {
707   /* field -> listfield | recfield */
708   switch(ls->t.token) {
709     case TK_NAME: {  /* may be 'listfield' or 'recfield' */
710       if (luaX_lookahead(ls) != '=')  /* expression? */
711         listfield(ls, cc);
712       else
713         recfield(ls, cc);
714       break;
715     }
716     case '[': {
717       recfield(ls, cc);
718       break;
719     }
720     default: {
721       listfield(ls, cc);
722       break;
723     }
724   }
725 }
726 
727 
728 static void constructor (LexState *ls, expdesc *t) {
729   /* constructor -> '{' [ field { sep field } [sep] ] '}'
730      sep -> ',' | ';' */
731   FuncState *fs = ls->fs;
732   int line = ls->linenumber;
733   int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
734   struct ConsControl cc;
735   cc.na = cc.nh = cc.tostore = 0;
736   cc.t = t;
737   init_exp(t, VRELOCABLE, pc);
738   init_exp(&cc.v, VVOID, 0);  /* no value (yet) */
739   luaK_exp2nextreg(ls->fs, t);  /* fix it at stack top */
740   checknext(ls, '{');
741   do {
742     lua_assert(cc.v.k == VVOID || cc.tostore > 0);
743     if (ls->t.token == '}') break;
744     closelistfield(fs, &cc);
745     field(ls, &cc);
746   } while (testnext(ls, ',') || testnext(ls, ';'));
747   check_match(ls, '}', '{', line);
748   lastlistfield(fs, &cc);
749   SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
750   SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh));  /* set initial table size */
751 }
752 
753 /* }====================================================================== */
754 
755 
756 
757 static void parlist (LexState *ls) {
758   /* parlist -> [ param { ',' param } ] */
759   FuncState *fs = ls->fs;
760   Proto *f = fs->f;
761   int nparams = 0;
762   f->is_vararg = 0;
763   if (ls->t.token != ')') {  /* is 'parlist' not empty? */
764     do {
765       switch (ls->t.token) {
766         case TK_NAME: {  /* param -> NAME */
767           new_localvar(ls, str_checkname(ls));
768           nparams++;
769           break;
770         }
771         case TK_DOTS: {  /* param -> '...' */
772           luaX_next(ls);
773           f->is_vararg = 1;  /* declared vararg */
774           break;
775         }
776         default: luaX_syntaxerror(ls, "<name> or '...' expected");
777       }
778     } while (!f->is_vararg && testnext(ls, ','));
779   }
780   adjustlocalvars(ls, nparams);
781   f->numparams = cast_byte(fs->nactvar);
782   luaK_reserveregs(fs, fs->nactvar);  /* reserve register for parameters */
783 }
784 
785 
786 static void body (LexState *ls, expdesc *e, int ismethod, int line) {
787   /* body ->  '(' parlist ')' block END */
788   FuncState new_fs;
789   BlockCnt bl;
790   new_fs.f = addprototype(ls);
791   new_fs.f->linedefined = line;
792   open_func(ls, &new_fs, &bl);
793   checknext(ls, '(');
794   if (ismethod) {
795     new_localvarliteral(ls, "self");  /* create 'self' parameter */
796     adjustlocalvars(ls, 1);
797   }
798   parlist(ls);
799   checknext(ls, ')');
800   statlist(ls);
801   new_fs.f->lastlinedefined = ls->linenumber;
802   check_match(ls, TK_END, TK_FUNCTION, line);
803   codeclosure(ls, e);
804   close_func(ls);
805 }
806 
807 
808 static int explist (LexState *ls, expdesc *v) {
809   /* explist -> expr { ',' expr } */
810   int n = 1;  /* at least one expression */
811   expr(ls, v);
812   while (testnext(ls, ',')) {
813     luaK_exp2nextreg(ls->fs, v);
814     expr(ls, v);
815     n++;
816   }
817   return n;
818 }
819 
820 
821 static void funcargs (LexState *ls, expdesc *f, int line) {
822   FuncState *fs = ls->fs;
823   expdesc args;
824   int base, nparams;
825   switch (ls->t.token) {
826     case '(': {  /* funcargs -> '(' [ explist ] ')' */
827       luaX_next(ls);
828       if (ls->t.token == ')')  /* arg list is empty? */
829         args.k = VVOID;
830       else {
831         explist(ls, &args);
832         luaK_setmultret(fs, &args);
833       }
834       check_match(ls, ')', '(', line);
835       break;
836     }
837     case '{': {  /* funcargs -> constructor */
838       constructor(ls, &args);
839       break;
840     }
841     case TK_STRING: {  /* funcargs -> STRING */
842       codestring(ls, &args, ls->t.seminfo.ts);
843       luaX_next(ls);  /* must use 'seminfo' before 'next' */
844       break;
845     }
846     default: {
847       luaX_syntaxerror(ls, "function arguments expected");
848     }
849   }
850   lua_assert(f->k == VNONRELOC);
851   base = f->u.info;  /* base register for call */
852   if (hasmultret(args.k))
853     nparams = LUA_MULTRET;  /* open call */
854   else {
855     if (args.k != VVOID)
856       luaK_exp2nextreg(fs, &args);  /* close last argument */
857     nparams = fs->freereg - (base+1);
858   }
859   init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
860   luaK_fixline(fs, line);
861   fs->freereg = base+1;  /* call remove function and arguments and leaves
862                             (unless changed) one result */
863 }
864 
865 
866 
867 
868 /*
869 ** {======================================================================
870 ** Expression parsing
871 ** =======================================================================
872 */
873 
874 
875 static void primaryexp (LexState *ls, expdesc *v) {
876   /* primaryexp -> NAME | '(' expr ')' */
877   switch (ls->t.token) {
878     case '(': {
879       int line = ls->linenumber;
880       luaX_next(ls);
881       expr(ls, v);
882       check_match(ls, ')', '(', line);
883       luaK_dischargevars(ls->fs, v);
884       return;
885     }
886     case TK_NAME: {
887       singlevar(ls, v);
888       return;
889     }
890     default: {
891       luaX_syntaxerror(ls, "unexpected symbol");
892     }
893   }
894 }
895 
896 
897 static void suffixedexp (LexState *ls, expdesc *v) {
898   /* suffixedexp ->
899        primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
900   FuncState *fs = ls->fs;
901   int line = ls->linenumber;
902   primaryexp(ls, v);
903   for (;;) {
904     switch (ls->t.token) {
905       case '.': {  /* fieldsel */
906         fieldsel(ls, v);
907         break;
908       }
909       case '[': {  /* '[' exp1 ']' */
910         expdesc key;
911         luaK_exp2anyregup(fs, v);
912         yindex(ls, &key);
913         luaK_indexed(fs, v, &key);
914         break;
915       }
916       case ':': {  /* ':' NAME funcargs */
917         expdesc key;
918         luaX_next(ls);
919         checkname(ls, &key);
920         luaK_self(fs, v, &key);
921         funcargs(ls, v, line);
922         break;
923       }
924       case '(': case TK_STRING: case '{': {  /* funcargs */
925         luaK_exp2nextreg(fs, v);
926         funcargs(ls, v, line);
927         break;
928       }
929       default: return;
930     }
931   }
932 }
933 
934 
935 static void simpleexp (LexState *ls, expdesc *v) {
936   /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
937                   constructor | FUNCTION body | suffixedexp */
938   switch (ls->t.token) {
939 #ifndef _KERNEL
940     case TK_FLT: {
941       init_exp(v, VKFLT, 0);
942       v->u.nval = ls->t.seminfo.r;
943       break;
944     }
945 #endif /* _KERNEL */
946     case TK_INT: {
947       init_exp(v, VKINT, 0);
948       v->u.ival = ls->t.seminfo.i;
949       break;
950     }
951     case TK_STRING: {
952       codestring(ls, v, ls->t.seminfo.ts);
953       break;
954     }
955     case TK_NIL: {
956       init_exp(v, VNIL, 0);
957       break;
958     }
959     case TK_TRUE: {
960       init_exp(v, VTRUE, 0);
961       break;
962     }
963     case TK_FALSE: {
964       init_exp(v, VFALSE, 0);
965       break;
966     }
967     case TK_DOTS: {  /* vararg */
968       FuncState *fs = ls->fs;
969       check_condition(ls, fs->f->is_vararg,
970                       "cannot use '...' outside a vararg function");
971       init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
972       break;
973     }
974     case '{': {  /* constructor */
975       constructor(ls, v);
976       return;
977     }
978     case TK_FUNCTION: {
979       luaX_next(ls);
980       body(ls, v, 0, ls->linenumber);
981       return;
982     }
983     default: {
984       suffixedexp(ls, v);
985       return;
986     }
987   }
988   luaX_next(ls);
989 }
990 
991 
992 static UnOpr getunopr (int op) {
993   switch (op) {
994     case TK_NOT: return OPR_NOT;
995     case '-': return OPR_MINUS;
996     case '~': return OPR_BNOT;
997     case '#': return OPR_LEN;
998     default: return OPR_NOUNOPR;
999   }
1000 }
1001 
1002 
1003 static BinOpr getbinopr (int op) {
1004   switch (op) {
1005     case '+': return OPR_ADD;
1006     case '-': return OPR_SUB;
1007     case '*': return OPR_MUL;
1008     case '%': return OPR_MOD;
1009 #ifndef _KERNEL
1010     case '^': return OPR_POW;
1011     case '/': return OPR_DIV;
1012 #else /* _KERNEL */
1013     case '/': return OPR_IDIV;
1014 #endif /* _KERNEL */
1015     case TK_IDIV: return OPR_IDIV;
1016     case '&': return OPR_BAND;
1017     case '|': return OPR_BOR;
1018     case '~': return OPR_BXOR;
1019     case TK_SHL: return OPR_SHL;
1020     case TK_SHR: return OPR_SHR;
1021     case TK_CONCAT: return OPR_CONCAT;
1022     case TK_NE: return OPR_NE;
1023     case TK_EQ: return OPR_EQ;
1024     case '<': return OPR_LT;
1025     case TK_LE: return OPR_LE;
1026     case '>': return OPR_GT;
1027     case TK_GE: return OPR_GE;
1028     case TK_AND: return OPR_AND;
1029     case TK_OR: return OPR_OR;
1030     default: return OPR_NOBINOPR;
1031   }
1032 }
1033 
1034 
1035 static const struct {
1036   lu_byte left;  /* left priority for each binary operator */
1037   lu_byte right; /* right priority */
1038 } priority[] = {  /* ORDER OPR */
1039    {10, 10}, {10, 10},           /* '+' '-' */
1040    {11, 11}, {11, 11},           /* '*' '%' */
1041 #ifndef _KERNEL
1042    {14, 13},                  /* '^' (right associative) */
1043    {11, 11}, {11, 11},           /* '/' '//' */
1044 #else /* _KERNEL */
1045    {11, 11},                  /* '//' */
1046 #endif /* _KERNEL */
1047    {6, 6}, {4, 4}, {5, 5},   /* '&' '|' '~' */
1048    {7, 7}, {7, 7},           /* '<<' '>>' */
1049    {9, 8},                   /* '..' (right associative) */
1050    {3, 3}, {3, 3}, {3, 3},   /* ==, <, <= */
1051    {3, 3}, {3, 3}, {3, 3},   /* ~=, >, >= */
1052    {2, 2}, {1, 1}            /* and, or */
1053 };
1054 
1055 #define UNARY_PRIORITY	12  /* priority for unary operators */
1056 
1057 
1058 /*
1059 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1060 ** where 'binop' is any binary operator with a priority higher than 'limit'
1061 */
1062 static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
1063   BinOpr op;
1064   UnOpr uop;
1065   enterlevel(ls);
1066   uop = getunopr(ls->t.token);
1067   if (uop != OPR_NOUNOPR) {
1068     int line = ls->linenumber;
1069     luaX_next(ls);
1070     subexpr(ls, v, UNARY_PRIORITY);
1071     luaK_prefix(ls->fs, uop, v, line);
1072   }
1073   else simpleexp(ls, v);
1074   /* expand while operators have priorities higher than 'limit' */
1075   op = getbinopr(ls->t.token);
1076   while (op != OPR_NOBINOPR && priority[op].left > limit) {
1077     expdesc v2;
1078     BinOpr nextop;
1079     int line = ls->linenumber;
1080     luaX_next(ls);
1081     luaK_infix(ls->fs, op, v);
1082     /* read sub-expression with higher priority */
1083     nextop = subexpr(ls, &v2, priority[op].right);
1084     luaK_posfix(ls->fs, op, v, &v2, line);
1085     op = nextop;
1086   }
1087   leavelevel(ls);
1088   return op;  /* return first untreated operator */
1089 }
1090 
1091 
1092 static void expr (LexState *ls, expdesc *v) {
1093   subexpr(ls, v, 0);
1094 }
1095 
1096 /* }==================================================================== */
1097 
1098 
1099 
1100 /*
1101 ** {======================================================================
1102 ** Rules for Statements
1103 ** =======================================================================
1104 */
1105 
1106 
1107 static void block (LexState *ls) {
1108   /* block -> statlist */
1109   FuncState *fs = ls->fs;
1110   BlockCnt bl;
1111   enterblock(fs, &bl, 0);
1112   statlist(ls);
1113   leaveblock(fs);
1114 }
1115 
1116 
1117 /*
1118 ** structure to chain all variables in the left-hand side of an
1119 ** assignment
1120 */
1121 struct LHS_assign {
1122   struct LHS_assign *prev;
1123   expdesc v;  /* variable (global, local, upvalue, or indexed) */
1124 };
1125 
1126 
1127 /*
1128 ** check whether, in an assignment to an upvalue/local variable, the
1129 ** upvalue/local variable is begin used in a previous assignment to a
1130 ** table. If so, save original upvalue/local value in a safe place and
1131 ** use this safe copy in the previous assignment.
1132 */
1133 static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
1134   FuncState *fs = ls->fs;
1135   int extra = fs->freereg;  /* eventual position to save local variable */
1136   int conflict = 0;
1137   for (; lh; lh = lh->prev) {  /* check all previous assignments */
1138     if (lh->v.k == VINDEXED) {  /* assigning to a table? */
1139       /* table is the upvalue/local being assigned now? */
1140       if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {
1141         conflict = 1;
1142         lh->v.u.ind.vt = VLOCAL;
1143         lh->v.u.ind.t = extra;  /* previous assignment will use safe copy */
1144       }
1145       /* index is the local being assigned? (index cannot be upvalue) */
1146       if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {
1147         conflict = 1;
1148         lh->v.u.ind.idx = extra;  /* previous assignment will use safe copy */
1149       }
1150     }
1151   }
1152   if (conflict) {
1153     /* copy upvalue/local value to a temporary (in position 'extra') */
1154     OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
1155     luaK_codeABC(fs, op, extra, v->u.info, 0);
1156     luaK_reserveregs(fs, 1);
1157   }
1158 }
1159 
1160 
1161 static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
1162   expdesc e;
1163   check_condition(ls, vkisvar(lh->v.k), "syntax error");
1164   if (testnext(ls, ',')) {  /* assignment -> ',' suffixedexp assignment */
1165     struct LHS_assign nv;
1166     nv.prev = lh;
1167     suffixedexp(ls, &nv.v);
1168     if (nv.v.k != VINDEXED)
1169       check_conflict(ls, lh, &nv.v);
1170     checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,
1171                     "C levels");
1172     assignment(ls, &nv, nvars+1);
1173   }
1174   else {  /* assignment -> '=' explist */
1175     int nexps;
1176     checknext(ls, '=');
1177     nexps = explist(ls, &e);
1178     if (nexps != nvars)
1179       adjust_assign(ls, nvars, nexps, &e);
1180     else {
1181       luaK_setoneret(ls->fs, &e);  /* close last expression */
1182       luaK_storevar(ls->fs, &lh->v, &e);
1183       return;  /* avoid default */
1184     }
1185   }
1186   init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */
1187   luaK_storevar(ls->fs, &lh->v, &e);
1188 }
1189 
1190 
1191 static int cond (LexState *ls) {
1192   /* cond -> exp */
1193   expdesc v;
1194   expr(ls, &v);  /* read condition */
1195   if (v.k == VNIL) v.k = VFALSE;  /* 'falses' are all equal here */
1196   luaK_goiftrue(ls->fs, &v);
1197   return v.f;
1198 }
1199 
1200 
1201 static void gotostat (LexState *ls, int pc) {
1202   int line = ls->linenumber;
1203   TString *label;
1204   int g;
1205   if (testnext(ls, TK_GOTO))
1206     label = str_checkname(ls);
1207   else {
1208     luaX_next(ls);  /* skip break */
1209     label = luaS_new(ls->L, "break");
1210   }
1211   g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);
1212   findlabel(ls, g);  /* close it if label already defined */
1213 }
1214 
1215 
1216 /* check for repeated labels on the same block */
1217 static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
1218   int i;
1219   for (i = fs->bl->firstlabel; i < ll->n; i++) {
1220     if (eqstr(label, ll->arr[i].name)) {
1221       const char *msg = luaO_pushfstring(fs->ls->L,
1222                           "label '%s' already defined on line %d",
1223                           getstr(label), ll->arr[i].line);
1224       semerror(fs->ls, msg);
1225     }
1226   }
1227 }
1228 
1229 
1230 /* skip no-op statements */
1231 static void skipnoopstat (LexState *ls) {
1232   while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
1233     statement(ls);
1234 }
1235 
1236 
1237 static void labelstat (LexState *ls, TString *label, int line) {
1238   /* label -> '::' NAME '::' */
1239   FuncState *fs = ls->fs;
1240   Labellist *ll = &ls->dyd->label;
1241   int l;  /* index of new label being created */
1242   checkrepeated(fs, ll, label);  /* check for repeated labels */
1243   checknext(ls, TK_DBCOLON);  /* skip double colon */
1244   /* create new entry for this label */
1245   l = newlabelentry(ls, ll, label, line, luaK_getlabel(fs));
1246   skipnoopstat(ls);  /* skip other no-op statements */
1247   if (block_follow(ls, 0)) {  /* label is last no-op statement in the block? */
1248     /* assume that locals are already out of scope */
1249     ll->arr[l].nactvar = fs->bl->nactvar;
1250   }
1251   findgotos(ls, &ll->arr[l]);
1252 }
1253 
1254 
1255 static void whilestat (LexState *ls, int line) {
1256   /* whilestat -> WHILE cond DO block END */
1257   FuncState *fs = ls->fs;
1258   int whileinit;
1259   int condexit;
1260   BlockCnt bl;
1261   luaX_next(ls);  /* skip WHILE */
1262   whileinit = luaK_getlabel(fs);
1263   condexit = cond(ls);
1264   enterblock(fs, &bl, 1);
1265   checknext(ls, TK_DO);
1266   block(ls);
1267   luaK_jumpto(fs, whileinit);
1268   check_match(ls, TK_END, TK_WHILE, line);
1269   leaveblock(fs);
1270   luaK_patchtohere(fs, condexit);  /* false conditions finish the loop */
1271 }
1272 
1273 
1274 static void repeatstat (LexState *ls, int line) {
1275   /* repeatstat -> REPEAT block UNTIL cond */
1276   int condexit;
1277   FuncState *fs = ls->fs;
1278   int repeat_init = luaK_getlabel(fs);
1279   BlockCnt bl1, bl2;
1280   enterblock(fs, &bl1, 1);  /* loop block */
1281   enterblock(fs, &bl2, 0);  /* scope block */
1282   luaX_next(ls);  /* skip REPEAT */
1283   statlist(ls);
1284   check_match(ls, TK_UNTIL, TK_REPEAT, line);
1285   condexit = cond(ls);  /* read condition (inside scope block) */
1286   if (bl2.upval)  /* upvalues? */
1287     luaK_patchclose(fs, condexit, bl2.nactvar);
1288   leaveblock(fs);  /* finish scope */
1289   luaK_patchlist(fs, condexit, repeat_init);  /* close the loop */
1290   leaveblock(fs);  /* finish loop */
1291 }
1292 
1293 
1294 static int exp1 (LexState *ls) {
1295   expdesc e;
1296   int reg;
1297   expr(ls, &e);
1298   luaK_exp2nextreg(ls->fs, &e);
1299   lua_assert(e.k == VNONRELOC);
1300   reg = e.u.info;
1301   return reg;
1302 }
1303 
1304 
1305 static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1306   /* forbody -> DO block */
1307   BlockCnt bl;
1308   FuncState *fs = ls->fs;
1309   int prep, endfor;
1310   adjustlocalvars(ls, 3);  /* control variables */
1311   checknext(ls, TK_DO);
1312   prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1313   enterblock(fs, &bl, 0);  /* scope for declared variables */
1314   adjustlocalvars(ls, nvars);
1315   luaK_reserveregs(fs, nvars);
1316   block(ls);
1317   leaveblock(fs);  /* end of scope for declared variables */
1318   luaK_patchtohere(fs, prep);
1319   if (isnum)  /* numeric for? */
1320     endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
1321   else {  /* generic for */
1322     luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
1323     luaK_fixline(fs, line);
1324     endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
1325   }
1326   luaK_patchlist(fs, endfor, prep + 1);
1327   luaK_fixline(fs, line);
1328 }
1329 
1330 
1331 static void fornum (LexState *ls, TString *varname, int line) {
1332   /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1333   FuncState *fs = ls->fs;
1334   int base = fs->freereg;
1335   new_localvarliteral(ls, "(for index)");
1336   new_localvarliteral(ls, "(for limit)");
1337   new_localvarliteral(ls, "(for step)");
1338   new_localvar(ls, varname);
1339   checknext(ls, '=');
1340   exp1(ls);  /* initial value */
1341   checknext(ls, ',');
1342   exp1(ls);  /* limit */
1343   if (testnext(ls, ','))
1344     exp1(ls);  /* optional step */
1345   else {  /* default step = 1 */
1346     luaK_codek(fs, fs->freereg, luaK_intK(fs, 1));
1347     luaK_reserveregs(fs, 1);
1348   }
1349   forbody(ls, base, line, 1, 1);
1350 }
1351 
1352 
1353 static void forlist (LexState *ls, TString *indexname) {
1354   /* forlist -> NAME {,NAME} IN explist forbody */
1355   FuncState *fs = ls->fs;
1356   expdesc e;
1357   int nvars = 4;  /* gen, state, control, plus at least one declared var */
1358   int line;
1359   int base = fs->freereg;
1360   /* create control variables */
1361   new_localvarliteral(ls, "(for generator)");
1362   new_localvarliteral(ls, "(for state)");
1363   new_localvarliteral(ls, "(for control)");
1364   /* create declared variables */
1365   new_localvar(ls, indexname);
1366   while (testnext(ls, ',')) {
1367     new_localvar(ls, str_checkname(ls));
1368     nvars++;
1369   }
1370   checknext(ls, TK_IN);
1371   line = ls->linenumber;
1372   adjust_assign(ls, 3, explist(ls, &e), &e);
1373   luaK_checkstack(fs, 3);  /* extra space to call generator */
1374   forbody(ls, base, line, nvars - 3, 0);
1375 }
1376 
1377 
1378 static void forstat (LexState *ls, int line) {
1379   /* forstat -> FOR (fornum | forlist) END */
1380   FuncState *fs = ls->fs;
1381   TString *varname;
1382   BlockCnt bl;
1383   enterblock(fs, &bl, 1);  /* scope for loop and control variables */
1384   luaX_next(ls);  /* skip 'for' */
1385   varname = str_checkname(ls);  /* first variable name */
1386   switch (ls->t.token) {
1387     case '=': fornum(ls, varname, line); break;
1388     case ',': case TK_IN: forlist(ls, varname); break;
1389     default: luaX_syntaxerror(ls, "'=' or 'in' expected");
1390   }
1391   check_match(ls, TK_END, TK_FOR, line);
1392   leaveblock(fs);  /* loop scope ('break' jumps to this point) */
1393 }
1394 
1395 
1396 static void test_then_block (LexState *ls, int *escapelist) {
1397   /* test_then_block -> [IF | ELSEIF] cond THEN block */
1398   BlockCnt bl;
1399   FuncState *fs = ls->fs;
1400   expdesc v;
1401   int jf;  /* instruction to skip 'then' code (if condition is false) */
1402   luaX_next(ls);  /* skip IF or ELSEIF */
1403   expr(ls, &v);  /* read condition */
1404   checknext(ls, TK_THEN);
1405   if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
1406     luaK_goiffalse(ls->fs, &v);  /* will jump to label if condition is true */
1407     enterblock(fs, &bl, 0);  /* must enter block before 'goto' */
1408     gotostat(ls, v.t);  /* handle goto/break */
1409     while (testnext(ls, ';')) {}  /* skip colons */
1410     if (block_follow(ls, 0)) {  /* 'goto' is the entire block? */
1411       leaveblock(fs);
1412       return;  /* and that is it */
1413     }
1414     else  /* must skip over 'then' part if condition is false */
1415       jf = luaK_jump(fs);
1416   }
1417   else {  /* regular case (not goto/break) */
1418     luaK_goiftrue(ls->fs, &v);  /* skip over block if condition is false */
1419     enterblock(fs, &bl, 0);
1420     jf = v.f;
1421   }
1422   statlist(ls);  /* 'then' part */
1423   leaveblock(fs);
1424   if (ls->t.token == TK_ELSE ||
1425       ls->t.token == TK_ELSEIF)  /* followed by 'else'/'elseif'? */
1426     luaK_concat(fs, escapelist, luaK_jump(fs));  /* must jump over it */
1427   luaK_patchtohere(fs, jf);
1428 }
1429 
1430 
1431 static void ifstat (LexState *ls, int line) {
1432   /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1433   FuncState *fs = ls->fs;
1434   int escapelist = NO_JUMP;  /* exit list for finished parts */
1435   test_then_block(ls, &escapelist);  /* IF cond THEN block */
1436   while (ls->t.token == TK_ELSEIF)
1437     test_then_block(ls, &escapelist);  /* ELSEIF cond THEN block */
1438   if (testnext(ls, TK_ELSE))
1439     block(ls);  /* 'else' part */
1440   check_match(ls, TK_END, TK_IF, line);
1441   luaK_patchtohere(fs, escapelist);  /* patch escape list to 'if' end */
1442 }
1443 
1444 
1445 static void localfunc (LexState *ls) {
1446   expdesc b;
1447   FuncState *fs = ls->fs;
1448   new_localvar(ls, str_checkname(ls));  /* new local variable */
1449   adjustlocalvars(ls, 1);  /* enter its scope */
1450   body(ls, &b, 0, ls->linenumber);  /* function created in next register */
1451   /* debug information will only see the variable after this point! */
1452   getlocvar(fs, b.u.info)->startpc = fs->pc;
1453 }
1454 
1455 
1456 static void localstat (LexState *ls) {
1457   /* stat -> LOCAL NAME {',' NAME} ['=' explist] */
1458   int nvars = 0;
1459   int nexps;
1460   expdesc e;
1461   do {
1462     new_localvar(ls, str_checkname(ls));
1463     nvars++;
1464   } while (testnext(ls, ','));
1465   if (testnext(ls, '='))
1466     nexps = explist(ls, &e);
1467   else {
1468     e.k = VVOID;
1469     nexps = 0;
1470   }
1471   adjust_assign(ls, nvars, nexps, &e);
1472   adjustlocalvars(ls, nvars);
1473 }
1474 
1475 
1476 static int funcname (LexState *ls, expdesc *v) {
1477   /* funcname -> NAME {fieldsel} [':' NAME] */
1478   int ismethod = 0;
1479   singlevar(ls, v);
1480   while (ls->t.token == '.')
1481     fieldsel(ls, v);
1482   if (ls->t.token == ':') {
1483     ismethod = 1;
1484     fieldsel(ls, v);
1485   }
1486   return ismethod;
1487 }
1488 
1489 
1490 static void funcstat (LexState *ls, int line) {
1491   /* funcstat -> FUNCTION funcname body */
1492   int ismethod;
1493   expdesc v, b;
1494   luaX_next(ls);  /* skip FUNCTION */
1495   ismethod = funcname(ls, &v);
1496   body(ls, &b, ismethod, line);
1497   luaK_storevar(ls->fs, &v, &b);
1498   luaK_fixline(ls->fs, line);  /* definition "happens" in the first line */
1499 }
1500 
1501 
1502 static void exprstat (LexState *ls) {
1503   /* stat -> func | assignment */
1504   FuncState *fs = ls->fs;
1505   struct LHS_assign v;
1506   suffixedexp(ls, &v.v);
1507   if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
1508     v.prev = NULL;
1509     assignment(ls, &v, 1);
1510   }
1511   else {  /* stat -> func */
1512     check_condition(ls, v.v.k == VCALL, "syntax error");
1513     SETARG_C(getinstruction(fs, &v.v), 1);  /* call statement uses no results */
1514   }
1515 }
1516 
1517 
1518 static void retstat (LexState *ls) {
1519   /* stat -> RETURN [explist] [';'] */
1520   FuncState *fs = ls->fs;
1521   expdesc e;
1522   int first, nret;  /* registers with returned values */
1523   if (block_follow(ls, 1) || ls->t.token == ';')
1524     first = nret = 0;  /* return no values */
1525   else {
1526     nret = explist(ls, &e);  /* optional return values */
1527     if (hasmultret(e.k)) {
1528       luaK_setmultret(fs, &e);
1529       if (e.k == VCALL && nret == 1) {  /* tail call? */
1530         SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);
1531         lua_assert(GETARG_A(getinstruction(fs,&e)) == fs->nactvar);
1532       }
1533       first = fs->nactvar;
1534       nret = LUA_MULTRET;  /* return all values */
1535     }
1536     else {
1537       if (nret == 1)  /* only one single value? */
1538         first = luaK_exp2anyreg(fs, &e);
1539       else {
1540         luaK_exp2nextreg(fs, &e);  /* values must go to the stack */
1541         first = fs->nactvar;  /* return all active values */
1542         lua_assert(nret == fs->freereg - first);
1543       }
1544     }
1545   }
1546   luaK_ret(fs, first, nret);
1547   testnext(ls, ';');  /* skip optional semicolon */
1548 }
1549 
1550 
1551 static void statement (LexState *ls) {
1552   int line = ls->linenumber;  /* may be needed for error messages */
1553   enterlevel(ls);
1554   switch (ls->t.token) {
1555     case ';': {  /* stat -> ';' (empty statement) */
1556       luaX_next(ls);  /* skip ';' */
1557       break;
1558     }
1559     case TK_IF: {  /* stat -> ifstat */
1560       ifstat(ls, line);
1561       break;
1562     }
1563     case TK_WHILE: {  /* stat -> whilestat */
1564       whilestat(ls, line);
1565       break;
1566     }
1567     case TK_DO: {  /* stat -> DO block END */
1568       luaX_next(ls);  /* skip DO */
1569       block(ls);
1570       check_match(ls, TK_END, TK_DO, line);
1571       break;
1572     }
1573     case TK_FOR: {  /* stat -> forstat */
1574       forstat(ls, line);
1575       break;
1576     }
1577     case TK_REPEAT: {  /* stat -> repeatstat */
1578       repeatstat(ls, line);
1579       break;
1580     }
1581     case TK_FUNCTION: {  /* stat -> funcstat */
1582       funcstat(ls, line);
1583       break;
1584     }
1585     case TK_LOCAL: {  /* stat -> localstat */
1586       luaX_next(ls);  /* skip LOCAL */
1587       if (testnext(ls, TK_FUNCTION))  /* local function? */
1588         localfunc(ls);
1589       else
1590         localstat(ls);
1591       break;
1592     }
1593     case TK_DBCOLON: {  /* stat -> label */
1594       luaX_next(ls);  /* skip double colon */
1595       labelstat(ls, str_checkname(ls), line);
1596       break;
1597     }
1598     case TK_RETURN: {  /* stat -> retstat */
1599       luaX_next(ls);  /* skip RETURN */
1600       retstat(ls);
1601       break;
1602     }
1603     case TK_BREAK:   /* stat -> breakstat */
1604     case TK_GOTO: {  /* stat -> 'goto' NAME */
1605       gotostat(ls, luaK_jump(ls->fs));
1606       break;
1607     }
1608     default: {  /* stat -> func | assignment */
1609       exprstat(ls);
1610       break;
1611     }
1612   }
1613   lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1614              ls->fs->freereg >= ls->fs->nactvar);
1615   ls->fs->freereg = ls->fs->nactvar;  /* free registers */
1616   leavelevel(ls);
1617 }
1618 
1619 /* }====================================================================== */
1620 
1621 
1622 /*
1623 ** compiles the main function, which is a regular vararg function with an
1624 ** upvalue named LUA_ENV
1625 */
1626 static void mainfunc (LexState *ls, FuncState *fs) {
1627   BlockCnt bl;
1628   expdesc v;
1629   open_func(ls, fs, &bl);
1630   fs->f->is_vararg = 1;  /* main function is always declared vararg */
1631   init_exp(&v, VLOCAL, 0);  /* create and... */
1632   newupvalue(fs, ls->envn, &v);  /* ...set environment upvalue */
1633   luaX_next(ls);  /* read first token */
1634   statlist(ls);  /* parse main body */
1635   check(ls, TK_EOS);
1636   close_func(ls);
1637 }
1638 
1639 
1640 LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1641                        Dyndata *dyd, const char *name, int firstchar) {
1642   LexState lexstate;
1643   FuncState funcstate;
1644   LClosure *cl = luaF_newLclosure(L, 1);  /* create main closure */
1645   setclLvalue(L, L->top, cl);  /* anchor it (to avoid being collected) */
1646   luaD_inctop(L);
1647   lexstate.h = luaH_new(L);  /* create table for scanner */
1648   sethvalue(L, L->top, lexstate.h);  /* anchor it */
1649   luaD_inctop(L);
1650   funcstate.f = cl->p = luaF_newproto(L);
1651   funcstate.f->source = luaS_new(L, name);  /* create and anchor TString */
1652   lua_assert(iswhite(funcstate.f));  /* do not need barrier here */
1653   lexstate.buff = buff;
1654   lexstate.dyd = dyd;
1655   dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
1656   luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
1657   mainfunc(&lexstate, &funcstate);
1658   lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
1659   /* all scopes should be correctly finished */
1660   lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
1661   L->top--;  /* remove scanner's table */
1662   return cl;  /* closure is on the stack, too */
1663 }
1664 
1665