lparser.c 60 KB

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