lparser.c 56 KB

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