lparser.c 51 KB

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