lparser.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  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. luaC_objbarrier(ls->L, f, f->source);
  629. f->maxstacksize = 2; /* registers 0/1 are always valid */
  630. enterblock(fs, bl, 0);
  631. }
  632. static void close_func (LexState *ls) {
  633. lua_State *L = ls->L;
  634. FuncState *fs = ls->fs;
  635. Proto *f = fs->f;
  636. luaK_ret(fs, luaY_nvarstack(fs), 0); /* final return */
  637. leaveblock(fs);
  638. lua_assert(fs->bl == NULL);
  639. luaK_finish(fs);
  640. luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction);
  641. luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte);
  642. luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo,
  643. fs->nabslineinfo, AbsLineInfo);
  644. luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue);
  645. luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *);
  646. luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar);
  647. luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
  648. ls->fs = fs->prev;
  649. luaC_checkGC(L);
  650. }
  651. /*============================================================*/
  652. /* GRAMMAR RULES */
  653. /*============================================================*/
  654. /*
  655. ** check whether current token is in the follow set of a block.
  656. ** 'until' closes syntactical blocks, but do not close scope,
  657. ** so it is handled in separate.
  658. */
  659. static int block_follow (LexState *ls, int withuntil) {
  660. switch (ls->t.token) {
  661. case TK_ELSE: case TK_ELSEIF:
  662. case TK_END: case TK_EOS:
  663. return 1;
  664. case TK_UNTIL: return withuntil;
  665. default: return 0;
  666. }
  667. }
  668. static void statlist (LexState *ls) {
  669. /* statlist -> { stat [';'] } */
  670. while (!block_follow(ls, 1)) {
  671. if (ls->t.token == TK_RETURN) {
  672. statement(ls);
  673. return; /* 'return' must be last statement */
  674. }
  675. statement(ls);
  676. }
  677. }
  678. static void fieldsel (LexState *ls, expdesc *v) {
  679. /* fieldsel -> ['.' | ':'] NAME */
  680. FuncState *fs = ls->fs;
  681. expdesc key;
  682. luaK_exp2anyregup(fs, v);
  683. luaX_next(ls); /* skip the dot or colon */
  684. codename(ls, &key);
  685. luaK_indexed(fs, v, &key);
  686. }
  687. static void yindex (LexState *ls, expdesc *v) {
  688. /* index -> '[' expr ']' */
  689. luaX_next(ls); /* skip the '[' */
  690. expr(ls, v);
  691. luaK_exp2val(ls->fs, v);
  692. checknext(ls, ']');
  693. }
  694. /*
  695. ** {======================================================================
  696. ** Rules for Constructors
  697. ** =======================================================================
  698. */
  699. typedef struct ConsControl {
  700. expdesc v; /* last list item read */
  701. expdesc *t; /* table descriptor */
  702. int nh; /* total number of 'record' elements */
  703. int na; /* number of array elements already stored */
  704. int tostore; /* number of array elements pending to be stored */
  705. } ConsControl;
  706. static void recfield (LexState *ls, ConsControl *cc) {
  707. /* recfield -> (NAME | '['exp']') = exp */
  708. FuncState *fs = ls->fs;
  709. int reg = ls->fs->freereg;
  710. expdesc tab, key, val;
  711. if (ls->t.token == TK_NAME) {
  712. checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
  713. codename(ls, &key);
  714. }
  715. else /* ls->t.token == '[' */
  716. yindex(ls, &key);
  717. cc->nh++;
  718. checknext(ls, '=');
  719. tab = *cc->t;
  720. luaK_indexed(fs, &tab, &key);
  721. expr(ls, &val);
  722. luaK_storevar(fs, &tab, &val);
  723. fs->freereg = reg; /* free registers */
  724. }
  725. static void closelistfield (FuncState *fs, ConsControl *cc) {
  726. if (cc->v.k == VVOID) return; /* there is no list item */
  727. luaK_exp2nextreg(fs, &cc->v);
  728. cc->v.k = VVOID;
  729. if (cc->tostore == LFIELDS_PER_FLUSH) {
  730. luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
  731. cc->na += cc->tostore;
  732. cc->tostore = 0; /* no more items pending */
  733. }
  734. }
  735. static void lastlistfield (FuncState *fs, ConsControl *cc) {
  736. if (cc->tostore == 0) return;
  737. if (hasmultret(cc->v.k)) {
  738. luaK_setmultret(fs, &cc->v);
  739. luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
  740. cc->na--; /* do not count last expression (unknown number of elements) */
  741. }
  742. else {
  743. if (cc->v.k != VVOID)
  744. luaK_exp2nextreg(fs, &cc->v);
  745. luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
  746. }
  747. cc->na += cc->tostore;
  748. }
  749. static void listfield (LexState *ls, ConsControl *cc) {
  750. /* listfield -> exp */
  751. expr(ls, &cc->v);
  752. cc->tostore++;
  753. }
  754. static void field (LexState *ls, ConsControl *cc) {
  755. /* field -> listfield | recfield */
  756. switch(ls->t.token) {
  757. case TK_NAME: { /* may be 'listfield' or 'recfield' */
  758. if (luaX_lookahead(ls) != '=') /* expression? */
  759. listfield(ls, cc);
  760. else
  761. recfield(ls, cc);
  762. break;
  763. }
  764. case '[': {
  765. recfield(ls, cc);
  766. break;
  767. }
  768. default: {
  769. listfield(ls, cc);
  770. break;
  771. }
  772. }
  773. }
  774. static void constructor (LexState *ls, expdesc *t) {
  775. /* constructor -> '{' [ field { sep field } [sep] ] '}'
  776. sep -> ',' | ';' */
  777. FuncState *fs = ls->fs;
  778. int line = ls->linenumber;
  779. int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  780. ConsControl cc;
  781. luaK_code(fs, 0); /* space for extra arg. */
  782. cc.na = cc.nh = cc.tostore = 0;
  783. cc.t = t;
  784. init_exp(t, VNONRELOC, fs->freereg); /* table will be at stack top */
  785. luaK_reserveregs(fs, 1);
  786. init_exp(&cc.v, VVOID, 0); /* no value (yet) */
  787. checknext(ls, '{');
  788. do {
  789. lua_assert(cc.v.k == VVOID || cc.tostore > 0);
  790. if (ls->t.token == '}') break;
  791. closelistfield(fs, &cc);
  792. field(ls, &cc);
  793. } while (testnext(ls, ',') || testnext(ls, ';'));
  794. check_match(ls, '}', '{', line);
  795. lastlistfield(fs, &cc);
  796. luaK_settablesize(fs, pc, t->u.info, cc.na, cc.nh);
  797. }
  798. /* }====================================================================== */
  799. static void setvararg (FuncState *fs, int nparams) {
  800. fs->f->is_vararg = 1;
  801. luaK_codeABC(fs, OP_VARARGPREP, nparams, 0, 0);
  802. }
  803. static void parlist (LexState *ls) {
  804. /* parlist -> [ param { ',' param } ] */
  805. FuncState *fs = ls->fs;
  806. Proto *f = fs->f;
  807. int nparams = 0;
  808. int isvararg = 0;
  809. if (ls->t.token != ')') { /* is 'parlist' not empty? */
  810. do {
  811. switch (ls->t.token) {
  812. case TK_NAME: { /* param -> NAME */
  813. new_localvar(ls, str_checkname(ls));
  814. nparams++;
  815. break;
  816. }
  817. case TK_DOTS: { /* param -> '...' */
  818. luaX_next(ls);
  819. isvararg = 1;
  820. break;
  821. }
  822. default: luaX_syntaxerror(ls, "<name> or '...' expected");
  823. }
  824. } while (!isvararg && testnext(ls, ','));
  825. }
  826. adjustlocalvars(ls, nparams);
  827. f->numparams = cast_byte(fs->nactvar);
  828. if (isvararg)
  829. setvararg(fs, f->numparams); /* declared vararg */
  830. luaK_reserveregs(fs, fs->nactvar); /* reserve registers for parameters */
  831. }
  832. static void body (LexState *ls, expdesc *e, int ismethod, int line) {
  833. /* body -> '(' parlist ')' block END */
  834. FuncState new_fs;
  835. BlockCnt bl;
  836. new_fs.f = addprototype(ls);
  837. new_fs.f->linedefined = line;
  838. open_func(ls, &new_fs, &bl);
  839. checknext(ls, '(');
  840. if (ismethod) {
  841. new_localvarliteral(ls, "self"); /* create 'self' parameter */
  842. adjustlocalvars(ls, 1);
  843. }
  844. parlist(ls);
  845. checknext(ls, ')');
  846. statlist(ls);
  847. new_fs.f->lastlinedefined = ls->linenumber;
  848. check_match(ls, TK_END, TK_FUNCTION, line);
  849. codeclosure(ls, e);
  850. close_func(ls);
  851. }
  852. static int explist (LexState *ls, expdesc *v) {
  853. /* explist -> expr { ',' expr } */
  854. int n = 1; /* at least one expression */
  855. expr(ls, v);
  856. while (testnext(ls, ',')) {
  857. luaK_exp2nextreg(ls->fs, v);
  858. expr(ls, v);
  859. n++;
  860. }
  861. return n;
  862. }
  863. static void funcargs (LexState *ls, expdesc *f, int line) {
  864. FuncState *fs = ls->fs;
  865. expdesc args;
  866. int base, nparams;
  867. switch (ls->t.token) {
  868. case '(': { /* funcargs -> '(' [ explist ] ')' */
  869. luaX_next(ls);
  870. if (ls->t.token == ')') /* arg list is empty? */
  871. args.k = VVOID;
  872. else {
  873. explist(ls, &args);
  874. if (hasmultret(args.k))
  875. luaK_setmultret(fs, &args);
  876. }
  877. check_match(ls, ')', '(', line);
  878. break;
  879. }
  880. case '{': { /* funcargs -> constructor */
  881. constructor(ls, &args);
  882. break;
  883. }
  884. case TK_STRING: { /* funcargs -> STRING */
  885. codestring(&args, ls->t.seminfo.ts);
  886. luaX_next(ls); /* must use 'seminfo' before 'next' */
  887. break;
  888. }
  889. default: {
  890. luaX_syntaxerror(ls, "function arguments expected");
  891. }
  892. }
  893. lua_assert(f->k == VNONRELOC);
  894. base = f->u.info; /* base register for call */
  895. if (hasmultret(args.k))
  896. nparams = LUA_MULTRET; /* open call */
  897. else {
  898. if (args.k != VVOID)
  899. luaK_exp2nextreg(fs, &args); /* close last argument */
  900. nparams = fs->freereg - (base+1);
  901. }
  902. init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
  903. luaK_fixline(fs, line);
  904. fs->freereg = base+1; /* call remove function and arguments and leaves
  905. (unless changed) one result */
  906. }
  907. /*
  908. ** {======================================================================
  909. ** Expression parsing
  910. ** =======================================================================
  911. */
  912. static void primaryexp (LexState *ls, expdesc *v) {
  913. /* primaryexp -> NAME | '(' expr ')' */
  914. switch (ls->t.token) {
  915. case '(': {
  916. int line = ls->linenumber;
  917. luaX_next(ls);
  918. expr(ls, v);
  919. check_match(ls, ')', '(', line);
  920. luaK_dischargevars(ls->fs, v);
  921. return;
  922. }
  923. case TK_NAME: {
  924. singlevar(ls, v);
  925. return;
  926. }
  927. default: {
  928. luaX_syntaxerror(ls, "unexpected symbol");
  929. }
  930. }
  931. }
  932. static void suffixedexp (LexState *ls, expdesc *v) {
  933. /* suffixedexp ->
  934. primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
  935. FuncState *fs = ls->fs;
  936. int line = ls->linenumber;
  937. primaryexp(ls, v);
  938. for (;;) {
  939. switch (ls->t.token) {
  940. case '.': { /* fieldsel */
  941. fieldsel(ls, v);
  942. break;
  943. }
  944. case '[': { /* '[' exp ']' */
  945. expdesc key;
  946. luaK_exp2anyregup(fs, v);
  947. yindex(ls, &key);
  948. luaK_indexed(fs, v, &key);
  949. break;
  950. }
  951. case ':': { /* ':' NAME funcargs */
  952. expdesc key;
  953. luaX_next(ls);
  954. codename(ls, &key);
  955. luaK_self(fs, v, &key);
  956. funcargs(ls, v, line);
  957. break;
  958. }
  959. case '(': case TK_STRING: case '{': { /* funcargs */
  960. luaK_exp2nextreg(fs, v);
  961. funcargs(ls, v, line);
  962. break;
  963. }
  964. default: return;
  965. }
  966. }
  967. }
  968. static void simpleexp (LexState *ls, expdesc *v) {
  969. /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
  970. constructor | FUNCTION body | suffixedexp */
  971. switch (ls->t.token) {
  972. case TK_FLT: {
  973. init_exp(v, VKFLT, 0);
  974. v->u.nval = ls->t.seminfo.r;
  975. break;
  976. }
  977. case TK_INT: {
  978. init_exp(v, VKINT, 0);
  979. v->u.ival = ls->t.seminfo.i;
  980. break;
  981. }
  982. case TK_STRING: {
  983. codestring(v, ls->t.seminfo.ts);
  984. break;
  985. }
  986. case TK_NIL: {
  987. init_exp(v, VNIL, 0);
  988. break;
  989. }
  990. case TK_TRUE: {
  991. init_exp(v, VTRUE, 0);
  992. break;
  993. }
  994. case TK_FALSE: {
  995. init_exp(v, VFALSE, 0);
  996. break;
  997. }
  998. case TK_DOTS: { /* vararg */
  999. FuncState *fs = ls->fs;
  1000. check_condition(ls, fs->f->is_vararg,
  1001. "cannot use '...' outside a vararg function");
  1002. init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 0, 1));
  1003. break;
  1004. }
  1005. case '{': { /* constructor */
  1006. constructor(ls, v);
  1007. return;
  1008. }
  1009. case TK_FUNCTION: {
  1010. luaX_next(ls);
  1011. body(ls, v, 0, ls->linenumber);
  1012. return;
  1013. }
  1014. default: {
  1015. suffixedexp(ls, v);
  1016. return;
  1017. }
  1018. }
  1019. luaX_next(ls);
  1020. }
  1021. static UnOpr getunopr (int op) {
  1022. switch (op) {
  1023. case TK_NOT: return OPR_NOT;
  1024. case '-': return OPR_MINUS;
  1025. case '~': return OPR_BNOT;
  1026. case '#': return OPR_LEN;
  1027. default: return OPR_NOUNOPR;
  1028. }
  1029. }
  1030. static BinOpr getbinopr (int op) {
  1031. switch (op) {
  1032. case '+': return OPR_ADD;
  1033. case '-': return OPR_SUB;
  1034. case '*': return OPR_MUL;
  1035. case '%': return OPR_MOD;
  1036. case '^': return OPR_POW;
  1037. case '/': return OPR_DIV;
  1038. case TK_IDIV: return OPR_IDIV;
  1039. case '&': return OPR_BAND;
  1040. case '|': return OPR_BOR;
  1041. case '~': return OPR_BXOR;
  1042. case TK_SHL: return OPR_SHL;
  1043. case TK_SHR: return OPR_SHR;
  1044. case TK_CONCAT: return OPR_CONCAT;
  1045. case TK_NE: return OPR_NE;
  1046. case TK_EQ: return OPR_EQ;
  1047. case '<': return OPR_LT;
  1048. case TK_LE: return OPR_LE;
  1049. case '>': return OPR_GT;
  1050. case TK_GE: return OPR_GE;
  1051. case TK_AND: return OPR_AND;
  1052. case TK_OR: return OPR_OR;
  1053. default: return OPR_NOBINOPR;
  1054. }
  1055. }
  1056. /*
  1057. ** Priority table for binary operators.
  1058. */
  1059. static const struct {
  1060. lu_byte left; /* left priority for each binary operator */
  1061. lu_byte right; /* right priority */
  1062. } priority[] = { /* ORDER OPR */
  1063. {10, 10}, {10, 10}, /* '+' '-' */
  1064. {11, 11}, {11, 11}, /* '*' '%' */
  1065. {14, 13}, /* '^' (right associative) */
  1066. {11, 11}, {11, 11}, /* '/' '//' */
  1067. {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
  1068. {7, 7}, {7, 7}, /* '<<' '>>' */
  1069. {9, 8}, /* '..' (right associative) */
  1070. {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
  1071. {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
  1072. {2, 2}, {1, 1} /* and, or */
  1073. };
  1074. #define UNARY_PRIORITY 12 /* priority for unary operators */
  1075. /*
  1076. ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
  1077. ** where 'binop' is any binary operator with a priority higher than 'limit'
  1078. */
  1079. static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
  1080. BinOpr op;
  1081. UnOpr uop;
  1082. enterlevel(ls);
  1083. uop = getunopr(ls->t.token);
  1084. if (uop != OPR_NOUNOPR) { /* prefix (unary) operator? */
  1085. int line = ls->linenumber;
  1086. luaX_next(ls); /* skip operator */
  1087. subexpr(ls, v, UNARY_PRIORITY);
  1088. luaK_prefix(ls->fs, uop, v, line);
  1089. }
  1090. else simpleexp(ls, v);
  1091. /* expand while operators have priorities higher than 'limit' */
  1092. op = getbinopr(ls->t.token);
  1093. while (op != OPR_NOBINOPR && priority[op].left > limit) {
  1094. expdesc v2;
  1095. BinOpr nextop;
  1096. int line = ls->linenumber;
  1097. luaX_next(ls); /* skip operator */
  1098. luaK_infix(ls->fs, op, v);
  1099. /* read sub-expression with higher priority */
  1100. nextop = subexpr(ls, &v2, priority[op].right);
  1101. luaK_posfix(ls->fs, op, v, &v2, line);
  1102. op = nextop;
  1103. }
  1104. leavelevel(ls);
  1105. return op; /* return first untreated operator */
  1106. }
  1107. static void expr (LexState *ls, expdesc *v) {
  1108. subexpr(ls, v, 0);
  1109. }
  1110. /* }==================================================================== */
  1111. /*
  1112. ** {======================================================================
  1113. ** Rules for Statements
  1114. ** =======================================================================
  1115. */
  1116. static void block (LexState *ls) {
  1117. /* block -> statlist */
  1118. FuncState *fs = ls->fs;
  1119. BlockCnt bl;
  1120. enterblock(fs, &bl, 0);
  1121. statlist(ls);
  1122. leaveblock(fs);
  1123. }
  1124. /*
  1125. ** structure to chain all variables in the left-hand side of an
  1126. ** assignment
  1127. */
  1128. struct LHS_assign {
  1129. struct LHS_assign *prev;
  1130. expdesc v; /* variable (global, local, upvalue, or indexed) */
  1131. };
  1132. /*
  1133. ** check whether, in an assignment to an upvalue/local variable, the
  1134. ** upvalue/local variable is begin used in a previous assignment to a
  1135. ** table. If so, save original upvalue/local value in a safe place and
  1136. ** use this safe copy in the previous assignment.
  1137. */
  1138. static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
  1139. FuncState *fs = ls->fs;
  1140. int extra = fs->freereg; /* eventual position to save local variable */
  1141. int conflict = 0;
  1142. for (; lh; lh = lh->prev) { /* check all previous assignments */
  1143. if (vkisindexed(lh->v.k)) { /* assignment to table field? */
  1144. if (lh->v.k == VINDEXUP) { /* is table an upvalue? */
  1145. if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) {
  1146. conflict = 1; /* table is the upvalue being assigned now */
  1147. lh->v.k = VINDEXSTR;
  1148. lh->v.u.ind.t = extra; /* assignment will use safe copy */
  1149. }
  1150. }
  1151. else { /* table is a register */
  1152. if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.sidx) {
  1153. conflict = 1; /* table is the local being assigned now */
  1154. lh->v.u.ind.t = extra; /* assignment will use safe copy */
  1155. }
  1156. /* is index the local being assigned? */
  1157. if (lh->v.k == VINDEXED && v->k == VLOCAL &&
  1158. lh->v.u.ind.idx == v->u.var.sidx) {
  1159. conflict = 1;
  1160. lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
  1161. }
  1162. }
  1163. }
  1164. }
  1165. if (conflict) {
  1166. /* copy upvalue/local value to a temporary (in position 'extra') */
  1167. if (v->k == VLOCAL)
  1168. luaK_codeABC(fs, OP_MOVE, extra, v->u.var.sidx, 0);
  1169. else
  1170. luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0);
  1171. luaK_reserveregs(fs, 1);
  1172. }
  1173. }
  1174. /*
  1175. ** Parse and compile a multiple assignment. The first "variable"
  1176. ** (a 'suffixedexp') was already read by the caller.
  1177. **
  1178. ** assignment -> suffixedexp restassign
  1179. ** restassign -> ',' suffixedexp restassign | '=' explist
  1180. */
  1181. static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) {
  1182. expdesc e;
  1183. check_condition(ls, vkisvar(lh->v.k), "syntax error");
  1184. check_readonly(ls, &lh->v);
  1185. if (testnext(ls, ',')) { /* restassign -> ',' suffixedexp restassign */
  1186. struct LHS_assign nv;
  1187. nv.prev = lh;
  1188. suffixedexp(ls, &nv.v);
  1189. if (!vkisindexed(nv.v.k))
  1190. check_conflict(ls, lh, &nv.v);
  1191. enterlevel(ls); /* control recursion depth */
  1192. restassign(ls, &nv, nvars+1);
  1193. leavelevel(ls);
  1194. }
  1195. else { /* restassign -> '=' explist */
  1196. int nexps;
  1197. checknext(ls, '=');
  1198. nexps = explist(ls, &e);
  1199. if (nexps != nvars)
  1200. adjust_assign(ls, nvars, nexps, &e);
  1201. else {
  1202. luaK_setoneret(ls->fs, &e); /* close last expression */
  1203. luaK_storevar(ls->fs, &lh->v, &e);
  1204. return; /* avoid default */
  1205. }
  1206. }
  1207. init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
  1208. luaK_storevar(ls->fs, &lh->v, &e);
  1209. }
  1210. static int cond (LexState *ls) {
  1211. /* cond -> exp */
  1212. expdesc v;
  1213. expr(ls, &v); /* read condition */
  1214. if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */
  1215. luaK_goiftrue(ls->fs, &v);
  1216. return v.f;
  1217. }
  1218. static void gotostat (LexState *ls) {
  1219. FuncState *fs = ls->fs;
  1220. int line = ls->linenumber;
  1221. TString *name = str_checkname(ls); /* label's name */
  1222. Labeldesc *lb = findlabel(ls, name);
  1223. if (lb == NULL) /* no label? */
  1224. /* forward jump; will be resolved when the label is declared */
  1225. newgotoentry(ls, name, line, luaK_jump(fs));
  1226. else { /* found a label */
  1227. /* backward jump; will be resolved here */
  1228. int lblevel = stacklevel(fs, lb->nactvar); /* label level */
  1229. if (luaY_nvarstack(fs) > lblevel) /* leaving the scope of a variable? */
  1230. luaK_codeABC(fs, OP_CLOSE, lblevel, 0, 0);
  1231. /* create jump and link it to the label */
  1232. luaK_patchlist(fs, luaK_jump(fs), lb->pc);
  1233. }
  1234. }
  1235. /*
  1236. ** Break statement. Semantically equivalent to "goto break".
  1237. */
  1238. static void breakstat (LexState *ls) {
  1239. int line = ls->linenumber;
  1240. luaX_next(ls); /* skip break */
  1241. newgotoentry(ls, luaS_newliteral(ls->L, "break"), line, luaK_jump(ls->fs));
  1242. }
  1243. /*
  1244. ** Check whether there is already a label with the given 'name'.
  1245. */
  1246. static void checkrepeated (LexState *ls, TString *name) {
  1247. Labeldesc *lb = findlabel(ls, name);
  1248. if (unlikely(lb != NULL)) { /* already defined? */
  1249. const char *msg = "label '%s' already defined on line %d";
  1250. msg = luaO_pushfstring(ls->L, msg, getstr(name), lb->line);
  1251. luaK_semerror(ls, msg); /* error */
  1252. }
  1253. }
  1254. static void labelstat (LexState *ls, TString *name, int line) {
  1255. /* label -> '::' NAME '::' */
  1256. checknext(ls, TK_DBCOLON); /* skip double colon */
  1257. while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
  1258. statement(ls); /* skip other no-op statements */
  1259. checkrepeated(ls, name); /* check for repeated labels */
  1260. createlabel(ls, name, line, block_follow(ls, 0));
  1261. }
  1262. static void whilestat (LexState *ls, int line) {
  1263. /* whilestat -> WHILE cond DO block END */
  1264. FuncState *fs = ls->fs;
  1265. int whileinit;
  1266. int condexit;
  1267. BlockCnt bl;
  1268. luaX_next(ls); /* skip WHILE */
  1269. whileinit = luaK_getlabel(fs);
  1270. condexit = cond(ls);
  1271. enterblock(fs, &bl, 1);
  1272. checknext(ls, TK_DO);
  1273. block(ls);
  1274. luaK_jumpto(fs, whileinit);
  1275. check_match(ls, TK_END, TK_WHILE, line);
  1276. leaveblock(fs);
  1277. luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
  1278. }
  1279. static void repeatstat (LexState *ls, int line) {
  1280. /* repeatstat -> REPEAT block UNTIL cond */
  1281. int condexit;
  1282. FuncState *fs = ls->fs;
  1283. int repeat_init = luaK_getlabel(fs);
  1284. BlockCnt bl1, bl2;
  1285. enterblock(fs, &bl1, 1); /* loop block */
  1286. enterblock(fs, &bl2, 0); /* scope block */
  1287. luaX_next(ls); /* skip REPEAT */
  1288. statlist(ls);
  1289. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  1290. condexit = cond(ls); /* read condition (inside scope block) */
  1291. leaveblock(fs); /* finish scope */
  1292. if (bl2.upval) { /* upvalues? */
  1293. int exit = luaK_jump(fs); /* normal exit must jump over fix */
  1294. luaK_patchtohere(fs, condexit); /* repetition must close upvalues */
  1295. luaK_codeABC(fs, OP_CLOSE, stacklevel(fs, bl2.nactvar), 0, 0);
  1296. condexit = luaK_jump(fs); /* repeat after closing upvalues */
  1297. luaK_patchtohere(fs, exit); /* normal exit comes to here */
  1298. }
  1299. luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
  1300. leaveblock(fs); /* finish loop */
  1301. }
  1302. /*
  1303. ** Read an expression and generate code to put its results in next
  1304. ** stack slot.
  1305. **
  1306. */
  1307. static void exp1 (LexState *ls) {
  1308. expdesc e;
  1309. expr(ls, &e);
  1310. luaK_exp2nextreg(ls->fs, &e);
  1311. lua_assert(e.k == VNONRELOC);
  1312. }
  1313. /*
  1314. ** Fix for instruction at position 'pc' to jump to 'dest'.
  1315. ** (Jump addresses are relative in Lua). 'back' true means
  1316. ** a back jump.
  1317. */
  1318. static void fixforjump (FuncState *fs, int pc, int dest, int back) {
  1319. Instruction *jmp = &fs->f->code[pc];
  1320. int offset = dest - (pc + 1);
  1321. if (back)
  1322. offset = -offset;
  1323. if (unlikely(offset > MAXARG_Bx))
  1324. luaX_syntaxerror(fs->ls, "control structure too long");
  1325. SETARG_Bx(*jmp, offset);
  1326. }
  1327. /*
  1328. ** Generate code for a 'for' loop.
  1329. */
  1330. static void forbody (LexState *ls, int base, int line, int nvars, int isgen) {
  1331. /* forbody -> DO block */
  1332. static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP};
  1333. static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP};
  1334. BlockCnt bl;
  1335. FuncState *fs = ls->fs;
  1336. int prep, endfor;
  1337. checknext(ls, TK_DO);
  1338. prep = luaK_codeABx(fs, forprep[isgen], base, 0);
  1339. enterblock(fs, &bl, 0); /* scope for declared variables */
  1340. adjustlocalvars(ls, nvars);
  1341. luaK_reserveregs(fs, nvars);
  1342. block(ls);
  1343. leaveblock(fs); /* end of scope for declared variables */
  1344. fixforjump(fs, prep, luaK_getlabel(fs), 0);
  1345. if (isgen) { /* generic for? */
  1346. luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
  1347. luaK_fixline(fs, line);
  1348. }
  1349. endfor = luaK_codeABx(fs, forloop[isgen], base, 0);
  1350. fixforjump(fs, endfor, prep + 1, 1);
  1351. luaK_fixline(fs, line);
  1352. }
  1353. static void fornum (LexState *ls, TString *varname, int line) {
  1354. /* fornum -> NAME = exp,exp[,exp] forbody */
  1355. FuncState *fs = ls->fs;
  1356. int base = fs->freereg;
  1357. new_localvarliteral(ls, "(for state)");
  1358. new_localvarliteral(ls, "(for state)");
  1359. new_localvarliteral(ls, "(for state)");
  1360. new_localvar(ls, varname);
  1361. checknext(ls, '=');
  1362. exp1(ls); /* initial value */
  1363. checknext(ls, ',');
  1364. exp1(ls); /* limit */
  1365. if (testnext(ls, ','))
  1366. exp1(ls); /* optional step */
  1367. else { /* default step = 1 */
  1368. luaK_int(fs, fs->freereg, 1);
  1369. luaK_reserveregs(fs, 1);
  1370. }
  1371. adjustlocalvars(ls, 3); /* control variables */
  1372. forbody(ls, base, line, 1, 0);
  1373. }
  1374. static void forlist (LexState *ls, TString *indexname) {
  1375. /* forlist -> NAME {,NAME} IN explist forbody */
  1376. FuncState *fs = ls->fs;
  1377. expdesc e;
  1378. int nvars = 5; /* gen, state, control, toclose, 'indexname' */
  1379. int line;
  1380. int base = fs->freereg;
  1381. /* create control variables */
  1382. new_localvarliteral(ls, "(for state)");
  1383. new_localvarliteral(ls, "(for state)");
  1384. new_localvarliteral(ls, "(for state)");
  1385. new_localvarliteral(ls, "(for state)");
  1386. /* create declared variables */
  1387. new_localvar(ls, indexname);
  1388. while (testnext(ls, ',')) {
  1389. new_localvar(ls, str_checkname(ls));
  1390. nvars++;
  1391. }
  1392. checknext(ls, TK_IN);
  1393. line = ls->linenumber;
  1394. adjust_assign(ls, 4, explist(ls, &e), &e);
  1395. adjustlocalvars(ls, 4); /* control variables */
  1396. markupval(fs, fs->nactvar); /* last control var. must be closed */
  1397. luaK_checkstack(fs, 3); /* extra space to call generator */
  1398. forbody(ls, base, line, nvars - 4, 1);
  1399. }
  1400. static void forstat (LexState *ls, int line) {
  1401. /* forstat -> FOR (fornum | forlist) END */
  1402. FuncState *fs = ls->fs;
  1403. TString *varname;
  1404. BlockCnt bl;
  1405. enterblock(fs, &bl, 1); /* scope for loop and control variables */
  1406. luaX_next(ls); /* skip 'for' */
  1407. varname = str_checkname(ls); /* first variable name */
  1408. switch (ls->t.token) {
  1409. case '=': fornum(ls, varname, line); break;
  1410. case ',': case TK_IN: forlist(ls, varname); break;
  1411. default: luaX_syntaxerror(ls, "'=' or 'in' expected");
  1412. }
  1413. check_match(ls, TK_END, TK_FOR, line);
  1414. leaveblock(fs); /* loop scope ('break' jumps to this point) */
  1415. }
  1416. /*
  1417. ** Check whether next instruction is a single jump (a 'break', a 'goto'
  1418. ** to a forward label, or a 'goto' to a backward label with no variable
  1419. ** to close). If so, set the name of the 'label' it is jumping to
  1420. ** ("break" for a 'break') or to where it is jumping to ('target') and
  1421. ** return true. If not a single jump, leave input unchanged, to be
  1422. ** handled as a regular statement.
  1423. */
  1424. static int issinglejump (LexState *ls, TString **label, int *target) {
  1425. if (testnext(ls, TK_BREAK)) { /* a break? */
  1426. *label = luaS_newliteral(ls->L, "break");
  1427. return 1;
  1428. }
  1429. else if (ls->t.token != TK_GOTO || luaX_lookahead(ls) != TK_NAME)
  1430. return 0; /* not a valid goto */
  1431. else {
  1432. TString *lname = ls->lookahead.seminfo.ts; /* label's id */
  1433. Labeldesc *lb = findlabel(ls, lname);
  1434. if (lb) { /* a backward jump? */
  1435. /* does it need to close variables? */
  1436. if (luaY_nvarstack(ls->fs) > stacklevel(ls->fs, lb->nactvar))
  1437. return 0; /* not a single jump; cannot optimize */
  1438. *target = lb->pc;
  1439. }
  1440. else /* jump forward */
  1441. *label = lname;
  1442. luaX_next(ls); /* skip goto */
  1443. luaX_next(ls); /* skip name */
  1444. return 1;
  1445. }
  1446. }
  1447. static void test_then_block (LexState *ls, int *escapelist) {
  1448. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  1449. BlockCnt bl;
  1450. int line;
  1451. FuncState *fs = ls->fs;
  1452. TString *jlb = NULL;
  1453. int target = NO_JUMP;
  1454. expdesc v;
  1455. int jf; /* instruction to skip 'then' code (if condition is false) */
  1456. luaX_next(ls); /* skip IF or ELSEIF */
  1457. expr(ls, &v); /* read condition */
  1458. checknext(ls, TK_THEN);
  1459. line = ls->linenumber;
  1460. if (issinglejump(ls, &jlb, &target)) { /* 'if x then goto' ? */
  1461. luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */
  1462. enterblock(fs, &bl, 0); /* must enter block before 'goto' */
  1463. if (jlb != NULL) /* forward jump? */
  1464. newgotoentry(ls, jlb, line, v.t); /* will be resolved later */
  1465. else /* backward jump */
  1466. luaK_patchlist(fs, v.t, target); /* jump directly to 'target' */
  1467. while (testnext(ls, ';')) {} /* skip semicolons */
  1468. if (block_follow(ls, 0)) { /* jump is the entire block? */
  1469. leaveblock(fs);
  1470. return; /* and that is it */
  1471. }
  1472. else /* must skip over 'then' part if condition is false */
  1473. jf = luaK_jump(fs);
  1474. }
  1475. else { /* regular case (not a jump) */
  1476. luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */
  1477. enterblock(fs, &bl, 0);
  1478. jf = v.f;
  1479. }
  1480. statlist(ls); /* 'then' part */
  1481. leaveblock(fs);
  1482. if (ls->t.token == TK_ELSE ||
  1483. ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
  1484. luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
  1485. luaK_patchtohere(fs, jf);
  1486. }
  1487. static void ifstat (LexState *ls, int line) {
  1488. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  1489. FuncState *fs = ls->fs;
  1490. int escapelist = NO_JUMP; /* exit list for finished parts */
  1491. test_then_block(ls, &escapelist); /* IF cond THEN block */
  1492. while (ls->t.token == TK_ELSEIF)
  1493. test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
  1494. if (testnext(ls, TK_ELSE))
  1495. block(ls); /* 'else' part */
  1496. check_match(ls, TK_END, TK_IF, line);
  1497. luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
  1498. }
  1499. static void localfunc (LexState *ls) {
  1500. expdesc b;
  1501. FuncState *fs = ls->fs;
  1502. int fvar = fs->nactvar; /* function's variable index */
  1503. new_localvar(ls, str_checkname(ls)); /* new local variable */
  1504. adjustlocalvars(ls, 1); /* enter its scope */
  1505. body(ls, &b, 0, ls->linenumber); /* function created in next register */
  1506. /* debug information will only see the variable after this point! */
  1507. localdebuginfo(fs, fvar)->startpc = fs->pc;
  1508. }
  1509. static int getlocalattribute (LexState *ls) {
  1510. /* ATTRIB -> ['<' Name '>'] */
  1511. if (testnext(ls, '<')) {
  1512. const char *attr = getstr(str_checkname(ls));
  1513. checknext(ls, '>');
  1514. if (strcmp(attr, "const") == 0)
  1515. return RDKCONST; /* read-only variable */
  1516. else if (strcmp(attr, "close") == 0)
  1517. return RDKTOCLOSE; /* to-be-closed variable */
  1518. else
  1519. luaK_semerror(ls,
  1520. luaO_pushfstring(ls->L, "unknown attribute '%s'", attr));
  1521. }
  1522. return VDKREG; /* regular variable */
  1523. }
  1524. static void checktoclose (LexState *ls, int level) {
  1525. if (level != -1) { /* is there a to-be-closed variable? */
  1526. FuncState *fs = ls->fs;
  1527. markupval(fs, level + 1);
  1528. fs->bl->insidetbc = 1; /* in the scope of a to-be-closed variable */
  1529. luaK_codeABC(fs, OP_TBC, stacklevel(fs, level), 0, 0);
  1530. }
  1531. }
  1532. static void localstat (LexState *ls) {
  1533. /* stat -> LOCAL ATTRIB NAME {',' ATTRIB NAME} ['=' explist] */
  1534. FuncState *fs = ls->fs;
  1535. int toclose = -1; /* index of to-be-closed variable (if any) */
  1536. Vardesc *var; /* last variable */
  1537. int vidx, kind; /* index and kind of last variable */
  1538. int nvars = 0;
  1539. int nexps;
  1540. expdesc e;
  1541. do {
  1542. vidx = new_localvar(ls, str_checkname(ls));
  1543. kind = getlocalattribute(ls);
  1544. getlocalvardesc(fs, vidx)->vd.kind = kind;
  1545. if (kind == RDKTOCLOSE) { /* to-be-closed? */
  1546. if (toclose != -1) /* one already present? */
  1547. luaK_semerror(ls, "multiple to-be-closed variables in local list");
  1548. toclose = fs->nactvar + nvars;
  1549. }
  1550. nvars++;
  1551. } while (testnext(ls, ','));
  1552. if (testnext(ls, '='))
  1553. nexps = explist(ls, &e);
  1554. else {
  1555. e.k = VVOID;
  1556. nexps = 0;
  1557. }
  1558. var = getlocalvardesc(fs, vidx); /* get last variable */
  1559. if (nvars == nexps && /* no adjustments? */
  1560. var->vd.kind == RDKCONST && /* last variable is const? */
  1561. luaK_exp2const(fs, &e, &var->k)) { /* compile-time constant? */
  1562. var->vd.kind = RDKCTC; /* variable is a compile-time constant */
  1563. adjustlocalvars(ls, nvars - 1); /* exclude last variable */
  1564. fs->nactvar++; /* but count it */
  1565. }
  1566. else {
  1567. adjust_assign(ls, nvars, nexps, &e);
  1568. adjustlocalvars(ls, nvars);
  1569. }
  1570. checktoclose(ls, toclose);
  1571. }
  1572. static int funcname (LexState *ls, expdesc *v) {
  1573. /* funcname -> NAME {fieldsel} [':' NAME] */
  1574. int ismethod = 0;
  1575. singlevar(ls, v);
  1576. while (ls->t.token == '.')
  1577. fieldsel(ls, v);
  1578. if (ls->t.token == ':') {
  1579. ismethod = 1;
  1580. fieldsel(ls, v);
  1581. }
  1582. return ismethod;
  1583. }
  1584. static void funcstat (LexState *ls, int line) {
  1585. /* funcstat -> FUNCTION funcname body */
  1586. int ismethod;
  1587. expdesc v, b;
  1588. luaX_next(ls); /* skip FUNCTION */
  1589. ismethod = funcname(ls, &v);
  1590. body(ls, &b, ismethod, line);
  1591. luaK_storevar(ls->fs, &v, &b);
  1592. luaK_fixline(ls->fs, line); /* definition "happens" in the first line */
  1593. }
  1594. static void exprstat (LexState *ls) {
  1595. /* stat -> func | assignment */
  1596. FuncState *fs = ls->fs;
  1597. struct LHS_assign v;
  1598. suffixedexp(ls, &v.v);
  1599. if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
  1600. v.prev = NULL;
  1601. restassign(ls, &v, 1);
  1602. }
  1603. else { /* stat -> func */
  1604. Instruction *inst;
  1605. check_condition(ls, v.v.k == VCALL, "syntax error");
  1606. inst = &getinstruction(fs, &v.v);
  1607. SETARG_C(*inst, 1); /* call statement uses no results */
  1608. }
  1609. }
  1610. static void retstat (LexState *ls) {
  1611. /* stat -> RETURN [explist] [';'] */
  1612. FuncState *fs = ls->fs;
  1613. expdesc e;
  1614. int nret; /* number of values being returned */
  1615. int first = luaY_nvarstack(fs); /* first slot to be returned */
  1616. if (block_follow(ls, 1) || ls->t.token == ';')
  1617. nret = 0; /* return no values */
  1618. else {
  1619. nret = explist(ls, &e); /* optional return values */
  1620. if (hasmultret(e.k)) {
  1621. luaK_setmultret(fs, &e);
  1622. if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc) { /* tail call? */
  1623. SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);
  1624. lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs));
  1625. }
  1626. nret = LUA_MULTRET; /* return all values */
  1627. }
  1628. else {
  1629. if (nret == 1) /* only one single value? */
  1630. first = luaK_exp2anyreg(fs, &e); /* can use original slot */
  1631. else { /* values must go to the top of the stack */
  1632. luaK_exp2nextreg(fs, &e);
  1633. lua_assert(nret == fs->freereg - first);
  1634. }
  1635. }
  1636. }
  1637. luaK_ret(fs, first, nret);
  1638. testnext(ls, ';'); /* skip optional semicolon */
  1639. }
  1640. static void statement (LexState *ls) {
  1641. int line = ls->linenumber; /* may be needed for error messages */
  1642. enterlevel(ls);
  1643. switch (ls->t.token) {
  1644. case ';': { /* stat -> ';' (empty statement) */
  1645. luaX_next(ls); /* skip ';' */
  1646. break;
  1647. }
  1648. case TK_IF: { /* stat -> ifstat */
  1649. ifstat(ls, line);
  1650. break;
  1651. }
  1652. case TK_WHILE: { /* stat -> whilestat */
  1653. whilestat(ls, line);
  1654. break;
  1655. }
  1656. case TK_DO: { /* stat -> DO block END */
  1657. luaX_next(ls); /* skip DO */
  1658. block(ls);
  1659. check_match(ls, TK_END, TK_DO, line);
  1660. break;
  1661. }
  1662. case TK_FOR: { /* stat -> forstat */
  1663. forstat(ls, line);
  1664. break;
  1665. }
  1666. case TK_REPEAT: { /* stat -> repeatstat */
  1667. repeatstat(ls, line);
  1668. break;
  1669. }
  1670. case TK_FUNCTION: { /* stat -> funcstat */
  1671. funcstat(ls, line);
  1672. break;
  1673. }
  1674. case TK_LOCAL: { /* stat -> localstat */
  1675. luaX_next(ls); /* skip LOCAL */
  1676. if (testnext(ls, TK_FUNCTION)) /* local function? */
  1677. localfunc(ls);
  1678. else
  1679. localstat(ls);
  1680. break;
  1681. }
  1682. case TK_DBCOLON: { /* stat -> label */
  1683. luaX_next(ls); /* skip double colon */
  1684. labelstat(ls, str_checkname(ls), line);
  1685. break;
  1686. }
  1687. case TK_RETURN: { /* stat -> retstat */
  1688. luaX_next(ls); /* skip RETURN */
  1689. retstat(ls);
  1690. break;
  1691. }
  1692. case TK_BREAK: { /* stat -> breakstat */
  1693. breakstat(ls);
  1694. break;
  1695. }
  1696. case TK_GOTO: { /* stat -> 'goto' NAME */
  1697. luaX_next(ls); /* skip 'goto' */
  1698. gotostat(ls);
  1699. break;
  1700. }
  1701. default: { /* stat -> func | assignment */
  1702. exprstat(ls);
  1703. break;
  1704. }
  1705. }
  1706. lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
  1707. ls->fs->freereg >= luaY_nvarstack(ls->fs));
  1708. ls->fs->freereg = luaY_nvarstack(ls->fs); /* free registers */
  1709. leavelevel(ls);
  1710. }
  1711. /* }====================================================================== */
  1712. /*
  1713. ** compiles the main function, which is a regular vararg function with an
  1714. ** upvalue named LUA_ENV
  1715. */
  1716. static void mainfunc (LexState *ls, FuncState *fs) {
  1717. BlockCnt bl;
  1718. Upvaldesc *env;
  1719. open_func(ls, fs, &bl);
  1720. setvararg(fs, 0); /* main function is always declared vararg */
  1721. env = allocupvalue(fs); /* ...set environment upvalue */
  1722. env->instack = 1;
  1723. env->idx = 0;
  1724. env->kind = VDKREG;
  1725. env->name = ls->envn;
  1726. luaC_objbarrier(ls->L, fs->f, env->name);
  1727. luaX_next(ls); /* read first token */
  1728. statlist(ls); /* parse main body */
  1729. check(ls, TK_EOS);
  1730. close_func(ls);
  1731. }
  1732. LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
  1733. Dyndata *dyd, const char *name, int firstchar) {
  1734. LexState lexstate;
  1735. FuncState funcstate;
  1736. LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */
  1737. setclLvalue2s(L, L->top, cl); /* anchor it (to avoid being collected) */
  1738. luaD_inctop(L);
  1739. lexstate.h = luaH_new(L); /* create table for scanner */
  1740. sethvalue2s(L, L->top, lexstate.h); /* anchor it */
  1741. luaD_inctop(L);
  1742. funcstate.f = cl->p = luaF_newproto(L);
  1743. luaC_objbarrier(L, cl, cl->p);
  1744. funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
  1745. luaC_objbarrier(L, funcstate.f, funcstate.f->source);
  1746. lexstate.buff = buff;
  1747. lexstate.dyd = dyd;
  1748. dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
  1749. luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
  1750. mainfunc(&lexstate, &funcstate);
  1751. lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
  1752. /* all scopes should be correctly finished */
  1753. lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
  1754. L->top--; /* remove scanner's table */
  1755. return cl; /* closure is on the stack, too */
  1756. }