lparser.c 56 KB

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