lparser.c 56 KB

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