1 /* $NetBSD: lparser.c,v 1.1.1.2 2012/03/15 00:08:07 alnsn Exp $ */
4 ** $Id: lparser.c,v 1.1.1.2 2012/03/15 00:08:07 alnsn Exp $
6 ** See Copyright Notice in lua.h
32 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
34 #define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]])
36 #define luaY_checklimit(fs,v,l,m) if ((v)>(l)) errorlimit(fs,l,m)
40 ** nodes for block list (list of active blocks)
42 typedef struct BlockCnt
{
43 struct BlockCnt
*previous
; /* chain */
44 int breaklist
; /* list of jumps out of this loop */
45 lu_byte nactvar
; /* # active locals outside the breakable structure */
46 lu_byte upval
; /* true if some variable in the block is an upvalue */
47 lu_byte isbreakable
; /* true if `block' is a loop */
53 ** prototypes for recursive non-terminal functions
55 static void chunk (LexState
*ls
);
56 static void expr (LexState
*ls
, expdesc
*v
);
59 static void anchor_token (LexState
*ls
) {
60 if (ls
->t
.token
== TK_NAME
|| ls
->t
.token
== TK_STRING
) {
61 TString
*ts
= ls
->t
.seminfo
.ts
;
62 luaX_newstring(ls
, getstr(ts
), ts
->tsv
.len
);
67 static void error_expected (LexState
*ls
, int token
) {
69 luaO_pushfstring(ls
->L
, LUA_QS
" expected", luaX_token2str(ls
, token
)));
73 static void errorlimit (FuncState
*fs
, int limit
, const char *what
) {
74 const char *msg
= (fs
->f
->linedefined
== 0) ?
75 luaO_pushfstring(fs
->L
, "main function has more than %d %s", limit
, what
) :
76 luaO_pushfstring(fs
->L
, "function at line %d has more than %d %s",
77 fs
->f
->linedefined
, limit
, what
);
78 luaX_lexerror(fs
->ls
, msg
, 0);
82 static int testnext (LexState
*ls
, int c
) {
83 if (ls
->t
.token
== c
) {
91 static void check (LexState
*ls
, int c
) {
93 error_expected(ls
, c
);
96 static void checknext (LexState
*ls
, int c
) {
102 #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
106 static void check_match (LexState
*ls
, int what
, int who
, int where
) {
107 if (!testnext(ls
, what
)) {
108 if (where
== ls
->linenumber
)
109 error_expected(ls
, what
);
111 luaX_syntaxerror(ls
, luaO_pushfstring(ls
->L
,
112 LUA_QS
" expected (to close " LUA_QS
" at line %d)",
113 luaX_token2str(ls
, what
), luaX_token2str(ls
, who
), where
));
119 static TString
*str_checkname (LexState
*ls
) {
122 ts
= ls
->t
.seminfo
.ts
;
128 static void init_exp (expdesc
*e
, expkind k
, int i
) {
129 e
->f
= e
->t
= NO_JUMP
;
135 static void codestring (LexState
*ls
, expdesc
*e
, TString
*s
) {
136 init_exp(e
, VK
, luaK_stringK(ls
->fs
, s
));
140 static void checkname(LexState
*ls
, expdesc
*e
) {
141 codestring(ls
, e
, str_checkname(ls
));
145 static int registerlocalvar (LexState
*ls
, TString
*varname
) {
146 FuncState
*fs
= ls
->fs
;
148 int oldsize
= f
->sizelocvars
;
149 luaM_growvector(ls
->L
, f
->locvars
, fs
->nlocvars
, f
->sizelocvars
,
150 LocVar
, SHRT_MAX
, "too many local variables");
151 while (oldsize
< f
->sizelocvars
) f
->locvars
[oldsize
++].varname
= NULL
;
152 f
->locvars
[fs
->nlocvars
].varname
= varname
;
153 luaC_objbarrier(ls
->L
, f
, varname
);
154 return fs
->nlocvars
++;
158 #define new_localvarliteral(ls,v,n) \
159 new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n)
162 static void new_localvar (LexState
*ls
, TString
*name
, int n
) {
163 FuncState
*fs
= ls
->fs
;
164 luaY_checklimit(fs
, fs
->nactvar
+n
+1, LUAI_MAXVARS
, "local variables");
165 fs
->actvar
[fs
->nactvar
+n
] = cast(unsigned short, registerlocalvar(ls
, name
));
169 static void adjustlocalvars (LexState
*ls
, int nvars
) {
170 FuncState
*fs
= ls
->fs
;
171 fs
->nactvar
= cast_byte(fs
->nactvar
+ nvars
);
172 for (; nvars
; nvars
--) {
173 getlocvar(fs
, fs
->nactvar
- nvars
).startpc
= fs
->pc
;
178 static void removevars (LexState
*ls
, int tolevel
) {
179 FuncState
*fs
= ls
->fs
;
180 while (fs
->nactvar
> tolevel
)
181 getlocvar(fs
, --fs
->nactvar
).endpc
= fs
->pc
;
185 static int indexupvalue (FuncState
*fs
, TString
*name
, expdesc
*v
) {
188 int oldsize
= f
->sizeupvalues
;
189 for (i
=0; i
<f
->nups
; i
++) {
190 if (fs
->upvalues
[i
].k
== v
->k
&& fs
->upvalues
[i
].info
== v
->u
.s
.info
) {
191 lua_assert(f
->upvalues
[i
] == name
);
196 luaY_checklimit(fs
, f
->nups
+ 1, LUAI_MAXUPVALUES
, "upvalues");
197 luaM_growvector(fs
->L
, f
->upvalues
, f
->nups
, f
->sizeupvalues
,
198 TString
*, MAX_INT
, "");
199 while (oldsize
< f
->sizeupvalues
) f
->upvalues
[oldsize
++] = NULL
;
200 f
->upvalues
[f
->nups
] = name
;
201 luaC_objbarrier(fs
->L
, f
, name
);
202 lua_assert(v
->k
== VLOCAL
|| v
->k
== VUPVAL
);
203 fs
->upvalues
[f
->nups
].k
= cast_byte(v
->k
);
204 fs
->upvalues
[f
->nups
].info
= cast_byte(v
->u
.s
.info
);
209 static int searchvar (FuncState
*fs
, TString
*n
) {
211 for (i
=fs
->nactvar
-1; i
>= 0; i
--) {
212 if (n
== getlocvar(fs
, i
).varname
)
215 return -1; /* not found */
219 static void markupval (FuncState
*fs
, int level
) {
220 BlockCnt
*bl
= fs
->bl
;
221 while (bl
&& bl
->nactvar
> level
) bl
= bl
->previous
;
222 if (bl
) bl
->upval
= 1;
226 static int singlevaraux (FuncState
*fs
, TString
*n
, expdesc
*var
, int base
) {
227 if (fs
== NULL
) { /* no more levels? */
228 init_exp(var
, VGLOBAL
, NO_REG
); /* default is global variable */
232 int v
= searchvar(fs
, n
); /* look up at current level */
234 init_exp(var
, VLOCAL
, v
);
236 markupval(fs
, v
); /* local will be used as an upval */
239 else { /* not found at current level; try upper one */
240 if (singlevaraux(fs
->prev
, n
, var
, 0) == VGLOBAL
)
242 var
->u
.s
.info
= indexupvalue(fs
, n
, var
); /* else was LOCAL or UPVAL */
243 var
->k
= VUPVAL
; /* upvalue in this level */
250 static void singlevar (LexState
*ls
, expdesc
*var
) {
251 TString
*varname
= str_checkname(ls
);
252 FuncState
*fs
= ls
->fs
;
253 if (singlevaraux(fs
, varname
, var
, 1) == VGLOBAL
)
254 var
->u
.s
.info
= luaK_stringK(fs
, varname
); /* info points to global name */
258 static void adjust_assign (LexState
*ls
, int nvars
, int nexps
, expdesc
*e
) {
259 FuncState
*fs
= ls
->fs
;
260 int extra
= nvars
- nexps
;
261 if (hasmultret(e
->k
)) {
262 extra
++; /* includes call itself */
263 if (extra
< 0) extra
= 0;
264 luaK_setreturns(fs
, e
, extra
); /* last exp. provides the difference */
265 if (extra
> 1) luaK_reserveregs(fs
, extra
-1);
268 if (e
->k
!= VVOID
) luaK_exp2nextreg(fs
, e
); /* close last expression */
270 int reg
= fs
->freereg
;
271 luaK_reserveregs(fs
, extra
);
272 luaK_nil(fs
, reg
, extra
);
278 static void enterlevel (LexState
*ls
) {
279 if (++ls
->L
->nCcalls
> LUAI_MAXCCALLS
)
280 luaX_lexerror(ls
, "chunk has too many syntax levels", 0);
284 #define leavelevel(ls) ((ls)->L->nCcalls--)
287 static void enterblock (FuncState
*fs
, BlockCnt
*bl
, lu_byte isbreakable
) {
288 bl
->breaklist
= NO_JUMP
;
289 bl
->isbreakable
= isbreakable
;
290 bl
->nactvar
= fs
->nactvar
;
292 bl
->previous
= fs
->bl
;
294 lua_assert(fs
->freereg
== fs
->nactvar
);
298 static void leaveblock (FuncState
*fs
) {
299 BlockCnt
*bl
= fs
->bl
;
300 fs
->bl
= bl
->previous
;
301 removevars(fs
->ls
, bl
->nactvar
);
303 luaK_codeABC(fs
, OP_CLOSE
, bl
->nactvar
, 0, 0);
304 /* a block either controls scope or breaks (never both) */
305 lua_assert(!bl
->isbreakable
|| !bl
->upval
);
306 lua_assert(bl
->nactvar
== fs
->nactvar
);
307 fs
->freereg
= fs
->nactvar
; /* free registers */
308 luaK_patchtohere(fs
, bl
->breaklist
);
312 static void pushclosure (LexState
*ls
, FuncState
*func
, expdesc
*v
) {
313 FuncState
*fs
= ls
->fs
;
315 int oldsize
= f
->sizep
;
317 luaM_growvector(ls
->L
, f
->p
, fs
->np
, f
->sizep
, Proto
*,
318 MAXARG_Bx
, "constant table overflow");
319 while (oldsize
< f
->sizep
) f
->p
[oldsize
++] = NULL
;
320 f
->p
[fs
->np
++] = func
->f
;
321 luaC_objbarrier(ls
->L
, f
, func
->f
);
322 init_exp(v
, VRELOCABLE
, luaK_codeABx(fs
, OP_CLOSURE
, 0, fs
->np
-1));
323 for (i
=0; i
<func
->f
->nups
; i
++) {
324 OpCode o
= (func
->upvalues
[i
].k
== VLOCAL
) ? OP_MOVE
: OP_GETUPVAL
;
325 luaK_codeABC(fs
, o
, 0, func
->upvalues
[i
].info
, 0);
330 static void open_func (LexState
*ls
, FuncState
*fs
) {
331 lua_State
*L
= ls
->L
;
332 Proto
*f
= luaF_newproto(L
);
334 fs
->prev
= ls
->fs
; /* linked list of funcstates */
347 f
->source
= ls
->source
;
348 f
->maxstacksize
= 2; /* registers 0/1 are always valid */
349 fs
->h
= luaH_new(L
, 0, 0);
350 /* anchor table of constants and prototype (to avoid being collected) */
351 sethvalue2s(L
, L
->top
, fs
->h
);
353 setptvalue2s(L
, L
->top
, f
);
358 static void close_func (LexState
*ls
) {
359 lua_State
*L
= ls
->L
;
360 FuncState
*fs
= ls
->fs
;
363 luaK_ret(fs
, 0, 0); /* final return */
364 luaM_reallocvector(L
, f
->code
, f
->sizecode
, fs
->pc
, Instruction
);
365 f
->sizecode
= fs
->pc
;
366 luaM_reallocvector(L
, f
->lineinfo
, f
->sizelineinfo
, fs
->pc
, int);
367 f
->sizelineinfo
= fs
->pc
;
368 luaM_reallocvector(L
, f
->k
, f
->sizek
, fs
->nk
, TValue
);
370 luaM_reallocvector(L
, f
->p
, f
->sizep
, fs
->np
, Proto
*);
372 luaM_reallocvector(L
, f
->locvars
, f
->sizelocvars
, fs
->nlocvars
, LocVar
);
373 f
->sizelocvars
= fs
->nlocvars
;
374 luaM_reallocvector(L
, f
->upvalues
, f
->sizeupvalues
, f
->nups
, TString
*);
375 f
->sizeupvalues
= f
->nups
;
376 lua_assert(luaG_checkcode(f
));
377 lua_assert(fs
->bl
== NULL
);
379 /* last token read was anchored in defunct function; must reanchor it */
380 if (fs
) anchor_token(ls
);
381 L
->top
-= 2; /* remove table and prototype from the stack */
385 Proto
*luaY_parser (lua_State
*L
, ZIO
*z
, Mbuffer
*buff
, const char *name
) {
386 struct LexState lexstate
;
387 struct FuncState funcstate
;
388 lexstate
.buff
= buff
;
389 luaX_setinput(L
, &lexstate
, z
, luaS_new(L
, name
));
390 open_func(&lexstate
, &funcstate
);
391 funcstate
.f
->is_vararg
= VARARG_ISVARARG
; /* main func. is always vararg */
392 luaX_next(&lexstate
); /* read first token */
394 check(&lexstate
, TK_EOS
);
395 close_func(&lexstate
);
396 lua_assert(funcstate
.prev
== NULL
);
397 lua_assert(funcstate
.f
->nups
== 0);
398 lua_assert(lexstate
.fs
== NULL
);
404 /*============================================================*/
406 /*============================================================*/
409 static void field (LexState
*ls
, expdesc
*v
) {
410 /* field -> ['.' | ':'] NAME */
411 FuncState
*fs
= ls
->fs
;
413 luaK_exp2anyreg(fs
, v
);
414 luaX_next(ls
); /* skip the dot or colon */
416 luaK_indexed(fs
, v
, &key
);
420 static void yindex (LexState
*ls
, expdesc
*v
) {
421 /* index -> '[' expr ']' */
422 luaX_next(ls
); /* skip the '[' */
424 luaK_exp2val(ls
->fs
, v
);
430 ** {======================================================================
431 ** Rules for Constructors
432 ** =======================================================================
437 expdesc v
; /* last list item read */
438 expdesc
*t
; /* table descriptor */
439 int nh
; /* total number of `record' elements */
440 int na
; /* total number of array elements */
441 int tostore
; /* number of array elements pending to be stored */
445 static void recfield (LexState
*ls
, struct ConsControl
*cc
) {
446 /* recfield -> (NAME | `['exp1`]') = exp1 */
447 FuncState
*fs
= ls
->fs
;
448 int reg
= ls
->fs
->freereg
;
451 if (ls
->t
.token
== TK_NAME
) {
452 luaY_checklimit(fs
, cc
->nh
, MAX_INT
, "items in a constructor");
455 else /* ls->t.token == '[' */
459 rkkey
= luaK_exp2RK(fs
, &key
);
461 luaK_codeABC(fs
, OP_SETTABLE
, cc
->t
->u
.s
.info
, rkkey
, luaK_exp2RK(fs
, &val
));
462 fs
->freereg
= reg
; /* free registers */
466 static void closelistfield (FuncState
*fs
, struct ConsControl
*cc
) {
467 if (cc
->v
.k
== VVOID
) return; /* there is no list item */
468 luaK_exp2nextreg(fs
, &cc
->v
);
470 if (cc
->tostore
== LFIELDS_PER_FLUSH
) {
471 luaK_setlist(fs
, cc
->t
->u
.s
.info
, cc
->na
, cc
->tostore
); /* flush */
472 cc
->tostore
= 0; /* no more items pending */
477 static void lastlistfield (FuncState
*fs
, struct ConsControl
*cc
) {
478 if (cc
->tostore
== 0) return;
479 if (hasmultret(cc
->v
.k
)) {
480 luaK_setmultret(fs
, &cc
->v
);
481 luaK_setlist(fs
, cc
->t
->u
.s
.info
, cc
->na
, LUA_MULTRET
);
482 cc
->na
--; /* do not count last expression (unknown number of elements) */
485 if (cc
->v
.k
!= VVOID
)
486 luaK_exp2nextreg(fs
, &cc
->v
);
487 luaK_setlist(fs
, cc
->t
->u
.s
.info
, cc
->na
, cc
->tostore
);
492 static void listfield (LexState
*ls
, struct ConsControl
*cc
) {
494 luaY_checklimit(ls
->fs
, cc
->na
, MAX_INT
, "items in a constructor");
500 static void constructor (LexState
*ls
, expdesc
*t
) {
501 /* constructor -> ?? */
502 FuncState
*fs
= ls
->fs
;
503 int line
= ls
->linenumber
;
504 int pc
= luaK_codeABC(fs
, OP_NEWTABLE
, 0, 0, 0);
505 struct ConsControl cc
;
506 cc
.na
= cc
.nh
= cc
.tostore
= 0;
508 init_exp(t
, VRELOCABLE
, pc
);
509 init_exp(&cc
.v
, VVOID
, 0); /* no value (yet) */
510 luaK_exp2nextreg(ls
->fs
, t
); /* fix it at stack top (for gc) */
513 lua_assert(cc
.v
.k
== VVOID
|| cc
.tostore
> 0);
514 if (ls
->t
.token
== '}') break;
515 closelistfield(fs
, &cc
);
516 switch(ls
->t
.token
) {
517 case TK_NAME
: { /* may be listfields or recfields */
519 if (ls
->lookahead
.token
!= '=') /* expression? */
525 case '[': { /* constructor_item -> recfield */
529 default: { /* constructor_part -> listfield */
534 } while (testnext(ls
, ',') || testnext(ls
, ';'));
535 check_match(ls
, '}', '{', line
);
536 lastlistfield(fs
, &cc
);
537 SETARG_B(fs
->f
->code
[pc
], luaO_int2fb(cc
.na
)); /* set initial array size */
538 SETARG_C(fs
->f
->code
[pc
], luaO_int2fb(cc
.nh
)); /* set initial table size */
541 /* }====================================================================== */
545 static void parlist (LexState
*ls
) {
546 /* parlist -> [ param { `,' param } ] */
547 FuncState
*fs
= ls
->fs
;
551 if (ls
->t
.token
!= ')') { /* is `parlist' not empty? */
553 switch (ls
->t
.token
) {
554 case TK_NAME
: { /* param -> NAME */
555 new_localvar(ls
, str_checkname(ls
), nparams
++);
558 case TK_DOTS
: { /* param -> `...' */
560 #if defined(LUA_COMPAT_VARARG)
561 /* use `arg' as default name */
562 new_localvarliteral(ls
, "arg", nparams
++);
563 f
->is_vararg
= VARARG_HASARG
| VARARG_NEEDSARG
;
565 f
->is_vararg
|= VARARG_ISVARARG
;
568 default: luaX_syntaxerror(ls
, "<name> or " LUA_QL("...") " expected");
570 } while (!f
->is_vararg
&& testnext(ls
, ','));
572 adjustlocalvars(ls
, nparams
);
573 f
->numparams
= cast_byte(fs
->nactvar
- (f
->is_vararg
& VARARG_HASARG
));
574 luaK_reserveregs(fs
, fs
->nactvar
); /* reserve register for parameters */
578 static void body (LexState
*ls
, expdesc
*e
, int needself
, int line
) {
579 /* body -> `(' parlist `)' chunk END */
581 open_func(ls
, &new_fs
);
582 new_fs
.f
->linedefined
= line
;
585 new_localvarliteral(ls
, "self", 0);
586 adjustlocalvars(ls
, 1);
591 new_fs
.f
->lastlinedefined
= ls
->linenumber
;
592 check_match(ls
, TK_END
, TK_FUNCTION
, line
);
594 pushclosure(ls
, &new_fs
, e
);
598 static int explist1 (LexState
*ls
, expdesc
*v
) {
599 /* explist1 -> expr { `,' expr } */
600 int n
= 1; /* at least one expression */
602 while (testnext(ls
, ',')) {
603 luaK_exp2nextreg(ls
->fs
, v
);
611 static void funcargs (LexState
*ls
, expdesc
*f
) {
612 FuncState
*fs
= ls
->fs
;
615 int line
= ls
->linenumber
;
616 switch (ls
->t
.token
) {
617 case '(': { /* funcargs -> `(' [ explist1 ] `)' */
618 if (line
!= ls
->lastline
)
619 luaX_syntaxerror(ls
,"ambiguous syntax (function call x new statement)");
621 if (ls
->t
.token
== ')') /* arg list is empty? */
625 luaK_setmultret(fs
, &args
);
627 check_match(ls
, ')', '(', line
);
630 case '{': { /* funcargs -> constructor */
631 constructor(ls
, &args
);
634 case TK_STRING
: { /* funcargs -> STRING */
635 codestring(ls
, &args
, ls
->t
.seminfo
.ts
);
636 luaX_next(ls
); /* must use `seminfo' before `next' */
640 luaX_syntaxerror(ls
, "function arguments expected");
644 lua_assert(f
->k
== VNONRELOC
);
645 base
= f
->u
.s
.info
; /* base register for call */
646 if (hasmultret(args
.k
))
647 nparams
= LUA_MULTRET
; /* open call */
650 luaK_exp2nextreg(fs
, &args
); /* close last argument */
651 nparams
= fs
->freereg
- (base
+1);
653 init_exp(f
, VCALL
, luaK_codeABC(fs
, OP_CALL
, base
, nparams
+1, 2));
654 luaK_fixline(fs
, line
);
655 fs
->freereg
= base
+1; /* call remove function and arguments and leaves
656 (unless changed) one result */
663 ** {======================================================================
664 ** Expression parsing
665 ** =======================================================================
669 static void prefixexp (LexState
*ls
, expdesc
*v
) {
670 /* prefixexp -> NAME | '(' expr ')' */
671 switch (ls
->t
.token
) {
673 int line
= ls
->linenumber
;
676 check_match(ls
, ')', '(', line
);
677 luaK_dischargevars(ls
->fs
, v
);
685 luaX_syntaxerror(ls
, "unexpected symbol");
692 static void primaryexp (LexState
*ls
, expdesc
*v
) {
694 prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
695 FuncState
*fs
= ls
->fs
;
698 switch (ls
->t
.token
) {
699 case '.': { /* field */
703 case '[': { /* `[' exp1 `]' */
705 luaK_exp2anyreg(fs
, v
);
707 luaK_indexed(fs
, v
, &key
);
710 case ':': { /* `:' NAME funcargs */
714 luaK_self(fs
, v
, &key
);
718 case '(': case TK_STRING
: case '{': { /* funcargs */
719 luaK_exp2nextreg(fs
, v
);
729 static void simpleexp (LexState
*ls
, expdesc
*v
) {
730 /* simpleexp -> NUMBER | STRING | NIL | true | false | ... |
731 constructor | FUNCTION body | primaryexp */
732 switch (ls
->t
.token
) {
734 init_exp(v
, VKNUM
, 0);
735 v
->u
.nval
= ls
->t
.seminfo
.r
;
739 codestring(ls
, v
, ls
->t
.seminfo
.ts
);
743 init_exp(v
, VNIL
, 0);
747 init_exp(v
, VTRUE
, 0);
751 init_exp(v
, VFALSE
, 0);
754 case TK_DOTS
: { /* vararg */
755 FuncState
*fs
= ls
->fs
;
756 check_condition(ls
, fs
->f
->is_vararg
,
757 "cannot use " LUA_QL("...") " outside a vararg function");
758 fs
->f
->is_vararg
&= ~VARARG_NEEDSARG
; /* don't need 'arg' */
759 init_exp(v
, VVARARG
, luaK_codeABC(fs
, OP_VARARG
, 0, 1, 0));
762 case '{': { /* constructor */
768 body(ls
, v
, 0, ls
->linenumber
);
780 static UnOpr
getunopr (int op
) {
782 case TK_NOT
: return OPR_NOT
;
783 case '-': return OPR_MINUS
;
784 case '#': return OPR_LEN
;
785 default: return OPR_NOUNOPR
;
790 static BinOpr
getbinopr (int op
) {
792 case '+': return OPR_ADD
;
793 case '-': return OPR_SUB
;
794 case '*': return OPR_MUL
;
795 case '/': return OPR_DIV
;
796 case '%': return OPR_MOD
;
797 case '^': return OPR_POW
;
798 case TK_CONCAT
: return OPR_CONCAT
;
799 case TK_NE
: return OPR_NE
;
800 case TK_EQ
: return OPR_EQ
;
801 case '<': return OPR_LT
;
802 case TK_LE
: return OPR_LE
;
803 case '>': return OPR_GT
;
804 case TK_GE
: return OPR_GE
;
805 case TK_AND
: return OPR_AND
;
806 case TK_OR
: return OPR_OR
;
807 default: return OPR_NOBINOPR
;
812 static const struct {
813 lu_byte left
; /* left priority for each binary operator */
814 lu_byte right
; /* right priority */
815 } priority
[] = { /* ORDER OPR */
816 {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `/' `%' */
817 {10, 9}, {5, 4}, /* power and concat (right associative) */
818 {3, 3}, {3, 3}, /* equality and inequality */
819 {3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */
820 {2, 2}, {1, 1} /* logical (and/or) */
823 #define UNARY_PRIORITY 8 /* priority for unary operators */
827 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
828 ** where `binop' is any binary operator with a priority higher than `limit'
830 static BinOpr
subexpr (LexState
*ls
, expdesc
*v
, unsigned int limit
) {
834 uop
= getunopr(ls
->t
.token
);
835 if (uop
!= OPR_NOUNOPR
) {
837 subexpr(ls
, v
, UNARY_PRIORITY
);
838 luaK_prefix(ls
->fs
, uop
, v
);
840 else simpleexp(ls
, v
);
841 /* expand while operators have priorities higher than `limit' */
842 op
= getbinopr(ls
->t
.token
);
843 while (op
!= OPR_NOBINOPR
&& priority
[op
].left
> limit
) {
847 luaK_infix(ls
->fs
, op
, v
);
848 /* read sub-expression with higher priority */
849 nextop
= subexpr(ls
, &v2
, priority
[op
].right
);
850 luaK_posfix(ls
->fs
, op
, v
, &v2
);
854 return op
; /* return first untreated operator */
858 static void expr (LexState
*ls
, expdesc
*v
) {
862 /* }==================================================================== */
867 ** {======================================================================
868 ** Rules for Statements
869 ** =======================================================================
873 static int block_follow (int token
) {
875 case TK_ELSE
: case TK_ELSEIF
: case TK_END
:
876 case TK_UNTIL
: case TK_EOS
:
883 static void block (LexState
*ls
) {
885 FuncState
*fs
= ls
->fs
;
887 enterblock(fs
, &bl
, 0);
889 lua_assert(bl
.breaklist
== NO_JUMP
);
895 ** structure to chain all variables in the left-hand side of an
899 struct LHS_assign
*prev
;
900 expdesc v
; /* variable (global, local, upvalue, or indexed) */
905 ** check whether, in an assignment to a local variable, the local variable
906 ** is needed in a previous assignment (to a table). If so, save original
907 ** local value in a safe place and use this safe copy in the previous
910 static void check_conflict (LexState
*ls
, struct LHS_assign
*lh
, expdesc
*v
) {
911 FuncState
*fs
= ls
->fs
;
912 int extra
= fs
->freereg
; /* eventual position to save local variable */
914 for (; lh
; lh
= lh
->prev
) {
915 if (lh
->v
.k
== VINDEXED
) {
916 if (lh
->v
.u
.s
.info
== v
->u
.s
.info
) { /* conflict? */
918 lh
->v
.u
.s
.info
= extra
; /* previous assignment will use safe copy */
920 if (lh
->v
.u
.s
.aux
== v
->u
.s
.info
) { /* conflict? */
922 lh
->v
.u
.s
.aux
= extra
; /* previous assignment will use safe copy */
927 luaK_codeABC(fs
, OP_MOVE
, fs
->freereg
, v
->u
.s
.info
, 0); /* make copy */
928 luaK_reserveregs(fs
, 1);
933 static void assignment (LexState
*ls
, struct LHS_assign
*lh
, int nvars
) {
935 check_condition(ls
, VLOCAL
<= lh
->v
.k
&& lh
->v
.k
<= VINDEXED
,
937 if (testnext(ls
, ',')) { /* assignment -> `,' primaryexp assignment */
938 struct LHS_assign nv
;
940 primaryexp(ls
, &nv
.v
);
941 if (nv
.v
.k
== VLOCAL
)
942 check_conflict(ls
, lh
, &nv
.v
);
943 luaY_checklimit(ls
->fs
, nvars
, LUAI_MAXCCALLS
- ls
->L
->nCcalls
,
944 "variables in assignment");
945 assignment(ls
, &nv
, nvars
+1);
947 else { /* assignment -> `=' explist1 */
950 nexps
= explist1(ls
, &e
);
951 if (nexps
!= nvars
) {
952 adjust_assign(ls
, nvars
, nexps
, &e
);
954 ls
->fs
->freereg
-= nexps
- nvars
; /* remove extra values */
957 luaK_setoneret(ls
->fs
, &e
); /* close last expression */
958 luaK_storevar(ls
->fs
, &lh
->v
, &e
);
959 return; /* avoid default */
962 init_exp(&e
, VNONRELOC
, ls
->fs
->freereg
-1); /* default assignment */
963 luaK_storevar(ls
->fs
, &lh
->v
, &e
);
967 static int cond (LexState
*ls
) {
970 expr(ls
, &v
); /* read condition */
971 if (v
.k
== VNIL
) v
.k
= VFALSE
; /* `falses' are all equal here */
972 luaK_goiftrue(ls
->fs
, &v
);
977 static void breakstat (LexState
*ls
) {
978 FuncState
*fs
= ls
->fs
;
979 BlockCnt
*bl
= fs
->bl
;
981 while (bl
&& !bl
->isbreakable
) {
986 luaX_syntaxerror(ls
, "no loop to break");
988 luaK_codeABC(fs
, OP_CLOSE
, bl
->nactvar
, 0, 0);
989 luaK_concat(fs
, &bl
->breaklist
, luaK_jump(fs
));
993 static void whilestat (LexState
*ls
, int line
) {
994 /* whilestat -> WHILE cond DO block END */
995 FuncState
*fs
= ls
->fs
;
999 luaX_next(ls
); /* skip WHILE */
1000 whileinit
= luaK_getlabel(fs
);
1001 condexit
= cond(ls
);
1002 enterblock(fs
, &bl
, 1);
1003 checknext(ls
, TK_DO
);
1005 luaK_patchlist(fs
, luaK_jump(fs
), whileinit
);
1006 check_match(ls
, TK_END
, TK_WHILE
, line
);
1008 luaK_patchtohere(fs
, condexit
); /* false conditions finish the loop */
1012 static void repeatstat (LexState
*ls
, int line
) {
1013 /* repeatstat -> REPEAT block UNTIL cond */
1015 FuncState
*fs
= ls
->fs
;
1016 int repeat_init
= luaK_getlabel(fs
);
1018 enterblock(fs
, &bl1
, 1); /* loop block */
1019 enterblock(fs
, &bl2
, 0); /* scope block */
1020 luaX_next(ls
); /* skip REPEAT */
1022 check_match(ls
, TK_UNTIL
, TK_REPEAT
, line
);
1023 condexit
= cond(ls
); /* read condition (inside scope block) */
1024 if (!bl2
.upval
) { /* no upvalues? */
1025 leaveblock(fs
); /* finish scope */
1026 luaK_patchlist(ls
->fs
, condexit
, repeat_init
); /* close the loop */
1028 else { /* complete semantics when there are upvalues */
1029 breakstat(ls
); /* if condition then break */
1030 luaK_patchtohere(ls
->fs
, condexit
); /* else... */
1031 leaveblock(fs
); /* finish scope... */
1032 luaK_patchlist(ls
->fs
, luaK_jump(fs
), repeat_init
); /* and repeat */
1034 leaveblock(fs
); /* finish loop */
1038 static int exp1 (LexState
*ls
) {
1043 luaK_exp2nextreg(ls
->fs
, &e
);
1048 static void forbody (LexState
*ls
, int base
, int line
, int nvars
, int isnum
) {
1049 /* forbody -> DO block */
1051 FuncState
*fs
= ls
->fs
;
1053 adjustlocalvars(ls
, 3); /* control variables */
1054 checknext(ls
, TK_DO
);
1055 prep
= isnum
? luaK_codeAsBx(fs
, OP_FORPREP
, base
, NO_JUMP
) : luaK_jump(fs
);
1056 enterblock(fs
, &bl
, 0); /* scope for declared variables */
1057 adjustlocalvars(ls
, nvars
);
1058 luaK_reserveregs(fs
, nvars
);
1060 leaveblock(fs
); /* end of scope for declared variables */
1061 luaK_patchtohere(fs
, prep
);
1062 endfor
= (isnum
) ? luaK_codeAsBx(fs
, OP_FORLOOP
, base
, NO_JUMP
) :
1063 luaK_codeABC(fs
, OP_TFORLOOP
, base
, 0, nvars
);
1064 luaK_fixline(fs
, line
); /* pretend that `OP_FOR' starts the loop */
1065 luaK_patchlist(fs
, (isnum
? endfor
: luaK_jump(fs
)), prep
+ 1);
1069 static void fornum (LexState
*ls
, TString
*varname
, int line
) {
1070 /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1071 FuncState
*fs
= ls
->fs
;
1072 int base
= fs
->freereg
;
1073 new_localvarliteral(ls
, "(for index)", 0);
1074 new_localvarliteral(ls
, "(for limit)", 1);
1075 new_localvarliteral(ls
, "(for step)", 2);
1076 new_localvar(ls
, varname
, 3);
1078 exp1(ls
); /* initial value */
1080 exp1(ls
); /* limit */
1081 if (testnext(ls
, ','))
1082 exp1(ls
); /* optional step */
1083 else { /* default step = 1 */
1084 luaK_codeABx(fs
, OP_LOADK
, fs
->freereg
, luaK_numberK(fs
, 1));
1085 luaK_reserveregs(fs
, 1);
1087 forbody(ls
, base
, line
, 1, 1);
1091 static void forlist (LexState
*ls
, TString
*indexname
) {
1092 /* forlist -> NAME {,NAME} IN explist1 forbody */
1093 FuncState
*fs
= ls
->fs
;
1097 int base
= fs
->freereg
;
1098 /* create control variables */
1099 new_localvarliteral(ls
, "(for generator)", nvars
++);
1100 new_localvarliteral(ls
, "(for state)", nvars
++);
1101 new_localvarliteral(ls
, "(for control)", nvars
++);
1102 /* create declared variables */
1103 new_localvar(ls
, indexname
, nvars
++);
1104 while (testnext(ls
, ','))
1105 new_localvar(ls
, str_checkname(ls
), nvars
++);
1106 checknext(ls
, TK_IN
);
1107 line
= ls
->linenumber
;
1108 adjust_assign(ls
, 3, explist1(ls
, &e
), &e
);
1109 luaK_checkstack(fs
, 3); /* extra space to call generator */
1110 forbody(ls
, base
, line
, nvars
- 3, 0);
1114 static void forstat (LexState
*ls
, int line
) {
1115 /* forstat -> FOR (fornum | forlist) END */
1116 FuncState
*fs
= ls
->fs
;
1119 enterblock(fs
, &bl
, 1); /* scope for loop and control variables */
1120 luaX_next(ls
); /* skip `for' */
1121 varname
= str_checkname(ls
); /* first variable name */
1122 switch (ls
->t
.token
) {
1123 case '=': fornum(ls
, varname
, line
); break;
1124 case ',': case TK_IN
: forlist(ls
, varname
); break;
1125 default: luaX_syntaxerror(ls
, LUA_QL("=") " or " LUA_QL("in") " expected");
1127 check_match(ls
, TK_END
, TK_FOR
, line
);
1128 leaveblock(fs
); /* loop scope (`break' jumps to this point) */
1132 static int test_then_block (LexState
*ls
) {
1133 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1135 luaX_next(ls
); /* skip IF or ELSEIF */
1136 condexit
= cond(ls
);
1137 checknext(ls
, TK_THEN
);
1138 block(ls
); /* `then' part */
1143 static void ifstat (LexState
*ls
, int line
) {
1144 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1145 FuncState
*fs
= ls
->fs
;
1147 int escapelist
= NO_JUMP
;
1148 flist
= test_then_block(ls
); /* IF cond THEN block */
1149 while (ls
->t
.token
== TK_ELSEIF
) {
1150 luaK_concat(fs
, &escapelist
, luaK_jump(fs
));
1151 luaK_patchtohere(fs
, flist
);
1152 flist
= test_then_block(ls
); /* ELSEIF cond THEN block */
1154 if (ls
->t
.token
== TK_ELSE
) {
1155 luaK_concat(fs
, &escapelist
, luaK_jump(fs
));
1156 luaK_patchtohere(fs
, flist
);
1157 luaX_next(ls
); /* skip ELSE (after patch, for correct line info) */
1158 block(ls
); /* `else' part */
1161 luaK_concat(fs
, &escapelist
, flist
);
1162 luaK_patchtohere(fs
, escapelist
);
1163 check_match(ls
, TK_END
, TK_IF
, line
);
1167 static void localfunc (LexState
*ls
) {
1169 FuncState
*fs
= ls
->fs
;
1170 new_localvar(ls
, str_checkname(ls
), 0);
1171 init_exp(&v
, VLOCAL
, fs
->freereg
);
1172 luaK_reserveregs(fs
, 1);
1173 adjustlocalvars(ls
, 1);
1174 body(ls
, &b
, 0, ls
->linenumber
);
1175 luaK_storevar(fs
, &v
, &b
);
1176 /* debug information will only see the variable after this point! */
1177 getlocvar(fs
, fs
->nactvar
- 1).startpc
= fs
->pc
;
1181 static void localstat (LexState
*ls
) {
1182 /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
1187 new_localvar(ls
, str_checkname(ls
), nvars
++);
1188 } while (testnext(ls
, ','));
1189 if (testnext(ls
, '='))
1190 nexps
= explist1(ls
, &e
);
1195 adjust_assign(ls
, nvars
, nexps
, &e
);
1196 adjustlocalvars(ls
, nvars
);
1200 static int funcname (LexState
*ls
, expdesc
*v
) {
1201 /* funcname -> NAME {field} [`:' NAME] */
1204 while (ls
->t
.token
== '.')
1206 if (ls
->t
.token
== ':') {
1214 static void funcstat (LexState
*ls
, int line
) {
1215 /* funcstat -> FUNCTION funcname body */
1218 luaX_next(ls
); /* skip FUNCTION */
1219 needself
= funcname(ls
, &v
);
1220 body(ls
, &b
, needself
, line
);
1221 luaK_storevar(ls
->fs
, &v
, &b
);
1222 luaK_fixline(ls
->fs
, line
); /* definition `happens' in the first line */
1226 static void exprstat (LexState
*ls
) {
1227 /* stat -> func | assignment */
1228 FuncState
*fs
= ls
->fs
;
1229 struct LHS_assign v
;
1230 primaryexp(ls
, &v
.v
);
1231 if (v
.v
.k
== VCALL
) /* stat -> func */
1232 SETARG_C(getcode(fs
, &v
.v
), 1); /* call statement uses no results */
1233 else { /* stat -> assignment */
1235 assignment(ls
, &v
, 1);
1240 static void retstat (LexState
*ls
) {
1241 /* stat -> RETURN explist */
1242 FuncState
*fs
= ls
->fs
;
1244 int first
, nret
; /* registers with returned values */
1245 luaX_next(ls
); /* skip RETURN */
1246 if (block_follow(ls
->t
.token
) || ls
->t
.token
== ';')
1247 first
= nret
= 0; /* return no values */
1249 nret
= explist1(ls
, &e
); /* optional return values */
1250 if (hasmultret(e
.k
)) {
1251 luaK_setmultret(fs
, &e
);
1252 if (e
.k
== VCALL
&& nret
== 1) { /* tail call? */
1253 SET_OPCODE(getcode(fs
,&e
), OP_TAILCALL
);
1254 lua_assert(GETARG_A(getcode(fs
,&e
)) == fs
->nactvar
);
1256 first
= fs
->nactvar
;
1257 nret
= LUA_MULTRET
; /* return all values */
1260 if (nret
== 1) /* only one single value? */
1261 first
= luaK_exp2anyreg(fs
, &e
);
1263 luaK_exp2nextreg(fs
, &e
); /* values must go to the `stack' */
1264 first
= fs
->nactvar
; /* return all `active' values */
1265 lua_assert(nret
== fs
->freereg
- first
);
1269 luaK_ret(fs
, first
, nret
);
1273 static int statement (LexState
*ls
) {
1274 int line
= ls
->linenumber
; /* may be needed for error messages */
1275 switch (ls
->t
.token
) {
1276 case TK_IF
: { /* stat -> ifstat */
1280 case TK_WHILE
: { /* stat -> whilestat */
1281 whilestat(ls
, line
);
1284 case TK_DO
: { /* stat -> DO block END */
1285 luaX_next(ls
); /* skip DO */
1287 check_match(ls
, TK_END
, TK_DO
, line
);
1290 case TK_FOR
: { /* stat -> forstat */
1294 case TK_REPEAT
: { /* stat -> repeatstat */
1295 repeatstat(ls
, line
);
1299 funcstat(ls
, line
); /* stat -> funcstat */
1302 case TK_LOCAL
: { /* stat -> localstat */
1303 luaX_next(ls
); /* skip LOCAL */
1304 if (testnext(ls
, TK_FUNCTION
)) /* local function? */
1310 case TK_RETURN
: { /* stat -> retstat */
1312 return 1; /* must be last statement */
1314 case TK_BREAK
: { /* stat -> breakstat */
1315 luaX_next(ls
); /* skip BREAK */
1317 return 1; /* must be last statement */
1321 return 0; /* to avoid warnings */
1327 static void chunk (LexState
*ls
) {
1328 /* chunk -> { stat [`;'] } */
1331 while (!islast
&& !block_follow(ls
->t
.token
)) {
1332 islast
= statement(ls
);
1334 lua_assert(ls
->fs
->f
->maxstacksize
>= ls
->fs
->freereg
&&
1335 ls
->fs
->freereg
>= ls
->fs
->nactvar
);
1336 ls
->fs
->freereg
= ls
->fs
->nactvar
; /* free registers */
1341 /* }====================================================================== */