lparser.c 37 KB

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