Coverage Report

Created: 2026-03-12 07:07

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