• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tarantool / luajit / 5784628350

07 Aug 2023 11:39AM UTC coverage: 87.373% (+2.2%) from 85.197%
5784628350

push

github

ligurio
setup-gcovr [TO SQUASH]

5317 of 6002 branches covered (88.59%)

Branch coverage included in aggregate %.

20381 of 23410 relevant lines covered (87.06%)

242527.58 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.4
/src/lj_parse.c
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_buf.h"
17
#include "lj_str.h"
18
#include "lj_tab.h"
19
#include "lj_func.h"
20
#include "lj_state.h"
21
#include "lj_bc.h"
22
#if LJ_HASFFI
23
#include "lj_ctype.h"
24
#endif
25
#include "lj_strfmt.h"
26
#include "lj_lex.h"
27
#include "lj_parse.h"
28
#include "lj_vm.h"
29
#include "lj_vmevent.h"
30
#if LJ_HASMEMPROF
31
#include "lj_memprof.h"
32
#endif
33
#if LJ_HASSYSPROF
34
#include "lj_sysprof.h"
35
#endif
36

37
/* -- Parser structures and definitions ----------------------------------- */
38

39
/* Expression kinds. */
40
typedef enum {
41
  /* Constant expressions must be first and in this order: */
42
  VKNIL,
43
  VKFALSE,
44
  VKTRUE,
45
  VKSTR,        /* sval = string value */
46
  VKNUM,        /* nval = number value */
47
  VKLAST = VKNUM,
48
  VKCDATA,        /* nval = cdata value, not treated as a constant expression */
49
  /* Non-constant expressions follow: */
50
  VLOCAL,        /* info = local register, aux = vstack index */
51
  VUPVAL,        /* info = upvalue index, aux = vstack index */
52
  VGLOBAL,        /* sval = string value */
53
  VINDEXED,        /* info = table register, aux = index reg/byte/string const */
54
  VJMP,                /* info = instruction PC */
55
  VRELOCABLE,        /* info = instruction PC */
56
  VNONRELOC,        /* info = result register */
57
  VCALL,        /* info = instruction PC, aux = base */
58
  VVOID
59
} ExpKind;
60

61
/* Expression descriptor. */
62
typedef struct ExpDesc {
63
  union {
64
    struct {
65
      uint32_t info;        /* Primary info. */
66
      uint32_t aux;        /* Secondary info. */
67
    } s;
68
    TValue nval;        /* Number value. */
69
    GCstr *sval;        /* String value. */
70
  } u;
71
  ExpKind k;
72
  BCPos t;                /* True condition jump list. */
73
  BCPos f;                /* False condition jump list. */
74
} ExpDesc;
75

76
/* Macros for expressions. */
77
#define expr_hasjump(e)                ((e)->t != (e)->f)
78

79
#define expr_isk(e)                ((e)->k <= VKLAST)
80
#define expr_isk_nojump(e)        (expr_isk(e) && !expr_hasjump(e))
81
#define expr_isnumk(e)                ((e)->k == VKNUM)
82
#define expr_isnumk_nojump(e)        (expr_isnumk(e) && !expr_hasjump(e))
83
#define expr_isstrk(e)                ((e)->k == VKSTR)
84

85
#define expr_numtv(e)                check_exp(expr_isnumk((e)), &(e)->u.nval)
86
#define expr_numberV(e)                numberVnum(expr_numtv((e)))
87

88
/* Initialize expression. */
89
static LJ_AINLINE void expr_init(ExpDesc *e, ExpKind k, uint32_t info)
791,742✔
90
{
91
  e->k = k;
791,742✔
92
  e->u.s.info = info;
791,742✔
93
  e->f = e->t = NO_JMP;
791,742✔
94
}
41,917✔
95

96
/* Check number constant for +-0. */
97
static int expr_numiszero(ExpDesc *e)
394✔
98
{
99
  TValue *o = expr_numtv(e);
394✔
100
  return tvisint(o) ? (intV(o) == 0) : tviszero(o);
394✔
101
}
102

103
/* Per-function linked list of scope blocks. */
104
typedef struct FuncScope {
105
  struct FuncScope *prev;        /* Link to outer scope. */
106
  MSize vstart;                        /* Start of block-local variables. */
107
  uint8_t nactvar;                /* Number of active vars outside the scope. */
108
  uint8_t flags;                /* Scope flags. */
109
} FuncScope;
110

111
#define FSCOPE_LOOP                0x01        /* Scope is a (breakable) loop. */
112
#define FSCOPE_BREAK                0x02        /* Break used in scope. */
113
#define FSCOPE_GOLA                0x04        /* Goto or label used in scope. */
114
#define FSCOPE_UPVAL                0x08        /* Upvalue in scope. */
115
#define FSCOPE_NOCLOSE                0x10        /* Do not close upvalues. */
116

117
#define NAME_BREAK                ((GCstr *)(uintptr_t)1)
118

119
/* Index into variable stack. */
120
typedef uint16_t VarIndex;
121
#define LJ_MAX_VSTACK                (65536 - LJ_MAX_UPVAL)
122

123
/* Variable/goto/label info. */
124
#define VSTACK_VAR_RW                0x01        /* R/W variable. */
125
#define VSTACK_GOTO                0x02        /* Pending goto. */
126
#define VSTACK_LABEL                0x04        /* Label. */
127

128
/* Per-function state. */
129
typedef struct FuncState {
130
  GCtab *kt;                        /* Hash table for constants. */
131
  LexState *ls;                        /* Lexer state. */
132
  lua_State *L;                        /* Lua state. */
133
  FuncScope *bl;                /* Current scope. */
134
  struct FuncState *prev;        /* Enclosing function. */
135
  BCPos pc;                        /* Next bytecode position. */
136
  BCPos lasttarget;                /* Bytecode position of last jump target. */
137
  BCPos jpc;                        /* Pending jump list to next bytecode. */
138
  BCReg freereg;                /* First free register. */
139
  BCReg nactvar;                /* Number of active local variables. */
140
  BCReg nkn, nkgc;                /* Number of lua_Number/GCobj constants */
141
  BCLine linedefined;                /* First line of the function definition. */
142
  BCInsLine *bcbase;                /* Base of bytecode stack. */
143
  BCPos bclim;                        /* Limit of bytecode stack. */
144
  MSize vbase;                        /* Base of variable stack for this function. */
145
  uint8_t flags;                /* Prototype flags. */
146
  uint8_t numparams;                /* Number of parameters. */
147
  uint8_t framesize;                /* Fixed frame size. */
148
  uint8_t nuv;                        /* Number of upvalues */
149
  VarIndex varmap[LJ_MAX_LOCVAR];  /* Map from register to variable idx. */
150
  VarIndex uvmap[LJ_MAX_UPVAL];        /* Map from upvalue to variable idx. */
151
  VarIndex uvtmp[LJ_MAX_UPVAL];        /* Temporary upvalue map. */
152
} FuncState;
153

154
/* Binary and unary operators. ORDER OPR */
155
typedef enum BinOpr {
156
  OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW,  /* ORDER ARITH */
157
  OPR_CONCAT,
158
  OPR_NE, OPR_EQ,
159
  OPR_LT, OPR_GE, OPR_LE, OPR_GT,
160
  OPR_AND, OPR_OR,
161
  OPR_NOBINOPR
162
} BinOpr;
163

164
LJ_STATIC_ASSERT((int)BC_ISGE-(int)BC_ISLT == (int)OPR_GE-(int)OPR_LT);
165
LJ_STATIC_ASSERT((int)BC_ISLE-(int)BC_ISLT == (int)OPR_LE-(int)OPR_LT);
166
LJ_STATIC_ASSERT((int)BC_ISGT-(int)BC_ISLT == (int)OPR_GT-(int)OPR_LT);
167
LJ_STATIC_ASSERT((int)BC_SUBVV-(int)BC_ADDVV == (int)OPR_SUB-(int)OPR_ADD);
168
LJ_STATIC_ASSERT((int)BC_MULVV-(int)BC_ADDVV == (int)OPR_MUL-(int)OPR_ADD);
169
LJ_STATIC_ASSERT((int)BC_DIVVV-(int)BC_ADDVV == (int)OPR_DIV-(int)OPR_ADD);
170
LJ_STATIC_ASSERT((int)BC_MODVV-(int)BC_ADDVV == (int)OPR_MOD-(int)OPR_ADD);
171

172
/* -- Error handling ------------------------------------------------------ */
173

174
LJ_NORET LJ_NOINLINE static void err_syntax(LexState *ls, ErrMsg em)
36✔
175
{
176
  lj_lex_error(ls, ls->tok, em);
36✔
177
}
178

179
LJ_NORET LJ_NOINLINE static void err_token(LexState *ls, LexToken tok)
28✔
180
{
181
  lj_lex_error(ls, ls->tok, LJ_ERR_XTOKEN, lj_lex_token2str(ls, tok));
28✔
182
}
183

184
LJ_NORET static void err_limit(FuncState *fs, uint32_t limit, const char *what)
185
{
186
  if (fs->linedefined == 0)
187
    lj_lex_error(fs->ls, 0, LJ_ERR_XLIMM, limit, what);
188
  else
189
    lj_lex_error(fs->ls, 0, LJ_ERR_XLIMF, fs->linedefined, limit, what);
190
}
191

192
#define checklimit(fs, v, l, m)                if ((v) >= (l)) err_limit(fs, l, m)
193
#define checklimitgt(fs, v, l, m)        if ((v) > (l)) err_limit(fs, l, m)
194
#define checkcond(ls, c, em)                { if (!(c)) err_syntax(ls, em); }
195

196
/* -- Management of constants --------------------------------------------- */
197

198
/* Return bytecode encoding for primitive constant. */
199
#define const_pri(e)                check_exp((e)->k <= VKTRUE, (e)->k)
200

201
#define tvhaskslot(o)        ((o)->u32.hi == 0)
202
#define tvkslot(o)        ((o)->u32.lo)
203

204
/* Add a number constant. */
205
static BCReg const_num(FuncState *fs, ExpDesc *e)
134,642✔
206
{
207
  lua_State *L = fs->L;
134,642✔
208
  TValue *o;
134,642✔
209
  lua_assert(expr_isnumk(e));
134,642✔
210
  o = lj_tab_set(L, fs->kt, &e->u.nval);
134,642✔
211
  if (tvhaskslot(o))
134,642✔
212
    return tvkslot(o);
990✔
213
  o->u64 = fs->nkn;
133,652✔
214
  return fs->nkn++;
133,652✔
215
}
216

217
/* Add a GC object constant. */
218
static BCReg const_gc(FuncState *fs, GCobj *gc, uint32_t itype)
207,165✔
219
{
220
  lua_State *L = fs->L;
207,165✔
221
  TValue key, *o;
207,165✔
222
  setgcV(L, &key, gc, itype);
207,165✔
223
  /* NOBARRIER: the key is new or kept alive. */
224
  o = lj_tab_set(L, fs->kt, &key);
207,165✔
225
  if (tvhaskslot(o))
207,165✔
226
    return tvkslot(o);
30,476✔
227
  o->u64 = fs->nkgc;
176,689✔
228
  return fs->nkgc++;
176,689✔
229
}
230

231
/* Add a string constant. */
232
static BCReg const_str(FuncState *fs, ExpDesc *e)
167,732✔
233
{
234
  lua_assert(expr_isstrk(e) || e->k == VGLOBAL);
167,732✔
235
  return const_gc(fs, obj2gco(e->u.sval), LJ_TSTR);
167,732✔
236
}
237

238
/* Anchor string constant to avoid GC. */
239
GCstr *lj_parse_keepstr(LexState *ls, const char *str, size_t len)
714,542✔
240
{
241
  /* NOBARRIER: the key is new or kept alive. */
242
  lua_State *L = ls->L;
714,542✔
243
  GCstr *s = lj_str_new(L, str, len);
714,542✔
244
  TValue *tv = lj_tab_setstr(L, ls->fs->kt, s);
714,542✔
245
  if (tvisnil(tv)) setboolV(tv, 1);
714,542✔
246
  lj_gc_check(L);
714,542✔
247
  return s;
714,542✔
248
}
249

250
#if LJ_HASFFI
251
/* Anchor cdata to avoid GC. */
252
void lj_parse_keepcdata(LexState *ls, TValue *tv, GCcdata *cd)
138✔
253
{
254
  /* NOBARRIER: the key is new or kept alive. */
255
  lua_State *L = ls->L;
138✔
256
  setcdataV(L, tv, cd);
138✔
257
  setboolV(lj_tab_set(L, ls->fs->kt, tv), 1);
138✔
258
}
138✔
259
#endif
260

261
/* -- Jump list handling -------------------------------------------------- */
262

263
/* Get next element in jump list. */
264
static BCPos jmp_next(FuncState *fs, BCPos pc)
36,332✔
265
{
266
  ptrdiff_t delta = bc_j(fs->bcbase[pc].ins);
36,332✔
267
  if ((BCPos)delta == NO_JMP)
36,332✔
268
    return NO_JMP;
269
  else
270
    return (BCPos)(((ptrdiff_t)pc+1)+delta);
4,716✔
271
}
272

273
/* Check if any of the instructions on the jump list produce no value. */
274
static int jmp_novalue(FuncState *fs, BCPos list)
275
{
276
  for (; list != NO_JMP; list = jmp_next(fs, list)) {
277
    BCIns p = fs->bcbase[list >= 1 ? list-1 : list].ins;
278
    if (!(bc_op(p) == BC_ISTC || bc_op(p) == BC_ISFC || bc_a(p) == NO_REG))
279
      return 1;
280
  }
281
  return 0;
282
}
283

284
/* Patch register of test instructions. */
285
static int jmp_patchtestreg(FuncState *fs, BCPos pc, BCReg reg)
286
{
287
  BCInsLine *ilp = &fs->bcbase[pc >= 1 ? pc-1 : pc];
288
  BCOp op = bc_op(ilp->ins);
289
  if (op == BC_ISTC || op == BC_ISFC) {
290
    if (reg != NO_REG && reg != bc_d(ilp->ins)) {
291
      setbc_a(&ilp->ins, reg);
292
    } else {  /* Nothing to store or already in the right register. */
293
      setbc_op(&ilp->ins, op+(BC_IST-BC_ISTC));
294
      setbc_a(&ilp->ins, 0);
295
    }
296
  } else if (bc_a(ilp->ins) == NO_REG) {
297
    if (reg == NO_REG) {
298
      ilp->ins = BCINS_AJ(BC_JMP, bc_a(fs->bcbase[pc].ins), 0);
299
    } else {
300
      setbc_a(&ilp->ins, reg);
301
      if (reg >= bc_a(ilp[1].ins))
302
        setbc_a(&ilp[1].ins, reg+1);
303
    }
304
  } else {
305
    return 0;  /* Cannot patch other instructions. */
306
  }
307
  return 1;
308
}
309

310
/* Drop values for all instructions on jump list. */
311
static void jmp_dropval(FuncState *fs, BCPos list)
1,962✔
312
{
313
  for (; list != NO_JMP; list = jmp_next(fs, list))
1,963✔
314
    jmp_patchtestreg(fs, list, NO_REG);
1✔
315
}
1,962✔
316

317
/* Patch jump instruction to target. */
318
static void jmp_patchins(FuncState *fs, BCPos pc, BCPos dest)
39,491✔
319
{
320
  BCIns *jmp = &fs->bcbase[pc].ins;
39,491✔
321
  BCPos offset = dest-(pc+1)+BCBIAS_J;
39,491✔
322
  lua_assert(dest != NO_JMP);
39,491✔
323
  if (offset > BCMAX_D)
39,491✔
324
    err_syntax(fs->ls, LJ_ERR_XJUMP);
×
325
  setbc_d(jmp, offset);
39,491✔
326
}
35,657✔
327

328
/* Append to jump list. */
329
static void jmp_append(FuncState *fs, BCPos *l1, BCPos l2)
175,693✔
330
{
331
  if (l2 == NO_JMP) {
175,693✔
332
    return;
333
  } else if (*l1 == NO_JMP) {
67,722✔
334
    *l1 = l2;
63,006✔
335
  } else {
336
    BCPos list = *l1;
337
    BCPos next;
338
    while ((next = jmp_next(fs, list)) != NO_JMP)  /* Find last element. */
5,390✔
339
      list = next;
340
    jmp_patchins(fs, list, l2);
4,716✔
341
  }
342
}
343

344
/* Patch jump list and preserve produced values. */
345
static void jmp_patchval(FuncState *fs, BCPos list, BCPos vtarget,
587,330✔
346
                         BCReg reg, BCPos dtarget)
347
{
348
  while (list != NO_JMP) {
587,330✔
349
    BCPos next = jmp_next(fs, list);
30,941✔
350
    if (jmp_patchtestreg(fs, list, reg))
30,941✔
351
      jmp_patchins(fs, list, vtarget);  /* Jump to target with value. */
21,880✔
352
    else
353
      jmp_patchins(fs, list, dtarget);  /* Jump to default target. */
627,332✔
354
    list = next;
355
  }
356
}
587,330✔
357

358
/* Jump to following instruction. Append to list of pending jumps. */
359
static void jmp_tohere(FuncState *fs, BCPos list)
53,034✔
360
{
361
  fs->lasttarget = fs->pc;
53,034✔
362
  jmp_append(fs, &fs->jpc, list);
53,034✔
363
}
3,018✔
364

365
/* Patch jump list to target. */
366
static void jmp_patch(FuncState *fs, BCPos list, BCPos target)
324✔
367
{
368
  if (target == fs->pc) {
324✔
369
    jmp_tohere(fs, list);
138✔
370
  } else {
371
    lua_assert(target < fs->pc);
186✔
372
    jmp_patchval(fs, list, target, NO_REG, target);
186✔
373
  }
374
}
324✔
375

376
/* -- Bytecode register allocator ----------------------------------------- */
377

378
/* Bump frame size. */
379
static void bcreg_bump(FuncState *fs, BCReg n)
170,298✔
380
{
381
  BCReg sz = fs->freereg + n;
170,298✔
382
  if (sz > fs->framesize) {
170,298✔
383
    if (sz >= LJ_MAX_SLOTS)
43,672✔
384
      err_syntax(fs->ls, LJ_ERR_XSLOTS);
×
385
    fs->framesize = (uint8_t)sz;
43,672✔
386
  }
387
}
388

389
/* Reserve registers. */
390
static void bcreg_reserve(FuncState *fs, BCReg n)
169,763✔
391
{
392
  bcreg_bump(fs, n);
169,763✔
393
  fs->freereg += n;
169,763✔
394
}
169,763✔
395

396
/* Free register. */
397
static void bcreg_free(FuncState *fs, BCReg reg)
79,520✔
398
{
399
  if (reg >= fs->nactvar) {
79,520✔
400
    fs->freereg--;
35,692✔
401
    lua_assert(reg == fs->freereg);
1,260✔
402
  }
403
}
404

405
/* Free register for expression. */
406
static void expr_free(FuncState *fs, ExpDesc *e)
425,884✔
407
{
408
  if (e->k == VNONRELOC)
425,884✔
409
    bcreg_free(fs, e->u.s.info);
57,591✔
410
}
411

412
/* -- Bytecode emitter ---------------------------------------------------- */
413

414
/* Emit bytecode instruction. */
415
static BCPos bcemit_INS(FuncState *fs, BCIns ins)
558,098✔
416
{
417
  BCPos pc = fs->pc;
558,098✔
418
  LexState *ls = fs->ls;
558,098✔
419
  jmp_patchval(fs, fs->jpc, pc, NO_REG, pc);
558,098✔
420
  fs->jpc = NO_JMP;
558,098✔
421
  if (LJ_UNLIKELY(pc >= fs->bclim)) {
558,098✔
422
    ptrdiff_t base = fs->bcbase - ls->bcstack;
18,797✔
423
    checklimit(fs, ls->sizebcstack, LJ_MAX_BCINS, "bytecode instructions");
18,797✔
424
    lj_mem_growvec(fs->L, ls->bcstack, ls->sizebcstack, LJ_MAX_BCINS,BCInsLine);
18,797✔
425
    fs->bclim = (BCPos)(ls->sizebcstack - base);
18,797✔
426
    fs->bcbase = ls->bcstack + base;
18,797✔
427
  }
428
  fs->bcbase[pc].ins = ins;
558,098✔
429
  fs->bcbase[pc].line = ls->lastline;
558,098✔
430
  fs->pc = pc+1;
558,098✔
431
  return pc;
558,098✔
432
}
433

434
#define bcemit_ABC(fs, o, a, b, c)        bcemit_INS(fs, BCINS_ABC(o, a, b, c))
435
#define bcemit_AD(fs, o, a, d)                bcemit_INS(fs, BCINS_AD(o, a, d))
436
#define bcemit_AJ(fs, o, a, j)                bcemit_INS(fs, BCINS_AJ(o, a, j))
437

438
#define bcptr(fs, e)                        (&(fs)->bcbase[(e)->u.s.info].ins)
439

440
/* -- Bytecode emitter for expressions ------------------------------------ */
441

442
/* Discharge non-constant expression to any register. */
443
static void expr_discharge(FuncState *fs, ExpDesc *e)
818,785✔
444
{
445
  BCIns ins;
818,785✔
446
  if (e->k == VUPVAL) {
818,785✔
447
    ins = BCINS_AD(BC_UGET, 0, e->u.s.info);
9,009✔
448
  } else if (e->k == VGLOBAL) {
809,776✔
449
    ins = BCINS_AD(BC_GGET, 0, const_str(fs, e));
16,155✔
450
  } else if (e->k == VINDEXED) {
793,621✔
451
    BCReg rc = e->u.s.aux;
20,669✔
452
    if ((int32_t)rc < 0) {
20,669✔
453
      ins = BCINS_ABC(BC_TGETS, 0, e->u.s.info, ~rc);
18,419✔
454
    } else if (rc > BCMAX_C) {
2,250✔
455
      ins = BCINS_ABC(BC_TGETB, 0, e->u.s.info, rc-(BCMAX_C+1));
990✔
456
    } else {
457
      bcreg_free(fs, rc);
1,260✔
458
      ins = BCINS_ABC(BC_TGETV, 0, e->u.s.info, rc);
1,260✔
459
    }
460
    bcreg_free(fs, e->u.s.info);
20,669✔
461
  } else if (e->k == VCALL) {
772,952✔
462
    e->u.s.info = e->u.s.aux;
7,029✔
463
    e->k = VNONRELOC;
7,029✔
464
    return;
7,029✔
465
  } else if (e->k == VLOCAL) {
765,923✔
466
    e->k = VNONRELOC;
68,247✔
467
    return;
68,247✔
468
  } else {
469
    return;
470
  }
471
  e->u.s.info = bcemit_INS(fs, ins);
45,833✔
472
  e->k = VRELOCABLE;
45,833✔
473
}
474

475
/* Emit bytecode to set a range of registers to nil. */
476
static void bcemit_nil(FuncState *fs, BCReg from, BCReg n)
8,629✔
477
{
478
  if (fs->pc > fs->lasttarget) {  /* No jumps to current position? */
8,629✔
479
    BCIns *ip = &fs->bcbase[fs->pc-1].ins;
2,450✔
480
    BCReg pto, pfrom = bc_a(*ip);
2,450✔
481
    switch (bc_op(*ip)) {  /* Try to merge with the previous instruction. */
2,450✔
482
    case BC_KPRI:
23✔
483
      if (bc_d(*ip) != ~LJ_TNIL) break;
23✔
484
      if (from == pfrom) {
20✔
485
        if (n == 1) return;
×
486
      } else if (from == pfrom+1) {
20✔
487
        from = pfrom;
20✔
488
        n++;
20✔
489
      } else {
490
        break;
491
      }
492
      *ip = BCINS_AD(BC_KNIL, from, from+n-1);  /* Replace KPRI. */
20✔
493
      return;
20✔
494
    case BC_KNIL:
111✔
495
      pto = bc_d(*ip);
111✔
496
      if (pfrom <= from && from <= pto+1) {  /* Can we connect both ranges? */
111✔
497
        if (from+n-1 > pto)
111✔
498
          setbc_d(ip, from+n-1);  /* Patch previous instruction range. */
111✔
499
        return;
111✔
500
      }
501
      break;
502
    default:
503
      break;
504
    }
505
  }
6,182✔
506
  /* Emit new instruction or replace old instruction. */
507
  bcemit_INS(fs, n == 1 ? BCINS_AD(BC_KPRI, from, VKNIL) :
8,560✔
508
                          BCINS_AD(BC_KNIL, from, from+n-1));
62✔
509
}
510

511
/* Discharge an expression to a specific register. Ignore branches. */
512
static void expr_toreg_nobranch(FuncState *fs, ExpDesc *e, BCReg reg)
412,837✔
513
{
514
  BCIns ins;
412,837✔
515
  expr_discharge(fs, e);
412,837✔
516
  if (e->k == VKSTR) {
412,837✔
517
    ins = BCINS_AD(BC_KSTR, reg, const_str(fs, e));
144,660✔
518
  } else if (e->k == VKNUM) {
268,177✔
519
#if LJ_DUALNUM
520
    cTValue *tv = expr_numtv(e);
521
    if (tvisint(tv) && checki16(intV(tv)))
522
      ins = BCINS_AD(BC_KSHORT, reg, (BCReg)(uint16_t)intV(tv));
523
    else
524
#else
525
    lua_Number n = expr_numberV(e);
147,207✔
526
    int32_t k = lj_num2int(n);
147,207✔
527
    if (checki16(k) && n == (lua_Number)k)
147,207✔
528
      ins = BCINS_AD(BC_KSHORT, reg, (BCReg)(uint16_t)k);
15,668✔
529
    else
530
#endif
531
      ins = BCINS_AD(BC_KNUM, reg, const_num(fs, e));
131,539✔
532
#if LJ_HASFFI
533
  } else if (e->k == VKCDATA) {
120,970✔
534
    fs->flags |= PROTO_FFI;
138✔
535
    ins = BCINS_AD(BC_KCDATA, reg,
138✔
536
                   const_gc(fs, obj2gco(cdataV(&e->u.nval)), LJ_TCDATA));
537
#endif
538
  } else if (e->k == VRELOCABLE) {
120,832✔
539
    setbc_a(bcptr(fs, e), reg);
66,287✔
540
    goto noins;
66,287✔
541
  } else if (e->k == VNONRELOC) {
54,545✔
542
    if (reg == e->u.s.info)
25,178✔
543
      goto noins;
4,331✔
544
    ins = BCINS_AD(BC_MOV, reg, e->u.s.info);
20,847✔
545
  } else if (e->k == VKNIL) {
29,367✔
546
    bcemit_nil(fs, reg, 1);
8,213✔
547
    goto noins;
8,213✔
548
  } else if (e->k <= VKTRUE) {
21,154✔
549
    ins = BCINS_AD(BC_KPRI, reg, const_pri(e));
18,334✔
550
  } else {
551
    lua_assert(e->k == VVOID || e->k == VJMP);
552
    return;
553
  }
554
  bcemit_INS(fs, ins);
331,186✔
555
noins:
410,017✔
556
  e->u.s.info = reg;
410,017✔
557
  e->k = VNONRELOC;
410,017✔
558
}
559

560
/* Forward declaration. */
561
static BCPos bcemit_jmp(FuncState *fs);
562

563
/* Discharge an expression to a specific register. */
564
static void expr_toreg(FuncState *fs, ExpDesc *e, BCReg reg)
393,230✔
565
{
566
  expr_toreg_nobranch(fs, e, reg);
393,230✔
567
  if (e->k == VJMP)
393,230✔
568
    jmp_append(fs, &e->t, e->u.s.info);  /* Add it to the true jump list. */
2,820✔
569
  if (expr_hasjump(e)) {  /* Discharge expression with branches. */
393,230✔
570
    BCPos jend, jfalse = NO_JMP, jtrue = NO_JMP;
14,523✔
571
    if (jmp_novalue(fs, e->t) || jmp_novalue(fs, e->f)) {
14,523✔
572
      BCPos jval = (e->k == VJMP) ? NO_JMP : bcemit_jmp(fs);
2,880✔
573
      jfalse = bcemit_AD(fs, BC_KPRI, reg, VKFALSE);
2,880✔
574
      bcemit_AJ(fs, BC_JMP, fs->freereg, 1);
2,880✔
575
      jtrue = bcemit_AD(fs, BC_KPRI, reg, VKTRUE);
2,880✔
576
      jmp_tohere(fs, jval);
2,880✔
577
    }
578
    jend = fs->pc;
14,523✔
579
    fs->lasttarget = jend;
14,523✔
580
    jmp_patchval(fs, e->f, jend, reg, jfalse);
14,523✔
581
    jmp_patchval(fs, e->t, jend, reg, jtrue);
14,523✔
582
  }
583
  e->f = e->t = NO_JMP;
393,230✔
584
  e->u.s.info = reg;
393,230✔
585
  e->k = VNONRELOC;
393,230✔
586
}
393,230✔
587

588
/* Discharge an expression to the next free register. */
589
static void expr_tonextreg(FuncState *fs, ExpDesc *e)
125,068✔
590
{
591
  expr_discharge(fs, e);
125,068✔
592
  expr_free(fs, e);
125,068✔
593
  bcreg_reserve(fs, 1);
125,068✔
594
  expr_toreg(fs, e, fs->freereg - 1);
125,068✔
595
}
125,068✔
596

597
/* Discharge an expression to any register. */
598
static BCReg expr_toanyreg(FuncState *fs, ExpDesc *e)
118,857✔
599
{
600
  expr_discharge(fs, e);
118,857✔
601
  if (e->k == VNONRELOC) {
118,857✔
602
    if (!expr_hasjump(e)) return e->u.s.info;  /* Already in a register. */
71,221✔
603
    if (e->u.s.info >= fs->nactvar) {
31✔
604
      expr_toreg(fs, e, e->u.s.info);  /* Discharge to temp. register. */
20✔
605
      return e->u.s.info;
20✔
606
    }
607
  }
608
  expr_tonextreg(fs, e);  /* Discharge to next register. */
47,647✔
609
  return e->u.s.info;
47,647✔
610
}
611

612
/* Partially discharge expression to a value. */
613
static void expr_toval(FuncState *fs, ExpDesc *e)
38,621✔
614
{
615
  if (expr_hasjump(e))
38,621✔
616
    expr_toanyreg(fs, e);
20✔
617
  else
618
    expr_discharge(fs, e);
38,601✔
619
}
38,621✔
620

621
/* Emit store for LHS expression. */
622
static void bcemit_store(FuncState *fs, ExpDesc *var, ExpDesc *e)
283,395✔
623
{
624
  BCIns ins;
283,395✔
625
  if (var->k == VLOCAL) {
283,395✔
626
    fs->ls->vstack[var->u.s.aux].info |= VSTACK_VAR_RW;
265,470✔
627
    expr_free(fs, e);
265,470✔
628
    expr_toreg(fs, e, var->u.s.info);
265,470✔
629
    return;
265,470✔
630
  } else if (var->k == VUPVAL) {
17,925✔
631
    fs->ls->vstack[var->u.s.aux].info |= VSTACK_VAR_RW;
342✔
632
    expr_toval(fs, e);
342✔
633
    if (e->k <= VKTRUE)
342✔
634
      ins = BCINS_AD(BC_USETP, var->u.s.info, const_pri(e));
24✔
635
    else if (e->k == VKSTR)
318✔
636
      ins = BCINS_AD(BC_USETS, var->u.s.info, const_str(fs, e));
9✔
637
    else if (e->k == VKNUM)
309✔
638
      ins = BCINS_AD(BC_USETN, var->u.s.info, const_num(fs, e));
3✔
639
    else
640
      ins = BCINS_AD(BC_USETV, var->u.s.info, expr_toanyreg(fs, e));
306✔
641
  } else if (var->k == VGLOBAL) {
17,583✔
642
    BCReg ra = expr_toanyreg(fs, e);
1,882✔
643
    ins = BCINS_AD(BC_GSET, ra, const_str(fs, var));
1,882✔
644
  } else {
645
    BCReg ra, rc;
15,701✔
646
    lua_assert(var->k == VINDEXED);
15,701✔
647
    ra = expr_toanyreg(fs, e);
15,701✔
648
    rc = var->u.s.aux;
15,701✔
649
    if ((int32_t)rc < 0) {
15,701✔
650
      ins = BCINS_ABC(BC_TSETS, ra, var->u.s.info, ~rc);
13,871✔
651
    } else if (rc > BCMAX_C) {
1,830✔
652
      ins = BCINS_ABC(BC_TSETB, ra, var->u.s.info, rc-(BCMAX_C+1));
1,180✔
653
    } else {
654
      /* Free late alloced key reg to avoid assert on free of value reg. */
655
      /* This can only happen when called from expr_table(). */
656
      lua_assert(e->k != VNONRELOC || ra < fs->nactvar ||
650✔
657
                 rc < ra || (bcreg_free(fs, rc),1));
658
      ins = BCINS_ABC(BC_TSETV, ra, var->u.s.info, rc);
650✔
659
    }
660
  }
661
  bcemit_INS(fs, ins);
17,925✔
662
  expr_free(fs, e);
17,925✔
663
}
664

665
/* Emit method lookup expression. */
666
static void bcemit_method(FuncState *fs, ExpDesc *e, ExpDesc *key)
3,532✔
667
{
668
  BCReg idx, func, obj = expr_toanyreg(fs, e);
3,532✔
669
  expr_free(fs, e);
3,532✔
670
  func = fs->freereg;
3,532✔
671
  bcemit_AD(fs, BC_MOV, func+1+LJ_FR2, obj);  /* Copy object to 1st argument. */
3,532✔
672
  lua_assert(expr_isstrk(key));
3,532✔
673
  idx = const_str(fs, key);
3,532✔
674
  if (idx <= BCMAX_C) {
3,532✔
675
    bcreg_reserve(fs, 2+LJ_FR2);
3,526✔
676
    bcemit_ABC(fs, BC_TGETS, func, obj, idx);
3,526✔
677
  } else {
678
    bcreg_reserve(fs, 3+LJ_FR2);
6✔
679
    bcemit_AD(fs, BC_KSTR, func+2+LJ_FR2, idx);
6✔
680
    bcemit_ABC(fs, BC_TGETV, func, obj, func+2+LJ_FR2);
6✔
681
    fs->freereg--;
6✔
682
  }
683
  e->u.s.info = func;
3,532✔
684
  e->k = VNONRELOC;
3,532✔
685
}
3,532✔
686

687
/* -- Bytecode emitter for branches --------------------------------------- */
688

689
/* Emit unconditional branch. */
690
static BCPos bcemit_jmp(FuncState *fs)
30,992✔
691
{
692
  BCPos jpc = fs->jpc;
30,992✔
693
  BCPos j = fs->pc - 1;
30,992✔
694
  BCIns *ip = &fs->bcbase[j].ins;
30,992✔
695
  fs->jpc = NO_JMP;
30,992✔
696
  if ((int32_t)j >= (int32_t)fs->lasttarget && bc_op(*ip) == BC_UCLO) {
30,992✔
697
    setbc_j(ip, NO_JMP);
32✔
698
    fs->lasttarget = j+1;
32✔
699
  } else {
700
    j = bcemit_AJ(fs, BC_JMP, fs->freereg, NO_JMP);
30,960✔
701
  }
702
  jmp_append(fs, &j, jpc);
30,992✔
703
  return j;
30,992✔
704
}
705

706
/* Invert branch condition of bytecode instruction. */
707
static void invertcond(FuncState *fs, ExpDesc *e)
3,417✔
708
{
709
  BCIns *ip = &fs->bcbase[e->u.s.info - 1].ins;
3,417✔
710
  setbc_op(ip, bc_op(*ip)^1);
3,417✔
711
}
712

713
/* Emit conditional branch. */
714
static BCPos bcemit_branch(FuncState *fs, ExpDesc *e, int cond)
4,275✔
715
{
716
  BCPos pc;
4,275✔
717
  if (e->k == VRELOCABLE) {
4,275✔
718
    BCIns *ip = bcptr(fs, e);
1,996✔
719
    if (bc_op(*ip) == BC_NOT) {
1,996✔
720
      *ip = BCINS_AD(cond ? BC_ISF : BC_IST, 0, bc_d(*ip));
717✔
721
      return bcemit_jmp(fs);
717✔
722
    }
723
  }
724
  if (e->k != VNONRELOC) {
3,558✔
725
    bcreg_reserve(fs, 1);
1,281✔
726
    expr_toreg_nobranch(fs, e, fs->freereg-1);
1,281✔
727
  }
728
  bcemit_AD(fs, cond ? BC_ISTC : BC_ISFC, NO_REG, e->u.s.info);
5,473✔
729
  pc = bcemit_jmp(fs);
3,558✔
730
  expr_free(fs, e);
3,558✔
731
  return pc;
732
}
733

734
/* Emit branch on true condition. */
735
static void bcemit_branch_t(FuncState *fs, ExpDesc *e)
24,055✔
736
{
737
  BCPos pc;
24,055✔
738
  expr_discharge(fs, e);
24,055✔
739
  if (e->k == VKSTR || e->k == VKNUM || e->k == VKTRUE)
24,055✔
740
    pc = NO_JMP;  /* Never jump. */
741
  else if (e->k == VJMP)
14,955✔
742
    invertcond(fs, e), pc = e->u.s.info;
3,317✔
743
  else if (e->k == VKFALSE || e->k == VKNIL)
11,638✔
744
    expr_toreg_nobranch(fs, e, NO_REG), pc = bcemit_jmp(fs);
9,020✔
745
  else
746
    pc = bcemit_branch(fs, e, 0);
2,618✔
747
  jmp_append(fs, &e->f, pc);
24,055✔
748
  jmp_tohere(fs, e->t);
24,055✔
749
  e->t = NO_JMP;
24,055✔
750
}
24,055✔
751

752
/* Emit branch on false condition. */
753
static void bcemit_branch_f(FuncState *fs, ExpDesc *e)
20,464✔
754
{
755
  BCPos pc;
20,464✔
756
  expr_discharge(fs, e);
20,464✔
757
  if (e->k == VKNIL || e->k == VKFALSE)
20,464✔
758
    pc = NO_JMP;  /* Never jump. */
759
  else if (e->k == VJMP)
11,452✔
760
    pc = e->u.s.info;
489✔
761
  else if (e->k == VKSTR || e->k == VKNUM || e->k == VKTRUE)
10,963✔
762
    expr_toreg_nobranch(fs, e, NO_REG), pc = bcemit_jmp(fs);
9,306✔
763
  else
764
    pc = bcemit_branch(fs, e, 1);
1,657✔
765
  jmp_append(fs, &e->t, pc);
20,464✔
766
  jmp_tohere(fs, e->f);
20,464✔
767
  e->f = NO_JMP;
20,464✔
768
}
20,464✔
769

770
/* -- Bytecode emitter for operators -------------------------------------- */
771

772
/* Try constant-folding of arithmetic operators. */
773
static int foldarith(BinOpr opr, ExpDesc *e1, ExpDesc *e2)
9,606✔
774
{
775
  TValue o;
9,606✔
776
  lua_Number n;
9,606✔
777
  if (!expr_isnumk_nojump(e1) || !expr_isnumk_nojump(e2)) return 0;
9,606✔
778
  n = lj_vm_foldarith(expr_numberV(e1), expr_numberV(e2), (int)opr-OPR_ADD);
179✔
779
  setnumV(&o, n);
179✔
780
  if (tvisnan(&o) || tvismzero(&o)) return 0;  /* Avoid NaN and -0 as consts. */
179✔
781
  if (LJ_DUALNUM) {
169✔
782
    int32_t k = lj_num2int(n);
783
    if ((lua_Number)k == n) {
784
      setintV(&e1->u.nval, k);
785
      return 1;
786
    }
787
  }
788
  setnumV(&e1->u.nval, n);
169✔
789
  return 1;
169✔
790
}
791

792
/* Emit arithmetic operator. */
793
static void bcemit_arith(FuncState *fs, BinOpr opr, ExpDesc *e1, ExpDesc *e2)
9,606✔
794
{
795
  BCReg rb, rc, t;
9,606✔
796
  uint32_t op;
9,606✔
797
  if (foldarith(opr, e1, e2))
9,606✔
798
    return;
799
  if (opr == OPR_POW) {
9,437✔
800
    op = BC_POW;
47✔
801
    rc = expr_toanyreg(fs, e2);
47✔
802
    rb = expr_toanyreg(fs, e1);
47✔
803
  } else {
804
    op = opr-OPR_ADD+BC_ADDVV;
9,390✔
805
    /* Must discharge 2nd operand first since VINDEXED might free regs. */
806
    expr_toval(fs, e2);
9,390✔
807
    if (expr_isnumk(e2) && (rc = const_num(fs, e2)) <= BCMAX_C)
9,390✔
808
      op -= BC_ADDVV-BC_ADDVN;
1,324✔
809
    else
810
      rc = expr_toanyreg(fs, e2);
8,066✔
811
    /* 1st operand discharged by bcemit_binop_left, but need KNUM/KSHORT. */
812
    lua_assert(expr_isnumk(e1) || e1->k == VNONRELOC);
9,390✔
813
    expr_toval(fs, e1);
9,390✔
814
    /* Avoid two consts to satisfy bytecode constraints. */
815
    if (expr_isnumk(e1) && !expr_isnumk(e2) &&
9,390✔
816
        (t = const_num(fs, e1)) <= BCMAX_B) {
119✔
817
      rb = rc; rc = t; op -= BC_ADDVV-BC_ADDNV;
119✔
818
    } else {
819
      rb = expr_toanyreg(fs, e1);
9,271✔
820
    }
821
  }
822
  /* Using expr_free might cause asserts if the order is wrong. */
823
  if (e1->k == VNONRELOC && e1->u.s.info >= fs->nactvar) fs->freereg--;
9,437✔
824
  if (e2->k == VNONRELOC && e2->u.s.info >= fs->nactvar) fs->freereg--;
9,437✔
825
  e1->u.s.info = bcemit_ABC(fs, op, 0, rb, rc);
9,437✔
826
  e1->k = VRELOCABLE;
9,437✔
827
}
828

829
/* Emit comparison operator. */
830
static void bcemit_comp(FuncState *fs, BinOpr opr, ExpDesc *e1, ExpDesc *e2)
6,628✔
831
{
832
  ExpDesc *eret = e1;
6,628✔
833
  BCIns ins;
6,628✔
834
  expr_toval(fs, e1);
6,628✔
835
  if (opr == OPR_EQ || opr == OPR_NE) {
6,628✔
836
    BCOp op = opr == OPR_EQ ? BC_ISEQV : BC_ISNEV;
5,708✔
837
    BCReg ra;
5,708✔
838
    if (expr_isk(e1)) { e1 = e2; e2 = eret; }  /* Need constant in 2nd arg. */
5,708✔
839
    ra = expr_toanyreg(fs, e1);  /* First arg must be in a reg. */
5,708✔
840
    expr_toval(fs, e2);
5,708✔
841
    switch (e2->k) {
5,708✔
842
    case VKNIL: case VKFALSE: case VKTRUE:
1,101✔
843
      ins = BCINS_AD(op+(BC_ISEQP-BC_ISEQV), ra, const_pri(e2));
1,101✔
844
      break;
1,101✔
845
    case VKSTR:
1,494✔
846
      ins = BCINS_AD(op+(BC_ISEQS-BC_ISEQV), ra, const_str(fs, e2));
1,494✔
847
      break;
1,494✔
848
    case VKNUM:
1,402✔
849
      ins = BCINS_AD(op+(BC_ISEQN-BC_ISEQV), ra, const_num(fs, e2));
1,402✔
850
      break;
1,402✔
851
    default:
1,711✔
852
      ins = BCINS_AD(op, ra, expr_toanyreg(fs, e2));
1,711✔
853
      break;
1,711✔
854
    }
855
  } else {
856
    uint32_t op = opr-OPR_LT+BC_ISLT;
920✔
857
    BCReg ra, rd;
920✔
858
    if ((op-BC_ISLT) & 1) {  /* GT -> LT, GE -> LE */
920✔
859
      e1 = e2; e2 = eret;  /* Swap operands. */
558✔
860
      op = ((op-BC_ISLT)^3)+BC_ISLT;
558✔
861
      expr_toval(fs, e1);
558✔
862
      ra = expr_toanyreg(fs, e1);
558✔
863
      rd = expr_toanyreg(fs, e2);
558✔
864
    } else {
865
      rd = expr_toanyreg(fs, e2);
362✔
866
      ra = expr_toanyreg(fs, e1);
362✔
867
    }
868
    ins = BCINS_AD(op, ra, rd);
920✔
869
  }
870
  /* Using expr_free might cause asserts if the order is wrong. */
871
  if (e1->k == VNONRELOC && e1->u.s.info >= fs->nactvar) fs->freereg--;
6,628✔
872
  if (e2->k == VNONRELOC && e2->u.s.info >= fs->nactvar) fs->freereg--;
6,628✔
873
  bcemit_INS(fs, ins);
6,628✔
874
  eret->u.s.info = bcemit_jmp(fs);
6,628✔
875
  eret->k = VJMP;
6,628✔
876
}
6,628✔
877

878
/* Fixup left side of binary operator. */
879
static void bcemit_binop_left(FuncState *fs, BinOpr op, ExpDesc *e)
59,654✔
880
{
881
  if (op == OPR_AND) {
59,654✔
882
    bcemit_branch_t(fs, e);
19,590✔
883
  } else if (op == OPR_OR) {
40,064✔
884
    bcemit_branch_f(fs, e);
20,464✔
885
  } else if (op == OPR_CONCAT) {
19,600✔
886
    expr_tonextreg(fs, e);
3,360✔
887
  } else if (op == OPR_EQ || op == OPR_NE) {
16,240✔
888
    if (!expr_isk_nojump(e)) expr_toanyreg(fs, e);
5,712✔
889
  } else {
890
    if (!expr_isnumk_nojump(e)) expr_toanyreg(fs, e);
10,528✔
891
  }
892
}
59,654✔
893

894
/* Emit binary operator. */
895
static void bcemit_binop(FuncState *fs, BinOpr op, ExpDesc *e1, ExpDesc *e2)
59,648✔
896
{
897
  if (op <= OPR_POW) {
59,648✔
898
    bcemit_arith(fs, op, e1, e2);
9,606✔
899
  } else if (op == OPR_AND) {
50,042✔
900
    lua_assert(e1->t == NO_JMP);  /* List must be closed. */
19,590✔
901
    expr_discharge(fs, e2);
19,590✔
902
    jmp_append(fs, &e2->f, e1->f);
19,590✔
903
    *e1 = *e2;
19,590✔
904
  } else if (op == OPR_OR) {
30,452✔
905
    lua_assert(e1->f == NO_JMP);  /* List must be closed. */
20,464✔
906
    expr_discharge(fs, e2);
20,464✔
907
    jmp_append(fs, &e2->t, e1->t);
20,464✔
908
    *e1 = *e2;
20,464✔
909
  } else if (op == OPR_CONCAT) {
9,988✔
910
    expr_toval(fs, e2);
3,360✔
911
    if (e2->k == VRELOCABLE && bc_op(*bcptr(fs, e2)) == BC_CAT) {
3,360✔
912
      lua_assert(e1->u.s.info == bc_b(*bcptr(fs, e2))-1);
1,015✔
913
      expr_free(fs, e1);
1,015✔
914
      setbc_b(bcptr(fs, e2), e1->u.s.info);
1,015✔
915
      e1->u.s.info = e2->u.s.info;
1,015✔
916
    } else {
917
      expr_tonextreg(fs, e2);
2,345✔
918
      expr_free(fs, e2);
2,345✔
919
      expr_free(fs, e1);
2,345✔
920
      e1->u.s.info = bcemit_ABC(fs, BC_CAT, 0, e1->u.s.info, e2->u.s.info);
2,345✔
921
    }
922
    e1->k = VRELOCABLE;
3,360✔
923
  } else {
924
    lua_assert(op == OPR_NE || op == OPR_EQ ||
6,628✔
925
               op == OPR_LT || op == OPR_GE || op == OPR_LE || op == OPR_GT);
926
    bcemit_comp(fs, op, e1, e2);
6,628✔
927
  }
928
}
59,648✔
929

930
/* Emit unary operator. */
931
static void bcemit_unop(FuncState *fs, BCOp op, ExpDesc *e)
2,402✔
932
{
933
  if (op == BC_NOT) {
2,402✔
934
    /* Swap true and false lists. */
935
    { BCPos temp = e->f; e->f = e->t; e->t = temp; }
981✔
936
    jmp_dropval(fs, e->f);
981✔
937
    jmp_dropval(fs, e->t);
981✔
938
    expr_discharge(fs, e);
981✔
939
    if (e->k == VKNIL || e->k == VKFALSE) {
981✔
940
      e->k = VKTRUE;
5✔
941
      return;
5✔
942
    } else if (expr_isk(e) || (LJ_HASFFI && e->k == VKCDATA)) {
976✔
943
      e->k = VKFALSE;
6✔
944
      return;
6✔
945
    } else if (e->k == VJMP) {
970✔
946
      invertcond(fs, e);
100✔
947
      return;
100✔
948
    } else if (e->k == VRELOCABLE) {
870✔
949
      bcreg_reserve(fs, 1);
151✔
950
      setbc_a(bcptr(fs, e), fs->freereg-1);
151✔
951
      e->u.s.info = fs->freereg-1;
151✔
952
      e->k = VNONRELOC;
151✔
953
    } else {
954
      lua_assert(e->k == VNONRELOC);
955
    }
956
  } else {
957
    lua_assert(op == BC_UNM || op == BC_LEN);
1,421✔
958
    if (op == BC_UNM && !expr_hasjump(e)) {  /* Constant-fold negations. */
1,421✔
959
#if LJ_HASFFI
960
      if (e->k == VKCDATA) {  /* Fold in-place since cdata is not interned. */
394✔
961
        GCcdata *cd = cdataV(&e->u.nval);
4✔
962
        int64_t *p = (int64_t *)cdataptr(cd);
4✔
963
        if (cd->ctypeid == CTID_COMPLEX_DOUBLE)
4✔
964
          p[1] ^= (int64_t)U64x(80000000,00000000);
×
965
        else
966
          *p = -*p;
4✔
967
        return;
4✔
968
      } else
969
#endif
970
      if (expr_isnumk(e) && !expr_numiszero(e)) {  /* Avoid folding to -0. */
390✔
971
        TValue *o = expr_numtv(e);
333✔
972
        if (tvisint(o)) {
333✔
973
          int32_t k = intV(o);
974
          if (k == -k)
975
            setnumV(o, -(lua_Number)k);
976
          else
977
            setintV(o, -k);
978
          return;
979
        } else {
980
          o->u64 ^= U64x(80000000,00000000);
333✔
981
          return;
333✔
982
        }
983
      }
984
    }
985
    expr_toanyreg(fs, e);
1,084✔
986
  }
987
  expr_free(fs, e);
1,954✔
988
  e->u.s.info = bcemit_AD(fs, op, 0, e->u.s.info);
1,954✔
989
  e->k = VRELOCABLE;
1,954✔
990
}
991

992
/* -- Lexer support ------------------------------------------------------- */
993

994
/* Check and consume optional token. */
995
static int lex_opt(LexState *ls, LexToken tok)
1,068,304✔
996
{
997
  if (ls->tok == tok) {
1,068,304✔
998
    lj_lex_next(ls);
101,129✔
999
    return 1;
544✔
1000
  }
1001
  return 0;
1002
}
1003

1004
/* Check and consume token. */
1005
static void lex_check(LexState *ls, LexToken tok)
309,151✔
1006
{
1007
  if (ls->tok != tok)
309,151✔
1008
    err_token(ls, tok);
13✔
1009
  lj_lex_next(ls);
309,138✔
1010
}
309,121✔
1011

1012
/* Check for matching token. */
1013
static void lex_match(LexState *ls, LexToken what, LexToken who, BCLine line)
73,614✔
1014
{
1015
  if (!lex_opt(ls, what)) {
73,614✔
1016
    if (line == ls->linenumber) {
67✔
1017
      err_token(ls, what);
9✔
1018
    } else {
1019
      const char *swhat = lj_lex_token2str(ls, what);
58✔
1020
      const char *swho = lj_lex_token2str(ls, who);
58✔
1021
      lj_lex_error(ls, ls->tok, LJ_ERR_XMATCH, swhat, swho, line);
58✔
1022
    }
1023
  }
1024
}
73,539✔
1025

1026
/* Check for string token. */
1027
static GCstr *lex_str(LexState *ls)
421,940✔
1028
{
1029
  GCstr *s;
421,940✔
1030
  if (ls->tok != TK_name && (LJ_52 || ls->tok != TK_goto))
421,940✔
1031
    err_token(ls, TK_name);
6✔
1032
  s = strV(&ls->tokval);
421,934✔
1033
  lj_lex_next(ls);
421,934✔
1034
  return s;
421,934✔
1035
}
1036

1037
/* -- Variable handling --------------------------------------------------- */
1038

1039
#define var_get(ls, fs, i)        ((ls)->vstack[(fs)->varmap[(i)]])
1040

1041
/* Define a new local variable. */
1042
static void var_new(LexState *ls, BCReg n, GCstr *name)
29,275✔
1043
{
1044
  FuncState *fs = ls->fs;
29,275✔
1045
  MSize vtop = ls->vtop;
29,275✔
1046
  checklimit(fs, fs->nactvar+n, LJ_MAX_LOCVAR, "local variables");
29,275✔
1047
  if (LJ_UNLIKELY(vtop >= ls->sizevstack)) {
29,275✔
1048
    if (ls->sizevstack >= LJ_MAX_VSTACK)
1,659✔
1049
      lj_lex_error(ls, 0, LJ_ERR_XLIMC, LJ_MAX_VSTACK);
×
1050
    lj_mem_growvec(ls->L, ls->vstack, ls->sizevstack, LJ_MAX_VSTACK, VarInfo);
1,659✔
1051
  }
1052
  lua_assert((uintptr_t)name < VARNAME__MAX ||
29,275✔
1053
             lj_tab_getstr(fs->kt, name) != NULL);
1054
  /* NOBARRIER: name is anchored in fs->kt and ls->vstack is not a GCobj. */
1055
  setgcref(ls->vstack[vtop].name, obj2gco(name));
29,275✔
1056
  fs->varmap[fs->nactvar+n] = (uint16_t)vtop;
29,275✔
1057
  ls->vtop = vtop+1;
29,275✔
1058
}
29,275✔
1059

1060
#define var_new_lit(ls, n, v) \
1061
  var_new(ls, (n), lj_parse_keepstr(ls, "" v, sizeof(v)-1))
1062

1063
#define var_new_fixed(ls, n, vn) \
1064
  var_new(ls, (n), (GCstr *)(uintptr_t)(vn))
1065

1066
/* Add local variables. */
1067
static void var_add(LexState *ls, BCReg nvars)
18,826✔
1068
{
1069
  FuncState *fs = ls->fs;
18,826✔
1070
  BCReg nactvar = fs->nactvar;
18,826✔
1071
  while (nvars--) {
48,092✔
1072
    VarInfo *v = &var_get(ls, fs, nactvar);
29,266✔
1073
    v->startpc = fs->pc;
29,266✔
1074
    v->slot = nactvar++;
29,266✔
1075
    v->info = 0;
29,266✔
1076
  }
1077
  fs->nactvar = nactvar;
18,826✔
1078
}
1079

1080
/* Remove local variables. */
1081
static void var_remove(LexState *ls, BCReg tolevel)
31,289✔
1082
{
1083
  FuncState *fs = ls->fs;
31,289✔
1084
  while (fs->nactvar > tolevel)
60,346✔
1085
    var_get(ls, fs, --fs->nactvar).endpc = fs->pc;
29,057✔
1086
}
1087

1088
/* Lookup local variable name. */
1089
static BCReg var_lookup_local(FuncState *fs, GCstr *n)
381,894✔
1090
{
1091
  int i;
381,894✔
1092
  for (i = fs->nactvar-1; i >= 0; i--) {
936,658✔
1093
    if (n == strref(var_get(fs->ls, fs, i).name))
897,832✔
1094
      return (BCReg)i;
343,068✔
1095
  }
1096
  return (BCReg)-1;  /* Not found. */
1097
}
1098

1099
/* Lookup or add upvalue index. */
1100
static MSize var_lookup_uv(FuncState *fs, MSize vidx, ExpDesc *e)
1101
{
1102
  MSize i, n = fs->nuv;
1103
  for (i = 0; i < n; i++)
1104
    if (fs->uvmap[i] == vidx)
1105
      return i;  /* Already exists. */
1106
  /* Otherwise create a new one. */
1107
  checklimit(fs, fs->nuv, LJ_MAX_UPVAL, "upvalues");
1108
  lua_assert(e->k == VLOCAL || e->k == VUPVAL);
1109
  fs->uvmap[n] = (uint16_t)vidx;
1110
  fs->uvtmp[n] = (uint16_t)(e->k == VLOCAL ? vidx : LJ_MAX_VSTACK+e->u.s.info);
1111
  fs->nuv = n+1;
1112
  return n;
1113
}
1114

1115
/* Forward declaration. */
1116
static void fscope_uvmark(FuncState *fs, BCReg level);
1117

1118
/* Recursively lookup variables in enclosing functions. */
1119
static MSize var_lookup_(FuncState *fs, GCstr *name, ExpDesc *e, int first)
400,045✔
1120
{
1121
  if (fs) {
400,045✔
1122
    BCReg reg = var_lookup_local(fs, name);
381,894✔
1123
    if ((int32_t)reg >= 0) {  /* Local in this function? */
381,894✔
1124
      expr_init(e, VLOCAL, reg);
343,068✔
1125
      if (!first)
343,068✔
1126
        fscope_uvmark(fs, reg);  /* Scope now has an upvalue. */
352,419✔
1127
      return (MSize)(e->u.s.aux = (uint32_t)fs->varmap[reg]);
343,068✔
1128
    } else {
1129
      MSize vidx = var_lookup_(fs->prev, name, e, 0);  /* Var in outer func? */
38,826✔
1130
      if ((int32_t)vidx >= 0) {  /* Yes, make it an upvalue here. */
38,826✔
1131
        e->u.s.info = (uint8_t)var_lookup_uv(fs, vidx, e);
9,892✔
1132
        e->k = VUPVAL;
9,892✔
1133
        return vidx;
9,892✔
1134
      }
1135
    }
1136
  } else {  /* Not found in any function, must be a global. */
1137
    expr_init(e, VGLOBAL, 0);
18,151✔
1138
    e->u.sval = name;
18,151✔
1139
  }
1140
  return (MSize)-1;  /* Global. */
1141
}
1142

1143
/* Lookup variable name. */
1144
#define var_lookup(ls, e) \
1145
  var_lookup_((ls)->fs, lex_str(ls), (e), 1)
1146

1147
/* -- Goto an label handling ---------------------------------------------- */
1148

1149
/* Add a new goto or label. */
1150
static MSize gola_new(LexState *ls, GCstr *name, uint8_t info, BCPos pc)
314✔
1151
{
1152
  FuncState *fs = ls->fs;
314✔
1153
  MSize vtop = ls->vtop;
314✔
1154
  if (LJ_UNLIKELY(vtop >= ls->sizevstack)) {
314✔
1155
    if (ls->sizevstack >= LJ_MAX_VSTACK)
90✔
1156
      lj_lex_error(ls, 0, LJ_ERR_XLIMC, LJ_MAX_VSTACK);
×
1157
    lj_mem_growvec(ls->L, ls->vstack, ls->sizevstack, LJ_MAX_VSTACK, VarInfo);
90✔
1158
  }
1159
  lua_assert(name == NAME_BREAK || lj_tab_getstr(fs->kt, name) != NULL);
314✔
1160
  /* NOBARRIER: name is anchored in fs->kt and ls->vstack is not a GCobj. */
1161
  setgcref(ls->vstack[vtop].name, obj2gco(name));
314✔
1162
  ls->vstack[vtop].startpc = pc;
314✔
1163
  ls->vstack[vtop].slot = (uint8_t)fs->nactvar;
314✔
1164
  ls->vstack[vtop].info = info;
314✔
1165
  ls->vtop = vtop+1;
314✔
1166
  return vtop;
314✔
1167
}
1168

1169
#define gola_isgoto(v)                ((v)->info & VSTACK_GOTO)
1170
#define gola_islabel(v)                ((v)->info & VSTACK_LABEL)
1171
#define gola_isgotolabel(v)        ((v)->info & (VSTACK_GOTO|VSTACK_LABEL))
1172

1173
/* Patch goto to jump to label. */
1174
static void gola_patch(LexState *ls, VarInfo *vg, VarInfo *vl)
4✔
1175
{
1176
  FuncState *fs = ls->fs;
4✔
1177
  BCPos pc = vg->startpc;
4✔
1178
  setgcrefnull(vg->name);  /* Invalidate pending goto. */
4✔
1179
  setbc_a(&fs->bcbase[pc].ins, vl->slot);
4✔
1180
  jmp_patch(fs, pc, vl->startpc);
4✔
1181
}
4✔
1182

1183
/* Patch goto to close upvalues. */
1184
static void gola_close(LexState *ls, VarInfo *vg)
1185
{
1186
  FuncState *fs = ls->fs;
1187
  BCPos pc = vg->startpc;
1188
  BCIns *ip = &fs->bcbase[pc].ins;
1189
  lua_assert(gola_isgoto(vg));
1190
  lua_assert(bc_op(*ip) == BC_JMP || bc_op(*ip) == BC_UCLO);
1191
  setbc_a(ip, vg->slot);
1192
  if (bc_op(*ip) == BC_JMP) {
1193
    BCPos next = jmp_next(fs, pc);
1194
    if (next != NO_JMP) jmp_patch(fs, next, pc);  /* Jump to UCLO. */
1195
    setbc_op(ip, BC_UCLO);  /* Turn into UCLO. */
1196
    setbc_j(ip, NO_JMP);
1197
  }
1198
}
1199

1200
/* Resolve pending forward gotos for label. */
1201
static void gola_resolve(LexState *ls, FuncScope *bl, MSize idx)
1202
{
1203
  VarInfo *vg = ls->vstack + bl->vstart;
1204
  VarInfo *vl = ls->vstack + idx;
1205
  for (; vg < vl; vg++)
1206
    if (gcrefeq(vg->name, vl->name) && gola_isgoto(vg)) {
1207
      if (vg->slot < vl->slot) {
1208
        GCstr *name = strref(var_get(ls, ls->fs, vg->slot).name);
1209
        lua_assert((uintptr_t)name >= VARNAME__MAX);
1210
        ls->linenumber = ls->fs->bcbase[vg->startpc].line;
1211
        lua_assert(strref(vg->name) != NAME_BREAK);
1212
        lj_lex_error(ls, 0, LJ_ERR_XGSCOPE,
1213
                     strdata(strref(vg->name)), strdata(name));
1214
      }
1215
      gola_patch(ls, vg, vl);
1216
    }
1217
}
1218

1219
/* Fixup remaining gotos and labels for scope. */
1220
static void gola_fixup(LexState *ls, FuncScope *bl)
326✔
1221
{
1222
  VarInfo *v = ls->vstack + bl->vstart;
326✔
1223
  VarInfo *ve = ls->vstack + ls->vtop;
326✔
1224
  for (; v < ve; v++) {
1,018✔
1225
    GCstr *name = strref(v->name);
700✔
1226
    if (name != NULL) {  /* Only consider remaining valid gotos/labels. */
700✔
1227
      if (gola_islabel(v)) {
667✔
1228
        VarInfo *vg;
20✔
1229
        setgcrefnull(v->name);  /* Invalidate label that goes out of scope. */
20✔
1230
        for (vg = v+1; vg < ve; vg++)  /* Resolve pending backward gotos. */
44✔
1231
          if (strref(vg->name) == name && gola_isgoto(vg)) {
24✔
1232
            if ((bl->flags&FSCOPE_UPVAL) && vg->slot > v->slot)
4✔
1233
              gola_close(ls, vg);
1✔
1234
            gola_patch(ls, vg, v);
28✔
1235
          }
1236
      } else if (gola_isgoto(v)) {
647✔
1237
        if (bl->prev) {  /* Propagate goto or break to outer scope. */
315✔
1238
          bl->prev->flags |= name == NAME_BREAK ? FSCOPE_BREAK : FSCOPE_GOLA;
307✔
1239
          v->slot = bl->nactvar;
307✔
1240
          if ((bl->flags & FSCOPE_UPVAL))
307✔
1241
            gola_close(ls, v);
5✔
1242
        } else {  /* No outer scope: undefined goto label or no loop. */
1243
          ls->linenumber = ls->fs->bcbase[v->startpc].line;
8✔
1244
          if (name == NAME_BREAK)
8✔
1245
            lj_lex_error(ls, 0, LJ_ERR_XBREAK);
3✔
1246
          else
1247
            lj_lex_error(ls, 0, LJ_ERR_XLUNDEF, strdata(name));
5✔
1248
        }
1249
      }
1250
    }
1251
  }
1252
}
318✔
1253

1254
/* Find existing label. */
1255
static VarInfo *gola_findlabel(LexState *ls, GCstr *name)
57✔
1256
{
1257
  VarInfo *v = ls->vstack + ls->fs->bl->vstart;
57✔
1258
  VarInfo *ve = ls->vstack + ls->vtop;
57✔
1259
  for (; v < ve; v++)
132✔
1260
    if (strref(v->name) == name && gola_islabel(v))
81✔
1261
      return v;
1262
  return NULL;
1263
}
1264

1265
/* -- Scope handling ------------------------------------------------------ */
1266

1267
/* Begin a scope. */
1268
static void fscope_begin(FuncState *fs, FuncScope *bl, int flags)
31,535✔
1269
{
1270
  bl->nactvar = (uint8_t)fs->nactvar;
31,535✔
1271
  bl->flags = flags;
31,535✔
1272
  bl->vstart = fs->ls->vtop;
31,535✔
1273
  bl->prev = fs->bl;
31,535✔
1274
  fs->bl = bl;
31,535✔
1275
  lua_assert(fs->freereg == fs->nactvar);
31,535✔
1276
}
1277

1278
/* End a scope. */
1279
static void fscope_end(FuncState *fs)
31,289✔
1280
{
1281
  FuncScope *bl = fs->bl;
31,289✔
1282
  LexState *ls = fs->ls;
31,289✔
1283
  fs->bl = bl->prev;
31,289✔
1284
  var_remove(ls, bl->nactvar);
31,289✔
1285
  fs->freereg = fs->nactvar;
31,289✔
1286
  lua_assert(bl->nactvar == fs->nactvar);
31,289✔
1287
  if ((bl->flags & (FSCOPE_UPVAL|FSCOPE_NOCLOSE)) == FSCOPE_UPVAL)
31,289✔
1288
    bcemit_AJ(fs, BC_UCLO, bl->nactvar, 0);
93✔
1289
  if ((bl->flags & FSCOPE_BREAK)) {
31,289✔
1290
    if ((bl->flags & FSCOPE_LOOP)) {
428✔
1291
      MSize idx = gola_new(ls, NAME_BREAK, VSTACK_LABEL, fs->pc);
127✔
1292
      ls->vtop = idx;  /* Drop break label immediately. */
127✔
1293
      gola_resolve(ls, bl, idx);
127✔
1294
    } else {  /* Need the fixup step to propagate the breaks. */
1295
      gola_fixup(ls, bl);
301✔
1296
      return;
301✔
1297
    }
1298
  }
1299
  if ((bl->flags & FSCOPE_GOLA)) {
30,988✔
1300
    gola_fixup(ls, bl);
25✔
1301
  }
1302
}
1303

1304
/* Mark scope as having an upvalue. */
1305
static void fscope_uvmark(FuncState *fs, BCReg level)
9,351✔
1306
{
1307
  FuncScope *bl;
9,351✔
1308
  for (bl = fs->bl; bl && bl->nactvar > level; bl = bl->prev)
9,375✔
1309
    ;
24✔
1310
  if (bl)
9,351✔
1311
    bl->flags |= FSCOPE_UPVAL;
9,351✔
1312
}
1313

1314
/* -- Function state management ------------------------------------------- */
1315

1316
/* Fixup bytecode for prototype. */
1317
static void fs_fixup_bc(FuncState *fs, GCproto *pt, BCIns *bc, MSize n)
19,772✔
1318
{
1319
  BCInsLine *base = fs->bcbase;
19,772✔
1320
  MSize i;
19,772✔
1321
  pt->sizebc = n;
19,772✔
1322
  bc[0] = BCINS_AD((fs->flags & PROTO_VARARG) ? BC_FUNCV : BC_FUNCF,
39,544✔
1323
                   fs->framesize, 0);
1324
  for (i = 1; i < n; i++)
555,262✔
1325
    bc[i] = base[i].ins;
535,490✔
1326
}
1327

1328
/* Fixup upvalues for child prototype, step #2. */
1329
static void fs_fixup_uv2(FuncState *fs, GCproto *pt)
1330
{
1331
  VarInfo *vstack = fs->ls->vstack;
1332
  uint16_t *uv = proto_uv(pt);
1333
  MSize i, n = pt->sizeuv;
1334
  for (i = 0; i < n; i++) {
1335
    VarIndex vidx = uv[i];
1336
    if (vidx >= LJ_MAX_VSTACK)
1337
      uv[i] = vidx - LJ_MAX_VSTACK;
1338
    else if ((vstack[vidx].info & VSTACK_VAR_RW))
1339
      uv[i] = vstack[vidx].slot | PROTO_UV_LOCAL;
1340
    else
1341
      uv[i] = vstack[vidx].slot | PROTO_UV_LOCAL | PROTO_UV_IMMUTABLE;
1342
  }
1343
}
1344

1345
/* Fixup constants for prototype. */
1346
static void fs_fixup_k(FuncState *fs, GCproto *pt, void *kptr)
19,772✔
1347
{
1348
  GCtab *kt;
19,772✔
1349
  TValue *array;
19,772✔
1350
  Node *node;
19,772✔
1351
  MSize i, hmask;
19,772✔
1352
  checklimitgt(fs, fs->nkn, BCMAX_D+1, "constants");
19,772✔
1353
  checklimitgt(fs, fs->nkgc, BCMAX_D+1, "constants");
19,771✔
1354
  setmref(pt->k, kptr);
19,770✔
1355
  pt->sizekn = fs->nkn;
19,770✔
1356
  pt->sizekgc = fs->nkgc;
19,770✔
1357
  kt = fs->kt;
19,770✔
1358
  array = tvref(kt->array);
19,770✔
1359
  for (i = 0; i < kt->asize; i++)
22,271✔
1360
    if (tvhaskslot(&array[i])) {
2,501✔
1361
      TValue *tv = &((TValue *)kptr)[tvkslot(&array[i])];
938✔
1362
      if (LJ_DUALNUM)
938✔
1363
        setintV(tv, (int32_t)i);
1364
      else
1365
        setnumV(tv, (lua_Number)i);
938✔
1366
    }
1367
  node = noderef(kt->node);
19,770✔
1368
  hmask = kt->hmask;
19,770✔
1369
  for (i = 0; i <= hmask; i++) {
515,533✔
1370
    Node *n = &node[i];
495,763✔
1371
    if (tvhaskslot(&n->val)) {
495,763✔
1372
      ptrdiff_t kidx = (ptrdiff_t)tvkslot(&n->val);
178,119✔
1373
      lua_assert(!tvisint(&n->key));
178,119✔
1374
      if (tvisnum(&n->key)) {
178,119✔
1375
        TValue *tv = &((TValue *)kptr)[kidx];
67,130✔
1376
        if (LJ_DUALNUM) {
67,130✔
1377
          lua_Number nn = numV(&n->key);
1378
          int32_t k = lj_num2int(nn);
1379
          lua_assert(!tvismzero(&n->key));
1380
          if ((lua_Number)k == nn)
1381
            setintV(tv, k);
1382
          else
1383
            *tv = n->key;
1384
        } else {
1385
          *tv = n->key;
67,130✔
1386
        }
1387
      } else {
1388
        GCobj *o = gcV(&n->key);
110,989✔
1389
        setgcref(((GCRef *)kptr)[~kidx], o);
110,989✔
1390
        lj_gc_objbarrier(fs->L, pt, o);
110,989✔
1391
        if (tvisproto(&n->key))
110,989✔
1392
          fs_fixup_uv2(fs, gco2pt(o));
5,499✔
1393
      }
1394
    }
1395
  }
1396
}
19,770✔
1397

1398
/* Fixup upvalues for prototype, step #1. */
1399
static void fs_fixup_uv1(FuncState *fs, GCproto *pt, uint16_t *uv)
19,770✔
1400
{
1401
  setmref(pt->uv, uv);
19,770✔
1402
  pt->sizeuv = fs->nuv;
19,770✔
1403
  memcpy(uv, fs->uvtmp, fs->nuv*sizeof(VarIndex));
19,770✔
1404
}
1405

1406
#ifndef LUAJIT_DISABLE_DEBUGINFO
1407
/* Prepare lineinfo for prototype. */
1408
static size_t fs_prep_line(FuncState *fs, BCLine numline)
19,772✔
1409
{
1410
  return (fs->pc-1) << (numline < 256 ? 0 : numline < 65536 ? 1 : 2);
109✔
1411
}
1412

1413
/* Fixup lineinfo for prototype. */
1414
static void fs_fixup_line(FuncState *fs, GCproto *pt,
19,770✔
1415
                          void *lineinfo, BCLine numline)
1416
{
1417
  BCInsLine *base = fs->bcbase + 1;
19,770✔
1418
  BCLine first = fs->linedefined;
19,770✔
1419
  MSize i = 0, n = fs->pc-1;
19,770✔
1420
  pt->firstline = fs->linedefined;
19,770✔
1421
  pt->numline = numline;
19,770✔
1422
  setmref(pt->lineinfo, lineinfo);
19,770✔
1423
  if (LJ_LIKELY(numline < 256)) {
19,770✔
1424
    uint8_t *li = (uint8_t *)lineinfo;
253,395✔
1425
    do {
253,395✔
1426
      BCLine delta = base[i].line - first;
253,395✔
1427
      lua_assert(delta >= 0 && delta < 256);
253,395✔
1428
      li[i] = (uint8_t)delta;
253,395✔
1429
    } while (++i < n);
253,395✔
1430
  } else if (LJ_LIKELY(numline < 65536)) {
107✔
1431
    uint16_t *li = (uint16_t *)lineinfo;
19,941✔
1432
    do {
19,941✔
1433
      BCLine delta = base[i].line - first;
19,941✔
1434
      lua_assert(delta >= 0 && delta < 65536);
19,941✔
1435
      li[i] = (uint16_t)delta;
19,941✔
1436
    } while (++i < n);
19,941✔
1437
  } else {
1438
    uint32_t *li = (uint32_t *)lineinfo;
131,076✔
1439
    do {
131,076✔
1440
      BCLine delta = base[i].line - first;
131,076✔
1441
      lua_assert(delta >= 0);
131,076✔
1442
      li[i] = (uint32_t)delta;
131,076✔
1443
    } while (++i < n);
131,076✔
1444
  }
1445
}
19,770✔
1446

1447
/* Prepare variable info for prototype. */
1448
static size_t fs_prep_var(LexState *ls, FuncState *fs, size_t *ofsvar)
19,772✔
1449
{
1450
  VarInfo *vs =ls->vstack, *ve;
19,772✔
1451
  MSize i, n;
19,772✔
1452
  BCPos lastpc;
19,772✔
1453
  lj_buf_reset(&ls->sb);  /* Copy to temp. string buffer. */
19,772✔
1454
  /* Store upvalue names. */
1455
  for (i = 0, n = fs->nuv; i < n; i++) {
26,412✔
1456
    GCstr *s = strref(vs[fs->uvmap[i]].name);
6,640✔
1457
    MSize len = s->len+1;
6,640✔
1458
    char *p = lj_buf_more(&ls->sb, len);
6,640✔
1459
    p = lj_buf_wmem(p, strdata(s), len);
6,640✔
1460
    setsbufP(&ls->sb, p);
6,640✔
1461
  }
1462
  *ofsvar = sbuflen(&ls->sb);
19,772✔
1463
  lastpc = 0;
19,772✔
1464
  /* Store local variable names and compressed ranges. */
1465
  for (ve = vs + ls->vtop, vs += fs->vbase; vs < ve; vs++) {
48,983✔
1466
    if (!gola_isgotolabel(vs)) {
29,211✔
1467
      GCstr *s = strref(vs->name);
29,053✔
1468
      BCPos startpc;
29,053✔
1469
      char *p;
29,053✔
1470
      if ((uintptr_t)s < VARNAME__MAX) {
29,053✔
1471
        p = lj_buf_more(&ls->sb, 1 + 2*5);
5,478✔
1472
        *p++ = (char)(uintptr_t)s;
5,478✔
1473
      } else {
1474
        MSize len = s->len+1;
23,575✔
1475
        p = lj_buf_more(&ls->sb, len + 2*5);
23,575✔
1476
        p = lj_buf_wmem(p, strdata(s), len);
23,575✔
1477
      }
1478
      startpc = vs->startpc;
29,053✔
1479
      p = lj_strfmt_wuleb128(p, startpc-lastpc);
29,053✔
1480
      p = lj_strfmt_wuleb128(p, vs->endpc-startpc);
29,053✔
1481
      setsbufP(&ls->sb, p);
29,053✔
1482
      lastpc = startpc;
29,053✔
1483
    }
1484
  }
1485
  lj_buf_putb(&ls->sb, '\0');  /* Terminator for varinfo. */
19,772✔
1486
  return sbuflen(&ls->sb);
19,772✔
1487
}
1488

1489
/* Fixup variable info for prototype. */
1490
static void fs_fixup_var(LexState *ls, GCproto *pt, uint8_t *p, size_t ofsvar)
19,770✔
1491
{
1492
  setmref(pt->uvinfo, p);
19,770✔
1493
  setmref(pt->varinfo, (char *)p + ofsvar);
19,770✔
1494
  memcpy(p, sbufB(&ls->sb), sbuflen(&ls->sb));  /* Copy from temp. buffer. */
19,770✔
1495
}
1496
#else
1497

1498
/* Initialize with empty debug info, if disabled. */
1499
#define fs_prep_line(fs, numline)                (UNUSED(numline), 0)
1500
#define fs_fixup_line(fs, pt, li, numline) \
1501
  pt->firstline = pt->numline = 0, setmref((pt)->lineinfo, NULL)
1502
#define fs_prep_var(ls, fs, ofsvar)                (UNUSED(ofsvar), 0)
1503
#define fs_fixup_var(ls, pt, p, ofsvar) \
1504
  setmref((pt)->uvinfo, NULL), setmref((pt)->varinfo, NULL)
1505

1506
#endif
1507

1508
/* Check if bytecode op returns. */
1509
static int bcopisret(BCOp op)
18,926✔
1510
{
1511
  switch (op) {
18,926✔
1512
  case BC_CALLMT: case BC_CALLT:
1513
  case BC_RETM: case BC_RET: case BC_RET0: case BC_RET1:
1514
    return 1;
1515
  default:
1516
    return 0;
1517
  }
1518
}
1519

1520
/* Fixup return instruction for prototype. */
1521
static void fs_fixup_ret(FuncState *fs)
19,780✔
1522
{
1523
  BCPos lastpc = fs->pc;
19,780✔
1524
  if (lastpc <= fs->lasttarget || !bcopisret(bc_op(fs->bcbase[lastpc-1].ins))) {
19,780✔
1525
    if ((fs->bl->flags & FSCOPE_UPVAL))
3,293✔
1526
      bcemit_AJ(fs, BC_UCLO, 0, 0);
270✔
1527
    bcemit_AD(fs, BC_RET0, 0, 1);  /* Need final return. */
3,293✔
1528
  }
1529
  fs->bl->flags |= FSCOPE_NOCLOSE;  /* Handled above. */
19,780✔
1530
  fscope_end(fs);
19,780✔
1531
  lua_assert(fs->bl == NULL);
19,772✔
1532
  /* May need to fixup returns encoded before first function was created. */
1533
  if (fs->flags & PROTO_FIXUP_RETURN) {
19,772✔
1534
    BCPos pc;
1535
    for (pc = 1; pc < lastpc; pc++) {
861✔
1536
      BCIns ins = fs->bcbase[pc].ins;
861✔
1537
      BCPos offset;
861✔
1538
      switch (bc_op(ins)) {
861✔
1539
      case BC_CALLMT: case BC_CALLT:
1✔
1540
      case BC_RETM: case BC_RET: case BC_RET0: case BC_RET1:
1541
        offset = bcemit_INS(fs, ins);  /* Copy original instruction. */
1✔
1542
        fs->bcbase[offset].line = fs->bcbase[pc].line;
1✔
1543
        offset = offset-(pc+1)+BCBIAS_J;
1✔
1544
        if (offset > BCMAX_D)
1✔
1545
          err_syntax(fs->ls, LJ_ERR_XFIXUP);
×
1546
        /* Replace with UCLO plus branch. */
1547
        fs->bcbase[pc].ins = BCINS_AD(BC_UCLO, 0, offset);
1✔
1548
        break;
1✔
1549
      case BC_FNEW:
1550
        return;  /* We're done. */
1551
      default:
1552
        break;
1553
      }
1554
    }
1555
  }
1556
}
1557

1558
/* Finish a FuncState and return the new prototype. */
1559
static GCproto *fs_finish(LexState *ls, BCLine line)
19,780✔
1560
{
1561
  lua_State *L = ls->L;
19,780✔
1562
  FuncState *fs = ls->fs;
19,780✔
1563
  BCLine numline = line - fs->linedefined;
19,780✔
1564
  size_t sizept, ofsk, ofsuv, ofsli, ofsdbg, ofsvar;
19,780✔
1565
  GCproto *pt;
19,780✔
1566

1567
  /* Apply final fixups. */
1568
  fs_fixup_ret(fs);
19,780✔
1569

1570
  /* Calculate total size of prototype including all colocated arrays. */
1571
  sizept = sizeof(GCproto) + fs->pc*sizeof(BCIns) + fs->nkgc*sizeof(GCRef);
19,772✔
1572
  sizept = (sizept + sizeof(TValue)-1) & ~(sizeof(TValue)-1);
19,772✔
1573
  ofsk = sizept; sizept += fs->nkn*sizeof(TValue);
19,772✔
1574
  ofsuv = sizept; sizept += ((fs->nuv+1)&~1)*2;
19,772✔
1575
  ofsli = sizept; sizept += fs_prep_line(fs, numline);
19,772✔
1576
  ofsdbg = sizept; sizept += fs_prep_var(ls, fs, &ofsvar);
19,772✔
1577

1578
  /* Allocate prototype and initialize its fields. */
1579
  pt = (GCproto *)lj_mem_newgco(L, (MSize)sizept);
19,772✔
1580
  pt->gct = ~LJ_TPROTO;
19,772✔
1581
  pt->sizept = (MSize)sizept;
19,772✔
1582
  pt->trace = 0;
19,772✔
1583
  pt->flags = (uint8_t)(fs->flags & ~(PROTO_HAS_RETURN|PROTO_FIXUP_RETURN));
19,772✔
1584
  pt->numparams = fs->numparams;
19,772✔
1585
  pt->framesize = fs->framesize;
19,772✔
1586
  setgcref(pt->chunkname, obj2gco(ls->chunkname));
19,772✔
1587

1588
  /* Close potentially uninitialized gap between bc and kgc. */
1589
  *(uint32_t *)((char *)pt + ofsk - sizeof(GCRef)*(fs->nkgc+1)) = 0;
19,772✔
1590
  fs_fixup_bc(fs, pt, (BCIns *)((char *)pt + sizeof(GCproto)), fs->pc);
19,772✔
1591
  fs_fixup_k(fs, pt, (void *)((char *)pt + ofsk));
19,772✔
1592
  fs_fixup_uv1(fs, pt, (uint16_t *)((char *)pt + ofsuv));
19,770✔
1593
  fs_fixup_line(fs, pt, (void *)((char *)pt + ofsli), numline);
19,770✔
1594
  fs_fixup_var(ls, pt, (uint8_t *)((char *)pt + ofsdbg), ofsvar);
19,770✔
1595

1596
  lj_vmevent_send(L, BC,
19,770✔
1597
    setprotoV(L, L->top++, pt);
1598
  );
19,770✔
1599

1600
  /* Add a new prototype to the profiler. */
1601
#if LJ_HASMEMPROF
1602
  lj_memprof_add_proto(pt);
19,770✔
1603
#endif
1604
#if LJ_HASSYSPROF
1605
  lj_sysprof_add_proto(pt);
19,770✔
1606
#endif
1607

1608
  L->top--;  /* Pop table of constants. */
19,770✔
1609
  ls->vtop = fs->vbase;  /* Reset variable stack. */
19,770✔
1610
  ls->fs = fs->prev;
19,770✔
1611
  lua_assert(ls->fs != NULL || ls->tok == TK_eof);
19,770✔
1612
  return pt;
19,770✔
1613
}
1614

1615
/* Initialize a new FuncState. */
1616
static void fs_init(LexState *ls, FuncState *fs)
20,027✔
1617
{
1618
  lua_State *L = ls->L;
20,027✔
1619
  fs->prev = ls->fs; ls->fs = fs;  /* Append to list. */
20,027✔
1620
  fs->ls = ls;
20,027✔
1621
  fs->vbase = ls->vtop;
20,027✔
1622
  fs->L = L;
20,027✔
1623
  fs->pc = 0;
20,027✔
1624
  fs->lasttarget = 0;
20,027✔
1625
  fs->jpc = NO_JMP;
20,027✔
1626
  fs->freereg = 0;
20,027✔
1627
  fs->nkgc = 0;
20,027✔
1628
  fs->nkn = 0;
20,027✔
1629
  fs->nactvar = 0;
20,027✔
1630
  fs->nuv = 0;
20,027✔
1631
  fs->bl = NULL;
20,027✔
1632
  fs->flags = 0;
20,027✔
1633
  fs->framesize = 1;  /* Minimum frame size. */
20,027✔
1634
  fs->kt = lj_tab_new(L, 0, 0);
20,027✔
1635
  /* Anchor table of constants in stack to avoid being collected. */
1636
  settabV(L, L->top, fs->kt);
20,027✔
1637
  incr_top(L);
20,027✔
1638
}
20,027✔
1639

1640
/* -- Expressions --------------------------------------------------------- */
1641

1642
/* Forward declaration. */
1643
static void expr(LexState *ls, ExpDesc *v);
1644

1645
/* Return string expression. */
1646
static void expr_str(LexState *ls, ExpDesc *e)
36,888✔
1647
{
1648
  expr_init(e, VKSTR, 0);
36,888✔
1649
  e->u.sval = lex_str(ls);
73,776✔
1650
}
1651

1652
/* Return index expression. */
1653
static void expr_index(FuncState *fs, ExpDesc *t, ExpDesc *e)
1654
{
1655
  /* Already called: expr_toval(fs, e). */
1656
  t->k = VINDEXED;
1657
  if (expr_isnumk(e)) {
1658
#if LJ_DUALNUM
1659
    if (tvisint(expr_numtv(e))) {
1660
      int32_t k = intV(expr_numtv(e));
1661
      if (checku8(k)) {
1662
        t->u.s.aux = BCMAX_C+1+(uint32_t)k;  /* 256..511: const byte key */
1663
        return;
1664
      }
1665
    }
1666
#else
1667
    lua_Number n = expr_numberV(e);
1668
    int32_t k = lj_num2int(n);
1669
    if (checku8(k) && n == (lua_Number)k) {
1670
      t->u.s.aux = BCMAX_C+1+(uint32_t)k;  /* 256..511: const byte key */
1671
      return;
1672
    }
1673
#endif
1674
  } else if (expr_isstrk(e)) {
1675
    BCReg idx = const_str(fs, e);
1676
    if (idx <= BCMAX_C) {
1677
      t->u.s.aux = ~idx;  /* -256..-1: const string key */
1678
      return;
1679
    }
1680
  }
1681
  t->u.s.aux = expr_toanyreg(fs, e);  /* 0..255: register */
1682
}
1683

1684
/* Parse index expression with named field. */
1685
static void expr_field(LexState *ls, ExpDesc *v)
28,813✔
1686
{
1687
  FuncState *fs = ls->fs;
28,813✔
1688
  ExpDesc key;
28,813✔
1689
  expr_toanyreg(fs, v);
28,813✔
1690
  lj_lex_next(ls);  /* Skip dot or colon. */
28,813✔
1691
  expr_str(ls, &key);
28,813✔
1692
  expr_index(fs, v, &key);
28,813✔
1693
}
28,813✔
1694

1695
/* Parse index expression with brackets. */
1696
static void expr_bracket(LexState *ls, ExpDesc *v)
3,245✔
1697
{
1698
  lj_lex_next(ls);  /* Skip '['. */
3,245✔
1699
  expr(ls, v);
6,490✔
1700
  expr_toval(ls->fs, v);
3,245✔
1701
  lex_check(ls, ']');
3,245✔
1702
}
3,245✔
1703

1704
/* Get value of constant expression. */
1705
static void expr_kvalue(TValue *v, ExpDesc *e)
14,300✔
1706
{
1707
  if (e->k <= VKTRUE) {
14,300✔
1708
    setpriV(v, ~(uint32_t)e->k);
643✔
1709
  } else if (e->k == VKSTR) {
13,657✔
1710
    setgcVraw(v, obj2gco(e->u.sval), LJ_TSTR);
10,057✔
1711
  } else {
1712
    lua_assert(tvisnumber(expr_numtv(e)));
5,491✔
1713
    *v = *expr_numtv(e);
5,491✔
1714
  }
1715
}
1716

1717
/* Parse table constructor expression. */
1718
static void expr_table(LexState *ls, ExpDesc *e)
3,324✔
1719
{
1720
  FuncState *fs = ls->fs;
3,324✔
1721
  BCLine line = ls->linenumber;
3,324✔
1722
  GCtab *t = NULL;
3,324✔
1723
  int vcall = 0, needarr = 0, fixt = 0;
3,324✔
1724
  uint32_t narr = 1;  /* First array index. */
3,324✔
1725
  uint32_t nhash = 0;  /* Number of hash entries. */
3,324✔
1726
  BCReg freg = fs->freereg;
3,324✔
1727
  BCPos pc = bcemit_AD(fs, BC_TNEW, freg, 0);
3,324✔
1728
  expr_init(e, VNONRELOC, freg);
3,324✔
1729
  bcreg_reserve(fs, 1);
3,324✔
1730
  freg++;
3,324✔
1731
  lex_check(ls, '{');
3,324✔
1732
  while (ls->tok != '}') {
12,125✔
1733
    ExpDesc key, val;
9,903✔
1734
    vcall = 0;
9,903✔
1735
    if (ls->tok == '[') {
9,903✔
1736
      expr_bracket(ls, &key);  /* Already calls expr_toval. */
171✔
1737
      if (!expr_isk(&key)) expr_index(fs, e, &key);
171✔
1738
      if (expr_isnumk(&key) && expr_numiszero(&key)) needarr = 1; else nhash++;
171✔
1739
      lex_check(ls, '=');
171✔
1740
    } else if ((ls->tok == TK_name || (!LJ_52 && ls->tok == TK_goto)) &&
14,680✔
1741
               lj_lex_lookahead(ls) == '=') {
4,948✔
1742
      expr_str(ls, &key);
4,543✔
1743
      lex_check(ls, '=');
4,543✔
1744
      nhash++;
4,543✔
1745
    } else {
1746
      expr_init(&key, VKNUM, 0);
5,189✔
1747
      setintV(&key.u.nval, (int)narr);
5,189✔
1748
      narr++;
5,189✔
1749
      needarr = vcall = 1;
5,189✔
1750
    }
1751
    expr(ls, &val);
19,806✔
1752
    if (expr_isk(&key) && key.k != VKNIL &&
9,903✔
1753
        (key.k == VKSTR || expr_isk_nojump(&val))) {
5,250✔
1754
      TValue k, *v;
8,880✔
1755
      if (!t) {  /* Create template table on demand. */
8,880✔
1756
        BCReg kidx;
1,499✔
1757
        t = lj_tab_new(fs->L, needarr ? narr : 0, hsize2hbits(nhash));
2,013✔
1758
        kidx = const_gc(fs, obj2gco(t), LJ_TTAB);
1,499✔
1759
        fs->bcbase[pc].ins = BCINS_AD(BC_TDUP, freg-1, kidx);
1,499✔
1760
      }
1761
      vcall = 0;
8,880✔
1762
      expr_kvalue(&k, &key);
8,880✔
1763
      v = lj_tab_set(fs->L, t, &k);
8,880✔
1764
      lj_gc_anybarriert(fs->L, t);
8,880✔
1765
      if (expr_isk_nojump(&val)) {  /* Add const key/value to template table. */
8,880✔
1766
        expr_kvalue(v, &val);
5,420✔
1767
      } else {  /* Otherwise create dummy string key (avoids lj_tab_newkey). */
1768
        settabV(fs->L, v, t);  /* Preserve key with table itself as value. */
3,460✔
1769
        fixt = 1;   /* Fix this later, after all resizes. */
3,460✔
1770
        goto nonconst;
3,460✔
1771
      }
1772
    } else {
1773
    nonconst:
1,023✔
1774
      if (val.k != VCALL) { expr_toanyreg(fs, &val); vcall = 0; }
4,483✔
1775
      if (expr_isk(&key)) expr_index(fs, e, &key);
4,483✔
1776
      bcemit_store(fs, e, &val);
4,483✔
1777
    }
1778
    fs->freereg = freg;
9,903✔
1779
    if (!lex_opt(ls, ',') && !lex_opt(ls, ';')) break;
9,903✔
1780
  }
1781
  lex_match(ls, '}', '{', line);
3,324✔
1782
  if (vcall) {
3,323✔
1783
    BCInsLine *ilp = &fs->bcbase[fs->pc-1];
255✔
1784
    ExpDesc en;
255✔
1785
    lua_assert(bc_a(ilp->ins) == freg &&
255✔
1786
               bc_op(ilp->ins) == (narr > 256 ? BC_TSETV : BC_TSETB));
1787
    expr_init(&en, VKNUM, 0);
255✔
1788
    en.u.nval.u32.lo = narr-1;
255✔
1789
    en.u.nval.u32.hi = 0x43300000;  /* Biased integer to avoid denormals. */
255✔
1790
    if (narr > 256) { fs->pc--; ilp--; }
255✔
1791
    ilp->ins = BCINS_AD(BC_TSETM, freg, const_num(fs, &en));
255✔
1792
    setbc_b(&ilp[-1].ins, 0);
255✔
1793
  }
1794
  if (pc == fs->pc-1) {  /* Make expr relocable if possible. */
3,323✔
1795
    e->u.s.info = pc;
2,085✔
1796
    fs->freereg--;
2,085✔
1797
    e->k = VRELOCABLE;
2,085✔
1798
  } else {
1799
    e->k = VNONRELOC;  /* May have been changed by expr_index. */
1,238✔
1800
  }
1801
  if (!t) {  /* Construct TNEW RD: hhhhhaaaaaaaaaaa. */
3,323✔
1802
    BCIns *ip = &fs->bcbase[pc].ins;
1,825✔
1803
    if (!needarr) narr = 0;
1,825✔
1804
    else if (narr < 3) narr = 3;
336✔
1805
    else if (narr > 0x7ff) narr = 0x7ff;
1806
    setbc_d(ip, narr|(hsize2hbits(nhash)<<11));
1,825✔
1807
  } else {
1808
    if (needarr && t->asize < narr)
1,498✔
1809
      lj_tab_reasize(fs->L, t, narr-1);
21✔
1810
    if (fixt) {  /* Fix value for dummy keys in template table. */
1,498✔
1811
      Node *node = noderef(t->node);
782✔
1812
      uint32_t i, hmask = t->hmask;
782✔
1813
      for (i = 0; i <= hmask; i++) {
5,612✔
1814
        Node *n = &node[i];
4,830✔
1815
        if (tvistab(&n->val)) {
4,830✔
1816
          lua_assert(tabV(&n->val) == t);
3,460✔
1817
          setnilV(&n->val);  /* Turn value into nil. */
3,460✔
1818
        }
1819
      }
1820
    }
1821
    lj_gc_check(fs->L);
1,498✔
1822
  }
1823
}
3,323✔
1824

1825
/* Parse function parameters. */
1826
static BCReg parse_params(LexState *ls, int needself)
5,588✔
1827
{
1828
  FuncState *fs = ls->fs;
5,588✔
1829
  BCReg nparams = 0;
5,588✔
1830
  lex_check(ls, '(');
5,588✔
1831
  if (needself)
5,586✔
1832
    var_new_lit(ls, nparams++, "self");
22✔
1833
  if (ls->tok != ')') {
5,586✔
1834
    do {
10,734✔
1835
      if (ls->tok == TK_name || (!LJ_52 && ls->tok == TK_goto)) {
10,734✔
1836
        var_new(ls, nparams++, lex_str(ls));
10,455✔
1837
      } else if (ls->tok == TK_dots) {
279✔
1838
        lj_lex_next(ls);
276✔
1839
        fs->flags |= PROTO_VARARG;
276✔
1840
        break;
276✔
1841
      } else {
1842
        err_syntax(ls, LJ_ERR_XPARAM);
3✔
1843
      }
1844
    } while (lex_opt(ls, ','));
10,455✔
1845
  }
1846
  var_add(ls, nparams);
5,583✔
1847
  lua_assert(fs->nactvar == nparams);
5,583✔
1848
  bcreg_reserve(fs, nparams);
5,583✔
1849
  lex_check(ls, ')');
5,583✔
1850
  return nparams;
5,581✔
1851
}
1852

1853
/* Forward declaration. */
1854
static void parse_chunk(LexState *ls);
1855

1856
/* Parse body of a function. */
1857
static void parse_body(LexState *ls, ExpDesc *e, int needself, BCLine line)
5,588✔
1858
{
1859
  FuncState fs, *pfs = ls->fs;
5,588✔
1860
  FuncScope bl;
5,588✔
1861
  GCproto *pt;
5,588✔
1862
  ptrdiff_t oldbase = pfs->bcbase - ls->bcstack;
5,588✔
1863
  fs_init(ls, &fs);
5,588✔
1864
  fscope_begin(&fs, &bl, 0);
5,588✔
1865
  fs.linedefined = line;
5,588✔
1866
  fs.numparams = (uint8_t)parse_params(ls, needself);
5,588✔
1867
  fs.bcbase = pfs->bcbase + pfs->pc;
5,581✔
1868
  fs.bclim = pfs->bclim - pfs->pc;
5,581✔
1869
  bcemit_AD(&fs, BC_FUNCF, 0, 0);  /* Placeholder. */
5,581✔
1870
  parse_chunk(ls);
5,581✔
1871
  if (ls->tok != TK_end) lex_match(ls, TK_end, TK_function, line);
5,539✔
1872
  pt = fs_finish(ls, (ls->lastline = ls->linenumber));
5,500✔
1873
  pfs->bcbase = ls->bcstack + oldbase;  /* May have been reallocated. */
5,499✔
1874
  pfs->bclim = (BCPos)(ls->sizebcstack - oldbase);
5,499✔
1875
  /* Store new prototype in the constant array of the parent. */
1876
  expr_init(e, VRELOCABLE,
16,497✔
1877
            bcemit_AD(pfs, BC_FNEW, 0, const_gc(pfs, obj2gco(pt), LJ_TPROTO)));
5,499✔
1878
#if LJ_HASFFI
1879
  pfs->flags |= (fs.flags & PROTO_FFI);
5,499✔
1880
#endif
1881
  if (!(pfs->flags & PROTO_CHILD)) {
5,499✔
1882
    if (pfs->flags & PROTO_HAS_RETURN)
1,034✔
1883
      pfs->flags |= PROTO_FIXUP_RETURN;
342✔
1884
    pfs->flags |= PROTO_CHILD;
1,034✔
1885
  }
1886
  lj_lex_next(ls);
5,499✔
1887
}
5,499✔
1888

1889
/* Parse expression list. Last expression is left open. */
1890
static BCReg expr_list(LexState *ls, ExpDesc *v)
327,226✔
1891
{
1892
  BCReg n = 1;
327,226✔
1893
  expr(ls, v);
671,911✔
1894
  while (lex_opt(ls, ',')) {
344,685✔
1895
    expr_tonextreg(ls->fs, v);
17,492✔
1896
    expr(ls, v);
34,982✔
1897
    n++;
17,490✔
1898
  }
1899
  return n;
327,193✔
1900
}
1901

1902
/* Parse function argument list. */
1903
static void parse_args(LexState *ls, ExpDesc *e)
26,877✔
1904
{
1905
  FuncState *fs = ls->fs;
26,877✔
1906
  ExpDesc args;
26,877✔
1907
  BCIns ins;
26,877✔
1908
  BCReg base;
26,877✔
1909
  BCLine line = ls->linenumber;
26,877✔
1910
  if (ls->tok == '(') {
26,877✔
1911
#if !LJ_52
1912
    if (line != ls->lastline)
26,087✔
1913
      err_syntax(ls, LJ_ERR_XAMBIG);
×
1914
#endif
1915
    lj_lex_next(ls);
26,087✔
1916
    if (ls->tok == ')') {  /* f(). */
26,087✔
1917
      args.k = VVOID;
1,222✔
1918
    } else {
1919
      expr_list(ls, &args);
24,865✔
1920
      if (args.k == VCALL)  /* f(a, b, g()) or f(a, b, ...). */
24,856✔
1921
        setbc_b(bcptr(fs, &args), 0);  /* Pass on multiple results. */
1,757✔
1922
    }
1923
    lex_match(ls, ')', '(', line);
26,078✔
1924
  } else if (ls->tok == '{') {
790✔
1925
    expr_table(ls, &args);
41✔
1926
  } else if (ls->tok == TK_string) {
749✔
1927
    expr_init(&args, VKSTR, 0);
748✔
1928
    args.u.sval = strV(&ls->tokval);
748✔
1929
    lj_lex_next(ls);
748✔
1930
  } else {
1931
    err_syntax(ls, LJ_ERR_XFUNARG);
1✔
1932
    return;  /* Silence compiler. */
1933
  }
1934
  lua_assert(e->k == VNONRELOC);
26,858✔
1935
  base = e->u.s.info;  /* Base register for call. */
26,858✔
1936
  if (args.k == VCALL) {
26,858✔
1937
    ins = BCINS_ABC(BC_CALLM, base, 2, args.u.s.aux - base - 1 - LJ_FR2);
1,757✔
1938
  } else {
1939
    if (args.k != VVOID)
25,101✔
1940
      expr_tonextreg(fs, &args);
23,879✔
1941
    ins = BCINS_ABC(BC_CALL, base, 2, fs->freereg - base - LJ_FR2);
25,101✔
1942
  }
1943
  expr_init(e, VCALL, bcemit_INS(fs, ins));
26,858✔
1944
  e->u.s.aux = base;
26,858✔
1945
  fs->bcbase[fs->pc - 1].line = line;
26,858✔
1946
  fs->freereg = base+1;  /* Leave one result by default. */
26,858✔
1947
}
1948

1949
/* Parse primary expression. */
1950
static void expr_primary(LexState *ls, ExpDesc *v)
397,710✔
1951
{
1952
  FuncState *fs = ls->fs;
397,710✔
1953
  /* Parse prefix expression. */
1954
  if (ls->tok == '(') {
397,710✔
1955
    BCLine line = ls->linenumber;
37,877✔
1956
    lj_lex_next(ls);
37,877✔
1957
    expr(ls, v);
75,748✔
1958
    lex_match(ls, ')', '(', line);
37,871✔
1959
    expr_discharge(ls->fs, v);
37,868✔
1960
  } else if (ls->tok == TK_name || (!LJ_52 && ls->tok == TK_goto)) {
359,833✔
1961
    var_lookup(ls, v);
359,803✔
1962
  } else {
1963
    err_syntax(ls, LJ_ERR_XSYMBOL);
30✔
1964
  }
1965
  for (;;) {  /* Parse multiple expression suffixes. */
456,304✔
1966
    if (ls->tok == '.') {
456,304✔
1967
      expr_field(ls, v);
28,701✔
1968
    } else if (ls->tok == '[') {
427,603✔
1969
      ExpDesc key;
3,074✔
1970
      expr_toanyreg(fs, v);
3,074✔
1971
      expr_bracket(ls, &key);
3,074✔
1972
      expr_index(fs, v, &key);
3,074✔
1973
    } else if (ls->tok == ':') {
424,529✔
1974
      ExpDesc key;
3,532✔
1975
      lj_lex_next(ls);
3,532✔
1976
      expr_str(ls, &key);
3,532✔
1977
      bcemit_method(fs, v, &key);
3,532✔
1978
      parse_args(ls, v);
3,532✔
1979
    } else if (ls->tok == '(' || ls->tok == TK_string || ls->tok == '{') {
420,997✔
1980
      expr_tonextreg(fs, v);
23,345✔
1981
      if (LJ_FR2) bcreg_reserve(fs, 1);
23,345✔
1982
      parse_args(ls, v);
23,345✔
1983
    } else {
1984
      break;
1985
    }
1986
  }
1987
}
397,652✔
1988

1989
/* Parse simple expression. */
1990
static void expr_simple(LexState *ls, ExpDesc *v)
462,504✔
1991
{
1992
  switch (ls->tok) {
462,504✔
1993
  case TK_number:
157,348✔
1994
    expr_init(v, (LJ_HASFFI && tviscdata(&ls->tokval)) ? VKCDATA : VKNUM, 0);
157,348✔
1995
    copyTV(ls->L, &v->u.nval, &ls->tokval);
157,348✔
1996
    break;
1997
  case TK_string:
1998
    expr_init(v, VKSTR, 0);
149,057✔
1999
    v->u.sval = strV(&ls->tokval);
149,057✔
2000
    break;
149,057✔
2001
  case TK_nil:
2002
    expr_init(v, VKNIL, 0);
13,568✔
2003
    break;
2004
  case TK_true:
2005
    expr_init(v, VKTRUE, 0);
14,402✔
2006
    break;
2007
  case TK_false:
2008
    expr_init(v, VKFALSE, 0);
13,947✔
2009
    break;
2010
  case TK_dots: {  /* Vararg. */
301✔
2011
    FuncState *fs = ls->fs;
301✔
2012
    BCReg base;
301✔
2013
    checkcond(ls, fs->flags & PROTO_VARARG, LJ_ERR_XDOTS);
301✔
2014
    bcreg_reserve(fs, 1);
300✔
2015
    base = fs->freereg-1;
300✔
2016
    expr_init(v, VCALL, bcemit_ABC(fs, BC_VARG, base, 2, fs->numparams));
300✔
2017
    v->u.s.aux = base;
300✔
2018
    break;
300✔
2019
  }
2020
  case '{':  /* Table constructor. */
3,283✔
2021
    expr_table(ls, v);
3,283✔
2022
    return;
3,283✔
2023
  case TK_function:
1,500✔
2024
    lj_lex_next(ls);
1,500✔
2025
    parse_body(ls, v, 0, ls->linenumber);
1,500✔
2026
    return;
1,500✔
2027
  default:
109,098✔
2028
    expr_primary(ls, v);
109,098✔
2029
    return;
109,098✔
2030
  }
2031
  lj_lex_next(ls);
348,622✔
2032
}
2033

2034
/* Manage syntactic levels to avoid blowing up the stack. */
2035
static void synlevel_begin(LexState *ls)
492,609✔
2036
{
2037
  if (++ls->level >= LJ_MAX_XLEVEL)
492,609✔
2038
    lj_lex_error(ls, 0, LJ_ERR_XLEVELS);
×
2039
}
2040

2041
#define synlevel_end(ls)        ((ls)->level--)
2042

2043
/* Convert token to binary operator. */
2044
static BinOpr token2binop(LexToken tok)
464,863✔
2045
{
2046
  switch (tok) {
464,863✔
2047
  case '+':        return OPR_ADD;
2048
  case '-':        return OPR_SUB;
689✔
2049
  case '*':        return OPR_MUL;
3,690✔
2050
  case '/':        return OPR_DIV;
96✔
2051
  case '%':        return OPR_MOD;
70✔
2052
  case '^':        return OPR_POW;
96✔
2053
  case TK_concat: return OPR_CONCAT;
3,360✔
2054
  case TK_ne:        return OPR_NE;
1,686✔
2055
  case TK_eq:        return OPR_EQ;
4,273✔
2056
  case '<':        return OPR_LT;
177✔
2057
  case TK_le:        return OPR_LE;
188✔
2058
  case '>':        return OPR_GT;
278✔
2059
  case TK_ge:        return OPR_GE;
296✔
2060
  case TK_and:        return OPR_AND;
19,636✔
2061
  case TK_or:        return OPR_OR;
20,480✔
2062
  default:        return OPR_NOBINOPR;
404,671✔
2063
  }
2064
}
2065

2066
/* Priorities for each binary operator. ORDER OPR. */
2067
static const struct {
2068
  uint8_t left;                /* Left priority. */
2069
  uint8_t right;        /* Right priority. */
2070
} priority[] = {
2071
  {6,6}, {6,6}, {7,7}, {7,7}, {7,7},        /* ADD SUB MUL DIV MOD */
2072
  {10,9}, {5,4},                        /* POW CONCAT (right associative) */
2073
  {3,3}, {3,3},                                /* EQ NE */
2074
  {3,3}, {3,3}, {3,3}, {3,3},                /* LT GE GT LE */
2075
  {2,2}, {1,1}                                /* AND OR */
2076
};
2077

2078
#define UNARY_PRIORITY                8  /* Priority for unary operators. */
2079

2080
/* Forward declaration. */
2081
static BinOpr expr_binop(LexState *ls, ExpDesc *v, uint32_t limit);
2082

2083
/* Parse unary expression. */
2084
static void expr_unop(LexState *ls, ExpDesc *v)
464,906✔
2085
{
2086
  BCOp op;
464,906✔
2087
  if (ls->tok == TK_not) {
464,906✔
2088
    op = BC_NOT;
2089
  } else if (ls->tok == '-') {
463,925✔
2090
    op = BC_UNM;
2091
  } else if (ls->tok == '#') {
463,531✔
2092
    op = BC_LEN;
2093
  } else {
2094
    expr_simple(ls, v);
462,504✔
2095
    return;
462,504✔
2096
  }
2097
  lj_lex_next(ls);
2,402✔
2098
  expr_binop(ls, v, UNARY_PRIORITY);
2,402✔
2099
  bcemit_unop(ls->fs, op, v);
2,402✔
2100
}
2101

2102
/* Parse binary expressions with priority higher than the limit. */
2103
static BinOpr expr_binop(LexState *ls, ExpDesc *v, uint32_t limit)
464,906✔
2104
{
2105
  BinOpr op;
464,906✔
2106
  synlevel_begin(ls);
464,906✔
2107
  expr_unop(ls, v);
464,906✔
2108
  op = token2binop(ls->tok);
464,863✔
2109
  while (op != OPR_NOBINOPR && priority[op].left > limit) {
524,511✔
2110
    ExpDesc v2;
59,654✔
2111
    BinOpr nextop;
59,654✔
2112
    lj_lex_next(ls);
59,654✔
2113
    bcemit_binop_left(ls->fs, op, v);
59,654✔
2114
    /* Parse binary expression with higher priority. */
2115
    nextop = expr_binop(ls, &v2, priority[op].right);
59,654✔
2116
    bcemit_binop(ls->fs, op, v, &v2);
59,648✔
2117
    op = nextop;
59,648✔
2118
  }
2119
  synlevel_end(ls);
464,857✔
2120
  return op;  /* Return unconsumed binary operator (if any). */
464,857✔
2121
}
2122

2123
/* Parse expression. */
2124
static void expr(LexState *ls, ExpDesc *v)
402,850✔
2125
{
2126
  expr_binop(ls, v, 0);  /* Priority 0: parse whole expression. */
395,743✔
2127
}
327,195✔
2128

2129
/* Assign expression to the next register. */
2130
static void expr_next(LexState *ls)
2,638✔
2131
{
2132
  ExpDesc e;
2,638✔
2133
  expr(ls, &e);
2,638✔
2134
  expr_tonextreg(ls->fs, &e);
2,638✔
2135
}
2,638✔
2136

2137
/* Parse conditional expression. */
2138
static BCPos expr_cond(LexState *ls)
4,469✔
2139
{
2140
  ExpDesc v;
4,469✔
2141
  expr(ls, &v);
4,469✔
2142
  if (v.k == VKNIL) v.k = VKFALSE;
4,465✔
2143
  bcemit_branch_t(ls->fs, &v);
4,465✔
2144
  return v.f;
4,465✔
2145
}
2146

2147
/* -- Assignments --------------------------------------------------------- */
2148

2149
/* List of LHS variables. */
2150
typedef struct LHSVarList {
2151
  ExpDesc v;                        /* LHS variable. */
2152
  struct LHSVarList *prev;        /* Link to previous LHS variable. */
2153
} LHSVarList;
2154

2155
/* Eliminate write-after-read hazards for local variable assignment. */
2156
static void assign_hazard(LexState *ls, LHSVarList *lh, const ExpDesc *v)
2157
{
2158
  FuncState *fs = ls->fs;
2159
  BCReg reg = v->u.s.info;  /* Check against this variable. */
2160
  BCReg tmp = fs->freereg;  /* Rename to this temp. register (if needed). */
2161
  int hazard = 0;
2162
  for (; lh; lh = lh->prev) {
2163
    if (lh->v.k == VINDEXED) {
2164
      if (lh->v.u.s.info == reg) {  /* t[i], t = 1, 2 */
2165
        hazard = 1;
2166
        lh->v.u.s.info = tmp;
2167
      }
2168
      if (lh->v.u.s.aux == reg) {  /* t[i], i = 1, 2 */
2169
        hazard = 1;
2170
        lh->v.u.s.aux = tmp;
2171
      }
2172
    }
2173
  }
2174
  if (hazard) {
2175
    bcemit_AD(fs, BC_MOV, tmp, reg);  /* Rename conflicting variable. */
2176
    bcreg_reserve(fs, 1);
2177
  }
2178
}
2179

2180
/* Adjust LHS/RHS of an assignment. */
2181
static void assign_adjust(LexState *ls, BCReg nvars, BCReg nexps, ExpDesc *e)
2182
{
2183
  FuncState *fs = ls->fs;
2184
  int32_t extra = (int32_t)nvars - (int32_t)nexps;
2185
  if (e->k == VCALL) {
2186
    extra++;  /* Compensate for the VCALL itself. */
2187
    if (extra < 0) extra = 0;
2188
    setbc_b(bcptr(fs, e), extra+1);  /* Fixup call results. */
2189
    if (extra > 1) bcreg_reserve(fs, (BCReg)extra-1);
2190
  } else {
2191
    if (e->k != VVOID)
2192
      expr_tonextreg(fs, e);  /* Close last expression. */
2193
    if (extra > 0) {  /* Leftover LHS are set to nil. */
2194
      BCReg reg = fs->freereg;
2195
      bcreg_reserve(fs, (BCReg)extra);
2196
      bcemit_nil(fs, reg, (BCReg)extra);
2197
    }
2198
  }
2199
  if (nexps > nvars)
2200
    ls->fs->freereg -= nexps - nvars;  /* Drop leftover regs. */
2201
}
2202

2203
/* Recursively parse assignment statement. */
2204
static void parse_assignment(LexState *ls, LHSVarList *lh, BCReg nvars)
277,608✔
2205
{
2206
  ExpDesc e;
277,608✔
2207
  checkcond(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED, LJ_ERR_XSYNTAX);
277,608✔
2208
  if (lex_opt(ls, ',')) {  /* Collect LHS list and recurse upwards. */
277,608✔
2209
    LHSVarList vl;
342✔
2210
    vl.prev = lh;
342✔
2211
    expr_primary(ls, &vl.v);
342✔
2212
    if (vl.v.k == VLOCAL)
342✔
2213
      assign_hazard(ls, lh, &vl.v);
318✔
2214
    checklimit(ls->fs, ls->level + nvars, LJ_MAX_XLEVEL, "variable names");
342✔
2215
    parse_assignment(ls, &vl, nvars+1);
342✔
2216
  } else {  /* Parse RHS. */
2217
    BCReg nexps;
277,266✔
2218
    lex_check(ls, '=');
277,266✔
2219
    nexps = expr_list(ls, &e);
277,247✔
2220
    if (nexps == nvars) {
277,243✔
2221
      if (e.k == VCALL) {
277,117✔
2222
        if (bc_op(*bcptr(ls->fs, &e)) == BC_VARG) {  /* Vararg assignment. */
2,338✔
2223
          ls->fs->freereg--;
2✔
2224
          e.k = VRELOCABLE;
2✔
2225
        } else {  /* Multiple call results. */
2226
          e.u.s.info = e.u.s.aux;  /* Base of call is not relocatable. */
2,336✔
2227
          e.k = VNONRELOC;
2,336✔
2228
        }
2229
      }
2230
      bcemit_store(ls->fs, &lh->v, &e);
277,117✔
2231
      return;
277,117✔
2232
    }
2233
    assign_adjust(ls, nvars, nexps, &e);
126✔
2234
  }
2235
  /* Assign RHS to LHS and recurse downwards. */
2236
  expr_init(&e, VNONRELOC, ls->fs->freereg-1);
468✔
2237
  bcemit_store(ls->fs, &lh->v, &e);
468✔
2238
}
2239

2240
/* Parse call statement or assignment. */
2241
static void parse_call_assign(LexState *ls)
288,270✔
2242
{
2243
  FuncState *fs = ls->fs;
288,270✔
2244
  LHSVarList vl;
288,270✔
2245
  expr_primary(ls, &vl.v);
288,270✔
2246
  if (vl.v.k == VCALL) {  /* Function call statement. */
288,253✔
2247
    setbc_b(bcptr(fs, &vl.v), 1);  /* No results. */
10,987✔
2248
  } else {  /* Start of an assignment. */
2249
    vl.prev = NULL;
277,266✔
2250
    parse_assignment(ls, &vl, 1);
277,266✔
2251
  }
2252
}
288,230✔
2253

2254
/* Parse 'local' statement. */
2255
static void parse_local(LexState *ls)
9,599✔
2256
{
2257
  if (lex_opt(ls, TK_function)) {  /* Local function declaration. */
9,599✔
2258
    ExpDesc v, b;
2,672✔
2259
    FuncState *fs = ls->fs;
2,672✔
2260
    var_new(ls, 0, lex_str(ls));
2,672✔
2261
    expr_init(&v, VLOCAL, fs->freereg);
2,672✔
2262
    v.u.s.aux = fs->varmap[fs->freereg];
2,672✔
2263
    bcreg_reserve(fs, 1);
2,672✔
2264
    var_add(ls, 1);
2,672✔
2265
    parse_body(ls, &b, 0, ls->linenumber);
2,672✔
2266
    /* bcemit_store(fs, &v, &b) without setting VSTACK_VAR_RW. */
2267
    expr_free(fs, &b);
2,672✔
2268
    expr_toreg(fs, &b, v.u.s.info);
2,672✔
2269
    /* The upvalue is in scope, but the local is only valid after the store. */
2270
    var_get(ls, fs, fs->nactvar - 1).startpc = fs->pc;
2,672✔
2271
  } else {  /* Local variable declaration. */
2272
    ExpDesc e;
2273
    BCReg nexps, nvars = 0;
2274
    do {  /* Collect LHS. */
8,313✔
2275
      var_new(ls, nvars++, lex_str(ls));
8,313✔
2276
    } while (lex_opt(ls, ','));
8,309✔
2277
    if (lex_opt(ls, '=')) {  /* Optional RHS. */
6,923✔
2278
      nexps = expr_list(ls, &e);
6,516✔
2279
    } else {  /* Or implicitly set to nil. */
2280
      e.k = VVOID;
404✔
2281
      nexps = 0;
404✔
2282
    }
2283
    assign_adjust(ls, nvars, nexps, &e);
6,916✔
2284
    var_add(ls, nvars);
13,832✔
2285
  }
2286
}
9,588✔
2287

2288
/* Parse 'function' statement. */
2289
static void parse_func(LexState *ls, BCLine line)
1,418✔
2290
{
2291
  FuncState *fs;
1,418✔
2292
  ExpDesc v, b;
1,418✔
2293
  int needself = 0;
1,418✔
2294
  lj_lex_next(ls);  /* Skip 'function'. */
1,418✔
2295
  /* Parse function name. */
2296
  var_lookup(ls, &v);
1,418✔
2297
  while (ls->tok == '.')  /* Multiple dot-separated fields. */
1,506✔
2298
    expr_field(ls, &v);
90✔
2299
  if (ls->tok == ':') {  /* Optional colon to signify method call. */
1,416✔
2300
    needself = 1;
22✔
2301
    expr_field(ls, &v);
22✔
2302
  }
2303
  parse_body(ls, &b, needself, line);
1,416✔
2304
  fs = ls->fs;
1,327✔
2305
  bcemit_store(fs, &v, &b);
1,327✔
2306
  fs->bcbase[fs->pc - 1].line = line;  /* Set line for the store. */
1,327✔
2307
}
1,327✔
2308

2309
/* -- Control transfer statements ----------------------------------------- */
2310

2311
/* Check for end of block. */
2312
static int parse_isend(LexToken tok)
351,387✔
2313
{
2314
  switch (tok) {
351,387✔
2315
  case TK_else: case TK_elseif: case TK_end: case TK_until: case TK_eof:
2316
    return 1;
2317
  default:
2318
    return 0;
342,040✔
2319
  }
2320
}
2321

2322
/* Parse 'return' statement. */
2323
static void parse_return(LexState *ls)
18,187✔
2324
{
2325
  BCIns ins;
18,187✔
2326
  FuncState *fs = ls->fs;
18,187✔
2327
  lj_lex_next(ls);  /* Skip 'return'. */
18,187✔
2328
  fs->flags |= PROTO_HAS_RETURN;
18,187✔
2329
  if (parse_isend(ls->tok) || ls->tok == ';') {  /* Bare return. */
18,187✔
2330
    ins = BCINS_AD(BC_RET0, 0, 1);
2331
  } else {  /* Return with one or more values. */
2332
    ExpDesc e;  /* Receives the _last_ expression in the list. */
18,063✔
2333
    BCReg nret = expr_list(ls, &e);
18,063✔
2334
    if (nret == 1) {  /* Return one result. */
18,047✔
2335
      if (e.k == VCALL) {  /* Check for tail call. */
17,954✔
2336
        BCIns *ip = bcptr(fs, &e);
2,141✔
2337
        /* It doesn't pay off to add BC_VARGT just for 'return ...'. */
2338
        if (bc_op(*ip) == BC_VARG) goto notailcall;
2,141✔
2339
        fs->pc--;
2,140✔
2340
        ins = BCINS_AD(bc_op(*ip)-BC_CALL+BC_CALLT, bc_a(*ip), bc_c(*ip));
2,140✔
2341
      } else {  /* Can return the result from any register. */
2342
        ins = BCINS_AD(BC_RET1, expr_toanyreg(fs, &e), 2);
15,813✔
2343
      }
2344
    } else {
2345
      if (e.k == VCALL) {  /* Append all results from a call. */
93✔
2346
      notailcall:
17✔
2347
        setbc_b(bcptr(fs, &e), 0);
18✔
2348
        ins = BCINS_AD(BC_RETM, fs->nactvar, e.u.s.aux - fs->nactvar);
18✔
2349
      } else {
2350
        expr_tonextreg(fs, &e);  /* Force contiguous registers. */
76✔
2351
        ins = BCINS_AD(BC_RET, fs->nactvar, nret+1);
76✔
2352
      }
2353
    }
2354
  }
2355
  if (fs->flags & PROTO_CHILD)
18,171✔
2356
    bcemit_AJ(fs, BC_UCLO, 0, 0);  /* May need to close upvalues first. */
617✔
2357
  bcemit_INS(fs, ins);
18,171✔
2358
}
18,171✔
2359

2360
/* Parse 'break' statement. */
2361
static void parse_break(LexState *ls)
133✔
2362
{
2363
  ls->fs->bl->flags |= FSCOPE_BREAK;
133✔
2364
  gola_new(ls, NAME_BREAK, VSTACK_GOTO, bcemit_jmp(ls->fs));
133✔
2365
}
133✔
2366

2367
/* Parse 'goto' statement. */
2368
static void parse_goto(LexState *ls)
24✔
2369
{
2370
  FuncState *fs = ls->fs;
24✔
2371
  GCstr *name = lex_str(ls);
24✔
2372
  VarInfo *vl = gola_findlabel(ls, name);
24✔
2373
  if (vl)  /* Treat backwards goto within same scope like a loop. */
24✔
2374
    bcemit_AJ(fs, BC_LOOP, vl->slot, -1);  /* No BC range check. */
3✔
2375
  fs->bl->flags |= FSCOPE_GOLA;
24✔
2376
  gola_new(ls, name, VSTACK_GOTO, bcemit_jmp(fs));
24✔
2377
}
24✔
2378

2379
/* Parse label. */
2380
static void parse_label(LexState *ls)
33✔
2381
{
2382
  FuncState *fs = ls->fs;
33✔
2383
  GCstr *name;
33✔
2384
  MSize idx;
33✔
2385
  fs->lasttarget = fs->pc;
33✔
2386
  fs->bl->flags |= FSCOPE_GOLA;
33✔
2387
  lj_lex_next(ls);  /* Skip '::'. */
33✔
2388
  name = lex_str(ls);
33✔
2389
  if (gola_findlabel(ls, name))
66✔
2390
    lj_lex_error(ls, 0, LJ_ERR_XLDUP, strdata(name));
3✔
2391
  idx = gola_new(ls, name, VSTACK_LABEL, fs->pc);
30✔
2392
  lex_check(ls, TK_label);
30✔
2393
  /* Recursively parse trailing statements: labels and ';' (Lua 5.2 only). */
2394
  for (;;) {
34✔
2395
    if (ls->tok == TK_label) {
32✔
2396
      synlevel_begin(ls);
3✔
2397
      parse_label(ls);
3✔
2398
      synlevel_end(ls);
2✔
2399
    } else if (LJ_52 && ls->tok == ';') {
29✔
2400
      lj_lex_next(ls);
2401
    } else {
2402
      break;
2403
    }
2404
  }
2405
  /* Trailing label is considered to be outside of scope. */
2406
  if (parse_isend(ls->tok) && ls->tok != TK_until)
29✔
2407
    ls->vstack[idx].slot = fs->bl->nactvar;
11✔
2408
  gola_resolve(ls, fs->bl, idx);
29✔
2409
}
25✔
2410

2411
/* -- Blocks, loops and conditional statements ---------------------------- */
2412

2413
/* Parse a block. */
2414
static void parse_block(LexState *ls)
7,666✔
2415
{
2416
  FuncState *fs = ls->fs;
7,666✔
2417
  FuncScope bl;
7,666✔
2418
  fscope_begin(fs, &bl, 0);
7,666✔
2419
  parse_chunk(ls);
7,666✔
2420
  fscope_end(fs);
7,663✔
2421
}
7,663✔
2422

2423
/* Parse 'while' statement. */
2424
static void parse_while(LexState *ls, BCLine line)
171✔
2425
{
2426
  FuncState *fs = ls->fs;
171✔
2427
  BCPos start, loop, condexit;
171✔
2428
  FuncScope bl;
171✔
2429
  lj_lex_next(ls);  /* Skip 'while'. */
171✔
2430
  start = fs->lasttarget = fs->pc;
171✔
2431
  condexit = expr_cond(ls);
171✔
2432
  fscope_begin(fs, &bl, FSCOPE_LOOP);
171✔
2433
  lex_check(ls, TK_do);
171✔
2434
  loop = bcemit_AD(fs, BC_LOOP, fs->nactvar, 0);
170✔
2435
  parse_block(ls);
170✔
2436
  jmp_patch(fs, bcemit_jmp(fs), start);
169✔
2437
  lex_match(ls, TK_end, TK_while, line);
169✔
2438
  fscope_end(fs);
167✔
2439
  jmp_tohere(fs, condexit);
167✔
2440
  jmp_patchins(fs, loop, fs->pc);
167✔
2441
}
167✔
2442

2443
/* Parse 'repeat' statement. */
2444
static void parse_repeat(LexState *ls, BCLine line)
15✔
2445
{
2446
  FuncState *fs = ls->fs;
15✔
2447
  BCPos loop = fs->lasttarget = fs->pc;
15✔
2448
  BCPos condexit;
15✔
2449
  FuncScope bl1, bl2;
15✔
2450
  fscope_begin(fs, &bl1, FSCOPE_LOOP);  /* Breakable loop scope. */
15✔
2451
  fscope_begin(fs, &bl2, 0);  /* Inner scope. */
15✔
2452
  lj_lex_next(ls);  /* Skip 'repeat'. */
15✔
2453
  bcemit_AD(fs, BC_LOOP, fs->nactvar, 0);
15✔
2454
  parse_chunk(ls);
15✔
2455
  lex_match(ls, TK_until, TK_repeat, line);
14✔
2456
  condexit = expr_cond(ls);  /* Parse condition (still inside inner scope). */
13✔
2457
  if (!(bl2.flags & FSCOPE_UPVAL)) {  /* No upvalues? Just end inner scope. */
13✔
2458
    fscope_end(fs);
11✔
2459
  } else {  /* Otherwise generate: cond: UCLO+JMP out, !cond: UCLO+JMP loop. */
2460
    parse_break(ls);  /* Break from loop and close upvalues. */
2✔
2461
    jmp_tohere(fs, condexit);
2✔
2462
    fscope_end(fs);  /* End inner scope and close upvalues. */
2✔
2463
    condexit = bcemit_jmp(fs);
2✔
2464
  }
2465
  jmp_patch(fs, condexit, loop);  /* Jump backwards if !cond. */
13✔
2466
  jmp_patchins(fs, loop, fs->pc);
13✔
2467
  fscope_end(fs);  /* End loop scope. */
13✔
2468
}
13✔
2469

2470
/* Parse numeric 'for'. */
2471
static void parse_for_num(LexState *ls, GCstr *varname, BCLine line)
1,293✔
2472
{
2473
  FuncState *fs = ls->fs;
1,293✔
2474
  BCReg base = fs->freereg;
1,293✔
2475
  FuncScope bl;
1,293✔
2476
  BCPos loop, loopend;
1,293✔
2477
  /* Hidden control variables. */
2478
  var_new_fixed(ls, FORL_IDX, VARNAME_FOR_IDX);
1,293✔
2479
  var_new_fixed(ls, FORL_STOP, VARNAME_FOR_STOP);
1,293✔
2480
  var_new_fixed(ls, FORL_STEP, VARNAME_FOR_STEP);
1,293✔
2481
  /* Visible copy of index variable. */
2482
  var_new(ls, FORL_EXT, varname);
1,293✔
2483
  lex_check(ls, '=');
1,293✔
2484
  expr_next(ls);
1,293✔
2485
  lex_check(ls, ',');
1,293✔
2486
  expr_next(ls);
1,293✔
2487
  if (lex_opt(ls, ',')) {
1,293✔
2488
    expr_next(ls);
52✔
2489
  } else {
2490
    bcemit_AD(fs, BC_KSHORT, fs->freereg, 1);  /* Default step is 1. */
1,241✔
2491
    bcreg_reserve(fs, 1);
1,241✔
2492
  }
2493
  var_add(ls, 3);  /* Hidden control variables. */
1,293✔
2494
  lex_check(ls, TK_do);
1,293✔
2495
  loop = bcemit_AJ(fs, BC_FORI, base, NO_JMP);
1,292✔
2496
  fscope_begin(fs, &bl, 0);  /* Scope for visible variables. */
1,292✔
2497
  var_add(ls, 1);
1,292✔
2498
  bcreg_reserve(fs, 1);
1,292✔
2499
  parse_block(ls);
1,292✔
2500
  fscope_end(fs);
1,292✔
2501
  /* Perform loop inversion. Loop control instructions are at the end. */
2502
  loopend = bcemit_AJ(fs, BC_FORL, base, NO_JMP);
1,292✔
2503
  fs->bcbase[loopend].line = line;  /* Fix line for control ins. */
1,292✔
2504
  jmp_patchins(fs, loopend, loop+1);
1,292✔
2505
  jmp_patchins(fs, loop, fs->pc);
1,292✔
2506
}
1,292✔
2507

2508
/* Try to predict whether the iterator is next() and specialize the bytecode.
2509
** Detecting next() and pairs() by name is simplistic, but quite effective.
2510
** The interpreter backs off if the check for the closure fails at runtime.
2511
*/
2512
static int predict_next(LexState *ls, FuncState *fs, BCPos pc)
2513
{
2514
  BCIns ins = fs->bcbase[pc].ins;
2515
  GCstr *name;
2516
  cTValue *o;
2517
  switch (bc_op(ins)) {
2518
  case BC_MOV:
2519
    name = gco2str(gcref(var_get(ls, fs, bc_d(ins)).name));
2520
    break;
2521
  case BC_UGET:
2522
    name = gco2str(gcref(ls->vstack[fs->uvmap[bc_d(ins)]].name));
2523
    break;
2524
  case BC_GGET:
2525
    /* There's no inverse index (yet), so lookup the strings. */
2526
    o = lj_tab_getstr(fs->kt, lj_str_newlit(ls->L, "pairs"));
2527
    if (o && tvhaskslot(o) && tvkslot(o) == bc_d(ins))
2528
      return 1;
2529
    o = lj_tab_getstr(fs->kt, lj_str_newlit(ls->L, "next"));
2530
    if (o && tvhaskslot(o) && tvkslot(o) == bc_d(ins))
2531
      return 1;
2532
    return 0;
2533
  default:
2534
    return 0;
2535
  }
2536
  return (name->len == 5 && !strcmp(strdata(name), "pairs")) ||
2537
         (name->len == 4 && !strcmp(strdata(name), "next"));
2538
}
2539

2540
/* Parse 'for' iterator. */
2541
static void parse_for_iter(LexState *ls, GCstr *indexname)
535✔
2542
{
2543
  FuncState *fs = ls->fs;
535✔
2544
  ExpDesc e;
535✔
2545
  BCReg nvars = 0;
535✔
2546
  BCLine line;
535✔
2547
  BCReg base = fs->freereg + 3;
535✔
2548
  BCPos loop, loopend, exprpc = fs->pc;
535✔
2549
  FuncScope bl;
535✔
2550
  int isnext;
535✔
2551
  /* Hidden control variables. */
2552
  var_new_fixed(ls, nvars++, VARNAME_FOR_GEN);
535✔
2553
  var_new_fixed(ls, nvars++, VARNAME_FOR_STATE);
535✔
2554
  var_new_fixed(ls, nvars++, VARNAME_FOR_CTL);
535✔
2555
  /* Visible variables returned from iterator. */
2556
  var_new(ls, nvars++, indexname);
535✔
2557
  while (lex_opt(ls, ','))
1,040✔
2558
    var_new(ls, nvars++, lex_str(ls));
505✔
2559
  lex_check(ls, TK_in);
535✔
2560
  line = ls->linenumber;
535✔
2561
  assign_adjust(ls, 3, expr_list(ls, &e), &e);
535✔
2562
  /* The iterator needs another 3 [4] slots (func [pc] | state ctl). */
2563
  bcreg_bump(fs, 3+LJ_FR2);
535✔
2564
  isnext = (nvars <= 5 && predict_next(ls, fs, exprpc));
535✔
2565
  var_add(ls, 3);  /* Hidden control variables. */
535✔
2566
  lex_check(ls, TK_do);
535✔
2567
  loop = bcemit_AJ(fs, isnext ? BC_ISNEXT : BC_JMP, base, NO_JMP);
687✔
2568
  fscope_begin(fs, &bl, 0);  /* Scope for visible variables. */
535✔
2569
  var_add(ls, nvars-3);
535✔
2570
  bcreg_reserve(fs, nvars-3);
535✔
2571
  parse_block(ls);
535✔
2572
  fscope_end(fs);
535✔
2573
  /* Perform loop inversion. Loop control instructions are at the end. */
2574
  jmp_patchins(fs, loop, fs->pc);
535✔
2575
  bcemit_ABC(fs, isnext ? BC_ITERN : BC_ITERC, base, nvars-3+1, 2+1);
535✔
2576
  loopend = bcemit_AJ(fs, BC_ITERL, base, NO_JMP);
535✔
2577
  fs->bcbase[loopend-1].line = line;  /* Fix line for control ins. */
535✔
2578
  fs->bcbase[loopend].line = line;
535✔
2579
  jmp_patchins(fs, loopend, loop+1);
535✔
2580
}
535✔
2581

2582
/* Parse 'for' statement. */
2583
static void parse_for(LexState *ls, BCLine line)
1,829✔
2584
{
2585
  FuncState *fs = ls->fs;
1,829✔
2586
  GCstr *varname;
1,829✔
2587
  FuncScope bl;
1,829✔
2588
  fscope_begin(fs, &bl, FSCOPE_LOOP);
1,829✔
2589
  lj_lex_next(ls);  /* Skip 'for'. */
1,829✔
2590
  varname = lex_str(ls);  /* Get first variable name. */
1,829✔
2591
  if (ls->tok == '=')
1,829✔
2592
    parse_for_num(ls, varname, line);
1,293✔
2593
  else if (ls->tok == ',' || ls->tok == TK_in)
536✔
2594
    parse_for_iter(ls, varname);
535✔
2595
  else
2596
    err_syntax(ls, LJ_ERR_XFOR);
1✔
2597
  lex_match(ls, TK_end, TK_for, line);
1,827✔
2598
  fscope_end(fs);  /* Resolve break list. */
1,826✔
2599
}
1,826✔
2600

2601
/* Parse condition and 'then' block. */
2602
static BCPos parse_then(LexState *ls)
4,285✔
2603
{
2604
  BCPos condexit;
4,285✔
2605
  lj_lex_next(ls);  /* Skip 'if' or 'elseif'. */
4,285✔
2606
  condexit = expr_cond(ls);
4,285✔
2607
  lex_check(ls, TK_then);
4,281✔
2608
  parse_block(ls);
4,276✔
2609
  return condexit;
4,274✔
2610
}
2611

2612
/* Parse 'if' statement. */
2613
static void parse_if(LexState *ls, BCLine line)
3,964✔
2614
{
2615
  FuncState *fs = ls->fs;
3,964✔
2616
  BCPos flist;
3,964✔
2617
  BCPos escapelist = NO_JMP;
3,964✔
2618
  flist = parse_then(ls);
3,964✔
2619
  while (ls->tok == TK_elseif) {  /* Parse multiple 'elseif' blocks. */
4,285✔
2620
    jmp_append(fs, &escapelist, bcemit_jmp(fs));
321✔
2621
    jmp_tohere(fs, flist);
321✔
2622
    flist = parse_then(ls);
321✔
2623
  }
2624
  if (ls->tok == TK_else) {  /* Parse optional 'else' block. */
3,953✔
2625
    jmp_append(fs, &escapelist, bcemit_jmp(fs));
1,054✔
2626
    jmp_tohere(fs, flist);
1,054✔
2627
    lj_lex_next(ls);  /* Skip 'else'. */
1,054✔
2628
    parse_block(ls);
1,054✔
2629
  } else {
2630
    jmp_append(fs, &escapelist, flist);
2,899✔
2631
  }
2632
  jmp_tohere(fs, escapelist);
3,953✔
2633
  lex_match(ls, TK_end, TK_if, line);
3,953✔
2634
}
3,935✔
2635

2636
/* -- Parse statements ---------------------------------------------------- */
2637

2638
/* Parse a statement. Returns 1 if it must be the last one in a chunk. */
2639
static int parse_stmt(LexState *ls)
323,977✔
2640
{
2641
  BCLine line = ls->linenumber;
323,977✔
2642
  switch (ls->tok) {
323,977✔
2643
  case TK_if:
3,964✔
2644
    parse_if(ls, line);
3,964✔
2645
    break;
3,964✔
2646
  case TK_while:
171✔
2647
    parse_while(ls, line);
171✔
2648
    break;
171✔
2649
  case TK_do:
339✔
2650
    lj_lex_next(ls);
339✔
2651
    parse_block(ls);
339✔
2652
    lex_match(ls, TK_end, TK_do, line);
339✔
2653
    break;
339✔
2654
  case TK_for:
1,829✔
2655
    parse_for(ls, line);
1,829✔
2656
    break;
1,829✔
2657
  case TK_repeat:
15✔
2658
    parse_repeat(ls, line);
15✔
2659
    break;
15✔
2660
  case TK_function:
1,418✔
2661
    parse_func(ls, line);
1,418✔
2662
    break;
1,418✔
2663
  case TK_local:
9,599✔
2664
    lj_lex_next(ls);
9,599✔
2665
    parse_local(ls);
9,599✔
2666
    break;
9,599✔
2667
  case TK_return:
18,187✔
2668
    parse_return(ls);
18,187✔
2669
    return 1;  /* Must be last. */
18,187✔
2670
  case TK_break:
131✔
2671
    lj_lex_next(ls);
131✔
2672
    parse_break(ls);
131✔
2673
    return !LJ_52;  /* Must be last in Lua 5.1. */
131✔
2674
#if LJ_52
2675
  case ';':
2676
    lj_lex_next(ls);
2677
    break;
2678
#endif
2679
  case TK_label:
30✔
2680
    parse_label(ls);
30✔
2681
    break;
30✔
2682
  case TK_goto:
25✔
2683
    if (LJ_52 || lj_lex_lookahead(ls) == TK_name) {
25✔
2684
      lj_lex_next(ls);
24✔
2685
      parse_goto(ls);
24✔
2686
      break;
24✔
2687
    }  /* else: fallthrough */
2688
  default:
2689
    parse_call_assign(ls);
288,270✔
2690
    break;
288,270✔
2691
  }
2692
  return 0;
2693
}
2694

2695
/* A chunk is a list of statements optionally separated by semicolons. */
2696
static void parse_chunk(LexState *ls)
27,700✔
2697
{
2698
  int islast = 0;
27,700✔
2699
  synlevel_begin(ls);
27,700✔
2700
  while (!islast && !parse_isend(ls->tok)) {
351,473✔
2701
    islast = parse_stmt(ls);
323,977✔
2702
    lex_opt(ls, ';');
323,773✔
2703
    lua_assert(ls->fs->framesize >= ls->fs->freereg &&
323,773✔
2704
               ls->fs->freereg >= ls->fs->nactvar);
2705
    ls->fs->freereg = ls->fs->nactvar;  /* Free registers after each stmt. */
323,773✔
2706
  }
2707
  synlevel_end(ls);
27,496✔
2708
}
27,496✔
2709

2710
/* Entry point of bytecode parser. */
2711
GCproto *lj_parse(LexState *ls)
14,439✔
2712
{
2713
  FuncState fs;
14,439✔
2714
  FuncScope bl;
14,439✔
2715
  GCproto *pt;
14,439✔
2716
  lua_State *L = ls->L;
14,439✔
2717
#ifdef LUAJIT_DISABLE_DEBUGINFO
2718
  ls->chunkname = lj_str_newlit(L, "=");
2719
#else
2720
  ls->chunkname = lj_str_newz(L, ls->chunkarg);
14,439✔
2721
#endif
2722
  setstrV(L, L->top, ls->chunkname);  /* Anchor chunkname string. */
14,439✔
2723
  incr_top(L);
14,439✔
2724
  ls->level = 0;
14,439✔
2725
  fs_init(ls, &fs);
14,439✔
2726
  fs.linedefined = 0;
14,439✔
2727
  fs.numparams = 0;
14,439✔
2728
  fs.bcbase = NULL;
14,439✔
2729
  fs.bclim = 0;
14,439✔
2730
  fs.flags |= PROTO_VARARG;  /* Main chunk is always a vararg func. */
14,439✔
2731
  fscope_begin(&fs, &bl, 0);
14,439✔
2732
  bcemit_AD(&fs, BC_FUNCV, 0, 0);  /* Placeholder. */
14,439✔
2733
  lj_lex_next(ls);  /* Read-ahead first token. */
14,439✔
2734
  parse_chunk(ls);
14,438✔
2735
  if (ls->tok != TK_eof)
14,280✔
2736
    err_token(ls, TK_eof);
×
2737
  pt = fs_finish(ls, ls->linenumber);
14,280✔
2738
  L->top--;  /* Drop chunkname. */
14,271✔
2739
  lua_assert(fs.prev == NULL);
14,271✔
2740
  lua_assert(ls->fs == NULL);
14,271✔
2741
  lua_assert(pt->sizeuv == 0);
14,271✔
2742
  return pt;
14,271✔
2743
}
2744

STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc