2 ** $Id: lparser.c,v 2.42.1.3 2007/12/28 15:32:23 roberto Exp $
4 ** See Copyright Notice in lua.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 */
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
) {
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
) {
90 static void check (LexState
*ls
, int c
) {
92 error_expected(ls
, c
);
95 static void checknext (LexState
*ls
, int c
) {
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
);
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
) {
121 ts
= ls
->t
.seminfo
.ts
;
127 static void init_exp (expdesc
*e
, expkind k
, int i
) {
128 e
->f
= e
->t
= NO_JUMP
;
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
;
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
) {
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
);
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
);
208 static int searchvar (FuncState
*fs
, TString
*n
) {
210 for (i
=fs
->nactvar
-1; i
>= 0; i
--) {
211 if (n
== getlocvar(fs
, i
).varname
)
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 */
231 int v
= searchvar(fs
, n
); /* look up at current level */
233 init_exp(var
, VLOCAL
, v
);
235 markupval(fs
, v
); /* local will be used as an upval */
238 else { /* not found at current level; try upper one */
239 if (singlevaraux(fs
->prev
, n
, var
, 0) == VGLOBAL
)
241 var
->u
.s
.info
= indexupvalue(fs
, n
, var
); /* else was LOCAL or UPVAL */
242 var
->k
= VUPVAL
; /* upvalue in this level */
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);
267 if (e
->k
!= VVOID
) luaK_exp2nextreg(fs
, e
); /* close last expression */
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
;
291 bl
->previous
= fs
->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
);
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
;
314 int oldsize
= f
->sizep
;
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
);
333 fs
->prev
= ls
->fs
; /* linked list of funcstates */
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
);
352 setptvalue2s(L
, L
->top
, f
);
357 static void close_func (LexState
*ls
) {
358 lua_State
*L
= ls
->L
;
359 FuncState
*fs
= ls
->fs
;
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
);
369 luaM_reallocvector(L
, f
->p
, f
->sizep
, fs
->np
, Proto
*);
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
);
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 */
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
);
403 /*============================================================*/
405 /*============================================================*/
408 static void field (LexState
*ls
, expdesc
*v
) {
409 /* field -> ['.' | ':'] NAME */
410 FuncState
*fs
= ls
->fs
;
412 luaK_exp2anyreg(fs
, v
);
413 luaX_next(ls
); /* skip the dot or colon */
415 luaK_indexed(fs
, v
, &key
);
419 static void yindex (LexState
*ls
, expdesc
*v
) {
420 /* index -> '[' expr ']' */
421 luaX_next(ls
); /* skip the '[' */
423 luaK_exp2val(ls
->fs
, v
);
429 ** {======================================================================
430 ** Rules for Constructors
431 ** =======================================================================
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
;
450 if (ls
->t
.token
== TK_NAME
) {
451 luaY_checklimit(fs
, cc
->nh
, MAX_INT
, "items in a constructor");
454 else /* ls->t.token == '[' */
458 rkkey
= luaK_exp2RK(fs
, &key
);
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
);
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) */
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
) {
493 luaY_checklimit(ls
->fs
, cc
->na
, MAX_INT
, "items in a constructor");
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;
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) */
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 */
518 if (ls
->lookahead
.token
!= '=') /* expression? */
524 case '[': { /* constructor_item -> recfield */
528 default: { /* constructor_part -> listfield */
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
;
550 if (ls
->t
.token
!= ')') { /* is `parlist' not empty? */
552 switch (ls
->t
.token
) {
553 case TK_NAME
: { /* param -> NAME */
554 new_localvar(ls
, str_checkname(ls
), nparams
++);
557 case TK_DOTS
: { /* param -> `...' */
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
;
564 f
->is_vararg
|= VARARG_ISVARARG
;
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 */
580 open_func(ls
, &new_fs
);
581 new_fs
.f
->linedefined
= line
;
584 new_localvarliteral(ls
, "self", 0);
585 adjustlocalvars(ls
, 1);
590 new_fs
.f
->lastlinedefined
= ls
->linenumber
;
591 check_match(ls
, TK_END
, TK_FUNCTION
, line
);
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 */
601 while (testnext(ls
, ',')) {
602 luaK_exp2nextreg(ls
->fs
, v
);
610 static void funcargs (LexState
*ls
, expdesc
*f
) {
611 FuncState
*fs
= ls
->fs
;
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)");
620 if (ls
->t
.token
== ')') /* arg list is empty? */
624 luaK_setmultret(fs
, &args
);
626 check_match(ls
, ')', '(', line
);
629 case '{': { /* funcargs -> constructor */
630 constructor(ls
, &args
);
633 case TK_STRING
: { /* funcargs -> STRING */
634 codestring(ls
, &args
, ls
->t
.seminfo
.ts
);
635 luaX_next(ls
); /* must use `seminfo' before `next' */
639 luaX_syntaxerror(ls
, "function arguments expected");
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 */
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
) {
672 int line
= ls
->linenumber
;
675 check_match(ls
, ')', '(', line
);
676 luaK_dischargevars(ls
->fs
, v
);
684 luaX_syntaxerror(ls
, "unexpected symbol");
691 static void primaryexp (LexState
*ls
, expdesc
*v
) {
693 prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
694 FuncState
*fs
= ls
->fs
;
697 switch (ls
->t
.token
) {
698 case '.': { /* field */
702 case '[': { /* `[' exp1 `]' */
704 luaK_exp2anyreg(fs
, v
);
706 luaK_indexed(fs
, v
, &key
);
709 case ':': { /* `:' NAME funcargs */
713 luaK_self(fs
, v
, &key
);
717 case '(': case TK_STRING
: case '{': { /* funcargs */
718 luaK_exp2nextreg(fs
, v
);
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
) {
733 init_exp(v
, VKNUM
, 0);
734 v
->u
.nval
= ls
->t
.seminfo
.r
;
738 codestring(ls
, v
, ls
->t
.seminfo
.ts
);
742 init_exp(v
, VNIL
, 0);
746 init_exp(v
, VTRUE
, 0);
750 init_exp(v
, VFALSE
, 0);
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));
761 case '{': { /* constructor */
767 body(ls
, v
, 0, ls
->linenumber
);
779 static UnOpr
getunopr (int 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
) {
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
) {
833 uop
= getunopr(ls
->t
.token
);
834 if (uop
!= OPR_NOUNOPR
) {
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
) {
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
);
853 return op
; /* return first untreated operator */
857 static void expr (LexState
*ls
, expdesc
*v
) {
861 /* }==================================================================== */
866 ** {======================================================================
867 ** Rules for Statements
868 ** =======================================================================
872 static int block_follow (int token
) {
874 case TK_ELSE
: case TK_ELSEIF
: case TK_END
:
875 case TK_UNTIL
: case TK_EOS
:
882 static void block (LexState
*ls
) {
884 FuncState
*fs
= ls
->fs
;
886 enterblock(fs
, &bl
, 0);
888 lua_assert(bl
.breaklist
== NO_JUMP
);
894 ** structure to chain all variables in the left-hand side of an
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
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 */
913 for (; lh
; lh
= lh
->prev
) {
914 if (lh
->v
.k
== VINDEXED
) {
915 if (lh
->v
.u
.s
.info
== v
->u
.s
.info
) { /* conflict? */
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? */
921 lh
->v
.u
.s
.aux
= extra
; /* previous assignment will use safe copy */
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
) {
934 check_condition(ls
, VLOCAL
<= lh
->v
.k
&& lh
->v
.k
<= VINDEXED
,
936 if (testnext(ls
, ',')) { /* assignment -> `,' primaryexp assignment */
937 struct LHS_assign nv
;
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 */
949 nexps
= explist1(ls
, &e
);
950 if (nexps
!= nvars
) {
951 adjust_assign(ls
, nvars
, nexps
, &e
);
953 ls
->fs
->freereg
-= nexps
- nvars
; /* remove extra values */
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
) {
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
);
976 static void breakstat (LexState
*ls
) {
977 FuncState
*fs
= ls
->fs
;
978 BlockCnt
*bl
= fs
->bl
;
980 while (bl
&& !bl
->isbreakable
) {
985 luaX_syntaxerror(ls
, "no loop to break");
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
;
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
);
1004 luaK_patchlist(fs
, luaK_jump(fs
), whileinit
);
1005 check_match(ls
, TK_END
, TK_WHILE
, line
);
1007 luaK_patchtohere(fs
, condexit
); /* false conditions finish the loop */
1011 static void repeatstat (LexState
*ls
, int line
) {
1012 /* repeatstat -> REPEAT block UNTIL cond */
1014 FuncState
*fs
= ls
->fs
;
1015 int repeat_init
= luaK_getlabel(fs
);
1017 enterblock(fs
, &bl1
, 1); /* loop block */
1018 enterblock(fs
, &bl2
, 0); /* scope block */
1019 luaX_next(ls
); /* skip REPEAT */
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
) {
1042 luaK_exp2nextreg(ls
->fs
, &e
);
1047 static void forbody (LexState
*ls
, int base
, int line
, int nvars
, int isnum
) {
1048 /* forbody -> DO block */
1050 FuncState
*fs
= ls
->fs
;
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
);
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);
1077 exp1(ls
); /* initial value */
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
;
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
;
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 */
1134 luaX_next(ls
); /* skip IF or ELSEIF */
1135 condexit
= cond(ls
);
1136 checknext(ls
, TK_THEN
);
1137 block(ls
); /* `then' part */
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
;
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 */
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
) {
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] */
1186 new_localvar(ls
, str_checkname(ls
), nvars
++);
1187 } while (testnext(ls
, ','));
1188 if (testnext(ls
, '='))
1189 nexps
= explist1(ls
, &e
);
1194 adjust_assign(ls
, nvars
, nexps
, &e
);
1195 adjustlocalvars(ls
, nvars
);
1199 static int funcname (LexState
*ls
, expdesc
*v
) {
1200 /* funcname -> NAME {field} [`:' NAME] */
1203 while (ls
->t
.token
== '.')
1205 if (ls
->t
.token
== ':') {
1213 static void funcstat (LexState
*ls
, int line
) {
1214 /* funcstat -> FUNCTION funcname body */
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 */
1234 assignment(ls
, &v
, 1);
1239 static void retstat (LexState
*ls
) {
1240 /* stat -> RETURN explist */
1241 FuncState
*fs
= ls
->fs
;
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 */
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 */
1259 if (nret
== 1) /* only one single value? */
1260 first
= luaK_exp2anyreg(fs
, &e
);
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 */
1279 case TK_WHILE
: { /* stat -> whilestat */
1280 whilestat(ls
, line
);
1283 case TK_DO
: { /* stat -> DO block END */
1284 luaX_next(ls
); /* skip DO */
1286 check_match(ls
, TK_END
, TK_DO
, line
);
1289 case TK_FOR
: { /* stat -> forstat */
1293 case TK_REPEAT
: { /* stat -> repeatstat */
1294 repeatstat(ls
, line
);
1298 funcstat(ls
, line
); /* stat -> funcstat */
1301 case TK_LOCAL
: { /* stat -> localstat */
1302 luaX_next(ls
); /* skip LOCAL */
1303 if (testnext(ls
, TK_FUNCTION
)) /* local function? */
1309 case TK_RETURN
: { /* stat -> retstat */
1311 return 1; /* must be last statement */
1313 case TK_BREAK
: { /* stat -> breakstat */
1314 luaX_next(ls
); /* skip BREAK */
1316 return 1; /* must be last statement */
1320 return 0; /* to avoid warnings */
1326 static void chunk (LexState
*ls
) {
1327 /* chunk -> { stat [`;'] } */
1330 while (!islast
&& !block_follow(ls
->t
.token
)) {
1331 islast
= statement(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 */
1340 /* }====================================================================== */