PageRenderTime 112ms CodeModel.GetById 16ms app.highlight 78ms RepoModel.GetById 1ms app.codeStats 0ms

/src/lparser.c

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