lparser.c 54 KB

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