lparser.c 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841
  1. /*
  2. ** $Id: lparser.c $
  3. ** Lua Parser
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lparser_c
  7. #define LUA_CORE
  8. #include "lprefix.h"
  9. #include <limits.h>
  10. #include <string.h>
  11. #include "lua.h"
  12. #include "lcode.h"
  13. #include "ldebug.h"
  14. #include "ldo.h"
  15. #include "lfunc.h"
  16. #include "llex.h"
  17. #include "lmem.h"
  18. #include "lobject.h"
  19. #include "lopcodes.h"
  20. #include "lparser.h"
  21. #include "lstate.h"
  22. #include "lstring.h"
  23. #include "ltable.h"
  24. /* maximum number of local variables per function (must be smaller
  25. than 250, due to the bytecode format) */
  26. #define MAXVARS 200
  27. #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
  28. /* because all strings are unified by the scanner, the parser
  29. can use pointer equality for string equality */
  30. #define eqstr(a,b) ((a) == (b))
  31. /*
  32. ** nodes for block list (list of active blocks)
  33. */
  34. typedef struct BlockCnt {
  35. struct BlockCnt *previous; /* chain */
  36. int firstlabel; /* index of first label in this block */
  37. int firstgoto; /* index of first pending goto in this block */
  38. lu_byte nactvar; /* # active locals outside the block */
  39. lu_byte upval; /* true if some variable in the block is an upvalue */
  40. lu_byte isloop; /* true if 'block' is a loop */
  41. } BlockCnt;
  42. /*
  43. ** prototypes for recursive non-terminal functions
  44. */
  45. static void statement (LexState *ls);
  46. static void expr (LexState *ls, expdesc *v);
  47. static l_noret error_expected (LexState *ls, int token) {
  48. luaX_syntaxerror(ls,
  49. luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
  50. }
  51. static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
  52. lua_State *L = fs->ls->L;
  53. const char *msg;
  54. int line = fs->f->linedefined;
  55. const char *where = (line == 0)
  56. ? "main function"
  57. : luaO_pushfstring(L, "function at line %d", line);
  58. msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
  59. what, limit, where);
  60. luaX_syntaxerror(fs->ls, msg);
  61. }
  62. static void checklimit (FuncState *fs, int v, int l, const char *what) {
  63. if (v > l) errorlimit(fs, l, what);
  64. }
  65. /*
  66. ** Test whether next token is 'c'; if so, skip it.
  67. */
  68. static int testnext (LexState *ls, int c) {
  69. if (ls->t.token == c) {
  70. luaX_next(ls);
  71. return 1;
  72. }
  73. else return 0;
  74. }
  75. /*
  76. ** Check that next token is 'c'.
  77. */
  78. static void check (LexState *ls, int c) {
  79. if (ls->t.token != c)
  80. error_expected(ls, c);
  81. }
  82. /*
  83. ** Check that next token is 'c' and skip it.
  84. */
  85. static void checknext (LexState *ls, int c) {
  86. check(ls, c);
  87. luaX_next(ls);
  88. }
  89. #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
  90. /*
  91. ** Check that next token is 'what' and skip it. In case of error,
  92. ** raise an error that the expected 'what' should match a 'who'
  93. ** in line 'where' (if that is not the current line).
  94. */
  95. static void check_match (LexState *ls, int what, int who, int where) {
  96. if (unlikely(!testnext(ls, what))) {
  97. if (where == ls->linenumber) /* all in the same line? */
  98. error_expected(ls, what); /* do not need a complex message */
  99. else {
  100. luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
  101. "%s expected (to close %s at line %d)",
  102. luaX_token2str(ls, what), luaX_token2str(ls, who), where));
  103. }
  104. }
  105. }
  106. static TString *str_checkname (LexState *ls) {
  107. TString *ts;
  108. check(ls, TK_NAME);
  109. ts = ls->t.seminfo.ts;
  110. luaX_next(ls);
  111. return ts;
  112. }
  113. static void init_exp (expdesc *e, expkind k, int i) {
  114. e->f = e->t = NO_JUMP;
  115. e->k = k;
  116. e->u.info = i;
  117. }
  118. static void codestring (LexState *ls, expdesc *e, TString *s) {
  119. init_exp(e, VK, luaK_stringK(ls->fs, s));
  120. }
  121. static void codename (LexState *ls, expdesc *e) {
  122. codestring(ls, e, str_checkname(ls));
  123. }
  124. /*
  125. ** Register a new local variable in the active 'Proto' (for debug
  126. ** information).
  127. */
  128. static int registerlocalvar (LexState *ls, TString *varname) {
  129. FuncState *fs = ls->fs;
  130. Proto *f = fs->f;
  131. int oldsize = f->sizelocvars;
  132. luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
  133. LocVar, SHRT_MAX, "local variables");
  134. while (oldsize < f->sizelocvars)
  135. f->locvars[oldsize++].varname = NULL;
  136. f->locvars[fs->nlocvars].varname = varname;
  137. luaC_objbarrier(ls->L, f, varname);
  138. return fs->nlocvars++;
  139. }
  140. /*
  141. ** Create a new local variable with the given 'name'.
  142. */
  143. static void new_localvar (LexState *ls, TString *name) {
  144. FuncState *fs = ls->fs;
  145. Dyndata *dyd = ls->dyd;
  146. int reg = registerlocalvar(ls, name);
  147. checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
  148. MAXVARS, "local variables");
  149. luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,
  150. dyd->actvar.size, Vardesc, MAX_INT, "local variables");
  151. dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg);
  152. }
  153. #define new_localvarliteral(ls,v) \
  154. new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1));
  155. /*
  156. ** Get the debug-information entry for current variable 'i'.
  157. */
  158. static LocVar *getlocvar (FuncState *fs, int i) {
  159. int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
  160. lua_assert(idx < fs->nlocvars);
  161. return &fs->f->locvars[idx];
  162. }
  163. /*
  164. ** Start the scope for the last 'nvars' created variables.
  165. ** (debug info.)
  166. */
  167. static void adjustlocalvars (LexState *ls, int nvars) {
  168. FuncState *fs = ls->fs;
  169. fs->nactvar = cast_byte(fs->nactvar + nvars);
  170. for (; nvars; nvars--) {
  171. getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;
  172. }
  173. }
  174. /*
  175. ** Close the scope for all variables up to level 'tolevel'.
  176. ** (debug info.)
  177. */
  178. static void removevars (FuncState *fs, int tolevel) {
  179. fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
  180. while (fs->nactvar > tolevel)
  181. getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
  182. }
  183. /*
  184. ** Search the upvalues of the function 'fs' for one
  185. ** with the given 'name'.
  186. */
  187. static int searchupvalue (FuncState *fs, TString *name) {
  188. int i;
  189. Upvaldesc *up = fs->f->upvalues;
  190. for (i = 0; i < fs->nups; i++) {
  191. if (eqstr(up[i].name, name)) return i;
  192. }
  193. return -1; /* not found */
  194. }
  195. static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
  196. Proto *f = fs->f;
  197. int oldsize = f->sizeupvalues;
  198. checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
  199. luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
  200. Upvaldesc, MAXUPVAL, "upvalues");
  201. while (oldsize < f->sizeupvalues)
  202. f->upvalues[oldsize++].name = NULL;
  203. f->upvalues[fs->nups].instack = (v->k == VLOCAL);
  204. f->upvalues[fs->nups].idx = cast_byte(v->u.info);
  205. f->upvalues[fs->nups].name = name;
  206. luaC_objbarrier(fs->ls->L, f, name);
  207. return fs->nups++;
  208. }
  209. /*
  210. ** Look for an active local variable with the name 'n' in the
  211. ** function 'fs'.
  212. */
  213. static int searchvar (FuncState *fs, TString *n) {
  214. int i;
  215. for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
  216. if (eqstr(n, getlocvar(fs, i)->varname))
  217. return i;
  218. }
  219. return -1; /* not found */
  220. }
  221. /*
  222. ** Mark block where variable at given level was defined
  223. ** (to emit close instructions later).
  224. */
  225. static void markupval (FuncState *fs, int level) {
  226. BlockCnt *bl = fs->bl;
  227. while (bl->nactvar > level)
  228. bl = bl->previous;
  229. bl->upval = 1;
  230. fs->needclose = 1;
  231. }
  232. /*
  233. ** Find a variable with the given name 'n'. If it is an upvalue, add
  234. ** this upvalue into all intermediate functions. If it is a global, set
  235. ** 'var' as 'void' as a flag.
  236. */
  237. static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
  238. if (fs == NULL) /* no more levels? */
  239. init_exp(var, VVOID, 0); /* default is global */
  240. else {
  241. int v = searchvar(fs, n); /* look up locals at current level */
  242. if (v >= 0) { /* found? */
  243. init_exp(var, VLOCAL, v); /* variable is local */
  244. if (!base)
  245. markupval(fs, v); /* local will be used as an upval */
  246. }
  247. else { /* not found as local at current level; try upvalues */
  248. int idx = searchupvalue(fs, n); /* try existing upvalues */
  249. if (idx < 0) { /* not found? */
  250. singlevaraux(fs->prev, n, var, 0); /* try upper levels */
  251. if (var->k == VVOID) /* not found? */
  252. return; /* it is a global */
  253. /* else was LOCAL or UPVAL */
  254. idx = newupvalue(fs, n, var); /* will be a new upvalue */
  255. }
  256. init_exp(var, VUPVAL, idx); /* new or old upvalue */
  257. }
  258. }
  259. }
  260. /*
  261. ** Find a variable with the given name 'n', handling global variables
  262. ** too.
  263. */
  264. static void singlevar (LexState *ls, expdesc *var) {
  265. TString *varname = str_checkname(ls);
  266. FuncState *fs = ls->fs;
  267. singlevaraux(fs, varname, var, 1);
  268. if (var->k == VVOID) { /* global name? */
  269. expdesc key;
  270. singlevaraux(fs, ls->envn, var, 1); /* get environment variable */
  271. lua_assert(var->k != VVOID); /* this one must exist */
  272. codestring(ls, &key, varname); /* key is variable name */
  273. luaK_indexed(fs, var, &key); /* env[varname] */
  274. }
  275. }
  276. /*
  277. ** Adjust the number of results from an expression list 'e' with 'nexps'
  278. ** expressions to 'nvars' values.
  279. */
  280. static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
  281. FuncState *fs = ls->fs;
  282. int needed = nvars - nexps; /* extra values needed */
  283. if (hasmultret(e->k)) { /* last expression has multiple returns? */
  284. int extra = needed + 1; /* discount last expression itself */
  285. if (extra < 0)
  286. extra = 0;
  287. luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
  288. }
  289. else {
  290. if (e->k != VVOID) /* at least one expression? */
  291. luaK_exp2nextreg(fs, e); /* close last expression */
  292. if (needed > 0) /* missing values? */
  293. luaK_nil(fs, fs->freereg, needed); /* complete with nils */
  294. }
  295. if (needed > 0)
  296. luaK_reserveregs(fs, needed); /* registers for extra values */
  297. else /* adding 'needed' is actually a subtraction */
  298. fs->freereg += needed; /* remove extra values */
  299. }
  300. #define enterlevel(ls) luaE_incCcalls((ls)->L)
  301. #define leavelevel(ls) ((ls)->L->nCcalls--)
  302. /*
  303. ** Generates an error that a goto jumps into the scope of some
  304. ** local variable.
  305. */
  306. static l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) {
  307. const char *varname = getstr(getlocvar(ls->fs, gt->nactvar)->varname);
  308. const char *msg = "<goto %s> at line %d jumps into the scope of local '%s'";
  309. msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line, varname);
  310. luaK_semerror(ls, msg); /* raise the error */
  311. }
  312. /*
  313. ** Solves the goto at index 'g' to given 'label' and removes it
  314. ** from the list of pending goto's.
  315. ** If it jumps into the scope of some variable, raises an error.
  316. */
  317. static void solvegoto (LexState *ls, int g, Labeldesc *label) {
  318. int i;
  319. Labellist *gl = &ls->dyd->gt; /* list of goto's */
  320. Labeldesc *gt = &gl->arr[g]; /* goto to be resolved */
  321. lua_assert(eqstr(gt->name, label->name));
  322. if (unlikely(gt->nactvar < label->nactvar)) /* enter some scope? */
  323. jumpscopeerror(ls, gt);
  324. luaK_patchlist(ls->fs, gt->pc, label->pc);
  325. for (i = g; i < gl->n - 1; i++) /* remove goto from pending list */
  326. gl->arr[i] = gl->arr[i + 1];
  327. gl->n--;
  328. }
  329. /*
  330. ** Search for an active label with the given name.
  331. */
  332. static Labeldesc *findlabel (LexState *ls, TString *name) {
  333. int i;
  334. Dyndata *dyd = ls->dyd;
  335. /* check labels in current function for a match */
  336. for (i = ls->fs->firstlabel; i < dyd->label.n; i++) {
  337. Labeldesc *lb = &dyd->label.arr[i];
  338. if (eqstr(lb->name, name)) /* correct label? */
  339. return lb;
  340. }
  341. return NULL; /* label not found */
  342. }
  343. /*
  344. ** Adds a new label/goto in the corresponding list.
  345. */
  346. static int newlabelentry (LexState *ls, Labellist *l, TString *name,
  347. int line, int pc) {
  348. int n = l->n;
  349. luaM_growvector(ls->L, l->arr, n, l->size,
  350. Labeldesc, SHRT_MAX, "labels/gotos");
  351. l->arr[n].name = name;
  352. l->arr[n].line = line;
  353. l->arr[n].nactvar = ls->fs->nactvar;
  354. l->arr[n].close = 0;
  355. l->arr[n].pc = pc;
  356. l->n = n + 1;
  357. return n;
  358. }
  359. static int newgotoentry (LexState *ls, TString *name, int line, int pc) {
  360. return newlabelentry(ls, &ls->dyd->gt, name, line, pc);
  361. }
  362. /*
  363. ** Solves forward jumps. Check whether new label 'lb' matches any
  364. ** pending gotos in current block and solves them. Return true
  365. ** if any of the goto's need to close upvalues.
  366. */
  367. static int solvegotos (LexState *ls, Labeldesc *lb) {
  368. Labellist *gl = &ls->dyd->gt;
  369. int i = ls->fs->bl->firstgoto;
  370. int needsclose = 0;
  371. while (i < gl->n) {
  372. if (eqstr(gl->arr[i].name, lb->name)) {
  373. needsclose |= gl->arr[i].close;
  374. solvegoto(ls, i, lb); /* will remove 'i' from the list */
  375. }
  376. else
  377. i++;
  378. }
  379. return needsclose;
  380. }
  381. /*
  382. ** Create a new label with the given 'name' at the given 'line'.
  383. ** 'last' tells whether label is the last non-op statement in its
  384. ** block. Solves all pending goto's to this new label and adds
  385. ** a close instruction if necessary.
  386. ** Returns true iff it added a close instruction.
  387. */
  388. static int createlabel (LexState *ls, TString *name, int line,
  389. int last) {
  390. FuncState *fs = ls->fs;
  391. Labellist *ll = &ls->dyd->label;
  392. int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs));
  393. if (last) { /* label is last no-op statement in the block? */
  394. /* assume that locals are already out of scope */
  395. ll->arr[l].nactvar = fs->bl->nactvar;
  396. }
  397. if (solvegotos(ls, &ll->arr[l])) { /* need close? */
  398. luaK_codeABC(fs, OP_CLOSE, fs->nactvar, 0, 0);
  399. return 1;
  400. }
  401. return 0;
  402. }
  403. /*
  404. ** Adjust pending gotos to outer level of a block.
  405. */
  406. static void movegotosout (FuncState *fs, BlockCnt *bl) {
  407. int i;
  408. Labellist *gl = &fs->ls->dyd->gt;
  409. /* correct pending gotos to current block */
  410. for (i = bl->firstgoto; i < gl->n; i++) { /* for each pending goto */
  411. Labeldesc *gt = &gl->arr[i];
  412. if (gt->nactvar > bl->nactvar) { /* leaving a variable scope? */
  413. gt->nactvar = bl->nactvar; /* update goto level */
  414. gt->close |= bl->upval; /* jump may need a close */
  415. }
  416. }
  417. }
  418. static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
  419. bl->isloop = isloop;
  420. bl->nactvar = fs->nactvar;
  421. bl->firstlabel = fs->ls->dyd->label.n;
  422. bl->firstgoto = fs->ls->dyd->gt.n;
  423. bl->upval = 0;
  424. bl->previous = fs->bl;
  425. fs->bl = bl;
  426. lua_assert(fs->freereg == fs->nactvar);
  427. }
  428. /*
  429. ** generates an error for an undefined 'goto'.
  430. */
  431. static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
  432. const char *msg;
  433. if (eqstr(gt->name, luaS_newliteral(ls->L, "break"))) {
  434. msg = "break outside loop at line %d";
  435. msg = luaO_pushfstring(ls->L, msg, gt->line);
  436. }
  437. else {
  438. msg = "no visible label '%s' for <goto> at line %d";
  439. msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
  440. }
  441. luaK_semerror(ls, msg);
  442. }
  443. static void leaveblock (FuncState *fs) {
  444. BlockCnt *bl = fs->bl;
  445. LexState *ls = fs->ls;
  446. int hasclose = 0;
  447. if (bl->isloop) /* fix pending breaks? */
  448. hasclose = createlabel(ls, luaS_newliteral(ls->L, "break"), 0, 0);
  449. if (!hasclose && bl->previous && bl->upval)
  450. luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
  451. fs->bl = bl->previous;
  452. removevars(fs, bl->nactvar);
  453. lua_assert(bl->nactvar == fs->nactvar);
  454. fs->freereg = fs->nactvar; /* free registers */
  455. ls->dyd->label.n = bl->firstlabel; /* remove local labels */
  456. if (bl->previous) /* inner block? */
  457. movegotosout(fs, bl); /* update pending gotos to outer block */
  458. else {
  459. if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */
  460. undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
  461. }
  462. }
  463. /*
  464. ** adds a new prototype into list of prototypes
  465. */
  466. static Proto *addprototype (LexState *ls) {
  467. Proto *clp;
  468. lua_State *L = ls->L;
  469. FuncState *fs = ls->fs;
  470. Proto *f = fs->f; /* prototype of current function */
  471. if (fs->np >= f->sizep) {
  472. int oldsize = f->sizep;
  473. luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
  474. while (oldsize < f->sizep)
  475. f->p[oldsize++] = NULL;
  476. }
  477. f->p[fs->np++] = clp = luaF_newproto(L);
  478. luaC_objbarrier(L, f, clp);
  479. return clp;
  480. }
  481. /*
  482. ** codes instruction to create new closure in parent function.
  483. ** The OP_CLOSURE instruction must use the last available register,
  484. ** so that, if it invokes the GC, the GC knows which registers
  485. ** are in use at that time.
  486. */
  487. static void codeclosure (LexState *ls, expdesc *v) {
  488. FuncState *fs = ls->fs->prev;
  489. init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
  490. luaK_exp2nextreg(fs, v); /* fix it at the last register */
  491. }
  492. static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
  493. Proto *f = fs->f;
  494. fs->prev = ls->fs; /* linked list of funcstates */
  495. fs->ls = ls;
  496. ls->fs = fs;
  497. fs->pc = 0;
  498. fs->previousline = f->linedefined;
  499. fs->iwthabs = 0;
  500. fs->lasttarget = 0;
  501. fs->freereg = 0;
  502. fs->nk = 0;
  503. fs->nabslineinfo = 0;
  504. fs->np = 0;
  505. fs->nups = 0;
  506. fs->nlocvars = 0;
  507. fs->nactvar = 0;
  508. fs->needclose = 0;
  509. fs->firstlocal = ls->dyd->actvar.n;
  510. fs->firstlabel = ls->dyd->label.n;
  511. fs->bl = NULL;
  512. f->source = ls->source;
  513. f->maxstacksize = 2; /* registers 0/1 are always valid */
  514. enterblock(fs, bl, 0);
  515. }
  516. static void close_func (LexState *ls) {
  517. lua_State *L = ls->L;
  518. FuncState *fs = ls->fs;
  519. Proto *f = fs->f;
  520. luaK_ret(fs, fs->nactvar, 0); /* final return */
  521. leaveblock(fs);
  522. lua_assert(fs->bl == NULL);
  523. luaK_finish(fs);
  524. luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction);
  525. luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte);
  526. luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo,
  527. fs->nabslineinfo, AbsLineInfo);
  528. luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue);
  529. luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *);
  530. luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
  531. luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
  532. ls->fs = fs->prev;
  533. luaC_checkGC(L);
  534. }
  535. /*============================================================*/
  536. /* GRAMMAR RULES */
  537. /*============================================================*/
  538. /*
  539. ** check whether current token is in the follow set of a block.
  540. ** 'until' closes syntactical blocks, but do not close scope,
  541. ** so it is handled in separate.
  542. */
  543. static int block_follow (LexState *ls, int withuntil) {
  544. switch (ls->t.token) {
  545. case TK_ELSE: case TK_ELSEIF:
  546. case TK_END: case TK_EOS:
  547. return 1;
  548. case TK_UNTIL: return withuntil;
  549. default: return 0;
  550. }
  551. }
  552. static void statlist (LexState *ls) {
  553. /* statlist -> { stat [';'] } */
  554. while (!block_follow(ls, 1)) {
  555. if (ls->t.token == TK_RETURN) {
  556. statement(ls);
  557. return; /* 'return' must be last statement */
  558. }
  559. statement(ls);
  560. }
  561. }
  562. static void fieldsel (LexState *ls, expdesc *v) {
  563. /* fieldsel -> ['.' | ':'] NAME */
  564. FuncState *fs = ls->fs;
  565. expdesc key;
  566. luaK_exp2anyregup(fs, v);
  567. luaX_next(ls); /* skip the dot or colon */
  568. codename(ls, &key);
  569. luaK_indexed(fs, v, &key);
  570. }
  571. static void yindex (LexState *ls, expdesc *v) {
  572. /* index -> '[' expr ']' */
  573. luaX_next(ls); /* skip the '[' */
  574. expr(ls, v);
  575. luaK_exp2val(ls->fs, v);
  576. checknext(ls, ']');
  577. }
  578. /*
  579. ** {======================================================================
  580. ** Rules for Constructors
  581. ** =======================================================================
  582. */
  583. struct ConsControl {
  584. expdesc v; /* last list item read */
  585. expdesc *t; /* table descriptor */
  586. int nh; /* total number of 'record' elements */
  587. int na; /* total number of array elements */
  588. int tostore; /* number of array elements pending to be stored */
  589. };
  590. static void recfield (LexState *ls, struct ConsControl *cc) {
  591. /* recfield -> (NAME | '['exp']') = exp */
  592. FuncState *fs = ls->fs;
  593. int reg = ls->fs->freereg;
  594. expdesc tab, key, val;
  595. if (ls->t.token == TK_NAME) {
  596. checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
  597. codename(ls, &key);
  598. }
  599. else /* ls->t.token == '[' */
  600. yindex(ls, &key);
  601. cc->nh++;
  602. checknext(ls, '=');
  603. tab = *cc->t;
  604. luaK_indexed(fs, &tab, &key);
  605. expr(ls, &val);
  606. luaK_storevar(fs, &tab, &val);
  607. fs->freereg = reg; /* free registers */
  608. }
  609. static void closelistfield (FuncState *fs, struct ConsControl *cc) {
  610. if (cc->v.k == VVOID) return; /* there is no list item */
  611. luaK_exp2nextreg(fs, &cc->v);
  612. cc->v.k = VVOID;
  613. if (cc->tostore == LFIELDS_PER_FLUSH) {
  614. luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
  615. cc->tostore = 0; /* no more items pending */
  616. }
  617. }
  618. static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
  619. if (cc->tostore == 0) return;
  620. if (hasmultret(cc->v.k)) {
  621. luaK_setmultret(fs, &cc->v);
  622. luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
  623. cc->na--; /* do not count last expression (unknown number of elements) */
  624. }
  625. else {
  626. if (cc->v.k != VVOID)
  627. luaK_exp2nextreg(fs, &cc->v);
  628. luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
  629. }
  630. }
  631. static void listfield (LexState *ls, struct ConsControl *cc) {
  632. /* listfield -> exp */
  633. expr(ls, &cc->v);
  634. checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
  635. cc->na++;
  636. cc->tostore++;
  637. }
  638. static void field (LexState *ls, struct ConsControl *cc) {
  639. /* field -> listfield | recfield */
  640. switch(ls->t.token) {
  641. case TK_NAME: { /* may be 'listfield' or 'recfield' */
  642. if (luaX_lookahead(ls) != '=') /* expression? */
  643. listfield(ls, cc);
  644. else
  645. recfield(ls, cc);
  646. break;
  647. }
  648. case '[': {
  649. recfield(ls, cc);
  650. break;
  651. }
  652. default: {
  653. listfield(ls, cc);
  654. break;
  655. }
  656. }
  657. }
  658. static void constructor (LexState *ls, expdesc *t) {
  659. /* constructor -> '{' [ field { sep field } [sep] ] '}'
  660. sep -> ',' | ';' */
  661. FuncState *fs = ls->fs;
  662. int line = ls->linenumber;
  663. int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  664. struct ConsControl cc;
  665. cc.na = cc.nh = cc.tostore = 0;
  666. cc.t = t;
  667. init_exp(t, VRELOC, pc);
  668. init_exp(&cc.v, VVOID, 0); /* no value (yet) */
  669. luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */
  670. checknext(ls, '{');
  671. do {
  672. lua_assert(cc.v.k == VVOID || cc.tostore > 0);
  673. if (ls->t.token == '}') break;
  674. closelistfield(fs, &cc);
  675. field(ls, &cc);
  676. } while (testnext(ls, ',') || testnext(ls, ';'));
  677. check_match(ls, '}', '{', line);
  678. lastlistfield(fs, &cc);
  679. SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
  680. SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
  681. }
  682. /* }====================================================================== */
  683. static void setvararg (FuncState *fs, int nparams) {
  684. fs->f->is_vararg = 1;
  685. luaK_codeABC(fs, OP_PREPVARARG, nparams, 0, 0);
  686. }
  687. static void parlist (LexState *ls) {
  688. /* parlist -> [ param { ',' param } ] */
  689. FuncState *fs = ls->fs;
  690. Proto *f = fs->f;
  691. int nparams = 0;
  692. int isvararg = 0;
  693. if (ls->t.token != ')') { /* is 'parlist' not empty? */
  694. do {
  695. switch (ls->t.token) {
  696. case TK_NAME: { /* param -> NAME */
  697. new_localvar(ls, str_checkname(ls));
  698. nparams++;
  699. break;
  700. }
  701. case TK_DOTS: { /* param -> '...' */
  702. luaX_next(ls);
  703. isvararg = 1;
  704. break;
  705. }
  706. default: luaX_syntaxerror(ls, "<name> or '...' expected");
  707. }
  708. } while (!isvararg && testnext(ls, ','));
  709. }
  710. adjustlocalvars(ls, nparams);
  711. f->numparams = cast_byte(fs->nactvar);
  712. if (isvararg)
  713. setvararg(fs, f->numparams); /* declared vararg */
  714. luaK_reserveregs(fs, fs->nactvar); /* reserve registers for parameters */
  715. }
  716. static void body (LexState *ls, expdesc *e, int ismethod, int line) {
  717. /* body -> '(' parlist ')' block END */
  718. FuncState new_fs;
  719. BlockCnt bl;
  720. new_fs.f = addprototype(ls);
  721. new_fs.f->linedefined = line;
  722. open_func(ls, &new_fs, &bl);
  723. checknext(ls, '(');
  724. if (ismethod) {
  725. new_localvarliteral(ls, "self"); /* create 'self' parameter */
  726. adjustlocalvars(ls, 1);
  727. }
  728. parlist(ls);
  729. checknext(ls, ')');
  730. statlist(ls);
  731. new_fs.f->lastlinedefined = ls->linenumber;
  732. check_match(ls, TK_END, TK_FUNCTION, line);
  733. codeclosure(ls, e);
  734. close_func(ls);
  735. }
  736. static int explist (LexState *ls, expdesc *v) {
  737. /* explist -> expr { ',' expr } */
  738. int n = 1; /* at least one expression */
  739. expr(ls, v);
  740. while (testnext(ls, ',')) {
  741. luaK_exp2nextreg(ls->fs, v);
  742. expr(ls, v);
  743. n++;
  744. }
  745. return n;
  746. }
  747. static void funcargs (LexState *ls, expdesc *f, int line) {
  748. FuncState *fs = ls->fs;
  749. expdesc args;
  750. int base, nparams;
  751. switch (ls->t.token) {
  752. case '(': { /* funcargs -> '(' [ explist ] ')' */
  753. luaX_next(ls);
  754. if (ls->t.token == ')') /* arg list is empty? */
  755. args.k = VVOID;
  756. else {
  757. explist(ls, &args);
  758. luaK_setmultret(fs, &args);
  759. }
  760. check_match(ls, ')', '(', line);
  761. break;
  762. }
  763. case '{': { /* funcargs -> constructor */
  764. constructor(ls, &args);
  765. break;
  766. }
  767. case TK_STRING: { /* funcargs -> STRING */
  768. codestring(ls, &args, ls->t.seminfo.ts);
  769. luaX_next(ls); /* must use 'seminfo' before 'next' */
  770. break;
  771. }
  772. default: {
  773. luaX_syntaxerror(ls, "function arguments expected");
  774. }
  775. }
  776. lua_assert(f->k == VNONRELOC);
  777. base = f->u.info; /* base register for call */
  778. if (hasmultret(args.k))
  779. nparams = LUA_MULTRET; /* open call */
  780. else {
  781. if (args.k != VVOID)
  782. luaK_exp2nextreg(fs, &args); /* close last argument */
  783. nparams = fs->freereg - (base+1);
  784. }
  785. init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
  786. luaK_fixline(fs, line);
  787. fs->freereg = base+1; /* call remove function and arguments and leaves
  788. (unless changed) one result */
  789. }
  790. /*
  791. ** {======================================================================
  792. ** Expression parsing
  793. ** =======================================================================
  794. */
  795. static void primaryexp (LexState *ls, expdesc *v) {
  796. /* primaryexp -> NAME | '(' expr ')' */
  797. switch (ls->t.token) {
  798. case '(': {
  799. int line = ls->linenumber;
  800. luaX_next(ls);
  801. expr(ls, v);
  802. check_match(ls, ')', '(', line);
  803. luaK_dischargevars(ls->fs, v);
  804. return;
  805. }
  806. case TK_NAME: {
  807. singlevar(ls, v);
  808. return;
  809. }
  810. default: {
  811. luaX_syntaxerror(ls, "unexpected symbol");
  812. }
  813. }
  814. }
  815. static void suffixedexp (LexState *ls, expdesc *v) {
  816. /* suffixedexp ->
  817. primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
  818. FuncState *fs = ls->fs;
  819. int line = ls->linenumber;
  820. primaryexp(ls, v);
  821. for (;;) {
  822. switch (ls->t.token) {
  823. case '.': { /* fieldsel */
  824. fieldsel(ls, v);
  825. break;
  826. }
  827. case '[': { /* '[' exp ']' */
  828. expdesc key;
  829. luaK_exp2anyregup(fs, v);
  830. yindex(ls, &key);
  831. luaK_indexed(fs, v, &key);
  832. break;
  833. }
  834. case ':': { /* ':' NAME funcargs */
  835. expdesc key;
  836. luaX_next(ls);
  837. codename(ls, &key);
  838. luaK_self(fs, v, &key);
  839. funcargs(ls, v, line);
  840. break;
  841. }
  842. case '(': case TK_STRING: case '{': { /* funcargs */
  843. luaK_exp2nextreg(fs, v);
  844. funcargs(ls, v, line);
  845. break;
  846. }
  847. default: return;
  848. }
  849. }
  850. }
  851. static void simpleexp (LexState *ls, expdesc *v) {
  852. /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
  853. constructor | FUNCTION body | suffixedexp */
  854. switch (ls->t.token) {
  855. case TK_FLT: {
  856. init_exp(v, VKFLT, 0);
  857. v->u.nval = ls->t.seminfo.r;
  858. break;
  859. }
  860. case TK_INT: {
  861. init_exp(v, VKINT, 0);
  862. v->u.ival = ls->t.seminfo.i;
  863. break;
  864. }
  865. case TK_STRING: {
  866. codestring(ls, v, ls->t.seminfo.ts);
  867. break;
  868. }
  869. case TK_NIL: {
  870. init_exp(v, VNIL, 0);
  871. break;
  872. }
  873. case TK_TRUE: {
  874. init_exp(v, VTRUE, 0);
  875. break;
  876. }
  877. case TK_FALSE: {
  878. init_exp(v, VFALSE, 0);
  879. break;
  880. }
  881. case TK_DOTS: { /* vararg */
  882. FuncState *fs = ls->fs;
  883. check_condition(ls, fs->f->is_vararg,
  884. "cannot use '...' outside a vararg function");
  885. init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 0, 1));
  886. break;
  887. }
  888. case '{': { /* constructor */
  889. constructor(ls, v);
  890. return;
  891. }
  892. case TK_FUNCTION: {
  893. luaX_next(ls);
  894. body(ls, v, 0, ls->linenumber);
  895. return;
  896. }
  897. default: {
  898. suffixedexp(ls, v);
  899. return;
  900. }
  901. }
  902. luaX_next(ls);
  903. }
  904. static UnOpr getunopr (int op) {
  905. switch (op) {
  906. case TK_NOT: return OPR_NOT;
  907. case '-': return OPR_MINUS;
  908. case '~': return OPR_BNOT;
  909. case '#': return OPR_LEN;
  910. default: return OPR_NOUNOPR;
  911. }
  912. }
  913. static BinOpr getbinopr (int op) {
  914. switch (op) {
  915. case '+': return OPR_ADD;
  916. case '-': return OPR_SUB;
  917. case '*': return OPR_MUL;
  918. case '%': return OPR_MOD;
  919. case '^': return OPR_POW;
  920. case '/': return OPR_DIV;
  921. case TK_IDIV: return OPR_IDIV;
  922. case '&': return OPR_BAND;
  923. case '|': return OPR_BOR;
  924. case '~': return OPR_BXOR;
  925. case TK_SHL: return OPR_SHL;
  926. case TK_SHR: return OPR_SHR;
  927. case TK_CONCAT: return OPR_CONCAT;
  928. case TK_NE: return OPR_NE;
  929. case TK_EQ: return OPR_EQ;
  930. case '<': return OPR_LT;
  931. case TK_LE: return OPR_LE;
  932. case '>': return OPR_GT;
  933. case TK_GE: return OPR_GE;
  934. case TK_AND: return OPR_AND;
  935. case TK_OR: return OPR_OR;
  936. default: return OPR_NOBINOPR;
  937. }
  938. }
  939. /*
  940. ** Priority table for binary operators.
  941. */
  942. static const struct {
  943. lu_byte left; /* left priority for each binary operator */
  944. lu_byte right; /* right priority */
  945. } priority[] = { /* ORDER OPR */
  946. {10, 10}, {10, 10}, /* '+' '-' */
  947. {11, 11}, {11, 11}, /* '*' '%' */
  948. {14, 13}, /* '^' (right associative) */
  949. {11, 11}, {11, 11}, /* '/' '//' */
  950. {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
  951. {7, 7}, {7, 7}, /* '<<' '>>' */
  952. {9, 8}, /* '..' (right associative) */
  953. {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
  954. {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
  955. {2, 2}, {1, 1} /* and, or */
  956. };
  957. #define UNARY_PRIORITY 12 /* priority for unary operators */
  958. /*
  959. ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
  960. ** where 'binop' is any binary operator with a priority higher than 'limit'
  961. */
  962. static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
  963. BinOpr op;
  964. UnOpr uop;
  965. enterlevel(ls);
  966. uop = getunopr(ls->t.token);
  967. if (uop != OPR_NOUNOPR) { /* prefix (unary) operator? */
  968. int line = ls->linenumber;
  969. luaX_next(ls); /* skip operator */
  970. subexpr(ls, v, UNARY_PRIORITY);
  971. luaK_prefix(ls->fs, uop, v, line);
  972. }
  973. else simpleexp(ls, v);
  974. /* expand while operators have priorities higher than 'limit' */
  975. op = getbinopr(ls->t.token);
  976. while (op != OPR_NOBINOPR && priority[op].left > limit) {
  977. expdesc v2;
  978. BinOpr nextop;
  979. int line = ls->linenumber;
  980. luaX_next(ls); /* skip operator */
  981. luaK_infix(ls->fs, op, v);
  982. /* read sub-expression with higher priority */
  983. nextop = subexpr(ls, &v2, priority[op].right);
  984. luaK_posfix(ls->fs, op, v, &v2, line);
  985. op = nextop;
  986. }
  987. leavelevel(ls);
  988. return op; /* return first untreated operator */
  989. }
  990. static void expr (LexState *ls, expdesc *v) {
  991. subexpr(ls, v, 0);
  992. }
  993. /* }==================================================================== */
  994. /*
  995. ** {======================================================================
  996. ** Rules for Statements
  997. ** =======================================================================
  998. */
  999. static void block (LexState *ls) {
  1000. /* block -> statlist */
  1001. FuncState *fs = ls->fs;
  1002. BlockCnt bl;
  1003. enterblock(fs, &bl, 0);
  1004. statlist(ls);
  1005. leaveblock(fs);
  1006. }
  1007. /*
  1008. ** structure to chain all variables in the left-hand side of an
  1009. ** assignment
  1010. */
  1011. struct LHS_assign {
  1012. struct LHS_assign *prev;
  1013. expdesc v; /* variable (global, local, upvalue, or indexed) */
  1014. };
  1015. /*
  1016. ** check whether, in an assignment to an upvalue/local variable, the
  1017. ** upvalue/local variable is begin used in a previous assignment to a
  1018. ** table. If so, save original upvalue/local value in a safe place and
  1019. ** use this safe copy in the previous assignment.
  1020. */
  1021. static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
  1022. FuncState *fs = ls->fs;
  1023. int extra = fs->freereg; /* eventual position to save local variable */
  1024. int conflict = 0;
  1025. for (; lh; lh = lh->prev) { /* check all previous assignments */
  1026. if (vkisindexed(lh->v.k)) { /* assignment to table field? */
  1027. if (lh->v.k == VINDEXUP) { /* is table an upvalue? */
  1028. if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) {
  1029. conflict = 1; /* table is the upvalue being assigned now */
  1030. lh->v.k = VINDEXSTR;
  1031. lh->v.u.ind.t = extra; /* assignment will use safe copy */
  1032. }
  1033. }
  1034. else { /* table is a register */
  1035. if (v->k == VLOCAL && lh->v.u.ind.t == v->u.info) {
  1036. conflict = 1; /* table is the local being assigned now */
  1037. lh->v.u.ind.t = extra; /* assignment will use safe copy */
  1038. }
  1039. /* is index the local being assigned? */
  1040. if (lh->v.k == VINDEXED && v->k == VLOCAL &&
  1041. lh->v.u.ind.idx == v->u.info) {
  1042. conflict = 1;
  1043. lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
  1044. }
  1045. }
  1046. }
  1047. }
  1048. if (conflict) {
  1049. /* copy upvalue/local value to a temporary (in position 'extra') */
  1050. OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
  1051. luaK_codeABC(fs, op, extra, v->u.info, 0);
  1052. luaK_reserveregs(fs, 1);
  1053. }
  1054. }
  1055. /*
  1056. ** Parse and compile a mulitple assignment. The first "variable"
  1057. ** (a 'suffixedexp') was already read by the caller.
  1058. **
  1059. ** assignment -> suffixedexp restassign
  1060. ** restassign -> ',' suffixedexp restassign | '=' explist
  1061. */
  1062. static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) {
  1063. expdesc e;
  1064. check_condition(ls, vkisvar(lh->v.k), "syntax error");
  1065. if (testnext(ls, ',')) { /* restassign -> ',' suffixedexp restassign */
  1066. struct LHS_assign nv;
  1067. nv.prev = lh;
  1068. suffixedexp(ls, &nv.v);
  1069. if (!vkisindexed(nv.v.k))
  1070. check_conflict(ls, lh, &nv.v);
  1071. enterlevel(ls); /* control recursion depth */
  1072. restassign(ls, &nv, nvars+1);
  1073. leavelevel(ls);
  1074. }
  1075. else { /* restassign -> '=' explist */
  1076. int nexps;
  1077. checknext(ls, '=');
  1078. nexps = explist(ls, &e);
  1079. if (nexps != nvars)
  1080. adjust_assign(ls, nvars, nexps, &e);
  1081. else {
  1082. luaK_setoneret(ls->fs, &e); /* close last expression */
  1083. luaK_storevar(ls->fs, &lh->v, &e);
  1084. return; /* avoid default */
  1085. }
  1086. }
  1087. init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
  1088. luaK_storevar(ls->fs, &lh->v, &e);
  1089. }
  1090. static int cond (LexState *ls) {
  1091. /* cond -> exp */
  1092. expdesc v;
  1093. expr(ls, &v); /* read condition */
  1094. if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */
  1095. luaK_goiftrue(ls->fs, &v);
  1096. return v.f;
  1097. }
  1098. static void gotostat (LexState *ls) {
  1099. FuncState *fs = ls->fs;
  1100. int line = ls->linenumber;
  1101. TString *name = str_checkname(ls); /* label's name */
  1102. Labeldesc *lb = findlabel(ls, name);
  1103. if (lb == NULL) /* no label? */
  1104. /* forward jump; will be resolved when the label is declared */
  1105. newgotoentry(ls, name, line, luaK_jump(fs));
  1106. else { /* found a label */
  1107. /* backward jump; will be resolved here */
  1108. if (fs->nactvar > lb->nactvar) /* leaving the scope of some variable? */
  1109. luaK_codeABC(fs, OP_CLOSE, lb->nactvar, 0, 0);
  1110. /* create jump and link it to the label */
  1111. luaK_patchlist(fs, luaK_jump(fs), lb->pc);
  1112. }
  1113. }
  1114. /*
  1115. ** Break statement. Semantically equivalent to "goto break".
  1116. */
  1117. static void breakstat (LexState *ls) {
  1118. int line = ls->linenumber;
  1119. luaX_next(ls); /* skip break */
  1120. newgotoentry(ls, luaS_newliteral(ls->L, "break"), line, luaK_jump(ls->fs));
  1121. }
  1122. /*
  1123. ** Check whether there is already a label with the given 'name'.
  1124. */
  1125. static void checkrepeated (LexState *ls, TString *name) {
  1126. Labeldesc *lb = findlabel(ls, name);
  1127. if (unlikely(lb != NULL)) { /* already defined? */
  1128. const char *msg = "label '%s' already defined on line %d";
  1129. msg = luaO_pushfstring(ls->L, msg, getstr(name), lb->line);
  1130. luaK_semerror(ls, msg); /* error */
  1131. }
  1132. }
  1133. static void labelstat (LexState *ls, TString *name, int line) {
  1134. /* label -> '::' NAME '::' */
  1135. checknext(ls, TK_DBCOLON); /* skip double colon */
  1136. while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
  1137. statement(ls); /* skip other no-op statements */
  1138. checkrepeated(ls, name); /* check for repeated labels */
  1139. createlabel(ls, name, line, block_follow(ls, 0));
  1140. }
  1141. static void whilestat (LexState *ls, int line) {
  1142. /* whilestat -> WHILE cond DO block END */
  1143. FuncState *fs = ls->fs;
  1144. int whileinit;
  1145. int condexit;
  1146. BlockCnt bl;
  1147. luaX_next(ls); /* skip WHILE */
  1148. whileinit = luaK_getlabel(fs);
  1149. condexit = cond(ls);
  1150. enterblock(fs, &bl, 1);
  1151. checknext(ls, TK_DO);
  1152. block(ls);
  1153. luaK_jumpto(fs, whileinit);
  1154. check_match(ls, TK_END, TK_WHILE, line);
  1155. leaveblock(fs);
  1156. luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
  1157. }
  1158. static void repeatstat (LexState *ls, int line) {
  1159. /* repeatstat -> REPEAT block UNTIL cond */
  1160. int condexit;
  1161. FuncState *fs = ls->fs;
  1162. int repeat_init = luaK_getlabel(fs);
  1163. BlockCnt bl1, bl2;
  1164. enterblock(fs, &bl1, 1); /* loop block */
  1165. enterblock(fs, &bl2, 0); /* scope block */
  1166. luaX_next(ls); /* skip REPEAT */
  1167. statlist(ls);
  1168. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  1169. condexit = cond(ls); /* read condition (inside scope block) */
  1170. leaveblock(fs); /* finish scope */
  1171. if (bl2.upval) { /* upvalues? */
  1172. int exit = luaK_jump(fs); /* normal exit must jump over fix */
  1173. luaK_patchtohere(fs, condexit); /* repetition must close upvalues */
  1174. luaK_codeABC(fs, OP_CLOSE, bl2.nactvar, 0, 0);
  1175. condexit = luaK_jump(fs); /* repeat after closing upvalues */
  1176. luaK_patchtohere(fs, exit); /* normal exit comes to here */
  1177. }
  1178. luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
  1179. leaveblock(fs); /* finish loop */
  1180. }
  1181. /*
  1182. ** Read an expression and generate code to put its results in next
  1183. ** stack slot. Return true if expression is a constant integer and,
  1184. ** if 'i' is not-zero, its value is equal to 'i'.
  1185. **
  1186. */
  1187. static int exp1 (LexState *ls, int i) {
  1188. expdesc e;
  1189. int res;
  1190. expr(ls, &e);
  1191. res = luaK_isKint(&e) && (i == 0 || i == e.u.ival);
  1192. luaK_exp2nextreg(ls->fs, &e);
  1193. lua_assert(e.k == VNONRELOC);
  1194. return res;
  1195. }
  1196. /*
  1197. ** Fix for instruction at position 'pc' to jump to 'dest'.
  1198. ** (Jump addresses are relative in Lua). 'back' true means
  1199. ** a back jump.
  1200. */
  1201. static void fixforjump (FuncState *fs, int pc, int dest, int back) {
  1202. Instruction *jmp = &fs->f->code[pc];
  1203. int offset = dest - (pc + 1);
  1204. if (back)
  1205. offset = -offset;
  1206. if (unlikely(offset > MAXARG_Bx))
  1207. luaX_syntaxerror(fs->ls, "control structure too long");
  1208. SETARG_Bx(*jmp, offset);
  1209. }
  1210. /*
  1211. ** Generate code for a 'for' loop. 'kind' can be zero (a common for
  1212. ** loop), one (a basic for loop, with integer values and increment of
  1213. ** 1), or two (a generic for loop).
  1214. */
  1215. static void forbody (LexState *ls, int base, int line, int nvars, int kind) {
  1216. /* forbody -> DO block */
  1217. static OpCode forprep[3] = {OP_FORPREP, OP_FORPREP1, OP_TFORPREP};
  1218. static OpCode forloop[3] = {OP_FORLOOP, OP_FORLOOP1, OP_TFORLOOP};
  1219. BlockCnt bl;
  1220. FuncState *fs = ls->fs;
  1221. int prep, endfor;
  1222. checknext(ls, TK_DO);
  1223. prep = luaK_codeABx(fs, forprep[kind], base, 0);
  1224. enterblock(fs, &bl, 0); /* scope for declared variables */
  1225. adjustlocalvars(ls, nvars);
  1226. luaK_reserveregs(fs, nvars);
  1227. block(ls);
  1228. leaveblock(fs); /* end of scope for declared variables */
  1229. fixforjump(fs, prep, luaK_getlabel(fs), 0);
  1230. if (kind == 2) { /* generic for? */
  1231. luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
  1232. luaK_fixline(fs, line);
  1233. base += 2; /* base for 'OP_TFORLOOP' (skips function and state) */
  1234. }
  1235. endfor = luaK_codeABx(fs, forloop[kind], base, 0);
  1236. fixforjump(fs, endfor, prep + 1, 1);
  1237. luaK_fixline(fs, line);
  1238. }
  1239. static void fornum (LexState *ls, TString *varname, int line) {
  1240. /* fornum -> NAME = exp,exp[,exp] forbody */
  1241. FuncState *fs = ls->fs;
  1242. int base = fs->freereg;
  1243. int basicfor = 1; /* true if it is a "basic" 'for' (integer + 1) */
  1244. new_localvarliteral(ls, "(for index)");
  1245. new_localvarliteral(ls, "(for limit)");
  1246. new_localvarliteral(ls, "(for step)");
  1247. new_localvar(ls, varname);
  1248. checknext(ls, '=');
  1249. if (!exp1(ls, 0)) /* initial value not an integer? */
  1250. basicfor = 0; /* not a basic 'for' */
  1251. checknext(ls, ',');
  1252. exp1(ls, 0); /* limit */
  1253. if (testnext(ls, ',')) {
  1254. if (!exp1(ls, 1)) /* optional step not 1? */
  1255. basicfor = 0; /* not a basic 'for' */
  1256. }
  1257. else { /* default step = 1 */
  1258. luaK_int(fs, fs->freereg, 1);
  1259. luaK_reserveregs(fs, 1);
  1260. }
  1261. adjustlocalvars(ls, 3); /* control variables */
  1262. forbody(ls, base, line, 1, basicfor);
  1263. }
  1264. static void forlist (LexState *ls, TString *indexname) {
  1265. /* forlist -> NAME {,NAME} IN explist forbody */
  1266. FuncState *fs = ls->fs;
  1267. expdesc e;
  1268. int nvars = 5; /* gen, state, control, toclose, 'indexname' */
  1269. int line;
  1270. int base = fs->freereg;
  1271. /* create control variables */
  1272. new_localvarliteral(ls, "(for generator)");
  1273. new_localvarliteral(ls, "(for state)");
  1274. markupval(fs, fs->nactvar); /* state may create an upvalue */
  1275. new_localvarliteral(ls, "(for control)");
  1276. new_localvarliteral(ls, "(for toclose)");
  1277. /* create declared variables */
  1278. new_localvar(ls, indexname);
  1279. while (testnext(ls, ',')) {
  1280. new_localvar(ls, str_checkname(ls));
  1281. nvars++;
  1282. }
  1283. checknext(ls, TK_IN);
  1284. line = ls->linenumber;
  1285. adjust_assign(ls, 4, explist(ls, &e), &e);
  1286. adjustlocalvars(ls, 4); /* control variables */
  1287. luaK_checkstack(fs, 3); /* extra space to call generator */
  1288. forbody(ls, base, line, nvars - 4, 2);
  1289. }
  1290. static void forstat (LexState *ls, int line) {
  1291. /* forstat -> FOR (fornum | forlist) END */
  1292. FuncState *fs = ls->fs;
  1293. TString *varname;
  1294. BlockCnt bl;
  1295. enterblock(fs, &bl, 1); /* scope for loop and control variables */
  1296. luaX_next(ls); /* skip 'for' */
  1297. varname = str_checkname(ls); /* first variable name */
  1298. switch (ls->t.token) {
  1299. case '=': fornum(ls, varname, line); break;
  1300. case ',': case TK_IN: forlist(ls, varname); break;
  1301. default: luaX_syntaxerror(ls, "'=' or 'in' expected");
  1302. }
  1303. check_match(ls, TK_END, TK_FOR, line);
  1304. leaveblock(fs); /* loop scope ('break' jumps to this point) */
  1305. }
  1306. /*
  1307. ** Check whether next instruction is a single jump (a 'break', a 'goto'
  1308. ** to a forward label, or a 'goto' to a backward label with no variable
  1309. ** to close). If so, set the name of the 'label' it is jumping to
  1310. ** ("break" for a 'break') or to where it is jumping to ('target') and
  1311. ** return true. If not a single jump, leave input unchanged, to be
  1312. ** handled as a regular statement.
  1313. */
  1314. static int issinglejump (LexState *ls, TString **label, int *target) {
  1315. if (testnext(ls, TK_BREAK)) { /* a break? */
  1316. *label = luaS_newliteral(ls->L, "break");
  1317. return 1;
  1318. }
  1319. else if (ls->t.token != TK_GOTO || luaX_lookahead(ls) != TK_NAME)
  1320. return 0; /* not a valid goto */
  1321. else {
  1322. TString *lname = ls->lookahead.seminfo.ts; /* label's id */
  1323. Labeldesc *lb = findlabel(ls, lname);
  1324. if (lb) { /* a backward jump? */
  1325. if (ls->fs->nactvar > lb->nactvar) /* needs to close variables? */
  1326. return 0; /* not a single jump; cannot optimize */
  1327. *target = lb->pc;
  1328. }
  1329. else /* jump forward */
  1330. *label = lname;
  1331. luaX_next(ls); /* skip goto */
  1332. luaX_next(ls); /* skip name */
  1333. return 1;
  1334. }
  1335. }
  1336. static void test_then_block (LexState *ls, int *escapelist) {
  1337. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  1338. BlockCnt bl;
  1339. int line;
  1340. FuncState *fs = ls->fs;
  1341. TString *jlb = NULL;
  1342. int target = NO_JUMP;
  1343. expdesc v;
  1344. int jf; /* instruction to skip 'then' code (if condition is false) */
  1345. luaX_next(ls); /* skip IF or ELSEIF */
  1346. expr(ls, &v); /* read condition */
  1347. checknext(ls, TK_THEN);
  1348. line = ls->linenumber;
  1349. if (issinglejump(ls, &jlb, &target)) { /* 'if x then goto' ? */
  1350. luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */
  1351. enterblock(fs, &bl, 0); /* must enter block before 'goto' */
  1352. if (jlb != NULL) /* forward jump? */
  1353. newgotoentry(ls, jlb, line, v.t); /* will be resolved later */
  1354. else /* backward jump */
  1355. luaK_patchlist(fs, v.t, target); /* jump directly to 'target' */
  1356. while (testnext(ls, ';')) {} /* skip semicolons */
  1357. if (block_follow(ls, 0)) { /* jump is the entire block? */
  1358. leaveblock(fs);
  1359. return; /* and that is it */
  1360. }
  1361. else /* must skip over 'then' part if condition is false */
  1362. jf = luaK_jump(fs);
  1363. }
  1364. else { /* regular case (not a jump) */
  1365. luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */
  1366. enterblock(fs, &bl, 0);
  1367. jf = v.f;
  1368. }
  1369. statlist(ls); /* 'then' part */
  1370. leaveblock(fs);
  1371. if (ls->t.token == TK_ELSE ||
  1372. ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
  1373. luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
  1374. luaK_patchtohere(fs, jf);
  1375. }
  1376. static void ifstat (LexState *ls, int line) {
  1377. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  1378. FuncState *fs = ls->fs;
  1379. int escapelist = NO_JUMP; /* exit list for finished parts */
  1380. test_then_block(ls, &escapelist); /* IF cond THEN block */
  1381. while (ls->t.token == TK_ELSEIF)
  1382. test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
  1383. if (testnext(ls, TK_ELSE))
  1384. block(ls); /* 'else' part */
  1385. check_match(ls, TK_END, TK_IF, line);
  1386. luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
  1387. }
  1388. static void localfunc (LexState *ls) {
  1389. expdesc b;
  1390. FuncState *fs = ls->fs;
  1391. new_localvar(ls, str_checkname(ls)); /* new local variable */
  1392. adjustlocalvars(ls, 1); /* enter its scope */
  1393. body(ls, &b, 0, ls->linenumber); /* function created in next register */
  1394. /* debug information will only see the variable after this point! */
  1395. getlocvar(fs, b.u.info)->startpc = fs->pc;
  1396. }
  1397. static void commonlocalstat (LexState *ls) {
  1398. /* stat -> LOCAL NAME {',' NAME} ['=' explist] */
  1399. int nvars = 0;
  1400. int nexps;
  1401. expdesc e;
  1402. do {
  1403. new_localvar(ls, str_checkname(ls));
  1404. nvars++;
  1405. } while (testnext(ls, ','));
  1406. if (testnext(ls, '='))
  1407. nexps = explist(ls, &e);
  1408. else {
  1409. e.k = VVOID;
  1410. nexps = 0;
  1411. }
  1412. adjust_assign(ls, nvars, nexps, &e);
  1413. adjustlocalvars(ls, nvars);
  1414. }
  1415. static void tocloselocalstat (LexState *ls) {
  1416. FuncState *fs = ls->fs;
  1417. TString *attr = str_checkname(ls);
  1418. if (strcmp(getstr(attr), "toclose") != 0)
  1419. luaK_semerror(ls,
  1420. luaO_pushfstring(ls->L, "unknown attribute '%s'", getstr(attr)));
  1421. new_localvar(ls, str_checkname(ls));
  1422. checknext(ls, '=');
  1423. exp1(ls, 0);
  1424. markupval(fs, fs->nactvar);
  1425. adjustlocalvars(ls, 1);
  1426. luaK_codeABC(fs, OP_TBC, fs->nactvar - 1, 0, 0);
  1427. }
  1428. static void localstat (LexState *ls) {
  1429. /* stat -> LOCAL NAME {',' NAME} ['=' explist]
  1430. | LOCAL *toclose NAME '=' exp */
  1431. if (testnext(ls, '*'))
  1432. tocloselocalstat(ls);
  1433. else
  1434. commonlocalstat(ls);
  1435. }
  1436. static int funcname (LexState *ls, expdesc *v) {
  1437. /* funcname -> NAME {fieldsel} [':' NAME] */
  1438. int ismethod = 0;
  1439. singlevar(ls, v);
  1440. while (ls->t.token == '.')
  1441. fieldsel(ls, v);
  1442. if (ls->t.token == ':') {
  1443. ismethod = 1;
  1444. fieldsel(ls, v);
  1445. }
  1446. return ismethod;
  1447. }
  1448. static void funcstat (LexState *ls, int line) {
  1449. /* funcstat -> FUNCTION funcname body */
  1450. int ismethod;
  1451. expdesc v, b;
  1452. luaX_next(ls); /* skip FUNCTION */
  1453. ismethod = funcname(ls, &v);
  1454. body(ls, &b, ismethod, line);
  1455. luaK_storevar(ls->fs, &v, &b);
  1456. luaK_fixline(ls->fs, line); /* definition "happens" in the first line */
  1457. }
  1458. static void exprstat (LexState *ls) {
  1459. /* stat -> func | assignment */
  1460. FuncState *fs = ls->fs;
  1461. struct LHS_assign v;
  1462. suffixedexp(ls, &v.v);
  1463. if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
  1464. v.prev = NULL;
  1465. restassign(ls, &v, 1);
  1466. }
  1467. else { /* stat -> func */
  1468. Instruction *inst = &getinstruction(fs, &v.v);
  1469. check_condition(ls, v.v.k == VCALL, "syntax error");
  1470. SETARG_C(*inst, 1); /* call statement uses no results */
  1471. }
  1472. }
  1473. static void retstat (LexState *ls) {
  1474. /* stat -> RETURN [explist] [';'] */
  1475. FuncState *fs = ls->fs;
  1476. expdesc e;
  1477. int nret; /* number of values being returned */
  1478. int first = fs->nactvar; /* first slot to be returned */
  1479. if (block_follow(ls, 1) || ls->t.token == ';')
  1480. nret = 0; /* return no values */
  1481. else {
  1482. nret = explist(ls, &e); /* optional return values */
  1483. if (hasmultret(e.k)) {
  1484. luaK_setmultret(fs, &e);
  1485. if (e.k == VCALL && nret == 1) { /* tail call? */
  1486. SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);
  1487. lua_assert(GETARG_A(getinstruction(fs,&e)) == fs->nactvar);
  1488. }
  1489. nret = LUA_MULTRET; /* return all values */
  1490. }
  1491. else {
  1492. if (nret == 1) /* only one single value? */
  1493. first = luaK_exp2anyreg(fs, &e); /* can use original slot */
  1494. else { /* values must go to the top of the stack */
  1495. luaK_exp2nextreg(fs, &e);
  1496. lua_assert(nret == fs->freereg - first);
  1497. }
  1498. }
  1499. }
  1500. luaK_ret(fs, first, nret);
  1501. testnext(ls, ';'); /* skip optional semicolon */
  1502. }
  1503. static void statement (LexState *ls) {
  1504. int line = ls->linenumber; /* may be needed for error messages */
  1505. enterlevel(ls);
  1506. switch (ls->t.token) {
  1507. case ';': { /* stat -> ';' (empty statement) */
  1508. luaX_next(ls); /* skip ';' */
  1509. break;
  1510. }
  1511. case TK_IF: { /* stat -> ifstat */
  1512. ifstat(ls, line);
  1513. break;
  1514. }
  1515. case TK_WHILE: { /* stat -> whilestat */
  1516. whilestat(ls, line);
  1517. break;
  1518. }
  1519. case TK_DO: { /* stat -> DO block END */
  1520. luaX_next(ls); /* skip DO */
  1521. block(ls);
  1522. check_match(ls, TK_END, TK_DO, line);
  1523. break;
  1524. }
  1525. case TK_FOR: { /* stat -> forstat */
  1526. forstat(ls, line);
  1527. break;
  1528. }
  1529. case TK_REPEAT: { /* stat -> repeatstat */
  1530. repeatstat(ls, line);
  1531. break;
  1532. }
  1533. case TK_FUNCTION: { /* stat -> funcstat */
  1534. funcstat(ls, line);
  1535. break;
  1536. }
  1537. case TK_LOCAL: { /* stat -> localstat */
  1538. luaX_next(ls); /* skip LOCAL */
  1539. if (testnext(ls, TK_FUNCTION)) /* local function? */
  1540. localfunc(ls);
  1541. else
  1542. localstat(ls);
  1543. break;
  1544. }
  1545. case TK_DBCOLON: { /* stat -> label */
  1546. luaX_next(ls); /* skip double colon */
  1547. labelstat(ls, str_checkname(ls), line);
  1548. break;
  1549. }
  1550. case TK_RETURN: { /* stat -> retstat */
  1551. luaX_next(ls); /* skip RETURN */
  1552. retstat(ls);
  1553. break;
  1554. }
  1555. case TK_BREAK: { /* stat -> breakstat */
  1556. breakstat(ls);
  1557. break;
  1558. }
  1559. case TK_GOTO: { /* stat -> 'goto' NAME */
  1560. luaX_next(ls); /* skip 'goto' */
  1561. gotostat(ls);
  1562. break;
  1563. }
  1564. default: { /* stat -> func | assignment */
  1565. exprstat(ls);
  1566. break;
  1567. }
  1568. }
  1569. lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
  1570. ls->fs->freereg >= ls->fs->nactvar);
  1571. ls->fs->freereg = ls->fs->nactvar; /* free registers */
  1572. leavelevel(ls);
  1573. }
  1574. /* }====================================================================== */
  1575. /*
  1576. ** compiles the main function, which is a regular vararg function with an
  1577. ** upvalue named LUA_ENV
  1578. */
  1579. static void mainfunc (LexState *ls, FuncState *fs) {
  1580. BlockCnt bl;
  1581. expdesc v;
  1582. open_func(ls, fs, &bl);
  1583. setvararg(fs, 0); /* main function is always declared vararg */
  1584. init_exp(&v, VLOCAL, 0); /* create and... */
  1585. newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */
  1586. luaX_next(ls); /* read first token */
  1587. statlist(ls); /* parse main body */
  1588. check(ls, TK_EOS);
  1589. close_func(ls);
  1590. }
  1591. LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
  1592. Dyndata *dyd, const char *name, int firstchar) {
  1593. LexState lexstate;
  1594. FuncState funcstate;
  1595. LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */
  1596. setclLvalue2s(L, L->top, cl); /* anchor it (to avoid being collected) */
  1597. luaD_inctop(L);
  1598. lexstate.h = luaH_new(L); /* create table for scanner */
  1599. sethvalue2s(L, L->top, lexstate.h); /* anchor it */
  1600. luaD_inctop(L);
  1601. funcstate.f = cl->p = luaF_newproto(L);
  1602. funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
  1603. luaC_objbarrier(L, funcstate.f, funcstate.f->source);
  1604. lexstate.buff = buff;
  1605. lexstate.dyd = dyd;
  1606. dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
  1607. luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
  1608. mainfunc(&lexstate, &funcstate);
  1609. lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
  1610. /* all scopes should be correctly finished */
  1611. lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
  1612. L->top--; /* remove scanner's table */
  1613. return cl; /* closure is on the stack, too */
  1614. }