]>
git.proxmox.com Git - ceph.git/blob - ceph/src/jaegertracing/opentelemetry-cpp/third_party/prometheus-cpp/3rdparty/civetweb/src/third_party/lua-5.4.3/src/lparser.c
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
) {
105 ** Check that next token is 'c'.
107 static void check (LexState
*ls
, int c
) {
108 if (ls
->t
.token
!= c
)
109 error_expected(ls
, c
);
114 ** Check that next token is 'c' and skip it.
116 static void checknext (LexState
*ls
, int c
) {
122 #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
126 ** Check that next token is 'what' and skip it. In case of error,
127 ** raise an error that the expected 'what' should match a 'who'
128 ** in line 'where' (if that is not the current line).
130 static void check_match (LexState
*ls
, int what
, int who
, int where
) {
131 if (l_unlikely(!testnext(ls
, what
))) {
132 if (where
== ls
->linenumber
) /* all in the same line? */
133 error_expected(ls
, what
); /* do not need a complex message */
135 luaX_syntaxerror(ls
, luaO_pushfstring(ls
->L
,
136 "%s expected (to close %s at line %d)",
137 luaX_token2str(ls
, what
), luaX_token2str(ls
, who
), where
));
143 static TString
*str_checkname (LexState
*ls
) {
146 ts
= ls
->t
.seminfo
.ts
;
152 static void init_exp (expdesc
*e
, expkind k
, int i
) {
153 e
->f
= e
->t
= NO_JUMP
;
159 static void codestring (expdesc
*e
, TString
*s
) {
160 e
->f
= e
->t
= NO_JUMP
;
166 static void codename (LexState
*ls
, expdesc
*e
) {
167 codestring(e
, str_checkname(ls
));
172 ** Register a new local variable in the active 'Proto' (for debug
175 static int registerlocalvar (LexState
*ls
, FuncState
*fs
, TString
*varname
) {
177 int oldsize
= f
->sizelocvars
;
178 luaM_growvector(ls
->L
, f
->locvars
, fs
->ndebugvars
, f
->sizelocvars
,
179 LocVar
, SHRT_MAX
, "local variables");
180 while (oldsize
< f
->sizelocvars
)
181 f
->locvars
[oldsize
++].varname
= NULL
;
182 f
->locvars
[fs
->ndebugvars
].varname
= varname
;
183 f
->locvars
[fs
->ndebugvars
].startpc
= fs
->pc
;
184 luaC_objbarrier(ls
->L
, f
, varname
);
185 return fs
->ndebugvars
++;
190 ** Create a new local variable with the given 'name'. Return its index
193 static int new_localvar (LexState
*ls
, TString
*name
) {
194 lua_State
*L
= ls
->L
;
195 FuncState
*fs
= ls
->fs
;
196 Dyndata
*dyd
= ls
->dyd
;
198 checklimit(fs
, dyd
->actvar
.n
+ 1 - fs
->firstlocal
,
199 MAXVARS
, "local variables");
200 luaM_growvector(L
, dyd
->actvar
.arr
, dyd
->actvar
.n
+ 1,
201 dyd
->actvar
.size
, Vardesc
, USHRT_MAX
, "local variables");
202 var
= &dyd
->actvar
.arr
[dyd
->actvar
.n
++];
203 var
->vd
.kind
= VDKREG
; /* default */
205 return dyd
->actvar
.n
- 1 - fs
->firstlocal
;
208 #define new_localvarliteral(ls,v) \
210 luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1));
215 ** Return the "variable description" (Vardesc) of a given variable.
216 ** (Unless noted otherwise, all variables are referred to by their
217 ** compiler indices.)
219 static Vardesc
*getlocalvardesc (FuncState
*fs
, int vidx
) {
220 return &fs
->ls
->dyd
->actvar
.arr
[fs
->firstlocal
+ vidx
];
225 ** Convert 'nvar', a compiler index level, to its corresponding
226 ** register. For that, search for the highest variable below that level
227 ** that is in a register and uses its register index ('ridx') plus one.
229 static int reglevel (FuncState
*fs
, int nvar
) {
231 Vardesc
*vd
= getlocalvardesc(fs
, nvar
); /* get previous variable */
232 if (vd
->vd
.kind
!= RDKCTC
) /* is in a register? */
233 return vd
->vd
.ridx
+ 1;
235 return 0; /* no variables in registers */
240 ** Return the number of variables in the register stack for the given
243 int luaY_nvarstack (FuncState
*fs
) {
244 return reglevel(fs
, fs
->nactvar
);
249 ** Get the debug-information entry for current variable 'vidx'.
251 static LocVar
*localdebuginfo (FuncState
*fs
, int vidx
) {
252 Vardesc
*vd
= getlocalvardesc(fs
, vidx
);
253 if (vd
->vd
.kind
== RDKCTC
)
254 return NULL
; /* no debug info. for constants */
256 int idx
= vd
->vd
.pidx
;
257 lua_assert(idx
< fs
->ndebugvars
);
258 return &fs
->f
->locvars
[idx
];
264 ** Create an expression representing variable 'vidx'
266 static void init_var (FuncState
*fs
, expdesc
*e
, int vidx
) {
267 e
->f
= e
->t
= NO_JUMP
;
269 e
->u
.var
.vidx
= vidx
;
270 e
->u
.var
.ridx
= getlocalvardesc(fs
, vidx
)->vd
.ridx
;
275 ** Raises an error if variable described by 'e' is read only
277 static void check_readonly (LexState
*ls
, expdesc
*e
) {
278 FuncState
*fs
= ls
->fs
;
279 TString
*varname
= NULL
; /* to be set if variable is const */
282 varname
= ls
->dyd
->actvar
.arr
[e
->u
.info
].vd
.name
;
286 Vardesc
*vardesc
= getlocalvardesc(fs
, e
->u
.var
.vidx
);
287 if (vardesc
->vd
.kind
!= VDKREG
) /* not a regular variable? */
288 varname
= vardesc
->vd
.name
;
292 Upvaldesc
*up
= &fs
->f
->upvalues
[e
->u
.info
];
293 if (up
->kind
!= VDKREG
)
298 return; /* other cases cannot be read-only */
301 const char *msg
= luaO_pushfstring(ls
->L
,
302 "attempt to assign to const variable '%s'", getstr(varname
));
303 luaK_semerror(ls
, msg
); /* error */
309 ** Start the scope for the last 'nvars' created variables.
311 static void adjustlocalvars (LexState
*ls
, int nvars
) {
312 FuncState
*fs
= ls
->fs
;
313 int reglevel
= luaY_nvarstack(fs
);
315 for (i
= 0; i
< nvars
; i
++) {
316 int vidx
= fs
->nactvar
++;
317 Vardesc
*var
= getlocalvardesc(fs
, vidx
);
318 var
->vd
.ridx
= reglevel
++;
319 var
->vd
.pidx
= registerlocalvar(ls
, fs
, var
->vd
.name
);
325 ** Close the scope for all variables up to level 'tolevel'.
328 static void removevars (FuncState
*fs
, int tolevel
) {
329 fs
->ls
->dyd
->actvar
.n
-= (fs
->nactvar
- tolevel
);
330 while (fs
->nactvar
> tolevel
) {
331 LocVar
*var
= localdebuginfo(fs
, --fs
->nactvar
);
332 if (var
) /* does it have debug information? */
339 ** Search the upvalues of the function 'fs' for one
340 ** with the given 'name'.
342 static int searchupvalue (FuncState
*fs
, TString
*name
) {
344 Upvaldesc
*up
= fs
->f
->upvalues
;
345 for (i
= 0; i
< fs
->nups
; i
++) {
346 if (eqstr(up
[i
].name
, name
)) return i
;
348 return -1; /* not found */
352 static Upvaldesc
*allocupvalue (FuncState
*fs
) {
354 int oldsize
= f
->sizeupvalues
;
355 checklimit(fs
, fs
->nups
+ 1, MAXUPVAL
, "upvalues");
356 luaM_growvector(fs
->ls
->L
, f
->upvalues
, fs
->nups
, f
->sizeupvalues
,
357 Upvaldesc
, MAXUPVAL
, "upvalues");
358 while (oldsize
< f
->sizeupvalues
)
359 f
->upvalues
[oldsize
++].name
= NULL
;
360 return &f
->upvalues
[fs
->nups
++];
364 static int newupvalue (FuncState
*fs
, TString
*name
, expdesc
*v
) {
365 Upvaldesc
*up
= allocupvalue(fs
);
366 FuncState
*prev
= fs
->prev
;
367 if (v
->k
== VLOCAL
) {
369 up
->idx
= v
->u
.var
.ridx
;
370 up
->kind
= getlocalvardesc(prev
, v
->u
.var
.vidx
)->vd
.kind
;
371 lua_assert(eqstr(name
, getlocalvardesc(prev
, v
->u
.var
.vidx
)->vd
.name
));
375 up
->idx
= cast_byte(v
->u
.info
);
376 up
->kind
= prev
->f
->upvalues
[v
->u
.info
].kind
;
377 lua_assert(eqstr(name
, prev
->f
->upvalues
[v
->u
.info
].name
));
380 luaC_objbarrier(fs
->ls
->L
, fs
->f
, name
);
386 ** Look for an active local variable with the name 'n' in the
387 ** function 'fs'. If found, initialize 'var' with it and return
388 ** its expression kind; otherwise return -1.
390 static int searchvar (FuncState
*fs
, TString
*n
, expdesc
*var
) {
392 for (i
= cast_int(fs
->nactvar
) - 1; i
>= 0; i
--) {
393 Vardesc
*vd
= getlocalvardesc(fs
, i
);
394 if (eqstr(n
, vd
->vd
.name
)) { /* found? */
395 if (vd
->vd
.kind
== RDKCTC
) /* compile-time constant? */
396 init_exp(var
, VCONST
, fs
->firstlocal
+ i
);
397 else /* real variable */
398 init_var(fs
, var
, i
);
402 return -1; /* not found */
407 ** Mark block where variable at given level was defined
408 ** (to emit close instructions later).
410 static void markupval (FuncState
*fs
, int level
) {
411 BlockCnt
*bl
= fs
->bl
;
412 while (bl
->nactvar
> level
)
420 ** Find a variable with the given name 'n'. If it is an upvalue, add
421 ** this upvalue into all intermediate functions. If it is a global, set
422 ** 'var' as 'void' as a flag.
424 static void singlevaraux (FuncState
*fs
, TString
*n
, expdesc
*var
, int base
) {
425 if (fs
== NULL
) /* no more levels? */
426 init_exp(var
, VVOID
, 0); /* default is global */
428 int v
= searchvar(fs
, n
, var
); /* look up locals at current level */
429 if (v
>= 0) { /* found? */
430 if (v
== VLOCAL
&& !base
)
431 markupval(fs
, var
->u
.var
.vidx
); /* local will be used as an upval */
433 else { /* not found as local at current level; try upvalues */
434 int idx
= searchupvalue(fs
, n
); /* try existing upvalues */
435 if (idx
< 0) { /* not found? */
436 singlevaraux(fs
->prev
, n
, var
, 0); /* try upper levels */
437 if (var
->k
== VLOCAL
|| var
->k
== VUPVAL
) /* local or upvalue? */
438 idx
= newupvalue(fs
, n
, var
); /* will be a new upvalue */
439 else /* it is a global or a constant */
440 return; /* don't need to do anything at this level */
442 init_exp(var
, VUPVAL
, idx
); /* new or old upvalue */
449 ** Find a variable with the given name 'n', handling global variables
452 static void singlevar (LexState
*ls
, expdesc
*var
) {
453 TString
*varname
= str_checkname(ls
);
454 FuncState
*fs
= ls
->fs
;
455 singlevaraux(fs
, varname
, var
, 1);
456 if (var
->k
== VVOID
) { /* global name? */
458 singlevaraux(fs
, ls
->envn
, var
, 1); /* get environment variable */
459 lua_assert(var
->k
!= VVOID
); /* this one must exist */
460 codestring(&key
, varname
); /* key is variable name */
461 luaK_indexed(fs
, var
, &key
); /* env[varname] */
467 ** Adjust the number of results from an expression list 'e' with 'nexps'
468 ** expressions to 'nvars' values.
470 static void adjust_assign (LexState
*ls
, int nvars
, int nexps
, expdesc
*e
) {
471 FuncState
*fs
= ls
->fs
;
472 int needed
= nvars
- nexps
; /* extra values needed */
473 if (hasmultret(e
->k
)) { /* last expression has multiple returns? */
474 int extra
= needed
+ 1; /* discount last expression itself */
477 luaK_setreturns(fs
, e
, extra
); /* last exp. provides the difference */
480 if (e
->k
!= VVOID
) /* at least one expression? */
481 luaK_exp2nextreg(fs
, e
); /* close last expression */
482 if (needed
> 0) /* missing values? */
483 luaK_nil(fs
, fs
->freereg
, needed
); /* complete with nils */
486 luaK_reserveregs(fs
, needed
); /* registers for extra values */
487 else /* adding 'needed' is actually a subtraction */
488 fs
->freereg
+= needed
; /* remove extra values */
492 #define enterlevel(ls) luaE_incCstack(ls->L)
495 #define leavelevel(ls) ((ls)->L->nCcalls--)
499 ** Generates an error that a goto jumps into the scope of some
502 static l_noret
jumpscopeerror (LexState
*ls
, Labeldesc
*gt
) {
503 const char *varname
= getstr(getlocalvardesc(ls
->fs
, gt
->nactvar
)->vd
.name
);
504 const char *msg
= "<goto %s> at line %d jumps into the scope of local '%s'";
505 msg
= luaO_pushfstring(ls
->L
, msg
, getstr(gt
->name
), gt
->line
, varname
);
506 luaK_semerror(ls
, msg
); /* raise the error */
511 ** Solves the goto at index 'g' to given 'label' and removes it
512 ** from the list of pending goto's.
513 ** If it jumps into the scope of some variable, raises an error.
515 static void solvegoto (LexState
*ls
, int g
, Labeldesc
*label
) {
517 Labellist
*gl
= &ls
->dyd
->gt
; /* list of goto's */
518 Labeldesc
*gt
= &gl
->arr
[g
]; /* goto to be resolved */
519 lua_assert(eqstr(gt
->name
, label
->name
));
520 if (l_unlikely(gt
->nactvar
< label
->nactvar
)) /* enter some scope? */
521 jumpscopeerror(ls
, gt
);
522 luaK_patchlist(ls
->fs
, gt
->pc
, label
->pc
);
523 for (i
= g
; i
< gl
->n
- 1; i
++) /* remove goto from pending list */
524 gl
->arr
[i
] = gl
->arr
[i
+ 1];
530 ** Search for an active label with the given name.
532 static Labeldesc
*findlabel (LexState
*ls
, TString
*name
) {
534 Dyndata
*dyd
= ls
->dyd
;
535 /* check labels in current function for a match */
536 for (i
= ls
->fs
->firstlabel
; i
< dyd
->label
.n
; i
++) {
537 Labeldesc
*lb
= &dyd
->label
.arr
[i
];
538 if (eqstr(lb
->name
, name
)) /* correct label? */
541 return NULL
; /* label not found */
546 ** Adds a new label/goto in the corresponding list.
548 static int newlabelentry (LexState
*ls
, Labellist
*l
, TString
*name
,
551 luaM_growvector(ls
->L
, l
->arr
, n
, l
->size
,
552 Labeldesc
, SHRT_MAX
, "labels/gotos");
553 l
->arr
[n
].name
= name
;
554 l
->arr
[n
].line
= line
;
555 l
->arr
[n
].nactvar
= ls
->fs
->nactvar
;
563 static int newgotoentry (LexState
*ls
, TString
*name
, int line
, int pc
) {
564 return newlabelentry(ls
, &ls
->dyd
->gt
, name
, line
, pc
);
569 ** Solves forward jumps. Check whether new label 'lb' matches any
570 ** pending gotos in current block and solves them. Return true
571 ** if any of the goto's need to close upvalues.
573 static int solvegotos (LexState
*ls
, Labeldesc
*lb
) {
574 Labellist
*gl
= &ls
->dyd
->gt
;
575 int i
= ls
->fs
->bl
->firstgoto
;
578 if (eqstr(gl
->arr
[i
].name
, lb
->name
)) {
579 needsclose
|= gl
->arr
[i
].close
;
580 solvegoto(ls
, i
, lb
); /* will remove 'i' from the list */
590 ** Create a new label with the given 'name' at the given 'line'.
591 ** 'last' tells whether label is the last non-op statement in its
592 ** block. Solves all pending goto's to this new label and adds
593 ** a close instruction if necessary.
594 ** Returns true iff it added a close instruction.
596 static int createlabel (LexState
*ls
, TString
*name
, int line
,
598 FuncState
*fs
= ls
->fs
;
599 Labellist
*ll
= &ls
->dyd
->label
;
600 int l
= newlabelentry(ls
, ll
, name
, line
, luaK_getlabel(fs
));
601 if (last
) { /* label is last no-op statement in the block? */
602 /* assume that locals are already out of scope */
603 ll
->arr
[l
].nactvar
= fs
->bl
->nactvar
;
605 if (solvegotos(ls
, &ll
->arr
[l
])) { /* need close? */
606 luaK_codeABC(fs
, OP_CLOSE
, luaY_nvarstack(fs
), 0, 0);
614 ** Adjust pending gotos to outer level of a block.
616 static void movegotosout (FuncState
*fs
, BlockCnt
*bl
) {
618 Labellist
*gl
= &fs
->ls
->dyd
->gt
;
619 /* correct pending gotos to current block */
620 for (i
= bl
->firstgoto
; i
< gl
->n
; i
++) { /* for each pending goto */
621 Labeldesc
*gt
= &gl
->arr
[i
];
622 /* leaving a variable scope? */
623 if (reglevel(fs
, gt
->nactvar
) > reglevel(fs
, bl
->nactvar
))
624 gt
->close
|= bl
->upval
; /* jump may need a close */
625 gt
->nactvar
= bl
->nactvar
; /* update goto level */
630 static void enterblock (FuncState
*fs
, BlockCnt
*bl
, lu_byte isloop
) {
632 bl
->nactvar
= fs
->nactvar
;
633 bl
->firstlabel
= fs
->ls
->dyd
->label
.n
;
634 bl
->firstgoto
= fs
->ls
->dyd
->gt
.n
;
636 bl
->insidetbc
= (fs
->bl
!= NULL
&& fs
->bl
->insidetbc
);
637 bl
->previous
= fs
->bl
;
639 lua_assert(fs
->freereg
== luaY_nvarstack(fs
));
644 ** generates an error for an undefined 'goto'.
646 static l_noret
undefgoto (LexState
*ls
, Labeldesc
*gt
) {
648 if (eqstr(gt
->name
, luaS_newliteral(ls
->L
, "break"))) {
649 msg
= "break outside loop at line %d";
650 msg
= luaO_pushfstring(ls
->L
, msg
, gt
->line
);
653 msg
= "no visible label '%s' for <goto> at line %d";
654 msg
= luaO_pushfstring(ls
->L
, msg
, getstr(gt
->name
), gt
->line
);
656 luaK_semerror(ls
, msg
);
660 static void leaveblock (FuncState
*fs
) {
661 BlockCnt
*bl
= fs
->bl
;
662 LexState
*ls
= fs
->ls
;
664 int stklevel
= reglevel(fs
, bl
->nactvar
); /* level outside the block */
665 if (bl
->isloop
) /* fix pending breaks? */
666 hasclose
= createlabel(ls
, luaS_newliteral(ls
->L
, "break"), 0, 0);
667 if (!hasclose
&& bl
->previous
&& bl
->upval
)
668 luaK_codeABC(fs
, OP_CLOSE
, stklevel
, 0, 0);
669 fs
->bl
= bl
->previous
;
670 removevars(fs
, bl
->nactvar
);
671 lua_assert(bl
->nactvar
== fs
->nactvar
);
672 fs
->freereg
= stklevel
; /* free registers */
673 ls
->dyd
->label
.n
= bl
->firstlabel
; /* remove local labels */
674 if (bl
->previous
) /* inner block? */
675 movegotosout(fs
, bl
); /* update pending gotos to outer block */
677 if (bl
->firstgoto
< ls
->dyd
->gt
.n
) /* pending gotos in outer block? */
678 undefgoto(ls
, &ls
->dyd
->gt
.arr
[bl
->firstgoto
]); /* error */
684 ** adds a new prototype into list of prototypes
686 static Proto
*addprototype (LexState
*ls
) {
688 lua_State
*L
= ls
->L
;
689 FuncState
*fs
= ls
->fs
;
690 Proto
*f
= fs
->f
; /* prototype of current function */
691 if (fs
->np
>= f
->sizep
) {
692 int oldsize
= f
->sizep
;
693 luaM_growvector(L
, f
->p
, fs
->np
, f
->sizep
, Proto
*, MAXARG_Bx
, "functions");
694 while (oldsize
< f
->sizep
)
695 f
->p
[oldsize
++] = NULL
;
697 f
->p
[fs
->np
++] = clp
= luaF_newproto(L
);
698 luaC_objbarrier(L
, f
, clp
);
704 ** codes instruction to create new closure in parent function.
705 ** The OP_CLOSURE instruction uses the last available register,
706 ** so that, if it invokes the GC, the GC knows which registers
707 ** are in use at that time.
710 static void codeclosure (LexState
*ls
, expdesc
*v
) {
711 FuncState
*fs
= ls
->fs
->prev
;
712 init_exp(v
, VRELOC
, luaK_codeABx(fs
, OP_CLOSURE
, 0, fs
->np
- 1));
713 luaK_exp2nextreg(fs
, v
); /* fix it at the last register */
717 static void open_func (LexState
*ls
, FuncState
*fs
, BlockCnt
*bl
) {
719 fs
->prev
= ls
->fs
; /* linked list of funcstates */
723 fs
->previousline
= f
->linedefined
;
728 fs
->nabslineinfo
= 0;
734 fs
->firstlocal
= ls
->dyd
->actvar
.n
;
735 fs
->firstlabel
= ls
->dyd
->label
.n
;
737 f
->source
= ls
->source
;
738 luaC_objbarrier(ls
->L
, f
, f
->source
);
739 f
->maxstacksize
= 2; /* registers 0/1 are always valid */
740 enterblock(fs
, bl
, 0);
744 static void close_func (LexState
*ls
) {
745 lua_State
*L
= ls
->L
;
746 FuncState
*fs
= ls
->fs
;
748 luaK_ret(fs
, luaY_nvarstack(fs
), 0); /* final return */
750 lua_assert(fs
->bl
== NULL
);
752 luaM_shrinkvector(L
, f
->code
, f
->sizecode
, fs
->pc
, Instruction
);
753 luaM_shrinkvector(L
, f
->lineinfo
, f
->sizelineinfo
, fs
->pc
, ls_byte
);
754 luaM_shrinkvector(L
, f
->abslineinfo
, f
->sizeabslineinfo
,
755 fs
->nabslineinfo
, AbsLineInfo
);
756 luaM_shrinkvector(L
, f
->k
, f
->sizek
, fs
->nk
, TValue
);
757 luaM_shrinkvector(L
, f
->p
, f
->sizep
, fs
->np
, Proto
*);
758 luaM_shrinkvector(L
, f
->locvars
, f
->sizelocvars
, fs
->ndebugvars
, LocVar
);
759 luaM_shrinkvector(L
, f
->upvalues
, f
->sizeupvalues
, fs
->nups
, Upvaldesc
);
766 /*============================================================*/
768 /*============================================================*/
772 ** check whether current token is in the follow set of a block.
773 ** 'until' closes syntactical blocks, but do not close scope,
774 ** so it is handled in separate.
776 static int block_follow (LexState
*ls
, int withuntil
) {
777 switch (ls
->t
.token
) {
778 case TK_ELSE
: case TK_ELSEIF
:
779 case TK_END
: case TK_EOS
:
781 case TK_UNTIL
: return withuntil
;
787 static void statlist (LexState
*ls
) {
788 /* statlist -> { stat [';'] } */
789 while (!block_follow(ls
, 1)) {
790 if (ls
->t
.token
== TK_RETURN
) {
792 return; /* 'return' must be last statement */
799 static void fieldsel (LexState
*ls
, expdesc
*v
) {
800 /* fieldsel -> ['.' | ':'] NAME */
801 FuncState
*fs
= ls
->fs
;
803 luaK_exp2anyregup(fs
, v
);
804 luaX_next(ls
); /* skip the dot or colon */
806 luaK_indexed(fs
, v
, &key
);
810 static void yindex (LexState
*ls
, expdesc
*v
) {
811 /* index -> '[' expr ']' */
812 luaX_next(ls
); /* skip the '[' */
814 luaK_exp2val(ls
->fs
, v
);
820 ** {======================================================================
821 ** Rules for Constructors
822 ** =======================================================================
826 typedef struct ConsControl
{
827 expdesc v
; /* last list item read */
828 expdesc
*t
; /* table descriptor */
829 int nh
; /* total number of 'record' elements */
830 int na
; /* number of array elements already stored */
831 int tostore
; /* number of array elements pending to be stored */
835 static void recfield (LexState
*ls
, ConsControl
*cc
) {
836 /* recfield -> (NAME | '['exp']') = exp */
837 FuncState
*fs
= ls
->fs
;
838 int reg
= ls
->fs
->freereg
;
839 expdesc tab
, key
, val
;
840 if (ls
->t
.token
== TK_NAME
) {
841 checklimit(fs
, cc
->nh
, MAX_INT
, "items in a constructor");
844 else /* ls->t.token == '[' */
849 luaK_indexed(fs
, &tab
, &key
);
851 luaK_storevar(fs
, &tab
, &val
);
852 fs
->freereg
= reg
; /* free registers */
856 static void closelistfield (FuncState
*fs
, ConsControl
*cc
) {
857 if (cc
->v
.k
== VVOID
) return; /* there is no list item */
858 luaK_exp2nextreg(fs
, &cc
->v
);
860 if (cc
->tostore
== LFIELDS_PER_FLUSH
) {
861 luaK_setlist(fs
, cc
->t
->u
.info
, cc
->na
, cc
->tostore
); /* flush */
862 cc
->na
+= cc
->tostore
;
863 cc
->tostore
= 0; /* no more items pending */
868 static void lastlistfield (FuncState
*fs
, ConsControl
*cc
) {
869 if (cc
->tostore
== 0) return;
870 if (hasmultret(cc
->v
.k
)) {
871 luaK_setmultret(fs
, &cc
->v
);
872 luaK_setlist(fs
, cc
->t
->u
.info
, cc
->na
, LUA_MULTRET
);
873 cc
->na
--; /* do not count last expression (unknown number of elements) */
876 if (cc
->v
.k
!= VVOID
)
877 luaK_exp2nextreg(fs
, &cc
->v
);
878 luaK_setlist(fs
, cc
->t
->u
.info
, cc
->na
, cc
->tostore
);
880 cc
->na
+= cc
->tostore
;
884 static void listfield (LexState
*ls
, ConsControl
*cc
) {
885 /* listfield -> exp */
891 static void field (LexState
*ls
, ConsControl
*cc
) {
892 /* field -> listfield | recfield */
893 switch(ls
->t
.token
) {
894 case TK_NAME
: { /* may be 'listfield' or 'recfield' */
895 if (luaX_lookahead(ls
) != '=') /* expression? */
913 static void constructor (LexState
*ls
, expdesc
*t
) {
914 /* constructor -> '{' [ field { sep field } [sep] ] '}'
916 FuncState
*fs
= ls
->fs
;
917 int line
= ls
->linenumber
;
918 int pc
= luaK_codeABC(fs
, OP_NEWTABLE
, 0, 0, 0);
920 luaK_code(fs
, 0); /* space for extra arg. */
921 cc
.na
= cc
.nh
= cc
.tostore
= 0;
923 init_exp(t
, VNONRELOC
, fs
->freereg
); /* table will be at stack top */
924 luaK_reserveregs(fs
, 1);
925 init_exp(&cc
.v
, VVOID
, 0); /* no value (yet) */
928 lua_assert(cc
.v
.k
== VVOID
|| cc
.tostore
> 0);
929 if (ls
->t
.token
== '}') break;
930 closelistfield(fs
, &cc
);
932 } while (testnext(ls
, ',') || testnext(ls
, ';'));
933 check_match(ls
, '}', '{', line
);
934 lastlistfield(fs
, &cc
);
935 luaK_settablesize(fs
, pc
, t
->u
.info
, cc
.na
, cc
.nh
);
938 /* }====================================================================== */
941 static void setvararg (FuncState
*fs
, int nparams
) {
942 fs
->f
->is_vararg
= 1;
943 luaK_codeABC(fs
, OP_VARARGPREP
, nparams
, 0, 0);
947 static void parlist (LexState
*ls
) {
948 /* parlist -> [ {NAME ','} (NAME | '...') ] */
949 FuncState
*fs
= ls
->fs
;
953 if (ls
->t
.token
!= ')') { /* is 'parlist' not empty? */
955 switch (ls
->t
.token
) {
957 new_localvar(ls
, str_checkname(ls
));
966 default: luaX_syntaxerror(ls
, "<name> or '...' expected");
968 } while (!isvararg
&& testnext(ls
, ','));
970 adjustlocalvars(ls
, nparams
);
971 f
->numparams
= cast_byte(fs
->nactvar
);
973 setvararg(fs
, f
->numparams
); /* declared vararg */
974 luaK_reserveregs(fs
, fs
->nactvar
); /* reserve registers for parameters */
978 static void body (LexState
*ls
, expdesc
*e
, int ismethod
, int line
) {
979 /* body -> '(' parlist ')' block END */
982 new_fs
.f
= addprototype(ls
);
983 new_fs
.f
->linedefined
= line
;
984 open_func(ls
, &new_fs
, &bl
);
987 new_localvarliteral(ls
, "self"); /* create 'self' parameter */
988 adjustlocalvars(ls
, 1);
993 new_fs
.f
->lastlinedefined
= ls
->linenumber
;
994 check_match(ls
, TK_END
, TK_FUNCTION
, line
);
1000 static int explist (LexState
*ls
, expdesc
*v
) {
1001 /* explist -> expr { ',' expr } */
1002 int n
= 1; /* at least one expression */
1004 while (testnext(ls
, ',')) {
1005 luaK_exp2nextreg(ls
->fs
, v
);
1013 static void funcargs (LexState
*ls
, expdesc
*f
, int line
) {
1014 FuncState
*fs
= ls
->fs
;
1017 switch (ls
->t
.token
) {
1018 case '(': { /* funcargs -> '(' [ explist ] ')' */
1020 if (ls
->t
.token
== ')') /* arg list is empty? */
1024 if (hasmultret(args
.k
))
1025 luaK_setmultret(fs
, &args
);
1027 check_match(ls
, ')', '(', line
);
1030 case '{': { /* funcargs -> constructor */
1031 constructor(ls
, &args
);
1034 case TK_STRING
: { /* funcargs -> STRING */
1035 codestring(&args
, ls
->t
.seminfo
.ts
);
1036 luaX_next(ls
); /* must use 'seminfo' before 'next' */
1040 luaX_syntaxerror(ls
, "function arguments expected");
1043 lua_assert(f
->k
== VNONRELOC
);
1044 base
= f
->u
.info
; /* base register for call */
1045 if (hasmultret(args
.k
))
1046 nparams
= LUA_MULTRET
; /* open call */
1048 if (args
.k
!= VVOID
)
1049 luaK_exp2nextreg(fs
, &args
); /* close last argument */
1050 nparams
= fs
->freereg
- (base
+1);
1052 init_exp(f
, VCALL
, luaK_codeABC(fs
, OP_CALL
, base
, nparams
+1, 2));
1053 luaK_fixline(fs
, line
);
1054 fs
->freereg
= base
+1; /* call remove function and arguments and leaves
1055 (unless changed) one result */
1062 ** {======================================================================
1063 ** Expression parsing
1064 ** =======================================================================
1068 static void primaryexp (LexState
*ls
, expdesc
*v
) {
1069 /* primaryexp -> NAME | '(' expr ')' */
1070 switch (ls
->t
.token
) {
1072 int line
= ls
->linenumber
;
1075 check_match(ls
, ')', '(', line
);
1076 luaK_dischargevars(ls
->fs
, v
);
1084 luaX_syntaxerror(ls
, "unexpected symbol");
1090 static void suffixedexp (LexState
*ls
, expdesc
*v
) {
1092 primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
1093 FuncState
*fs
= ls
->fs
;
1094 int line
= ls
->linenumber
;
1097 switch (ls
->t
.token
) {
1098 case '.': { /* fieldsel */
1102 case '[': { /* '[' exp ']' */
1104 luaK_exp2anyregup(fs
, v
);
1106 luaK_indexed(fs
, v
, &key
);
1109 case ':': { /* ':' NAME funcargs */
1113 luaK_self(fs
, v
, &key
);
1114 funcargs(ls
, v
, line
);
1117 case '(': case TK_STRING
: case '{': { /* funcargs */
1118 luaK_exp2nextreg(fs
, v
);
1119 funcargs(ls
, v
, line
);
1128 static void simpleexp (LexState
*ls
, expdesc
*v
) {
1129 /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
1130 constructor | FUNCTION body | suffixedexp */
1131 switch (ls
->t
.token
) {
1133 init_exp(v
, VKFLT
, 0);
1134 v
->u
.nval
= ls
->t
.seminfo
.r
;
1138 init_exp(v
, VKINT
, 0);
1139 v
->u
.ival
= ls
->t
.seminfo
.i
;
1143 codestring(v
, ls
->t
.seminfo
.ts
);
1147 init_exp(v
, VNIL
, 0);
1151 init_exp(v
, VTRUE
, 0);
1155 init_exp(v
, VFALSE
, 0);
1158 case TK_DOTS
: { /* vararg */
1159 FuncState
*fs
= ls
->fs
;
1160 check_condition(ls
, fs
->f
->is_vararg
,
1161 "cannot use '...' outside a vararg function");
1162 init_exp(v
, VVARARG
, luaK_codeABC(fs
, OP_VARARG
, 0, 0, 1));
1165 case '{': { /* constructor */
1171 body(ls
, v
, 0, ls
->linenumber
);
1183 static UnOpr
getunopr (int op
) {
1185 case TK_NOT
: return OPR_NOT
;
1186 case '-': return OPR_MINUS
;
1187 case '~': return OPR_BNOT
;
1188 case '#': return OPR_LEN
;
1189 default: return OPR_NOUNOPR
;
1194 static BinOpr
getbinopr (int op
) {
1196 case '+': return OPR_ADD
;
1197 case '-': return OPR_SUB
;
1198 case '*': return OPR_MUL
;
1199 case '%': return OPR_MOD
;
1200 case '^': return OPR_POW
;
1201 case '/': return OPR_DIV
;
1202 case TK_IDIV
: return OPR_IDIV
;
1203 case '&': return OPR_BAND
;
1204 case '|': return OPR_BOR
;
1205 case '~': return OPR_BXOR
;
1206 case TK_SHL
: return OPR_SHL
;
1207 case TK_SHR
: return OPR_SHR
;
1208 case TK_CONCAT
: return OPR_CONCAT
;
1209 case TK_NE
: return OPR_NE
;
1210 case TK_EQ
: return OPR_EQ
;
1211 case '<': return OPR_LT
;
1212 case TK_LE
: return OPR_LE
;
1213 case '>': return OPR_GT
;
1214 case TK_GE
: return OPR_GE
;
1215 case TK_AND
: return OPR_AND
;
1216 case TK_OR
: return OPR_OR
;
1217 default: return OPR_NOBINOPR
;
1223 ** Priority table for binary operators.
1225 static const struct {
1226 lu_byte left
; /* left priority for each binary operator */
1227 lu_byte right
; /* right priority */
1228 } priority
[] = { /* ORDER OPR */
1229 {10, 10}, {10, 10}, /* '+' '-' */
1230 {11, 11}, {11, 11}, /* '*' '%' */
1231 {14, 13}, /* '^' (right associative) */
1232 {11, 11}, {11, 11}, /* '/' '//' */
1233 {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
1234 {7, 7}, {7, 7}, /* '<<' '>>' */
1235 {9, 8}, /* '..' (right associative) */
1236 {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
1237 {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
1238 {2, 2}, {1, 1} /* and, or */
1241 #define UNARY_PRIORITY 12 /* priority for unary operators */
1245 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1246 ** where 'binop' is any binary operator with a priority higher than 'limit'
1248 static BinOpr
subexpr (LexState
*ls
, expdesc
*v
, int limit
) {
1252 uop
= getunopr(ls
->t
.token
);
1253 if (uop
!= OPR_NOUNOPR
) { /* prefix (unary) operator? */
1254 int line
= ls
->linenumber
;
1255 luaX_next(ls
); /* skip operator */
1256 subexpr(ls
, v
, UNARY_PRIORITY
);
1257 luaK_prefix(ls
->fs
, uop
, v
, line
);
1259 else simpleexp(ls
, v
);
1260 /* expand while operators have priorities higher than 'limit' */
1261 op
= getbinopr(ls
->t
.token
);
1262 while (op
!= OPR_NOBINOPR
&& priority
[op
].left
> limit
) {
1265 int line
= ls
->linenumber
;
1266 luaX_next(ls
); /* skip operator */
1267 luaK_infix(ls
->fs
, op
, v
);
1268 /* read sub-expression with higher priority */
1269 nextop
= subexpr(ls
, &v2
, priority
[op
].right
);
1270 luaK_posfix(ls
->fs
, op
, v
, &v2
, line
);
1274 return op
; /* return first untreated operator */
1278 static void expr (LexState
*ls
, expdesc
*v
) {
1282 /* }==================================================================== */
1287 ** {======================================================================
1288 ** Rules for Statements
1289 ** =======================================================================
1293 static void block (LexState
*ls
) {
1294 /* block -> statlist */
1295 FuncState
*fs
= ls
->fs
;
1297 enterblock(fs
, &bl
, 0);
1304 ** structure to chain all variables in the left-hand side of an
1308 struct LHS_assign
*prev
;
1309 expdesc v
; /* variable (global, local, upvalue, or indexed) */
1314 ** check whether, in an assignment to an upvalue/local variable, the
1315 ** upvalue/local variable is begin used in a previous assignment to a
1316 ** table. If so, save original upvalue/local value in a safe place and
1317 ** use this safe copy in the previous assignment.
1319 static void check_conflict (LexState
*ls
, struct LHS_assign
*lh
, expdesc
*v
) {
1320 FuncState
*fs
= ls
->fs
;
1321 int extra
= fs
->freereg
; /* eventual position to save local variable */
1323 for (; lh
; lh
= lh
->prev
) { /* check all previous assignments */
1324 if (vkisindexed(lh
->v
.k
)) { /* assignment to table field? */
1325 if (lh
->v
.k
== VINDEXUP
) { /* is table an upvalue? */
1326 if (v
->k
== VUPVAL
&& lh
->v
.u
.ind
.t
== v
->u
.info
) {
1327 conflict
= 1; /* table is the upvalue being assigned now */
1328 lh
->v
.k
= VINDEXSTR
;
1329 lh
->v
.u
.ind
.t
= extra
; /* assignment will use safe copy */
1332 else { /* table is a register */
1333 if (v
->k
== VLOCAL
&& lh
->v
.u
.ind
.t
== v
->u
.var
.ridx
) {
1334 conflict
= 1; /* table is the local being assigned now */
1335 lh
->v
.u
.ind
.t
= extra
; /* assignment will use safe copy */
1337 /* is index the local being assigned? */
1338 if (lh
->v
.k
== VINDEXED
&& v
->k
== VLOCAL
&&
1339 lh
->v
.u
.ind
.idx
== v
->u
.var
.ridx
) {
1341 lh
->v
.u
.ind
.idx
= extra
; /* previous assignment will use safe copy */
1347 /* copy upvalue/local value to a temporary (in position 'extra') */
1349 luaK_codeABC(fs
, OP_MOVE
, extra
, v
->u
.var
.ridx
, 0);
1351 luaK_codeABC(fs
, OP_GETUPVAL
, extra
, v
->u
.info
, 0);
1352 luaK_reserveregs(fs
, 1);
1357 ** Parse and compile a multiple assignment. The first "variable"
1358 ** (a 'suffixedexp') was already read by the caller.
1360 ** assignment -> suffixedexp restassign
1361 ** restassign -> ',' suffixedexp restassign | '=' explist
1363 static void restassign (LexState
*ls
, struct LHS_assign
*lh
, int nvars
) {
1365 check_condition(ls
, vkisvar(lh
->v
.k
), "syntax error");
1366 check_readonly(ls
, &lh
->v
);
1367 if (testnext(ls
, ',')) { /* restassign -> ',' suffixedexp restassign */
1368 struct LHS_assign nv
;
1370 suffixedexp(ls
, &nv
.v
);
1371 if (!vkisindexed(nv
.v
.k
))
1372 check_conflict(ls
, lh
, &nv
.v
);
1373 enterlevel(ls
); /* control recursion depth */
1374 restassign(ls
, &nv
, nvars
+1);
1377 else { /* restassign -> '=' explist */
1380 nexps
= explist(ls
, &e
);
1382 adjust_assign(ls
, nvars
, nexps
, &e
);
1384 luaK_setoneret(ls
->fs
, &e
); /* close last expression */
1385 luaK_storevar(ls
->fs
, &lh
->v
, &e
);
1386 return; /* avoid default */
1389 init_exp(&e
, VNONRELOC
, ls
->fs
->freereg
-1); /* default assignment */
1390 luaK_storevar(ls
->fs
, &lh
->v
, &e
);
1394 static int cond (LexState
*ls
) {
1397 expr(ls
, &v
); /* read condition */
1398 if (v
.k
== VNIL
) v
.k
= VFALSE
; /* 'falses' are all equal here */
1399 luaK_goiftrue(ls
->fs
, &v
);
1404 static void gotostat (LexState
*ls
) {
1405 FuncState
*fs
= ls
->fs
;
1406 int line
= ls
->linenumber
;
1407 TString
*name
= str_checkname(ls
); /* label's name */
1408 Labeldesc
*lb
= findlabel(ls
, name
);
1409 if (lb
== NULL
) /* no label? */
1410 /* forward jump; will be resolved when the label is declared */
1411 newgotoentry(ls
, name
, line
, luaK_jump(fs
));
1412 else { /* found a label */
1413 /* backward jump; will be resolved here */
1414 int lblevel
= reglevel(fs
, lb
->nactvar
); /* label level */
1415 if (luaY_nvarstack(fs
) > lblevel
) /* leaving the scope of a variable? */
1416 luaK_codeABC(fs
, OP_CLOSE
, lblevel
, 0, 0);
1417 /* create jump and link it to the label */
1418 luaK_patchlist(fs
, luaK_jump(fs
), lb
->pc
);
1424 ** Break statement. Semantically equivalent to "goto break".
1426 static void breakstat (LexState
*ls
) {
1427 int line
= ls
->linenumber
;
1428 luaX_next(ls
); /* skip break */
1429 newgotoentry(ls
, luaS_newliteral(ls
->L
, "break"), line
, luaK_jump(ls
->fs
));
1434 ** Check whether there is already a label with the given 'name'.
1436 static void checkrepeated (LexState
*ls
, TString
*name
) {
1437 Labeldesc
*lb
= findlabel(ls
, name
);
1438 if (l_unlikely(lb
!= NULL
)) { /* already defined? */
1439 const char *msg
= "label '%s' already defined on line %d";
1440 msg
= luaO_pushfstring(ls
->L
, msg
, getstr(name
), lb
->line
);
1441 luaK_semerror(ls
, msg
); /* error */
1446 static void labelstat (LexState
*ls
, TString
*name
, int line
) {
1447 /* label -> '::' NAME '::' */
1448 checknext(ls
, TK_DBCOLON
); /* skip double colon */
1449 while (ls
->t
.token
== ';' || ls
->t
.token
== TK_DBCOLON
)
1450 statement(ls
); /* skip other no-op statements */
1451 checkrepeated(ls
, name
); /* check for repeated labels */
1452 createlabel(ls
, name
, line
, block_follow(ls
, 0));
1456 static void whilestat (LexState
*ls
, int line
) {
1457 /* whilestat -> WHILE cond DO block END */
1458 FuncState
*fs
= ls
->fs
;
1462 luaX_next(ls
); /* skip WHILE */
1463 whileinit
= luaK_getlabel(fs
);
1464 condexit
= cond(ls
);
1465 enterblock(fs
, &bl
, 1);
1466 checknext(ls
, TK_DO
);
1468 luaK_jumpto(fs
, whileinit
);
1469 check_match(ls
, TK_END
, TK_WHILE
, line
);
1471 luaK_patchtohere(fs
, condexit
); /* false conditions finish the loop */
1475 static void repeatstat (LexState
*ls
, int line
) {
1476 /* repeatstat -> REPEAT block UNTIL cond */
1478 FuncState
*fs
= ls
->fs
;
1479 int repeat_init
= luaK_getlabel(fs
);
1481 enterblock(fs
, &bl1
, 1); /* loop block */
1482 enterblock(fs
, &bl2
, 0); /* scope block */
1483 luaX_next(ls
); /* skip REPEAT */
1485 check_match(ls
, TK_UNTIL
, TK_REPEAT
, line
);
1486 condexit
= cond(ls
); /* read condition (inside scope block) */
1487 leaveblock(fs
); /* finish scope */
1488 if (bl2
.upval
) { /* upvalues? */
1489 int exit
= luaK_jump(fs
); /* normal exit must jump over fix */
1490 luaK_patchtohere(fs
, condexit
); /* repetition must close upvalues */
1491 luaK_codeABC(fs
, OP_CLOSE
, reglevel(fs
, bl2
.nactvar
), 0, 0);
1492 condexit
= luaK_jump(fs
); /* repeat after closing upvalues */
1493 luaK_patchtohere(fs
, exit
); /* normal exit comes to here */
1495 luaK_patchlist(fs
, condexit
, repeat_init
); /* close the loop */
1496 leaveblock(fs
); /* finish loop */
1501 ** Read an expression and generate code to put its results in next
1505 static void exp1 (LexState
*ls
) {
1508 luaK_exp2nextreg(ls
->fs
, &e
);
1509 lua_assert(e
.k
== VNONRELOC
);
1514 ** Fix for instruction at position 'pc' to jump to 'dest'.
1515 ** (Jump addresses are relative in Lua). 'back' true means
1518 static void fixforjump (FuncState
*fs
, int pc
, int dest
, int back
) {
1519 Instruction
*jmp
= &fs
->f
->code
[pc
];
1520 int offset
= dest
- (pc
+ 1);
1523 if (l_unlikely(offset
> MAXARG_Bx
))
1524 luaX_syntaxerror(fs
->ls
, "control structure too long");
1525 SETARG_Bx(*jmp
, offset
);
1530 ** Generate code for a 'for' loop.
1532 static void forbody (LexState
*ls
, int base
, int line
, int nvars
, int isgen
) {
1533 /* forbody -> DO block */
1534 static const OpCode forprep
[2] = {OP_FORPREP
, OP_TFORPREP
};
1535 static const OpCode forloop
[2] = {OP_FORLOOP
, OP_TFORLOOP
};
1537 FuncState
*fs
= ls
->fs
;
1539 checknext(ls
, TK_DO
);
1540 prep
= luaK_codeABx(fs
, forprep
[isgen
], base
, 0);
1541 enterblock(fs
, &bl
, 0); /* scope for declared variables */
1542 adjustlocalvars(ls
, nvars
);
1543 luaK_reserveregs(fs
, nvars
);
1545 leaveblock(fs
); /* end of scope for declared variables */
1546 fixforjump(fs
, prep
, luaK_getlabel(fs
), 0);
1547 if (isgen
) { /* generic for? */
1548 luaK_codeABC(fs
, OP_TFORCALL
, base
, 0, nvars
);
1549 luaK_fixline(fs
, line
);
1551 endfor
= luaK_codeABx(fs
, forloop
[isgen
], base
, 0);
1552 fixforjump(fs
, endfor
, prep
+ 1, 1);
1553 luaK_fixline(fs
, line
);
1557 static void fornum (LexState
*ls
, TString
*varname
, int line
) {
1558 /* fornum -> NAME = exp,exp[,exp] forbody */
1559 FuncState
*fs
= ls
->fs
;
1560 int base
= fs
->freereg
;
1561 new_localvarliteral(ls
, "(for state)");
1562 new_localvarliteral(ls
, "(for state)");
1563 new_localvarliteral(ls
, "(for state)");
1564 new_localvar(ls
, varname
);
1566 exp1(ls
); /* initial value */
1568 exp1(ls
); /* limit */
1569 if (testnext(ls
, ','))
1570 exp1(ls
); /* optional step */
1571 else { /* default step = 1 */
1572 luaK_int(fs
, fs
->freereg
, 1);
1573 luaK_reserveregs(fs
, 1);
1575 adjustlocalvars(ls
, 3); /* control variables */
1576 forbody(ls
, base
, line
, 1, 0);
1580 static void forlist (LexState
*ls
, TString
*indexname
) {
1581 /* forlist -> NAME {,NAME} IN explist forbody */
1582 FuncState
*fs
= ls
->fs
;
1584 int nvars
= 5; /* gen, state, control, toclose, 'indexname' */
1586 int base
= fs
->freereg
;
1587 /* create control variables */
1588 new_localvarliteral(ls
, "(for state)");
1589 new_localvarliteral(ls
, "(for state)");
1590 new_localvarliteral(ls
, "(for state)");
1591 new_localvarliteral(ls
, "(for state)");
1592 /* create declared variables */
1593 new_localvar(ls
, indexname
);
1594 while (testnext(ls
, ',')) {
1595 new_localvar(ls
, str_checkname(ls
));
1598 checknext(ls
, TK_IN
);
1599 line
= ls
->linenumber
;
1600 adjust_assign(ls
, 4, explist(ls
, &e
), &e
);
1601 adjustlocalvars(ls
, 4); /* control variables */
1602 markupval(fs
, fs
->nactvar
); /* last control var. must be closed */
1603 luaK_checkstack(fs
, 3); /* extra space to call generator */
1604 forbody(ls
, base
, line
, nvars
- 4, 1);
1608 static void forstat (LexState
*ls
, int line
) {
1609 /* forstat -> FOR (fornum | forlist) END */
1610 FuncState
*fs
= ls
->fs
;
1613 enterblock(fs
, &bl
, 1); /* scope for loop and control variables */
1614 luaX_next(ls
); /* skip 'for' */
1615 varname
= str_checkname(ls
); /* first variable name */
1616 switch (ls
->t
.token
) {
1617 case '=': fornum(ls
, varname
, line
); break;
1618 case ',': case TK_IN
: forlist(ls
, varname
); break;
1619 default: luaX_syntaxerror(ls
, "'=' or 'in' expected");
1621 check_match(ls
, TK_END
, TK_FOR
, line
);
1622 leaveblock(fs
); /* loop scope ('break' jumps to this point) */
1626 static void test_then_block (LexState
*ls
, int *escapelist
) {
1627 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1629 FuncState
*fs
= ls
->fs
;
1631 int jf
; /* instruction to skip 'then' code (if condition is false) */
1632 luaX_next(ls
); /* skip IF or ELSEIF */
1633 expr(ls
, &v
); /* read condition */
1634 checknext(ls
, TK_THEN
);
1635 if (ls
->t
.token
== TK_BREAK
) { /* 'if x then break' ? */
1636 int line
= ls
->linenumber
;
1637 luaK_goiffalse(ls
->fs
, &v
); /* will jump if condition is true */
1638 luaX_next(ls
); /* skip 'break' */
1639 enterblock(fs
, &bl
, 0); /* must enter block before 'goto' */
1640 newgotoentry(ls
, luaS_newliteral(ls
->L
, "break"), line
, v
.t
);
1641 while (testnext(ls
, ';')) {} /* skip semicolons */
1642 if (block_follow(ls
, 0)) { /* jump is the entire block? */
1644 return; /* and that is it */
1646 else /* must skip over 'then' part if condition is false */
1649 else { /* regular case (not a break) */
1650 luaK_goiftrue(ls
->fs
, &v
); /* skip over block if condition is false */
1651 enterblock(fs
, &bl
, 0);
1654 statlist(ls
); /* 'then' part */
1656 if (ls
->t
.token
== TK_ELSE
||
1657 ls
->t
.token
== TK_ELSEIF
) /* followed by 'else'/'elseif'? */
1658 luaK_concat(fs
, escapelist
, luaK_jump(fs
)); /* must jump over it */
1659 luaK_patchtohere(fs
, jf
);
1663 static void ifstat (LexState
*ls
, int line
) {
1664 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1665 FuncState
*fs
= ls
->fs
;
1666 int escapelist
= NO_JUMP
; /* exit list for finished parts */
1667 test_then_block(ls
, &escapelist
); /* IF cond THEN block */
1668 while (ls
->t
.token
== TK_ELSEIF
)
1669 test_then_block(ls
, &escapelist
); /* ELSEIF cond THEN block */
1670 if (testnext(ls
, TK_ELSE
))
1671 block(ls
); /* 'else' part */
1672 check_match(ls
, TK_END
, TK_IF
, line
);
1673 luaK_patchtohere(fs
, escapelist
); /* patch escape list to 'if' end */
1677 static void localfunc (LexState
*ls
) {
1679 FuncState
*fs
= ls
->fs
;
1680 int fvar
= fs
->nactvar
; /* function's variable index */
1681 new_localvar(ls
, str_checkname(ls
)); /* new local variable */
1682 adjustlocalvars(ls
, 1); /* enter its scope */
1683 body(ls
, &b
, 0, ls
->linenumber
); /* function created in next register */
1684 /* debug information will only see the variable after this point! */
1685 localdebuginfo(fs
, fvar
)->startpc
= fs
->pc
;
1689 static int getlocalattribute (LexState
*ls
) {
1690 /* ATTRIB -> ['<' Name '>'] */
1691 if (testnext(ls
, '<')) {
1692 const char *attr
= getstr(str_checkname(ls
));
1694 if (strcmp(attr
, "const") == 0)
1695 return RDKCONST
; /* read-only variable */
1696 else if (strcmp(attr
, "close") == 0)
1697 return RDKTOCLOSE
; /* to-be-closed variable */
1700 luaO_pushfstring(ls
->L
, "unknown attribute '%s'", attr
));
1702 return VDKREG
; /* regular variable */
1706 static void checktoclose (LexState
*ls
, int level
) {
1707 if (level
!= -1) { /* is there a to-be-closed variable? */
1708 FuncState
*fs
= ls
->fs
;
1709 markupval(fs
, level
+ 1);
1710 fs
->bl
->insidetbc
= 1; /* in the scope of a to-be-closed variable */
1711 luaK_codeABC(fs
, OP_TBC
, reglevel(fs
, level
), 0, 0);
1716 static void localstat (LexState
*ls
) {
1717 /* stat -> LOCAL NAME ATTRIB { ',' NAME ATTRIB } ['=' explist] */
1718 FuncState
*fs
= ls
->fs
;
1719 int toclose
= -1; /* index of to-be-closed variable (if any) */
1720 Vardesc
*var
; /* last variable */
1721 int vidx
, kind
; /* index and kind of last variable */
1726 vidx
= new_localvar(ls
, str_checkname(ls
));
1727 kind
= getlocalattribute(ls
);
1728 getlocalvardesc(fs
, vidx
)->vd
.kind
= kind
;
1729 if (kind
== RDKTOCLOSE
) { /* to-be-closed? */
1730 if (toclose
!= -1) /* one already present? */
1731 luaK_semerror(ls
, "multiple to-be-closed variables in local list");
1732 toclose
= fs
->nactvar
+ nvars
;
1735 } while (testnext(ls
, ','));
1736 if (testnext(ls
, '='))
1737 nexps
= explist(ls
, &e
);
1742 var
= getlocalvardesc(fs
, vidx
); /* get last variable */
1743 if (nvars
== nexps
&& /* no adjustments? */
1744 var
->vd
.kind
== RDKCONST
&& /* last variable is const? */
1745 luaK_exp2const(fs
, &e
, &var
->k
)) { /* compile-time constant? */
1746 var
->vd
.kind
= RDKCTC
; /* variable is a compile-time constant */
1747 adjustlocalvars(ls
, nvars
- 1); /* exclude last variable */
1748 fs
->nactvar
++; /* but count it */
1751 adjust_assign(ls
, nvars
, nexps
, &e
);
1752 adjustlocalvars(ls
, nvars
);
1754 checktoclose(ls
, toclose
);
1758 static int funcname (LexState
*ls
, expdesc
*v
) {
1759 /* funcname -> NAME {fieldsel} [':' NAME] */
1762 while (ls
->t
.token
== '.')
1764 if (ls
->t
.token
== ':') {
1772 static void funcstat (LexState
*ls
, int line
) {
1773 /* funcstat -> FUNCTION funcname body */
1776 luaX_next(ls
); /* skip FUNCTION */
1777 ismethod
= funcname(ls
, &v
);
1778 body(ls
, &b
, ismethod
, line
);
1779 luaK_storevar(ls
->fs
, &v
, &b
);
1780 luaK_fixline(ls
->fs
, line
); /* definition "happens" in the first line */
1784 static void exprstat (LexState
*ls
) {
1785 /* stat -> func | assignment */
1786 FuncState
*fs
= ls
->fs
;
1787 struct LHS_assign v
;
1788 suffixedexp(ls
, &v
.v
);
1789 if (ls
->t
.token
== '=' || ls
->t
.token
== ',') { /* stat -> assignment ? */
1791 restassign(ls
, &v
, 1);
1793 else { /* stat -> func */
1795 check_condition(ls
, v
.v
.k
== VCALL
, "syntax error");
1796 inst
= &getinstruction(fs
, &v
.v
);
1797 SETARG_C(*inst
, 1); /* call statement uses no results */
1802 static void retstat (LexState
*ls
) {
1803 /* stat -> RETURN [explist] [';'] */
1804 FuncState
*fs
= ls
->fs
;
1806 int nret
; /* number of values being returned */
1807 int first
= luaY_nvarstack(fs
); /* first slot to be returned */
1808 if (block_follow(ls
, 1) || ls
->t
.token
== ';')
1809 nret
= 0; /* return no values */
1811 nret
= explist(ls
, &e
); /* optional return values */
1812 if (hasmultret(e
.k
)) {
1813 luaK_setmultret(fs
, &e
);
1814 if (e
.k
== VCALL
&& nret
== 1 && !fs
->bl
->insidetbc
) { /* tail call? */
1815 SET_OPCODE(getinstruction(fs
,&e
), OP_TAILCALL
);
1816 lua_assert(GETARG_A(getinstruction(fs
,&e
)) == luaY_nvarstack(fs
));
1818 nret
= LUA_MULTRET
; /* return all values */
1821 if (nret
== 1) /* only one single value? */
1822 first
= luaK_exp2anyreg(fs
, &e
); /* can use original slot */
1823 else { /* values must go to the top of the stack */
1824 luaK_exp2nextreg(fs
, &e
);
1825 lua_assert(nret
== fs
->freereg
- first
);
1829 luaK_ret(fs
, first
, nret
);
1830 testnext(ls
, ';'); /* skip optional semicolon */
1834 static void statement (LexState
*ls
) {
1835 int line
= ls
->linenumber
; /* may be needed for error messages */
1837 switch (ls
->t
.token
) {
1838 case ';': { /* stat -> ';' (empty statement) */
1839 luaX_next(ls
); /* skip ';' */
1842 case TK_IF
: { /* stat -> ifstat */
1846 case TK_WHILE
: { /* stat -> whilestat */
1847 whilestat(ls
, line
);
1850 case TK_DO
: { /* stat -> DO block END */
1851 luaX_next(ls
); /* skip DO */
1853 check_match(ls
, TK_END
, TK_DO
, line
);
1856 case TK_FOR
: { /* stat -> forstat */
1860 case TK_REPEAT
: { /* stat -> repeatstat */
1861 repeatstat(ls
, line
);
1864 case TK_FUNCTION
: { /* stat -> funcstat */
1868 case TK_LOCAL
: { /* stat -> localstat */
1869 luaX_next(ls
); /* skip LOCAL */
1870 if (testnext(ls
, TK_FUNCTION
)) /* local function? */
1876 case TK_DBCOLON
: { /* stat -> label */
1877 luaX_next(ls
); /* skip double colon */
1878 labelstat(ls
, str_checkname(ls
), line
);
1881 case TK_RETURN
: { /* stat -> retstat */
1882 luaX_next(ls
); /* skip RETURN */
1886 case TK_BREAK
: { /* stat -> breakstat */
1890 case TK_GOTO
: { /* stat -> 'goto' NAME */
1891 luaX_next(ls
); /* skip 'goto' */
1895 default: { /* stat -> func | assignment */
1900 lua_assert(ls
->fs
->f
->maxstacksize
>= ls
->fs
->freereg
&&
1901 ls
->fs
->freereg
>= luaY_nvarstack(ls
->fs
));
1902 ls
->fs
->freereg
= luaY_nvarstack(ls
->fs
); /* free registers */
1906 /* }====================================================================== */
1910 ** compiles the main function, which is a regular vararg function with an
1911 ** upvalue named LUA_ENV
1913 static void mainfunc (LexState
*ls
, FuncState
*fs
) {
1916 open_func(ls
, fs
, &bl
);
1917 setvararg(fs
, 0); /* main function is always declared vararg */
1918 env
= allocupvalue(fs
); /* ...set environment upvalue */
1922 env
->name
= ls
->envn
;
1923 luaC_objbarrier(ls
->L
, fs
->f
, env
->name
);
1924 luaX_next(ls
); /* read first token */
1925 statlist(ls
); /* parse main body */
1931 LClosure
*luaY_parser (lua_State
*L
, ZIO
*z
, Mbuffer
*buff
,
1932 Dyndata
*dyd
, const char *name
, int firstchar
) {
1934 FuncState funcstate
;
1935 LClosure
*cl
= luaF_newLclosure(L
, 1); /* create main closure */
1936 setclLvalue2s(L
, L
->top
, cl
); /* anchor it (to avoid being collected) */
1938 lexstate
.h
= luaH_new(L
); /* create table for scanner */
1939 sethvalue2s(L
, L
->top
, lexstate
.h
); /* anchor it */
1941 funcstate
.f
= cl
->p
= luaF_newproto(L
);
1942 luaC_objbarrier(L
, cl
, cl
->p
);
1943 funcstate
.f
->source
= luaS_new(L
, name
); /* create and anchor TString */
1944 luaC_objbarrier(L
, funcstate
.f
, funcstate
.f
->source
);
1945 lexstate
.buff
= buff
;
1947 dyd
->actvar
.n
= dyd
->gt
.n
= dyd
->label
.n
= 0;
1948 luaX_setinput(L
, &lexstate
, z
, funcstate
.f
->source
, firstchar
);
1949 mainfunc(&lexstate
, &funcstate
);
1950 lua_assert(!funcstate
.prev
&& funcstate
.nups
== 1 && !lexstate
.fs
);
1951 /* all scopes should be correctly finished */
1952 lua_assert(dyd
->actvar
.n
== 0 && dyd
->gt
.n
== 0 && dyd
->label
.n
== 0);
1953 L
->top
--; /* remove scanner's table */
1954 return cl
; /* closure is on the stack, too */