1 /*
2 ** $Id: lparser.c,v 2.147 2014/12/27 20:31:43 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 */
semerror(LexState * ls,const char * msg)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
error_expected(LexState * ls,int token)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
errorlimit(FuncState * fs,int limit,const char * what)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
checklimit(FuncState * fs,int v,int l,const char * what)92 static void checklimit (FuncState *fs, int v, int l, const char *what) {
93 if (v > l) errorlimit(fs, l, what);
94 }
95
96
testnext(LexState * ls,int c)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
check(LexState * ls,int c)106 static void check (LexState *ls, int c) {
107 if (ls->t.token != c)
108 error_expected(ls, c);
109 }
110
111
checknext(LexState * ls,int c)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
check_match(LexState * ls,int what,int who,int where)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
str_checkname(LexState * ls)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
init_exp(expdesc * e,expkind k,int i)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
codestring(LexState * ls,expdesc * e,TString * s)151 static void codestring (LexState *ls, expdesc *e, TString *s) {
152 init_exp(e, VK, luaK_stringK(ls->fs, s));
153 }
154
155
checkname(LexState * ls,expdesc * e)156 static void checkname (LexState *ls, expdesc *e) {
157 codestring(ls, e, str_checkname(ls));
158 }
159
160
registerlocalvar(LexState * ls,TString * varname)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
new_localvar(LexState * ls,TString * name)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
new_localvarliteral_(LexState * ls,const char * name,size_t sz)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
getlocvar(FuncState * fs,int i)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
adjustlocalvars(LexState * ls,int nvars)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
removevars(FuncState * fs,int tolevel)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
searchupvalue(FuncState * fs,TString * name)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
newupvalue(FuncState * fs,TString * name,expdesc * v)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
searchvar(FuncState * fs,TString * n)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 */
markupval(FuncState * fs,int level)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 */
singlevaraux(FuncState * fs,TString * n,expdesc * var,int base)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
singlevar(LexState * ls,expdesc * var)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
adjust_assign(LexState * ls,int nvars,int nexps,expdesc * e)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
enterlevel(LexState * ls)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
closegoto(LexState * ls,int g,Labeldesc * label)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 */
findlabel(LexState * ls,int g)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
newlabelentry(LexState * ls,Labellist * l,TString * name,int line,int pc)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 */
findgotos(LexState * ls,Labeldesc * lb)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 */
movegotosout(FuncState * fs,BlockCnt * bl)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
enterblock(FuncState * fs,BlockCnt * bl,lu_byte isloop)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 */
breaklabel(LexState * ls)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 */
undefgoto(LexState * ls,Labeldesc * gt)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
leaveblock(FuncState * fs)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 */
addprototype(LexState * ls)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 */
codeclosure(LexState * ls,expdesc * v)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
open_func(LexState * ls,FuncState * fs,BlockCnt * bl)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
close_func(LexState * ls)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 */
block_follow(LexState * ls,int withuntil)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
statlist(LexState * ls)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
fieldsel(LexState * ls,expdesc * v)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
yindex(LexState * ls,expdesc * v)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
recfield(LexState * ls,struct ConsControl * cc)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
closelistfield(FuncState * fs,struct ConsControl * cc)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
lastlistfield(FuncState * fs,struct ConsControl * cc)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
listfield(LexState * ls,struct ConsControl * cc)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
field(LexState * ls,struct ConsControl * cc)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
constructor(LexState * ls,expdesc * t)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
parlist(LexState * ls)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 = 1;
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
body(LexState * ls,expdesc * e,int ismethod,int line)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
explist(LexState * ls,expdesc * v)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
funcargs(LexState * ls,expdesc * f,int line)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
primaryexp(LexState * ls,expdesc * v)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
suffixedexp(LexState * ls,expdesc * v)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
simpleexp(LexState * ls,expdesc * v)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 init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
960 break;
961 }
962 case '{': { /* constructor */
963 constructor(ls, v);
964 return;
965 }
966 case TK_FUNCTION: {
967 luaX_next(ls);
968 body(ls, v, 0, ls->linenumber);
969 return;
970 }
971 default: {
972 suffixedexp(ls, v);
973 return;
974 }
975 }
976 luaX_next(ls);
977 }
978
979
getunopr(int op)980 static UnOpr getunopr (int op) {
981 switch (op) {
982 case TK_NOT: return OPR_NOT;
983 case '-': return OPR_MINUS;
984 case '~': return OPR_BNOT;
985 case '#': return OPR_LEN;
986 default: return OPR_NOUNOPR;
987 }
988 }
989
990
getbinopr(int op)991 static BinOpr getbinopr (int op) {
992 switch (op) {
993 case '+': return OPR_ADD;
994 case '-': return OPR_SUB;
995 case '*': return OPR_MUL;
996 case '%': return OPR_MOD;
997 case '^': return OPR_POW;
998 case '/': return OPR_DIV;
999 case TK_IDIV: return OPR_IDIV;
1000 case '&': return OPR_BAND;
1001 case '|': return OPR_BOR;
1002 case '~': return OPR_BXOR;
1003 case TK_SHL: return OPR_SHL;
1004 case TK_SHR: return OPR_SHR;
1005 case TK_CONCAT: return OPR_CONCAT;
1006 case TK_NE: return OPR_NE;
1007 case TK_EQ: return OPR_EQ;
1008 case '<': return OPR_LT;
1009 case TK_LE: return OPR_LE;
1010 case '>': return OPR_GT;
1011 case TK_GE: return OPR_GE;
1012 case TK_AND: return OPR_AND;
1013 case TK_OR: return OPR_OR;
1014 default: return OPR_NOBINOPR;
1015 }
1016 }
1017
1018
1019 static const struct {
1020 lu_byte left; /* left priority for each binary operator */
1021 lu_byte right; /* right priority */
1022 } priority[] = { /* ORDER OPR */
1023 {10, 10}, {10, 10}, /* '+' '-' */
1024 {11, 11}, {11, 11}, /* '*' '%' */
1025 {14, 13}, /* '^' (right associative) */
1026 {11, 11}, {11, 11}, /* '/' '//' */
1027 {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
1028 {7, 7}, {7, 7}, /* '<<' '>>' */
1029 {9, 8}, /* '..' (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 12 /* 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 */
subexpr(LexState * ls,expdesc * v,int limit)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
expr(LexState * ls,expdesc * v)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
block(LexState * ls)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 */
check_conflict(LexState * ls,struct LHS_assign * lh,expdesc * v)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
assignment(LexState * ls,struct LHS_assign * lh,int nvars)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 -> ',' suffixedexp assignment */
1145 struct LHS_assign nv;
1146 nv.prev = lh;
1147 suffixedexp(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
cond(LexState * ls)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
gotostat(LexState * ls,int pc)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 */
checkrepeated(FuncState * fs,Labellist * ll,TString * label)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 '%s' already defined on line %d",
1206 getstr(label), ll->arr[i].line);
1207 semerror(fs->ls, msg);
1208 }
1209 }
1210 }
1211
1212
1213 /* skip no-op statements */
skipnoopstat(LexState * ls)1214 static void skipnoopstat (LexState *ls) {
1215 while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
1216 statement(ls);
1217 }
1218
1219
labelstat(LexState * ls,TString * label,int line)1220 static void labelstat (LexState *ls, TString *label, int line) {
1221 /* label -> '::' NAME '::' */
1222 FuncState *fs = ls->fs;
1223 Labellist *ll = &ls->dyd->label;
1224 int l; /* index of new label being created */
1225 checkrepeated(fs, ll, label); /* check for repeated labels */
1226 checknext(ls, TK_DBCOLON); /* skip double colon */
1227 /* create new entry for this label */
1228 l = newlabelentry(ls, ll, label, line, fs->pc);
1229 skipnoopstat(ls); /* skip other no-op statements */
1230 if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */
1231 /* assume that locals are already out of scope */
1232 ll->arr[l].nactvar = fs->bl->nactvar;
1233 }
1234 findgotos(ls, &ll->arr[l]);
1235 }
1236
1237
whilestat(LexState * ls,int line)1238 static void whilestat (LexState *ls, int line) {
1239 /* whilestat -> WHILE cond DO block END */
1240 FuncState *fs = ls->fs;
1241 int whileinit;
1242 int condexit;
1243 BlockCnt bl;
1244 luaX_next(ls); /* skip WHILE */
1245 whileinit = luaK_getlabel(fs);
1246 condexit = cond(ls);
1247 enterblock(fs, &bl, 1);
1248 checknext(ls, TK_DO);
1249 block(ls);
1250 luaK_jumpto(fs, whileinit);
1251 check_match(ls, TK_END, TK_WHILE, line);
1252 leaveblock(fs);
1253 luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
1254 }
1255
1256
repeatstat(LexState * ls,int line)1257 static void repeatstat (LexState *ls, int line) {
1258 /* repeatstat -> REPEAT block UNTIL cond */
1259 int condexit;
1260 FuncState *fs = ls->fs;
1261 int repeat_init = luaK_getlabel(fs);
1262 BlockCnt bl1, bl2;
1263 enterblock(fs, &bl1, 1); /* loop block */
1264 enterblock(fs, &bl2, 0); /* scope block */
1265 luaX_next(ls); /* skip REPEAT */
1266 statlist(ls);
1267 check_match(ls, TK_UNTIL, TK_REPEAT, line);
1268 condexit = cond(ls); /* read condition (inside scope block) */
1269 if (bl2.upval) /* upvalues? */
1270 luaK_patchclose(fs, condexit, bl2.nactvar);
1271 leaveblock(fs); /* finish scope */
1272 luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
1273 leaveblock(fs); /* finish loop */
1274 }
1275
1276
exp1(LexState * ls)1277 static int exp1 (LexState *ls) {
1278 expdesc e;
1279 int reg;
1280 expr(ls, &e);
1281 luaK_exp2nextreg(ls->fs, &e);
1282 lua_assert(e.k == VNONRELOC);
1283 reg = e.u.info;
1284 return reg;
1285 }
1286
1287
forbody(LexState * ls,int base,int line,int nvars,int isnum)1288 static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1289 /* forbody -> DO block */
1290 BlockCnt bl;
1291 FuncState *fs = ls->fs;
1292 int prep, endfor;
1293 adjustlocalvars(ls, 3); /* control variables */
1294 checknext(ls, TK_DO);
1295 prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1296 enterblock(fs, &bl, 0); /* scope for declared variables */
1297 adjustlocalvars(ls, nvars);
1298 luaK_reserveregs(fs, nvars);
1299 block(ls);
1300 leaveblock(fs); /* end of scope for declared variables */
1301 luaK_patchtohere(fs, prep);
1302 if (isnum) /* numeric for? */
1303 endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
1304 else { /* generic for */
1305 luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
1306 luaK_fixline(fs, line);
1307 endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
1308 }
1309 luaK_patchlist(fs, endfor, prep + 1);
1310 luaK_fixline(fs, line);
1311 }
1312
1313
fornum(LexState * ls,TString * varname,int line)1314 static void fornum (LexState *ls, TString *varname, int line) {
1315 /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1316 FuncState *fs = ls->fs;
1317 int base = fs->freereg;
1318 new_localvarliteral(ls, "(for index)");
1319 new_localvarliteral(ls, "(for limit)");
1320 new_localvarliteral(ls, "(for step)");
1321 new_localvar(ls, varname);
1322 checknext(ls, '=');
1323 exp1(ls); /* initial value */
1324 checknext(ls, ',');
1325 exp1(ls); /* limit */
1326 if (testnext(ls, ','))
1327 exp1(ls); /* optional step */
1328 else { /* default step = 1 */
1329 luaK_codek(fs, fs->freereg, luaK_intK(fs, 1));
1330 luaK_reserveregs(fs, 1);
1331 }
1332 forbody(ls, base, line, 1, 1);
1333 }
1334
1335
forlist(LexState * ls,TString * indexname)1336 static void forlist (LexState *ls, TString *indexname) {
1337 /* forlist -> NAME {,NAME} IN explist forbody */
1338 FuncState *fs = ls->fs;
1339 expdesc e;
1340 int nvars = 4; /* gen, state, control, plus at least one declared var */
1341 int line;
1342 int base = fs->freereg;
1343 /* create control variables */
1344 new_localvarliteral(ls, "(for generator)");
1345 new_localvarliteral(ls, "(for state)");
1346 new_localvarliteral(ls, "(for control)");
1347 /* create declared variables */
1348 new_localvar(ls, indexname);
1349 while (testnext(ls, ',')) {
1350 new_localvar(ls, str_checkname(ls));
1351 nvars++;
1352 }
1353 checknext(ls, TK_IN);
1354 line = ls->linenumber;
1355 adjust_assign(ls, 3, explist(ls, &e), &e);
1356 luaK_checkstack(fs, 3); /* extra space to call generator */
1357 forbody(ls, base, line, nvars - 3, 0);
1358 }
1359
1360
forstat(LexState * ls,int line)1361 static void forstat (LexState *ls, int line) {
1362 /* forstat -> FOR (fornum | forlist) END */
1363 FuncState *fs = ls->fs;
1364 TString *varname;
1365 BlockCnt bl;
1366 enterblock(fs, &bl, 1); /* scope for loop and control variables */
1367 luaX_next(ls); /* skip 'for' */
1368 varname = str_checkname(ls); /* first variable name */
1369 switch (ls->t.token) {
1370 case '=': fornum(ls, varname, line); break;
1371 case ',': case TK_IN: forlist(ls, varname); break;
1372 default: luaX_syntaxerror(ls, "'=' or 'in' expected");
1373 }
1374 check_match(ls, TK_END, TK_FOR, line);
1375 leaveblock(fs); /* loop scope ('break' jumps to this point) */
1376 }
1377
1378
test_then_block(LexState * ls,int * escapelist)1379 static void test_then_block (LexState *ls, int *escapelist) {
1380 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1381 BlockCnt bl;
1382 FuncState *fs = ls->fs;
1383 expdesc v;
1384 int jf; /* instruction to skip 'then' code (if condition is false) */
1385 luaX_next(ls); /* skip IF or ELSEIF */
1386 expr(ls, &v); /* read condition */
1387 checknext(ls, TK_THEN);
1388 if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
1389 luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */
1390 enterblock(fs, &bl, 0); /* must enter block before 'goto' */
1391 gotostat(ls, v.t); /* handle goto/break */
1392 skipnoopstat(ls); /* skip other no-op statements */
1393 if (block_follow(ls, 0)) { /* 'goto' is the entire block? */
1394 leaveblock(fs);
1395 return; /* and that is it */
1396 }
1397 else /* must skip over 'then' part if condition is false */
1398 jf = luaK_jump(fs);
1399 }
1400 else { /* regular case (not goto/break) */
1401 luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */
1402 enterblock(fs, &bl, 0);
1403 jf = v.f;
1404 }
1405 statlist(ls); /* 'then' part */
1406 leaveblock(fs);
1407 if (ls->t.token == TK_ELSE ||
1408 ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
1409 luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
1410 luaK_patchtohere(fs, jf);
1411 }
1412
1413
ifstat(LexState * ls,int line)1414 static void ifstat (LexState *ls, int line) {
1415 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1416 FuncState *fs = ls->fs;
1417 int escapelist = NO_JUMP; /* exit list for finished parts */
1418 test_then_block(ls, &escapelist); /* IF cond THEN block */
1419 while (ls->t.token == TK_ELSEIF)
1420 test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
1421 if (testnext(ls, TK_ELSE))
1422 block(ls); /* 'else' part */
1423 check_match(ls, TK_END, TK_IF, line);
1424 luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
1425 }
1426
1427
localfunc(LexState * ls)1428 static void localfunc (LexState *ls) {
1429 expdesc b;
1430 FuncState *fs = ls->fs;
1431 new_localvar(ls, str_checkname(ls)); /* new local variable */
1432 adjustlocalvars(ls, 1); /* enter its scope */
1433 body(ls, &b, 0, ls->linenumber); /* function created in next register */
1434 /* debug information will only see the variable after this point! */
1435 getlocvar(fs, b.u.info)->startpc = fs->pc;
1436 }
1437
1438
localstat(LexState * ls)1439 static void localstat (LexState *ls) {
1440 /* stat -> LOCAL NAME {',' NAME} ['=' explist] */
1441 int nvars = 0;
1442 int nexps;
1443 expdesc e;
1444 do {
1445 new_localvar(ls, str_checkname(ls));
1446 nvars++;
1447 } while (testnext(ls, ','));
1448 if (testnext(ls, '='))
1449 nexps = explist(ls, &e);
1450 else {
1451 e.k = VVOID;
1452 nexps = 0;
1453 }
1454 adjust_assign(ls, nvars, nexps, &e);
1455 adjustlocalvars(ls, nvars);
1456 }
1457
1458
funcname(LexState * ls,expdesc * v)1459 static int funcname (LexState *ls, expdesc *v) {
1460 /* funcname -> NAME {fieldsel} [':' NAME] */
1461 int ismethod = 0;
1462 singlevar(ls, v);
1463 while (ls->t.token == '.')
1464 fieldsel(ls, v);
1465 if (ls->t.token == ':') {
1466 ismethod = 1;
1467 fieldsel(ls, v);
1468 }
1469 return ismethod;
1470 }
1471
1472
funcstat(LexState * ls,int line)1473 static void funcstat (LexState *ls, int line) {
1474 /* funcstat -> FUNCTION funcname body */
1475 int ismethod;
1476 expdesc v, b;
1477 luaX_next(ls); /* skip FUNCTION */
1478 ismethod = funcname(ls, &v);
1479 body(ls, &b, ismethod, line);
1480 luaK_storevar(ls->fs, &v, &b);
1481 luaK_fixline(ls->fs, line); /* definition "happens" in the first line */
1482 }
1483
1484
exprstat(LexState * ls)1485 static void exprstat (LexState *ls) {
1486 /* stat -> func | assignment */
1487 FuncState *fs = ls->fs;
1488 struct LHS_assign v;
1489 suffixedexp(ls, &v.v);
1490 if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
1491 v.prev = NULL;
1492 assignment(ls, &v, 1);
1493 }
1494 else { /* stat -> func */
1495 check_condition(ls, v.v.k == VCALL, "syntax error");
1496 SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
1497 }
1498 }
1499
1500
retstat(LexState * ls)1501 static void retstat (LexState *ls) {
1502 /* stat -> RETURN [explist] [';'] */
1503 FuncState *fs = ls->fs;
1504 expdesc e;
1505 int first, nret; /* registers with returned values */
1506 if (block_follow(ls, 1) || ls->t.token == ';')
1507 first = nret = 0; /* return no values */
1508 else {
1509 nret = explist(ls, &e); /* optional return values */
1510 if (hasmultret(e.k)) {
1511 luaK_setmultret(fs, &e);
1512 if (e.k == VCALL && nret == 1) { /* tail call? */
1513 SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1514 lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1515 }
1516 first = fs->nactvar;
1517 nret = LUA_MULTRET; /* return all values */
1518 }
1519 else {
1520 if (nret == 1) /* only one single value? */
1521 first = luaK_exp2anyreg(fs, &e);
1522 else {
1523 luaK_exp2nextreg(fs, &e); /* values must go to the stack */
1524 first = fs->nactvar; /* return all active values */
1525 lua_assert(nret == fs->freereg - first);
1526 }
1527 }
1528 }
1529 luaK_ret(fs, first, nret);
1530 testnext(ls, ';'); /* skip optional semicolon */
1531 }
1532
1533
statement(LexState * ls)1534 static void statement (LexState *ls) {
1535 int line = ls->linenumber; /* may be needed for error messages */
1536 enterlevel(ls);
1537 switch (ls->t.token) {
1538 case ';': { /* stat -> ';' (empty statement) */
1539 luaX_next(ls); /* skip ';' */
1540 break;
1541 }
1542 case TK_IF: { /* stat -> ifstat */
1543 ifstat(ls, line);
1544 break;
1545 }
1546 case TK_WHILE: { /* stat -> whilestat */
1547 whilestat(ls, line);
1548 break;
1549 }
1550 case TK_DO: { /* stat -> DO block END */
1551 luaX_next(ls); /* skip DO */
1552 block(ls);
1553 check_match(ls, TK_END, TK_DO, line);
1554 break;
1555 }
1556 case TK_FOR: { /* stat -> forstat */
1557 forstat(ls, line);
1558 break;
1559 }
1560 case TK_REPEAT: { /* stat -> repeatstat */
1561 repeatstat(ls, line);
1562 break;
1563 }
1564 case TK_FUNCTION: { /* stat -> funcstat */
1565 funcstat(ls, line);
1566 break;
1567 }
1568 case TK_LOCAL: { /* stat -> localstat */
1569 luaX_next(ls); /* skip LOCAL */
1570 if (testnext(ls, TK_FUNCTION)) /* local function? */
1571 localfunc(ls);
1572 else
1573 localstat(ls);
1574 break;
1575 }
1576 case TK_DBCOLON: { /* stat -> label */
1577 luaX_next(ls); /* skip double colon */
1578 labelstat(ls, str_checkname(ls), line);
1579 break;
1580 }
1581 case TK_RETURN: { /* stat -> retstat */
1582 luaX_next(ls); /* skip RETURN */
1583 retstat(ls);
1584 break;
1585 }
1586 case TK_BREAK: /* stat -> breakstat */
1587 case TK_GOTO: { /* stat -> 'goto' NAME */
1588 gotostat(ls, luaK_jump(ls->fs));
1589 break;
1590 }
1591 default: { /* stat -> func | assignment */
1592 exprstat(ls);
1593 break;
1594 }
1595 }
1596 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1597 ls->fs->freereg >= ls->fs->nactvar);
1598 ls->fs->freereg = ls->fs->nactvar; /* free registers */
1599 leavelevel(ls);
1600 }
1601
1602 /* }====================================================================== */
1603
1604
1605 /*
1606 ** compiles the main function, which is a regular vararg function with an
1607 ** upvalue named LUA_ENV
1608 */
mainfunc(LexState * ls,FuncState * fs)1609 static void mainfunc (LexState *ls, FuncState *fs) {
1610 BlockCnt bl;
1611 expdesc v;
1612 open_func(ls, fs, &bl);
1613 fs->f->is_vararg = 1; /* main function is always vararg */
1614 init_exp(&v, VLOCAL, 0); /* create and... */
1615 newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */
1616 luaX_next(ls); /* read first token */
1617 statlist(ls); /* parse main body */
1618 check(ls, TK_EOS);
1619 close_func(ls);
1620 }
1621
1622
luaY_parser(lua_State * L,ZIO * z,Mbuffer * buff,Dyndata * dyd,const char * name,int firstchar)1623 LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1624 Dyndata *dyd, const char *name, int firstchar) {
1625 LexState lexstate;
1626 FuncState funcstate;
1627 LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */
1628 setclLvalue(L, L->top, cl); /* anchor it (to avoid being collected) */
1629 incr_top(L);
1630 lexstate.h = luaH_new(L); /* create table for scanner */
1631 sethvalue(L, L->top, lexstate.h); /* anchor it */
1632 incr_top(L);
1633 funcstate.f = cl->p = luaF_newproto(L);
1634 funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
1635 lua_assert(iswhite(funcstate.f)); /* do not need barrier here */
1636 lexstate.buff = buff;
1637 lexstate.dyd = dyd;
1638 dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
1639 luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
1640 mainfunc(&lexstate, &funcstate);
1641 lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
1642 /* all scopes should be correctly finished */
1643 lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
1644 L->top--; /* remove scanner's table */
1645 return cl; /* closure is on the stack, too */
1646 }
1647
1648