lparser.c 44 KB

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