ljx

FORK: LuaJIT with native 5.2 and 5.3 support
git clone https://git.neptards.moe/neptards/ljx.git
Log | Files | Refs | README

lj_parse.c (84286B)


      1 /*
      2 ** Lua parser (source code -> bytecode).
      3 ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h
      4 **
      5 ** Lua 5.2 port, variable resolution, closure lifting.
      6 ** Copyright (C) 2014 Karel Tuma. See Copyright Notice in luajit.h
      7 **
      8 ** Major portions taken verbatim or adapted from the Lua interpreter.
      9 ** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
     10 */
     11 
     12 #define lj_parse_c
     13 #define LUA_CORE
     14 #include <stdio.h>
     15 
     16 #include "lj_obj.h"
     17 #include "lj_gc.h"
     18 #include "lj_err.h"
     19 #include "lj_debug.h"
     20 #include "lj_buf.h"
     21 #include "lj_str.h"
     22 #include "lj_tab.h"
     23 #include "lj_func.h"
     24 #include "lj_state.h"
     25 #include "lj_bc.h"
     26 #if LJ_HASFFI
     27 #include "lj_ctype.h"
     28 #endif
     29 #include "lj_strfmt.h"
     30 #include "lj_lex.h"
     31 #include "lj_parse.h"
     32 #include "lj_vm.h"
     33 #include "lj_vmevent.h"
     34 #include "lj_jit.h"
     35 #include "lj_dispatch.h"
     36 
     37 /* -- Parser structures and definitions ----------------------------------- */
     38 
     39 /* Expression kinds. */
     40 typedef enum {
     41   /* Constant expressions must be first and in this order: */
     42   VKNIL,
     43   VKFALSE,
     44   VKTRUE,
     45   VKSTR,	/* sval = string value */
     46   VKNUM,	/* nval = number value */
     47   VKLAST = VKNUM,
     48   VKCDATA,	/* nval = cdata value, not treated as a constant expression */
     49   /* Non-constant expressions follow: */
     50   VLOCAL,	/* info = local register, aux = vstack index */
     51   VUPVAL,	/* info = upvalue index, aux = vstack index */
     52   VGLOBAL,	/* sval = string value */
     53   VINDEXED,	/* info = table register, aux = index reg/byte/string const */
     54   VJMP,		/* info = instruction PC */
     55   VRELOCABLE,	/* info = instruction PC */
     56   VNONRELOC,	/* info = result register */
     57   VCALL,	/* info = instruction PC, aux = base */
     58   VVOID
     59 } ExpKind;
     60 
     61 /* Expression descriptor. */
     62 typedef struct ExpDesc {
     63   union {
     64     struct {
     65       uint32_t info;	/* Primary info. */
     66       uint32_t aux;	/* Secondary info. */
     67     } s;
     68     TValue nval;	/* Number value. */
     69     GCstr *sval;	/* String value. */
     70   } u;
     71   ExpKind k;
     72   BCPos t;		/* True condition jump list. */
     73   BCPos f;		/* False condition jump list. */
     74 } ExpDesc;
     75 
     76 /* Macros for expressions. */
     77 #define expr_hasjump(e)		((e)->t != (e)->f)
     78 
     79 #define expr_isk(e)		((e)->k <= VKLAST)
     80 #define expr_isk_nojump(e)	(expr_isk(e) && !expr_hasjump(e))
     81 #define expr_isnumk(e)		((e)->k == VKNUM)
     82 #define expr_isnumk_nojump(e)	(expr_isnumk(e) && !expr_hasjump(e))
     83 #define expr_isstrk(e)		((e)->k == VKSTR)
     84 
     85 #define expr_numtv(e)		check_exp(expr_isnumk((e)), &(e)->u.nval)
     86 #define expr_numberV(e)		numberVnum(expr_numtv((e)))
     87 
     88 /* Initialize expression. */
     89 static LJ_AINLINE void expr_init(ExpDesc *e, ExpKind k, uint32_t info)
     90 {
     91   e->k = k;
     92   e->u.s.info = info;
     93   e->f = e->t = NO_JMP;
     94 }
     95 
     96 /* Check number constant for +-0. */
     97 static int expr_numiszero(ExpDesc *e)
     98 {
     99   TValue *o = expr_numtv(e);
    100   return tvisint(o) ? (intV(o) == 0) : tviszero(o);
    101 }
    102 
    103 /* Per-function linked list of scope blocks. */
    104 typedef struct FuncScope {
    105   struct FuncScope *prev;	/* Link to outer scope. */
    106   MSize vstart;			/* Start of block-local variables. */
    107   uint8_t nactvar;		/* Number of active vars outside the scope. */
    108   uint8_t flags;		/* Scope flags. */
    109 } FuncScope;
    110 
    111 #define FSCOPE_LOOP		0x01	/* Scope is a (breakable) loop. */
    112 #define FSCOPE_BREAK		0x02	/* Break used in scope. */
    113 #define FSCOPE_GOLA		0x04	/* Goto or label used in scope. */
    114 #define FSCOPE_UPVAL		0x08	/* Upvalue in scope. */
    115 #define FSCOPE_NOCLOSE		0x10	/* Do not close upvalues. */
    116 
    117 #define NAME_BREAK		((GCstr *)(uintptr_t)1)
    118 
    119 /* Index into variable stack. */
    120 typedef uint16_t VarIndex;
    121 #define LJ_MAX_VSTACK		(PROTO_UV_MASK - LJ_MAX_UPVAL)
    122 
    123 /* Variable/goto/label info. */
    124 #define VSTACK_VAR_RW		0x01	/* R/W variable. */
    125 #define VSTACK_GOTO		0x02	/* Pending goto. */
    126 #define VSTACK_LABEL		0x04	/* Label. */
    127 
    128 /* Per-function state. */
    129 typedef struct FuncState {
    130   GCtab *kt;			/* Hash table for constants. */
    131   LexState *ls;			/* Lexer state. */
    132   lua_State *L;			/* Lua state. */
    133   FuncScope *bl;		/* Current scope. */
    134   struct FuncState *prev;	/* Enclosing function. */
    135   BCPos pc;			/* Next bytecode position. */
    136   BCPos lasttarget;		/* Bytecode position of last jump target. */
    137   BCPos jpc;			/* Pending jump list to next bytecode. */
    138   BCReg freereg;		/* First free register. */
    139   BCReg nactvar;		/* Number of active local variables. */
    140   BCReg nkn, nkgc;		/* Number of lua_Number/GCobj constants */
    141   BCLine linedefined;		/* First line of the function definition. */
    142   BCInsLine *bcbase;		/* Base of bytecode stack. */
    143   BCPos bclim;			/* Limit of bytecode stack. */
    144   MSize vbase;			/* Base of variable stack for this function. */
    145   uint8_t flags;		/* Prototype flags. */
    146   uint8_t numparams;		/* Number of parameters. */
    147   uint8_t framesize;		/* Fixed frame size. */
    148   uint8_t nuv;			/* Number of upvalues */
    149   VarIndex varmap[LJ_MAX_LOCVAR];  /* Map from register to vstack idx. */
    150   VarIndex uvmap[LJ_MAX_UPVAL];	/* Map from upvalue to vstack idx. */
    151   VarIndex uvval[LJ_MAX_UPVAL]; /* Upvalue in proto (index and flags). */
    152   uint8_t uvcount[LJ_MAX_UPVAL]; /* Usage count of each upvalue link. */
    153 } FuncState;
    154 
    155 /* Binary and unary operators. ORDER OPR */
    156 typedef enum BinOpr {
    157   OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW,
    158 #if LJ_53
    159   OPR_DUMMY1, OPR_DUMMY2, /* ORDER ARITH */
    160   OPR_IDIV, OPR_BAND, OPR_BOR, OPR_BXOR, OPR_SHL, OPR_SHR,
    161 #endif
    162   OPR_CONCAT,
    163   OPR_NE, OPR_EQ,
    164   OPR_LT, OPR_GE, OPR_LE, OPR_GT,
    165   OPR_AND, OPR_OR,
    166   OPR_NOBINOPR
    167 } BinOpr;
    168 
    169 #define OPR_ARITH_LAST (OPR_CONCAT-1)
    170 
    171 LJ_STATIC_ASSERT((int)BC_ISGE-(int)BC_ISLT == (int)OPR_GE-(int)OPR_LT);
    172 LJ_STATIC_ASSERT((int)BC_ISLE-(int)BC_ISLT == (int)OPR_LE-(int)OPR_LT);
    173 LJ_STATIC_ASSERT((int)BC_ISGT-(int)BC_ISLT == (int)OPR_GT-(int)OPR_LT);
    174 LJ_STATIC_ASSERT((int)BC_SUBVV-(int)BC_ADDVV == (int)OPR_SUB-(int)OPR_ADD);
    175 LJ_STATIC_ASSERT((int)BC_MULVV-(int)BC_ADDVV == (int)OPR_MUL-(int)OPR_ADD);
    176 LJ_STATIC_ASSERT((int)BC_DIVVV-(int)BC_ADDVV == (int)OPR_DIV-(int)OPR_ADD);
    177 LJ_STATIC_ASSERT((int)BC_MODVV-(int)BC_ADDVV == (int)OPR_MOD-(int)OPR_ADD);
    178 
    179 /* -- Error handling ------------------------------------------------------ */
    180 
    181 LJ_NORET LJ_NOINLINE static void err_syntax(LexState *ls, ErrMsg em)
    182 {
    183   lj_lex_error(ls, ls->tok, em);
    184 }
    185 
    186 LJ_NORET LJ_NOINLINE static void err_token(LexState *ls, LexToken tok)
    187 {
    188   lj_lex_error(ls, ls->tok, LJ_ERR_XTOKEN, lj_lex_token2str(ls, tok));
    189 }
    190 
    191 LJ_NORET static void err_limit(FuncState *fs, uint32_t limit, const char *what)
    192 {
    193   if (fs->linedefined == 0)
    194     lj_lex_error(fs->ls, 0, LJ_ERR_XLIMM, limit, what);
    195   else
    196     lj_lex_error(fs->ls, 0, LJ_ERR_XLIMF, fs->linedefined, limit, what);
    197 }
    198 
    199 #define checklimit(fs, v, l, m)		if ((v) >= (l)) err_limit(fs, l, m)
    200 #define checklimitgt(fs, v, l, m)	if ((v) > (l)) err_limit(fs, l, m)
    201 #define checkcond(ls, c, em)		{ if (!(c)) err_syntax(ls, em); }
    202 
    203 /* -- Management of constants --------------------------------------------- */
    204 
    205 /* Return bytecode encoding for primitive constant. */
    206 #define const_pri(e)		check_exp((e)->k <= VKTRUE, (e)->k)
    207 
    208 #define tvhaskslot(o)	((o)->u32.hi == 0)
    209 #define tvkslot(o)	((o)->u32.lo)
    210 
    211 /* Add a number constant. */
    212 static BCReg const_num(FuncState *fs, ExpDesc *e)
    213 {
    214   lua_State *L = fs->L;
    215   TValue *o;
    216   lua_assert(expr_isnumk(e));
    217   o = lj_tab_set(L, fs->kt, &e->u.nval);
    218   if (tvhaskslot(o))
    219     return tvkslot(o);
    220   o->u64 = fs->nkn;
    221   return fs->nkn++;
    222 }
    223 
    224 /* Add a GC object constant. */
    225 static BCReg const_gc(FuncState *fs, GCobj *gc, uint32_t itype)
    226 {
    227   lua_State *L = fs->L;
    228   TValue key, *o;
    229   setgcV(L, &key, gc, itype);
    230   /* NOBARRIER: the key is new or kept alive. */
    231   o = lj_tab_set(L, fs->kt, &key);
    232   if (tvhaskslot(o))
    233     return tvkslot(o);
    234   o->u64 = fs->nkgc;
    235   return fs->nkgc++;
    236 }
    237 
    238 /* Add a string constant. */
    239 static BCReg const_str(FuncState *fs, ExpDesc *e)
    240 {
    241   lua_assert(expr_isstrk(e) || e->k == VGLOBAL);
    242   return const_gc(fs, obj2gco(e->u.sval), LJ_TSTR);
    243 }
    244 
    245 /* Anchor string constant to avoid GC. */
    246 GCstr *lj_parse_keepstr(LexState *ls, const char *str, size_t len)
    247 {
    248   /* NOBARRIER: the key is new or kept alive. */
    249   lua_State *L = ls->L;
    250   GCstr *s = lj_str_new(L, str, len);
    251   TValue *tv = lj_tab_setstr(L, ls->fs->kt, s);
    252   if (tvisnil(tv)) setboolV(tv, 1);
    253   lj_gc_check(L);
    254   return s;
    255 }
    256 
    257 #if LJ_HASFFI
    258 /* Anchor cdata to avoid GC. */
    259 void lj_parse_keepcdata(LexState *ls, TValue *tv, GCcdata *cd)
    260 {
    261   /* NOBARRIER: the key is new or kept alive. */
    262   lua_State *L = ls->L;
    263   setcdataV(L, tv, cd);
    264   setboolV(lj_tab_set(L, ls->fs->kt, tv), 1);
    265 }
    266 #endif
    267 
    268 /* -- Jump list handling -------------------------------------------------- */
    269 
    270 /* Get next element in jump list. */
    271 static BCPos jmp_next(FuncState *fs, BCPos pc)
    272 {
    273   ptrdiff_t delta = bc_j(fs->bcbase[pc].ins);
    274   if ((BCPos)delta == NO_JMP)
    275     return NO_JMP;
    276   else
    277     return (BCPos)(((ptrdiff_t)pc+1)+delta);
    278 }
    279 
    280 /* Check if any of the instructions on the jump list produce no value. */
    281 static int jmp_novalue(FuncState *fs, BCPos list)
    282 {
    283   for (; list != NO_JMP; list = jmp_next(fs, list)) {
    284     BCIns p = fs->bcbase[list >= 1 ? list-1 : list].ins;
    285     if (!(bc_op(p) == BC_ISTC || bc_op(p) == BC_ISFC || bc_a(p) == NO_REG))
    286       return 1;
    287   }
    288   return 0;
    289 }
    290 
    291 /* Patch register of test instructions. */
    292 static int jmp_patchtestreg(FuncState *fs, BCPos pc, BCReg reg)
    293 {
    294   BCInsLine *ilp = &fs->bcbase[pc >= 1 ? pc-1 : pc];
    295   BCOp op = bc_op(ilp->ins);
    296   if (op == BC_ISTC || op == BC_ISFC) {
    297     if (reg != NO_REG && reg != bc_d(ilp->ins)) {
    298       setbc_a(&ilp->ins, reg);
    299     } else {  /* Nothing to store or already in the right register. */
    300       setbc_op(&ilp->ins, op+(BC_IST-BC_ISTC));
    301       setbc_a(&ilp->ins, 0);
    302     }
    303   } else if (bc_a(ilp->ins) == NO_REG) {
    304     if (reg == NO_REG) {
    305       ilp->ins = BCINS_AJ(BC_JMP, bc_a(fs->bcbase[pc].ins), 0);
    306     } else {
    307       setbc_a(&ilp->ins, reg);
    308       if (reg >= bc_a(ilp[1].ins))
    309 	setbc_a(&ilp[1].ins, reg+1);
    310     }
    311   } else {
    312     return 0;  /* Cannot patch other instructions. */
    313   }
    314   return 1;
    315 }
    316 
    317 /* Drop values for all instructions on jump list. */
    318 static void jmp_dropval(FuncState *fs, BCPos list)
    319 {
    320   for (; list != NO_JMP; list = jmp_next(fs, list))
    321     jmp_patchtestreg(fs, list, NO_REG);
    322 }
    323 
    324 /* Patch jump instruction to target. */
    325 static void jmp_patchins(FuncState *fs, BCPos pc, BCPos dest)
    326 {
    327   BCIns *jmp = &fs->bcbase[pc].ins;
    328   BCPos offset = dest-(pc+1)+BCBIAS_J;
    329   lua_assert(dest != NO_JMP);
    330   if (offset > BCMAX_D)
    331     err_syntax(fs->ls, LJ_ERR_XJUMP);
    332   setbc_d(jmp, offset);
    333 }
    334 
    335 /* Append to jump list. */
    336 static void jmp_append(FuncState *fs, BCPos *l1, BCPos l2)
    337 {
    338   if (l2 == NO_JMP) {
    339     return;
    340   } else if (*l1 == NO_JMP) {
    341     *l1 = l2;
    342   } else {
    343     BCPos list = *l1;
    344     BCPos next;
    345     while ((next = jmp_next(fs, list)) != NO_JMP)  /* Find last element. */
    346       list = next;
    347     jmp_patchins(fs, list, l2);
    348   }
    349 }
    350 
    351 /* Patch jump list and preserve produced values. */
    352 static void jmp_patchval(FuncState *fs, BCPos list, BCPos vtarget,
    353 			 BCReg reg, BCPos dtarget)
    354 {
    355   while (list != NO_JMP) {
    356     BCPos next = jmp_next(fs, list);
    357     if (jmp_patchtestreg(fs, list, reg))
    358       jmp_patchins(fs, list, vtarget);  /* Jump to target with value. */
    359     else
    360       jmp_patchins(fs, list, dtarget);  /* Jump to default target. */
    361     list = next;
    362   }
    363 }
    364 
    365 /* Jump to following instruction. Append to list of pending jumps. */
    366 static void jmp_tohere(FuncState *fs, BCPos list)
    367 {
    368   fs->lasttarget = fs->pc;
    369   jmp_append(fs, &fs->jpc, list);
    370 }
    371 
    372 /* Patch jump list to target. */
    373 static void jmp_patch(FuncState *fs, BCPos list, BCPos target)
    374 {
    375   if (target == fs->pc) {
    376     jmp_tohere(fs, list);
    377   } else {
    378     lua_assert(target < fs->pc);
    379     jmp_patchval(fs, list, target, NO_REG, target);
    380   }
    381 }
    382 
    383 /* -- Bytecode register allocator ----------------------------------------- */
    384 
    385 /* Bump frame size. */
    386 static void bcreg_bump(FuncState *fs, BCReg n)
    387 {
    388   BCReg sz = fs->freereg + n;
    389   if (sz > fs->framesize) {
    390     if (sz >= LJ_MAX_SLOTS)
    391       err_syntax(fs->ls, LJ_ERR_XSLOTS);
    392     fs->framesize = (uint8_t)sz;
    393   }
    394 }
    395 
    396 /* Reserve registers. */
    397 static void bcreg_reserve(FuncState *fs, BCReg n)
    398 {
    399   bcreg_bump(fs, n);
    400   fs->freereg += n;
    401 }
    402 
    403 /* Free register. */
    404 static void bcreg_free(FuncState *fs, BCReg reg)
    405 {
    406   if (reg >= fs->nactvar) {
    407     fs->freereg--;
    408     lua_assert(reg == fs->freereg);
    409   }
    410 }
    411 
    412 /* Free register for expression. */
    413 static void expr_free(FuncState *fs, ExpDesc *e)
    414 {
    415   if (e->k == VNONRELOC)
    416     bcreg_free(fs, e->u.s.info);
    417 }
    418 
    419 /* -- Bytecode emitter ---------------------------------------------------- */
    420 
    421 /* Emit bytecode instruction. */
    422 static BCPos bcemit_INS(FuncState *fs, BCIns ins)
    423 {
    424   BCPos pc = fs->pc;
    425   LexState *ls = fs->ls;
    426   jmp_patchval(fs, fs->jpc, pc, NO_REG, pc);
    427   fs->jpc = NO_JMP;
    428   if (LJ_UNLIKELY(pc >= fs->bclim)) {
    429     ptrdiff_t base = fs->bcbase - ls->bcstack;
    430     checklimit(fs, ls->sizebcstack, LJ_MAX_BCINS, "bytecode instructions");
    431     lj_mem_growvec(fs->L, ls->bcstack, ls->sizebcstack, LJ_MAX_BCINS,BCInsLine);
    432     fs->bclim = (BCPos)(ls->sizebcstack - base);
    433     fs->bcbase = ls->bcstack + base;
    434   }
    435   fs->bcbase[pc].ins = ins;
    436   fs->bcbase[pc].line = ls->lastline;
    437   fs->pc = pc+1;
    438   return pc;
    439 }
    440 
    441 #define bcemit_ABC(fs, o, a, b, c)	bcemit_INS(fs, BCINS_ABC(o, a, b, c))
    442 #define bcemit_AD(fs, o, a, d)		bcemit_INS(fs, BCINS_AD(o, a, d))
    443 #define bcemit_AJ(fs, o, a, j)		bcemit_INS(fs, BCINS_AJ(o, a, j))
    444 
    445 #define bcptr(fs, e)			(&(fs)->bcbase[(e)->u.s.info].ins)
    446 
    447 /* -- Bytecode emitter for expressions ------------------------------------ */
    448 
    449 static BCReg expr_toanyreg(FuncState *fs, ExpDesc *e);
    450 /* Discharge non-constant expression to any register. */
    451 static void expr_discharge(FuncState *fs, ExpDesc *e)
    452 {
    453   BCIns ins;
    454   if (e->k == VUPVAL) {
    455     ins = BCINS_AD(BC_UGET, 0, e->u.s.info);
    456   } else if (e->k == VGLOBAL) {
    457     ins = BCINS_AD(BC_GGET, 0, const_str(fs, e));
    458   } else if (e->k == VINDEXED) {
    459     BCReg rc = e->u.s.aux;
    460     if ((int32_t)rc < 0) {
    461       ins = BCINS_ABC(BC_TGETS, 0, e->u.s.info, ~rc);
    462     } else if (rc > BCMAX_C) {
    463       ins = BCINS_ABC(BC_TGETB, 0, e->u.s.info, rc-(BCMAX_C+1));
    464     } else {
    465       bcreg_free(fs, rc);
    466       ins = BCINS_ABC(BC_TGETV, 0, e->u.s.info, rc);
    467     }
    468     bcreg_free(fs, e->u.s.info);
    469   } else if (e->k == VCALL) {
    470     e->u.s.info = e->u.s.aux;
    471     e->k = VNONRELOC;
    472     return;
    473   } else if (e->k == VLOCAL) {
    474     e->k = VNONRELOC;
    475     return;
    476   } else {
    477     return;
    478   }
    479   e->u.s.info = bcemit_INS(fs, ins);
    480   e->k = VRELOCABLE;
    481 }
    482 
    483 /* Emit bytecode to set a range of registers to nil. */
    484 static void bcemit_nil(FuncState *fs, BCReg from, BCReg n)
    485 {
    486   if (fs->pc > fs->lasttarget) {  /* No jumps to current position? */
    487     BCIns *ip = &fs->bcbase[fs->pc-1].ins;
    488     BCReg pto, pfrom = bc_a(*ip);
    489     switch (bc_op(*ip)) {  /* Try to merge with the previous instruction. */
    490     case BC_KPRI:
    491       if (bc_d(*ip) != ~LJ_TNIL) break;
    492       if (from == pfrom) {
    493 	if (n == 1) return;
    494       } else if (from == pfrom+1) {
    495 	from = pfrom;
    496 	n++;
    497       } else {
    498 	break;
    499       }
    500       *ip = BCINS_AD(BC_KNIL, from, from+n-1);  /* Replace KPRI. */
    501       return;
    502     case BC_KNIL:
    503       pto = bc_d(*ip);
    504       if (pfrom <= from && from <= pto+1) {  /* Can we connect both ranges? */
    505 	if (from+n-1 > pto)
    506 	  setbc_d(ip, from+n-1);  /* Patch previous instruction range. */
    507 	return;
    508       }
    509       break;
    510     default:
    511       break;
    512     }
    513   }
    514   /* Emit new instruction or replace old instruction. */
    515   bcemit_INS(fs, n == 1 ? BCINS_AD(BC_KPRI, from, VKNIL) :
    516 			  BCINS_AD(BC_KNIL, from, from+n-1));
    517 }
    518 
    519 /* Discharge an expression to a specific register. Ignore branches. */
    520 static void expr_toreg_nobranch(FuncState *fs, ExpDesc *e, BCReg reg)
    521 {
    522   BCIns ins;
    523   expr_discharge(fs, e);
    524   if (e->k == VKSTR) {
    525     ins = BCINS_AD(BC_KSTR, reg, const_str(fs, e));
    526   } else if (e->k == VKNUM) {
    527 #if LJ_DUALNUM
    528     cTValue *tv = expr_numtv(e);
    529     if (tvisint(tv) && checki16(intV(tv)))
    530       ins = BCINS_AD(BC_KSHORT, reg, (BCReg)(uint16_t)intV(tv));
    531     else
    532 #else
    533     lua_Number n = expr_numberV(e);
    534     int32_t k = lj_num2int(n);
    535     if (checki16(k) && n == (lua_Number)k)
    536       ins = BCINS_AD(BC_KSHORT, reg, (BCReg)(uint16_t)k);
    537     else
    538 #endif
    539       ins = BCINS_AD(BC_KNUM, reg, const_num(fs, e));
    540 #if LJ_HASFFI
    541   } else if (e->k == VKCDATA) {
    542     fs->flags |= PROTO_FFI;
    543     ins = BCINS_AD(BC_KCDATA, reg,
    544 		   const_gc(fs, obj2gco(cdataV(&e->u.nval)), LJ_TCDATA));
    545 #endif
    546   } else if (e->k == VRELOCABLE) {
    547     setbc_a(bcptr(fs, e), reg);
    548     goto noins;
    549   } else if (e->k == VNONRELOC) {
    550     if (reg == e->u.s.info)
    551       goto noins;
    552     ins = BCINS_AD(BC_MOV, reg, e->u.s.info);
    553   } else if (e->k == VKNIL) {
    554     bcemit_nil(fs, reg, 1);
    555     goto noins;
    556   } else if (e->k <= VKTRUE) {
    557     ins = BCINS_AD(BC_KPRI, reg, const_pri(e));
    558   } else {
    559     lua_assert(e->k == VVOID || e->k == VJMP);
    560     return;
    561   }
    562   bcemit_INS(fs, ins);
    563 noins:
    564   e->u.s.info = reg;
    565   e->k = VNONRELOC;
    566 }
    567 
    568 /* Forward declaration. */
    569 static BCPos bcemit_jmp(FuncState *fs);
    570 
    571 /* Discharge an expression to a specific register. */
    572 static void expr_toreg(FuncState *fs, ExpDesc *e, BCReg reg)
    573 {
    574   expr_toreg_nobranch(fs, e, reg);
    575   if (e->k == VJMP)
    576     jmp_append(fs, &e->t, e->u.s.info);  /* Add it to the true jump list. */
    577   if (expr_hasjump(e)) {  /* Discharge expression with branches. */
    578     BCPos jend, jfalse = NO_JMP, jtrue = NO_JMP;
    579     if (jmp_novalue(fs, e->t) || jmp_novalue(fs, e->f)) {
    580       BCPos jval = (e->k == VJMP) ? NO_JMP : bcemit_jmp(fs);
    581       jfalse = bcemit_AD(fs, BC_KPRI, reg, VKFALSE);
    582       bcemit_AJ(fs, BC_JMP, fs->freereg, 1);
    583       jtrue = bcemit_AD(fs, BC_KPRI, reg, VKTRUE);
    584       jmp_tohere(fs, jval);
    585     }
    586     jend = fs->pc;
    587     fs->lasttarget = jend;
    588     jmp_patchval(fs, e->f, jend, reg, jfalse);
    589     jmp_patchval(fs, e->t, jend, reg, jtrue);
    590   }
    591   e->f = e->t = NO_JMP;
    592   e->u.s.info = reg;
    593   e->k = VNONRELOC;
    594 }
    595 
    596 /* Discharge an expression to the next free register. */
    597 static void expr_tonextreg(FuncState *fs, ExpDesc *e)
    598 {
    599   expr_discharge(fs, e);
    600   expr_free(fs, e);
    601   bcreg_reserve(fs, 1);
    602   expr_toreg(fs, e, fs->freereg - 1);
    603 }
    604 
    605 /* Discharge an expression to any register. */
    606 static BCReg expr_toanyreg(FuncState *fs, ExpDesc *e)
    607 {
    608   expr_discharge(fs, e);
    609   if (e->k == VNONRELOC) {
    610     if (!expr_hasjump(e)) return e->u.s.info;  /* Already in a register. */
    611     if (e->u.s.info >= fs->nactvar) {
    612       expr_toreg(fs, e, e->u.s.info);  /* Discharge to temp. register. */
    613       return e->u.s.info;
    614     }
    615   }
    616   expr_tonextreg(fs, e);  /* Discharge to next register. */
    617   return e->u.s.info;
    618 }
    619 
    620 /* Partially discharge expression to a value. */
    621 static void expr_toval(FuncState *fs, ExpDesc *e)
    622 {
    623   if (expr_hasjump(e))
    624     expr_toanyreg(fs, e);
    625   else
    626     expr_discharge(fs, e);
    627 }
    628 
    629 /* Emit store for LHS expression. */
    630 static void bcemit_store(FuncState *fs, ExpDesc *var, ExpDesc *e)
    631 {
    632   BCIns ins;
    633   if (var->k == VLOCAL) {
    634     fs->ls->vstack[var->u.s.aux].info |= VSTACK_VAR_RW;
    635     expr_free(fs, e);
    636     expr_toreg(fs, e, var->u.s.info);
    637     return;
    638   } else if (var->k == VUPVAL) {
    639     fs->ls->vstack[var->u.s.aux].info |= VSTACK_VAR_RW;
    640     expr_toval(fs, e);
    641     /* setting _ENV is special opcode */
    642     if (var->u.s.aux == 0)
    643       ins = BCINS_AD(BC_ESETV, var->u.s.info, expr_toanyreg(fs, e));
    644     else if (e->k <= VKTRUE)
    645       ins = BCINS_AD(BC_USETP, var->u.s.info, const_pri(e));
    646     else if (e->k == VKSTR)
    647       ins = BCINS_AD(BC_USETS, var->u.s.info, const_str(fs, e));
    648     else if (e->k == VKNUM)
    649       ins = BCINS_AD(BC_USETN, var->u.s.info, const_num(fs, e));
    650     else
    651       ins = BCINS_AD(BC_USETV, var->u.s.info, expr_toanyreg(fs, e));
    652   } else if (var->k == VGLOBAL) {
    653     BCReg ra = expr_toanyreg(fs, e);
    654     ins = BCINS_AD(BC_GSET, ra, const_str(fs, var));
    655   } else {
    656     BCReg ra, rc;
    657     lua_assert(var->k == VINDEXED);
    658     ra = expr_toanyreg(fs, e);
    659     rc = var->u.s.aux;
    660     if ((int32_t)rc < 0) {
    661       ins = BCINS_ABC(BC_TSETS, ra, var->u.s.info, ~rc);
    662     } else if (rc > BCMAX_C) {
    663       ins = BCINS_ABC(BC_TSETB, ra, var->u.s.info, rc-(BCMAX_C+1));
    664     } else {
    665       /* Free late alloced key reg to avoid assert on free of value reg. */
    666       /* This can only happen when called from expr_table(). */
    667       lua_assert(e->k != VNONRELOC || ra < fs->nactvar ||
    668 		 rc < ra || (bcreg_free(fs, rc),1));
    669       ins = BCINS_ABC(BC_TSETV, ra, var->u.s.info, rc);
    670     }
    671   }
    672   bcemit_INS(fs, ins);
    673   expr_free(fs, e);
    674 }
    675 
    676 /* Emit method lookup expression. */
    677 static void bcemit_method(FuncState *fs, ExpDesc *e, ExpDesc *key)
    678 {
    679   BCReg idx, func, obj = expr_toanyreg(fs, e);
    680   expr_free(fs, e);
    681   func = fs->freereg;
    682   bcemit_AD(fs, BC_MOV, func+1+LJ_FR2, obj);  /* Copy object to 1st argument. */
    683   lua_assert(expr_isstrk(key));
    684   idx = const_str(fs, key);
    685   if (idx <= BCMAX_C) {
    686     bcreg_reserve(fs, 2+LJ_FR2);
    687     bcemit_ABC(fs, BC_TGETS, func, obj, idx);
    688   } else {
    689     bcreg_reserve(fs, 3+LJ_FR2);
    690     bcemit_AD(fs, BC_KSTR, func+2+LJ_FR2, idx);
    691     bcemit_ABC(fs, BC_TGETV, func, obj, func+2+LJ_FR2);
    692     fs->freereg--;
    693   }
    694   e->u.s.info = func;
    695   e->k = VNONRELOC;
    696 }
    697 
    698 /* -- Bytecode emitter for branches --------------------------------------- */
    699 
    700 /* Emit unconditional branch. */
    701 static BCPos bcemit_jmp(FuncState *fs)
    702 {
    703   BCPos jpc = fs->jpc;
    704   BCPos j = fs->pc - 1;
    705   BCIns *ip = &fs->bcbase[j].ins;
    706   fs->jpc = NO_JMP;
    707   if ((int32_t)j >= (int32_t)fs->lasttarget && bc_op(*ip) == BC_UCLO) {
    708     setbc_j(ip, NO_JMP);
    709     fs->lasttarget = j+1;
    710   } else {
    711     j = bcemit_AJ(fs, BC_JMP, fs->freereg, NO_JMP);
    712   }
    713   jmp_append(fs, &j, jpc);
    714   return j;
    715 }
    716 
    717 /* Invert branch condition of bytecode instruction. */
    718 static void invertcond(FuncState *fs, ExpDesc *e)
    719 {
    720   BCIns *ip = &fs->bcbase[e->u.s.info - 1].ins;
    721   setbc_op(ip, bc_op(*ip)^1);
    722 }
    723 
    724 /* Emit conditional branch. */
    725 static BCPos bcemit_branch(FuncState *fs, ExpDesc *e, int cond)
    726 {
    727   BCPos pc;
    728   if (e->k == VRELOCABLE) {
    729     BCIns *ip = bcptr(fs, e);
    730     if (bc_op(*ip) == BC_NOT) {
    731       *ip = BCINS_AD(cond ? BC_ISF : BC_IST, 0, bc_d(*ip));
    732       return bcemit_jmp(fs);
    733     }
    734   }
    735   if (e->k != VNONRELOC) {
    736     bcreg_reserve(fs, 1);
    737     expr_toreg_nobranch(fs, e, fs->freereg-1);
    738   }
    739   bcemit_AD(fs, cond ? BC_ISTC : BC_ISFC, NO_REG, e->u.s.info);
    740   pc = bcemit_jmp(fs);
    741   expr_free(fs, e);
    742   return pc;
    743 }
    744 
    745 /* Emit branch on true condition. */
    746 static void bcemit_branch_t(FuncState *fs, ExpDesc *e)
    747 {
    748   BCPos pc;
    749   expr_discharge(fs, e);
    750   if (e->k == VKSTR || e->k == VKNUM || e->k == VKTRUE)
    751     pc = NO_JMP;  /* Never jump. */
    752   else if (e->k == VJMP)
    753     invertcond(fs, e), pc = e->u.s.info;
    754   else if (e->k == VKFALSE || e->k == VKNIL)
    755     expr_toreg_nobranch(fs, e, NO_REG), pc = bcemit_jmp(fs);
    756   else
    757     pc = bcemit_branch(fs, e, 0);
    758   jmp_append(fs, &e->f, pc);
    759   jmp_tohere(fs, e->t);
    760   e->t = NO_JMP;
    761 }
    762 
    763 /* Emit branch on false condition. */
    764 static void bcemit_branch_f(FuncState *fs, ExpDesc *e)
    765 {
    766   BCPos pc;
    767   expr_discharge(fs, e);
    768   if (e->k == VKNIL || e->k == VKFALSE)
    769     pc = NO_JMP;  /* Never jump. */
    770   else if (e->k == VJMP)
    771     pc = e->u.s.info;
    772   else if (e->k == VKSTR || e->k == VKNUM || e->k == VKTRUE)
    773     expr_toreg_nobranch(fs, e, NO_REG), pc = bcemit_jmp(fs);
    774   else
    775     pc = bcemit_branch(fs, e, 1);
    776   jmp_append(fs, &e->t, pc);
    777   jmp_tohere(fs, e->f);
    778   e->f = NO_JMP;
    779 }
    780 
    781 /* -- Bytecode emitter for operators -------------------------------------- */
    782 
    783 /* Try constant-folding of arithmetic operators. */
    784 static int foldarith(BinOpr opr, ExpDesc *e1, ExpDesc *e2)
    785 {
    786   TValue o;
    787   lua_Number n;
    788   if (!expr_isnumk_nojump(e1) || !expr_isnumk_nojump(e2)) return 0;
    789   n = lj_vm_foldarith(expr_numberV(e1), expr_numberV(e2), (int)opr-OPR_ADD);
    790   setnumV(&o, n);
    791   if (tvisnan(&o) || tvismzero(&o)) return 0;  /* Avoid NaN and -0 as consts. */
    792   if (LJ_DUALNUM) {
    793     int32_t k = lj_num2int(n);
    794     if ((lua_Number)k == n) {
    795       setintV(&e1->u.nval, k);
    796       return 1;
    797     }
    798   }
    799   setnumV(&e1->u.nval, n);
    800   return 1;
    801 }
    802 
    803 /* Emit arithmetic operator. */
    804 static void bcemit_arith(FuncState *fs, BinOpr opr, ExpDesc *e1, ExpDesc *e2)
    805 {
    806   BCReg rb, rc, t;
    807   uint32_t op;
    808   if ((opr < OPR_POW) && foldarith(opr, e1, e2))
    809     return;
    810   if (opr == OPR_POW) {
    811     op = BC_POW;
    812     rc = expr_toanyreg(fs, e2);
    813     rb = expr_toanyreg(fs, e1);
    814 #if LJ_53
    815   } if (opr >= OPR_IDIV) {
    816     op = opr - OPR_IDIV + BC_IDIV;
    817     rc = expr_toanyreg(fs, e2);
    818     rb = expr_toanyreg(fs, e1);
    819 #endif
    820   } else {
    821     op = opr-OPR_ADD+BC_ADDVV;
    822     /* Must discharge 2nd operand first since VINDEXED might free regs. */
    823     expr_toval(fs, e2);
    824     if (expr_isnumk(e2) && (rc = const_num(fs, e2)) <= BCMAX_C)
    825       op -= BC_ADDVV-BC_ADDVN;
    826     else
    827       rc = expr_toanyreg(fs, e2);
    828     /* 1st operand discharged by bcemit_binop_left, but need KNUM/KSHORT. */
    829     lua_assert(expr_isnumk(e1) || e1->k == VNONRELOC);
    830     expr_toval(fs, e1);
    831     /* Avoid two consts to satisfy bytecode constraints. */
    832     if (expr_isnumk(e1) && !expr_isnumk(e2) &&
    833 	(t = const_num(fs, e1)) <= BCMAX_B) {
    834       rb = rc; rc = t; op -= BC_ADDVV-BC_ADDNV;
    835     } else {
    836       rb = expr_toanyreg(fs, e1);
    837     }
    838   }
    839   /* Using expr_free might cause asserts if the order is wrong. */
    840   if (e1->k == VNONRELOC && e1->u.s.info >= fs->nactvar) fs->freereg--;
    841   if (e2->k == VNONRELOC && e2->u.s.info >= fs->nactvar) fs->freereg--;
    842   e1->u.s.info = bcemit_ABC(fs, op, 0, rb, rc);
    843   e1->k = VRELOCABLE;
    844 }
    845 
    846 /* Emit comparison operator. */
    847 static void bcemit_comp(FuncState *fs, BinOpr opr, ExpDesc *e1, ExpDesc *e2)
    848 {
    849   ExpDesc *eret = e1;
    850   BCIns ins;
    851   expr_toval(fs, e1);
    852   if (opr == OPR_EQ || opr == OPR_NE) {
    853     BCOp op = opr == OPR_EQ ? BC_ISEQV : BC_ISNEV;
    854     BCReg ra;
    855     if (expr_isk(e1)) { e1 = e2; e2 = eret; }  /* Need constant in 2nd arg. */
    856     ra = expr_toanyreg(fs, e1);  /* First arg must be in a reg. */
    857     expr_toval(fs, e2);
    858     switch (e2->k) {
    859     case VKNIL: case VKFALSE: case VKTRUE:
    860       ins = BCINS_AD(op+(BC_ISEQP-BC_ISEQV), ra, const_pri(e2));
    861       break;
    862     case VKSTR:
    863       ins = BCINS_AD(op+(BC_ISEQS-BC_ISEQV), ra, const_str(fs, e2));
    864       break;
    865     case VKNUM:
    866       ins = BCINS_AD(op+(BC_ISEQN-BC_ISEQV), ra, const_num(fs, e2));
    867       break;
    868     default:
    869       ins = BCINS_AD(op, ra, expr_toanyreg(fs, e2));
    870       break;
    871     }
    872   } else {
    873     uint32_t op = opr-OPR_LT+BC_ISLT;
    874     BCReg ra, rd;
    875     if ((op-BC_ISLT) & 1) {  /* GT -> LT, GE -> LE */
    876       e1 = e2; e2 = eret;  /* Swap operands. */
    877       op = ((op-BC_ISLT)^3)+BC_ISLT;
    878       expr_toval(fs, e1);
    879     }
    880     rd = expr_toanyreg(fs, e2);
    881     ra = expr_toanyreg(fs, e1);
    882     ins = BCINS_AD(op, ra, rd);
    883   }
    884   /* Using expr_free might cause asserts if the order is wrong. */
    885   if (e1->k == VNONRELOC && e1->u.s.info >= fs->nactvar) fs->freereg--;
    886   if (e2->k == VNONRELOC && e2->u.s.info >= fs->nactvar) fs->freereg--;
    887   bcemit_INS(fs, ins);
    888   eret->u.s.info = bcemit_jmp(fs);
    889   eret->k = VJMP;
    890 }
    891 
    892 /* Fixup left side of binary operator. */
    893 static void bcemit_binop_left(FuncState *fs, BinOpr op, ExpDesc *e)
    894 {
    895   if (op == OPR_AND) {
    896     bcemit_branch_t(fs, e);
    897   } else if (op == OPR_OR) {
    898     bcemit_branch_f(fs, e);
    899   } else if (op == OPR_CONCAT) {
    900     expr_tonextreg(fs, e);
    901   } else if (op == OPR_EQ || op == OPR_NE) {
    902     if (!expr_isk_nojump(e)) expr_toanyreg(fs, e);
    903   } else {
    904     if (!expr_isnumk_nojump(e)) expr_toanyreg(fs, e);
    905   }
    906 }
    907 
    908 /* Emit binary operator. */
    909 static void bcemit_binop(FuncState *fs, BinOpr op, ExpDesc *e1, ExpDesc *e2)
    910 {
    911   if (op <= OPR_ARITH_LAST) {
    912     bcemit_arith(fs, op, e1, e2);
    913   } else if (op == OPR_AND) {
    914     lua_assert(e1->t == NO_JMP);  /* List must be closed. */
    915     expr_discharge(fs, e2);
    916     jmp_append(fs, &e2->f, e1->f);
    917     *e1 = *e2;
    918   } else if (op == OPR_OR) {
    919     lua_assert(e1->f == NO_JMP);  /* List must be closed. */
    920     expr_discharge(fs, e2);
    921     jmp_append(fs, &e2->t, e1->t);
    922     *e1 = *e2;
    923   } else if (op == OPR_CONCAT) {
    924     expr_toval(fs, e2);
    925     if (e2->k == VRELOCABLE && bc_op(*bcptr(fs, e2)) == BC_CAT) {
    926       lua_assert(e1->u.s.info == bc_b(*bcptr(fs, e2))-1);
    927       expr_free(fs, e1);
    928       setbc_b(bcptr(fs, e2), e1->u.s.info);
    929       e1->u.s.info = e2->u.s.info;
    930     } else {
    931       expr_tonextreg(fs, e2);
    932       expr_free(fs, e2);
    933       expr_free(fs, e1);
    934       e1->u.s.info = bcemit_ABC(fs, BC_CAT, 0, e1->u.s.info, e2->u.s.info);
    935     }
    936     e1->k = VRELOCABLE;
    937   } else {
    938     lua_assert(op == OPR_NE || op == OPR_EQ ||
    939 	       op == OPR_LT || op == OPR_GE || op == OPR_LE || op == OPR_GT);
    940     bcemit_comp(fs, op, e1, e2);
    941   }
    942 }
    943 
    944 /* Emit unary operator. */
    945 static void bcemit_unop(FuncState *fs, BCOp op, ExpDesc *e)
    946 {
    947   if (op == BC_NOT) {
    948     /* Swap true and false lists. */
    949     { BCPos temp = e->f; e->f = e->t; e->t = temp; }
    950     jmp_dropval(fs, e->f);
    951     jmp_dropval(fs, e->t);
    952     expr_discharge(fs, e);
    953     if (e->k == VKNIL || e->k == VKFALSE) {
    954       e->k = VKTRUE;
    955       return;
    956     } else if (expr_isk(e) || (LJ_HASFFI && e->k == VKCDATA)) {
    957       e->k = VKFALSE;
    958       return;
    959     } else if (e->k == VJMP) {
    960       invertcond(fs, e);
    961       return;
    962     } else if (e->k == VRELOCABLE) {
    963       bcreg_reserve(fs, 1);
    964       setbc_a(bcptr(fs, e), fs->freereg-1);
    965       e->u.s.info = fs->freereg-1;
    966       e->k = VNONRELOC;
    967     } else {
    968       lua_assert(e->k == VNONRELOC);
    969     }
    970   } else {
    971     lua_assert(op == BC_UNM || op == BC_LEN || op == BC_BNOT);
    972     if (op == BC_UNM && !expr_hasjump(e)) {  /* Constant-fold negations. */
    973 #if LJ_HASFFI
    974       if (e->k == VKCDATA) {  /* Fold in-place since cdata is not interned. */
    975 	GCcdata *cd = cdataV(&e->u.nval);
    976 	int64_t *p = (int64_t *)cdataptr(cd);
    977 	if (cd->ctypeid == CTID_COMPLEX_DOUBLE)
    978 	  p[1] ^= (int64_t)U64x(80000000,00000000);
    979 	else
    980 	  *p = -*p;
    981 	return;
    982       } else
    983 #endif
    984       if (expr_isnumk(e) && !expr_numiszero(e)) {  /* Avoid folding to -0. */
    985 	TValue *o = expr_numtv(e);
    986 	if (tvisint(o)) {
    987 	  int32_t k = intV(o);
    988 	  if (k == -k)
    989 	    setnumV(o, -(lua_Number)k);
    990 	  else
    991 	    setintV(o, -k);
    992 	  return;
    993 	} else {
    994 	  o->u64 ^= U64x(80000000,00000000);
    995 	  return;
    996 	}
    997       }
    998     }
    999     expr_toanyreg(fs, e);
   1000   }
   1001   expr_free(fs, e);
   1002   e->u.s.info = bcemit_AD(fs, op, 0, e->u.s.info);
   1003   e->k = VRELOCABLE;
   1004 }
   1005 
   1006 /* -- Lexer support ------------------------------------------------------- */
   1007 
   1008 /* Check and consume optional token. */
   1009 static int lex_opt(LexState *ls, LexToken tok)
   1010 {
   1011   if (ls->tok == tok) {
   1012     lj_lex_next(ls);
   1013     return 1;
   1014   }
   1015   return 0;
   1016 }
   1017 
   1018 /* Check and consume token. */
   1019 static void lex_check(LexState *ls, LexToken tok)
   1020 {
   1021   if (ls->tok != tok)
   1022     err_token(ls, tok);
   1023   lj_lex_next(ls);
   1024 }
   1025 
   1026 /* Check for matching token. */
   1027 static void lex_match(LexState *ls, LexToken what, LexToken who, BCLine line)
   1028 {
   1029   if (!lex_opt(ls, what)) {
   1030     if (line == ls->linenumber) {
   1031       err_token(ls, what);
   1032     } else {
   1033       const char *swhat = lj_lex_token2str(ls, what);
   1034       const char *swho = lj_lex_token2str(ls, who);
   1035       lj_lex_error(ls, ls->tok, LJ_ERR_XMATCH, swhat, swho, line);
   1036     }
   1037   }
   1038 }
   1039 
   1040 /* Check for string token. */
   1041 static GCstr *lex_str(LexState *ls)
   1042 {
   1043   GCstr *s;
   1044   if (ls->tok != TK_name && ((!LJ_51) || ls->tok != TK_goto))
   1045     err_token(ls, TK_name);
   1046   s = strV(&ls->tokval);
   1047   lj_lex_next(ls);
   1048   return s;
   1049 }
   1050 
   1051 /* -- Variable handling --------------------------------------------------- */
   1052 
   1053 #define var_get(ls, fs, i)	((ls)->vstack[(fs)->varmap[(i)]])
   1054 
   1055 /* Define a new local variable. */
   1056 static void var_new(LexState *ls, BCReg n, GCstr *name)
   1057 {
   1058   FuncState *fs = ls->fs;
   1059   MSize vtop = ls->vtop;
   1060   checklimit(fs, fs->nactvar+n, LJ_MAX_LOCVAR, "local variables");
   1061   if (LJ_UNLIKELY(vtop >= ls->sizevstack)) {
   1062     if (ls->sizevstack >= LJ_MAX_VSTACK)
   1063       lj_lex_error(ls, 0, LJ_ERR_XLIMC, LJ_MAX_VSTACK);
   1064     lj_mem_growvec(ls->L, ls->vstack, ls->sizevstack, LJ_MAX_VSTACK, VarInfo);
   1065   }
   1066   lua_assert((uintptr_t)name < VARNAME__MAX ||
   1067 	     lj_tab_getstr(fs->kt, name) != NULL);
   1068   /* NOBARRIER: name is anchored in fs->kt and ls->vstack is not a GCobj. */
   1069   setgcref(ls->vstack[vtop].name, obj2gco(name));
   1070   fs->varmap[fs->nactvar+n] = (uint16_t)vtop;
   1071   ls->vtop = vtop+1;
   1072 }
   1073 
   1074 #define var_new_lit(ls, n, v) \
   1075   var_new(ls, (n), lj_parse_keepstr(ls, "" v, sizeof(v)-1))
   1076 
   1077 #define var_new_fixed(ls, n, vn) \
   1078   var_new(ls, (n), (GCstr *)(uintptr_t)(vn))
   1079 
   1080 /* Add local variables. */
   1081 static void var_add(LexState *ls, BCReg nvars)
   1082 {
   1083   FuncState *fs = ls->fs;
   1084   BCReg nactvar = fs->nactvar;
   1085   while (nvars--) {
   1086     VarInfo *v = &var_get(ls, fs, nactvar);
   1087     v->startpc = fs->pc;
   1088     v->slot = nactvar++;
   1089     v->info = 0;
   1090   }
   1091   fs->nactvar = nactvar;
   1092 }
   1093 
   1094 /* Remove local variables. */
   1095 static void var_remove(LexState *ls, BCReg tolevel)
   1096 {
   1097   FuncState *fs = ls->fs;
   1098   while (fs->nactvar > tolevel) {
   1099     var_get(ls, fs, --fs->nactvar).endpc = fs->pc;
   1100   }
   1101 }
   1102 
   1103 /* Mark scope as having an upvalue. */
   1104 static void fscope_uvmark(FuncState *fs, BCReg level)
   1105 {
   1106   FuncScope *bl;
   1107   for (bl = fs->bl; bl && bl->nactvar > level; bl = bl->prev)
   1108     ;
   1109   if (bl)
   1110     bl->flags |= FSCOPE_UPVAL;
   1111 }
   1112 
   1113 
   1114 static void expr_index(FuncState *fs, ExpDesc *t, ExpDesc *e);
   1115 
   1116 /*
   1117  * Look-up variable 'name' in all frames, with _ENV scoping,
   1118  * create upvalue links if necessary.
   1119  *
   1120  * The code is a bit of spaghetti; but avoids recursion.
   1121  * Variable lookups happen a lot.
   1122  */
   1123 static void do_var_lookup(LexState LJ_RESTRICT *ls, ExpDesc LJ_RESTRICT *e, GCstr LJ_RESTRICT *name)
   1124 {
   1125   ExpDesc key;
   1126   int i, uvidx, uvres, vidx, hasenv = 0;
   1127   FuncState LJ_RESTRICT *frame, *uvfs, *fs = ls->fs;
   1128   VarInfo *vstack = ls->vstack;
   1129   GCstr *nref;
   1130 
   1131   /* Walk both upvalues and locals in single loop. */
   1132   for (frame = fs; frame; frame = frame->prev) {
   1133     int nvar = frame->nactvar-1;
   1134     int nuv = frame->nuv;
   1135     /* First, search known locals. */
   1136     for (i = nvar; i >= 0; i--) {
   1137       vidx = frame->varmap[i];
   1138       nref = strref(vstack[vidx].name);
   1139       if (vidx && (nref == ls->env)) hasenv = 1;
   1140       if (nref != name)
   1141         continue;
   1142       /* Found a local. */
   1143       uvidx = e->u.s.aux = vidx;
   1144       if (frame == fs) { /* In our scope. */
   1145         expr_init(e, VLOCAL, i);
   1146         return;
   1147       }
   1148       /* An upvalue. */
   1149       fscope_uvmark(frame, i);
   1150       uvres = fs->nuv; /* If frame == fs->prev. */
   1151       goto link_uvs; /* Link upvalue chain. */
   1152     }
   1153 
   1154     /* Now search upvalues we already know about. */
   1155     for (i = 0; i < nuv; i++) {
   1156       vidx = frame->uvmap[i]; /* vstack[] index. */
   1157       if (vidx == LJ_MAX_VSTACK) continue;
   1158       nref = strref(vstack[vidx].name);
   1159       if (nref != name) continue; /* Not found. */
   1160       uvidx = i | PROTO_UV_CHAINED; /* Used if frame != fs. */
   1161       uvres = i; /* Used if frame == fs. */
   1162       goto link_uvs; /* Extend upvalue chain if necessary. */
   1163     }
   1164   }
   1165 
   1166   /* Nothing found, it is global. */
   1167   do_var_lookup(ls, e, ls->env);
   1168   if (hasenv) { /* lexical _ENV.name */
   1169     expr_init(&key, VKSTR, 0);
   1170     key.u.sval = name;
   1171     expr_toanyreg(ls->fs, e);
   1172     expr_index(ls->fs, e, &key);
   1173     return;
   1174   }
   1175 
   1176   /* Otherwise true global. */
   1177   expr_init(e, VGLOBAL, 0);
   1178   e->u.sval = name;
   1179   return;
   1180 
   1181 link_uvs:;
   1182   uvfs = fs; /* For incrementing refcount. */
   1183   /* Create or extend UV chain to a local. */
   1184   if (frame != fs) { /* Not in origin scope */
   1185     uvres = uvfs->nuv;
   1186     for (; uvfs->prev != frame; uvfs = uvfs->prev) {
   1187       /* Link chain until uvfs->prev = frame. */
   1188       uvfs->uvval[uvfs->nuv] = uvfs->prev->nuv | PROTO_UV_CHAINED;
   1189       uvfs->uvcount[uvfs->nuv] = 1;
   1190       uvfs->uvmap[uvfs->nuv++] = vidx;
   1191     }
   1192     /* And put final pointer there. */
   1193     uvfs->uvval[uvfs->nuv] = uvidx;
   1194     uvfs->uvmap[uvfs->nuv] = vidx;
   1195     uvfs->uvcount[uvfs->nuv++] = 1;
   1196     /* If connected to previous UV chain, bump refcount of all links. */
   1197     while (uvidx & PROTO_UV_CHAINED) {
   1198       uvidx &= PROTO_UV_MASK;
   1199       uvfs = uvfs->prev;
   1200       uvfs->uvcount[uvidx]++;
   1201       uvidx = uvfs->uvval[uvidx];
   1202     }
   1203   } else uvfs->uvcount[uvres]++; /* Resident UV. */
   1204   expr_init(e, VUPVAL, uvres);
   1205   e->u.s.aux = vidx;
   1206 }
   1207 
   1208 #define var_lookup(ls, e) do_var_lookup(ls, e, lex_str(ls))
   1209 
   1210 /* -- Goto an label handling ---------------------------------------------- */
   1211 
   1212 /* Add a new goto or label. */
   1213 static MSize gola_new(LexState *ls, GCstr *name, uint8_t info, BCPos pc)
   1214 {
   1215   FuncState *fs = ls->fs;
   1216   MSize vtop = ls->vtop;
   1217   if (LJ_UNLIKELY(vtop >= ls->sizevstack)) {
   1218     if (ls->sizevstack >= LJ_MAX_VSTACK)
   1219       lj_lex_error(ls, 0, LJ_ERR_XLIMC, LJ_MAX_VSTACK);
   1220     lj_mem_growvec(ls->L, ls->vstack, ls->sizevstack, LJ_MAX_VSTACK, VarInfo);
   1221   }
   1222   lua_assert(name == NAME_BREAK || lj_tab_getstr(fs->kt, name) != NULL);
   1223   /* NOBARRIER: name is anchored in fs->kt and ls->vstack is not a GCobj. */
   1224   setgcref(ls->vstack[vtop].name, obj2gco(name));
   1225   ls->vstack[vtop].startpc = pc;
   1226   ls->vstack[vtop].slot = (uint8_t)fs->nactvar;
   1227   ls->vstack[vtop].info = info;
   1228   ls->vtop = vtop+1;
   1229   return vtop;
   1230 }
   1231 
   1232 #define gola_isgoto(v)		((v)->info & VSTACK_GOTO)
   1233 #define gola_islabel(v)		((v)->info & VSTACK_LABEL)
   1234 #define gola_isgotolabel(v)	((v)->info & (VSTACK_GOTO|VSTACK_LABEL))
   1235 
   1236 /* Patch goto to jump to label. */
   1237 static void gola_patch(LexState *ls, VarInfo *vg, VarInfo *vl)
   1238 {
   1239   FuncState *fs = ls->fs;
   1240   BCPos pc = vg->startpc;
   1241   setgcrefnull(vg->name);  /* Invalidate pending goto. */
   1242   setbc_a(&fs->bcbase[pc].ins, vl->slot);
   1243   jmp_patch(fs, pc, vl->startpc);
   1244 }
   1245 
   1246 /* Patch goto to close upvalues. */
   1247 static void gola_close(LexState *ls, VarInfo *vg)
   1248 {
   1249   FuncState *fs = ls->fs;
   1250   BCPos pc = vg->startpc;
   1251   BCIns *ip = &fs->bcbase[pc].ins;
   1252   lua_assert(gola_isgoto(vg));
   1253   lua_assert(bc_op(*ip) == BC_JMP || bc_op(*ip) == BC_UCLO);
   1254   setbc_a(ip, vg->slot);
   1255   if (bc_op(*ip) == BC_JMP) {
   1256     BCPos next = jmp_next(fs, pc);
   1257     if (next != NO_JMP) jmp_patch(fs, next, pc);  /* Jump to UCLO. */
   1258     setbc_op(ip, BC_UCLO);  /* Turn into UCLO. */
   1259     setbc_j(ip, NO_JMP);
   1260   }
   1261 }
   1262 
   1263 /* Resolve pending forward gotos for label. */
   1264 static void gola_resolve(LexState *ls, FuncScope *bl, MSize idx)
   1265 {
   1266   VarInfo *vg = ls->vstack + bl->vstart;
   1267   VarInfo *vl = ls->vstack + idx;
   1268   for (; vg < vl; vg++)
   1269     if (gcrefeq(vg->name, vl->name) && gola_isgoto(vg)) {
   1270       if (vg->slot < vl->slot) {
   1271 	GCstr *name = strref(var_get(ls, ls->fs, vg->slot).name);
   1272 	lua_assert((uintptr_t)name >= VARNAME__MAX);
   1273 	ls->linenumber = ls->fs->bcbase[vg->startpc].line;
   1274 	lua_assert(strref(vg->name) != NAME_BREAK);
   1275 	lj_lex_error(ls, 0, LJ_ERR_XGSCOPE,
   1276 		     strdata(strref(vg->name)), strdata(name));
   1277       }
   1278       gola_patch(ls, vg, vl);
   1279     }
   1280 }
   1281 
   1282 /* Fixup remaining gotos and labels for scope. */
   1283 static void gola_fixup(LexState *ls, FuncScope *bl)
   1284 {
   1285   VarInfo *v = ls->vstack + bl->vstart;
   1286   VarInfo *ve = ls->vstack + ls->vtop;
   1287   for (; v < ve; v++) {
   1288     GCstr *name = strref(v->name);
   1289     if (name != NULL) {  /* Only consider remaining valid gotos/labels. */
   1290       if (gola_islabel(v)) {
   1291 	VarInfo *vg;
   1292 	setgcrefnull(v->name);  /* Invalidate label that goes out of scope. */
   1293 	for (vg = v+1; vg < ve; vg++)  /* Resolve pending backward gotos. */
   1294 	  if (strref(vg->name) == name && gola_isgoto(vg)) {
   1295 	    if ((bl->flags&FSCOPE_UPVAL) && vg->slot > v->slot)
   1296 	      gola_close(ls, vg);
   1297 	    gola_patch(ls, vg, v);
   1298 	  }
   1299       } else if (gola_isgoto(v)) {
   1300 	if (bl->prev) {  /* Propagate goto or break to outer scope. */
   1301 	  bl->prev->flags |= name == NAME_BREAK ? FSCOPE_BREAK : FSCOPE_GOLA;
   1302 	  v->slot = bl->nactvar;
   1303 	  if ((bl->flags & FSCOPE_UPVAL))
   1304 	    gola_close(ls, v);
   1305 	} else {  /* No outer scope: undefined goto label or no loop. */
   1306 	  ls->linenumber = ls->fs->bcbase[v->startpc].line;
   1307 	  if (name == NAME_BREAK)
   1308 	    lj_lex_error(ls, 0, LJ_ERR_XBREAK);
   1309 	  else
   1310 	    lj_lex_error(ls, 0, LJ_ERR_XLUNDEF, strdata(name));
   1311 	}
   1312       }
   1313     }
   1314   }
   1315 }
   1316 
   1317 /* Find existing label. */
   1318 static VarInfo *gola_findlabel(LexState *ls, GCstr *name)
   1319 {
   1320   VarInfo *v = ls->vstack + ls->fs->bl->vstart;
   1321   VarInfo *ve = ls->vstack + ls->vtop;
   1322   for (; v < ve; v++)
   1323     if (strref(v->name) == name && gola_islabel(v))
   1324       return v;
   1325   return NULL;
   1326 }
   1327 
   1328 /* -- Scope handling ------------------------------------------------------ */
   1329 
   1330 /* Begin a scope. */
   1331 static void fscope_begin(FuncState *fs, FuncScope *bl, int flags)
   1332 {
   1333   bl->nactvar = (uint8_t)fs->nactvar;
   1334   bl->flags = flags;
   1335   bl->vstart = fs->ls->vtop;
   1336   bl->prev = fs->bl;
   1337   fs->bl = bl;
   1338   lua_assert(fs->freereg == fs->nactvar);
   1339 }
   1340 
   1341 /* End a scope. */
   1342 static void fscope_end(FuncState *fs)
   1343 {
   1344   FuncScope *bl = fs->bl;
   1345   LexState *ls = fs->ls;
   1346   fs->bl = bl->prev;
   1347   var_remove(ls, bl->nactvar);
   1348   fs->freereg = fs->nactvar;
   1349   lua_assert(bl->nactvar == fs->nactvar);
   1350   if ((bl->flags & (FSCOPE_UPVAL|FSCOPE_NOCLOSE)) == FSCOPE_UPVAL)
   1351     bcemit_AJ(fs, BC_UCLO, bl->nactvar, 0);
   1352   if ((bl->flags & FSCOPE_BREAK)) {
   1353     if ((bl->flags & FSCOPE_LOOP)) {
   1354       MSize idx = gola_new(ls, NAME_BREAK, VSTACK_LABEL, fs->pc);
   1355       ls->vtop = idx;  /* Drop break label immediately. */
   1356       gola_resolve(ls, bl, idx);
   1357       return;
   1358     }  /* else: need the fixup step to propagate the breaks. */
   1359   } else if (!(bl->flags & FSCOPE_GOLA)) {
   1360     return;
   1361   }
   1362   gola_fixup(ls, bl);
   1363 }
   1364 
   1365 /* -- Function state management ------------------------------------------- */
   1366 
   1367 /* Fixup bytecode for prototype. */
   1368 static void fs_fixup_bc(FuncState *fs, GCproto *pt, BCIns *bc, MSize n)
   1369 {
   1370   BCInsLine *base = fs->bcbase;
   1371   MSize i;
   1372   pt->sizebc = n;
   1373   bc[0] = BCINS_AD((fs->flags & PROTO_VARARG) ? BC_FUNCV : BC_FUNCF,
   1374 		   fs->framesize, 0);
   1375   for (i = 1; i < n; i++)
   1376     bc[i] = base[i].ins;
   1377 }
   1378 
   1379 /* Fixup upvalues for child prototype, step #2. */
   1380 static void fs_fixup_uv2(FuncState *fs, GCproto *pt)
   1381 {
   1382   VarInfo *vstack = fs->ls->vstack;
   1383   uint16_t *uv = proto_uv(pt);
   1384   MSize i, n = pt->sizeuv;
   1385   for (i = 0; i < n; i++) {
   1386     VarIndex vidx = uv[i];
   1387     /* Child uv pointing to our local. Mark immutable if no writes were observed. */
   1388     if (vidx <= PROTO_UV_MASK) {
   1389       uint16_t immu = ((!(vstack[vidx].info & VSTACK_VAR_RW))*PROTO_UV_IMMUTABLE);
   1390       uv[i] = vstack[vidx].slot | immu;
   1391     }
   1392   }
   1393 }
   1394 
   1395 /* Fixup constants for prototype. */
   1396 static void fs_fixup_k(FuncState *fs, GCproto *pt, void *kptr)
   1397 {
   1398   GCtab *kt;
   1399   TValue *array;
   1400   Node *node;
   1401   MSize i, hmask;
   1402   checklimitgt(fs, fs->nkn, BCMAX_D+1, "constants");
   1403   checklimitgt(fs, fs->nkgc, BCMAX_D+1, "constants");
   1404   setmref(pt->k, kptr);
   1405   pt->sizekn = fs->nkn;
   1406   pt->sizekgc = fs->nkgc;
   1407   kt = fs->kt;
   1408   array = tvref(kt->array);
   1409   for (i = 0; i < kt->asize; i++)
   1410     if (tvhaskslot(&array[i])) {
   1411       TValue *tv = &((TValue *)kptr)[tvkslot(&array[i])];
   1412       if (LJ_DUALNUM)
   1413 	setintV(tv, (int32_t)i);
   1414       else
   1415 	setnumV(tv, (lua_Number)i);
   1416     }
   1417   node = noderef(kt->node);
   1418   hmask = kt->hmask;
   1419   for (i = 0; i <= hmask; i++) {
   1420     Node *n = &node[i];
   1421     if (tvhaskslot(&n->val)) {
   1422       ptrdiff_t kidx = (ptrdiff_t)tvkslot(&n->val);
   1423       lua_assert(!tvisint(&n->key));
   1424       if (tvisnum(&n->key)) {
   1425 	TValue *tv = &((TValue *)kptr)[kidx];
   1426 	if (LJ_DUALNUM) {
   1427 	  lua_Number nn = numV(&n->key);
   1428 	  int32_t k = lj_num2int(nn);
   1429 	  lua_assert(!tvismzero(&n->key));
   1430 	  if ((lua_Number)k == nn)
   1431 	    setintV(tv, k);
   1432 	  else
   1433 	    *tv = n->key;
   1434 	} else {
   1435 	  *tv = n->key;
   1436 	}
   1437       } else {
   1438 	GCobj *o = gcV(&n->key);
   1439 	setgcref(((GCRef *)kptr)[~kidx], o);
   1440 	lj_gc_objbarrier(fs->L, pt, o);
   1441 	if (tvisproto(&n->key))
   1442 	  fs_fixup_uv2(fs, gco2pt(o));
   1443       }
   1444     }
   1445   }
   1446 }
   1447 
   1448 /* Attempt to lift closures to upper scopes. */
   1449 static void fs_fixup_uv1(FuncState *fs, GCproto *pt, uint16_t *uv)
   1450 {
   1451   int i;
   1452   uint16_t puv[LJ_MAX_UPVAL];
   1453   FuncState *t,*p = fs;
   1454   int nuv = fs->nuv;
   1455 
   1456   setmref(pt->uv, uv);
   1457   pt->sizeuv = fs->nuv;
   1458   memcpy(uv, fs->uvval, fs->nuv*sizeof(VarIndex));
   1459 
   1460   if (!(L2J(fs->ls->L)->flags & JIT_F_OPT_LLIFT))
   1461     return;
   1462 
   1463   while (p->prev) {
   1464     /* check */
   1465     for (i = 0; i < nuv; i++) {
   1466       if ((uv[i] != PROTO_UV_HOLE) && ((!(uv[i] & PROTO_UV_CHAINED)) && (p->uvcount[i])))
   1467         goto stop;
   1468     }
   1469 
   1470     /* remember status for current fun if next check above bails in next round */
   1471     memcpy(puv, uv, fs->nuv*sizeof(VarIndex));
   1472 
   1473     /* and resolve one step up */
   1474     for (i = 0; i < nuv; i++) {
   1475       if (p->uvcount[i] == 0) /* this uv is dead */
   1476         uv[i] = PROTO_UV_HOLE;
   1477       if (uv[i] == PROTO_UV_HOLE)
   1478         continue;
   1479       if (uv[i] & PROTO_UV_CHAINED) { /* it is chained to prev, resolve */
   1480         p->uvcount[i]--;
   1481         uv[i] = p->prev->uvval[uv[i] & PROTO_UV_MASK];
   1482       } else {
   1483         lua_assert(0);
   1484       }
   1485     }
   1486     p = p->prev;
   1487   }
   1488 stop:;
   1489   /* Lifted? */
   1490   if (p != fs) {
   1491     /* Create uv chain. */
   1492     for (t = fs->prev; t != p; t = t->prev) {
   1493       t->uvcount[t->nuv] = 1;
   1494       t->uvmap[t->nuv] = LJ_MAX_VSTACK;
   1495       t->uvval[t->nuv++] = t->prev->nuv | PROTO_UV_CHAINED;
   1496     }
   1497     /* And install the closure. */
   1498     t->uvval[t->nuv] = const_gc(t, obj2gco(pt), LJ_TPROTO) | PROTO_UV_CLOSURE;
   1499     t->uvmap[t->nuv] = LJ_MAX_VSTACK;
   1500     t->uvcount[t->nuv++] = 1;
   1501     fs->flags = PROTO_LIFTED;
   1502     memcpy(uv, puv, fs->nuv*sizeof(VarIndex));
   1503   }
   1504 }
   1505 
   1506 #ifndef LUAJIT_DISABLE_DEBUGINFO
   1507 /* Prepare lineinfo for prototype. */
   1508 static size_t fs_prep_line(FuncState *fs, BCLine numline)
   1509 {
   1510   return (fs->pc-1) << (numline < 256 ? 0 : numline < 65536 ? 1 : 2);
   1511 }
   1512 
   1513 /* Fixup lineinfo for prototype. */
   1514 static void fs_fixup_line(FuncState *fs, GCproto *pt,
   1515 			  void *lineinfo, BCLine numline)
   1516 {
   1517   BCInsLine *base = fs->bcbase + 1;
   1518   BCLine first = fs->linedefined;
   1519   MSize i = 0, n = fs->pc-1;
   1520   pt->firstline = fs->linedefined;
   1521   pt->numline = numline;
   1522   setmref(pt->lineinfo, lineinfo);
   1523   if (LJ_LIKELY(numline < 256)) {
   1524     uint8_t *li = (uint8_t *)lineinfo;
   1525     do {
   1526       BCLine delta = base[i].line - first;
   1527       lua_assert(delta >= 0 && delta < 256);
   1528       li[i] = (uint8_t)delta;
   1529     } while (++i < n);
   1530   } else if (LJ_LIKELY(numline < 65536)) {
   1531     uint16_t *li = (uint16_t *)lineinfo;
   1532     do {
   1533       BCLine delta = base[i].line - first;
   1534       lua_assert(delta >= 0 && delta < 65536);
   1535       li[i] = (uint16_t)delta;
   1536     } while (++i < n);
   1537   } else {
   1538     uint32_t *li = (uint32_t *)lineinfo;
   1539     do {
   1540       BCLine delta = base[i].line - first;
   1541       lua_assert(delta >= 0);
   1542       li[i] = (uint32_t)delta;
   1543     } while (++i < n);
   1544   }
   1545 }
   1546 
   1547 /* Prepare variable info for prototype. */
   1548 static size_t fs_prep_var(LexState *ls, FuncState *fs, size_t *ofsvar)
   1549 {
   1550   VarInfo *vs =ls->vstack, *ve;
   1551   MSize i, n;
   1552   BCPos lastpc;
   1553   lj_buf_reset(&ls->sb);  /* Copy to temp. string buffer. */
   1554   /* Store upvalue names. */
   1555   for (i = 0, n = fs->nuv; i < n; i++) {
   1556     char *p;
   1557     const char *ss = "";
   1558     MSize len = 1;
   1559     VarIndex idx = fs->uvmap[i];
   1560     /* Named var? */
   1561     if (idx < LJ_MAX_VSTACK) {
   1562       GCstr *s = strref(vs[idx].name);
   1563       len += s->len;
   1564       ss = strdata(s);
   1565     }
   1566     p = lj_buf_more(&ls->sb, len);
   1567     p = lj_buf_wmem(p, ss, len);
   1568     setsbufP(&ls->sb, p);
   1569   }
   1570   *ofsvar = sbuflen(&ls->sb);
   1571   lastpc = 0;
   1572   /* Store local variable names and compressed ranges. */
   1573   for (ve = vs + ls->vtop, vs += fs->vbase; vs < ve; vs++) {
   1574     if (!gola_isgotolabel(vs)) {
   1575       GCstr *s = strref(vs->name);
   1576       BCPos startpc;
   1577       char *p;
   1578       if ((uintptr_t)s < VARNAME__MAX) {
   1579 	p = lj_buf_more(&ls->sb, 1 + 2*5);
   1580 	*p++ = (char)(uintptr_t)s;
   1581       } else {
   1582 	MSize len = s->len+1;
   1583 	p = lj_buf_more(&ls->sb, len + 2*5);
   1584 	p = lj_buf_wmem(p, strdata(s), len);
   1585       }
   1586       startpc = vs->startpc;
   1587       p = lj_strfmt_wuleb128(p, startpc-lastpc);
   1588       p = lj_strfmt_wuleb128(p, vs->endpc-startpc);
   1589       setsbufP(&ls->sb, p);
   1590       lastpc = startpc;
   1591     }
   1592   }
   1593   lj_buf_putb(&ls->sb, '\0');  /* Terminator for varinfo. */
   1594   return sbuflen(&ls->sb);
   1595 }
   1596 
   1597 /* Fixup variable info for prototype. */
   1598 static void fs_fixup_var(LexState *ls, GCproto *pt, uint8_t *p, size_t ofsvar)
   1599 {
   1600   setmref(pt->uvinfo, p);
   1601   setmref(pt->varinfo, (char *)p + ofsvar);
   1602   memcpy(p, sbufB(&ls->sb), sbuflen(&ls->sb));  /* Copy from temp. buffer. */
   1603 }
   1604 #else
   1605 
   1606 /* Initialize with empty debug info, if disabled. */
   1607 #define fs_prep_line(fs, numline)		(UNUSED(numline), 0)
   1608 #define fs_fixup_line(fs, pt, li, numline) \
   1609   pt->firstline = pt->numline = 0, setmref((pt)->lineinfo, NULL)
   1610 #define fs_prep_var(ls, fs, ofsvar)		(UNUSED(ofsvar), 0)
   1611 #define fs_fixup_var(ls, pt, p, ofsvar) \
   1612   setmref((pt)->uvinfo, NULL), setmref((pt)->varinfo, NULL)
   1613 
   1614 #endif
   1615 
   1616 /* Check if bytecode op returns. */
   1617 static int bcopisret(BCOp op)
   1618 {
   1619   switch (op) {
   1620   case BC_CALLMT: case BC_CALLT:
   1621   case BC_RETM: case BC_RET: case BC_RET0: case BC_RET1:
   1622     return 1;
   1623   default:
   1624     return 0;
   1625   }
   1626 }
   1627 
   1628 /* Fixup return instruction for prototype. */
   1629 static void fs_fixup_ret(FuncState *fs)
   1630 {
   1631   BCPos lastpc = fs->pc;
   1632   if (lastpc <= fs->lasttarget || !bcopisret(bc_op(fs->bcbase[lastpc-1].ins))) {
   1633     if ((fs->bl->flags & FSCOPE_UPVAL))
   1634       bcemit_AJ(fs, BC_UCLO, 0, 0);
   1635     bcemit_AD(fs, BC_RET0, 0, 1);  /* Need final return. */
   1636   }
   1637   fs->bl->flags |= FSCOPE_NOCLOSE;  /* Handled above. */
   1638   fscope_end(fs);
   1639   lua_assert(fs->bl == NULL);
   1640   /* May need to fixup returns encoded before first function was created. */
   1641   if (fs->flags & PROTO_FIXUP_RETURN) {
   1642     BCPos pc;
   1643     for (pc = 1; pc < lastpc; pc++) {
   1644       BCIns ins = fs->bcbase[pc].ins;
   1645       BCPos offset;
   1646       switch (bc_op(ins)) {
   1647       case BC_CALLMT: case BC_CALLT:
   1648       case BC_RETM: case BC_RET: case BC_RET0: case BC_RET1:
   1649 	offset = bcemit_INS(fs, ins);  /* Copy original instruction. */
   1650 	fs->bcbase[offset].line = fs->bcbase[pc].line;
   1651 	offset = offset-(pc+1)+BCBIAS_J;
   1652 	if (offset > BCMAX_D)
   1653 	  err_syntax(fs->ls, LJ_ERR_XFIXUP);
   1654 	/* Replace with UCLO plus branch. */
   1655 	fs->bcbase[pc].ins = BCINS_AD(BC_UCLO, 0, offset);
   1656 	break;
   1657       case BC_UCLO:
   1658 	return;  /* We're done. */
   1659       default:
   1660 	break;
   1661       }
   1662     }
   1663   }
   1664 }
   1665 
   1666 /* Finish a FuncState and return the new prototype. */
   1667 static GCproto *fs_finish(LexState *ls, BCLine line)
   1668 {
   1669   lua_State *L = ls->L;
   1670   FuncState *fs = ls->fs;
   1671   BCLine numline = line - fs->linedefined;
   1672   size_t sizept, ofsk, ofsuv, ofsli, ofsdbg, ofsvar;
   1673   GCproto *pt;
   1674 
   1675   /* Apply final fixups. */
   1676   fs_fixup_ret(fs);
   1677 
   1678   /* Calculate total size of prototype including all colocated arrays. */
   1679   sizept = sizeof(GCproto) + fs->pc*sizeof(BCIns) + fs->nkgc*sizeof(GCRef);
   1680   sizept = (sizept + sizeof(TValue)-1) & ~(sizeof(TValue)-1);
   1681   ofsk = sizept; sizept += fs->nkn*sizeof(TValue);
   1682   ofsuv = sizept; sizept += ((fs->nuv+1)&~1)*2;
   1683   ofsli = sizept; sizept += fs_prep_line(fs, numline);
   1684   ofsdbg = sizept; sizept += fs_prep_var(ls, fs, &ofsvar);
   1685 
   1686   /* Allocate prototype and initialize its fields. */
   1687   pt = (GCproto *)lj_mem_newgco(L, (MSize)sizept);
   1688   pt->gct = ~LJ_TPROTO;
   1689   pt->sizept = (MSize)sizept;
   1690   pt->trace = 0;
   1691   pt->flags = (uint8_t)(fs->flags & ~(PROTO_HAS_RETURN|PROTO_FIXUP_RETURN|PROTO_LIFTED));
   1692   pt->numparams = fs->numparams;
   1693   pt->framesize = fs->framesize;
   1694   setgcref(pt->chunkname, obj2gco(ls->chunkname));
   1695 
   1696   /* Close potentially uninitialized gap between bc and kgc. */
   1697   *(uint32_t *)((char *)pt + ofsk - sizeof(GCRef)*(fs->nkgc+1)) = 0;
   1698   fs_fixup_bc(fs, pt, (BCIns *)((char *)pt + sizeof(GCproto)), fs->pc);
   1699   fs_fixup_k(fs, pt, (void *)((char *)pt + ofsk));
   1700   fs_fixup_uv1(fs, pt, (uint16_t *)((char *)pt + ofsuv));
   1701   fs_fixup_line(fs, pt, (void *)((char *)pt + ofsli), numline);
   1702   fs_fixup_var(ls, pt, (uint8_t *)((char *)pt + ofsdbg), ofsvar);
   1703 
   1704   lj_vmevent_send(L, BC,
   1705     setprotoV(L, L->top++, pt);
   1706   );
   1707 
   1708   L->top--;  /* Pop table of constants. */
   1709   ls->vtop = fs->vbase;  /* Reset variable stack. */
   1710   ls->fs = fs->prev;
   1711   lua_assert(ls->fs != NULL || ls->tok == TK_eof);
   1712   return pt;
   1713 }
   1714 
   1715 /* Initialize a new FuncState. */
   1716 static void fs_init(LexState *ls, FuncState *fs)
   1717 {
   1718   lua_State *L = ls->L;
   1719   memset(fs->uvcount, 0, sizeof(fs->uvcount));
   1720   fs->prev = ls->fs; ls->fs = fs;  /* Append to list. */
   1721   fs->ls = ls;
   1722   fs->vbase = ls->vtop;
   1723   fs->L = L;
   1724   fs->pc = 0;
   1725   fs->lasttarget = 0;
   1726   fs->jpc = NO_JMP;
   1727   fs->freereg = 0;
   1728   fs->nkgc = 0;
   1729   fs->nkn = 0;
   1730   fs->nactvar = 0;
   1731   fs->nuv = 0;
   1732   fs->bl = NULL;
   1733   fs->flags = 0;
   1734   fs->flags = 0;
   1735   fs->framesize = 1;  /* Minimum frame size. */
   1736   fs->kt = lj_tab_new(L, 0, 0);
   1737 
   1738   /* Anchor table of constants in stack to avoid being collected. */
   1739   settabV(L, L->top, fs->kt);
   1740   incr_top(L);
   1741 }
   1742 
   1743 /* -- Expressions --------------------------------------------------------- */
   1744 
   1745 /* Forward declaration. */
   1746 static void expr(LexState *ls, ExpDesc *v);
   1747 
   1748 /* Return string expression. */
   1749 static void expr_str(LexState *ls, ExpDesc *e)
   1750 {
   1751   expr_init(e, VKSTR, 0);
   1752   e->u.sval = lex_str(ls);
   1753 }
   1754 
   1755 /* Return index expression. */
   1756 static void expr_index(FuncState *fs, ExpDesc *t, ExpDesc *e)
   1757 {
   1758   /* Already called: expr_toval(fs, e). */
   1759   t->k = VINDEXED;
   1760   if (expr_isnumk(e)) {
   1761 #if LJ_DUALNUM
   1762     if (tvisint(expr_numtv(e))) {
   1763       int32_t k = intV(expr_numtv(e));
   1764       if (checku8(k)) {
   1765 	t->u.s.aux = BCMAX_C+1+(uint32_t)k;  /* 256..511: const byte key */
   1766 	return;
   1767       }
   1768     }
   1769 #else
   1770     lua_Number n = expr_numberV(e);
   1771     int32_t k = lj_num2int(n);
   1772     if (checku8(k) && n == (lua_Number)k) {
   1773       t->u.s.aux = BCMAX_C+1+(uint32_t)k;  /* 256..511: const byte key */
   1774       return;
   1775     }
   1776 #endif
   1777   } else if (expr_isstrk(e)) {
   1778     BCReg idx = const_str(fs, e);
   1779     if (idx <= BCMAX_C) {
   1780       t->u.s.aux = ~idx;  /* -256..-1: const string key */
   1781       return;
   1782     }
   1783   }
   1784   t->u.s.aux = expr_toanyreg(fs, e);  /* 0..255: register */
   1785 }
   1786 
   1787 /* Parse index expression with named field. */
   1788 static void expr_field(LexState *ls, ExpDesc *v)
   1789 {
   1790   FuncState *fs = ls->fs;
   1791   ExpDesc key;
   1792   expr_toanyreg(fs, v);
   1793   lj_lex_next(ls);  /* Skip dot or colon. */
   1794   expr_str(ls, &key);
   1795   expr_index(fs, v, &key);
   1796 }
   1797 
   1798 /* Parse index expression with brackets. */
   1799 static void expr_bracket(LexState *ls, ExpDesc *v)
   1800 {
   1801   lj_lex_next(ls);  /* Skip '['. */
   1802   expr(ls, v);
   1803   expr_toval(ls->fs, v);
   1804   lex_check(ls, ']');
   1805 }
   1806 
   1807 /* Get value of constant expression. */
   1808 static void expr_kvalue(TValue *v, ExpDesc *e)
   1809 {
   1810   if (e->k <= VKTRUE) {
   1811     setpriV(v, ~(uint32_t)e->k);
   1812   } else if (e->k == VKSTR) {
   1813     setgcVraw(v, obj2gco(e->u.sval), LJ_TSTR);
   1814   } else {
   1815     lua_assert(tvisnumber(expr_numtv(e)));
   1816     *v = *expr_numtv(e);
   1817   }
   1818 }
   1819 
   1820 /* Parse table constructor expression. */
   1821 static void expr_table(LexState *ls, ExpDesc *e)
   1822 {
   1823   FuncState *fs = ls->fs;
   1824   BCLine line = ls->linenumber;
   1825   GCtab *t = NULL;
   1826   int vcall = 0, needarr = 0, fixt = 0;
   1827   uint32_t narr = 1;  /* First array index. */
   1828   uint32_t nhash = 0;  /* Number of hash entries. */
   1829   BCReg freg = fs->freereg;
   1830   BCPos pc = bcemit_AD(fs, BC_TNEW, freg, 0);
   1831   expr_init(e, VNONRELOC, freg);
   1832   bcreg_reserve(fs, 1);
   1833   freg++;
   1834   lex_check(ls, '{');
   1835   while (ls->tok != '}') {
   1836     ExpDesc key, val;
   1837     vcall = 0;
   1838     if (ls->tok == '[') {
   1839       expr_bracket(ls, &key);  /* Already calls expr_toval. */
   1840       if (!expr_isk(&key)) expr_index(fs, e, &key);
   1841       if (expr_isnumk(&key) && expr_numiszero(&key)) needarr = 1; else nhash++;
   1842       lex_check(ls, '=');
   1843     } else if ((ls->tok == TK_name || (LJ_51 && ls->tok == TK_goto)) &&
   1844 	       lj_lex_lookahead(ls) == '=') {
   1845       expr_str(ls, &key);
   1846       lex_check(ls, '=');
   1847       nhash++;
   1848     } else {
   1849       expr_init(&key, VKNUM, 0);
   1850       setintV(&key.u.nval, (int)narr);
   1851       narr++;
   1852       needarr = vcall = 1;
   1853     }
   1854     expr(ls, &val);
   1855     if (expr_isk(&key) && key.k != VKNIL &&
   1856 	(key.k == VKSTR || expr_isk_nojump(&val))) {
   1857       TValue k, *v;
   1858       if (!t) {  /* Create template table on demand. */
   1859 	BCReg kidx;
   1860 	t = lj_tab_new(fs->L, needarr ? narr : 0, hsize2hbits(nhash));
   1861 	kidx = const_gc(fs, obj2gco(t), LJ_TTAB);
   1862 	fs->bcbase[pc].ins = BCINS_AD(BC_TDUP, freg-1, kidx);
   1863       }
   1864       vcall = 0;
   1865       expr_kvalue(&k, &key);
   1866       v = lj_tab_set(fs->L, t, &k);
   1867       lj_gc_anybarriert(fs->L, t);
   1868       if (expr_isk_nojump(&val)) {  /* Add const key/value to template table. */
   1869 	expr_kvalue(v, &val);
   1870       } else {  /* Otherwise create dummy string key (avoids lj_tab_newkey). */
   1871 	settabV(fs->L, v, t);  /* Preserve key with table itself as value. */
   1872 	fixt = 1;   /* Fix this later, after all resizes. */
   1873 	goto nonconst;
   1874       }
   1875     } else {
   1876     nonconst:
   1877       if (val.k != VCALL) { expr_toanyreg(fs, &val); vcall = 0; }
   1878       if (expr_isk(&key)) expr_index(fs, e, &key);
   1879       bcemit_store(fs, e, &val);
   1880     }
   1881     fs->freereg = freg;
   1882     if (!lex_opt(ls, ',') && !lex_opt(ls, ';')) break;
   1883   }
   1884   lex_match(ls, '}', '{', line);
   1885   if (vcall) {
   1886     BCInsLine *ilp = &fs->bcbase[fs->pc-1];
   1887     ExpDesc en;
   1888     lua_assert(bc_a(ilp->ins) == freg &&
   1889 	       bc_op(ilp->ins) == (narr > 256 ? BC_TSETV : BC_TSETB));
   1890     expr_init(&en, VKNUM, 0);
   1891     en.u.nval.u32.lo = narr-1;
   1892     en.u.nval.u32.hi = 0x43300000;  /* Biased integer to avoid denormals. */
   1893     if (narr > 256) { fs->pc--; ilp--; }
   1894     ilp->ins = BCINS_AD(BC_TSETM, freg, const_num(fs, &en));
   1895     setbc_b(&ilp[-1].ins, 0);
   1896   }
   1897   if (pc == fs->pc-1) {  /* Make expr relocable if possible. */
   1898     e->u.s.info = pc;
   1899     fs->freereg--;
   1900     e->k = VRELOCABLE;
   1901   } else {
   1902     e->k = VNONRELOC;  /* May have been changed by expr_index. */
   1903   }
   1904   if (!t) {  /* Construct TNEW RD: hhhhhaaaaaaaaaaa. */
   1905     BCIns *ip = &fs->bcbase[pc].ins;
   1906     if (!needarr) narr = 0;
   1907     else if (narr < 3) narr = 3;
   1908     else if (narr > 0x7ff) narr = 0x7ff;
   1909     setbc_d(ip, narr|(hsize2hbits(nhash)<<11));
   1910   } else {
   1911     if (needarr && t->asize < narr)
   1912       lj_tab_reasize(fs->L, t, narr-1);
   1913     if (fixt) {  /* Fix value for dummy keys in template table. */
   1914       Node *node = noderef(t->node);
   1915       uint32_t i, hmask = t->hmask;
   1916       for (i = 0; i <= hmask; i++) {
   1917 	Node *n = &node[i];
   1918 	if (tvistab(&n->val)) {
   1919 	  lua_assert(tabV(&n->val) == t);
   1920 	  setnilV(&n->val);  /* Turn value into nil. */
   1921 	}
   1922       }
   1923     }
   1924     lj_gc_check(fs->L);
   1925   }
   1926 }
   1927 
   1928 /* Parse function parameters. */
   1929 static BCReg parse_params(LexState *ls, int needself)
   1930 {
   1931   FuncState *fs = ls->fs;
   1932   BCReg nparams = 0;
   1933   lex_check(ls, '(');
   1934   if (needself)
   1935     var_new_lit(ls, nparams++, "self");
   1936   if (ls->tok != ')') {
   1937     do {
   1938       if (ls->tok == TK_name || (LJ_51 && ls->tok == TK_goto)) {
   1939 	var_new(ls, nparams++, lex_str(ls));
   1940       } else if (ls->tok == TK_dots) {
   1941 	lj_lex_next(ls);
   1942 	fs->flags |= PROTO_VARARG;
   1943 	break;
   1944       } else {
   1945 	err_syntax(ls, LJ_ERR_XPARAM);
   1946       }
   1947     } while (lex_opt(ls, ','));
   1948   }
   1949   var_add(ls, nparams);
   1950   lua_assert(fs->nactvar == nparams);
   1951   bcreg_reserve(fs, nparams);
   1952   lex_check(ls, ')');
   1953   return nparams;
   1954 }
   1955 
   1956 /* Forward declaration. */
   1957 static void parse_chunk(LexState *ls);
   1958 
   1959 /* Parse body of a function. */
   1960 static void parse_body(LexState *ls, ExpDesc *e, int needself, BCLine line)
   1961 {
   1962   FuncState fs, *pfs = ls->fs;
   1963   FuncScope bl;
   1964   GCproto *pt;
   1965   ptrdiff_t oldbase = pfs->bcbase - ls->bcstack;
   1966   fs_init(ls, &fs);
   1967   fscope_begin(&fs, &bl, 0);
   1968   fs.linedefined = line;
   1969   fs.numparams = (uint8_t)parse_params(ls, needself);
   1970   fs.bcbase = pfs->bcbase + pfs->pc;
   1971   fs.bclim = pfs->bclim - pfs->pc;
   1972   bcemit_AD(&fs, BC_FUNCF, 0, 0);  /* Placeholder. */
   1973   parse_chunk(ls);
   1974   if (ls->tok != TK_end) lex_match(ls, TK_end, TK_function, line);
   1975   pt = fs_finish(ls, (ls->lastline = ls->linenumber));
   1976   pfs->bcbase = ls->bcstack + oldbase;  /* May have been reallocated. */
   1977   pfs->bclim = (BCPos)(ls->sizebcstack - oldbase);
   1978   /* Store new prototype in the constant array of the parent. */
   1979   if (!(fs.flags & PROTO_LIFTED)) {
   1980     expr_init(e, VRELOCABLE,
   1981 	    bcemit_AD(pfs, BC_FNEW, 0, const_gc(pfs, obj2gco(pt), LJ_TPROTO)));
   1982   } else { 
   1983     expr_init(e, VRELOCABLE, bcemit_AD(pfs, BC_UGET, 0, pfs->nuv-1));
   1984   }
   1985 #if LJ_HASFFI
   1986   pfs->flags |= (fs.flags & PROTO_FFI);
   1987 #endif
   1988   if (!(pfs->flags & PROTO_CHILD)) {
   1989     if (pfs->flags & PROTO_HAS_RETURN)
   1990       pfs->flags |= PROTO_FIXUP_RETURN;
   1991     pfs->flags |= PROTO_CHILD;
   1992   }
   1993   lj_lex_next(ls);
   1994 }
   1995 
   1996 /* Parse expression list. Last expression is left open. */
   1997 static BCReg expr_list(LexState *ls, ExpDesc *v)
   1998 {
   1999   BCReg n = 1;
   2000   expr(ls, v);
   2001   while (lex_opt(ls, ',')) {
   2002     expr_tonextreg(ls->fs, v);
   2003     expr(ls, v);
   2004     n++;
   2005   }
   2006   return n;
   2007 }
   2008 
   2009 /* Parse function argument list. */
   2010 static void parse_args(LexState *ls, ExpDesc *e)
   2011 {
   2012   FuncState *fs = ls->fs;
   2013   ExpDesc args;
   2014   BCIns ins;
   2015   BCReg base;
   2016   BCLine line = ls->linenumber;
   2017   if (ls->tok == '(') {
   2018 #if LJ_51
   2019     if (line != ls->lastline)
   2020       err_syntax(ls, LJ_ERR_XAMBIG);
   2021 #endif
   2022     lj_lex_next(ls);
   2023     if (ls->tok == ')') {  /* f(). */
   2024       args.k = VVOID;
   2025     } else {
   2026       expr_list(ls, &args);
   2027       if (args.k == VCALL)  /* f(a, b, g()) or f(a, b, ...). */
   2028 	setbc_b(bcptr(fs, &args), 0);  /* Pass on multiple results. */
   2029     }
   2030     lex_match(ls, ')', '(', line);
   2031   } else if (ls->tok == '{') {
   2032     expr_table(ls, &args);
   2033   } else if (ls->tok == TK_string) {
   2034     expr_init(&args, VKSTR, 0);
   2035     args.u.sval = strV(&ls->tokval);
   2036     lj_lex_next(ls);
   2037   } else {
   2038     err_syntax(ls, LJ_ERR_XFUNARG);
   2039     return;  /* Silence compiler. */
   2040   }
   2041   lua_assert(e->k == VNONRELOC);
   2042   base = e->u.s.info;  /* Base register for call. */
   2043   if (args.k == VCALL) {
   2044     ins = BCINS_ABC(BC_CALLM, base, 2, args.u.s.aux - base - 1 - LJ_FR2);
   2045   } else {
   2046     if (args.k != VVOID)
   2047       expr_tonextreg(fs, &args);
   2048     ins = BCINS_ABC(BC_CALL, base, 2, fs->freereg - base - LJ_FR2);
   2049   }
   2050   expr_init(e, VCALL, bcemit_INS(fs, ins));
   2051   e->u.s.aux = base;
   2052   fs->bcbase[fs->pc - 1].line = line;
   2053   fs->freereg = base+1;  /* Leave one result by default. */
   2054 }
   2055 
   2056 /* Parse primary expression. */
   2057 static void expr_primary(LexState *ls, ExpDesc *v)
   2058 {
   2059   FuncState *fs = ls->fs;
   2060   /* Parse prefix expression. */
   2061   if (ls->tok == '(') {
   2062     BCLine line = ls->linenumber;
   2063     lj_lex_next(ls);
   2064     expr(ls, v);
   2065     lex_match(ls, ')', '(', line);
   2066     expr_discharge(ls->fs, v);
   2067   } else if (ls->tok == TK_name || (LJ_51 && ls->tok == TK_goto)) {
   2068     var_lookup(ls, v);
   2069   } else {
   2070     err_syntax(ls, LJ_ERR_XSYMBOL);
   2071   }
   2072   for (;;) {  /* Parse multiple expression suffixes. */
   2073     if (ls->tok == '.') {
   2074       expr_field(ls, v);
   2075     } else if (ls->tok == '[') {
   2076       ExpDesc key;
   2077       expr_toanyreg(fs, v);
   2078       expr_bracket(ls, &key);
   2079       expr_index(fs, v, &key);
   2080     } else if (ls->tok == ':') {
   2081       ExpDesc key;
   2082       lj_lex_next(ls);
   2083       expr_str(ls, &key);
   2084       bcemit_method(fs, v, &key);
   2085       parse_args(ls, v);
   2086     } else if (ls->tok == '(' || ls->tok == TK_string || ls->tok == '{') {
   2087       expr_tonextreg(fs, v);
   2088       if (LJ_FR2) bcreg_reserve(fs, 1);
   2089       parse_args(ls, v);
   2090     } else {
   2091       break;
   2092     }
   2093   }
   2094 }
   2095 
   2096 /* Parse simple expression. */
   2097 static void expr_simple(LexState *ls, ExpDesc *v)
   2098 {
   2099   switch (ls->tok) {
   2100   case TK_number:
   2101     expr_init(v, (LJ_HASFFI && tviscdata(&ls->tokval)) ? VKCDATA : VKNUM, 0);
   2102     copyTV(ls->L, &v->u.nval, &ls->tokval);
   2103     break;
   2104   case TK_string:
   2105     expr_init(v, VKSTR, 0);
   2106     v->u.sval = strV(&ls->tokval);
   2107     break;
   2108   case TK_nil:
   2109     expr_init(v, VKNIL, 0);
   2110     break;
   2111   case TK_true:
   2112     expr_init(v, VKTRUE, 0);
   2113     break;
   2114   case TK_false:
   2115     expr_init(v, VKFALSE, 0);
   2116     break;
   2117   case TK_dots: {  /* Vararg. */
   2118     FuncState *fs = ls->fs;
   2119     BCReg base;
   2120     checkcond(ls, fs->flags & PROTO_VARARG, LJ_ERR_XDOTS);
   2121     bcreg_reserve(fs, 1);
   2122     base = fs->freereg-1;
   2123     expr_init(v, VCALL, bcemit_ABC(fs, BC_VARG, base, 2, fs->numparams));
   2124     v->u.s.aux = base;
   2125     break;
   2126   }
   2127   case '{':  /* Table constructor. */
   2128     expr_table(ls, v);
   2129     return;
   2130   case TK_function:
   2131     lj_lex_next(ls);
   2132     parse_body(ls, v, 0, ls->linenumber);
   2133     return;
   2134   default:
   2135     expr_primary(ls, v);
   2136     return;
   2137   }
   2138   lj_lex_next(ls);
   2139 }
   2140 
   2141 /* Manage syntactic levels to avoid blowing up the stack. */
   2142 static void synlevel_begin(LexState *ls)
   2143 {
   2144   if (++ls->level >= LJ_MAX_XLEVEL)
   2145     lj_lex_error(ls, 0, LJ_ERR_XLEVELS);
   2146 }
   2147 
   2148 #define synlevel_end(ls)	((ls)->level--)
   2149 
   2150 /* Convert token to binary operator. */
   2151 static BinOpr token2binop(LexToken tok)
   2152 {
   2153   switch (tok) {
   2154   case '+':	return OPR_ADD;
   2155   case '-':	return OPR_SUB;
   2156   case '*':	return OPR_MUL;
   2157   case '/':	return OPR_DIV;
   2158   case '%':	return OPR_MOD;
   2159   case '^':	return OPR_POW;
   2160   case TK_concat: return OPR_CONCAT;
   2161   case TK_ne:	return OPR_NE;
   2162   case TK_eq:	return OPR_EQ;
   2163   case '<':	return OPR_LT;
   2164   case TK_le:	return OPR_LE;
   2165   case '>':	return OPR_GT;
   2166   case TK_ge:	return OPR_GE;
   2167   case TK_and:	return OPR_AND;
   2168   case TK_or:	return OPR_OR;
   2169 #if LJ_53
   2170   case TK_idiv: return OPR_IDIV;
   2171   case '&':     return OPR_BAND;
   2172   case '|':     return OPR_BOR;
   2173   case '~':     return OPR_BXOR;
   2174   case TK_shl:  return OPR_SHL;
   2175   case TK_shr:  return OPR_SHR;
   2176 #endif
   2177   default:	return OPR_NOBINOPR;
   2178   }
   2179 }
   2180 
   2181 /* Priorities for each binary operator. ORDER OPR. */
   2182 static const struct {
   2183   uint8_t left;		/* Left priority. */
   2184   uint8_t right;	/* Right priority. */
   2185 } priority[] = {
   2186   /* ADD SUB MUL DIV MOD POW */
   2187   {10,10}, {10,10}, {11,11}, {11,11}, {11,11}, {14,13},
   2188 #if LJ_53
   2189   {0,0},{0,0}, /* dummy */
   2190   {11,11}, {6,6}, {4,4}, {5,5}, 	/* IDIV BAND BOR BXOR */
   2191   {7,7}, {7,7}, 			/* SHL SHR */
   2192 #endif
   2193   {9,8},				/* CONCAT (right associative) */
   2194   {3,3}, {3,3},				/* EQ NE */
   2195   {3,3}, {3,3}, {3,3}, {3,3},		/* LT GE GT LE */
   2196   {2,2}, {1,1}				/* AND OR */
   2197 };
   2198 
   2199 #define UNARY_PRIORITY		12  /* Priority for unary operators. */
   2200 
   2201 /* Forward declaration. */
   2202 static BinOpr expr_binop(LexState *ls, ExpDesc *v, uint32_t limit);
   2203 
   2204 /* Parse unary expression. */
   2205 static void expr_unop(LexState *ls, ExpDesc *v)
   2206 {
   2207   BCOp op;
   2208   if (ls->tok == TK_not) {
   2209     op = BC_NOT;
   2210   } else if (ls->tok == '-') {
   2211     op = BC_UNM;
   2212   } else if (ls->tok == '#') {
   2213     op = BC_LEN;
   2214 #if LJ_53
   2215   } else if (ls->tok == '~') {
   2216     op = BC_BNOT;
   2217 #endif
   2218   } else {
   2219     expr_simple(ls, v);
   2220     return;
   2221   }
   2222   lj_lex_next(ls);
   2223   expr_binop(ls, v, UNARY_PRIORITY);
   2224   bcemit_unop(ls->fs, op, v);
   2225 }
   2226 
   2227 /* Parse binary expressions with priority higher than the limit. */
   2228 static BinOpr expr_binop(LexState *ls, ExpDesc *v, uint32_t limit)
   2229 {
   2230   BinOpr op;
   2231   synlevel_begin(ls);
   2232   expr_unop(ls, v);
   2233   op = token2binop(ls->tok);
   2234   while (op != OPR_NOBINOPR && priority[op].left > limit) {
   2235     ExpDesc v2;
   2236     BinOpr nextop;
   2237     lj_lex_next(ls);
   2238     bcemit_binop_left(ls->fs, op, v);
   2239     /* Parse binary expression with higher priority. */
   2240     nextop = expr_binop(ls, &v2, priority[op].right);
   2241     bcemit_binop(ls->fs, op, v, &v2);
   2242     op = nextop;
   2243   }
   2244   synlevel_end(ls);
   2245   return op;  /* Return unconsumed binary operator (if any). */
   2246 }
   2247 
   2248 /* Parse expression. */
   2249 static void expr(LexState *ls, ExpDesc *v)
   2250 {
   2251   expr_binop(ls, v, 0);  /* Priority 0: parse whole expression. */
   2252 }
   2253 
   2254 /* Assign expression to the next register. */
   2255 static void expr_next(LexState *ls)
   2256 {
   2257   ExpDesc e;
   2258   expr(ls, &e);
   2259   expr_tonextreg(ls->fs, &e);
   2260 }
   2261 
   2262 /* Parse conditional expression. */
   2263 static BCPos expr_cond(LexState *ls)
   2264 {
   2265   ExpDesc v;
   2266   expr(ls, &v);
   2267   if (v.k == VKNIL) v.k = VKFALSE;
   2268   bcemit_branch_t(ls->fs, &v);
   2269   return v.f;
   2270 }
   2271 
   2272 /* -- Assignments --------------------------------------------------------- */
   2273 
   2274 /* List of LHS variables. */
   2275 typedef struct LHSVarList {
   2276   ExpDesc v;			/* LHS variable. */
   2277   struct LHSVarList *prev;	/* Link to previous LHS variable. */
   2278 } LHSVarList;
   2279 
   2280 /* Eliminate write-after-read hazards for local variable assignment. */
   2281 static void assign_hazard(LexState *ls, LHSVarList *lh, const ExpDesc *v)
   2282 {
   2283   FuncState *fs = ls->fs;
   2284   BCReg reg = v->u.s.info;  /* Check against this variable. */
   2285   BCReg tmp = fs->freereg;  /* Rename to this temp. register (if needed). */
   2286   int hazard = 0;
   2287   for (; lh; lh = lh->prev) {
   2288     if (lh->v.k == VINDEXED) {
   2289       if (lh->v.u.s.info == reg) {  /* t[i], t = 1, 2 */
   2290 	hazard = 1;
   2291 	lh->v.u.s.info = tmp;
   2292       }
   2293       if (lh->v.u.s.aux == reg) {  /* t[i], i = 1, 2 */
   2294 	hazard = 1;
   2295 	lh->v.u.s.aux = tmp;
   2296       }
   2297     }
   2298   }
   2299   if (hazard) {
   2300     bcemit_AD(fs, BC_MOV, tmp, reg);  /* Rename conflicting variable. */
   2301     bcreg_reserve(fs, 1);
   2302   }
   2303 }
   2304 
   2305 /* Adjust LHS/RHS of an assignment. */
   2306 static void assign_adjust(LexState *ls, BCReg nvars, BCReg nexps, ExpDesc *e)
   2307 {
   2308   FuncState *fs = ls->fs;
   2309   int32_t extra = (int32_t)nvars - (int32_t)nexps;
   2310   if (e->k == VCALL) {
   2311     extra++;  /* Compensate for the VCALL itself. */
   2312     if (extra < 0) extra = 0;
   2313     setbc_b(bcptr(fs, e), extra+1);  /* Fixup call results. */
   2314     if (extra > 1) bcreg_reserve(fs, (BCReg)extra-1);
   2315   } else {
   2316     if (e->k != VVOID)
   2317       expr_tonextreg(fs, e);  /* Close last expression. */
   2318     if (extra > 0) {  /* Leftover LHS are set to nil. */
   2319       BCReg reg = fs->freereg;
   2320       bcreg_reserve(fs, (BCReg)extra);
   2321       bcemit_nil(fs, reg, (BCReg)extra);
   2322     }
   2323   }
   2324 }
   2325 
   2326 /* Recursively parse assignment statement. */
   2327 static void parse_assignment(LexState *ls, LHSVarList *lh, BCReg nvars)
   2328 {
   2329   ExpDesc e;
   2330   checkcond(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED, LJ_ERR_XSYNTAX);
   2331   if (lex_opt(ls, ',')) {  /* Collect LHS list and recurse upwards. */
   2332     LHSVarList vl;
   2333     vl.prev = lh;
   2334     expr_primary(ls, &vl.v);
   2335     if (vl.v.k == VLOCAL)
   2336       assign_hazard(ls, lh, &vl.v);
   2337     checklimit(ls->fs, ls->level + nvars, LJ_MAX_XLEVEL, "variable names");
   2338     parse_assignment(ls, &vl, nvars+1);
   2339   } else {  /* Parse RHS. */
   2340     BCReg nexps;
   2341     lex_check(ls, '=');
   2342     nexps = expr_list(ls, &e);
   2343     if (nexps == nvars) {
   2344       if (e.k == VCALL) {
   2345 	if (bc_op(*bcptr(ls->fs, &e)) == BC_VARG) {  /* Vararg assignment. */
   2346 	  ls->fs->freereg--;
   2347 	  e.k = VRELOCABLE;
   2348 	} else {  /* Multiple call results. */
   2349 	  e.u.s.info = e.u.s.aux;  /* Base of call is not relocatable. */
   2350 	  e.k = VNONRELOC;
   2351 	}
   2352       }
   2353       bcemit_store(ls->fs, &lh->v, &e);
   2354       return;
   2355     }
   2356     assign_adjust(ls, nvars, nexps, &e);
   2357     if (nexps > nvars)
   2358       ls->fs->freereg -= nexps - nvars;  /* Drop leftover regs. */
   2359   }
   2360   /* Assign RHS to LHS and recurse downwards. */
   2361   expr_init(&e, VNONRELOC, ls->fs->freereg-1);
   2362   bcemit_store(ls->fs, &lh->v, &e);
   2363 }
   2364 
   2365 /* Parse call statement or assignment. */
   2366 static void parse_call_assign(LexState *ls)
   2367 {
   2368   FuncState *fs = ls->fs;
   2369   LHSVarList vl;
   2370   expr_primary(ls, &vl.v);
   2371   if (vl.v.k == VCALL) {  /* Function call statement. */
   2372     setbc_b(bcptr(fs, &vl.v), 1);  /* No results. */
   2373   } else {  /* Start of an assignment. */
   2374     vl.prev = NULL;
   2375     parse_assignment(ls, &vl, 1);
   2376   }
   2377 }
   2378 
   2379 /* Parse 'local' statement. */
   2380 static void parse_local(LexState *ls)
   2381 {
   2382   if (lex_opt(ls, TK_function)) {  /* Local function declaration. */
   2383     ExpDesc v, b;
   2384     FuncState *fs = ls->fs;
   2385     var_new(ls, 0, lex_str(ls));
   2386     expr_init(&v, VLOCAL, fs->freereg);
   2387     v.u.s.aux = fs->varmap[fs->freereg];
   2388     bcreg_reserve(fs, 1);
   2389     var_add(ls, 1);
   2390     parse_body(ls, &b, 0, ls->linenumber);
   2391     /* bcemit_store(fs, &v, &b) without setting VSTACK_VAR_RW. */
   2392     expr_free(fs, &b);
   2393     expr_toreg(fs, &b, v.u.s.info);
   2394     /* The upvalue is in scope, but the local is only valid after the store. */
   2395     var_get(ls, fs, fs->nactvar - 1).startpc = fs->pc;
   2396   } else {  /* Local variable declaration. */
   2397     ExpDesc e;
   2398     BCReg nexps, nvars = 0;
   2399     do {  /* Collect LHS. */
   2400       var_new(ls, nvars++, lex_str(ls));
   2401     } while (lex_opt(ls, ','));
   2402     if (lex_opt(ls, '=')) {  /* Optional RHS. */
   2403       nexps = expr_list(ls, &e);
   2404     } else {  /* Or implicitly set to nil. */
   2405       e.k = VVOID;
   2406       nexps = 0;
   2407     }
   2408     assign_adjust(ls, nvars, nexps, &e);
   2409     var_add(ls, nvars);
   2410   }
   2411 }
   2412 
   2413 /* Parse 'function' statement. */
   2414 static void parse_func(LexState *ls, BCLine line)
   2415 {
   2416   FuncState *fs;
   2417   ExpDesc v, b;
   2418   int needself = 0;
   2419   lj_lex_next(ls);  /* Skip 'function'. */
   2420   /* Parse function name. */
   2421   var_lookup(ls, &v);
   2422   while (ls->tok == '.')  /* Multiple dot-separated fields. */
   2423     expr_field(ls, &v);
   2424   if (ls->tok == ':') {  /* Optional colon to signify method call. */
   2425     needself = 1;
   2426     expr_field(ls, &v);
   2427   }
   2428   parse_body(ls, &b, needself, line);
   2429   fs = ls->fs;
   2430   bcemit_store(fs, &v, &b);
   2431   fs->bcbase[fs->pc - 1].line = line;  /* Set line for the store. */
   2432 }
   2433 
   2434 /* -- Control transfer statements ----------------------------------------- */
   2435 
   2436 /* Check for end of block. */
   2437 static int parse_isend(LexToken tok)
   2438 {
   2439   switch (tok) {
   2440   case TK_else: case TK_elseif: case TK_end: case TK_until: case TK_eof:
   2441     return 1;
   2442   default:
   2443     return 0;
   2444   }
   2445 }
   2446 
   2447 /* Parse 'return' statement. */
   2448 static void parse_return(LexState *ls)
   2449 {
   2450   BCIns ins;
   2451   FuncState *fs = ls->fs;
   2452   lj_lex_next(ls);  /* Skip 'return'. */
   2453   fs->flags |= PROTO_HAS_RETURN;
   2454   if (parse_isend(ls->tok) || ls->tok == ';') {  /* Bare return. */
   2455     ins = BCINS_AD(BC_RET0, 0, 1);
   2456   } else {  /* Return with one or more values. */
   2457     ExpDesc e;  /* Receives the _last_ expression in the list. */
   2458     BCReg nret = expr_list(ls, &e);
   2459     if (nret == 1) {  /* Return one result. */
   2460       if (e.k == VCALL) {  /* Check for tail call. */
   2461 	BCIns *ip = bcptr(fs, &e);
   2462 	/* It doesn't pay off to add BC_VARGT just for 'return ...'. */
   2463 	if (bc_op(*ip) == BC_VARG) goto notailcall;
   2464 	fs->pc--;
   2465 	ins = BCINS_AD(bc_op(*ip)-BC_CALL+BC_CALLT, bc_a(*ip), bc_c(*ip));
   2466       } else {  /* Can return the result from any register. */
   2467 	ins = BCINS_AD(BC_RET1, expr_toanyreg(fs, &e), 2);
   2468       }
   2469     } else {
   2470       if (e.k == VCALL) {  /* Append all results from a call. */
   2471       notailcall:
   2472 	setbc_b(bcptr(fs, &e), 0);
   2473 	ins = BCINS_AD(BC_RETM, fs->nactvar, e.u.s.aux - fs->nactvar);
   2474       } else {
   2475 	expr_tonextreg(fs, &e);  /* Force contiguous registers. */
   2476 	ins = BCINS_AD(BC_RET, fs->nactvar, nret+1);
   2477       }
   2478     }
   2479   }
   2480   if (fs->flags & PROTO_CHILD)
   2481     bcemit_AJ(fs, BC_UCLO, 0, 0);  /* May need to close upvalues first. */
   2482   bcemit_INS(fs, ins);
   2483 }
   2484 
   2485 /* Parse 'break' statement. */
   2486 static void parse_break(LexState *ls)
   2487 {
   2488   ls->fs->bl->flags |= FSCOPE_BREAK;
   2489   gola_new(ls, NAME_BREAK, VSTACK_GOTO, bcemit_jmp(ls->fs));
   2490 }
   2491 
   2492 /* Parse 'goto' statement. */
   2493 static void parse_goto(LexState *ls)
   2494 {
   2495   FuncState *fs = ls->fs;
   2496   GCstr *name = lex_str(ls);
   2497   VarInfo *vl = gola_findlabel(ls, name);
   2498   if (vl)  /* Treat backwards goto within same scope like a loop. */
   2499     bcemit_AJ(fs, BC_LOOP, vl->slot, -1);  /* No BC range check. */
   2500   fs->bl->flags |= FSCOPE_GOLA;
   2501   gola_new(ls, name, VSTACK_GOTO, bcemit_jmp(fs));
   2502 }
   2503 
   2504 /* Parse label. */
   2505 static void parse_label(LexState *ls)
   2506 {
   2507   FuncState *fs = ls->fs;
   2508   GCstr *name;
   2509   MSize idx;
   2510   fs->lasttarget = fs->pc;
   2511   fs->bl->flags |= FSCOPE_GOLA;
   2512   lj_lex_next(ls);  /* Skip '::'. */
   2513   name = lex_str(ls);
   2514   if (gola_findlabel(ls, name))
   2515     lj_lex_error(ls, 0, LJ_ERR_XLDUP, strdata(name));
   2516   idx = gola_new(ls, name, VSTACK_LABEL, fs->pc);
   2517   lex_check(ls, TK_label);
   2518   /* Recursively parse trailing statements: labels and ';' (Lua 5.2 only). */
   2519   for (;;) {
   2520     if (ls->tok == TK_label) {
   2521       synlevel_begin(ls);
   2522       parse_label(ls);
   2523       synlevel_end(ls);
   2524     } else if (!LJ_51 && ls->tok == ';') {
   2525       lj_lex_next(ls);
   2526     } else {
   2527       break;
   2528     }
   2529   }
   2530   /* Trailing label is considered to be outside of scope. */
   2531   if (parse_isend(ls->tok) && ls->tok != TK_until)
   2532     ls->vstack[idx].slot = fs->bl->nactvar;
   2533   gola_resolve(ls, fs->bl, idx);
   2534 }
   2535 
   2536 /* -- Blocks, loops and conditional statements ---------------------------- */
   2537 
   2538 /* Parse a block. */
   2539 static void parse_block(LexState *ls)
   2540 {
   2541   FuncState *fs = ls->fs;
   2542   FuncScope bl;
   2543   fscope_begin(fs, &bl, 0);
   2544   parse_chunk(ls);
   2545   fscope_end(fs);
   2546 }
   2547 
   2548 /* Parse 'while' statement. */
   2549 static void parse_while(LexState *ls, BCLine line)
   2550 {
   2551   FuncState *fs = ls->fs;
   2552   BCPos start, loop, condexit;
   2553   FuncScope bl;
   2554   lj_lex_next(ls);  /* Skip 'while'. */
   2555   start = fs->lasttarget = fs->pc;
   2556   condexit = expr_cond(ls);
   2557   fscope_begin(fs, &bl, FSCOPE_LOOP);
   2558   lex_check(ls, TK_do);
   2559   loop = bcemit_AD(fs, BC_LOOP, fs->nactvar, 0);
   2560   parse_block(ls);
   2561   jmp_patch(fs, bcemit_jmp(fs), start);
   2562   lex_match(ls, TK_end, TK_while, line);
   2563   fscope_end(fs);
   2564   jmp_tohere(fs, condexit);
   2565   jmp_patchins(fs, loop, fs->pc);
   2566 }
   2567 
   2568 /* Parse 'repeat' statement. */
   2569 static void parse_repeat(LexState *ls, BCLine line)
   2570 {
   2571   FuncState *fs = ls->fs;
   2572   BCPos loop = fs->lasttarget = fs->pc;
   2573   BCPos condexit;
   2574   FuncScope bl1, bl2;
   2575   fscope_begin(fs, &bl1, FSCOPE_LOOP);  /* Breakable loop scope. */
   2576   fscope_begin(fs, &bl2, 0);  /* Inner scope. */
   2577   lj_lex_next(ls);  /* Skip 'repeat'. */
   2578   bcemit_AD(fs, BC_LOOP, fs->nactvar, 0);
   2579   parse_chunk(ls);
   2580   lex_match(ls, TK_until, TK_repeat, line);
   2581   condexit = expr_cond(ls);  /* Parse condition (still inside inner scope). */
   2582   if (!(bl2.flags & FSCOPE_UPVAL)) {  /* No upvalues? Just end inner scope. */
   2583     fscope_end(fs);
   2584   } else {  /* Otherwise generate: cond: UCLO+JMP out, !cond: UCLO+JMP loop. */
   2585     parse_break(ls);  /* Break from loop and close upvalues. */
   2586     jmp_tohere(fs, condexit);
   2587     fscope_end(fs);  /* End inner scope and close upvalues. */
   2588     condexit = bcemit_jmp(fs);
   2589   }
   2590   jmp_patch(fs, condexit, loop);  /* Jump backwards if !cond. */
   2591   jmp_patchins(fs, loop, fs->pc);
   2592   fscope_end(fs);  /* End loop scope. */
   2593 }
   2594 
   2595 /* Parse numeric 'for'. */
   2596 static void parse_for_num(LexState *ls, GCstr *varname, BCLine line)
   2597 {
   2598   FuncState *fs = ls->fs;
   2599   BCReg base = fs->freereg;
   2600   FuncScope bl;
   2601   BCPos loop, loopend;
   2602   /* Hidden control variables. */
   2603   var_new_fixed(ls, FORL_IDX, VARNAME_FOR_IDX);
   2604   var_new_fixed(ls, FORL_STOP, VARNAME_FOR_STOP);
   2605   var_new_fixed(ls, FORL_STEP, VARNAME_FOR_STEP);
   2606   /* Visible copy of index variable. */
   2607   var_new(ls, FORL_EXT, varname);
   2608   lex_check(ls, '=');
   2609   expr_next(ls);
   2610   lex_check(ls, ',');
   2611   expr_next(ls);
   2612   if (lex_opt(ls, ',')) {
   2613     expr_next(ls);
   2614   } else {
   2615     bcemit_AD(fs, BC_KSHORT, fs->freereg, 1);  /* Default step is 1. */
   2616     bcreg_reserve(fs, 1);
   2617   }
   2618   var_add(ls, 3);  /* Hidden control variables. */
   2619   lex_check(ls, TK_do);
   2620   loop = bcemit_AJ(fs, BC_FORI, base, NO_JMP);
   2621   fscope_begin(fs, &bl, 0);  /* Scope for visible variables. */
   2622   var_add(ls, 1);
   2623   bcreg_reserve(fs, 1);
   2624   parse_block(ls);
   2625   fscope_end(fs);
   2626   /* Perform loop inversion. Loop control instructions are at the end. */
   2627   loopend = bcemit_AJ(fs, BC_FORL, base, NO_JMP);
   2628   fs->bcbase[loopend].line = line;  /* Fix line for control ins. */
   2629   jmp_patchins(fs, loopend, loop+1);
   2630   jmp_patchins(fs, loop, fs->pc);
   2631 }
   2632 
   2633 /* Try to predict whether the iterator is next() and specialize the bytecode.
   2634 ** Detecting next() and pairs() by name is simplistic, but quite effective.
   2635 ** The interpreter backs off if the check for the closure fails at runtime.
   2636 */
   2637 static int predict_next(LexState *ls, FuncState *fs, BCPos pc)
   2638 {
   2639   BCIns ins = fs->bcbase[pc].ins;
   2640   int idx;
   2641   GCstr *name;
   2642   cTValue *o;
   2643   switch (bc_op(ins)) {
   2644   case BC_MOV:
   2645     name = gco2str(gcref(var_get(ls, fs, bc_d(ins)).name));
   2646     break;
   2647   case BC_UGET:
   2648     idx = fs->uvmap[bc_d(ins)];
   2649     if (idx == LJ_MAX_VSTACK) return 0; /* UV not associated with var */
   2650     name = gco2str(gcref(ls->vstack[idx].name));
   2651     break;
   2652   case BC_GGET:
   2653     /* There's no inverse index (yet), so lookup the strings. */
   2654     o = lj_tab_getstr(fs->kt, lj_str_newlit(ls->L, "pairs"));
   2655     if (o && tvhaskslot(o) && tvkslot(o) == bc_d(ins))
   2656       return 1;
   2657     o = lj_tab_getstr(fs->kt, lj_str_newlit(ls->L, "next"));
   2658     if (o && tvhaskslot(o) && tvkslot(o) == bc_d(ins))
   2659       return 1;
   2660     return 0;
   2661   default:
   2662     return 0;
   2663   }
   2664   return (name->len == 5 && !strcmp(strdata(name), "pairs")) ||
   2665 	 (name->len == 4 && !strcmp(strdata(name), "next"));
   2666 }
   2667 
   2668 /* Parse 'for' iterator. */
   2669 static void parse_for_iter(LexState *ls, GCstr *indexname)
   2670 {
   2671   FuncState *fs = ls->fs;
   2672   ExpDesc e;
   2673   BCReg nvars = 0;
   2674   BCLine line;
   2675   BCReg base = fs->freereg + 3;
   2676   BCPos loop, loopend, exprpc = fs->pc;
   2677   FuncScope bl;
   2678   int isnext;
   2679   /* Hidden control variables. */
   2680   var_new_fixed(ls, nvars++, VARNAME_FOR_GEN);
   2681   var_new_fixed(ls, nvars++, VARNAME_FOR_STATE);
   2682   var_new_fixed(ls, nvars++, VARNAME_FOR_CTL);
   2683   /* Visible variables returned from iterator. */
   2684   var_new(ls, nvars++, indexname);
   2685   while (lex_opt(ls, ','))
   2686     var_new(ls, nvars++, lex_str(ls));
   2687   lex_check(ls, TK_in);
   2688   line = ls->linenumber;
   2689   assign_adjust(ls, 3, expr_list(ls, &e), &e);
   2690   /* The iterator needs another 3 [4] slots (func [pc] | state ctl). */
   2691   bcreg_bump(fs, 3+LJ_FR2);
   2692   isnext = (nvars <= 5 && predict_next(ls, fs, exprpc));
   2693   var_add(ls, 3);  /* Hidden control variables. */
   2694   lex_check(ls, TK_do);
   2695   loop = bcemit_AJ(fs, isnext ? BC_ISNEXT : BC_JMP, base, NO_JMP);
   2696   fscope_begin(fs, &bl, 0);  /* Scope for visible variables. */
   2697   var_add(ls, nvars-3);
   2698   bcreg_reserve(fs, nvars-3);
   2699   parse_block(ls);
   2700   fscope_end(fs);
   2701   /* Perform loop inversion. Loop control instructions are at the end. */
   2702   jmp_patchins(fs, loop, fs->pc);
   2703   bcemit_ABC(fs, isnext ? BC_ITERN : BC_ITERC, base, nvars-3+1, 2+1);
   2704   loopend = bcemit_AJ(fs, BC_ITERL, base, NO_JMP);
   2705   fs->bcbase[loopend-1].line = line;  /* Fix line for control ins. */
   2706   fs->bcbase[loopend].line = line;
   2707   jmp_patchins(fs, loopend, loop+1);
   2708 }
   2709 
   2710 /* Parse 'for' statement. */
   2711 static void parse_for(LexState *ls, BCLine line)
   2712 {
   2713   FuncState *fs = ls->fs;
   2714   GCstr *varname;
   2715   FuncScope bl;
   2716   fscope_begin(fs, &bl, FSCOPE_LOOP);
   2717   lj_lex_next(ls);  /* Skip 'for'. */
   2718   varname = lex_str(ls);  /* Get first variable name. */
   2719   if (ls->tok == '=')
   2720     parse_for_num(ls, varname, line);
   2721   else if (ls->tok == ',' || ls->tok == TK_in)
   2722     parse_for_iter(ls, varname);
   2723   else
   2724     err_syntax(ls, LJ_ERR_XFOR);
   2725   lex_match(ls, TK_end, TK_for, line);
   2726   fscope_end(fs);  /* Resolve break list. */
   2727 }
   2728 
   2729 /* Parse condition and 'then' block. */
   2730 static BCPos parse_then(LexState *ls)
   2731 {
   2732   BCPos condexit;
   2733   lj_lex_next(ls);  /* Skip 'if' or 'elseif'. */
   2734   condexit = expr_cond(ls);
   2735   lex_check(ls, TK_then);
   2736   parse_block(ls);
   2737   return condexit;
   2738 }
   2739 
   2740 /* Parse 'if' statement. */
   2741 static void parse_if(LexState *ls, BCLine line)
   2742 {
   2743   FuncState *fs = ls->fs;
   2744   BCPos flist;
   2745   BCPos escapelist = NO_JMP;
   2746   flist = parse_then(ls);
   2747   while (ls->tok == TK_elseif) {  /* Parse multiple 'elseif' blocks. */
   2748     jmp_append(fs, &escapelist, bcemit_jmp(fs));
   2749     jmp_tohere(fs, flist);
   2750     flist = parse_then(ls);
   2751   }
   2752   if (ls->tok == TK_else) {  /* Parse optional 'else' block. */
   2753     jmp_append(fs, &escapelist, bcemit_jmp(fs));
   2754     jmp_tohere(fs, flist);
   2755     lj_lex_next(ls);  /* Skip 'else'. */
   2756     parse_block(ls);
   2757   } else {
   2758     jmp_append(fs, &escapelist, flist);
   2759   }
   2760   jmp_tohere(fs, escapelist);
   2761   lex_match(ls, TK_end, TK_if, line);
   2762 }
   2763 
   2764 /* -- Parse statements ---------------------------------------------------- */
   2765 
   2766 /* Parse a statement. Returns 1 if it must be the last one in a chunk. */
   2767 static int parse_stmt(LexState *ls)
   2768 {
   2769   BCLine line = ls->linenumber;
   2770   switch (ls->tok) {
   2771   case TK_if:
   2772     parse_if(ls, line);
   2773     break;
   2774   case TK_while:
   2775     parse_while(ls, line);
   2776     break;
   2777   case TK_do:
   2778     lj_lex_next(ls);
   2779     parse_block(ls);
   2780     lex_match(ls, TK_end, TK_do, line);
   2781     break;
   2782   case TK_for:
   2783     parse_for(ls, line);
   2784     break;
   2785   case TK_repeat:
   2786     parse_repeat(ls, line);
   2787     break;
   2788   case TK_function:
   2789     parse_func(ls, line);
   2790     break;
   2791   case TK_local:
   2792     lj_lex_next(ls);
   2793     parse_local(ls);
   2794     break;
   2795   case TK_return:
   2796     parse_return(ls);
   2797     return 1;  /* Must be last. */
   2798   case TK_break:
   2799     lj_lex_next(ls);
   2800     parse_break(ls);
   2801     return LJ_51;
   2802 #if !LJ_51
   2803   case ';':
   2804     lj_lex_next(ls);
   2805     break;
   2806 #endif
   2807   case TK_label:
   2808     parse_label(ls);
   2809     break;
   2810   case TK_goto:
   2811     if (!LJ_51 || lj_lex_lookahead(ls) == TK_name) {
   2812       lj_lex_next(ls);
   2813       parse_goto(ls);
   2814       break;
   2815     }  /* else: fallthrough */
   2816   default:
   2817     parse_call_assign(ls);
   2818     break;
   2819   }
   2820   return 0;
   2821 }
   2822 
   2823 /* A chunk is a list of statements optionally separated by semicolons. */
   2824 static void parse_chunk(LexState *ls)
   2825 {
   2826   int islast = 0;
   2827   synlevel_begin(ls);
   2828   while (!islast && !parse_isend(ls->tok)) {
   2829     islast = parse_stmt(ls);
   2830     lex_opt(ls, ';');
   2831     lua_assert(ls->fs->framesize >= ls->fs->freereg &&
   2832 	       ls->fs->freereg >= ls->fs->nactvar);
   2833     ls->fs->freereg = ls->fs->nactvar;  /* Free registers after each stmt. */
   2834   }
   2835   synlevel_end(ls);
   2836 }
   2837 
   2838 /* Entry point of bytecode parser. */
   2839 GCproto *lj_parse(LexState *ls)
   2840 {
   2841   FuncState fs;
   2842   FuncScope bl;
   2843   GCproto *pt;
   2844   lua_State *L = ls->L;
   2845 #ifdef LUAJIT_DISABLE_DEBUGINFO
   2846   ls->chunkname = lj_str_newlit(L, "=");
   2847 #else
   2848   ls->chunkname = lj_str_newz(L, ls->chunkarg);
   2849 #endif
   2850   setstrV(L, L->top, ls->chunkname);  /* Anchor chunkname string. */
   2851   incr_top(L);
   2852   ls->level = 0;
   2853   fs_init(ls, &fs);
   2854   fs.linedefined = 0;
   2855   fs.numparams = 0;
   2856   fs.bcbase = NULL;
   2857   fs.bclim = 0;
   2858   fs.flags |= PROTO_VARARG;  /* Main chunk is always a vararg func. */
   2859 
   2860   /* Pretend _ENV is coming from previous virtual scope */
   2861   ls->env = lj_parse_keepstr(ls, "_ENV", 4);
   2862   var_new(ls, 0, ls->env);
   2863   ls->vstack[0].startpc = 0;
   2864   ls->vstack[0].endpc = 0;
   2865   ls->vstack[0].slot = 0;
   2866   ls->vstack[0].info = 0;
   2867   fs.uvmap[0] = 0;
   2868   fs.uvval[0] = PROTO_UV_ENV;
   2869   fs.nuv++;
   2870   fs.vbase = 1;
   2871   lua_assert(ls->vtop == 1);
   2872   fscope_begin(&fs, &bl, 0);
   2873   bcemit_AD(&fs, BC_FUNCV, 0, 0);  /* Placeholder. */
   2874   lj_lex_next(ls);  /* Read-ahead first token. */
   2875   parse_chunk(ls);
   2876   if (ls->tok != TK_eof)
   2877     err_token(ls, TK_eof);
   2878   pt = fs_finish(ls, ls->linenumber);
   2879   L->top--;  /* Drop chunkname. */
   2880   lua_assert(fs.prev == NULL);
   2881   lua_assert(ls->fs == NULL);
   2882   return pt;
   2883 }
   2884