lparser.c 55 KB

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