lparser.c 46 KB

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