1/*	$NetBSD$	*/
2
3/*
4** Id: lparser.c,v 2.42.1.3 2007/12/28 15:32:23 roberto Exp
5** Lua Parser
6** See Copyright Notice in lua.h
7*/
8
9
10#include <string.h>
11
12#define lparser_c
13#define LUA_CORE
14
15#include "lua.h"
16
17#include "lcode.h"
18#include "ldebug.h"
19#include "ldo.h"
20#include "lfunc.h"
21#include "llex.h"
22#include "lmem.h"
23#include "lobject.h"
24#include "lopcodes.h"
25#include "lparser.h"
26#include "lstate.h"
27#include "lstring.h"
28#include "ltable.h"
29
30
31
32#define hasmultret(k)		((k) == VCALL || (k) == VVARARG)
33
34#define getlocvar(fs, i)	((fs)->f->locvars[(fs)->actvar[i]])
35
36#define luaY_checklimit(fs,v,l,m)	if ((v)>(l)) errorlimit(fs,l,m)
37
38
39/*
40** nodes for block list (list of active blocks)
41*/
42typedef struct BlockCnt {
43  struct BlockCnt *previous;  /* chain */
44  int breaklist;  /* list of jumps out of this loop */
45  lu_byte nactvar;  /* # active locals outside the breakable structure */
46  lu_byte upval;  /* true if some variable in the block is an upvalue */
47  lu_byte isbreakable;  /* true if `block' is a loop */
48} BlockCnt;
49
50
51
52/*
53** prototypes for recursive non-terminal functions
54*/
55static void chunk (LexState *ls);
56static void expr (LexState *ls, expdesc *v);
57
58
59static void anchor_token (LexState *ls) {
60  if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
61    TString *ts = ls->t.seminfo.ts;
62    luaX_newstring(ls, getstr(ts), ts->tsv.len);
63  }
64}
65
66
67static void error_expected (LexState *ls, int token) {
68  luaX_syntaxerror(ls,
69      luaO_pushfstring(ls->L, LUA_QS " expected", luaX_token2str(ls, token)));
70}
71
72
73static void errorlimit (FuncState *fs, int limit, const char *what) {
74  const char *msg = (fs->f->linedefined == 0) ?
75    luaO_pushfstring(fs->L, "main function has more than %d %s", limit, what) :
76    luaO_pushfstring(fs->L, "function at line %d has more than %d %s",
77                            fs->f->linedefined, limit, what);
78  luaX_lexerror(fs->ls, msg, 0);
79}
80
81
82static int testnext (LexState *ls, int c) {
83  if (ls->t.token == c) {
84    luaX_next(ls);
85    return 1;
86  }
87  else return 0;
88}
89
90
91static void check (LexState *ls, int c) {
92  if (ls->t.token != c)
93    error_expected(ls, c);
94}
95
96static void checknext (LexState *ls, int c) {
97  check(ls, c);
98  luaX_next(ls);
99}
100
101
102#define check_condition(ls,c,msg)	{ if (!(c)) luaX_syntaxerror(ls, msg); }
103
104
105
106static void check_match (LexState *ls, int what, int who, int where) {
107  if (!testnext(ls, what)) {
108    if (where == ls->linenumber)
109      error_expected(ls, what);
110    else {
111      luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
112             LUA_QS " expected (to close " LUA_QS " at line %d)",
113              luaX_token2str(ls, what), luaX_token2str(ls, who), where));
114    }
115  }
116}
117
118
119static TString *str_checkname (LexState *ls) {
120  TString *ts;
121  check(ls, TK_NAME);
122  ts = ls->t.seminfo.ts;
123  luaX_next(ls);
124  return ts;
125}
126
127
128static void init_exp (expdesc *e, expkind k, int i) {
129  e->f = e->t = NO_JUMP;
130  e->k = k;
131  e->u.s.info = i;
132}
133
134
135static void codestring (LexState *ls, expdesc *e, TString *s) {
136  init_exp(e, VK, luaK_stringK(ls->fs, s));
137}
138
139
140static void checkname(LexState *ls, expdesc *e) {
141  codestring(ls, e, str_checkname(ls));
142}
143
144
145static int registerlocalvar (LexState *ls, TString *varname) {
146  FuncState *fs = ls->fs;
147  Proto *f = fs->f;
148  int oldsize = f->sizelocvars;
149  luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
150                  LocVar, SHRT_MAX, "too many local variables");
151  while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
152  f->locvars[fs->nlocvars].varname = varname;
153  luaC_objbarrier(ls->L, f, varname);
154  return fs->nlocvars++;
155}
156
157
158#define new_localvarliteral(ls,v,n) \
159  new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n)
160
161
162static void new_localvar (LexState *ls, TString *name, int n) {
163  FuncState *fs = ls->fs;
164  luaY_checklimit(fs, fs->nactvar+n+1, LUAI_MAXVARS, "local variables");
165  fs->actvar[fs->nactvar+n] = cast(unsigned short, registerlocalvar(ls, name));
166}
167
168
169static void adjustlocalvars (LexState *ls, int nvars) {
170  FuncState *fs = ls->fs;
171  fs->nactvar = cast_byte(fs->nactvar + nvars);
172  for (; nvars; nvars--) {
173    getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc;
174  }
175}
176
177
178static void removevars (LexState *ls, int tolevel) {
179  FuncState *fs = ls->fs;
180  while (fs->nactvar > tolevel)
181    getlocvar(fs, --fs->nactvar).endpc = fs->pc;
182}
183
184
185static int indexupvalue (FuncState *fs, TString *name, expdesc *v) {
186  int i;
187  Proto *f = fs->f;
188  int oldsize = f->sizeupvalues;
189  for (i=0; i<f->nups; i++) {
190    if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->u.s.info) {
191      lua_assert(f->upvalues[i] == name);
192      return i;
193    }
194  }
195  /* new one */
196  luaY_checklimit(fs, f->nups + 1, LUAI_MAXUPVALUES, "upvalues");
197  luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues,
198                  TString *, MAX_INT, "");
199  while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL;
200  f->upvalues[f->nups] = name;
201  luaC_objbarrier(fs->L, f, name);
202  lua_assert(v->k == VLOCAL || v->k == VUPVAL);
203  fs->upvalues[f->nups].k = cast_byte(v->k);
204  fs->upvalues[f->nups].info = cast_byte(v->u.s.info);
205  return f->nups++;
206}
207
208
209static int searchvar (FuncState *fs, TString *n) {
210  int i;
211  for (i=fs->nactvar-1; i >= 0; i--) {
212    if (n == getlocvar(fs, i).varname)
213      return i;
214  }
215  return -1;  /* not found */
216}
217
218
219static void markupval (FuncState *fs, int level) {
220  BlockCnt *bl = fs->bl;
221  while (bl && bl->nactvar > level) bl = bl->previous;
222  if (bl) bl->upval = 1;
223}
224
225
226static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
227  if (fs == NULL) {  /* no more levels? */
228    init_exp(var, VGLOBAL, NO_REG);  /* default is global variable */
229    return VGLOBAL;
230  }
231  else {
232    int v = searchvar(fs, n);  /* look up at current level */
233    if (v >= 0) {
234      init_exp(var, VLOCAL, v);
235      if (!base)
236        markupval(fs, v);  /* local will be used as an upval */
237      return VLOCAL;
238    }
239    else {  /* not found at current level; try upper one */
240      if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL)
241        return VGLOBAL;
242      var->u.s.info = indexupvalue(fs, n, var);  /* else was LOCAL or UPVAL */
243      var->k = VUPVAL;  /* upvalue in this level */
244      return VUPVAL;
245    }
246  }
247}
248
249
250static void singlevar (LexState *ls, expdesc *var) {
251  TString *varname = str_checkname(ls);
252  FuncState *fs = ls->fs;
253  if (singlevaraux(fs, varname, var, 1) == VGLOBAL)
254    var->u.s.info = luaK_stringK(fs, varname);  /* info points to global name */
255}
256
257
258static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
259  FuncState *fs = ls->fs;
260  int extra = nvars - nexps;
261  if (hasmultret(e->k)) {
262    extra++;  /* includes call itself */
263    if (extra < 0) extra = 0;
264    luaK_setreturns(fs, e, extra);  /* last exp. provides the difference */
265    if (extra > 1) luaK_reserveregs(fs, extra-1);
266  }
267  else {
268    if (e->k != VVOID) luaK_exp2nextreg(fs, e);  /* close last expression */
269    if (extra > 0) {
270      int reg = fs->freereg;
271      luaK_reserveregs(fs, extra);
272      luaK_nil(fs, reg, extra);
273    }
274  }
275}
276
277
278static void enterlevel (LexState *ls) {
279  if (++ls->L->nCcalls > LUAI_MAXCCALLS)
280	luaX_lexerror(ls, "chunk has too many syntax levels", 0);
281}
282
283
284#define leavelevel(ls)	((ls)->L->nCcalls--)
285
286
287static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) {
288  bl->breaklist = NO_JUMP;
289  bl->isbreakable = isbreakable;
290  bl->nactvar = fs->nactvar;
291  bl->upval = 0;
292  bl->previous = fs->bl;
293  fs->bl = bl;
294  lua_assert(fs->freereg == fs->nactvar);
295}
296
297
298static void leaveblock (FuncState *fs) {
299  BlockCnt *bl = fs->bl;
300  fs->bl = bl->previous;
301  removevars(fs->ls, bl->nactvar);
302  if (bl->upval)
303    luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
304  /* a block either controls scope or breaks (never both) */
305  lua_assert(!bl->isbreakable || !bl->upval);
306  lua_assert(bl->nactvar == fs->nactvar);
307  fs->freereg = fs->nactvar;  /* free registers */
308  luaK_patchtohere(fs, bl->breaklist);
309}
310
311
312static void pushclosure (LexState *ls, FuncState *func, expdesc *v) {
313  FuncState *fs = ls->fs;
314  Proto *f = fs->f;
315  int oldsize = f->sizep;
316  int i;
317  luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
318                  MAXARG_Bx, "constant table overflow");
319  while (oldsize < f->sizep) f->p[oldsize++] = NULL;
320  f->p[fs->np++] = func->f;
321  luaC_objbarrier(ls->L, f, func->f);
322  init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
323  for (i=0; i<func->f->nups; i++) {
324    OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
325    luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0);
326  }
327}
328
329
330static void open_func (LexState *ls, FuncState *fs) {
331  lua_State *L = ls->L;
332  Proto *f = luaF_newproto(L);
333  fs->f = f;
334  fs->prev = ls->fs;  /* linked list of funcstates */
335  fs->ls = ls;
336  fs->L = L;
337  ls->fs = fs;
338  fs->pc = 0;
339  fs->lasttarget = -1;
340  fs->jpc = NO_JUMP;
341  fs->freereg = 0;
342  fs->nk = 0;
343  fs->np = 0;
344  fs->nlocvars = 0;
345  fs->nactvar = 0;
346  fs->bl = NULL;
347  f->source = ls->source;
348  f->maxstacksize = 2;  /* registers 0/1 are always valid */
349  fs->h = luaH_new(L, 0, 0);
350  /* anchor table of constants and prototype (to avoid being collected) */
351  sethvalue2s(L, L->top, fs->h);
352  incr_top(L);
353  setptvalue2s(L, L->top, f);
354  incr_top(L);
355}
356
357
358static void close_func (LexState *ls) {
359  lua_State *L = ls->L;
360  FuncState *fs = ls->fs;
361  Proto *f = fs->f;
362  removevars(ls, 0);
363  luaK_ret(fs, 0, 0);  /* final return */
364  luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
365  f->sizecode = fs->pc;
366  luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
367  f->sizelineinfo = fs->pc;
368  luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
369  f->sizek = fs->nk;
370  luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
371  f->sizep = fs->np;
372  luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
373  f->sizelocvars = fs->nlocvars;
374  luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *);
375  f->sizeupvalues = f->nups;
376  lua_assert(luaG_checkcode(f));
377  lua_assert(fs->bl == NULL);
378  ls->fs = fs->prev;
379  L->top -= 2;  /* remove table and prototype from the stack */
380  /* last token read was anchored in defunct function; must reanchor it */
381  if (fs) anchor_token(ls);
382}
383
384
385Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
386  struct LexState lexstate;
387  struct FuncState funcstate;
388  lexstate.buff = buff;
389  luaX_setinput(L, &lexstate, z, luaS_new(L, name));
390  open_func(&lexstate, &funcstate);
391  funcstate.f->is_vararg = VARARG_ISVARARG;  /* main func. is always vararg */
392  luaX_next(&lexstate);  /* read first token */
393  chunk(&lexstate);
394  check(&lexstate, TK_EOS);
395  close_func(&lexstate);
396  lua_assert(funcstate.prev == NULL);
397  lua_assert(funcstate.f->nups == 0);
398  lua_assert(lexstate.fs == NULL);
399  return funcstate.f;
400}
401
402
403
404/*============================================================*/
405/* GRAMMAR RULES */
406/*============================================================*/
407
408
409static void field (LexState *ls, expdesc *v) {
410  /* field -> ['.' | ':'] NAME */
411  FuncState *fs = ls->fs;
412  expdesc key;
413  luaK_exp2anyreg(fs, v);
414  luaX_next(ls);  /* skip the dot or colon */
415  checkname(ls, &key);
416  luaK_indexed(fs, v, &key);
417}
418
419
420static void yindex (LexState *ls, expdesc *v) {
421  /* index -> '[' expr ']' */
422  luaX_next(ls);  /* skip the '[' */
423  expr(ls, v);
424  luaK_exp2val(ls->fs, v);
425  checknext(ls, ']');
426}
427
428
429/*
430** {======================================================================
431** Rules for Constructors
432** =======================================================================
433*/
434
435
436struct ConsControl {
437  expdesc v;  /* last list item read */
438  expdesc *t;  /* table descriptor */
439  int nh;  /* total number of `record' elements */
440  int na;  /* total number of array elements */
441  int tostore;  /* number of array elements pending to be stored */
442};
443
444
445static void recfield (LexState *ls, struct ConsControl *cc) {
446  /* recfield -> (NAME | `['exp1`]') = exp1 */
447  FuncState *fs = ls->fs;
448  int reg = ls->fs->freereg;
449  expdesc key, val;
450  int rkkey;
451  if (ls->t.token == TK_NAME) {
452    luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
453    checkname(ls, &key);
454  }
455  else  /* ls->t.token == '[' */
456    yindex(ls, &key);
457  cc->nh++;
458  checknext(ls, '=');
459  rkkey = luaK_exp2RK(fs, &key);
460  expr(ls, &val);
461  luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val));
462  fs->freereg = reg;  /* free registers */
463}
464
465
466static void closelistfield (FuncState *fs, struct ConsControl *cc) {
467  if (cc->v.k == VVOID) return;  /* there is no list item */
468  luaK_exp2nextreg(fs, &cc->v);
469  cc->v.k = VVOID;
470  if (cc->tostore == LFIELDS_PER_FLUSH) {
471    luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);  /* flush */
472    cc->tostore = 0;  /* no more items pending */
473  }
474}
475
476
477static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
478  if (cc->tostore == 0) return;
479  if (hasmultret(cc->v.k)) {
480    luaK_setmultret(fs, &cc->v);
481    luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET);
482    cc->na--;  /* do not count last expression (unknown number of elements) */
483  }
484  else {
485    if (cc->v.k != VVOID)
486      luaK_exp2nextreg(fs, &cc->v);
487    luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);
488  }
489}
490
491
492static void listfield (LexState *ls, struct ConsControl *cc) {
493  expr(ls, &cc->v);
494  luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
495  cc->na++;
496  cc->tostore++;
497}
498
499
500static void constructor (LexState *ls, expdesc *t) {
501  /* constructor -> ?? */
502  FuncState *fs = ls->fs;
503  int line = ls->linenumber;
504  int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
505  struct ConsControl cc;
506  cc.na = cc.nh = cc.tostore = 0;
507  cc.t = t;
508  init_exp(t, VRELOCABLE, pc);
509  init_exp(&cc.v, VVOID, 0);  /* no value (yet) */
510  luaK_exp2nextreg(ls->fs, t);  /* fix it at stack top (for gc) */
511  checknext(ls, '{');
512  do {
513    lua_assert(cc.v.k == VVOID || cc.tostore > 0);
514    if (ls->t.token == '}') break;
515    closelistfield(fs, &cc);
516    switch(ls->t.token) {
517      case TK_NAME: {  /* may be listfields or recfields */
518        luaX_lookahead(ls);
519        if (ls->lookahead.token != '=')  /* expression? */
520          listfield(ls, &cc);
521        else
522          recfield(ls, &cc);
523        break;
524      }
525      case '[': {  /* constructor_item -> recfield */
526        recfield(ls, &cc);
527        break;
528      }
529      default: {  /* constructor_part -> listfield */
530        listfield(ls, &cc);
531        break;
532      }
533    }
534  } while (testnext(ls, ',') || testnext(ls, ';'));
535  check_match(ls, '}', '{', line);
536  lastlistfield(fs, &cc);
537  SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
538  SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh));  /* set initial table size */
539}
540
541/* }====================================================================== */
542
543
544
545static void parlist (LexState *ls) {
546  /* parlist -> [ param { `,' param } ] */
547  FuncState *fs = ls->fs;
548  Proto *f = fs->f;
549  int nparams = 0;
550  f->is_vararg = 0;
551  if (ls->t.token != ')') {  /* is `parlist' not empty? */
552    do {
553      switch (ls->t.token) {
554        case TK_NAME: {  /* param -> NAME */
555          new_localvar(ls, str_checkname(ls), nparams++);
556          break;
557        }
558        case TK_DOTS: {  /* param -> `...' */
559          luaX_next(ls);
560#if defined(LUA_COMPAT_VARARG)
561          /* use `arg' as default name */
562          new_localvarliteral(ls, "arg", nparams++);
563          f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG;
564#endif
565          f->is_vararg |= VARARG_ISVARARG;
566          break;
567        }
568        default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
569      }
570    } while (!f->is_vararg && testnext(ls, ','));
571  }
572  adjustlocalvars(ls, nparams);
573  f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG));
574  luaK_reserveregs(fs, fs->nactvar);  /* reserve register for parameters */
575}
576
577
578static void body (LexState *ls, expdesc *e, int needself, int line) {
579  /* body ->  `(' parlist `)' chunk END */
580  FuncState new_fs;
581  open_func(ls, &new_fs);
582  new_fs.f->linedefined = line;
583  checknext(ls, '(');
584  if (needself) {
585    new_localvarliteral(ls, "self", 0);
586    adjustlocalvars(ls, 1);
587  }
588  parlist(ls);
589  checknext(ls, ')');
590  chunk(ls);
591  new_fs.f->lastlinedefined = ls->linenumber;
592  check_match(ls, TK_END, TK_FUNCTION, line);
593  close_func(ls);
594  pushclosure(ls, &new_fs, e);
595}
596
597
598static int explist1 (LexState *ls, expdesc *v) {
599  /* explist1 -> expr { `,' expr } */
600  int n = 1;  /* at least one expression */
601  expr(ls, v);
602  while (testnext(ls, ',')) {
603    luaK_exp2nextreg(ls->fs, v);
604    expr(ls, v);
605    n++;
606  }
607  return n;
608}
609
610
611static void funcargs (LexState *ls, expdesc *f) {
612  FuncState *fs = ls->fs;
613  expdesc args;
614  int base, nparams;
615  int line = ls->linenumber;
616  switch (ls->t.token) {
617    case '(': {  /* funcargs -> `(' [ explist1 ] `)' */
618      if (line != ls->lastline)
619        luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
620      luaX_next(ls);
621      if (ls->t.token == ')')  /* arg list is empty? */
622        args.k = VVOID;
623      else {
624        explist1(ls, &args);
625        luaK_setmultret(fs, &args);
626      }
627      check_match(ls, ')', '(', line);
628      break;
629    }
630    case '{': {  /* funcargs -> constructor */
631      constructor(ls, &args);
632      break;
633    }
634    case TK_STRING: {  /* funcargs -> STRING */
635      codestring(ls, &args, ls->t.seminfo.ts);
636      luaX_next(ls);  /* must use `seminfo' before `next' */
637      break;
638    }
639    default: {
640      luaX_syntaxerror(ls, "function arguments expected");
641      return;
642    }
643  }
644  lua_assert(f->k == VNONRELOC);
645  base = f->u.s.info;  /* base register for call */
646  if (hasmultret(args.k))
647    nparams = LUA_MULTRET;  /* open call */
648  else {
649    if (args.k != VVOID)
650      luaK_exp2nextreg(fs, &args);  /* close last argument */
651    nparams = fs->freereg - (base+1);
652  }
653  init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
654  luaK_fixline(fs, line);
655  fs->freereg = base+1;  /* call remove function and arguments and leaves
656                            (unless changed) one result */
657}
658
659
660
661
662/*
663** {======================================================================
664** Expression parsing
665** =======================================================================
666*/
667
668
669static void prefixexp (LexState *ls, expdesc *v) {
670  /* prefixexp -> NAME | '(' expr ')' */
671  switch (ls->t.token) {
672    case '(': {
673      int line = ls->linenumber;
674      luaX_next(ls);
675      expr(ls, v);
676      check_match(ls, ')', '(', line);
677      luaK_dischargevars(ls->fs, v);
678      return;
679    }
680    case TK_NAME: {
681      singlevar(ls, v);
682      return;
683    }
684    default: {
685      luaX_syntaxerror(ls, "unexpected symbol");
686      return;
687    }
688  }
689}
690
691
692static void primaryexp (LexState *ls, expdesc *v) {
693  /* primaryexp ->
694        prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
695  FuncState *fs = ls->fs;
696  prefixexp(ls, v);
697  for (;;) {
698    switch (ls->t.token) {
699      case '.': {  /* field */
700        field(ls, v);
701        break;
702      }
703      case '[': {  /* `[' exp1 `]' */
704        expdesc key;
705        luaK_exp2anyreg(fs, v);
706        yindex(ls, &key);
707        luaK_indexed(fs, v, &key);
708        break;
709      }
710      case ':': {  /* `:' NAME funcargs */
711        expdesc key;
712        luaX_next(ls);
713        checkname(ls, &key);
714        luaK_self(fs, v, &key);
715        funcargs(ls, v);
716        break;
717      }
718      case '(': case TK_STRING: case '{': {  /* funcargs */
719        luaK_exp2nextreg(fs, v);
720        funcargs(ls, v);
721        break;
722      }
723      default: return;
724    }
725  }
726}
727
728
729static void simpleexp (LexState *ls, expdesc *v) {
730  /* simpleexp -> NUMBER | STRING | NIL | true | false | ... |
731                  constructor | FUNCTION body | primaryexp */
732  switch (ls->t.token) {
733    case TK_NUMBER: {
734      init_exp(v, VKNUM, 0);
735      v->u.nval = ls->t.seminfo.r;
736      break;
737    }
738    case TK_STRING: {
739      codestring(ls, v, ls->t.seminfo.ts);
740      break;
741    }
742    case TK_NIL: {
743      init_exp(v, VNIL, 0);
744      break;
745    }
746    case TK_TRUE: {
747      init_exp(v, VTRUE, 0);
748      break;
749    }
750    case TK_FALSE: {
751      init_exp(v, VFALSE, 0);
752      break;
753    }
754    case TK_DOTS: {  /* vararg */
755      FuncState *fs = ls->fs;
756      check_condition(ls, fs->f->is_vararg,
757                      "cannot use " LUA_QL("...") " outside a vararg function");
758      fs->f->is_vararg &= ~VARARG_NEEDSARG;  /* don't need 'arg' */
759      init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
760      break;
761    }
762    case '{': {  /* constructor */
763      constructor(ls, v);
764      return;
765    }
766    case TK_FUNCTION: {
767      luaX_next(ls);
768      body(ls, v, 0, ls->linenumber);
769      return;
770    }
771    default: {
772      primaryexp(ls, v);
773      return;
774    }
775  }
776  luaX_next(ls);
777}
778
779
780static UnOpr getunopr (int op) {
781  switch (op) {
782    case TK_NOT: return OPR_NOT;
783    case '-': return OPR_MINUS;
784    case '#': return OPR_LEN;
785    default: return OPR_NOUNOPR;
786  }
787}
788
789
790static BinOpr getbinopr (int op) {
791  switch (op) {
792    case '+': return OPR_ADD;
793    case '-': return OPR_SUB;
794    case '*': return OPR_MUL;
795    case '/': return OPR_DIV;
796    case '%': return OPR_MOD;
797    case '^': return OPR_POW;
798    case TK_CONCAT: return OPR_CONCAT;
799    case TK_NE: return OPR_NE;
800    case TK_EQ: return OPR_EQ;
801    case '<': return OPR_LT;
802    case TK_LE: return OPR_LE;
803    case '>': return OPR_GT;
804    case TK_GE: return OPR_GE;
805    case TK_AND: return OPR_AND;
806    case TK_OR: return OPR_OR;
807    default: return OPR_NOBINOPR;
808  }
809}
810
811
812static const struct {
813  lu_byte left;  /* left priority for each binary operator */
814  lu_byte right; /* right priority */
815} priority[] = {  /* ORDER OPR */
816   {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7},  /* `+' `-' `/' `%' */
817   {10, 9}, {5, 4},                 /* power and concat (right associative) */
818   {3, 3}, {3, 3},                  /* equality and inequality */
819   {3, 3}, {3, 3}, {3, 3}, {3, 3},  /* order */
820   {2, 2}, {1, 1}                   /* logical (and/or) */
821};
822
823#define UNARY_PRIORITY	8  /* priority for unary operators */
824
825
826/*
827** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
828** where `binop' is any binary operator with a priority higher than `limit'
829*/
830static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) {
831  BinOpr op;
832  UnOpr uop;
833  enterlevel(ls);
834  uop = getunopr(ls->t.token);
835  if (uop != OPR_NOUNOPR) {
836    luaX_next(ls);
837    subexpr(ls, v, UNARY_PRIORITY);
838    luaK_prefix(ls->fs, uop, v);
839  }
840  else simpleexp(ls, v);
841  /* expand while operators have priorities higher than `limit' */
842  op = getbinopr(ls->t.token);
843  while (op != OPR_NOBINOPR && priority[op].left > limit) {
844    expdesc v2;
845    BinOpr nextop;
846    luaX_next(ls);
847    luaK_infix(ls->fs, op, v);
848    /* read sub-expression with higher priority */
849    nextop = subexpr(ls, &v2, priority[op].right);
850    luaK_posfix(ls->fs, op, v, &v2);
851    op = nextop;
852  }
853  leavelevel(ls);
854  return op;  /* return first untreated operator */
855}
856
857
858static void expr (LexState *ls, expdesc *v) {
859  subexpr(ls, v, 0);
860}
861
862/* }==================================================================== */
863
864
865
866/*
867** {======================================================================
868** Rules for Statements
869** =======================================================================
870*/
871
872
873static int block_follow (int token) {
874  switch (token) {
875    case TK_ELSE: case TK_ELSEIF: case TK_END:
876    case TK_UNTIL: case TK_EOS:
877      return 1;
878    default: return 0;
879  }
880}
881
882
883static void block (LexState *ls) {
884  /* block -> chunk */
885  FuncState *fs = ls->fs;
886  BlockCnt bl;
887  enterblock(fs, &bl, 0);
888  chunk(ls);
889  lua_assert(bl.breaklist == NO_JUMP);
890  leaveblock(fs);
891}
892
893
894/*
895** structure to chain all variables in the left-hand side of an
896** assignment
897*/
898struct LHS_assign {
899  struct LHS_assign *prev;
900  expdesc v;  /* variable (global, local, upvalue, or indexed) */
901};
902
903
904/*
905** check whether, in an assignment to a local variable, the local variable
906** is needed in a previous assignment (to a table). If so, save original
907** local value in a safe place and use this safe copy in the previous
908** assignment.
909*/
910static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
911  FuncState *fs = ls->fs;
912  int extra = fs->freereg;  /* eventual position to save local variable */
913  int conflict = 0;
914  for (; lh; lh = lh->prev) {
915    if (lh->v.k == VINDEXED) {
916      if (lh->v.u.s.info == v->u.s.info) {  /* conflict? */
917        conflict = 1;
918        lh->v.u.s.info = extra;  /* previous assignment will use safe copy */
919      }
920      if (lh->v.u.s.aux == v->u.s.info) {  /* conflict? */
921        conflict = 1;
922        lh->v.u.s.aux = extra;  /* previous assignment will use safe copy */
923      }
924    }
925  }
926  if (conflict) {
927    luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0);  /* make copy */
928    luaK_reserveregs(fs, 1);
929  }
930}
931
932
933static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
934  expdesc e;
935  check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
936                      "syntax error");
937  if (testnext(ls, ',')) {  /* assignment -> `,' primaryexp assignment */
938    struct LHS_assign nv;
939    nv.prev = lh;
940    primaryexp(ls, &nv.v);
941    if (nv.v.k == VLOCAL)
942      check_conflict(ls, lh, &nv.v);
943    luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - ls->L->nCcalls,
944                    "variables in assignment");
945    assignment(ls, &nv, nvars+1);
946  }
947  else {  /* assignment -> `=' explist1 */
948    int nexps;
949    checknext(ls, '=');
950    nexps = explist1(ls, &e);
951    if (nexps != nvars) {
952      adjust_assign(ls, nvars, nexps, &e);
953      if (nexps > nvars)
954        ls->fs->freereg -= nexps - nvars;  /* remove extra values */
955    }
956    else {
957      luaK_setoneret(ls->fs, &e);  /* close last expression */
958      luaK_storevar(ls->fs, &lh->v, &e);
959      return;  /* avoid default */
960    }
961  }
962  init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */
963  luaK_storevar(ls->fs, &lh->v, &e);
964}
965
966
967static int cond (LexState *ls) {
968  /* cond -> exp */
969  expdesc v;
970  expr(ls, &v);  /* read condition */
971  if (v.k == VNIL) v.k = VFALSE;  /* `falses' are all equal here */
972  luaK_goiftrue(ls->fs, &v);
973  return v.f;
974}
975
976
977static void breakstat (LexState *ls) {
978  FuncState *fs = ls->fs;
979  BlockCnt *bl = fs->bl;
980  int upval = 0;
981  while (bl && !bl->isbreakable) {
982    upval |= bl->upval;
983    bl = bl->previous;
984  }
985  if (!bl)
986    luaX_syntaxerror(ls, "no loop to break");
987  if (upval)
988    luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
989  luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
990}
991
992
993static void whilestat (LexState *ls, int line) {
994  /* whilestat -> WHILE cond DO block END */
995  FuncState *fs = ls->fs;
996  int whileinit;
997  int condexit;
998  BlockCnt bl;
999  luaX_next(ls);  /* skip WHILE */
1000  whileinit = luaK_getlabel(fs);
1001  condexit = cond(ls);
1002  enterblock(fs, &bl, 1);
1003  checknext(ls, TK_DO);
1004  block(ls);
1005  luaK_patchlist(fs, luaK_jump(fs), whileinit);
1006  check_match(ls, TK_END, TK_WHILE, line);
1007  leaveblock(fs);
1008  luaK_patchtohere(fs, condexit);  /* false conditions finish the loop */
1009}
1010
1011
1012static void repeatstat (LexState *ls, int line) {
1013  /* repeatstat -> REPEAT block UNTIL cond */
1014  int condexit;
1015  FuncState *fs = ls->fs;
1016  int repeat_init = luaK_getlabel(fs);
1017  BlockCnt bl1, bl2;
1018  enterblock(fs, &bl1, 1);  /* loop block */
1019  enterblock(fs, &bl2, 0);  /* scope block */
1020  luaX_next(ls);  /* skip REPEAT */
1021  chunk(ls);
1022  check_match(ls, TK_UNTIL, TK_REPEAT, line);
1023  condexit = cond(ls);  /* read condition (inside scope block) */
1024  if (!bl2.upval) {  /* no upvalues? */
1025    leaveblock(fs);  /* finish scope */
1026    luaK_patchlist(ls->fs, condexit, repeat_init);  /* close the loop */
1027  }
1028  else {  /* complete semantics when there are upvalues */
1029    breakstat(ls);  /* if condition then break */
1030    luaK_patchtohere(ls->fs, condexit);  /* else... */
1031    leaveblock(fs);  /* finish scope... */
1032    luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init);  /* and repeat */
1033  }
1034  leaveblock(fs);  /* finish loop */
1035}
1036
1037
1038static int exp1 (LexState *ls) {
1039  expdesc e;
1040  int k;
1041  expr(ls, &e);
1042  k = e.k;
1043  luaK_exp2nextreg(ls->fs, &e);
1044  return k;
1045}
1046
1047
1048static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
1049  /* forbody -> DO block */
1050  BlockCnt bl;
1051  FuncState *fs = ls->fs;
1052  int prep, endfor;
1053  adjustlocalvars(ls, 3);  /* control variables */
1054  checknext(ls, TK_DO);
1055  prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
1056  enterblock(fs, &bl, 0);  /* scope for declared variables */
1057  adjustlocalvars(ls, nvars);
1058  luaK_reserveregs(fs, nvars);
1059  block(ls);
1060  leaveblock(fs);  /* end of scope for declared variables */
1061  luaK_patchtohere(fs, prep);
1062  endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) :
1063                     luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars);
1064  luaK_fixline(fs, line);  /* pretend that `OP_FOR' starts the loop */
1065  luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1);
1066}
1067
1068
1069static void fornum (LexState *ls, TString *varname, int line) {
1070  /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1071  FuncState *fs = ls->fs;
1072  int base = fs->freereg;
1073  new_localvarliteral(ls, "(for index)", 0);
1074  new_localvarliteral(ls, "(for limit)", 1);
1075  new_localvarliteral(ls, "(for step)", 2);
1076  new_localvar(ls, varname, 3);
1077  checknext(ls, '=');
1078  exp1(ls);  /* initial value */
1079  checknext(ls, ',');
1080  exp1(ls);  /* limit */
1081  if (testnext(ls, ','))
1082    exp1(ls);  /* optional step */
1083  else {  /* default step = 1 */
1084    luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1));
1085    luaK_reserveregs(fs, 1);
1086  }
1087  forbody(ls, base, line, 1, 1);
1088}
1089
1090
1091static void forlist (LexState *ls, TString *indexname) {
1092  /* forlist -> NAME {,NAME} IN explist1 forbody */
1093  FuncState *fs = ls->fs;
1094  expdesc e;
1095  int nvars = 0;
1096  int line;
1097  int base = fs->freereg;
1098  /* create control variables */
1099  new_localvarliteral(ls, "(for generator)", nvars++);
1100  new_localvarliteral(ls, "(for state)", nvars++);
1101  new_localvarliteral(ls, "(for control)", nvars++);
1102  /* create declared variables */
1103  new_localvar(ls, indexname, nvars++);
1104  while (testnext(ls, ','))
1105    new_localvar(ls, str_checkname(ls), nvars++);
1106  checknext(ls, TK_IN);
1107  line = ls->linenumber;
1108  adjust_assign(ls, 3, explist1(ls, &e), &e);
1109  luaK_checkstack(fs, 3);  /* extra space to call generator */
1110  forbody(ls, base, line, nvars - 3, 0);
1111}
1112
1113
1114static void forstat (LexState *ls, int line) {
1115  /* forstat -> FOR (fornum | forlist) END */
1116  FuncState *fs = ls->fs;
1117  TString *varname;
1118  BlockCnt bl;
1119  enterblock(fs, &bl, 1);  /* scope for loop and control variables */
1120  luaX_next(ls);  /* skip `for' */
1121  varname = str_checkname(ls);  /* first variable name */
1122  switch (ls->t.token) {
1123    case '=': fornum(ls, varname, line); break;
1124    case ',': case TK_IN: forlist(ls, varname); break;
1125    default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
1126  }
1127  check_match(ls, TK_END, TK_FOR, line);
1128  leaveblock(fs);  /* loop scope (`break' jumps to this point) */
1129}
1130
1131
1132static int test_then_block (LexState *ls) {
1133  /* test_then_block -> [IF | ELSEIF] cond THEN block */
1134  int condexit;
1135  luaX_next(ls);  /* skip IF or ELSEIF */
1136  condexit = cond(ls);
1137  checknext(ls, TK_THEN);
1138  block(ls);  /* `then' part */
1139  return condexit;
1140}
1141
1142
1143static void ifstat (LexState *ls, int line) {
1144  /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1145  FuncState *fs = ls->fs;
1146  int flist;
1147  int escapelist = NO_JUMP;
1148  flist = test_then_block(ls);  /* IF cond THEN block */
1149  while (ls->t.token == TK_ELSEIF) {
1150    luaK_concat(fs, &escapelist, luaK_jump(fs));
1151    luaK_patchtohere(fs, flist);
1152    flist = test_then_block(ls);  /* ELSEIF cond THEN block */
1153  }
1154  if (ls->t.token == TK_ELSE) {
1155    luaK_concat(fs, &escapelist, luaK_jump(fs));
1156    luaK_patchtohere(fs, flist);
1157    luaX_next(ls);  /* skip ELSE (after patch, for correct line info) */
1158    block(ls);  /* `else' part */
1159  }
1160  else
1161    luaK_concat(fs, &escapelist, flist);
1162  luaK_patchtohere(fs, escapelist);
1163  check_match(ls, TK_END, TK_IF, line);
1164}
1165
1166
1167static void localfunc (LexState *ls) {
1168  expdesc v, b;
1169  FuncState *fs = ls->fs;
1170  new_localvar(ls, str_checkname(ls), 0);
1171  init_exp(&v, VLOCAL, fs->freereg);
1172  luaK_reserveregs(fs, 1);
1173  adjustlocalvars(ls, 1);
1174  body(ls, &b, 0, ls->linenumber);
1175  luaK_storevar(fs, &v, &b);
1176  /* debug information will only see the variable after this point! */
1177  getlocvar(fs, fs->nactvar - 1).startpc = fs->pc;
1178}
1179
1180
1181static void localstat (LexState *ls) {
1182  /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
1183  int nvars = 0;
1184  int nexps;
1185  expdesc e;
1186  do {
1187    new_localvar(ls, str_checkname(ls), nvars++);
1188  } while (testnext(ls, ','));
1189  if (testnext(ls, '='))
1190    nexps = explist1(ls, &e);
1191  else {
1192    e.k = VVOID;
1193    nexps = 0;
1194  }
1195  adjust_assign(ls, nvars, nexps, &e);
1196  adjustlocalvars(ls, nvars);
1197}
1198
1199
1200static int funcname (LexState *ls, expdesc *v) {
1201  /* funcname -> NAME {field} [`:' NAME] */
1202  int needself = 0;
1203  singlevar(ls, v);
1204  while (ls->t.token == '.')
1205    field(ls, v);
1206  if (ls->t.token == ':') {
1207    needself = 1;
1208    field(ls, v);
1209  }
1210  return needself;
1211}
1212
1213
1214static void funcstat (LexState *ls, int line) {
1215  /* funcstat -> FUNCTION funcname body */
1216  int needself;
1217  expdesc v, b;
1218  luaX_next(ls);  /* skip FUNCTION */
1219  needself = funcname(ls, &v);
1220  body(ls, &b, needself, line);
1221  luaK_storevar(ls->fs, &v, &b);
1222  luaK_fixline(ls->fs, line);  /* definition `happens' in the first line */
1223}
1224
1225
1226static void exprstat (LexState *ls) {
1227  /* stat -> func | assignment */
1228  FuncState *fs = ls->fs;
1229  struct LHS_assign v;
1230  primaryexp(ls, &v.v);
1231  if (v.v.k == VCALL)  /* stat -> func */
1232    SETARG_C(getcode(fs, &v.v), 1);  /* call statement uses no results */
1233  else {  /* stat -> assignment */
1234    v.prev = NULL;
1235    assignment(ls, &v, 1);
1236  }
1237}
1238
1239
1240static void retstat (LexState *ls) {
1241  /* stat -> RETURN explist */
1242  FuncState *fs = ls->fs;
1243  expdesc e;
1244  int first, nret;  /* registers with returned values */
1245  luaX_next(ls);  /* skip RETURN */
1246  if (block_follow(ls->t.token) || ls->t.token == ';')
1247    first = nret = 0;  /* return no values */
1248  else {
1249    nret = explist1(ls, &e);  /* optional return values */
1250    if (hasmultret(e.k)) {
1251      luaK_setmultret(fs, &e);
1252      if (e.k == VCALL && nret == 1) {  /* tail call? */
1253        SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1254        lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1255      }
1256      first = fs->nactvar;
1257      nret = LUA_MULTRET;  /* return all values */
1258    }
1259    else {
1260      if (nret == 1)  /* only one single value? */
1261        first = luaK_exp2anyreg(fs, &e);
1262      else {
1263        luaK_exp2nextreg(fs, &e);  /* values must go to the `stack' */
1264        first = fs->nactvar;  /* return all `active' values */
1265        lua_assert(nret == fs->freereg - first);
1266      }
1267    }
1268  }
1269  luaK_ret(fs, first, nret);
1270}
1271
1272
1273static int statement (LexState *ls) {
1274  int line = ls->linenumber;  /* may be needed for error messages */
1275  switch (ls->t.token) {
1276    case TK_IF: {  /* stat -> ifstat */
1277      ifstat(ls, line);
1278      return 0;
1279    }
1280    case TK_WHILE: {  /* stat -> whilestat */
1281      whilestat(ls, line);
1282      return 0;
1283    }
1284    case TK_DO: {  /* stat -> DO block END */
1285      luaX_next(ls);  /* skip DO */
1286      block(ls);
1287      check_match(ls, TK_END, TK_DO, line);
1288      return 0;
1289    }
1290    case TK_FOR: {  /* stat -> forstat */
1291      forstat(ls, line);
1292      return 0;
1293    }
1294    case TK_REPEAT: {  /* stat -> repeatstat */
1295      repeatstat(ls, line);
1296      return 0;
1297    }
1298    case TK_FUNCTION: {
1299      funcstat(ls, line);  /* stat -> funcstat */
1300      return 0;
1301    }
1302    case TK_LOCAL: {  /* stat -> localstat */
1303      luaX_next(ls);  /* skip LOCAL */
1304      if (testnext(ls, TK_FUNCTION))  /* local function? */
1305        localfunc(ls);
1306      else
1307        localstat(ls);
1308      return 0;
1309    }
1310    case TK_RETURN: {  /* stat -> retstat */
1311      retstat(ls);
1312      return 1;  /* must be last statement */
1313    }
1314    case TK_BREAK: {  /* stat -> breakstat */
1315      luaX_next(ls);  /* skip BREAK */
1316      breakstat(ls);
1317      return 1;  /* must be last statement */
1318    }
1319    default: {
1320      exprstat(ls);
1321      return 0;  /* to avoid warnings */
1322    }
1323  }
1324}
1325
1326
1327static void chunk (LexState *ls) {
1328  /* chunk -> { stat [`;'] } */
1329  int islast = 0;
1330  enterlevel(ls);
1331  while (!islast && !block_follow(ls->t.token)) {
1332    islast = statement(ls);
1333    testnext(ls, ';');
1334    lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1335               ls->fs->freereg >= ls->fs->nactvar);
1336    ls->fs->freereg = ls->fs->nactvar;  /* free registers */
1337  }
1338  leavelevel(ls);
1339}
1340
1341/* }====================================================================== */
1342