Subversion Repositories Kolibri OS

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
5205 clevermous 1
/*
2
** $Id: lparser.c,v 2.124 2011/12/02 13:23:56 roberto Exp $
3
** Lua Parser
4
** See Copyright Notice in lua.h
5
*/
6
 
7
 
8
#include 
9
 
10
#define lparser_c
11
#define LUA_CORE
12
 
13
#include "lua.h"
14
 
15
#include "lcode.h"
16
#include "ldebug.h"
17
#include "ldo.h"
18
#include "lfunc.h"
19
#include "llex.h"
20
#include "lmem.h"
21
#include "lobject.h"
22
#include "lopcodes.h"
23
#include "lparser.h"
24
#include "lstate.h"
25
#include "lstring.h"
26
#include "ltable.h"
27
 
28
 
29
 
30
/* maximum number of local variables per function (must be smaller
31
   than 250, due to the bytecode format) */
32
#define MAXVARS		200
33
 
34
 
35
#define hasmultret(k)		((k) == VCALL || (k) == VVARARG)
36
 
37
 
38
 
39
/*
40
** nodes for block list (list of active blocks)
41
*/
42
typedef struct BlockCnt {
43
  struct BlockCnt *previous;  /* chain */
44
  short firstlabel;  /* index of first label in this block */
45
  short firstgoto;  /* index of first pending goto in this block */
46
  lu_byte nactvar;  /* # active locals outside the block */
47
  lu_byte upval;  /* true if some variable in the block is an upvalue */
48
  lu_byte isloop;  /* true if `block' is a loop */
49
} BlockCnt;
50
 
51
 
52
 
53
/*
54
** prototypes for recursive non-terminal functions
55
*/
56
static void statement (LexState *ls);
57
static void expr (LexState *ls, expdesc *v);
58
 
59
 
60
static void anchor_token (LexState *ls) {
61
  /* last token from outer function must be EOS */
62
  lua_assert(ls->fs != NULL || ls->t.token == TK_EOS);
63
  if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
64
    TString *ts = ls->t.seminfo.ts;
65
    luaX_newstring(ls, getstr(ts), ts->tsv.len);
66
  }
67
}
68
 
69
 
70
/* semantic error */
71
static l_noret semerror (LexState *ls, const char *msg) {
72
  ls->t.token = 0;  /* remove 'near to' from final message */
73
  luaX_syntaxerror(ls, msg);
74
}
75
 
76
 
77
static l_noret error_expected (LexState *ls, int token) {
78
  luaX_syntaxerror(ls,
79
      luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
80
}
81
 
82
 
83
static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
84
  lua_State *L = fs->ls->L;
85
  const char *msg;
86
  int line = fs->f->linedefined;
87
  const char *where = (line == 0)
88
                      ? "main function"
89
                      : luaO_pushfstring(L, "function at line %d", line);
90
  msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
91
                             what, limit, where);
92
  luaX_syntaxerror(fs->ls, msg);
93
}
94
 
95
 
96
static void checklimit (FuncState *fs, int v, int l, const char *what) {
97
  if (v > l) errorlimit(fs, l, what);
98
}
99
 
100
 
101
static int testnext (LexState *ls, int c) {
102
  if (ls->t.token == c) {
103
    luaX_next(ls);
104
    return 1;
105
  }
106
  else return 0;
107
}
108
 
109
 
110
static void check (LexState *ls, int c) {
111
  if (ls->t.token != c)
112
    error_expected(ls, c);
113
}
114
 
115
 
116
static void checknext (LexState *ls, int c) {
117
  check(ls, c);
118
  luaX_next(ls);
119
}
120
 
121
 
122
#define check_condition(ls,c,msg)	{ if (!(c)) luaX_syntaxerror(ls, msg); }
123
 
124
 
125
 
126
static void check_match (LexState *ls, int what, int who, int where) {
127
  if (!testnext(ls, what)) {
128
    if (where == ls->linenumber)
129
      error_expected(ls, what);
130
    else {
131
      luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
132
             "%s expected (to close %s at line %d)",
133
              luaX_token2str(ls, what), luaX_token2str(ls, who), where));
134
    }
135
  }
136
}
137
 
138
 
139
static TString *str_checkname (LexState *ls) {
140
  TString *ts;
141
  check(ls, TK_NAME);
142
  ts = ls->t.seminfo.ts;
143
  luaX_next(ls);
144
  return ts;
145
}
146
 
147
 
148
static void init_exp (expdesc *e, expkind k, int i) {
149
  e->f = e->t = NO_JUMP;
150
  e->k = k;
151
  e->u.info = i;
152
}
153
 
154
 
155
static void codestring (LexState *ls, expdesc *e, TString *s) {
156
  init_exp(e, VK, luaK_stringK(ls->fs, s));
157
}
158
 
159
 
160
static void checkname (LexState *ls, expdesc *e) {
161
  codestring(ls, e, str_checkname(ls));
162
}
163
 
164
 
165
static int registerlocalvar (LexState *ls, TString *varname) {
166
  FuncState *fs = ls->fs;
167
  Proto *f = fs->f;
168
  int oldsize = f->sizelocvars;
169
  luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
170
                  LocVar, SHRT_MAX, "local variables");
171
  while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
172
  f->locvars[fs->nlocvars].varname = varname;
173
  luaC_objbarrier(ls->L, f, varname);
174
  return fs->nlocvars++;
175
}
176
 
177
 
178
static void new_localvar (LexState *ls, TString *name) {
179
  FuncState *fs = ls->fs;
180
  Dyndata *dyd = ls->dyd;
181
  int reg = registerlocalvar(ls, name);
182
  checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
183
                  MAXVARS, "local variables");
184
  luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,
185
                  dyd->actvar.size, Vardesc, MAX_INT, "local variables");
186
  dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg);
187
}
188
 
189
 
190
static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) {
191
  new_localvar(ls, luaX_newstring(ls, name, sz));
192
}
193
 
194
#define new_localvarliteral(ls,v) \
195
	new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1)
196
 
197
 
198
static LocVar *getlocvar (FuncState *fs, int i) {
199
  int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
200
  lua_assert(idx < fs->nlocvars);
201
  return &fs->f->locvars[idx];
202
}
203
 
204
 
205
static void adjustlocalvars (LexState *ls, int nvars) {
206
  FuncState *fs = ls->fs;
207
  fs->nactvar = cast_byte(fs->nactvar + nvars);
208
  for (; nvars; nvars--) {
209
    getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;
210
  }
211
}
212
 
213
 
214
static void removevars (FuncState *fs, int tolevel) {
215
  fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
216
  while (fs->nactvar > tolevel)
217
    getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
218
}
219
 
220
 
221
static int searchupvalue (FuncState *fs, TString *name) {
222
  int i;
223
  Upvaldesc *up = fs->f->upvalues;
224
  for (i = 0; i < fs->nups; i++) {
225
    if (eqstr(up[i].name, name)) return i;
226
  }
227
  return -1;  /* not found */
228
}
229
 
230
 
231
static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
232
  Proto *f = fs->f;
233
  int oldsize = f->sizeupvalues;
234
  checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
235
  luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
236
                  Upvaldesc, MAXUPVAL, "upvalues");
237
  while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL;
238
  f->upvalues[fs->nups].instack = (v->k == VLOCAL);
239
  f->upvalues[fs->nups].idx = cast_byte(v->u.info);
240
  f->upvalues[fs->nups].name = name;
241
  luaC_objbarrier(fs->ls->L, f, name);
242
  return fs->nups++;
243
}
244
 
245
 
246
static int searchvar (FuncState *fs, TString *n) {
247
  int i;
248
  for (i=fs->nactvar-1; i >= 0; i--) {
249
    if (eqstr(n, getlocvar(fs, i)->varname))
250
      return i;
251
  }
252
  return -1;  /* not found */
253
}
254
 
255
 
256
/*
257
  Mark block where variable at given level was defined
258
  (to emit close instructions later).
259
*/
260
static void markupval (FuncState *fs, int level) {
261
  BlockCnt *bl = fs->bl;
262
  while (bl->nactvar > level) bl = bl->previous;
263
  bl->upval = 1;
264
}
265
 
266
 
267
/*
268
  Find variable with given name 'n'. If it is an upvalue, add this
269
  upvalue into all intermediate functions.
270
*/
271
static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
272
  if (fs == NULL)  /* no more levels? */
273
    return VVOID;  /* default is global */
274
  else {
275
    int v = searchvar(fs, n);  /* look up locals at current level */
276
    if (v >= 0) {  /* found? */
277
      init_exp(var, VLOCAL, v);  /* variable is local */
278
      if (!base)
279
        markupval(fs, v);  /* local will be used as an upval */
280
      return VLOCAL;
281
    }
282
    else {  /* not found as local at current level; try upvalues */
283
      int idx = searchupvalue(fs, n);  /* try existing upvalues */
284
      if (idx < 0) {  /* not found? */
285
        if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */
286
          return VVOID;  /* not found; is a global */
287
        /* else was LOCAL or UPVAL */
288
        idx  = newupvalue(fs, n, var);  /* will be a new upvalue */
289
      }
290
      init_exp(var, VUPVAL, idx);
291
      return VUPVAL;
292
    }
293
  }
294
}
295
 
296
 
297
static void singlevar (LexState *ls, expdesc *var) {
298
  TString *varname = str_checkname(ls);
299
  FuncState *fs = ls->fs;
300
  if (singlevaraux(fs, varname, var, 1) == VVOID) {  /* global name? */
301
    expdesc key;
302
    singlevaraux(fs, ls->envn, var, 1);  /* get environment variable */
303
    lua_assert(var->k == VLOCAL || var->k == VUPVAL);
304
    codestring(ls, &key, varname);  /* key is variable name */
305
    luaK_indexed(fs, var, &key);  /* env[varname] */
306
  }
307
}
308
 
309
 
310
static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
311
  FuncState *fs = ls->fs;
312
  int extra = nvars - nexps;
313
  if (hasmultret(e->k)) {
314
    extra++;  /* includes call itself */
315
    if (extra < 0) extra = 0;
316
    luaK_setreturns(fs, e, extra);  /* last exp. provides the difference */
317
    if (extra > 1) luaK_reserveregs(fs, extra-1);
318
  }
319
  else {
320
    if (e->k != VVOID) luaK_exp2nextreg(fs, e);  /* close last expression */
321
    if (extra > 0) {
322
      int reg = fs->freereg;
323
      luaK_reserveregs(fs, extra);
324
      luaK_nil(fs, reg, extra);
325
    }
326
  }
327
}
328
 
329
 
330
static void enterlevel (LexState *ls) {
331
  lua_State *L = ls->L;
332
  ++L->nCcalls;
333
  checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels");
334
}
335
 
336
 
337
#define leavelevel(ls)	((ls)->L->nCcalls--)
338
 
339
 
340
static void closegoto (LexState *ls, int g, Labeldesc *label) {
341
  int i;
342
  FuncState *fs = ls->fs;
343
  Labellist *gl = &ls->dyd->gt;
344
  Labeldesc *gt = &gl->arr[g];
345
  lua_assert(eqstr(gt->name, label->name));
346
  if (gt->nactvar < label->nactvar) {
347
    TString *vname = getlocvar(fs, gt->nactvar)->varname;
348
    const char *msg = luaO_pushfstring(ls->L,
349
      " at line %d jumps into the scope of local " LUA_QS,
350
      getstr(gt->name), gt->line, getstr(vname));
351
    semerror(ls, msg);
352
  }
353
  luaK_patchlist(fs, gt->pc, label->pc);
354
  /* remove goto from pending list */
355
  for (i = g; i < gl->n - 1; i++)
356
    gl->arr[i] = gl->arr[i + 1];
357
  gl->n--;
358
}
359
 
360
 
361
/*
362
** try to close a goto with existing labels; this solves backward jumps
363
*/
364
static int findlabel (LexState *ls, int g) {
365
  int i;
366
  BlockCnt *bl = ls->fs->bl;
367
  Dyndata *dyd = ls->dyd;
368
  Labeldesc *gt = &dyd->gt.arr[g];
369
  /* check labels in current block for a match */
370
  for (i = bl->firstlabel; i < dyd->label.n; i++) {
371
    Labeldesc *lb = &dyd->label.arr[i];
372
    if (eqstr(lb->name, gt->name)) {  /* correct label? */
373
      if (gt->nactvar > lb->nactvar &&
374
          (bl->upval || dyd->label.n > bl->firstlabel))
375
        luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
376
      closegoto(ls, g, lb);  /* close it */
377
      return 1;
378
    }
379
  }
380
  return 0;  /* label not found; cannot close goto */
381
}
382
 
383
 
384
static int newlabelentry (LexState *ls, Labellist *l, TString *name,
385
                          int line, int pc) {
386
  int n = l->n;
387
  luaM_growvector(ls->L, l->arr, n, l->size,
388
                  Labeldesc, SHRT_MAX, "labels/gotos");
389
  l->arr[n].name = name;
390
  l->arr[n].line = line;
391
  l->arr[n].nactvar = ls->fs->nactvar;
392
  l->arr[n].pc = pc;
393
  l->n++;
394
  return n;
395
}
396
 
397
 
398
/*
399
** check whether new label 'lb' matches any pending gotos in current
400
** block; solves forward jumps
401
*/
402
static void findgotos (LexState *ls, Labeldesc *lb) {
403
  Labellist *gl = &ls->dyd->gt;
404
  int i = ls->fs->bl->firstgoto;
405
  while (i < gl->n) {
406
    if (eqstr(gl->arr[i].name, lb->name))
407
      closegoto(ls, i, lb);
408
    else
409
      i++;
410
  }
411
}
412
 
413
 
414
/*
415
** "export" pending gotos to outer level, to check them against
416
** outer labels; if the block being exited has upvalues, and
417
** the goto exits the scope of any variable (which can be the
418
** upvalue), close those variables being exited.
419
*/
420
static void movegotosout (FuncState *fs, BlockCnt *bl) {
421
  int i = bl->firstgoto;
422
  Labellist *gl = &fs->ls->dyd->gt;
423
  /* correct pending gotos to current block and try to close it
424
     with visible labels */
425
  while (i < gl->n) {
426
    Labeldesc *gt = &gl->arr[i];
427
    if (gt->nactvar > bl->nactvar) {
428
      if (bl->upval)
429
        luaK_patchclose(fs, gt->pc, bl->nactvar);
430
      gt->nactvar = bl->nactvar;
431
    }
432
    if (!findlabel(fs->ls, i))
433
      i++;  /* move to next one */
434
  }
435
}
436
 
437
 
438
static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
439
  bl->isloop = isloop;
440
  bl->nactvar = fs->nactvar;
441
  bl->firstlabel = fs->ls->dyd->label.n;
442
  bl->firstgoto = fs->ls->dyd->gt.n;
443
  bl->upval = 0;
444
  bl->previous = fs->bl;
445
  fs->bl = bl;
446
  lua_assert(fs->freereg == fs->nactvar);
447
}
448
 
449
 
450
/*
451
** create a label named "break" to resolve break statements
452
*/
453
static void breaklabel (LexState *ls) {
454
  TString *n = luaS_new(ls->L, "break");
455
  int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);
456
  findgotos(ls, &ls->dyd->label.arr[l]);
457
}
458
 
459
/*
460
** generates an error for an undefined 'goto'; choose appropriate
461
** message when label name is a reserved word (which can only be 'break')
462
*/
463
static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
464
  const char *msg = (gt->name->tsv.reserved > 0)
465
                    ? "<%s> at line %d not inside a loop"
466
                    : "no visible label " LUA_QS " for  at line %d";
467
  msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
468
  semerror(ls, msg);
469
}
470
 
471
 
472
static void leaveblock (FuncState *fs) {
473
  BlockCnt *bl = fs->bl;
474
  LexState *ls = fs->ls;
475
  if (bl->previous && bl->upval) {
476
    /* create a 'jump to here' to close upvalues */
477
    int j = luaK_jump(fs);
478
    luaK_patchclose(fs, j, bl->nactvar);
479
    luaK_patchtohere(fs, j);
480
  }
481
  if (bl->isloop)
482
    breaklabel(ls);  /* close pending breaks */
483
  fs->bl = bl->previous;
484
  removevars(fs, bl->nactvar);
485
  lua_assert(bl->nactvar == fs->nactvar);
486
  fs->freereg = fs->nactvar;  /* free registers */
487
  ls->dyd->label.n = bl->firstlabel;  /* remove local labels */
488
  if (bl->previous)  /* inner block? */
489
    movegotosout(fs, bl);  /* update pending gotos to outer block */
490
  else if (bl->firstgoto < ls->dyd->gt.n)  /* pending gotos in outer block? */
491
    undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]);  /* error */
492
}
493
 
494
 
495
/*
496
** adds prototype being created into its parent list of prototypes
497
** and codes instruction to create new closure
498
*/
499
static void codeclosure (LexState *ls, Proto *clp, expdesc *v) {
500
  FuncState *fs = ls->fs->prev;
501
  Proto *f = fs->f;  /* prototype of function creating new closure */
502
  if (fs->np >= f->sizep) {
503
    int oldsize = f->sizep;
504
    luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
505
                    MAXARG_Bx, "functions");
506
    while (oldsize < f->sizep) f->p[oldsize++] = NULL;
507
  }
508
  f->p[fs->np++] = clp;
509
  luaC_objbarrier(ls->L, f, clp);
510
  init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
511
  luaK_exp2nextreg(fs, v);  /* fix it at stack top (for GC) */
512
}
513
 
514
 
515
static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
516
  lua_State *L = ls->L;
517
  Proto *f;
518
  fs->prev = ls->fs;  /* linked list of funcstates */
519
  fs->ls = ls;
520
  ls->fs = fs;
521
  fs->pc = 0;
522
  fs->lasttarget = 0;
523
  fs->jpc = NO_JUMP;
524
  fs->freereg = 0;
525
  fs->nk = 0;
526
  fs->np = 0;
527
  fs->nups = 0;
528
  fs->nlocvars = 0;
529
  fs->nactvar = 0;
530
  fs->firstlocal = ls->dyd->actvar.n;
531
  fs->bl = NULL;
532
  f = luaF_newproto(L);
533
  fs->f = f;
534
  f->source = ls->source;
535
  f->maxstacksize = 2;  /* registers 0/1 are always valid */
536
  /* anchor prototype (to avoid being collected) */
537
  setptvalue2s(L, L->top, f);
538
  incr_top(L);
539
  fs->h = luaH_new(L);
540
  /* anchor table of constants (to avoid being collected) */
541
  sethvalue2s(L, L->top, fs->h);
542
  incr_top(L);
543
  enterblock(fs, bl, 0);
544
}
545
 
546
 
547
static void close_func (LexState *ls) {
548
  lua_State *L = ls->L;
549
  FuncState *fs = ls->fs;
550
  Proto *f = fs->f;
551
  luaK_ret(fs, 0, 0);  /* final return */
552
  leaveblock(fs);
553
  luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
554
  f->sizecode = fs->pc;
555
  luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
556
  f->sizelineinfo = fs->pc;
557
  luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
558
  f->sizek = fs->nk;
559
  luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
560
  f->sizep = fs->np;
561
  luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
562
  f->sizelocvars = fs->nlocvars;
563
  luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
564
  f->sizeupvalues = fs->nups;
565
  lua_assert(fs->bl == NULL);
566
  ls->fs = fs->prev;
567
  /* last token read was anchored in defunct function; must re-anchor it */
568
  anchor_token(ls);
569
  L->top--;  /* pop table of constants */
570
  luaC_checkGC(L);
571
  L->top--;  /* pop prototype (after possible collection) */
572
}
573
 
574
 
575
/*
576
** opens the main function, which is a regular vararg function with an
577
** upvalue named LUA_ENV
578
*/
579
static void open_mainfunc (LexState *ls, FuncState *fs, BlockCnt *bl) {
580
  expdesc v;
581
  open_func(ls, fs, bl);
582
  fs->f->is_vararg = 1;  /* main function is always vararg */
583
  init_exp(&v, VLOCAL, 0);
584
  newupvalue(fs, ls->envn, &v);  /* create environment upvalue */
585
}
586
 
587
 
588
 
589
/*============================================================*/
590
/* GRAMMAR RULES */
591
/*============================================================*/
592
 
593
 
594
/*
595
** check whether current token is in the follow set of a block.
596
** 'until' closes syntactical blocks, but do not close scope,
597
** so it handled in separate.
598
*/
599
static int block_follow (LexState *ls, int withuntil) {
600
  switch (ls->t.token) {
601
    case TK_ELSE: case TK_ELSEIF:
602
    case TK_END: case TK_EOS:
603
      return 1;
604
    case TK_UNTIL: return withuntil;
605
    default: return 0;
606
  }
607
}
608
 
609
 
610
static void statlist (LexState *ls) {
611
  /* statlist -> { stat [`;'] } */
612
  while (!block_follow(ls, 1)) {
613
    if (ls->t.token == TK_RETURN) {
614
      statement(ls);
615
      return;  /* 'return' must be last statement */
616
    }
617
    statement(ls);
618
  }
619
}
620
 
621
 
622
static void fieldsel (LexState *ls, expdesc *v) {
623
  /* fieldsel -> ['.' | ':'] NAME */
624
  FuncState *fs = ls->fs;
625
  expdesc key;
626
  luaK_exp2anyregup(fs, v);
627
  luaX_next(ls);  /* skip the dot or colon */
628
  checkname(ls, &key);
629
  luaK_indexed(fs, v, &key);
630
}
631
 
632
 
633
static void yindex (LexState *ls, expdesc *v) {
634
  /* index -> '[' expr ']' */
635
  luaX_next(ls);  /* skip the '[' */
636
  expr(ls, v);
637
  luaK_exp2val(ls->fs, v);
638
  checknext(ls, ']');
639
}
640
 
641
 
642
/*
643
** {======================================================================
644
** Rules for Constructors
645
** =======================================================================
646
*/
647
 
648
 
649
struct ConsControl {
650
  expdesc v;  /* last list item read */
651
  expdesc *t;  /* table descriptor */
652
  int nh;  /* total number of `record' elements */
653
  int na;  /* total number of array elements */
654
  int tostore;  /* number of array elements pending to be stored */
655
};
656
 
657
 
658
static void recfield (LexState *ls, struct ConsControl *cc) {
659
  /* recfield -> (NAME | `['exp1`]') = exp1 */
660
  FuncState *fs = ls->fs;
661
  int reg = ls->fs->freereg;
662
  expdesc key, val;
663
  int rkkey;
664
  if (ls->t.token == TK_NAME) {
665
    checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
666
    checkname(ls, &key);
667
  }
668
  else  /* ls->t.token == '[' */
669
    yindex(ls, &key);
670
  cc->nh++;
671
  checknext(ls, '=');
672
  rkkey = luaK_exp2RK(fs, &key);
673
  expr(ls, &val);
674
  luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val));
675
  fs->freereg = reg;  /* free registers */
676
}
677
 
678
 
679
static void closelistfield (FuncState *fs, struct ConsControl *cc) {
680
  if (cc->v.k == VVOID) return;  /* there is no list item */
681
  luaK_exp2nextreg(fs, &cc->v);
682
  cc->v.k = VVOID;
683
  if (cc->tostore == LFIELDS_PER_FLUSH) {
684
    luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);  /* flush */
685
    cc->tostore = 0;  /* no more items pending */
686
  }
687
}
688
 
689
 
690
static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
691
  if (cc->tostore == 0) return;
692
  if (hasmultret(cc->v.k)) {
693
    luaK_setmultret(fs, &cc->v);
694
    luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
695
    cc->na--;  /* do not count last expression (unknown number of elements) */
696
  }
697
  else {
698
    if (cc->v.k != VVOID)
699
      luaK_exp2nextreg(fs, &cc->v);
700
    luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
701
  }
702
}
703
 
704
 
705
static void listfield (LexState *ls, struct ConsControl *cc) {
706
  /* listfield -> exp */
707
  expr(ls, &cc->v);
708
  checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
709
  cc->na++;
710
  cc->tostore++;
711
}
712
 
713
 
714
static void field (LexState *ls, struct ConsControl *cc) {
715
  /* field -> listfield | recfield */
716
  switch(ls->t.token) {
717
    case TK_NAME: {  /* may be 'listfield' or 'recfield' */
718
      if (luaX_lookahead(ls) != '=')  /* expression? */
719
        listfield(ls, cc);
720
      else
721
        recfield(ls, cc);
722
      break;
723
    }
724
    case '[': {
725
      recfield(ls, cc);
726
      break;
727
    }
728
    default: {
729
      listfield(ls, cc);
730
      break;
731
    }
732
  }
733
}
734
 
735
 
736
static void constructor (LexState *ls, expdesc *t) {
737
  /* constructor -> '{' [ field { sep field } [sep] ] '}'
738
     sep -> ',' | ';' */
739
  FuncState *fs = ls->fs;
740
  int line = ls->linenumber;
741
  int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
742
  struct ConsControl cc;
743
  cc.na = cc.nh = cc.tostore = 0;
744
  cc.t = t;
745
  init_exp(t, VRELOCABLE, pc);
746
  init_exp(&cc.v, VVOID, 0);  /* no value (yet) */
747
  luaK_exp2nextreg(ls->fs, t);  /* fix it at stack top */
748
  checknext(ls, '{');
749
  do {
750
    lua_assert(cc.v.k == VVOID || cc.tostore > 0);
751
    if (ls->t.token == '}') break;
752
    closelistfield(fs, &cc);
753
    field(ls, &cc);
754
  } while (testnext(ls, ',') || testnext(ls, ';'));
755
  check_match(ls, '}', '{', line);
756
  lastlistfield(fs, &cc);
757
  SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
758
  SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh));  /* set initial table size */
759
}
760
 
761
/* }====================================================================== */
762
 
763
 
764
 
765
static void parlist (LexState *ls) {
766
  /* parlist -> [ param { `,' param } ] */
767
  FuncState *fs = ls->fs;
768
  Proto *f = fs->f;
769
  int nparams = 0;
770
  f->is_vararg = 0;
771
  if (ls->t.token != ')') {  /* is `parlist' not empty? */
772
    do {
773
      switch (ls->t.token) {
774
        case TK_NAME: {  /* param -> NAME */
775
          new_localvar(ls, str_checkname(ls));
776
          nparams++;
777
          break;
778
        }
779
        case TK_DOTS: {  /* param -> `...' */
780
          luaX_next(ls);
781
          f->is_vararg = 1;
782
          break;
783
        }
784
        default: luaX_syntaxerror(ls, " or " LUA_QL("...") " expected");
785
      }
786
    } while (!f->is_vararg && testnext(ls, ','));
787
  }
788
  adjustlocalvars(ls, nparams);
789
  f->numparams = cast_byte(fs->nactvar);
790
  luaK_reserveregs(fs, fs->nactvar);  /* reserve register for parameters */
791
}
792
 
793
 
794
static void body (LexState *ls, expdesc *e, int ismethod, int line) {
795
  /* body ->  `(' parlist `)' block END */
796
  FuncState new_fs;
797
  BlockCnt bl;
798
  open_func(ls, &new_fs, &bl);
799
  new_fs.f->linedefined = line;
800
  checknext(ls, '(');
801
  if (ismethod) {
802
    new_localvarliteral(ls, "self");  /* create 'self' parameter */
803
    adjustlocalvars(ls, 1);
804
  }
805
  parlist(ls);
806
  checknext(ls, ')');
807
  statlist(ls);
808
  new_fs.f->lastlinedefined = ls->linenumber;
809
  check_match(ls, TK_END, TK_FUNCTION, line);
810
  codeclosure(ls, new_fs.f, e);
811
  close_func(ls);
812
}
813
 
814
 
815
static int explist (LexState *ls, expdesc *v) {
816
  /* explist -> expr { `,' expr } */
817
  int n = 1;  /* at least one expression */
818
  expr(ls, v);
819
  while (testnext(ls, ',')) {
820
    luaK_exp2nextreg(ls->fs, v);
821
    expr(ls, v);
822
    n++;
823
  }
824
  return n;
825
}
826
 
827
 
828
static void funcargs (LexState *ls, expdesc *f, int line) {
829
  FuncState *fs = ls->fs;
830
  expdesc args;
831
  int base, nparams;
832
  switch (ls->t.token) {
833
    case '(': {  /* funcargs -> `(' [ explist ] `)' */
834
      luaX_next(ls);
835
      if (ls->t.token == ')')  /* arg list is empty? */
836
        args.k = VVOID;
837
      else {
838
        explist(ls, &args);
839
        luaK_setmultret(fs, &args);
840
      }
841
      check_match(ls, ')', '(', line);
842
      break;
843
    }
844
    case '{': {  /* funcargs -> constructor */
845
      constructor(ls, &args);
846
      break;
847
    }
848
    case TK_STRING: {  /* funcargs -> STRING */
849
      codestring(ls, &args, ls->t.seminfo.ts);
850
      luaX_next(ls);  /* must use `seminfo' before `next' */
851
      break;
852
    }
853
    default: {
854
      luaX_syntaxerror(ls, "function arguments expected");
855
    }
856
  }
857
  lua_assert(f->k == VNONRELOC);
858
  base = f->u.info;  /* base register for call */
859
  if (hasmultret(args.k))
860
    nparams = LUA_MULTRET;  /* open call */
861
  else {
862
    if (args.k != VVOID)
863
      luaK_exp2nextreg(fs, &args);  /* close last argument */
864
    nparams = fs->freereg - (base+1);
865
  }
866
  init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
867
  luaK_fixline(fs, line);
868
  fs->freereg = base+1;  /* call remove function and arguments and leaves
869
                            (unless changed) one result */
870
}
871
 
872
 
873
 
874
 
875
/*
876
** {======================================================================
877
** Expression parsing
878
** =======================================================================
879
*/
880
 
881
 
882
static void prefixexp (LexState *ls, expdesc *v) {
883
  /* prefixexp -> NAME | '(' expr ')' */
884
  switch (ls->t.token) {
885
    case '(': {
886
      int line = ls->linenumber;
887
      luaX_next(ls);
888
      expr(ls, v);
889
      check_match(ls, ')', '(', line);
890
      luaK_dischargevars(ls->fs, v);
891
      return;
892
    }
893
    case TK_NAME: {
894
      singlevar(ls, v);
895
      return;
896
    }
897
    default: {
898
      luaX_syntaxerror(ls, "unexpected symbol");
899
    }
900
  }
901
}
902
 
903
 
904
static void primaryexp (LexState *ls, expdesc *v) {
905
  /* primaryexp ->
906
        prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
907
  FuncState *fs = ls->fs;
908
  int line = ls->linenumber;
909
  prefixexp(ls, v);
910
  for (;;) {
911
    switch (ls->t.token) {
912
      case '.': {  /* fieldsel */
913
        fieldsel(ls, v);
914
        break;
915
      }
916
      case '[': {  /* `[' exp1 `]' */
917
        expdesc key;
918
        luaK_exp2anyregup(fs, v);
919
        yindex(ls, &key);
920
        luaK_indexed(fs, v, &key);
921
        break;
922
      }
923
      case ':': {  /* `:' NAME funcargs */
924
        expdesc key;
925
        luaX_next(ls);
926
        checkname(ls, &key);
927
        luaK_self(fs, v, &key);
928
        funcargs(ls, v, line);
929
        break;
930
      }
931
      case '(': case TK_STRING: case '{': {  /* funcargs */
932
        luaK_exp2nextreg(fs, v);
933
        funcargs(ls, v, line);
934
        break;
935
      }
936
      default: return;
937
    }
938
  }
939
}
940
 
941
 
942
static void simpleexp (LexState *ls, expdesc *v) {
943
  /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
944
                  constructor | FUNCTION body | primaryexp */
945
  switch (ls->t.token) {
946
    case TK_NUMBER: {
947
      init_exp(v, VKNUM, 0);
948
      v->u.nval = ls->t.seminfo.r;
949
      break;
950
    }
951
    case TK_STRING: {
952
      codestring(ls, v, ls->t.seminfo.ts);
953
      break;
954
    }
955
    case TK_NIL: {
956
      init_exp(v, VNIL, 0);
957
      break;
958
    }
959
    case TK_TRUE: {
960
      init_exp(v, VTRUE, 0);
961
      break;
962
    }
963
    case TK_FALSE: {
964
      init_exp(v, VFALSE, 0);
965
      break;
966
    }
967
    case TK_DOTS: {  /* vararg */
968
      FuncState *fs = ls->fs;
969
      check_condition(ls, fs->f->is_vararg,
970
                      "cannot use " LUA_QL("...") " outside a vararg function");
971
      init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
972
      break;
973
    }
974
    case '{': {  /* constructor */
975
      constructor(ls, v);
976
      return;
977
    }
978
    case TK_FUNCTION: {
979
      luaX_next(ls);
980
      body(ls, v, 0, ls->linenumber);
981
      return;
982
    }
983
    default: {
984
      primaryexp(ls, v);
985
      return;
986
    }
987
  }
988
  luaX_next(ls);
989
}
990
 
991
 
992
static UnOpr getunopr (int op) {
993
  switch (op) {
994
    case TK_NOT: return OPR_NOT;
995
    case '-': return OPR_MINUS;
996
    case '#': return OPR_LEN;
997
    default: return OPR_NOUNOPR;
998
  }
999
}
1000
 
1001
 
1002
static BinOpr getbinopr (int op) {
1003
  switch (op) {
1004
    case '+': return OPR_ADD;
1005
    case '-': return OPR_SUB;
1006
    case '*': return OPR_MUL;
1007
    case '/': return OPR_DIV;
1008
    case '%': return OPR_MOD;
1009
    case '^': return OPR_POW;
1010
    case TK_CONCAT: return OPR_CONCAT;
1011
    case TK_NE: return OPR_NE;
1012
    case TK_EQ: return OPR_EQ;
1013
    case '<': return OPR_LT;
1014
    case TK_LE: return OPR_LE;
1015
    case '>': return OPR_GT;
1016
    case TK_GE: return OPR_GE;
1017
    case TK_AND: return OPR_AND;
1018
    case TK_OR: return OPR_OR;
1019
    default: return OPR_NOBINOPR;
1020
  }
1021
}
1022
 
1023
 
1024
static const struct {
1025
  lu_byte left;  /* left priority for each binary operator */
1026
  lu_byte right; /* right priority */
1027
} priority[] = {  /* ORDER OPR */
1028
   {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7},  /* `+' `-' `*' `/' `%' */
1029
   {10, 9}, {5, 4},                 /* ^, .. (right associative) */
1030
   {3, 3}, {3, 3}, {3, 3},          /* ==, <, <= */
1031
   {3, 3}, {3, 3}, {3, 3},          /* ~=, >, >= */
1032
   {2, 2}, {1, 1}                   /* and, or */
1033
};
1034
 
1035
#define UNARY_PRIORITY	8  /* priority for unary operators */
1036
 
1037
 
1038
/*
1039
** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1040
** where `binop' is any binary operator with a priority higher than `limit'
1041
*/
1042
static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
1043
  BinOpr op;
1044
  UnOpr uop;
1045
  enterlevel(ls);
1046
  uop = getunopr(ls->t.token);
1047
  if (uop != OPR_NOUNOPR) {
1048
    int line = ls->linenumber;
1049
    luaX_next(ls);
1050
    subexpr(ls, v, UNARY_PRIORITY);
1051
    luaK_prefix(ls->fs, uop, v, line);
1052
  }
1053
  else simpleexp(ls, v);
1054
  /* expand while operators have priorities higher than `limit' */
1055
  op = getbinopr(ls->t.token);
1056
  while (op != OPR_NOBINOPR && priority[op].left > limit) {
1057
    expdesc v2;
1058
    BinOpr nextop;
1059
    int line = ls->linenumber;
1060
    luaX_next(ls);
1061
    luaK_infix(ls->fs, op, v);
1062
    /* read sub-expression with higher priority */
1063
    nextop = subexpr(ls, &v2, priority[op].right);
1064
    luaK_posfix(ls->fs, op, v, &v2, line);
1065
    op = nextop;
1066
  }
1067
  leavelevel(ls);
1068
  return op;  /* return first untreated operator */
1069
}
1070
 
1071
 
1072
static void expr (LexState *ls, expdesc *v) {
1073
  subexpr(ls, v, 0);
1074
}
1075
 
1076
/* }==================================================================== */
1077
 
1078
 
1079
 
1080
/*
1081
** {======================================================================
1082
** Rules for Statements
1083
** =======================================================================
1084
*/
1085
 
1086
 
1087
static void block (LexState *ls) {
1088
  /* block -> statlist */
1089
  FuncState *fs = ls->fs;
1090
  BlockCnt bl;
1091
  enterblock(fs, &bl, 0);
1092
  statlist(ls);
1093
  leaveblock(fs);
1094
}
1095
 
1096
 
1097
/*
1098
** structure to chain all variables in the left-hand side of an
1099
** assignment
1100
*/
1101
struct LHS_assign {
1102
  struct LHS_assign *prev;
1103
  expdesc v;  /* variable (global, local, upvalue, or indexed) */
1104
};
1105
 
1106
 
1107
/*
1108
** check whether, in an assignment to an upvalue/local variable, the
1109
** upvalue/local variable is begin used in a previous assignment to a
1110
** table. If so, save original upvalue/local value in a safe place and
1111
** use this safe copy in the previous assignment.
1112
*/
1113
static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
1114
  FuncState *fs = ls->fs;
1115
  int extra = fs->freereg;  /* eventual position to save local variable */
1116
  int conflict = 0;
1117
  for (; lh; lh = lh->prev) {  /* check all previous assignments */
1118
    if (lh->v.k == VINDEXED) {  /* assigning to a table? */
1119
      /* table is the upvalue/local being assigned now? */
1120
      if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {
1121
        conflict = 1;
1122
        lh->v.u.ind.vt = VLOCAL;
1123
        lh->v.u.ind.t = extra;  /* previous assignment will use safe copy */
1124
      }
1125
      /* index is the local being assigned? (index cannot be upvalue) */
1126
      if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {
1127
        conflict = 1;
1128
        lh->v.u.ind.idx = extra;  /* previous assignment will use safe copy */
1129
      }
1130
    }
1131
  }
1132
  if (conflict) {
1133
    /* copy upvalue/local value to a temporary (in position 'extra') */
1134
    OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
1135
    luaK_codeABC(fs, op, extra, v->u.info, 0);
1136
    luaK_reserveregs(fs, 1);
1137
  }
1138
}
1139
 
1140
 
1141
static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
1142
  expdesc e;
1143
  check_condition(ls, vkisvar(lh->v.k), "syntax error");
1144
  if (testnext(ls, ',')) {  /* assignment -> `,' primaryexp assignment */
1145
    struct LHS_assign nv;
1146
    nv.prev = lh;
1147
    primaryexp(ls, &nv.v);
1148
    if (nv.v.k != VINDEXED)
1149
      check_conflict(ls, lh, &nv.v);
1150
    checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,
1151
                    "C levels");
1152
    assignment(ls, &nv, nvars+1);
1153
  }
1154
  else {  /* assignment -> `=' explist */
1155
    int nexps;
1156
    checknext(ls, '=');
1157
    nexps = explist(ls, &e);
1158
    if (nexps != nvars) {
1159
      adjust_assign(ls, nvars, nexps, &e);
1160
      if (nexps > nvars)
1161
        ls->fs->freereg -= nexps - nvars;  /* remove extra values */
1162
    }
1163
    else {
1164
      luaK_setoneret(ls->fs, &e);  /* close last expression */
1165
      luaK_storevar(ls->fs, &lh->v, &e);
1166
      return;  /* avoid default */
1167
    }
1168
  }
1169
  init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */
1170
  luaK_storevar(ls->fs, &lh->v, &e);
1171
}
1172
 
1173
 
1174
static int cond (LexState *ls) {
1175
  /* cond -> exp */
1176
  expdesc v;
1177
  expr(ls, &v);  /* read condition */
1178
  if (v.k == VNIL) v.k = VFALSE;  /* `falses' are all equal here */
1179
  luaK_goiftrue(ls->fs, &v);
1180
  return v.f;
1181
}
1182
 
1183
 
1184
static void gotostat (LexState *ls, int pc) {
1185
  int line = ls->linenumber;
1186
  TString *label;
1187
  int g;
1188
  if (testnext(ls, TK_GOTO))
1189
    label = str_checkname(ls);
1190
  else {
1191
    luaX_next(ls);  /* skip break */
1192
    label = luaS_new(ls->L, "break");
1193
  }
1194
  g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);
1195
  findlabel(ls, g);  /* close it if label already defined */
1196
}
1197
 
1198
 
1199
/* check for repeated labels on the same block */
1200
static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
1201
  int i;
1202
  for (i = fs->bl->firstlabel; i < ll->n; i++) {
1203
    if (eqstr(label, ll->arr[i].name)) {
1204
      const char *msg = luaO_pushfstring(fs->ls->L,
1205
                          "label " LUA_QS " already defined on line %d",
1206
                          getstr(label), ll->arr[i].line);
1207
      semerror(fs->ls, msg);
1208
    }
1209
  }
1210
}
1211
 
1212
 
1213
static void labelstat (LexState *ls, TString *label, int line) {
1214
  /* label -> '::' NAME '::' */
1215
  FuncState *fs = ls->fs;
1216
  Labellist *ll = &ls->dyd->label;
1217
  int l;  /* index of new label being created */
1218
  checkrepeated(fs, ll, label);  /* check for repeated labels */
1219
  checknext(ls, TK_DBCOLON);  /* skip double colon */
1220
  /* create new entry for this label */
1221
  l = newlabelentry(ls, ll, label, line, fs->pc);
1222
  /* skip other no-op statements */
1223
  while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
1224
    statement(ls);
1225
  if (block_follow(ls, 0)) {  /* label is last no-op statement in the block? */
1226
    /* assume that locals are already out of scope */
1227
    ll->arr[l].nactvar = fs->bl->nactvar;
1228
  }
1229
  findgotos(ls, &ll->arr[l]);
1230
}
1231
 
1232
 
1233
static void whilestat (LexState *ls, int line) {
1234
  /* whilestat -> WHILE cond DO block END */
1235
  FuncState *fs = ls->fs;
1236
  int whileinit;
1237
  int condexit;
1238
  BlockCnt bl;
1239
  luaX_next(ls);  /* skip WHILE */
1240
  whileinit = luaK_getlabel(fs);
1241
  condexit = cond(ls);
1242
  enterblock(fs, &bl, 1);
1243
  checknext(ls, TK_DO);
1244
  block(ls);
1245
  luaK_jumpto(fs, whileinit);
1246
  check_match(ls, TK_END, TK_WHILE, line);
1247
  leaveblock(fs);
1248
  luaK_patchtohere(fs, condexit);  /* false conditions finish the loop */
1249
}
1250
 
1251
 
1252
static void repeatstat (LexState *ls, int line) {
1253
  /* repeatstat -> REPEAT block UNTIL cond */
1254
  int condexit;
1255
  FuncState *fs = ls->fs;
1256
  int repeat_init = luaK_getlabel(fs);
1257
  BlockCnt bl1, bl2;
1258
  enterblock(fs, &bl1, 1);  /* loop block */
1259
  enterblock(fs, &bl2, 0);  /* scope block */
1260
  luaX_next(ls);  /* skip REPEAT */
1261
  statlist(ls);
1262
  check_match(ls, TK_UNTIL, TK_REPEAT, line);
1263
  condexit = cond(ls);  /* read condition (inside scope block) */
1264
  if (bl2.upval)  /* upvalues? */
1265
    luaK_patchclose(fs, condexit, bl2.nactvar);
1266
  leaveblock(fs);  /* finish scope */
1267
  luaK_patchlist(fs, condexit, repeat_init);  /* close the loop */
1268
  leaveblock(fs);  /* finish loop */
1269
}
1270
 
1271
 
1272
static int exp1 (LexState *ls) {
1273
  expdesc e;
1274
  int reg;
1275
  expr(ls, &e);
1276
  luaK_exp2nextreg(ls->fs, &e);
1277
  lua_assert(e.k == VNONRELOC);
1278
  reg = e.u.info;
1279
  return reg;
1280
}
1281
 
1282
 
1283
static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1284
  /* forbody -> DO block */
1285
  BlockCnt bl;
1286
  FuncState *fs = ls->fs;
1287
  int prep, endfor;
1288
  adjustlocalvars(ls, 3);  /* control variables */
1289
  checknext(ls, TK_DO);
1290
  prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1291
  enterblock(fs, &bl, 0);  /* scope for declared variables */
1292
  adjustlocalvars(ls, nvars);
1293
  luaK_reserveregs(fs, nvars);
1294
  block(ls);
1295
  leaveblock(fs);  /* end of scope for declared variables */
1296
  luaK_patchtohere(fs, prep);
1297
  if (isnum)  /* numeric for? */
1298
    endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
1299
  else {  /* generic for */
1300
    luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
1301
    luaK_fixline(fs, line);
1302
    endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
1303
  }
1304
  luaK_patchlist(fs, endfor, prep + 1);
1305
  luaK_fixline(fs, line);
1306
}
1307
 
1308
 
1309
static void fornum (LexState *ls, TString *varname, int line) {
1310
  /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1311
  FuncState *fs = ls->fs;
1312
  int base = fs->freereg;
1313
  new_localvarliteral(ls, "(for index)");
1314
  new_localvarliteral(ls, "(for limit)");
1315
  new_localvarliteral(ls, "(for step)");
1316
  new_localvar(ls, varname);
1317
  checknext(ls, '=');
1318
  exp1(ls);  /* initial value */
1319
  checknext(ls, ',');
1320
  exp1(ls);  /* limit */
1321
  if (testnext(ls, ','))
1322
    exp1(ls);  /* optional step */
1323
  else {  /* default step = 1 */
1324
    luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1));
1325
    luaK_reserveregs(fs, 1);
1326
  }
1327
  forbody(ls, base, line, 1, 1);
1328
}
1329
 
1330
 
1331
static void forlist (LexState *ls, TString *indexname) {
1332
  /* forlist -> NAME {,NAME} IN explist forbody */
1333
  FuncState *fs = ls->fs;
1334
  expdesc e;
1335
  int nvars = 4;  /* gen, state, control, plus at least one declared var */
1336
  int line;
1337
  int base = fs->freereg;
1338
  /* create control variables */
1339
  new_localvarliteral(ls, "(for generator)");
1340
  new_localvarliteral(ls, "(for state)");
1341
  new_localvarliteral(ls, "(for control)");
1342
  /* create declared variables */
1343
  new_localvar(ls, indexname);
1344
  while (testnext(ls, ',')) {
1345
    new_localvar(ls, str_checkname(ls));
1346
    nvars++;
1347
  }
1348
  checknext(ls, TK_IN);
1349
  line = ls->linenumber;
1350
  adjust_assign(ls, 3, explist(ls, &e), &e);
1351
  luaK_checkstack(fs, 3);  /* extra space to call generator */
1352
  forbody(ls, base, line, nvars - 3, 0);
1353
}
1354
 
1355
 
1356
static void forstat (LexState *ls, int line) {
1357
  /* forstat -> FOR (fornum | forlist) END */
1358
  FuncState *fs = ls->fs;
1359
  TString *varname;
1360
  BlockCnt bl;
1361
  enterblock(fs, &bl, 1);  /* scope for loop and control variables */
1362
  luaX_next(ls);  /* skip `for' */
1363
  varname = str_checkname(ls);  /* first variable name */
1364
  switch (ls->t.token) {
1365
    case '=': fornum(ls, varname, line); break;
1366
    case ',': case TK_IN: forlist(ls, varname); break;
1367
    default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
1368
  }
1369
  check_match(ls, TK_END, TK_FOR, line);
1370
  leaveblock(fs);  /* loop scope (`break' jumps to this point) */
1371
}
1372
 
1373
 
1374
static void test_then_block (LexState *ls, int *escapelist) {
1375
  /* test_then_block -> [IF | ELSEIF] cond THEN block */
1376
  BlockCnt bl;
1377
  FuncState *fs = ls->fs;
1378
  expdesc v;
1379
  int jf;  /* instruction to skip 'then' code (if condition is false) */
1380
  luaX_next(ls);  /* skip IF or ELSEIF */
1381
  expr(ls, &v);  /* read condition */
1382
  checknext(ls, TK_THEN);
1383
  if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
1384
    luaK_goiffalse(ls->fs, &v);  /* will jump to label if condition is true */
1385
    enterblock(fs, &bl, 0);  /* must enter block before 'goto' */
1386
    gotostat(ls, v.t);  /* handle goto/break */
1387
    if (block_follow(ls, 0)) {  /* 'goto' is the entire block? */
1388
      leaveblock(fs);
1389
      return;  /* and that is it */
1390
    }
1391
    else  /* must skip over 'then' part if condition is false */
1392
      jf = luaK_jump(fs);
1393
  }
1394
  else {  /* regular case (not goto/break) */
1395
    luaK_goiftrue(ls->fs, &v);  /* skip over block if condition is false */
1396
    enterblock(fs, &bl, 0);
1397
    jf = v.f;
1398
  }
1399
  statlist(ls);  /* `then' part */
1400
  leaveblock(fs);
1401
  if (ls->t.token == TK_ELSE ||
1402
      ls->t.token == TK_ELSEIF)  /* followed by 'else'/'elseif'? */
1403
    luaK_concat(fs, escapelist, luaK_jump(fs));  /* must jump over it */
1404
  luaK_patchtohere(fs, jf);
1405
}
1406
 
1407
 
1408
static void ifstat (LexState *ls, int line) {
1409
  /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1410
  FuncState *fs = ls->fs;
1411
  int escapelist = NO_JUMP;  /* exit list for finished parts */
1412
  test_then_block(ls, &escapelist);  /* IF cond THEN block */
1413
  while (ls->t.token == TK_ELSEIF)
1414
    test_then_block(ls, &escapelist);  /* ELSEIF cond THEN block */
1415
  if (testnext(ls, TK_ELSE))
1416
    block(ls);  /* `else' part */
1417
  check_match(ls, TK_END, TK_IF, line);
1418
  luaK_patchtohere(fs, escapelist);  /* patch escape list to 'if' end */
1419
}
1420
 
1421
 
1422
static void localfunc (LexState *ls) {
1423
  expdesc b;
1424
  FuncState *fs = ls->fs;
1425
  new_localvar(ls, str_checkname(ls));  /* new local variable */
1426
  adjustlocalvars(ls, 1);  /* enter its scope */
1427
  body(ls, &b, 0, ls->linenumber);  /* function created in next register */
1428
  /* debug information will only see the variable after this point! */
1429
  getlocvar(fs, b.u.info)->startpc = fs->pc;
1430
}
1431
 
1432
 
1433
static void localstat (LexState *ls) {
1434
  /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
1435
  int nvars = 0;
1436
  int nexps;
1437
  expdesc e;
1438
  do {
1439
    new_localvar(ls, str_checkname(ls));
1440
    nvars++;
1441
  } while (testnext(ls, ','));
1442
  if (testnext(ls, '='))
1443
    nexps = explist(ls, &e);
1444
  else {
1445
    e.k = VVOID;
1446
    nexps = 0;
1447
  }
1448
  adjust_assign(ls, nvars, nexps, &e);
1449
  adjustlocalvars(ls, nvars);
1450
}
1451
 
1452
 
1453
static int funcname (LexState *ls, expdesc *v) {
1454
  /* funcname -> NAME {fieldsel} [`:' NAME] */
1455
  int ismethod = 0;
1456
  singlevar(ls, v);
1457
  while (ls->t.token == '.')
1458
    fieldsel(ls, v);
1459
  if (ls->t.token == ':') {
1460
    ismethod = 1;
1461
    fieldsel(ls, v);
1462
  }
1463
  return ismethod;
1464
}
1465
 
1466
 
1467
static void funcstat (LexState *ls, int line) {
1468
  /* funcstat -> FUNCTION funcname body */
1469
  int ismethod;
1470
  expdesc v, b;
1471
  luaX_next(ls);  /* skip FUNCTION */
1472
  ismethod = funcname(ls, &v);
1473
  body(ls, &b, ismethod, line);
1474
  luaK_storevar(ls->fs, &v, &b);
1475
  luaK_fixline(ls->fs, line);  /* definition `happens' in the first line */
1476
}
1477
 
1478
 
1479
static void exprstat (LexState *ls) {
1480
  /* stat -> func | assignment */
1481
  FuncState *fs = ls->fs;
1482
  struct LHS_assign v;
1483
  primaryexp(ls, &v.v);
1484
  if (v.v.k == VCALL)  /* stat -> func */
1485
    SETARG_C(getcode(fs, &v.v), 1);  /* call statement uses no results */
1486
  else {  /* stat -> assignment */
1487
    v.prev = NULL;
1488
    assignment(ls, &v, 1);
1489
  }
1490
}
1491
 
1492
 
1493
static void retstat (LexState *ls) {
1494
  /* stat -> RETURN [explist] [';'] */
1495
  FuncState *fs = ls->fs;
1496
  expdesc e;
1497
  int first, nret;  /* registers with returned values */
1498
  if (block_follow(ls, 1) || ls->t.token == ';')
1499
    first = nret = 0;  /* return no values */
1500
  else {
1501
    nret = explist(ls, &e);  /* optional return values */
1502
    if (hasmultret(e.k)) {
1503
      luaK_setmultret(fs, &e);
1504
      if (e.k == VCALL && nret == 1) {  /* tail call? */
1505
        SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1506
        lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1507
      }
1508
      first = fs->nactvar;
1509
      nret = LUA_MULTRET;  /* return all values */
1510
    }
1511
    else {
1512
      if (nret == 1)  /* only one single value? */
1513
        first = luaK_exp2anyreg(fs, &e);
1514
      else {
1515
        luaK_exp2nextreg(fs, &e);  /* values must go to the `stack' */
1516
        first = fs->nactvar;  /* return all `active' values */
1517
        lua_assert(nret == fs->freereg - first);
1518
      }
1519
    }
1520
  }
1521
  luaK_ret(fs, first, nret);
1522
  testnext(ls, ';');  /* skip optional semicolon */
1523
}
1524
 
1525
 
1526
static void statement (LexState *ls) {
1527
  int line = ls->linenumber;  /* may be needed for error messages */
1528
  enterlevel(ls);
1529
  switch (ls->t.token) {
1530
    case ';': {  /* stat -> ';' (empty statement) */
1531
      luaX_next(ls);  /* skip ';' */
1532
      break;
1533
    }
1534
    case TK_IF: {  /* stat -> ifstat */
1535
      ifstat(ls, line);
1536
      break;
1537
    }
1538
    case TK_WHILE: {  /* stat -> whilestat */
1539
      whilestat(ls, line);
1540
      break;
1541
    }
1542
    case TK_DO: {  /* stat -> DO block END */
1543
      luaX_next(ls);  /* skip DO */
1544
      block(ls);
1545
      check_match(ls, TK_END, TK_DO, line);
1546
      break;
1547
    }
1548
    case TK_FOR: {  /* stat -> forstat */
1549
      forstat(ls, line);
1550
      break;
1551
    }
1552
    case TK_REPEAT: {  /* stat -> repeatstat */
1553
      repeatstat(ls, line);
1554
      break;
1555
    }
1556
    case TK_FUNCTION: {  /* stat -> funcstat */
1557
      funcstat(ls, line);
1558
      break;
1559
    }
1560
    case TK_LOCAL: {  /* stat -> localstat */
1561
      luaX_next(ls);  /* skip LOCAL */
1562
      if (testnext(ls, TK_FUNCTION))  /* local function? */
1563
        localfunc(ls);
1564
      else
1565
        localstat(ls);
1566
      break;
1567
    }
1568
    case TK_DBCOLON: {  /* stat -> label */
1569
      luaX_next(ls);  /* skip double colon */
1570
      labelstat(ls, str_checkname(ls), line);
1571
      break;
1572
    }
1573
    case TK_RETURN: {  /* stat -> retstat */
1574
      luaX_next(ls);  /* skip RETURN */
1575
      retstat(ls);
1576
      break;
1577
    }
1578
    case TK_BREAK:   /* stat -> breakstat */
1579
    case TK_GOTO: {  /* stat -> 'goto' NAME */
1580
      gotostat(ls, luaK_jump(ls->fs));
1581
      break;
1582
    }
1583
    default: {  /* stat -> func | assignment */
1584
      exprstat(ls);
1585
      break;
1586
    }
1587
  }
1588
  lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1589
             ls->fs->freereg >= ls->fs->nactvar);
1590
  ls->fs->freereg = ls->fs->nactvar;  /* free registers */
1591
  leavelevel(ls);
1592
}
1593
 
1594
/* }====================================================================== */
1595
 
1596
 
1597
Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1598
                    Dyndata *dyd, const char *name, int firstchar) {
1599
  LexState lexstate;
1600
  FuncState funcstate;
1601
  BlockCnt bl;
1602
  TString *tname = luaS_new(L, name);
1603
  setsvalue2s(L, L->top, tname);  /* push name to protect it */
1604
  incr_top(L);
1605
  lexstate.buff = buff;
1606
  lexstate.dyd = dyd;
1607
  dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
1608
  luaX_setinput(L, &lexstate, z, tname, firstchar);
1609
  open_mainfunc(&lexstate, &funcstate, &bl);
1610
  luaX_next(&lexstate);  /* read first token */
1611
  statlist(&lexstate);  /* main body */
1612
  check(&lexstate, TK_EOS);
1613
  close_func(&lexstate);
1614
  L->top--;  /* pop name */
1615
  lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
1616
  /* all scopes should be correctly finished */
1617
  lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
1618
  return funcstate.f;
1619
}
1620