lparser.c 55 KB

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