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