Imported from ../lua-4.0.tar.gz.
[lua.git] / src / lparser.c
blobb792c95685e40a7ca1ffa1e771974caced5b4374
1 /*
2 ** $Id: lparser.c,v 1.116 2000/10/27 11:39:52 roberto Exp $
3 ** LL(1) Parser and code generator for Lua
4 ** See Copyright Notice in lua.h
5 */
8 #include <stdio.h>
9 #include <string.h>
11 #include "lua.h"
13 #include "lcode.h"
14 #include "lfunc.h"
15 #include "llex.h"
16 #include "lmem.h"
17 #include "lobject.h"
18 #include "lopcodes.h"
19 #include "lparser.h"
20 #include "lstate.h"
21 #include "lstring.h"
25 ** Constructors descriptor:
26 ** `n' indicates number of elements, and `k' signals whether
27 ** it is a list constructor (k = 0) or a record constructor (k = 1)
28 ** or empty (k = ';' or '}')
30 typedef struct Constdesc {
31 int n;
32 int k;
33 } Constdesc;
36 typedef struct Breaklabel {
37 struct Breaklabel *previous; /* chain */
38 int breaklist;
39 int stacklevel;
40 } Breaklabel;
46 ** prototypes for recursive non-terminal functions
48 static void body (LexState *ls, int needself, int line);
49 static void chunk (LexState *ls);
50 static void constructor (LexState *ls);
51 static void expr (LexState *ls, expdesc *v);
52 static void exp1 (LexState *ls);
56 static void next (LexState *ls) {
57 ls->lastline = ls->linenumber;
58 if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
59 ls->t = ls->lookahead; /* use this one */
60 ls->lookahead.token = TK_EOS; /* and discharge it */
62 else
63 ls->t.token = luaX_lex(ls, &ls->t.seminfo); /* read next token */
67 static void lookahead (LexState *ls) {
68 LUA_ASSERT(ls->lookahead.token == TK_EOS, "two look-aheads");
69 ls->lookahead.token = luaX_lex(ls, &ls->lookahead.seminfo);
73 static void error_expected (LexState *ls, int token) {
74 char buff[100], t[TOKEN_LEN];
75 luaX_token2str(token, t);
76 sprintf(buff, "`%.20s' expected", t);
77 luaK_error(ls, buff);
81 static void check (LexState *ls, int c) {
82 if (ls->t.token != c)
83 error_expected(ls, c);
84 next(ls);
88 static void check_condition (LexState *ls, int c, const char *msg) {
89 if (!c) luaK_error(ls, msg);
93 static int optional (LexState *ls, int c) {
94 if (ls->t.token == c) {
95 next(ls);
96 return 1;
98 else return 0;
102 static void check_match (LexState *ls, int what, int who, int where) {
103 if (ls->t.token != what) {
104 if (where == ls->linenumber)
105 error_expected(ls, what);
106 else {
107 char buff[100];
108 char t_what[TOKEN_LEN], t_who[TOKEN_LEN];
109 luaX_token2str(what, t_what);
110 luaX_token2str(who, t_who);
111 sprintf(buff, "`%.20s' expected (to close `%.20s' at line %d)",
112 t_what, t_who, where);
113 luaK_error(ls, buff);
116 next(ls);
120 static int string_constant (FuncState *fs, TString *s) {
121 Proto *f = fs->f;
122 int c = s->u.s.constindex;
123 if (c >= f->nkstr || f->kstr[c] != s) {
124 luaM_growvector(fs->L, f->kstr, f->nkstr, 1, TString *,
125 "constant table overflow", MAXARG_U);
126 c = f->nkstr++;
127 f->kstr[c] = s;
128 s->u.s.constindex = c; /* hint for next time */
130 return c;
134 static void code_string (LexState *ls, TString *s) {
135 luaK_kstr(ls, string_constant(ls->fs, s));
139 static TString *str_checkname (LexState *ls) {
140 TString *ts;
141 check_condition(ls, (ls->t.token == TK_NAME), "<name> expected");
142 ts = ls->t.seminfo.ts;
143 next(ls);
144 return ts;
148 static int checkname (LexState *ls) {
149 return string_constant(ls->fs, str_checkname(ls));
153 static int luaI_registerlocalvar (LexState *ls, TString *varname) {
154 Proto *f = ls->fs->f;
155 luaM_growvector(ls->L, f->locvars, f->nlocvars, 1, LocVar, "", MAX_INT);
156 f->locvars[f->nlocvars].varname = varname;
157 return f->nlocvars++;
161 static void new_localvar (LexState *ls, TString *name, int n) {
162 FuncState *fs = ls->fs;
163 luaX_checklimit(ls, fs->nactloc+n+1, MAXLOCALS, "local variables");
164 fs->actloc[fs->nactloc+n] = luaI_registerlocalvar(ls, name);
168 static void adjustlocalvars (LexState *ls, int nvars) {
169 FuncState *fs = ls->fs;
170 while (nvars--)
171 fs->f->locvars[fs->actloc[fs->nactloc++]].startpc = fs->pc;
175 static void removelocalvars (LexState *ls, int nvars) {
176 FuncState *fs = ls->fs;
177 while (nvars--)
178 fs->f->locvars[fs->actloc[--fs->nactloc]].endpc = fs->pc;
182 static void new_localvarstr (LexState *ls, const char *name, int n) {
183 new_localvar(ls, luaS_newfixed(ls->L, name), n);
187 static int search_local (LexState *ls, TString *n, expdesc *var) {
188 FuncState *fs;
189 int level = 0;
190 for (fs=ls->fs; fs; fs=fs->prev) {
191 int i;
192 for (i=fs->nactloc-1; i >= 0; i--) {
193 if (n == fs->f->locvars[fs->actloc[i]].varname) {
194 var->k = VLOCAL;
195 var->u.index = i;
196 return level;
199 level++; /* `var' not found; check outer level */
201 var->k = VGLOBAL; /* not found in any level; must be global */
202 return -1;
206 static void singlevar (LexState *ls, TString *n, expdesc *var) {
207 int level = search_local(ls, n, var);
208 if (level >= 1) /* neither local (0) nor global (-1)? */
209 luaX_syntaxerror(ls, "cannot access a variable in outer scope", n->str);
210 else if (level == -1) /* global? */
211 var->u.index = string_constant(ls->fs, n);
215 static int indexupvalue (LexState *ls, expdesc *v) {
216 FuncState *fs = ls->fs;
217 int i;
218 for (i=0; i<fs->nupvalues; i++) {
219 if (fs->upvalues[i].k == v->k && fs->upvalues[i].u.index == v->u.index)
220 return i;
222 /* new one */
223 luaX_checklimit(ls, fs->nupvalues+1, MAXUPVALUES, "upvalues");
224 fs->upvalues[fs->nupvalues] = *v;
225 return fs->nupvalues++;
229 static void pushupvalue (LexState *ls, TString *n) {
230 FuncState *fs = ls->fs;
231 expdesc v;
232 int level = search_local(ls, n, &v);
233 if (level == -1) { /* global? */
234 if (fs->prev == NULL)
235 luaX_syntaxerror(ls, "cannot access upvalue in main", n->str);
236 v.u.index = string_constant(fs->prev, n);
238 else if (level != 1)
239 luaX_syntaxerror(ls,
240 "upvalue must be global or local to immediately outer scope", n->str);
241 luaK_code1(fs, OP_PUSHUPVALUE, indexupvalue(ls, &v));
245 static void adjust_mult_assign (LexState *ls, int nvars, int nexps) {
246 FuncState *fs = ls->fs;
247 int diff = nexps - nvars;
248 if (nexps > 0 && luaK_lastisopen(fs)) { /* list ends in a function call */
249 diff--; /* do not count function call itself */
250 if (diff <= 0) { /* more variables than values? */
251 luaK_setcallreturns(fs, -diff); /* function call provide extra values */
252 diff = 0; /* no more difference */
254 else /* more values than variables */
255 luaK_setcallreturns(fs, 0); /* call should provide no value */
257 /* push or pop eventual difference between list lengths */
258 luaK_adjuststack(fs, diff);
262 static void code_params (LexState *ls, int nparams, int dots) {
263 FuncState *fs = ls->fs;
264 adjustlocalvars(ls, nparams);
265 luaX_checklimit(ls, fs->nactloc, MAXPARAMS, "parameters");
266 fs->f->numparams = fs->nactloc; /* `self' could be there already */
267 fs->f->is_vararg = dots;
268 if (dots) {
269 new_localvarstr(ls, "arg", 0);
270 adjustlocalvars(ls, 1);
272 luaK_deltastack(fs, fs->nactloc); /* count parameters in the stack */
276 static void enterbreak (FuncState *fs, Breaklabel *bl) {
277 bl->stacklevel = fs->stacklevel;
278 bl->breaklist = NO_JUMP;
279 bl->previous = fs->bl;
280 fs->bl = bl;
284 static void leavebreak (FuncState *fs, Breaklabel *bl) {
285 fs->bl = bl->previous;
286 LUA_ASSERT(bl->stacklevel == fs->stacklevel, "wrong levels");
287 luaK_patchlist(fs, bl->breaklist, luaK_getlabel(fs));
291 static void pushclosure (LexState *ls, FuncState *func) {
292 FuncState *fs = ls->fs;
293 Proto *f = fs->f;
294 int i;
295 for (i=0; i<func->nupvalues; i++)
296 luaK_tostack(ls, &func->upvalues[i], 1);
297 luaM_growvector(ls->L, f->kproto, f->nkproto, 1, Proto *,
298 "constant table overflow", MAXARG_A);
299 f->kproto[f->nkproto++] = func->f;
300 luaK_code2(fs, OP_CLOSURE, f->nkproto-1, func->nupvalues);
304 static void open_func (LexState *ls, FuncState *fs) {
305 Proto *f = luaF_newproto(ls->L);
306 fs->prev = ls->fs; /* linked list of funcstates */
307 fs->ls = ls;
308 fs->L = ls->L;
309 ls->fs = fs;
310 fs->stacklevel = 0;
311 fs->nactloc = 0;
312 fs->nupvalues = 0;
313 fs->bl = NULL;
314 fs->f = f;
315 f->source = ls->source;
316 fs->pc = 0;
317 fs->lasttarget = 0;
318 fs->lastline = 0;
319 fs->jlt = NO_JUMP;
320 f->code = NULL;
321 f->maxstacksize = 0;
322 f->numparams = 0; /* default for main chunk */
323 f->is_vararg = 0; /* default for main chunk */
327 static void close_func (LexState *ls) {
328 lua_State *L = ls->L;
329 FuncState *fs = ls->fs;
330 Proto *f = fs->f;
331 luaK_code0(fs, OP_END);
332 luaK_getlabel(fs); /* close eventual list of pending jumps */
333 luaM_reallocvector(L, f->code, fs->pc, Instruction);
334 luaM_reallocvector(L, f->kstr, f->nkstr, TString *);
335 luaM_reallocvector(L, f->knum, f->nknum, Number);
336 luaM_reallocvector(L, f->kproto, f->nkproto, Proto *);
337 removelocalvars(ls, fs->nactloc);
338 luaM_reallocvector(L, f->locvars, f->nlocvars, LocVar);
339 luaM_reallocvector(L, f->lineinfo, f->nlineinfo+1, int);
340 f->lineinfo[f->nlineinfo++] = MAX_INT; /* end flag */
341 luaF_protook(L, f, fs->pc); /* proto is ok now */
342 ls->fs = fs->prev;
343 LUA_ASSERT(fs->bl == NULL, "wrong list end");
347 Proto *luaY_parser (lua_State *L, ZIO *z) {
348 struct LexState lexstate;
349 struct FuncState funcstate;
350 luaX_setinput(L, &lexstate, z, luaS_new(L, zname(z)));
351 open_func(&lexstate, &funcstate);
352 next(&lexstate); /* read first token */
353 chunk(&lexstate);
354 check_condition(&lexstate, (lexstate.t.token == TK_EOS), "<eof> expected");
355 close_func(&lexstate);
356 LUA_ASSERT(funcstate.prev == NULL, "wrong list end");
357 LUA_ASSERT(funcstate.nupvalues == 0, "no upvalues in main");
358 return funcstate.f;
363 /*============================================================*/
364 /* GRAMMAR RULES */
365 /*============================================================*/
368 static int explist1 (LexState *ls) {
369 /* explist1 -> expr { ',' expr } */
370 int n = 1; /* at least one expression */
371 expdesc v;
372 expr(ls, &v);
373 while (ls->t.token == ',') {
374 luaK_tostack(ls, &v, 1); /* gets only 1 value from previous expression */
375 next(ls); /* skip comma */
376 expr(ls, &v);
377 n++;
379 luaK_tostack(ls, &v, 0); /* keep open number of values of last expression */
380 return n;
384 static void funcargs (LexState *ls, int slf) {
385 FuncState *fs = ls->fs;
386 int slevel = fs->stacklevel - slf - 1; /* where is func in the stack */
387 switch (ls->t.token) {
388 case '(': { /* funcargs -> '(' [ explist1 ] ')' */
389 int line = ls->linenumber;
390 int nargs = 0;
391 next(ls);
392 if (ls->t.token != ')') /* arg list not empty? */
393 nargs = explist1(ls);
394 check_match(ls, ')', '(', line);
395 #ifdef LUA_COMPAT_ARGRET
396 if (nargs > 0) /* arg list is not empty? */
397 luaK_setcallreturns(fs, 1); /* last call returns only 1 value */
398 #else
399 UNUSED(nargs); /* to avoid warnings */
400 #endif
401 break;
403 case '{': { /* funcargs -> constructor */
404 constructor(ls);
405 break;
407 case TK_STRING: { /* funcargs -> STRING */
408 code_string(ls, ls->t.seminfo.ts); /* must use `seminfo' before `next' */
409 next(ls);
410 break;
412 default: {
413 luaK_error(ls, "function arguments expected");
414 break;
417 fs->stacklevel = slevel; /* call will remove function and arguments */
418 luaK_code2(fs, OP_CALL, slevel, MULT_RET);
422 static void var_or_func_tail (LexState *ls, expdesc *v) {
423 for (;;) {
424 switch (ls->t.token) {
425 case '.': { /* var_or_func_tail -> '.' NAME */
426 next(ls);
427 luaK_tostack(ls, v, 1); /* `v' must be on stack */
428 luaK_kstr(ls, checkname(ls));
429 v->k = VINDEXED;
430 break;
432 case '[': { /* var_or_func_tail -> '[' exp1 ']' */
433 next(ls);
434 luaK_tostack(ls, v, 1); /* `v' must be on stack */
435 v->k = VINDEXED;
436 exp1(ls);
437 check(ls, ']');
438 break;
440 case ':': { /* var_or_func_tail -> ':' NAME funcargs */
441 int name;
442 next(ls);
443 name = checkname(ls);
444 luaK_tostack(ls, v, 1); /* `v' must be on stack */
445 luaK_code1(ls->fs, OP_PUSHSELF, name);
446 funcargs(ls, 1);
447 v->k = VEXP;
448 v->u.l.t = v->u.l.f = NO_JUMP;
449 break;
451 case '(': case TK_STRING: case '{': { /* var_or_func_tail -> funcargs */
452 luaK_tostack(ls, v, 1); /* `v' must be on stack */
453 funcargs(ls, 0);
454 v->k = VEXP;
455 v->u.l.t = v->u.l.f = NO_JUMP;
456 break;
458 default: return; /* should be follow... */
464 static void var_or_func (LexState *ls, expdesc *v) {
465 /* var_or_func -> ['%'] NAME var_or_func_tail */
466 if (optional(ls, '%')) { /* upvalue? */
467 pushupvalue(ls, str_checkname(ls));
468 v->k = VEXP;
469 v->u.l.t = v->u.l.f = NO_JUMP;
471 else /* variable name */
472 singlevar(ls, str_checkname(ls), v);
473 var_or_func_tail(ls, v);
479 ** {======================================================================
480 ** Rules for Constructors
481 ** =======================================================================
485 static void recfield (LexState *ls) {
486 /* recfield -> (NAME | '['exp1']') = exp1 */
487 switch (ls->t.token) {
488 case TK_NAME: {
489 luaK_kstr(ls, checkname(ls));
490 break;
492 case '[': {
493 next(ls);
494 exp1(ls);
495 check(ls, ']');
496 break;
498 default: luaK_error(ls, "<name> or `[' expected");
500 check(ls, '=');
501 exp1(ls);
505 static int recfields (LexState *ls) {
506 /* recfields -> recfield { ',' recfield } [','] */
507 FuncState *fs = ls->fs;
508 int n = 1; /* at least one element */
509 recfield(ls);
510 while (ls->t.token == ',') {
511 next(ls);
512 if (ls->t.token == ';' || ls->t.token == '}')
513 break;
514 recfield(ls);
515 n++;
516 if (n%RFIELDS_PER_FLUSH == 0)
517 luaK_code1(fs, OP_SETMAP, RFIELDS_PER_FLUSH);
519 luaK_code1(fs, OP_SETMAP, n%RFIELDS_PER_FLUSH);
520 return n;
524 static int listfields (LexState *ls) {
525 /* listfields -> exp1 { ',' exp1 } [','] */
526 FuncState *fs = ls->fs;
527 int n = 1; /* at least one element */
528 exp1(ls);
529 while (ls->t.token == ',') {
530 next(ls);
531 if (ls->t.token == ';' || ls->t.token == '}')
532 break;
533 exp1(ls);
534 n++;
535 luaX_checklimit(ls, n/LFIELDS_PER_FLUSH, MAXARG_A,
536 "`item groups' in a list initializer");
537 if (n%LFIELDS_PER_FLUSH == 0)
538 luaK_code2(fs, OP_SETLIST, n/LFIELDS_PER_FLUSH - 1, LFIELDS_PER_FLUSH);
540 luaK_code2(fs, OP_SETLIST, n/LFIELDS_PER_FLUSH, n%LFIELDS_PER_FLUSH);
541 return n;
546 static void constructor_part (LexState *ls, Constdesc *cd) {
547 switch (ls->t.token) {
548 case ';': case '}': { /* constructor_part -> empty */
549 cd->n = 0;
550 cd->k = ls->t.token;
551 break;
553 case TK_NAME: { /* may be listfields or recfields */
554 lookahead(ls);
555 if (ls->lookahead.token != '=') /* expression? */
556 goto case_default;
557 /* else go through to recfields */
559 case '[': { /* constructor_part -> recfields */
560 cd->n = recfields(ls);
561 cd->k = 1; /* record */
562 break;
564 default: { /* constructor_part -> listfields */
565 case_default:
566 cd->n = listfields(ls);
567 cd->k = 0; /* list */
568 break;
574 static void constructor (LexState *ls) {
575 /* constructor -> '{' constructor_part [';' constructor_part] '}' */
576 FuncState *fs = ls->fs;
577 int line = ls->linenumber;
578 int pc = luaK_code1(fs, OP_CREATETABLE, 0);
579 int nelems;
580 Constdesc cd;
581 check(ls, '{');
582 constructor_part(ls, &cd);
583 nelems = cd.n;
584 if (optional(ls, ';')) {
585 Constdesc other_cd;
586 constructor_part(ls, &other_cd);
587 check_condition(ls, (cd.k != other_cd.k), "invalid constructor syntax");
588 nelems += other_cd.n;
590 check_match(ls, '}', '{', line);
591 luaX_checklimit(ls, nelems, MAXARG_U, "elements in a table constructor");
592 SETARG_U(fs->f->code[pc], nelems); /* set initial table size */
595 /* }====================================================================== */
601 ** {======================================================================
602 ** Expression parsing
603 ** =======================================================================
607 static void simpleexp (LexState *ls, expdesc *v) {
608 FuncState *fs = ls->fs;
609 switch (ls->t.token) {
610 case TK_NUMBER: { /* simpleexp -> NUMBER */
611 Number r = ls->t.seminfo.r;
612 next(ls);
613 luaK_number(fs, r);
614 break;
616 case TK_STRING: { /* simpleexp -> STRING */
617 code_string(ls, ls->t.seminfo.ts); /* must use `seminfo' before `next' */
618 next(ls);
619 break;
621 case TK_NIL: { /* simpleexp -> NIL */
622 luaK_adjuststack(fs, -1);
623 next(ls);
624 break;
626 case '{': { /* simpleexp -> constructor */
627 constructor(ls);
628 break;
630 case TK_FUNCTION: { /* simpleexp -> FUNCTION body */
631 next(ls);
632 body(ls, 0, ls->linenumber);
633 break;
635 case '(': { /* simpleexp -> '(' expr ')' */
636 next(ls);
637 expr(ls, v);
638 check(ls, ')');
639 return;
641 case TK_NAME: case '%': {
642 var_or_func(ls, v);
643 return;
645 default: {
646 luaK_error(ls, "<expression> expected");
647 return;
650 v->k = VEXP;
651 v->u.l.t = v->u.l.f = NO_JUMP;
655 static void exp1 (LexState *ls) {
656 expdesc v;
657 expr(ls, &v);
658 luaK_tostack(ls, &v, 1);
662 static UnOpr getunopr (int op) {
663 switch (op) {
664 case TK_NOT: return OPR_NOT;
665 case '-': return OPR_MINUS;
666 default: return OPR_NOUNOPR;
671 static BinOpr getbinopr (int op) {
672 switch (op) {
673 case '+': return OPR_ADD;
674 case '-': return OPR_SUB;
675 case '*': return OPR_MULT;
676 case '/': return OPR_DIV;
677 case '^': return OPR_POW;
678 case TK_CONCAT: return OPR_CONCAT;
679 case TK_NE: return OPR_NE;
680 case TK_EQ: return OPR_EQ;
681 case '<': return OPR_LT;
682 case TK_LE: return OPR_LE;
683 case '>': return OPR_GT;
684 case TK_GE: return OPR_GE;
685 case TK_AND: return OPR_AND;
686 case TK_OR: return OPR_OR;
687 default: return OPR_NOBINOPR;
692 static const struct {
693 char left; /* left priority for each binary operator */
694 char right; /* right priority */
695 } priority[] = { /* ORDER OPR */
696 {5, 5}, {5, 5}, {6, 6}, {6, 6}, /* arithmetic */
697 {9, 8}, {4, 3}, /* power and concat (right associative) */
698 {2, 2}, {2, 2}, /* equality */
699 {2, 2}, {2, 2}, {2, 2}, {2, 2}, /* order */
700 {1, 1}, {1, 1} /* logical */
703 #define UNARY_PRIORITY 7 /* priority for unary operators */
707 ** subexpr -> (simplexep | unop subexpr) { binop subexpr }
708 ** where `binop' is any binary operator with a priority higher than `limit'
710 static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
711 BinOpr op;
712 UnOpr uop = getunopr(ls->t.token);
713 if (uop != OPR_NOUNOPR) {
714 next(ls);
715 subexpr(ls, v, UNARY_PRIORITY);
716 luaK_prefix(ls, uop, v);
718 else simpleexp(ls, v);
719 /* expand while operators have priorities higher than `limit' */
720 op = getbinopr(ls->t.token);
721 while (op != OPR_NOBINOPR && priority[op].left > limit) {
722 expdesc v2;
723 BinOpr nextop;
724 next(ls);
725 luaK_infix(ls, op, v);
726 /* read sub-expression with higher priority */
727 nextop = subexpr(ls, &v2, priority[op].right);
728 luaK_posfix(ls, op, v, &v2);
729 op = nextop;
731 return op; /* return first untreated operator */
735 static void expr (LexState *ls, expdesc *v) {
736 subexpr(ls, v, -1);
739 /* }==================================================================== */
743 ** {======================================================================
744 ** Rules for Statements
745 ** =======================================================================
749 static int block_follow (int token) {
750 switch (token) {
751 case TK_ELSE: case TK_ELSEIF: case TK_END:
752 case TK_UNTIL: case TK_EOS:
753 return 1;
754 default: return 0;
759 static void block (LexState *ls) {
760 /* block -> chunk */
761 FuncState *fs = ls->fs;
762 int nactloc = fs->nactloc;
763 chunk(ls);
764 luaK_adjuststack(fs, fs->nactloc - nactloc); /* remove local variables */
765 removelocalvars(ls, fs->nactloc - nactloc);
769 static int assignment (LexState *ls, expdesc *v, int nvars) {
770 int left = 0; /* number of values left in the stack after assignment */
771 luaX_checklimit(ls, nvars, MAXVARSLH, "variables in a multiple assignment");
772 if (ls->t.token == ',') { /* assignment -> ',' NAME assignment */
773 expdesc nv;
774 next(ls);
775 var_or_func(ls, &nv);
776 check_condition(ls, (nv.k != VEXP), "syntax error");
777 left = assignment(ls, &nv, nvars+1);
779 else { /* assignment -> '=' explist1 */
780 int nexps;
781 check(ls, '=');
782 nexps = explist1(ls);
783 adjust_mult_assign(ls, nvars, nexps);
785 if (v->k != VINDEXED)
786 luaK_storevar(ls, v);
787 else { /* there may be garbage between table-index and value */
788 luaK_code2(ls->fs, OP_SETTABLE, left+nvars+2, 1);
789 left += 2;
791 return left;
795 static void cond (LexState *ls, expdesc *v) {
796 /* cond -> exp */
797 expr(ls, v); /* read condition */
798 luaK_goiftrue(ls->fs, v, 0);
802 static void whilestat (LexState *ls, int line) {
803 /* whilestat -> WHILE cond DO block END */
804 FuncState *fs = ls->fs;
805 int while_init = luaK_getlabel(fs);
806 expdesc v;
807 Breaklabel bl;
808 enterbreak(fs, &bl);
809 next(ls);
810 cond(ls, &v);
811 check(ls, TK_DO);
812 block(ls);
813 luaK_patchlist(fs, luaK_jump(fs), while_init);
814 luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
815 check_match(ls, TK_END, TK_WHILE, line);
816 leavebreak(fs, &bl);
820 static void repeatstat (LexState *ls, int line) {
821 /* repeatstat -> REPEAT block UNTIL cond */
822 FuncState *fs = ls->fs;
823 int repeat_init = luaK_getlabel(fs);
824 expdesc v;
825 Breaklabel bl;
826 enterbreak(fs, &bl);
827 next(ls);
828 block(ls);
829 check_match(ls, TK_UNTIL, TK_REPEAT, line);
830 cond(ls, &v);
831 luaK_patchlist(fs, v.u.l.f, repeat_init);
832 leavebreak(fs, &bl);
836 static void forbody (LexState *ls, int nvar, OpCode prepfor, OpCode loopfor) {
837 /* forbody -> DO block END */
838 FuncState *fs = ls->fs;
839 int prep = luaK_code1(fs, prepfor, NO_JUMP);
840 int blockinit = luaK_getlabel(fs);
841 check(ls, TK_DO);
842 adjustlocalvars(ls, nvar); /* scope for control variables */
843 block(ls);
844 luaK_patchlist(fs, luaK_code1(fs, loopfor, NO_JUMP), blockinit);
845 luaK_patchlist(fs, prep, luaK_getlabel(fs));
846 removelocalvars(ls, nvar);
850 static void fornum (LexState *ls, TString *varname) {
851 /* fornum -> NAME = exp1,exp1[,exp1] forbody */
852 FuncState *fs = ls->fs;
853 check(ls, '=');
854 exp1(ls); /* initial value */
855 check(ls, ',');
856 exp1(ls); /* limit */
857 if (optional(ls, ','))
858 exp1(ls); /* optional step */
859 else
860 luaK_code1(fs, OP_PUSHINT, 1); /* default step */
861 new_localvar(ls, varname, 0);
862 new_localvarstr(ls, "(limit)", 1);
863 new_localvarstr(ls, "(step)", 2);
864 forbody(ls, 3, OP_FORPREP, OP_FORLOOP);
868 static void forlist (LexState *ls, TString *indexname) {
869 /* forlist -> NAME,NAME IN exp1 forbody */
870 TString *valname;
871 check(ls, ',');
872 valname = str_checkname(ls);
873 /* next test is dirty, but avoids `in' being a reserved word */
874 check_condition(ls,
875 (ls->t.token == TK_NAME && ls->t.seminfo.ts == luaS_new(ls->L, "in")),
876 "`in' expected");
877 next(ls); /* skip `in' */
878 exp1(ls); /* table */
879 new_localvarstr(ls, "(table)", 0);
880 new_localvar(ls, indexname, 1);
881 new_localvar(ls, valname, 2);
882 forbody(ls, 3, OP_LFORPREP, OP_LFORLOOP);
886 static void forstat (LexState *ls, int line) {
887 /* forstat -> fornum | forlist */
888 FuncState *fs = ls->fs;
889 TString *varname;
890 Breaklabel bl;
891 enterbreak(fs, &bl);
892 next(ls); /* skip `for' */
893 varname = str_checkname(ls); /* first variable name */
894 switch (ls->t.token) {
895 case '=': fornum(ls, varname); break;
896 case ',': forlist(ls, varname); break;
897 default: luaK_error(ls, "`=' or `,' expected");
899 check_match(ls, TK_END, TK_FOR, line);
900 leavebreak(fs, &bl);
904 static void test_then_block (LexState *ls, expdesc *v) {
905 /* test_then_block -> [IF | ELSEIF] cond THEN block */
906 next(ls); /* skip IF or ELSEIF */
907 cond(ls, v);
908 check(ls, TK_THEN);
909 block(ls); /* `then' part */
913 static void ifstat (LexState *ls, int line) {
914 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
915 FuncState *fs = ls->fs;
916 expdesc v;
917 int escapelist = NO_JUMP;
918 test_then_block(ls, &v); /* IF cond THEN block */
919 while (ls->t.token == TK_ELSEIF) {
920 luaK_concat(fs, &escapelist, luaK_jump(fs));
921 luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
922 test_then_block(ls, &v); /* ELSEIF cond THEN block */
924 if (ls->t.token == TK_ELSE) {
925 luaK_concat(fs, &escapelist, luaK_jump(fs));
926 luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
927 next(ls); /* skip ELSE */
928 block(ls); /* `else' part */
930 else
931 luaK_concat(fs, &escapelist, v.u.l.f);
932 luaK_patchlist(fs, escapelist, luaK_getlabel(fs));
933 check_match(ls, TK_END, TK_IF, line);
937 static void localstat (LexState *ls) {
938 /* stat -> LOCAL NAME {',' NAME} ['=' explist1] */
939 int nvars = 0;
940 int nexps;
941 do {
942 next(ls); /* skip LOCAL or ',' */
943 new_localvar(ls, str_checkname(ls), nvars++);
944 } while (ls->t.token == ',');
945 if (optional(ls, '='))
946 nexps = explist1(ls);
947 else
948 nexps = 0;
949 adjust_mult_assign(ls, nvars, nexps);
950 adjustlocalvars(ls, nvars);
954 static int funcname (LexState *ls, expdesc *v) {
955 /* funcname -> NAME [':' NAME | '.' NAME] */
956 int needself = 0;
957 singlevar(ls, str_checkname(ls), v);
958 if (ls->t.token == ':' || ls->t.token == '.') {
959 needself = (ls->t.token == ':');
960 next(ls);
961 luaK_tostack(ls, v, 1);
962 luaK_kstr(ls, checkname(ls));
963 v->k = VINDEXED;
965 return needself;
969 static void funcstat (LexState *ls, int line) {
970 /* funcstat -> FUNCTION funcname body */
971 int needself;
972 expdesc v;
973 next(ls); /* skip FUNCTION */
974 needself = funcname(ls, &v);
975 body(ls, needself, line);
976 luaK_storevar(ls, &v);
980 static void namestat (LexState *ls) {
981 /* stat -> func | ['%'] NAME assignment */
982 FuncState *fs = ls->fs;
983 expdesc v;
984 var_or_func(ls, &v);
985 if (v.k == VEXP) { /* stat -> func */
986 check_condition(ls, luaK_lastisopen(fs), "syntax error"); /* an upvalue? */
987 luaK_setcallreturns(fs, 0); /* call statement uses no results */
989 else { /* stat -> ['%'] NAME assignment */
990 int left = assignment(ls, &v, 1);
991 luaK_adjuststack(fs, left); /* remove eventual garbage left on stack */
996 static void retstat (LexState *ls) {
997 /* stat -> RETURN explist */
998 FuncState *fs = ls->fs;
999 next(ls); /* skip RETURN */
1000 if (!block_follow(ls->t.token))
1001 explist1(ls); /* optional return values */
1002 luaK_code1(fs, OP_RETURN, ls->fs->nactloc);
1003 fs->stacklevel = fs->nactloc; /* removes all temp values */
1007 static void breakstat (LexState *ls) {
1008 /* stat -> BREAK [NAME] */
1009 FuncState *fs = ls->fs;
1010 int currentlevel = fs->stacklevel;
1011 Breaklabel *bl = fs->bl;
1012 if (!bl)
1013 luaK_error(ls, "no loop to break");
1014 next(ls); /* skip BREAK */
1015 luaK_adjuststack(fs, currentlevel - bl->stacklevel);
1016 luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
1017 /* correct stack for compiler and symbolic execution */
1018 luaK_adjuststack(fs, bl->stacklevel - currentlevel);
1022 static int stat (LexState *ls) {
1023 int line = ls->linenumber; /* may be needed for error messages */
1024 switch (ls->t.token) {
1025 case TK_IF: { /* stat -> ifstat */
1026 ifstat(ls, line);
1027 return 0;
1029 case TK_WHILE: { /* stat -> whilestat */
1030 whilestat(ls, line);
1031 return 0;
1033 case TK_DO: { /* stat -> DO block END */
1034 next(ls); /* skip DO */
1035 block(ls);
1036 check_match(ls, TK_END, TK_DO, line);
1037 return 0;
1039 case TK_FOR: { /* stat -> forstat */
1040 forstat(ls, line);
1041 return 0;
1043 case TK_REPEAT: { /* stat -> repeatstat */
1044 repeatstat(ls, line);
1045 return 0;
1047 case TK_FUNCTION: { /* stat -> funcstat */
1048 funcstat(ls, line);
1049 return 0;
1051 case TK_LOCAL: { /* stat -> localstat */
1052 localstat(ls);
1053 return 0;
1055 case TK_NAME: case '%': { /* stat -> namestat */
1056 namestat(ls);
1057 return 0;
1059 case TK_RETURN: { /* stat -> retstat */
1060 retstat(ls);
1061 return 1; /* must be last statement */
1063 case TK_BREAK: { /* stat -> breakstat */
1064 breakstat(ls);
1065 return 1; /* must be last statement */
1067 default: {
1068 luaK_error(ls, "<statement> expected");
1069 return 0; /* to avoid warnings */
1075 static void parlist (LexState *ls) {
1076 /* parlist -> [ param { ',' param } ] */
1077 int nparams = 0;
1078 int dots = 0;
1079 if (ls->t.token != ')') { /* is `parlist' not empty? */
1080 do {
1081 switch (ls->t.token) {
1082 case TK_DOTS: next(ls); dots = 1; break;
1083 case TK_NAME: new_localvar(ls, str_checkname(ls), nparams++); break;
1084 default: luaK_error(ls, "<name> or `...' expected");
1086 } while (!dots && optional(ls, ','));
1088 code_params(ls, nparams, dots);
1092 static void body (LexState *ls, int needself, int line) {
1093 /* body -> '(' parlist ')' chunk END */
1094 FuncState new_fs;
1095 open_func(ls, &new_fs);
1096 new_fs.f->lineDefined = line;
1097 check(ls, '(');
1098 if (needself) {
1099 new_localvarstr(ls, "self", 0);
1100 adjustlocalvars(ls, 1);
1102 parlist(ls);
1103 check(ls, ')');
1104 chunk(ls);
1105 check_match(ls, TK_END, TK_FUNCTION, line);
1106 close_func(ls);
1107 pushclosure(ls, &new_fs);
1111 /* }====================================================================== */
1114 static void chunk (LexState *ls) {
1115 /* chunk -> { stat [';'] } */
1116 int islast = 0;
1117 while (!islast && !block_follow(ls->t.token)) {
1118 islast = stat(ls);
1119 optional(ls, ';');
1120 LUA_ASSERT(ls->fs->stacklevel == ls->fs->nactloc,
1121 "stack size != # local vars");