lparser.c 37 KB

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