lparser.c 49 KB

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