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