lparser.c 61 KB

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