Coverage Report

Created: 2023-04-27 06:14

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