root/lj_parse.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. expr_init
  2. expr_numiszero
  3. err_syntax
  4. err_token
  5. err_limit
  6. const_num
  7. const_gc
  8. const_str
  9. lj_parse_keepstr
  10. lj_parse_keepcdata
  11. jmp_next
  12. jmp_novalue
  13. jmp_patchtestreg
  14. jmp_dropval
  15. jmp_patchins
  16. jmp_append
  17. jmp_patchval
  18. jmp_tohere
  19. jmp_patch
  20. bcreg_bump
  21. bcreg_reserve
  22. bcreg_free
  23. expr_free
  24. bcemit_INS
  25. expr_discharge
  26. bcemit_nil
  27. expr_toreg_nobranch
  28. expr_toreg
  29. expr_tonextreg
  30. expr_toanyreg
  31. expr_toval
  32. bcemit_store
  33. bcemit_method
  34. bcemit_jmp
  35. invertcond
  36. bcemit_branch
  37. bcemit_branch_t
  38. bcemit_branch_f
  39. foldarith
  40. bcemit_arith
  41. bcemit_comp
  42. bcemit_binop_left
  43. bcemit_binop
  44. bcemit_unop
  45. lex_opt
  46. lex_check
  47. lex_match
  48. lex_str
  49. var_new
  50. var_add
  51. var_remove
  52. var_lookup_local
  53. var_lookup_uv
  54. var_lookup_
  55. gola_new
  56. gola_patch
  57. gola_close
  58. gola_resolve
  59. gola_fixup
  60. gola_findlabel
  61. fscope_begin
  62. fscope_end
  63. fscope_uvmark
  64. fs_fixup_bc
  65. fs_fixup_uv2
  66. fs_fixup_k
  67. fs_fixup_uv1
  68. fs_prep_line
  69. fs_fixup_line
  70. fs_buf_resize
  71. fs_buf_need
  72. fs_buf_str
  73. fs_buf_uleb128
  74. fs_prep_var
  75. fs_fixup_var
  76. bcopisret
  77. fs_fixup_ret
  78. fs_finish
  79. fs_init
  80. expr_str
  81. expr_index
  82. expr_field
  83. expr_bracket
  84. expr_kvalue
  85. expr_table
  86. parse_params
  87. parse_body
  88. expr_list
  89. parse_args
  90. expr_primary
  91. expr_simple
  92. synlevel_begin
  93. token2binop
  94. expr_unop
  95. expr_binop
  96. expr
  97. expr_next
  98. expr_cond
  99. assign_hazard
  100. assign_adjust
  101. parse_assignment
  102. parse_call_assign
  103. parse_local
  104. parse_func
  105. endofblock
  106. parse_return
  107. parse_break
  108. parse_goto
  109. parse_label
  110. parse_block
  111. parse_while
  112. parse_repeat
  113. parse_for_num
  114. predict_next
  115. parse_for_iter
  116. parse_for
  117. parse_then
  118. parse_if
  119. parse_stmt
  120. parse_chunk
  121. lj_parse

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

/* [<][>][^][v][top][bottom][index][help] */