Coverage Report

Created: 2025-07-18 06:59

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