]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/lua/lparser.c
Vendor import of openzfs master @ 184df27eef0abdc7ab2105b21257f753834b936b
[FreeBSD/FreeBSD.git] / module / lua / lparser.c
1 /* BEGIN CSTYLED */
2 /*
3 ** $Id: lparser.c,v 2.130.1.1 2013/04/12 18:48:47 roberto Exp $
4 ** Lua Parser
5 ** See Copyright Notice in lua.h
6 */
7
8 #define lparser_c
9 #define LUA_CORE
10
11 #include <sys/lua/lua.h>
12
13 #include "lcode.h"
14 #include "ldebug.h"
15 #include "ldo.h"
16 #include "lfunc.h"
17 #include "llex.h"
18 #include "lmem.h"
19 #include "lobject.h"
20 #include "lopcodes.h"
21 #include "lparser.h"
22 #include "lstate.h"
23 #include "lstring.h"
24 #include "ltable.h"
25
26
27
28 /* maximum number of local variables per function (must be smaller
29    than 250, due to the bytecode format) */
30 #define MAXVARS         200
31
32
33 #define hasmultret(k)           ((k) == VCALL || (k) == VVARARG)
34
35
36
37 /*
38 ** nodes for block list (list of active blocks)
39 */
40 typedef struct BlockCnt {
41   struct BlockCnt *previous;  /* chain */
42   short firstlabel;  /* index of first label in this block */
43   short firstgoto;  /* index of first pending goto in this block */
44   lu_byte nactvar;  /* # active locals outside the block */
45   lu_byte upval;  /* true if some variable in the block is an upvalue */
46   lu_byte isloop;  /* true if `block' is a loop */
47 } BlockCnt;
48
49
50
51 /*
52 ** prototypes for recursive non-terminal functions
53 */
54 static void statement (LexState *ls);
55 static void expr (LexState *ls, expdesc *v);
56
57
58 static void anchor_token (LexState *ls) {
59   /* last token from outer function must be EOS */
60   lua_assert(ls->fs != NULL || ls->t.token == TK_EOS);
61   if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
62     TString *ts = ls->t.seminfo.ts;
63     luaX_newstring(ls, getstr(ts), ts->tsv.len);
64   }
65 }
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 (luaS_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 (luaS_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(luaS_eqstr(gt->name, label->name));
344   if (gt->nactvar < label->nactvar) {
345     TString *vname = getlocvar(fs, gt->nactvar)->varname;
346     const char *msg = luaO_pushfstring(ls->L,
347       "<goto %s> at line %d jumps into the scope of local " LUA_QS,
348       getstr(gt->name), gt->line, getstr(vname));
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 (luaS_eqstr(lb->name, gt->name)) {  /* correct label? */
371       if (gt->nactvar > lb->nactvar &&
372           (bl->upval || dyd->label.n > bl->firstlabel))
373         luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
374       closegoto(ls, g, lb);  /* close it */
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 (luaS_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   lua_State *L = ls->L;
527   Proto *f;
528   fs->prev = ls->fs;  /* linked list of funcstates */
529   fs->ls = ls;
530   ls->fs = fs;
531   fs->pc = 0;
532   fs->lasttarget = 0;
533   fs->jpc = NO_JUMP;
534   fs->freereg = 0;
535   fs->nk = 0;
536   fs->np = 0;
537   fs->nups = 0;
538   fs->nlocvars = 0;
539   fs->nactvar = 0;
540   fs->firstlocal = ls->dyd->actvar.n;
541   fs->bl = NULL;
542   f = fs->f;
543   f->source = ls->source;
544   f->maxstacksize = 2;  /* registers 0/1 are always valid */
545   fs->h = luaH_new(L);
546   /* anchor table of constants (to avoid being collected) */
547   sethvalue2s(L, L->top, fs->h);
548   incr_top(L);
549   enterblock(fs, bl, 0);
550 }
551
552
553 static void close_func (LexState *ls) {
554   lua_State *L = ls->L;
555   FuncState *fs = ls->fs;
556   Proto *f = fs->f;
557   luaK_ret(fs, 0, 0);  /* final return */
558   leaveblock(fs);
559   luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
560   f->sizecode = fs->pc;
561   luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
562   f->sizelineinfo = fs->pc;
563   luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
564   f->sizek = fs->nk;
565   luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
566   f->sizep = fs->np;
567   luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
568   f->sizelocvars = fs->nlocvars;
569   luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
570   f->sizeupvalues = fs->nups;
571   lua_assert(fs->bl == NULL);
572   ls->fs = fs->prev;
573   /* last token read was anchored in defunct function; must re-anchor it */
574   anchor_token(ls);
575   L->top--;  /* pop table of constants */
576   luaC_checkGC(L);
577 }
578
579
580
581 /*============================================================*/
582 /* GRAMMAR RULES */
583 /*============================================================*/
584
585
586 /*
587 ** check whether current token is in the follow set of a block.
588 ** 'until' closes syntactical blocks, but do not close scope,
589 ** so it handled in separate.
590 */
591 static int block_follow (LexState *ls, int withuntil) {
592   switch (ls->t.token) {
593     case TK_ELSE: case TK_ELSEIF:
594     case TK_END: case TK_EOS:
595       return 1;
596     case TK_UNTIL: return withuntil;
597     default: return 0;
598   }
599 }
600
601
602 /*
603  * by inlining statlist() and test_then_block() we cut back the
604  * native stack usage per nested C call from 272 bytes to 152
605  * which allows us to stay within budget for 8K kernel stacks
606  */
607 __attribute__((always_inline)) inline
608 static void statlist (LexState *ls) {
609   /* statlist -> { stat [`;'] } */
610   while (!block_follow(ls, 1)) {
611     if (ls->t.token == TK_RETURN) {
612       statement(ls);
613       return;  /* 'return' must be last statement */
614     }
615     statement(ls);
616   }
617 }
618
619
620 static void fieldsel (LexState *ls, expdesc *v) {
621   /* fieldsel -> ['.' | ':'] NAME */
622   FuncState *fs = ls->fs;
623   expdesc key;
624   luaK_exp2anyregup(fs, v);
625   luaX_next(ls);  /* skip the dot or colon */
626   checkname(ls, &key);
627   luaK_indexed(fs, v, &key);
628 }
629
630
631 static void yindex (LexState *ls, expdesc *v) {
632   /* index -> '[' expr ']' */
633   luaX_next(ls);  /* skip the '[' */
634   expr(ls, v);
635   luaK_exp2val(ls->fs, v);
636   checknext(ls, ']');
637 }
638
639
640 /*
641 ** {======================================================================
642 ** Rules for Constructors
643 ** =======================================================================
644 */
645
646
647 struct ConsControl {
648   expdesc v;  /* last list item read */
649   expdesc *t;  /* table descriptor */
650   int nh;  /* total number of `record' elements */
651   int na;  /* total number of array elements */
652   int tostore;  /* number of array elements pending to be stored */
653 };
654
655
656 static void recfield (LexState *ls, struct ConsControl *cc) {
657   /* recfield -> (NAME | `['exp1`]') = exp1 */
658   FuncState *fs = ls->fs;
659   int reg = ls->fs->freereg;
660   expdesc key, val;
661   int rkkey;
662   if (ls->t.token == TK_NAME) {
663     checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
664     checkname(ls, &key);
665   }
666   else  /* ls->t.token == '[' */
667     yindex(ls, &key);
668   cc->nh++;
669   checknext(ls, '=');
670   rkkey = luaK_exp2RK(fs, &key);
671   expr(ls, &val);
672   luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val));
673   fs->freereg = reg;  /* free registers */
674 }
675
676
677 static void closelistfield (FuncState *fs, struct ConsControl *cc) {
678   if (cc->v.k == VVOID) return;  /* there is no list item */
679   luaK_exp2nextreg(fs, &cc->v);
680   cc->v.k = VVOID;
681   if (cc->tostore == LFIELDS_PER_FLUSH) {
682     luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);  /* flush */
683     cc->tostore = 0;  /* no more items pending */
684   }
685 }
686
687
688 static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
689   if (cc->tostore == 0) return;
690   if (hasmultret(cc->v.k)) {
691     luaK_setmultret(fs, &cc->v);
692     luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
693     cc->na--;  /* do not count last expression (unknown number of elements) */
694   }
695   else {
696     if (cc->v.k != VVOID)
697       luaK_exp2nextreg(fs, &cc->v);
698     luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
699   }
700 }
701
702
703 static void listfield (LexState *ls, struct ConsControl *cc) {
704   /* listfield -> exp */
705   expr(ls, &cc->v);
706   checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
707   cc->na++;
708   cc->tostore++;
709 }
710
711
712 static void field (LexState *ls, struct ConsControl *cc) {
713   /* field -> listfield | recfield */
714   switch(ls->t.token) {
715     case TK_NAME: {  /* may be 'listfield' or 'recfield' */
716       if (luaX_lookahead(ls) != '=')  /* expression? */
717         listfield(ls, cc);
718       else
719         recfield(ls, cc);
720       break;
721     }
722     case '[': {
723       recfield(ls, cc);
724       break;
725     }
726     default: {
727       listfield(ls, cc);
728       break;
729     }
730   }
731 }
732
733
734 static void constructor (LexState *ls, expdesc *t) {
735   /* constructor -> '{' [ field { sep field } [sep] ] '}'
736      sep -> ',' | ';' */
737   FuncState *fs = ls->fs;
738   int line = ls->linenumber;
739   int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
740   struct ConsControl cc;
741   cc.na = cc.nh = cc.tostore = 0;
742   cc.t = t;
743   init_exp(t, VRELOCABLE, pc);
744   init_exp(&cc.v, VVOID, 0);  /* no value (yet) */
745   luaK_exp2nextreg(ls->fs, t);  /* fix it at stack top */
746   checknext(ls, '{');
747   do {
748     lua_assert(cc.v.k == VVOID || cc.tostore > 0);
749     if (ls->t.token == '}') break;
750     closelistfield(fs, &cc);
751     field(ls, &cc);
752   } while (testnext(ls, ',') || testnext(ls, ';'));
753   check_match(ls, '}', '{', line);
754   lastlistfield(fs, &cc);
755   SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
756   SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh));  /* set initial table size */
757 }
758
759 /* }====================================================================== */
760
761
762
763 static void parlist (LexState *ls) {
764   /* parlist -> [ param { `,' param } ] */
765   FuncState *fs = ls->fs;
766   Proto *f = fs->f;
767   int nparams = 0;
768   f->is_vararg = 0;
769   if (ls->t.token != ')') {  /* is `parlist' not empty? */
770     do {
771       switch (ls->t.token) {
772         case TK_NAME: {  /* param -> NAME */
773           new_localvar(ls, str_checkname(ls));
774           nparams++;
775           break;
776         }
777         case TK_DOTS: {  /* param -> `...' */
778           luaX_next(ls);
779           f->is_vararg = 1;
780           break;
781         }
782         default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
783       }
784     } while (!f->is_vararg && testnext(ls, ','));
785   }
786   adjustlocalvars(ls, nparams);
787   f->numparams = cast_byte(fs->nactvar);
788   luaK_reserveregs(fs, fs->nactvar);  /* reserve register for parameters */
789 }
790
791
792 static void body (LexState *ls, expdesc *e, int ismethod, int line) {
793   /* body ->  `(' parlist `)' block END */
794   FuncState new_fs;
795   BlockCnt bl;
796   new_fs.f = addprototype(ls);
797   new_fs.f->linedefined = line;
798   open_func(ls, &new_fs, &bl);
799   checknext(ls, '(');
800   if (ismethod) {
801     new_localvarliteral(ls, "self");  /* create 'self' parameter */
802     adjustlocalvars(ls, 1);
803   }
804   parlist(ls);
805   checknext(ls, ')');
806   statlist(ls);
807   new_fs.f->lastlinedefined = ls->linenumber;
808   check_match(ls, TK_END, TK_FUNCTION, line);
809   codeclosure(ls, e);
810   close_func(ls);
811 }
812
813
814 static int explist (LexState *ls, expdesc *v) {
815   /* explist -> expr { `,' expr } */
816   int n = 1;  /* at least one expression */
817   expr(ls, v);
818   while (testnext(ls, ',')) {
819     luaK_exp2nextreg(ls->fs, v);
820     expr(ls, v);
821     n++;
822   }
823   return n;
824 }
825
826
827 static void funcargs (LexState *ls, expdesc *f, int line) {
828   FuncState *fs = ls->fs;
829   expdesc args;
830   int base, nparams;
831   switch (ls->t.token) {
832     case '(': {  /* funcargs -> `(' [ explist ] `)' */
833       luaX_next(ls);
834       if (ls->t.token == ')')  /* arg list is empty? */
835         args.k = VVOID;
836       else {
837         explist(ls, &args);
838         luaK_setmultret(fs, &args);
839       }
840       check_match(ls, ')', '(', line);
841       break;
842     }
843     case '{': {  /* funcargs -> constructor */
844       constructor(ls, &args);
845       break;
846     }
847     case TK_STRING: {  /* funcargs -> STRING */
848       codestring(ls, &args, ls->t.seminfo.ts);
849       luaX_next(ls);  /* must use `seminfo' before `next' */
850       break;
851     }
852     default: {
853       luaX_syntaxerror(ls, "function arguments expected");
854     }
855   }
856   lua_assert(f->k == VNONRELOC);
857   base = f->u.info;  /* base register for call */
858   if (hasmultret(args.k))
859     nparams = LUA_MULTRET;  /* open call */
860   else {
861     if (args.k != VVOID)
862       luaK_exp2nextreg(fs, &args);  /* close last argument */
863     nparams = fs->freereg - (base+1);
864   }
865   init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
866   luaK_fixline(fs, line);
867   fs->freereg = base+1;  /* call remove function and arguments and leaves
868                             (unless changed) one result */
869 }
870
871
872
873
874 /*
875 ** {======================================================================
876 ** Expression parsing
877 ** =======================================================================
878 */
879
880
881 static void primaryexp (LexState *ls, expdesc *v) {
882   /* primaryexp -> NAME | '(' expr ')' */
883   switch (ls->t.token) {
884     case '(': {
885       int line = ls->linenumber;
886       luaX_next(ls);
887       expr(ls, v);
888       check_match(ls, ')', '(', line);
889       luaK_dischargevars(ls->fs, v);
890       return;
891     }
892     case TK_NAME: {
893       singlevar(ls, v);
894       return;
895     }
896     default: {
897       luaX_syntaxerror(ls, "unexpected symbol");
898     }
899   }
900 }
901
902
903 static void suffixedexp (LexState *ls, expdesc *v) {
904   /* suffixedexp ->
905        primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
906   FuncState *fs = ls->fs;
907   int line = ls->linenumber;
908   primaryexp(ls, v);
909   for (;;) {
910     switch (ls->t.token) {
911       case '.': {  /* fieldsel */
912         fieldsel(ls, v);
913         break;
914       }
915       case '[': {  /* `[' exp1 `]' */
916         expdesc key;
917         luaK_exp2anyregup(fs, v);
918         yindex(ls, &key);
919         luaK_indexed(fs, v, &key);
920         break;
921       }
922       case ':': {  /* `:' NAME funcargs */
923         expdesc key;
924         luaX_next(ls);
925         checkname(ls, &key);
926         luaK_self(fs, v, &key);
927         funcargs(ls, v, line);
928         break;
929       }
930       case '(': case TK_STRING: case '{': {  /* funcargs */
931         luaK_exp2nextreg(fs, v);
932         funcargs(ls, v, line);
933         break;
934       }
935       default: return;
936     }
937   }
938 }
939
940
941 static void simpleexp (LexState *ls, expdesc *v) {
942   /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
943                   constructor | FUNCTION body | suffixedexp */
944   switch (ls->t.token) {
945     case TK_NUMBER: {
946       init_exp(v, VKNUM, 0);
947       v->u.nval = ls->t.seminfo.r;
948       break;
949     }
950     case TK_STRING: {
951       codestring(ls, v, ls->t.seminfo.ts);
952       break;
953     }
954     case TK_NIL: {
955       init_exp(v, VNIL, 0);
956       break;
957     }
958     case TK_TRUE: {
959       init_exp(v, VTRUE, 0);
960       break;
961     }
962     case TK_FALSE: {
963       init_exp(v, VFALSE, 0);
964       break;
965     }
966     case TK_DOTS: {  /* vararg */
967       FuncState *fs = ls->fs;
968       check_condition(ls, fs->f->is_vararg,
969                       "cannot use " LUA_QL("...") " outside a vararg function");
970       init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
971       break;
972     }
973     case '{': {  /* constructor */
974       constructor(ls, v);
975       return;
976     }
977     case TK_FUNCTION: {
978       luaX_next(ls);
979       body(ls, v, 0, ls->linenumber);
980       return;
981     }
982     default: {
983       suffixedexp(ls, v);
984       return;
985     }
986   }
987   luaX_next(ls);
988 }
989
990
991 static UnOpr getunopr (int op) {
992   switch (op) {
993     case TK_NOT: return OPR_NOT;
994     case '-': return OPR_MINUS;
995     case '#': return OPR_LEN;
996     default: return OPR_NOUNOPR;
997   }
998 }
999
1000
1001 static BinOpr getbinopr (int op) {
1002   switch (op) {
1003     case '+': return OPR_ADD;
1004     case '-': return OPR_SUB;
1005     case '*': return OPR_MUL;
1006     case '/': return OPR_DIV;
1007     case '%': return OPR_MOD;
1008     case '^': return OPR_POW;
1009     case TK_CONCAT: return OPR_CONCAT;
1010     case TK_NE: return OPR_NE;
1011     case TK_EQ: return OPR_EQ;
1012     case '<': return OPR_LT;
1013     case TK_LE: return OPR_LE;
1014     case '>': return OPR_GT;
1015     case TK_GE: return OPR_GE;
1016     case TK_AND: return OPR_AND;
1017     case TK_OR: return OPR_OR;
1018     default: return OPR_NOBINOPR;
1019   }
1020 }
1021
1022
1023 static const struct {
1024   lu_byte left;  /* left priority for each binary operator */
1025   lu_byte right; /* right priority */
1026 } priority[] = {  /* ORDER OPR */
1027    {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7},  /* `+' `-' `*' `/' `%' */
1028    {10, 9}, {5, 4},                 /* ^, .. (right associative) */
1029    {3, 3}, {3, 3}, {3, 3},          /* ==, <, <= */
1030    {3, 3}, {3, 3}, {3, 3},          /* ~=, >, >= */
1031    {2, 2}, {1, 1}                   /* and, or */
1032 };
1033
1034 #define UNARY_PRIORITY  8  /* priority for unary operators */
1035
1036
1037 /*
1038 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1039 ** where `binop' is any binary operator with a priority higher than `limit'
1040 */
1041 static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
1042   BinOpr op;
1043   UnOpr uop;
1044   enterlevel(ls);
1045   uop = getunopr(ls->t.token);
1046   if (uop != OPR_NOUNOPR) {
1047     int line = ls->linenumber;
1048     luaX_next(ls);
1049     subexpr(ls, v, UNARY_PRIORITY);
1050     luaK_prefix(ls->fs, uop, v, line);
1051   }
1052   else simpleexp(ls, v);
1053   /* expand while operators have priorities higher than `limit' */
1054   op = getbinopr(ls->t.token);
1055   while (op != OPR_NOBINOPR && priority[op].left > limit) {
1056     expdesc v2;
1057     BinOpr nextop;
1058     int line = ls->linenumber;
1059     luaX_next(ls);
1060     luaK_infix(ls->fs, op, v);
1061     /* read sub-expression with higher priority */
1062     nextop = subexpr(ls, &v2, priority[op].right);
1063     luaK_posfix(ls->fs, op, v, &v2, line);
1064     op = nextop;
1065   }
1066   leavelevel(ls);
1067   return op;  /* return first untreated operator */
1068 }
1069
1070
1071 static void expr (LexState *ls, expdesc *v) {
1072   subexpr(ls, v, 0);
1073 }
1074
1075 /* }==================================================================== */
1076
1077
1078
1079 /*
1080 ** {======================================================================
1081 ** Rules for Statements
1082 ** =======================================================================
1083 */
1084
1085
1086 static void block (LexState *ls) {
1087   /* block -> statlist */
1088   FuncState *fs = ls->fs;
1089   BlockCnt bl;
1090   enterblock(fs, &bl, 0);
1091   statlist(ls);
1092   leaveblock(fs);
1093 }
1094
1095
1096 /*
1097 ** structure to chain all variables in the left-hand side of an
1098 ** assignment
1099 */
1100 struct LHS_assign {
1101   struct LHS_assign *prev;
1102   expdesc v;  /* variable (global, local, upvalue, or indexed) */
1103 };
1104
1105
1106 /*
1107 ** check whether, in an assignment to an upvalue/local variable, the
1108 ** upvalue/local variable is begin used in a previous assignment to a
1109 ** table. If so, save original upvalue/local value in a safe place and
1110 ** use this safe copy in the previous assignment.
1111 */
1112 static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
1113   FuncState *fs = ls->fs;
1114   int extra = fs->freereg;  /* eventual position to save local variable */
1115   int conflict = 0;
1116   for (; lh; lh = lh->prev) {  /* check all previous assignments */
1117     if (lh->v.k == VINDEXED) {  /* assigning to a table? */
1118       /* table is the upvalue/local being assigned now? */
1119       if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {
1120         conflict = 1;
1121         lh->v.u.ind.vt = VLOCAL;
1122         lh->v.u.ind.t = extra;  /* previous assignment will use safe copy */
1123       }
1124       /* index is the local being assigned? (index cannot be upvalue) */
1125       if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {
1126         conflict = 1;
1127         lh->v.u.ind.idx = extra;  /* previous assignment will use safe copy */
1128       }
1129     }
1130   }
1131   if (conflict) {
1132     /* copy upvalue/local value to a temporary (in position 'extra') */
1133     OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
1134     luaK_codeABC(fs, op, extra, v->u.info, 0);
1135     luaK_reserveregs(fs, 1);
1136   }
1137 }
1138
1139
1140 static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
1141   expdesc e;
1142   check_condition(ls, vkisvar(lh->v.k), "syntax error");
1143   if (testnext(ls, ',')) {  /* assignment -> ',' suffixedexp assignment */
1144     struct LHS_assign nv;
1145     nv.prev = lh;
1146     suffixedexp(ls, &nv.v);
1147     if (nv.v.k != VINDEXED)
1148       check_conflict(ls, lh, &nv.v);
1149     checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,
1150                     "C levels");
1151     assignment(ls, &nv, nvars+1);
1152   }
1153   else {  /* assignment -> `=' explist */
1154     int nexps;
1155     checknext(ls, '=');
1156     nexps = explist(ls, &e);
1157     if (nexps != nvars) {
1158       adjust_assign(ls, nvars, nexps, &e);
1159       if (nexps > nvars)
1160         ls->fs->freereg -= nexps - nvars;  /* remove extra values */
1161     }
1162     else {
1163       luaK_setoneret(ls->fs, &e);  /* close last expression */
1164       luaK_storevar(ls->fs, &lh->v, &e);
1165       return;  /* avoid default */
1166     }
1167   }
1168   init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */
1169   luaK_storevar(ls->fs, &lh->v, &e);
1170 }
1171
1172
1173 static int cond (LexState *ls) {
1174   /* cond -> exp */
1175   expdesc v;
1176   expr(ls, &v);  /* read condition */
1177   if (v.k == VNIL) v.k = VFALSE;  /* `falses' are all equal here */
1178   luaK_goiftrue(ls->fs, &v);
1179   return v.f;
1180 }
1181
1182
1183 static void gotostat (LexState *ls, int pc) {
1184   int line = ls->linenumber;
1185   TString *label;
1186   int g;
1187   if (testnext(ls, TK_GOTO))
1188     label = str_checkname(ls);
1189   else {
1190     luaX_next(ls);  /* skip break */
1191     label = luaS_new(ls->L, "break");
1192   }
1193   g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);
1194   findlabel(ls, g);  /* close it if label already defined */
1195 }
1196
1197
1198 /* check for repeated labels on the same block */
1199 static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
1200   int i;
1201   for (i = fs->bl->firstlabel; i < ll->n; i++) {
1202     if (luaS_eqstr(label, ll->arr[i].name)) {
1203       const char *msg = luaO_pushfstring(fs->ls->L,
1204                           "label " LUA_QS " already defined on line %d",
1205                           getstr(label), ll->arr[i].line);
1206       semerror(fs->ls, msg);
1207     }
1208   }
1209 }
1210
1211
1212 /* skip no-op statements */
1213 static void skipnoopstat (LexState *ls) {
1214   while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
1215     statement(ls);
1216 }
1217
1218
1219 static void labelstat (LexState *ls, TString *label, int line) {
1220   /* label -> '::' NAME '::' */
1221   FuncState *fs = ls->fs;
1222   Labellist *ll = &ls->dyd->label;
1223   int l;  /* index of new label being created */
1224   checkrepeated(fs, ll, label);  /* check for repeated labels */
1225   checknext(ls, TK_DBCOLON);  /* skip double colon */
1226   /* create new entry for this label */
1227   l = newlabelentry(ls, ll, label, line, fs->pc);
1228   skipnoopstat(ls);  /* skip other no-op statements */
1229   if (block_follow(ls, 0)) {  /* label is last no-op statement in the block? */
1230     /* assume that locals are already out of scope */
1231     ll->arr[l].nactvar = fs->bl->nactvar;
1232   }
1233   findgotos(ls, &ll->arr[l]);
1234 }
1235
1236
1237 static void whilestat (LexState *ls, int line) {
1238   /* whilestat -> WHILE cond DO block END */
1239   FuncState *fs = ls->fs;
1240   int whileinit;
1241   int condexit;
1242   BlockCnt bl;
1243   luaX_next(ls);  /* skip WHILE */
1244   whileinit = luaK_getlabel(fs);
1245   condexit = cond(ls);
1246   enterblock(fs, &bl, 1);
1247   checknext(ls, TK_DO);
1248   block(ls);
1249   luaK_jumpto(fs, whileinit);
1250   check_match(ls, TK_END, TK_WHILE, line);
1251   leaveblock(fs);
1252   luaK_patchtohere(fs, condexit);  /* false conditions finish the loop */
1253 }
1254
1255
1256 static void repeatstat (LexState *ls, int line) {
1257   /* repeatstat -> REPEAT block UNTIL cond */
1258   int condexit;
1259   FuncState *fs = ls->fs;
1260   int repeat_init = luaK_getlabel(fs);
1261   BlockCnt bl1, bl2;
1262   enterblock(fs, &bl1, 1);  /* loop block */
1263   enterblock(fs, &bl2, 0);  /* scope block */
1264   luaX_next(ls);  /* skip REPEAT */
1265   statlist(ls);
1266   check_match(ls, TK_UNTIL, TK_REPEAT, line);
1267   condexit = cond(ls);  /* read condition (inside scope block) */
1268   if (bl2.upval)  /* upvalues? */
1269     luaK_patchclose(fs, condexit, bl2.nactvar);
1270   leaveblock(fs);  /* finish scope */
1271   luaK_patchlist(fs, condexit, repeat_init);  /* close the loop */
1272   leaveblock(fs);  /* finish loop */
1273 }
1274
1275
1276 static int exp1 (LexState *ls) {
1277   expdesc e;
1278   int reg;
1279   expr(ls, &e);
1280   luaK_exp2nextreg(ls->fs, &e);
1281   lua_assert(e.k == VNONRELOC);
1282   reg = e.u.info;
1283   return reg;
1284 }
1285
1286
1287 static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1288   /* forbody -> DO block */
1289   BlockCnt bl;
1290   FuncState *fs = ls->fs;
1291   int prep, endfor;
1292   adjustlocalvars(ls, 3);  /* control variables */
1293   checknext(ls, TK_DO);
1294   prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1295   enterblock(fs, &bl, 0);  /* scope for declared variables */
1296   adjustlocalvars(ls, nvars);
1297   luaK_reserveregs(fs, nvars);
1298   block(ls);
1299   leaveblock(fs);  /* end of scope for declared variables */
1300   luaK_patchtohere(fs, prep);
1301   if (isnum)  /* numeric for? */
1302     endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
1303   else {  /* generic for */
1304     luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
1305     luaK_fixline(fs, line);
1306     endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
1307   }
1308   luaK_patchlist(fs, endfor, prep + 1);
1309   luaK_fixline(fs, line);
1310 }
1311
1312
1313 static void fornum (LexState *ls, TString *varname, int line) {
1314   /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1315   FuncState *fs = ls->fs;
1316   int base = fs->freereg;
1317   new_localvarliteral(ls, "(for index)");
1318   new_localvarliteral(ls, "(for limit)");
1319   new_localvarliteral(ls, "(for step)");
1320   new_localvar(ls, varname);
1321   checknext(ls, '=');
1322   exp1(ls);  /* initial value */
1323   checknext(ls, ',');
1324   exp1(ls);  /* limit */
1325   if (testnext(ls, ','))
1326     exp1(ls);  /* optional step */
1327   else {  /* default step = 1 */
1328     luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1));
1329     luaK_reserveregs(fs, 1);
1330   }
1331   forbody(ls, base, line, 1, 1);
1332 }
1333
1334
1335 static void forlist (LexState *ls, TString *indexname) {
1336   /* forlist -> NAME {,NAME} IN explist forbody */
1337   FuncState *fs = ls->fs;
1338   expdesc e;
1339   int nvars = 4;  /* gen, state, control, plus at least one declared var */
1340   int line;
1341   int base = fs->freereg;
1342   /* create control variables */
1343   new_localvarliteral(ls, "(for generator)");
1344   new_localvarliteral(ls, "(for state)");
1345   new_localvarliteral(ls, "(for control)");
1346   /* create declared variables */
1347   new_localvar(ls, indexname);
1348   while (testnext(ls, ',')) {
1349     new_localvar(ls, str_checkname(ls));
1350     nvars++;
1351   }
1352   checknext(ls, TK_IN);
1353   line = ls->linenumber;
1354   adjust_assign(ls, 3, explist(ls, &e), &e);
1355   luaK_checkstack(fs, 3);  /* extra space to call generator */
1356   forbody(ls, base, line, nvars - 3, 0);
1357 }
1358
1359
1360 static void forstat (LexState *ls, int line) {
1361   /* forstat -> FOR (fornum | forlist) END */
1362   FuncState *fs = ls->fs;
1363   TString *varname;
1364   BlockCnt bl;
1365   enterblock(fs, &bl, 1);  /* scope for loop and control variables */
1366   luaX_next(ls);  /* skip `for' */
1367   varname = str_checkname(ls);  /* first variable name */
1368   switch (ls->t.token) {
1369     case '=': fornum(ls, varname, line); break;
1370     case ',': case TK_IN: forlist(ls, varname); break;
1371     default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
1372   }
1373   check_match(ls, TK_END, TK_FOR, line);
1374   leaveblock(fs);  /* loop scope (`break' jumps to this point) */
1375 }
1376
1377
1378 __attribute__((always_inline)) inline
1379 static void test_then_block (LexState *ls, int *escapelist) {
1380   /* test_then_block -> [IF | ELSEIF] cond THEN block */
1381   BlockCnt bl;
1382   FuncState *fs = ls->fs;
1383   expdesc v;
1384   int jf;  /* instruction to skip 'then' code (if condition is false) */
1385   luaX_next(ls);  /* skip IF or ELSEIF */
1386   expr(ls, &v);  /* read condition */
1387   checknext(ls, TK_THEN);
1388   if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
1389     luaK_goiffalse(ls->fs, &v);  /* will jump to label if condition is true */
1390     enterblock(fs, &bl, 0);  /* must enter block before 'goto' */
1391     gotostat(ls, v.t);  /* handle goto/break */
1392     skipnoopstat(ls);  /* skip other no-op statements */
1393     if (block_follow(ls, 0)) {  /* 'goto' is the entire block? */
1394       leaveblock(fs);
1395       return;  /* and that is it */
1396     }
1397     else  /* must skip over 'then' part if condition is false */
1398       jf = luaK_jump(fs);
1399   }
1400   else {  /* regular case (not goto/break) */
1401     luaK_goiftrue(ls->fs, &v);  /* skip over block if condition is false */
1402     enterblock(fs, &bl, 0);
1403     jf = v.f;
1404   }
1405   statlist(ls);  /* `then' part */
1406   leaveblock(fs);
1407   if (ls->t.token == TK_ELSE ||
1408       ls->t.token == TK_ELSEIF)  /* followed by 'else'/'elseif'? */
1409     luaK_concat(fs, escapelist, luaK_jump(fs));  /* must jump over it */
1410   luaK_patchtohere(fs, jf);
1411 }
1412
1413
1414 static void ifstat (LexState *ls, int line) {
1415   /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1416   FuncState *fs = ls->fs;
1417   int escapelist = NO_JUMP;  /* exit list for finished parts */
1418   test_then_block(ls, &escapelist);  /* IF cond THEN block */
1419   while (ls->t.token == TK_ELSEIF)
1420     test_then_block(ls, &escapelist);  /* ELSEIF cond THEN block */
1421   if (testnext(ls, TK_ELSE))
1422     block(ls);  /* `else' part */
1423   check_match(ls, TK_END, TK_IF, line);
1424   luaK_patchtohere(fs, escapelist);  /* patch escape list to 'if' end */
1425 }
1426
1427
1428 static void localfunc (LexState *ls) {
1429   expdesc b;
1430   FuncState *fs = ls->fs;
1431   new_localvar(ls, str_checkname(ls));  /* new local variable */
1432   adjustlocalvars(ls, 1);  /* enter its scope */
1433   body(ls, &b, 0, ls->linenumber);  /* function created in next register */
1434   /* debug information will only see the variable after this point! */
1435   getlocvar(fs, b.u.info)->startpc = fs->pc;
1436 }
1437
1438
1439 static void localstat (LexState *ls) {
1440   /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
1441   int nvars = 0;
1442   int nexps;
1443   expdesc e;
1444   do {
1445     new_localvar(ls, str_checkname(ls));
1446     nvars++;
1447   } while (testnext(ls, ','));
1448   if (testnext(ls, '='))
1449     nexps = explist(ls, &e);
1450   else {
1451     e.k = VVOID;
1452     nexps = 0;
1453   }
1454   adjust_assign(ls, nvars, nexps, &e);
1455   adjustlocalvars(ls, nvars);
1456 }
1457
1458
1459 static int funcname (LexState *ls, expdesc *v) {
1460   /* funcname -> NAME {fieldsel} [`:' NAME] */
1461   int ismethod = 0;
1462   singlevar(ls, v);
1463   while (ls->t.token == '.')
1464     fieldsel(ls, v);
1465   if (ls->t.token == ':') {
1466     ismethod = 1;
1467     fieldsel(ls, v);
1468   }
1469   return ismethod;
1470 }
1471
1472
1473 static void funcstat (LexState *ls, int line) {
1474   /* funcstat -> FUNCTION funcname body */
1475   int ismethod;
1476   expdesc v, b;
1477   luaX_next(ls);  /* skip FUNCTION */
1478   ismethod = funcname(ls, &v);
1479   body(ls, &b, ismethod, line);
1480   luaK_storevar(ls->fs, &v, &b);
1481   luaK_fixline(ls->fs, line);  /* definition `happens' in the first line */
1482 }
1483
1484
1485 static void exprstat (LexState *ls) {
1486   /* stat -> func | assignment */
1487   FuncState *fs = ls->fs;
1488   struct LHS_assign v;
1489   suffixedexp(ls, &v.v);
1490   if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
1491     v.prev = NULL;
1492     assignment(ls, &v, 1);
1493   }
1494   else {  /* stat -> func */
1495     check_condition(ls, v.v.k == VCALL, "syntax error");
1496     SETARG_C(getcode(fs, &v.v), 1);  /* call statement uses no results */
1497   }
1498 }
1499
1500
1501 static void retstat (LexState *ls) {
1502   /* stat -> RETURN [explist] [';'] */
1503   FuncState *fs = ls->fs;
1504   expdesc e;
1505   int first, nret;  /* registers with returned values */
1506   if (block_follow(ls, 1) || ls->t.token == ';')
1507     first = nret = 0;  /* return no values */
1508   else {
1509     nret = explist(ls, &e);  /* optional return values */
1510     if (hasmultret(e.k)) {
1511       luaK_setmultret(fs, &e);
1512       if (e.k == VCALL && nret == 1) {  /* tail call? */
1513         SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1514         lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1515       }
1516       first = fs->nactvar;
1517       nret = LUA_MULTRET;  /* return all values */
1518     }
1519     else {
1520       if (nret == 1)  /* only one single value? */
1521         first = luaK_exp2anyreg(fs, &e);
1522       else {
1523         luaK_exp2nextreg(fs, &e);  /* values must go to the `stack' */
1524         first = fs->nactvar;  /* return all `active' values */
1525         lua_assert(nret == fs->freereg - first);
1526       }
1527     }
1528   }
1529   luaK_ret(fs, first, nret);
1530   (void) testnext(ls, ';');  /* skip optional semicolon */
1531 }
1532
1533
1534 static void statement (LexState *ls) {
1535   int line = ls->linenumber;  /* may be needed for error messages */
1536   enterlevel(ls);
1537   switch (ls->t.token) {
1538     case ';': {  /* stat -> ';' (empty statement) */
1539       luaX_next(ls);  /* skip ';' */
1540       break;
1541     }
1542     case TK_IF: {  /* stat -> ifstat */
1543       ifstat(ls, line);
1544       break;
1545     }
1546     case TK_WHILE: {  /* stat -> whilestat */
1547       whilestat(ls, line);
1548       break;
1549     }
1550     case TK_DO: {  /* stat -> DO block END */
1551       luaX_next(ls);  /* skip DO */
1552       block(ls);
1553       check_match(ls, TK_END, TK_DO, line);
1554       break;
1555     }
1556     case TK_FOR: {  /* stat -> forstat */
1557       forstat(ls, line);
1558       break;
1559     }
1560     case TK_REPEAT: {  /* stat -> repeatstat */
1561       repeatstat(ls, line);
1562       break;
1563     }
1564     case TK_FUNCTION: {  /* stat -> funcstat */
1565       funcstat(ls, line);
1566       break;
1567     }
1568     case TK_LOCAL: {  /* stat -> localstat */
1569       luaX_next(ls);  /* skip LOCAL */
1570       if (testnext(ls, TK_FUNCTION))  /* local function? */
1571         localfunc(ls);
1572       else
1573         localstat(ls);
1574       break;
1575     }
1576     case TK_DBCOLON: {  /* stat -> label */
1577       luaX_next(ls);  /* skip double colon */
1578       labelstat(ls, str_checkname(ls), line);
1579       break;
1580     }
1581     case TK_RETURN: {  /* stat -> retstat */
1582       luaX_next(ls);  /* skip RETURN */
1583       retstat(ls);
1584       break;
1585     }
1586     case TK_BREAK:   /* stat -> breakstat */
1587     case TK_GOTO: {  /* stat -> 'goto' NAME */
1588       gotostat(ls, luaK_jump(ls->fs));
1589       break;
1590     }
1591     default: {  /* stat -> func | assignment */
1592       exprstat(ls);
1593       break;
1594     }
1595   }
1596   lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1597              ls->fs->freereg >= ls->fs->nactvar);
1598   ls->fs->freereg = ls->fs->nactvar;  /* free registers */
1599   leavelevel(ls);
1600 }
1601
1602 /* }====================================================================== */
1603
1604
1605 /*
1606 ** compiles the main function, which is a regular vararg function with an
1607 ** upvalue named LUA_ENV
1608 */
1609 static void mainfunc (LexState *ls, FuncState *fs) {
1610   BlockCnt bl;
1611   expdesc v;
1612   open_func(ls, fs, &bl);
1613   fs->f->is_vararg = 1;  /* main function is always vararg */
1614   init_exp(&v, VLOCAL, 0);  /* create and... */
1615   newupvalue(fs, ls->envn, &v);  /* ...set environment upvalue */
1616   luaX_next(ls);  /* read first token */
1617   statlist(ls);  /* parse main body */
1618   check(ls, TK_EOS);
1619   close_func(ls);
1620 }
1621
1622
1623 Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1624                       Dyndata *dyd, const char *name, int firstchar) {
1625   LexState lexstate;
1626   FuncState funcstate;
1627   Closure *cl = luaF_newLclosure(L, 1);  /* create main closure */
1628   /* anchor closure (to avoid being collected) */
1629   setclLvalue(L, L->top, cl);
1630   incr_top(L);
1631   funcstate.f = cl->l.p = luaF_newproto(L);
1632   funcstate.f->source = luaS_new(L, name);  /* create and anchor TString */
1633   lexstate.buff = buff;
1634   lexstate.dyd = dyd;
1635   dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
1636   luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
1637   mainfunc(&lexstate, &funcstate);
1638   lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
1639   /* all scopes should be correctly finished */
1640   lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
1641   return cl;  /* it's on the stack too */
1642 }
1643 /* END CSTYLED */