lparser.c 37 KB

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