History

Lua 4.0

Lua Team committed 26 years ago

Commit e22497f1 parent 0125a77117 files · +12837 −10103Browse files

Showing the changes to src/lparser.c (1 of 117 files). Show all

Unified · Split

src/lparser.c+822−1090
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lparser.c,v 1.37a 1999/06/17 17:04:03 roberto Exp $2** $Id: lparser.c,v 1.116 2000/10/27 11:39:52 roberto Exp $
3** LL(1) Parser and code generator for Lua3** LL(1) Parser and code generator for Lua
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -8,1385 +8,1117 @@ · 2 unmodified lines
8#include <stdio.h>8#include <stdio.h>
9#include <string.h>9#include <string.h>
10 10
11#include "lauxlib.h"11#include "lua.h"
12#include "ldo.h"12
13#include "lcode.h"
13#include "lfunc.h"14#include "lfunc.h"
14#include "llex.h"15#include "llex.h"
15#include "lmem.h"16#include "lmem.h"
17#include "lobject.h"
16#include "lopcodes.h"18#include "lopcodes.h"
17#include "lparser.h"19#include "lparser.h"
18#include "lstate.h"20#include "lstate.h"
19#include "lstring.h"21#include "lstring.h"
20#include "lua.h"
21#include "luadebug.h"
22#include "lzio.h"
23
24
25
26/* size of a "normal" jump instruction: OpCode + 1 byte */
27#define JMPSIZE 2
28
29/* maximum number of local variables */
30#ifndef MAXLOCALS
31#define MAXLOCALS 200 /* arbitrary limit (<256) */
32#endif
33
34
35/* maximum number of upvalues */
36#ifndef MAXUPVALUES
37#define MAXUPVALUES 32 /* arbitrary limit (<256) */
38#endif
39
40
41/* maximum number of variables in the left side of an assignment */
42#ifndef MAXVARSLH
43#define MAXVARSLH 100 /* arbitrary limit (<255) */
44#endif
45
46
47/* maximum number of parameters in a function */
48#ifndef MAXPARAMS
49#define MAXPARAMS 100 /* arbitrary limit (<ZEROVARARG) */
50#endif
51
52
53/*
54** Variable descriptor:
55** must include an "exp" option because LL(1) cannot distinguish
56** between variables, upvalues and function calls on first sight.
57*/
58typedef enum {
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) */
64} varkind;
65
66typedef struct vardesc {
67 varkind k;
68 int info;
69} vardesc;
70
71
72/*
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"
77*/
78typedef struct listdesc {
79 int n;
80 int pc; /* 0 if last expression is closed */
81} listdesc;
82 22
83 23
84/*24/*
85** Constructors descriptor:25** Constructors descriptor:
86** "n" indicates number of elements, and "k" signals whether26** `n' indicates number of elements, and `k' signals whether
87** it is a list constructor (k = 0) or a record constructor (k = 1)27** it is a list constructor (k = 0) or a record constructor (k = 1)
88** or empty (k = ';' or '}')28** or empty (k = ';' or '}')
89*/29*/
90typedef struct constdesc {30typedef struct Constdesc {
91 int n;31 int n;
92 int k;32 int k;
93} constdesc;33} Constdesc;
34
35
36typedef struct Breaklabel {
37 struct Breaklabel *previous; /* chain */
38 int breaklist;
39 int stacklevel;
40} Breaklabel;
94 41
95 42
96/* state needed to generate code for a given function */
97typedef 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 */
109} FuncState;
110 43
111 44
112/*45/*
113** prototypes for non-terminal functions46** prototypes for recursive non-terminal functions
114*/47*/
115static int assignment (LexState *ls, vardesc *v, int nvars);
116static int cond (LexState *ls);
117static int funcname (LexState *ls, vardesc *v);
118static int funcparams (LexState *ls, int slf);
119static int listfields (LexState *ls);
120static int localnamelist (LexState *ls);
121static int optional (LexState *ls, int c);
122static int recfields (LexState *ls);
123static int stat (LexState *ls);
124static void block (LexState *ls);
125static void body (LexState *ls, int needself, int line);48static void body (LexState *ls, int needself, int line);
126static void chunk (LexState *ls);49static void chunk (LexState *ls);
127static void constructor (LexState *ls);50static void constructor (LexState *ls);
128static void decinit (LexState *ls, listdesc *d);51static void expr (LexState *ls, expdesc *v);
129static void exp0 (LexState *ls, vardesc *v);
130static void exp1 (LexState *ls);52static void exp1 (LexState *ls);
131static void exp2 (LexState *ls, vardesc *v);
132static void explist (LexState *ls, listdesc *e);
133static void explist1 (LexState *ls, listdesc *e);
134static void ifpart (LexState *ls, int line);
135static void parlist (LexState *ls);
136static void part (LexState *ls, constdesc *cd);
137static void recfield (LexState *ls);
138static void ret (LexState *ls);
139static void statlist (LexState *ls);
140static void var_or_func (LexState *ls, vardesc *v);
141static void var_or_func_tail (LexState *ls, vardesc *v);
142
143
144
145static void checklimit (LexState *ls, int val, int limit, char *msg) {
146 if (val > limit) {
147 char buff[100];
148 sprintf(buff, "too many %s (limit=%d)", msg, limit);
149 luaX_error(ls, buff);
150 }
151}
152
153 53
154static void check_pc (FuncState *fs, int n) {
155 luaM_growvector(fs->f->code, fs->pc, n, Byte, codeEM, MAX_INT);
156}
157
158
159static void code_byte (FuncState *fs, Byte c) {
160 check_pc(fs, 1);
161 fs->f->code[fs->pc++] = c;
162}
163
164
165static 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;
172 }
173}
174 54
175 55
176static void code_oparg_at (LexState *ls, int pc, OpCode op,56static void next (LexState *ls) {
177 int arg, int delta) {57 ls->lastline = ls->linenumber;
178 Byte *code = ls->fs->f->code;58 if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
179 deltastack(ls, delta);59 ls->t = ls->lookahead; /* use this one */
180 if (arg <= MAX_BYTE) {60 ls->lookahead.token = TK_EOS; /* and discharge it */
181 code[pc] = (Byte)op;
182 code[pc+1] = (Byte)arg;
183 }
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);
190 pc += 2;
191 }
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);
195 }61 }
62 else
63 ls->t.token = luaX_lex(ls, &ls->t.seminfo); /* read next token */
196}64}
197 65
198 66
199static int codesize (int arg) {67static void lookahead (LexState *ls) {
200 if (arg <= MAX_BYTE) return 2; /* opcode + 1 byte */68 LUA_ASSERT(ls->lookahead.token == TK_EOS, "two look-aheads");
201 else if (arg <= MAX_WORD) return 3; /* opcode + 1 word (2 bytes) */69 ls->lookahead.token = luaX_lex(ls, &ls->lookahead.seminfo);
202 else return 5; /* LONGARG + 1 byte + opcode + 1 word (2 bytes) */
203}70}
204 71
205 72
206static int fix_opcode (LexState *ls, int pc, OpCode op, int arg) {73static void error_expected (LexState *ls, int token) {
207 int tomove = codesize(arg)-2;74 char buff[100], t[TOKEN_LEN];
208 if (tomove > 0) { /* need to open space? */75 luaX_token2str(token, t);
209 FuncState *fs = ls->fs;76 sprintf(buff, "`%.20s' expected", t);
210 TProtoFunc *f = fs->f;77 luaK_error(ls, buff);
211 check_pc(fs, tomove);
212 luaO_memup(f->code+pc+tomove, f->code+pc, fs->pc-pc);
213 fs->pc += tomove;
214 }
215 code_oparg_at(ls, pc, op, arg, 0);
216 return tomove;
217}78}
218 79
219 80
220static void code_oparg (LexState *ls, OpCode op, int arg, int delta) {81static void check (LexState *ls, int c) {
221 int size = codesize(arg);82 if (ls->t.token != c)
222 check_pc(ls->fs, size);83 error_expected(ls, c);
223 code_oparg_at(ls, ls->fs->pc, op, arg, delta);84 next(ls);
224 ls->fs->pc += size;
225}85}
226 86
227 87
228static void code_opcode (LexState *ls, OpCode op, int delta) {88static void check_condition (LexState *ls, int c, const char *msg) {
229 deltastack(ls, delta);89 if (!c) luaK_error(ls, msg);
230 code_byte(ls->fs, (Byte)op);
231}90}
232 91
233 92
234static void code_constant (LexState *ls, int c) {93static int optional (LexState *ls, int c) {
235 code_oparg(ls, PUSHCONSTANT, c, 1);94 if (ls->t.token == c) {
95 next(ls);
96 return 1;
97 }
98 else return 0;
236}99}
237 100
238 101
239static int next_constant (FuncState *fs) {102static void check_match (LexState *ls, int what, int who, int where) {
240 TProtoFunc *f = fs->f;103 if (ls->t.token != what) {
241 luaM_growvector(f->consts, f->nconsts, 1, TObject, constantEM, MAX_ARG);104 if (where == ls->linenumber)
242 return f->nconsts++;105 error_expected(ls, what);
106 else {
107 char buff[100];
108 char t_what[TOKEN_LEN], t_who[TOKEN_LEN];
109 luaX_token2str(what, t_what);
110 luaX_token2str(who, t_who);
111 sprintf(buff, "`%.20s' expected (to close `%.20s' at line %d)",
112 t_what, t_who, where);
113 luaK_error(ls, buff);
114 }
115 }
116 next(ls);
243}117}
244 118
245 119
246static int string_constant (FuncState *fs, TaggedString *s) {120static int string_constant (FuncState *fs, TString *s) {
247 TProtoFunc *f = fs->f;121 Proto *f = fs->f;
248 int c = s->constindex;122 int c = s->u.s.constindex;
249 if (!(c < f->nconsts &&123 if (c >= f->nkstr || f->kstr[c] != s) {
250 ttype(&f->consts[c]) == LUA_T_STRING && tsvalue(&f->consts[c]) == s)) {124 luaM_growvector(fs->L, f->kstr, f->nkstr, 1, TString *,
251 c = next_constant(fs);125 "constant table overflow", MAXARG_U);
252 ttype(&f->consts[c]) = LUA_T_STRING;126 c = f->nkstr++;
253 tsvalue(&f->consts[c]) = s;127 f->kstr[c] = s;
254 s->constindex = c; /* hint for next time */128 s->u.s.constindex = c; /* hint for next time */
255 }129 }
256 return c;130 return c;
257}131}
258 132
259 133
260static void code_string (LexState *ls, TaggedString *s) {134static void code_string (LexState *ls, TString *s) {
261 code_constant(ls, string_constant(ls->fs, s));135 luaK_kstr(ls, string_constant(ls->fs, s));
262}
263
264
265#define LIM 20
266static 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;
271 while (--c >= lim) {
272 if (ttype(&cnt[c]) == LUA_T_NUMBER && nvalue(&cnt[c]) == r)
273 return c;
274 }
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;
279 nvalue(&cnt[c]) = r;
280 return c;
281}136}
282 137
283 138
284static void code_number (LexState *ls, real f) {139static TString *str_checkname (LexState *ls) {
285 real af = (f<0) ? -f : f;140 TString *ts;
286 if (0 <= af && af <= (real)MAX_WORD && (int)af == af) {141 check_condition(ls, (ls->t.token == TK_NAME), "<name> expected");
287 /* abs(f) has a short integer value */142 ts = ls->t.seminfo.ts;
288 code_oparg(ls, (f<0) ? PUSHNUMBERNEG : PUSHNUMBER, (int)af, 1);143 next(ls);
289 }144 return ts;
290 else
291 code_constant(ls, real_constant(ls->fs, f));
292}145}
293 146
294 147
295static void flush_record (LexState *ls, int n) {148static int checkname (LexState *ls) {
296 if (n > 0)149 return string_constant(ls->fs, str_checkname(ls));
297 code_oparg(ls, SETMAP, n-1, -2*n);
298}150}
299 151
300 152
301static void flush_list (LexState *ls, int m, int n) {153static int luaI_registerlocalvar (LexState *ls, TString *varname) {
302 if (n > 0) {154 Proto *f = ls->fs->f;
303 code_oparg(ls, SETLIST, m, -n);155 luaM_growvector(ls->L, f->locvars, f->nlocvars, 1, LocVar, "", MAX_INT);
304 code_byte(ls->fs, (Byte)n);156 f->locvars[f->nlocvars].varname = varname;
305 }157 return f->nlocvars++;
306}158}
307 159
308 160
309static void luaI_registerlocalvar (FuncState *fs, TaggedString *varname,161static void new_localvar (LexState *ls, TString *name, int n) {
310 int line) {162 FuncState *fs = ls->fs;
311 if (fs->nvars != -1) { /* debug information? */163 luaX_checklimit(ls, fs->nactloc+n+1, MAXLOCALS, "local variables");
312 TProtoFunc *f = fs->f;164 fs->actloc[fs->nactloc+n] = luaI_registerlocalvar(ls, name);
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;
316 fs->nvars++;
317 }
318}165}
319 166
320 167
321static void luaI_unregisterlocalvar (FuncState *fs, int line) {168static void adjustlocalvars (LexState *ls, int nvars) {
322 luaI_registerlocalvar(fs, NULL, line);169 FuncState *fs = ls->fs;
170 while (nvars--)
171 fs->f->locvars[fs->actloc[fs->nactloc++]].startpc = fs->pc;
323}172}
324 173
325 174
326static void store_localvar (LexState *ls, TaggedString *name, int n) {175static void removelocalvars (LexState *ls, int nvars) {
327 FuncState *fs = ls->fs;176 FuncState *fs = ls->fs;
328 checklimit(ls, fs->nlocalvar+n+1, MAXLOCALS, "local variables");177 while (nvars--)
329 fs->localvar[fs->nlocalvar+n] = name;178 fs->f->locvars[fs->actloc[--fs->nactloc]].endpc = fs->pc;
330 luaI_registerlocalvar(fs, name, ls->linenumber);
331}179}
332 180
333 181
334static void add_localvar (LexState *ls, TaggedString *name) {182static void new_localvarstr (LexState *ls, const char *name, int n) {
335 store_localvar(ls, name, 0);183 new_localvar(ls, luaS_newfixed(ls->L, name), n);
336 ls->fs->nlocalvar++;
337}184}
338 185
339 186
340static void correctvarlines (LexState *ls, int nvars) {187static int search_local (LexState *ls, TString *n, expdesc *var) {
341 FuncState *fs = ls->fs;188 FuncState *fs;
342 if (fs->nvars != -1) { /* debug information? */189 int level = 0;
343 for (; nvars; nvars--) { /* correct line information */190 for (fs=ls->fs; fs; fs=fs->prev) {
344 fs->f->locvars[fs->nvars-nvars].line = fs->lastsetline; 191 int i;
192 for (i=fs->nactloc-1; i >= 0; i--) {
193 if (n == fs->f->locvars[fs->actloc[i]].varname) {
194 var->k = VLOCAL;
195 var->u.index = i;
196 return level;
197 }
345 }198 }
199 level++; /* `var' not found; check outer level */
346 }200 }
201 var->k = VGLOBAL; /* not found in any level; must be global */
202 return -1;
347}203}
348 204
349 205
350static int aux_localname (FuncState *fs, TaggedString *n) {206static void singlevar (LexState *ls, TString *n, expdesc *var) {
351 int i;207 int level = search_local(ls, n, var);
352 for (i=fs->nlocalvar-1; i >= 0; i--)208 if (level >= 1) /* neither local (0) nor global (-1)? */
353 if (n == fs->localvar[i]) return i; /* local var index */209 luaX_syntaxerror(ls, "cannot access a variable in outer scope", n->str);
354 return -1; /* not found */210 else if (level == -1) /* global? */
355}211 var->u.index = string_constant(ls->fs, n);
356
357
358static 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? */
362 var->k = VLOCAL;
363 var->info = i;
364 }
365 else {
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);
370 var->k = VGLOBAL;
371 var->info = string_constant(fs, n);
372 }
373}212}
374 213
375 214
376static int indexupvalue (LexState *ls, TaggedString *n) {215static int indexupvalue (LexState *ls, expdesc *v) {
377 FuncState *fs = ls->fs;216 FuncState *fs = ls->fs;
378 vardesc v;
379 int i;217 int i;
380 singlevar(ls, n, &v, 1);
381 for (i=0; i<fs->nupvalues; i++) {218 for (i=0; i<fs->nupvalues; i++) {
382 if (fs->upvalues[i].k == v.k && fs->upvalues[i].info == v.info)219 if (fs->upvalues[i].k == v->k && fs->upvalues[i].u.index == v->u.index)
383 return i;220 return i;
384 }221 }
385 /* new one */222 /* new one */
386 ++(fs->nupvalues);223 luaX_checklimit(ls, fs->nupvalues+1, MAXUPVALUES, "upvalues");
387 checklimit(ls, fs->nupvalues, MAXUPVALUES, "upvalues");224 fs->upvalues[fs->nupvalues] = *v;
388 fs->upvalues[i] = v; /* i = fs->nupvalues - 1 */225 return fs->nupvalues++;
389 return i;
390}
391
392
393static 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);
399}
400
401
402
403static 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;
407 }
408}
409
410
411static void adjuststack (LexState *ls, int n) {
412 if (n > 0)
413 code_oparg(ls, POP, n, -n);
414 else if (n < 0)
415 code_oparg(ls, PUSHNIL, (-n)-1, -n);
416}226}
417 227
418 228
419static void close_exp (LexState *ls, int pc, int nresults) {229static void pushupvalue (LexState *ls, TString *n) {
420 if (pc > 0) { /* expression is an open function call? */230 FuncState *fs = ls->fs;
421 Byte *code = ls->fs->f->code;231 expdesc v;
422 code[pc-1] = (Byte)nresults; /* set nresults */232 int level = search_local(ls, n, &v);
423 /* push results, pop params (at code[pc]) and function */233 if (level == -1) { /* global? */
424 deltastack(ls, nresults-(code[pc]+1));234 if (fs->prev == NULL)
235 luaX_syntaxerror(ls, "cannot access upvalue in main", n->str);
236 v.u.index = string_constant(fs->prev, n);
425 }237 }
426#ifdef DEBUG238 else if (level != 1)
427 code_oparg(ls, CHECKSTACK, ls->fs->stacksize, 0);239 luaX_syntaxerror(ls,
428#endif240 "upvalue must be global or local to immediately outer scope", n->str);
241 luaK_code1(fs, OP_PUSHUPVALUE, indexupvalue(ls, &v));
429}242}
430 243
431 244
432static void adjust_mult_assign (LexState *ls, int nvars, listdesc *d) {245static void adjust_mult_assign (LexState *ls, int nvars, int nexps) {
433 int diff = d->n - nvars;246 FuncState *fs = ls->fs;
434 if (d->pc == 0) { /* list is closed */247 int diff = nexps - nvars;
435 /* push or pop eventual difference between list lengths */248 if (nexps > 0 && luaK_lastisopen(fs)) { /* list ends in a function call */
436 adjuststack(ls, diff);
437 }
438 else { /* must correct function call */
439 diff--; /* do not count function call itself */249 diff--; /* do not count function call itself */
440 if (diff <= 0) { /* more variables than values? */250 if (diff <= 0) { /* more variables than values? */
441 /* function call must provide extra values */251 luaK_setcallreturns(fs, -diff); /* function call provide extra values */
442 close_exp(ls, d->pc, -diff);252 diff = 0; /* no more difference */
443 }
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 */
447 }253 }
254 else /* more values than variables */
255 luaK_setcallreturns(fs, 0); /* call should provide no value */
448 }256 }
257 /* push or pop eventual difference between list lengths */
258 luaK_adjuststack(fs, diff);
449}259}
450 260
451 261
452static void code_args (LexState *ls, int nparams, int dots) {262static void code_params (LexState *ls, int nparams, int dots) {
453 FuncState *fs = ls->fs;263 FuncState *fs = ls->fs;
454 fs->nlocalvar += nparams; /* "self" may already be there */264 adjustlocalvars(ls, nparams);
455 checklimit(ls, fs->nlocalvar, MAXPARAMS, "parameters");265 luaX_checklimit(ls, fs->nactloc, MAXPARAMS, "parameters");
456 nparams = fs->nlocalvar;266 fs->f->numparams = fs->nactloc; /* `self' could be there already */
457 if (!dots) {267 fs->f->is_vararg = dots;
458 fs->f->code[1] = (Byte)nparams; /* fill-in arg information */268 if (dots) {
459 deltastack(ls, nparams);269 new_localvarstr(ls, "arg", 0);
460 }270 adjustlocalvars(ls, 1);
461 else {
462 fs->f->code[1] = (Byte)(nparams+ZEROVARARG);
463 deltastack(ls, nparams+1);
464 add_localvar(ls, luaS_new("arg"));
465 }
466}
467
468
469static void unloaddot (LexState *ls, vardesc *v) {
470 /* dotted variables <a.x> must be stored like regular indexed vars <a["x"]> */
471 if (v->k == VDOT) {
472 code_constant(ls, v->info);
473 v->k = VINDEXED;
474 }
475}
476
477
478static void lua_pushvar (LexState *ls, vardesc *var) {
479 switch (var->k) {
480 case VLOCAL:
481 code_oparg(ls, PUSHLOCAL, var->info, 1);
482 break;
483 case VGLOBAL:
484 code_oparg(ls, GETGLOBAL, var->info, 1);
485 break;
486 case VDOT:
487 code_oparg(ls, GETDOTTED, var->info, 0);
488 break;
489 case VINDEXED:
490 code_opcode(ls, GETTABLE, -1);
491 break;
492 case VEXP:
493 close_exp(ls, var->info, 1); /* function must return 1 value */
494 break;
495 }
496 var->k = VEXP;
497 var->info = 0; /* now this is a closed expression */
498}
499
500
501static void storevar (LexState *ls, vardesc *var) {
502 switch (var->k) {
503 case VLOCAL:
504 code_oparg(ls, SETLOCAL, var->info, -1);
505 break;
506 case VGLOBAL:
507 code_oparg(ls, SETGLOBAL, var->info, -1);
508 break;
509 case VINDEXED:
510 code_opcode(ls, SETTABLEPOP, -3);
511 break;
512 default:
513 LUA_INTERNALERROR("invalid var kind to store");
514 }271 }
272 luaK_deltastack(fs, fs->nactloc); /* count parameters in the stack */
515}273}
516 274
517 275
518static int fix_jump (LexState *ls, int pc, OpCode op, int n) {276static void enterbreak (FuncState *fs, Breaklabel *bl) {
519 /* jump is relative to position following jump instruction */277 bl->stacklevel = fs->stacklevel;
520 return fix_opcode(ls, pc, op, n-(pc+JMPSIZE));278 bl->breaklist = NO_JUMP;
521}279 bl->previous = fs->bl;
522 280 fs->bl = bl;
523
524static 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);
527}281}
528 282
529 283
530static void codeIf (LexState *ls, int thenAdd, int elseAdd) {284static void leavebreak (FuncState *fs, Breaklabel *bl) {
531 FuncState *fs = ls->fs;285 fs->bl = bl->previous;
532 int elseinit = elseAdd+JMPSIZE;286 LUA_ASSERT(bl->stacklevel == fs->stacklevel, "wrong levels");
533 if (fs->pc == elseinit) { /* no else part? */287 luaK_patchlist(fs, bl->breaklist, luaK_getlabel(fs));
534 fs->pc -= JMPSIZE;
535 elseinit = fs->pc;
536 }
537 else
538 elseinit += fix_jump(ls, elseAdd, JMP, fs->pc);
539 fix_jump(ls, thenAdd, IFFJMP, elseinit);
540}288}
541 289
542 290
543static void func_onstack (LexState *ls, FuncState *func) {291static void pushclosure (LexState *ls, FuncState *func) {
544 FuncState *fs = ls->fs;292 FuncState *fs = ls->fs;
293 Proto *f = fs->f;
545 int i;294 int i;
546 int c = next_constant(fs);295 for (i=0; i<func->nupvalues; i++)
547 ttype(&fs->f->consts[c]) = LUA_T_PROTO;296 luaK_tostack(ls, &func->upvalues[i], 1);
548 fs->f->consts[c].value.tf = func->f;297 luaM_growvector(ls->L, f->kproto, f->nkproto, 1, Proto *,
549 if (func->nupvalues == 0)298 "constant table overflow", MAXARG_A);
550 code_constant(ls, c);299 f->kproto[f->nkproto++] = func->f;
551 else {300 luaK_code2(fs, OP_CLOSURE, f->nkproto-1, func->nupvalues);
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);
557 }
558}301}
559 302
560 303
561static void init_state (LexState *ls, FuncState *fs, TaggedString *source) {304static void open_func (LexState *ls, FuncState *fs) {
562 TProtoFunc *f = luaF_newproto();305 Proto *f = luaF_newproto(ls->L);
563 fs->prev = ls->fs; /* linked list of funcstates */306 fs->prev = ls->fs; /* linked list of funcstates */
307 fs->ls = ls;
308 fs->L = ls->L;
564 ls->fs = fs;309 ls->fs = fs;
565 fs->stacksize = 0;310 fs->stacklevel = 0;
566 fs->maxstacksize = 0;311 fs->nactloc = 0;
567 fs->nlocalvar = 0;
568 fs->nupvalues = 0;312 fs->nupvalues = 0;
569 fs->lastsetline = 0;313 fs->bl = NULL;
570 fs->f = f;314 fs->f = f;
571 f->source = source;315 f->source = ls->source;
572 fs->pc = 0;316 fs->pc = 0;
317 fs->lasttarget = 0;
318 fs->lastline = 0;
319 fs->jlt = NO_JUMP;
573 f->code = NULL;320 f->code = NULL;
574 fs->nvars = (L->debug) ? 0 : -1; /* flag no debug information? */321 f->maxstacksize = 0;
575 code_byte(fs, 0); /* to be filled with maxstacksize */322 f->numparams = 0; /* default for main chunk */
576 code_byte(fs, 0); /* to be filled with arg information */323 f->is_vararg = 0; /* default for main chunk */
577 /* push function (to avoid GC) */
578 tfvalue(L->stack.top) = f; ttype(L->stack.top) = LUA_T_PROTO;
579 incr_top;
580}324}
581 325
582 326
583static void close_func (LexState *ls) {327static void close_func (LexState *ls) {
328 lua_State *L = ls->L;
584 FuncState *fs = ls->fs;329 FuncState *fs = ls->fs;
585 TProtoFunc *f = fs->f;330 Proto *f = fs->f;
586 code_opcode(ls, ENDCODE, 0);331 luaK_code0(fs, OP_END);
587 f->code[0] = (Byte)fs->maxstacksize;332 luaK_getlabel(fs); /* close eventual list of pending jumps */
588 luaM_reallocvector(f->code, fs->pc, Byte);333 luaM_reallocvector(L, f->code, fs->pc, Instruction);
589 luaM_reallocvector(f->consts, f->nconsts, TObject);334 luaM_reallocvector(L, f->kstr, f->nkstr, TString *);
590 if (fs->nvars != -1) { /* debug information? */335 luaM_reallocvector(L, f->knum, f->nknum, Number);
591 luaI_registerlocalvar(fs, NULL, -1); /* flag end of vector */336 luaM_reallocvector(L, f->kproto, f->nkproto, Proto *);
592 luaM_reallocvector(f->locvars, fs->nvars, LocVar);337 removelocalvars(ls, fs->nactloc);
593 }338 luaM_reallocvector(L, f->locvars, f->nlocvars, LocVar);
339 luaM_reallocvector(L, f->lineinfo, f->nlineinfo+1, int);
340 f->lineinfo[f->nlineinfo++] = MAX_INT; /* end flag */
341 luaF_protook(L, f, fs->pc); /* proto is ok now */
594 ls->fs = fs->prev;342 ls->fs = fs->prev;
595 L->stack.top--; /* pop function */343 LUA_ASSERT(fs->bl == NULL, "wrong list end");
596}
597
598
599
600static int expfollow [] = {ELSE, ELSEIF, THEN, IF, WHILE, REPEAT, DO, NAME,
601 LOCAL, FUNCTION, END, UNTIL, RETURN, ')', ']', '}', ';', EOS, ',', 0};
602
603
604static int is_in (int tok, int *toks) {
605 int *t;
606 for (t=toks; *t; t++)
607 if (*t == tok) return t-toks;
608 return -1;
609}
610
611
612static void next (LexState *ls) {
613 ls->token = luaX_lex(ls);
614}
615
616
617static 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);
622}
623
624
625static void error_unexpected (LexState *ls) {
626 luaX_error(ls, "unexpected token");
627}
628
629
630static void error_unmatched (LexState *ls, int what, int who, int where) {
631 if (where == ls->linenumber)
632 error_expected(ls, what);
633 else {
634 char buff[100];
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);
641 }
642}
643
644static void check (LexState *ls, int c) {
645 if (ls->token != c)
646 error_expected(ls, c);
647 next(ls);
648}
649
650static 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' */
654 next(ls);
655}
656
657static int checkname (LexState *ls) {
658 int sc;
659 if (ls->token != NAME)
660 luaX_error(ls, "`NAME' expected");
661 sc = string_constant(ls->fs, ls->seminfo.ts);
662 next(ls);
663 return sc;
664}
665
666
667static TaggedString *str_checkname (LexState *ls) {
668 int i = checkname(ls); /* this call may realloc `f->consts' */
669 return tsvalue(&ls->fs->f->consts[i]);
670}
671
672
673static int optional (LexState *ls, int c) {
674 if (ls->token == c) {
675 next(ls);
676 return 1;
677 }
678 else return 0;
679}344}
680 345
681 346
682TProtoFunc *luaY_parser (ZIO *z) {347Proto *luaY_parser (lua_State *L, ZIO *z) {
683 struct LexState lexstate;348 struct LexState lexstate;
684 struct FuncState funcstate;349 struct FuncState funcstate;
685 luaX_setinput(&lexstate, z);350 luaX_setinput(L, &lexstate, z, luaS_new(L, zname(z)));
686 init_state(&lexstate, &funcstate, luaS_new(zname(z)));351 open_func(&lexstate, &funcstate);
687 next(&lexstate); /* read first token */352 next(&lexstate); /* read first token */
688 chunk(&lexstate);353 chunk(&lexstate);
689 if (lexstate.token != EOS)354 check_condition(&lexstate, (lexstate.t.token == TK_EOS), "<eof> expected");
690 luaX_error(&lexstate, "<eof> expected");
691 close_func(&lexstate);355 close_func(&lexstate);
356 LUA_ASSERT(funcstate.prev == NULL, "wrong list end");
357 LUA_ASSERT(funcstate.nupvalues == 0, "no upvalues in main");
692 return funcstate.f;358 return funcstate.f;
693}359}
694 360
695 361
696 362
697/*============================================================*/363/*============================================================*/
698/* GRAMAR RULES */364/* GRAMMAR RULES */
699/*============================================================*/365/*============================================================*/
700 366
701static void chunk (LexState *ls) {
702 /* chunk -> statlist ret */
703 statlist(ls);
704 ret(ls);
705}
706 367
707static void statlist (LexState *ls) {368static int explist1 (LexState *ls) {
708 /* statlist -> { stat [;] } */369 /* explist1 -> expr { ',' expr } */
709 while (stat(ls)) {370 int n = 1; /* at least one expression */
710 LUA_ASSERT(ls->fs->stacksize == ls->fs->nlocalvar,371 expdesc v;
711 "stack size != # local vars");372 expr(ls, &v);
712 optional(ls, ';');373 while (ls->t.token == ',') {
374 luaK_tostack(ls, &v, 1); /* gets only 1 value from previous expression */
375 next(ls); /* skip comma */
376 expr(ls, &v);
377 n++;
713 }378 }
379 luaK_tostack(ls, &v, 0); /* keep open number of values of last expression */
380 return n;
714}381}
715 382
716static int stat (LexState *ls) {
717 int line = ls->linenumber; /* may be needed for error messages */
718 FuncState *fs = ls->fs;
719 switch (ls->token) {
720 case IF: /* stat -> IF ifpart END */
721 ifpart(ls, line);
722 return 1;
723 383
724 case WHILE: { /* stat -> WHILE cond DO block END */384static void funcargs (LexState *ls, int slf) {
725 TProtoFunc *f = fs->f;385 FuncState *fs = ls->fs;
726 int while_init = fs->pc;386 int slevel = fs->stacklevel - slf - 1; /* where is func in the stack */
727 int cond_end, cond_size;387 switch (ls->t.token) {
388 case '(': { /* funcargs -> '(' [ explist1 ] ')' */
389 int line = ls->linenumber;
390 int nargs = 0;
728 next(ls);391 next(ls);
729 cond_end = cond(ls);392 if (ls->t.token != ')') /* arg list not empty? */
730 check(ls, DO);393 nargs = explist1(ls);
731 block(ls);394 check_match(ls, ')', '(', line);
732 check_match(ls, END, WHILE, line);395#ifdef LUA_COMPAT_ARGRET
733 cond_size = cond_end-while_init;396 if (nargs > 0) /* arg list is not empty? */
734 check_pc(fs, cond_size);397 luaK_setcallreturns(fs, 1); /* last call returns only 1 value */
735 memcpy(f->code+fs->pc, f->code+while_init, cond_size);398#else
736 luaO_memdown(f->code+while_init, f->code+cond_end, fs->pc-while_init);399 UNUSED(nargs); /* to avoid warnings */
737 while_init += JMPSIZE + fix_jump(ls, while_init, JMP, fs->pc-cond_size);400#endif
738 fix_upjmp(ls, IFTUPJMP, while_init);401 break;
739 return 1;
740 }402 }
741 403 case '{': { /* funcargs -> constructor */
742 case DO: { /* stat -> DO block END */404 constructor(ls);
743 next(ls);405 break;
744 block(ls);
745 check_match(ls, END, DO, line);
746 return 1;
747 }406 }
748 407 case TK_STRING: { /* funcargs -> STRING */
749 case REPEAT: { /* stat -> REPEAT block UNTIL exp1 */408 code_string(ls, ls->t.seminfo.ts); /* must use `seminfo' before `next' */
750 int repeat_init = fs->pc;
751 next(ls);409 next(ls);
752 block(ls);410 break;
753 check_match(ls, UNTIL, REPEAT, line);
754 exp1(ls);
755 fix_upjmp(ls, IFFUPJMP, repeat_init);
756 deltastack(ls, -1); /* pops condition */
757 return 1;
758 }411 }
759 412 default: {
760 case FUNCTION: { /* stat -> FUNCTION funcname body */413 luaK_error(ls, "function arguments expected");
761 int needself;414 break;
762 vardesc v;
763 if (ls->fs->prev) /* inside other function? */
764 return 0;
765 check_debugline(ls);
766 next(ls);
767 needself = funcname(ls, &v);
768 body(ls, needself, line);
769 storevar(ls, &v);
770 return 1;
771 }415 }
416 }
417 fs->stacklevel = slevel; /* call will remove function and arguments */
418 luaK_code2(fs, OP_CALL, slevel, MULT_RET);
419}
772 420
773 case LOCAL: { /* stat -> LOCAL localnamelist decinit */
774 listdesc d;
775 int nvars;
776 check_debugline(ls);
777 next(ls);
778 nvars = localnamelist(ls);
779 decinit(ls, &d);
780 fs->nlocalvar += nvars;
781 correctvarlines(ls, nvars); /* vars will be alive only after decinit */
782 adjust_mult_assign(ls, nvars, &d);
783 return 1;
784 }
785 421
786 case NAME: case '%': { /* stat -> func | ['%'] NAME assignment */422static void var_or_func_tail (LexState *ls, expdesc *v) {
787 vardesc v;423 for (;;) {
788 check_debugline(ls);424 switch (ls->t.token) {
789 var_or_func(ls, &v);425 case '.': { /* var_or_func_tail -> '.' NAME */
790 if (v.k == VEXP) { /* stat -> func */426 next(ls);
791 if (v.info == 0) /* is just an upper value? */427 luaK_tostack(ls, v, 1); /* `v' must be on stack */
792 luaX_error(ls, "syntax error");428 luaK_kstr(ls, checkname(ls));
793 close_exp(ls, v.info, 0);429 v->k = VINDEXED;
430 break;
794 }431 }
795 else { /* stat -> ['%'] NAME assignment */432 case '[': { /* var_or_func_tail -> '[' exp1 ']' */
796 int left = assignment(ls, &v, 1);433 next(ls);
797 adjuststack(ls, left); /* remove eventual 'garbage' left on stack */434 luaK_tostack(ls, v, 1); /* `v' must be on stack */
435 v->k = VINDEXED;
436 exp1(ls);
437 check(ls, ']');
438 break;
798 }439 }
799 return 1;440 case ':': { /* var_or_func_tail -> ':' NAME funcargs */
441 int name;
442 next(ls);
443 name = checkname(ls);
444 luaK_tostack(ls, v, 1); /* `v' must be on stack */
445 luaK_code1(ls->fs, OP_PUSHSELF, name);
446 funcargs(ls, 1);
447 v->k = VEXP;
448 v->u.l.t = v->u.l.f = NO_JUMP;
449 break;
450 }
451 case '(': case TK_STRING: case '{': { /* var_or_func_tail -> funcargs */
452 luaK_tostack(ls, v, 1); /* `v' must be on stack */
453 funcargs(ls, 0);
454 v->k = VEXP;
455 v->u.l.t = v->u.l.f = NO_JUMP;
456 break;
457 }
458 default: return; /* should be follow... */
800 }459 }
460 }
461}
801 462
802 case RETURN: case ';': case ELSE: case ELSEIF:
803 case END: case UNTIL: case EOS: /* 'stat' follow */
804 return 0;
805 463
806 default:464static void var_or_func (LexState *ls, expdesc *v) {
807 error_unexpected(ls);465 /* var_or_func -> ['%'] NAME var_or_func_tail */
808 return 0; /* to avoid warnings */466 if (optional(ls, '%')) { /* upvalue? */
467 pushupvalue(ls, str_checkname(ls));
468 v->k = VEXP;
469 v->u.l.t = v->u.l.f = NO_JUMP;
809 }470 }
471 else /* variable name */
472 singlevar(ls, str_checkname(ls), v);
473 var_or_func_tail(ls, v);
810}474}
811 475
812static int SaveWord (LexState *ls) {
813 int res = ls->fs->pc;
814 check_pc(ls->fs, JMPSIZE);
815 ls->fs->pc += JMPSIZE; /* open space */
816 return res;
817}
818 476
819static int SaveWordPop (LexState *ls) {
820 deltastack(ls, -1); /* pop condition */
821 return SaveWord(ls);
822}
823 477
824static int cond (LexState *ls) {478/*
825 /* cond -> exp1 */479** {======================================================================
826 exp1(ls);480** Rules for Constructors
827 return SaveWordPop(ls);481** =======================================================================
828}482*/
829 483
830static void block (LexState *ls) {
831 /* block -> chunk */
832 FuncState *fs = ls->fs;
833 int nlocalvar = fs->nlocalvar;
834 chunk(ls);
835 adjuststack(ls, fs->nlocalvar - nlocalvar);
836 for (; fs->nlocalvar > nlocalvar; fs->nlocalvar--)
837 luaI_unregisterlocalvar(fs, fs->lastsetline);
838}
839 484
840static int funcname (LexState *ls, vardesc *v) {485static void recfield (LexState *ls) {
841 /* funcname -> NAME [':' NAME | '.' NAME] */486 /* recfield -> (NAME | '['exp1']') = exp1 */
842 int needself = 0;487 switch (ls->t.token) {
843 singlevar(ls, str_checkname(ls), v, 0);488 case TK_NAME: {
844 if (ls->token == ':' || ls->token == '.') {489 luaK_kstr(ls, checkname(ls));
845 needself = (ls->token == ':');490 break;
846 next(ls);491 }
847 lua_pushvar(ls, v);492 case '[': {
848 code_constant(ls, checkname(ls));493 next(ls);
849 v->k = VINDEXED;494 exp1(ls);
495 check(ls, ']');
496 break;
497 }
498 default: luaK_error(ls, "<name> or `[' expected");
850 }499 }
851 return needself;500 check(ls, '=');
852}501 exp1(ls);
853
854static void body (LexState *ls, int needself, int line) {
855 /* body -> '(' parlist ')' chunk END */
856 FuncState newfs;
857 init_state(ls, &newfs, ls->fs->f->source);
858 newfs.f->lineDefined = line;
859 check(ls, '(');
860 if (needself)
861 add_localvar(ls, luaS_new("self"));
862 parlist(ls);
863 check(ls, ')');
864 chunk(ls);
865 check_match(ls, END, FUNCTION, line);
866 close_func(ls);
867 func_onstack(ls, &newfs);
868}502}
869 503
870 504
871static void ifpart (LexState *ls, int line) {505static int recfields (LexState *ls) {
872 /* ifpart -> cond THEN block [ELSE block | ELSEIF ifpart] */506 /* recfields -> recfield { ',' recfield } [','] */
873 int c;507 FuncState *fs = ls->fs;
874 int e;508 int n = 1; /* at least one element */
875 next(ls); /* skip IF or ELSEIF */509 recfield(ls);
876 c = cond(ls);510 while (ls->t.token == ',') {
877 check(ls, THEN);511 next(ls);
878 block(ls);512 if (ls->t.token == ';' || ls->t.token == '}')
879 e = SaveWord(ls);513 break;
880 if (ls->token == ELSEIF)514 recfield(ls);
881 ifpart(ls, line);515 n++;
882 else {516 if (n%RFIELDS_PER_FLUSH == 0)
883 if (optional(ls, ELSE))517 luaK_code1(fs, OP_SETMAP, RFIELDS_PER_FLUSH);
884 block(ls);
885 check_match(ls, END, IF, line);
886 }518 }
887 codeIf(ls, c, e);519 luaK_code1(fs, OP_SETMAP, n%RFIELDS_PER_FLUSH);
520 return n;
888}521}
889 522
890 523
891static void ret (LexState *ls) {524static int listfields (LexState *ls) {
892 /* ret -> [RETURN explist sc] */525 /* listfields -> exp1 { ',' exp1 } [','] */
893 if (optional(ls, RETURN)) {526 FuncState *fs = ls->fs;
894 listdesc e;527 int n = 1; /* at least one element */
895 check_debugline(ls);528 exp1(ls);
896 explist(ls, &e); 529 while (ls->t.token == ',') {
897 if (e.pc > 0) { /* expression is an open function call? */530 next(ls);
898 Byte *code = ls->fs->f->code;531 if (ls->t.token == ';' || ls->t.token == '}')
899 code[e.pc-2] = TAILCALL; /* instead of a conventional CALL */532 break;
900 code[e.pc-1] = (Byte)ls->fs->nlocalvar;533 exp1(ls);
901 }534 n++;
902 else535 luaX_checklimit(ls, n/LFIELDS_PER_FLUSH, MAXARG_A,
903 code_oparg(ls, RETCODE, ls->fs->nlocalvar, 0);536 "`item groups' in a list initializer");
904 ls->fs->stacksize = ls->fs->nlocalvar; /* removes all temp values */537 if (n%LFIELDS_PER_FLUSH == 0)
905 optional(ls, ';');538 luaK_code2(fs, OP_SETLIST, n/LFIELDS_PER_FLUSH - 1, LFIELDS_PER_FLUSH);
906 }539 }
540 luaK_code2(fs, OP_SETLIST, n/LFIELDS_PER_FLUSH, n%LFIELDS_PER_FLUSH);
541 return n;
907}542}
908 543
909 544
910/*
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.
914*/
915
916#define INDNOT 0
917#define INDMINUS 1
918
919/* code of first binary operator */
920#define FIRSTBIN 2
921
922/* code for power operator (last operator)
923** '^' needs special treatment because it is right associative
924*/
925#define POW 13
926
927static int binop [] = {EQ, NE, '>', '<', LE, GE, CONC,
928 '+', '-', '*', '/', '^', 0};
929
930static int priority [POW+1] = {5, 5, 1, 1, 1, 1, 1, 1, 2, 3, 3, 4, 4, 6};
931
932static OpCode opcodes [POW+1] = {NOTOP, MINUSOP, EQOP, NEQOP, GTOP, LTOP,
933 LEOP, GEOP, CONCOP, ADDOP, SUBOP, MULTOP, DIVOP, POWOP};
934
935#define MAXOPS 20 /* op's stack size (arbitrary limit) */
936 545
937typedef struct stack_op {546static void constructor_part (LexState *ls, Constdesc *cd) {
938 int ops[MAXOPS];547 switch (ls->t.token) {
939 int top;548 case ';': case '}': { /* constructor_part -> empty */
940} stack_op;549 cd->n = 0;
941 550 cd->k = ls->t.token;
942 551 break;
943static void exp1 (LexState *ls) {552 }
944 vardesc v;553 case TK_NAME: { /* may be listfields or recfields */
945 exp0(ls, &v);554 lookahead(ls);
946 lua_pushvar(ls, &v);555 if (ls->lookahead.token != '=') /* expression? */
947 if (is_in(ls->token, expfollow) < 0)556 goto case_default;
948 luaX_error(ls, "ill-formed expression");557 /* else go through to recfields */
558 }
559 case '[': { /* constructor_part -> recfields */
560 cd->n = recfields(ls);
561 cd->k = 1; /* record */
562 break;
563 }
564 default: { /* constructor_part -> listfields */
565 case_default:
566 cd->n = listfields(ls);
567 cd->k = 0; /* list */
568 break;
569 }
570 }
949}571}
950 572
951 573
952static void exp0 (LexState *ls, vardesc *v) {574static void constructor (LexState *ls) {
953 /* exp0 -> exp2 {(AND | OR) exp2} */575 /* constructor -> '{' constructor_part [';' constructor_part] '}' */
954 exp2(ls, v);576 FuncState *fs = ls->fs;
955 while (ls->token == AND || ls->token == OR) {577 int line = ls->linenumber;
956 int op = (ls->token == AND) ? ONFJMP : ONTJMP;578 int pc = luaK_code1(fs, OP_CREATETABLE, 0);
957 int pc;579 int nelems;
958 lua_pushvar(ls, v);580 Constdesc cd;
959 next(ls);581 check(ls, '{');
960 pc = SaveWordPop(ls);582 constructor_part(ls, &cd);
961 exp2(ls, v);583 nelems = cd.n;
962 lua_pushvar(ls, v);584 if (optional(ls, ';')) {
963 fix_jump(ls, pc, op, ls->fs->pc);585 Constdesc other_cd;
586 constructor_part(ls, &other_cd);
587 check_condition(ls, (cd.k != other_cd.k), "invalid constructor syntax");
588 nelems += other_cd.n;
964 }589 }
590 check_match(ls, '}', '{', line);
591 luaX_checklimit(ls, nelems, MAXARG_U, "elements in a table constructor");
592 SETARG_U(fs->f->code[pc], nelems); /* set initial table size */
965}593}
966 594
595/* }====================================================================== */
967 596
968static 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;
972}
973 597
974 598
975static void pop_to (LexState *ls, stack_op *s, int prio) {
976 int op;
977 while (s->top > 0 && priority[(op=s->ops[s->top-1])] >= prio) {
978 code_opcode(ls, opcodes[op], op<FIRSTBIN?0:-1);
979 s->top--;
980 }
981}
982 599
983static void simpleexp (LexState *ls, vardesc *v, stack_op *s) {600/*
984 check_debugline(ls);601** {======================================================================
985 switch (ls->token) {602** Expression parsing
986 case NUMBER: { /* simpleexp -> NUMBER */603** =======================================================================
987 real r = ls->seminfo.r;604*/
605
606
607static void simpleexp (LexState *ls, expdesc *v) {
608 FuncState *fs = ls->fs;
609 switch (ls->t.token) {
610 case TK_NUMBER: { /* simpleexp -> NUMBER */
611 Number r = ls->t.seminfo.r;
988 next(ls);612 next(ls);
989 /* dirty trick: check whether it is a -NUMBER not followed by '^' */613 luaK_number(fs, r);
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 */
993 r = -r;
994 }
995 code_number(ls, r);
996 break;614 break;
997 }615 }
998 616 case TK_STRING: { /* simpleexp -> STRING */
999 case STRING: /* simpleexp -> STRING */617 code_string(ls, ls->t.seminfo.ts); /* must use `seminfo' before `next' */
1000 code_string(ls, ls->seminfo.ts); /* must use 'seminfo' before "next" */
1001 next(ls);618 next(ls);
1002 break;619 break;
1003 620 }
1004 case NIL: /* simpleexp -> NIL */621 case TK_NIL: { /* simpleexp -> NIL */
1005 adjuststack(ls, -1);622 luaK_adjuststack(fs, -1);
1006 next(ls);623 next(ls);
1007 break;624 break;
1008 625 }
1009 case '{': /* simpleexp -> constructor */626 case '{': { /* simpleexp -> constructor */
1010 constructor(ls);627 constructor(ls);
1011 break;628 break;
1012 629 }
1013 case FUNCTION: /* simpleexp -> FUNCTION body */630 case TK_FUNCTION: { /* simpleexp -> FUNCTION body */
1014 next(ls);631 next(ls);
1015 body(ls, 0, ls->linenumber);632 body(ls, 0, ls->linenumber);
1016 break;633 break;
1017 634 }
1018 case '(': /* simpleexp -> '(' exp0 ')' */635 case '(': { /* simpleexp -> '(' expr ')' */
1019 next(ls);636 next(ls);
1020 exp0(ls, v);637 expr(ls, v);
1021 check(ls, ')');638 check(ls, ')');
1022 return;639 return;
1023 640 }
1024 case NAME: case '%':641 case TK_NAME: case '%': {
1025 var_or_func(ls, v);642 var_or_func(ls, v);
1026 return;643 return;
1027 644 }
1028 default:645 default: {
1029 luaX_error(ls, "<expression> expected");646 luaK_error(ls, "<expression> expected");
1030 return;647 return;
648 }
1031 }649 }
1032 v->k = VEXP; v->info = 0;650 v->k = VEXP;
651 v->u.l.t = v->u.l.f = NO_JUMP;
1033}652}
1034 653
1035 654
1036static void prefixexp (LexState *ls, vardesc *v, stack_op *s) {655static void exp1 (LexState *ls) {
1037 /* prefixexp -> {NOT | '-'} simpleexp */656 expdesc v;
1038 while (ls->token == NOT || ls->token == '-') {657 expr(ls, &v);
1039 push(ls, s, (ls->token==NOT)?INDNOT:INDMINUS);658 luaK_tostack(ls, &v, 1);
1040 next(ls);
1041 }
1042 simpleexp(ls, v, s);
1043}659}
1044 660
1045 661
1046static void exp2 (LexState *ls, vardesc *v) {662static UnOpr getunopr (int op) {
1047 stack_op s;663 switch (op) {
1048 int op;664 case TK_NOT: return OPR_NOT;
1049 s.top = 0;665 case '-': return OPR_MINUS;
1050 prefixexp(ls, v, &s);666 default: return OPR_NOUNOPR;
1051 while ((op = is_in(ls->token, binop)) >= 0) {
1052 op += FIRSTBIN;
1053 lua_pushvar(ls, v);
1054 /* '^' is right associative, so must 'simulate' a higher priority */
1055 pop_to(ls, &s, (op == POW)?priority[op]+1:priority[op]);
1056 push(ls, &s, op);
1057 next(ls);
1058 prefixexp(ls, v, &s);
1059 lua_pushvar(ls, v);
1060 }
1061 if (s.top > 0) {
1062 lua_pushvar(ls, v);
1063 pop_to(ls, &s, 0);
1064 }667 }
1065}668}
1066 669
1067 670
1068static void var_or_func (LexState *ls, vardesc *v) {671static BinOpr getbinopr (int op) {
1069 /* var_or_func -> ['%'] NAME var_or_func_tail */672 switch (op) {
1070 if (optional(ls, '%')) { /* upvalue? */673 case '+': return OPR_ADD;
1071 pushupvalue(ls, str_checkname(ls));674 case '-': return OPR_SUB;
1072 v->k = VEXP;675 case '*': return OPR_MULT;
1073 v->info = 0; /* closed expression */676 case '/': return OPR_DIV;
677 case '^': return OPR_POW;
678 case TK_CONCAT: return OPR_CONCAT;
679 case TK_NE: return OPR_NE;
680 case TK_EQ: return OPR_EQ;
681 case '<': return OPR_LT;
682 case TK_LE: return OPR_LE;
683 case '>': return OPR_GT;
684 case TK_GE: return OPR_GE;
685 case TK_AND: return OPR_AND;
686 case TK_OR: return OPR_OR;
687 default: return OPR_NOBINOPR;
1074 }688 }
1075 else /* variable name */
1076 singlevar(ls, str_checkname(ls), v, 0);
1077 var_or_func_tail(ls, v);
1078}689}
1079 690
1080 691
1081static void var_or_func_tail (LexState *ls, vardesc *v) {692static const struct {
1082 for (;;) {693 char left; /* left priority for each binary operator */
1083 switch (ls->token) {694 char right; /* right priority */
1084 case '.': /* var_or_func_tail -> '.' NAME */695} priority[] = { /* ORDER OPR */
1085 next(ls);696 {5, 5}, {5, 5}, {6, 6}, {6, 6}, /* arithmetic */
1086 lua_pushvar(ls, v); /* 'v' must be on stack */697 {9, 8}, {4, 3}, /* power and concat (right associative) */
1087 v->k = VDOT;698 {2, 2}, {2, 2}, /* equality */
1088 v->info = checkname(ls);699 {2, 2}, {2, 2}, {2, 2}, {2, 2}, /* order */
1089 break;700 {1, 1}, {1, 1} /* logical */
1090 701};
1091 case '[': /* var_or_func_tail -> '[' exp1 ']' */
1092 next(ls);
1093 lua_pushvar(ls, v); /* 'v' must be on stack */
1094 exp1(ls);
1095 check(ls, ']');
1096 v->k = VINDEXED;
1097 break;
1098 702
1099 case ':': /* var_or_func_tail -> ':' NAME funcparams */703#define UNARY_PRIORITY 7 /* priority for unary operators */
1100 next(ls);
1101 lua_pushvar(ls, v); /* 'v' must be on stack */
1102 code_oparg(ls, PUSHSELF, checkname(ls), 1);
1103 v->k = VEXP;
1104 v->info = funcparams(ls, 1);
1105 break;
1106 704
1107 case '(': case STRING: case '{': /* var_or_func_tail -> funcparams */
1108 lua_pushvar(ls, v); /* 'v' must be on stack */
1109 v->k = VEXP;
1110 v->info = funcparams(ls, 0);
1111 break;
1112 705
1113 default: return; /* should be follow... */706/*
1114 }707** subexpr -> (simplexep | unop subexpr) { binop subexpr }
708** where `binop' is any binary operator with a priority higher than `limit'
709*/
710static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
711 BinOpr op;
712 UnOpr uop = getunopr(ls->t.token);
713 if (uop != OPR_NOUNOPR) {
714 next(ls);
715 subexpr(ls, v, UNARY_PRIORITY);
716 luaK_prefix(ls, uop, v);
1115 }717 }
718 else simpleexp(ls, v);
719 /* expand while operators have priorities higher than `limit' */
720 op = getbinopr(ls->t.token);
721 while (op != OPR_NOBINOPR && priority[op].left > limit) {
722 expdesc v2;
723 BinOpr nextop;
724 next(ls);
725 luaK_infix(ls, op, v);
726 /* read sub-expression with higher priority */
727 nextop = subexpr(ls, &v2, priority[op].right);
728 luaK_posfix(ls, op, v, &v2);
729 op = nextop;
730 }
731 return op; /* return first untreated operator */
1116}732}
1117 733
1118static 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;
1124 listdesc e;
1125 next(ls);
1126 explist(ls, &e);
1127 check_match(ls, ')', '(', line);
1128 close_exp(ls, e.pc, 1);
1129 nparams = e.n;
1130 break;
1131 }
1132 734
1133 case '{': /* funcparams -> constructor */735static void expr (LexState *ls, expdesc *v) {
1134 constructor(ls);736 subexpr(ls, v, -1);
1135 break;737}
1136 738
1137 case STRING: /* funcparams -> STRING */739/* }==================================================================== */
1138 code_string(ls, ls->seminfo.ts); /* must use 'seminfo' before "next" */740
1139 next(ls);741
1140 break;742/*
743** {======================================================================
744** Rules for Statements
745** =======================================================================
746*/
1141 747
1142 default:
1143 luaX_error(ls, "function arguments expected");
1144 break;
1145 }
1146 code_byte(fs, CALL);
1147 code_byte(fs, 0); /* save space for nresult */
1148 code_byte(fs, (Byte)(nparams+slf));
1149 return fs->pc-1;
1150}
1151
1152static void explist (LexState *ls, listdesc *d) {
1153 switch (ls->token) {
1154 case ELSE: case ELSEIF: case END: case UNTIL:
1155 case EOS: case ';': case ')':
1156 d->pc = 0;
1157 d->n = 0;
1158 break;
1159 748
1160 default:749static int block_follow (int token) {
1161 explist1(ls, d);750 switch (token) {
751 case TK_ELSE: case TK_ELSEIF: case TK_END:
752 case TK_UNTIL: case TK_EOS:
753 return 1;
754 default: return 0;
1162 }755 }
1163}756}
1164 757
1165static void explist1 (LexState *ls, listdesc *d) {758
1166 vardesc v;759static void block (LexState *ls) {
1167 exp0(ls, &v);760 /* block -> chunk */
1168 d->n = 1;761 FuncState *fs = ls->fs;
1169 while (ls->token == ',') {762 int nactloc = fs->nactloc;
1170 d->n++;763 chunk(ls);
1171 lua_pushvar(ls, &v);764 luaK_adjuststack(fs, fs->nactloc - nactloc); /* remove local variables */
765 removelocalvars(ls, fs->nactloc - nactloc);
766}
767
768
769static int assignment (LexState *ls, expdesc *v, int nvars) {
770 int left = 0; /* number of values left in the stack after assignment */
771 luaX_checklimit(ls, nvars, MAXVARSLH, "variables in a multiple assignment");
772 if (ls->t.token == ',') { /* assignment -> ',' NAME assignment */
773 expdesc nv;
1172 next(ls);774 next(ls);
1173 exp0(ls, &v);775 var_or_func(ls, &nv);
776 check_condition(ls, (nv.k != VEXP), "syntax error");
777 left = assignment(ls, &nv, nvars+1);
778 }
779 else { /* assignment -> '=' explist1 */
780 int nexps;
781 check(ls, '=');
782 nexps = explist1(ls);
783 adjust_mult_assign(ls, nvars, nexps);
1174 }784 }
1175 if (v.k == VEXP)785 if (v->k != VINDEXED)
1176 d->pc = v.info;786 luaK_storevar(ls, v);
1177 else {787 else { /* there may be garbage between table-index and value */
1178 lua_pushvar(ls, &v);788 luaK_code2(ls->fs, OP_SETTABLE, left+nvars+2, 1);
1179 d->pc = 0;789 left += 2;
1180 }790 }
791 return left;
1181}792}
1182 793
1183static void parlist (LexState *ls) {
1184 int nparams = 0;
1185 int dots = 0;
1186 switch (ls->token) {
1187 case DOTS: /* parlist -> DOTS */
1188 next(ls);
1189 dots = 1;
1190 break;
1191 794
1192 case NAME: /* parlist, tailparlist -> NAME [',' tailparlist] */795static void cond (LexState *ls, expdesc *v) {
1193 init:796 /* cond -> exp */
1194 store_localvar(ls, str_checkname(ls), nparams++);797 expr(ls, v); /* read condition */
1195 if (ls->token == ',') {798 luaK_goiftrue(ls->fs, v, 0);
1196 next(ls);799}
1197 switch (ls->token) {
1198 case DOTS: /* tailparlist -> DOTS */
1199 next(ls);
1200 dots = 1;
1201 break;
1202 800
1203 case NAME: /* tailparlist -> NAME [',' tailparlist] */
1204 goto init;
1205 801
1206 default: luaX_error(ls, "NAME or `...' expected");802static void whilestat (LexState *ls, int line) {
1207 }803 /* whilestat -> WHILE cond DO block END */
1208 }804 FuncState *fs = ls->fs;
1209 break;805 int while_init = luaK_getlabel(fs);
806 expdesc v;
807 Breaklabel bl;
808 enterbreak(fs, &bl);
809 next(ls);
810 cond(ls, &v);
811 check(ls, TK_DO);
812 block(ls);
813 luaK_patchlist(fs, luaK_jump(fs), while_init);
814 luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
815 check_match(ls, TK_END, TK_WHILE, line);
816 leavebreak(fs, &bl);
817}
1210 818
1211 case ')': break; /* parlist -> empty */
1212 819
1213 default: luaX_error(ls, "NAME or `...' expected");820static void repeatstat (LexState *ls, int line) {
1214 }821 /* repeatstat -> REPEAT block UNTIL cond */
1215 code_args(ls, nparams, dots);822 FuncState *fs = ls->fs;
823 int repeat_init = luaK_getlabel(fs);
824 expdesc v;
825 Breaklabel bl;
826 enterbreak(fs, &bl);
827 next(ls);
828 block(ls);
829 check_match(ls, TK_UNTIL, TK_REPEAT, line);
830 cond(ls, &v);
831 luaK_patchlist(fs, v.u.l.f, repeat_init);
832 leavebreak(fs, &bl);
1216}833}
1217 834
1218static int localnamelist (LexState *ls) {835
1219 /* localnamelist -> NAME {',' NAME} */836static void forbody (LexState *ls, int nvar, OpCode prepfor, OpCode loopfor) {
1220 int i = 1;837 /* forbody -> DO block END */
1221 store_localvar(ls, str_checkname(ls), 0);838 FuncState *fs = ls->fs;
1222 while (ls->token == ',') {839 int prep = luaK_code1(fs, prepfor, NO_JUMP);
1223 next(ls);840 int blockinit = luaK_getlabel(fs);
1224 store_localvar(ls, str_checkname(ls), i++);841 check(ls, TK_DO);
842 adjustlocalvars(ls, nvar); /* scope for control variables */
843 block(ls);
844 luaK_patchlist(fs, luaK_code1(fs, loopfor, NO_JUMP), blockinit);
845 luaK_patchlist(fs, prep, luaK_getlabel(fs));
846 removelocalvars(ls, nvar);
847}
848
849
850static void fornum (LexState *ls, TString *varname) {
851 /* fornum -> NAME = exp1,exp1[,exp1] forbody */
852 FuncState *fs = ls->fs;
853 check(ls, '=');
854 exp1(ls); /* initial value */
855 check(ls, ',');
856 exp1(ls); /* limit */
857 if (optional(ls, ','))
858 exp1(ls); /* optional step */
859 else
860 luaK_code1(fs, OP_PUSHINT, 1); /* default step */
861 new_localvar(ls, varname, 0);
862 new_localvarstr(ls, "(limit)", 1);
863 new_localvarstr(ls, "(step)", 2);
864 forbody(ls, 3, OP_FORPREP, OP_FORLOOP);
865}
866
867
868static void forlist (LexState *ls, TString *indexname) {
869 /* forlist -> NAME,NAME IN exp1 forbody */
870 TString *valname;
871 check(ls, ',');
872 valname = str_checkname(ls);
873 /* next test is dirty, but avoids `in' being a reserved word */
874 check_condition(ls,
875 (ls->t.token == TK_NAME && ls->t.seminfo.ts == luaS_new(ls->L, "in")),
876 "`in' expected");
877 next(ls); /* skip `in' */
878 exp1(ls); /* table */
879 new_localvarstr(ls, "(table)", 0);
880 new_localvar(ls, indexname, 1);
881 new_localvar(ls, valname, 2);
882 forbody(ls, 3, OP_LFORPREP, OP_LFORLOOP);
883}
884
885
886static void forstat (LexState *ls, int line) {
887 /* forstat -> fornum | forlist */
888 FuncState *fs = ls->fs;
889 TString *varname;
890 Breaklabel bl;
891 enterbreak(fs, &bl);
892 next(ls); /* skip `for' */
893 varname = str_checkname(ls); /* first variable name */
894 switch (ls->t.token) {
895 case '=': fornum(ls, varname); break;
896 case ',': forlist(ls, varname); break;
897 default: luaK_error(ls, "`=' or `,' expected");
1225 }898 }
1226 return i;899 check_match(ls, TK_END, TK_FOR, line);
900 leavebreak(fs, &bl);
1227}901}
1228 902
1229static void decinit (LexState *ls, listdesc *d) {903
1230 /* decinit -> ['=' explist1] */904static void test_then_block (LexState *ls, expdesc *v) {
1231 if (ls->token == '=') {905 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1232 next(ls);906 next(ls); /* skip IF or ELSEIF */
1233 explist1(ls, d);907 cond(ls, v);
908 check(ls, TK_THEN);
909 block(ls); /* `then' part */
910}
911
912
913static void ifstat (LexState *ls, int line) {
914 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
915 FuncState *fs = ls->fs;
916 expdesc v;
917 int escapelist = NO_JUMP;
918 test_then_block(ls, &v); /* IF cond THEN block */
919 while (ls->t.token == TK_ELSEIF) {
920 luaK_concat(fs, &escapelist, luaK_jump(fs));
921 luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
922 test_then_block(ls, &v); /* ELSEIF cond THEN block */
1234 }923 }
1235 else {924 if (ls->t.token == TK_ELSE) {
1236 d->n = 0;925 luaK_concat(fs, &escapelist, luaK_jump(fs));
1237 d->pc = 0;926 luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
927 next(ls); /* skip ELSE */
928 block(ls); /* `else' part */
1238 }929 }
930 else
931 luaK_concat(fs, &escapelist, v.u.l.f);
932 luaK_patchlist(fs, escapelist, luaK_getlabel(fs));
933 check_match(ls, TK_END, TK_IF, line);
934}
935
936
937static void localstat (LexState *ls) {
938 /* stat -> LOCAL NAME {',' NAME} ['=' explist1] */
939 int nvars = 0;
940 int nexps;
941 do {
942 next(ls); /* skip LOCAL or ',' */
943 new_localvar(ls, str_checkname(ls), nvars++);
944 } while (ls->t.token == ',');
945 if (optional(ls, '='))
946 nexps = explist1(ls);
947 else
948 nexps = 0;
949 adjust_mult_assign(ls, nvars, nexps);
950 adjustlocalvars(ls, nvars);
1239}951}
1240 952
1241 953
1242static int assignment (LexState *ls, vardesc *v, int nvars) {954static int funcname (LexState *ls, expdesc *v) {
1243 int left = 0;955 /* funcname -> NAME [':' NAME | '.' NAME] */
1244 checklimit(ls, nvars, MAXVARSLH, "variables in a multiple assignment");956 int needself = 0;
1245 unloaddot(ls, v);957 singlevar(ls, str_checkname(ls), v);
1246 if (ls->token == ',') { /* assignment -> ',' NAME assignment */958 if (ls->t.token == ':' || ls->t.token == '.') {
1247 vardesc nv;959 needself = (ls->t.token == ':');
1248 next(ls);960 next(ls);
1249 var_or_func(ls, &nv);961 luaK_tostack(ls, v, 1);
1250 if (nv.k == VEXP)962 luaK_kstr(ls, checkname(ls));
1251 luaX_error(ls, "syntax error");963 v->k = VINDEXED;
1252 left = assignment(ls, &nv, nvars+1);
1253 }
1254 else { /* assignment -> '=' explist1 */
1255 listdesc d;
1256 check(ls, '=');
1257 explist1(ls, &d);
1258 adjust_mult_assign(ls, nvars, &d);
1259 }964 }
1260 if (v->k != VINDEXED || left+(nvars-1) == 0) {965 return needself;
1261 /* global/local var or indexed var without values in between */966}
1262 storevar(ls, v);967
968
969static void funcstat (LexState *ls, int line) {
970 /* funcstat -> FUNCTION funcname body */
971 int needself;
972 expdesc v;
973 next(ls); /* skip FUNCTION */
974 needself = funcname(ls, &v);
975 body(ls, needself, line);
976 luaK_storevar(ls, &v);
977}
978
979
980static void namestat (LexState *ls) {
981 /* stat -> func | ['%'] NAME assignment */
982 FuncState *fs = ls->fs;
983 expdesc v;
984 var_or_func(ls, &v);
985 if (v.k == VEXP) { /* stat -> func */
986 check_condition(ls, luaK_lastisopen(fs), "syntax error"); /* an upvalue? */
987 luaK_setcallreturns(fs, 0); /* call statement uses no results */
1263 }988 }
1264 else { /* indexed var with values in between*/989 else { /* stat -> ['%'] NAME assignment */
1265 code_oparg(ls, SETTABLE, left+(nvars-1), -1);990 int left = assignment(ls, &v, 1);
1266 left += 2; /* table&index are not popped, because they aren't on top */991 luaK_adjuststack(fs, left); /* remove eventual garbage left on stack */
1267 }992 }
1268 return left;
1269}993}
1270 994
1271 995
1272static void constructor (LexState *ls) {996static void retstat (LexState *ls) {
1273 /* constructor -> '{' part [';' part] '}' */997 /* stat -> RETURN explist */
1274 int line = ls->linenumber;998 FuncState *fs = ls->fs;
1275 int pc = SaveWord(ls);999 next(ls); /* skip RETURN */
1276 int nelems;1000 if (!block_follow(ls->t.token))
1277 constdesc cd;1001 explist1(ls); /* optional return values */
1278 deltastack(ls, 1);1002 luaK_code1(fs, OP_RETURN, ls->fs->nactloc);
1279 check(ls, '{');1003 fs->stacklevel = fs->nactloc; /* removes all temp values */
1280 part(ls, &cd);
1281 nelems = cd.n;
1282 if (ls->token == ';') {
1283 constdesc other_cd;
1284 next(ls);
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;
1289 }
1290 check_match(ls, '}', '{', line);
1291 fix_opcode(ls, pc, CREATEARRAY, nelems);
1292}1004}
1293 1005
1294static void part (LexState *ls, constdesc *cd) {
1295 switch (ls->token) {
1296 case ';': case '}': /* part -> empty */
1297 cd->n = 0;
1298 cd->k = ls->token;
1299 return;
1300 1006
1301 case NAME: {1007static void breakstat (LexState *ls) {
1302 vardesc v;1008 /* stat -> BREAK [NAME] */
1303 exp0(ls, &v);1009 FuncState *fs = ls->fs;
1304 if (ls->token == '=') {1010 int currentlevel = fs->stacklevel;
1305 switch (v.k) {1011 Breaklabel *bl = fs->bl;
1306 case VGLOBAL:1012 if (!bl)
1307 code_constant(ls, v.info);1013 luaK_error(ls, "no loop to break");
1308 break;1014 next(ls); /* skip BREAK */
1309 case VLOCAL:1015 luaK_adjuststack(fs, currentlevel - bl->stacklevel);
1310 code_string(ls, ls->fs->localvar[v.info]);1016 luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
1311 break;1017 /* correct stack for compiler and symbolic execution */
1312 default:1018 luaK_adjuststack(fs, bl->stacklevel - currentlevel);
1313 error_unexpected(ls);1019}
1314 }
1315 next(ls);
1316 exp1(ls);
1317 cd->n = recfields(ls);
1318 cd->k = 1; /* record */
1319 }
1320 else {
1321 lua_pushvar(ls, &v);
1322 cd->n = listfields(ls);
1323 cd->k = 0; /* list */
1324 }
1325 break;
1326 }
1327 1020
1328 case '[': /* part -> recfield recfields */
1329 recfield(ls);
1330 cd->n = recfields(ls);
1331 cd->k = 1; /* record */
1332 break;
1333 1021
1334 default: /* part -> exp1 listfields */1022static int stat (LexState *ls) {
1335 exp1(ls);1023 int line = ls->linenumber; /* may be needed for error messages */
1336 cd->n = listfields(ls);1024 switch (ls->t.token) {
1337 cd->k = 0; /* list */1025 case TK_IF: { /* stat -> ifstat */
1338 break;1026 ifstat(ls, line);
1027 return 0;
1028 }
1029 case TK_WHILE: { /* stat -> whilestat */
1030 whilestat(ls, line);
1031 return 0;
1032 }
1033 case TK_DO: { /* stat -> DO block END */
1034 next(ls); /* skip DO */
1035 block(ls);
1036 check_match(ls, TK_END, TK_DO, line);
1037 return 0;
1038 }
1039 case TK_FOR: { /* stat -> forstat */
1040 forstat(ls, line);
1041 return 0;
1042 }
1043 case TK_REPEAT: { /* stat -> repeatstat */
1044 repeatstat(ls, line);
1045 return 0;
1046 }
1047 case TK_FUNCTION: { /* stat -> funcstat */
1048 funcstat(ls, line);
1049 return 0;
1050 }
1051 case TK_LOCAL: { /* stat -> localstat */
1052 localstat(ls);
1053 return 0;
1054 }
1055 case TK_NAME: case '%': { /* stat -> namestat */
1056 namestat(ls);
1057 return 0;
1058 }
1059 case TK_RETURN: { /* stat -> retstat */
1060 retstat(ls);
1061 return 1; /* must be last statement */
1062 }
1063 case TK_BREAK: { /* stat -> breakstat */
1064 breakstat(ls);
1065 return 1; /* must be last statement */
1066 }
1067 default: {
1068 luaK_error(ls, "<statement> expected");
1069 return 0; /* to avoid warnings */
1070 }
1339 }1071 }
1340}1072}
1341 1073
1342static int recfields (LexState *ls) {1074
1343 /* recfields -> { ',' recfield } [','] */1075static void parlist (LexState *ls) {
1344 int n = 1; /* one has been read before */1076 /* parlist -> [ param { ',' param } ] */
1345 while (ls->token == ',') {1077 int nparams = 0;
1346 next(ls);1078 int dots = 0;
1347 if (ls->token == ';' || ls->token == '}')1079 if (ls->t.token != ')') { /* is `parlist' not empty? */
1348 break;1080 do {
1349 recfield(ls);1081 switch (ls->t.token) {
1350 n++;1082 case TK_DOTS: next(ls); dots = 1; break;
1351 if (n%RFIELDS_PER_FLUSH == 0)1083 case TK_NAME: new_localvar(ls, str_checkname(ls), nparams++); break;
1352 flush_record(ls, RFIELDS_PER_FLUSH);1084 default: luaK_error(ls, "<name> or `...' expected");
1085 }
1086 } while (!dots && optional(ls, ','));
1353 }1087 }
1354 flush_record(ls, n%RFIELDS_PER_FLUSH);1088 code_params(ls, nparams, dots);
1355 return n;
1356}1089}
1357 1090
1358static int listfields (LexState *ls) {1091
1359 /* listfields -> { ',' exp1 } [','] */1092static void body (LexState *ls, int needself, int line) {
1360 int n = 1; /* one has been read before */1093 /* body -> '(' parlist ')' chunk END */
1361 while (ls->token == ',') {1094 FuncState new_fs;
1362 next(ls);1095 open_func(ls, &new_fs);
1363 if (ls->token == ';' || ls->token == '}')1096 new_fs.f->lineDefined = line;
1364 break;1097 check(ls, '(');
1365 exp1(ls);1098 if (needself) {
1366 n++;1099 new_localvarstr(ls, "self", 0);
1367 if (n%LFIELDS_PER_FLUSH == 0)1100 adjustlocalvars(ls, 1);
1368 flush_list(ls, n/LFIELDS_PER_FLUSH - 1, LFIELDS_PER_FLUSH);
1369 }1101 }
1370 flush_list(ls, n/LFIELDS_PER_FLUSH, n%LFIELDS_PER_FLUSH);1102 parlist(ls);
1371 return n;1103 check(ls, ')');
1104 chunk(ls);
1105 check_match(ls, TK_END, TK_FUNCTION, line);
1106 close_func(ls);
1107 pushclosure(ls, &new_fs);
1372}1108}
1373 1109
1374static void recfield (LexState *ls) {
1375 /* recfield -> (NAME | '['exp1']') = exp1 */
1376 switch (ls->token) {
1377 case NAME:
1378 code_constant(ls, checkname(ls));
1379 break;
1380 1110
1381 case '[':1111/* }====================================================================== */
1382 next(ls);
1383 exp1(ls);
1384 check(ls, ']');
1385 break;
1386 1112
1387 default: luaX_error(ls, "NAME or `[' expected");1113
1114static void chunk (LexState *ls) {
1115 /* chunk -> { stat [';'] } */
1116 int islast = 0;
1117 while (!islast && !block_follow(ls->t.token)) {
1118 islast = stat(ls);
1119 optional(ls, ';');
1120 LUA_ASSERT(ls->fs->stacklevel == ls->fs->nactloc,
1121 "stack size != # local vars");
1388 }1122 }
1389 check(ls, '=');
1390 exp1(ls);
1391}1123}
1392 1124

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t