Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/lua/blob/master/lparser.c # lua [Ported from github.com/lua/lua] Cast in 'rl_readline_name' Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `lua / lparser.c` 2193 lines ยท 65674 bytes Raw Blame History 1 /* 2 ** $Id: lparser.c $ 3 ** Lua Parser 4 ** See Copyright Notice in lua.h 5 */ 6 7 #define lparser_c 8 #define LUA_CORE 9 10 #include "lprefix.h" 11 12 13 #include 14 #include 15 16 #include "lua.h" 17 18 #include "lcode.h" 19 #include "ldebug.h" 20 #include "ldo.h" 21 #include "lfunc.h" 22 #include "llex.h" 23 #include "lmem.h" 24 #include "lobject.h" 25 #include "lopcodes.h" 26 #include "lparser.h" 27 #include "lstate.h" 28 #include "lstring.h" 29 #include "ltable.h" 30 31 32 33 /* maximum number of variable declarations per function (must be 34 smaller than 250, due to the bytecode format) */ 35 #define MAXVARS 200 36 37 38 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG) 39 40 41 /* because all strings are unified by the scanner, the parser 42 can use pointer equality for string equality */ 43 #define eqstr(a,b) ((a) == (b)) 44 45 46 /* 47 ** nodes for block list (list of active blocks) 48 */ 49 typedef struct BlockCnt { 50 struct BlockCnt *previous; /* chain */ 51 int firstlabel; /* index of first label in this block */ 52 int firstgoto; /* index of first pending goto in this block */ 53 short nactvar; /* number of active declarations at block entry */ 54 lu_byte upval; /* true if some variable in the block is an upvalue */ 55 lu_byte isloop; /* 1 if 'block' is a loop; 2 if it has pending breaks */ 56 lu_byte insidetbc; /* true if inside the scope of a to-be-closed var. */ 57 } BlockCnt; 58 59 60 61 /* 62 ** prototypes for recursive non-terminal functions 63 */ 64 static void statement (LexState *ls); 65 static void expr (LexState *ls, expdesc *v); 66 67 68 static l_noret error_expected (LexState *ls, int token) { 69 luaX_syntaxerror(ls, 70 luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); 71 } 72 73 74 static l_noret errorlimit (FuncState *fs, int limit, const char *what) { 75 lua_State *L = fs->ls->L; 76 const char *msg; 77 int line = fs->f->linedefined; 78 const char *where = (line == 0) 79 ? "main function" 80 : luaO_pushfstring(L, "function at line %d", line); 81 msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s", 82 what, limit, where); 83 luaX_syntaxerror(fs->ls, msg); 84 } 85 86 87 void luaY_checklimit (FuncState *fs, int v, int l, const char *what) { 88 if (l_unlikely(v > l)) errorlimit(fs, l, what); 89 } 90 91 92 /* 93 ** Test whether next token is 'c'; if so, skip it. 94 */ 95 static int testnext (LexState *ls, int c) { 96 if (ls->t.token == c) { 97 luaX_next(ls); 98 return 1; 99 } 100 else return 0; 101 } 102 103 104 /* 105 ** Check that next token is 'c'. 106 */ 107 static void check (LexState *ls, int c) { 108 if (ls->t.token != c) 109 error_expected(ls, c); 110 } 111 112 113 /* 114 ** Check that next token is 'c' and skip it. 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 ** Check that next token is 'what' and skip it. In case of error, 127 ** raise an error that the expected 'what' should match a 'who' 128 ** in line 'where' (if that is not the current line). 129 */ 130 static void check_match (LexState *ls, int what, int who, int where) { 131 if (l_unlikely(!testnext(ls, what))) { 132 if (where == ls->linenumber) /* all in the same line? */ 133 error_expected(ls, what); /* do not need a complex message */ 134 else { 135 luaX_syntaxerror(ls, luaO_pushfstring(ls->L, 136 "%s expected (to close %s at line %d)", 137 luaX_token2str(ls, what), luaX_token2str(ls, who), where)); 138 } 139 } 140 } 141 142 143 static TString *str_checkname (LexState *ls) { 144 TString *ts; 145 check(ls, TK_NAME); 146 ts = ls->t.seminfo.ts; 147 luaX_next(ls); 148 return ts; 149 } 150 151 152 static void init_exp (expdesc *e, expkind k, int i) { 153 e->f = e->t = NO_JUMP; 154 e->k = k; 155 e->u.info = i; 156 } 157 158 159 static void codestring (expdesc *e, TString *s) { 160 e->f = e->t = NO_JUMP; 161 e->k = VKSTR; 162 e->u.strval = s; 163 } 164 165 166 static void codename (LexState *ls, expdesc *e) { 167 codestring(e, str_checkname(ls)); 168 } 169 170 171 /* 172 ** Register a new local variable in the active 'Proto' (for debug 173 ** information). 174 */ 175 static short registerlocalvar (LexState *ls, FuncState *fs, 176 TString *varname) { 177 Proto *f = fs->f; 178 int oldsize = f->sizelocvars; 179 luaM_growvector(ls->L, f->locvars, fs->ndebugvars, f->sizelocvars, 180 LocVar, SHRT_MAX, "local variables"); 181 while (oldsize < f->sizelocvars) 182 f->locvars[oldsize++].varname = NULL; 183 f->locvars[fs->ndebugvars].varname = varname; 184 f->locvars[fs->ndebugvars].startpc = fs->pc; 185 luaC_objbarrier(ls->L, f, varname); 186 return fs->ndebugvars++; 187 } 188 189 190 /* 191 ** Create a new variable with the given 'name' and given 'kind'. 192 ** Return its index in the function. 193 */ 194 static int new_varkind (LexState *ls, TString *name, lu_byte kind) { 195 lua_State *L = ls->L; 196 FuncState *fs = ls->fs; 197 Dyndata *dyd = ls->dyd; 198 Vardesc *var; 199 luaM_growvector(L, dyd->actvar.arr, dyd->actvar.n + 1, 200 dyd->actvar.size, Vardesc, SHRT_MAX, "variable declarations"); 201 var = &dyd->actvar.arr[dyd->actvar.n++]; 202 var->vd.kind = kind; /* default */ 203 var->vd.name = name; 204 return dyd->actvar.n - 1 - fs->firstlocal; 205 } 206 207 208 /* 209 ** Create a new local variable with the given 'name' and regular kind. 210 */ 211 static int new_localvar (LexState *ls, TString *name) { 212 return new_varkind(ls, name, VDKREG); 213 } 214 215 #define new_localvarliteral(ls,v) \ 216 new_localvar(ls, \ 217 luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1)); 218 219 220 221 /* 222 ** Return the "variable description" (Vardesc) of a given variable. 223 ** (Unless noted otherwise, all variables are referred to by their 224 ** compiler indices.) 225 */ 226 static Vardesc *getlocalvardesc (FuncState *fs, int vidx) { 227 return &fs->ls->dyd->actvar.arr[fs->firstlocal + vidx]; 228 } 229 230 231 /* 232 ** Convert 'nvar', a compiler index level, to its corresponding 233 ** register. For that, search for the highest variable below that level 234 ** that is in a register and uses its register index ('ridx') plus one. 235 */ 236 static lu_byte reglevel (FuncState *fs, int nvar) { 237 while (nvar-- > 0) { 238 Vardesc *vd = getlocalvardesc(fs, nvar); /* get previous variable */ 239 if (varinreg(vd)) /* is in a register? */ 240 return cast_byte(vd->vd.ridx + 1); 241 } 242 return 0; /* no variables in registers */ 243 } 244 245 246 /* 247 ** Return the number of variables in the register stack for the given 248 ** function. 249 */ 250 lu_byte luaY_nvarstack (FuncState *fs) { 251 return reglevel(fs, fs->nactvar); 252 } 253 254 255 /* 256 ** Get the debug-information entry for current variable 'vidx'. 257 */ 258 static LocVar *localdebuginfo (FuncState *fs, int vidx) { 259 Vardesc *vd = getlocalvardesc(fs, vidx); 260 if (!varinreg(vd)) 261 return NULL; /* no debug info. for constants */ 262 else { 263 int idx = vd->vd.pidx; 264 lua_assert(idx < fs->ndebugvars); 265 return &fs->f->locvars[idx]; 266 } 267 } 268 269 270 /* 271 ** Create an expression representing variable 'vidx' 272 */ 273 static void init_var (FuncState *fs, expdesc *e, int vidx) { 274 e->f = e->t = NO_JUMP; 275 e->k = VLOCAL; 276 e->u.var.vidx = cast_short(vidx); 277 e->u.var.ridx = getlocalvardesc(fs, vidx)->vd.ridx; 278 } 279 280 281 /* 282 ** Raises an error if variable described by 'e' is read only; moreover, 283 ** if 'e' is t[exp] where t is the vararg parameter, change it to index 284 ** a real table. (Virtual vararg tables cannot be changed.) 285 */ 286 static void check_readonly (LexState *ls, expdesc *e) { 287 FuncState *fs = ls->fs; 288 TString *varname = NULL; /* to be set if variable is const */ 289 switch (e->k) { 290 case VCONST: { 291 varname = ls->dyd->actvar.arr[e->u.info].vd.name; 292 break; 293 } 294 case VLOCAL: case VVARGVAR: { 295 Vardesc *vardesc = getlocalvardesc(fs, e->u.var.vidx); 296 if (vardesc->vd.kind != VDKREG) /* not a regular variable? */ 297 varname = vardesc->vd.name; 298 break; 299 } 300 case VUPVAL: { 301 Upvaldesc *up = &fs->f->upvalues[e->u.info]; 302 if (up->kind != VDKREG) 303 varname = up->name; 304 break; 305 } 306 case VVARGIND: { 307 needvatab(fs->f); /* function will need a vararg table */ 308 e->k = VINDEXED; 309 } /* FALLTHROUGH */ 310 case VINDEXUP: case VINDEXSTR: case VINDEXED: { /* global variable */ 311 if (e->u.ind.ro) /* read-only? */ 312 varname = tsvalue(&fs->f->k[e->u.ind.keystr]); 313 break; 314 } 315 default: 316 lua_assert(e->k == VINDEXI); /* this one doesn't need any check */ 317 return; /* integer index cannot be read-only */ 318 } 319 if (varname) 320 luaK_semerror(ls, "attempt to assign to const variable '%s'", 321 getstr(varname)); 322 } 323 324 325 /* 326 ** Start the scope for the last 'nvars' created variables. 327 */ 328 static void adjustlocalvars (LexState *ls, int nvars) { 329 FuncState *fs = ls->fs; 330 int reglevel = luaY_nvarstack(fs); 331 int i; 332 for (i = 0; i < nvars; i++) { 333 int vidx = fs->nactvar++; 334 Vardesc *var = getlocalvardesc(fs, vidx); 335 var->vd.ridx = cast_byte(reglevel++); 336 var->vd.pidx = registerlocalvar(ls, fs, var->vd.name); 337 luaY_checklimit(fs, reglevel, MAXVARS, "local variables"); 338 } 339 } 340 341 342 /* 343 ** Close the scope for all variables up to level 'tolevel'. 344 ** (debug info.) 345 */ 346 static void removevars (FuncState *fs, int tolevel) { 347 fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel); 348 while (fs->nactvar > tolevel) { 349 LocVar *var = localdebuginfo(fs, --fs->nactvar); 350 if (var) /* does it have debug information? */ 351 var->endpc = fs->pc; 352 } 353 } 354 355 356 /* 357 ** Search the upvalues of the function 'fs' for one 358 ** with the given 'name'. 359 */ 360 static int searchupvalue (FuncState *fs, TString *name) { 361 int i; 362 Upvaldesc *up = fs->f->upvalues; 363 for (i = 0; i < fs->nups; i++) { 364 if (eqstr(up[i].name, name)) return i; 365 } 366 return -1; /* not found */ 367 } 368 369 370 static Upvaldesc *allocupvalue (FuncState *fs) { 371 Proto *f = fs->f; 372 int oldsize = f->sizeupvalues; 373 luaY_checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); 374 luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues, 375 Upvaldesc, MAXUPVAL, "upvalues"); 376 while (oldsize < f->sizeupvalues) 377 f->upvalues[oldsize++].name = NULL; 378 return &f->upvalues[fs->nups++]; 379 } 380 381 382 static int newupvalue (FuncState *fs, TString *name, expdesc *v) { 383 Upvaldesc *up = allocupvalue(fs); 384 FuncState *prev = fs->prev; 385 if (v->k == VLOCAL) { 386 up->instack = 1; 387 up->idx = v->u.var.ridx; 388 up->kind = getlocalvardesc(prev, v->u.var.vidx)->vd.kind; 389 lua_assert(eqstr(name, getlocalvardesc(prev, v->u.var.vidx)->vd.name)); 390 } 391 else { 392 up->instack = 0; 393 up->idx = cast_byte(v->u.info); 394 up->kind = prev->f->upvalues[v->u.info].kind; 395 lua_assert(eqstr(name, prev->f->upvalues[v->u.info].name)); 396 } 397 up->name = name; 398 luaC_objbarrier(fs->ls->L, fs->f, name); 399 return fs->nups - 1; 400 } 401 402 403 /* 404 ** Look for an active variable with the name 'n' in the 405 ** function 'fs'. If found, initialize 'var' with it and return 406 ** its expression kind; otherwise return -1. While searching, 407 ** var->u.info==-1 means that the preambular global declaration is 408 ** active (the default while there is no other global declaration); 409 ** var->u.info==-2 means there is no active collective declaration 410 ** (some previous global declaration but no collective declaration); 411 ** and var->u.info>=0 points to the inner-most (the first one found) 412 ** collective declaration, if there is one. 413 */ 414 static int searchvar (FuncState *fs, TString *n, expdesc *var) { 415 int i; 416 for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) { 417 Vardesc *vd = getlocalvardesc(fs, i); 418 if (varglobal(vd)) { /* global declaration? */ 419 if (vd->vd.name == NULL) { /* collective declaration? */ 420 if (var->u.info < 0) /* no previous collective declaration? */ 421 var->u.info = fs->firstlocal + i; /* this is the first one */ 422 } 423 else { /* global name */ 424 if (eqstr(n, vd->vd.name)) { /* found? */ 425 init_exp(var, VGLOBAL, fs->firstlocal + i); 426 return VGLOBAL; 427 } 428 else if (var->u.info == -1) /* active preambular declaration? */ 429 var->u.info = -2; /* invalidate preambular declaration */ 430 } 431 } 432 else if (eqstr(n, vd->vd.name)) { /* found? */ 433 if (vd->vd.kind == RDKCTC) /* compile-time constant? */ 434 init_exp(var, VCONST, fs->firstlocal + i); 435 else { /* local variable */ 436 init_var(fs, var, i); 437 if (vd->vd.kind == RDKVAVAR) /* vararg parameter? */ 438 var->k = VVARGVAR; 439 } 440 return cast_int(var->k); 441 } 442 } 443 return -1; /* not found */ 444 } 445 446 447 /* 448 ** Mark block where variable at given level was defined 449 ** (to emit close instructions later). 450 */ 451 static void markupval (FuncState *fs, int level) { 452 BlockCnt *bl = fs->bl; 453 while (bl->nactvar > level) 454 bl = bl->previous; 455 bl->upval = 1; 456 fs->needclose = 1; 457 } 458 459 460 /* 461 ** Mark that current block has a to-be-closed variable. 462 */ 463 static void marktobeclosed (FuncState *fs) { 464 BlockCnt *bl = fs->bl; 465 bl->upval = 1; 466 bl->insidetbc = 1; 467 fs->needclose = 1; 468 } 469 470 471 /* 472 ** Find a variable with the given name 'n'. If it is an upvalue, add 473 ** this upvalue into all intermediate functions. If it is a global, set 474 ** 'var' as 'void' as a flag. 475 */ 476 static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { 477 int v = searchvar(fs, n, var); /* look up variables at current level */ 478 if (v >= 0) { /* found? */ 479 if (!base) { 480 if (var->k == VVARGVAR) /* vararg parameter? */ 481 luaK_vapar2local(fs, var); /* change it to a regular local */ 482 if (var->k == VLOCAL) 483 markupval(fs, var->u.var.vidx); /* will be used as an upvalue */ 484 } 485 /* else nothing else to be done */ 486 } 487 else { /* not found at current level; try upvalues */ 488 int idx = searchupvalue(fs, n); /* try existing upvalues */ 489 if (idx < 0) { /* not found? */ 490 if (fs->prev != NULL) /* more levels? */ 491 singlevaraux(fs->prev, n, var, 0); /* try upper levels */ 492 if (var->k == VLOCAL || var->k == VUPVAL) /* local or upvalue? */ 493 idx = newupvalue(fs, n, var); /* will be a new upvalue */ 494 else /* it is a global or a constant */ 495 return; /* don't need to do anything at this level */ 496 } 497 init_exp(var, VUPVAL, idx); /* new or old upvalue */ 498 } 499 } 500 501 502 static void buildglobal (LexState *ls, TString *varname, expdesc *var) { 503 FuncState *fs = ls->fs; 504 expdesc key; 505 init_exp(var, VGLOBAL, -1); /* global by default */ 506 singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ 507 if (var->k == VGLOBAL) 508 luaK_semerror(ls, "%s is global when accessing variable '%s'", 509 LUA_ENV, getstr(varname)); 510 luaK_exp2anyregup(fs, var); /* _ENV could be a constant */ 511 codestring(&key, varname); /* key is variable name */ 512 luaK_indexed(fs, var, &key); /* 'var' represents _ENV[varname] */ 513 } 514 515 516 /* 517 ** Find a variable with the given name 'n', handling global variables 518 ** too. 519 */ 520 static void buildvar (LexState *ls, TString *varname, expdesc *var) { 521 FuncState *fs = ls->fs; 522 init_exp(var, VGLOBAL, -1); /* global by default */ 523 singlevaraux(fs, varname, var, 1); 524 if (var->k == VGLOBAL) { /* global name? */ 525 int info = var->u.info; 526 /* global by default in the scope of a global declaration? */ 527 if (info == -2) 528 luaK_semerror(ls, "variable '%s' not declared", getstr(varname)); 529 buildglobal(ls, varname, var); 530 if (info != -1 && ls->dyd->actvar.arr[info].vd.kind == GDKCONST) 531 var->u.ind.ro = 1; /* mark variable as read-only */ 532 else /* anyway must be a global */ 533 lua_assert(info == -1 || ls->dyd->actvar.arr[info].vd.kind == GDKREG); 534 } 535 } 536 537 538 static void singlevar (LexState *ls, expdesc *var) { 539 buildvar(ls, str_checkname(ls), var); 540 } 541 542 543 /* 544 ** Adjust the number of results from an expression list 'e' with 'nexps' 545 ** expressions to 'nvars' values. 546 */ 547 static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { 548 FuncState *fs = ls->fs; 549 int needed = nvars - nexps; /* extra values needed */ 550 luaK_checkstack(fs, needed); 551 if (hasmultret(e->k)) { /* last expression has multiple returns? */ 552 int extra = needed + 1; /* discount last expression itself */ 553 if (extra < 0) 554 extra = 0; 555 luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ 556 } 557 else { 558 if (e->k != VVOID) /* at least one expression? */ 559 luaK_exp2nextreg(fs, e); /* close last expression */ 560 if (needed > 0) /* missing values? */ 561 luaK_nil(fs, fs->freereg, needed); /* complete with nils */ 562 } 563 if (needed > 0) 564 luaK_reserveregs(fs, needed); /* registers for extra values */ 565 else /* adding 'needed' is actually a subtraction */ 566 fs->freereg = cast_byte(fs->freereg + needed); /* remove extra values */ 567 } 568 569 570 #define enterlevel(ls) luaE_incCstack(ls->L) 571 572 573 #define leavelevel(ls) ((ls)->L->nCcalls--) 574 575 576 /* 577 ** Generates an error that a goto jumps into the scope of some 578 ** variable declaration. 579 */ 580 static l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) { 581 TString *tsname = getlocalvardesc(ls->fs, gt->nactvar)->vd.name; 582 const char *varname = (tsname != NULL) ? getstr(tsname) : "*"; 583 luaK_semerror(ls, 584 " at line %d jumps into the scope of '%s'", 585 getstr(gt->name), gt->line, varname); /* raise the error */ 586 } 587 588 589 /* 590 ** Closes the goto at index 'g' to given 'label' and removes it 591 ** from the list of pending gotos. 592 ** If it jumps into the scope of some variable, raises an error. 593 ** The goto needs a CLOSE if it jumps out of a block with upvalues, 594 ** or out of the scope of some variable and the block has upvalues 595 ** (signaled by parameter 'bup'). 596 */ 597 static void closegoto (LexState *ls, int g, Labeldesc *label, int bup) { 598 int i; 599 FuncState *fs = ls->fs; 600 Labellist *gl = &ls->dyd->gt; /* list of gotos */ 601 Labeldesc *gt = &gl->arr[g]; /* goto to be resolved */ 602 lua_assert(eqstr(gt->name, label->name)); 603 if (l_unlikely(gt->nactvar < label->nactvar)) /* enter some scope? */ 604 jumpscopeerror(ls, gt); 605 if (gt->close || 606 (label->nactvar < gt->nactvar && bup)) { /* needs close? */ 607 lu_byte stklevel = reglevel(fs, label->nactvar); 608 /* move jump to CLOSE position */ 609 fs->f->code[gt->pc + 1] = fs->f->code[gt->pc]; 610 /* put CLOSE instruction at original position */ 611 fs->f->code[gt->pc] = CREATE_ABCk(OP_CLOSE, stklevel, 0, 0, 0); 612 gt->pc++; /* must point to jump instruction */ 613 } 614 luaK_patchlist(ls->fs, gt->pc, label->pc); /* goto jumps to label */ 615 for (i = g; i < gl->n - 1; i++) /* remove goto from pending list */ 616 gl->arr[i] = gl->arr[i + 1]; 617 gl->n--; 618 } 619 620 621 /* 622 ** Search for an active label with the given name, starting at 623 ** index 'ilb' (so that it can search for all labels in current block 624 ** or all labels in current function). 625 */ 626 static Labeldesc *findlabel (LexState *ls, TString *name, int ilb) { 627 Dyndata *dyd = ls->dyd; 628 for (; ilb < dyd->label.n; ilb++) { 629 Labeldesc *lb = &dyd->label.arr[ilb]; 630 if (eqstr(lb->name, name)) /* correct label? */ 631 return lb; 632 } 633 return NULL; /* label not found */ 634 } 635 636 637 /* 638 ** Adds a new label/goto in the corresponding list. 639 */ 640 static int newlabelentry (LexState *ls, Labellist *l, TString *name, 641 int line, int pc) { 642 int n = l->n; 643 luaM_growvector(ls->L, l->arr, n, l->size, 644 Labeldesc, SHRT_MAX, "labels/gotos"); 645 l->arr[n].name = name; 646 l->arr[n].line = line; 647 l->arr[n].nactvar = ls->fs->nactvar; 648 l->arr[n].close = 0; 649 l->arr[n].pc = pc; 650 l->n = n + 1; 651 return n; 652 } 653 654 655 /* 656 ** Create an entry for the goto and the code for it. As it is not known 657 ** at this point whether the goto may need a CLOSE, the code has a jump 658 ** followed by an CLOSE. (As the CLOSE comes after the jump, it is a 659 ** dead instruction; it works as a placeholder.) When the goto is closed 660 ** against a label, if it needs a CLOSE, the two instructions swap 661 ** positions, so that the CLOSE comes before the jump. 662 */ 663 static int newgotoentry (LexState *ls, TString *name, int line) { 664 FuncState *fs = ls->fs; 665 int pc = luaK_jump(fs); /* create jump */ 666 luaK_codeABC(fs, OP_CLOSE, 0, 1, 0); /* spaceholder, marked as dead */ 667 return newlabelentry(ls, &ls->dyd->gt, name, line, pc); 668 } 669 670 671 /* 672 ** Create a new label with the given 'name' at the given 'line'. 673 ** 'last' tells whether label is the last non-op statement in its 674 ** block. Solves all pending gotos to this new label and adds 675 ** a close instruction if necessary. 676 ** Returns true iff it added a close instruction. 677 */ 678 static void createlabel (LexState *ls, TString *name, int line, int last) { 679 FuncState *fs = ls->fs; 680 Labellist *ll = &ls->dyd->label; 681 int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs)); 682 if (last) { /* label is last no-op statement in the block? */ 683 /* assume that locals are already out of scope */ 684 ll->arr[l].nactvar = fs->bl->nactvar; 685 } 686 } 687 688 689 /* 690 ** Traverse the pending gotos of the finishing block checking whether 691 ** each match some label of that block. Those that do not match are 692 ** "exported" to the outer block, to be solved there. In particular, 693 ** its 'nactvar' is updated with the level of the inner block, 694 ** as the variables of the inner block are now out of scope. 695 */ 696 static void solvegotos (FuncState *fs, BlockCnt *bl) { 697 LexState *ls = fs->ls; 698 Labellist *gl = &ls->dyd->gt; 699 int outlevel = reglevel(fs, bl->nactvar); /* level outside the block */ 700 int igt = bl->firstgoto; /* first goto in the finishing block */ 701 while (igt < gl->n) { /* for each pending goto */ 702 Labeldesc *gt = &gl->arr[igt]; 703 /* search for a matching label in the current block */ 704 Labeldesc *lb = findlabel(ls, gt->name, bl->firstlabel); 705 if (lb != NULL) /* found a match? */ 706 closegoto(ls, igt, lb, bl->upval); /* close and remove goto */ 707 else { /* adjust 'goto' for outer block */ 708 /* block has variables to be closed and goto escapes the scope of 709 some variable? */ 710 if (bl->upval && reglevel(fs, gt->nactvar) > outlevel) 711 gt->close = 1; /* jump may need a close */ 712 gt->nactvar = bl->nactvar; /* correct level for outer block */ 713 igt++; /* go to next goto */ 714 } 715 } 716 ls->dyd->label.n = bl->firstlabel; /* remove local labels */ 717 } 718 719 720 static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) { 721 bl->isloop = isloop; 722 bl->nactvar = fs->nactvar; 723 bl->firstlabel = fs->ls->dyd->label.n; 724 bl->firstgoto = fs->ls->dyd->gt.n; 725 bl->upval = 0; 726 /* inherit 'insidetbc' from enclosing block */ 727 bl->insidetbc = (fs->bl != NULL && fs->bl->insidetbc); 728 bl->previous = fs->bl; /* link block in function's block list */ 729 fs->bl = bl; 730 lua_assert(fs->freereg == luaY_nvarstack(fs)); 731 } 732 733 734 /* 735 ** generates an error for an undefined 'goto'. 736 */ 737 static l_noret undefgoto (LexState *ls, Labeldesc *gt) { 738 /* breaks are checked when created, cannot be undefined */ 739 lua_assert(!eqstr(gt->name, ls->brkn)); 740 luaK_semerror(ls, "no visible label '%s' for at line %d", 741 getstr(gt->name), gt->line); 742 } 743 744 745 static void leaveblock (FuncState *fs) { 746 BlockCnt *bl = fs->bl; 747 LexState *ls = fs->ls; 748 lu_byte stklevel = reglevel(fs, bl->nactvar); /* level outside block */ 749 if (bl->previous && bl->upval) /* need a 'close'? */ 750 luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0); 751 fs->freereg = stklevel; /* free registers */ 752 removevars(fs, bl->nactvar); /* remove block locals */ 753 lua_assert(bl->nactvar == fs->nactvar); /* back to level on entry */ 754 if (bl->isloop == 2) /* has to fix pending breaks? */ 755 createlabel(ls, ls->brkn, 0, 0); 756 solvegotos(fs, bl); 757 if (bl->previous == NULL) { /* was it the last block? */ 758 if (bl->firstgoto < ls->dyd->gt.n) /* still pending gotos? */ 759 undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */ 760 } 761 fs->bl = bl->previous; /* current block now is previous one */ 762 } 763 764 765 /* 766 ** adds a new prototype into list of prototypes 767 */ 768 static Proto *addprototype (LexState *ls) { 769 Proto *clp; 770 lua_State *L = ls->L; 771 FuncState *fs = ls->fs; 772 Proto *f = fs->f; /* prototype of current function */ 773 if (fs->np >= f->sizep) { 774 int oldsize = f->sizep; 775 luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions"); 776 while (oldsize < f->sizep) 777 f->p[oldsize++] = NULL; 778 } 779 f->p[fs->np++] = clp = luaF_newproto(L); 780 luaC_objbarrier(L, f, clp); 781 return clp; 782 } 783 784 785 /* 786 ** codes instruction to create new closure in parent function. 787 ** The OP_CLOSURE instruction uses the last available register, 788 ** so that, if it invokes the GC, the GC knows which registers 789 ** are in use at that time. 790 791 */ 792 static void codeclosure (LexState *ls, expdesc *v) { 793 FuncState *fs = ls->fs->prev; 794 init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1)); 795 luaK_exp2nextreg(fs, v); /* fix it at the last register */ 796 } 797 798 799 static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) { 800 lua_State *L = ls->L; 801 Proto *f = fs->f; 802 fs->prev = ls->fs; /* linked list of funcstates */ 803 fs->ls = ls; 804 ls->fs = fs; 805 fs->pc = 0; 806 fs->previousline = f->linedefined; 807 fs->iwthabs = 0; 808 fs->lasttarget = 0; 809 fs->freereg = 0; 810 fs->nk = 0; 811 fs->nabslineinfo = 0; 812 fs->np = 0; 813 fs->nups = 0; 814 fs->ndebugvars = 0; 815 fs->nactvar = 0; 816 fs->needclose = 0; 817 fs->firstlocal = ls->dyd->actvar.n; 818 fs->firstlabel = ls->dyd->label.n; 819 fs->bl = NULL; 820 f->source = ls->source; 821 luaC_objbarrier(L, f, f->source); 822 f->maxstacksize = 2; /* registers 0/1 are always valid */ 823 fs->kcache = luaH_new(L); /* create table for function */ 824 luaD_anchorobj(L, ls->h, obj2gco(fs->kcache)); /* anchor it */ 825 enterblock(fs, bl, 0); 826 } 827 828 829 static void close_func (LexState *ls) { 830 lua_State *L = ls->L; 831 FuncState *fs = ls->fs; 832 Proto *f = fs->f; 833 TValue temp; 834 luaK_ret(fs, luaY_nvarstack(fs), 0); /* final return */ 835 leaveblock(fs); 836 lua_assert(fs->bl == NULL); 837 luaK_finish(fs); 838 luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction); 839 luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte); 840 luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo, 841 fs->nabslineinfo, AbsLineInfo); 842 luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue); 843 luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *); 844 luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar); 845 luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc); 846 /* remove kcache table from scanner table ("weigh" its anchor) */ 847 sethvalue(L, &temp, fs->kcache); /* key to be set to nil */ 848 luaH_set(L, ls->h, &temp, &G(L)->nilvalue); 849 ls->fs = fs->prev; 850 luaC_checkGC(L); 851 } 852 853 854 /* 855 ** {====================================================================== 856 ** GRAMMAR RULES 857 ** ======================================================================= 858 */ 859 860 861 /* 862 ** check whether current token is in the follow set of a block. 863 ** 'until' closes syntactical blocks, but do not close scope, 864 ** so it is handled in separate. 865 */ 866 static int block_follow (LexState *ls, int withuntil) { 867 switch (ls->t.token) { 868 case TK_ELSE: case TK_ELSEIF: 869 case TK_END: case TK_EOS: 870 return 1; 871 case TK_UNTIL: return withuntil; 872 default: return 0; 873 } 874 } 875 876 877 static void statlist (LexState *ls) { 878 /* statlist -> { stat [';'] } */ 879 while (!block_follow(ls, 1)) { 880 if (ls->t.token == TK_RETURN) { 881 statement(ls); 882 return; /* 'return' must be last statement */ 883 } 884 statement(ls); 885 } 886 } 887 888 889 static void fieldsel (LexState *ls, expdesc *v) { 890 /* fieldsel -> ['.' | ':'] NAME */ 891 FuncState *fs = ls->fs; 892 expdesc key; 893 luaK_exp2anyregup(fs, v); 894 luaX_next(ls); /* skip the dot or colon */ 895 codename(ls, &key); 896 luaK_indexed(fs, v, &key); 897 } 898 899 900 static void yindex (LexState *ls, expdesc *v) { 901 /* index -> '[' expr ']' */ 902 luaX_next(ls); /* skip the '[' */ 903 expr(ls, v); 904 luaK_exp2val(ls->fs, v); 905 checknext(ls, ']'); 906 } 907 908 909 /* 910 ** {====================================================================== 911 ** Rules for Constructors 912 ** ======================================================================= 913 */ 914 915 typedef struct ConsControl { 916 expdesc v; /* last list item read */ 917 expdesc *t; /* table descriptor */ 918 int nh; /* total number of 'record' elements */ 919 int na; /* number of array elements already stored */ 920 int tostore; /* number of array elements pending to be stored */ 921 int maxtostore; /* maximum number of pending elements */ 922 } ConsControl; 923 924 925 /* 926 ** Maximum number of elements in a constructor, to control the following: 927 ** * counter overflows; 928 ** * overflows in 'extra' for OP_NEWTABLE and OP_SETLIST; 929 ** * overflows when adding multiple returns in OP_SETLIST. 930 */ 931 #define MAX_CNST (INT_MAX/2) 932 #if MAX_CNST/(MAXARG_vC + 1) > MAXARG_Ax 933 #undef MAX_CNST 934 #define MAX_CNST (MAXARG_Ax * (MAXARG_vC + 1)) 935 #endif 936 937 938 static void recfield (LexState *ls, ConsControl *cc) { 939 /* recfield -> (NAME | '['exp']') = exp */ 940 FuncState *fs = ls->fs; 941 lu_byte reg = ls->fs->freereg; 942 expdesc tab, key, val; 943 if (ls->t.token == TK_NAME) 944 codename(ls, &key); 945 else /* ls->t.token == '[' */ 946 yindex(ls, &key); 947 cc->nh++; 948 checknext(ls, '='); 949 tab = *cc->t; 950 luaK_indexed(fs, &tab, &key); 951 expr(ls, &val); 952 luaK_storevar(fs, &tab, &val); 953 fs->freereg = reg; /* free registers */ 954 } 955 956 957 static void closelistfield (FuncState *fs, ConsControl *cc) { 958 lua_assert(cc->tostore > 0); 959 luaK_exp2nextreg(fs, &cc->v); 960 cc->v.k = VVOID; 961 if (cc->tostore >= cc->maxtostore) { 962 luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */ 963 cc->na += cc->tostore; 964 cc->tostore = 0; /* no more items pending */ 965 } 966 } 967 968 969 static void lastlistfield (FuncState *fs, ConsControl *cc) { 970 if (cc->tostore == 0) return; 971 if (hasmultret(cc->v.k)) { 972 luaK_setmultret(fs, &cc->v); 973 luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET); 974 cc->na--; /* do not count last expression (unknown number of elements) */ 975 } 976 else { 977 if (cc->v.k != VVOID) 978 luaK_exp2nextreg(fs, &cc->v); 979 luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); 980 } 981 cc->na += cc->tostore; 982 } 983 984 985 static void listfield (LexState *ls, ConsControl *cc) { 986 /* listfield -> exp */ 987 expr(ls, &cc->v); 988 cc->tostore++; 989 } 990 991 992 static void field (LexState *ls, ConsControl *cc) { 993 /* field -> listfield | recfield */ 994 switch(ls->t.token) { 995 case TK_NAME: { /* may be 'listfield' or 'recfield' */ 996 if (luaX_lookahead(ls) != '=') /* expression? */ 997 listfield(ls, cc); 998 else 999 recfield(ls, cc); 1000 break; 1001 } 1002 case '[': { 1003 recfield(ls, cc); 1004 break; 1005 } 1006 default: { 1007 listfield(ls, cc); 1008 break; 1009 } 1010 } 1011 } 1012 1013 1014 /* 1015 ** Compute a limit for how many registers a constructor can use before 1016 ** emitting a 'SETLIST' instruction, based on how many registers are 1017 ** available. 1018 */ 1019 static int maxtostore (FuncState *fs) { 1020 int numfreeregs = MAX_FSTACK - fs->freereg; 1021 if (numfreeregs >= 160) /* "lots" of registers? */ 1022 return numfreeregs / 5; /* use up to 1/5 of them */ 1023 else if (numfreeregs >= 80) /* still "enough" registers? */ 1024 return 10; /* one 'SETLIST' instruction for each 10 values */ 1025 else /* save registers for potential more nesting */ 1026 return 1; 1027 } 1028 1029 1030 static void constructor (LexState *ls, expdesc *t) { 1031 /* constructor -> '{' [ field { sep field } [sep] ] '}' 1032 sep -> ',' | ';' */ 1033 FuncState *fs = ls->fs; 1034 int line = ls->linenumber; 1035 int pc = luaK_codevABCk(fs, OP_NEWTABLE, 0, 0, 0, 0); 1036 ConsControl cc; 1037 luaK_code(fs, 0); /* space for extra arg. */ 1038 cc.na = cc.nh = cc.tostore = 0; 1039 cc.t = t; 1040 init_exp(t, VNONRELOC, fs->freereg); /* table will be at stack top */ 1041 luaK_reserveregs(fs, 1); 1042 init_exp(&cc.v, VVOID, 0); /* no value (yet) */ 1043 checknext(ls, '{' /*}*/); 1044 cc.maxtostore = maxtostore(fs); 1045 do { 1046 if (ls->t.token == /*{*/ '}') break; 1047 if (cc.v.k != VVOID) /* is there a previous list item? */ 1048 closelistfield(fs, &cc); /* close it */ 1049 field(ls, &cc); 1050 luaY_checklimit(fs, cc.tostore + cc.na + cc.nh, MAX_CNST, 1051 "items in a constructor"); 1052 } while (testnext(ls, ',') || testnext(ls, ';')); 1053 check_match(ls, /*{*/ '}', '{' /*}*/, line); 1054 lastlistfield(fs, &cc); 1055 luaK_settablesize(fs, pc, t->u.info, cc.na, cc.nh); 1056 } 1057 1058 /* }====================================================================== */ 1059 1060 1061 static void setvararg (FuncState *fs) { 1062 fs->f->flag |= PF_VAHID; /* by default, use hidden vararg arguments */ 1063 luaK_codeABC(fs, OP_VARARGPREP, 0, 0, 0); 1064 } 1065 1066 1067 static void parlist (LexState *ls) { 1068 /* parlist -> [ {NAME ','} (NAME | '...') ] */ 1069 FuncState *fs = ls->fs; 1070 Proto *f = fs->f; 1071 int nparams = 0; 1072 int varargk = 0; 1073 if (ls->t.token != ')') { /* is 'parlist' not empty? */ 1074 do { 1075 switch (ls->t.token) { 1076 case TK_NAME: { 1077 new_localvar(ls, str_checkname(ls)); 1078 nparams++; 1079 break; 1080 } 1081 case TK_DOTS: { 1082 varargk = 1; 1083 luaX_next(ls); /* skip '...' */ 1084 if (ls->t.token == TK_NAME) 1085 new_varkind(ls, str_checkname(ls), RDKVAVAR); 1086 else 1087 new_localvarliteral(ls, "(vararg table)"); 1088 break; 1089 } 1090 default: luaX_syntaxerror(ls, " or '...' expected"); 1091 } 1092 } while (!varargk && testnext(ls, ',')); 1093 } 1094 adjustlocalvars(ls, nparams); 1095 f->numparams = cast_byte(fs->nactvar); 1096 if (varargk) { 1097 setvararg(fs); /* declared vararg */ 1098 adjustlocalvars(ls, 1); /* vararg parameter */ 1099 } 1100 /* reserve registers for parameters (plus vararg parameter, if present) */ 1101 luaK_reserveregs(fs, fs->nactvar); 1102 } 1103 1104 1105 static void body (LexState *ls, expdesc *e, int ismethod, int line) { 1106 /* body -> '(' parlist ')' block END */ 1107 FuncState new_fs; 1108 BlockCnt bl; 1109 new_fs.f = addprototype(ls); 1110 new_fs.f->linedefined = line; 1111 open_func(ls, &new_fs, &bl); 1112 checknext(ls, '('); 1113 if (ismethod) { 1114 new_localvarliteral(ls, "self"); /* create 'self' parameter */ 1115 adjustlocalvars(ls, 1); 1116 } 1117 parlist(ls); 1118 checknext(ls, ')'); 1119 statlist(ls); 1120 new_fs.f->lastlinedefined = ls->linenumber; 1121 check_match(ls, TK_END, TK_FUNCTION, line); 1122 codeclosure(ls, e); 1123 close_func(ls); 1124 } 1125 1126 1127 static int explist (LexState *ls, expdesc *v) { 1128 /* explist -> expr { ',' expr } */ 1129 int n = 1; /* at least one expression */ 1130 expr(ls, v); 1131 while (testnext(ls, ',')) { 1132 luaK_exp2nextreg(ls->fs, v); 1133 expr(ls, v); 1134 n++; 1135 } 1136 return n; 1137 } 1138 1139 1140 static void funcargs (LexState *ls, expdesc *f) { 1141 FuncState *fs = ls->fs; 1142 expdesc args; 1143 int base, nparams; 1144 int line = ls->linenumber; 1145 switch (ls->t.token) { 1146 case '(': { /* funcargs -> '(' [ explist ] ')' */ 1147 luaX_next(ls); 1148 if (ls->t.token == ')') /* arg list is empty? */ 1149 args.k = VVOID; 1150 else { 1151 explist(ls, &args); 1152 if (hasmultret(args.k)) 1153 luaK_setmultret(fs, &args); 1154 } 1155 check_match(ls, ')', '(', line); 1156 break; 1157 } 1158 case '{' /*}*/: { /* funcargs -> constructor */ 1159 constructor(ls, &args); 1160 break; 1161 } 1162 case TK_STRING: { /* funcargs -> STRING */ 1163 codestring(&args, ls->t.seminfo.ts); 1164 luaX_next(ls); /* must use 'seminfo' before 'next' */ 1165 break; 1166 } 1167 default: { 1168 luaX_syntaxerror(ls, "function arguments expected"); 1169 return; /* to avoid warnings */ 1170 } 1171 } 1172 lua_assert(f->k == VNONRELOC); 1173 base = f->u.info; /* base register for call */ 1174 if (hasmultret(args.k)) 1175 nparams = LUA_MULTRET; /* open call */ 1176 else { 1177 if (args.k != VVOID) 1178 luaK_exp2nextreg(fs, &args); /* close last argument */ 1179 nparams = fs->freereg - (base+1); 1180 } 1181 init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); 1182 luaK_fixline(fs, line); 1183 /* call removes function and arguments and leaves one result (unless 1184 changed later) */ 1185 fs->freereg = cast_byte(base + 1); 1186 } 1187 1188 1189 1190 1191 /* 1192 ** {====================================================================== 1193 ** Expression parsing 1194 ** ======================================================================= 1195 */ 1196 1197 1198 static void primaryexp (LexState *ls, expdesc *v) { 1199 /* primaryexp -> NAME | '(' expr ')' */ 1200 switch (ls->t.token) { 1201 case '(': { 1202 int line = ls->linenumber; 1203 luaX_next(ls); 1204 expr(ls, v); 1205 check_match(ls, ')', '(', line); 1206 luaK_dischargevars(ls->fs, v); 1207 return; 1208 } 1209 case TK_NAME: { 1210 singlevar(ls, v); 1211 return; 1212 } 1213 default: { 1214 luaX_syntaxerror(ls, "unexpected symbol"); 1215 } 1216 } 1217 } 1218 1219 1220 static void suffixedexp (LexState *ls, expdesc *v) { 1221 /* suffixedexp -> 1222 primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */ 1223 FuncState *fs = ls->fs; 1224 primaryexp(ls, v); 1225 for (;;) { 1226 switch (ls->t.token) { 1227 case '.': { /* fieldsel */ 1228 fieldsel(ls, v); 1229 break; 1230 } 1231 case '[': { /* '[' exp ']' */ 1232 expdesc key; 1233 luaK_exp2anyregup(fs, v); 1234 yindex(ls, &key); 1235 luaK_indexed(fs, v, &key); 1236 break; 1237 } 1238 case ':': { /* ':' NAME funcargs */ 1239 expdesc key; 1240 luaX_next(ls); 1241 codename(ls, &key); 1242 luaK_self(fs, v, &key); 1243 funcargs(ls, v); 1244 break; 1245 } 1246 case '(': case TK_STRING: case '{' /*}*/: { /* funcargs */ 1247 luaK_exp2nextreg(fs, v); 1248 funcargs(ls, v); 1249 break; 1250 } 1251 default: return; 1252 } 1253 } 1254 } 1255 1256 1257 static void simpleexp (LexState *ls, expdesc *v) { 1258 /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... | 1259 constructor | FUNCTION body | suffixedexp */ 1260 switch (ls->t.token) { 1261 case TK_FLT: { 1262 init_exp(v, VKFLT, 0); 1263 v->u.nval = ls->t.seminfo.r; 1264 break; 1265 } 1266 case TK_INT: { 1267 init_exp(v, VKINT, 0); 1268 v->u.ival = ls->t.seminfo.i; 1269 break; 1270 } 1271 case TK_STRING: { 1272 codestring(v, ls->t.seminfo.ts); 1273 break; 1274 } 1275 case TK_NIL: { 1276 init_exp(v, VNIL, 0); 1277 break; 1278 } 1279 case TK_TRUE: { 1280 init_exp(v, VTRUE, 0); 1281 break; 1282 } 1283 case TK_FALSE: { 1284 init_exp(v, VFALSE, 0); 1285 break; 1286 } 1287 case TK_DOTS: { /* vararg */ 1288 FuncState *fs = ls->fs; 1289 check_condition(ls, isvararg(fs->f), 1290 "cannot use '...' outside a vararg function"); 1291 init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, fs->f->numparams, 1)); 1292 break; 1293 } 1294 case '{' /*}*/: { /* constructor */ 1295 constructor(ls, v); 1296 return; 1297 } 1298 case TK_FUNCTION: { 1299 luaX_next(ls); 1300 body(ls, v, 0, ls->linenumber); 1301 return; 1302 } 1303 default: { 1304 suffixedexp(ls, v); 1305 return; 1306 } 1307 } 1308 luaX_next(ls); 1309 } 1310 1311 1312 static UnOpr getunopr (int op) { 1313 switch (op) { 1314 case TK_NOT: return OPR_NOT; 1315 case '-': return OPR_MINUS; 1316 case '~': return OPR_BNOT; 1317 case '#': return OPR_LEN; 1318 default: return OPR_NOUNOPR; 1319 } 1320 } 1321 1322 1323 static BinOpr getbinopr (int op) { 1324 switch (op) { 1325 case '+': return OPR_ADD; 1326 case '-': return OPR_SUB; 1327 case '*': return OPR_MUL; 1328 case '%': return OPR_MOD; 1329 case '^': return OPR_POW; 1330 case '/': return OPR_DIV; 1331 case TK_IDIV: return OPR_IDIV; 1332 case '&': return OPR_BAND; 1333 case '|': return OPR_BOR; 1334 case '~': return OPR_BXOR; 1335 case TK_SHL: return OPR_SHL; 1336 case TK_SHR: return OPR_SHR; 1337 case TK_CONCAT: return OPR_CONCAT; 1338 case TK_NE: return OPR_NE; 1339 case TK_EQ: return OPR_EQ; 1340 case '<': return OPR_LT; 1341 case TK_LE: return OPR_LE; 1342 case '>': return OPR_GT; 1343 case TK_GE: return OPR_GE; 1344 case TK_AND: return OPR_AND; 1345 case TK_OR: return OPR_OR; 1346 default: return OPR_NOBINOPR; 1347 } 1348 } 1349 1350 1351 /* 1352 ** Priority table for binary operators. 1353 */ 1354 static const struct { 1355 lu_byte left; /* left priority for each binary operator */ 1356 lu_byte right; /* right priority */ 1357 } priority[] = { /* ORDER OPR */ 1358 {10, 10}, {10, 10}, /* '+' '-' */ 1359 {11, 11}, {11, 11}, /* '*' '%' */ 1360 {14, 13}, /* '^' (right associative) */ 1361 {11, 11}, {11, 11}, /* '/' '//' */ 1362 {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */ 1363 {7, 7}, {7, 7}, /* '<<' '>>' */ 1364 {9, 8}, /* '..' (right associative) */ 1365 {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ 1366 {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ 1367 {2, 2}, {1, 1} /* and, or */ 1368 }; 1369 1370 #define UNARY_PRIORITY 12 /* priority for unary operators */ 1371 1372 1373 /* 1374 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr } 1375 ** where 'binop' is any binary operator with a priority higher than 'limit' 1376 */ 1377 static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { 1378 BinOpr op; 1379 UnOpr uop; 1380 enterlevel(ls); 1381 uop = getunopr(ls->t.token); 1382 if (uop != OPR_NOUNOPR) { /* prefix (unary) operator? */ 1383 int line = ls->linenumber; 1384 luaX_next(ls); /* skip operator */ 1385 subexpr(ls, v, UNARY_PRIORITY); 1386 luaK_prefix(ls->fs, uop, v, line); 1387 } 1388 else simpleexp(ls, v); 1389 /* expand while operators have priorities higher than 'limit' */ 1390 op = getbinopr(ls->t.token); 1391 while (op != OPR_NOBINOPR && priority[op].left > limit) { 1392 expdesc v2; 1393 BinOpr nextop; 1394 int line = ls->linenumber; 1395 luaX_next(ls); /* skip operator */ 1396 luaK_infix(ls->fs, op, v); 1397 /* read sub-expression with higher priority */ 1398 nextop = subexpr(ls, &v2, priority[op].right); 1399 luaK_posfix(ls->fs, op, v, &v2, line); 1400 op = nextop; 1401 } 1402 leavelevel(ls); 1403 return op; /* return first untreated operator */ 1404 } 1405 1406 1407 static void expr (LexState *ls, expdesc *v) { 1408 subexpr(ls, v, 0); 1409 } 1410 1411 /* }==================================================================== */ 1412 1413 1414 1415 /* 1416 ** {====================================================================== 1417 ** Rules for Statements 1418 ** ======================================================================= 1419 */ 1420 1421 1422 static void block (LexState *ls) { 1423 /* block -> statlist */ 1424 FuncState *fs = ls->fs; 1425 BlockCnt bl; 1426 enterblock(fs, &bl, 0); 1427 statlist(ls); 1428 leaveblock(fs); 1429 } 1430 1431 1432 /* 1433 ** structure to chain all variables in the left-hand side of an 1434 ** assignment 1435 */ 1436 struct LHS_assign { 1437 struct LHS_assign *prev; 1438 expdesc v; /* variable (global, local, upvalue, or indexed) */ 1439 }; 1440 1441 1442 /* 1443 ** check whether, in an assignment to an upvalue/local variable, the 1444 ** upvalue/local variable is begin used in a previous assignment to a 1445 ** table. If so, save original upvalue/local value in a safe place and 1446 ** use this safe copy in the previous assignment. 1447 */ 1448 static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { 1449 FuncState *fs = ls->fs; 1450 lu_byte extra = fs->freereg; /* eventual position to save local variable */ 1451 int conflict = 0; 1452 for (; lh; lh = lh->prev) { /* check all previous assignments */ 1453 if (vkisindexed(lh->v.k)) { /* assignment to table field? */ 1454 if (lh->v.k == VINDEXUP) { /* is table an upvalue? */ 1455 if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) { 1456 conflict = 1; /* table is the upvalue being assigned now */ 1457 lh->v.k = VINDEXSTR; 1458 lh->v.u.ind.t = extra; /* assignment will use safe copy */ 1459 } 1460 } 1461 else { /* table is a register */ 1462 if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.ridx) { 1463 conflict = 1; /* table is the local being assigned now */ 1464 lh->v.u.ind.t = extra; /* assignment will use safe copy */ 1465 } 1466 /* is index the local being assigned? */ 1467 if (lh->v.k == VINDEXED && v->k == VLOCAL && 1468 lh->v.u.ind.idx == v->u.var.ridx) { 1469 conflict = 1; 1470 lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ 1471 } 1472 } 1473 } 1474 } 1475 if (conflict) { 1476 /* copy upvalue/local value to a temporary (in position 'extra') */ 1477 if (v->k == VLOCAL) 1478 luaK_codeABC(fs, OP_MOVE, extra, v->u.var.ridx, 0); 1479 else 1480 luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0); 1481 luaK_reserveregs(fs, 1); 1482 } 1483 } 1484 1485 1486 /* Create code to store the "top" register in 'var' */ 1487 static void storevartop (FuncState *fs, expdesc *var) { 1488 expdesc e; 1489 init_exp(&e, VNONRELOC, fs->freereg - 1); 1490 luaK_storevar(fs, var, &e); /* will also free the top register */ 1491 } 1492 1493 1494 /* 1495 ** Parse and compile a multiple assignment. The first "variable" 1496 ** (a 'suffixedexp') was already read by the caller. 1497 ** 1498 ** assignment -> suffixedexp restassign 1499 ** restassign -> ',' suffixedexp restassign | '=' explist 1500 */ 1501 static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) { 1502 expdesc e; 1503 check_condition(ls, vkisvar(lh->v.k), "syntax error"); 1504 check_readonly(ls, &lh->v); 1505 if (testnext(ls, ',')) { /* restassign -> ',' suffixedexp restassign */ 1506 struct LHS_assign nv; 1507 nv.prev = lh; 1508 suffixedexp(ls, &nv.v); 1509 if (!vkisindexed(nv.v.k)) 1510 check_conflict(ls, lh, &nv.v); 1511 enterlevel(ls); /* control recursion depth */ 1512 restassign(ls, &nv, nvars+1); 1513 leavelevel(ls); 1514 } 1515 else { /* restassign -> '=' explist */ 1516 int nexps; 1517 checknext(ls, '='); 1518 nexps = explist(ls, &e); 1519 if (nexps != nvars) 1520 adjust_assign(ls, nvars, nexps, &e); 1521 else { 1522 luaK_setoneret(ls->fs, &e); /* close last expression */ 1523 luaK_storevar(ls->fs, &lh->v, &e); 1524 return; /* avoid default */ 1525 } 1526 } 1527 storevartop(ls->fs, &lh->v); /* default assignment */ 1528 } 1529 1530 1531 static int cond (LexState *ls) { 1532 /* cond -> exp */ 1533 expdesc v; 1534 expr(ls, &v); /* read condition */ 1535 if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */ 1536 luaK_goiftrue(ls->fs, &v); 1537 return v.f; 1538 } 1539 1540 1541 static void gotostat (LexState *ls, int line) { 1542 TString *name = str_checkname(ls); /* label's name */ 1543 newgotoentry(ls, name, line); 1544 } 1545 1546 1547 /* 1548 ** Break statement. Semantically equivalent to "goto break". 1549 */ 1550 static void breakstat (LexState *ls, int line) { 1551 BlockCnt *bl; /* to look for an enclosing loop */ 1552 for (bl = ls->fs->bl; bl != NULL; bl = bl->previous) { 1553 if (bl->isloop) /* found one? */ 1554 goto ok; 1555 } 1556 luaX_syntaxerror(ls, "break outside loop"); 1557 ok: 1558 bl->isloop = 2; /* signal that block has pending breaks */ 1559 luaX_next(ls); /* skip break */ 1560 newgotoentry(ls, ls->brkn, line); 1561 } 1562 1563 1564 /* 1565 ** Check whether there is already a label with the given 'name' at 1566 ** current function. 1567 */ 1568 static void checkrepeated (LexState *ls, TString *name) { 1569 Labeldesc *lb = findlabel(ls, name, ls->fs->firstlabel); 1570 if (l_unlikely(lb != NULL)) /* already defined? */ 1571 luaK_semerror(ls, "label '%s' already defined on line %d", 1572 getstr(name), lb->line); /* error */ 1573 } 1574 1575 1576 static void labelstat (LexState *ls, TString *name, int line) { 1577 /* label -> '::' NAME '::' */ 1578 checknext(ls, TK_DBCOLON); /* skip double colon */ 1579 while (ls->t.token == ';' || ls->t.token == TK_DBCOLON) 1580 statement(ls); /* skip other no-op statements */ 1581 checkrepeated(ls, name); /* check for repeated labels */ 1582 createlabel(ls, name, line, block_follow(ls, 0)); 1583 } 1584 1585 1586 static void whilestat (LexState *ls, int line) { 1587 /* whilestat -> WHILE cond DO block END */ 1588 FuncState *fs = ls->fs; 1589 int whileinit; 1590 int condexit; 1591 BlockCnt bl; 1592 luaX_next(ls); /* skip WHILE */ 1593 whileinit = luaK_getlabel(fs); 1594 condexit = cond(ls); 1595 enterblock(fs, &bl, 1); 1596 checknext(ls, TK_DO); 1597 block(ls); 1598 luaK_jumpto(fs, whileinit); 1599 check_match(ls, TK_END, TK_WHILE, line); 1600 leaveblock(fs); 1601 luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ 1602 } 1603 1604 1605 static void repeatstat (LexState *ls, int line) { 1606 /* repeatstat -> REPEAT block UNTIL cond */ 1607 int condexit; 1608 FuncState *fs = ls->fs; 1609 int repeat_init = luaK_getlabel(fs); 1610 BlockCnt bl1, bl2; 1611 enterblock(fs, &bl1, 1); /* loop block */ 1612 enterblock(fs, &bl2, 0); /* scope block */ 1613 luaX_next(ls); /* skip REPEAT */ 1614 statlist(ls); 1615 check_match(ls, TK_UNTIL, TK_REPEAT, line); 1616 condexit = cond(ls); /* read condition (inside scope block) */ 1617 if (bl2.upval) { /* upvalues? */ 1618 int exit = luaK_jump(fs); /* normal exit must jump over fix */ 1619 luaK_patchtohere(fs, condexit); /* repetition must close upvalues */ 1620 luaK_codeABC(fs, OP_CLOSE, reglevel(fs, bl2.nactvar), 0, 0); 1621 condexit = luaK_jump(fs); /* repeat after closing upvalues */ 1622 luaK_patchtohere(fs, exit); /* normal exit comes to here */ 1623 } 1624 luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ 1625 leaveblock(fs); /* finish scope */ 1626 leaveblock(fs); /* finish loop */ 1627 } 1628 1629 1630 /* 1631 ** Read an expression and generate code to put its results in next 1632 ** stack slot. 1633 ** 1634 */ 1635 static void exp1 (LexState *ls) { 1636 expdesc e; 1637 expr(ls, &e); 1638 luaK_exp2nextreg(ls->fs, &e); 1639 lua_assert(e.k == VNONRELOC); 1640 } 1641 1642 1643 /* 1644 ** Fix for instruction at position 'pc' to jump to 'dest'. 1645 ** (Jump addresses are relative in Lua). 'back' true means 1646 ** a back jump. 1647 */ 1648 static void fixforjump (FuncState *fs, int pc, int dest, int back) { 1649 Instruction *jmp = &fs->f->code[pc]; 1650 int offset = dest - (pc + 1); 1651 if (back) 1652 offset = -offset; 1653 if (l_unlikely(offset > MAXARG_Bx)) 1654 luaX_syntaxerror(fs->ls, "control structure too long"); 1655 SETARG_Bx(*jmp, offset); 1656 } 1657 1658 1659 /* 1660 ** Generate code for a 'for' loop. 1661 */ 1662 static void forbody (LexState *ls, int base, int line, int nvars, int isgen) { 1663 /* forbody -> DO block */ 1664 static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP}; 1665 static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP}; 1666 BlockCnt bl; 1667 FuncState *fs = ls->fs; 1668 int prep, endfor; 1669 checknext(ls, TK_DO); 1670 prep = luaK_codeABx(fs, forprep[isgen], base, 0); 1671 fs->freereg--; /* both 'forprep' remove one register from the stack */ 1672 enterblock(fs, &bl, 0); /* scope for declared variables */ 1673 adjustlocalvars(ls, nvars); 1674 luaK_reserveregs(fs, nvars); 1675 block(ls); 1676 leaveblock(fs); /* end of scope for declared variables */ 1677 fixforjump(fs, prep, luaK_getlabel(fs), 0); 1678 if (isgen) { /* generic for? */ 1679 luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars); 1680 luaK_fixline(fs, line); 1681 } 1682 endfor = luaK_codeABx(fs, forloop[isgen], base, 0); 1683 fixforjump(fs, endfor, prep + 1, 1); 1684 luaK_fixline(fs, line); 1685 } 1686 1687 1688 static void fornum (LexState *ls, TString *varname, int line) { 1689 /* fornum -> NAME = exp,exp[,exp] forbody */ 1690 FuncState *fs = ls->fs; 1691 int base = fs->freereg; 1692 new_localvarliteral(ls, "(for state)"); 1693 new_localvarliteral(ls, "(for state)"); 1694 new_varkind(ls, varname, RDKCONST); /* control variable */ 1695 checknext(ls, '='); 1696 exp1(ls); /* initial value */ 1697 checknext(ls, ','); 1698 exp1(ls); /* limit */ 1699 if (testnext(ls, ',')) 1700 exp1(ls); /* optional step */ 1701 else { /* default step = 1 */ 1702 luaK_int(fs, fs->freereg, 1); 1703 luaK_reserveregs(fs, 1); 1704 } 1705 adjustlocalvars(ls, 2); /* start scope for internal variables */ 1706 forbody(ls, base, line, 1, 0); 1707 } 1708 1709 1710 static void forlist (LexState *ls, TString *indexname) { 1711 /* forlist -> NAME {,NAME} IN explist forbody */ 1712 FuncState *fs = ls->fs; 1713 expdesc e; 1714 int nvars = 4; /* function, state, closing, control */ 1715 int line; 1716 int base = fs->freereg; 1717 /* create internal variables */ 1718 new_localvarliteral(ls, "(for state)"); /* iterator function */ 1719 new_localvarliteral(ls, "(for state)"); /* state */ 1720 new_localvarliteral(ls, "(for state)"); /* closing var. (after swap) */ 1721 new_varkind(ls, indexname, RDKCONST); /* control variable */ 1722 /* other declared variables */ 1723 while (testnext(ls, ',')) { 1724 new_localvar(ls, str_checkname(ls)); 1725 nvars++; 1726 } 1727 checknext(ls, TK_IN); 1728 line = ls->linenumber; 1729 adjust_assign(ls, 4, explist(ls, &e), &e); 1730 adjustlocalvars(ls, 3); /* start scope for internal variables */ 1731 marktobeclosed(fs); /* last internal var. must be closed */ 1732 luaK_checkstack(fs, 2); /* extra space to call iterator */ 1733 forbody(ls, base, line, nvars - 3, 1); 1734 } 1735 1736 1737 static void forstat (LexState *ls, int line) { 1738 /* forstat -> FOR (fornum | forlist) END */ 1739 FuncState *fs = ls->fs; 1740 TString *varname; 1741 BlockCnt bl; 1742 enterblock(fs, &bl, 1); /* scope for loop and control variables */ 1743 luaX_next(ls); /* skip 'for' */ 1744 varname = str_checkname(ls); /* first variable name */ 1745 switch (ls->t.token) { 1746 case '=': fornum(ls, varname, line); break; 1747 case ',': case TK_IN: forlist(ls, varname); break; 1748 default: luaX_syntaxerror(ls, "'=' or 'in' expected"); 1749 } 1750 check_match(ls, TK_END, TK_FOR, line); 1751 leaveblock(fs); /* loop scope ('break' jumps to this point) */ 1752 } 1753 1754 1755 static void test_then_block (LexState *ls, int *escapelist) { 1756 /* test_then_block -> [IF | ELSEIF] cond THEN block */ 1757 FuncState *fs = ls->fs; 1758 int condtrue; 1759 luaX_next(ls); /* skip IF or ELSEIF */ 1760 condtrue = cond(ls); /* read condition */ 1761 checknext(ls, TK_THEN); 1762 block(ls); /* 'then' part */ 1763 if (ls->t.token == TK_ELSE || 1764 ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ 1765 luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */ 1766 luaK_patchtohere(fs, condtrue); 1767 } 1768 1769 1770 static void ifstat (LexState *ls, int line) { 1771 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ 1772 FuncState *fs = ls->fs; 1773 int escapelist = NO_JUMP; /* exit list for finished parts */ 1774 test_then_block(ls, &escapelist); /* IF cond THEN block */ 1775 while (ls->t.token == TK_ELSEIF) 1776 test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ 1777 if (testnext(ls, TK_ELSE)) 1778 block(ls); /* 'else' part */ 1779 check_match(ls, TK_END, TK_IF, line); 1780 luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ 1781 } 1782 1783 1784 static void localfunc (LexState *ls) { 1785 expdesc b; 1786 FuncState *fs = ls->fs; 1787 int fvar = fs->nactvar; /* function's variable index */ 1788 new_localvar(ls, str_checkname(ls)); /* new local variable */ 1789 adjustlocalvars(ls, 1); /* enter its scope */ 1790 body(ls, &b, 0, ls->linenumber); /* function created in next register */ 1791 /* debug information will only see the variable after this point! */ 1792 localdebuginfo(fs, fvar)->startpc = fs->pc; 1793 } 1794 1795 1796 static lu_byte getvarattribute (LexState *ls, lu_byte df) { 1797 /* attrib -> ['<' NAME '>'] */ 1798 if (testnext(ls, '<')) { 1799 TString *ts = str_checkname(ls); 1800 const char *attr = getstr(ts); 1801 checknext(ls, '>'); 1802 if (strcmp(attr, "const") == 0) 1803 return RDKCONST; /* read-only variable */ 1804 else if (strcmp(attr, "close") == 0) 1805 return RDKTOCLOSE; /* to-be-closed variable */ 1806 else 1807 luaK_semerror(ls, "unknown attribute '%s'", attr); 1808 } 1809 return df; /* return default value */ 1810 } 1811 1812 1813 static void checktoclose (FuncState *fs, int level) { 1814 if (level != -1) { /* is there a to-be-closed variable? */ 1815 marktobeclosed(fs); 1816 luaK_codeABC(fs, OP_TBC, reglevel(fs, level), 0, 0); 1817 } 1818 } 1819 1820 1821 static void localstat (LexState *ls) { 1822 /* stat -> LOCAL NAME attrib { ',' NAME attrib } ['=' explist] */ 1823 FuncState *fs = ls->fs; 1824 int toclose = -1; /* index of to-be-closed variable (if any) */ 1825 Vardesc *var; /* last variable */ 1826 int vidx; /* index of last variable */ 1827 int nvars = 0; 1828 int nexps; 1829 expdesc e; 1830 /* get prefixed attribute (if any); default is regular local variable */ 1831 lu_byte defkind = getvarattribute(ls, VDKREG); 1832 do { /* for each variable */ 1833 TString *vname = str_checkname(ls); /* get its name */ 1834 lu_byte kind = getvarattribute(ls, defkind); /* postfixed attribute */ 1835 vidx = new_varkind(ls, vname, kind); /* predeclare it */ 1836 if (kind == RDKTOCLOSE) { /* to-be-closed? */ 1837 if (toclose != -1) /* one already present? */ 1838 luaK_semerror(ls, "multiple to-be-closed variables in local list"); 1839 toclose = fs->nactvar + nvars; 1840 } 1841 nvars++; 1842 } while (testnext(ls, ',')); 1843 if (testnext(ls, '=')) /* initialization? */ 1844 nexps = explist(ls, &e); 1845 else { 1846 e.k = VVOID; 1847 nexps = 0; 1848 } 1849 var = getlocalvardesc(fs, vidx); /* retrieve last variable */ 1850 if (nvars == nexps && /* no adjustments? */ 1851 var->vd.kind == RDKCONST && /* last variable is const? */ 1852 luaK_exp2const(fs, &e, &var->k)) { /* compile-time constant? */ 1853 var->vd.kind = RDKCTC; /* variable is a compile-time constant */ 1854 adjustlocalvars(ls, nvars - 1); /* exclude last variable */ 1855 fs->nactvar++; /* but count it */ 1856 } 1857 else { 1858 adjust_assign(ls, nvars, nexps, &e); 1859 adjustlocalvars(ls, nvars); 1860 } 1861 checktoclose(fs, toclose); 1862 } 1863 1864 1865 static lu_byte getglobalattribute (LexState *ls, lu_byte df) { 1866 lu_byte kind = getvarattribute(ls, df); 1867 switch (kind) { 1868 case RDKTOCLOSE: 1869 luaK_semerror(ls, "global variables cannot be to-be-closed"); 1870 return kind; /* to avoid warnings */ 1871 case RDKCONST: 1872 return GDKCONST; /* adjust kind for global variable */ 1873 default: 1874 return kind; 1875 } 1876 } 1877 1878 1879 static void checkglobal (LexState *ls, TString *varname, int line) { 1880 FuncState *fs = ls->fs; 1881 expdesc var; 1882 int k; 1883 buildglobal(ls, varname, &var); /* create global variable in 'var' */ 1884 k = var.u.ind.keystr; /* index of global name in 'k' */ 1885 luaK_codecheckglobal(fs, &var, k, line); 1886 } 1887 1888 1889 /* 1890 ** Recursively traverse list of globals to be initalized. When 1891 ** going, generate table description for the global. In the end, 1892 ** after all indices have been generated, read list of initializing 1893 ** expressions. When returning, generate the assignment of the value on 1894 ** the stack to the corresponding table description. 'n' is the variable 1895 ** being handled, range [0, nvars - 1]. 1896 */ 1897 static void initglobal (LexState *ls, int nvars, int firstidx, int n, 1898 int line) { 1899 if (n == nvars) { /* traversed all variables? */ 1900 expdesc e; 1901 int nexps = explist(ls, &e); /* read list of expressions */ 1902 adjust_assign(ls, nvars, nexps, &e); 1903 } 1904 else { /* handle variable 'n' */ 1905 FuncState *fs = ls->fs; 1906 expdesc var; 1907 TString *varname = getlocalvardesc(fs, firstidx + n)->vd.name; 1908 buildglobal(ls, varname, &var); /* create global variable in 'var' */ 1909 enterlevel(ls); /* control recursion depth */ 1910 initglobal(ls, nvars, firstidx, n + 1, line); 1911 leavelevel(ls); 1912 checkglobal(ls, varname, line); 1913 storevartop(fs, &var); 1914 } 1915 } 1916 1917 1918 static void globalnames (LexState *ls, lu_byte defkind) { 1919 FuncState *fs = ls->fs; 1920 int nvars = 0; 1921 int lastidx; /* index of last registered variable */ 1922 do { /* for each name */ 1923 TString *vname = str_checkname(ls); 1924 lu_byte kind = getglobalattribute(ls, defkind); 1925 lastidx = new_varkind(ls, vname, kind); 1926 nvars++; 1927 } while (testnext(ls, ',')); 1928 if (testnext(ls, '=')) /* initialization? */ 1929 initglobal(ls, nvars, lastidx - nvars + 1, 0, ls->linenumber); 1930 fs->nactvar = cast_short(fs->nactvar + nvars); /* activate declaration */ 1931 } 1932 1933 1934 static void globalstat (LexState *ls) { 1935 /* globalstat -> (GLOBAL) attrib '*' 1936 globalstat -> (GLOBAL) attrib NAME attrib {',' NAME attrib} */ 1937 FuncState *fs = ls->fs; 1938 /* get prefixed attribute (if any); default is regular global variable */ 1939 lu_byte defkind = getglobalattribute(ls, GDKREG); 1940 if (!testnext(ls, '*')) 1941 globalnames(ls, defkind); 1942 else { 1943 /* use NULL as name to represent '*' entries */ 1944 new_varkind(ls, NULL, defkind); 1945 fs->nactvar++; /* activate declaration */ 1946 } 1947 } 1948 1949 1950 static void globalfunc (LexState *ls, int line) { 1951 /* globalfunc -> (GLOBAL FUNCTION) NAME body */ 1952 expdesc var, b; 1953 FuncState *fs = ls->fs; 1954 TString *fname = str_checkname(ls); 1955 new_varkind(ls, fname, GDKREG); /* declare global variable */ 1956 fs->nactvar++; /* enter its scope */ 1957 buildglobal(ls, fname, &var); 1958 body(ls, &b, 0, ls->linenumber); /* compile and return closure in 'b' */ 1959 checkglobal(ls, fname, line); 1960 luaK_storevar(fs, &var, &b); 1961 luaK_fixline(fs, line); /* definition "happens" in the first line */ 1962 } 1963 1964 1965 static void globalstatfunc (LexState *ls, int line) { 1966 /* stat -> GLOBAL globalfunc | GLOBAL globalstat */ 1967 luaX_next(ls); /* skip 'global' */ 1968 if (testnext(ls, TK_FUNCTION)) 1969 globalfunc(ls, line); 1970 else 1971 globalstat(ls); 1972 } 1973 1974 1975 static int funcname (LexState *ls, expdesc *v) { 1976 /* funcname -> NAME {fieldsel} [':' NAME] */ 1977 int ismethod = 0; 1978 singlevar(ls, v); 1979 while (ls->t.token == '.') 1980 fieldsel(ls, v); 1981 if (ls->t.token == ':') { 1982 ismethod = 1; 1983 fieldsel(ls, v); 1984 } 1985 return ismethod; 1986 } 1987 1988 1989 static void funcstat (LexState *ls, int line) { 1990 /* funcstat -> FUNCTION funcname body */ 1991 int ismethod; 1992 expdesc v, b; 1993 luaX_next(ls); /* skip FUNCTION */ 1994 ismethod = funcname(ls, &v); 1995 check_readonly(ls, &v); 1996 body(ls, &b, ismethod, line); 1997 luaK_storevar(ls->fs, &v, &b); 1998 luaK_fixline(ls->fs, line); /* definition "happens" in the first line */ 1999 } 2000 2001 2002 static void exprstat (LexState *ls) { 2003 /* stat -> func | assignment */ 2004 FuncState *fs = ls->fs; 2005 struct LHS_assign v; 2006 suffixedexp(ls, &v.v); 2007 if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */ 2008 v.prev = NULL; 2009 restassign(ls, &v, 1); 2010 } 2011 else { /* stat -> func */ 2012 Instruction *inst; 2013 check_condition(ls, v.v.k == VCALL, "syntax error"); 2014 inst = &getinstruction(fs, &v.v); 2015 SETARG_C(*inst, 1); /* call statement uses no results */ 2016 } 2017 } 2018 2019 2020 static void retstat (LexState *ls) { 2021 /* stat -> RETURN [explist] [';'] */ 2022 FuncState *fs = ls->fs; 2023 expdesc e; 2024 int nret; /* number of values being returned */ 2025 int first = luaY_nvarstack(fs); /* first slot to be returned */ 2026 if (block_follow(ls, 1) || ls->t.token == ';') 2027 nret = 0; /* return no values */ 2028 else { 2029 nret = explist(ls, &e); /* optional return values */ 2030 if (hasmultret(e.k)) { 2031 luaK_setmultret(fs, &e); 2032 if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc) { /* tail call? */ 2033 SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL); 2034 lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs)); 2035 } 2036 nret = LUA_MULTRET; /* return all values */ 2037 } 2038 else { 2039 if (nret == 1) /* only one single value? */ 2040 first = luaK_exp2anyreg(fs, &e); /* can use original slot */ 2041 else { /* values must go to the top of the stack */ 2042 luaK_exp2nextreg(fs, &e); 2043 lua_assert(nret == fs->freereg - first); 2044 } 2045 } 2046 } 2047 luaK_ret(fs, first, nret); 2048 testnext(ls, ';'); /* skip optional semicolon */ 2049 } 2050 2051 2052 static void statement (LexState *ls) { 2053 int line = ls->linenumber; /* may be needed for error messages */ 2054 enterlevel(ls); 2055 switch (ls->t.token) { 2056 case ';': { /* stat -> ';' (empty statement) */ 2057 luaX_next(ls); /* skip ';' */ 2058 break; 2059 } 2060 case TK_IF: { /* stat -> ifstat */ 2061 ifstat(ls, line); 2062 break; 2063 } 2064 case TK_WHILE: { /* stat -> whilestat */ 2065 whilestat(ls, line); 2066 break; 2067 } 2068 case TK_DO: { /* stat -> DO block END */ 2069 luaX_next(ls); /* skip DO */ 2070 block(ls); 2071 check_match(ls, TK_END, TK_DO, line); 2072 break; 2073 } 2074 case TK_FOR: { /* stat -> forstat */ 2075 forstat(ls, line); 2076 break; 2077 } 2078 case TK_REPEAT: { /* stat -> repeatstat */ 2079 repeatstat(ls, line); 2080 break; 2081 } 2082 case TK_FUNCTION: { /* stat -> funcstat */ 2083 funcstat(ls, line); 2084 break; 2085 } 2086 case TK_LOCAL: { /* stat -> localstat */ 2087 luaX_next(ls); /* skip LOCAL */ 2088 if (testnext(ls, TK_FUNCTION)) /* local function? */ 2089 localfunc(ls); 2090 else 2091 localstat(ls); 2092 break; 2093 } 2094 case TK_GLOBAL: { /* stat -> globalstatfunc */ 2095 globalstatfunc(ls, line); 2096 break; 2097 } 2098 case TK_DBCOLON: { /* stat -> label */ 2099 luaX_next(ls); /* skip double colon */ 2100 labelstat(ls, str_checkname(ls), line); 2101 break; 2102 } 2103 case TK_RETURN: { /* stat -> retstat */ 2104 luaX_next(ls); /* skip RETURN */ 2105 retstat(ls); 2106 break; 2107 } 2108 case TK_BREAK: { /* stat -> breakstat */ 2109 breakstat(ls, line); 2110 break; 2111 } 2112 case TK_GOTO: { /* stat -> 'goto' NAME */ 2113 luaX_next(ls); /* skip 'goto' */ 2114 gotostat(ls, line); 2115 break; 2116 } 2117 #if LUA_COMPAT_GLOBAL 2118 case TK_NAME: { 2119 /* compatibility code to parse global keyword when "global" 2120 is not reserved */ 2121 if (ls->t.seminfo.ts == ls->glbn) { /* current = "global"? */ 2122 int lk = luaX_lookahead(ls); 2123 if (lk == '<' || lk == TK_NAME || lk == '*' || lk == TK_FUNCTION) { 2124 /* 'global ' or 'global name' or 'global *' or 2125 'global function' */ 2126 globalstatfunc(ls, line); 2127 break; 2128 } 2129 } /* else... */ 2130 } 2131 #endif 2132 /* FALLTHROUGH */ 2133 default: { /* stat -> func | assignment */ 2134 exprstat(ls); 2135 break; 2136 } 2137 } 2138 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && 2139 ls->fs->freereg >= luaY_nvarstack(ls->fs)); 2140 ls->fs->freereg = luaY_nvarstack(ls->fs); /* free registers */ 2141 leavelevel(ls); 2142 } 2143 2144 /* }====================================================================== */ 2145 2146 /* }====================================================================== */ 2147 2148 2149 /* 2150 ** compiles the main function, which is a regular vararg function with an 2151 ** upvalue named LUA_ENV 2152 */ 2153 static void mainfunc (LexState *ls, FuncState *fs) { 2154 BlockCnt bl; 2155 Upvaldesc *env; 2156 open_func(ls, fs, &bl); 2157 setvararg(fs); /* main function is always vararg */ 2158 env = allocupvalue(fs); /* ...set environment upvalue */ 2159 env->instack = 1; 2160 env->idx = 0; 2161 env->kind = VDKREG; 2162 env->name = ls->envn; 2163 luaC_objbarrier(ls->L, fs->f, env->name); 2164 luaX_next(ls); /* read first token */ 2165 statlist(ls); /* parse main body */ 2166 check(ls, TK_EOS); 2167 close_func(ls); 2168 } 2169 2170 2171 LClosure *luaY_parser (lua_State *L, ZIO *z, Table *anchor, Mbuffer *buff, 2172 Dyndata *dyd, const char *name, int firstchar) { 2173 LexState lexstate; 2174 FuncState funcstate; 2175 LClosure *cl; 2176 lexstate.h = anchor; /* table for scanner */ 2177 cl = luaF_newLclosure(L, 1); /* create main closure */ 2178 luaD_anchorobj(L, anchor, obj2gco(cl)); /* anchor it in scanner table */ 2179 funcstate.f = cl->p = luaF_newproto(L); 2180 luaC_objbarrier(L, cl, cl->p); 2181 funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ 2182 luaC_objbarrier(L, funcstate.f, funcstate.f->source); 2183 lexstate.buff = buff; 2184 lexstate.dyd = dyd; 2185 dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; 2186 luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); 2187 mainfunc(&lexstate, &funcstate); 2188 lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); 2189 /* all scopes should be correctly finished */ 2190 lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); 2191 return cl; 2192 } 2193