2 ** $Id: lparser.c,v 1.208a 2003/04/03 13:35:34 roberto Exp $
4 ** See Copyright Notice in lua.h
28 #define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]])
31 #define enterlevel(ls) if (++(ls)->nestlevel > LUA_MAXPARSERLEVEL) \
32 luaX_syntaxerror(ls, "too many syntax levels");
33 #define leavelevel(ls) ((ls)->nestlevel--)
37 ** nodes for block list (list of active blocks)
39 typedef struct BlockCnt
{
40 struct BlockCnt
*previous
; /* chain */
41 int breaklist
; /* list of jumps out of this loop */
42 int nactvar
; /* # active local variables outside the breakable structure */
43 int upval
; /* true if some variable in the block is an upvalue */
44 int isbreakable
; /* true if `block' is a loop */
50 ** prototypes for recursive non-terminal functions
52 static void chunk (LexState
*ls
);
53 static void expr (LexState
*ls
, expdesc
*v
);
57 static void next (LexState
*ls
) {
58 ls
->lastline
= ls
->linenumber
;
59 if (ls
->lookahead
.token
!= TK_EOS
) { /* is there a look-ahead token? */
60 ls
->t
= ls
->lookahead
; /* use this one */
61 ls
->lookahead
.token
= TK_EOS
; /* and discharge it */
64 ls
->t
.token
= luaX_lex(ls
, &ls
->t
.seminfo
); /* read next token */
68 static void lookahead (LexState
*ls
) {
69 lua_assert(ls
->lookahead
.token
== TK_EOS
);
70 ls
->lookahead
.token
= luaX_lex(ls
, &ls
->lookahead
.seminfo
);
74 static void error_expected (LexState
*ls
, int token
) {
76 luaO_pushfstring(ls
->L
, "`%s' expected", luaX_token2str(ls
, token
)));
80 static int testnext (LexState
*ls
, int c
) {
81 if (ls
->t
.token
== c
) {
89 static void check (LexState
*ls
, int c
) {
91 error_expected(ls
, c
);
95 #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
99 static void check_match (LexState
*ls
, int what
, int who
, int where
) {
100 if (!testnext(ls
, what
)) {
101 if (where
== ls
->linenumber
)
102 error_expected(ls
, what
);
104 luaX_syntaxerror(ls
, luaO_pushfstring(ls
->L
,
105 "`%s' expected (to close `%s' at line %d)",
106 luaX_token2str(ls
, what
), luaX_token2str(ls
, who
), where
));
112 static TString
*str_checkname (LexState
*ls
) {
114 check_condition(ls
, (ls
->t
.token
== TK_NAME
), "<name> expected");
115 ts
= ls
->t
.seminfo
.ts
;
121 static void init_exp (expdesc
*e
, expkind k
, int i
) {
122 e
->f
= e
->t
= NO_JUMP
;
128 static void codestring (LexState
*ls
, expdesc
*e
, TString
*s
) {
129 init_exp(e
, VK
, luaK_stringK(ls
->fs
, s
));
133 static void checkname(LexState
*ls
, expdesc
*e
) {
134 codestring(ls
, e
, str_checkname(ls
));
138 static int luaI_registerlocalvar (LexState
*ls
, TString
*varname
) {
139 FuncState
*fs
= ls
->fs
;
141 luaM_growvector(ls
->L
, f
->locvars
, fs
->nlocvars
, f
->sizelocvars
,
142 LocVar
, MAX_INT
, "");
143 f
->locvars
[fs
->nlocvars
].varname
= varname
;
144 return fs
->nlocvars
++;
148 static void new_localvar (LexState
*ls
, TString
*name
, int n
) {
149 FuncState
*fs
= ls
->fs
;
150 luaX_checklimit(ls
, fs
->nactvar
+n
+1, MAXVARS
, "local variables");
151 fs
->actvar
[fs
->nactvar
+n
] = luaI_registerlocalvar(ls
, name
);
155 static void adjustlocalvars (LexState
*ls
, int nvars
) {
156 FuncState
*fs
= ls
->fs
;
157 fs
->nactvar
+= nvars
;
158 for (; nvars
; nvars
--) {
159 getlocvar(fs
, fs
->nactvar
- nvars
).startpc
= fs
->pc
;
164 static void removevars (LexState
*ls
, int tolevel
) {
165 FuncState
*fs
= ls
->fs
;
166 while (fs
->nactvar
> tolevel
)
167 getlocvar(fs
, --fs
->nactvar
).endpc
= fs
->pc
;
171 static void new_localvarstr (LexState
*ls
, const char *name
, int n
) {
172 new_localvar(ls
, luaS_new(ls
->L
, name
), n
);
176 static void create_local (LexState
*ls
, const char *name
) {
177 new_localvarstr(ls
, name
, 0);
178 adjustlocalvars(ls
, 1);
182 static int indexupvalue (FuncState
*fs
, TString
*name
, expdesc
*v
) {
185 for (i
=0; i
<f
->nups
; i
++) {
186 if (fs
->upvalues
[i
].k
== v
->k
&& fs
->upvalues
[i
].info
== v
->info
) {
187 lua_assert(fs
->f
->upvalues
[i
] == name
);
192 luaX_checklimit(fs
->ls
, f
->nups
+ 1, MAXUPVALUES
, "upvalues");
193 luaM_growvector(fs
->L
, fs
->f
->upvalues
, f
->nups
, fs
->f
->sizeupvalues
,
194 TString
*, MAX_INT
, "");
195 fs
->f
->upvalues
[f
->nups
] = name
;
196 fs
->upvalues
[f
->nups
] = *v
;
201 static int searchvar (FuncState
*fs
, TString
*n
) {
203 for (i
=fs
->nactvar
-1; i
>= 0; i
--) {
204 if (n
== getlocvar(fs
, i
).varname
)
207 return -1; /* not found */
211 static void markupval (FuncState
*fs
, int level
) {
212 BlockCnt
*bl
= fs
->bl
;
213 while (bl
&& bl
->nactvar
> level
) bl
= bl
->previous
;
214 if (bl
) bl
->upval
= 1;
218 static void singlevaraux (FuncState
*fs
, TString
*n
, expdesc
*var
, int base
) {
219 if (fs
== NULL
) /* no more levels? */
220 init_exp(var
, VGLOBAL
, NO_REG
); /* default is global variable */
222 int v
= searchvar(fs
, n
); /* look up at current level */
224 init_exp(var
, VLOCAL
, v
);
226 markupval(fs
, v
); /* local will be used as an upval */
228 else { /* not found at current level; try upper one */
229 singlevaraux(fs
->prev
, n
, var
, 0);
230 if (var
->k
== VGLOBAL
) {
232 var
->info
= luaK_stringK(fs
, n
); /* info points to global name */
234 else { /* LOCAL or UPVAL */
235 var
->info
= indexupvalue(fs
, n
, var
);
236 var
->k
= VUPVAL
; /* upvalue in this level */
243 static TString
*singlevar (LexState
*ls
, expdesc
*var
, int base
) {
244 TString
*varname
= str_checkname(ls
);
245 singlevaraux(ls
->fs
, varname
, var
, base
);
250 static void adjust_assign (LexState
*ls
, int nvars
, int nexps
, expdesc
*e
) {
251 FuncState
*fs
= ls
->fs
;
252 int extra
= nvars
- nexps
;
254 extra
++; /* includes call itself */
255 if (extra
<= 0) extra
= 0;
256 else luaK_reserveregs(fs
, extra
-1);
257 luaK_setcallreturns(fs
, e
, extra
); /* call provides the difference */
260 if (e
->k
!= VVOID
) luaK_exp2nextreg(fs
, e
); /* close last expression */
262 int reg
= fs
->freereg
;
263 luaK_reserveregs(fs
, extra
);
264 luaK_nil(fs
, reg
, extra
);
270 static void code_params (LexState
*ls
, int nparams
, int dots
) {
271 FuncState
*fs
= ls
->fs
;
272 adjustlocalvars(ls
, nparams
);
273 luaX_checklimit(ls
, fs
->nactvar
, MAXPARAMS
, "parameters");
274 fs
->f
->numparams
= cast(lu_byte
, fs
->nactvar
);
275 fs
->f
->is_vararg
= cast(lu_byte
, dots
);
277 create_local(ls
, "arg");
278 luaK_reserveregs(fs
, fs
->nactvar
); /* reserve register for parameters */
282 static void enterblock (FuncState
*fs
, BlockCnt
*bl
, int isbreakable
) {
283 bl
->breaklist
= NO_JUMP
;
284 bl
->isbreakable
= isbreakable
;
285 bl
->nactvar
= fs
->nactvar
;
287 bl
->previous
= fs
->bl
;
289 lua_assert(fs
->freereg
== fs
->nactvar
);
293 static void leaveblock (FuncState
*fs
) {
294 BlockCnt
*bl
= fs
->bl
;
295 fs
->bl
= bl
->previous
;
296 removevars(fs
->ls
, bl
->nactvar
);
298 luaK_codeABC(fs
, OP_CLOSE
, bl
->nactvar
, 0, 0);
299 lua_assert(bl
->nactvar
== fs
->nactvar
);
300 fs
->freereg
= fs
->nactvar
; /* free registers */
301 luaK_patchtohere(fs
, bl
->breaklist
);
305 static void pushclosure (LexState
*ls
, FuncState
*func
, expdesc
*v
) {
306 FuncState
*fs
= ls
->fs
;
309 luaM_growvector(ls
->L
, f
->p
, fs
->np
, f
->sizep
, Proto
*,
310 MAXARG_Bx
, "constant table overflow");
311 f
->p
[fs
->np
++] = func
->f
;
312 init_exp(v
, VRELOCABLE
, luaK_codeABx(fs
, OP_CLOSURE
, 0, fs
->np
-1));
313 for (i
=0; i
<func
->f
->nups
; i
++) {
314 OpCode o
= (func
->upvalues
[i
].k
== VLOCAL
) ? OP_MOVE
: OP_GETUPVAL
;
315 luaK_codeABC(fs
, o
, 0, func
->upvalues
[i
].info
, 0);
320 static void open_func (LexState
*ls
, FuncState
*fs
) {
321 Proto
*f
= luaF_newproto(ls
->L
);
323 fs
->prev
= ls
->fs
; /* linked list of funcstates */
332 fs
->h
= luaH_new(ls
->L
, 0, 0);
337 f
->source
= ls
->source
;
338 f
->maxstacksize
= 2; /* registers 0/1 are always valid */
342 static void close_func (LexState
*ls
) {
343 lua_State
*L
= ls
->L
;
344 FuncState
*fs
= ls
->fs
;
347 luaK_codeABC(fs
, OP_RETURN
, 0, 1, 0); /* final return */
348 luaM_reallocvector(L
, f
->code
, f
->sizecode
, fs
->pc
, Instruction
);
349 f
->sizecode
= fs
->pc
;
350 luaM_reallocvector(L
, f
->lineinfo
, f
->sizelineinfo
, fs
->pc
, int);
351 f
->sizelineinfo
= fs
->pc
;
352 luaM_reallocvector(L
, f
->k
, f
->sizek
, fs
->nk
, TObject
);
354 luaM_reallocvector(L
, f
->p
, f
->sizep
, fs
->np
, Proto
*);
356 luaM_reallocvector(L
, f
->locvars
, f
->sizelocvars
, fs
->nlocvars
, LocVar
);
357 f
->sizelocvars
= fs
->nlocvars
;
358 luaM_reallocvector(L
, f
->upvalues
, f
->sizeupvalues
, f
->nups
, TString
*);
359 f
->sizeupvalues
= f
->nups
;
360 lua_assert(luaG_checkcode(f
));
361 lua_assert(fs
->bl
== NULL
);
366 Proto
*luaY_parser (lua_State
*L
, ZIO
*z
, Mbuffer
*buff
) {
367 struct LexState lexstate
;
368 struct FuncState funcstate
;
369 lexstate
.buff
= buff
;
370 lexstate
.nestlevel
= 0;
371 luaX_setinput(L
, &lexstate
, z
, luaS_new(L
, zname(z
)));
372 open_func(&lexstate
, &funcstate
);
373 next(&lexstate
); /* read first token */
375 check_condition(&lexstate
, (lexstate
.t
.token
== TK_EOS
), "<eof> expected");
376 close_func(&lexstate
);
377 lua_assert(funcstate
.prev
== NULL
);
378 lua_assert(funcstate
.f
->nups
== 0);
379 lua_assert(lexstate
.nestlevel
== 0);
385 /*============================================================*/
387 /*============================================================*/
390 static void luaY_field (LexState
*ls
, expdesc
*v
) {
391 /* field -> ['.' | ':'] NAME */
392 FuncState
*fs
= ls
->fs
;
394 luaK_exp2anyreg(fs
, v
);
395 next(ls
); /* skip the dot or colon */
397 luaK_indexed(fs
, v
, &key
);
401 static void luaY_index (LexState
*ls
, expdesc
*v
) {
402 /* index -> '[' expr ']' */
403 next(ls
); /* skip the '[' */
405 luaK_exp2val(ls
->fs
, v
);
411 ** {======================================================================
412 ** Rules for Constructors
413 ** =======================================================================
418 expdesc v
; /* last list item read */
419 expdesc
*t
; /* table descriptor */
420 int nh
; /* total number of `record' elements */
421 int na
; /* total number of array elements */
422 int tostore
; /* number of array elements pending to be stored */
426 static void recfield (LexState
*ls
, struct ConsControl
*cc
) {
427 /* recfield -> (NAME | `['exp1`]') = exp1 */
428 FuncState
*fs
= ls
->fs
;
429 int reg
= ls
->fs
->freereg
;
431 if (ls
->t
.token
== TK_NAME
) {
432 luaX_checklimit(ls
, cc
->nh
, MAX_INT
, "items in a constructor");
436 else /* ls->t.token == '[' */
437 luaY_index(ls
, &key
);
439 luaK_exp2RK(fs
, &key
);
441 luaK_codeABC(fs
, OP_SETTABLE
, cc
->t
->info
, luaK_exp2RK(fs
, &key
),
442 luaK_exp2RK(fs
, &val
));
443 fs
->freereg
= reg
; /* free registers */
447 static void closelistfield (FuncState
*fs
, struct ConsControl
*cc
) {
448 if (cc
->v
.k
== VVOID
) return; /* there is no list item */
449 luaK_exp2nextreg(fs
, &cc
->v
);
451 if (cc
->tostore
== LFIELDS_PER_FLUSH
) {
452 luaK_codeABx(fs
, OP_SETLIST
, cc
->t
->info
, cc
->na
-1); /* flush */
453 cc
->tostore
= 0; /* no more items pending */
454 fs
->freereg
= cc
->t
->info
+ 1; /* free registers */
459 static void lastlistfield (FuncState
*fs
, struct ConsControl
*cc
) {
460 if (cc
->tostore
== 0) return;
461 if (cc
->v
.k
== VCALL
) {
462 luaK_setcallreturns(fs
, &cc
->v
, LUA_MULTRET
);
463 luaK_codeABx(fs
, OP_SETLISTO
, cc
->t
->info
, cc
->na
-1);
466 if (cc
->v
.k
!= VVOID
)
467 luaK_exp2nextreg(fs
, &cc
->v
);
468 luaK_codeABx(fs
, OP_SETLIST
, cc
->t
->info
, cc
->na
-1);
470 fs
->freereg
= cc
->t
->info
+ 1; /* free registers */
474 static void listfield (LexState
*ls
, struct ConsControl
*cc
) {
476 luaX_checklimit(ls
, cc
->na
, MAXARG_Bx
, "items in a constructor");
482 static void constructor (LexState
*ls
, expdesc
*t
) {
483 /* constructor -> ?? */
484 FuncState
*fs
= ls
->fs
;
485 int line
= ls
->linenumber
;
486 int pc
= luaK_codeABC(fs
, OP_NEWTABLE
, 0, 0, 0);
487 struct ConsControl cc
;
488 cc
.na
= cc
.nh
= cc
.tostore
= 0;
490 init_exp(t
, VRELOCABLE
, pc
);
491 init_exp(&cc
.v
, VVOID
, 0); /* no value (yet) */
492 luaK_exp2nextreg(ls
->fs
, t
); /* fix it at stack top (for gc) */
495 lua_assert(cc
.v
.k
== VVOID
|| cc
.tostore
> 0);
496 testnext(ls
, ';'); /* compatibility only */
497 if (ls
->t
.token
== '}') break;
498 closelistfield(fs
, &cc
);
499 switch(ls
->t
.token
) {
500 case TK_NAME
: { /* may be listfields or recfields */
502 if (ls
->lookahead
.token
!= '=') /* expression? */
508 case '[': { /* constructor_item -> recfield */
512 default: { /* constructor_part -> listfield */
517 } while (testnext(ls
, ',') || testnext(ls
, ';'));
518 check_match(ls
, '}', '{', line
);
519 lastlistfield(fs
, &cc
);
520 SETARG_B(fs
->f
->code
[pc
], luaO_int2fb(cc
.na
)); /* set initial array size */
521 SETARG_C(fs
->f
->code
[pc
], luaO_log2(cc
.nh
)+1); /* set initial table size */
524 /* }====================================================================== */
528 static void parlist (LexState
*ls
) {
529 /* parlist -> [ param { `,' param } ] */
532 if (ls
->t
.token
!= ')') { /* is `parlist' not empty? */
534 switch (ls
->t
.token
) {
535 case TK_DOTS
: dots
= 1; next(ls
); break;
536 case TK_NAME
: new_localvar(ls
, str_checkname(ls
), nparams
++); break;
537 default: luaX_syntaxerror(ls
, "<name> or `...' expected");
539 } while (!dots
&& testnext(ls
, ','));
541 code_params(ls
, nparams
, dots
);
545 static void body (LexState
*ls
, expdesc
*e
, int needself
, int line
) {
546 /* body -> `(' parlist `)' chunk END */
548 open_func(ls
, &new_fs
);
549 new_fs
.f
->lineDefined
= line
;
552 create_local(ls
, "self");
556 check_match(ls
, TK_END
, TK_FUNCTION
, line
);
558 pushclosure(ls
, &new_fs
, e
);
562 static int explist1 (LexState
*ls
, expdesc
*v
) {
563 /* explist1 -> expr { `,' expr } */
564 int n
= 1; /* at least one expression */
566 while (testnext(ls
, ',')) {
567 luaK_exp2nextreg(ls
->fs
, v
);
575 static void funcargs (LexState
*ls
, expdesc
*f
) {
576 FuncState
*fs
= ls
->fs
;
579 int line
= ls
->linenumber
;
580 switch (ls
->t
.token
) {
581 case '(': { /* funcargs -> `(' [ explist1 ] `)' */
582 if (line
!= ls
->lastline
)
583 luaX_syntaxerror(ls
,"ambiguous syntax (function call x new statement)");
585 if (ls
->t
.token
== ')') /* arg list is empty? */
589 luaK_setcallreturns(fs
, &args
, LUA_MULTRET
);
591 check_match(ls
, ')', '(', line
);
594 case '{': { /* funcargs -> constructor */
595 constructor(ls
, &args
);
598 case TK_STRING
: { /* funcargs -> STRING */
599 codestring(ls
, &args
, ls
->t
.seminfo
.ts
);
600 next(ls
); /* must use `seminfo' before `next' */
604 luaX_syntaxerror(ls
, "function arguments expected");
608 lua_assert(f
->k
== VNONRELOC
);
609 base
= f
->info
; /* base register for call */
611 nparams
= LUA_MULTRET
; /* open call */
614 luaK_exp2nextreg(fs
, &args
); /* close last argument */
615 nparams
= fs
->freereg
- (base
+1);
617 init_exp(f
, VCALL
, luaK_codeABC(fs
, OP_CALL
, base
, nparams
+1, 2));
618 luaK_fixline(fs
, line
);
619 fs
->freereg
= base
+1; /* call remove function and arguments and leaves
620 (unless changed) one result */
627 ** {======================================================================
628 ** Expression parsing
629 ** =======================================================================
633 static void prefixexp (LexState
*ls
, expdesc
*v
) {
634 /* prefixexp -> NAME | '(' expr ')' */
635 switch (ls
->t
.token
) {
637 int line
= ls
->linenumber
;
640 check_match(ls
, ')', '(', line
);
641 luaK_dischargevars(ls
->fs
, v
);
648 #ifdef LUA_COMPATUPSYNTAX
649 case '%': { /* for compatibility only */
651 int line
= ls
->linenumber
;
652 next(ls
); /* skip `%' */
653 varname
= singlevar(ls
, v
, 1);
655 luaX_errorline(ls
, "global upvalues are obsolete",
656 getstr(varname
), line
);
661 luaX_syntaxerror(ls
, "unexpected symbol");
668 static void primaryexp (LexState
*ls
, expdesc
*v
) {
670 prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
671 FuncState
*fs
= ls
->fs
;
674 switch (ls
->t
.token
) {
675 case '.': { /* field */
679 case '[': { /* `[' exp1 `]' */
681 luaK_exp2anyreg(fs
, v
);
682 luaY_index(ls
, &key
);
683 luaK_indexed(fs
, v
, &key
);
686 case ':': { /* `:' NAME funcargs */
690 luaK_self(fs
, v
, &key
);
694 case '(': case TK_STRING
: case '{': { /* funcargs */
695 luaK_exp2nextreg(fs
, v
);
705 static void simpleexp (LexState
*ls
, expdesc
*v
) {
706 /* simpleexp -> NUMBER | STRING | NIL | constructor | FUNCTION body
708 switch (ls
->t
.token
) {
710 init_exp(v
, VK
, luaK_numberK(ls
->fs
, ls
->t
.seminfo
.r
));
711 next(ls
); /* must use `seminfo' before `next' */
715 codestring(ls
, v
, ls
->t
.seminfo
.ts
);
716 next(ls
); /* must use `seminfo' before `next' */
720 init_exp(v
, VNIL
, 0);
725 init_exp(v
, VTRUE
, 0);
730 init_exp(v
, VFALSE
, 0);
734 case '{': { /* constructor */
740 body(ls
, v
, 0, ls
->linenumber
);
751 static UnOpr
getunopr (int op
) {
753 case TK_NOT
: return OPR_NOT
;
754 case '-': return OPR_MINUS
;
755 default: return OPR_NOUNOPR
;
760 static BinOpr
getbinopr (int op
) {
762 case '+': return OPR_ADD
;
763 case '-': return OPR_SUB
;
764 case '*': return OPR_MULT
;
765 case '/': return OPR_DIV
;
766 case '^': return OPR_POW
;
767 case TK_CONCAT
: return OPR_CONCAT
;
768 case TK_NE
: return OPR_NE
;
769 case TK_EQ
: return OPR_EQ
;
770 case '<': return OPR_LT
;
771 case TK_LE
: return OPR_LE
;
772 case '>': return OPR_GT
;
773 case TK_GE
: return OPR_GE
;
774 case TK_AND
: return OPR_AND
;
775 case TK_OR
: return OPR_OR
;
776 default: return OPR_NOBINOPR
;
781 static const struct {
782 lu_byte left
; /* left priority for each binary operator */
783 lu_byte right
; /* right priority */
784 } priority
[] = { /* ORDER OPR */
785 {6, 6}, {6, 6}, {7, 7}, {7, 7}, /* arithmetic */
786 {10, 9}, {5, 4}, /* power and concat (right associative) */
787 {3, 3}, {3, 3}, /* equality */
788 {3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */
789 {2, 2}, {1, 1} /* logical (and/or) */
792 #define UNARY_PRIORITY 8 /* priority for unary operators */
796 ** subexpr -> (simplexep | unop subexpr) { binop subexpr }
797 ** where `binop' is any binary operator with a priority higher than `limit'
799 static BinOpr
subexpr (LexState
*ls
, expdesc
*v
, int limit
) {
803 uop
= getunopr(ls
->t
.token
);
804 if (uop
!= OPR_NOUNOPR
) {
806 subexpr(ls
, v
, UNARY_PRIORITY
);
807 luaK_prefix(ls
->fs
, uop
, v
);
809 else simpleexp(ls
, v
);
810 /* expand while operators have priorities higher than `limit' */
811 op
= getbinopr(ls
->t
.token
);
812 while (op
!= OPR_NOBINOPR
&& cast(int, priority
[op
].left
) > limit
) {
816 luaK_infix(ls
->fs
, op
, v
);
817 /* read sub-expression with higher priority */
818 nextop
= subexpr(ls
, &v2
, cast(int, priority
[op
].right
));
819 luaK_posfix(ls
->fs
, op
, v
, &v2
);
823 return op
; /* return first untreated operator */
827 static void expr (LexState
*ls
, expdesc
*v
) {
831 /* }==================================================================== */
836 ** {======================================================================
837 ** Rules for Statements
838 ** =======================================================================
842 static int block_follow (int token
) {
844 case TK_ELSE
: case TK_ELSEIF
: case TK_END
:
845 case TK_UNTIL
: case TK_EOS
:
852 static void block (LexState
*ls
) {
854 FuncState
*fs
= ls
->fs
;
856 enterblock(fs
, &bl
, 0);
858 lua_assert(bl
.breaklist
== NO_JUMP
);
864 ** structure to chain all variables in the left-hand side of an
868 struct LHS_assign
*prev
;
869 expdesc v
; /* variable (global, local, upvalue, or indexed) */
874 ** check whether, in an assignment to a local variable, the local variable
875 ** is needed in a previous assignment (to a table). If so, save original
876 ** local value in a safe place and use this safe copy in the previous
879 static void check_conflict (LexState
*ls
, struct LHS_assign
*lh
, expdesc
*v
) {
880 FuncState
*fs
= ls
->fs
;
881 int extra
= fs
->freereg
; /* eventual position to save local variable */
883 for (; lh
; lh
= lh
->prev
) {
884 if (lh
->v
.k
== VINDEXED
) {
885 if (lh
->v
.info
== v
->info
) { /* conflict? */
887 lh
->v
.info
= extra
; /* previous assignment will use safe copy */
889 if (lh
->v
.aux
== v
->info
) { /* conflict? */
891 lh
->v
.aux
= extra
; /* previous assignment will use safe copy */
896 luaK_codeABC(fs
, OP_MOVE
, fs
->freereg
, v
->info
, 0); /* make copy */
897 luaK_reserveregs(fs
, 1);
902 static void assignment (LexState
*ls
, struct LHS_assign
*lh
, int nvars
) {
904 check_condition(ls
, VLOCAL
<= lh
->v
.k
&& lh
->v
.k
<= VINDEXED
,
906 if (testnext(ls
, ',')) { /* assignment -> `,' primaryexp assignment */
907 struct LHS_assign nv
;
909 primaryexp(ls
, &nv
.v
);
910 if (nv
.v
.k
== VLOCAL
)
911 check_conflict(ls
, lh
, &nv
.v
);
912 assignment(ls
, &nv
, nvars
+1);
914 else { /* assignment -> `=' explist1 */
917 nexps
= explist1(ls
, &e
);
918 if (nexps
!= nvars
) {
919 adjust_assign(ls
, nvars
, nexps
, &e
);
921 ls
->fs
->freereg
-= nexps
- nvars
; /* remove extra values */
924 luaK_setcallreturns(ls
->fs
, &e
, 1); /* close last expression */
925 luaK_storevar(ls
->fs
, &lh
->v
, &e
);
926 return; /* avoid default */
929 init_exp(&e
, VNONRELOC
, ls
->fs
->freereg
-1); /* default assignment */
930 luaK_storevar(ls
->fs
, &lh
->v
, &e
);
934 static void cond (LexState
*ls
, expdesc
*v
) {
936 expr(ls
, v
); /* read condition */
937 if (v
->k
== VNIL
) v
->k
= VFALSE
; /* `falses' are all equal here */
938 luaK_goiftrue(ls
->fs
, v
);
939 luaK_patchtohere(ls
->fs
, v
->t
);
944 ** The while statement optimizes its code by coding the condition
945 ** after its body (and thus avoiding one jump in the loop).
949 ** maximum size of expressions for optimizing `while' code
952 #define MAXEXPWHILE 100
956 ** the call `luaK_goiffalse' may grow the size of an expression by
961 static void whilestat (LexState
*ls
, int line
) {
962 /* whilestat -> WHILE cond DO block END */
963 Instruction codeexp
[MAXEXPWHILE
+ EXTRAEXP
];
967 FuncState
*fs
= ls
->fs
;
968 int whileinit
, blockinit
, expinit
;
971 next(ls
); /* skip WHILE */
972 whileinit
= luaK_jump(fs
); /* jump to condition (which will be moved) */
973 expinit
= luaK_getlabel(fs
);
974 expr(ls
, &v
); /* parse condition */
975 if (v
.k
== VK
) v
.k
= VTRUE
; /* `trues' are all equal here */
976 lineexp
= ls
->linenumber
;
977 luaK_goiffalse(fs
, &v
);
978 luaK_concat(fs
, &v
.f
, fs
->jpc
);
980 sizeexp
= fs
->pc
- expinit
; /* size of expression code */
981 if (sizeexp
> MAXEXPWHILE
)
982 luaX_syntaxerror(ls
, "`while' condition too complex");
983 for (i
= 0; i
< sizeexp
; i
++) /* save `exp' code */
984 codeexp
[i
] = fs
->f
->code
[expinit
+ i
];
985 fs
->pc
= expinit
; /* remove `exp' code */
986 enterblock(fs
, &bl
, 1);
988 blockinit
= luaK_getlabel(fs
);
990 luaK_patchtohere(fs
, whileinit
); /* initial jump jumps to here */
991 /* move `exp' back to code */
992 if (v
.t
!= NO_JUMP
) v
.t
+= fs
->pc
- expinit
;
993 if (v
.f
!= NO_JUMP
) v
.f
+= fs
->pc
- expinit
;
994 for (i
=0; i
<sizeexp
; i
++)
995 luaK_code(fs
, codeexp
[i
], lineexp
);
996 check_match(ls
, TK_END
, TK_WHILE
, line
);
998 luaK_patchlist(fs
, v
.t
, blockinit
); /* true conditions go back to loop */
999 luaK_patchtohere(fs
, v
.f
); /* false conditions finish the loop */
1003 static void repeatstat (LexState
*ls
, int line
) {
1004 /* repeatstat -> REPEAT block UNTIL cond */
1005 FuncState
*fs
= ls
->fs
;
1006 int repeat_init
= luaK_getlabel(fs
);
1009 enterblock(fs
, &bl
, 1);
1012 check_match(ls
, TK_UNTIL
, TK_REPEAT
, line
);
1014 luaK_patchlist(fs
, v
.f
, repeat_init
);
1019 static int exp1 (LexState
*ls
) {
1024 luaK_exp2nextreg(ls
->fs
, &e
);
1029 static void forbody (LexState
*ls
, int base
, int line
, int nvars
, int isnum
) {
1031 FuncState
*fs
= ls
->fs
;
1033 adjustlocalvars(ls
, nvars
); /* scope for all variables */
1035 enterblock(fs
, &bl
, 1); /* loop block */
1036 prep
= luaK_getlabel(fs
);
1038 luaK_patchtohere(fs
, prep
-1);
1039 endfor
= (isnum
) ? luaK_codeAsBx(fs
, OP_FORLOOP
, base
, NO_JUMP
) :
1040 luaK_codeABC(fs
, OP_TFORLOOP
, base
, 0, nvars
- 3);
1041 luaK_fixline(fs
, line
); /* pretend that `OP_FOR' starts the loop */
1042 luaK_patchlist(fs
, (isnum
) ? endfor
: luaK_jump(fs
), prep
);
1047 static void fornum (LexState
*ls
, TString
*varname
, int line
) {
1048 /* fornum -> NAME = exp1,exp1[,exp1] DO body */
1049 FuncState
*fs
= ls
->fs
;
1050 int base
= fs
->freereg
;
1051 new_localvar(ls
, varname
, 0);
1052 new_localvarstr(ls
, "(for limit)", 1);
1053 new_localvarstr(ls
, "(for step)", 2);
1055 exp1(ls
); /* initial value */
1057 exp1(ls
); /* limit */
1058 if (testnext(ls
, ','))
1059 exp1(ls
); /* optional step */
1060 else { /* default step = 1 */
1061 luaK_codeABx(fs
, OP_LOADK
, fs
->freereg
, luaK_numberK(fs
, 1));
1062 luaK_reserveregs(fs
, 1);
1064 luaK_codeABC(fs
, OP_SUB
, fs
->freereg
- 3, fs
->freereg
- 3, fs
->freereg
- 1);
1066 forbody(ls
, base
, line
, 3, 1);
1070 static void forlist (LexState
*ls
, TString
*indexname
) {
1071 /* forlist -> NAME {,NAME} IN explist1 DO body */
1072 FuncState
*fs
= ls
->fs
;
1076 int base
= fs
->freereg
;
1077 new_localvarstr(ls
, "(for generator)", nvars
++);
1078 new_localvarstr(ls
, "(for state)", nvars
++);
1079 new_localvar(ls
, indexname
, nvars
++);
1080 while (testnext(ls
, ','))
1081 new_localvar(ls
, str_checkname(ls
), nvars
++);
1083 line
= ls
->linenumber
;
1084 adjust_assign(ls
, nvars
, explist1(ls
, &e
), &e
);
1085 luaK_checkstack(fs
, 3); /* extra space to call generator */
1086 luaK_codeAsBx(fs
, OP_TFORPREP
, base
, NO_JUMP
);
1087 forbody(ls
, base
, line
, nvars
, 0);
1091 static void forstat (LexState
*ls
, int line
) {
1092 /* forstat -> fornum | forlist */
1093 FuncState
*fs
= ls
->fs
;
1096 enterblock(fs
, &bl
, 0); /* block to control variable scope */
1097 next(ls
); /* skip `for' */
1098 varname
= str_checkname(ls
); /* first variable name */
1099 switch (ls
->t
.token
) {
1100 case '=': fornum(ls
, varname
, line
); break;
1101 case ',': case TK_IN
: forlist(ls
, varname
); break;
1102 default: luaX_syntaxerror(ls
, "`=' or `in' expected");
1104 check_match(ls
, TK_END
, TK_FOR
, line
);
1109 static void test_then_block (LexState
*ls
, expdesc
*v
) {
1110 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1111 next(ls
); /* skip IF or ELSEIF */
1114 block(ls
); /* `then' part */
1118 static void ifstat (LexState
*ls
, int line
) {
1119 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1120 FuncState
*fs
= ls
->fs
;
1122 int escapelist
= NO_JUMP
;
1123 test_then_block(ls
, &v
); /* IF cond THEN block */
1124 while (ls
->t
.token
== TK_ELSEIF
) {
1125 luaK_concat(fs
, &escapelist
, luaK_jump(fs
));
1126 luaK_patchtohere(fs
, v
.f
);
1127 test_then_block(ls
, &v
); /* ELSEIF cond THEN block */
1129 if (ls
->t
.token
== TK_ELSE
) {
1130 luaK_concat(fs
, &escapelist
, luaK_jump(fs
));
1131 luaK_patchtohere(fs
, v
.f
);
1132 next(ls
); /* skip ELSE (after patch, for correct line info) */
1133 block(ls
); /* `else' part */
1136 luaK_concat(fs
, &escapelist
, v
.f
);
1137 luaK_patchtohere(fs
, escapelist
);
1138 check_match(ls
, TK_END
, TK_IF
, line
);
1142 static void localfunc (LexState
*ls
) {
1144 FuncState
*fs
= ls
->fs
;
1145 new_localvar(ls
, str_checkname(ls
), 0);
1146 init_exp(&v
, VLOCAL
, fs
->freereg
);
1147 luaK_reserveregs(fs
, 1);
1148 adjustlocalvars(ls
, 1);
1149 body(ls
, &b
, 0, ls
->linenumber
);
1150 luaK_storevar(fs
, &v
, &b
);
1151 /* debug information will only see the variable after this point! */
1152 getlocvar(fs
, fs
->nactvar
- 1).startpc
= fs
->pc
;
1156 static void localstat (LexState
*ls
) {
1157 /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
1162 new_localvar(ls
, str_checkname(ls
), nvars
++);
1163 } while (testnext(ls
, ','));
1164 if (testnext(ls
, '='))
1165 nexps
= explist1(ls
, &e
);
1170 adjust_assign(ls
, nvars
, nexps
, &e
);
1171 adjustlocalvars(ls
, nvars
);
1175 static int funcname (LexState
*ls
, expdesc
*v
) {
1176 /* funcname -> NAME {field} [`:' NAME] */
1178 singlevar(ls
, v
, 1);
1179 while (ls
->t
.token
== '.')
1181 if (ls
->t
.token
== ':') {
1189 static void funcstat (LexState
*ls
, int line
) {
1190 /* funcstat -> FUNCTION funcname body */
1193 next(ls
); /* skip FUNCTION */
1194 needself
= funcname(ls
, &v
);
1195 body(ls
, &b
, needself
, line
);
1196 luaK_storevar(ls
->fs
, &v
, &b
);
1197 luaK_fixline(ls
->fs
, line
); /* definition `happens' in the first line */
1201 static void exprstat (LexState
*ls
) {
1202 /* stat -> func | assignment */
1203 FuncState
*fs
= ls
->fs
;
1204 struct LHS_assign v
;
1205 primaryexp(ls
, &v
.v
);
1206 if (v
.v
.k
== VCALL
) { /* stat -> func */
1207 luaK_setcallreturns(fs
, &v
.v
, 0); /* call statement uses no results */
1209 else { /* stat -> assignment */
1211 assignment(ls
, &v
, 1);
1216 static void retstat (LexState
*ls
) {
1217 /* stat -> RETURN explist */
1218 FuncState
*fs
= ls
->fs
;
1220 int first
, nret
; /* registers with returned values */
1221 next(ls
); /* skip RETURN */
1222 if (block_follow(ls
->t
.token
) || ls
->t
.token
== ';')
1223 first
= nret
= 0; /* return no values */
1225 nret
= explist1(ls
, &e
); /* optional return values */
1227 luaK_setcallreturns(fs
, &e
, LUA_MULTRET
);
1228 if (nret
== 1) { /* tail call? */
1229 SET_OPCODE(getcode(fs
,&e
), OP_TAILCALL
);
1230 lua_assert(GETARG_A(getcode(fs
,&e
)) == fs
->nactvar
);
1232 first
= fs
->nactvar
;
1233 nret
= LUA_MULTRET
; /* return all values */
1236 if (nret
== 1) /* only one single value? */
1237 first
= luaK_exp2anyreg(fs
, &e
);
1239 luaK_exp2nextreg(fs
, &e
); /* values must go to the `stack' */
1240 first
= fs
->nactvar
; /* return all `active' values */
1241 lua_assert(nret
== fs
->freereg
- first
);
1245 luaK_codeABC(fs
, OP_RETURN
, first
, nret
+1, 0);
1249 static void breakstat (LexState
*ls
) {
1250 /* stat -> BREAK [NAME] */
1251 FuncState
*fs
= ls
->fs
;
1252 BlockCnt
*bl
= fs
->bl
;
1254 next(ls
); /* skip BREAK */
1255 while (bl
&& !bl
->isbreakable
) {
1260 luaX_syntaxerror(ls
, "no loop to break");
1262 luaK_codeABC(fs
, OP_CLOSE
, bl
->nactvar
, 0, 0);
1263 luaK_concat(fs
, &bl
->breaklist
, luaK_jump(fs
));
1267 static int statement (LexState
*ls
) {
1268 int line
= ls
->linenumber
; /* may be needed for error messages */
1269 switch (ls
->t
.token
) {
1270 case TK_IF
: { /* stat -> ifstat */
1274 case TK_WHILE
: { /* stat -> whilestat */
1275 whilestat(ls
, line
);
1278 case TK_DO
: { /* stat -> DO block END */
1279 next(ls
); /* skip DO */
1281 check_match(ls
, TK_END
, TK_DO
, line
);
1284 case TK_FOR
: { /* stat -> forstat */
1288 case TK_REPEAT
: { /* stat -> repeatstat */
1289 repeatstat(ls
, line
);
1293 funcstat(ls
, line
); /* stat -> funcstat */
1296 case TK_LOCAL
: { /* stat -> localstat */
1297 next(ls
); /* skip LOCAL */
1298 if (testnext(ls
, TK_FUNCTION
)) /* local function? */
1304 case TK_RETURN
: { /* stat -> retstat */
1306 return 1; /* must be last statement */
1308 case TK_BREAK
: { /* stat -> breakstat */
1310 return 1; /* must be last statement */
1314 return 0; /* to avoid warnings */
1320 static void chunk (LexState
*ls
) {
1321 /* chunk -> { stat [`;'] } */
1324 while (!islast
&& !block_follow(ls
->t
.token
)) {
1325 islast
= statement(ls
);
1327 lua_assert(ls
->fs
->freereg
>= ls
->fs
->nactvar
);
1328 ls
->fs
->freereg
= ls
->fs
->nactvar
; /* free registers */
1333 /* }====================================================================== */