lparser.c 45 KB

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