use lua_mem(L, +-size) to track your additional userdata sizes. keep it balanced...
[blua.git] / src / lparser.c
blob12be12fae38fa8125880b06f95a84bf258f40b27
1 /*
2 ** $Id: lparser.c,v 2.42.1.3 2007/12/28 15:32:23 roberto Exp $
3 ** Lua Parser
4 ** See Copyright Notice in lua.h
5 */
8 #include <string.h>
10 #define lparser_c
11 #define LUA_CORE
13 #include "lua.h"
15 #include "lcode.h"
16 #include "ldebug.h"
17 #include "ldo.h"
18 #include "lfunc.h"
19 #include "llex.h"
20 #include "lmem.h"
21 #include "lobject.h"
22 #include "lopcodes.h"
23 #include "lparser.h"
24 #include "lstate.h"
25 #include "lstring.h"
26 #include "ltable.h"
30 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
32 #define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]])
34 #define luaY_checklimit(fs,v,l,m) if ((v)>(l)) errorlimit(fs,l,m)
38 ** nodes for block list (list of active blocks)
40 typedef struct BlockCnt {
41 struct BlockCnt *previous; /* chain */
42 int breaklist; /* list of jumps out of this loop */
43 int continuelist;
44 lu_byte nactvar; /* # active locals outside the breakable structure */
45 lu_byte upval; /* true if some variable in the block is an upvalue */
46 lu_byte isbreakable; /* true if `block' is a loop */
47 } BlockCnt;
52 ** prototypes for recursive non-terminal functions
54 static void chunk (LexState *ls);
55 static void expr (LexState *ls, expdesc *v);
58 static void anchor_token (LexState *ls) {
59 if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
60 TString *ts = ls->t.seminfo.ts;
61 luaX_newstring(ls, getstr(ts), ts->tsv.len);
66 static void error_expected (LexState *ls, int token) {
67 luaX_syntaxerror(ls,
68 luaO_pushfstring(ls->L, LUA_QS " expected", luaX_token2str(ls, token)));
72 static void errorlimit (FuncState *fs, int limit, const char *what) {
73 const char *msg = (fs->f->linedefined == 0) ?
74 luaO_pushfstring(fs->L, "main function has more than %d %s", limit, what) :
75 luaO_pushfstring(fs->L, "function at line %d has more than %d %s",
76 fs->f->linedefined, limit, what);
77 luaX_lexerror(fs->ls, msg, 0);
81 static int testnext (LexState *ls, int c) {
82 if (ls->t.token == c) {
83 luaX_next(ls);
84 return 1;
86 else return 0;
90 static void check (LexState *ls, int c) {
91 if (ls->t.token != c)
92 error_expected(ls, c);
95 static void checknext (LexState *ls, int c) {
96 check(ls, c);
97 luaX_next(ls);
101 #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
105 static void check_match (LexState *ls, int what, int who, int where) {
106 if (!testnext(ls, what)) {
107 if (where == ls->linenumber)
108 error_expected(ls, what);
109 else {
110 luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
111 LUA_QS " expected (to close " LUA_QS " at line %d)",
112 luaX_token2str(ls, what), luaX_token2str(ls, who), where));
118 static TString *str_checkname (LexState *ls) {
119 TString *ts;
120 check(ls, TK_NAME);
121 ts = ls->t.seminfo.ts;
122 luaX_next(ls);
123 return ts;
127 static void init_exp (expdesc *e, expkind k, int i) {
128 e->f = e->t = NO_JUMP;
129 e->k = k;
130 e->u.s.info = i;
134 static void codestring (LexState *ls, expdesc *e, TString *s) {
135 init_exp(e, VK, luaK_stringK(ls->fs, s));
139 static void checkname(LexState *ls, expdesc *e) {
140 codestring(ls, e, str_checkname(ls));
144 static int registerlocalvar (LexState *ls, TString *varname) {
145 FuncState *fs = ls->fs;
146 Proto *f = fs->f;
147 int oldsize = f->sizelocvars;
148 luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
149 LocVar, SHRT_MAX, "too many local variables");
150 while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
151 f->locvars[fs->nlocvars].varname = varname;
152 luaC_objbarrier(ls->L, f, varname);
153 return fs->nlocvars++;
157 #define new_localvarliteral(ls,v,n) \
158 new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n)
161 static void new_localvar (LexState *ls, TString *name, int n) {
162 FuncState *fs = ls->fs;
163 luaY_checklimit(fs, fs->nactvar+n+1, LUAI_MAXVARS, "local variables");
164 fs->actvar[fs->nactvar+n] = cast(unsigned short, registerlocalvar(ls, name));
168 static void adjustlocalvars (LexState *ls, int nvars) {
169 FuncState *fs = ls->fs;
170 fs->nactvar = cast_byte(fs->nactvar + nvars);
171 for (; nvars; nvars--) {
172 getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc;
177 static void removevars (LexState *ls, int tolevel) {
178 FuncState *fs = ls->fs;
179 while (fs->nactvar > tolevel)
180 getlocvar(fs, --fs->nactvar).endpc = fs->pc;
184 static int indexupvalue (FuncState *fs, TString *name, expdesc *v) {
185 int i;
186 Proto *f = fs->f;
187 int oldsize = f->sizeupvalues;
188 for (i=0; i<f->nups; i++) {
189 if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->u.s.info) {
190 lua_assert(f->upvalues[i] == name);
191 return i;
194 /* new one */
195 luaY_checklimit(fs, f->nups + 1, LUAI_MAXUPVALUES, "upvalues");
196 luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues,
197 TString *, MAX_INT, "");
198 while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL;
199 f->upvalues[f->nups] = name;
200 luaC_objbarrier(fs->L, f, name);
201 lua_assert(v->k == VLOCAL || v->k == VUPVAL);
202 fs->upvalues[f->nups].k = cast_byte(v->k);
203 fs->upvalues[f->nups].info = cast_byte(v->u.s.info);
204 return f->nups++;
208 static int searchvar (FuncState *fs, TString *n) {
209 int i;
210 for (i=fs->nactvar-1; i >= 0; i--) {
211 if (n == getlocvar(fs, i).varname)
212 return i;
214 return -1; /* not found */
218 static void markupval (FuncState *fs, int level) {
219 BlockCnt *bl = fs->bl;
220 while (bl && bl->nactvar > level) bl = bl->previous;
221 if (bl) bl->upval = 1;
225 static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
226 if (fs == NULL) { /* no more levels? */
227 init_exp(var, VGLOBAL, NO_REG); /* default is global variable */
228 return VGLOBAL;
230 else {
231 int v = searchvar(fs, n); /* look up at current level */
232 if (v >= 0) {
233 init_exp(var, VLOCAL, v);
234 if (!base)
235 markupval(fs, v); /* local will be used as an upval */
236 return VLOCAL;
238 else { /* not found at current level; try upper one */
239 if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL)
240 return VGLOBAL;
241 var->u.s.info = indexupvalue(fs, n, var); /* else was LOCAL or UPVAL */
242 var->k = VUPVAL; /* upvalue in this level */
243 return VUPVAL;
249 static void singlevar (LexState *ls, expdesc *var) {
250 TString *varname = str_checkname(ls);
251 FuncState *fs = ls->fs;
252 if (singlevaraux(fs, varname, var, 1) == VGLOBAL)
253 var->u.s.info = luaK_stringK(fs, varname); /* info points to global name */
257 static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
258 FuncState *fs = ls->fs;
259 int extra = nvars - nexps;
260 if (hasmultret(e->k)) {
261 extra++; /* includes call itself */
262 if (extra < 0) extra = 0;
263 luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
264 if (extra > 1) luaK_reserveregs(fs, extra-1);
266 else {
267 if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */
268 if (extra > 0) {
269 int reg = fs->freereg;
270 luaK_reserveregs(fs, extra);
271 luaK_nil(fs, reg, extra);
277 static void enterlevel (LexState *ls) {
278 if (++ls->L->nCcalls > LUAI_MAXCCALLS)
279 luaX_lexerror(ls, "chunk has too many syntax levels", 0);
283 #define leavelevel(ls) ((ls)->L->nCcalls--)
286 static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) {
287 bl->breaklist = NO_JUMP;
288 bl->continuelist = NO_JUMP;
289 bl->isbreakable = isbreakable;
290 bl->nactvar = fs->nactvar;
291 bl->upval = 0;
292 bl->previous = fs->bl;
293 fs->bl = bl;
294 lua_assert(fs->freereg == fs->nactvar);
298 static void leaveblock (FuncState *fs) {
299 BlockCnt *bl = fs->bl;
300 fs->bl = bl->previous;
301 removevars(fs->ls, bl->nactvar);
302 if (bl->upval)
303 luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
304 /* a block either controls scope or breaks (never both) */
305 lua_assert(!bl->isbreakable || !bl->upval);
306 lua_assert(bl->nactvar == fs->nactvar);
307 fs->freereg = fs->nactvar; /* free registers */
308 luaK_patchtohere(fs, bl->breaklist);
312 static void pushclosure (LexState *ls, FuncState *func, expdesc *v) {
313 FuncState *fs = ls->fs;
314 Proto *f = fs->f;
315 int oldsize = f->sizep;
316 int i;
317 luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
318 MAXARG_Bx, "constant table overflow");
319 while (oldsize < f->sizep) f->p[oldsize++] = NULL;
320 f->p[fs->np++] = func->f;
321 luaC_objbarrier(ls->L, f, func->f);
322 init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
323 for (i=0; i<func->f->nups; i++) {
324 OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
325 luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0);
330 static void open_func (LexState *ls, FuncState *fs) {
331 lua_State *L = ls->L;
332 Proto *f = luaF_newproto(L);
333 fs->f = f;
334 fs->prev = ls->fs; /* linked list of funcstates */
335 fs->ls = ls;
336 fs->L = L;
337 ls->fs = fs;
338 fs->lhs = NULL;
339 fs->nlhs = 0;
340 fs->nrhs = 0;
341 fs->pc = 0;
342 fs->lasttarget = -1;
343 fs->jpc = NO_JUMP;
344 fs->freereg = 0;
345 fs->nk = 0;
346 fs->np = 0;
347 fs->nlocvars = 0;
348 fs->nactvar = 0;
349 fs->bl = NULL;
350 f->source = ls->source;
351 f->maxstacksize = 2; /* registers 0/1 are always valid */
352 fs->h = luaH_new(L, 0, 0);
353 /* anchor table of constants and prototype (to avoid being collected) */
354 sethvalue2s(L, L->top, fs->h);
355 incr_top(L);
356 setptvalue2s(L, L->top, f);
357 incr_top(L);
361 static void close_func (LexState *ls) {
362 lua_State *L = ls->L;
363 FuncState *fs = ls->fs;
364 Proto *f = fs->f;
365 removevars(ls, 0);
366 luaK_ret(fs, 0, 0); /* final return */
367 luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
368 f->sizecode = fs->pc;
369 luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
370 f->sizelineinfo = fs->pc;
371 luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
372 f->sizek = fs->nk;
373 luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
374 f->sizep = fs->np;
375 luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
376 f->sizelocvars = fs->nlocvars;
377 luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *);
378 f->sizeupvalues = f->nups;
379 lua_assert(luaG_checkcode(f));
380 lua_assert(fs->bl == NULL);
381 ls->fs = fs->prev;
382 L->top -= 2; /* remove table and prototype from the stack */
383 /* last token read was anchored in defunct function; must reanchor it */
384 if (fs) anchor_token(ls);
388 Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
389 struct LexState lexstate;
390 struct FuncState funcstate;
391 lexstate.buff = buff;
392 luaX_setinput(L, &lexstate, z, luaS_new(L, name));
393 open_func(&lexstate, &funcstate);
394 funcstate.f->is_vararg = VARARG_ISVARARG; /* main func. is always vararg */
395 luaX_next(&lexstate); /* read first token */
396 chunk(&lexstate);
397 check(&lexstate, TK_EOS);
398 close_func(&lexstate);
399 lua_assert(funcstate.prev == NULL);
400 lua_assert(funcstate.f->nups == 0);
401 lua_assert(lexstate.fs == NULL);
402 return funcstate.f;
407 /*============================================================*/
408 /* GRAMMAR RULES */
409 /*============================================================*/
412 static void field (LexState *ls, expdesc *v) {
413 /* field -> ['.' | ':'] NAME */
414 FuncState *fs = ls->fs;
415 expdesc key;
416 luaK_exp2anyreg(fs, v);
417 luaX_next(ls); /* skip the dot or colon */
418 checkname(ls, &key);
419 luaK_indexed(fs, v, &key);
423 static void yindex (LexState *ls, expdesc *v) {
424 /* index -> '[' expr ']' */
425 luaX_next(ls); /* skip the '[' */
426 expr(ls, v);
427 luaK_exp2val(ls->fs, v);
428 checknext(ls, ']');
433 ** {======================================================================
434 ** Rules for Constructors
435 ** =======================================================================
439 struct ConsControl {
440 expdesc v; /* last list item read */
441 expdesc *t; /* table descriptor */
442 int nh; /* total number of `record' elements */
443 int na; /* total number of array elements */
444 int tostore; /* number of array elements pending to be stored */
448 static void recfield (LexState *ls, struct ConsControl *cc) {
449 /* recfield -> (NAME | `['exp1`]') = exp1 */
450 FuncState *fs = ls->fs;
451 int reg = ls->fs->freereg;
452 expdesc key, val;
453 int rkkey;
454 if (ls->t.token == TK_NAME) {
455 luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
456 checkname(ls, &key);
458 else /* ls->t.token == '[' */
459 yindex(ls, &key);
460 cc->nh++;
461 checknext(ls, '=');
462 rkkey = luaK_exp2RK(fs, &key);
463 expr(ls, &val);
464 luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val));
465 fs->freereg = reg; /* free registers */
469 static void closelistfield (FuncState *fs, struct ConsControl *cc) {
470 if (cc->v.k == VVOID) return; /* there is no list item */
471 luaK_exp2nextreg(fs, &cc->v);
472 cc->v.k = VVOID;
473 if (cc->tostore == LFIELDS_PER_FLUSH) {
474 luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore); /* flush */
475 cc->tostore = 0; /* no more items pending */
480 static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
481 if (cc->tostore == 0) return;
482 if (hasmultret(cc->v.k)) {
483 luaK_setmultret(fs, &cc->v);
484 luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET);
485 cc->na--; /* do not count last expression (unknown number of elements) */
487 else {
488 if (cc->v.k != VVOID)
489 luaK_exp2nextreg(fs, &cc->v);
490 luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);
495 static void listfield (LexState *ls, struct ConsControl *cc) {
496 expr(ls, &cc->v);
497 luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
498 cc->na++;
499 cc->tostore++;
503 static void constructor (LexState *ls, expdesc *t) {
504 /* constructor -> ?? */
505 FuncState *fs = ls->fs;
506 int line = ls->linenumber;
507 int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
508 struct ConsControl cc;
509 cc.na = cc.nh = cc.tostore = 0;
510 cc.t = t;
511 init_exp(t, VRELOCABLE, pc);
512 init_exp(&cc.v, VVOID, 0); /* no value (yet) */
513 luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */
514 checknext(ls, '{');
515 do {
516 lua_assert(cc.v.k == VVOID || cc.tostore > 0);
517 if (ls->t.token == '}') break;
518 closelistfield(fs, &cc);
519 switch(ls->t.token) {
520 case TK_NAME: { /* may be listfields or recfields */
521 luaX_lookahead(ls);
522 if (ls->lookahead.token != '=') /* expression? */
523 listfield(ls, &cc);
524 else
525 recfield(ls, &cc);
526 break;
528 case '[': { /* constructor_item -> recfield */
529 recfield(ls, &cc);
530 break;
532 default: { /* constructor_part -> listfield */
533 listfield(ls, &cc);
534 break;
537 } while (testnext(ls, ',') || testnext(ls, ';'));
538 check_match(ls, '}', '{', line);
539 lastlistfield(fs, &cc);
540 SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
541 SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
544 /* }====================================================================== */
548 static void parlist (LexState *ls) {
549 /* parlist -> [ param { `,' param } ] */
550 FuncState *fs = ls->fs;
551 Proto *f = fs->f;
552 int nparams = 0;
553 f->is_vararg = 0;
554 if (ls->t.token != ')') { /* is `parlist' not empty? */
555 do {
556 switch (ls->t.token) {
557 case TK_NAME: { /* param -> NAME */
558 new_localvar(ls, str_checkname(ls), nparams++);
559 break;
561 case TK_DOTS: { /* param -> `...' */
562 luaX_next(ls);
563 #if defined(LUA_COMPAT_VARARG)
564 /* use `arg' as default name */
565 new_localvarliteral(ls, "arg", nparams++);
566 f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG;
567 #endif
568 f->is_vararg |= VARARG_ISVARARG;
569 break;
571 default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
573 } while (!f->is_vararg && testnext(ls, ','));
575 adjustlocalvars(ls, nparams);
576 f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG));
577 luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
581 /*AK(12-Jan-06): DO_PATCH "do .. end" same as "function() ... end"
583 * The following functions are shortened versions of 'parlist()' and
584 * 'body()', please compare with them if there's issues.
586 static void parlist_empty (LexState *ls) {
587 FuncState *fs = ls->fs;
588 Proto *f = fs->f;
589 f->is_vararg = 0;
590 adjustlocalvars(ls, 0 /*nparams*/);
591 f->numparams = cast_byte(fs->nactvar);
592 luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
594 static void body_noparms (LexState *ls, expdesc *e, int line) {
595 /* body -> chunk END */
596 FuncState new_fs;
597 open_func(ls, &new_fs);
598 new_fs.f->linedefined = line;
599 parlist_empty(ls);
600 chunk(ls);
601 new_fs.f->lastlinedefined = ls->linenumber;
602 check_match(ls, TK_END, TK_DO /*TK_FUNCTION*/, line);
603 close_func(ls);
604 pushclosure(ls, &new_fs, e);
606 static void body (LexState *ls, expdesc *e, int needself, int line) {
607 /* body -> `(' parlist `)' chunk END */
608 FuncState new_fs;
609 open_func(ls, &new_fs);
610 new_fs.f->linedefined = line;
611 checknext(ls, '(');
612 if (needself) {
613 new_localvarliteral(ls, "self", 0);
614 adjustlocalvars(ls, 1);
616 parlist(ls);
617 checknext(ls, ')');
618 chunk(ls);
619 new_fs.f->lastlinedefined = ls->linenumber;
620 check_match(ls, TK_END, TK_FUNCTION, line);
621 close_func(ls);
622 pushclosure(ls, &new_fs, e);
626 static int explist1 (LexState *ls, expdesc *v) {
627 /* explist1 -> expr { `,' expr } */
628 int n = 1; /* at least one expression */
629 expr(ls, v);
630 while (testnext(ls, ',')) {
631 luaK_exp2nextreg(ls->fs, v);
632 expr(ls, v);
633 n++;
635 return n;
639 static void funcargs (LexState *ls, expdesc *f) {
640 FuncState *fs = ls->fs;
641 expdesc args;
642 int base, nparams;
643 int line = ls->linenumber;
644 switch (ls->t.token) {
645 case '(': { /* funcargs -> `(' [ explist1 ] `)' */
646 // if (line != ls->lastline)
647 // luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
648 luaX_next(ls);
649 if (ls->t.token == ')') /* arg list is empty? */
650 args.k = VVOID;
651 else {
652 explist1(ls, &args);
653 luaK_setmultret(fs, &args);
655 check_match(ls, ')', '(', line);
656 break;
658 case '{': { /* funcargs -> constructor */
659 constructor(ls, &args);
660 break;
662 case TK_STRING: { /* funcargs -> STRING */
663 codestring(ls, &args, ls->t.seminfo.ts);
664 luaX_next(ls); /* must use `seminfo' before `next' */
665 break;
667 default: {
668 luaX_syntaxerror(ls, "function arguments expected");
669 return;
672 lua_assert(f->k == VNONRELOC);
673 base = f->u.s.info; /* base register for call */
674 if (hasmultret(args.k))
675 nparams = LUA_MULTRET; /* open call */
676 else {
677 if (args.k != VVOID)
678 luaK_exp2nextreg(fs, &args); /* close last argument */
679 nparams = fs->freereg - (base+1);
681 init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
682 luaK_fixline(fs, line);
683 fs->freereg = base+1; /* call remove function and arguments and leaves
684 (unless changed) one result */
691 ** {======================================================================
692 ** Expression parsing
693 ** =======================================================================
697 static void prefixexp (LexState *ls, expdesc *v) {
698 /* prefixexp -> NAME | '(' expr ')' */
699 switch (ls->t.token) {
700 case '(': {
701 int line = ls->linenumber;
702 luaX_next(ls);
703 expr(ls, v);
704 check_match(ls, ')', '(', line);
705 luaK_dischargevars(ls->fs, v);
706 return;
708 case TK_NAME: {
709 singlevar(ls, v);
710 return;
712 case '$': {
713 int i = ls->t.seminfo.r;
714 if (i == 0) i = ls->fs->nrhs;
715 if (i <= 0 || i > ls->fs->nlhs)
716 luaX_syntaxerror(ls, "pseudo-variable out of range or not in assignment");
717 else {
718 expdesc_list *lhs = ls->fs->lhs;
719 i = ls->fs->nlhs - i;
720 while (i--) lhs = lhs->prev;
721 *v = lhs->v;
722 /* If this is a VINDEXED, we need to stash the result in a temporary without
723 * freereg'ing the index locals. Really, it would be better to keep the value
724 * in case we repeat the $, but there's no way to do that without shifting all
725 * the temps up one slot to create room for the value. It would be semantically
726 * correct to also do that for globals, in case I ever get around to importing
727 * the shift mechanism from comprehensions.
729 if (v->k == VINDEXED) {
730 int extra = ls->fs->freereg;
731 luaK_codeABC(ls->fs, OP_GETTABLE, extra, v->u.s.info, v->u.s.aux);
732 v->k = VNONRELOC;
733 v->u.s.info = extra;
734 luaK_reserveregs(ls->fs, 1);
737 luaX_next(ls);
738 return;
740 default: {
741 luaX_syntaxerror(ls, "unexpected symbol");
742 return;
748 static void primaryexp (LexState *ls, expdesc *v) {
749 /* primaryexp ->
750 prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
751 FuncState *fs = ls->fs;
752 prefixexp(ls, v);
753 for (;;) {
754 switch (ls->t.token) {
755 case '.': { /* field */
756 field(ls, v);
757 break;
759 case '[': { /* `[' exp1 `]' */
760 expdesc key;
761 luaK_exp2anyreg(fs, v);
762 yindex(ls, &key);
763 luaK_indexed(fs, v, &key);
764 break;
766 case ':': { /* `:' NAME funcargs */
767 expdesc key;
768 luaX_next(ls);
769 checkname(ls, &key);
770 luaK_self(fs, v, &key);
771 funcargs(ls, v);
772 break;
774 case '(': case TK_STRING: case '{': { /* funcargs */
775 luaK_exp2nextreg(fs, v);
776 funcargs(ls, v);
777 break;
779 default: return;
785 static void simpleexp (LexState *ls, expdesc *v) {
786 /* simpleexp -> NUMBER | STRING | NIL | true | false | ... |
787 constructor | FUNCTION body | primaryexp */
788 switch (ls->t.token) {
789 case TK_NUMBER: {
790 init_exp(v, VKNUM, 0);
791 v->u.nval = ls->t.seminfo.r;
792 break;
794 case TK_STRING: {
795 codestring(ls, v, ls->t.seminfo.ts);
796 break;
798 case TK_NIL: {
799 init_exp(v, VNIL, 0);
800 break;
802 case TK_TRUE: {
803 init_exp(v, VTRUE, 0);
804 break;
806 case TK_FALSE: {
807 init_exp(v, VFALSE, 0);
808 break;
810 case TK_DOTS: { /* vararg */
811 FuncState *fs = ls->fs;
812 check_condition(ls, fs->f->is_vararg,
813 "cannot use " LUA_QL("...") " outside a vararg function");
814 fs->f->is_vararg &= ~VARARG_NEEDSARG; /* don't need 'arg' */
815 init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
816 break;
818 case '{': { /* constructor */
819 constructor(ls, v);
820 return;
822 case TK_DO: { /* "do .. end" same as "function() .. end" */
823 luaX_next(ls); /* skip 'do' */
824 body_noparms(ls, v, ls->linenumber);
825 return;
827 case TK_FUNCTION: {
828 luaX_next(ls);
829 body(ls, v, 0, ls->linenumber);
830 return;
832 default: {
833 primaryexp(ls, v);
834 return;
837 luaX_next(ls);
841 static UnOpr getunopr (int op) {
842 switch (op) {
843 case TK_NOT: return OPR_NOT;
844 case '-': return OPR_MINUS;
845 case '#': return OPR_LEN;
846 case '~': return OPR_BNOT;
847 default: return OPR_NOUNOPR;
852 static BinOpr getbinopr (int op) {
853 switch (op) {
854 case '+': return OPR_ADD;
855 case '-': return OPR_SUB;
856 case '*': return OPR_MUL;
857 case '/': return OPR_DIV;
858 case '%': return OPR_MOD;
859 case '^': return OPR_POW;
860 case TK_CONCAT: return OPR_CONCAT;
861 case TK_NE: return OPR_NE;
862 case TK_EQ: return OPR_EQ;
863 case '<': return OPR_LT;
864 case TK_LE: return OPR_LE;
865 case '>': return OPR_GT;
866 case TK_GE: return OPR_GE;
867 case TK_AND: return OPR_AND;
868 case TK_OR: return OPR_OR;
869 case '&': return OPR_BAND;
870 case '|': return OPR_BOR;
871 case TK_XOR: return OPR_BXOR;
872 case TK_SHL: return OPR_BSHL;
873 case TK_SHR: return OPR_BSHR;
874 default: return OPR_NOBINOPR;
879 static const struct {
880 lu_byte left; /* left priority for each binary operator */
881 lu_byte right; /* right priority */
882 } priority[] = { /* ORDER OPR */
883 {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `/' `%' */
884 {10, 9}, {5, 4}, /* power and concat (right associative) */
885 {3, 3}, {3, 3}, /* equality and inequality */
886 {3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */
887 {2, 2}, {1, 1} /* logical (and/or) */
888 ,{6, 6}, {6, 6}, {6, 6}, /* bit-wise (band/bor/bxor) */
889 {7, 7}, {7, 7} /* shl/shr */
892 #define UNARY_PRIORITY 8 /* priority for unary operators */
896 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
897 ** where `binop' is any binary operator with a priority higher than `limit'
899 static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) {
900 BinOpr op;
901 UnOpr uop;
902 enterlevel(ls);
903 uop = getunopr(ls->t.token);
904 if (uop != OPR_NOUNOPR) {
905 luaX_next(ls);
906 subexpr(ls, v, UNARY_PRIORITY);
907 luaK_prefix(ls->fs, uop, v);
909 else simpleexp(ls, v);
910 /* expand while operators have priorities higher than `limit' */
911 op = getbinopr(ls->t.token);
912 while (op != OPR_NOBINOPR && priority[op].left > limit) {
913 expdesc v2;
914 BinOpr nextop;
915 luaX_next(ls);
916 luaK_infix(ls->fs, op, v);
917 /* read sub-expression with higher priority */
918 nextop = subexpr(ls, &v2, priority[op].right);
919 luaK_posfix(ls->fs, op, v, &v2);
920 op = nextop;
922 leavelevel(ls);
923 return op; /* return first untreated operator */
927 static void expr (LexState *ls, expdesc *v) {
928 subexpr(ls, v, 0);
931 /* }==================================================================== */
936 ** {======================================================================
937 ** Rules for Statements
938 ** =======================================================================
942 static int block_follow (int token) {
943 switch (token) {
944 case TK_ELSE: case TK_ELSEIF: case TK_END:
945 case TK_UNTIL: case TK_EOS:
946 return 1;
947 default: return 0;
952 static void block (LexState *ls) {
953 /* block -> chunk */
954 FuncState *fs = ls->fs;
955 BlockCnt bl;
956 enterblock(fs, &bl, 0);
957 chunk(ls);
958 lua_assert(bl.breaklist == NO_JUMP);
959 leaveblock(fs);
964 ** structure to chain all variables in the left-hand side of an
965 ** assignment
970 ** check whether, in an assignment to a local variable, the local variable
971 ** is needed in a previous assignment (to a table). If so, save original
972 ** local value in a safe place and use this safe copy in the previous
973 ** assignment.
975 static void check_conflict (LexState *ls, expdesc_list *lh, expdesc *v) {
976 FuncState *fs = ls->fs;
977 int extra = fs->freereg; /* eventual position to save local variable */
978 int conflict = 0;
979 for (; lh; lh = lh->prev) {
980 if (lh->v.k == VINDEXED) {
981 if (lh->v.u.s.info == v->u.s.info) { /* conflict? */
982 conflict = 1;
983 lh->v.u.s.info = extra; /* previous assignment will use safe copy */
985 if (lh->v.u.s.aux == v->u.s.info) { /* conflict? */
986 conflict = 1;
987 lh->v.u.s.aux = extra; /* previous assignment will use safe copy */
991 if (conflict) {
992 luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0); /* make copy */
993 luaK_reserveregs(fs, 1);
996 static void pushlhs (FuncState *fs, expdesc_list *v) {
997 fs->lhs = v;
998 fs->nlhs++;
999 fs->nrhs++;
1002 static void poplhs (FuncState *fs) {
1003 lua_assert(fs->lhs != NULL);
1004 fs->lhs = fs->lhs->prev;
1005 fs->nlhs--;
1009 static void assignment (LexState *ls) {
1010 expdesc e;
1011 expdesc_list *lh = ls->fs->lhs;
1012 check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
1013 "syntax error");
1014 if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */
1015 expdesc_list nv;
1016 nv.prev = lh;
1017 primaryexp(ls, &nv.v);
1018 if (nv.v.k == VLOCAL)
1019 check_conflict(ls, lh, &nv.v);
1020 luaY_checklimit(ls->fs, ls->fs->nrhs, LUAI_MAXCCALLS - ls->L->nCcalls,
1021 "variables in assignment");
1022 pushlhs(ls->fs, &nv);
1023 assignment(ls);
1024 poplhs(ls->fs);
1026 else { /* assignment -> `=' explist1 */
1027 // int nexps;
1028 checknext(ls, '=');
1029 ls->fs->nrhs = 1;
1030 expr(ls, &e);
1031 while (testnext(ls, ',')) {
1032 luaK_exp2nextreg(ls->fs, &e);
1033 ls->fs->nrhs++;
1034 expr(ls, &e);
1036 if (ls->fs->nrhs != ls->fs->nlhs) {
1037 adjust_assign(ls, ls->fs->nlhs, ls->fs->nrhs, &e);
1038 if (ls->fs->nrhs > ls->fs->nlhs)
1039 ls->fs->freereg -= ls->fs->nrhs - ls->fs->nlhs; /* remove extra values */
1041 else {
1042 luaK_setoneret(ls->fs, &e); /* close last expression */
1043 luaK_storevar(ls->fs, &lh->v, &e);
1044 return; /* avoid default */
1047 init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
1048 luaK_storevar(ls->fs, &lh->v, &e);
1051 #if 0
1053 static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
1054 expdesc e;
1055 check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
1056 "syntax error");
1057 if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */
1058 expdesc_list nv;
1059 nv.prev = lh;
1060 primaryexp(ls, &nv.v);
1061 if (nv.v.k == VLOCAL)
1062 check_conflict(ls, lh, &nv.v);
1063 luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - ls->L->nCcalls,
1064 "variables in assignment");
1065 pushlhs(ls->fs, &nv);
1066 assignment(ls);
1067 poplhs(ls->fs);
1068 assignment(ls, &nv, nvars+1);
1070 else { /* assignment -> `=' explist1 */
1071 int nexps;
1072 checknext(ls, '=');
1073 nexps = explist1(ls, &e);
1074 if (nexps != nvars) {
1075 adjust_assign(ls, nvars, nexps, &e);
1076 if (nexps > nvars)
1077 ls->fs->freereg -= nexps - nvars; /* remove extra values */
1079 else {
1080 luaK_setoneret(ls->fs, &e); /* close last expression */
1081 luaK_storevar(ls->fs, &lh->v, &e);
1082 return; /* avoid default */
1085 init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
1086 luaK_storevar(ls->fs, &lh->v, &e);
1088 #endif
1090 static int cond (LexState *ls) {
1091 /* cond -> exp */
1092 expdesc v;
1093 expr(ls, &v); /* read condition */
1094 if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
1095 luaK_goiftrue(ls->fs, &v);
1096 return v.f;
1100 static void breakstat (LexState *ls, int n) {
1101 FuncState *fs = ls->fs;
1102 BlockCnt *bl = fs->bl;
1103 int upval = 0;
1104 while (bl && (!bl->isbreakable || --n)) {
1105 upval |= bl->upval;
1106 bl = bl->previous;
1108 if (!bl)
1109 luaX_syntaxerror(ls, "no loop to break");
1110 if (upval)
1111 luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
1112 luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
1116 static void continuestat (LexState *ls) {
1117 /* stat -> CONTINUE */
1118 FuncState *fs = ls->fs;
1119 BlockCnt *bl = fs->bl;
1120 // TBD: Not sure if also continue should have the upvalue check? Original patch had not.
1121 //int upval = 0;
1122 luaX_next(ls); /* skip CONTINUE */
1123 while (bl && !bl->isbreakable) {
1124 //upval |= bl->upval; // AK: ADDITION (would this fix forbody probs?)
1125 bl = bl->previous;
1127 if (!bl)
1128 luaX_syntaxerror(ls, "no loop to continue");
1130 //if (upval) //AK: experimental
1131 // luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
1133 luaK_concat(fs, &bl->continuelist, luaK_jump(fs));
1135 //fprintf( stderr, "continue: bl->continuelist=%d %p %p\n", bl->continuelist, bl, bl->previous );
1137 static void whilestat (LexState *ls, int line) {
1138 /* whilestat -> WHILE cond DO block END */
1139 FuncState *fs = ls->fs;
1140 int whileinit;
1141 int condexit;
1142 BlockCnt bl;
1143 luaX_next(ls); /* skip WHILE */
1144 whileinit = luaK_getlabel(fs);
1145 condexit = cond(ls);
1146 enterblock(fs, &bl, 1);
1147 testnext(ls, TK_DO);
1148 block(ls);
1149 // luaK_patchlist(fs, luaK_jump(fs), bl.continuelist); -- bug rendering 'continue' useless in 'while', asko?
1150 luaK_patchtohere(fs, bl.continuelist); // this one works for me --kt
1151 luaK_patchlist(fs, luaK_jump(fs), whileinit);
1152 check_match(ls, TK_END, TK_WHILE, line);
1153 leaveblock(fs);
1154 luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
1158 static void repeatstat (LexState *ls, int line) {
1159 /* repeatstat -> REPEAT block UNTIL cond */
1160 int condexit;
1161 FuncState *fs = ls->fs;
1162 int repeat_init = luaK_getlabel(fs);
1163 BlockCnt bl1, bl2;
1164 enterblock(fs, &bl1, 1); /* loop block */
1165 enterblock(fs, &bl2, 0); /* scope block */
1166 luaX_next(ls); /* skip REPEAT */
1167 chunk(ls);
1168 luaK_patchtohere(fs, bl1.continuelist);
1169 check_match(ls, TK_UNTIL, TK_REPEAT, line);
1170 condexit = cond(ls); /* read condition (inside scope block) */
1171 if (!bl2.upval) { /* no upvalues? */
1172 leaveblock(fs); /* finish scope */
1173 luaK_patchlist(ls->fs, condexit, repeat_init); /* close the loop */
1175 else { /* complete semantics when there are upvalues */
1176 breakstat(ls, 1); /* if condition then break */
1177 luaK_patchtohere(ls->fs, condexit); /* else... */
1178 leaveblock(fs); /* finish scope... */
1179 luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init); /* and repeat */
1181 leaveblock(fs); /* finish loop */
1185 static int exp1 (LexState *ls) {
1186 expdesc e;
1187 int k;
1188 expr(ls, &e);
1189 k = e.k;
1190 luaK_exp2nextreg(ls->fs, &e);
1191 return k;
1195 static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1196 /* forbody -> DO block */
1197 BlockCnt bl;
1198 FuncState *fs = ls->fs;
1199 int prep, endfor;
1200 adjustlocalvars(ls, 3); /* control variables */
1201 testnext(ls, TK_DO);
1202 prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1203 enterblock(fs, &bl, 0); /* scope for declared variables */
1204 adjustlocalvars(ls, nvars);
1205 luaK_reserveregs(fs, nvars);
1206 block(ls);
1207 luaK_patchtohere(fs, bl.previous->continuelist);
1208 leaveblock(fs); /* end of scope for declared variables */
1209 luaK_patchtohere(fs, prep);
1210 endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) :
1211 luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars);
1212 luaK_fixline(fs, line); /* pretend that `OP_FOR' starts the loop */
1213 luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1);
1217 static void fornum (LexState *ls, TString *varname, int line) {
1218 /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1219 FuncState *fs = ls->fs;
1220 int base = fs->freereg;
1221 new_localvarliteral(ls, "(for index)", 0);
1222 new_localvarliteral(ls, "(for limit)", 1);
1223 new_localvarliteral(ls, "(for step)", 2);
1224 new_localvar(ls, varname, 3);
1225 checknext(ls, '=');
1226 exp1(ls); /* initial value */
1227 checknext(ls, ',');
1228 exp1(ls); /* limit */
1229 if (testnext(ls, ','))
1230 exp1(ls); /* optional step */
1231 else { /* default step = 1 */
1232 luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1));
1233 luaK_reserveregs(fs, 1);
1235 forbody(ls, base, line, 1, 1);
1239 static void forlist (LexState *ls, TString *indexname) {
1240 /* forlist -> NAME {,NAME} IN explist1 forbody */
1241 FuncState *fs = ls->fs;
1242 expdesc e;
1243 int nvars = 0;
1244 int line;
1245 int base = fs->freereg;
1246 /* create control variables */
1247 new_localvarliteral(ls, "(for generator)", nvars++);
1248 new_localvarliteral(ls, "(for state)", nvars++);
1249 new_localvarliteral(ls, "(for control)", nvars++);
1250 /* create declared variables */
1251 new_localvar(ls, indexname, nvars++);
1252 while (testnext(ls, ','))
1253 new_localvar(ls, str_checkname(ls), nvars++);
1254 checknext(ls, TK_IN);
1255 line = ls->linenumber;
1256 adjust_assign(ls, 3, explist1(ls, &e), &e);
1257 luaK_checkstack(fs, 3); /* extra space to call generator */
1258 forbody(ls, base, line, nvars - 3, 0);
1262 static void forstat (LexState *ls, int line) {
1263 /* forstat -> FOR (fornum | forlist) END */
1264 FuncState *fs = ls->fs;
1265 TString *varname;
1266 BlockCnt bl;
1267 enterblock(fs, &bl, 1); /* scope for loop and control variables */
1268 luaX_next(ls); /* skip `for' */
1269 varname = str_checkname(ls); /* first variable name */
1270 switch (ls->t.token) {
1271 case '=': fornum(ls, varname, line); break;
1272 case ',': case TK_IN: forlist(ls, varname); break;
1273 default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
1275 check_match(ls, TK_END, TK_FOR, line);
1276 leaveblock(fs); /* loop scope (`break' jumps to this point) */
1280 static int test_then_block (LexState *ls) {
1281 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1282 int condexit;
1283 luaX_next(ls); /* skip IF or ELSEIF */
1284 condexit = cond(ls);
1285 testnext(ls, TK_THEN);
1286 block(ls); /* `then' part */
1287 return condexit;
1291 static void ifstat (LexState *ls, int line) {
1292 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1293 FuncState *fs = ls->fs;
1294 int flist;
1295 int escapelist = NO_JUMP;
1296 flist = test_then_block(ls); /* IF cond THEN block */
1297 while (ls->t.token == TK_ELSEIF) {
1298 luaK_concat(fs, &escapelist, luaK_jump(fs));
1299 luaK_patchtohere(fs, flist);
1300 flist = test_then_block(ls); /* ELSEIF cond THEN block */
1302 if (ls->t.token == TK_ELSE) {
1303 luaK_concat(fs, &escapelist, luaK_jump(fs));
1304 luaK_patchtohere(fs, flist);
1305 luaX_next(ls); /* skip ELSE (after patch, for correct line info) */
1306 block(ls); /* `else' part */
1308 else
1309 luaK_concat(fs, &escapelist, flist);
1310 luaK_patchtohere(fs, escapelist);
1311 check_match(ls, TK_END, TK_IF, line);
1315 static void localfunc (LexState *ls) {
1316 expdesc v, b;
1317 FuncState *fs = ls->fs;
1318 new_localvar(ls, str_checkname(ls), 0);
1319 init_exp(&v, VLOCAL, fs->freereg);
1320 luaK_reserveregs(fs, 1);
1321 adjustlocalvars(ls, 1);
1322 body(ls, &b, 0, ls->linenumber);
1323 luaK_storevar(fs, &v, &b);
1324 /* debug information will only see the variable after this point! */
1325 getlocvar(fs, fs->nactvar - 1).startpc = fs->pc;
1329 static void localstat (LexState *ls) {
1330 /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
1331 int nvars = 0;
1332 int nexps;
1333 expdesc e;
1334 do {
1335 new_localvar(ls, str_checkname(ls), nvars++);
1336 } while (testnext(ls, ','));
1337 if (testnext(ls, '='))
1338 nexps = explist1(ls, &e);
1339 else {
1340 e.k = VVOID;
1341 nexps = 0;
1343 adjust_assign(ls, nvars, nexps, &e);
1344 adjustlocalvars(ls, nvars);
1348 static int funcname (LexState *ls, expdesc *v) {
1349 /* funcname -> NAME {field} [`:' NAME] */
1350 int needself = 0;
1351 singlevar(ls, v);
1352 while (ls->t.token == '.')
1353 field(ls, v);
1354 if (ls->t.token == ':') {
1355 needself = 1;
1356 field(ls, v);
1358 return needself;
1362 static void funcstat (LexState *ls, int line) {
1363 /* funcstat -> FUNCTION funcname body */
1364 int needself;
1365 expdesc v, b;
1366 luaX_next(ls); /* skip FUNCTION */
1367 needself = funcname(ls, &v);
1368 body(ls, &b, needself, line);
1369 luaK_storevar(ls->fs, &v, &b);
1370 luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
1374 static void exprstat (LexState *ls) {
1375 /* stat -> func | assignment */
1376 FuncState *fs = ls->fs;
1377 expdesc_list v;
1378 primaryexp(ls, &v.v);
1379 if (v.v.k == VCALL) /* stat -> func */
1380 SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
1381 else { /* stat -> assignment */
1382 v.prev = NULL;
1383 lua_assert(ls->fs->lhs == NULL && ls->fs->nlhs == 0 && ls->fs->nrhs == 0);
1384 pushlhs(ls->fs, &v);
1385 assignment(ls);
1386 poplhs(ls->fs);
1387 ls->fs->nrhs = 0;
1388 lua_assert(ls->fs->lhs == NULL && ls->fs->nlhs == 0);
1393 static void retstat (LexState *ls) {
1394 /* stat -> RETURN explist */
1395 FuncState *fs = ls->fs;
1396 expdesc e;
1397 int first, nret; /* registers with returned values */
1398 luaX_next(ls); /* skip RETURN */
1399 if (block_follow(ls->t.token) || ls->t.token == ';')
1400 first = nret = 0; /* return no values */
1401 else {
1402 nret = explist1(ls, &e); /* optional return values */
1403 if (hasmultret(e.k)) {
1404 luaK_setmultret(fs, &e);
1405 if (e.k == VCALL && nret == 1) { /* tail call? */
1406 SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1407 lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1409 first = fs->nactvar;
1410 nret = LUA_MULTRET; /* return all values */
1412 else {
1413 if (nret == 1) /* only one single value? */
1414 first = luaK_exp2anyreg(fs, &e);
1415 else {
1416 luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
1417 first = fs->nactvar; /* return all `active' values */
1418 lua_assert(nret == fs->freereg - first);
1422 luaK_ret(fs, first, nret);
1426 static int statement (LexState *ls) {
1427 int line = ls->linenumber; /* may be needed for error messages */
1428 switch (ls->t.token) {
1429 case TK_IF: { /* stat -> ifstat */
1430 ifstat(ls, line);
1431 return 0;
1433 case TK_WHILE: { /* stat -> whilestat */
1434 whilestat(ls, line);
1435 return 0;
1437 case TK_DO: { /* stat -> DO block END */
1438 luaX_next(ls); /* skip DO */
1439 block(ls);
1440 check_match(ls, TK_END, TK_DO, line);
1441 return 0;
1443 case TK_FOR: { /* stat -> forstat */
1444 forstat(ls, line);
1445 return 0;
1447 case TK_REPEAT: { /* stat -> repeatstat */
1448 repeatstat(ls, line);
1449 return 0;
1451 case TK_FUNCTION: {
1452 funcstat(ls, line); /* stat -> funcstat */
1453 return 0;
1455 case TK_LOCAL: { /* stat -> localstat */
1456 luaX_next(ls); /* skip LOCAL */
1457 if (testnext(ls, TK_FUNCTION)) /* local function? */
1458 localfunc(ls);
1459 else
1460 localstat(ls);
1461 return 0;
1463 case TK_RETURN: { /* stat -> retstat */
1464 retstat(ls);
1465 return 1; /* must be last statement */
1467 case TK_BREAK: { /* stat -> breakstat */
1468 luaX_next(ls); /* skip BREAK */
1469 if (testnext(ls, TK_NUMBER)) { /* multi scope 'break n' */
1470 breakstat(ls, ls->t.seminfo.r);
1471 } else breakstat(ls, 1);
1472 return 1; /* must be last statement */
1474 case TK_CONTINUE: { /* stat -> continuestat */
1475 continuestat(ls);
1476 return 1; /* must be last statement */
1478 default: {
1479 exprstat(ls);
1480 return 0; /* to avoid warnings */
1486 static void chunk (LexState *ls) {
1487 /* chunk -> { stat [`;'] } */
1488 int islast = 0;
1489 enterlevel(ls);
1490 while (!islast && !block_follow(ls->t.token)) {
1491 islast = statement(ls);
1492 testnext(ls, ';');
1493 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1494 ls->fs->freereg >= ls->fs->nactvar);
1495 ls->fs->freereg = ls->fs->nactvar; /* free registers */
1497 leavelevel(ls);
1500 /* }====================================================================== */