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