grub-extras/lua: add fs label to grub.enum_device
[grub-extras.git] / lua / lparser.c
blob309f51891433c05d50685ab0f9d802a18a2491b4
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 */
7 #if 0
8 #include <string.h>
9 #endif
11 #define lparser_c
12 #define LUA_CORE
14 #include "lua.h"
16 #include "lcode.h"
17 #include "ldebug.h"
18 #include "ldo.h"
19 #include "lfunc.h"
20 #include "llex.h"
21 #include "lmem.h"
22 #include "lobject.h"
23 #include "lopcodes.h"
24 #include "lparser.h"
25 #include "lstate.h"
26 #include "lstring.h"
27 #include "ltable.h"
31 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
33 #define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]])
35 #define luaY_checklimit(fs,v,l,m) if ((v)>(l)) errorlimit(fs,l,m)
39 ** nodes for block list (list of active blocks)
41 typedef struct BlockCnt {
42 struct BlockCnt *previous; /* chain */
43 int breaklist; /* list of jumps out of this loop */
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->isbreakable = isbreakable;
289 bl->nactvar = fs->nactvar;
290 bl->upval = 0;
291 bl->previous = fs->bl;
292 fs->bl = bl;
293 lua_assert(fs->freereg == fs->nactvar);
297 static void leaveblock (FuncState *fs) {
298 BlockCnt *bl = fs->bl;
299 fs->bl = bl->previous;
300 removevars(fs->ls, bl->nactvar);
301 if (bl->upval)
302 luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
303 /* a block either controls scope or breaks (never both) */
304 lua_assert(!bl->isbreakable || !bl->upval);
305 lua_assert(bl->nactvar == fs->nactvar);
306 fs->freereg = fs->nactvar; /* free registers */
307 luaK_patchtohere(fs, bl->breaklist);
311 static void pushclosure (LexState *ls, FuncState *func, expdesc *v) {
312 FuncState *fs = ls->fs;
313 Proto *f = fs->f;
314 int oldsize = f->sizep;
315 int i;
316 luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
317 MAXARG_Bx, "constant table overflow");
318 while (oldsize < f->sizep) f->p[oldsize++] = NULL;
319 f->p[fs->np++] = func->f;
320 luaC_objbarrier(ls->L, f, func->f);
321 init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
322 for (i=0; i<func->f->nups; i++) {
323 OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
324 luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0);
329 static void open_func (LexState *ls, FuncState *fs) {
330 lua_State *L = ls->L;
331 Proto *f = luaF_newproto(L);
332 fs->f = f;
333 fs->prev = ls->fs; /* linked list of funcstates */
334 fs->ls = ls;
335 fs->L = L;
336 ls->fs = fs;
337 fs->pc = 0;
338 fs->lasttarget = -1;
339 fs->jpc = NO_JUMP;
340 fs->freereg = 0;
341 fs->nk = 0;
342 fs->np = 0;
343 fs->nlocvars = 0;
344 fs->nactvar = 0;
345 fs->bl = NULL;
346 f->source = ls->source;
347 f->maxstacksize = 2; /* registers 0/1 are always valid */
348 fs->h = luaH_new(L, 0, 0);
349 /* anchor table of constants and prototype (to avoid being collected) */
350 sethvalue2s(L, L->top, fs->h);
351 incr_top(L);
352 setptvalue2s(L, L->top, f);
353 incr_top(L);
357 static void close_func (LexState *ls) {
358 lua_State *L = ls->L;
359 FuncState *fs = ls->fs;
360 Proto *f = fs->f;
361 removevars(ls, 0);
362 luaK_ret(fs, 0, 0); /* final return */
363 luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
364 f->sizecode = fs->pc;
365 luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
366 f->sizelineinfo = fs->pc;
367 luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
368 f->sizek = fs->nk;
369 luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
370 f->sizep = fs->np;
371 luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
372 f->sizelocvars = fs->nlocvars;
373 luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *);
374 f->sizeupvalues = f->nups;
375 lua_assert(luaG_checkcode(f));
376 lua_assert(fs->bl == NULL);
377 ls->fs = fs->prev;
378 L->top -= 2; /* remove table and prototype from the stack */
379 /* last token read was anchored in defunct function; must reanchor it */
380 if (fs) anchor_token(ls);
384 Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
385 struct LexState lexstate;
386 struct FuncState funcstate;
387 lexstate.buff = buff;
388 luaX_setinput(L, &lexstate, z, luaS_new(L, name));
389 open_func(&lexstate, &funcstate);
390 funcstate.f->is_vararg = VARARG_ISVARARG; /* main func. is always vararg */
391 luaX_next(&lexstate); /* read first token */
392 chunk(&lexstate);
393 check(&lexstate, TK_EOS);
394 close_func(&lexstate);
395 lua_assert(funcstate.prev == NULL);
396 lua_assert(funcstate.f->nups == 0);
397 lua_assert(lexstate.fs == NULL);
398 return funcstate.f;
403 /*============================================================*/
404 /* GRAMMAR RULES */
405 /*============================================================*/
408 static void field (LexState *ls, expdesc *v) {
409 /* field -> ['.' | ':'] NAME */
410 FuncState *fs = ls->fs;
411 expdesc key;
412 luaK_exp2anyreg(fs, v);
413 luaX_next(ls); /* skip the dot or colon */
414 checkname(ls, &key);
415 luaK_indexed(fs, v, &key);
419 static void yindex (LexState *ls, expdesc *v) {
420 /* index -> '[' expr ']' */
421 luaX_next(ls); /* skip the '[' */
422 expr(ls, v);
423 luaK_exp2val(ls->fs, v);
424 checknext(ls, ']');
429 ** {======================================================================
430 ** Rules for Constructors
431 ** =======================================================================
435 struct ConsControl {
436 expdesc v; /* last list item read */
437 expdesc *t; /* table descriptor */
438 int nh; /* total number of `record' elements */
439 int na; /* total number of array elements */
440 int tostore; /* number of array elements pending to be stored */
444 static void recfield (LexState *ls, struct ConsControl *cc) {
445 /* recfield -> (NAME | `['exp1`]') = exp1 */
446 FuncState *fs = ls->fs;
447 int reg = ls->fs->freereg;
448 expdesc key, val;
449 int rkkey;
450 if (ls->t.token == TK_NAME) {
451 luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
452 checkname(ls, &key);
454 else /* ls->t.token == '[' */
455 yindex(ls, &key);
456 cc->nh++;
457 checknext(ls, '=');
458 rkkey = luaK_exp2RK(fs, &key);
459 expr(ls, &val);
460 luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val));
461 fs->freereg = reg; /* free registers */
465 static void closelistfield (FuncState *fs, struct ConsControl *cc) {
466 if (cc->v.k == VVOID) return; /* there is no list item */
467 luaK_exp2nextreg(fs, &cc->v);
468 cc->v.k = VVOID;
469 if (cc->tostore == LFIELDS_PER_FLUSH) {
470 luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore); /* flush */
471 cc->tostore = 0; /* no more items pending */
476 static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
477 if (cc->tostore == 0) return;
478 if (hasmultret(cc->v.k)) {
479 luaK_setmultret(fs, &cc->v);
480 luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET);
481 cc->na--; /* do not count last expression (unknown number of elements) */
483 else {
484 if (cc->v.k != VVOID)
485 luaK_exp2nextreg(fs, &cc->v);
486 luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);
491 static void listfield (LexState *ls, struct ConsControl *cc) {
492 expr(ls, &cc->v);
493 luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
494 cc->na++;
495 cc->tostore++;
499 static void constructor (LexState *ls, expdesc *t) {
500 /* constructor -> ?? */
501 FuncState *fs = ls->fs;
502 int line = ls->linenumber;
503 int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
504 struct ConsControl cc;
505 cc.na = cc.nh = cc.tostore = 0;
506 cc.t = t;
507 init_exp(t, VRELOCABLE, pc);
508 init_exp(&cc.v, VVOID, 0); /* no value (yet) */
509 luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */
510 checknext(ls, '{');
511 do {
512 lua_assert(cc.v.k == VVOID || cc.tostore > 0);
513 if (ls->t.token == '}') break;
514 closelistfield(fs, &cc);
515 switch(ls->t.token) {
516 case TK_NAME: { /* may be listfields or recfields */
517 luaX_lookahead(ls);
518 if (ls->lookahead.token != '=') /* expression? */
519 listfield(ls, &cc);
520 else
521 recfield(ls, &cc);
522 break;
524 case '[': { /* constructor_item -> recfield */
525 recfield(ls, &cc);
526 break;
528 default: { /* constructor_part -> listfield */
529 listfield(ls, &cc);
530 break;
533 } while (testnext(ls, ',') || testnext(ls, ';'));
534 check_match(ls, '}', '{', line);
535 lastlistfield(fs, &cc);
536 SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
537 SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
540 /* }====================================================================== */
544 static void parlist (LexState *ls) {
545 /* parlist -> [ param { `,' param } ] */
546 FuncState *fs = ls->fs;
547 Proto *f = fs->f;
548 int nparams = 0;
549 f->is_vararg = 0;
550 if (ls->t.token != ')') { /* is `parlist' not empty? */
551 do {
552 switch (ls->t.token) {
553 case TK_NAME: { /* param -> NAME */
554 new_localvar(ls, str_checkname(ls), nparams++);
555 break;
557 case TK_DOTS: { /* param -> `...' */
558 luaX_next(ls);
559 #if defined(LUA_COMPAT_VARARG)
560 /* use `arg' as default name */
561 new_localvarliteral(ls, "arg", nparams++);
562 f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG;
563 #endif
564 f->is_vararg |= VARARG_ISVARARG;
565 break;
567 default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
569 } while (!f->is_vararg && testnext(ls, ','));
571 adjustlocalvars(ls, nparams);
572 f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG));
573 luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
577 static void body (LexState *ls, expdesc *e, int needself, int line) {
578 /* body -> `(' parlist `)' chunk END */
579 FuncState new_fs;
580 open_func(ls, &new_fs);
581 new_fs.f->linedefined = line;
582 checknext(ls, '(');
583 if (needself) {
584 new_localvarliteral(ls, "self", 0);
585 adjustlocalvars(ls, 1);
587 parlist(ls);
588 checknext(ls, ')');
589 chunk(ls);
590 new_fs.f->lastlinedefined = ls->linenumber;
591 check_match(ls, TK_END, TK_FUNCTION, line);
592 close_func(ls);
593 pushclosure(ls, &new_fs, e);
597 static int explist1 (LexState *ls, expdesc *v) {
598 /* explist1 -> expr { `,' expr } */
599 int n = 1; /* at least one expression */
600 expr(ls, v);
601 while (testnext(ls, ',')) {
602 luaK_exp2nextreg(ls->fs, v);
603 expr(ls, v);
604 n++;
606 return n;
610 static void funcargs (LexState *ls, expdesc *f) {
611 FuncState *fs = ls->fs;
612 expdesc args;
613 int base, nparams;
614 int line = ls->linenumber;
615 switch (ls->t.token) {
616 case '(': { /* funcargs -> `(' [ explist1 ] `)' */
617 if (line != ls->lastline)
618 luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
619 luaX_next(ls);
620 if (ls->t.token == ')') /* arg list is empty? */
621 args.k = VVOID;
622 else {
623 explist1(ls, &args);
624 luaK_setmultret(fs, &args);
626 check_match(ls, ')', '(', line);
627 break;
629 case '{': { /* funcargs -> constructor */
630 constructor(ls, &args);
631 break;
633 case TK_STRING: { /* funcargs -> STRING */
634 codestring(ls, &args, ls->t.seminfo.ts);
635 luaX_next(ls); /* must use `seminfo' before `next' */
636 break;
638 default: {
639 luaX_syntaxerror(ls, "function arguments expected");
640 return;
643 lua_assert(f->k == VNONRELOC);
644 base = f->u.s.info; /* base register for call */
645 if (hasmultret(args.k))
646 nparams = LUA_MULTRET; /* open call */
647 else {
648 if (args.k != VVOID)
649 luaK_exp2nextreg(fs, &args); /* close last argument */
650 nparams = fs->freereg - (base+1);
652 init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
653 luaK_fixline(fs, line);
654 fs->freereg = base+1; /* call remove function and arguments and leaves
655 (unless changed) one result */
662 ** {======================================================================
663 ** Expression parsing
664 ** =======================================================================
668 static void prefixexp (LexState *ls, expdesc *v) {
669 /* prefixexp -> NAME | '(' expr ')' */
670 switch (ls->t.token) {
671 case '(': {
672 int line = ls->linenumber;
673 luaX_next(ls);
674 expr(ls, v);
675 check_match(ls, ')', '(', line);
676 luaK_dischargevars(ls->fs, v);
677 return;
679 case TK_NAME: {
680 singlevar(ls, v);
681 return;
683 default: {
684 luaX_syntaxerror(ls, "unexpected symbol");
685 return;
691 static void primaryexp (LexState *ls, expdesc *v) {
692 /* primaryexp ->
693 prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
694 FuncState *fs = ls->fs;
695 prefixexp(ls, v);
696 for (;;) {
697 switch (ls->t.token) {
698 case '.': { /* field */
699 field(ls, v);
700 break;
702 case '[': { /* `[' exp1 `]' */
703 expdesc key;
704 luaK_exp2anyreg(fs, v);
705 yindex(ls, &key);
706 luaK_indexed(fs, v, &key);
707 break;
709 case ':': { /* `:' NAME funcargs */
710 expdesc key;
711 luaX_next(ls);
712 checkname(ls, &key);
713 luaK_self(fs, v, &key);
714 funcargs(ls, v);
715 break;
717 case '(': case TK_STRING: case '{': { /* funcargs */
718 luaK_exp2nextreg(fs, v);
719 funcargs(ls, v);
720 break;
722 default: return;
728 static void simpleexp (LexState *ls, expdesc *v) {
729 /* simpleexp -> NUMBER | STRING | NIL | true | false | ... |
730 constructor | FUNCTION body | primaryexp */
731 switch (ls->t.token) {
732 case TK_NUMBER: {
733 init_exp(v, VKNUM, 0);
734 v->u.nval = ls->t.seminfo.r;
735 break;
737 case TK_STRING: {
738 codestring(ls, v, ls->t.seminfo.ts);
739 break;
741 case TK_NIL: {
742 init_exp(v, VNIL, 0);
743 break;
745 case TK_TRUE: {
746 init_exp(v, VTRUE, 0);
747 break;
749 case TK_FALSE: {
750 init_exp(v, VFALSE, 0);
751 break;
753 case TK_DOTS: { /* vararg */
754 FuncState *fs = ls->fs;
755 check_condition(ls, fs->f->is_vararg,
756 "cannot use " LUA_QL("...") " outside a vararg function");
757 fs->f->is_vararg &= ~VARARG_NEEDSARG; /* don't need 'arg' */
758 init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
759 break;
761 case '{': { /* constructor */
762 constructor(ls, v);
763 return;
765 case TK_FUNCTION: {
766 luaX_next(ls);
767 body(ls, v, 0, ls->linenumber);
768 return;
770 default: {
771 primaryexp(ls, v);
772 return;
775 luaX_next(ls);
779 static UnOpr getunopr (int op) {
780 switch (op) {
781 case TK_NOT: return OPR_NOT;
782 case '-': return OPR_MINUS;
783 case '#': return OPR_LEN;
784 default: return OPR_NOUNOPR;
789 static BinOpr getbinopr (int op) {
790 switch (op) {
791 case '+': return OPR_ADD;
792 case '-': return OPR_SUB;
793 case '*': return OPR_MUL;
794 case '/': return OPR_DIV;
795 case '%': return OPR_MOD;
796 case '^': return OPR_POW;
797 case TK_CONCAT: return OPR_CONCAT;
798 case TK_NE: return OPR_NE;
799 case TK_EQ: return OPR_EQ;
800 case '<': return OPR_LT;
801 case TK_LE: return OPR_LE;
802 case '>': return OPR_GT;
803 case TK_GE: return OPR_GE;
804 case TK_AND: return OPR_AND;
805 case TK_OR: return OPR_OR;
806 default: return OPR_NOBINOPR;
811 static const struct {
812 lu_byte left; /* left priority for each binary operator */
813 lu_byte right; /* right priority */
814 } priority[] = { /* ORDER OPR */
815 {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `/' `%' */
816 {10, 9}, {5, 4}, /* power and concat (right associative) */
817 {3, 3}, {3, 3}, /* equality and inequality */
818 {3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */
819 {2, 2}, {1, 1} /* logical (and/or) */
822 #define UNARY_PRIORITY 8 /* priority for unary operators */
826 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
827 ** where `binop' is any binary operator with a priority higher than `limit'
829 static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) {
830 BinOpr op;
831 UnOpr uop;
832 enterlevel(ls);
833 uop = getunopr(ls->t.token);
834 if (uop != OPR_NOUNOPR) {
835 luaX_next(ls);
836 subexpr(ls, v, UNARY_PRIORITY);
837 luaK_prefix(ls->fs, uop, v);
839 else simpleexp(ls, v);
840 /* expand while operators have priorities higher than `limit' */
841 op = getbinopr(ls->t.token);
842 while (op != OPR_NOBINOPR && priority[op].left > limit) {
843 expdesc v2;
844 BinOpr nextop;
845 luaX_next(ls);
846 luaK_infix(ls->fs, op, v);
847 /* read sub-expression with higher priority */
848 nextop = subexpr(ls, &v2, priority[op].right);
849 luaK_posfix(ls->fs, op, v, &v2);
850 op = nextop;
852 leavelevel(ls);
853 return op; /* return first untreated operator */
857 static void expr (LexState *ls, expdesc *v) {
858 subexpr(ls, v, 0);
861 /* }==================================================================== */
866 ** {======================================================================
867 ** Rules for Statements
868 ** =======================================================================
872 static int block_follow (int token) {
873 switch (token) {
874 case TK_ELSE: case TK_ELSEIF: case TK_END:
875 case TK_UNTIL: case TK_EOS:
876 return 1;
877 default: return 0;
882 static void block (LexState *ls) {
883 /* block -> chunk */
884 FuncState *fs = ls->fs;
885 BlockCnt bl;
886 enterblock(fs, &bl, 0);
887 chunk(ls);
888 lua_assert(bl.breaklist == NO_JUMP);
889 leaveblock(fs);
894 ** structure to chain all variables in the left-hand side of an
895 ** assignment
897 struct LHS_assign {
898 struct LHS_assign *prev;
899 expdesc v; /* variable (global, local, upvalue, or indexed) */
904 ** check whether, in an assignment to a local variable, the local variable
905 ** is needed in a previous assignment (to a table). If so, save original
906 ** local value in a safe place and use this safe copy in the previous
907 ** assignment.
909 static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
910 FuncState *fs = ls->fs;
911 int extra = fs->freereg; /* eventual position to save local variable */
912 int conflict = 0;
913 for (; lh; lh = lh->prev) {
914 if (lh->v.k == VINDEXED) {
915 if (lh->v.u.s.info == v->u.s.info) { /* conflict? */
916 conflict = 1;
917 lh->v.u.s.info = extra; /* previous assignment will use safe copy */
919 if (lh->v.u.s.aux == v->u.s.info) { /* conflict? */
920 conflict = 1;
921 lh->v.u.s.aux = extra; /* previous assignment will use safe copy */
925 if (conflict) {
926 luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0); /* make copy */
927 luaK_reserveregs(fs, 1);
932 static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
933 expdesc e;
934 check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
935 "syntax error");
936 if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */
937 struct LHS_assign nv;
938 nv.prev = lh;
939 primaryexp(ls, &nv.v);
940 if (nv.v.k == VLOCAL)
941 check_conflict(ls, lh, &nv.v);
942 luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - ls->L->nCcalls,
943 "variables in assignment");
944 assignment(ls, &nv, nvars+1);
946 else { /* assignment -> `=' explist1 */
947 int nexps;
948 checknext(ls, '=');
949 nexps = explist1(ls, &e);
950 if (nexps != nvars) {
951 adjust_assign(ls, nvars, nexps, &e);
952 if (nexps > nvars)
953 ls->fs->freereg -= nexps - nvars; /* remove extra values */
955 else {
956 luaK_setoneret(ls->fs, &e); /* close last expression */
957 luaK_storevar(ls->fs, &lh->v, &e);
958 return; /* avoid default */
961 init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
962 luaK_storevar(ls->fs, &lh->v, &e);
966 static int cond (LexState *ls) {
967 /* cond -> exp */
968 expdesc v;
969 expr(ls, &v); /* read condition */
970 if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
971 luaK_goiftrue(ls->fs, &v);
972 return v.f;
976 static void breakstat (LexState *ls) {
977 FuncState *fs = ls->fs;
978 BlockCnt *bl = fs->bl;
979 int upval = 0;
980 while (bl && !bl->isbreakable) {
981 upval |= bl->upval;
982 bl = bl->previous;
984 if (!bl)
985 luaX_syntaxerror(ls, "no loop to break");
986 if (upval)
987 luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
988 luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
992 static void whilestat (LexState *ls, int line) {
993 /* whilestat -> WHILE cond DO block END */
994 FuncState *fs = ls->fs;
995 int whileinit;
996 int condexit;
997 BlockCnt bl;
998 luaX_next(ls); /* skip WHILE */
999 whileinit = luaK_getlabel(fs);
1000 condexit = cond(ls);
1001 enterblock(fs, &bl, 1);
1002 checknext(ls, TK_DO);
1003 block(ls);
1004 luaK_patchlist(fs, luaK_jump(fs), whileinit);
1005 check_match(ls, TK_END, TK_WHILE, line);
1006 leaveblock(fs);
1007 luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
1011 static void repeatstat (LexState *ls, int line) {
1012 /* repeatstat -> REPEAT block UNTIL cond */
1013 int condexit;
1014 FuncState *fs = ls->fs;
1015 int repeat_init = luaK_getlabel(fs);
1016 BlockCnt bl1, bl2;
1017 enterblock(fs, &bl1, 1); /* loop block */
1018 enterblock(fs, &bl2, 0); /* scope block */
1019 luaX_next(ls); /* skip REPEAT */
1020 chunk(ls);
1021 check_match(ls, TK_UNTIL, TK_REPEAT, line);
1022 condexit = cond(ls); /* read condition (inside scope block) */
1023 if (!bl2.upval) { /* no upvalues? */
1024 leaveblock(fs); /* finish scope */
1025 luaK_patchlist(ls->fs, condexit, repeat_init); /* close the loop */
1027 else { /* complete semantics when there are upvalues */
1028 breakstat(ls); /* if condition then break */
1029 luaK_patchtohere(ls->fs, condexit); /* else... */
1030 leaveblock(fs); /* finish scope... */
1031 luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init); /* and repeat */
1033 leaveblock(fs); /* finish loop */
1037 static int exp1 (LexState *ls) {
1038 expdesc e;
1039 int k;
1040 expr(ls, &e);
1041 k = e.k;
1042 luaK_exp2nextreg(ls->fs, &e);
1043 return k;
1047 static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1048 /* forbody -> DO block */
1049 BlockCnt bl;
1050 FuncState *fs = ls->fs;
1051 int prep, endfor;
1052 adjustlocalvars(ls, 3); /* control variables */
1053 checknext(ls, TK_DO);
1054 prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1055 enterblock(fs, &bl, 0); /* scope for declared variables */
1056 adjustlocalvars(ls, nvars);
1057 luaK_reserveregs(fs, nvars);
1058 block(ls);
1059 leaveblock(fs); /* end of scope for declared variables */
1060 luaK_patchtohere(fs, prep);
1061 endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) :
1062 luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars);
1063 luaK_fixline(fs, line); /* pretend that `OP_FOR' starts the loop */
1064 luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1);
1068 static void fornum (LexState *ls, TString *varname, int line) {
1069 /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1070 FuncState *fs = ls->fs;
1071 int base = fs->freereg;
1072 new_localvarliteral(ls, "(for index)", 0);
1073 new_localvarliteral(ls, "(for limit)", 1);
1074 new_localvarliteral(ls, "(for step)", 2);
1075 new_localvar(ls, varname, 3);
1076 checknext(ls, '=');
1077 exp1(ls); /* initial value */
1078 checknext(ls, ',');
1079 exp1(ls); /* limit */
1080 if (testnext(ls, ','))
1081 exp1(ls); /* optional step */
1082 else { /* default step = 1 */
1083 luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1));
1084 luaK_reserveregs(fs, 1);
1086 forbody(ls, base, line, 1, 1);
1090 static void forlist (LexState *ls, TString *indexname) {
1091 /* forlist -> NAME {,NAME} IN explist1 forbody */
1092 FuncState *fs = ls->fs;
1093 expdesc e;
1094 int nvars = 0;
1095 int line;
1096 int base = fs->freereg;
1097 /* create control variables */
1098 new_localvarliteral(ls, "(for generator)", nvars++);
1099 new_localvarliteral(ls, "(for state)", nvars++);
1100 new_localvarliteral(ls, "(for control)", nvars++);
1101 /* create declared variables */
1102 new_localvar(ls, indexname, nvars++);
1103 while (testnext(ls, ','))
1104 new_localvar(ls, str_checkname(ls), nvars++);
1105 checknext(ls, TK_IN);
1106 line = ls->linenumber;
1107 adjust_assign(ls, 3, explist1(ls, &e), &e);
1108 luaK_checkstack(fs, 3); /* extra space to call generator */
1109 forbody(ls, base, line, nvars - 3, 0);
1113 static void forstat (LexState *ls, int line) {
1114 /* forstat -> FOR (fornum | forlist) END */
1115 FuncState *fs = ls->fs;
1116 TString *varname;
1117 BlockCnt bl;
1118 enterblock(fs, &bl, 1); /* scope for loop and control variables */
1119 luaX_next(ls); /* skip `for' */
1120 varname = str_checkname(ls); /* first variable name */
1121 switch (ls->t.token) {
1122 case '=': fornum(ls, varname, line); break;
1123 case ',': case TK_IN: forlist(ls, varname); break;
1124 default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
1126 check_match(ls, TK_END, TK_FOR, line);
1127 leaveblock(fs); /* loop scope (`break' jumps to this point) */
1131 static int test_then_block (LexState *ls) {
1132 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1133 int condexit;
1134 luaX_next(ls); /* skip IF or ELSEIF */
1135 condexit = cond(ls);
1136 checknext(ls, TK_THEN);
1137 block(ls); /* `then' part */
1138 return condexit;
1142 static void ifstat (LexState *ls, int line) {
1143 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1144 FuncState *fs = ls->fs;
1145 int flist;
1146 int escapelist = NO_JUMP;
1147 flist = test_then_block(ls); /* IF cond THEN block */
1148 while (ls->t.token == TK_ELSEIF) {
1149 luaK_concat(fs, &escapelist, luaK_jump(fs));
1150 luaK_patchtohere(fs, flist);
1151 flist = test_then_block(ls); /* ELSEIF cond THEN block */
1153 if (ls->t.token == TK_ELSE) {
1154 luaK_concat(fs, &escapelist, luaK_jump(fs));
1155 luaK_patchtohere(fs, flist);
1156 luaX_next(ls); /* skip ELSE (after patch, for correct line info) */
1157 block(ls); /* `else' part */
1159 else
1160 luaK_concat(fs, &escapelist, flist);
1161 luaK_patchtohere(fs, escapelist);
1162 check_match(ls, TK_END, TK_IF, line);
1166 static void localfunc (LexState *ls) {
1167 expdesc v, b;
1168 FuncState *fs = ls->fs;
1169 new_localvar(ls, str_checkname(ls), 0);
1170 init_exp(&v, VLOCAL, fs->freereg);
1171 luaK_reserveregs(fs, 1);
1172 adjustlocalvars(ls, 1);
1173 body(ls, &b, 0, ls->linenumber);
1174 luaK_storevar(fs, &v, &b);
1175 /* debug information will only see the variable after this point! */
1176 getlocvar(fs, fs->nactvar - 1).startpc = fs->pc;
1180 static void localstat (LexState *ls) {
1181 /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
1182 int nvars = 0;
1183 int nexps;
1184 expdesc e;
1185 do {
1186 new_localvar(ls, str_checkname(ls), nvars++);
1187 } while (testnext(ls, ','));
1188 if (testnext(ls, '='))
1189 nexps = explist1(ls, &e);
1190 else {
1191 e.k = VVOID;
1192 nexps = 0;
1194 adjust_assign(ls, nvars, nexps, &e);
1195 adjustlocalvars(ls, nvars);
1199 static int funcname (LexState *ls, expdesc *v) {
1200 /* funcname -> NAME {field} [`:' NAME] */
1201 int needself = 0;
1202 singlevar(ls, v);
1203 while (ls->t.token == '.')
1204 field(ls, v);
1205 if (ls->t.token == ':') {
1206 needself = 1;
1207 field(ls, v);
1209 return needself;
1213 static void funcstat (LexState *ls, int line) {
1214 /* funcstat -> FUNCTION funcname body */
1215 int needself;
1216 expdesc v, b;
1217 luaX_next(ls); /* skip FUNCTION */
1218 needself = funcname(ls, &v);
1219 body(ls, &b, needself, line);
1220 luaK_storevar(ls->fs, &v, &b);
1221 luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
1225 static void exprstat (LexState *ls) {
1226 /* stat -> func | assignment */
1227 FuncState *fs = ls->fs;
1228 struct LHS_assign v;
1229 primaryexp(ls, &v.v);
1230 if (v.v.k == VCALL) /* stat -> func */
1231 SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
1232 else { /* stat -> assignment */
1233 v.prev = NULL;
1234 assignment(ls, &v, 1);
1239 static void retstat (LexState *ls) {
1240 /* stat -> RETURN explist */
1241 FuncState *fs = ls->fs;
1242 expdesc e;
1243 int first, nret; /* registers with returned values */
1244 luaX_next(ls); /* skip RETURN */
1245 if (block_follow(ls->t.token) || ls->t.token == ';')
1246 first = nret = 0; /* return no values */
1247 else {
1248 nret = explist1(ls, &e); /* optional return values */
1249 if (hasmultret(e.k)) {
1250 luaK_setmultret(fs, &e);
1251 if (e.k == VCALL && nret == 1) { /* tail call? */
1252 SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1253 lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1255 first = fs->nactvar;
1256 nret = LUA_MULTRET; /* return all values */
1258 else {
1259 if (nret == 1) /* only one single value? */
1260 first = luaK_exp2anyreg(fs, &e);
1261 else {
1262 luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
1263 first = fs->nactvar; /* return all `active' values */
1264 lua_assert(nret == fs->freereg - first);
1268 luaK_ret(fs, first, nret);
1272 static int statement (LexState *ls) {
1273 int line = ls->linenumber; /* may be needed for error messages */
1274 switch (ls->t.token) {
1275 case TK_IF: { /* stat -> ifstat */
1276 ifstat(ls, line);
1277 return 0;
1279 case TK_WHILE: { /* stat -> whilestat */
1280 whilestat(ls, line);
1281 return 0;
1283 case TK_DO: { /* stat -> DO block END */
1284 luaX_next(ls); /* skip DO */
1285 block(ls);
1286 check_match(ls, TK_END, TK_DO, line);
1287 return 0;
1289 case TK_FOR: { /* stat -> forstat */
1290 forstat(ls, line);
1291 return 0;
1293 case TK_REPEAT: { /* stat -> repeatstat */
1294 repeatstat(ls, line);
1295 return 0;
1297 case TK_FUNCTION: {
1298 funcstat(ls, line); /* stat -> funcstat */
1299 return 0;
1301 case TK_LOCAL: { /* stat -> localstat */
1302 luaX_next(ls); /* skip LOCAL */
1303 if (testnext(ls, TK_FUNCTION)) /* local function? */
1304 localfunc(ls);
1305 else
1306 localstat(ls);
1307 return 0;
1309 case TK_RETURN: { /* stat -> retstat */
1310 retstat(ls);
1311 return 1; /* must be last statement */
1313 case TK_BREAK: { /* stat -> breakstat */
1314 luaX_next(ls); /* skip BREAK */
1315 breakstat(ls);
1316 return 1; /* must be last statement */
1318 default: {
1319 exprstat(ls);
1320 return 0; /* to avoid warnings */
1326 static void chunk (LexState *ls) {
1327 /* chunk -> { stat [`;'] } */
1328 int islast = 0;
1329 enterlevel(ls);
1330 while (!islast && !block_follow(ls->t.token)) {
1331 islast = statement(ls);
1332 testnext(ls, ';');
1333 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1334 ls->fs->freereg >= ls->fs->nactvar);
1335 ls->fs->freereg = ls->fs->nactvar; /* free registers */
1337 leavelevel(ls);
1340 /* }====================================================================== */