lparser.c 56 KB

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