lparser.c 53 KB

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