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