lparser.c 60 KB

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