Coverage Report

Created: 2025-10-10 06:38

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