lparser.c 48 KB

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