lparser.c 49 KB

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