Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/ceguilua/src/lua-5.0.3/lua/lparser.c @ 1803

Last change on this file since 1803 was 1803, checked in by rgrieder, 16 years ago

added files for lua 5.1.3, lua 5.0.3, CEGUILua-0.6.1 and CEGUILua-0.5.0b

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