lparser.c 37 KB

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