lparser.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  1. /*
  2. ** $Id: lparser.c,v 2.70 2009/10/13 19:35:42 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. fs->h = luaH_new(L);
  296. /* anchor table of constants (to avoid being collected) */
  297. sethvalue2s(L, L->top, fs->h);
  298. incr_top(L);
  299. f = luaF_newproto(L);
  300. fs->f = f;
  301. f->source = ls->source;
  302. f->maxstacksize = 2; /* registers 0/1 are always valid */
  303. /* anchor prototype (to avoid being collected) */
  304. setptvalue2s(L, L->top, f);
  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. L->top -= 2; /* remove table and prototype from the stack */
  328. /* last token read was anchored in defunct function; must reanchor it */
  329. anchor_token(ls);
  330. }
  331. Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, Varlist *varl,
  332. const char *name) {
  333. struct LexState lexstate;
  334. struct FuncState funcstate;
  335. TString *tname = luaS_new(L, name);
  336. setsvalue2s(L, L->top, tname); /* protect name */
  337. incr_top(L);
  338. lexstate.buff = buff;
  339. lexstate.varl = varl;
  340. luaX_setinput(L, &lexstate, z, tname);
  341. open_func(&lexstate, &funcstate);
  342. funcstate.f->is_vararg = 1; /* main func. is always vararg */
  343. luaX_next(&lexstate); /* read first token */
  344. chunk(&lexstate);
  345. check(&lexstate, TK_EOS);
  346. close_func(&lexstate);
  347. L->top--;
  348. lua_assert(funcstate.prev == NULL);
  349. lua_assert(funcstate.nups == 0);
  350. lua_assert(lexstate.fs == NULL);
  351. return funcstate.f;
  352. }
  353. /*============================================================*/
  354. /* GRAMMAR RULES */
  355. /*============================================================*/
  356. static void fieldsel (LexState *ls, expdesc *v) {
  357. /* fieldsel -> ['.' | ':'] NAME */
  358. FuncState *fs = ls->fs;
  359. expdesc key;
  360. luaK_exp2anyreg(fs, v);
  361. luaX_next(ls); /* skip the dot or colon */
  362. checkname(ls, &key);
  363. luaK_indexed(fs, v, &key);
  364. }
  365. static void yindex (LexState *ls, expdesc *v) {
  366. /* index -> '[' expr ']' */
  367. luaX_next(ls); /* skip the '[' */
  368. expr(ls, v);
  369. luaK_exp2val(ls->fs, v);
  370. checknext(ls, ']');
  371. }
  372. /*
  373. ** {======================================================================
  374. ** Rules for Constructors
  375. ** =======================================================================
  376. */
  377. struct ConsControl {
  378. expdesc v; /* last list item read */
  379. expdesc *t; /* table descriptor */
  380. int nh; /* total number of `record' elements */
  381. int na; /* total number of array elements */
  382. int tostore; /* number of array elements pending to be stored */
  383. };
  384. static void recfield (LexState *ls, struct ConsControl *cc) {
  385. /* recfield -> (NAME | `['exp1`]') = exp1 */
  386. FuncState *fs = ls->fs;
  387. int reg = ls->fs->freereg;
  388. expdesc key, val;
  389. int rkkey;
  390. if (ls->t.token == TK_NAME) {
  391. luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
  392. checkname(ls, &key);
  393. }
  394. else /* ls->t.token == '[' */
  395. yindex(ls, &key);
  396. cc->nh++;
  397. checknext(ls, '=');
  398. rkkey = luaK_exp2RK(fs, &key);
  399. expr(ls, &val);
  400. luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val));
  401. fs->freereg = reg; /* free registers */
  402. }
  403. static void closelistfield (FuncState *fs, struct ConsControl *cc) {
  404. if (cc->v.k == VVOID) return; /* there is no list item */
  405. luaK_exp2nextreg(fs, &cc->v);
  406. cc->v.k = VVOID;
  407. if (cc->tostore == LFIELDS_PER_FLUSH) {
  408. luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore); /* flush */
  409. cc->tostore = 0; /* no more items pending */
  410. }
  411. }
  412. static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
  413. if (cc->tostore == 0) return;
  414. if (hasmultret(cc->v.k)) {
  415. luaK_setmultret(fs, &cc->v);
  416. luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET);
  417. cc->na--; /* do not count last expression (unknown number of elements) */
  418. }
  419. else {
  420. if (cc->v.k != VVOID)
  421. luaK_exp2nextreg(fs, &cc->v);
  422. luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);
  423. }
  424. }
  425. static void listfield (LexState *ls, struct ConsControl *cc) {
  426. /* listfield -> exp */
  427. expr(ls, &cc->v);
  428. luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
  429. cc->na++;
  430. cc->tostore++;
  431. }
  432. static void field (LexState *ls, struct ConsControl *cc) {
  433. /* field -> listfield | recfield */
  434. switch(ls->t.token) {
  435. case TK_NAME: { /* may be 'listfield' or 'recfield' */
  436. if (luaX_lookahead(ls) != '=') /* expression? */
  437. listfield(ls, cc);
  438. else
  439. recfield(ls, cc);
  440. break;
  441. }
  442. case '[': {
  443. recfield(ls, cc);
  444. break;
  445. }
  446. default: {
  447. listfield(ls, cc);
  448. break;
  449. }
  450. }
  451. }
  452. static void constructor (LexState *ls, expdesc *t) {
  453. /* constructor -> '{' [ field { sep field } [sep] ] '}'
  454. sep -> ',' | ';' */
  455. FuncState *fs = ls->fs;
  456. int line = ls->linenumber;
  457. int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  458. struct ConsControl cc;
  459. cc.na = cc.nh = cc.tostore = 0;
  460. cc.t = t;
  461. init_exp(t, VRELOCABLE, pc);
  462. init_exp(&cc.v, VVOID, 0); /* no value (yet) */
  463. luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */
  464. checknext(ls, '{');
  465. do {
  466. lua_assert(cc.v.k == VVOID || cc.tostore > 0);
  467. if (ls->t.token == '}') break;
  468. closelistfield(fs, &cc);
  469. field(ls, &cc);
  470. } while (testnext(ls, ',') || testnext(ls, ';'));
  471. check_match(ls, '}', '{', line);
  472. lastlistfield(fs, &cc);
  473. SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
  474. SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
  475. }
  476. /* }====================================================================== */
  477. static void parlist (LexState *ls) {
  478. /* parlist -> [ param { `,' param } ] */
  479. FuncState *fs = ls->fs;
  480. Proto *f = fs->f;
  481. int nparams = 0;
  482. f->is_vararg = 0;
  483. if (ls->t.token != ')') { /* is `parlist' not empty? */
  484. do {
  485. switch (ls->t.token) {
  486. case TK_NAME: { /* param -> NAME */
  487. new_localvar(ls, str_checkname(ls));
  488. nparams++;
  489. break;
  490. }
  491. case TK_DOTS: { /* param -> `...' */
  492. luaX_next(ls);
  493. f->is_vararg = 1;
  494. break;
  495. }
  496. default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
  497. }
  498. } while (!f->is_vararg && testnext(ls, ','));
  499. }
  500. adjustlocalvars(ls, nparams);
  501. f->numparams = cast_byte(fs->nactvar);
  502. luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
  503. }
  504. static void body (LexState *ls, expdesc *e, int needself, int line) {
  505. /* body -> `(' parlist `)' chunk END */
  506. FuncState new_fs;
  507. open_func(ls, &new_fs);
  508. new_fs.f->linedefined = line;
  509. checknext(ls, '(');
  510. if (needself) {
  511. new_localvarliteral(ls, "self");
  512. adjustlocalvars(ls, 1);
  513. }
  514. parlist(ls);
  515. checknext(ls, ')');
  516. chunk(ls);
  517. new_fs.f->lastlinedefined = ls->linenumber;
  518. check_match(ls, TK_END, TK_FUNCTION, line);
  519. pushclosure(ls, new_fs.f, e);
  520. close_func(ls);
  521. }
  522. static int explist1 (LexState *ls, expdesc *v) {
  523. /* explist1 -> expr { `,' expr } */
  524. int n = 1; /* at least one expression */
  525. expr(ls, v);
  526. while (testnext(ls, ',')) {
  527. luaK_exp2nextreg(ls->fs, v);
  528. expr(ls, v);
  529. n++;
  530. }
  531. return n;
  532. }
  533. static void funcargs (LexState *ls, expdesc *f) {
  534. FuncState *fs = ls->fs;
  535. expdesc args;
  536. int base, nparams;
  537. int line = ls->linenumber;
  538. switch (ls->t.token) {
  539. case '(': { /* funcargs -> `(' [ explist1 ] `)' */
  540. if (line != ls->lastline)
  541. luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
  542. luaX_next(ls);
  543. if (ls->t.token == ')') /* arg list is empty? */
  544. args.k = VVOID;
  545. else {
  546. explist1(ls, &args);
  547. luaK_setmultret(fs, &args);
  548. }
  549. check_match(ls, ')', '(', line);
  550. break;
  551. }
  552. case '{': { /* funcargs -> constructor */
  553. constructor(ls, &args);
  554. break;
  555. }
  556. case TK_STRING: { /* funcargs -> STRING */
  557. codestring(ls, &args, ls->t.seminfo.ts);
  558. luaX_next(ls); /* must use `seminfo' before `next' */
  559. break;
  560. }
  561. default: {
  562. luaX_syntaxerror(ls, "function arguments expected");
  563. return;
  564. }
  565. }
  566. lua_assert(f->k == VNONRELOC);
  567. base = f->u.s.info; /* base register for call */
  568. if (hasmultret(args.k))
  569. nparams = LUA_MULTRET; /* open call */
  570. else {
  571. if (args.k != VVOID)
  572. luaK_exp2nextreg(fs, &args); /* close last argument */
  573. nparams = fs->freereg - (base+1);
  574. }
  575. init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
  576. luaK_fixline(fs, line);
  577. fs->freereg = base+1; /* call remove function and arguments and leaves
  578. (unless changed) one result */
  579. }
  580. /*
  581. ** {======================================================================
  582. ** Expression parsing
  583. ** =======================================================================
  584. */
  585. static void prefixexp (LexState *ls, expdesc *v) {
  586. /* prefixexp -> NAME | '(' expr ')' */
  587. switch (ls->t.token) {
  588. case '(': {
  589. int line = ls->linenumber;
  590. luaX_next(ls);
  591. expr(ls, v);
  592. check_match(ls, ')', '(', line);
  593. luaK_dischargevars(ls->fs, v);
  594. return;
  595. }
  596. case TK_NAME: {
  597. singlevar(ls, v);
  598. return;
  599. }
  600. default: {
  601. luaX_syntaxerror(ls, "unexpected symbol");
  602. return;
  603. }
  604. }
  605. }
  606. static void primaryexp (LexState *ls, expdesc *v) {
  607. /* primaryexp ->
  608. prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
  609. FuncState *fs = ls->fs;
  610. prefixexp(ls, v);
  611. for (;;) {
  612. switch (ls->t.token) {
  613. case '.': { /* fieldsel */
  614. fieldsel(ls, v);
  615. break;
  616. }
  617. case '[': { /* `[' exp1 `]' */
  618. expdesc key;
  619. luaK_exp2anyreg(fs, v);
  620. yindex(ls, &key);
  621. luaK_indexed(fs, v, &key);
  622. break;
  623. }
  624. case ':': { /* `:' NAME funcargs */
  625. expdesc key;
  626. luaX_next(ls);
  627. checkname(ls, &key);
  628. luaK_self(fs, v, &key);
  629. funcargs(ls, v);
  630. break;
  631. }
  632. case '(': case TK_STRING: case '{': { /* funcargs */
  633. luaK_exp2nextreg(fs, v);
  634. funcargs(ls, v);
  635. break;
  636. }
  637. default: return;
  638. }
  639. }
  640. }
  641. static void simpleexp (LexState *ls, expdesc *v) {
  642. /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
  643. constructor | FUNCTION body | primaryexp */
  644. switch (ls->t.token) {
  645. case TK_NUMBER: {
  646. init_exp(v, VKNUM, 0);
  647. v->u.nval = ls->t.seminfo.r;
  648. break;
  649. }
  650. case TK_STRING: {
  651. codestring(ls, v, ls->t.seminfo.ts);
  652. break;
  653. }
  654. case TK_NIL: {
  655. init_exp(v, VNIL, 0);
  656. break;
  657. }
  658. case TK_TRUE: {
  659. init_exp(v, VTRUE, 0);
  660. break;
  661. }
  662. case TK_FALSE: {
  663. init_exp(v, VFALSE, 0);
  664. break;
  665. }
  666. case TK_DOTS: { /* vararg */
  667. FuncState *fs = ls->fs;
  668. check_condition(ls, fs->f->is_vararg,
  669. "cannot use " LUA_QL("...") " outside a vararg function");
  670. init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
  671. break;
  672. }
  673. case '{': { /* constructor */
  674. constructor(ls, v);
  675. return;
  676. }
  677. case TK_FUNCTION: {
  678. luaX_next(ls);
  679. body(ls, v, 0, ls->linenumber);
  680. return;
  681. }
  682. default: {
  683. primaryexp(ls, v);
  684. return;
  685. }
  686. }
  687. luaX_next(ls);
  688. }
  689. static UnOpr getunopr (int op) {
  690. switch (op) {
  691. case TK_NOT: return OPR_NOT;
  692. case '-': return OPR_MINUS;
  693. case '#': return OPR_LEN;
  694. default: return OPR_NOUNOPR;
  695. }
  696. }
  697. static BinOpr getbinopr (int op) {
  698. switch (op) {
  699. case '+': return OPR_ADD;
  700. case '-': return OPR_SUB;
  701. case '*': return OPR_MUL;
  702. case '/': return OPR_DIV;
  703. case '%': return OPR_MOD;
  704. case '^': return OPR_POW;
  705. case TK_CONCAT: return OPR_CONCAT;
  706. case TK_NE: return OPR_NE;
  707. case TK_EQ: return OPR_EQ;
  708. case '<': return OPR_LT;
  709. case TK_LE: return OPR_LE;
  710. case '>': return OPR_GT;
  711. case TK_GE: return OPR_GE;
  712. case TK_AND: return OPR_AND;
  713. case TK_OR: return OPR_OR;
  714. default: return OPR_NOBINOPR;
  715. }
  716. }
  717. static const struct {
  718. lu_byte left; /* left priority for each binary operator */
  719. lu_byte right; /* right priority */
  720. } priority[] = { /* ORDER OPR */
  721. {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `*' `/' `%' */
  722. {10, 9}, {5, 4}, /* ^, .. (right associative) */
  723. {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
  724. {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
  725. {2, 2}, {1, 1} /* and, or */
  726. };
  727. #define UNARY_PRIORITY 8 /* priority for unary operators */
  728. /*
  729. ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
  730. ** where `binop' is any binary operator with a priority higher than `limit'
  731. */
  732. static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) {
  733. BinOpr op;
  734. UnOpr uop;
  735. enterlevel(ls);
  736. uop = getunopr(ls->t.token);
  737. if (uop != OPR_NOUNOPR) {
  738. luaX_next(ls);
  739. subexpr(ls, v, UNARY_PRIORITY);
  740. luaK_prefix(ls->fs, uop, v);
  741. }
  742. else simpleexp(ls, v);
  743. /* expand while operators have priorities higher than `limit' */
  744. op = getbinopr(ls->t.token);
  745. while (op != OPR_NOBINOPR && priority[op].left > limit) {
  746. expdesc v2;
  747. BinOpr nextop;
  748. luaX_next(ls);
  749. luaK_infix(ls->fs, op, v);
  750. /* read sub-expression with higher priority */
  751. nextop = subexpr(ls, &v2, priority[op].right);
  752. luaK_posfix(ls->fs, op, v, &v2);
  753. op = nextop;
  754. }
  755. leavelevel(ls);
  756. return op; /* return first untreated operator */
  757. }
  758. static void expr (LexState *ls, expdesc *v) {
  759. subexpr(ls, v, 0);
  760. }
  761. /* }==================================================================== */
  762. /*
  763. ** {======================================================================
  764. ** Rules for Statements
  765. ** =======================================================================
  766. */
  767. static int block_follow (int token) {
  768. switch (token) {
  769. case TK_ELSE: case TK_ELSEIF: case TK_END:
  770. case TK_UNTIL: case TK_EOS:
  771. return 1;
  772. default: return 0;
  773. }
  774. }
  775. static void block (LexState *ls) {
  776. /* block -> chunk */
  777. FuncState *fs = ls->fs;
  778. BlockCnt bl;
  779. enterblock(fs, &bl, 0);
  780. chunk(ls);
  781. lua_assert(bl.breaklist == NO_JUMP);
  782. leaveblock(fs);
  783. }
  784. /*
  785. ** structure to chain all variables in the left-hand side of an
  786. ** assignment
  787. */
  788. struct LHS_assign {
  789. struct LHS_assign *prev;
  790. expdesc v; /* variable (global, local, upvalue, or indexed) */
  791. };
  792. /*
  793. ** check whether, in an assignment to a local variable, the local variable
  794. ** is needed in a previous assignment (to a table). If so, save original
  795. ** local value in a safe place and use this safe copy in the previous
  796. ** assignment.
  797. */
  798. static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
  799. FuncState *fs = ls->fs;
  800. int extra = fs->freereg; /* eventual position to save local variable */
  801. int conflict = 0;
  802. for (; lh; lh = lh->prev) {
  803. if (lh->v.k == VINDEXED) {
  804. if (lh->v.u.s.info == v->u.s.info) { /* conflict? */
  805. conflict = 1;
  806. lh->v.u.s.info = extra; /* previous assignment will use safe copy */
  807. }
  808. if (lh->v.u.s.aux == v->u.s.info) { /* conflict? */
  809. conflict = 1;
  810. lh->v.u.s.aux = extra; /* previous assignment will use safe copy */
  811. }
  812. }
  813. }
  814. if (conflict) {
  815. luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0); /* make copy */
  816. luaK_reserveregs(fs, 1);
  817. }
  818. }
  819. static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
  820. expdesc e;
  821. check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
  822. "syntax error");
  823. if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */
  824. struct LHS_assign nv;
  825. nv.prev = lh;
  826. primaryexp(ls, &nv.v);
  827. if (nv.v.k == VLOCAL)
  828. check_conflict(ls, lh, &nv.v);
  829. luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - G(ls->L)->nCcalls,
  830. "variable names");
  831. assignment(ls, &nv, nvars+1);
  832. }
  833. else { /* assignment -> `=' explist1 */
  834. int nexps;
  835. checknext(ls, '=');
  836. nexps = explist1(ls, &e);
  837. if (nexps != nvars) {
  838. adjust_assign(ls, nvars, nexps, &e);
  839. if (nexps > nvars)
  840. ls->fs->freereg -= nexps - nvars; /* remove extra values */
  841. }
  842. else {
  843. luaK_setoneret(ls->fs, &e); /* close last expression */
  844. luaK_storevar(ls->fs, &lh->v, &e);
  845. return; /* avoid default */
  846. }
  847. }
  848. init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
  849. luaK_storevar(ls->fs, &lh->v, &e);
  850. }
  851. static int cond (LexState *ls) {
  852. /* cond -> exp */
  853. expdesc v;
  854. expr(ls, &v); /* read condition */
  855. if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
  856. luaK_goiftrue(ls->fs, &v);
  857. return v.f;
  858. }
  859. static void breakstat (LexState *ls) {
  860. FuncState *fs = ls->fs;
  861. BlockCnt *bl = fs->bl;
  862. int upval = 0;
  863. while (bl && !bl->isbreakable) {
  864. upval |= bl->upval;
  865. bl = bl->previous;
  866. }
  867. if (!bl)
  868. luaX_syntaxerror(ls, "no loop to break");
  869. if (upval)
  870. luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
  871. luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
  872. }
  873. static void whilestat (LexState *ls, int line) {
  874. /* whilestat -> WHILE cond DO block END */
  875. FuncState *fs = ls->fs;
  876. int whileinit;
  877. int condexit;
  878. BlockCnt bl;
  879. luaX_next(ls); /* skip WHILE */
  880. whileinit = luaK_getlabel(fs);
  881. condexit = cond(ls);
  882. enterblock(fs, &bl, 1);
  883. checknext(ls, TK_DO);
  884. block(ls);
  885. luaK_jumpto(fs, whileinit);
  886. check_match(ls, TK_END, TK_WHILE, line);
  887. leaveblock(fs);
  888. luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
  889. }
  890. static void repeatstat (LexState *ls, int line) {
  891. /* repeatstat -> REPEAT block UNTIL cond */
  892. int condexit;
  893. FuncState *fs = ls->fs;
  894. int repeat_init = luaK_getlabel(fs);
  895. BlockCnt bl1, bl2;
  896. enterblock(fs, &bl1, 1); /* loop block */
  897. enterblock(fs, &bl2, 0); /* scope block */
  898. luaX_next(ls); /* skip REPEAT */
  899. chunk(ls);
  900. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  901. condexit = cond(ls); /* read condition (inside scope block) */
  902. if (!bl2.upval) { /* no upvalues? */
  903. leaveblock(fs); /* finish scope */
  904. luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
  905. }
  906. else { /* complete semantics when there are upvalues */
  907. breakstat(ls); /* if condition then break */
  908. luaK_patchtohere(ls->fs, condexit); /* else... */
  909. leaveblock(fs); /* finish scope... */
  910. luaK_jumpto(fs, repeat_init); /* and repeat */
  911. }
  912. leaveblock(fs); /* finish loop */
  913. }
  914. static int exp1 (LexState *ls) {
  915. expdesc e;
  916. int reg;
  917. expr(ls, &e);
  918. luaK_exp2nextreg(ls->fs, &e);
  919. lua_assert(e.k == VNONRELOC);
  920. reg = e.u.s.info;
  921. return reg;
  922. }
  923. static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
  924. /* forbody -> DO block */
  925. BlockCnt bl;
  926. FuncState *fs = ls->fs;
  927. int prep, endfor;
  928. adjustlocalvars(ls, 3); /* control variables */
  929. checknext(ls, TK_DO);
  930. prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
  931. enterblock(fs, &bl, 0); /* scope for declared variables */
  932. adjustlocalvars(ls, nvars);
  933. luaK_reserveregs(fs, nvars);
  934. block(ls);
  935. leaveblock(fs); /* end of scope for declared variables */
  936. luaK_patchtohere(fs, prep);
  937. if (isnum) /* numeric for? */
  938. endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
  939. else { /* generic for */
  940. luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
  941. luaK_fixline(fs, line);
  942. endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
  943. }
  944. luaK_patchlist(fs, endfor, prep + 1);
  945. luaK_fixline(fs, line);
  946. }
  947. static void fornum (LexState *ls, TString *varname, int line) {
  948. /* fornum -> NAME = exp1,exp1[,exp1] forbody */
  949. FuncState *fs = ls->fs;
  950. int base = fs->freereg;
  951. new_localvarliteral(ls, "(for index)");
  952. new_localvarliteral(ls, "(for limit)");
  953. new_localvarliteral(ls, "(for step)");
  954. new_localvar(ls, varname);
  955. checknext(ls, '=');
  956. exp1(ls); /* initial value */
  957. checknext(ls, ',');
  958. exp1(ls); /* limit */
  959. if (testnext(ls, ','))
  960. exp1(ls); /* optional step */
  961. else { /* default step = 1 */
  962. luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1));
  963. luaK_reserveregs(fs, 1);
  964. }
  965. forbody(ls, base, line, 1, 1);
  966. }
  967. static void forlist (LexState *ls, TString *indexname) {
  968. /* forlist -> NAME {,NAME} IN explist1 forbody */
  969. FuncState *fs = ls->fs;
  970. expdesc e;
  971. int nvars = 4; /* gen, state, control, plus at least one declared var */
  972. int line;
  973. int base = fs->freereg;
  974. /* create control variables */
  975. new_localvarliteral(ls, "(for generator)");
  976. new_localvarliteral(ls, "(for state)");
  977. new_localvarliteral(ls, "(for control)");
  978. /* create declared variables */
  979. new_localvar(ls, indexname);
  980. while (testnext(ls, ',')) {
  981. new_localvar(ls, str_checkname(ls));
  982. nvars++;
  983. }
  984. checknext(ls, TK_IN);
  985. line = ls->linenumber;
  986. adjust_assign(ls, 3, explist1(ls, &e), &e);
  987. luaK_checkstack(fs, 3); /* extra space to call generator */
  988. forbody(ls, base, line, nvars - 3, 0);
  989. }
  990. static void forstat (LexState *ls, int line) {
  991. /* forstat -> FOR (fornum | forlist) END */
  992. FuncState *fs = ls->fs;
  993. TString *varname;
  994. BlockCnt bl;
  995. enterblock(fs, &bl, 1); /* scope for loop and control variables */
  996. luaX_next(ls); /* skip `for' */
  997. varname = str_checkname(ls); /* first variable name */
  998. switch (ls->t.token) {
  999. case '=': fornum(ls, varname, line); break;
  1000. case ',': case TK_IN: forlist(ls, varname); break;
  1001. default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
  1002. }
  1003. check_match(ls, TK_END, TK_FOR, line);
  1004. leaveblock(fs); /* loop scope (`break' jumps to this point) */
  1005. }
  1006. static int test_then_block (LexState *ls) {
  1007. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  1008. int condexit;
  1009. luaX_next(ls); /* skip IF or ELSEIF */
  1010. condexit = cond(ls);
  1011. checknext(ls, TK_THEN);
  1012. block(ls); /* `then' part */
  1013. return condexit;
  1014. }
  1015. static void ifstat (LexState *ls, int line) {
  1016. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  1017. FuncState *fs = ls->fs;
  1018. int flist;
  1019. int escapelist = NO_JUMP;
  1020. flist = test_then_block(ls); /* IF cond THEN block */
  1021. while (ls->t.token == TK_ELSEIF) {
  1022. luaK_concat(fs, &escapelist, luaK_jump(fs));
  1023. luaK_patchtohere(fs, flist);
  1024. flist = test_then_block(ls); /* ELSEIF cond THEN block */
  1025. }
  1026. if (ls->t.token == TK_ELSE) {
  1027. luaK_concat(fs, &escapelist, luaK_jump(fs));
  1028. luaK_patchtohere(fs, flist);
  1029. luaX_next(ls); /* skip ELSE (after patch, for correct line info) */
  1030. block(ls); /* `else' part */
  1031. }
  1032. else
  1033. luaK_concat(fs, &escapelist, flist);
  1034. luaK_patchtohere(fs, escapelist);
  1035. check_match(ls, TK_END, TK_IF, line);
  1036. }
  1037. static void localfunc (LexState *ls) {
  1038. expdesc v, b;
  1039. FuncState *fs = ls->fs;
  1040. new_localvar(ls, str_checkname(ls));
  1041. init_exp(&v, VLOCAL, fs->freereg);
  1042. luaK_reserveregs(fs, 1);
  1043. adjustlocalvars(ls, 1);
  1044. body(ls, &b, 0, ls->linenumber);
  1045. luaK_storevar(fs, &v, &b);
  1046. }
  1047. static void localstat (LexState *ls) {
  1048. /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
  1049. int nvars = 0;
  1050. int nexps;
  1051. expdesc e;
  1052. do {
  1053. new_localvar(ls, str_checkname(ls));
  1054. nvars++;
  1055. } while (testnext(ls, ','));
  1056. if (testnext(ls, '='))
  1057. nexps = explist1(ls, &e);
  1058. else {
  1059. e.k = VVOID;
  1060. nexps = 0;
  1061. }
  1062. adjust_assign(ls, nvars, nexps, &e);
  1063. adjustlocalvars(ls, nvars);
  1064. }
  1065. static int funcname (LexState *ls, expdesc *v) {
  1066. /* funcname -> NAME {fieldsel} [`:' NAME] */
  1067. int needself = 0;
  1068. singlevar(ls, v);
  1069. while (ls->t.token == '.')
  1070. fieldsel(ls, v);
  1071. if (ls->t.token == ':') {
  1072. needself = 1;
  1073. fieldsel(ls, v);
  1074. }
  1075. return needself;
  1076. }
  1077. static void funcstat (LexState *ls, int line) {
  1078. /* funcstat -> FUNCTION funcname body */
  1079. int needself;
  1080. expdesc v, b;
  1081. luaX_next(ls); /* skip FUNCTION */
  1082. needself = funcname(ls, &v);
  1083. body(ls, &b, needself, line);
  1084. luaK_storevar(ls->fs, &v, &b);
  1085. luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
  1086. }
  1087. static void instat (LexState *ls, int line) {
  1088. /* instat -> IN exp DO block END */
  1089. FuncState *fs = ls->fs;
  1090. int oldenv = fs->envreg; /* save current environment */
  1091. BlockCnt bl;
  1092. luaX_next(ls); /* skip IN */
  1093. enterblock(fs, &bl, 0); /* scope for environment variable */
  1094. new_localvarliteral(ls, "(environment)");
  1095. fs->envreg = exp1(ls); /* new environment */
  1096. adjustlocalvars(ls, 1);
  1097. checknext(ls, TK_DO);
  1098. block(ls);
  1099. leaveblock(fs);
  1100. check_match(ls, TK_END, TK_IN, line);
  1101. fs->envreg = oldenv; /* restore outer environment */
  1102. }
  1103. static void exprstat (LexState *ls) {
  1104. /* stat -> func | assignment */
  1105. FuncState *fs = ls->fs;
  1106. struct LHS_assign v;
  1107. primaryexp(ls, &v.v);
  1108. if (v.v.k == VCALL) /* stat -> func */
  1109. SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
  1110. else { /* stat -> assignment */
  1111. v.prev = NULL;
  1112. assignment(ls, &v, 1);
  1113. }
  1114. }
  1115. static void retstat (LexState *ls) {
  1116. /* stat -> RETURN explist */
  1117. FuncState *fs = ls->fs;
  1118. expdesc e;
  1119. int first, nret; /* registers with returned values */
  1120. luaX_next(ls); /* skip RETURN */
  1121. if (block_follow(ls->t.token) || ls->t.token == ';')
  1122. first = nret = 0; /* return no values */
  1123. else {
  1124. nret = explist1(ls, &e); /* optional return values */
  1125. if (hasmultret(e.k)) {
  1126. luaK_setmultret(fs, &e);
  1127. if (e.k == VCALL && nret == 1) { /* tail call? */
  1128. SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
  1129. lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
  1130. }
  1131. first = fs->nactvar;
  1132. nret = LUA_MULTRET; /* return all values */
  1133. }
  1134. else {
  1135. if (nret == 1) /* only one single value? */
  1136. first = luaK_exp2anyreg(fs, &e);
  1137. else {
  1138. luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
  1139. first = fs->nactvar; /* return all `active' values */
  1140. lua_assert(nret == fs->freereg - first);
  1141. }
  1142. }
  1143. }
  1144. luaK_ret(fs, first, nret);
  1145. }
  1146. static int statement (LexState *ls) {
  1147. int line = ls->linenumber; /* may be needed for error messages */
  1148. switch (ls->t.token) {
  1149. case TK_IF: { /* stat -> ifstat */
  1150. ifstat(ls, line);
  1151. return 0;
  1152. }
  1153. case TK_WHILE: { /* stat -> whilestat */
  1154. whilestat(ls, line);
  1155. return 0;
  1156. }
  1157. case TK_DO: { /* stat -> DO block END */
  1158. luaX_next(ls); /* skip DO */
  1159. block(ls);
  1160. check_match(ls, TK_END, TK_DO, line);
  1161. return 0;
  1162. }
  1163. case TK_IN: {
  1164. instat(ls, line);
  1165. return 0;
  1166. }
  1167. case TK_FOR: { /* stat -> forstat */
  1168. forstat(ls, line);
  1169. return 0;
  1170. }
  1171. case TK_REPEAT: { /* stat -> repeatstat */
  1172. repeatstat(ls, line);
  1173. return 0;
  1174. }
  1175. case TK_FUNCTION: {
  1176. funcstat(ls, line); /* stat -> funcstat */
  1177. return 0;
  1178. }
  1179. case TK_LOCAL: { /* stat -> localstat */
  1180. luaX_next(ls); /* skip LOCAL */
  1181. if (testnext(ls, TK_FUNCTION)) /* local function? */
  1182. localfunc(ls);
  1183. else
  1184. localstat(ls);
  1185. return 0;
  1186. }
  1187. case TK_RETURN: { /* stat -> retstat */
  1188. retstat(ls);
  1189. return 1; /* must be last statement */
  1190. }
  1191. case TK_BREAK: { /* stat -> breakstat */
  1192. luaX_next(ls); /* skip BREAK */
  1193. breakstat(ls);
  1194. return 1; /* must be last statement */
  1195. }
  1196. default: {
  1197. exprstat(ls);
  1198. return 0; /* to avoid warnings */
  1199. }
  1200. }
  1201. }
  1202. static void chunk (LexState *ls) {
  1203. /* chunk -> { stat [`;'] } */
  1204. int islast = 0;
  1205. enterlevel(ls);
  1206. while (!islast && !block_follow(ls->t.token)) {
  1207. islast = statement(ls);
  1208. testnext(ls, ';');
  1209. lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
  1210. ls->fs->freereg >= ls->fs->nactvar);
  1211. ls->fs->freereg = ls->fs->nactvar; /* free registers */
  1212. }
  1213. leavelevel(ls);
  1214. }
  1215. /* }====================================================================== */