1 /* $NetBSD: lparser.c,v 1.3 2015/02/02 14:03:05 lneto Exp $ */ 2 3 /* 4 ** Id: lparser.c,v 2.147 2014/12/27 20:31:43 roberto Exp 5 ** Lua Parser 6 ** See Copyright Notice in lua.h 7 */ 8 9 #define lparser_c 10 #define LUA_CORE 11 12 #include "lprefix.h" 13 14 15 #ifndef _KERNEL 16 #include <string.h> 17 #endif 18 19 #include "lua.h" 20 21 #include "lcode.h" 22 #include "ldebug.h" 23 #include "ldo.h" 24 #include "lfunc.h" 25 #include "llex.h" 26 #include "lmem.h" 27 #include "lobject.h" 28 #include "lopcodes.h" 29 #include "lparser.h" 30 #include "lstate.h" 31 #include "lstring.h" 32 #include "ltable.h" 33 34 35 36 /* maximum number of local variables per function (must be smaller 37 than 250, due to the bytecode format) */ 38 #define MAXVARS 200 39 40 41 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG) 42 43 44 /* because all strings are unified by the scanner, the parser 45 can use pointer equality for string equality */ 46 #define eqstr(a,b) ((a) == (b)) 47 48 49 /* 50 ** nodes for block list (list of active blocks) 51 */ 52 typedef struct BlockCnt { 53 struct BlockCnt *previous; /* chain */ 54 int firstlabel; /* index of first label in this block */ 55 int firstgoto; /* index of first pending goto in this block */ 56 lu_byte nactvar; /* # active locals outside the block */ 57 lu_byte upval; /* true if some variable in the block is an upvalue */ 58 lu_byte isloop; /* true if 'block' is a loop */ 59 } BlockCnt; 60 61 62 63 /* 64 ** prototypes for recursive non-terminal functions 65 */ 66 static void statement (LexState *ls); 67 static void expr (LexState *ls, expdesc *v); 68 69 70 /* semantic error */ 71 static l_noret semerror (LexState *ls, const char *msg) { 72 ls->t.token = 0; /* remove "near <token>" from final message */ 73 luaX_syntaxerror(ls, msg); 74 } 75 76 77 static l_noret error_expected (LexState *ls, int token) { 78 luaX_syntaxerror(ls, 79 luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); 80 } 81 82 83 static l_noret errorlimit (FuncState *fs, int limit, const char *what) { 84 lua_State *L = fs->ls->L; 85 const char *msg; 86 int line = fs->f->linedefined; 87 const char *where = (line == 0) 88 ? "main function" 89 : luaO_pushfstring(L, "function at line %d", line); 90 msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s", 91 what, limit, where); 92 luaX_syntaxerror(fs->ls, msg); 93 } 94 95 96 static void checklimit (FuncState *fs, int v, int l, const char *what) { 97 if (v > l) errorlimit(fs, l, what); 98 } 99 100 101 static int testnext (LexState *ls, int c) { 102 if (ls->t.token == c) { 103 luaX_next(ls); 104 return 1; 105 } 106 else return 0; 107 } 108 109 110 static void check (LexState *ls, int c) { 111 if (ls->t.token != c) 112 error_expected(ls, c); 113 } 114 115 116 static void checknext (LexState *ls, int c) { 117 check(ls, c); 118 luaX_next(ls); 119 } 120 121 122 #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } 123 124 125 126 static void check_match (LexState *ls, int what, int who, int where) { 127 if (!testnext(ls, what)) { 128 if (where == ls->linenumber) 129 error_expected(ls, what); 130 else { 131 luaX_syntaxerror(ls, luaO_pushfstring(ls->L, 132 "%s expected (to close %s at line %d)", 133 luaX_token2str(ls, what), luaX_token2str(ls, who), where)); 134 } 135 } 136 } 137 138 139 static TString *str_checkname (LexState *ls) { 140 TString *ts; 141 check(ls, TK_NAME); 142 ts = ls->t.seminfo.ts; 143 luaX_next(ls); 144 return ts; 145 } 146 147 148 static void init_exp (expdesc *e, expkind k, int i) { 149 e->f = e->t = NO_JUMP; 150 e->k = k; 151 e->u.info = i; 152 } 153 154 155 static void codestring (LexState *ls, expdesc *e, TString *s) { 156 init_exp(e, VK, luaK_stringK(ls->fs, s)); 157 } 158 159 160 static void checkname (LexState *ls, expdesc *e) { 161 codestring(ls, e, str_checkname(ls)); 162 } 163 164 165 static int registerlocalvar (LexState *ls, TString *varname) { 166 FuncState *fs = ls->fs; 167 Proto *f = fs->f; 168 int oldsize = f->sizelocvars; 169 luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars, 170 LocVar, SHRT_MAX, "local variables"); 171 while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL; 172 f->locvars[fs->nlocvars].varname = varname; 173 luaC_objbarrier(ls->L, f, varname); 174 return fs->nlocvars++; 175 } 176 177 178 static void new_localvar (LexState *ls, TString *name) { 179 FuncState *fs = ls->fs; 180 Dyndata *dyd = ls->dyd; 181 int reg = registerlocalvar(ls, name); 182 checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal, 183 MAXVARS, "local variables"); 184 luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1, 185 dyd->actvar.size, Vardesc, MAX_INT, "local variables"); 186 dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg); 187 } 188 189 190 static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) { 191 new_localvar(ls, luaX_newstring(ls, name, sz)); 192 } 193 194 #define new_localvarliteral(ls,v) \ 195 new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1) 196 197 198 static LocVar *getlocvar (FuncState *fs, int i) { 199 int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx; 200 lua_assert(idx < fs->nlocvars); 201 return &fs->f->locvars[idx]; 202 } 203 204 205 static void adjustlocalvars (LexState *ls, int nvars) { 206 FuncState *fs = ls->fs; 207 fs->nactvar = cast_byte(fs->nactvar + nvars); 208 for (; nvars; nvars--) { 209 getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc; 210 } 211 } 212 213 214 static void removevars (FuncState *fs, int tolevel) { 215 fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel); 216 while (fs->nactvar > tolevel) 217 getlocvar(fs, --fs->nactvar)->endpc = fs->pc; 218 } 219 220 221 static int searchupvalue (FuncState *fs, TString *name) { 222 int i; 223 Upvaldesc *up = fs->f->upvalues; 224 for (i = 0; i < fs->nups; i++) { 225 if (eqstr(up[i].name, name)) return i; 226 } 227 return -1; /* not found */ 228 } 229 230 231 static int newupvalue (FuncState *fs, TString *name, expdesc *v) { 232 Proto *f = fs->f; 233 int oldsize = f->sizeupvalues; 234 checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); 235 luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues, 236 Upvaldesc, MAXUPVAL, "upvalues"); 237 while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL; 238 f->upvalues[fs->nups].instack = (v->k == VLOCAL); 239 f->upvalues[fs->nups].idx = cast_byte(v->u.info); 240 f->upvalues[fs->nups].name = name; 241 luaC_objbarrier(fs->ls->L, f, name); 242 return fs->nups++; 243 } 244 245 246 static int searchvar (FuncState *fs, TString *n) { 247 int i; 248 for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) { 249 if (eqstr(n, getlocvar(fs, i)->varname)) 250 return i; 251 } 252 return -1; /* not found */ 253 } 254 255 256 /* 257 Mark block where variable at given level was defined 258 (to emit close instructions later). 259 */ 260 static void markupval (FuncState *fs, int level) { 261 BlockCnt *bl = fs->bl; 262 while (bl->nactvar > level) bl = bl->previous; 263 bl->upval = 1; 264 } 265 266 267 /* 268 Find variable with given name 'n'. If it is an upvalue, add this 269 upvalue into all intermediate functions. 270 */ 271 static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { 272 if (fs == NULL) /* no more levels? */ 273 return VVOID; /* default is global */ 274 else { 275 int v = searchvar(fs, n); /* look up locals at current level */ 276 if (v >= 0) { /* found? */ 277 init_exp(var, VLOCAL, v); /* variable is local */ 278 if (!base) 279 markupval(fs, v); /* local will be used as an upval */ 280 return VLOCAL; 281 } 282 else { /* not found as local at current level; try upvalues */ 283 int idx = searchupvalue(fs, n); /* try existing upvalues */ 284 if (idx < 0) { /* not found? */ 285 if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */ 286 return VVOID; /* not found; is a global */ 287 /* else was LOCAL or UPVAL */ 288 idx = newupvalue(fs, n, var); /* will be a new upvalue */ 289 } 290 init_exp(var, VUPVAL, idx); 291 return VUPVAL; 292 } 293 } 294 } 295 296 297 static void singlevar (LexState *ls, expdesc *var) { 298 TString *varname = str_checkname(ls); 299 FuncState *fs = ls->fs; 300 if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */ 301 expdesc key; 302 singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ 303 lua_assert(var->k == VLOCAL || var->k == VUPVAL); 304 codestring(ls, &key, varname); /* key is variable name */ 305 luaK_indexed(fs, var, &key); /* env[varname] */ 306 } 307 } 308 309 310 static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { 311 FuncState *fs = ls->fs; 312 int extra = nvars - nexps; 313 if (hasmultret(e->k)) { 314 extra++; /* includes call itself */ 315 if (extra < 0) extra = 0; 316 luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ 317 if (extra > 1) luaK_reserveregs(fs, extra-1); 318 } 319 else { 320 if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */ 321 if (extra > 0) { 322 int reg = fs->freereg; 323 luaK_reserveregs(fs, extra); 324 luaK_nil(fs, reg, extra); 325 } 326 } 327 } 328 329 330 static void enterlevel (LexState *ls) { 331 lua_State *L = ls->L; 332 ++L->nCcalls; 333 checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels"); 334 } 335 336 337 #define leavelevel(ls) ((ls)->L->nCcalls--) 338 339 340 static void closegoto (LexState *ls, int g, Labeldesc *label) { 341 int i; 342 FuncState *fs = ls->fs; 343 Labellist *gl = &ls->dyd->gt; 344 Labeldesc *gt = &gl->arr[g]; 345 lua_assert(eqstr(gt->name, label->name)); 346 if (gt->nactvar < label->nactvar) { 347 TString *vname = getlocvar(fs, gt->nactvar)->varname; 348 const char *msg = luaO_pushfstring(ls->L, 349 "<goto %s> at line %d jumps into the scope of local '%s'", 350 getstr(gt->name), gt->line, getstr(vname)); 351 semerror(ls, msg); 352 } 353 luaK_patchlist(fs, gt->pc, label->pc); 354 /* remove goto from pending list */ 355 for (i = g; i < gl->n - 1; i++) 356 gl->arr[i] = gl->arr[i + 1]; 357 gl->n--; 358 } 359 360 361 /* 362 ** try to close a goto with existing labels; this solves backward jumps 363 */ 364 static int findlabel (LexState *ls, int g) { 365 int i; 366 BlockCnt *bl = ls->fs->bl; 367 Dyndata *dyd = ls->dyd; 368 Labeldesc *gt = &dyd->gt.arr[g]; 369 /* check labels in current block for a match */ 370 for (i = bl->firstlabel; i < dyd->label.n; i++) { 371 Labeldesc *lb = &dyd->label.arr[i]; 372 if (eqstr(lb->name, gt->name)) { /* correct label? */ 373 if (gt->nactvar > lb->nactvar && 374 (bl->upval || dyd->label.n > bl->firstlabel)) 375 luaK_patchclose(ls->fs, gt->pc, lb->nactvar); 376 closegoto(ls, g, lb); /* close it */ 377 return 1; 378 } 379 } 380 return 0; /* label not found; cannot close goto */ 381 } 382 383 384 static int newlabelentry (LexState *ls, Labellist *l, TString *name, 385 int line, int pc) { 386 int n = l->n; 387 luaM_growvector(ls->L, l->arr, n, l->size, 388 Labeldesc, SHRT_MAX, "labels/gotos"); 389 l->arr[n].name = name; 390 l->arr[n].line = line; 391 l->arr[n].nactvar = ls->fs->nactvar; 392 l->arr[n].pc = pc; 393 l->n = n + 1; 394 return n; 395 } 396 397 398 /* 399 ** check whether new label 'lb' matches any pending gotos in current 400 ** block; solves forward jumps 401 */ 402 static void findgotos (LexState *ls, Labeldesc *lb) { 403 Labellist *gl = &ls->dyd->gt; 404 int i = ls->fs->bl->firstgoto; 405 while (i < gl->n) { 406 if (eqstr(gl->arr[i].name, lb->name)) 407 closegoto(ls, i, lb); 408 else 409 i++; 410 } 411 } 412 413 414 /* 415 ** export pending gotos to outer level, to check them against 416 ** outer labels; if the block being exited has upvalues, and 417 ** the goto exits the scope of any variable (which can be the 418 ** upvalue), close those variables being exited. 419 */ 420 static void movegotosout (FuncState *fs, BlockCnt *bl) { 421 int i = bl->firstgoto; 422 Labellist *gl = &fs->ls->dyd->gt; 423 /* correct pending gotos to current block and try to close it 424 with visible labels */ 425 while (i < gl->n) { 426 Labeldesc *gt = &gl->arr[i]; 427 if (gt->nactvar > bl->nactvar) { 428 if (bl->upval) 429 luaK_patchclose(fs, gt->pc, bl->nactvar); 430 gt->nactvar = bl->nactvar; 431 } 432 if (!findlabel(fs->ls, i)) 433 i++; /* move to next one */ 434 } 435 } 436 437 438 static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) { 439 bl->isloop = isloop; 440 bl->nactvar = fs->nactvar; 441 bl->firstlabel = fs->ls->dyd->label.n; 442 bl->firstgoto = fs->ls->dyd->gt.n; 443 bl->upval = 0; 444 bl->previous = fs->bl; 445 fs->bl = bl; 446 lua_assert(fs->freereg == fs->nactvar); 447 } 448 449 450 /* 451 ** create a label named 'break' to resolve break statements 452 */ 453 static void breaklabel (LexState *ls) { 454 TString *n = luaS_new(ls->L, "break"); 455 int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc); 456 findgotos(ls, &ls->dyd->label.arr[l]); 457 } 458 459 /* 460 ** generates an error for an undefined 'goto'; choose appropriate 461 ** message when label name is a reserved word (which can only be 'break') 462 */ 463 static l_noret undefgoto (LexState *ls, Labeldesc *gt) { 464 const char *msg = isreserved(gt->name) 465 ? "<%s> at line %d not inside a loop" 466 : "no visible label '%s' for <goto> at line %d"; 467 msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line); 468 semerror(ls, msg); 469 } 470 471 472 static void leaveblock (FuncState *fs) { 473 BlockCnt *bl = fs->bl; 474 LexState *ls = fs->ls; 475 if (bl->previous && bl->upval) { 476 /* create a 'jump to here' to close upvalues */ 477 int j = luaK_jump(fs); 478 luaK_patchclose(fs, j, bl->nactvar); 479 luaK_patchtohere(fs, j); 480 } 481 if (bl->isloop) 482 breaklabel(ls); /* close pending breaks */ 483 fs->bl = bl->previous; 484 removevars(fs, bl->nactvar); 485 lua_assert(bl->nactvar == fs->nactvar); 486 fs->freereg = fs->nactvar; /* free registers */ 487 ls->dyd->label.n = bl->firstlabel; /* remove local labels */ 488 if (bl->previous) /* inner block? */ 489 movegotosout(fs, bl); /* update pending gotos to outer block */ 490 else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */ 491 undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */ 492 } 493 494 495 /* 496 ** adds a new prototype into list of prototypes 497 */ 498 static Proto *addprototype (LexState *ls) { 499 Proto *clp; 500 lua_State *L = ls->L; 501 FuncState *fs = ls->fs; 502 Proto *f = fs->f; /* prototype of current function */ 503 if (fs->np >= f->sizep) { 504 int oldsize = f->sizep; 505 luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions"); 506 while (oldsize < f->sizep) f->p[oldsize++] = NULL; 507 } 508 f->p[fs->np++] = clp = luaF_newproto(L); 509 luaC_objbarrier(L, f, clp); 510 return clp; 511 } 512 513 514 /* 515 ** codes instruction to create new closure in parent function. 516 ** The OP_CLOSURE instruction must use the last available register, 517 ** so that, if it invokes the GC, the GC knows which registers 518 ** are in use at that time. 519 */ 520 static void codeclosure (LexState *ls, expdesc *v) { 521 FuncState *fs = ls->fs->prev; 522 init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1)); 523 luaK_exp2nextreg(fs, v); /* fix it at the last register */ 524 } 525 526 527 static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) { 528 Proto *f; 529 fs->prev = ls->fs; /* linked list of funcstates */ 530 fs->ls = ls; 531 ls->fs = fs; 532 fs->pc = 0; 533 fs->lasttarget = 0; 534 fs->jpc = NO_JUMP; 535 fs->freereg = 0; 536 fs->nk = 0; 537 fs->np = 0; 538 fs->nups = 0; 539 fs->nlocvars = 0; 540 fs->nactvar = 0; 541 fs->firstlocal = ls->dyd->actvar.n; 542 fs->bl = NULL; 543 f = fs->f; 544 f->source = ls->source; 545 f->maxstacksize = 2; /* registers 0/1 are always valid */ 546 enterblock(fs, bl, 0); 547 } 548 549 550 static void close_func (LexState *ls) { 551 lua_State *L = ls->L; 552 FuncState *fs = ls->fs; 553 Proto *f = fs->f; 554 luaK_ret(fs, 0, 0); /* final return */ 555 leaveblock(fs); 556 luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); 557 f->sizecode = fs->pc; 558 luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int); 559 f->sizelineinfo = fs->pc; 560 luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue); 561 f->sizek = fs->nk; 562 luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *); 563 f->sizep = fs->np; 564 luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar); 565 f->sizelocvars = fs->nlocvars; 566 luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc); 567 f->sizeupvalues = fs->nups; 568 lua_assert(fs->bl == NULL); 569 ls->fs = fs->prev; 570 luaC_checkGC(L); 571 } 572 573 574 575 /*============================================================*/ 576 /* GRAMMAR RULES */ 577 /*============================================================*/ 578 579 580 /* 581 ** check whether current token is in the follow set of a block. 582 ** 'until' closes syntactical blocks, but do not close scope, 583 ** so it is handled in separate. 584 */ 585 static int block_follow (LexState *ls, int withuntil) { 586 switch (ls->t.token) { 587 case TK_ELSE: case TK_ELSEIF: 588 case TK_END: case TK_EOS: 589 return 1; 590 case TK_UNTIL: return withuntil; 591 default: return 0; 592 } 593 } 594 595 596 static void statlist (LexState *ls) { 597 /* statlist -> { stat [';'] } */ 598 while (!block_follow(ls, 1)) { 599 if (ls->t.token == TK_RETURN) { 600 statement(ls); 601 return; /* 'return' must be last statement */ 602 } 603 statement(ls); 604 } 605 } 606 607 608 static void fieldsel (LexState *ls, expdesc *v) { 609 /* fieldsel -> ['.' | ':'] NAME */ 610 FuncState *fs = ls->fs; 611 expdesc key; 612 luaK_exp2anyregup(fs, v); 613 luaX_next(ls); /* skip the dot or colon */ 614 checkname(ls, &key); 615 luaK_indexed(fs, v, &key); 616 } 617 618 619 static void yindex (LexState *ls, expdesc *v) { 620 /* index -> '[' expr ']' */ 621 luaX_next(ls); /* skip the '[' */ 622 expr(ls, v); 623 luaK_exp2val(ls->fs, v); 624 checknext(ls, ']'); 625 } 626 627 628 /* 629 ** {====================================================================== 630 ** Rules for Constructors 631 ** ======================================================================= 632 */ 633 634 635 struct ConsControl { 636 expdesc v; /* last list item read */ 637 expdesc *t; /* table descriptor */ 638 int nh; /* total number of 'record' elements */ 639 int na; /* total number of array elements */ 640 int tostore; /* number of array elements pending to be stored */ 641 }; 642 643 644 static void recfield (LexState *ls, struct ConsControl *cc) { 645 /* recfield -> (NAME | '['exp1']') = exp1 */ 646 FuncState *fs = ls->fs; 647 int reg = ls->fs->freereg; 648 expdesc key, val; 649 int rkkey; 650 if (ls->t.token == TK_NAME) { 651 checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); 652 checkname(ls, &key); 653 } 654 else /* ls->t.token == '[' */ 655 yindex(ls, &key); 656 cc->nh++; 657 checknext(ls, '='); 658 rkkey = luaK_exp2RK(fs, &key); 659 expr(ls, &val); 660 luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val)); 661 fs->freereg = reg; /* free registers */ 662 } 663 664 665 static void closelistfield (FuncState *fs, struct ConsControl *cc) { 666 if (cc->v.k == VVOID) return; /* there is no list item */ 667 luaK_exp2nextreg(fs, &cc->v); 668 cc->v.k = VVOID; 669 if (cc->tostore == LFIELDS_PER_FLUSH) { 670 luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */ 671 cc->tostore = 0; /* no more items pending */ 672 } 673 } 674 675 676 static void lastlistfield (FuncState *fs, struct ConsControl *cc) { 677 if (cc->tostore == 0) return; 678 if (hasmultret(cc->v.k)) { 679 luaK_setmultret(fs, &cc->v); 680 luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET); 681 cc->na--; /* do not count last expression (unknown number of elements) */ 682 } 683 else { 684 if (cc->v.k != VVOID) 685 luaK_exp2nextreg(fs, &cc->v); 686 luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); 687 } 688 } 689 690 691 static void listfield (LexState *ls, struct ConsControl *cc) { 692 /* listfield -> exp */ 693 expr(ls, &cc->v); 694 checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor"); 695 cc->na++; 696 cc->tostore++; 697 } 698 699 700 static void field (LexState *ls, struct ConsControl *cc) { 701 /* field -> listfield | recfield */ 702 switch(ls->t.token) { 703 case TK_NAME: { /* may be 'listfield' or 'recfield' */ 704 if (luaX_lookahead(ls) != '=') /* expression? */ 705 listfield(ls, cc); 706 else 707 recfield(ls, cc); 708 break; 709 } 710 case '[': { 711 recfield(ls, cc); 712 break; 713 } 714 default: { 715 listfield(ls, cc); 716 break; 717 } 718 } 719 } 720 721 722 static void constructor (LexState *ls, expdesc *t) { 723 /* constructor -> '{' [ field { sep field } [sep] ] '}' 724 sep -> ',' | ';' */ 725 FuncState *fs = ls->fs; 726 int line = ls->linenumber; 727 int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); 728 struct ConsControl cc; 729 cc.na = cc.nh = cc.tostore = 0; 730 cc.t = t; 731 init_exp(t, VRELOCABLE, pc); 732 init_exp(&cc.v, VVOID, 0); /* no value (yet) */ 733 luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */ 734 checknext(ls, '{'); 735 do { 736 lua_assert(cc.v.k == VVOID || cc.tostore > 0); 737 if (ls->t.token == '}') break; 738 closelistfield(fs, &cc); 739 field(ls, &cc); 740 } while (testnext(ls, ',') || testnext(ls, ';')); 741 check_match(ls, '}', '{', line); 742 lastlistfield(fs, &cc); 743 SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */ 744 SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */ 745 } 746 747 /* }====================================================================== */ 748 749 750 751 static void parlist (LexState *ls) { 752 /* parlist -> [ param { ',' param } ] */ 753 FuncState *fs = ls->fs; 754 Proto *f = fs->f; 755 int nparams = 0; 756 f->is_vararg = 0; 757 if (ls->t.token != ')') { /* is 'parlist' not empty? */ 758 do { 759 switch (ls->t.token) { 760 case TK_NAME: { /* param -> NAME */ 761 new_localvar(ls, str_checkname(ls)); 762 nparams++; 763 break; 764 } 765 case TK_DOTS: { /* param -> '...' */ 766 luaX_next(ls); 767 f->is_vararg = 1; 768 break; 769 } 770 default: luaX_syntaxerror(ls, "<name> or '...' expected"); 771 } 772 } while (!f->is_vararg && testnext(ls, ',')); 773 } 774 adjustlocalvars(ls, nparams); 775 f->numparams = cast_byte(fs->nactvar); 776 luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */ 777 } 778 779 780 static void body (LexState *ls, expdesc *e, int ismethod, int line) { 781 /* body -> '(' parlist ')' block END */ 782 FuncState new_fs; 783 BlockCnt bl; 784 new_fs.f = addprototype(ls); 785 new_fs.f->linedefined = line; 786 open_func(ls, &new_fs, &bl); 787 checknext(ls, '('); 788 if (ismethod) { 789 new_localvarliteral(ls, "self"); /* create 'self' parameter */ 790 adjustlocalvars(ls, 1); 791 } 792 parlist(ls); 793 checknext(ls, ')'); 794 statlist(ls); 795 new_fs.f->lastlinedefined = ls->linenumber; 796 check_match(ls, TK_END, TK_FUNCTION, line); 797 codeclosure(ls, e); 798 close_func(ls); 799 } 800 801 802 static int explist (LexState *ls, expdesc *v) { 803 /* explist -> expr { ',' expr } */ 804 int n = 1; /* at least one expression */ 805 expr(ls, v); 806 while (testnext(ls, ',')) { 807 luaK_exp2nextreg(ls->fs, v); 808 expr(ls, v); 809 n++; 810 } 811 return n; 812 } 813 814 815 static void funcargs (LexState *ls, expdesc *f, int line) { 816 FuncState *fs = ls->fs; 817 expdesc args; 818 int base, nparams; 819 switch (ls->t.token) { 820 case '(': { /* funcargs -> '(' [ explist ] ')' */ 821 luaX_next(ls); 822 if (ls->t.token == ')') /* arg list is empty? */ 823 args.k = VVOID; 824 else { 825 explist(ls, &args); 826 luaK_setmultret(fs, &args); 827 } 828 check_match(ls, ')', '(', line); 829 break; 830 } 831 case '{': { /* funcargs -> constructor */ 832 constructor(ls, &args); 833 break; 834 } 835 case TK_STRING: { /* funcargs -> STRING */ 836 codestring(ls, &args, ls->t.seminfo.ts); 837 luaX_next(ls); /* must use 'seminfo' before 'next' */ 838 break; 839 } 840 default: { 841 luaX_syntaxerror(ls, "function arguments expected"); 842 } 843 } 844 lua_assert(f->k == VNONRELOC); 845 base = f->u.info; /* base register for call */ 846 if (hasmultret(args.k)) 847 nparams = LUA_MULTRET; /* open call */ 848 else { 849 if (args.k != VVOID) 850 luaK_exp2nextreg(fs, &args); /* close last argument */ 851 nparams = fs->freereg - (base+1); 852 } 853 init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); 854 luaK_fixline(fs, line); 855 fs->freereg = base+1; /* call remove function and arguments and leaves 856 (unless changed) one result */ 857 } 858 859 860 861 862 /* 863 ** {====================================================================== 864 ** Expression parsing 865 ** ======================================================================= 866 */ 867 868 869 static void primaryexp (LexState *ls, expdesc *v) { 870 /* primaryexp -> NAME | '(' expr ')' */ 871 switch (ls->t.token) { 872 case '(': { 873 int line = ls->linenumber; 874 luaX_next(ls); 875 expr(ls, v); 876 check_match(ls, ')', '(', line); 877 luaK_dischargevars(ls->fs, v); 878 return; 879 } 880 case TK_NAME: { 881 singlevar(ls, v); 882 return; 883 } 884 default: { 885 luaX_syntaxerror(ls, "unexpected symbol"); 886 } 887 } 888 } 889 890 891 static void suffixedexp (LexState *ls, expdesc *v) { 892 /* suffixedexp -> 893 primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */ 894 FuncState *fs = ls->fs; 895 int line = ls->linenumber; 896 primaryexp(ls, v); 897 for (;;) { 898 switch (ls->t.token) { 899 case '.': { /* fieldsel */ 900 fieldsel(ls, v); 901 break; 902 } 903 case '[': { /* '[' exp1 ']' */ 904 expdesc key; 905 luaK_exp2anyregup(fs, v); 906 yindex(ls, &key); 907 luaK_indexed(fs, v, &key); 908 break; 909 } 910 case ':': { /* ':' NAME funcargs */ 911 expdesc key; 912 luaX_next(ls); 913 checkname(ls, &key); 914 luaK_self(fs, v, &key); 915 funcargs(ls, v, line); 916 break; 917 } 918 case '(': case TK_STRING: case '{': { /* funcargs */ 919 luaK_exp2nextreg(fs, v); 920 funcargs(ls, v, line); 921 break; 922 } 923 default: return; 924 } 925 } 926 } 927 928 929 static void simpleexp (LexState *ls, expdesc *v) { 930 /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... | 931 constructor | FUNCTION body | suffixedexp */ 932 switch (ls->t.token) { 933 #ifndef _KERNEL 934 case TK_FLT: { 935 init_exp(v, VKFLT, 0); 936 v->u.nval = ls->t.seminfo.r; 937 break; 938 } 939 #endif 940 case TK_INT: { 941 init_exp(v, VKINT, 0); 942 v->u.ival = ls->t.seminfo.i; 943 break; 944 } 945 case TK_STRING: { 946 codestring(ls, v, ls->t.seminfo.ts); 947 break; 948 } 949 case TK_NIL: { 950 init_exp(v, VNIL, 0); 951 break; 952 } 953 case TK_TRUE: { 954 init_exp(v, VTRUE, 0); 955 break; 956 } 957 case TK_FALSE: { 958 init_exp(v, VFALSE, 0); 959 break; 960 } 961 case TK_DOTS: { /* vararg */ 962 FuncState *fs = ls->fs; 963 check_condition(ls, fs->f->is_vararg, 964 "cannot use '...' outside a vararg function"); 965 init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0)); 966 break; 967 } 968 case '{': { /* constructor */ 969 constructor(ls, v); 970 return; 971 } 972 case TK_FUNCTION: { 973 luaX_next(ls); 974 body(ls, v, 0, ls->linenumber); 975 return; 976 } 977 default: { 978 suffixedexp(ls, v); 979 return; 980 } 981 } 982 luaX_next(ls); 983 } 984 985 986 static UnOpr getunopr (int op) { 987 switch (op) { 988 case TK_NOT: return OPR_NOT; 989 case '-': return OPR_MINUS; 990 case '~': return OPR_BNOT; 991 case '#': return OPR_LEN; 992 default: return OPR_NOUNOPR; 993 } 994 } 995 996 997 static BinOpr getbinopr (int op) { 998 switch (op) { 999 case '+': return OPR_ADD; 1000 case '-': return OPR_SUB; 1001 case '*': return OPR_MUL; 1002 case '%': return OPR_MOD; 1003 #ifndef _KERNEL 1004 case '^': return OPR_POW; 1005 case '/': return OPR_DIV; 1006 #else 1007 case '/': return OPR_IDIV; 1008 #endif 1009 case TK_IDIV: return OPR_IDIV; 1010 case '&': return OPR_BAND; 1011 case '|': return OPR_BOR; 1012 case '~': return OPR_BXOR; 1013 case TK_SHL: return OPR_SHL; 1014 case TK_SHR: return OPR_SHR; 1015 case TK_CONCAT: return OPR_CONCAT; 1016 case TK_NE: return OPR_NE; 1017 case TK_EQ: return OPR_EQ; 1018 case '<': return OPR_LT; 1019 case TK_LE: return OPR_LE; 1020 case '>': return OPR_GT; 1021 case TK_GE: return OPR_GE; 1022 case TK_AND: return OPR_AND; 1023 case TK_OR: return OPR_OR; 1024 default: return OPR_NOBINOPR; 1025 } 1026 } 1027 1028 1029 static const struct { 1030 lu_byte left; /* left priority for each binary operator */ 1031 lu_byte right; /* right priority */ 1032 } priority[] = { /* ORDER OPR */ 1033 {10, 10}, {10, 10}, /* '+' '-' */ 1034 {11, 11}, {11, 11}, /* '*' '%' */ 1035 {14, 13}, /* '^' (right associative) */ 1036 {11, 11}, {11, 11}, /* '/' '//' */ 1037 {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */ 1038 {7, 7}, {7, 7}, /* '<<' '>>' */ 1039 {9, 8}, /* '..' (right associative) */ 1040 {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ 1041 {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ 1042 {2, 2}, {1, 1} /* and, or */ 1043 }; 1044 1045 #define UNARY_PRIORITY 12 /* priority for unary operators */ 1046 1047 1048 /* 1049 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr } 1050 ** where 'binop' is any binary operator with a priority higher than 'limit' 1051 */ 1052 static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { 1053 BinOpr op; 1054 UnOpr uop; 1055 enterlevel(ls); 1056 uop = getunopr(ls->t.token); 1057 if (uop != OPR_NOUNOPR) { 1058 int line = ls->linenumber; 1059 luaX_next(ls); 1060 subexpr(ls, v, UNARY_PRIORITY); 1061 luaK_prefix(ls->fs, uop, v, line); 1062 } 1063 else simpleexp(ls, v); 1064 /* expand while operators have priorities higher than 'limit' */ 1065 op = getbinopr(ls->t.token); 1066 while (op != OPR_NOBINOPR && priority[op].left > limit) { 1067 expdesc v2; 1068 BinOpr nextop; 1069 int line = ls->linenumber; 1070 luaX_next(ls); 1071 luaK_infix(ls->fs, op, v); 1072 /* read sub-expression with higher priority */ 1073 nextop = subexpr(ls, &v2, priority[op].right); 1074 luaK_posfix(ls->fs, op, v, &v2, line); 1075 op = nextop; 1076 } 1077 leavelevel(ls); 1078 return op; /* return first untreated operator */ 1079 } 1080 1081 1082 static void expr (LexState *ls, expdesc *v) { 1083 subexpr(ls, v, 0); 1084 } 1085 1086 /* }==================================================================== */ 1087 1088 1089 1090 /* 1091 ** {====================================================================== 1092 ** Rules for Statements 1093 ** ======================================================================= 1094 */ 1095 1096 1097 static void block (LexState *ls) { 1098 /* block -> statlist */ 1099 FuncState *fs = ls->fs; 1100 BlockCnt bl; 1101 enterblock(fs, &bl, 0); 1102 statlist(ls); 1103 leaveblock(fs); 1104 } 1105 1106 1107 /* 1108 ** structure to chain all variables in the left-hand side of an 1109 ** assignment 1110 */ 1111 struct LHS_assign { 1112 struct LHS_assign *prev; 1113 expdesc v; /* variable (global, local, upvalue, or indexed) */ 1114 }; 1115 1116 1117 /* 1118 ** check whether, in an assignment to an upvalue/local variable, the 1119 ** upvalue/local variable is begin used in a previous assignment to a 1120 ** table. If so, save original upvalue/local value in a safe place and 1121 ** use this safe copy in the previous assignment. 1122 */ 1123 static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { 1124 FuncState *fs = ls->fs; 1125 int extra = fs->freereg; /* eventual position to save local variable */ 1126 int conflict = 0; 1127 for (; lh; lh = lh->prev) { /* check all previous assignments */ 1128 if (lh->v.k == VINDEXED) { /* assigning to a table? */ 1129 /* table is the upvalue/local being assigned now? */ 1130 if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) { 1131 conflict = 1; 1132 lh->v.u.ind.vt = VLOCAL; 1133 lh->v.u.ind.t = extra; /* previous assignment will use safe copy */ 1134 } 1135 /* index is the local being assigned? (index cannot be upvalue) */ 1136 if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) { 1137 conflict = 1; 1138 lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ 1139 } 1140 } 1141 } 1142 if (conflict) { 1143 /* copy upvalue/local value to a temporary (in position 'extra') */ 1144 OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL; 1145 luaK_codeABC(fs, op, extra, v->u.info, 0); 1146 luaK_reserveregs(fs, 1); 1147 } 1148 } 1149 1150 1151 static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) { 1152 expdesc e; 1153 check_condition(ls, vkisvar(lh->v.k), "syntax error"); 1154 if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */ 1155 struct LHS_assign nv; 1156 nv.prev = lh; 1157 suffixedexp(ls, &nv.v); 1158 if (nv.v.k != VINDEXED) 1159 check_conflict(ls, lh, &nv.v); 1160 checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS, 1161 "C levels"); 1162 assignment(ls, &nv, nvars+1); 1163 } 1164 else { /* assignment -> '=' explist */ 1165 int nexps; 1166 checknext(ls, '='); 1167 nexps = explist(ls, &e); 1168 if (nexps != nvars) { 1169 adjust_assign(ls, nvars, nexps, &e); 1170 if (nexps > nvars) 1171 ls->fs->freereg -= nexps - nvars; /* remove extra values */ 1172 } 1173 else { 1174 luaK_setoneret(ls->fs, &e); /* close last expression */ 1175 luaK_storevar(ls->fs, &lh->v, &e); 1176 return; /* avoid default */ 1177 } 1178 } 1179 init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */ 1180 luaK_storevar(ls->fs, &lh->v, &e); 1181 } 1182 1183 1184 static int cond (LexState *ls) { 1185 /* cond -> exp */ 1186 expdesc v; 1187 expr(ls, &v); /* read condition */ 1188 if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */ 1189 luaK_goiftrue(ls->fs, &v); 1190 return v.f; 1191 } 1192 1193 1194 static void gotostat (LexState *ls, int pc) { 1195 int line = ls->linenumber; 1196 TString *label; 1197 int g; 1198 if (testnext(ls, TK_GOTO)) 1199 label = str_checkname(ls); 1200 else { 1201 luaX_next(ls); /* skip break */ 1202 label = luaS_new(ls->L, "break"); 1203 } 1204 g = newlabelentry(ls, &ls->dyd->gt, label, line, pc); 1205 findlabel(ls, g); /* close it if label already defined */ 1206 } 1207 1208 1209 /* check for repeated labels on the same block */ 1210 static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) { 1211 int i; 1212 for (i = fs->bl->firstlabel; i < ll->n; i++) { 1213 if (eqstr(label, ll->arr[i].name)) { 1214 const char *msg = luaO_pushfstring(fs->ls->L, 1215 "label '%s' already defined on line %d", 1216 getstr(label), ll->arr[i].line); 1217 semerror(fs->ls, msg); 1218 } 1219 } 1220 } 1221 1222 1223 /* skip no-op statements */ 1224 static void skipnoopstat (LexState *ls) { 1225 while (ls->t.token == ';' || ls->t.token == TK_DBCOLON) 1226 statement(ls); 1227 } 1228 1229 1230 static void labelstat (LexState *ls, TString *label, int line) { 1231 /* label -> '::' NAME '::' */ 1232 FuncState *fs = ls->fs; 1233 Labellist *ll = &ls->dyd->label; 1234 int l; /* index of new label being created */ 1235 checkrepeated(fs, ll, label); /* check for repeated labels */ 1236 checknext(ls, TK_DBCOLON); /* skip double colon */ 1237 /* create new entry for this label */ 1238 l = newlabelentry(ls, ll, label, line, fs->pc); 1239 skipnoopstat(ls); /* skip other no-op statements */ 1240 if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */ 1241 /* assume that locals are already out of scope */ 1242 ll->arr[l].nactvar = fs->bl->nactvar; 1243 } 1244 findgotos(ls, &ll->arr[l]); 1245 } 1246 1247 1248 static void whilestat (LexState *ls, int line) { 1249 /* whilestat -> WHILE cond DO block END */ 1250 FuncState *fs = ls->fs; 1251 int whileinit; 1252 int condexit; 1253 BlockCnt bl; 1254 luaX_next(ls); /* skip WHILE */ 1255 whileinit = luaK_getlabel(fs); 1256 condexit = cond(ls); 1257 enterblock(fs, &bl, 1); 1258 checknext(ls, TK_DO); 1259 block(ls); 1260 luaK_jumpto(fs, whileinit); 1261 check_match(ls, TK_END, TK_WHILE, line); 1262 leaveblock(fs); 1263 luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ 1264 } 1265 1266 1267 static void repeatstat (LexState *ls, int line) { 1268 /* repeatstat -> REPEAT block UNTIL cond */ 1269 int condexit; 1270 FuncState *fs = ls->fs; 1271 int repeat_init = luaK_getlabel(fs); 1272 BlockCnt bl1, bl2; 1273 enterblock(fs, &bl1, 1); /* loop block */ 1274 enterblock(fs, &bl2, 0); /* scope block */ 1275 luaX_next(ls); /* skip REPEAT */ 1276 statlist(ls); 1277 check_match(ls, TK_UNTIL, TK_REPEAT, line); 1278 condexit = cond(ls); /* read condition (inside scope block) */ 1279 if (bl2.upval) /* upvalues? */ 1280 luaK_patchclose(fs, condexit, bl2.nactvar); 1281 leaveblock(fs); /* finish scope */ 1282 luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ 1283 leaveblock(fs); /* finish loop */ 1284 } 1285 1286 1287 static int exp1 (LexState *ls) { 1288 expdesc e; 1289 int reg; 1290 expr(ls, &e); 1291 luaK_exp2nextreg(ls->fs, &e); 1292 lua_assert(e.k == VNONRELOC); 1293 reg = e.u.info; 1294 return reg; 1295 } 1296 1297 1298 static void forbody (LexState *ls, int base, int line, int nvars, int isnum) { 1299 /* forbody -> DO block */ 1300 BlockCnt bl; 1301 FuncState *fs = ls->fs; 1302 int prep, endfor; 1303 adjustlocalvars(ls, 3); /* control variables */ 1304 checknext(ls, TK_DO); 1305 prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs); 1306 enterblock(fs, &bl, 0); /* scope for declared variables */ 1307 adjustlocalvars(ls, nvars); 1308 luaK_reserveregs(fs, nvars); 1309 block(ls); 1310 leaveblock(fs); /* end of scope for declared variables */ 1311 luaK_patchtohere(fs, prep); 1312 if (isnum) /* numeric for? */ 1313 endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP); 1314 else { /* generic for */ 1315 luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars); 1316 luaK_fixline(fs, line); 1317 endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP); 1318 } 1319 luaK_patchlist(fs, endfor, prep + 1); 1320 luaK_fixline(fs, line); 1321 } 1322 1323 1324 static void fornum (LexState *ls, TString *varname, int line) { 1325 /* fornum -> NAME = exp1,exp1[,exp1] forbody */ 1326 FuncState *fs = ls->fs; 1327 int base = fs->freereg; 1328 new_localvarliteral(ls, "(for index)"); 1329 new_localvarliteral(ls, "(for limit)"); 1330 new_localvarliteral(ls, "(for step)"); 1331 new_localvar(ls, varname); 1332 checknext(ls, '='); 1333 exp1(ls); /* initial value */ 1334 checknext(ls, ','); 1335 exp1(ls); /* limit */ 1336 if (testnext(ls, ',')) 1337 exp1(ls); /* optional step */ 1338 else { /* default step = 1 */ 1339 luaK_codek(fs, fs->freereg, luaK_intK(fs, 1)); 1340 luaK_reserveregs(fs, 1); 1341 } 1342 forbody(ls, base, line, 1, 1); 1343 } 1344 1345 1346 static void forlist (LexState *ls, TString *indexname) { 1347 /* forlist -> NAME {,NAME} IN explist forbody */ 1348 FuncState *fs = ls->fs; 1349 expdesc e; 1350 int nvars = 4; /* gen, state, control, plus at least one declared var */ 1351 int line; 1352 int base = fs->freereg; 1353 /* create control variables */ 1354 new_localvarliteral(ls, "(for generator)"); 1355 new_localvarliteral(ls, "(for state)"); 1356 new_localvarliteral(ls, "(for control)"); 1357 /* create declared variables */ 1358 new_localvar(ls, indexname); 1359 while (testnext(ls, ',')) { 1360 new_localvar(ls, str_checkname(ls)); 1361 nvars++; 1362 } 1363 checknext(ls, TK_IN); 1364 line = ls->linenumber; 1365 adjust_assign(ls, 3, explist(ls, &e), &e); 1366 luaK_checkstack(fs, 3); /* extra space to call generator */ 1367 forbody(ls, base, line, nvars - 3, 0); 1368 } 1369 1370 1371 static void forstat (LexState *ls, int line) { 1372 /* forstat -> FOR (fornum | forlist) END */ 1373 FuncState *fs = ls->fs; 1374 TString *varname; 1375 BlockCnt bl; 1376 enterblock(fs, &bl, 1); /* scope for loop and control variables */ 1377 luaX_next(ls); /* skip 'for' */ 1378 varname = str_checkname(ls); /* first variable name */ 1379 switch (ls->t.token) { 1380 case '=': fornum(ls, varname, line); break; 1381 case ',': case TK_IN: forlist(ls, varname); break; 1382 default: luaX_syntaxerror(ls, "'=' or 'in' expected"); 1383 } 1384 check_match(ls, TK_END, TK_FOR, line); 1385 leaveblock(fs); /* loop scope ('break' jumps to this point) */ 1386 } 1387 1388 1389 static void test_then_block (LexState *ls, int *escapelist) { 1390 /* test_then_block -> [IF | ELSEIF] cond THEN block */ 1391 BlockCnt bl; 1392 FuncState *fs = ls->fs; 1393 expdesc v; 1394 int jf; /* instruction to skip 'then' code (if condition is false) */ 1395 luaX_next(ls); /* skip IF or ELSEIF */ 1396 expr(ls, &v); /* read condition */ 1397 checknext(ls, TK_THEN); 1398 if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) { 1399 luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */ 1400 enterblock(fs, &bl, 0); /* must enter block before 'goto' */ 1401 gotostat(ls, v.t); /* handle goto/break */ 1402 skipnoopstat(ls); /* skip other no-op statements */ 1403 if (block_follow(ls, 0)) { /* 'goto' is the entire block? */ 1404 leaveblock(fs); 1405 return; /* and that is it */ 1406 } 1407 else /* must skip over 'then' part if condition is false */ 1408 jf = luaK_jump(fs); 1409 } 1410 else { /* regular case (not goto/break) */ 1411 luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */ 1412 enterblock(fs, &bl, 0); 1413 jf = v.f; 1414 } 1415 statlist(ls); /* 'then' part */ 1416 leaveblock(fs); 1417 if (ls->t.token == TK_ELSE || 1418 ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ 1419 luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */ 1420 luaK_patchtohere(fs, jf); 1421 } 1422 1423 1424 static void ifstat (LexState *ls, int line) { 1425 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ 1426 FuncState *fs = ls->fs; 1427 int escapelist = NO_JUMP; /* exit list for finished parts */ 1428 test_then_block(ls, &escapelist); /* IF cond THEN block */ 1429 while (ls->t.token == TK_ELSEIF) 1430 test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ 1431 if (testnext(ls, TK_ELSE)) 1432 block(ls); /* 'else' part */ 1433 check_match(ls, TK_END, TK_IF, line); 1434 luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ 1435 } 1436 1437 1438 static void localfunc (LexState *ls) { 1439 expdesc b; 1440 FuncState *fs = ls->fs; 1441 new_localvar(ls, str_checkname(ls)); /* new local variable */ 1442 adjustlocalvars(ls, 1); /* enter its scope */ 1443 body(ls, &b, 0, ls->linenumber); /* function created in next register */ 1444 /* debug information will only see the variable after this point! */ 1445 getlocvar(fs, b.u.info)->startpc = fs->pc; 1446 } 1447 1448 1449 static void localstat (LexState *ls) { 1450 /* stat -> LOCAL NAME {',' NAME} ['=' explist] */ 1451 int nvars = 0; 1452 int nexps; 1453 expdesc e; 1454 do { 1455 new_localvar(ls, str_checkname(ls)); 1456 nvars++; 1457 } while (testnext(ls, ',')); 1458 if (testnext(ls, '=')) 1459 nexps = explist(ls, &e); 1460 else { 1461 e.k = VVOID; 1462 nexps = 0; 1463 } 1464 adjust_assign(ls, nvars, nexps, &e); 1465 adjustlocalvars(ls, nvars); 1466 } 1467 1468 1469 static int funcname (LexState *ls, expdesc *v) { 1470 /* funcname -> NAME {fieldsel} [':' NAME] */ 1471 int ismethod = 0; 1472 singlevar(ls, v); 1473 while (ls->t.token == '.') 1474 fieldsel(ls, v); 1475 if (ls->t.token == ':') { 1476 ismethod = 1; 1477 fieldsel(ls, v); 1478 } 1479 return ismethod; 1480 } 1481 1482 1483 static void funcstat (LexState *ls, int line) { 1484 /* funcstat -> FUNCTION funcname body */ 1485 int ismethod; 1486 expdesc v, b; 1487 luaX_next(ls); /* skip FUNCTION */ 1488 ismethod = funcname(ls, &v); 1489 body(ls, &b, ismethod, line); 1490 luaK_storevar(ls->fs, &v, &b); 1491 luaK_fixline(ls->fs, line); /* definition "happens" in the first line */ 1492 } 1493 1494 1495 static void exprstat (LexState *ls) { 1496 /* stat -> func | assignment */ 1497 FuncState *fs = ls->fs; 1498 struct LHS_assign v; 1499 suffixedexp(ls, &v.v); 1500 if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */ 1501 v.prev = NULL; 1502 assignment(ls, &v, 1); 1503 } 1504 else { /* stat -> func */ 1505 check_condition(ls, v.v.k == VCALL, "syntax error"); 1506 SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */ 1507 } 1508 } 1509 1510 1511 static void retstat (LexState *ls) { 1512 /* stat -> RETURN [explist] [';'] */ 1513 FuncState *fs = ls->fs; 1514 expdesc e; 1515 int first, nret; /* registers with returned values */ 1516 if (block_follow(ls, 1) || ls->t.token == ';') 1517 first = nret = 0; /* return no values */ 1518 else { 1519 nret = explist(ls, &e); /* optional return values */ 1520 if (hasmultret(e.k)) { 1521 luaK_setmultret(fs, &e); 1522 if (e.k == VCALL && nret == 1) { /* tail call? */ 1523 SET_OPCODE(getcode(fs,&e), OP_TAILCALL); 1524 lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar); 1525 } 1526 first = fs->nactvar; 1527 nret = LUA_MULTRET; /* return all values */ 1528 } 1529 else { 1530 if (nret == 1) /* only one single value? */ 1531 first = luaK_exp2anyreg(fs, &e); 1532 else { 1533 luaK_exp2nextreg(fs, &e); /* values must go to the stack */ 1534 first = fs->nactvar; /* return all active values */ 1535 lua_assert(nret == fs->freereg - first); 1536 } 1537 } 1538 } 1539 luaK_ret(fs, first, nret); 1540 testnext(ls, ';'); /* skip optional semicolon */ 1541 } 1542 1543 1544 static void statement (LexState *ls) { 1545 int line = ls->linenumber; /* may be needed for error messages */ 1546 enterlevel(ls); 1547 switch (ls->t.token) { 1548 case ';': { /* stat -> ';' (empty statement) */ 1549 luaX_next(ls); /* skip ';' */ 1550 break; 1551 } 1552 case TK_IF: { /* stat -> ifstat */ 1553 ifstat(ls, line); 1554 break; 1555 } 1556 case TK_WHILE: { /* stat -> whilestat */ 1557 whilestat(ls, line); 1558 break; 1559 } 1560 case TK_DO: { /* stat -> DO block END */ 1561 luaX_next(ls); /* skip DO */ 1562 block(ls); 1563 check_match(ls, TK_END, TK_DO, line); 1564 break; 1565 } 1566 case TK_FOR: { /* stat -> forstat */ 1567 forstat(ls, line); 1568 break; 1569 } 1570 case TK_REPEAT: { /* stat -> repeatstat */ 1571 repeatstat(ls, line); 1572 break; 1573 } 1574 case TK_FUNCTION: { /* stat -> funcstat */ 1575 funcstat(ls, line); 1576 break; 1577 } 1578 case TK_LOCAL: { /* stat -> localstat */ 1579 luaX_next(ls); /* skip LOCAL */ 1580 if (testnext(ls, TK_FUNCTION)) /* local function? */ 1581 localfunc(ls); 1582 else 1583 localstat(ls); 1584 break; 1585 } 1586 case TK_DBCOLON: { /* stat -> label */ 1587 luaX_next(ls); /* skip double colon */ 1588 labelstat(ls, str_checkname(ls), line); 1589 break; 1590 } 1591 case TK_RETURN: { /* stat -> retstat */ 1592 luaX_next(ls); /* skip RETURN */ 1593 retstat(ls); 1594 break; 1595 } 1596 case TK_BREAK: /* stat -> breakstat */ 1597 case TK_GOTO: { /* stat -> 'goto' NAME */ 1598 gotostat(ls, luaK_jump(ls->fs)); 1599 break; 1600 } 1601 default: { /* stat -> func | assignment */ 1602 exprstat(ls); 1603 break; 1604 } 1605 } 1606 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && 1607 ls->fs->freereg >= ls->fs->nactvar); 1608 ls->fs->freereg = ls->fs->nactvar; /* free registers */ 1609 leavelevel(ls); 1610 } 1611 1612 /* }====================================================================== */ 1613 1614 1615 /* 1616 ** compiles the main function, which is a regular vararg function with an 1617 ** upvalue named LUA_ENV 1618 */ 1619 static void mainfunc (LexState *ls, FuncState *fs) { 1620 BlockCnt bl; 1621 expdesc v; 1622 open_func(ls, fs, &bl); 1623 fs->f->is_vararg = 1; /* main function is always vararg */ 1624 init_exp(&v, VLOCAL, 0); /* create and... */ 1625 newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */ 1626 luaX_next(ls); /* read first token */ 1627 statlist(ls); /* parse main body */ 1628 check(ls, TK_EOS); 1629 close_func(ls); 1630 } 1631 1632 1633 LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, 1634 Dyndata *dyd, const char *name, int firstchar) { 1635 LexState lexstate; 1636 FuncState funcstate; 1637 LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */ 1638 setclLvalue(L, L->top, cl); /* anchor it (to avoid being collected) */ 1639 incr_top(L); 1640 lexstate.h = luaH_new(L); /* create table for scanner */ 1641 sethvalue(L, L->top, lexstate.h); /* anchor it */ 1642 incr_top(L); 1643 funcstate.f = cl->p = luaF_newproto(L); 1644 funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ 1645 lua_assert(iswhite(funcstate.f)); /* do not need barrier here */ 1646 lexstate.buff = buff; 1647 lexstate.dyd = dyd; 1648 dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; 1649 luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); 1650 mainfunc(&lexstate, &funcstate); 1651 lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); 1652 /* all scopes should be correctly finished */ 1653 lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); 1654 L->top--; /* remove scanner's table */ 1655 return cl; /* closure is on the stack, too */ 1656 } 1657 1658