lparser.c 55 KB

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