2 ** $Id: lparser.c,v 1.37a 1999/06/17 17:04:03 roberto Exp $
3 ** LL(1) Parser and code generator for Lua
4 ** See Copyright Notice in lua.h
26 /* size of a "normal" jump instruction: OpCode + 1 byte */
29 /* maximum number of local variables */
31 #define MAXLOCALS 200 /* arbitrary limit (<256) */
35 /* maximum number of upvalues */
37 #define MAXUPVALUES 32 /* arbitrary limit (<256) */
41 /* maximum number of variables in the left side of an assignment */
43 #define MAXVARSLH 100 /* arbitrary limit (<255) */
47 /* maximum number of parameters in a function */
49 #define MAXPARAMS 100 /* arbitrary limit (<ZEROVARARG) */
54 ** Variable descriptor:
55 ** must include an "exp" option because LL(1) cannot distinguish
56 ** between variables, upvalues and function calls on first sight.
59 VGLOBAL
, /* info is constant index of global name */
60 VLOCAL
, /* info is stack index */
61 VDOT
, /* info is constant index of index name */
62 VINDEXED
, /* no info (table and index are on the stack) */
63 VEXP
/* info is pc index of "nparam" of a call (or 0 if exp is closed) */
66 typedef struct vardesc
{
73 ** Expression List descriptor:
74 ** tells number of expressions in the list,
75 ** and, if last expression is open (a function call),
76 ** where is its pc index of "nparam"
78 typedef struct listdesc
{
80 int pc
; /* 0 if last expression is closed */
85 ** Constructors descriptor:
86 ** "n" indicates number of elements, and "k" signals whether
87 ** it is a list constructor (k = 0) or a record constructor (k = 1)
88 ** or empty (k = ';' or '}')
90 typedef struct constdesc
{
96 /* state needed to generate code for a given function */
97 typedef struct FuncState
{
98 TProtoFunc
*f
; /* current function header */
99 struct FuncState
*prev
; /* enclosuring function */
100 int pc
; /* next position to code */
101 int stacksize
; /* number of values on activation register */
102 int maxstacksize
; /* maximum number of values on activation register */
103 int nlocalvar
; /* number of active local variables */
104 int nupvalues
; /* number of upvalues */
105 int nvars
; /* number of entries in f->locvars (-1 if no debug information) */
106 int lastsetline
; /* line where last SETLINE was issued */
107 vardesc upvalues
[MAXUPVALUES
]; /* upvalues */
108 TaggedString
*localvar
[MAXLOCALS
]; /* store local variable names */
113 ** prototypes for non-terminal functions
115 static int assignment (LexState
*ls
, vardesc
*v
, int nvars
);
116 static int cond (LexState
*ls
);
117 static int funcname (LexState
*ls
, vardesc
*v
);
118 static int funcparams (LexState
*ls
, int slf
);
119 static int listfields (LexState
*ls
);
120 static int localnamelist (LexState
*ls
);
121 static int optional (LexState
*ls
, int c
);
122 static int recfields (LexState
*ls
);
123 static int stat (LexState
*ls
);
124 static void block (LexState
*ls
);
125 static void body (LexState
*ls
, int needself
, int line
);
126 static void chunk (LexState
*ls
);
127 static void constructor (LexState
*ls
);
128 static void decinit (LexState
*ls
, listdesc
*d
);
129 static void exp0 (LexState
*ls
, vardesc
*v
);
130 static void exp1 (LexState
*ls
);
131 static void exp2 (LexState
*ls
, vardesc
*v
);
132 static void explist (LexState
*ls
, listdesc
*e
);
133 static void explist1 (LexState
*ls
, listdesc
*e
);
134 static void ifpart (LexState
*ls
, int line
);
135 static void parlist (LexState
*ls
);
136 static void part (LexState
*ls
, constdesc
*cd
);
137 static void recfield (LexState
*ls
);
138 static void ret (LexState
*ls
);
139 static void statlist (LexState
*ls
);
140 static void var_or_func (LexState
*ls
, vardesc
*v
);
141 static void var_or_func_tail (LexState
*ls
, vardesc
*v
);
145 static void checklimit (LexState
*ls
, int val
, int limit
, char *msg
) {
148 sprintf(buff
, "too many %s (limit=%d)", msg
, limit
);
149 luaX_error(ls
, buff
);
154 static void check_pc (FuncState
*fs
, int n
) {
155 luaM_growvector(fs
->f
->code
, fs
->pc
, n
, Byte
, codeEM
, MAX_INT
);
159 static void code_byte (FuncState
*fs
, Byte c
) {
161 fs
->f
->code
[fs
->pc
++] = c
;
165 static void deltastack (LexState
*ls
, int delta
) {
166 FuncState
*fs
= ls
->fs
;
167 fs
->stacksize
+= delta
;
168 if (fs
->stacksize
> fs
->maxstacksize
) {
169 if (fs
->stacksize
> MAX_BYTE
)
170 luaX_error(ls
, "function/expression too complex");
171 fs
->maxstacksize
= fs
->stacksize
;
176 static void code_oparg_at (LexState
*ls
, int pc
, OpCode op
,
177 int arg
, int delta
) {
178 Byte
*code
= ls
->fs
->f
->code
;
179 deltastack(ls
, delta
);
180 if (arg
<= MAX_BYTE
) {
182 code
[pc
+1] = (Byte
)arg
;
184 else if (arg
> MAX_ARG
)
185 luaX_error(ls
, "code too long");
186 else { /* MAX_BYTE < arg < MAX_ARG */
187 if (arg
> MAX_WORD
) {
188 code
[pc
] = (Byte
)LONGARG
;
189 code
[pc
+1] = (Byte
)(arg
>>16);
192 code
[pc
] = (Byte
)(op
-1); /* opcode for word argument */
193 code
[pc
+1] = (Byte
)((arg
&0xFFFF)>>8);
194 code
[pc
+2] = (Byte
)(arg
&0xFF);
199 static int codesize (int arg
) {
200 if (arg
<= MAX_BYTE
) return 2; /* opcode + 1 byte */
201 else if (arg
<= MAX_WORD
) return 3; /* opcode + 1 word (2 bytes) */
202 else return 5; /* LONGARG + 1 byte + opcode + 1 word (2 bytes) */
206 static int fix_opcode (LexState
*ls
, int pc
, OpCode op
, int arg
) {
207 int tomove
= codesize(arg
)-2;
208 if (tomove
> 0) { /* need to open space? */
209 FuncState
*fs
= ls
->fs
;
210 TProtoFunc
*f
= fs
->f
;
211 check_pc(fs
, tomove
);
212 luaO_memup(f
->code
+pc
+tomove
, f
->code
+pc
, fs
->pc
-pc
);
215 code_oparg_at(ls
, pc
, op
, arg
, 0);
220 static void code_oparg (LexState
*ls
, OpCode op
, int arg
, int delta
) {
221 int size
= codesize(arg
);
222 check_pc(ls
->fs
, size
);
223 code_oparg_at(ls
, ls
->fs
->pc
, op
, arg
, delta
);
228 static void code_opcode (LexState
*ls
, OpCode op
, int delta
) {
229 deltastack(ls
, delta
);
230 code_byte(ls
->fs
, (Byte
)op
);
234 static void code_constant (LexState
*ls
, int c
) {
235 code_oparg(ls
, PUSHCONSTANT
, c
, 1);
239 static int next_constant (FuncState
*fs
) {
240 TProtoFunc
*f
= fs
->f
;
241 luaM_growvector(f
->consts
, f
->nconsts
, 1, TObject
, constantEM
, MAX_ARG
);
246 static int string_constant (FuncState
*fs
, TaggedString
*s
) {
247 TProtoFunc
*f
= fs
->f
;
248 int c
= s
->constindex
;
249 if (!(c
< f
->nconsts
&&
250 ttype(&f
->consts
[c
]) == LUA_T_STRING
&& tsvalue(&f
->consts
[c
]) == s
)) {
251 c
= next_constant(fs
);
252 ttype(&f
->consts
[c
]) = LUA_T_STRING
;
253 tsvalue(&f
->consts
[c
]) = s
;
254 s
->constindex
= c
; /* hint for next time */
260 static void code_string (LexState
*ls
, TaggedString
*s
) {
261 code_constant(ls
, string_constant(ls
->fs
, s
));
266 static int real_constant (FuncState
*fs
, real r
) {
267 /* check whether 'r' has appeared within the last LIM entries */
268 TObject
*cnt
= fs
->f
->consts
;
269 int c
= fs
->f
->nconsts
;
270 int lim
= c
< LIM
? 0 : c
-LIM
;
272 if (ttype(&cnt
[c
]) == LUA_T_NUMBER
&& nvalue(&cnt
[c
]) == r
)
275 /* not found; create a new entry */
276 c
= next_constant(fs
);
277 cnt
= fs
->f
->consts
; /* 'next_constant' may have reallocated this vector */
278 ttype(&cnt
[c
]) = LUA_T_NUMBER
;
284 static void code_number (LexState
*ls
, real f
) {
285 real af
= (f
<0) ? -f
: f
;
286 if (0 <= af
&& af
<= (real
)MAX_WORD
&& (int)af
== af
) {
287 /* abs(f) has a short integer value */
288 code_oparg(ls
, (f
<0) ? PUSHNUMBERNEG
: PUSHNUMBER
, (int)af
, 1);
291 code_constant(ls
, real_constant(ls
->fs
, f
));
295 static void flush_record (LexState
*ls
, int n
) {
297 code_oparg(ls
, SETMAP
, n
-1, -2*n
);
301 static void flush_list (LexState
*ls
, int m
, int n
) {
303 code_oparg(ls
, SETLIST
, m
, -n
);
304 code_byte(ls
->fs
, (Byte
)n
);
309 static void luaI_registerlocalvar (FuncState
*fs
, TaggedString
*varname
,
311 if (fs
->nvars
!= -1) { /* debug information? */
312 TProtoFunc
*f
= fs
->f
;
313 luaM_growvector(f
->locvars
, fs
->nvars
, 1, LocVar
, "", MAX_INT
);
314 f
->locvars
[fs
->nvars
].varname
= varname
;
315 f
->locvars
[fs
->nvars
].line
= line
;
321 static void luaI_unregisterlocalvar (FuncState
*fs
, int line
) {
322 luaI_registerlocalvar(fs
, NULL
, line
);
326 static void store_localvar (LexState
*ls
, TaggedString
*name
, int n
) {
327 FuncState
*fs
= ls
->fs
;
328 checklimit(ls
, fs
->nlocalvar
+n
+1, MAXLOCALS
, "local variables");
329 fs
->localvar
[fs
->nlocalvar
+n
] = name
;
330 luaI_registerlocalvar(fs
, name
, ls
->linenumber
);
334 static void add_localvar (LexState
*ls
, TaggedString
*name
) {
335 store_localvar(ls
, name
, 0);
340 static void correctvarlines (LexState
*ls
, int nvars
) {
341 FuncState
*fs
= ls
->fs
;
342 if (fs
->nvars
!= -1) { /* debug information? */
343 for (; nvars
; nvars
--) { /* correct line information */
344 fs
->f
->locvars
[fs
->nvars
-nvars
].line
= fs
->lastsetline
;
350 static int aux_localname (FuncState
*fs
, TaggedString
*n
) {
352 for (i
=fs
->nlocalvar
-1; i
>= 0; i
--)
353 if (n
== fs
->localvar
[i
]) return i
; /* local var index */
354 return -1; /* not found */
358 static void singlevar (LexState
*ls
, TaggedString
*n
, vardesc
*var
, int prev
) {
359 FuncState
*fs
= prev
? ls
->fs
->prev
: ls
->fs
;
360 int i
= aux_localname(fs
, n
);
361 if (i
>= 0) { /* local value? */
366 FuncState
*level
= fs
;
367 while ((level
= level
->prev
) != NULL
) /* check shadowing */
368 if (aux_localname(level
, n
) >= 0)
369 luaX_syntaxerror(ls
, "cannot access a variable in outer scope", n
->str
);
371 var
->info
= string_constant(fs
, n
);
376 static int indexupvalue (LexState
*ls
, TaggedString
*n
) {
377 FuncState
*fs
= ls
->fs
;
380 singlevar(ls
, n
, &v
, 1);
381 for (i
=0; i
<fs
->nupvalues
; i
++) {
382 if (fs
->upvalues
[i
].k
== v
.k
&& fs
->upvalues
[i
].info
== v
.info
)
387 checklimit(ls
, fs
->nupvalues
, MAXUPVALUES
, "upvalues");
388 fs
->upvalues
[i
] = v
; /* i = fs->nupvalues - 1 */
393 static void pushupvalue (LexState
*ls
, TaggedString
*n
) {
394 if (ls
->fs
->prev
== NULL
)
395 luaX_syntaxerror(ls
, "cannot access upvalue in main", n
->str
);
396 if (aux_localname(ls
->fs
, n
) >= 0)
397 luaX_syntaxerror(ls
, "cannot access an upvalue in current scope", n
->str
);
398 code_oparg(ls
, PUSHUPVALUE
, indexupvalue(ls
, n
), 1);
403 static void check_debugline (LexState
*ls
) {
404 if (L
->debug
&& ls
->linenumber
!= ls
->fs
->lastsetline
) {
405 code_oparg(ls
, SETLINE
, ls
->linenumber
, 0);
406 ls
->fs
->lastsetline
= ls
->linenumber
;
411 static void adjuststack (LexState
*ls
, int n
) {
413 code_oparg(ls
, POP
, n
, -n
);
415 code_oparg(ls
, PUSHNIL
, (-n
)-1, -n
);
419 static void close_exp (LexState
*ls
, int pc
, int nresults
) {
420 if (pc
> 0) { /* expression is an open function call? */
421 Byte
*code
= ls
->fs
->f
->code
;
422 code
[pc
-1] = (Byte
)nresults
; /* set nresults */
423 /* push results, pop params (at code[pc]) and function */
424 deltastack(ls
, nresults
-(code
[pc
]+1));
427 code_oparg(ls
, CHECKSTACK
, ls
->fs
->stacksize
, 0);
432 static void adjust_mult_assign (LexState
*ls
, int nvars
, listdesc
*d
) {
433 int diff
= d
->n
- nvars
;
434 if (d
->pc
== 0) { /* list is closed */
435 /* push or pop eventual difference between list lengths */
436 adjuststack(ls
, diff
);
438 else { /* must correct function call */
439 diff
--; /* do not count function call itself */
440 if (diff
<= 0) { /* more variables than values? */
441 /* function call must provide extra values */
442 close_exp(ls
, d
->pc
, -diff
);
444 else { /* more values than variables */
445 close_exp(ls
, d
->pc
, 0); /* call should provide no value */
446 adjuststack(ls
, diff
); /* pop eventual extra values */
452 static void code_args (LexState
*ls
, int nparams
, int dots
) {
453 FuncState
*fs
= ls
->fs
;
454 fs
->nlocalvar
+= nparams
; /* "self" may already be there */
455 checklimit(ls
, fs
->nlocalvar
, MAXPARAMS
, "parameters");
456 nparams
= fs
->nlocalvar
;
458 fs
->f
->code
[1] = (Byte
)nparams
; /* fill-in arg information */
459 deltastack(ls
, nparams
);
462 fs
->f
->code
[1] = (Byte
)(nparams
+ZEROVARARG
);
463 deltastack(ls
, nparams
+1);
464 add_localvar(ls
, luaS_new("arg"));
469 static void unloaddot (LexState
*ls
, vardesc
*v
) {
470 /* dotted variables <a.x> must be stored like regular indexed vars <a["x"]> */
472 code_constant(ls
, v
->info
);
478 static void lua_pushvar (LexState
*ls
, vardesc
*var
) {
481 code_oparg(ls
, PUSHLOCAL
, var
->info
, 1);
484 code_oparg(ls
, GETGLOBAL
, var
->info
, 1);
487 code_oparg(ls
, GETDOTTED
, var
->info
, 0);
490 code_opcode(ls
, GETTABLE
, -1);
493 close_exp(ls
, var
->info
, 1); /* function must return 1 value */
497 var
->info
= 0; /* now this is a closed expression */
501 static void storevar (LexState
*ls
, vardesc
*var
) {
504 code_oparg(ls
, SETLOCAL
, var
->info
, -1);
507 code_oparg(ls
, SETGLOBAL
, var
->info
, -1);
510 code_opcode(ls
, SETTABLEPOP
, -3);
513 LUA_INTERNALERROR("invalid var kind to store");
518 static int fix_jump (LexState
*ls
, int pc
, OpCode op
, int n
) {
519 /* jump is relative to position following jump instruction */
520 return fix_opcode(ls
, pc
, op
, n
-(pc
+JMPSIZE
));
524 static void fix_upjmp (LexState
*ls
, OpCode op
, int pos
) {
525 int delta
= ls
->fs
->pc
+JMPSIZE
- pos
; /* jump is relative */
526 code_oparg(ls
, op
, delta
+(codesize(delta
)-2), 0);
530 static void codeIf (LexState
*ls
, int thenAdd
, int elseAdd
) {
531 FuncState
*fs
= ls
->fs
;
532 int elseinit
= elseAdd
+JMPSIZE
;
533 if (fs
->pc
== elseinit
) { /* no else part? */
538 elseinit
+= fix_jump(ls
, elseAdd
, JMP
, fs
->pc
);
539 fix_jump(ls
, thenAdd
, IFFJMP
, elseinit
);
543 static void func_onstack (LexState
*ls
, FuncState
*func
) {
544 FuncState
*fs
= ls
->fs
;
546 int c
= next_constant(fs
);
547 ttype(&fs
->f
->consts
[c
]) = LUA_T_PROTO
;
548 fs
->f
->consts
[c
].value
.tf
= func
->f
;
549 if (func
->nupvalues
== 0)
550 code_constant(ls
, c
);
552 for (i
=0; i
<func
->nupvalues
; i
++)
553 lua_pushvar(ls
, &func
->upvalues
[i
]);
554 deltastack(ls
, 1); /* CLOSURE puts one extra element (before poping) */
555 code_oparg(ls
, CLOSURE
, c
, -func
->nupvalues
);
556 code_byte(fs
, (Byte
)func
->nupvalues
);
561 static void init_state (LexState
*ls
, FuncState
*fs
, TaggedString
*source
) {
562 TProtoFunc
*f
= luaF_newproto();
563 fs
->prev
= ls
->fs
; /* linked list of funcstates */
566 fs
->maxstacksize
= 0;
574 fs
->nvars
= (L
->debug
) ? 0 : -1; /* flag no debug information? */
575 code_byte(fs
, 0); /* to be filled with maxstacksize */
576 code_byte(fs
, 0); /* to be filled with arg information */
577 /* push function (to avoid GC) */
578 tfvalue(L
->stack
.top
) = f
; ttype(L
->stack
.top
) = LUA_T_PROTO
;
583 static void close_func (LexState
*ls
) {
584 FuncState
*fs
= ls
->fs
;
585 TProtoFunc
*f
= fs
->f
;
586 code_opcode(ls
, ENDCODE
, 0);
587 f
->code
[0] = (Byte
)fs
->maxstacksize
;
588 luaM_reallocvector(f
->code
, fs
->pc
, Byte
);
589 luaM_reallocvector(f
->consts
, f
->nconsts
, TObject
);
590 if (fs
->nvars
!= -1) { /* debug information? */
591 luaI_registerlocalvar(fs
, NULL
, -1); /* flag end of vector */
592 luaM_reallocvector(f
->locvars
, fs
->nvars
, LocVar
);
595 L
->stack
.top
--; /* pop function */
600 static int expfollow
[] = {ELSE
, ELSEIF
, THEN
, IF
, WHILE
, REPEAT
, DO
, NAME
,
601 LOCAL
, FUNCTION
, END
, UNTIL
, RETURN
, ')', ']', '}', ';', EOS
, ',', 0};
604 static int is_in (int tok
, int *toks
) {
606 for (t
=toks
; *t
; t
++)
607 if (*t
== tok
) return t
-toks
;
612 static void next (LexState
*ls
) {
613 ls
->token
= luaX_lex(ls
);
617 static void error_expected (LexState
*ls
, int token
) {
618 char buff
[100], t
[TOKEN_LEN
];
619 luaX_token2str(token
, t
);
620 sprintf(buff
, "`%s' expected", t
);
621 luaX_error(ls
, buff
);
625 static void error_unexpected (LexState
*ls
) {
626 luaX_error(ls
, "unexpected token");
630 static void error_unmatched (LexState
*ls
, int what
, int who
, int where
) {
631 if (where
== ls
->linenumber
)
632 error_expected(ls
, what
);
635 char t_what
[TOKEN_LEN
], t_who
[TOKEN_LEN
];
636 luaX_token2str(what
, t_what
);
637 luaX_token2str(who
, t_who
);
638 sprintf(buff
, "`%s' expected (to close `%s' at line %d)",
639 t_what
, t_who
, where
);
640 luaX_error(ls
, buff
);
644 static void check (LexState
*ls
, int c
) {
646 error_expected(ls
, c
);
650 static void check_match (LexState
*ls
, int what
, int who
, int where
) {
651 if (ls
->token
!= what
)
652 error_unmatched(ls
, what
, who
, where
);
653 check_debugline(ls
); /* to 'mark' the 'what' */
657 static int checkname (LexState
*ls
) {
659 if (ls
->token
!= NAME
)
660 luaX_error(ls
, "`NAME' expected");
661 sc
= string_constant(ls
->fs
, ls
->seminfo
.ts
);
667 static TaggedString
*str_checkname (LexState
*ls
) {
668 int i
= checkname(ls
); /* this call may realloc `f->consts' */
669 return tsvalue(&ls
->fs
->f
->consts
[i
]);
673 static int optional (LexState
*ls
, int c
) {
674 if (ls
->token
== c
) {
682 TProtoFunc
*luaY_parser (ZIO
*z
) {
683 struct LexState lexstate
;
684 struct FuncState funcstate
;
685 luaX_setinput(&lexstate
, z
);
686 init_state(&lexstate
, &funcstate
, luaS_new(zname(z
)));
687 next(&lexstate
); /* read first token */
689 if (lexstate
.token
!= EOS
)
690 luaX_error(&lexstate
, "<eof> expected");
691 close_func(&lexstate
);
697 /*============================================================*/
699 /*============================================================*/
701 static void chunk (LexState
*ls
) {
702 /* chunk -> statlist ret */
707 static void statlist (LexState
*ls
) {
708 /* statlist -> { stat [;] } */
710 LUA_ASSERT(ls
->fs
->stacksize
== ls
->fs
->nlocalvar
,
711 "stack size != # local vars");
716 static int stat (LexState
*ls
) {
717 int line
= ls
->linenumber
; /* may be needed for error messages */
718 FuncState
*fs
= ls
->fs
;
720 case IF
: /* stat -> IF ifpart END */
724 case WHILE
: { /* stat -> WHILE cond DO block END */
725 TProtoFunc
*f
= fs
->f
;
726 int while_init
= fs
->pc
;
727 int cond_end
, cond_size
;
732 check_match(ls
, END
, WHILE
, line
);
733 cond_size
= cond_end
-while_init
;
734 check_pc(fs
, cond_size
);
735 memcpy(f
->code
+fs
->pc
, f
->code
+while_init
, cond_size
);
736 luaO_memdown(f
->code
+while_init
, f
->code
+cond_end
, fs
->pc
-while_init
);
737 while_init
+= JMPSIZE
+ fix_jump(ls
, while_init
, JMP
, fs
->pc
-cond_size
);
738 fix_upjmp(ls
, IFTUPJMP
, while_init
);
742 case DO
: { /* stat -> DO block END */
745 check_match(ls
, END
, DO
, line
);
749 case REPEAT
: { /* stat -> REPEAT block UNTIL exp1 */
750 int repeat_init
= fs
->pc
;
753 check_match(ls
, UNTIL
, REPEAT
, line
);
755 fix_upjmp(ls
, IFFUPJMP
, repeat_init
);
756 deltastack(ls
, -1); /* pops condition */
760 case FUNCTION
: { /* stat -> FUNCTION funcname body */
763 if (ls
->fs
->prev
) /* inside other function? */
767 needself
= funcname(ls
, &v
);
768 body(ls
, needself
, line
);
773 case LOCAL
: { /* stat -> LOCAL localnamelist decinit */
778 nvars
= localnamelist(ls
);
780 fs
->nlocalvar
+= nvars
;
781 correctvarlines(ls
, nvars
); /* vars will be alive only after decinit */
782 adjust_mult_assign(ls
, nvars
, &d
);
786 case NAME
: case '%': { /* stat -> func | ['%'] NAME assignment */
790 if (v
.k
== VEXP
) { /* stat -> func */
791 if (v
.info
== 0) /* is just an upper value? */
792 luaX_error(ls
, "syntax error");
793 close_exp(ls
, v
.info
, 0);
795 else { /* stat -> ['%'] NAME assignment */
796 int left
= assignment(ls
, &v
, 1);
797 adjuststack(ls
, left
); /* remove eventual 'garbage' left on stack */
802 case RETURN
: case ';': case ELSE
: case ELSEIF
:
803 case END
: case UNTIL
: case EOS
: /* 'stat' follow */
807 error_unexpected(ls
);
808 return 0; /* to avoid warnings */
812 static int SaveWord (LexState
*ls
) {
813 int res
= ls
->fs
->pc
;
814 check_pc(ls
->fs
, JMPSIZE
);
815 ls
->fs
->pc
+= JMPSIZE
; /* open space */
819 static int SaveWordPop (LexState
*ls
) {
820 deltastack(ls
, -1); /* pop condition */
824 static int cond (LexState
*ls
) {
827 return SaveWordPop(ls
);
830 static void block (LexState
*ls
) {
832 FuncState
*fs
= ls
->fs
;
833 int nlocalvar
= fs
->nlocalvar
;
835 adjuststack(ls
, fs
->nlocalvar
- nlocalvar
);
836 for (; fs
->nlocalvar
> nlocalvar
; fs
->nlocalvar
--)
837 luaI_unregisterlocalvar(fs
, fs
->lastsetline
);
840 static int funcname (LexState
*ls
, vardesc
*v
) {
841 /* funcname -> NAME [':' NAME | '.' NAME] */
843 singlevar(ls
, str_checkname(ls
), v
, 0);
844 if (ls
->token
== ':' || ls
->token
== '.') {
845 needself
= (ls
->token
== ':');
848 code_constant(ls
, checkname(ls
));
854 static void body (LexState
*ls
, int needself
, int line
) {
855 /* body -> '(' parlist ')' chunk END */
857 init_state(ls
, &newfs
, ls
->fs
->f
->source
);
858 newfs
.f
->lineDefined
= line
;
861 add_localvar(ls
, luaS_new("self"));
865 check_match(ls
, END
, FUNCTION
, line
);
867 func_onstack(ls
, &newfs
);
871 static void ifpart (LexState
*ls
, int line
) {
872 /* ifpart -> cond THEN block [ELSE block | ELSEIF ifpart] */
875 next(ls
); /* skip IF or ELSEIF */
880 if (ls
->token
== ELSEIF
)
883 if (optional(ls
, ELSE
))
885 check_match(ls
, END
, IF
, line
);
891 static void ret (LexState
*ls
) {
892 /* ret -> [RETURN explist sc] */
893 if (optional(ls
, RETURN
)) {
897 if (e
.pc
> 0) { /* expression is an open function call? */
898 Byte
*code
= ls
->fs
->f
->code
;
899 code
[e
.pc
-2] = TAILCALL
; /* instead of a conventional CALL */
900 code
[e
.pc
-1] = (Byte
)ls
->fs
->nlocalvar
;
903 code_oparg(ls
, RETCODE
, ls
->fs
->nlocalvar
, 0);
904 ls
->fs
->stacksize
= ls
->fs
->nlocalvar
; /* removes all temp values */
911 ** For parsing expressions, we use a classic stack with priorities.
912 ** Each binary operator is represented by its index in "binop" + FIRSTBIN
913 ** (EQ=2, NE=3, ... '^'=13). The unary NOT is 0 and UNMINUS is 1.
919 /* code of first binary operator */
922 /* code for power operator (last operator)
923 ** '^' needs special treatment because it is right associative
927 static int binop
[] = {EQ
, NE
, '>', '<', LE
, GE
, CONC
,
928 '+', '-', '*', '/', '^', 0};
930 static int priority
[POW
+1] = {5, 5, 1, 1, 1, 1, 1, 1, 2, 3, 3, 4, 4, 6};
932 static OpCode opcodes
[POW
+1] = {NOTOP
, MINUSOP
, EQOP
, NEQOP
, GTOP
, LTOP
,
933 LEOP
, GEOP
, CONCOP
, ADDOP
, SUBOP
, MULTOP
, DIVOP
, POWOP
};
935 #define MAXOPS 20 /* op's stack size (arbitrary limit) */
937 typedef struct stack_op
{
943 static void exp1 (LexState
*ls
) {
947 if (is_in(ls
->token
, expfollow
) < 0)
948 luaX_error(ls
, "ill-formed expression");
952 static void exp0 (LexState
*ls
, vardesc
*v
) {
953 /* exp0 -> exp2 {(AND | OR) exp2} */
955 while (ls
->token
== AND
|| ls
->token
== OR
) {
956 int op
= (ls
->token
== AND
) ? ONFJMP
: ONTJMP
;
960 pc
= SaveWordPop(ls
);
963 fix_jump(ls
, pc
, op
, ls
->fs
->pc
);
968 static void push (LexState
*ls
, stack_op
*s
, int op
) {
969 if (s
->top
>= MAXOPS
)
970 luaX_error(ls
, "expression too complex");
971 s
->ops
[s
->top
++] = op
;
975 static void pop_to (LexState
*ls
, stack_op
*s
, int prio
) {
977 while (s
->top
> 0 && priority
[(op
=s
->ops
[s
->top
-1])] >= prio
) {
978 code_opcode(ls
, opcodes
[op
], op
<FIRSTBIN
?0:-1);
983 static void simpleexp (LexState
*ls
, vardesc
*v
, stack_op
*s
) {
986 case NUMBER
: { /* simpleexp -> NUMBER */
987 real r
= ls
->seminfo
.r
;
989 /* dirty trick: check whether it is a -NUMBER not followed by '^' */
990 /* (because the priority of '^' is closer than '-'...) */
991 if (s
->top
> 0 && s
->ops
[s
->top
-1] == INDMINUS
&& ls
->token
!= '^') {
992 s
->top
--; /* remove '-' from stack */
999 case STRING
: /* simpleexp -> STRING */
1000 code_string(ls
, ls
->seminfo
.ts
); /* must use 'seminfo' before "next" */
1004 case NIL
: /* simpleexp -> NIL */
1005 adjuststack(ls
, -1);
1009 case '{': /* simpleexp -> constructor */
1013 case FUNCTION
: /* simpleexp -> FUNCTION body */
1015 body(ls
, 0, ls
->linenumber
);
1018 case '(': /* simpleexp -> '(' exp0 ')' */
1024 case NAME
: case '%':
1029 luaX_error(ls
, "<expression> expected");
1032 v
->k
= VEXP
; v
->info
= 0;
1036 static void prefixexp (LexState
*ls
, vardesc
*v
, stack_op
*s
) {
1037 /* prefixexp -> {NOT | '-'} simpleexp */
1038 while (ls
->token
== NOT
|| ls
->token
== '-') {
1039 push(ls
, s
, (ls
->token
==NOT
)?INDNOT
:INDMINUS
);
1042 simpleexp(ls
, v
, s
);
1046 static void exp2 (LexState
*ls
, vardesc
*v
) {
1050 prefixexp(ls
, v
, &s
);
1051 while ((op
= is_in(ls
->token
, binop
)) >= 0) {
1054 /* '^' is right associative, so must 'simulate' a higher priority */
1055 pop_to(ls
, &s
, (op
== POW
)?priority
[op
]+1:priority
[op
]);
1058 prefixexp(ls
, v
, &s
);
1068 static void var_or_func (LexState
*ls
, vardesc
*v
) {
1069 /* var_or_func -> ['%'] NAME var_or_func_tail */
1070 if (optional(ls
, '%')) { /* upvalue? */
1071 pushupvalue(ls
, str_checkname(ls
));
1073 v
->info
= 0; /* closed expression */
1075 else /* variable name */
1076 singlevar(ls
, str_checkname(ls
), v
, 0);
1077 var_or_func_tail(ls
, v
);
1081 static void var_or_func_tail (LexState
*ls
, vardesc
*v
) {
1083 switch (ls
->token
) {
1084 case '.': /* var_or_func_tail -> '.' NAME */
1086 lua_pushvar(ls
, v
); /* 'v' must be on stack */
1088 v
->info
= checkname(ls
);
1091 case '[': /* var_or_func_tail -> '[' exp1 ']' */
1093 lua_pushvar(ls
, v
); /* 'v' must be on stack */
1099 case ':': /* var_or_func_tail -> ':' NAME funcparams */
1101 lua_pushvar(ls
, v
); /* 'v' must be on stack */
1102 code_oparg(ls
, PUSHSELF
, checkname(ls
), 1);
1104 v
->info
= funcparams(ls
, 1);
1107 case '(': case STRING
: case '{': /* var_or_func_tail -> funcparams */
1108 lua_pushvar(ls
, v
); /* 'v' must be on stack */
1110 v
->info
= funcparams(ls
, 0);
1113 default: return; /* should be follow... */
1118 static int funcparams (LexState
*ls
, int slf
) {
1119 FuncState
*fs
= ls
->fs
;
1120 int nparams
= 1; /* in cases STRING and constructor */
1121 switch (ls
->token
) {
1122 case '(': { /* funcparams -> '(' explist ')' */
1123 int line
= ls
->linenumber
;
1127 check_match(ls
, ')', '(', line
);
1128 close_exp(ls
, e
.pc
, 1);
1133 case '{': /* funcparams -> constructor */
1137 case STRING
: /* funcparams -> STRING */
1138 code_string(ls
, ls
->seminfo
.ts
); /* must use 'seminfo' before "next" */
1143 luaX_error(ls
, "function arguments expected");
1146 code_byte(fs
, CALL
);
1147 code_byte(fs
, 0); /* save space for nresult */
1148 code_byte(fs
, (Byte
)(nparams
+slf
));
1152 static void explist (LexState
*ls
, listdesc
*d
) {
1153 switch (ls
->token
) {
1154 case ELSE
: case ELSEIF
: case END
: case UNTIL
:
1155 case EOS
: case ';': case ')':
1165 static void explist1 (LexState
*ls
, listdesc
*d
) {
1169 while (ls
->token
== ',') {
1171 lua_pushvar(ls
, &v
);
1178 lua_pushvar(ls
, &v
);
1183 static void parlist (LexState
*ls
) {
1186 switch (ls
->token
) {
1187 case DOTS
: /* parlist -> DOTS */
1192 case NAME
: /* parlist, tailparlist -> NAME [',' tailparlist] */
1194 store_localvar(ls
, str_checkname(ls
), nparams
++);
1195 if (ls
->token
== ',') {
1197 switch (ls
->token
) {
1198 case DOTS
: /* tailparlist -> DOTS */
1203 case NAME
: /* tailparlist -> NAME [',' tailparlist] */
1206 default: luaX_error(ls
, "NAME or `...' expected");
1211 case ')': break; /* parlist -> empty */
1213 default: luaX_error(ls
, "NAME or `...' expected");
1215 code_args(ls
, nparams
, dots
);
1218 static int localnamelist (LexState
*ls
) {
1219 /* localnamelist -> NAME {',' NAME} */
1221 store_localvar(ls
, str_checkname(ls
), 0);
1222 while (ls
->token
== ',') {
1224 store_localvar(ls
, str_checkname(ls
), i
++);
1229 static void decinit (LexState
*ls
, listdesc
*d
) {
1230 /* decinit -> ['=' explist1] */
1231 if (ls
->token
== '=') {
1242 static int assignment (LexState
*ls
, vardesc
*v
, int nvars
) {
1244 checklimit(ls
, nvars
, MAXVARSLH
, "variables in a multiple assignment");
1246 if (ls
->token
== ',') { /* assignment -> ',' NAME assignment */
1249 var_or_func(ls
, &nv
);
1251 luaX_error(ls
, "syntax error");
1252 left
= assignment(ls
, &nv
, nvars
+1);
1254 else { /* assignment -> '=' explist1 */
1258 adjust_mult_assign(ls
, nvars
, &d
);
1260 if (v
->k
!= VINDEXED
|| left
+(nvars
-1) == 0) {
1261 /* global/local var or indexed var without values in between */
1264 else { /* indexed var with values in between*/
1265 code_oparg(ls
, SETTABLE
, left
+(nvars
-1), -1);
1266 left
+= 2; /* table&index are not popped, because they aren't on top */
1272 static void constructor (LexState
*ls
) {
1273 /* constructor -> '{' part [';' part] '}' */
1274 int line
= ls
->linenumber
;
1275 int pc
= SaveWord(ls
);
1282 if (ls
->token
== ';') {
1285 part(ls
, &other_cd
);
1286 if (cd
.k
== other_cd
.k
) /* repeated parts? */
1287 luaX_error(ls
, "invalid constructor syntax");
1288 nelems
+= other_cd
.n
;
1290 check_match(ls
, '}', '{', line
);
1291 fix_opcode(ls
, pc
, CREATEARRAY
, nelems
);
1294 static void part (LexState
*ls
, constdesc
*cd
) {
1295 switch (ls
->token
) {
1296 case ';': case '}': /* part -> empty */
1304 if (ls
->token
== '=') {
1307 code_constant(ls
, v
.info
);
1310 code_string(ls
, ls
->fs
->localvar
[v
.info
]);
1313 error_unexpected(ls
);
1317 cd
->n
= recfields(ls
);
1318 cd
->k
= 1; /* record */
1321 lua_pushvar(ls
, &v
);
1322 cd
->n
= listfields(ls
);
1323 cd
->k
= 0; /* list */
1328 case '[': /* part -> recfield recfields */
1330 cd
->n
= recfields(ls
);
1331 cd
->k
= 1; /* record */
1334 default: /* part -> exp1 listfields */
1336 cd
->n
= listfields(ls
);
1337 cd
->k
= 0; /* list */
1342 static int recfields (LexState
*ls
) {
1343 /* recfields -> { ',' recfield } [','] */
1344 int n
= 1; /* one has been read before */
1345 while (ls
->token
== ',') {
1347 if (ls
->token
== ';' || ls
->token
== '}')
1351 if (n
%RFIELDS_PER_FLUSH
== 0)
1352 flush_record(ls
, RFIELDS_PER_FLUSH
);
1354 flush_record(ls
, n
%RFIELDS_PER_FLUSH
);
1358 static int listfields (LexState
*ls
) {
1359 /* listfields -> { ',' exp1 } [','] */
1360 int n
= 1; /* one has been read before */
1361 while (ls
->token
== ',') {
1363 if (ls
->token
== ';' || ls
->token
== '}')
1367 if (n
%LFIELDS_PER_FLUSH
== 0)
1368 flush_list(ls
, n
/LFIELDS_PER_FLUSH
- 1, LFIELDS_PER_FLUSH
);
1370 flush_list(ls
, n
/LFIELDS_PER_FLUSH
, n
%LFIELDS_PER_FLUSH
);
1374 static void recfield (LexState
*ls
) {
1375 /* recfield -> (NAME | '['exp1']') = exp1 */
1376 switch (ls
->token
) {
1378 code_constant(ls
, checkname(ls
));
1387 default: luaX_error(ls
, "NAME or `[' expected");