lparser.c 60 KB

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