lparser.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  1. /*
  2. ** $Id: lparser.c,v 2.132 2013/04/25 19:35:19 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 l_noret 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 l_noret error_expected (LexState *ls, int token) {
  56. luaX_syntaxerror(ls,
  57. luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
  58. }
  59. static l_noret 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 (luaS_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 = cast_int(fs->nactvar) - 1; i >= 0; i--) {
  185. if (luaS_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, "C 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(luaS_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 (luaS_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 (luaS_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 l_noret undefgoto (LexState *ls, Labeldesc *gt) {
  373. const char *msg = isreserved(gt->name)
  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 a new prototype into list of prototypes
  402. */
  403. static Proto *addprototype (LexState *ls) {
  404. Proto *clp;
  405. lua_State *L = ls->L;
  406. FuncState *fs = ls->fs;
  407. Proto *f = fs->f; /* prototype of current function */
  408. if (fs->np >= f->sizep) {
  409. int oldsize = f->sizep;
  410. luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
  411. while (oldsize < f->sizep) f->p[oldsize++] = NULL;
  412. }
  413. f->p[fs->np++] = clp = luaF_newproto(L);
  414. luaC_objbarrier(L, f, clp);
  415. return clp;
  416. }
  417. /*
  418. ** codes instruction to create new closure in parent function.
  419. ** The OP_CLOSURE instruction must use the last available register,
  420. ** so that, if it invokes the GC, the GC knows which registers
  421. ** are in use at that time.
  422. */
  423. static void codeclosure (LexState *ls, expdesc *v) {
  424. FuncState *fs = ls->fs->prev;
  425. init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
  426. luaK_exp2nextreg(fs, v); /* fix it at the last register */
  427. }
  428. static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
  429. lua_State *L = ls->L;
  430. Proto *f;
  431. fs->prev = ls->fs; /* linked list of funcstates */
  432. fs->ls = ls;
  433. ls->fs = fs;
  434. fs->pc = 0;
  435. fs->lasttarget = 0;
  436. fs->jpc = NO_JUMP;
  437. fs->freereg = 0;
  438. fs->nk = 0;
  439. fs->np = 0;
  440. fs->nups = 0;
  441. fs->nlocvars = 0;
  442. fs->nactvar = 0;
  443. fs->firstlocal = ls->dyd->actvar.n;
  444. fs->bl = NULL;
  445. f = fs->f;
  446. f->source = ls->source;
  447. f->maxstacksize = 2; /* registers 0/1 are always valid */
  448. fs->h = luaH_new(L);
  449. /* anchor table of constants (to avoid being collected) */
  450. sethvalue2s(L, L->top, fs->h);
  451. incr_top(L);
  452. enterblock(fs, bl, 0);
  453. }
  454. static void close_func (LexState *ls) {
  455. lua_State *L = ls->L;
  456. FuncState *fs = ls->fs;
  457. Proto *f = fs->f;
  458. luaK_ret(fs, 0, 0); /* final return */
  459. leaveblock(fs);
  460. luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
  461. f->sizecode = fs->pc;
  462. luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
  463. f->sizelineinfo = fs->pc;
  464. luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
  465. f->sizek = fs->nk;
  466. luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
  467. f->sizep = fs->np;
  468. luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
  469. f->sizelocvars = fs->nlocvars;
  470. luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
  471. f->sizeupvalues = fs->nups;
  472. lua_assert(fs->bl == NULL);
  473. ls->fs = fs->prev;
  474. /* last token read was anchored in defunct function; must re-anchor it */
  475. anchor_token(ls);
  476. L->top--; /* pop table of constants */
  477. luaC_checkGC(L);
  478. }
  479. /*============================================================*/
  480. /* GRAMMAR RULES */
  481. /*============================================================*/
  482. /*
  483. ** check whether current token is in the follow set of a block.
  484. ** 'until' closes syntactical blocks, but do not close scope,
  485. ** so it handled in separate.
  486. */
  487. static int block_follow (LexState *ls, int withuntil) {
  488. switch (ls->t.token) {
  489. case TK_ELSE: case TK_ELSEIF:
  490. case TK_END: case TK_EOS:
  491. return 1;
  492. case TK_UNTIL: return withuntil;
  493. default: return 0;
  494. }
  495. }
  496. static void statlist (LexState *ls) {
  497. /* statlist -> { stat [`;'] } */
  498. while (!block_follow(ls, 1)) {
  499. if (ls->t.token == TK_RETURN) {
  500. statement(ls);
  501. return; /* 'return' must be last statement */
  502. }
  503. statement(ls);
  504. }
  505. }
  506. static void fieldsel (LexState *ls, expdesc *v) {
  507. /* fieldsel -> ['.' | ':'] NAME */
  508. FuncState *fs = ls->fs;
  509. expdesc key;
  510. luaK_exp2anyregup(fs, v);
  511. luaX_next(ls); /* skip the dot or colon */
  512. checkname(ls, &key);
  513. luaK_indexed(fs, v, &key);
  514. }
  515. static void yindex (LexState *ls, expdesc *v) {
  516. /* index -> '[' expr ']' */
  517. luaX_next(ls); /* skip the '[' */
  518. expr(ls, v);
  519. luaK_exp2val(ls->fs, v);
  520. checknext(ls, ']');
  521. }
  522. /*
  523. ** {======================================================================
  524. ** Rules for Constructors
  525. ** =======================================================================
  526. */
  527. struct ConsControl {
  528. expdesc v; /* last list item read */
  529. expdesc *t; /* table descriptor */
  530. int nh; /* total number of `record' elements */
  531. int na; /* total number of array elements */
  532. int tostore; /* number of array elements pending to be stored */
  533. };
  534. static void recfield (LexState *ls, struct ConsControl *cc) {
  535. /* recfield -> (NAME | `['exp1`]') = exp1 */
  536. FuncState *fs = ls->fs;
  537. int reg = ls->fs->freereg;
  538. expdesc key, val;
  539. int rkkey;
  540. if (ls->t.token == TK_NAME) {
  541. checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
  542. checkname(ls, &key);
  543. }
  544. else /* ls->t.token == '[' */
  545. yindex(ls, &key);
  546. cc->nh++;
  547. checknext(ls, '=');
  548. rkkey = luaK_exp2RK(fs, &key);
  549. expr(ls, &val);
  550. luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val));
  551. fs->freereg = reg; /* free registers */
  552. }
  553. static void closelistfield (FuncState *fs, struct ConsControl *cc) {
  554. if (cc->v.k == VVOID) return; /* there is no list item */
  555. luaK_exp2nextreg(fs, &cc->v);
  556. cc->v.k = VVOID;
  557. if (cc->tostore == LFIELDS_PER_FLUSH) {
  558. luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
  559. cc->tostore = 0; /* no more items pending */
  560. }
  561. }
  562. static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
  563. if (cc->tostore == 0) return;
  564. if (hasmultret(cc->v.k)) {
  565. luaK_setmultret(fs, &cc->v);
  566. luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
  567. cc->na--; /* do not count last expression (unknown number of elements) */
  568. }
  569. else {
  570. if (cc->v.k != VVOID)
  571. luaK_exp2nextreg(fs, &cc->v);
  572. luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
  573. }
  574. }
  575. static void listfield (LexState *ls, struct ConsControl *cc) {
  576. /* listfield -> exp */
  577. expr(ls, &cc->v);
  578. checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
  579. cc->na++;
  580. cc->tostore++;
  581. }
  582. static void field (LexState *ls, struct ConsControl *cc) {
  583. /* field -> listfield | recfield */
  584. switch(ls->t.token) {
  585. case TK_NAME: { /* may be 'listfield' or 'recfield' */
  586. if (luaX_lookahead(ls) != '=') /* expression? */
  587. listfield(ls, cc);
  588. else
  589. recfield(ls, cc);
  590. break;
  591. }
  592. case '[': {
  593. recfield(ls, cc);
  594. break;
  595. }
  596. default: {
  597. listfield(ls, cc);
  598. break;
  599. }
  600. }
  601. }
  602. static void constructor (LexState *ls, expdesc *t) {
  603. /* constructor -> '{' [ field { sep field } [sep] ] '}'
  604. sep -> ',' | ';' */
  605. FuncState *fs = ls->fs;
  606. int line = ls->linenumber;
  607. int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  608. struct ConsControl cc;
  609. cc.na = cc.nh = cc.tostore = 0;
  610. cc.t = t;
  611. init_exp(t, VRELOCABLE, pc);
  612. init_exp(&cc.v, VVOID, 0); /* no value (yet) */
  613. luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */
  614. checknext(ls, '{');
  615. do {
  616. lua_assert(cc.v.k == VVOID || cc.tostore > 0);
  617. if (ls->t.token == '}') break;
  618. closelistfield(fs, &cc);
  619. field(ls, &cc);
  620. } while (testnext(ls, ',') || testnext(ls, ';'));
  621. check_match(ls, '}', '{', line);
  622. lastlistfield(fs, &cc);
  623. SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
  624. SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
  625. }
  626. /* }====================================================================== */
  627. static void parlist (LexState *ls) {
  628. /* parlist -> [ param { `,' param } ] */
  629. FuncState *fs = ls->fs;
  630. Proto *f = fs->f;
  631. int nparams = 0;
  632. f->is_vararg = 0;
  633. if (ls->t.token != ')') { /* is `parlist' not empty? */
  634. do {
  635. switch (ls->t.token) {
  636. case TK_NAME: { /* param -> NAME */
  637. new_localvar(ls, str_checkname(ls));
  638. nparams++;
  639. break;
  640. }
  641. case TK_DOTS: { /* param -> `...' */
  642. luaX_next(ls);
  643. f->is_vararg = 1;
  644. break;
  645. }
  646. default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
  647. }
  648. } while (!f->is_vararg && testnext(ls, ','));
  649. }
  650. adjustlocalvars(ls, nparams);
  651. f->numparams = cast_byte(fs->nactvar);
  652. luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
  653. }
  654. static void body (LexState *ls, expdesc *e, int ismethod, int line) {
  655. /* body -> `(' parlist `)' block END */
  656. FuncState new_fs;
  657. BlockCnt bl;
  658. new_fs.f = addprototype(ls);
  659. new_fs.f->linedefined = line;
  660. open_func(ls, &new_fs, &bl);
  661. checknext(ls, '(');
  662. if (ismethod) {
  663. new_localvarliteral(ls, "self"); /* create 'self' parameter */
  664. adjustlocalvars(ls, 1);
  665. }
  666. parlist(ls);
  667. checknext(ls, ')');
  668. statlist(ls);
  669. new_fs.f->lastlinedefined = ls->linenumber;
  670. check_match(ls, TK_END, TK_FUNCTION, line);
  671. codeclosure(ls, e);
  672. close_func(ls);
  673. }
  674. static int explist (LexState *ls, expdesc *v) {
  675. /* explist -> expr { `,' expr } */
  676. int n = 1; /* at least one expression */
  677. expr(ls, v);
  678. while (testnext(ls, ',')) {
  679. luaK_exp2nextreg(ls->fs, v);
  680. expr(ls, v);
  681. n++;
  682. }
  683. return n;
  684. }
  685. static void funcargs (LexState *ls, expdesc *f, int line) {
  686. FuncState *fs = ls->fs;
  687. expdesc args;
  688. int base, nparams;
  689. switch (ls->t.token) {
  690. case '(': { /* funcargs -> `(' [ explist ] `)' */
  691. luaX_next(ls);
  692. if (ls->t.token == ')') /* arg list is empty? */
  693. args.k = VVOID;
  694. else {
  695. explist(ls, &args);
  696. luaK_setmultret(fs, &args);
  697. }
  698. check_match(ls, ')', '(', line);
  699. break;
  700. }
  701. case '{': { /* funcargs -> constructor */
  702. constructor(ls, &args);
  703. break;
  704. }
  705. case TK_STRING: { /* funcargs -> STRING */
  706. codestring(ls, &args, ls->t.seminfo.ts);
  707. luaX_next(ls); /* must use `seminfo' before `next' */
  708. break;
  709. }
  710. default: {
  711. luaX_syntaxerror(ls, "function arguments expected");
  712. }
  713. }
  714. lua_assert(f->k == VNONRELOC);
  715. base = f->u.info; /* base register for call */
  716. if (hasmultret(args.k))
  717. nparams = LUA_MULTRET; /* open call */
  718. else {
  719. if (args.k != VVOID)
  720. luaK_exp2nextreg(fs, &args); /* close last argument */
  721. nparams = fs->freereg - (base+1);
  722. }
  723. init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
  724. luaK_fixline(fs, line);
  725. fs->freereg = base+1; /* call remove function and arguments and leaves
  726. (unless changed) one result */
  727. }
  728. /*
  729. ** {======================================================================
  730. ** Expression parsing
  731. ** =======================================================================
  732. */
  733. static void primaryexp (LexState *ls, expdesc *v) {
  734. /* primaryexp -> NAME | '(' expr ')' */
  735. switch (ls->t.token) {
  736. case '(': {
  737. int line = ls->linenumber;
  738. luaX_next(ls);
  739. expr(ls, v);
  740. check_match(ls, ')', '(', line);
  741. luaK_dischargevars(ls->fs, v);
  742. return;
  743. }
  744. case TK_NAME: {
  745. singlevar(ls, v);
  746. return;
  747. }
  748. default: {
  749. luaX_syntaxerror(ls, "unexpected symbol");
  750. }
  751. }
  752. }
  753. static void suffixedexp (LexState *ls, expdesc *v) {
  754. /* suffixedexp ->
  755. primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
  756. FuncState *fs = ls->fs;
  757. int line = ls->linenumber;
  758. primaryexp(ls, v);
  759. for (;;) {
  760. switch (ls->t.token) {
  761. case '.': { /* fieldsel */
  762. fieldsel(ls, v);
  763. break;
  764. }
  765. case '[': { /* `[' exp1 `]' */
  766. expdesc key;
  767. luaK_exp2anyregup(fs, v);
  768. yindex(ls, &key);
  769. luaK_indexed(fs, v, &key);
  770. break;
  771. }
  772. case ':': { /* `:' NAME funcargs */
  773. expdesc key;
  774. luaX_next(ls);
  775. checkname(ls, &key);
  776. luaK_self(fs, v, &key);
  777. funcargs(ls, v, line);
  778. break;
  779. }
  780. case '(': case TK_STRING: case '{': { /* funcargs */
  781. luaK_exp2nextreg(fs, v);
  782. funcargs(ls, v, line);
  783. break;
  784. }
  785. default: return;
  786. }
  787. }
  788. }
  789. static void simpleexp (LexState *ls, expdesc *v) {
  790. /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
  791. constructor | FUNCTION body | suffixedexp */
  792. switch (ls->t.token) {
  793. case TK_FLT: {
  794. init_exp(v, VKFLT, 0);
  795. v->u.nval = ls->t.seminfo.r;
  796. break;
  797. }
  798. case TK_INT: {
  799. init_exp(v, VKINT, 0);
  800. v->u.ival = ls->t.seminfo.i;
  801. break;
  802. }
  803. case TK_STRING: {
  804. codestring(ls, v, ls->t.seminfo.ts);
  805. break;
  806. }
  807. case TK_NIL: {
  808. init_exp(v, VNIL, 0);
  809. break;
  810. }
  811. case TK_TRUE: {
  812. init_exp(v, VTRUE, 0);
  813. break;
  814. }
  815. case TK_FALSE: {
  816. init_exp(v, VFALSE, 0);
  817. break;
  818. }
  819. case TK_DOTS: { /* vararg */
  820. FuncState *fs = ls->fs;
  821. check_condition(ls, fs->f->is_vararg,
  822. "cannot use " LUA_QL("...") " outside a vararg function");
  823. init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
  824. break;
  825. }
  826. case '{': { /* constructor */
  827. constructor(ls, v);
  828. return;
  829. }
  830. case TK_FUNCTION: {
  831. luaX_next(ls);
  832. body(ls, v, 0, ls->linenumber);
  833. return;
  834. }
  835. default: {
  836. suffixedexp(ls, v);
  837. return;
  838. }
  839. }
  840. luaX_next(ls);
  841. }
  842. static UnOpr getunopr (int op) {
  843. switch (op) {
  844. case TK_NOT: return OPR_NOT;
  845. case '-': return OPR_MINUS;
  846. case '#': return OPR_LEN;
  847. default: return OPR_NOUNOPR;
  848. }
  849. }
  850. static BinOpr getbinopr (int op) {
  851. switch (op) {
  852. case '+': return OPR_ADD;
  853. case '-': return OPR_SUB;
  854. case '*': return OPR_MUL;
  855. case '/': return OPR_DIV;
  856. case TK_IDIV: return OPR_IDIV;
  857. case '%': return OPR_MOD;
  858. case '^': return OPR_POW;
  859. case TK_CONCAT: return OPR_CONCAT;
  860. case TK_NE: return OPR_NE;
  861. case TK_EQ: return OPR_EQ;
  862. case '<': return OPR_LT;
  863. case TK_LE: return OPR_LE;
  864. case '>': return OPR_GT;
  865. case TK_GE: return OPR_GE;
  866. case TK_AND: return OPR_AND;
  867. case TK_OR: return OPR_OR;
  868. default: return OPR_NOBINOPR;
  869. }
  870. }
  871. static const struct {
  872. lu_byte left; /* left priority for each binary operator */
  873. lu_byte right; /* right priority */
  874. } priority[] = { /* ORDER OPR */
  875. {6, 6}, {6, 6}, /* '+' '-' */
  876. {7, 7}, {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 -> ',' suffixedexp assignment */
  976. struct LHS_assign nv;
  977. nv.prev = lh;
  978. suffixedexp(ls, &nv.v);
  979. if (nv.v.k != VINDEXED)
  980. check_conflict(ls, lh, &nv.v);
  981. checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS,
  982. "C levels");
  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 (luaS_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. /* skip no-op statements */
  1037. static void skipnoopstat (LexState *ls) {
  1038. while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
  1039. statement(ls);
  1040. }
  1041. static void labelstat (LexState *ls, TString *label, int line) {
  1042. /* label -> '::' NAME '::' */
  1043. FuncState *fs = ls->fs;
  1044. Labellist *ll = &ls->dyd->label;
  1045. int l; /* index of new label being created */
  1046. checkrepeated(fs, ll, label); /* check for repeated labels */
  1047. checknext(ls, TK_DBCOLON); /* skip double colon */
  1048. /* create new entry for this label */
  1049. l = newlabelentry(ls, ll, label, line, fs->pc);
  1050. skipnoopstat(ls); /* skip other no-op statements */
  1051. if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */
  1052. /* assume that locals are already out of scope */
  1053. ll->arr[l].nactvar = fs->bl->nactvar;
  1054. }
  1055. findgotos(ls, &ll->arr[l]);
  1056. }
  1057. static void whilestat (LexState *ls, int line) {
  1058. /* whilestat -> WHILE cond DO block END */
  1059. FuncState *fs = ls->fs;
  1060. int whileinit;
  1061. int condexit;
  1062. BlockCnt bl;
  1063. luaX_next(ls); /* skip WHILE */
  1064. whileinit = luaK_getlabel(fs);
  1065. condexit = cond(ls);
  1066. enterblock(fs, &bl, 1);
  1067. checknext(ls, TK_DO);
  1068. block(ls);
  1069. luaK_jumpto(fs, whileinit);
  1070. check_match(ls, TK_END, TK_WHILE, line);
  1071. leaveblock(fs);
  1072. luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
  1073. }
  1074. static void repeatstat (LexState *ls, int line) {
  1075. /* repeatstat -> REPEAT block UNTIL cond */
  1076. int condexit;
  1077. FuncState *fs = ls->fs;
  1078. int repeat_init = luaK_getlabel(fs);
  1079. BlockCnt bl1, bl2;
  1080. enterblock(fs, &bl1, 1); /* loop block */
  1081. enterblock(fs, &bl2, 0); /* scope block */
  1082. luaX_next(ls); /* skip REPEAT */
  1083. statlist(ls);
  1084. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  1085. condexit = cond(ls); /* read condition (inside scope block) */
  1086. if (bl2.upval) /* upvalues? */
  1087. luaK_patchclose(fs, condexit, bl2.nactvar);
  1088. leaveblock(fs); /* finish scope */
  1089. luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
  1090. leaveblock(fs); /* finish loop */
  1091. }
  1092. static int exp1 (LexState *ls) {
  1093. expdesc e;
  1094. int reg;
  1095. expr(ls, &e);
  1096. luaK_exp2nextreg(ls->fs, &e);
  1097. lua_assert(e.k == VNONRELOC);
  1098. reg = e.u.info;
  1099. return reg;
  1100. }
  1101. static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
  1102. /* forbody -> DO block */
  1103. BlockCnt bl;
  1104. FuncState *fs = ls->fs;
  1105. int prep, endfor;
  1106. adjustlocalvars(ls, 3); /* control variables */
  1107. checknext(ls, TK_DO);
  1108. prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
  1109. enterblock(fs, &bl, 0); /* scope for declared variables */
  1110. adjustlocalvars(ls, nvars);
  1111. luaK_reserveregs(fs, nvars);
  1112. block(ls);
  1113. leaveblock(fs); /* end of scope for declared variables */
  1114. luaK_patchtohere(fs, prep);
  1115. if (isnum) /* numeric for? */
  1116. endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
  1117. else { /* generic for */
  1118. luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
  1119. luaK_fixline(fs, line);
  1120. endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
  1121. }
  1122. luaK_patchlist(fs, endfor, prep + 1);
  1123. luaK_fixline(fs, line);
  1124. }
  1125. static void fornum (LexState *ls, TString *varname, int line) {
  1126. /* fornum -> NAME = exp1,exp1[,exp1] forbody */
  1127. FuncState *fs = ls->fs;
  1128. int base = fs->freereg;
  1129. new_localvarliteral(ls, "(for index)");
  1130. new_localvarliteral(ls, "(for limit)");
  1131. new_localvarliteral(ls, "(for step)");
  1132. new_localvar(ls, varname);
  1133. checknext(ls, '=');
  1134. exp1(ls); /* initial value */
  1135. checknext(ls, ',');
  1136. exp1(ls); /* limit */
  1137. if (testnext(ls, ','))
  1138. exp1(ls); /* optional step */
  1139. else { /* default step = 1 */
  1140. luaK_codek(fs, fs->freereg, luaK_intK(fs, 1));
  1141. luaK_reserveregs(fs, 1);
  1142. }
  1143. forbody(ls, base, line, 1, 1);
  1144. }
  1145. static void forlist (LexState *ls, TString *indexname) {
  1146. /* forlist -> NAME {,NAME} IN explist forbody */
  1147. FuncState *fs = ls->fs;
  1148. expdesc e;
  1149. int nvars = 4; /* gen, state, control, plus at least one declared var */
  1150. int line;
  1151. int base = fs->freereg;
  1152. /* create control variables */
  1153. new_localvarliteral(ls, "(for generator)");
  1154. new_localvarliteral(ls, "(for state)");
  1155. new_localvarliteral(ls, "(for control)");
  1156. /* create declared variables */
  1157. new_localvar(ls, indexname);
  1158. while (testnext(ls, ',')) {
  1159. new_localvar(ls, str_checkname(ls));
  1160. nvars++;
  1161. }
  1162. checknext(ls, TK_IN);
  1163. line = ls->linenumber;
  1164. adjust_assign(ls, 3, explist(ls, &e), &e);
  1165. luaK_checkstack(fs, 3); /* extra space to call generator */
  1166. forbody(ls, base, line, nvars - 3, 0);
  1167. }
  1168. static void forstat (LexState *ls, int line) {
  1169. /* forstat -> FOR (fornum | forlist) END */
  1170. FuncState *fs = ls->fs;
  1171. TString *varname;
  1172. BlockCnt bl;
  1173. enterblock(fs, &bl, 1); /* scope for loop and control variables */
  1174. luaX_next(ls); /* skip `for' */
  1175. varname = str_checkname(ls); /* first variable name */
  1176. switch (ls->t.token) {
  1177. case '=': fornum(ls, varname, line); break;
  1178. case ',': case TK_IN: forlist(ls, varname); break;
  1179. default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
  1180. }
  1181. check_match(ls, TK_END, TK_FOR, line);
  1182. leaveblock(fs); /* loop scope (`break' jumps to this point) */
  1183. }
  1184. static void test_then_block (LexState *ls, int *escapelist) {
  1185. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  1186. BlockCnt bl;
  1187. FuncState *fs = ls->fs;
  1188. expdesc v;
  1189. int jf; /* instruction to skip 'then' code (if condition is false) */
  1190. luaX_next(ls); /* skip IF or ELSEIF */
  1191. expr(ls, &v); /* read condition */
  1192. checknext(ls, TK_THEN);
  1193. if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
  1194. luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */
  1195. enterblock(fs, &bl, 0); /* must enter block before 'goto' */
  1196. gotostat(ls, v.t); /* handle goto/break */
  1197. skipnoopstat(ls); /* skip other no-op statements */
  1198. if (block_follow(ls, 0)) { /* 'goto' is the entire block? */
  1199. leaveblock(fs);
  1200. return; /* and that is it */
  1201. }
  1202. else /* must skip over 'then' part if condition is false */
  1203. jf = luaK_jump(fs);
  1204. }
  1205. else { /* regular case (not goto/break) */
  1206. luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */
  1207. enterblock(fs, &bl, 0);
  1208. jf = v.f;
  1209. }
  1210. statlist(ls); /* `then' part */
  1211. leaveblock(fs);
  1212. if (ls->t.token == TK_ELSE ||
  1213. ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
  1214. luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
  1215. luaK_patchtohere(fs, jf);
  1216. }
  1217. static void ifstat (LexState *ls, int line) {
  1218. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  1219. FuncState *fs = ls->fs;
  1220. int escapelist = NO_JUMP; /* exit list for finished parts */
  1221. test_then_block(ls, &escapelist); /* IF cond THEN block */
  1222. while (ls->t.token == TK_ELSEIF)
  1223. test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
  1224. if (testnext(ls, TK_ELSE))
  1225. block(ls); /* `else' part */
  1226. check_match(ls, TK_END, TK_IF, line);
  1227. luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
  1228. }
  1229. static void localfunc (LexState *ls) {
  1230. expdesc b;
  1231. FuncState *fs = ls->fs;
  1232. new_localvar(ls, str_checkname(ls)); /* new local variable */
  1233. adjustlocalvars(ls, 1); /* enter its scope */
  1234. body(ls, &b, 0, ls->linenumber); /* function created in next register */
  1235. /* debug information will only see the variable after this point! */
  1236. getlocvar(fs, b.u.info)->startpc = fs->pc;
  1237. }
  1238. static void localstat (LexState *ls) {
  1239. /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
  1240. int nvars = 0;
  1241. int nexps;
  1242. expdesc e;
  1243. do {
  1244. new_localvar(ls, str_checkname(ls));
  1245. nvars++;
  1246. } while (testnext(ls, ','));
  1247. if (testnext(ls, '='))
  1248. nexps = explist(ls, &e);
  1249. else {
  1250. e.k = VVOID;
  1251. nexps = 0;
  1252. }
  1253. adjust_assign(ls, nvars, nexps, &e);
  1254. adjustlocalvars(ls, nvars);
  1255. }
  1256. static int funcname (LexState *ls, expdesc *v) {
  1257. /* funcname -> NAME {fieldsel} [`:' NAME] */
  1258. int ismethod = 0;
  1259. singlevar(ls, v);
  1260. while (ls->t.token == '.')
  1261. fieldsel(ls, v);
  1262. if (ls->t.token == ':') {
  1263. ismethod = 1;
  1264. fieldsel(ls, v);
  1265. }
  1266. return ismethod;
  1267. }
  1268. static void funcstat (LexState *ls, int line) {
  1269. /* funcstat -> FUNCTION funcname body */
  1270. int ismethod;
  1271. expdesc v, b;
  1272. luaX_next(ls); /* skip FUNCTION */
  1273. ismethod = funcname(ls, &v);
  1274. body(ls, &b, ismethod, line);
  1275. luaK_storevar(ls->fs, &v, &b);
  1276. luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
  1277. }
  1278. static void exprstat (LexState *ls) {
  1279. /* stat -> func | assignment */
  1280. FuncState *fs = ls->fs;
  1281. struct LHS_assign v;
  1282. suffixedexp(ls, &v.v);
  1283. if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
  1284. v.prev = NULL;
  1285. assignment(ls, &v, 1);
  1286. }
  1287. else { /* stat -> func */
  1288. check_condition(ls, v.v.k == VCALL, "syntax error");
  1289. SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
  1290. }
  1291. }
  1292. static void retstat (LexState *ls) {
  1293. /* stat -> RETURN [explist] [';'] */
  1294. FuncState *fs = ls->fs;
  1295. expdesc e;
  1296. int first, nret; /* registers with returned values */
  1297. if (block_follow(ls, 1) || ls->t.token == ';')
  1298. first = nret = 0; /* return no values */
  1299. else {
  1300. nret = explist(ls, &e); /* optional return values */
  1301. if (hasmultret(e.k)) {
  1302. luaK_setmultret(fs, &e);
  1303. if (e.k == VCALL && nret == 1) { /* tail call? */
  1304. SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
  1305. lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
  1306. }
  1307. first = fs->nactvar;
  1308. nret = LUA_MULTRET; /* return all values */
  1309. }
  1310. else {
  1311. if (nret == 1) /* only one single value? */
  1312. first = luaK_exp2anyreg(fs, &e);
  1313. else {
  1314. luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
  1315. first = fs->nactvar; /* return all `active' values */
  1316. lua_assert(nret == fs->freereg - first);
  1317. }
  1318. }
  1319. }
  1320. luaK_ret(fs, first, nret);
  1321. testnext(ls, ';'); /* skip optional semicolon */
  1322. }
  1323. static void statement (LexState *ls) {
  1324. int line = ls->linenumber; /* may be needed for error messages */
  1325. enterlevel(ls);
  1326. switch (ls->t.token) {
  1327. case ';': { /* stat -> ';' (empty statement) */
  1328. luaX_next(ls); /* skip ';' */
  1329. break;
  1330. }
  1331. case TK_IF: { /* stat -> ifstat */
  1332. ifstat(ls, line);
  1333. break;
  1334. }
  1335. case TK_WHILE: { /* stat -> whilestat */
  1336. whilestat(ls, line);
  1337. break;
  1338. }
  1339. case TK_DO: { /* stat -> DO block END */
  1340. luaX_next(ls); /* skip DO */
  1341. block(ls);
  1342. check_match(ls, TK_END, TK_DO, line);
  1343. break;
  1344. }
  1345. case TK_FOR: { /* stat -> forstat */
  1346. forstat(ls, line);
  1347. break;
  1348. }
  1349. case TK_REPEAT: { /* stat -> repeatstat */
  1350. repeatstat(ls, line);
  1351. break;
  1352. }
  1353. case TK_FUNCTION: { /* stat -> funcstat */
  1354. funcstat(ls, line);
  1355. break;
  1356. }
  1357. case TK_LOCAL: { /* stat -> localstat */
  1358. luaX_next(ls); /* skip LOCAL */
  1359. if (testnext(ls, TK_FUNCTION)) /* local function? */
  1360. localfunc(ls);
  1361. else
  1362. localstat(ls);
  1363. break;
  1364. }
  1365. case TK_DBCOLON: { /* stat -> label */
  1366. luaX_next(ls); /* skip double colon */
  1367. labelstat(ls, str_checkname(ls), line);
  1368. break;
  1369. }
  1370. case TK_RETURN: { /* stat -> retstat */
  1371. luaX_next(ls); /* skip RETURN */
  1372. retstat(ls);
  1373. break;
  1374. }
  1375. case TK_BREAK: /* stat -> breakstat */
  1376. case TK_GOTO: { /* stat -> 'goto' NAME */
  1377. gotostat(ls, luaK_jump(ls->fs));
  1378. break;
  1379. }
  1380. default: { /* stat -> func | assignment */
  1381. exprstat(ls);
  1382. break;
  1383. }
  1384. }
  1385. lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
  1386. ls->fs->freereg >= ls->fs->nactvar);
  1387. ls->fs->freereg = ls->fs->nactvar; /* free registers */
  1388. leavelevel(ls);
  1389. }
  1390. /* }====================================================================== */
  1391. /*
  1392. ** compiles the main function, which is a regular vararg function with an
  1393. ** upvalue named LUA_ENV
  1394. */
  1395. static void mainfunc (LexState *ls, FuncState *fs) {
  1396. BlockCnt bl;
  1397. expdesc v;
  1398. open_func(ls, fs, &bl);
  1399. fs->f->is_vararg = 1; /* main function is always vararg */
  1400. init_exp(&v, VLOCAL, 0); /* create and... */
  1401. newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */
  1402. luaX_next(ls); /* read first token */
  1403. statlist(ls); /* parse main body */
  1404. check(ls, TK_EOS);
  1405. close_func(ls);
  1406. }
  1407. Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
  1408. Dyndata *dyd, const char *name, int firstchar) {
  1409. LexState lexstate;
  1410. FuncState funcstate;
  1411. Closure *cl = luaF_newLclosure(L, 1); /* create main closure */
  1412. /* anchor closure (to avoid being collected) */
  1413. setclLvalue(L, L->top, cl);
  1414. incr_top(L);
  1415. funcstate.f = cl->l.p = luaF_newproto(L);
  1416. funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
  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. return cl; /* it's on the stack too */
  1426. }