lparser.c 61 KB

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