lparser.c 38 KB

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