lua

A copy of the Lua development repository
Log | Files | Refs | README

lparser.c (57937B)


      1 /*
      2 ** $Id: lparser.c $
      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 <limits.h>
     14 #include <string.h>
     15 
     16 #include "lua.h"
     17 
     18 #include "lcode.h"
     19 #include "ldebug.h"
     20 #include "ldo.h"
     21 #include "lfunc.h"
     22 #include "llex.h"
     23 #include "lmem.h"
     24 #include "lobject.h"
     25 #include "lopcodes.h"
     26 #include "lparser.h"
     27 #include "lstate.h"
     28 #include "lstring.h"
     29 #include "ltable.h"
     30 
     31 
     32 
     33 /* maximum number of local variables per function (must be smaller
     34    than 250, due to the bytecode format) */
     35 #define MAXVARS		200
     36 
     37 
     38 #define hasmultret(k)		((k) == VCALL || (k) == VVARARG)
     39 
     40 
     41 /* because all strings are unified by the scanner, the parser
     42    can use pointer equality for string equality */
     43 #define eqstr(a,b)	((a) == (b))
     44 
     45 
     46 /*
     47 ** nodes for block list (list of active blocks)
     48 */
     49 typedef struct BlockCnt {
     50   struct BlockCnt *previous;  /* chain */
     51   int firstlabel;  /* index of first label in this block */
     52   int firstgoto;  /* index of first pending goto in this block */
     53   lu_byte nactvar;  /* # active locals outside the block */
     54   lu_byte upval;  /* true if some variable in the block is an upvalue */
     55   lu_byte isloop;  /* 1 if 'block' is a loop; 2 if it has pending breaks */
     56   lu_byte insidetbc;  /* true if inside the scope of a to-be-closed var. */
     57 } BlockCnt;
     58 
     59 
     60 
     61 /*
     62 ** prototypes for recursive non-terminal functions
     63 */
     64 static void statement (LexState *ls);
     65 static void expr (LexState *ls, expdesc *v);
     66 
     67 
     68 static l_noret error_expected (LexState *ls, int token) {
     69   luaX_syntaxerror(ls,
     70       luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
     71 }
     72 
     73 
     74 static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
     75   lua_State *L = fs->ls->L;
     76   const char *msg;
     77   int line = fs->f->linedefined;
     78   const char *where = (line == 0)
     79                       ? "main function"
     80                       : luaO_pushfstring(L, "function at line %d", line);
     81   msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
     82                              what, limit, where);
     83   luaX_syntaxerror(fs->ls, msg);
     84 }
     85 
     86 
     87 void luaY_checklimit (FuncState *fs, int v, int l, const char *what) {
     88   if (l_unlikely(v > l)) errorlimit(fs, l, what);
     89 }
     90 
     91 
     92 /*
     93 ** Test whether next token is 'c'; if so, skip it.
     94 */
     95 static int testnext (LexState *ls, int c) {
     96   if (ls->t.token == c) {
     97     luaX_next(ls);
     98     return 1;
     99   }
    100   else return 0;
    101 }
    102 
    103 
    104 /*
    105 ** Check that next token is 'c'.
    106 */
    107 static void check (LexState *ls, int c) {
    108   if (ls->t.token != c)
    109     error_expected(ls, c);
    110 }
    111 
    112 
    113 /*
    114 ** Check that next token is 'c' and skip it.
    115 */
    116 static void checknext (LexState *ls, int c) {
    117   check(ls, c);
    118   luaX_next(ls);
    119 }
    120 
    121 
    122 #define check_condition(ls,c,msg)	{ if (!(c)) luaX_syntaxerror(ls, msg); }
    123 
    124 
    125 /*
    126 ** Check that next token is 'what' and skip it. In case of error,
    127 ** raise an error that the expected 'what' should match a 'who'
    128 ** in line 'where' (if that is not the current line).
    129 */
    130 static void check_match (LexState *ls, int what, int who, int where) {
    131   if (l_unlikely(!testnext(ls, what))) {
    132     if (where == ls->linenumber)  /* all in the same line? */
    133       error_expected(ls, what);  /* do not need a complex message */
    134     else {
    135       luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
    136              "%s expected (to close %s at line %d)",
    137               luaX_token2str(ls, what), luaX_token2str(ls, who), where));
    138     }
    139   }
    140 }
    141 
    142 
    143 static TString *str_checkname (LexState *ls) {
    144   TString *ts;
    145   check(ls, TK_NAME);
    146   ts = ls->t.seminfo.ts;
    147   luaX_next(ls);
    148   return ts;
    149 }
    150 
    151 
    152 static void init_exp (expdesc *e, expkind k, int i) {
    153   e->f = e->t = NO_JUMP;
    154   e->k = k;
    155   e->u.info = i;
    156 }
    157 
    158 
    159 static void codestring (expdesc *e, TString *s) {
    160   e->f = e->t = NO_JUMP;
    161   e->k = VKSTR;
    162   e->u.strval = s;
    163 }
    164 
    165 
    166 static void codename (LexState *ls, expdesc *e) {
    167   codestring(e, str_checkname(ls));
    168 }
    169 
    170 
    171 /*
    172 ** Register a new local variable in the active 'Proto' (for debug
    173 ** information).
    174 */
    175 static short registerlocalvar (LexState *ls, FuncState *fs,
    176                                TString *varname) {
    177   Proto *f = fs->f;
    178   int oldsize = f->sizelocvars;
    179   luaM_growvector(ls->L, f->locvars, fs->ndebugvars, f->sizelocvars,
    180                   LocVar, SHRT_MAX, "local variables");
    181   while (oldsize < f->sizelocvars)
    182     f->locvars[oldsize++].varname = NULL;
    183   f->locvars[fs->ndebugvars].varname = varname;
    184   f->locvars[fs->ndebugvars].startpc = fs->pc;
    185   luaC_objbarrier(ls->L, f, varname);
    186   return fs->ndebugvars++;
    187 }
    188 
    189 
    190 /*
    191 ** Create a new local variable with the given 'name' and given 'kind'.
    192 ** Return its index in the function.
    193 */
    194 static int new_localvarkind (LexState *ls, TString *name, lu_byte kind) {
    195   lua_State *L = ls->L;
    196   FuncState *fs = ls->fs;
    197   Dyndata *dyd = ls->dyd;
    198   Vardesc *var;
    199   luaY_checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
    200                  MAXVARS, "local variables");
    201   luaM_growvector(L, dyd->actvar.arr, dyd->actvar.n + 1,
    202                   dyd->actvar.size, Vardesc, SHRT_MAX, "local variables");
    203   var = &dyd->actvar.arr[dyd->actvar.n++];
    204   var->vd.kind = kind;  /* default */
    205   var->vd.name = name;
    206   return dyd->actvar.n - 1 - fs->firstlocal;
    207 }
    208 
    209 
    210 /*
    211 ** Create a new local variable with the given 'name' and regular kind.
    212 */
    213 static int new_localvar (LexState *ls, TString *name) {
    214   return new_localvarkind(ls, name, VDKREG);
    215 }
    216 
    217 #define new_localvarliteral(ls,v) \
    218     new_localvar(ls,  \
    219       luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1));
    220 
    221 
    222 
    223 /*
    224 ** Return the "variable description" (Vardesc) of a given variable.
    225 ** (Unless noted otherwise, all variables are referred to by their
    226 ** compiler indices.)
    227 */
    228 static Vardesc *getlocalvardesc (FuncState *fs, int vidx) {
    229   return &fs->ls->dyd->actvar.arr[fs->firstlocal + vidx];
    230 }
    231 
    232 
    233 /*
    234 ** Convert 'nvar', a compiler index level, to its corresponding
    235 ** register. For that, search for the highest variable below that level
    236 ** that is in a register and uses its register index ('ridx') plus one.
    237 */
    238 static lu_byte reglevel (FuncState *fs, int nvar) {
    239   while (nvar-- > 0) {
    240     Vardesc *vd = getlocalvardesc(fs, nvar);  /* get previous variable */
    241     if (vd->vd.kind != RDKCTC)  /* is in a register? */
    242       return cast_byte(vd->vd.ridx + 1);
    243   }
    244   return 0;  /* no variables in registers */
    245 }
    246 
    247 
    248 /*
    249 ** Return the number of variables in the register stack for the given
    250 ** function.
    251 */
    252 lu_byte luaY_nvarstack (FuncState *fs) {
    253   return reglevel(fs, fs->nactvar);
    254 }
    255 
    256 
    257 /*
    258 ** Get the debug-information entry for current variable 'vidx'.
    259 */
    260 static LocVar *localdebuginfo (FuncState *fs, int vidx) {
    261   Vardesc *vd = getlocalvardesc(fs,  vidx);
    262   if (vd->vd.kind == RDKCTC)
    263     return NULL;  /* no debug info. for constants */
    264   else {
    265     int idx = vd->vd.pidx;
    266     lua_assert(idx < fs->ndebugvars);
    267     return &fs->f->locvars[idx];
    268   }
    269 }
    270 
    271 
    272 /*
    273 ** Create an expression representing variable 'vidx'
    274 */
    275 static void init_var (FuncState *fs, expdesc *e, int vidx) {
    276   e->f = e->t = NO_JUMP;
    277   e->k = VLOCAL;
    278   e->u.var.vidx = cast(unsigned short, vidx);
    279   e->u.var.ridx = getlocalvardesc(fs, vidx)->vd.ridx;
    280 }
    281 
    282 
    283 /*
    284 ** Raises an error if variable described by 'e' is read only
    285 */
    286 static void check_readonly (LexState *ls, expdesc *e) {
    287   FuncState *fs = ls->fs;
    288   TString *varname = NULL;  /* to be set if variable is const */
    289   switch (e->k) {
    290     case VCONST: {
    291       varname = ls->dyd->actvar.arr[e->u.info].vd.name;
    292       break;
    293     }
    294     case VLOCAL: {
    295       Vardesc *vardesc = getlocalvardesc(fs, e->u.var.vidx);
    296       if (vardesc->vd.kind != VDKREG)  /* not a regular variable? */
    297         varname = vardesc->vd.name;
    298       break;
    299     }
    300     case VUPVAL: {
    301       Upvaldesc *up = &fs->f->upvalues[e->u.info];
    302       if (up->kind != VDKREG)
    303         varname = up->name;
    304       break;
    305     }
    306     default:
    307       return;  /* other cases cannot be read-only */
    308   }
    309   if (varname) {
    310     const char *msg = luaO_pushfstring(ls->L,
    311        "attempt to assign to const variable '%s'", getstr(varname));
    312     luaK_semerror(ls, msg);  /* error */
    313   }
    314 }
    315 
    316 
    317 /*
    318 ** Start the scope for the last 'nvars' created variables.
    319 */
    320 static void adjustlocalvars (LexState *ls, int nvars) {
    321   FuncState *fs = ls->fs;
    322   int reglevel = luaY_nvarstack(fs);
    323   int i;
    324   for (i = 0; i < nvars; i++) {
    325     int vidx = fs->nactvar++;
    326     Vardesc *var = getlocalvardesc(fs, vidx);
    327     var->vd.ridx = cast_byte(reglevel++);
    328     var->vd.pidx = registerlocalvar(ls, fs, var->vd.name);
    329   }
    330 }
    331 
    332 
    333 /*
    334 ** Close the scope for all variables up to level 'tolevel'.
    335 ** (debug info.)
    336 */
    337 static void removevars (FuncState *fs, int tolevel) {
    338   fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
    339   while (fs->nactvar > tolevel) {
    340     LocVar *var = localdebuginfo(fs, --fs->nactvar);
    341     if (var)  /* does it have debug information? */
    342       var->endpc = fs->pc;
    343   }
    344 }
    345 
    346 
    347 /*
    348 ** Search the upvalues of the function 'fs' for one
    349 ** with the given 'name'.
    350 */
    351 static int searchupvalue (FuncState *fs, TString *name) {
    352   int i;
    353   Upvaldesc *up = fs->f->upvalues;
    354   for (i = 0; i < fs->nups; i++) {
    355     if (eqstr(up[i].name, name)) return i;
    356   }
    357   return -1;  /* not found */
    358 }
    359 
    360 
    361 static Upvaldesc *allocupvalue (FuncState *fs) {
    362   Proto *f = fs->f;
    363   int oldsize = f->sizeupvalues;
    364   luaY_checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
    365   luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
    366                   Upvaldesc, MAXUPVAL, "upvalues");
    367   while (oldsize < f->sizeupvalues)
    368     f->upvalues[oldsize++].name = NULL;
    369   return &f->upvalues[fs->nups++];
    370 }
    371 
    372 
    373 static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
    374   Upvaldesc *up = allocupvalue(fs);
    375   FuncState *prev = fs->prev;
    376   if (v->k == VLOCAL) {
    377     up->instack = 1;
    378     up->idx = v->u.var.ridx;
    379     up->kind = getlocalvardesc(prev, v->u.var.vidx)->vd.kind;
    380     lua_assert(eqstr(name, getlocalvardesc(prev, v->u.var.vidx)->vd.name));
    381   }
    382   else {
    383     up->instack = 0;
    384     up->idx = cast_byte(v->u.info);
    385     up->kind = prev->f->upvalues[v->u.info].kind;
    386     lua_assert(eqstr(name, prev->f->upvalues[v->u.info].name));
    387   }
    388   up->name = name;
    389   luaC_objbarrier(fs->ls->L, fs->f, name);
    390   return fs->nups - 1;
    391 }
    392 
    393 
    394 /*
    395 ** Look for an active local variable with the name 'n' in the
    396 ** function 'fs'. If found, initialize 'var' with it and return
    397 ** its expression kind; otherwise return -1.
    398 */
    399 static int searchvar (FuncState *fs, TString *n, expdesc *var) {
    400   int i;
    401   for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
    402     Vardesc *vd = getlocalvardesc(fs, i);
    403     if (eqstr(n, vd->vd.name)) {  /* found? */
    404       if (vd->vd.kind == RDKCTC)  /* compile-time constant? */
    405         init_exp(var, VCONST, fs->firstlocal + i);
    406       else  /* real variable */
    407         init_var(fs, var, i);
    408       return cast_int(var->k);
    409     }
    410   }
    411   return -1;  /* not found */
    412 }
    413 
    414 
    415 /*
    416 ** Mark block where variable at given level was defined
    417 ** (to emit close instructions later).
    418 */
    419 static void markupval (FuncState *fs, int level) {
    420   BlockCnt *bl = fs->bl;
    421   while (bl->nactvar > level)
    422     bl = bl->previous;
    423   bl->upval = 1;
    424   fs->needclose = 1;
    425 }
    426 
    427 
    428 /*
    429 ** Mark that current block has a to-be-closed variable.
    430 */
    431 static void marktobeclosed (FuncState *fs) {
    432   BlockCnt *bl = fs->bl;
    433   bl->upval = 1;
    434   bl->insidetbc = 1;
    435   fs->needclose = 1;
    436 }
    437 
    438 
    439 /*
    440 ** Find a variable with the given name 'n'. If it is an upvalue, add
    441 ** this upvalue into all intermediate functions. If it is a global, set
    442 ** 'var' as 'void' as a flag.
    443 */
    444 static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
    445   if (fs == NULL)  /* no more levels? */
    446     init_exp(var, VVOID, 0);  /* default is global */
    447   else {
    448     int v = searchvar(fs, n, var);  /* look up locals at current level */
    449     if (v >= 0) {  /* found? */
    450       if (v == VLOCAL && !base)
    451         markupval(fs, var->u.var.vidx);  /* local will be used as an upval */
    452     }
    453     else {  /* not found as local at current level; try upvalues */
    454       int idx = searchupvalue(fs, n);  /* try existing upvalues */
    455       if (idx < 0) {  /* not found? */
    456         singlevaraux(fs->prev, n, var, 0);  /* try upper levels */
    457         if (var->k == VLOCAL || var->k == VUPVAL)  /* local or upvalue? */
    458           idx  = newupvalue(fs, n, var);  /* will be a new upvalue */
    459         else  /* it is a global or a constant */
    460           return;  /* don't need to do anything at this level */
    461       }
    462       init_exp(var, VUPVAL, idx);  /* new or old upvalue */
    463     }
    464   }
    465 }
    466 
    467 
    468 /*
    469 ** Find a variable with the given name 'n', handling global variables
    470 ** too.
    471 */
    472 static void singlevar (LexState *ls, expdesc *var) {
    473   TString *varname = str_checkname(ls);
    474   FuncState *fs = ls->fs;
    475   singlevaraux(fs, varname, var, 1);
    476   if (var->k == VVOID) {  /* global name? */
    477     expdesc key;
    478     singlevaraux(fs, ls->envn, var, 1);  /* get environment variable */
    479     lua_assert(var->k != VVOID);  /* this one must exist */
    480     luaK_exp2anyregup(fs, var);  /* but could be a constant */
    481     codestring(&key, varname);  /* key is variable name */
    482     luaK_indexed(fs, var, &key);  /* env[varname] */
    483   }
    484 }
    485 
    486 
    487 /*
    488 ** Adjust the number of results from an expression list 'e' with 'nexps'
    489 ** expressions to 'nvars' values.
    490 */
    491 static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
    492   FuncState *fs = ls->fs;
    493   int needed = nvars - nexps;  /* extra values needed */
    494   if (hasmultret(e->k)) {  /* last expression has multiple returns? */
    495     int extra = needed + 1;  /* discount last expression itself */
    496     if (extra < 0)
    497       extra = 0;
    498     luaK_setreturns(fs, e, extra);  /* last exp. provides the difference */
    499   }
    500   else {
    501     if (e->k != VVOID)  /* at least one expression? */
    502       luaK_exp2nextreg(fs, e);  /* close last expression */
    503     if (needed > 0)  /* missing values? */
    504       luaK_nil(fs, fs->freereg, needed);  /* complete with nils */
    505   }
    506   if (needed > 0)
    507     luaK_reserveregs(fs, needed);  /* registers for extra values */
    508   else  /* adding 'needed' is actually a subtraction */
    509     fs->freereg = cast_byte(fs->freereg + needed);  /* remove extra values */
    510 }
    511 
    512 
    513 #define enterlevel(ls)	luaE_incCstack(ls->L)
    514 
    515 
    516 #define leavelevel(ls) ((ls)->L->nCcalls--)
    517 
    518 
    519 /*
    520 ** Generates an error that a goto jumps into the scope of some
    521 ** local variable.
    522 */
    523 static l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) {
    524   TString *tsname = getlocalvardesc(ls->fs, gt->nactvar)->vd.name;
    525   const char *varname = getstr(tsname);
    526   const char *msg = "<goto %s> at line %d jumps into the scope of local '%s'";
    527   msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line, varname);
    528   luaK_semerror(ls, msg);  /* raise the error */
    529 }
    530 
    531 
    532 /*
    533 ** Closes the goto at index 'g' to given 'label' and removes it
    534 ** from the list of pending gotos.
    535 ** If it jumps into the scope of some variable, raises an error.
    536 ** The goto needs a CLOSE if it jumps out of a block with upvalues,
    537 ** or out of the scope of some variable and the block has upvalues
    538 ** (signaled by parameter 'bup').
    539 */
    540 static void closegoto (LexState *ls, int g, Labeldesc *label, int bup) {
    541   int i;
    542   FuncState *fs = ls->fs;
    543   Labellist *gl = &ls->dyd->gt;  /* list of gotos */
    544   Labeldesc *gt = &gl->arr[g];  /* goto to be resolved */
    545   lua_assert(eqstr(gt->name, label->name));
    546   if (l_unlikely(gt->nactvar < label->nactvar))  /* enter some scope? */
    547     jumpscopeerror(ls, gt);
    548   if (gt->close ||
    549       (label->nactvar < gt->nactvar && bup)) {  /* needs close? */
    550     lu_byte stklevel = reglevel(fs, label->nactvar);
    551     /* move jump to CLOSE position */
    552     fs->f->code[gt->pc + 1] = fs->f->code[gt->pc];
    553     /* put CLOSE instruction at original position */
    554     fs->f->code[gt->pc] = CREATE_ABCk(OP_CLOSE, stklevel, 0, 0, 0);
    555     gt->pc++;  /* must point to jump instruction */
    556   }
    557   luaK_patchlist(ls->fs, gt->pc, label->pc);  /* goto jumps to label */
    558   for (i = g; i < gl->n - 1; i++)  /* remove goto from pending list */
    559     gl->arr[i] = gl->arr[i + 1];
    560   gl->n--;
    561 }
    562 
    563 
    564 /*
    565 ** Search for an active label with the given name, starting at
    566 ** index 'ilb' (so that it can searh for all labels in current block
    567 ** or all labels in current function).
    568 */
    569 static Labeldesc *findlabel (LexState *ls, TString *name, int ilb) {
    570   Dyndata *dyd = ls->dyd;
    571   for (; ilb < dyd->label.n; ilb++) {
    572     Labeldesc *lb = &dyd->label.arr[ilb];
    573     if (eqstr(lb->name, name))  /* correct label? */
    574       return lb;
    575   }
    576   return NULL;  /* label not found */
    577 }
    578 
    579 
    580 /*
    581 ** Adds a new label/goto in the corresponding list.
    582 */
    583 static int newlabelentry (LexState *ls, Labellist *l, TString *name,
    584                           int line, int pc) {
    585   int n = l->n;
    586   luaM_growvector(ls->L, l->arr, n, l->size,
    587                   Labeldesc, SHRT_MAX, "labels/gotos");
    588   l->arr[n].name = name;
    589   l->arr[n].line = line;
    590   l->arr[n].nactvar = ls->fs->nactvar;
    591   l->arr[n].close = 0;
    592   l->arr[n].pc = pc;
    593   l->n = n + 1;
    594   return n;
    595 }
    596 
    597 
    598 /*
    599 ** Create an entry for the goto and the code for it. As it is not known
    600 ** at this point whether the goto may need a CLOSE, the code has a jump
    601 ** followed by an CLOSE. (As the CLOSE comes after the jump, it is a
    602 ** dead instruction; it works as a placeholder.) When the goto is closed
    603 ** against a label, if it needs a CLOSE, the two instructions swap
    604 ** positions, so that the CLOSE comes before the jump.
    605 */
    606 static int newgotoentry (LexState *ls, TString *name, int line) {
    607   FuncState *fs = ls->fs;
    608   int pc = luaK_jump(fs);  /* create jump */
    609   luaK_codeABC(fs, OP_CLOSE, 0, 1, 0);  /* spaceholder, marked as dead */
    610   return newlabelentry(ls, &ls->dyd->gt, name, line, pc);
    611 }
    612 
    613 
    614 /*
    615 ** Create a new label with the given 'name' at the given 'line'.
    616 ** 'last' tells whether label is the last non-op statement in its
    617 ** block. Solves all pending gotos to this new label and adds
    618 ** a close instruction if necessary.
    619 ** Returns true iff it added a close instruction.
    620 */
    621 static void createlabel (LexState *ls, TString *name, int line, int last) {
    622   FuncState *fs = ls->fs;
    623   Labellist *ll = &ls->dyd->label;
    624   int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs));
    625   if (last) {  /* label is last no-op statement in the block? */
    626     /* assume that locals are already out of scope */
    627     ll->arr[l].nactvar = fs->bl->nactvar;
    628   }
    629 }
    630 
    631 
    632 /*
    633 ** Traverse the pending goto's of the finishing block checking whether
    634 ** each match some label of that block. Those that do not match are
    635 ** "exported" to the outer block, to be solved there. In particular,
    636 ** its 'nactvar' is updated with the level of the inner block,
    637 ** as the variables of the inner block are now out of scope.
    638 */
    639 static void solvegotos (FuncState *fs, BlockCnt *bl) {
    640   LexState *ls = fs->ls;
    641   Labellist *gl = &ls->dyd->gt;
    642   int outlevel = reglevel(fs, bl->nactvar);  /* level outside the block */
    643   int igt = bl->firstgoto;  /* first goto in the finishing block */
    644   while (igt < gl->n) {   /* for each pending goto */
    645     Labeldesc *gt = &gl->arr[igt];
    646     /* search for a matching label in the current block */
    647     Labeldesc *lb = findlabel(ls, gt->name, bl->firstlabel);
    648     if (lb != NULL)  /* found a match? */
    649       closegoto(ls, igt, lb, bl->upval);  /* close and remove goto */
    650     else {  /* adjust 'goto' for outer block */
    651       /* block has variables to be closed and goto escapes the scope of
    652          some variable? */
    653       if (bl->upval && reglevel(fs, gt->nactvar) > outlevel)
    654         gt->close = 1;  /* jump may need a close */
    655       gt->nactvar = bl->nactvar;  /* correct level for outer block */
    656       igt++;  /* go to next goto */
    657     }
    658   }
    659   ls->dyd->label.n = bl->firstlabel;  /* remove local labels */
    660 }
    661 
    662 
    663 static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
    664   bl->isloop = isloop;
    665   bl->nactvar = fs->nactvar;
    666   bl->firstlabel = fs->ls->dyd->label.n;
    667   bl->firstgoto = fs->ls->dyd->gt.n;
    668   bl->upval = 0;
    669   bl->insidetbc = (fs->bl != NULL && fs->bl->insidetbc);
    670   bl->previous = fs->bl;
    671   fs->bl = bl;
    672   lua_assert(fs->freereg == luaY_nvarstack(fs));
    673 }
    674 
    675 
    676 /*
    677 ** generates an error for an undefined 'goto'.
    678 */
    679 static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
    680   const char *msg = "no visible label '%s' for <goto> at line %d";
    681   msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
    682   /* breaks are checked when created, cannot be undefined */
    683   lua_assert(!eqstr(gt->name, luaS_newliteral(ls->L, "break")));
    684   luaK_semerror(ls, msg);
    685 }
    686 
    687 
    688 static void leaveblock (FuncState *fs) {
    689   BlockCnt *bl = fs->bl;
    690   LexState *ls = fs->ls;
    691   lu_byte stklevel = reglevel(fs, bl->nactvar);  /* level outside block */
    692   if (bl->previous && bl->upval)  /* need a 'close'? */
    693     luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0);
    694   fs->freereg = stklevel;  /* free registers */
    695   removevars(fs, bl->nactvar);  /* remove block locals */
    696   lua_assert(bl->nactvar == fs->nactvar);  /* back to level on entry */
    697   if (bl->isloop == 2)  /* has to fix pending breaks? */
    698     createlabel(ls, luaS_newliteral(ls->L, "break"), 0, 0);
    699   solvegotos(fs, bl);
    700   if (bl->previous == NULL) {  /* was it the last block? */
    701     if (bl->firstgoto < ls->dyd->gt.n)  /* still pending gotos? */
    702       undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]);  /* error */
    703   }
    704   fs->bl = bl->previous;  /* current block now is previous one */
    705 }
    706 
    707 
    708 /*
    709 ** adds a new prototype into list of prototypes
    710 */
    711 static Proto *addprototype (LexState *ls) {
    712   Proto *clp;
    713   lua_State *L = ls->L;
    714   FuncState *fs = ls->fs;
    715   Proto *f = fs->f;  /* prototype of current function */
    716   if (fs->np >= f->sizep) {
    717     int oldsize = f->sizep;
    718     luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
    719     while (oldsize < f->sizep)
    720       f->p[oldsize++] = NULL;
    721   }
    722   f->p[fs->np++] = clp = luaF_newproto(L);
    723   luaC_objbarrier(L, f, clp);
    724   return clp;
    725 }
    726 
    727 
    728 /*
    729 ** codes instruction to create new closure in parent function.
    730 ** The OP_CLOSURE instruction uses the last available register,
    731 ** so that, if it invokes the GC, the GC knows which registers
    732 ** are in use at that time.
    733 
    734 */
    735 static void codeclosure (LexState *ls, expdesc *v) {
    736   FuncState *fs = ls->fs->prev;
    737   init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
    738   luaK_exp2nextreg(fs, v);  /* fix it at the last register */
    739 }
    740 
    741 
    742 static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
    743   lua_State *L = ls->L;
    744   Proto *f = fs->f;
    745   fs->prev = ls->fs;  /* linked list of funcstates */
    746   fs->ls = ls;
    747   ls->fs = fs;
    748   fs->pc = 0;
    749   fs->previousline = f->linedefined;
    750   fs->iwthabs = 0;
    751   fs->lasttarget = 0;
    752   fs->freereg = 0;
    753   fs->nk = 0;
    754   fs->nabslineinfo = 0;
    755   fs->np = 0;
    756   fs->nups = 0;
    757   fs->ndebugvars = 0;
    758   fs->nactvar = 0;
    759   fs->needclose = 0;
    760   fs->firstlocal = ls->dyd->actvar.n;
    761   fs->firstlabel = ls->dyd->label.n;
    762   fs->bl = NULL;
    763   f->source = ls->source;
    764   luaC_objbarrier(L, f, f->source);
    765   f->maxstacksize = 2;  /* registers 0/1 are always valid */
    766   fs->kcache = luaH_new(L);  /* create table for function */
    767   sethvalue2s(L, L->top.p, fs->kcache);  /* anchor it */
    768   luaD_inctop(L);
    769   enterblock(fs, bl, 0);
    770 }
    771 
    772 
    773 static void close_func (LexState *ls) {
    774   lua_State *L = ls->L;
    775   FuncState *fs = ls->fs;
    776   Proto *f = fs->f;
    777   luaK_ret(fs, luaY_nvarstack(fs), 0);  /* final return */
    778   leaveblock(fs);
    779   lua_assert(fs->bl == NULL);
    780   luaK_finish(fs);
    781   luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction);
    782   luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte);
    783   luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo,
    784                        fs->nabslineinfo, AbsLineInfo);
    785   luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue);
    786   luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *);
    787   luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar);
    788   luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
    789   ls->fs = fs->prev;
    790   L->top.p--;  /* pop kcache table */
    791   luaC_checkGC(L);
    792 }
    793 
    794 
    795 /*
    796 ** {======================================================================
    797 ** GRAMMAR RULES
    798 ** =======================================================================
    799 */
    800 
    801 
    802 /*
    803 ** check whether current token is in the follow set of a block.
    804 ** 'until' closes syntactical blocks, but do not close scope,
    805 ** so it is handled in separate.
    806 */
    807 static int block_follow (LexState *ls, int withuntil) {
    808   switch (ls->t.token) {
    809     case TK_ELSE: case TK_ELSEIF:
    810     case TK_END: case TK_EOS:
    811       return 1;
    812     case TK_UNTIL: return withuntil;
    813     default: return 0;
    814   }
    815 }
    816 
    817 
    818 static void statlist (LexState *ls) {
    819   /* statlist -> { stat [';'] } */
    820   while (!block_follow(ls, 1)) {
    821     if (ls->t.token == TK_RETURN) {
    822       statement(ls);
    823       return;  /* 'return' must be last statement */
    824     }
    825     statement(ls);
    826   }
    827 }
    828 
    829 
    830 static void fieldsel (LexState *ls, expdesc *v) {
    831   /* fieldsel -> ['.' | ':'] NAME */
    832   FuncState *fs = ls->fs;
    833   expdesc key;
    834   luaK_exp2anyregup(fs, v);
    835   luaX_next(ls);  /* skip the dot or colon */
    836   codename(ls, &key);
    837   luaK_indexed(fs, v, &key);
    838 }
    839 
    840 
    841 static void yindex (LexState *ls, expdesc *v) {
    842   /* index -> '[' expr ']' */
    843   luaX_next(ls);  /* skip the '[' */
    844   expr(ls, v);
    845   luaK_exp2val(ls->fs, v);
    846   checknext(ls, ']');
    847 }
    848 
    849 
    850 /*
    851 ** {======================================================================
    852 ** Rules for Constructors
    853 ** =======================================================================
    854 */
    855 
    856 typedef struct ConsControl {
    857   expdesc v;  /* last list item read */
    858   expdesc *t;  /* table descriptor */
    859   int nh;  /* total number of 'record' elements */
    860   int na;  /* number of array elements already stored */
    861   int tostore;  /* number of array elements pending to be stored */
    862   int maxtostore;  /* maximum number of pending elements */
    863 } ConsControl;
    864 
    865 
    866 static void recfield (LexState *ls, ConsControl *cc) {
    867   /* recfield -> (NAME | '['exp']') = exp */
    868   FuncState *fs = ls->fs;
    869   lu_byte reg = ls->fs->freereg;
    870   expdesc tab, key, val;
    871   if (ls->t.token == TK_NAME) {
    872     luaY_checklimit(fs, cc->nh, INT_MAX / 2, "items in a constructor");
    873     codename(ls, &key);
    874   }
    875   else  /* ls->t.token == '[' */
    876     yindex(ls, &key);
    877   cc->nh++;
    878   checknext(ls, '=');
    879   tab = *cc->t;
    880   luaK_indexed(fs, &tab, &key);
    881   expr(ls, &val);
    882   luaK_storevar(fs, &tab, &val);
    883   fs->freereg = reg;  /* free registers */
    884 }
    885 
    886 
    887 static void closelistfield (FuncState *fs, ConsControl *cc) {
    888   if (cc->v.k == VVOID) return;  /* there is no list item */
    889   luaK_exp2nextreg(fs, &cc->v);
    890   cc->v.k = VVOID;
    891   if (cc->tostore >= cc->maxtostore) {
    892     luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);  /* flush */
    893     cc->na += cc->tostore;
    894     cc->tostore = 0;  /* no more items pending */
    895   }
    896 }
    897 
    898 
    899 static void lastlistfield (FuncState *fs, ConsControl *cc) {
    900   if (cc->tostore == 0) return;
    901   if (hasmultret(cc->v.k)) {
    902     luaK_setmultret(fs, &cc->v);
    903     luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
    904     cc->na--;  /* do not count last expression (unknown number of elements) */
    905   }
    906   else {
    907     if (cc->v.k != VVOID)
    908       luaK_exp2nextreg(fs, &cc->v);
    909     luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
    910   }
    911   cc->na += cc->tostore;
    912 }
    913 
    914 
    915 static void listfield (LexState *ls, ConsControl *cc) {
    916   /* listfield -> exp */
    917   expr(ls, &cc->v);
    918   cc->tostore++;
    919 }
    920 
    921 
    922 static void field (LexState *ls, ConsControl *cc) {
    923   /* field -> listfield | recfield */
    924   switch(ls->t.token) {
    925     case TK_NAME: {  /* may be 'listfield' or 'recfield' */
    926       if (luaX_lookahead(ls) != '=')  /* expression? */
    927         listfield(ls, cc);
    928       else
    929         recfield(ls, cc);
    930       break;
    931     }
    932     case '[': {
    933       recfield(ls, cc);
    934       break;
    935     }
    936     default: {
    937       listfield(ls, cc);
    938       break;
    939     }
    940   }
    941 }
    942 
    943 
    944 /*
    945 ** Compute a limit for how many registers a constructor can use before
    946 ** emitting a 'SETLIST' instruction, based on how many registers are
    947 ** available.
    948 */
    949 static int maxtostore (FuncState *fs) {
    950   int numfreeregs = MAX_FSTACK - fs->freereg;
    951   if (numfreeregs >= 160)  /* "lots" of registers? */
    952     return numfreeregs / 5;  /* use up to 1/5 of them */
    953   else if (numfreeregs >= 80)  /* still "enough" registers? */
    954     return 10;  /* one 'SETLIST' instruction for each 10 values */
    955   else  /* save registers for potential more nesting */
    956     return 1;
    957 }
    958 
    959 
    960 static void constructor (LexState *ls, expdesc *t) {
    961   /* constructor -> '{' [ field { sep field } [sep] ] '}'
    962      sep -> ',' | ';' */
    963   FuncState *fs = ls->fs;
    964   int line = ls->linenumber;
    965   int pc = luaK_codevABCk(fs, OP_NEWTABLE, 0, 0, 0, 0);
    966   ConsControl cc;
    967   luaK_code(fs, 0);  /* space for extra arg. */
    968   cc.na = cc.nh = cc.tostore = 0;
    969   cc.t = t;
    970   init_exp(t, VNONRELOC, fs->freereg);  /* table will be at stack top */
    971   luaK_reserveregs(fs, 1);
    972   init_exp(&cc.v, VVOID, 0);  /* no value (yet) */
    973   checknext(ls, '{' /*}*/);
    974   cc.maxtostore = maxtostore(fs);
    975   do {
    976     lua_assert(cc.v.k == VVOID || cc.tostore > 0);
    977     if (ls->t.token == /*{*/ '}') break;
    978     closelistfield(fs, &cc);
    979     field(ls, &cc);
    980   } while (testnext(ls, ',') || testnext(ls, ';'));
    981   check_match(ls, /*{*/ '}', '{' /*}*/, line);
    982   lastlistfield(fs, &cc);
    983   luaK_settablesize(fs, pc, t->u.info, cc.na, cc.nh);
    984 }
    985 
    986 /* }====================================================================== */
    987 
    988 
    989 static void setvararg (FuncState *fs, int nparams) {
    990   fs->f->flag |= PF_ISVARARG;
    991   luaK_codeABC(fs, OP_VARARGPREP, nparams, 0, 0);
    992 }
    993 
    994 
    995 static void parlist (LexState *ls) {
    996   /* parlist -> [ {NAME ','} (NAME | '...') ] */
    997   FuncState *fs = ls->fs;
    998   Proto *f = fs->f;
    999   int nparams = 0;
   1000   int isvararg = 0;
   1001   if (ls->t.token != ')') {  /* is 'parlist' not empty? */
   1002     do {
   1003       switch (ls->t.token) {
   1004         case TK_NAME: {
   1005           new_localvar(ls, str_checkname(ls));
   1006           nparams++;
   1007           break;
   1008         }
   1009         case TK_DOTS: {
   1010           luaX_next(ls);
   1011           isvararg = 1;
   1012           break;
   1013         }
   1014         default: luaX_syntaxerror(ls, "<name> or '...' expected");
   1015       }
   1016     } while (!isvararg && testnext(ls, ','));
   1017   }
   1018   adjustlocalvars(ls, nparams);
   1019   f->numparams = cast_byte(fs->nactvar);
   1020   if (isvararg)
   1021     setvararg(fs, f->numparams);  /* declared vararg */
   1022   luaK_reserveregs(fs, fs->nactvar);  /* reserve registers for parameters */
   1023 }
   1024 
   1025 
   1026 static void body (LexState *ls, expdesc *e, int ismethod, int line) {
   1027   /* body ->  '(' parlist ')' block END */
   1028   FuncState new_fs;
   1029   BlockCnt bl;
   1030   new_fs.f = addprototype(ls);
   1031   new_fs.f->linedefined = line;
   1032   open_func(ls, &new_fs, &bl);
   1033   checknext(ls, '(');
   1034   if (ismethod) {
   1035     new_localvarliteral(ls, "self");  /* create 'self' parameter */
   1036     adjustlocalvars(ls, 1);
   1037   }
   1038   parlist(ls);
   1039   checknext(ls, ')');
   1040   statlist(ls);
   1041   new_fs.f->lastlinedefined = ls->linenumber;
   1042   check_match(ls, TK_END, TK_FUNCTION, line);
   1043   codeclosure(ls, e);
   1044   close_func(ls);
   1045 }
   1046 
   1047 
   1048 static int explist (LexState *ls, expdesc *v) {
   1049   /* explist -> expr { ',' expr } */
   1050   int n = 1;  /* at least one expression */
   1051   expr(ls, v);
   1052   while (testnext(ls, ',')) {
   1053     luaK_exp2nextreg(ls->fs, v);
   1054     expr(ls, v);
   1055     n++;
   1056   }
   1057   return n;
   1058 }
   1059 
   1060 
   1061 static void funcargs (LexState *ls, expdesc *f) {
   1062   FuncState *fs = ls->fs;
   1063   expdesc args;
   1064   int base, nparams;
   1065   int line = ls->linenumber;
   1066   switch (ls->t.token) {
   1067     case '(': {  /* funcargs -> '(' [ explist ] ')' */
   1068       luaX_next(ls);
   1069       if (ls->t.token == ')')  /* arg list is empty? */
   1070         args.k = VVOID;
   1071       else {
   1072         explist(ls, &args);
   1073         if (hasmultret(args.k))
   1074           luaK_setmultret(fs, &args);
   1075       }
   1076       check_match(ls, ')', '(', line);
   1077       break;
   1078     }
   1079     case '{' /*}*/: {  /* funcargs -> constructor */
   1080       constructor(ls, &args);
   1081       break;
   1082     }
   1083     case TK_STRING: {  /* funcargs -> STRING */
   1084       codestring(&args, ls->t.seminfo.ts);
   1085       luaX_next(ls);  /* must use 'seminfo' before 'next' */
   1086       break;
   1087     }
   1088     default: {
   1089       luaX_syntaxerror(ls, "function arguments expected");
   1090     }
   1091   }
   1092   lua_assert(f->k == VNONRELOC);
   1093   base = f->u.info;  /* base register for call */
   1094   if (hasmultret(args.k))
   1095     nparams = LUA_MULTRET;  /* open call */
   1096   else {
   1097     if (args.k != VVOID)
   1098       luaK_exp2nextreg(fs, &args);  /* close last argument */
   1099     nparams = fs->freereg - (base+1);
   1100   }
   1101   init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
   1102   luaK_fixline(fs, line);
   1103   /* call removes function and arguments and leaves one result (unless
   1104      changed later) */
   1105   fs->freereg = cast_byte(base + 1);
   1106 }
   1107 
   1108 
   1109 
   1110 
   1111 /*
   1112 ** {======================================================================
   1113 ** Expression parsing
   1114 ** =======================================================================
   1115 */
   1116 
   1117 
   1118 static void primaryexp (LexState *ls, expdesc *v) {
   1119   /* primaryexp -> NAME | '(' expr ')' */
   1120   switch (ls->t.token) {
   1121     case '(': {
   1122       int line = ls->linenumber;
   1123       luaX_next(ls);
   1124       expr(ls, v);
   1125       check_match(ls, ')', '(', line);
   1126       luaK_dischargevars(ls->fs, v);
   1127       return;
   1128     }
   1129     case TK_NAME: {
   1130       singlevar(ls, v);
   1131       return;
   1132     }
   1133     default: {
   1134       luaX_syntaxerror(ls, "unexpected symbol");
   1135     }
   1136   }
   1137 }
   1138 
   1139 
   1140 static void suffixedexp (LexState *ls, expdesc *v) {
   1141   /* suffixedexp ->
   1142        primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
   1143   FuncState *fs = ls->fs;
   1144   primaryexp(ls, v);
   1145   for (;;) {
   1146     switch (ls->t.token) {
   1147       case '.': {  /* fieldsel */
   1148         fieldsel(ls, v);
   1149         break;
   1150       }
   1151       case '[': {  /* '[' exp ']' */
   1152         expdesc key;
   1153         luaK_exp2anyregup(fs, v);
   1154         yindex(ls, &key);
   1155         luaK_indexed(fs, v, &key);
   1156         break;
   1157       }
   1158       case ':': {  /* ':' NAME funcargs */
   1159         expdesc key;
   1160         luaX_next(ls);
   1161         codename(ls, &key);
   1162         luaK_self(fs, v, &key);
   1163         funcargs(ls, v);
   1164         break;
   1165       }
   1166       case '(': case TK_STRING: case '{' /*}*/: {  /* funcargs */
   1167         luaK_exp2nextreg(fs, v);
   1168         funcargs(ls, v);
   1169         break;
   1170       }
   1171       default: return;
   1172     }
   1173   }
   1174 }
   1175 
   1176 
   1177 static void simpleexp (LexState *ls, expdesc *v) {
   1178   /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
   1179                   constructor | FUNCTION body | suffixedexp */
   1180   switch (ls->t.token) {
   1181     case TK_FLT: {
   1182       init_exp(v, VKFLT, 0);
   1183       v->u.nval = ls->t.seminfo.r;
   1184       break;
   1185     }
   1186     case TK_INT: {
   1187       init_exp(v, VKINT, 0);
   1188       v->u.ival = ls->t.seminfo.i;
   1189       break;
   1190     }
   1191     case TK_STRING: {
   1192       codestring(v, ls->t.seminfo.ts);
   1193       break;
   1194     }
   1195     case TK_NIL: {
   1196       init_exp(v, VNIL, 0);
   1197       break;
   1198     }
   1199     case TK_TRUE: {
   1200       init_exp(v, VTRUE, 0);
   1201       break;
   1202     }
   1203     case TK_FALSE: {
   1204       init_exp(v, VFALSE, 0);
   1205       break;
   1206     }
   1207     case TK_DOTS: {  /* vararg */
   1208       FuncState *fs = ls->fs;
   1209       check_condition(ls, fs->f->flag & PF_ISVARARG,
   1210                       "cannot use '...' outside a vararg function");
   1211       init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 0, 1));
   1212       break;
   1213     }
   1214     case '{' /*}*/: {  /* constructor */
   1215       constructor(ls, v);
   1216       return;
   1217     }
   1218     case TK_FUNCTION: {
   1219       luaX_next(ls);
   1220       body(ls, v, 0, ls->linenumber);
   1221       return;
   1222     }
   1223     default: {
   1224       suffixedexp(ls, v);
   1225       return;
   1226     }
   1227   }
   1228   luaX_next(ls);
   1229 }
   1230 
   1231 
   1232 static UnOpr getunopr (int op) {
   1233   switch (op) {
   1234     case TK_NOT: return OPR_NOT;
   1235     case '-': return OPR_MINUS;
   1236     case '~': return OPR_BNOT;
   1237     case '#': return OPR_LEN;
   1238     default: return OPR_NOUNOPR;
   1239   }
   1240 }
   1241 
   1242 
   1243 static BinOpr getbinopr (int op) {
   1244   switch (op) {
   1245     case '+': return OPR_ADD;
   1246     case '-': return OPR_SUB;
   1247     case '*': return OPR_MUL;
   1248     case '%': return OPR_MOD;
   1249     case '^': return OPR_POW;
   1250     case '/': return OPR_DIV;
   1251     case TK_IDIV: return OPR_IDIV;
   1252     case '&': return OPR_BAND;
   1253     case '|': return OPR_BOR;
   1254     case '~': return OPR_BXOR;
   1255     case TK_SHL: return OPR_SHL;
   1256     case TK_SHR: return OPR_SHR;
   1257     case TK_CONCAT: return OPR_CONCAT;
   1258     case TK_NE: return OPR_NE;
   1259     case TK_EQ: return OPR_EQ;
   1260     case '<': return OPR_LT;
   1261     case TK_LE: return OPR_LE;
   1262     case '>': return OPR_GT;
   1263     case TK_GE: return OPR_GE;
   1264     case TK_AND: return OPR_AND;
   1265     case TK_OR: return OPR_OR;
   1266     default: return OPR_NOBINOPR;
   1267   }
   1268 }
   1269 
   1270 
   1271 /*
   1272 ** Priority table for binary operators.
   1273 */
   1274 static const struct {
   1275   lu_byte left;  /* left priority for each binary operator */
   1276   lu_byte right; /* right priority */
   1277 } priority[] = {  /* ORDER OPR */
   1278    {10, 10}, {10, 10},           /* '+' '-' */
   1279    {11, 11}, {11, 11},           /* '*' '%' */
   1280    {14, 13},                  /* '^' (right associative) */
   1281    {11, 11}, {11, 11},           /* '/' '//' */
   1282    {6, 6}, {4, 4}, {5, 5},   /* '&' '|' '~' */
   1283    {7, 7}, {7, 7},           /* '<<' '>>' */
   1284    {9, 8},                   /* '..' (right associative) */
   1285    {3, 3}, {3, 3}, {3, 3},   /* ==, <, <= */
   1286    {3, 3}, {3, 3}, {3, 3},   /* ~=, >, >= */
   1287    {2, 2}, {1, 1}            /* and, or */
   1288 };
   1289 
   1290 #define UNARY_PRIORITY	12  /* priority for unary operators */
   1291 
   1292 
   1293 /*
   1294 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
   1295 ** where 'binop' is any binary operator with a priority higher than 'limit'
   1296 */
   1297 static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
   1298   BinOpr op;
   1299   UnOpr uop;
   1300   enterlevel(ls);
   1301   uop = getunopr(ls->t.token);
   1302   if (uop != OPR_NOUNOPR) {  /* prefix (unary) operator? */
   1303     int line = ls->linenumber;
   1304     luaX_next(ls);  /* skip operator */
   1305     subexpr(ls, v, UNARY_PRIORITY);
   1306     luaK_prefix(ls->fs, uop, v, line);
   1307   }
   1308   else simpleexp(ls, v);
   1309   /* expand while operators have priorities higher than 'limit' */
   1310   op = getbinopr(ls->t.token);
   1311   while (op != OPR_NOBINOPR && priority[op].left > limit) {
   1312     expdesc v2;
   1313     BinOpr nextop;
   1314     int line = ls->linenumber;
   1315     luaX_next(ls);  /* skip operator */
   1316     luaK_infix(ls->fs, op, v);
   1317     /* read sub-expression with higher priority */
   1318     nextop = subexpr(ls, &v2, priority[op].right);
   1319     luaK_posfix(ls->fs, op, v, &v2, line);
   1320     op = nextop;
   1321   }
   1322   leavelevel(ls);
   1323   return op;  /* return first untreated operator */
   1324 }
   1325 
   1326 
   1327 static void expr (LexState *ls, expdesc *v) {
   1328   subexpr(ls, v, 0);
   1329 }
   1330 
   1331 /* }==================================================================== */
   1332 
   1333 
   1334 
   1335 /*
   1336 ** {======================================================================
   1337 ** Rules for Statements
   1338 ** =======================================================================
   1339 */
   1340 
   1341 
   1342 static void block (LexState *ls) {
   1343   /* block -> statlist */
   1344   FuncState *fs = ls->fs;
   1345   BlockCnt bl;
   1346   enterblock(fs, &bl, 0);
   1347   statlist(ls);
   1348   leaveblock(fs);
   1349 }
   1350 
   1351 
   1352 /*
   1353 ** structure to chain all variables in the left-hand side of an
   1354 ** assignment
   1355 */
   1356 struct LHS_assign {
   1357   struct LHS_assign *prev;
   1358   expdesc v;  /* variable (global, local, upvalue, or indexed) */
   1359 };
   1360 
   1361 
   1362 /*
   1363 ** check whether, in an assignment to an upvalue/local variable, the
   1364 ** upvalue/local variable is begin used in a previous assignment to a
   1365 ** table. If so, save original upvalue/local value in a safe place and
   1366 ** use this safe copy in the previous assignment.
   1367 */
   1368 static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
   1369   FuncState *fs = ls->fs;
   1370   lu_byte extra = fs->freereg;  /* eventual position to save local variable */
   1371   int conflict = 0;
   1372   for (; lh; lh = lh->prev) {  /* check all previous assignments */
   1373     if (vkisindexed(lh->v.k)) {  /* assignment to table field? */
   1374       if (lh->v.k == VINDEXUP) {  /* is table an upvalue? */
   1375         if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) {
   1376           conflict = 1;  /* table is the upvalue being assigned now */
   1377           lh->v.k = VINDEXSTR;
   1378           lh->v.u.ind.t = extra;  /* assignment will use safe copy */
   1379         }
   1380       }
   1381       else {  /* table is a register */
   1382         if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.ridx) {
   1383           conflict = 1;  /* table is the local being assigned now */
   1384           lh->v.u.ind.t = extra;  /* assignment will use safe copy */
   1385         }
   1386         /* is index the local being assigned? */
   1387         if (lh->v.k == VINDEXED && v->k == VLOCAL &&
   1388             lh->v.u.ind.idx == v->u.var.ridx) {
   1389           conflict = 1;
   1390           lh->v.u.ind.idx = extra;  /* previous assignment will use safe copy */
   1391         }
   1392       }
   1393     }
   1394   }
   1395   if (conflict) {
   1396     /* copy upvalue/local value to a temporary (in position 'extra') */
   1397     if (v->k == VLOCAL)
   1398       luaK_codeABC(fs, OP_MOVE, extra, v->u.var.ridx, 0);
   1399     else
   1400       luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0);
   1401     luaK_reserveregs(fs, 1);
   1402   }
   1403 }
   1404 
   1405 /*
   1406 ** Parse and compile a multiple assignment. The first "variable"
   1407 ** (a 'suffixedexp') was already read by the caller.
   1408 **
   1409 ** assignment -> suffixedexp restassign
   1410 ** restassign -> ',' suffixedexp restassign | '=' explist
   1411 */
   1412 static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) {
   1413   expdesc e;
   1414   check_condition(ls, vkisvar(lh->v.k), "syntax error");
   1415   check_readonly(ls, &lh->v);
   1416   if (testnext(ls, ',')) {  /* restassign -> ',' suffixedexp restassign */
   1417     struct LHS_assign nv;
   1418     nv.prev = lh;
   1419     suffixedexp(ls, &nv.v);
   1420     if (!vkisindexed(nv.v.k))
   1421       check_conflict(ls, lh, &nv.v);
   1422     enterlevel(ls);  /* control recursion depth */
   1423     restassign(ls, &nv, nvars+1);
   1424     leavelevel(ls);
   1425   }
   1426   else {  /* restassign -> '=' explist */
   1427     int nexps;
   1428     checknext(ls, '=');
   1429     nexps = explist(ls, &e);
   1430     if (nexps != nvars)
   1431       adjust_assign(ls, nvars, nexps, &e);
   1432     else {
   1433       luaK_setoneret(ls->fs, &e);  /* close last expression */
   1434       luaK_storevar(ls->fs, &lh->v, &e);
   1435       return;  /* avoid default */
   1436     }
   1437   }
   1438   init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */
   1439   luaK_storevar(ls->fs, &lh->v, &e);
   1440 }
   1441 
   1442 
   1443 static int cond (LexState *ls) {
   1444   /* cond -> exp */
   1445   expdesc v;
   1446   expr(ls, &v);  /* read condition */
   1447   if (v.k == VNIL) v.k = VFALSE;  /* 'falses' are all equal here */
   1448   luaK_goiftrue(ls->fs, &v);
   1449   return v.f;
   1450 }
   1451 
   1452 
   1453 static void gotostat (LexState *ls, int line) {
   1454   TString *name = str_checkname(ls);  /* label's name */
   1455   newgotoentry(ls, name, line);
   1456 }
   1457 
   1458 
   1459 /*
   1460 ** Break statement. Semantically equivalent to "goto break".
   1461 */
   1462 static void breakstat (LexState *ls, int line) {
   1463   BlockCnt *bl;  /* to look for an enclosing loop */
   1464   for (bl = ls->fs->bl; bl != NULL; bl = bl->previous) {
   1465     if (bl->isloop)  /* found one? */
   1466       goto ok;
   1467   }
   1468   luaX_syntaxerror(ls, "break outside loop");
   1469  ok:
   1470   bl->isloop = 2;  /* signal that block has pending breaks */
   1471   luaX_next(ls);  /* skip break */
   1472   newgotoentry(ls, luaS_newliteral(ls->L, "break"), line);
   1473 }
   1474 
   1475 
   1476 /*
   1477 ** Check whether there is already a label with the given 'name' at
   1478 ** current function.
   1479 */
   1480 static void checkrepeated (LexState *ls, TString *name) {
   1481   Labeldesc *lb = findlabel(ls, name, ls->fs->firstlabel);
   1482   if (l_unlikely(lb != NULL)) {  /* already defined? */
   1483     const char *msg = "label '%s' already defined on line %d";
   1484     msg = luaO_pushfstring(ls->L, msg, getstr(name), lb->line);
   1485     luaK_semerror(ls, msg);  /* error */
   1486   }
   1487 }
   1488 
   1489 
   1490 static void labelstat (LexState *ls, TString *name, int line) {
   1491   /* label -> '::' NAME '::' */
   1492   checknext(ls, TK_DBCOLON);  /* skip double colon */
   1493   while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
   1494     statement(ls);  /* skip other no-op statements */
   1495   checkrepeated(ls, name);  /* check for repeated labels */
   1496   createlabel(ls, name, line, block_follow(ls, 0));
   1497 }
   1498 
   1499 
   1500 static void whilestat (LexState *ls, int line) {
   1501   /* whilestat -> WHILE cond DO block END */
   1502   FuncState *fs = ls->fs;
   1503   int whileinit;
   1504   int condexit;
   1505   BlockCnt bl;
   1506   luaX_next(ls);  /* skip WHILE */
   1507   whileinit = luaK_getlabel(fs);
   1508   condexit = cond(ls);
   1509   enterblock(fs, &bl, 1);
   1510   checknext(ls, TK_DO);
   1511   block(ls);
   1512   luaK_jumpto(fs, whileinit);
   1513   check_match(ls, TK_END, TK_WHILE, line);
   1514   leaveblock(fs);
   1515   luaK_patchtohere(fs, condexit);  /* false conditions finish the loop */
   1516 }
   1517 
   1518 
   1519 static void repeatstat (LexState *ls, int line) {
   1520   /* repeatstat -> REPEAT block UNTIL cond */
   1521   int condexit;
   1522   FuncState *fs = ls->fs;
   1523   int repeat_init = luaK_getlabel(fs);
   1524   BlockCnt bl1, bl2;
   1525   enterblock(fs, &bl1, 1);  /* loop block */
   1526   enterblock(fs, &bl2, 0);  /* scope block */
   1527   luaX_next(ls);  /* skip REPEAT */
   1528   statlist(ls);
   1529   check_match(ls, TK_UNTIL, TK_REPEAT, line);
   1530   condexit = cond(ls);  /* read condition (inside scope block) */
   1531   leaveblock(fs);  /* finish scope */
   1532   if (bl2.upval) {  /* upvalues? */
   1533     int exit = luaK_jump(fs);  /* normal exit must jump over fix */
   1534     luaK_patchtohere(fs, condexit);  /* repetition must close upvalues */
   1535     luaK_codeABC(fs, OP_CLOSE, reglevel(fs, bl2.nactvar), 0, 0);
   1536     condexit = luaK_jump(fs);  /* repeat after closing upvalues */
   1537     luaK_patchtohere(fs, exit);  /* normal exit comes to here */
   1538   }
   1539   luaK_patchlist(fs, condexit, repeat_init);  /* close the loop */
   1540   leaveblock(fs);  /* finish loop */
   1541 }
   1542 
   1543 
   1544 /*
   1545 ** Read an expression and generate code to put its results in next
   1546 ** stack slot.
   1547 **
   1548 */
   1549 static void exp1 (LexState *ls) {
   1550   expdesc e;
   1551   expr(ls, &e);
   1552   luaK_exp2nextreg(ls->fs, &e);
   1553   lua_assert(e.k == VNONRELOC);
   1554 }
   1555 
   1556 
   1557 /*
   1558 ** Fix for instruction at position 'pc' to jump to 'dest'.
   1559 ** (Jump addresses are relative in Lua). 'back' true means
   1560 ** a back jump.
   1561 */
   1562 static void fixforjump (FuncState *fs, int pc, int dest, int back) {
   1563   Instruction *jmp = &fs->f->code[pc];
   1564   int offset = dest - (pc + 1);
   1565   if (back)
   1566     offset = -offset;
   1567   if (l_unlikely(offset > MAXARG_Bx))
   1568     luaX_syntaxerror(fs->ls, "control structure too long");
   1569   SETARG_Bx(*jmp, offset);
   1570 }
   1571 
   1572 
   1573 /*
   1574 ** Generate code for a 'for' loop.
   1575 */
   1576 static void forbody (LexState *ls, int base, int line, int nvars, int isgen) {
   1577   /* forbody -> DO block */
   1578   static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP};
   1579   static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP};
   1580   BlockCnt bl;
   1581   FuncState *fs = ls->fs;
   1582   int prep, endfor;
   1583   checknext(ls, TK_DO);
   1584   prep = luaK_codeABx(fs, forprep[isgen], base, 0);
   1585   fs->freereg--;  /* both 'forprep' remove one register from the stack */
   1586   enterblock(fs, &bl, 0);  /* scope for declared variables */
   1587   adjustlocalvars(ls, nvars);
   1588   luaK_reserveregs(fs, nvars);
   1589   block(ls);
   1590   leaveblock(fs);  /* end of scope for declared variables */
   1591   fixforjump(fs, prep, luaK_getlabel(fs), 0);
   1592   if (isgen) {  /* generic for? */
   1593     luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
   1594     luaK_fixline(fs, line);
   1595   }
   1596   endfor = luaK_codeABx(fs, forloop[isgen], base, 0);
   1597   fixforjump(fs, endfor, prep + 1, 1);
   1598   luaK_fixline(fs, line);
   1599 }
   1600 
   1601 
   1602 static void fornum (LexState *ls, TString *varname, int line) {
   1603   /* fornum -> NAME = exp,exp[,exp] forbody */
   1604   FuncState *fs = ls->fs;
   1605   int base = fs->freereg;
   1606   new_localvarliteral(ls, "(for state)");
   1607   new_localvarliteral(ls, "(for state)");
   1608   new_localvarkind(ls, varname, RDKCONST);  /* control variable */
   1609   checknext(ls, '=');
   1610   exp1(ls);  /* initial value */
   1611   checknext(ls, ',');
   1612   exp1(ls);  /* limit */
   1613   if (testnext(ls, ','))
   1614     exp1(ls);  /* optional step */
   1615   else {  /* default step = 1 */
   1616     luaK_int(fs, fs->freereg, 1);
   1617     luaK_reserveregs(fs, 1);
   1618   }
   1619   adjustlocalvars(ls, 2);  /* start scope for internal variables */
   1620   forbody(ls, base, line, 1, 0);
   1621 }
   1622 
   1623 
   1624 static void forlist (LexState *ls, TString *indexname) {
   1625   /* forlist -> NAME {,NAME} IN explist forbody */
   1626   FuncState *fs = ls->fs;
   1627   expdesc e;
   1628   int nvars = 4;  /* function, state, closing, control */
   1629   int line;
   1630   int base = fs->freereg;
   1631   /* create internal variables */
   1632   new_localvarliteral(ls, "(for state)");  /* iterator function */
   1633   new_localvarliteral(ls, "(for state)");  /* state */
   1634   new_localvarliteral(ls, "(for state)");  /* closing var. (after swap) */
   1635   new_localvarkind(ls, indexname, RDKCONST);  /* control variable */
   1636   /* other declared variables */
   1637   while (testnext(ls, ',')) {
   1638     new_localvar(ls, str_checkname(ls));
   1639     nvars++;
   1640   }
   1641   checknext(ls, TK_IN);
   1642   line = ls->linenumber;
   1643   adjust_assign(ls, 4, explist(ls, &e), &e);
   1644   adjustlocalvars(ls, 3);  /* start scope for internal variables */
   1645   marktobeclosed(fs);  /* last internal var. must be closed */
   1646   luaK_checkstack(fs, 2);  /* extra space to call iterator */
   1647   forbody(ls, base, line, nvars - 3, 1);
   1648 }
   1649 
   1650 
   1651 static void forstat (LexState *ls, int line) {
   1652   /* forstat -> FOR (fornum | forlist) END */
   1653   FuncState *fs = ls->fs;
   1654   TString *varname;
   1655   BlockCnt bl;
   1656   enterblock(fs, &bl, 1);  /* scope for loop and control variables */
   1657   luaX_next(ls);  /* skip 'for' */
   1658   varname = str_checkname(ls);  /* first variable name */
   1659   switch (ls->t.token) {
   1660     case '=': fornum(ls, varname, line); break;
   1661     case ',': case TK_IN: forlist(ls, varname); break;
   1662     default: luaX_syntaxerror(ls, "'=' or 'in' expected");
   1663   }
   1664   check_match(ls, TK_END, TK_FOR, line);
   1665   leaveblock(fs);  /* loop scope ('break' jumps to this point) */
   1666 }
   1667 
   1668 
   1669 static void test_then_block (LexState *ls, int *escapelist) {
   1670   /* test_then_block -> [IF | ELSEIF] cond THEN block */
   1671   FuncState *fs = ls->fs;
   1672   int condtrue;
   1673   luaX_next(ls);  /* skip IF or ELSEIF */
   1674   condtrue = cond(ls);  /* read condition */
   1675   checknext(ls, TK_THEN);
   1676   block(ls);  /* 'then' part */
   1677   if (ls->t.token == TK_ELSE ||
   1678       ls->t.token == TK_ELSEIF)  /* followed by 'else'/'elseif'? */
   1679     luaK_concat(fs, escapelist, luaK_jump(fs));  /* must jump over it */
   1680   luaK_patchtohere(fs, condtrue);
   1681 }
   1682 
   1683 
   1684 static void ifstat (LexState *ls, int line) {
   1685   /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
   1686   FuncState *fs = ls->fs;
   1687   int escapelist = NO_JUMP;  /* exit list for finished parts */
   1688   test_then_block(ls, &escapelist);  /* IF cond THEN block */
   1689   while (ls->t.token == TK_ELSEIF)
   1690     test_then_block(ls, &escapelist);  /* ELSEIF cond THEN block */
   1691   if (testnext(ls, TK_ELSE))
   1692     block(ls);  /* 'else' part */
   1693   check_match(ls, TK_END, TK_IF, line);
   1694   luaK_patchtohere(fs, escapelist);  /* patch escape list to 'if' end */
   1695 }
   1696 
   1697 
   1698 static void localfunc (LexState *ls) {
   1699   expdesc b;
   1700   FuncState *fs = ls->fs;
   1701   int fvar = fs->nactvar;  /* function's variable index */
   1702   new_localvar(ls, str_checkname(ls));  /* new local variable */
   1703   adjustlocalvars(ls, 1);  /* enter its scope */
   1704   body(ls, &b, 0, ls->linenumber);  /* function created in next register */
   1705   /* debug information will only see the variable after this point! */
   1706   localdebuginfo(fs, fvar)->startpc = fs->pc;
   1707 }
   1708 
   1709 
   1710 static lu_byte getlocalattribute (LexState *ls) {
   1711   /* ATTRIB -> ['<' Name '>'] */
   1712   if (testnext(ls, '<')) {
   1713     TString *ts = str_checkname(ls);
   1714     const char *attr = getstr(ts);
   1715     checknext(ls, '>');
   1716     if (strcmp(attr, "const") == 0)
   1717       return RDKCONST;  /* read-only variable */
   1718     else if (strcmp(attr, "close") == 0)
   1719       return RDKTOCLOSE;  /* to-be-closed variable */
   1720     else
   1721       luaK_semerror(ls,
   1722         luaO_pushfstring(ls->L, "unknown attribute '%s'", attr));
   1723   }
   1724   return VDKREG;  /* regular variable */
   1725 }
   1726 
   1727 
   1728 static void checktoclose (FuncState *fs, int level) {
   1729   if (level != -1) {  /* is there a to-be-closed variable? */
   1730     marktobeclosed(fs);
   1731     luaK_codeABC(fs, OP_TBC, reglevel(fs, level), 0, 0);
   1732   }
   1733 }
   1734 
   1735 
   1736 static void localstat (LexState *ls) {
   1737   /* stat -> LOCAL NAME ATTRIB { ',' NAME ATTRIB } ['=' explist] */
   1738   FuncState *fs = ls->fs;
   1739   int toclose = -1;  /* index of to-be-closed variable (if any) */
   1740   Vardesc *var;  /* last variable */
   1741   int vidx;  /* index of last variable */
   1742   int nvars = 0;
   1743   int nexps;
   1744   expdesc e;
   1745   do {
   1746     TString *vname = str_checkname(ls);
   1747     lu_byte kind = getlocalattribute(ls);
   1748     vidx = new_localvarkind(ls, vname, kind);
   1749     if (kind == RDKTOCLOSE) {  /* to-be-closed? */
   1750       if (toclose != -1)  /* one already present? */
   1751         luaK_semerror(ls, "multiple to-be-closed variables in local list");
   1752       toclose = fs->nactvar + nvars;
   1753     }
   1754     nvars++;
   1755   } while (testnext(ls, ','));
   1756   if (testnext(ls, '='))
   1757     nexps = explist(ls, &e);
   1758   else {
   1759     e.k = VVOID;
   1760     nexps = 0;
   1761   }
   1762   var = getlocalvardesc(fs, vidx);  /* get last variable */
   1763   if (nvars == nexps &&  /* no adjustments? */
   1764       var->vd.kind == RDKCONST &&  /* last variable is const? */
   1765       luaK_exp2const(fs, &e, &var->k)) {  /* compile-time constant? */
   1766     var->vd.kind = RDKCTC;  /* variable is a compile-time constant */
   1767     adjustlocalvars(ls, nvars - 1);  /* exclude last variable */
   1768     fs->nactvar++;  /* but count it */
   1769   }
   1770   else {
   1771     adjust_assign(ls, nvars, nexps, &e);
   1772     adjustlocalvars(ls, nvars);
   1773   }
   1774   checktoclose(fs, toclose);
   1775 }
   1776 
   1777 
   1778 static int funcname (LexState *ls, expdesc *v) {
   1779   /* funcname -> NAME {fieldsel} [':' NAME] */
   1780   int ismethod = 0;
   1781   singlevar(ls, v);
   1782   while (ls->t.token == '.')
   1783     fieldsel(ls, v);
   1784   if (ls->t.token == ':') {
   1785     ismethod = 1;
   1786     fieldsel(ls, v);
   1787   }
   1788   return ismethod;
   1789 }
   1790 
   1791 
   1792 static void funcstat (LexState *ls, int line) {
   1793   /* funcstat -> FUNCTION funcname body */
   1794   int ismethod;
   1795   expdesc v, b;
   1796   luaX_next(ls);  /* skip FUNCTION */
   1797   ismethod = funcname(ls, &v);
   1798   body(ls, &b, ismethod, line);
   1799   check_readonly(ls, &v);
   1800   luaK_storevar(ls->fs, &v, &b);
   1801   luaK_fixline(ls->fs, line);  /* definition "happens" in the first line */
   1802 }
   1803 
   1804 
   1805 static void exprstat (LexState *ls) {
   1806   /* stat -> func | assignment */
   1807   FuncState *fs = ls->fs;
   1808   struct LHS_assign v;
   1809   suffixedexp(ls, &v.v);
   1810   if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
   1811     v.prev = NULL;
   1812     restassign(ls, &v, 1);
   1813   }
   1814   else {  /* stat -> func */
   1815     Instruction *inst;
   1816     check_condition(ls, v.v.k == VCALL, "syntax error");
   1817     inst = &getinstruction(fs, &v.v);
   1818     SETARG_C(*inst, 1);  /* call statement uses no results */
   1819   }
   1820 }
   1821 
   1822 
   1823 static void retstat (LexState *ls) {
   1824   /* stat -> RETURN [explist] [';'] */
   1825   FuncState *fs = ls->fs;
   1826   expdesc e;
   1827   int nret;  /* number of values being returned */
   1828   int first = luaY_nvarstack(fs);  /* first slot to be returned */
   1829   if (block_follow(ls, 1) || ls->t.token == ';')
   1830     nret = 0;  /* return no values */
   1831   else {
   1832     nret = explist(ls, &e);  /* optional return values */
   1833     if (hasmultret(e.k)) {
   1834       luaK_setmultret(fs, &e);
   1835       if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc) {  /* tail call? */
   1836         SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);
   1837         lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs));
   1838       }
   1839       nret = LUA_MULTRET;  /* return all values */
   1840     }
   1841     else {
   1842       if (nret == 1)  /* only one single value? */
   1843         first = luaK_exp2anyreg(fs, &e);  /* can use original slot */
   1844       else {  /* values must go to the top of the stack */
   1845         luaK_exp2nextreg(fs, &e);
   1846         lua_assert(nret == fs->freereg - first);
   1847       }
   1848     }
   1849   }
   1850   luaK_ret(fs, first, nret);
   1851   testnext(ls, ';');  /* skip optional semicolon */
   1852 }
   1853 
   1854 
   1855 static void statement (LexState *ls) {
   1856   int line = ls->linenumber;  /* may be needed for error messages */
   1857   enterlevel(ls);
   1858   switch (ls->t.token) {
   1859     case ';': {  /* stat -> ';' (empty statement) */
   1860       luaX_next(ls);  /* skip ';' */
   1861       break;
   1862     }
   1863     case TK_IF: {  /* stat -> ifstat */
   1864       ifstat(ls, line);
   1865       break;
   1866     }
   1867     case TK_WHILE: {  /* stat -> whilestat */
   1868       whilestat(ls, line);
   1869       break;
   1870     }
   1871     case TK_DO: {  /* stat -> DO block END */
   1872       luaX_next(ls);  /* skip DO */
   1873       block(ls);
   1874       check_match(ls, TK_END, TK_DO, line);
   1875       break;
   1876     }
   1877     case TK_FOR: {  /* stat -> forstat */
   1878       forstat(ls, line);
   1879       break;
   1880     }
   1881     case TK_REPEAT: {  /* stat -> repeatstat */
   1882       repeatstat(ls, line);
   1883       break;
   1884     }
   1885     case TK_FUNCTION: {  /* stat -> funcstat */
   1886       funcstat(ls, line);
   1887       break;
   1888     }
   1889     case TK_LOCAL: {  /* stat -> localstat */
   1890       luaX_next(ls);  /* skip LOCAL */
   1891       if (testnext(ls, TK_FUNCTION))  /* local function? */
   1892         localfunc(ls);
   1893       else
   1894         localstat(ls);
   1895       break;
   1896     }
   1897     case TK_DBCOLON: {  /* stat -> label */
   1898       luaX_next(ls);  /* skip double colon */
   1899       labelstat(ls, str_checkname(ls), line);
   1900       break;
   1901     }
   1902     case TK_RETURN: {  /* stat -> retstat */
   1903       luaX_next(ls);  /* skip RETURN */
   1904       retstat(ls);
   1905       break;
   1906     }
   1907     case TK_BREAK: {  /* stat -> breakstat */
   1908       breakstat(ls, line);
   1909       break;
   1910     }
   1911     case TK_GOTO: {  /* stat -> 'goto' NAME */
   1912       luaX_next(ls);  /* skip 'goto' */
   1913       gotostat(ls, line);
   1914       break;
   1915     }
   1916     default: {  /* stat -> func | assignment */
   1917       exprstat(ls);
   1918       break;
   1919     }
   1920   }
   1921   lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
   1922              ls->fs->freereg >= luaY_nvarstack(ls->fs));
   1923   ls->fs->freereg = luaY_nvarstack(ls->fs);  /* free registers */
   1924   leavelevel(ls);
   1925 }
   1926 
   1927 /* }====================================================================== */
   1928 
   1929 /* }====================================================================== */
   1930 
   1931 
   1932 /*
   1933 ** compiles the main function, which is a regular vararg function with an
   1934 ** upvalue named LUA_ENV
   1935 */
   1936 static void mainfunc (LexState *ls, FuncState *fs) {
   1937   BlockCnt bl;
   1938   Upvaldesc *env;
   1939   open_func(ls, fs, &bl);
   1940   setvararg(fs, 0);  /* main function is always declared vararg */
   1941   env = allocupvalue(fs);  /* ...set environment upvalue */
   1942   env->instack = 1;
   1943   env->idx = 0;
   1944   env->kind = VDKREG;
   1945   env->name = ls->envn;
   1946   luaC_objbarrier(ls->L, fs->f, env->name);
   1947   luaX_next(ls);  /* read first token */
   1948   statlist(ls);  /* parse main body */
   1949   check(ls, TK_EOS);
   1950   close_func(ls);
   1951 }
   1952 
   1953 
   1954 LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
   1955                        Dyndata *dyd, const char *name, int firstchar) {
   1956   LexState lexstate;
   1957   FuncState funcstate;
   1958   LClosure *cl = luaF_newLclosure(L, 1);  /* create main closure */
   1959   setclLvalue2s(L, L->top.p, cl);  /* anchor it (to avoid being collected) */
   1960   luaD_inctop(L);
   1961   lexstate.h = luaH_new(L);  /* create table for scanner */
   1962   sethvalue2s(L, L->top.p, lexstate.h);  /* anchor it */
   1963   luaD_inctop(L);
   1964   funcstate.f = cl->p = luaF_newproto(L);
   1965   luaC_objbarrier(L, cl, cl->p);
   1966   funcstate.f->source = luaS_new(L, name);  /* create and anchor TString */
   1967   luaC_objbarrier(L, funcstate.f, funcstate.f->source);
   1968   lexstate.buff = buff;
   1969   lexstate.dyd = dyd;
   1970   dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
   1971   luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
   1972   mainfunc(&lexstate, &funcstate);
   1973   lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
   1974   /* all scopes should be correctly finished */
   1975   lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
   1976   L->top.p--;  /* remove scanner's table */
   1977   return cl;  /* closure is on the stack, too */
   1978 }
   1979