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