lparser.c 55 KB

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