lparser.c 48 KB

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