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