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