Coverage Report

Created: 2025-08-25 06:57

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