lua/lparser.c

Go to the documentation of this file.
00001 /*
00002 ** $Id: lparser.c,v 2.124 2011/12/02 13:23:56 roberto Exp $
00003 ** Lua Parser
00004 ** See Copyright Notice in lua.h
00005 */
00006 
00007 
00008 #include <string.h>
00009 
00010 #define lparser_c
00011 #define LUA_CORE
00012 
00013 #include "lua.h"
00014 
00015 #include "lcode.h"
00016 #include "ldebug.h"
00017 #include "ldo.h"
00018 #include "lfunc.h"
00019 #include "llex.h"
00020 #include "lmem.h"
00021 #include "lobject.h"
00022 #include "lopcodes.h"
00023 #include "lparser.h"
00024 #include "lstate.h"
00025 #include "lstring.h"
00026 #include "ltable.h"
00027 
00028 
00029 
00030 /* maximum number of local variables per function (must be smaller
00031    than 250, due to the bytecode format) */
00032 #define MAXVARS     200
00033 
00034 
00035 #define hasmultret(k)       ((k) == VCALL || (k) == VVARARG)
00036 
00037 
00038 
00039 /*
00040 ** nodes for block list (list of active blocks)
00041 */
00042 typedef struct BlockCnt {
00043   struct BlockCnt *previous;  /* chain */
00044   short firstlabel;  /* index of first label in this block */
00045   short firstgoto;  /* index of first pending goto in this block */
00046   lu_byte nactvar;  /* # active locals outside the block */
00047   lu_byte upval;  /* true if some variable in the block is an upvalue */
00048   lu_byte isloop;  /* true if `block' is a loop */
00049 } BlockCnt;
00050 
00051 
00052 
00053 /*
00054 ** prototypes for recursive non-terminal functions
00055 */
00056 static void statement (LexState *ls);
00057 static void expr (LexState *ls, expdesc *v);
00058 
00059 
00060 static void anchor_token (LexState *ls) {
00061   /* last token from outer function must be EOS */
00062   lua_assert(ls->fs != NULL || ls->t.token == TK_EOS);
00063   if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
00064     TString *ts = ls->t.seminfo.ts;
00065     luaX_newstring(ls, getstr(ts), ts->tsv.len);
00066   }
00067 }
00068 
00069 
00070 /* semantic error */
00071 static l_noret semerror (LexState *ls, const char *msg) {
00072   ls->t.token = 0;  /* remove 'near to' from final message */
00073   luaX_syntaxerror(ls, msg);
00074 }
00075 
00076 
00077 static l_noret error_expected (LexState *ls, int token) {
00078   luaX_syntaxerror(ls,
00079       luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
00080 }
00081 
00082 
00083 static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
00084   lua_State *L = fs->ls->L;
00085   const char *msg;
00086   int line = fs->f->linedefined;
00087   const char *where = (line == 0)
00088                       ? "main function"
00089                       : luaO_pushfstring(L, "function at line %d", line);
00090   msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
00091                              what, limit, where);
00092   luaX_syntaxerror(fs->ls, msg);
00093 }
00094 
00095 
00096 static void checklimit (FuncState *fs, int v, int l, const char *what) {
00097   if (v > l) errorlimit(fs, l, what);
00098 }
00099 
00100 
00101 static int testnext (LexState *ls, int c) {
00102   if (ls->t.token == c) {
00103     luaX_next(ls);
00104     return 1;
00105   }
00106   else return 0;
00107 }
00108 
00109 
00110 static void check (LexState *ls, int c) {
00111   if (ls->t.token != c)
00112     error_expected(ls, c);
00113 }
00114 
00115 
00116 static void checknext (LexState *ls, int c) {
00117   check(ls, c);
00118   luaX_next(ls);
00119 }
00120 
00121 
00122 #define check_condition(ls,c,msg)   { if (!(c)) luaX_syntaxerror(ls, msg); }
00123 
00124 
00125 
00126 static void check_match (LexState *ls, int what, int who, int where) {
00127   if (!testnext(ls, what)) {
00128     if (where == ls->linenumber)
00129       error_expected(ls, what);
00130     else {
00131       luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
00132              "%s expected (to close %s at line %d)",
00133               luaX_token2str(ls, what), luaX_token2str(ls, who), where));
00134     }
00135   }
00136 }
00137 
00138 
00139 static TString *str_checkname (LexState *ls) {
00140   TString *ts;
00141   check(ls, TK_NAME);
00142   ts = ls->t.seminfo.ts;
00143   luaX_next(ls);
00144   return ts;
00145 }
00146 
00147 
00148 static void init_exp (expdesc *e, expkind k, int i) {
00149   e->f = e->t = NO_JUMP;
00150   e->k = k;
00151   e->u.info = i;
00152 }
00153 
00154 
00155 static void codestring (LexState *ls, expdesc *e, TString *s) {
00156   init_exp(e, VK, luaK_stringK(ls->fs, s));
00157 }
00158 
00159 
00160 static void checkname (LexState *ls, expdesc *e) {
00161   codestring(ls, e, str_checkname(ls));
00162 }
00163 
00164 
00165 static int registerlocalvar (LexState *ls, TString *varname) {
00166   FuncState *fs = ls->fs;
00167   Proto *f = fs->f;
00168   int oldsize = f->sizelocvars;
00169   luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
00170                   LocVar, SHRT_MAX, "local variables");
00171   while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
00172   f->locvars[fs->nlocvars].varname = varname;
00173   luaC_objbarrier(ls->L, f, varname);
00174   return fs->nlocvars++;
00175 }
00176 
00177 
00178 static void new_localvar (LexState *ls, TString *name) {
00179   FuncState *fs = ls->fs;
00180   Dyndata *dyd = ls->dyd;
00181   int reg = registerlocalvar(ls, name);
00182   checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
00183                   MAXVARS, "local variables");
00184   luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,
00185                   dyd->actvar.size, Vardesc, MAX_INT, "local variables");
00186   dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg);
00187 }
00188 
00189 
00190 static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) {
00191   new_localvar(ls, luaX_newstring(ls, name, sz));
00192 }
00193 
00194 #define new_localvarliteral(ls,v) \
00195     new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1)
00196 
00197 
00198 static LocVar *getlocvar (FuncState *fs, int i) {
00199   int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
00200   lua_assert(idx < fs->nlocvars);
00201   return &fs->f->locvars[idx];
00202 }
00203 
00204 
00205 static void adjustlocalvars (LexState *ls, int nvars) {
00206   FuncState *fs = ls->fs;
00207   fs->nactvar = cast_byte(fs->nactvar + nvars);
00208   for (; nvars; nvars--) {
00209     getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;
00210   }
00211 }
00212 
00213 
00214 static void removevars (FuncState *fs, int tolevel) {
00215   fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
00216   while (fs->nactvar > tolevel)
00217     getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
00218 }
00219 
00220 
00221 static int searchupvalue (FuncState *fs, TString *name) {
00222   int i;
00223   Upvaldesc *up = fs->f->upvalues;
00224   for (i = 0; i < fs->nups; i++) {
00225     if (eqstr(up[i].name, name)) return i;
00226   }
00227   return -1;  /* not found */
00228 }
00229 
00230 
00231 static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
00232   Proto *f = fs->f;
00233   int oldsize = f->sizeupvalues;
00234   checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
00235   luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
00236                   Upvaldesc, MAXUPVAL, "upvalues");
00237   while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL;
00238   f->upvalues[fs->nups].instack = (v->k == VLOCAL);
00239   f->upvalues[fs->nups].idx = cast_byte(v->u.info);
00240   f->upvalues[fs->nups].name = name;
00241   luaC_objbarrier(fs->ls->L, f, name);
00242   return fs->nups++;
00243 }
00244 
00245 
00246 static int searchvar (FuncState *fs, TString *n) {
00247   int i;
00248   for (i=fs->nactvar-1; i >= 0; i--) {
00249     if (eqstr(n, getlocvar(fs, i)->varname))
00250       return i;
00251   }
00252   return -1;  /* not found */
00253 }
00254 
00255 
00256 /*
00257   Mark block where variable at given level was defined
00258   (to emit close instructions later).
00259 */
00260 static void markupval (FuncState *fs, int level) {
00261   BlockCnt *bl = fs->bl;
00262   while (bl->nactvar > level) bl = bl->previous;
00263   bl->upval = 1;
00264 }
00265 
00266 
00267 /*
00268   Find variable with given name 'n'. If it is an upvalue, add this
00269   upvalue into all intermediate functions.
00270 */
00271 static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
00272   if (fs == NULL)  /* no more levels? */
00273     return VVOID;  /* default is global */
00274   else {
00275     int v = searchvar(fs, n);  /* look up locals at current level */
00276     if (v >= 0) {  /* found? */
00277       init_exp(var, VLOCAL, v);  /* variable is local */
00278       if (!base)
00279         markupval(fs, v);  /* local will be used as an upval */
00280       return VLOCAL;
00281     }
00282     else {  /* not found as local at current level; try upvalues */
00283       int idx = searchupvalue(fs, n);  /* try existing upvalues */
00284       if (idx < 0) {  /* not found? */
00285         if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */
00286           return VVOID;  /* not found; is a global */
00287         /* else was LOCAL or UPVAL */
00288         idx  = newupvalue(fs, n, var);  /* will be a new upvalue */
00289       }
00290       init_exp(var, VUPVAL, idx);
00291       return VUPVAL;
00292     }
00293   }
00294 }
00295 
00296 
00297 static void singlevar (LexState *ls, expdesc *var) {
00298   TString *varname = str_checkname(ls);
00299   FuncState *fs = ls->fs;
00300   if (singlevaraux(fs, varname, var, 1) == VVOID) {  /* global name? */
00301     expdesc key;
00302     singlevaraux(fs, ls->envn, var, 1);  /* get environment variable */
00303     lua_assert(var->k == VLOCAL || var->k == VUPVAL);
00304     codestring(ls, &key, varname);  /* key is variable name */
00305     luaK_indexed(fs, var, &key);  /* env[varname] */
00306   }
00307 }
00308 
00309 
00310 static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
00311   FuncState *fs = ls->fs;
00312   int extra = nvars - nexps;
00313   if (hasmultret(e->k)) {
00314     extra++;  /* includes call itself */
00315     if (extra < 0) extra = 0;
00316     luaK_setreturns(fs, e, extra);  /* last exp. provides the difference */
00317     if (extra > 1) luaK_reserveregs(fs, extra-1);
00318   }
00319   else {
00320     if (e->k != VVOID) luaK_exp2nextreg(fs, e);  /* close last expression */
00321     if (extra > 0) {
00322       int reg = fs->freereg;
00323       luaK_reserveregs(fs, extra);
00324       luaK_nil(fs, reg, extra);
00325     }
00326   }
00327 }
00328 
00329 
00330 static void enterlevel (LexState *ls) {
00331   lua_State *L = ls->L;
00332   ++L->nCcalls;
00333   checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels");
00334 }
00335 
00336 
00337 #define leavelevel(ls)  ((ls)->L->nCcalls--)
00338 
00339 
00340 static void closegoto (LexState *ls, int g, Labeldesc *label) {
00341   int i;
00342   FuncState *fs = ls->fs;
00343   Labellist *gl = &ls->dyd->gt;
00344   Labeldesc *gt = &gl->arr[g];
00345   lua_assert(eqstr(gt->name, label->name));
00346   if (gt->nactvar < label->nactvar) {
00347     TString *vname = getlocvar(fs, gt->nactvar)->varname;
00348     const char *msg = luaO_pushfstring(ls->L,
00349       "<goto %s> at line %d jumps into the scope of local " LUA_QS,
00350       getstr(gt->name), gt->line, getstr(vname));
00351     semerror(ls, msg);
00352   }
00353   luaK_patchlist(fs, gt->pc, label->pc);
00354   /* remove goto from pending list */
00355   for (i = g; i < gl->n - 1; i++)
00356     gl->arr[i] = gl->arr[i + 1];
00357   gl->n--;
00358 }
00359 
00360 
00361 /*
00362 ** try to close a goto with existing labels; this solves backward jumps
00363 */
00364 static int findlabel (LexState *ls, int g) {
00365   int i;
00366   BlockCnt *bl = ls->fs->bl;
00367   Dyndata *dyd = ls->dyd;
00368   Labeldesc *gt = &dyd->gt.arr[g];
00369   /* check labels in current block for a match */
00370   for (i = bl->firstlabel; i < dyd->label.n; i++) {
00371     Labeldesc *lb = &dyd->label.arr[i];
00372     if (eqstr(lb->name, gt->name)) {  /* correct label? */
00373       if (gt->nactvar > lb->nactvar &&
00374           (bl->upval || dyd->label.n > bl->firstlabel))
00375         luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
00376       closegoto(ls, g, lb);  /* close it */
00377       return 1;
00378     }
00379   }
00380   return 0;  /* label not found; cannot close goto */
00381 }
00382 
00383 
00384 static int newlabelentry (LexState *ls, Labellist *l, TString *name,
00385                           int line, int pc) {
00386   int n = l->n;
00387   luaM_growvector(ls->L, l->arr, n, l->size,
00388                   Labeldesc, SHRT_MAX, "labels/gotos");
00389   l->arr[n].name = name;
00390   l->arr[n].line = line;
00391   l->arr[n].nactvar = ls->fs->nactvar;
00392   l->arr[n].pc = pc;
00393   l->n++;
00394   return n;
00395 }
00396 
00397 
00398 /*
00399 ** check whether new label 'lb' matches any pending gotos in current
00400 ** block; solves forward jumps
00401 */
00402 static void findgotos (LexState *ls, Labeldesc *lb) {
00403   Labellist *gl = &ls->dyd->gt;
00404   int i = ls->fs->bl->firstgoto;
00405   while (i < gl->n) {
00406     if (eqstr(gl->arr[i].name, lb->name))
00407       closegoto(ls, i, lb);
00408     else
00409       i++;
00410   }
00411 }
00412 
00413 
00414 /*
00415 ** "export" pending gotos to outer level, to check them against
00416 ** outer labels; if the block being exited has upvalues, and
00417 ** the goto exits the scope of any variable (which can be the
00418 ** upvalue), close those variables being exited.
00419 */
00420 static void movegotosout (FuncState *fs, BlockCnt *bl) {
00421   int i = bl->firstgoto;
00422   Labellist *gl = &fs->ls->dyd->gt;
00423   /* correct pending gotos to current block and try to close it
00424      with visible labels */
00425   while (i < gl->n) {
00426     Labeldesc *gt = &gl->arr[i];
00427     if (gt->nactvar > bl->nactvar) {
00428       if (bl->upval)
00429         luaK_patchclose(fs, gt->pc, bl->nactvar);
00430       gt->nactvar = bl->nactvar;
00431     }
00432     if (!findlabel(fs->ls, i))
00433       i++;  /* move to next one */
00434   }
00435 }
00436 
00437 
00438 static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
00439   bl->isloop = isloop;
00440   bl->nactvar = fs->nactvar;
00441   bl->firstlabel = fs->ls->dyd->label.n;
00442   bl->firstgoto = fs->ls->dyd->gt.n;
00443   bl->upval = 0;
00444   bl->previous = fs->bl;
00445   fs->bl = bl;
00446   lua_assert(fs->freereg == fs->nactvar);
00447 }
00448 
00449 
00450 /*
00451 ** create a label named "break" to resolve break statements
00452 */
00453 static void breaklabel (LexState *ls) {
00454   TString *n = luaS_new(ls->L, "break");
00455   int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);
00456   findgotos(ls, &ls->dyd->label.arr[l]);
00457 }
00458 
00459 /*
00460 ** generates an error for an undefined 'goto'; choose appropriate
00461 ** message when label name is a reserved word (which can only be 'break')
00462 */
00463 static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
00464   const char *msg = (gt->name->tsv.reserved > 0)
00465                     ? "<%s> at line %d not inside a loop"
00466                     : "no visible label " LUA_QS " for <goto> at line %d";
00467   msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
00468   semerror(ls, msg);
00469 }
00470 
00471 
00472 static void leaveblock (FuncState *fs) {
00473   BlockCnt *bl = fs->bl;
00474   LexState *ls = fs->ls;
00475   if (bl->previous && bl->upval) {
00476     /* create a 'jump to here' to close upvalues */
00477     int j = luaK_jump(fs);
00478     luaK_patchclose(fs, j, bl->nactvar);
00479     luaK_patchtohere(fs, j);
00480   }
00481   if (bl->isloop)
00482     breaklabel(ls);  /* close pending breaks */
00483   fs->bl = bl->previous;
00484   removevars(fs, bl->nactvar);
00485   lua_assert(bl->nactvar == fs->nactvar);
00486   fs->freereg = fs->nactvar;  /* free registers */
00487   ls->dyd->label.n = bl->firstlabel;  /* remove local labels */
00488   if (bl->previous)  /* inner block? */
00489     movegotosout(fs, bl);  /* update pending gotos to outer block */
00490   else if (bl->firstgoto < ls->dyd->gt.n)  /* pending gotos in outer block? */
00491     undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]);  /* error */
00492 }
00493 
00494 
00495 /*
00496 ** adds prototype being created into its parent list of prototypes
00497 ** and codes instruction to create new closure
00498 */
00499 static void codeclosure (LexState *ls, Proto *clp, expdesc *v) {
00500   FuncState *fs = ls->fs->prev;
00501   Proto *f = fs->f;  /* prototype of function creating new closure */
00502   if (fs->np >= f->sizep) {
00503     int oldsize = f->sizep;
00504     luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
00505                     MAXARG_Bx, "functions");
00506     while (oldsize < f->sizep) f->p[oldsize++] = NULL;
00507   }
00508   f->p[fs->np++] = clp;
00509   luaC_objbarrier(ls->L, f, clp);
00510   init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
00511   luaK_exp2nextreg(fs, v);  /* fix it at stack top (for GC) */
00512 }
00513 
00514 
00515 static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
00516   lua_State *L = ls->L;
00517   Proto *f;
00518   fs->prev = ls->fs;  /* linked list of funcstates */
00519   fs->ls = ls;
00520   ls->fs = fs;
00521   fs->pc = 0;
00522   fs->lasttarget = 0;
00523   fs->jpc = NO_JUMP;
00524   fs->freereg = 0;
00525   fs->nk = 0;
00526   fs->np = 0;
00527   fs->nups = 0;
00528   fs->nlocvars = 0;
00529   fs->nactvar = 0;
00530   fs->firstlocal = ls->dyd->actvar.n;
00531   fs->bl = NULL;
00532   f = luaF_newproto(L);
00533   fs->f = f;
00534   f->source = ls->source;
00535   f->maxstacksize = 2;  /* registers 0/1 are always valid */
00536   /* anchor prototype (to avoid being collected) */
00537   setptvalue2s(L, L->top, f);
00538   incr_top(L);
00539   fs->h = luaH_new(L);
00540   /* anchor table of constants (to avoid being collected) */
00541   sethvalue2s(L, L->top, fs->h);
00542   incr_top(L);
00543   enterblock(fs, bl, 0);
00544 }
00545 
00546 
00547 static void close_func (LexState *ls) {
00548   lua_State *L = ls->L;
00549   FuncState *fs = ls->fs;
00550   Proto *f = fs->f;
00551   luaK_ret(fs, 0, 0);  /* final return */
00552   leaveblock(fs);
00553   luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
00554   f->sizecode = fs->pc;
00555   luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
00556   f->sizelineinfo = fs->pc;
00557   luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
00558   f->sizek = fs->nk;
00559   luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
00560   f->sizep = fs->np;
00561   luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
00562   f->sizelocvars = fs->nlocvars;
00563   luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
00564   f->sizeupvalues = fs->nups;
00565   lua_assert(fs->bl == NULL);
00566   ls->fs = fs->prev;
00567   /* last token read was anchored in defunct function; must re-anchor it */
00568   anchor_token(ls);
00569   L->top--;  /* pop table of constants */
00570   luaC_checkGC(L);
00571   L->top--;  /* pop prototype (after possible collection) */
00572 }
00573 
00574 
00575 /*
00576 ** opens the main function, which is a regular vararg function with an
00577 ** upvalue named LUA_ENV
00578 */
00579 static void open_mainfunc (LexState *ls, FuncState *fs, BlockCnt *bl) {
00580   expdesc v;
00581   open_func(ls, fs, bl);
00582   fs->f->is_vararg = 1;  /* main function is always vararg */
00583   init_exp(&v, VLOCAL, 0);
00584   newupvalue(fs, ls->envn, &v);  /* create environment upvalue */
00585 }
00586 
00587 
00588 
00589 /*============================================================*/
00590 /* GRAMMAR RULES */
00591 /*============================================================*/
00592 
00593 
00594 /*
00595 ** check whether current token is in the follow set of a block.
00596 ** 'until' closes syntactical blocks, but do not close scope,
00597 ** so it handled in separate.
00598 */
00599 static int block_follow (LexState *ls, int withuntil) {
00600   switch (ls->t.token) {
00601     case TK_ELSE: case TK_ELSEIF:
00602     case TK_END: case TK_EOS:
00603       return 1;
00604     case TK_UNTIL: return withuntil;
00605     default: return 0;
00606   }
00607 }
00608 
00609 
00610 static void statlist (LexState *ls) {
00611   /* statlist -> { stat [`;'] } */
00612   while (!block_follow(ls, 1)) {
00613     if (ls->t.token == TK_RETURN) {
00614       statement(ls);
00615       return;  /* 'return' must be last statement */
00616     }
00617     statement(ls);
00618   }
00619 }
00620 
00621 
00622 static void fieldsel (LexState *ls, expdesc *v) {
00623   /* fieldsel -> ['.' | ':'] NAME */
00624   FuncState *fs = ls->fs;
00625   expdesc key;
00626   luaK_exp2anyregup(fs, v);
00627   luaX_next(ls);  /* skip the dot or colon */
00628   checkname(ls, &key);
00629   luaK_indexed(fs, v, &key);
00630 }
00631 
00632 
00633 static void yindex (LexState *ls, expdesc *v) {
00634   /* index -> '[' expr ']' */
00635   luaX_next(ls);  /* skip the '[' */
00636   expr(ls, v);
00637   luaK_exp2val(ls->fs, v);
00638   checknext(ls, ']');
00639 }
00640 
00641 
00642 /*
00643 ** {======================================================================
00644 ** Rules for Constructors
00645 ** =======================================================================
00646 */
00647 
00648 
00649 struct ConsControl {
00650   expdesc v;  /* last list item read */
00651   expdesc *t;  /* table descriptor */
00652   int nh;  /* total number of `record' elements */
00653   int na;  /* total number of array elements */
00654   int tostore;  /* number of array elements pending to be stored */
00655 };
00656 
00657 
00658 static void recfield (LexState *ls, struct ConsControl *cc) {
00659   /* recfield -> (NAME | `['exp1`]') = exp1 */
00660   FuncState *fs = ls->fs;
00661   int reg = ls->fs->freereg;
00662   expdesc key, val;
00663   int rkkey;
00664   if (ls->t.token == TK_NAME) {
00665     checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
00666     checkname(ls, &key);
00667   }
00668   else  /* ls->t.token == '[' */
00669     yindex(ls, &key);
00670   cc->nh++;
00671   checknext(ls, '=');
00672   rkkey = luaK_exp2RK(fs, &key);
00673   expr(ls, &val);
00674   luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val));
00675   fs->freereg = reg;  /* free registers */
00676 }
00677 
00678 
00679 static void closelistfield (FuncState *fs, struct ConsControl *cc) {
00680   if (cc->v.k == VVOID) return;  /* there is no list item */
00681   luaK_exp2nextreg(fs, &cc->v);
00682   cc->v.k = VVOID;
00683   if (cc->tostore == LFIELDS_PER_FLUSH) {
00684     luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);  /* flush */
00685     cc->tostore = 0;  /* no more items pending */
00686   }
00687 }
00688 
00689 
00690 static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
00691   if (cc->tostore == 0) return;
00692   if (hasmultret(cc->v.k)) {
00693     luaK_setmultret(fs, &cc->v);
00694     luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
00695     cc->na--;  /* do not count last expression (unknown number of elements) */
00696   }
00697   else {
00698     if (cc->v.k != VVOID)
00699       luaK_exp2nextreg(fs, &cc->v);
00700     luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
00701   }
00702 }
00703 
00704 
00705 static void listfield (LexState *ls, struct ConsControl *cc) {
00706   /* listfield -> exp */
00707   expr(ls, &cc->v);
00708   checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
00709   cc->na++;
00710   cc->tostore++;
00711 }
00712 
00713 
00714 static void field (LexState *ls, struct ConsControl *cc) {
00715   /* field -> listfield | recfield */
00716   switch(ls->t.token) {
00717     case TK_NAME: {  /* may be 'listfield' or 'recfield' */
00718       if (luaX_lookahead(ls) != '=')  /* expression? */
00719         listfield(ls, cc);
00720       else
00721         recfield(ls, cc);
00722       break;
00723     }
00724     case '[': {
00725       recfield(ls, cc);
00726       break;
00727     }
00728     default: {
00729       listfield(ls, cc);
00730       break;
00731     }
00732   }
00733 }
00734 
00735 
00736 static void constructor (LexState *ls, expdesc *t) {
00737   /* constructor -> '{' [ field { sep field } [sep] ] '}'
00738      sep -> ',' | ';' */
00739   FuncState *fs = ls->fs;
00740   int line = ls->linenumber;
00741   int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
00742   struct ConsControl cc;
00743   cc.na = cc.nh = cc.tostore = 0;
00744   cc.t = t;
00745   init_exp(t, VRELOCABLE, pc);
00746   init_exp(&cc.v, VVOID, 0);  /* no value (yet) */
00747   luaK_exp2nextreg(ls->fs, t);  /* fix it at stack top */
00748   checknext(ls, '{');
00749   do {
00750     lua_assert(cc.v.k == VVOID || cc.tostore > 0);
00751     if (ls->t.token == '}') break;
00752     closelistfield(fs, &cc);
00753     field(ls, &cc);
00754   } while (testnext(ls, ',') || testnext(ls, ';'));
00755   check_match(ls, '}', '{', line);
00756   lastlistfield(fs, &cc);
00757   SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
00758   SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh));  /* set initial table size */
00759 }
00760 
00761 /* }====================================================================== */
00762 
00763 
00764 
00765 static void parlist (LexState *ls) {
00766   /* parlist -> [ param { `,' param } ] */
00767   FuncState *fs = ls->fs;
00768   Proto *f = fs->f;
00769   int nparams = 0;
00770   f->is_vararg = 0;
00771   if (ls->t.token != ')') {  /* is `parlist' not empty? */
00772     do {
00773       switch (ls->t.token) {
00774         case TK_NAME: {  /* param -> NAME */
00775           new_localvar(ls, str_checkname(ls));
00776           nparams++;
00777           break;
00778         }
00779         case TK_DOTS: {  /* param -> `...' */
00780           luaX_next(ls);
00781           f->is_vararg = 1;
00782           break;
00783         }
00784         default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
00785       }
00786     } while (!f->is_vararg && testnext(ls, ','));
00787   }
00788   adjustlocalvars(ls, nparams);
00789   f->numparams = cast_byte(fs->nactvar);
00790   luaK_reserveregs(fs, fs->nactvar);  /* reserve register for parameters */
00791 }
00792 
00793 
00794 static void body (LexState *ls, expdesc *e, int ismethod, int line) {
00795   /* body ->  `(' parlist `)' block END */
00796   FuncState new_fs;
00797   BlockCnt bl;
00798   open_func(ls, &new_fs, &bl);
00799   new_fs.f->linedefined = line;
00800   checknext(ls, '(');
00801   if (ismethod) {
00802     new_localvarliteral(ls, "self");  /* create 'self' parameter */
00803     adjustlocalvars(ls, 1);
00804   }
00805   parlist(ls);
00806   checknext(ls, ')');
00807   statlist(ls);
00808   new_fs.f->lastlinedefined = ls->linenumber;
00809   check_match(ls, TK_END, TK_FUNCTION, line);
00810   codeclosure(ls, new_fs.f, e);
00811   close_func(ls);
00812 }
00813 
00814 
00815 static int explist (LexState *ls, expdesc *v) {
00816   /* explist -> expr { `,' expr } */
00817   int n = 1;  /* at least one expression */
00818   expr(ls, v);
00819   while (testnext(ls, ',')) {
00820     luaK_exp2nextreg(ls->fs, v);
00821     expr(ls, v);
00822     n++;
00823   }
00824   return n;
00825 }
00826 
00827 
00828 static void funcargs (LexState *ls, expdesc *f, int line) {
00829   FuncState *fs = ls->fs;
00830   expdesc args;
00831   int base, nparams;
00832   switch (ls->t.token) {
00833     case '(': {  /* funcargs -> `(' [ explist ] `)' */
00834       luaX_next(ls);
00835       if (ls->t.token == ')')  /* arg list is empty? */
00836         args.k = VVOID;
00837       else {
00838         explist(ls, &args);
00839         luaK_setmultret(fs, &args);
00840       }
00841       check_match(ls, ')', '(', line);
00842       break;
00843     }
00844     case '{': {  /* funcargs -> constructor */
00845       constructor(ls, &args);
00846       break;
00847     }
00848     case TK_STRING: {  /* funcargs -> STRING */
00849       codestring(ls, &args, ls->t.seminfo.ts);
00850       luaX_next(ls);  /* must use `seminfo' before `next' */
00851       break;
00852     }
00853     default: {
00854       luaX_syntaxerror(ls, "function arguments expected");
00855     }
00856   }
00857   lua_assert(f->k == VNONRELOC);
00858   base = f->u.info;  /* base register for call */
00859   if (hasmultret(args.k))
00860     nparams = LUA_MULTRET;  /* open call */
00861   else {
00862     if (args.k != VVOID)
00863       luaK_exp2nextreg(fs, &args);  /* close last argument */
00864     nparams = fs->freereg - (base+1);
00865   }
00866   init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
00867   luaK_fixline(fs, line);
00868   fs->freereg = base+1;  /* call remove function and arguments and leaves
00869                             (unless changed) one result */
00870 }
00871 
00872 
00873 
00874 
00875 /*
00876 ** {======================================================================
00877 ** Expression parsing
00878 ** =======================================================================
00879 */
00880 
00881 
00882 static void prefixexp (LexState *ls, expdesc *v) {
00883   /* prefixexp -> NAME | '(' expr ')' */
00884   switch (ls->t.token) {
00885     case '(': {
00886       int line = ls->linenumber;
00887       luaX_next(ls);
00888       expr(ls, v);
00889       check_match(ls, ')', '(', line);
00890       luaK_dischargevars(ls->fs, v);
00891       return;
00892     }
00893     case TK_NAME: {
00894       singlevar(ls, v);
00895       return;
00896     }
00897     default: {
00898       luaX_syntaxerror(ls, "unexpected symbol");
00899     }
00900   }
00901 }
00902 
00903 
00904 static void primaryexp (LexState *ls, expdesc *v) {
00905   /* primaryexp ->
00906         prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
00907   FuncState *fs = ls->fs;
00908   int line = ls->linenumber;
00909   prefixexp(ls, v);
00910   for (;;) {
00911     switch (ls->t.token) {
00912       case '.': {  /* fieldsel */
00913         fieldsel(ls, v);
00914         break;
00915       }
00916       case '[': {  /* `[' exp1 `]' */
00917         expdesc key;
00918         luaK_exp2anyregup(fs, v);
00919         yindex(ls, &key);
00920         luaK_indexed(fs, v, &key);
00921         break;
00922       }
00923       case ':': {  /* `:' NAME funcargs */
00924         expdesc key;
00925         luaX_next(ls);
00926         checkname(ls, &key);
00927         luaK_self(fs, v, &key);
00928         funcargs(ls, v, line);
00929         break;
00930       }
00931       case '(': case TK_STRING: case '{': {  /* funcargs */
00932         luaK_exp2nextreg(fs, v);
00933         funcargs(ls, v, line);
00934         break;
00935       }
00936       default: return;
00937     }
00938   }
00939 }
00940 
00941 
00942 static void simpleexp (LexState *ls, expdesc *v) {
00943   /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
00944                   constructor | FUNCTION body | primaryexp */
00945   switch (ls->t.token) {
00946     case TK_NUMBER: {
00947       init_exp(v, VKNUM, 0);
00948       v->u.nval = ls->t.seminfo.r;
00949       break;
00950     }
00951     case TK_STRING: {
00952       codestring(ls, v, ls->t.seminfo.ts);
00953       break;
00954     }
00955     case TK_NIL: {
00956       init_exp(v, VNIL, 0);
00957       break;
00958     }
00959     case TK_TRUE: {
00960       init_exp(v, VTRUE, 0);
00961       break;
00962     }
00963     case TK_FALSE: {
00964       init_exp(v, VFALSE, 0);
00965       break;
00966     }
00967     case TK_DOTS: {  /* vararg */
00968       FuncState *fs = ls->fs;
00969       check_condition(ls, fs->f->is_vararg,
00970                       "cannot use " LUA_QL("...") " outside a vararg function");
00971       init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
00972       break;
00973     }
00974     case '{': {  /* constructor */
00975       constructor(ls, v);
00976       return;
00977     }
00978     case TK_FUNCTION: {
00979       luaX_next(ls);
00980       body(ls, v, 0, ls->linenumber);
00981       return;
00982     }
00983     default: {
00984       primaryexp(ls, v);
00985       return;
00986     }
00987   }
00988   luaX_next(ls);
00989 }
00990 
00991 
00992 static UnOpr getunopr (int op) {
00993   switch (op) {
00994     case TK_NOT: return OPR_NOT;
00995     case '-': return OPR_MINUS;
00996     case '#': return OPR_LEN;
00997     default: return OPR_NOUNOPR;
00998   }
00999 }
01000 
01001 
01002 static BinOpr getbinopr (int op) {
01003   switch (op) {
01004     case '+': return OPR_ADD;
01005     case '-': return OPR_SUB;
01006     case '*': return OPR_MUL;
01007     case '/': return OPR_DIV;
01008     case '%': return OPR_MOD;
01009     case '^': return OPR_POW;
01010     case TK_CONCAT: return OPR_CONCAT;
01011     case TK_NE: return OPR_NE;
01012     case TK_EQ: return OPR_EQ;
01013     case '<': return OPR_LT;
01014     case TK_LE: return OPR_LE;
01015     case '>': return OPR_GT;
01016     case TK_GE: return OPR_GE;
01017     case TK_AND: return OPR_AND;
01018     case TK_OR: return OPR_OR;
01019     default: return OPR_NOBINOPR;
01020   }
01021 }
01022 
01023 
01024 static const struct {
01025   lu_byte left;  /* left priority for each binary operator */
01026   lu_byte right; /* right priority */
01027 } priority[] = {  /* ORDER OPR */
01028    {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7},  /* `+' `-' `*' `/' `%' */
01029    {10, 9}, {5, 4},                 /* ^, .. (right associative) */
01030    {3, 3}, {3, 3}, {3, 3},          /* ==, <, <= */
01031    {3, 3}, {3, 3}, {3, 3},          /* ~=, >, >= */
01032    {2, 2}, {1, 1}                   /* and, or */
01033 };
01034 
01035 #define UNARY_PRIORITY  8  /* priority for unary operators */
01036 
01037 
01038 /*
01039 ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
01040 ** where `binop' is any binary operator with a priority higher than `limit'
01041 */
01042 static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
01043   BinOpr op;
01044   UnOpr uop;
01045   enterlevel(ls);
01046   uop = getunopr(ls->t.token);
01047   if (uop != OPR_NOUNOPR) {
01048     int line = ls->linenumber;
01049     luaX_next(ls);
01050     subexpr(ls, v, UNARY_PRIORITY);
01051     luaK_prefix(ls->fs, uop, v, line);
01052   }
01053   else simpleexp(ls, v);
01054   /* expand while operators have priorities higher than `limit' */
01055   op = getbinopr(ls->t.token);
01056   while (op != OPR_NOBINOPR && priority[op].left > limit) {
01057     expdesc v2;
01058     BinOpr nextop;
01059     int line = ls->linenumber;
01060     luaX_next(ls);
01061     luaK_infix(ls->fs, op, v);
01062     /* read sub-expression with higher priority */
01063     nextop = subexpr(ls, &v2, priority[op].right);
01064     luaK_posfix(ls->fs, op, v, &v2, line);
01065     op = nextop;
01066   }
01067   leavelevel(ls);
01068   return op;  /* return first untreated operator */
01069 }
01070 
01071 
01072 static void expr (LexState *ls, expdesc *v) {
01073   subexpr(ls, v, 0);
01074 }
01075 
01076 /* }==================================================================== */
01077 
01078 
01079 
01080 /*
01081 ** {======================================================================
01082 ** Rules for Statements
01083 ** =======================================================================
01084 */
01085 
01086 
01087 static void block (LexState *ls) {
01088   /* block -> statlist */
01089   FuncState *fs = ls->fs;
01090   BlockCnt bl;
01091   enterblock(fs, &bl, 0);
01092   statlist(ls);
01093   leaveblock(fs);
01094 }
01095 
01096 
01097 /*
01098 ** structure to chain all variables in the left-hand side of an
01099 ** assignment
01100 */
01101 struct LHS_assign {
01102   struct LHS_assign *prev;
01103   expdesc v;  /* variable (global, local, upvalue, or indexed) */
01104 };
01105 
01106 
01107 /*
01108 ** check whether, in an assignment to an upvalue/local variable, the
01109 ** upvalue/local variable is begin used in a previous assignment to a
01110 ** table. If so, save original upvalue/local value in a safe place and
01111 ** use this safe copy in the previous assignment.
01112 */
01113 static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
01114   FuncState *fs = ls->fs;
01115   int extra = fs->freereg;  /* eventual position to save local variable */
01116   int conflict = 0;
01117   for (; lh; lh = lh->prev) {  /* check all previous assignments */
01118     if (lh->v.k == VINDEXED) {  /* assigning to a table? */
01119       /* table is the upvalue/local being assigned now? */
01120       if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {
01121         conflict = 1;
01122         lh->v.u.ind.vt = VLOCAL;
01123         lh->v.u.ind.t = extra;  /* previous assignment will use safe copy */
01124       }
01125       /* index is the local being assigned? (index cannot be upvalue) */
01126       if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {
01127         conflict = 1;
01128         lh->v.u.ind.idx = extra;  /* previous assignment will use safe copy */
01129       }
01130     }
01131   }
01132   if (conflict) {
01133     /* copy upvalue/local value to a temporary (in position 'extra') */
01134     OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
01135     luaK_codeABC(fs, op, extra, v->u.info, 0);
01136     luaK_reserveregs(fs, 1);
01137   }
01138 }
01139 
01140 
01141 static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
01142   expdesc e;
01143   check_condition(ls, vkisvar(lh->v.k), "syntax error");
01144   if (testnext(ls, ',')) {  /* assignment -> `,' primaryexp assignment */
01145     struct LHS_assign nv;
01146     nv.prev = lh;
01147     primaryexp(ls, &nv.v);
01148     if (nv.v.k != VINDEXED)
01149       check_conflict(ls, lh, &nv.v);
01150     checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,
01151                     "C levels");
01152     assignment(ls, &nv, nvars+1);
01153   }
01154   else {  /* assignment -> `=' explist */
01155     int nexps;
01156     checknext(ls, '=');
01157     nexps = explist(ls, &e);
01158     if (nexps != nvars) {
01159       adjust_assign(ls, nvars, nexps, &e);
01160       if (nexps > nvars)
01161         ls->fs->freereg -= nexps - nvars;  /* remove extra values */
01162     }
01163     else {
01164       luaK_setoneret(ls->fs, &e);  /* close last expression */
01165       luaK_storevar(ls->fs, &lh->v, &e);
01166       return;  /* avoid default */
01167     }
01168   }
01169   init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */
01170   luaK_storevar(ls->fs, &lh->v, &e);
01171 }
01172 
01173 
01174 static int cond (LexState *ls) {
01175   /* cond -> exp */
01176   expdesc v;
01177   expr(ls, &v);  /* read condition */
01178   if (v.k == VNIL) v.k = VFALSE;  /* `falses' are all equal here */
01179   luaK_goiftrue(ls->fs, &v);
01180   return v.f;
01181 }
01182 
01183 
01184 static void gotostat (LexState *ls, int pc) {
01185   int line = ls->linenumber;
01186   TString *label;
01187   int g;
01188   if (testnext(ls, TK_GOTO))
01189     label = str_checkname(ls);
01190   else {
01191     luaX_next(ls);  /* skip break */
01192     label = luaS_new(ls->L, "break");
01193   }
01194   g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);
01195   findlabel(ls, g);  /* close it if label already defined */
01196 }
01197 
01198 
01199 /* check for repeated labels on the same block */
01200 static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
01201   int i;
01202   for (i = fs->bl->firstlabel; i < ll->n; i++) {
01203     if (eqstr(label, ll->arr[i].name)) {
01204       const char *msg = luaO_pushfstring(fs->ls->L,
01205                           "label " LUA_QS " already defined on line %d",
01206                           getstr(label), ll->arr[i].line);
01207       semerror(fs->ls, msg);
01208     }
01209   }
01210 }
01211 
01212 
01213 static void labelstat (LexState *ls, TString *label, int line) {
01214   /* label -> '::' NAME '::' */
01215   FuncState *fs = ls->fs;
01216   Labellist *ll = &ls->dyd->label;
01217   int l;  /* index of new label being created */
01218   checkrepeated(fs, ll, label);  /* check for repeated labels */
01219   checknext(ls, TK_DBCOLON);  /* skip double colon */
01220   /* create new entry for this label */
01221   l = newlabelentry(ls, ll, label, line, fs->pc);
01222   /* skip other no-op statements */
01223   while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
01224     statement(ls);
01225   if (block_follow(ls, 0)) {  /* label is last no-op statement in the block? */
01226     /* assume that locals are already out of scope */
01227     ll->arr[l].nactvar = fs->bl->nactvar;
01228   }
01229   findgotos(ls, &ll->arr[l]);
01230 }
01231 
01232 
01233 static void whilestat (LexState *ls, int line) {
01234   /* whilestat -> WHILE cond DO block END */
01235   FuncState *fs = ls->fs;
01236   int whileinit;
01237   int condexit;
01238   BlockCnt bl;
01239   luaX_next(ls);  /* skip WHILE */
01240   whileinit = luaK_getlabel(fs);
01241   condexit = cond(ls);
01242   enterblock(fs, &bl, 1);
01243   checknext(ls, TK_DO);
01244   block(ls);
01245   luaK_jumpto(fs, whileinit);
01246   check_match(ls, TK_END, TK_WHILE, line);
01247   leaveblock(fs);
01248   luaK_patchtohere(fs, condexit);  /* false conditions finish the loop */
01249 }
01250 
01251 
01252 static void repeatstat (LexState *ls, int line) {
01253   /* repeatstat -> REPEAT block UNTIL cond */
01254   int condexit;
01255   FuncState *fs = ls->fs;
01256   int repeat_init = luaK_getlabel(fs);
01257   BlockCnt bl1, bl2;
01258   enterblock(fs, &bl1, 1);  /* loop block */
01259   enterblock(fs, &bl2, 0);  /* scope block */
01260   luaX_next(ls);  /* skip REPEAT */
01261   statlist(ls);
01262   check_match(ls, TK_UNTIL, TK_REPEAT, line);
01263   condexit = cond(ls);  /* read condition (inside scope block) */
01264   if (bl2.upval)  /* upvalues? */
01265     luaK_patchclose(fs, condexit, bl2.nactvar);
01266   leaveblock(fs);  /* finish scope */
01267   luaK_patchlist(fs, condexit, repeat_init);  /* close the loop */
01268   leaveblock(fs);  /* finish loop */
01269 }
01270 
01271 
01272 static int exp1 (LexState *ls) {
01273   expdesc e;
01274   int reg;
01275   expr(ls, &e);
01276   luaK_exp2nextreg(ls->fs, &e);
01277   lua_assert(e.k == VNONRELOC);
01278   reg = e.u.info;
01279   return reg;
01280 }
01281 
01282 
01283 static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
01284   /* forbody -> DO block */
01285   BlockCnt bl;
01286   FuncState *fs = ls->fs;
01287   int prep, endfor;
01288   adjustlocalvars(ls, 3);  /* control variables */
01289   checknext(ls, TK_DO);
01290   prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
01291   enterblock(fs, &bl, 0);  /* scope for declared variables */
01292   adjustlocalvars(ls, nvars);
01293   luaK_reserveregs(fs, nvars);
01294   block(ls);
01295   leaveblock(fs);  /* end of scope for declared variables */
01296   luaK_patchtohere(fs, prep);
01297   if (isnum)  /* numeric for? */
01298     endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
01299   else {  /* generic for */
01300     luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
01301     luaK_fixline(fs, line);
01302     endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
01303   }
01304   luaK_patchlist(fs, endfor, prep + 1);
01305   luaK_fixline(fs, line);
01306 }
01307 
01308 
01309 static void fornum (LexState *ls, TString *varname, int line) {
01310   /* fornum -> NAME = exp1,exp1[,exp1] forbody */
01311   FuncState *fs = ls->fs;
01312   int base = fs->freereg;
01313   new_localvarliteral(ls, "(for index)");
01314   new_localvarliteral(ls, "(for limit)");
01315   new_localvarliteral(ls, "(for step)");
01316   new_localvar(ls, varname);
01317   checknext(ls, '=');
01318   exp1(ls);  /* initial value */
01319   checknext(ls, ',');
01320   exp1(ls);  /* limit */
01321   if (testnext(ls, ','))
01322     exp1(ls);  /* optional step */
01323   else {  /* default step = 1 */
01324     luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1));
01325     luaK_reserveregs(fs, 1);
01326   }
01327   forbody(ls, base, line, 1, 1);
01328 }
01329 
01330 
01331 static void forlist (LexState *ls, TString *indexname) {
01332   /* forlist -> NAME {,NAME} IN explist forbody */
01333   FuncState *fs = ls->fs;
01334   expdesc e;
01335   int nvars = 4;  /* gen, state, control, plus at least one declared var */
01336   int line;
01337   int base = fs->freereg;
01338   /* create control variables */
01339   new_localvarliteral(ls, "(for generator)");
01340   new_localvarliteral(ls, "(for state)");
01341   new_localvarliteral(ls, "(for control)");
01342   /* create declared variables */
01343   new_localvar(ls, indexname);
01344   while (testnext(ls, ',')) {
01345     new_localvar(ls, str_checkname(ls));
01346     nvars++;
01347   }
01348   checknext(ls, TK_IN);
01349   line = ls->linenumber;
01350   adjust_assign(ls, 3, explist(ls, &e), &e);
01351   luaK_checkstack(fs, 3);  /* extra space to call generator */
01352   forbody(ls, base, line, nvars - 3, 0);
01353 }
01354 
01355 
01356 static void forstat (LexState *ls, int line) {
01357   /* forstat -> FOR (fornum | forlist) END */
01358   FuncState *fs = ls->fs;
01359   TString *varname;
01360   BlockCnt bl;
01361   enterblock(fs, &bl, 1);  /* scope for loop and control variables */
01362   luaX_next(ls);  /* skip `for' */
01363   varname = str_checkname(ls);  /* first variable name */
01364   switch (ls->t.token) {
01365     case '=': fornum(ls, varname, line); break;
01366     case ',': case TK_IN: forlist(ls, varname); break;
01367     default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
01368   }
01369   check_match(ls, TK_END, TK_FOR, line);
01370   leaveblock(fs);  /* loop scope (`break' jumps to this point) */
01371 }
01372 
01373 
01374 static void test_then_block (LexState *ls, int *escapelist) {
01375   /* test_then_block -> [IF | ELSEIF] cond THEN block */
01376   BlockCnt bl;
01377   FuncState *fs = ls->fs;
01378   expdesc v;
01379   int jf;  /* instruction to skip 'then' code (if condition is false) */
01380   luaX_next(ls);  /* skip IF or ELSEIF */
01381   expr(ls, &v);  /* read condition */
01382   checknext(ls, TK_THEN);
01383   if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
01384     luaK_goiffalse(ls->fs, &v);  /* will jump to label if condition is true */
01385     enterblock(fs, &bl, 0);  /* must enter block before 'goto' */
01386     gotostat(ls, v.t);  /* handle goto/break */
01387     if (block_follow(ls, 0)) {  /* 'goto' is the entire block? */
01388       leaveblock(fs);
01389       return;  /* and that is it */
01390     }
01391     else  /* must skip over 'then' part if condition is false */
01392       jf = luaK_jump(fs);
01393   }
01394   else {  /* regular case (not goto/break) */
01395     luaK_goiftrue(ls->fs, &v);  /* skip over block if condition is false */
01396     enterblock(fs, &bl, 0);
01397     jf = v.f;
01398   }
01399   statlist(ls);  /* `then' part */
01400   leaveblock(fs);
01401   if (ls->t.token == TK_ELSE ||
01402       ls->t.token == TK_ELSEIF)  /* followed by 'else'/'elseif'? */
01403     luaK_concat(fs, escapelist, luaK_jump(fs));  /* must jump over it */
01404   luaK_patchtohere(fs, jf);
01405 }
01406 
01407 
01408 static void ifstat (LexState *ls, int line) {
01409   /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
01410   FuncState *fs = ls->fs;
01411   int escapelist = NO_JUMP;  /* exit list for finished parts */
01412   test_then_block(ls, &escapelist);  /* IF cond THEN block */
01413   while (ls->t.token == TK_ELSEIF)
01414     test_then_block(ls, &escapelist);  /* ELSEIF cond THEN block */
01415   if (testnext(ls, TK_ELSE))
01416     block(ls);  /* `else' part */
01417   check_match(ls, TK_END, TK_IF, line);
01418   luaK_patchtohere(fs, escapelist);  /* patch escape list to 'if' end */
01419 }
01420 
01421 
01422 static void localfunc (LexState *ls) {
01423   expdesc b;
01424   FuncState *fs = ls->fs;
01425   new_localvar(ls, str_checkname(ls));  /* new local variable */
01426   adjustlocalvars(ls, 1);  /* enter its scope */
01427   body(ls, &b, 0, ls->linenumber);  /* function created in next register */
01428   /* debug information will only see the variable after this point! */
01429   getlocvar(fs, b.u.info)->startpc = fs->pc;
01430 }
01431 
01432 
01433 static void localstat (LexState *ls) {
01434   /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
01435   int nvars = 0;
01436   int nexps;
01437   expdesc e;
01438   do {
01439     new_localvar(ls, str_checkname(ls));
01440     nvars++;
01441   } while (testnext(ls, ','));
01442   if (testnext(ls, '='))
01443     nexps = explist(ls, &e);
01444   else {
01445     e.k = VVOID;
01446     nexps = 0;
01447   }
01448   adjust_assign(ls, nvars, nexps, &e);
01449   adjustlocalvars(ls, nvars);
01450 }
01451 
01452 
01453 static int funcname (LexState *ls, expdesc *v) {
01454   /* funcname -> NAME {fieldsel} [`:' NAME] */
01455   int ismethod = 0;
01456   singlevar(ls, v);
01457   while (ls->t.token == '.')
01458     fieldsel(ls, v);
01459   if (ls->t.token == ':') {
01460     ismethod = 1;
01461     fieldsel(ls, v);
01462   }
01463   return ismethod;
01464 }
01465 
01466 
01467 static void funcstat (LexState *ls, int line) {
01468   /* funcstat -> FUNCTION funcname body */
01469   int ismethod;
01470   expdesc v, b;
01471   luaX_next(ls);  /* skip FUNCTION */
01472   ismethod = funcname(ls, &v);
01473   body(ls, &b, ismethod, line);
01474   luaK_storevar(ls->fs, &v, &b);
01475   luaK_fixline(ls->fs, line);  /* definition `happens' in the first line */
01476 }
01477 
01478 
01479 static void exprstat (LexState *ls) {
01480   /* stat -> func | assignment */
01481   FuncState *fs = ls->fs;
01482   struct LHS_assign v;
01483   primaryexp(ls, &v.v);
01484   if (v.v.k == VCALL)  /* stat -> func */
01485     SETARG_C(getcode(fs, &v.v), 1);  /* call statement uses no results */
01486   else {  /* stat -> assignment */
01487     v.prev = NULL;
01488     assignment(ls, &v, 1);
01489   }
01490 }
01491 
01492 
01493 static void retstat (LexState *ls) {
01494   /* stat -> RETURN [explist] [';'] */
01495   FuncState *fs = ls->fs;
01496   expdesc e;
01497   int first, nret;  /* registers with returned values */
01498   if (block_follow(ls, 1) || ls->t.token == ';')
01499     first = nret = 0;  /* return no values */
01500   else {
01501     nret = explist(ls, &e);  /* optional return values */
01502     if (hasmultret(e.k)) {
01503       luaK_setmultret(fs, &e);
01504       if (e.k == VCALL && nret == 1) {  /* tail call? */
01505         SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
01506         lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
01507       }
01508       first = fs->nactvar;
01509       nret = LUA_MULTRET;  /* return all values */
01510     }
01511     else {
01512       if (nret == 1)  /* only one single value? */
01513         first = luaK_exp2anyreg(fs, &e);
01514       else {
01515         luaK_exp2nextreg(fs, &e);  /* values must go to the `stack' */
01516         first = fs->nactvar;  /* return all `active' values */
01517         lua_assert(nret == fs->freereg - first);
01518       }
01519     }
01520   }
01521   luaK_ret(fs, first, nret);
01522   testnext(ls, ';');  /* skip optional semicolon */
01523 }
01524 
01525 
01526 static void statement (LexState *ls) {
01527   int line = ls->linenumber;  /* may be needed for error messages */
01528   enterlevel(ls);
01529   switch (ls->t.token) {
01530     case ';': {  /* stat -> ';' (empty statement) */
01531       luaX_next(ls);  /* skip ';' */
01532       break;
01533     }
01534     case TK_IF: {  /* stat -> ifstat */
01535       ifstat(ls, line);
01536       break;
01537     }
01538     case TK_WHILE: {  /* stat -> whilestat */
01539       whilestat(ls, line);
01540       break;
01541     }
01542     case TK_DO: {  /* stat -> DO block END */
01543       luaX_next(ls);  /* skip DO */
01544       block(ls);
01545       check_match(ls, TK_END, TK_DO, line);
01546       break;
01547     }
01548     case TK_FOR: {  /* stat -> forstat */
01549       forstat(ls, line);
01550       break;
01551     }
01552     case TK_REPEAT: {  /* stat -> repeatstat */
01553       repeatstat(ls, line);
01554       break;
01555     }
01556     case TK_FUNCTION: {  /* stat -> funcstat */
01557       funcstat(ls, line);
01558       break;
01559     }
01560     case TK_LOCAL: {  /* stat -> localstat */
01561       luaX_next(ls);  /* skip LOCAL */
01562       if (testnext(ls, TK_FUNCTION))  /* local function? */
01563         localfunc(ls);
01564       else
01565         localstat(ls);
01566       break;
01567     }
01568     case TK_DBCOLON: {  /* stat -> label */
01569       luaX_next(ls);  /* skip double colon */
01570       labelstat(ls, str_checkname(ls), line);
01571       break;
01572     }
01573     case TK_RETURN: {  /* stat -> retstat */
01574       luaX_next(ls);  /* skip RETURN */
01575       retstat(ls);
01576       break;
01577     }
01578     case TK_BREAK:   /* stat -> breakstat */
01579     case TK_GOTO: {  /* stat -> 'goto' NAME */
01580       gotostat(ls, luaK_jump(ls->fs));
01581       break;
01582     }
01583     default: {  /* stat -> func | assignment */
01584       exprstat(ls);
01585       break;
01586     }
01587   }
01588   lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
01589              ls->fs->freereg >= ls->fs->nactvar);
01590   ls->fs->freereg = ls->fs->nactvar;  /* free registers */
01591   leavelevel(ls);
01592 }
01593 
01594 /* }====================================================================== */
01595 
01596 
01597 Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
01598                     Dyndata *dyd, const char *name, int firstchar) {
01599   LexState lexstate;
01600   FuncState funcstate;
01601   BlockCnt bl;
01602   TString *tname = luaS_new(L, name);
01603   setsvalue2s(L, L->top, tname);  /* push name to protect it */
01604   incr_top(L);
01605   lexstate.buff = buff;
01606   lexstate.dyd = dyd;
01607   dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
01608   luaX_setinput(L, &lexstate, z, tname, firstchar);
01609   open_mainfunc(&lexstate, &funcstate, &bl);
01610   luaX_next(&lexstate);  /* read first token */
01611   statlist(&lexstate);  /* main body */
01612   check(&lexstate, TK_EOS);
01613   close_func(&lexstate);
01614   L->top--;  /* pop name */
01615   lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
01616   /* all scopes should be correctly finished */
01617   lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
01618   return funcstate.f;
01619 }
01620 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines

Generated by doxygen 1.7.1 on Fri May 25 2012 01:03:04 for The Battle for Wesnoth
Gna! | Forum | Wiki | CIA | devdocs