4 ** See Copyright Notice in lua.h
33 /* maximum number of local variables per function (must be smaller
34 than 250, due to the bytecode format) */
38 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
41 /* because all strings are unified by the scanner, the parser
42 can use pointer equality for string equality */
43 #define eqstr(a,b) ((a) == (b))
47 ** nodes for block list (list of active blocks)
49 typedef struct BlockCnt
{
50 struct BlockCnt
*previous
; /* chain */
51 int firstlabel
; /* index of first label in this block */
52 int firstgoto
; /* index of first pending goto in this block */
53 lu_byte nactvar
; /* # active locals outside the block */
54 lu_byte upval
; /* true if some variable in the block is an upvalue */
55 lu_byte isloop
; /* true if 'block' is a loop */
56 lu_byte insidetbc
; /* true if inside the scope of a to-be-closed var. */
62 ** prototypes for recursive non-terminal functions
64 static void statement(LexState
*ls
);
65 static void expr(LexState
*ls
, expdesc
*v
);
68 static l_noret
error_expected(LexState
*ls
, int token
) {
70 luaO_pushfstring(ls
->L
, "%s expected", luaX_token2str(ls
, token
)));
74 static l_noret
errorlimit(FuncState
*fs
, int limit
, const char *what
) {
75 lua_State
*L
= fs
->ls
->L
;
77 int line
= fs
->f
->linedefined
;
78 const char *where
= (line
== 0)
80 : luaO_pushfstring(L
, "function at line %d", line
);
81 msg
= luaO_pushfstring(L
, "too many %s (limit is %d) in %s",
83 luaX_syntaxerror(fs
->ls
, msg
);
87 static void checklimit(FuncState
*fs
, int v
, int l
, const char *what
) {
88 if (v
> l
) errorlimit(fs
, l
, what
);
93 ** Test whether next token is 'c'; if so, skip it.
95 static int testnext(LexState
*ls
, int c
) {
96 if (ls
->t
.token
== c
) {
104 ** Check that next token is 'c'.
106 static void check(LexState
*ls
, int c
) {
107 if (ls
->t
.token
!= c
)
108 error_expected(ls
, c
);
113 ** Check that next token is 'c' and skip it.
115 static void checknext(LexState
*ls
, int c
) {
121 #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
125 ** Check that next token is 'what' and skip it. In case of error,
126 ** raise an error that the expected 'what' should match a 'who'
127 ** in line 'where' (if that is not the current line).
129 static void check_match(LexState
*ls
, int what
, int who
, int where
) {
130 if (l_unlikely(!testnext(ls
, what
))) {
131 if (where
== ls
->linenumber
) /* all in the same line? */
132 error_expected(ls
, what
); /* do not need a complex message */
134 luaX_syntaxerror(ls
, luaO_pushfstring(ls
->L
,
135 "%s expected (to close %s at line %d)",
136 luaX_token2str(ls
, what
), luaX_token2str(ls
, who
), where
));
142 static TString
*str_checkname(LexState
*ls
) {
145 ts
= ls
->t
.seminfo
.ts
;
151 static void init_exp(expdesc
*e
, expkind k
, int i
) {
152 e
->f
= e
->t
= NO_JUMP
;
158 static void codestring(expdesc
*e
, TString
*s
) {
159 e
->f
= e
->t
= NO_JUMP
;
165 static void codename(LexState
*ls
, expdesc
*e
) {
166 codestring(e
, str_checkname(ls
));
171 ** Register a new local variable in the active 'Proto' (for debug
174 static int registerlocalvar(LexState
*ls
, FuncState
*fs
, TString
*varname
) {
176 int oldsize
= f
->sizelocvars
;
177 luaM_growvector(ls
->L
, f
->locvars
, fs
->ndebugvars
, f
->sizelocvars
,
178 LocVar
, SHRT_MAX
, "local variables");
179 while (oldsize
< f
->sizelocvars
)
180 f
->locvars
[oldsize
++].varname
= NULL
;
181 f
->locvars
[fs
->ndebugvars
].varname
= varname
;
182 f
->locvars
[fs
->ndebugvars
].startpc
= fs
->pc
;
183 luaC_objbarrier(ls
->L
, f
, varname
);
184 return fs
->ndebugvars
++;
189 ** Create a new local variable with the given 'name'. Return its index
192 static int new_localvar(LexState
*ls
, TString
*name
) {
193 lua_State
*L
= ls
->L
;
194 FuncState
*fs
= ls
->fs
;
195 Dyndata
*dyd
= ls
->dyd
;
197 checklimit(fs
, dyd
->actvar
.n
+ 1 - fs
->firstlocal
,
198 MAXVARS
, "local variables");
199 luaM_growvector(L
, dyd
->actvar
.arr
, dyd
->actvar
.n
+ 1,
200 dyd
->actvar
.size
, Vardesc
, USHRT_MAX
, "local variables");
201 var
= &dyd
->actvar
.arr
[dyd
->actvar
.n
++];
202 var
->vd
.kind
= VDKREG
; /* default */
204 return dyd
->actvar
.n
- 1 - fs
->firstlocal
;
207 #define new_localvarliteral(ls,v) \
209 luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1));
214 ** Return the "variable description" (Vardesc) of a given variable.
215 ** (Unless noted otherwise, all variables are referred to by their
216 ** compiler indices.)
218 static Vardesc
*getlocalvardesc(FuncState
*fs
, int vidx
) {
219 return &fs
->ls
->dyd
->actvar
.arr
[fs
->firstlocal
+ vidx
];
224 ** Convert 'nvar', a compiler index level, to its corresponding
225 ** register. For that, search for the highest variable below that level
226 ** that is in a register and uses its register index ('ridx') plus one.
228 static int reglevel(FuncState
*fs
, int nvar
) {
230 Vardesc
*vd
= getlocalvardesc(fs
, nvar
); /* get previous variable */
231 if (vd
->vd
.kind
!= RDKCTC
) /* is in a register? */
232 return vd
->vd
.ridx
+ 1;
234 return 0; /* no variables in registers */
239 ** Return the number of variables in the register stack for the given
242 int luaY_nvarstack(FuncState
*fs
) {
243 return reglevel(fs
, fs
->nactvar
);
248 ** Get the debug-information entry for current variable 'vidx'.
250 static LocVar
*localdebuginfo(FuncState
*fs
, int vidx
) {
251 Vardesc
*vd
= getlocalvardesc(fs
, vidx
);
252 if (vd
->vd
.kind
== RDKCTC
)
253 return NULL
; /* no debug info. for constants */
255 int idx
= vd
->vd
.pidx
;
256 lua_assert(idx
< fs
->ndebugvars
);
257 return &fs
->f
->locvars
[idx
];
263 ** Create an expression representing variable 'vidx'
265 static void init_var(FuncState
*fs
, expdesc
*e
, int vidx
) {
266 e
->f
= e
->t
= NO_JUMP
;
268 e
->u
.var
.vidx
= vidx
;
269 e
->u
.var
.ridx
= getlocalvardesc(fs
, vidx
)->vd
.ridx
;
274 ** Raises an error if variable described by 'e' is read only
276 static void check_readonly(LexState
*ls
, expdesc
*e
) {
277 FuncState
*fs
= ls
->fs
;
278 TString
*varname
= NULL
; /* to be set if variable is const */
281 varname
= ls
->dyd
->actvar
.arr
[e
->u
.info
].vd
.name
;
285 Vardesc
*vardesc
= getlocalvardesc(fs
, e
->u
.var
.vidx
);
286 if (vardesc
->vd
.kind
!= VDKREG
) /* not a regular variable? */
287 varname
= vardesc
->vd
.name
;
291 Upvaldesc
*up
= &fs
->f
->upvalues
[e
->u
.info
];
292 if (up
->kind
!= VDKREG
)
297 return; /* other cases cannot be read-only */
300 const char *msg
= luaO_pushfstring(ls
->L
,
301 "attempt to assign to const variable '%s'", getstr(varname
));
302 luaK_semerror(ls
, msg
); /* error */
308 ** Start the scope for the last 'nvars' created variables.
310 static void adjustlocalvars(LexState
*ls
, int nvars
) {
311 FuncState
*fs
= ls
->fs
;
312 int reglevel
= luaY_nvarstack(fs
);
314 for (i
= 0; i
< nvars
; i
++) {
315 int vidx
= fs
->nactvar
++;
316 Vardesc
*var
= getlocalvardesc(fs
, vidx
);
317 var
->vd
.ridx
= reglevel
++;
318 var
->vd
.pidx
= registerlocalvar(ls
, fs
, var
->vd
.name
);
324 ** Close the scope for all variables up to level 'tolevel'.
327 static void removevars(FuncState
*fs
, int tolevel
) {
328 fs
->ls
->dyd
->actvar
.n
-= (fs
->nactvar
- tolevel
);
329 while (fs
->nactvar
> tolevel
) {
330 LocVar
*var
= localdebuginfo(fs
, --fs
->nactvar
);
331 if (var
) /* does it have debug information? */
338 ** Search the upvalues of the function 'fs' for one
339 ** with the given 'name'.
341 static int searchupvalue(FuncState
*fs
, TString
*name
) {
343 Upvaldesc
*up
= fs
->f
->upvalues
;
344 for (i
= 0; i
< fs
->nups
; i
++) {
345 if (eqstr(up
[i
].name
, name
)) return i
;
347 return -1; /* not found */
351 static Upvaldesc
*allocupvalue(FuncState
*fs
) {
353 int oldsize
= f
->sizeupvalues
;
354 checklimit(fs
, fs
->nups
+ 1, MAXUPVAL
, "upvalues");
355 luaM_growvector(fs
->ls
->L
, f
->upvalues
, fs
->nups
, f
->sizeupvalues
,
356 Upvaldesc
, MAXUPVAL
, "upvalues");
357 while (oldsize
< f
->sizeupvalues
)
358 f
->upvalues
[oldsize
++].name
= NULL
;
359 return &f
->upvalues
[fs
->nups
++];
363 static int newupvalue(FuncState
*fs
, TString
*name
, expdesc
*v
) {
364 Upvaldesc
*up
= allocupvalue(fs
);
365 FuncState
*prev
= fs
->prev
;
366 if (v
->k
== VLOCAL
) {
368 up
->idx
= v
->u
.var
.ridx
;
369 up
->kind
= getlocalvardesc(prev
, v
->u
.var
.vidx
)->vd
.kind
;
370 lua_assert(eqstr(name
, getlocalvardesc(prev
, v
->u
.var
.vidx
)->vd
.name
));
373 up
->idx
= cast_byte(v
->u
.info
);
374 up
->kind
= prev
->f
->upvalues
[v
->u
.info
].kind
;
375 lua_assert(eqstr(name
, prev
->f
->upvalues
[v
->u
.info
].name
));
378 luaC_objbarrier(fs
->ls
->L
, fs
->f
, name
);
384 ** Look for an active local variable with the name 'n' in the
385 ** function 'fs'. If found, initialize 'var' with it and return
386 ** its expression kind; otherwise return -1.
388 static int searchvar(FuncState
*fs
, TString
*n
, expdesc
*var
) {
390 for (i
= cast_int(fs
->nactvar
) - 1; i
>= 0; i
--) {
391 Vardesc
*vd
= getlocalvardesc(fs
, i
);
392 if (eqstr(n
, vd
->vd
.name
)) { /* found? */
393 if (vd
->vd
.kind
== RDKCTC
) /* compile-time constant? */
394 init_exp(var
, VCONST
, fs
->firstlocal
+ i
);
395 else /* real variable */
396 init_var(fs
, var
, i
);
400 return -1; /* not found */
405 ** Mark block where variable at given level was defined
406 ** (to emit close instructions later).
408 static void markupval(FuncState
*fs
, int level
) {
409 BlockCnt
*bl
= fs
->bl
;
410 while (bl
->nactvar
> level
)
418 ** Mark that current block has a to-be-closed variable.
420 static void marktobeclosed(FuncState
*fs
) {
421 BlockCnt
*bl
= fs
->bl
;
429 ** Find a variable with the given name 'n'. If it is an upvalue, add
430 ** this upvalue into all intermediate functions. If it is a global, set
431 ** 'var' as 'void' as a flag.
433 static void singlevaraux(FuncState
*fs
, TString
*n
, expdesc
*var
, int base
) {
434 if (fs
== NULL
) /* no more levels? */
435 init_exp(var
, VVOID
, 0); /* default is global */
437 int v
= searchvar(fs
, n
, var
); /* look up locals at current level */
438 if (v
>= 0) { /* found? */
439 if (v
== VLOCAL
&& !base
)
440 markupval(fs
, var
->u
.var
.vidx
); /* local will be used as an upval */
441 } else { /* not found as local at current level; try upvalues */
442 int idx
= searchupvalue(fs
, n
); /* try existing upvalues */
443 if (idx
< 0) { /* not found? */
444 singlevaraux(fs
->prev
, n
, var
, 0); /* try upper levels */
445 if (var
->k
== VLOCAL
|| var
->k
== VUPVAL
) /* local or upvalue? */
446 idx
= newupvalue(fs
, n
, var
); /* will be a new upvalue */
447 else /* it is a global or a constant */
448 return; /* don't need to do anything at this level */
450 init_exp(var
, VUPVAL
, idx
); /* new or old upvalue */
457 ** Find a variable with the given name 'n', handling global variables
460 static void singlevar(LexState
*ls
, expdesc
*var
) {
461 TString
*varname
= str_checkname(ls
);
462 FuncState
*fs
= ls
->fs
;
463 singlevaraux(fs
, varname
, var
, 1);
464 if (var
->k
== VVOID
) { /* global name? */
466 singlevaraux(fs
, ls
->envn
, var
, 1); /* get environment variable */
467 lua_assert(var
->k
!= VVOID
); /* this one must exist */
468 luaK_exp2anyregup(fs
, var
); /* but could be a constant */
469 codestring(&key
, varname
); /* key is variable name */
470 luaK_indexed(fs
, var
, &key
); /* env[varname] */
476 ** Adjust the number of results from an expression list 'e' with 'nexps'
477 ** expressions to 'nvars' values.
479 static void adjust_assign(LexState
*ls
, int nvars
, int nexps
, expdesc
*e
) {
480 FuncState
*fs
= ls
->fs
;
481 int needed
= nvars
- nexps
; /* extra values needed */
482 if (hasmultret(e
->k
)) { /* last expression has multiple returns? */
483 int extra
= needed
+ 1; /* discount last expression itself */
486 luaK_setreturns(fs
, e
, extra
); /* last exp. provides the difference */
488 if (e
->k
!= VVOID
) /* at least one expression? */
489 luaK_exp2nextreg(fs
, e
); /* close last expression */
490 if (needed
> 0) /* missing values? */
491 luaK_nil(fs
, fs
->freereg
, needed
); /* complete with nils */
494 luaK_reserveregs(fs
, needed
); /* registers for extra values */
495 else /* adding 'needed' is actually a subtraction */
496 fs
->freereg
+= needed
; /* remove extra values */
500 #define enterlevel(ls) luaE_incCstack(ls->L)
503 #define leavelevel(ls) ((ls)->L->nCcalls--)
507 ** Generates an error that a goto jumps into the scope of some
510 static l_noret
jumpscopeerror(LexState
*ls
, Labeldesc
*gt
) {
511 const char *varname
= getstr(getlocalvardesc(ls
->fs
, gt
->nactvar
)->vd
.name
);
512 const char *msg
= "<goto %s> at line %d jumps into the scope of local '%s'";
513 msg
= luaO_pushfstring(ls
->L
, msg
, getstr(gt
->name
), gt
->line
, varname
);
514 luaK_semerror(ls
, msg
); /* raise the error */
519 ** Solves the goto at index 'g' to given 'label' and removes it
520 ** from the list of pending gotos.
521 ** If it jumps into the scope of some variable, raises an error.
523 static void solvegoto(LexState
*ls
, int g
, Labeldesc
*label
) {
525 Labellist
*gl
= &ls
->dyd
->gt
; /* list of gotos */
526 Labeldesc
*gt
= &gl
->arr
[g
]; /* goto to be resolved */
527 lua_assert(eqstr(gt
->name
, label
->name
));
528 if (l_unlikely(gt
->nactvar
< label
->nactvar
)) /* enter some scope? */
529 jumpscopeerror(ls
, gt
);
530 luaK_patchlist(ls
->fs
, gt
->pc
, label
->pc
);
531 for (i
= g
; i
< gl
->n
- 1; i
++) /* remove goto from pending list */
532 gl
->arr
[i
] = gl
->arr
[i
+ 1];
538 ** Search for an active label with the given name.
540 static Labeldesc
*findlabel(LexState
*ls
, TString
*name
) {
542 Dyndata
*dyd
= ls
->dyd
;
543 /* check labels in current function for a match */
544 for (i
= ls
->fs
->firstlabel
; i
< dyd
->label
.n
; i
++) {
545 Labeldesc
*lb
= &dyd
->label
.arr
[i
];
546 if (eqstr(lb
->name
, name
)) /* correct label? */
549 return NULL
; /* label not found */
554 ** Adds a new label/goto in the corresponding list.
556 static int newlabelentry(LexState
*ls
, Labellist
*l
, TString
*name
,
559 luaM_growvector(ls
->L
, l
->arr
, n
, l
->size
,
560 Labeldesc
, SHRT_MAX
, "labels/gotos");
561 l
->arr
[n
].name
= name
;
562 l
->arr
[n
].line
= line
;
563 l
->arr
[n
].nactvar
= ls
->fs
->nactvar
;
571 static int newgotoentry(LexState
*ls
, TString
*name
, int line
, int pc
) {
572 return newlabelentry(ls
, &ls
->dyd
->gt
, name
, line
, pc
);
577 ** Solves forward jumps. Check whether new label 'lb' matches any
578 ** pending gotos in current block and solves them. Return true
579 ** if any of the gotos need to close upvalues.
581 static int solvegotos(LexState
*ls
, Labeldesc
*lb
) {
582 Labellist
*gl
= &ls
->dyd
->gt
;
583 int i
= ls
->fs
->bl
->firstgoto
;
586 if (eqstr(gl
->arr
[i
].name
, lb
->name
)) {
587 needsclose
|= gl
->arr
[i
].close
;
588 solvegoto(ls
, i
, lb
); /* will remove 'i' from the list */
597 ** Create a new label with the given 'name' at the given 'line'.
598 ** 'last' tells whether label is the last non-op statement in its
599 ** block. Solves all pending gotos to this new label and adds
600 ** a close instruction if necessary.
601 ** Returns true iff it added a close instruction.
603 static int createlabel(LexState
*ls
, TString
*name
, int line
,
605 FuncState
*fs
= ls
->fs
;
606 Labellist
*ll
= &ls
->dyd
->label
;
607 int l
= newlabelentry(ls
, ll
, name
, line
, luaK_getlabel(fs
));
608 if (last
) { /* label is last no-op statement in the block? */
609 /* assume that locals are already out of scope */
610 ll
->arr
[l
].nactvar
= fs
->bl
->nactvar
;
612 if (solvegotos(ls
, &ll
->arr
[l
])) { /* need close? */
613 luaK_codeABC(fs
, OP_CLOSE
, luaY_nvarstack(fs
), 0, 0);
621 ** Adjust pending gotos to outer level of a block.
623 static void movegotosout(FuncState
*fs
, BlockCnt
*bl
) {
625 Labellist
*gl
= &fs
->ls
->dyd
->gt
;
626 /* correct pending gotos to current block */
627 for (i
= bl
->firstgoto
; i
< gl
->n
; i
++) { /* for each pending goto */
628 Labeldesc
*gt
= &gl
->arr
[i
];
629 /* leaving a variable scope? */
630 if (reglevel(fs
, gt
->nactvar
) > reglevel(fs
, bl
->nactvar
))
631 gt
->close
|= bl
->upval
; /* jump may need a close */
632 gt
->nactvar
= bl
->nactvar
; /* update goto level */
637 static void enterblock(FuncState
*fs
, BlockCnt
*bl
, lu_byte isloop
) {
639 bl
->nactvar
= fs
->nactvar
;
640 bl
->firstlabel
= fs
->ls
->dyd
->label
.n
;
641 bl
->firstgoto
= fs
->ls
->dyd
->gt
.n
;
643 bl
->insidetbc
= (fs
->bl
!= NULL
&& fs
->bl
->insidetbc
);
644 bl
->previous
= fs
->bl
;
646 lua_assert(fs
->freereg
== luaY_nvarstack(fs
));
651 ** generates an error for an undefined 'goto'.
653 static l_noret
undefgoto(LexState
*ls
, Labeldesc
*gt
) {
655 if (eqstr(gt
->name
, luaS_newliteral(ls
->L
, "break"))) {
656 msg
= "break outside loop at line %d";
657 msg
= luaO_pushfstring(ls
->L
, msg
, gt
->line
);
659 msg
= "no visible label '%s' for <goto> at line %d";
660 msg
= luaO_pushfstring(ls
->L
, msg
, getstr(gt
->name
), gt
->line
);
662 luaK_semerror(ls
, msg
);
666 static void leaveblock(FuncState
*fs
) {
667 BlockCnt
*bl
= fs
->bl
;
668 LexState
*ls
= fs
->ls
;
670 int stklevel
= reglevel(fs
, bl
->nactvar
); /* level outside the block */
671 removevars(fs
, bl
->nactvar
); /* remove block locals */
672 lua_assert(bl
->nactvar
== fs
->nactvar
); /* back to level on entry */
673 if (bl
->isloop
) /* has to fix pending breaks? */
674 hasclose
= createlabel(ls
, luaS_newliteral(ls
->L
, "break"), 0, 0);
675 if (!hasclose
&& bl
->previous
&& bl
->upval
) /* still need a 'close'? */
676 luaK_codeABC(fs
, OP_CLOSE
, stklevel
, 0, 0);
677 fs
->freereg
= stklevel
; /* free registers */
678 ls
->dyd
->label
.n
= bl
->firstlabel
; /* remove local labels */
679 fs
->bl
= bl
->previous
; /* current block now is previous one */
680 if (bl
->previous
) /* was it a nested block? */
681 movegotosout(fs
, bl
); /* update pending gotos to enclosing block */
683 if (bl
->firstgoto
< ls
->dyd
->gt
.n
) /* still pending gotos? */
684 undefgoto(ls
, &ls
->dyd
->gt
.arr
[bl
->firstgoto
]); /* error */
690 ** adds a new prototype into list of prototypes
692 static Proto
*addprototype(LexState
*ls
) {
694 lua_State
*L
= ls
->L
;
695 FuncState
*fs
= ls
->fs
;
696 Proto
*f
= fs
->f
; /* prototype of current function */
697 if (fs
->np
>= f
->sizep
) {
698 int oldsize
= f
->sizep
;
699 luaM_growvector(L
, f
->p
, fs
->np
, f
->sizep
, Proto
*, MAXARG_Bx
, "functions");
700 while (oldsize
< f
->sizep
)
701 f
->p
[oldsize
++] = NULL
;
703 f
->p
[fs
->np
++] = clp
= luaF_newproto(L
);
704 luaC_objbarrier(L
, f
, clp
);
710 ** codes instruction to create new closure in parent function.
711 ** The OP_CLOSURE instruction uses the last available register,
712 ** so that, if it invokes the GC, the GC knows which registers
713 ** are in use at that time.
716 static void codeclosure(LexState
*ls
, expdesc
*v
) {
717 FuncState
*fs
= ls
->fs
->prev
;
718 init_exp(v
, VRELOC
, luaK_codeABx(fs
, OP_CLOSURE
, 0, fs
->np
- 1));
719 luaK_exp2nextreg(fs
, v
); /* fix it at the last register */
723 static void open_func(LexState
*ls
, FuncState
*fs
, BlockCnt
*bl
) {
725 fs
->prev
= ls
->fs
; /* linked list of funcstates */
729 fs
->previousline
= f
->linedefined
;
734 fs
->nabslineinfo
= 0;
740 fs
->firstlocal
= ls
->dyd
->actvar
.n
;
741 fs
->firstlabel
= ls
->dyd
->label
.n
;
743 f
->source
= ls
->source
;
744 luaC_objbarrier(ls
->L
, f
, f
->source
);
745 f
->maxstacksize
= 2; /* registers 0/1 are always valid */
746 enterblock(fs
, bl
, 0);
750 static void close_func(LexState
*ls
) {
751 lua_State
*L
= ls
->L
;
752 FuncState
*fs
= ls
->fs
;
754 luaK_ret(fs
, luaY_nvarstack(fs
), 0); /* final return */
756 lua_assert(fs
->bl
== NULL
);
758 luaM_shrinkvector(L
, f
->code
, f
->sizecode
, fs
->pc
, Instruction
);
759 luaM_shrinkvector(L
, f
->lineinfo
, f
->sizelineinfo
, fs
->pc
, ls_byte
);
760 luaM_shrinkvector(L
, f
->abslineinfo
, f
->sizeabslineinfo
,
761 fs
->nabslineinfo
, AbsLineInfo
);
762 luaM_shrinkvector(L
, f
->k
, f
->sizek
, fs
->nk
, TValue
);
763 luaM_shrinkvector(L
, f
->p
, f
->sizep
, fs
->np
, Proto
*);
764 luaM_shrinkvector(L
, f
->locvars
, f
->sizelocvars
, fs
->ndebugvars
, LocVar
);
765 luaM_shrinkvector(L
, f
->upvalues
, f
->sizeupvalues
, fs
->nups
, Upvaldesc
);
772 /*============================================================*/
774 /*============================================================*/
778 ** check whether current token is in the follow set of a block.
779 ** 'until' closes syntactical blocks, but do not close scope,
780 ** so it is handled in separate.
782 static int block_follow(LexState
*ls
, int withuntil
) {
783 switch (ls
->t
.token
) {
797 static void statlist(LexState
*ls
) {
798 /* statlist -> { stat [';'] } */
799 while (!block_follow(ls
, 1)) {
800 if (ls
->t
.token
== TK_RETURN
) {
802 return; /* 'return' must be last statement */
809 static void fieldsel(LexState
*ls
, expdesc
*v
) {
810 /* fieldsel -> ['.' | ':'] NAME */
811 FuncState
*fs
= ls
->fs
;
813 luaK_exp2anyregup(fs
, v
);
814 luaX_next(ls
); /* skip the dot or colon */
816 luaK_indexed(fs
, v
, &key
);
820 static void yindex(LexState
*ls
, expdesc
*v
) {
821 /* index -> '[' expr ']' */
822 luaX_next(ls
); /* skip the '[' */
824 luaK_exp2val(ls
->fs
, v
);
830 ** {======================================================================
831 ** Rules for Constructors
832 ** =======================================================================
836 typedef struct ConsControl
{
837 expdesc v
; /* last list item read */
838 expdesc
*t
; /* table descriptor */
839 int nh
; /* total number of 'record' elements */
840 int na
; /* number of array elements already stored */
841 int tostore
; /* number of array elements pending to be stored */
845 static void recfield(LexState
*ls
, ConsControl
*cc
) {
846 /* recfield -> (NAME | '['exp']') = exp */
847 FuncState
*fs
= ls
->fs
;
848 int reg
= ls
->fs
->freereg
;
849 expdesc tab
, key
, val
;
850 if (ls
->t
.token
== TK_NAME
) {
851 checklimit(fs
, cc
->nh
, MAX_INT
, "items in a constructor");
853 } else /* ls->t.token == '[' */
858 luaK_indexed(fs
, &tab
, &key
);
860 luaK_storevar(fs
, &tab
, &val
);
861 fs
->freereg
= reg
; /* free registers */
865 static void closelistfield(FuncState
*fs
, ConsControl
*cc
) {
866 if (cc
->v
.k
== VVOID
) return; /* there is no list item */
867 luaK_exp2nextreg(fs
, &cc
->v
);
869 if (cc
->tostore
== LFIELDS_PER_FLUSH
) {
870 luaK_setlist(fs
, cc
->t
->u
.info
, cc
->na
, cc
->tostore
); /* flush */
871 cc
->na
+= cc
->tostore
;
872 cc
->tostore
= 0; /* no more items pending */
877 static void lastlistfield(FuncState
*fs
, ConsControl
*cc
) {
878 if (cc
->tostore
== 0) return;
879 if (hasmultret(cc
->v
.k
)) {
880 luaK_setmultret(fs
, &cc
->v
);
881 luaK_setlist(fs
, cc
->t
->u
.info
, cc
->na
, LUA_MULTRET
);
882 cc
->na
--; /* do not count last expression (unknown number of elements) */
884 if (cc
->v
.k
!= VVOID
)
885 luaK_exp2nextreg(fs
, &cc
->v
);
886 luaK_setlist(fs
, cc
->t
->u
.info
, cc
->na
, cc
->tostore
);
888 cc
->na
+= cc
->tostore
;
892 static void listfield(LexState
*ls
, ConsControl
*cc
) {
893 /* listfield -> exp */
899 static void field(LexState
*ls
, ConsControl
*cc
) {
900 /* field -> listfield | recfield */
901 switch (ls
->t
.token
) {
902 case TK_NAME
: { /* may be 'listfield' or 'recfield' */
903 if (luaX_lookahead(ls
) != '=') /* expression? */
921 static void constructor(LexState
*ls
, expdesc
*t
) {
922 /* constructor -> '{' [ field { sep field } [sep] ] '}'
924 FuncState
*fs
= ls
->fs
;
925 int line
= ls
->linenumber
;
926 int pc
= luaK_codeABC(fs
, OP_NEWTABLE
, 0, 0, 0);
928 luaK_code(fs
, 0); /* space for extra arg. */
929 cc
.na
= cc
.nh
= cc
.tostore
= 0;
931 init_exp(t
, VNONRELOC
, fs
->freereg
); /* table will be at stack top */
932 luaK_reserveregs(fs
, 1);
933 init_exp(&cc
.v
, VVOID
, 0); /* no value (yet) */
936 lua_assert(cc
.v
.k
== VVOID
|| cc
.tostore
> 0);
937 if (ls
->t
.token
== '}') break;
938 closelistfield(fs
, &cc
);
940 } while (testnext(ls
, ',') || testnext(ls
, ';'));
941 check_match(ls
, '}', '{', line
);
942 lastlistfield(fs
, &cc
);
943 luaK_settablesize(fs
, pc
, t
->u
.info
, cc
.na
, cc
.nh
);
946 /* }====================================================================== */
949 static void setvararg(FuncState
*fs
, int nparams
) {
950 fs
->f
->is_vararg
= 1;
951 luaK_codeABC(fs
, OP_VARARGPREP
, nparams
, 0, 0);
955 static void parlist(LexState
*ls
) {
956 /* parlist -> [ {NAME ','} (NAME | '...') ] */
957 FuncState
*fs
= ls
->fs
;
961 if (ls
->t
.token
!= ')') { /* is 'parlist' not empty? */
963 switch (ls
->t
.token
) {
965 new_localvar(ls
, str_checkname(ls
));
975 luaX_syntaxerror(ls
, "<name> or '...' expected");
977 } while (!isvararg
&& testnext(ls
, ','));
979 adjustlocalvars(ls
, nparams
);
980 f
->numparams
= cast_byte(fs
->nactvar
);
982 setvararg(fs
, f
->numparams
); /* declared vararg */
983 luaK_reserveregs(fs
, fs
->nactvar
); /* reserve registers for parameters */
987 static void body(LexState
*ls
, expdesc
*e
, int ismethod
, int line
) {
988 /* body -> '(' parlist ')' block END */
991 new_fs
.f
= addprototype(ls
);
992 new_fs
.f
->linedefined
= line
;
993 open_func(ls
, &new_fs
, &bl
);
996 new_localvarliteral(ls
, "self"); /* create 'self' parameter */
997 adjustlocalvars(ls
, 1);
1002 new_fs
.f
->lastlinedefined
= ls
->linenumber
;
1003 check_match(ls
, TK_END
, TK_FUNCTION
, line
);
1009 static int explist(LexState
*ls
, expdesc
*v
) {
1010 /* explist -> expr { ',' expr } */
1011 int n
= 1; /* at least one expression */
1013 while (testnext(ls
, ',')) {
1014 luaK_exp2nextreg(ls
->fs
, v
);
1022 static void funcargs(LexState
*ls
, expdesc
*f
) {
1023 FuncState
*fs
= ls
->fs
;
1026 int line
= ls
->linenumber
;
1027 switch (ls
->t
.token
) {
1028 case '(': { /* funcargs -> '(' [ explist ] ')' */
1030 if (ls
->t
.token
== ')') /* arg list is empty? */
1034 if (hasmultret(args
.k
))
1035 luaK_setmultret(fs
, &args
);
1037 check_match(ls
, ')', '(', line
);
1040 case '{': { /* funcargs -> constructor */
1041 constructor(ls
, &args
);
1044 case TK_STRING
: { /* funcargs -> STRING */
1045 codestring(&args
, ls
->t
.seminfo
.ts
);
1046 luaX_next(ls
); /* must use 'seminfo' before 'next' */
1050 luaX_syntaxerror(ls
, "function arguments expected");
1053 lua_assert(f
->k
== VNONRELOC
);
1054 base
= f
->u
.info
; /* base register for call */
1055 if (hasmultret(args
.k
))
1056 nparams
= LUA_MULTRET
; /* open call */
1058 if (args
.k
!= VVOID
)
1059 luaK_exp2nextreg(fs
, &args
); /* close last argument */
1060 nparams
= fs
->freereg
- (base
+ 1);
1062 init_exp(f
, VCALL
, luaK_codeABC(fs
, OP_CALL
, base
, nparams
+ 1, 2));
1063 luaK_fixline(fs
, line
);
1064 fs
->freereg
= base
+ 1; /* call removes function and arguments and leaves
1065 one result (unless changed later) */
1072 ** {======================================================================
1073 ** Expression parsing
1074 ** =======================================================================
1078 static void primaryexp(LexState
*ls
, expdesc
*v
) {
1079 /* primaryexp -> NAME | '(' expr ')' */
1080 switch (ls
->t
.token
) {
1082 int line
= ls
->linenumber
;
1085 check_match(ls
, ')', '(', line
);
1086 luaK_dischargevars(ls
->fs
, v
);
1094 luaX_syntaxerror(ls
, "unexpected symbol");
1100 static void suffixedexp(LexState
*ls
, expdesc
*v
) {
1102 primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
1103 FuncState
*fs
= ls
->fs
;
1106 switch (ls
->t
.token
) {
1107 case '.': { /* fieldsel */
1111 case '[': { /* '[' exp ']' */
1113 luaK_exp2anyregup(fs
, v
);
1115 luaK_indexed(fs
, v
, &key
);
1118 case ':': { /* ':' NAME funcargs */
1122 luaK_self(fs
, v
, &key
);
1128 case '{': { /* funcargs */
1129 luaK_exp2nextreg(fs
, v
);
1140 static void simpleexp(LexState
*ls
, expdesc
*v
) {
1141 /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
1142 constructor | FUNCTION body | suffixedexp */
1143 switch (ls
->t
.token
) {
1145 init_exp(v
, VKFLT
, 0);
1146 v
->u
.nval
= ls
->t
.seminfo
.r
;
1150 init_exp(v
, VKINT
, 0);
1151 v
->u
.ival
= ls
->t
.seminfo
.i
;
1155 codestring(v
, ls
->t
.seminfo
.ts
);
1159 init_exp(v
, VNIL
, 0);
1163 init_exp(v
, VTRUE
, 0);
1167 init_exp(v
, VFALSE
, 0);
1170 case TK_DOTS
: { /* vararg */
1171 FuncState
*fs
= ls
->fs
;
1172 check_condition(ls
, fs
->f
->is_vararg
,
1173 "cannot use '...' outside a vararg function");
1174 init_exp(v
, VVARARG
, luaK_codeABC(fs
, OP_VARARG
, 0, 0, 1));
1177 case '{': { /* constructor */
1183 body(ls
, v
, 0, ls
->linenumber
);
1195 static UnOpr
getunopr(int op
) {
1211 static BinOpr
getbinopr(int op
) {
1256 return OPR_NOBINOPR
;
1262 ** Priority table for binary operators.
1264 static const struct {
1265 lu_byte left
; /* left priority for each binary operator */
1266 lu_byte right
; /* right priority */
1267 } priority
[] = { /* ORDER OPR */
1268 {10, 10}, {10, 10}, /* '+' '-' */
1269 {11, 11}, {11, 11}, /* '*' '%' */
1270 {14, 13}, /* '^' (right associative) */
1271 {11, 11}, {11, 11}, /* '/' '//' */
1272 {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
1273 {7, 7}, {7, 7}, /* '<<' '>>' */
1274 {9, 8}, /* '..' (right associative) */
1275 {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
1276 {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
1277 {2, 2}, {1, 1} /* and, or */
1280 #define UNARY_PRIORITY 12 /* priority for unary operators */
1284 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1285 ** where 'binop' is any binary operator with a priority higher than 'limit'
1287 static BinOpr
subexpr(LexState
*ls
, expdesc
*v
, int limit
) {
1291 uop
= getunopr(ls
->t
.token
);
1292 if (uop
!= OPR_NOUNOPR
) { /* prefix (unary) operator? */
1293 int line
= ls
->linenumber
;
1294 luaX_next(ls
); /* skip operator */
1295 subexpr(ls
, v
, UNARY_PRIORITY
);
1296 luaK_prefix(ls
->fs
, uop
, v
, line
);
1297 } else simpleexp(ls
, v
);
1298 /* expand while operators have priorities higher than 'limit' */
1299 op
= getbinopr(ls
->t
.token
);
1300 while (op
!= OPR_NOBINOPR
&& priority
[op
].left
> limit
) {
1303 int line
= ls
->linenumber
;
1304 luaX_next(ls
); /* skip operator */
1305 luaK_infix(ls
->fs
, op
, v
);
1306 /* read sub-expression with higher priority */
1307 nextop
= subexpr(ls
, &v2
, priority
[op
].right
);
1308 luaK_posfix(ls
->fs
, op
, v
, &v2
, line
);
1312 return op
; /* return first untreated operator */
1316 static void expr(LexState
*ls
, expdesc
*v
) {
1320 /* }==================================================================== */
1325 ** {======================================================================
1326 ** Rules for Statements
1327 ** =======================================================================
1331 static void block(LexState
*ls
) {
1332 /* block -> statlist */
1333 FuncState
*fs
= ls
->fs
;
1335 enterblock(fs
, &bl
, 0);
1342 ** structure to chain all variables in the left-hand side of an
1346 struct LHS_assign
*prev
;
1347 expdesc v
; /* variable (global, local, upvalue, or indexed) */
1352 ** check whether, in an assignment to an upvalue/local variable, the
1353 ** upvalue/local variable is begin used in a previous assignment to a
1354 ** table. If so, save original upvalue/local value in a safe place and
1355 ** use this safe copy in the previous assignment.
1357 static void check_conflict(LexState
*ls
, struct LHS_assign
*lh
, expdesc
*v
) {
1358 FuncState
*fs
= ls
->fs
;
1359 int extra
= fs
->freereg
; /* eventual position to save local variable */
1361 for (; lh
; lh
= lh
->prev
) { /* check all previous assignments */
1362 if (vkisindexed(lh
->v
.k
)) { /* assignment to table field? */
1363 if (lh
->v
.k
== VINDEXUP
) { /* is table an upvalue? */
1364 if (v
->k
== VUPVAL
&& lh
->v
.u
.ind
.t
== v
->u
.info
) {
1365 conflict
= 1; /* table is the upvalue being assigned now */
1366 lh
->v
.k
= VINDEXSTR
;
1367 lh
->v
.u
.ind
.t
= extra
; /* assignment will use safe copy */
1369 } else { /* table is a register */
1370 if (v
->k
== VLOCAL
&& lh
->v
.u
.ind
.t
== v
->u
.var
.ridx
) {
1371 conflict
= 1; /* table is the local being assigned now */
1372 lh
->v
.u
.ind
.t
= extra
; /* assignment will use safe copy */
1374 /* is index the local being assigned? */
1375 if (lh
->v
.k
== VINDEXED
&& v
->k
== VLOCAL
&&
1376 lh
->v
.u
.ind
.idx
== v
->u
.var
.ridx
) {
1378 lh
->v
.u
.ind
.idx
= extra
; /* previous assignment will use safe copy */
1384 /* copy upvalue/local value to a temporary (in position 'extra') */
1386 luaK_codeABC(fs
, OP_MOVE
, extra
, v
->u
.var
.ridx
, 0);
1388 luaK_codeABC(fs
, OP_GETUPVAL
, extra
, v
->u
.info
, 0);
1389 luaK_reserveregs(fs
, 1);
1394 ** Parse and compile a multiple assignment. The first "variable"
1395 ** (a 'suffixedexp') was already read by the caller.
1397 ** assignment -> suffixedexp restassign
1398 ** restassign -> ',' suffixedexp restassign | '=' explist
1400 static void restassign(LexState
*ls
, struct LHS_assign
*lh
, int nvars
) {
1402 check_condition(ls
, vkisvar(lh
->v
.k
), "syntax error");
1403 check_readonly(ls
, &lh
->v
);
1404 if (testnext(ls
, ',')) { /* restassign -> ',' suffixedexp restassign */
1405 struct LHS_assign nv
;
1407 suffixedexp(ls
, &nv
.v
);
1408 if (!vkisindexed(nv
.v
.k
))
1409 check_conflict(ls
, lh
, &nv
.v
);
1410 enterlevel(ls
); /* control recursion depth */
1411 restassign(ls
, &nv
, nvars
+ 1);
1413 } else { /* restassign -> '=' explist */
1416 nexps
= explist(ls
, &e
);
1418 adjust_assign(ls
, nvars
, nexps
, &e
);
1420 luaK_setoneret(ls
->fs
, &e
); /* close last expression */
1421 luaK_storevar(ls
->fs
, &lh
->v
, &e
);
1422 return; /* avoid default */
1425 init_exp(&e
, VNONRELOC
, ls
->fs
->freereg
- 1); /* default assignment */
1426 luaK_storevar(ls
->fs
, &lh
->v
, &e
);
1430 static int cond(LexState
*ls
) {
1433 expr(ls
, &v
); /* read condition */
1434 if (v
.k
== VNIL
) v
.k
= VFALSE
; /* 'falses' are all equal here */
1435 luaK_goiftrue(ls
->fs
, &v
);
1440 static void gotostat(LexState
*ls
) {
1441 FuncState
*fs
= ls
->fs
;
1442 int line
= ls
->linenumber
;
1443 TString
*name
= str_checkname(ls
); /* label's name */
1444 Labeldesc
*lb
= findlabel(ls
, name
);
1445 if (lb
== NULL
) /* no label? */
1446 /* forward jump; will be resolved when the label is declared */
1447 newgotoentry(ls
, name
, line
, luaK_jump(fs
));
1448 else { /* found a label */
1449 /* backward jump; will be resolved here */
1450 int lblevel
= reglevel(fs
, lb
->nactvar
); /* label level */
1451 if (luaY_nvarstack(fs
) > lblevel
) /* leaving the scope of a variable? */
1452 luaK_codeABC(fs
, OP_CLOSE
, lblevel
, 0, 0);
1453 /* create jump and link it to the label */
1454 luaK_patchlist(fs
, luaK_jump(fs
), lb
->pc
);
1460 ** Break statement. Semantically equivalent to "goto break".
1462 static void breakstat(LexState
*ls
) {
1463 int line
= ls
->linenumber
;
1464 luaX_next(ls
); /* skip break */
1465 newgotoentry(ls
, luaS_newliteral(ls
->L
, "break"), line
, luaK_jump(ls
->fs
));
1470 ** Check whether there is already a label with the given 'name'.
1472 static void checkrepeated(LexState
*ls
, TString
*name
) {
1473 Labeldesc
*lb
= findlabel(ls
, name
);
1474 if (l_unlikely(lb
!= NULL
)) { /* already defined? */
1475 const char *msg
= "label '%s' already defined on line %d";
1476 msg
= luaO_pushfstring(ls
->L
, msg
, getstr(name
), lb
->line
);
1477 luaK_semerror(ls
, msg
); /* error */
1482 static void labelstat(LexState
*ls
, TString
*name
, int line
) {
1483 /* label -> '::' NAME '::' */
1484 checknext(ls
, TK_DBCOLON
); /* skip double colon */
1485 while (ls
->t
.token
== ';' || ls
->t
.token
== TK_DBCOLON
)
1486 statement(ls
); /* skip other no-op statements */
1487 checkrepeated(ls
, name
); /* check for repeated labels */
1488 createlabel(ls
, name
, line
, block_follow(ls
, 0));
1492 static void whilestat(LexState
*ls
, int line
) {
1493 /* whilestat -> WHILE cond DO block END */
1494 FuncState
*fs
= ls
->fs
;
1498 luaX_next(ls
); /* skip WHILE */
1499 whileinit
= luaK_getlabel(fs
);
1500 condexit
= cond(ls
);
1501 enterblock(fs
, &bl
, 1);
1502 checknext(ls
, TK_DO
);
1504 luaK_jumpto(fs
, whileinit
);
1505 check_match(ls
, TK_END
, TK_WHILE
, line
);
1507 luaK_patchtohere(fs
, condexit
); /* false conditions finish the loop */
1511 static void repeatstat(LexState
*ls
, int line
) {
1512 /* repeatstat -> REPEAT block UNTIL cond */
1514 FuncState
*fs
= ls
->fs
;
1515 int repeat_init
= luaK_getlabel(fs
);
1517 enterblock(fs
, &bl1
, 1); /* loop block */
1518 enterblock(fs
, &bl2
, 0); /* scope block */
1519 luaX_next(ls
); /* skip REPEAT */
1521 check_match(ls
, TK_UNTIL
, TK_REPEAT
, line
);
1522 condexit
= cond(ls
); /* read condition (inside scope block) */
1523 leaveblock(fs
); /* finish scope */
1524 if (bl2
.upval
) { /* upvalues? */
1525 int exit
= luaK_jump(fs
); /* normal exit must jump over fix */
1526 luaK_patchtohere(fs
, condexit
); /* repetition must close upvalues */
1527 luaK_codeABC(fs
, OP_CLOSE
, reglevel(fs
, bl2
.nactvar
), 0, 0);
1528 condexit
= luaK_jump(fs
); /* repeat after closing upvalues */
1529 luaK_patchtohere(fs
, exit
); /* normal exit comes to here */
1531 luaK_patchlist(fs
, condexit
, repeat_init
); /* close the loop */
1532 leaveblock(fs
); /* finish loop */
1537 ** Read an expression and generate code to put its results in next
1541 static void exp1(LexState
*ls
) {
1544 luaK_exp2nextreg(ls
->fs
, &e
);
1545 lua_assert(e
.k
== VNONRELOC
);
1550 ** Fix for instruction at position 'pc' to jump to 'dest'.
1551 ** (Jump addresses are relative in Lua). 'back' true means
1554 static void fixforjump(FuncState
*fs
, int pc
, int dest
, int back
) {
1555 Instruction
*jmp
= &fs
->f
->code
[pc
];
1556 int offset
= dest
- (pc
+ 1);
1559 if (l_unlikely(offset
> MAXARG_Bx
))
1560 luaX_syntaxerror(fs
->ls
, "control structure too long");
1561 SETARG_Bx(*jmp
, offset
);
1566 ** Generate code for a 'for' loop.
1568 static void forbody(LexState
*ls
, int base
, int line
, int nvars
, int isgen
) {
1569 /* forbody -> DO block */
1570 static const OpCode forprep
[2] = {OP_FORPREP
, OP_TFORPREP
};
1571 static const OpCode forloop
[2] = {OP_FORLOOP
, OP_TFORLOOP
};
1573 FuncState
*fs
= ls
->fs
;
1575 checknext(ls
, TK_DO
);
1576 prep
= luaK_codeABx(fs
, forprep
[isgen
], base
, 0);
1577 enterblock(fs
, &bl
, 0); /* scope for declared variables */
1578 adjustlocalvars(ls
, nvars
);
1579 luaK_reserveregs(fs
, nvars
);
1581 leaveblock(fs
); /* end of scope for declared variables */
1582 fixforjump(fs
, prep
, luaK_getlabel(fs
), 0);
1583 if (isgen
) { /* generic for? */
1584 luaK_codeABC(fs
, OP_TFORCALL
, base
, 0, nvars
);
1585 luaK_fixline(fs
, line
);
1587 endfor
= luaK_codeABx(fs
, forloop
[isgen
], base
, 0);
1588 fixforjump(fs
, endfor
, prep
+ 1, 1);
1589 luaK_fixline(fs
, line
);
1593 static void fornum(LexState
*ls
, TString
*varname
, int line
) {
1594 /* fornum -> NAME = exp,exp[,exp] forbody */
1595 FuncState
*fs
= ls
->fs
;
1596 int base
= fs
->freereg
;
1597 new_localvarliteral(ls
, "(for state)");
1598 new_localvarliteral(ls
, "(for state)");
1599 new_localvarliteral(ls
, "(for state)");
1600 new_localvar(ls
, varname
);
1602 exp1(ls
); /* initial value */
1604 exp1(ls
); /* limit */
1605 if (testnext(ls
, ','))
1606 exp1(ls
); /* optional step */
1607 else { /* default step = 1 */
1608 luaK_int(fs
, fs
->freereg
, 1);
1609 luaK_reserveregs(fs
, 1);
1611 adjustlocalvars(ls
, 3); /* control variables */
1612 forbody(ls
, base
, line
, 1, 0);
1616 static void forlist(LexState
*ls
, TString
*indexname
) {
1617 /* forlist -> NAME {,NAME} IN explist forbody */
1618 FuncState
*fs
= ls
->fs
;
1620 int nvars
= 5; /* gen, state, control, toclose, 'indexname' */
1622 int base
= fs
->freereg
;
1623 /* create control variables */
1624 new_localvarliteral(ls
, "(for state)");
1625 new_localvarliteral(ls
, "(for state)");
1626 new_localvarliteral(ls
, "(for state)");
1627 new_localvarliteral(ls
, "(for state)");
1628 /* create declared variables */
1629 new_localvar(ls
, indexname
);
1630 while (testnext(ls
, ',')) {
1631 new_localvar(ls
, str_checkname(ls
));
1634 checknext(ls
, TK_IN
);
1635 line
= ls
->linenumber
;
1636 adjust_assign(ls
, 4, explist(ls
, &e
), &e
);
1637 adjustlocalvars(ls
, 4); /* control variables */
1638 marktobeclosed(fs
); /* last control var. must be closed */
1639 luaK_checkstack(fs
, 3); /* extra space to call generator */
1640 forbody(ls
, base
, line
, nvars
- 4, 1);
1644 static void forstat(LexState
*ls
, int line
) {
1645 /* forstat -> FOR (fornum | forlist) END */
1646 FuncState
*fs
= ls
->fs
;
1649 enterblock(fs
, &bl
, 1); /* scope for loop and control variables */
1650 luaX_next(ls
); /* skip 'for' */
1651 varname
= str_checkname(ls
); /* first variable name */
1652 switch (ls
->t
.token
) {
1654 fornum(ls
, varname
, line
);
1658 forlist(ls
, varname
);
1661 luaX_syntaxerror(ls
, "'=' or 'in' expected");
1663 check_match(ls
, TK_END
, TK_FOR
, line
);
1664 leaveblock(fs
); /* loop scope ('break' jumps to this point) */
1668 static void test_then_block(LexState
*ls
, int *escapelist
) {
1669 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1671 FuncState
*fs
= ls
->fs
;
1673 int jf
; /* instruction to skip 'then' code (if condition is false) */
1674 luaX_next(ls
); /* skip IF or ELSEIF */
1675 expr(ls
, &v
); /* read condition */
1676 checknext(ls
, TK_THEN
);
1677 if (ls
->t
.token
== TK_BREAK
) { /* 'if x then break' ? */
1678 int line
= ls
->linenumber
;
1679 luaK_goiffalse(ls
->fs
, &v
); /* will jump if condition is true */
1680 luaX_next(ls
); /* skip 'break' */
1681 enterblock(fs
, &bl
, 0); /* must enter block before 'goto' */
1682 newgotoentry(ls
, luaS_newliteral(ls
->L
, "break"), line
, v
.t
);
1683 while (testnext(ls
, ';')) {} /* skip semicolons */
1684 if (block_follow(ls
, 0)) { /* jump is the entire block? */
1686 return; /* and that is it */
1687 } else /* must skip over 'then' part if condition is false */
1689 } else { /* regular case (not a break) */
1690 luaK_goiftrue(ls
->fs
, &v
); /* skip over block if condition is false */
1691 enterblock(fs
, &bl
, 0);
1694 statlist(ls
); /* 'then' part */
1696 if (ls
->t
.token
== TK_ELSE
||
1697 ls
->t
.token
== TK_ELSEIF
) /* followed by 'else'/'elseif'? */
1698 luaK_concat(fs
, escapelist
, luaK_jump(fs
)); /* must jump over it */
1699 luaK_patchtohere(fs
, jf
);
1703 static void ifstat(LexState
*ls
, int line
) {
1704 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1705 FuncState
*fs
= ls
->fs
;
1706 int escapelist
= NO_JUMP
; /* exit list for finished parts */
1707 test_then_block(ls
, &escapelist
); /* IF cond THEN block */
1708 while (ls
->t
.token
== TK_ELSEIF
)
1709 test_then_block(ls
, &escapelist
); /* ELSEIF cond THEN block */
1710 if (testnext(ls
, TK_ELSE
))
1711 block(ls
); /* 'else' part */
1712 check_match(ls
, TK_END
, TK_IF
, line
);
1713 luaK_patchtohere(fs
, escapelist
); /* patch escape list to 'if' end */
1717 static void localfunc(LexState
*ls
) {
1719 FuncState
*fs
= ls
->fs
;
1720 int fvar
= fs
->nactvar
; /* function's variable index */
1721 new_localvar(ls
, str_checkname(ls
)); /* new local variable */
1722 adjustlocalvars(ls
, 1); /* enter its scope */
1723 body(ls
, &b
, 0, ls
->linenumber
); /* function created in next register */
1724 /* debug information will only see the variable after this point! */
1725 localdebuginfo(fs
, fvar
)->startpc
= fs
->pc
;
1729 static int getlocalattribute(LexState
*ls
) {
1730 /* ATTRIB -> ['<' Name '>'] */
1731 if (testnext(ls
, '<')) {
1732 const char *attr
= getstr(str_checkname(ls
));
1734 if (strcmp(attr
, "const") == 0)
1735 return RDKCONST
; /* read-only variable */
1736 else if (strcmp(attr
, "close") == 0)
1737 return RDKTOCLOSE
; /* to-be-closed variable */
1740 luaO_pushfstring(ls
->L
, "unknown attribute '%s'", attr
));
1742 return VDKREG
; /* regular variable */
1746 static void checktoclose(FuncState
*fs
, int level
) {
1747 if (level
!= -1) { /* is there a to-be-closed variable? */
1749 luaK_codeABC(fs
, OP_TBC
, reglevel(fs
, level
), 0, 0);
1754 static void localstat(LexState
*ls
) {
1755 /* stat -> LOCAL NAME ATTRIB { ',' NAME ATTRIB } ['=' explist] */
1756 FuncState
*fs
= ls
->fs
;
1757 int toclose
= -1; /* index of to-be-closed variable (if any) */
1758 Vardesc
*var
; /* last variable */
1759 int vidx
, kind
; /* index and kind of last variable */
1764 vidx
= new_localvar(ls
, str_checkname(ls
));
1765 kind
= getlocalattribute(ls
);
1766 getlocalvardesc(fs
, vidx
)->vd
.kind
= kind
;
1767 if (kind
== RDKTOCLOSE
) { /* to-be-closed? */
1768 if (toclose
!= -1) /* one already present? */
1769 luaK_semerror(ls
, "multiple to-be-closed variables in local list");
1770 toclose
= fs
->nactvar
+ nvars
;
1773 } while (testnext(ls
, ','));
1774 if (testnext(ls
, '='))
1775 nexps
= explist(ls
, &e
);
1780 var
= getlocalvardesc(fs
, vidx
); /* get last variable */
1781 if (nvars
== nexps
&& /* no adjustments? */
1782 var
->vd
.kind
== RDKCONST
&& /* last variable is const? */
1783 luaK_exp2const(fs
, &e
, &var
->k
)) { /* compile-time constant? */
1784 var
->vd
.kind
= RDKCTC
; /* variable is a compile-time constant */
1785 adjustlocalvars(ls
, nvars
- 1); /* exclude last variable */
1786 fs
->nactvar
++; /* but count it */
1788 adjust_assign(ls
, nvars
, nexps
, &e
);
1789 adjustlocalvars(ls
, nvars
);
1791 checktoclose(fs
, toclose
);
1795 static int funcname(LexState
*ls
, expdesc
*v
) {
1796 /* funcname -> NAME {fieldsel} [':' NAME] */
1799 while (ls
->t
.token
== '.')
1801 if (ls
->t
.token
== ':') {
1809 static void funcstat(LexState
*ls
, int line
) {
1810 /* funcstat -> FUNCTION funcname body */
1813 luaX_next(ls
); /* skip FUNCTION */
1814 ismethod
= funcname(ls
, &v
);
1815 body(ls
, &b
, ismethod
, line
);
1816 check_readonly(ls
, &v
);
1817 luaK_storevar(ls
->fs
, &v
, &b
);
1818 luaK_fixline(ls
->fs
, line
); /* definition "happens" in the first line */
1822 static void exprstat(LexState
*ls
) {
1823 /* stat -> func | assignment */
1824 FuncState
*fs
= ls
->fs
;
1825 struct LHS_assign v
;
1826 suffixedexp(ls
, &v
.v
);
1827 if (ls
->t
.token
== '=' || ls
->t
.token
== ',') { /* stat -> assignment ? */
1829 restassign(ls
, &v
, 1);
1830 } else { /* stat -> func */
1832 check_condition(ls
, v
.v
.k
== VCALL
, "syntax error");
1833 inst
= &getinstruction(fs
, &v
.v
);
1834 SETARG_C(*inst
, 1); /* call statement uses no results */
1839 static void retstat(LexState
*ls
) {
1840 /* stat -> RETURN [explist] [';'] */
1841 FuncState
*fs
= ls
->fs
;
1843 int nret
; /* number of values being returned */
1844 int first
= luaY_nvarstack(fs
); /* first slot to be returned */
1845 if (block_follow(ls
, 1) || ls
->t
.token
== ';')
1846 nret
= 0; /* return no values */
1848 nret
= explist(ls
, &e
); /* optional return values */
1849 if (hasmultret(e
.k
)) {
1850 luaK_setmultret(fs
, &e
);
1851 if (e
.k
== VCALL
&& nret
== 1 && !fs
->bl
->insidetbc
) { /* tail call? */
1852 SET_OPCODE(getinstruction(fs
, &e
), OP_TAILCALL
);
1853 lua_assert(GETARG_A(getinstruction(fs
, &e
)) == luaY_nvarstack(fs
));
1855 nret
= LUA_MULTRET
; /* return all values */
1857 if (nret
== 1) /* only one single value? */
1858 first
= luaK_exp2anyreg(fs
, &e
); /* can use original slot */
1859 else { /* values must go to the top of the stack */
1860 luaK_exp2nextreg(fs
, &e
);
1861 lua_assert(nret
== fs
->freereg
- first
);
1865 luaK_ret(fs
, first
, nret
);
1866 testnext(ls
, ';'); /* skip optional semicolon */
1870 static void statement(LexState
*ls
) {
1871 int line
= ls
->linenumber
; /* may be needed for error messages */
1873 switch (ls
->t
.token
) {
1874 case ';': { /* stat -> ';' (empty statement) */
1875 luaX_next(ls
); /* skip ';' */
1878 case TK_IF
: { /* stat -> ifstat */
1882 case TK_WHILE
: { /* stat -> whilestat */
1883 whilestat(ls
, line
);
1886 case TK_DO
: { /* stat -> DO block END */
1887 luaX_next(ls
); /* skip DO */
1889 check_match(ls
, TK_END
, TK_DO
, line
);
1892 case TK_FOR
: { /* stat -> forstat */
1896 case TK_REPEAT
: { /* stat -> repeatstat */
1897 repeatstat(ls
, line
);
1900 case TK_FUNCTION
: { /* stat -> funcstat */
1904 case TK_LOCAL
: { /* stat -> localstat */
1905 luaX_next(ls
); /* skip LOCAL */
1906 if (testnext(ls
, TK_FUNCTION
)) /* local function? */
1912 case TK_DBCOLON
: { /* stat -> label */
1913 luaX_next(ls
); /* skip double colon */
1914 labelstat(ls
, str_checkname(ls
), line
);
1917 case TK_RETURN
: { /* stat -> retstat */
1918 luaX_next(ls
); /* skip RETURN */
1922 case TK_BREAK
: { /* stat -> breakstat */
1926 case TK_GOTO
: { /* stat -> 'goto' NAME */
1927 luaX_next(ls
); /* skip 'goto' */
1931 default: { /* stat -> func | assignment */
1936 lua_assert(ls
->fs
->f
->maxstacksize
>= ls
->fs
->freereg
&&
1937 ls
->fs
->freereg
>= luaY_nvarstack(ls
->fs
));
1938 ls
->fs
->freereg
= luaY_nvarstack(ls
->fs
); /* free registers */
1942 /* }====================================================================== */
1946 ** compiles the main function, which is a regular vararg function with an
1947 ** upvalue named LUA_ENV
1949 static void mainfunc(LexState
*ls
, FuncState
*fs
) {
1952 open_func(ls
, fs
, &bl
);
1953 setvararg(fs
, 0); /* main function is always declared vararg */
1954 env
= allocupvalue(fs
); /* ...set environment upvalue */
1958 env
->name
= ls
->envn
;
1959 luaC_objbarrier(ls
->L
, fs
->f
, env
->name
);
1960 luaX_next(ls
); /* read first token */
1961 statlist(ls
); /* parse main body */
1967 LClosure
*luaY_parser(lua_State
*L
, ZIO
*z
, Mbuffer
*buff
,
1968 Dyndata
*dyd
, const char *name
, int firstchar
) {
1970 FuncState funcstate
;
1971 LClosure
*cl
= luaF_newLclosure(L
, 1); /* create main closure */
1972 setclLvalue2s(L
, L
->top
.p
, cl
); /* anchor it (to avoid being collected) */
1974 lexstate
.h
= luaH_new(L
); /* create table for scanner */
1975 sethvalue2s(L
, L
->top
.p
, lexstate
.h
); /* anchor it */
1977 funcstate
.f
= cl
->p
= luaF_newproto(L
);
1978 luaC_objbarrier(L
, cl
, cl
->p
);
1979 funcstate
.f
->source
= luaS_new(L
, name
); /* create and anchor TString */
1980 luaC_objbarrier(L
, funcstate
.f
, funcstate
.f
->source
);
1981 lexstate
.buff
= buff
;
1983 dyd
->actvar
.n
= dyd
->gt
.n
= dyd
->label
.n
= 0;
1984 luaX_setinput(L
, &lexstate
, z
, funcstate
.f
->source
, firstchar
);
1985 mainfunc(&lexstate
, &funcstate
);
1986 lua_assert(!funcstate
.prev
&& funcstate
.nups
== 1 && !lexstate
.fs
);
1987 /* all scopes should be correctly finished */
1988 lua_assert(dyd
->actvar
.n
== 0 && dyd
->gt
.n
== 0 && dyd
->label
.n
== 0);
1989 L
->top
.p
--; /* remove scanner's table */
1990 return cl
; /* closure is on the stack, too */