lparser.c 53 KB

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