lparser.c 56 KB

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