lparser.c 55 KB

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