lparser.c 38 KB

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