Coverage Report

Created: 2023-09-30 06:10

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