2
0

lparser.c 56 KB

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