lparser.c 48 KB

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