lparser.c 55 KB

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