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