1 /*
2 ** $Id$
3 ** Lua Parser
4 ** See Copyright Notice in lua.h
5 */
6 
7 
8 #define lparser_c
9 #define LUA_CORE
10 
11 #include "lua.h"
12 
13 #include "lcode.h"
14 #include "ldebug.h"
15 #include "ldo.h"
16 #include "lfunc.h"
17 #include "llex.h"
18 #include "lmem.h"
19 #include "lobject.h"
20 #include "lopcodes.h"
21 #include "lparser.h"
22 #include "lstate.h"
23 #include "lstring.h"
24 #include "ltable.h"
25 
26 
27 
28 #define hasmultret(k)		((k) == VCALL || (k) == VVARARG)
29 
30 #define getlocvar(fs, i)	((fs)->f->locvars[(fs)->actvar[i]])
31 
32 #define luaY_checklimit(fs,v,l,m)	if ((v)>(l)) errorlimit(fs,l,m)
33 
34 
35 /*
36 ** nodes for block list (list of active blocks)
37 */
38 typedef struct BlockCnt {
39   struct BlockCnt *previous;  /* chain */
40   int breaklist;  /* list of jumps out of this loop */
41   lu_byte nactvar;  /* # active locals outside the breakable structure */
42   lu_byte upval;  /* true if some variable in the block is an upvalue */
43   lu_byte isbreakable;  /* true if `block' is a loop */
44 } BlockCnt;
45 
46 
47 
48 /*
49 ** prototypes for recursive non-terminal functions
50 */
51 static void chunk (LexState *ls);
52 static void expr (LexState *ls, expdesc *v);
53 
54 
anchor_token(LexState * ls)55 static void anchor_token (LexState *ls) {
56   if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
57     TString *ts = ls->t.seminfo.ts;
58     luaX_newstring(ls, getstr(ts), ts->tsv.len);
59   }
60 }
61 
62 
error_expected(LexState * ls,int token)63 static void error_expected (LexState *ls, int token) {
64   luaX_syntaxerror(ls,
65       luaO_pushfstring(ls->L, LUA_QS " expected", luaX_token2str(ls, token)));
66 }
67 
68 
errorlimit(FuncState * fs,int limit,const char * what)69 static void errorlimit (FuncState *fs, int limit, const char *what) {
70   const char *msg = (fs->f->linedefined == 0) ?
71     luaO_pushfstring(fs->L, "main function has more than %d %s", limit, what) :
72     luaO_pushfstring(fs->L, "function at line %d has more than %d %s",
73                             fs->f->linedefined, limit, what);
74   luaX_lexerror(fs->ls, msg, 0);
75 }
76 
77 
testnext(LexState * ls,int c)78 static int testnext (LexState *ls, int c) {
79   if (ls->t.token == c) {
80     luaX_next(ls);
81     return 1;
82   }
83   else return 0;
84 }
85 
86 
check(LexState * ls,int c)87 static void check (LexState *ls, int c) {
88   if (ls->t.token != c)
89     error_expected(ls, c);
90 }
91 
checknext(LexState * ls,int c)92 static void checknext (LexState *ls, int c) {
93   check(ls, c);
94   luaX_next(ls);
95 }
96 
97 
98 #define check_condition(ls,c,msg)	{ if (!(c)) luaX_syntaxerror(ls, msg); }
99 
100 
101 
check_match(LexState * ls,int what,int who,int where)102 static void check_match (LexState *ls, int what, int who, int where) {
103   if (!testnext(ls, what)) {
104     if (where == ls->linenumber)
105       error_expected(ls, what);
106     else {
107       luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
108              LUA_QS " expected (to close " LUA_QS " at line %d)",
109               luaX_token2str(ls, what), luaX_token2str(ls, who), where));
110     }
111   }
112 }
113 
114 
str_checkname(LexState * ls)115 static TString *str_checkname (LexState *ls) {
116   TString *ts;
117   check(ls, TK_NAME);
118   ts = ls->t.seminfo.ts;
119   luaX_next(ls);
120   return ts;
121 }
122 
123 
init_exp(expdesc * e,expkind k,int i)124 static void init_exp (expdesc *e, expkind k, int i) {
125   e->f = e->t = NO_JUMP;
126   e->k = k;
127   e->u.s.info = i;
128 }
129 
130 
codestring(LexState * ls,expdesc * e,TString * s)131 static void codestring (LexState *ls, expdesc *e, TString *s) {
132   init_exp(e, VK, luaK_stringK(ls->fs, s));
133 }
134 
135 
checkname(LexState * ls,expdesc * e)136 static void checkname(LexState *ls, expdesc *e) {
137   codestring(ls, e, str_checkname(ls));
138 }
139 
140 
registerlocalvar(LexState * ls,TString * varname)141 static int registerlocalvar (LexState *ls, TString *varname) {
142   FuncState *fs = ls->fs;
143   Proto *f = fs->f;
144   int oldsize = f->sizelocvars;
145   luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
146                   LocVar, SHRT_MAX, "too many local variables");
147   while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
148   f->locvars[fs->nlocvars].varname = varname;
149   luaC_objbarrier(ls->L, f, varname);
150   return fs->nlocvars++;
151 }
152 
153 
154 #define new_localvarliteral(ls,v,n) \
155   new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n)
156 
157 
new_localvar(LexState * ls,TString * name,int n)158 static void new_localvar (LexState *ls, TString *name, int n) {
159   FuncState *fs = ls->fs;
160   luaY_checklimit(fs, fs->nactvar+n+1, LUAI_MAXVARS, "local variables");
161   fs->actvar[fs->nactvar+n] = cast(unsigned short, registerlocalvar(ls, name));
162 }
163 
164 
adjustlocalvars(LexState * ls,int nvars)165 static void adjustlocalvars (LexState *ls, int nvars) {
166   FuncState *fs = ls->fs;
167   fs->nactvar = cast_byte(fs->nactvar + nvars);
168   for (; nvars; nvars--) {
169     getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc;
170   }
171 }
172 
173 
removevars(LexState * ls,int tolevel)174 static void removevars (LexState *ls, int tolevel) {
175   FuncState *fs = ls->fs;
176   while (fs->nactvar > tolevel)
177     getlocvar(fs, --fs->nactvar).endpc = fs->pc;
178 }
179 
180 
indexupvalue(FuncState * fs,TString * name,expdesc * v)181 static int indexupvalue (FuncState *fs, TString *name, expdesc *v) {
182   int i;
183   Proto *f = fs->f;
184   int oldsize = f->sizeupvalues;
185   for (i=0; i<f->nups; i++) {
186     if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->u.s.info) {
187       lua_assert(f->upvalues[i] == name);
188       return i;
189     }
190   }
191   /* new one */
192   luaY_checklimit(fs, f->nups + 1, LUAI_MAXUPVALUES, "upvalues");
193   luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues,
194                   TString *, MAX_INT, "");
195   while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL;
196   f->upvalues[f->nups] = name;
197   luaC_objbarrier(fs->L, f, name);
198   lua_assert(v->k == VLOCAL || v->k == VUPVAL);
199   fs->upvalues[f->nups].k = cast_byte(v->k);
200   fs->upvalues[f->nups].info = cast_byte(v->u.s.info);
201   return f->nups++;
202 }
203 
204 
searchvar(FuncState * fs,TString * n)205 static int searchvar (FuncState *fs, TString *n) {
206   int i;
207   for (i=fs->nactvar-1; i >= 0; i--) {
208     if (n == getlocvar(fs, i).varname)
209       return i;
210   }
211   return -1;  /* not found */
212 }
213 
214 
markupval(FuncState * fs,int level)215 static void markupval (FuncState *fs, int level) {
216   BlockCnt *bl = fs->bl;
217   while (bl && bl->nactvar > level) bl = bl->previous;
218   if (bl) bl->upval = 1;
219 }
220 
221 
singlevaraux(FuncState * fs,TString * n,expdesc * var,int base)222 static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
223   if (fs == NULL) {  /* no more levels? */
224     init_exp(var, VGLOBAL, NO_REG);  /* default is global variable */
225     return VGLOBAL;
226   }
227   else {
228     int v = searchvar(fs, n);  /* look up at current level */
229     if (v >= 0) {
230       init_exp(var, VLOCAL, v);
231       if (!base)
232         markupval(fs, v);  /* local will be used as an upval */
233       return VLOCAL;
234     }
235     else {  /* not found at current level; try upper one */
236       if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL)
237         return VGLOBAL;
238       var->u.s.info = indexupvalue(fs, n, var);  /* else was LOCAL or UPVAL */
239       var->k = VUPVAL;  /* upvalue in this level */
240       return VUPVAL;
241     }
242   }
243 }
244 
245 
singlevar(LexState * ls,expdesc * var)246 static void singlevar (LexState *ls, expdesc *var) {
247   TString *varname = str_checkname(ls);
248   FuncState *fs = ls->fs;
249   if (singlevaraux(fs, varname, var, 1) == VGLOBAL)
250     var->u.s.info = luaK_stringK(fs, varname);  /* info points to global name */
251 }
252 
253 
adjust_assign(LexState * ls,int nvars,int nexps,expdesc * e)254 static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
255   FuncState *fs = ls->fs;
256   int extra = nvars - nexps;
257   if (hasmultret(e->k)) {
258     extra++;  /* includes call itself */
259     if (extra < 0) extra = 0;
260     luaK_setreturns(fs, e, extra);  /* last exp. provides the difference */
261     if (extra > 1) luaK_reserveregs(fs, extra-1);
262   }
263   else {
264     if (e->k != VVOID) luaK_exp2nextreg(fs, e);  /* close last expression */
265     if (extra > 0) {
266       int reg = fs->freereg;
267       luaK_reserveregs(fs, extra);
268       luaK_nil(fs, reg, extra);
269     }
270   }
271 }
272 
273 
enterlevel(LexState * ls)274 static void enterlevel (LexState *ls) {
275   if (++ls->L->nCcalls > LUAI_MAXCCALLS)
276 	luaX_lexerror(ls, "chunk has too many syntax levels", 0);
277 }
278 
279 
280 #define leavelevel(ls)	((ls)->L->nCcalls--)
281 
282 
enterblock(FuncState * fs,BlockCnt * bl,lu_byte isbreakable)283 static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) {
284   bl->breaklist = NO_JUMP;
285   bl->isbreakable = isbreakable;
286   bl->nactvar = fs->nactvar;
287   bl->upval = 0;
288   bl->previous = fs->bl;
289   fs->bl = bl;
290   lua_assert(fs->freereg == fs->nactvar);
291 }
292 
293 
leaveblock(FuncState * fs)294 static void leaveblock (FuncState *fs) {
295   BlockCnt *bl = fs->bl;
296   fs->bl = bl->previous;
297   removevars(fs->ls, bl->nactvar);
298   if (bl->upval)
299     luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
300   /* a block either controls scope or breaks (never both) */
301   lua_assert(!bl->isbreakable || !bl->upval);
302   lua_assert(bl->nactvar == fs->nactvar);
303   fs->freereg = fs->nactvar;  /* free registers */
304   luaK_patchtohere(fs, bl->breaklist);
305 }
306 
307 
pushclosure(LexState * ls,FuncState * func,expdesc * v)308 static void pushclosure (LexState *ls, FuncState *func, expdesc *v) {
309   FuncState *fs = ls->fs;
310   Proto *f = fs->f;
311   int oldsize = f->sizep;
312   int i;
313   luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
314                   MAXARG_Bx, "constant table overflow");
315   while (oldsize < f->sizep) f->p[oldsize++] = NULL;
316   f->p[fs->np++] = func->f;
317   luaC_objbarrier(ls->L, f, func->f);
318   init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
319   for (i=0; i<func->f->nups; i++) {
320     OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
321     luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0);
322   }
323 }
324 
325 
open_func(LexState * ls,FuncState * fs)326 static void open_func (LexState *ls, FuncState *fs) {
327   lua_State *L = ls->L;
328   Proto *f = luaF_newproto(L);
329   fs->f = f;
330   fs->prev = ls->fs;  /* linked list of funcstates */
331   fs->ls = ls;
332   fs->L = L;
333   ls->fs = fs;
334   fs->pc = 0;
335   fs->lasttarget = -1;
336   fs->jpc = NO_JUMP;
337   fs->freereg = 0;
338   fs->nk = 0;
339   fs->np = 0;
340   fs->nlocvars = 0;
341   fs->nactvar = 0;
342   fs->bl = NULL;
343   f->source = ls->source;
344   f->maxstacksize = 2;  /* registers 0/1 are always valid */
345   fs->h = luaH_new(L, 0, 0);
346   /* anchor table of constants and prototype (to avoid being collected) */
347   sethvalue2s(L, L->top, fs->h);
348   incr_top(L);
349   setptvalue2s(L, L->top, f);
350   incr_top(L);
351 }
352 
353 
close_func(LexState * ls)354 static void close_func (LexState *ls) {
355   lua_State *L = ls->L;
356   FuncState *fs = ls->fs;
357   Proto *f = fs->f;
358   removevars(ls, 0);
359   luaK_ret(fs, 0, 0);  /* final return */
360   luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
361   f->sizecode = fs->pc;
362   luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
363   f->sizelineinfo = fs->pc;
364   luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
365   f->sizek = fs->nk;
366   luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
367   f->sizep = fs->np;
368   luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
369   f->sizelocvars = fs->nlocvars;
370   luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *);
371   f->sizeupvalues = f->nups;
372   lua_assert(luaG_checkcode(f));
373   lua_assert(fs->bl == NULL);
374   ls->fs = fs->prev;
375   L->top -= 2;  /* remove table and prototype from the stack */
376   /* last token read was anchored in defunct function; must reanchor it */
377   if (fs) anchor_token(ls);
378 }
379 
380 
luaY_parser(lua_State * L,ZIO * z,Mbuffer * buff,const char * name)381 Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
382   struct LexState lexstate;
383   struct FuncState funcstate;
384   lexstate.buff = buff;
385   luaX_setinput(L, &lexstate, z, luaS_new(L, name));
386   open_func(&lexstate, &funcstate);
387   funcstate.f->is_vararg = VARARG_ISVARARG;  /* main func. is always vararg */
388   luaX_next(&lexstate);  /* read first token */
389   chunk(&lexstate);
390   check(&lexstate, TK_EOS);
391   close_func(&lexstate);
392   lua_assert(funcstate.prev == NULL);
393   lua_assert(funcstate.f->nups == 0);
394   lua_assert(lexstate.fs == NULL);
395   return funcstate.f;
396 }
397 
398 
399 
400 /*============================================================*/
401 /* GRAMMAR RULES */
402 /*============================================================*/
403 
404 
field(LexState * ls,expdesc * v)405 static void field (LexState *ls, expdesc *v) {
406   /* field -> ['.' | ':'] NAME */
407   FuncState *fs = ls->fs;
408   expdesc key;
409   luaK_exp2anyreg(fs, v);
410   luaX_next(ls);  /* skip the dot or colon */
411   checkname(ls, &key);
412   luaK_indexed(fs, v, &key);
413 }
414 
415 
yindex(LexState * ls,expdesc * v)416 static void yindex (LexState *ls, expdesc *v) {
417   /* index -> '[' expr ']' */
418   luaX_next(ls);  /* skip the '[' */
419   expr(ls, v);
420   luaK_exp2val(ls->fs, v);
421   checknext(ls, ']');
422 }
423 
424 
425 /*
426 ** {======================================================================
427 ** Rules for Constructors
428 ** =======================================================================
429 */
430 
431 
432 struct ConsControl {
433   expdesc v;  /* last list item read */
434   expdesc *t;  /* table descriptor */
435   int nh;  /* total number of `record' elements */
436   int na;  /* total number of array elements */
437   int tostore;  /* number of array elements pending to be stored */
438 };
439 
440 
recfield(LexState * ls,struct ConsControl * cc)441 static void recfield (LexState *ls, struct ConsControl *cc) {
442   /* recfield -> (NAME | `['exp1`]') = exp1 */
443   FuncState *fs = ls->fs;
444   int reg = ls->fs->freereg;
445   expdesc key, val;
446   int rkkey;
447   if (ls->t.token == TK_NAME) {
448     luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
449     checkname(ls, &key);
450   }
451   else  /* ls->t.token == '[' */
452     yindex(ls, &key);
453   cc->nh++;
454   checknext(ls, '=');
455   rkkey = luaK_exp2RK(fs, &key);
456   expr(ls, &val);
457   luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val));
458   fs->freereg = reg;  /* free registers */
459 }
460 
461 
closelistfield(FuncState * fs,struct ConsControl * cc)462 static void closelistfield (FuncState *fs, struct ConsControl *cc) {
463   if (cc->v.k == VVOID) return;  /* there is no list item */
464   luaK_exp2nextreg(fs, &cc->v);
465   cc->v.k = VVOID;
466   if (cc->tostore == LFIELDS_PER_FLUSH) {
467     luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);  /* flush */
468     cc->tostore = 0;  /* no more items pending */
469   }
470 }
471 
472 
lastlistfield(FuncState * fs,struct ConsControl * cc)473 static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
474   if (cc->tostore == 0) return;
475   if (hasmultret(cc->v.k)) {
476     luaK_setmultret(fs, &cc->v);
477     luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET);
478     cc->na--;  /* do not count last expression (unknown number of elements) */
479   }
480   else {
481     if (cc->v.k != VVOID)
482       luaK_exp2nextreg(fs, &cc->v);
483     luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);
484   }
485 }
486 
487 
listfield(LexState * ls,struct ConsControl * cc)488 static void listfield (LexState *ls, struct ConsControl *cc) {
489   expr(ls, &cc->v);
490   luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
491   cc->na++;
492   cc->tostore++;
493 }
494 
495 
constructor(LexState * ls,expdesc * t)496 static void constructor (LexState *ls, expdesc *t) {
497   /* constructor -> ?? */
498   FuncState *fs = ls->fs;
499   int line = ls->linenumber;
500   int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
501   struct ConsControl cc;
502   cc.na = cc.nh = cc.tostore = 0;
503   cc.t = t;
504   init_exp(t, VRELOCABLE, pc);
505   init_exp(&cc.v, VVOID, 0);  /* no value (yet) */
506   luaK_exp2nextreg(ls->fs, t);  /* fix it at stack top (for gc) */
507   checknext(ls, '{');
508   do {
509     lua_assert(cc.v.k == VVOID || cc.tostore > 0);
510     if (ls->t.token == '}') break;
511     closelistfield(fs, &cc);
512     switch(ls->t.token) {
513       case TK_NAME: {  /* may be listfields or recfields */
514         luaX_lookahead(ls);
515         if (ls->lookahead.token != '=')  /* expression? */
516           listfield(ls, &cc);
517         else
518           recfield(ls, &cc);
519         break;
520       }
521       case '[': {  /* constructor_item -> recfield */
522         recfield(ls, &cc);
523         break;
524       }
525       default: {  /* constructor_part -> listfield */
526         listfield(ls, &cc);
527         break;
528       }
529     }
530   } while (testnext(ls, ',') || testnext(ls, ';'));
531   check_match(ls, '}', '{', line);
532   lastlistfield(fs, &cc);
533   SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
534   SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh));  /* set initial table size */
535 }
536 
537 /* }====================================================================== */
538 
539 
540 
parlist(LexState * ls)541 static void parlist (LexState *ls) {
542   /* parlist -> [ param { `,' param } ] */
543   FuncState *fs = ls->fs;
544   Proto *f = fs->f;
545   int nparams = 0;
546   f->is_vararg = 0;
547   if (ls->t.token != ')') {  /* is `parlist' not empty? */
548     do {
549       switch (ls->t.token) {
550         case TK_NAME: {  /* param -> NAME */
551           new_localvar(ls, str_checkname(ls), nparams++);
552           break;
553         }
554         case TK_DOTS: {  /* param -> `...' */
555           luaX_next(ls);
556 #if defined(LUA_COMPAT_VARARG)
557           /* use `arg' as default name */
558           new_localvarliteral(ls, "arg", nparams++);
559           f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG;
560 #endif
561           f->is_vararg |= VARARG_ISVARARG;
562           break;
563         }
564         default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
565       }
566     } while (!f->is_vararg && testnext(ls, ','));
567   }
568   adjustlocalvars(ls, nparams);
569   f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG));
570   luaK_reserveregs(fs, fs->nactvar);  /* reserve register for parameters */
571 }
572 
573 
body(LexState * ls,expdesc * e,int needself,int line)574 static void body (LexState *ls, expdesc *e, int needself, int line) {
575   /* body ->  `(' parlist `)' chunk END */
576   FuncState new_fs;
577   open_func(ls, &new_fs);
578   new_fs.f->linedefined = line;
579   checknext(ls, '(');
580   if (needself) {
581     new_localvarliteral(ls, "self", 0);
582     adjustlocalvars(ls, 1);
583   }
584   parlist(ls);
585   checknext(ls, ')');
586   chunk(ls);
587   new_fs.f->lastlinedefined = ls->linenumber;
588   check_match(ls, TK_END, TK_FUNCTION, line);
589   close_func(ls);
590   pushclosure(ls, &new_fs, e);
591 }
592 
593 
explist1(LexState * ls,expdesc * v)594 static int explist1 (LexState *ls, expdesc *v) {
595   /* explist1 -> expr { `,' expr } */
596   int n = 1;  /* at least one expression */
597   expr(ls, v);
598   while (testnext(ls, ',')) {
599     luaK_exp2nextreg(ls->fs, v);
600     expr(ls, v);
601     n++;
602   }
603   return n;
604 }
605 
606 
funcargs(LexState * ls,expdesc * f)607 static void funcargs (LexState *ls, expdesc *f) {
608   FuncState *fs = ls->fs;
609   expdesc args;
610   int base, nparams;
611   int line = ls->linenumber;
612   switch (ls->t.token) {
613     case '(': {  /* funcargs -> `(' [ explist1 ] `)' */
614       if (line != ls->lastline)
615         luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
616       luaX_next(ls);
617       if (ls->t.token == ')')  /* arg list is empty? */
618         args.k = VVOID;
619       else {
620         explist1(ls, &args);
621         luaK_setmultret(fs, &args);
622       }
623       check_match(ls, ')', '(', line);
624       break;
625     }
626     case '{': {  /* funcargs -> constructor */
627       constructor(ls, &args);
628       break;
629     }
630     case TK_STRING: {  /* funcargs -> STRING */
631       codestring(ls, &args, ls->t.seminfo.ts);
632       luaX_next(ls);  /* must use `seminfo' before `next' */
633       break;
634     }
635     default: {
636       luaX_syntaxerror(ls, "function arguments expected");
637       return;
638     }
639   }
640   lua_assert(f->k == VNONRELOC);
641   base = f->u.s.info;  /* base register for call */
642   if (hasmultret(args.k))
643     nparams = LUA_MULTRET;  /* open call */
644   else {
645     if (args.k != VVOID)
646       luaK_exp2nextreg(fs, &args);  /* close last argument */
647     nparams = fs->freereg - (base+1);
648   }
649   init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
650   luaK_fixline(fs, line);
651   fs->freereg = base+1;  /* call remove function and arguments and leaves
652                             (unless changed) one result */
653 }
654 
655 
656 
657 
658 /*
659 ** {======================================================================
660 ** Expression parsing
661 ** =======================================================================
662 */
663 
664 
prefixexp(LexState * ls,expdesc * v)665 static void prefixexp (LexState *ls, expdesc *v) {
666   /* prefixexp -> NAME | '(' expr ')' */
667   switch (ls->t.token) {
668     case '(': {
669       int line = ls->linenumber;
670       luaX_next(ls);
671       expr(ls, v);
672       check_match(ls, ')', '(', line);
673       luaK_dischargevars(ls->fs, v);
674       return;
675     }
676     case TK_NAME: {
677       singlevar(ls, v);
678       return;
679     }
680     default: {
681       luaX_syntaxerror(ls, "unexpected symbol");
682       return;
683     }
684   }
685 }
686 
687 
primaryexp(LexState * ls,expdesc * v)688 static void primaryexp (LexState *ls, expdesc *v) {
689   /* primaryexp ->
690         prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
691   FuncState *fs = ls->fs;
692   prefixexp(ls, v);
693   for (;;) {
694     switch (ls->t.token) {
695       case '.': {  /* field */
696         field(ls, v);
697         break;
698       }
699       case '[': {  /* `[' exp1 `]' */
700         expdesc key;
701         luaK_exp2anyreg(fs, v);
702         yindex(ls, &key);
703         luaK_indexed(fs, v, &key);
704         break;
705       }
706       case ':': {  /* `:' NAME funcargs */
707         expdesc key;
708         luaX_next(ls);
709         checkname(ls, &key);
710         luaK_self(fs, v, &key);
711         funcargs(ls, v);
712         break;
713       }
714       case '(': case TK_STRING: case '{': {  /* funcargs */
715         luaK_exp2nextreg(fs, v);
716         funcargs(ls, v);
717         break;
718       }
719       default: return;
720     }
721   }
722 }
723 
724 
simpleexp(LexState * ls,expdesc * v)725 static void simpleexp (LexState *ls, expdesc *v) {
726   /* simpleexp -> NUMBER | STRING | NIL | true | false | ... |
727                   constructor | FUNCTION body | primaryexp */
728   switch (ls->t.token) {
729     case TK_NUMBER: {
730       init_exp(v, VKNUM, 0);
731       v->u.nval = ls->t.seminfo.r;
732       break;
733     }
734     case TK_STRING: {
735       codestring(ls, v, ls->t.seminfo.ts);
736       break;
737     }
738     case TK_NIL: {
739       init_exp(v, VNIL, 0);
740       break;
741     }
742     case TK_TRUE: {
743       init_exp(v, VTRUE, 0);
744       break;
745     }
746     case TK_FALSE: {
747       init_exp(v, VFALSE, 0);
748       break;
749     }
750     case TK_DOTS: {  /* vararg */
751       FuncState *fs = ls->fs;
752       check_condition(ls, fs->f->is_vararg,
753                       "cannot use " LUA_QL("...") " outside a vararg function");
754       fs->f->is_vararg &= ~VARARG_NEEDSARG;  /* don't need 'arg' */
755       init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
756       break;
757     }
758     case '{': {  /* constructor */
759       constructor(ls, v);
760       return;
761     }
762     case TK_FUNCTION: {
763       luaX_next(ls);
764       body(ls, v, 0, ls->linenumber);
765       return;
766     }
767     default: {
768       primaryexp(ls, v);
769       return;
770     }
771   }
772   luaX_next(ls);
773 }
774 
775 
getunopr(int op)776 static UnOpr getunopr (int op) {
777   switch (op) {
778     case TK_NOT: return OPR_NOT;
779     case '-': return OPR_MINUS;
780     case '#': return OPR_LEN;
781     default: return OPR_NOUNOPR;
782   }
783 }
784 
785 
getbinopr(int op)786 static BinOpr getbinopr (int op) {
787   switch (op) {
788     case '+': return OPR_ADD;
789     case '-': return OPR_SUB;
790     case '*': return OPR_MUL;
791     case '/': return OPR_DIV;
792     case '%': return OPR_MOD;
793     case '^': return OPR_POW;
794     case TK_CONCAT: return OPR_CONCAT;
795     case TK_NE: return OPR_NE;
796     case TK_EQ: return OPR_EQ;
797     case '<': return OPR_LT;
798     case TK_LE: return OPR_LE;
799     case '>': return OPR_GT;
800     case TK_GE: return OPR_GE;
801     case TK_AND: return OPR_AND;
802     case TK_OR: return OPR_OR;
803     default: return OPR_NOBINOPR;
804   }
805 }
806 
807 
808 static const struct {
809   lu_byte left;  /* left priority for each binary operator */
810   lu_byte right; /* right priority */
811 } priority[] = {  /* ORDER OPR */
812    {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7},  /* `+' `-' `/' `%' */
813    {10, 9}, {5, 4},                 /* power and concat (right associative) */
814    {3, 3}, {3, 3},                  /* equality and inequality */
815    {3, 3}, {3, 3}, {3, 3}, {3, 3},  /* order */
816    {2, 2}, {1, 1}                   /* logical (and/or) */
817 };
818 
819 #define UNARY_PRIORITY	8  /* priority for unary operators */
820 
821 
822 /*
823 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
824 ** where `binop' is any binary operator with a priority higher than `limit'
825 */
subexpr(LexState * ls,expdesc * v,unsigned int limit)826 static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) {
827   BinOpr op;
828   UnOpr uop;
829   enterlevel(ls);
830   uop = getunopr(ls->t.token);
831   if (uop != OPR_NOUNOPR) {
832     luaX_next(ls);
833     subexpr(ls, v, UNARY_PRIORITY);
834     luaK_prefix(ls->fs, uop, v);
835   }
836   else simpleexp(ls, v);
837   /* expand while operators have priorities higher than `limit' */
838   op = getbinopr(ls->t.token);
839   while (op != OPR_NOBINOPR && priority[op].left > limit) {
840     expdesc v2;
841     BinOpr nextop;
842     luaX_next(ls);
843     luaK_infix(ls->fs, op, v);
844     /* read sub-expression with higher priority */
845     nextop = subexpr(ls, &v2, priority[op].right);
846     luaK_posfix(ls->fs, op, v, &v2);
847     op = nextop;
848   }
849   leavelevel(ls);
850   return op;  /* return first untreated operator */
851 }
852 
853 
expr(LexState * ls,expdesc * v)854 static void expr (LexState *ls, expdesc *v) {
855   subexpr(ls, v, 0);
856 }
857 
858 /* }==================================================================== */
859 
860 
861 
862 /*
863 ** {======================================================================
864 ** Rules for Statements
865 ** =======================================================================
866 */
867 
868 
block_follow(int token)869 static int block_follow (int token) {
870   switch (token) {
871     case TK_ELSE: case TK_ELSEIF: case TK_END:
872     case TK_UNTIL: case TK_EOS:
873       return 1;
874     default: return 0;
875   }
876 }
877 
878 
block(LexState * ls)879 static void block (LexState *ls) {
880   /* block -> chunk */
881   FuncState *fs = ls->fs;
882   BlockCnt bl;
883   enterblock(fs, &bl, 0);
884   chunk(ls);
885   lua_assert(bl.breaklist == NO_JUMP);
886   leaveblock(fs);
887 }
888 
889 
890 /*
891 ** structure to chain all variables in the left-hand side of an
892 ** assignment
893 */
894 struct LHS_assign {
895   struct LHS_assign *prev;
896   expdesc v;  /* variable (global, local, upvalue, or indexed) */
897 };
898 
899 
900 /*
901 ** check whether, in an assignment to a local variable, the local variable
902 ** is needed in a previous assignment (to a table). If so, save original
903 ** local value in a safe place and use this safe copy in the previous
904 ** assignment.
905 */
check_conflict(LexState * ls,struct LHS_assign * lh,expdesc * v)906 static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
907   FuncState *fs = ls->fs;
908   int extra = fs->freereg;  /* eventual position to save local variable */
909   int conflict = 0;
910   for (; lh; lh = lh->prev) {
911     if (lh->v.k == VINDEXED) {
912       if (lh->v.u.s.info == v->u.s.info) {  /* conflict? */
913         conflict = 1;
914         lh->v.u.s.info = extra;  /* previous assignment will use safe copy */
915       }
916       if (lh->v.u.s.aux == v->u.s.info) {  /* conflict? */
917         conflict = 1;
918         lh->v.u.s.aux = extra;  /* previous assignment will use safe copy */
919       }
920     }
921   }
922   if (conflict) {
923     luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0);  /* make copy */
924     luaK_reserveregs(fs, 1);
925   }
926 }
927 
928 
assignment(LexState * ls,struct LHS_assign * lh,int nvars)929 static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
930   expdesc e;
931   check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
932                       "syntax error");
933   if (testnext(ls, ',')) {  /* assignment -> `,' primaryexp assignment */
934     struct LHS_assign nv;
935     nv.prev = lh;
936     primaryexp(ls, &nv.v);
937     if (nv.v.k == VLOCAL)
938       check_conflict(ls, lh, &nv.v);
939     luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - ls->L->nCcalls,
940                     "variables in assignment");
941     assignment(ls, &nv, nvars+1);
942   }
943   else {  /* assignment -> `=' explist1 */
944     int nexps;
945     checknext(ls, '=');
946     nexps = explist1(ls, &e);
947     if (nexps != nvars) {
948       adjust_assign(ls, nvars, nexps, &e);
949       if (nexps > nvars)
950         ls->fs->freereg -= nexps - nvars;  /* remove extra values */
951     }
952     else {
953       luaK_setoneret(ls->fs, &e);  /* close last expression */
954       luaK_storevar(ls->fs, &lh->v, &e);
955       return;  /* avoid default */
956     }
957   }
958   init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */
959   luaK_storevar(ls->fs, &lh->v, &e);
960 }
961 
962 
cond(LexState * ls)963 static int cond (LexState *ls) {
964   /* cond -> exp */
965   expdesc v;
966   expr(ls, &v);  /* read condition */
967   if (v.k == VNIL) v.k = VFALSE;  /* `falses' are all equal here */
968   luaK_goiftrue(ls->fs, &v);
969   return v.f;
970 }
971 
972 
breakstat(LexState * ls)973 static void breakstat (LexState *ls) {
974   FuncState *fs = ls->fs;
975   BlockCnt *bl = fs->bl;
976   int upval = 0;
977   while (bl && !bl->isbreakable) {
978     upval |= bl->upval;
979     bl = bl->previous;
980   }
981   if (!bl)
982     luaX_syntaxerror(ls, "no loop to break");
983   if (upval)
984     luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
985   luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
986 }
987 
988 
whilestat(LexState * ls,int line)989 static void whilestat (LexState *ls, int line) {
990   /* whilestat -> WHILE cond DO block END */
991   FuncState *fs = ls->fs;
992   int whileinit;
993   int condexit;
994   BlockCnt bl;
995   luaX_next(ls);  /* skip WHILE */
996   whileinit = luaK_getlabel(fs);
997   condexit = cond(ls);
998   enterblock(fs, &bl, 1);
999   checknext(ls, TK_DO);
1000   block(ls);
1001   luaK_patchlist(fs, luaK_jump(fs), whileinit);
1002   check_match(ls, TK_END, TK_WHILE, line);
1003   leaveblock(fs);
1004   luaK_patchtohere(fs, condexit);  /* false conditions finish the loop */
1005 }
1006 
1007 
repeatstat(LexState * ls,int line)1008 static void repeatstat (LexState *ls, int line) {
1009   /* repeatstat -> REPEAT block UNTIL cond */
1010   int condexit;
1011   FuncState *fs = ls->fs;
1012   int repeat_init = luaK_getlabel(fs);
1013   BlockCnt bl1, bl2;
1014   enterblock(fs, &bl1, 1);  /* loop block */
1015   enterblock(fs, &bl2, 0);  /* scope block */
1016   luaX_next(ls);  /* skip REPEAT */
1017   chunk(ls);
1018   check_match(ls, TK_UNTIL, TK_REPEAT, line);
1019   condexit = cond(ls);  /* read condition (inside scope block) */
1020   if (!bl2.upval) {  /* no upvalues? */
1021     leaveblock(fs);  /* finish scope */
1022     luaK_patchlist(ls->fs, condexit, repeat_init);  /* close the loop */
1023   }
1024   else {  /* complete semantics when there are upvalues */
1025     breakstat(ls);  /* if condition then break */
1026     luaK_patchtohere(ls->fs, condexit);  /* else... */
1027     leaveblock(fs);  /* finish scope... */
1028     luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init);  /* and repeat */
1029   }
1030   leaveblock(fs);  /* finish loop */
1031 }
1032 
1033 
exp1(LexState * ls)1034 static int exp1 (LexState *ls) {
1035   expdesc e;
1036   int k;
1037   expr(ls, &e);
1038   k = e.k;
1039   luaK_exp2nextreg(ls->fs, &e);
1040   return k;
1041 }
1042 
1043 
forbody(LexState * ls,int base,int line,int nvars,int isnum)1044 static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1045   /* forbody -> DO block */
1046   BlockCnt bl;
1047   FuncState *fs = ls->fs;
1048   int prep, endfor;
1049   adjustlocalvars(ls, 3);  /* control variables */
1050   checknext(ls, TK_DO);
1051   prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1052   enterblock(fs, &bl, 0);  /* scope for declared variables */
1053   adjustlocalvars(ls, nvars);
1054   luaK_reserveregs(fs, nvars);
1055   block(ls);
1056   leaveblock(fs);  /* end of scope for declared variables */
1057   luaK_patchtohere(fs, prep);
1058   endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) :
1059                      luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars);
1060   luaK_fixline(fs, line);  /* pretend that `OP_FOR' starts the loop */
1061   luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1);
1062 }
1063 
1064 
fornum(LexState * ls,TString * varname,int line)1065 static void fornum (LexState *ls, TString *varname, int line) {
1066   /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1067   FuncState *fs = ls->fs;
1068   int base = fs->freereg;
1069   new_localvarliteral(ls, "(for index)", 0);
1070   new_localvarliteral(ls, "(for limit)", 1);
1071   new_localvarliteral(ls, "(for step)", 2);
1072   new_localvar(ls, varname, 3);
1073   checknext(ls, '=');
1074   exp1(ls);  /* initial value */
1075   checknext(ls, ',');
1076   exp1(ls);  /* limit */
1077   if (testnext(ls, ','))
1078     exp1(ls);  /* optional step */
1079   else {  /* default step = 1 */
1080     luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1));
1081     luaK_reserveregs(fs, 1);
1082   }
1083   forbody(ls, base, line, 1, 1);
1084 }
1085 
1086 
forlist(LexState * ls,TString * indexname)1087 static void forlist (LexState *ls, TString *indexname) {
1088   /* forlist -> NAME {,NAME} IN explist1 forbody */
1089   FuncState *fs = ls->fs;
1090   expdesc e;
1091   int nvars = 0;
1092   int line;
1093   int base = fs->freereg;
1094   /* create control variables */
1095   new_localvarliteral(ls, "(for generator)", nvars++);
1096   new_localvarliteral(ls, "(for state)", nvars++);
1097   new_localvarliteral(ls, "(for control)", nvars++);
1098   /* create declared variables */
1099   new_localvar(ls, indexname, nvars++);
1100   while (testnext(ls, ','))
1101     new_localvar(ls, str_checkname(ls), nvars++);
1102   checknext(ls, TK_IN);
1103   line = ls->linenumber;
1104   adjust_assign(ls, 3, explist1(ls, &e), &e);
1105   luaK_checkstack(fs, 3);  /* extra space to call generator */
1106   forbody(ls, base, line, nvars - 3, 0);
1107 }
1108 
1109 
forstat(LexState * ls,int line)1110 static void forstat (LexState *ls, int line) {
1111   /* forstat -> FOR (fornum | forlist) END */
1112   FuncState *fs = ls->fs;
1113   TString *varname;
1114   BlockCnt bl;
1115   enterblock(fs, &bl, 1);  /* scope for loop and control variables */
1116   luaX_next(ls);  /* skip `for' */
1117   varname = str_checkname(ls);  /* first variable name */
1118   switch (ls->t.token) {
1119     case '=': fornum(ls, varname, line); break;
1120     case ',': case TK_IN: forlist(ls, varname); break;
1121     default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
1122   }
1123   check_match(ls, TK_END, TK_FOR, line);
1124   leaveblock(fs);  /* loop scope (`break' jumps to this point) */
1125 }
1126 
1127 
test_then_block(LexState * ls)1128 static int test_then_block (LexState *ls) {
1129   /* test_then_block -> [IF | ELSEIF] cond THEN block */
1130   int condexit;
1131   luaX_next(ls);  /* skip IF or ELSEIF */
1132   condexit = cond(ls);
1133   checknext(ls, TK_THEN);
1134   block(ls);  /* `then' part */
1135   return condexit;
1136 }
1137 
1138 
ifstat(LexState * ls,int line)1139 static void ifstat (LexState *ls, int line) {
1140   /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1141   FuncState *fs = ls->fs;
1142   int flist;
1143   int escapelist = NO_JUMP;
1144   flist = test_then_block(ls);  /* IF cond THEN block */
1145   while (ls->t.token == TK_ELSEIF) {
1146     luaK_concat(fs, &escapelist, luaK_jump(fs));
1147     luaK_patchtohere(fs, flist);
1148     flist = test_then_block(ls);  /* ELSEIF cond THEN block */
1149   }
1150   if (ls->t.token == TK_ELSE) {
1151     luaK_concat(fs, &escapelist, luaK_jump(fs));
1152     luaK_patchtohere(fs, flist);
1153     luaX_next(ls);  /* skip ELSE (after patch, for correct line info) */
1154     block(ls);  /* `else' part */
1155   }
1156   else
1157     luaK_concat(fs, &escapelist, flist);
1158   luaK_patchtohere(fs, escapelist);
1159   check_match(ls, TK_END, TK_IF, line);
1160 }
1161 
1162 
localfunc(LexState * ls)1163 static void localfunc (LexState *ls) {
1164   expdesc v, b;
1165   FuncState *fs = ls->fs;
1166   new_localvar(ls, str_checkname(ls), 0);
1167   init_exp(&v, VLOCAL, fs->freereg);
1168   luaK_reserveregs(fs, 1);
1169   adjustlocalvars(ls, 1);
1170   body(ls, &b, 0, ls->linenumber);
1171   luaK_storevar(fs, &v, &b);
1172   /* debug information will only see the variable after this point! */
1173   getlocvar(fs, fs->nactvar - 1).startpc = fs->pc;
1174 }
1175 
1176 
localstat(LexState * ls)1177 static void localstat (LexState *ls) {
1178   /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
1179   int nvars = 0;
1180   int nexps;
1181   expdesc e;
1182   do {
1183     new_localvar(ls, str_checkname(ls), nvars++);
1184   } while (testnext(ls, ','));
1185   if (testnext(ls, '='))
1186     nexps = explist1(ls, &e);
1187   else {
1188     e.k = VVOID;
1189     nexps = 0;
1190   }
1191   adjust_assign(ls, nvars, nexps, &e);
1192   adjustlocalvars(ls, nvars);
1193 }
1194 
1195 
funcname(LexState * ls,expdesc * v)1196 static int funcname (LexState *ls, expdesc *v) {
1197   /* funcname -> NAME {field} [`:' NAME] */
1198   int needself = 0;
1199   singlevar(ls, v);
1200   while (ls->t.token == '.')
1201     field(ls, v);
1202   if (ls->t.token == ':') {
1203     needself = 1;
1204     field(ls, v);
1205   }
1206   return needself;
1207 }
1208 
1209 
funcstat(LexState * ls,int line)1210 static void funcstat (LexState *ls, int line) {
1211   /* funcstat -> FUNCTION funcname body */
1212   int needself;
1213   expdesc v, b;
1214   luaX_next(ls);  /* skip FUNCTION */
1215   needself = funcname(ls, &v);
1216   body(ls, &b, needself, line);
1217   luaK_storevar(ls->fs, &v, &b);
1218   luaK_fixline(ls->fs, line);  /* definition `happens' in the first line */
1219 }
1220 
1221 
exprstat(LexState * ls)1222 static void exprstat (LexState *ls) {
1223   /* stat -> func | assignment */
1224   FuncState *fs = ls->fs;
1225   struct LHS_assign v;
1226   primaryexp(ls, &v.v);
1227   if (v.v.k == VCALL)  /* stat -> func */
1228     SETARG_C(getcode(fs, &v.v), 1);  /* call statement uses no results */
1229   else {  /* stat -> assignment */
1230     v.prev = NULL;
1231     assignment(ls, &v, 1);
1232   }
1233 }
1234 
1235 
retstat(LexState * ls)1236 static void retstat (LexState *ls) {
1237   /* stat -> RETURN explist */
1238   FuncState *fs = ls->fs;
1239   expdesc e;
1240   int first, nret;  /* registers with returned values */
1241   luaX_next(ls);  /* skip RETURN */
1242   if (block_follow(ls->t.token) || ls->t.token == ';')
1243     first = nret = 0;  /* return no values */
1244   else {
1245     nret = explist1(ls, &e);  /* optional return values */
1246     if (hasmultret(e.k)) {
1247       luaK_setmultret(fs, &e);
1248       if (e.k == VCALL && nret == 1) {  /* tail call? */
1249         SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1250         lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1251       }
1252       first = fs->nactvar;
1253       nret = LUA_MULTRET;  /* return all values */
1254     }
1255     else {
1256       if (nret == 1)  /* only one single value? */
1257         first = luaK_exp2anyreg(fs, &e);
1258       else {
1259         luaK_exp2nextreg(fs, &e);  /* values must go to the `stack' */
1260         first = fs->nactvar;  /* return all `active' values */
1261         lua_assert(nret == fs->freereg - first);
1262       }
1263     }
1264   }
1265   luaK_ret(fs, first, nret);
1266 }
1267 
1268 
statement(LexState * ls)1269 static int statement (LexState *ls) {
1270   int line = ls->linenumber;  /* may be needed for error messages */
1271   switch (ls->t.token) {
1272     case TK_IF: {  /* stat -> ifstat */
1273       ifstat(ls, line);
1274       return 0;
1275     }
1276     case TK_WHILE: {  /* stat -> whilestat */
1277       whilestat(ls, line);
1278       return 0;
1279     }
1280     case TK_DO: {  /* stat -> DO block END */
1281       luaX_next(ls);  /* skip DO */
1282       block(ls);
1283       check_match(ls, TK_END, TK_DO, line);
1284       return 0;
1285     }
1286     case TK_FOR: {  /* stat -> forstat */
1287       forstat(ls, line);
1288       return 0;
1289     }
1290     case TK_REPEAT: {  /* stat -> repeatstat */
1291       repeatstat(ls, line);
1292       return 0;
1293     }
1294     case TK_FUNCTION: {
1295       funcstat(ls, line);  /* stat -> funcstat */
1296       return 0;
1297     }
1298     case TK_LOCAL: {  /* stat -> localstat */
1299       luaX_next(ls);  /* skip LOCAL */
1300       if (testnext(ls, TK_FUNCTION))  /* local function? */
1301         localfunc(ls);
1302       else
1303         localstat(ls);
1304       return 0;
1305     }
1306     case TK_RETURN: {  /* stat -> retstat */
1307       retstat(ls);
1308       return 1;  /* must be last statement */
1309     }
1310     case TK_BREAK: {  /* stat -> breakstat */
1311       luaX_next(ls);  /* skip BREAK */
1312       breakstat(ls);
1313       return 1;  /* must be last statement */
1314     }
1315     default: {
1316       exprstat(ls);
1317       return 0;  /* to avoid warnings */
1318     }
1319   }
1320 }
1321 
1322 
chunk(LexState * ls)1323 static void chunk (LexState *ls) {
1324   /* chunk -> { stat [`;'] } */
1325   int islast = 0;
1326   enterlevel(ls);
1327   while (!islast && !block_follow(ls->t.token)) {
1328     islast = statement(ls);
1329     testnext(ls, ';');
1330     lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1331                ls->fs->freereg >= ls->fs->nactvar);
1332     ls->fs->freereg = ls->fs->nactvar;  /* free registers */
1333   }
1334   leavelevel(ls);
1335 }
1336 
1337 /* }====================================================================== */
1338