lparser.c 46 KB

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