lparser.c 64 KB

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