lparser.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  1. /*
  2. ** $Id: lparser.c,v 2.103 2011/02/09 17:03:18 roberto Exp $
  3. ** Lua Parser
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <string.h>
  7. #define lparser_c
  8. #define LUA_CORE
  9. #include "lua.h"
  10. #include "lcode.h"
  11. #include "ldebug.h"
  12. #include "ldo.h"
  13. #include "lfunc.h"
  14. #include "llex.h"
  15. #include "lmem.h"
  16. #include "lobject.h"
  17. #include "lopcodes.h"
  18. #include "lparser.h"
  19. #include "lstate.h"
  20. #include "lstring.h"
  21. #include "ltable.h"
  22. /* maximum number of local variables per function (must be smaller
  23. than 250, due to the bytecode format) */
  24. #define MAXVARS 200
  25. #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
  26. /*
  27. ** nodes for block list (list of active blocks)
  28. */
  29. typedef struct BlockCnt {
  30. struct BlockCnt *previous; /* chain */
  31. int firstlabel; /* index of first label in this block */
  32. int firstgoto; /* index of first pending goto in this block */
  33. lu_byte nactvar; /* # active locals outside the block */
  34. lu_byte upval; /* true if some variable in the block is an upvalue */
  35. lu_byte isloop; /* true if `block' is a loop */
  36. } BlockCnt;
  37. /*
  38. ** prototypes for recursive non-terminal functions
  39. */
  40. static void statlist (LexState *ls);
  41. static void expr (LexState *ls, expdesc *v);
  42. static void anchor_token (LexState *ls) {
  43. /* last token from outer function must be EOS */
  44. lua_assert(ls->fs != NULL || ls->t.token == TK_EOS);
  45. if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
  46. TString *ts = ls->t.seminfo.ts;
  47. luaX_newstring(ls, getstr(ts), ts->tsv.len);
  48. }
  49. }
  50. /* semantic error */
  51. static void semerror (LexState *ls, const char *msg) {
  52. ls->t.token = 0; /* remove 'near to' from final message */
  53. luaX_syntaxerror(ls, msg);
  54. }
  55. static void error_expected (LexState *ls, int token) {
  56. luaX_syntaxerror(ls,
  57. luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
  58. }
  59. static void errorlimit (FuncState *fs, int limit, const char *what) {
  60. const char *msg;
  61. int line = fs->f->linedefined;
  62. const char *where = (line == 0)
  63. ? "main function"
  64. : luaO_pushfstring(fs->L, "function at line %d", line);
  65. msg = luaO_pushfstring(fs->L, "too many %s (limit is %d) in %s",
  66. what, limit, where);
  67. luaX_syntaxerror(fs->ls, msg);
  68. }
  69. static void checklimit (FuncState *fs, int v, int l, const char *what) {
  70. if (v > l) errorlimit(fs, l, what);
  71. }
  72. static int testnext (LexState *ls, int c) {
  73. if (ls->t.token == c) {
  74. luaX_next(ls);
  75. return 1;
  76. }
  77. else return 0;
  78. }
  79. static void check (LexState *ls, int c) {
  80. if (ls->t.token != c)
  81. error_expected(ls, c);
  82. }
  83. static void checknext (LexState *ls, int c) {
  84. check(ls, c);
  85. luaX_next(ls);
  86. }
  87. #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
  88. static void check_match (LexState *ls, int what, int who, int where) {
  89. if (!testnext(ls, what)) {
  90. if (where == ls->linenumber)
  91. error_expected(ls, what);
  92. else {
  93. luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
  94. "%s expected (to close %s at line %d)",
  95. luaX_token2str(ls, what), luaX_token2str(ls, who), where));
  96. }
  97. }
  98. }
  99. static TString *str_checkname (LexState *ls) {
  100. TString *ts;
  101. check(ls, TK_NAME);
  102. ts = ls->t.seminfo.ts;
  103. luaX_next(ls);
  104. return ts;
  105. }
  106. static void init_exp (expdesc *e, expkind k, int i) {
  107. e->f = e->t = NO_JUMP;
  108. e->k = k;
  109. e->u.info = i;
  110. }
  111. static void codestring (LexState *ls, expdesc *e, TString *s) {
  112. init_exp(e, VK, luaK_stringK(ls->fs, s));
  113. }
  114. static void checkname (LexState *ls, expdesc *e) {
  115. codestring(ls, e, str_checkname(ls));
  116. }
  117. static int registerlocalvar (LexState *ls, TString *varname) {
  118. FuncState *fs = ls->fs;
  119. Proto *f = fs->f;
  120. int oldsize = f->sizelocvars;
  121. luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
  122. LocVar, SHRT_MAX, "local variables");
  123. while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
  124. f->locvars[fs->nlocvars].varname = varname;
  125. luaC_objbarrier(ls->L, f, varname);
  126. return fs->nlocvars++;
  127. }
  128. static void new_localvar (LexState *ls, TString *name) {
  129. FuncState *fs = ls->fs;
  130. Dyndata *dyd = ls->dyd;
  131. int reg = registerlocalvar(ls, name);
  132. checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
  133. MAXVARS, "local variables");
  134. luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,
  135. dyd->actvar.size, Vardesc, MAX_INT, "local variables");
  136. dyd->actvar.arr[dyd->actvar.n++].idx = cast(unsigned short, reg);
  137. }
  138. static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) {
  139. new_localvar(ls, luaX_newstring(ls, name, sz));
  140. }
  141. #define new_localvarliteral(ls,v) \
  142. new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1)
  143. static LocVar *getlocvar (FuncState *fs, int i) {
  144. int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
  145. lua_assert(idx < fs->nlocvars);
  146. return &fs->f->locvars[idx];
  147. }
  148. static void adjustlocalvars (LexState *ls, int nvars) {
  149. FuncState *fs = ls->fs;
  150. fs->nactvar = cast_byte(fs->nactvar + nvars);
  151. for (; nvars; nvars--) {
  152. getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;
  153. }
  154. }
  155. static void removevars (FuncState *fs, int tolevel) {
  156. fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
  157. while (fs->nactvar > tolevel)
  158. getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
  159. }
  160. static int searchupvalue (FuncState *fs, TString *name) {
  161. int i;
  162. Upvaldesc *up = fs->f->upvalues;
  163. for (i = 0; i < fs->nups; i++) {
  164. if (eqstr(up[i].name, name)) return i;
  165. }
  166. return -1; /* not found */
  167. }
  168. static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
  169. Proto *f = fs->f;
  170. int oldsize = f->sizeupvalues;
  171. checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
  172. luaM_growvector(fs->L, f->upvalues, fs->nups, f->sizeupvalues,
  173. Upvaldesc, MAXUPVAL, "upvalues");
  174. while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL;
  175. f->upvalues[fs->nups].instack = (v->k == VLOCAL);
  176. f->upvalues[fs->nups].idx = cast_byte(v->u.info);
  177. f->upvalues[fs->nups].name = name;
  178. luaC_objbarrier(fs->L, f, name);
  179. return fs->nups++;
  180. }
  181. static int searchvar (FuncState *fs, TString *n) {
  182. int i;
  183. for (i=fs->nactvar-1; i >= 0; i--) {
  184. if (eqstr(n, getlocvar(fs, i)->varname))
  185. return i;
  186. }
  187. return -1; /* not found */
  188. }
  189. /*
  190. Mark block where variable at given level was defined
  191. (to emit close instructions later).
  192. */
  193. static void markupval (FuncState *fs, int level) {
  194. BlockCnt *bl = fs->bl;
  195. while (bl->nactvar > level) bl = bl->previous;
  196. bl->upval = 1;
  197. }
  198. /*
  199. Find variable with given name 'n'. If it is an upvalue, add this
  200. upvalue into all intermediate functions.
  201. */
  202. static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
  203. if (fs == NULL) /* no more levels? */
  204. return VVOID; /* default is global */
  205. else {
  206. int v = searchvar(fs, n); /* look up locals at current level */
  207. if (v >= 0) { /* found? */
  208. init_exp(var, VLOCAL, v); /* variable is local */
  209. if (!base)
  210. markupval(fs, v); /* local will be used as an upval */
  211. return VLOCAL;
  212. }
  213. else { /* not found as local at current level; try upvalues */
  214. int idx = searchupvalue(fs, n); /* try existing upvalues */
  215. if (idx < 0) { /* not found? */
  216. if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */
  217. return VVOID; /* not found; is a global */
  218. /* else was LOCAL or UPVAL */
  219. idx = newupvalue(fs, n, var); /* will be a new upvalue */
  220. }
  221. init_exp(var, VUPVAL, idx);
  222. return VUPVAL;
  223. }
  224. }
  225. }
  226. static void singlevar (LexState *ls, expdesc *var) {
  227. TString *varname = str_checkname(ls);
  228. FuncState *fs = ls->fs;
  229. if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */
  230. expdesc key;
  231. singlevaraux(fs, ls->envn, var, 1); /* get environment variable */
  232. lua_assert(var->k == VLOCAL || var->k == VUPVAL);
  233. codestring(ls, &key, varname); /* key is variable name */
  234. luaK_indexed(fs, var, &key); /* env[varname] */
  235. }
  236. }
  237. static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
  238. FuncState *fs = ls->fs;
  239. int extra = nvars - nexps;
  240. if (hasmultret(e->k)) {
  241. extra++; /* includes call itself */
  242. if (extra < 0) extra = 0;
  243. luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
  244. if (extra > 1) luaK_reserveregs(fs, extra-1);
  245. }
  246. else {
  247. if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */
  248. if (extra > 0) {
  249. int reg = fs->freereg;
  250. luaK_reserveregs(fs, extra);
  251. luaK_nil(fs, reg, extra);
  252. }
  253. }
  254. }
  255. static void enterlevel (LexState *ls) {
  256. global_State *g = G(ls->L);
  257. ++g->nCcalls;
  258. checklimit(ls->fs, g->nCcalls, LUAI_MAXCCALLS, "syntax levels");
  259. }
  260. #define leavelevel(ls) (G((ls)->L)->nCcalls--)
  261. static void closegoto (LexState *ls, int g, Labeldesc *label) {
  262. int i;
  263. FuncState *fs = ls->fs;
  264. Dyndata *dyd = ls->dyd;
  265. Labeldesc *gt = &dyd->gt.arr[g];
  266. lua_assert(eqstr(gt->name, label->name));
  267. if (gt->nactvar < label->nactvar) {
  268. const char *msg = luaO_pushfstring(ls->L,
  269. "<goto %s> at line %d jumps into the scope of local " LUA_QS,
  270. getstr(gt->name), gt->line, getstr(getlocvar(fs, gt->nactvar)->varname));
  271. semerror(ls, msg);
  272. }
  273. luaK_patchlist(fs, gt->pc, label->pc);
  274. /* remove goto from pending list */
  275. for (i = g; i < dyd->gt.n - 1; i++)
  276. dyd->gt.arr[i] = dyd->gt.arr[i + 1];
  277. dyd->gt.n--;
  278. }
  279. /*
  280. ** try to close a goto with existing labels; this solves backward jumps
  281. */
  282. static int findlabel (LexState *ls, int g) {
  283. int i;
  284. BlockCnt *bl = ls->fs->bl;
  285. Dyndata *dyd = ls->dyd;
  286. Labeldesc *gt = &dyd->gt.arr[g];
  287. /* check labels in current block for a match */
  288. for (i = bl->firstlabel; i < dyd->label.n; i++) {
  289. Labeldesc *lb = &dyd->label.arr[i];
  290. if (eqstr(lb->name, gt->name)) { /* correct label? */
  291. if (gt->nactvar > lb->nactvar &&
  292. (bl->upval || dyd->label.n > bl->firstlabel))
  293. luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
  294. closegoto(ls, g, lb); /* close it */
  295. return 1;
  296. }
  297. }
  298. return 0; /* label not found; cannot close goto */
  299. }
  300. static int newlabelentry (LexState *ls, Labellist *l, TString *name,
  301. int line, int pc) {
  302. int n = l->n;
  303. luaM_growvector(ls->L, l->arr, n, l->size, Labeldesc, MAX_INT, "labels");
  304. l->arr[n].name = name;
  305. l->arr[n].line = line;
  306. l->arr[n].nactvar = ls->fs->nactvar;
  307. l->arr[n].pc = pc;
  308. l->n++;
  309. return n;
  310. }
  311. /*
  312. ** check whether new label 'lb' matches any pending gotos in current
  313. ** block; solves forward jumps
  314. */
  315. static void findgotos (LexState *ls, Labeldesc *lb) {
  316. Dyndata *dyd = ls->dyd;
  317. int i = ls->fs->bl->firstgoto;
  318. while (i < dyd->gt.n) {
  319. if (eqstr(dyd->gt.arr[i].name, lb->name))
  320. closegoto(ls, i, lb);
  321. else
  322. i++;
  323. }
  324. }
  325. /*
  326. ** "export" pending gotos to outer level, to check them against
  327. ** outer labels; if the block being exited has upvalues, and
  328. ** the goto exists the scope of any variable (which can be the
  329. ** upvalue), close those variables being exited.
  330. */
  331. static void movegotosout (FuncState *fs, BlockCnt *bl) {
  332. int i = bl->firstgoto;
  333. Dyndata *dyd = fs->ls->dyd;
  334. /* correct pending gotos to current block and try to close it
  335. with visible labels */
  336. while (i < dyd->gt.n) {
  337. Labeldesc *gt = &dyd->gt.arr[i];
  338. if (gt->nactvar > bl->nactvar) {
  339. if (bl->upval)
  340. luaK_patchclose(fs, gt->pc, bl->nactvar);
  341. gt->nactvar = bl->nactvar;
  342. }
  343. if (!findlabel(fs->ls, i))
  344. i++; /* move to next one */
  345. }
  346. }
  347. static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
  348. bl->isloop = isloop;
  349. bl->nactvar = fs->nactvar;
  350. bl->firstlabel = fs->ls->dyd->label.n;
  351. bl->firstgoto = fs->ls->dyd->gt.n;
  352. bl->upval = 0;
  353. bl->previous = fs->bl;
  354. fs->bl = bl;
  355. lua_assert(fs->freereg == fs->nactvar);
  356. }
  357. /*
  358. ** create a label named "break" to resolve break statements
  359. */
  360. static void breaklabel (LexState *ls) {
  361. TString *n = luaS_new(ls->L, "break");
  362. int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);
  363. findgotos(ls, &ls->dyd->label.arr[l]);
  364. }
  365. /*
  366. ** generates an error for an undefined 'goto'; choose appropriate
  367. ** message when label name is a resserved word (which can only be 'break')
  368. */
  369. static void undefgoto (LexState *ls, Labeldesc *gt) {
  370. const char *msg = (gt->name->tsv.reserved > 0)
  371. ? "<%s> at line %d not inside a loop"
  372. : "label " LUA_QS " (<goto> at line %d) undefined";
  373. msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
  374. semerror(ls, msg);
  375. }
  376. static void leaveblock (FuncState *fs) {
  377. BlockCnt *bl = fs->bl;
  378. LexState *ls = fs->ls;
  379. if (bl->previous && bl->upval) {
  380. /* create a 'jump to here' to close upvalues */
  381. int j = luaK_jump(fs);
  382. luaK_patchclose(fs, j, bl->nactvar);
  383. luaK_patchtohere(fs, j);
  384. }
  385. if (bl->isloop)
  386. breaklabel(ls); /* close pending breaks */
  387. fs->bl = bl->previous;
  388. removevars(fs, bl->nactvar);
  389. lua_assert(bl->nactvar == fs->nactvar);
  390. fs->freereg = fs->nactvar; /* free registers */
  391. ls->dyd->label.n = bl->firstlabel; /* remove local labels */
  392. if (bl->previous) /* inner block? */
  393. movegotosout(fs, bl); /* update pending gotos to outer block */
  394. else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */
  395. undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
  396. }
  397. /*
  398. ** adds prototype being created into its parent list of prototypes
  399. ** and codes instruction to create new closure
  400. */
  401. static void codeclosure (LexState *ls, Proto *clp, expdesc *v) {
  402. FuncState *fs = ls->fs->prev;
  403. Proto *f = fs->f; /* prototype of function creating new closure */
  404. if (fs->np >= f->sizep) {
  405. int oldsize = f->sizep;
  406. luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
  407. MAXARG_Bx, "functions");
  408. while (oldsize < f->sizep) f->p[oldsize++] = NULL;
  409. }
  410. f->p[fs->np++] = clp;
  411. luaC_objbarrier(ls->L, f, clp);
  412. init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
  413. luaK_exp2nextreg(fs, v); /* fix it at stack top (for GC) */
  414. }
  415. static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
  416. lua_State *L = ls->L;
  417. Proto *f;
  418. fs->prev = ls->fs; /* linked list of funcstates */
  419. fs->ls = ls;
  420. fs->L = L;
  421. ls->fs = fs;
  422. fs->pc = 0;
  423. fs->lasttarget = 0;
  424. fs->jpc = NO_JUMP;
  425. fs->freereg = 0;
  426. fs->nk = 0;
  427. fs->np = 0;
  428. fs->nups = 0;
  429. fs->nlocvars = 0;
  430. fs->nactvar = 0;
  431. fs->firstlocal = ls->dyd->actvar.n;
  432. fs->bl = NULL;
  433. f = luaF_newproto(L);
  434. fs->f = f;
  435. f->source = ls->source;
  436. f->maxstacksize = 2; /* registers 0/1 are always valid */
  437. /* anchor prototype (to avoid being collected) */
  438. setptvalue2s(L, L->top, f);
  439. incr_top(L);
  440. fs->h = luaH_new(L);
  441. /* anchor table of constants (to avoid being collected) */
  442. sethvalue2s(L, L->top, fs->h);
  443. incr_top(L);
  444. enterblock(fs, bl, 0);
  445. }
  446. static void close_func (LexState *ls) {
  447. lua_State *L = ls->L;
  448. FuncState *fs = ls->fs;
  449. Proto *f = fs->f;
  450. luaK_ret(fs, 0, 0); /* final return */
  451. leaveblock(fs);
  452. luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
  453. f->sizecode = fs->pc;
  454. luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
  455. f->sizelineinfo = fs->pc;
  456. luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
  457. f->sizek = fs->nk;
  458. luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
  459. f->sizep = fs->np;
  460. luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
  461. f->sizelocvars = fs->nlocvars;
  462. luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
  463. f->sizeupvalues = fs->nups;
  464. lua_assert(fs->bl == NULL);
  465. ls->fs = fs->prev;
  466. /* last token read was anchored in defunct function; must re-anchor it */
  467. anchor_token(ls);
  468. L->top--; /* pop table of constants */
  469. luaC_checkGC(L);
  470. L->top--; /* pop prototype (after possible collection) */
  471. }
  472. /*
  473. ** opens the main function, which is a regular vararg function with an
  474. ** upvalue named LUA_ENV
  475. */
  476. static void open_mainfunc (LexState *ls, FuncState *fs, BlockCnt *bl) {
  477. expdesc v;
  478. open_func(ls, fs, bl);
  479. fs->f->is_vararg = 1; /* main function is always vararg */
  480. init_exp(&v, VLOCAL, 0);
  481. newupvalue(fs, ls->envn, &v); /* create environment upvalue */
  482. }
  483. Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
  484. Dyndata *dyd, const char *name) {
  485. LexState lexstate;
  486. FuncState funcstate;
  487. BlockCnt bl;
  488. TString *tname = luaS_new(L, name);
  489. setsvalue2s(L, L->top, tname); /* push name to protect it */
  490. incr_top(L);
  491. lexstate.buff = buff;
  492. lexstate.dyd = dyd;
  493. dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
  494. luaX_setinput(L, &lexstate, z, tname);
  495. open_mainfunc(&lexstate, &funcstate, &bl);
  496. luaX_next(&lexstate); /* read first token */
  497. statlist(&lexstate); /* main body */
  498. check(&lexstate, TK_EOS);
  499. close_func(&lexstate);
  500. L->top--; /* pop name */
  501. lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
  502. return funcstate.f;
  503. }
  504. /*============================================================*/
  505. /* GRAMMAR RULES */
  506. /*============================================================*/
  507. static void fieldsel (LexState *ls, expdesc *v) {
  508. /* fieldsel -> ['.' | ':'] NAME */
  509. FuncState *fs = ls->fs;
  510. expdesc key;
  511. luaK_exp2anyregup(fs, v);
  512. luaX_next(ls); /* skip the dot or colon */
  513. checkname(ls, &key);
  514. luaK_indexed(fs, v, &key);
  515. }
  516. static void yindex (LexState *ls, expdesc *v) {
  517. /* index -> '[' expr ']' */
  518. luaX_next(ls); /* skip the '[' */
  519. expr(ls, v);
  520. luaK_exp2val(ls->fs, v);
  521. checknext(ls, ']');
  522. }
  523. /*
  524. ** {======================================================================
  525. ** Rules for Constructors
  526. ** =======================================================================
  527. */
  528. struct ConsControl {
  529. expdesc v; /* last list item read */
  530. expdesc *t; /* table descriptor */
  531. int nh; /* total number of `record' elements */
  532. int na; /* total number of array elements */
  533. int tostore; /* number of array elements pending to be stored */
  534. };
  535. static void recfield (LexState *ls, struct ConsControl *cc) {
  536. /* recfield -> (NAME | `['exp1`]') = exp1 */
  537. FuncState *fs = ls->fs;
  538. int reg = ls->fs->freereg;
  539. expdesc key, val;
  540. int rkkey;
  541. if (ls->t.token == TK_NAME) {
  542. checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
  543. checkname(ls, &key);
  544. }
  545. else /* ls->t.token == '[' */
  546. yindex(ls, &key);
  547. cc->nh++;
  548. checknext(ls, '=');
  549. rkkey = luaK_exp2RK(fs, &key);
  550. expr(ls, &val);
  551. luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val));
  552. fs->freereg = reg; /* free registers */
  553. }
  554. static void closelistfield (FuncState *fs, struct ConsControl *cc) {
  555. if (cc->v.k == VVOID) return; /* there is no list item */
  556. luaK_exp2nextreg(fs, &cc->v);
  557. cc->v.k = VVOID;
  558. if (cc->tostore == LFIELDS_PER_FLUSH) {
  559. luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
  560. cc->tostore = 0; /* no more items pending */
  561. }
  562. }
  563. static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
  564. if (cc->tostore == 0) return;
  565. if (hasmultret(cc->v.k)) {
  566. luaK_setmultret(fs, &cc->v);
  567. luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
  568. cc->na--; /* do not count last expression (unknown number of elements) */
  569. }
  570. else {
  571. if (cc->v.k != VVOID)
  572. luaK_exp2nextreg(fs, &cc->v);
  573. luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
  574. }
  575. }
  576. static void listfield (LexState *ls, struct ConsControl *cc) {
  577. /* listfield -> exp */
  578. expr(ls, &cc->v);
  579. checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
  580. cc->na++;
  581. cc->tostore++;
  582. }
  583. static void field (LexState *ls, struct ConsControl *cc) {
  584. /* field -> listfield | recfield */
  585. switch(ls->t.token) {
  586. case TK_NAME: { /* may be 'listfield' or 'recfield' */
  587. if (luaX_lookahead(ls) != '=') /* expression? */
  588. listfield(ls, cc);
  589. else
  590. recfield(ls, cc);
  591. break;
  592. }
  593. case '[': {
  594. recfield(ls, cc);
  595. break;
  596. }
  597. default: {
  598. listfield(ls, cc);
  599. break;
  600. }
  601. }
  602. }
  603. static void constructor (LexState *ls, expdesc *t) {
  604. /* constructor -> '{' [ field { sep field } [sep] ] '}'
  605. sep -> ',' | ';' */
  606. FuncState *fs = ls->fs;
  607. int line = ls->linenumber;
  608. int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  609. struct ConsControl cc;
  610. cc.na = cc.nh = cc.tostore = 0;
  611. cc.t = t;
  612. init_exp(t, VRELOCABLE, pc);
  613. init_exp(&cc.v, VVOID, 0); /* no value (yet) */
  614. luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */
  615. checknext(ls, '{');
  616. do {
  617. lua_assert(cc.v.k == VVOID || cc.tostore > 0);
  618. if (ls->t.token == '}') break;
  619. closelistfield(fs, &cc);
  620. field(ls, &cc);
  621. } while (testnext(ls, ',') || testnext(ls, ';'));
  622. check_match(ls, '}', '{', line);
  623. lastlistfield(fs, &cc);
  624. SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
  625. SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
  626. }
  627. /* }====================================================================== */
  628. static void parlist (LexState *ls) {
  629. /* parlist -> [ param { `,' param } ] */
  630. FuncState *fs = ls->fs;
  631. Proto *f = fs->f;
  632. int nparams = 0;
  633. f->is_vararg = 0;
  634. if (ls->t.token != ')') { /* is `parlist' not empty? */
  635. do {
  636. switch (ls->t.token) {
  637. case TK_NAME: { /* param -> NAME */
  638. new_localvar(ls, str_checkname(ls));
  639. nparams++;
  640. break;
  641. }
  642. case TK_DOTS: { /* param -> `...' */
  643. luaX_next(ls);
  644. f->is_vararg = 1;
  645. break;
  646. }
  647. default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
  648. }
  649. } while (!f->is_vararg && testnext(ls, ','));
  650. }
  651. adjustlocalvars(ls, nparams);
  652. f->numparams = cast_byte(fs->nactvar);
  653. luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
  654. }
  655. static void body (LexState *ls, expdesc *e, int ismethod, int line) {
  656. /* body -> `(' parlist `)' block END */
  657. FuncState new_fs;
  658. BlockCnt bl;
  659. open_func(ls, &new_fs, &bl);
  660. new_fs.f->linedefined = line;
  661. checknext(ls, '(');
  662. if (ismethod) {
  663. new_localvarliteral(ls, "self"); /* create 'self' parameter */
  664. adjustlocalvars(ls, 1);
  665. }
  666. parlist(ls);
  667. checknext(ls, ')');
  668. statlist(ls);
  669. new_fs.f->lastlinedefined = ls->linenumber;
  670. check_match(ls, TK_END, TK_FUNCTION, line);
  671. codeclosure(ls, new_fs.f, e);
  672. close_func(ls);
  673. }
  674. static int explist1 (LexState *ls, expdesc *v) {
  675. /* explist1 -> expr { `,' expr } */
  676. int n = 1; /* at least one expression */
  677. expr(ls, v);
  678. while (testnext(ls, ',')) {
  679. luaK_exp2nextreg(ls->fs, v);
  680. expr(ls, v);
  681. n++;
  682. }
  683. return n;
  684. }
  685. static void funcargs (LexState *ls, expdesc *f, int line) {
  686. FuncState *fs = ls->fs;
  687. expdesc args;
  688. int base, nparams;
  689. switch (ls->t.token) {
  690. case '(': { /* funcargs -> `(' [ explist1 ] `)' */
  691. luaX_next(ls);
  692. if (ls->t.token == ')') /* arg list is empty? */
  693. args.k = VVOID;
  694. else {
  695. explist1(ls, &args);
  696. luaK_setmultret(fs, &args);
  697. }
  698. check_match(ls, ')', '(', line);
  699. break;
  700. }
  701. case '{': { /* funcargs -> constructor */
  702. constructor(ls, &args);
  703. break;
  704. }
  705. case TK_STRING: { /* funcargs -> STRING */
  706. codestring(ls, &args, ls->t.seminfo.ts);
  707. luaX_next(ls); /* must use `seminfo' before `next' */
  708. break;
  709. }
  710. default: {
  711. luaX_syntaxerror(ls, "function arguments expected");
  712. return;
  713. }
  714. }
  715. lua_assert(f->k == VNONRELOC);
  716. base = f->u.info; /* base register for call */
  717. if (hasmultret(args.k))
  718. nparams = LUA_MULTRET; /* open call */
  719. else {
  720. if (args.k != VVOID)
  721. luaK_exp2nextreg(fs, &args); /* close last argument */
  722. nparams = fs->freereg - (base+1);
  723. }
  724. init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
  725. luaK_fixline(fs, line);
  726. fs->freereg = base+1; /* call remove function and arguments and leaves
  727. (unless changed) one result */
  728. }
  729. /*
  730. ** {======================================================================
  731. ** Expression parsing
  732. ** =======================================================================
  733. */
  734. static void prefixexp (LexState *ls, expdesc *v) {
  735. /* prefixexp -> NAME | '(' expr ')' */
  736. switch (ls->t.token) {
  737. case '(': {
  738. int line = ls->linenumber;
  739. luaX_next(ls);
  740. expr(ls, v);
  741. check_match(ls, ')', '(', line);
  742. luaK_dischargevars(ls->fs, v);
  743. return;
  744. }
  745. case TK_NAME: {
  746. singlevar(ls, v);
  747. return;
  748. }
  749. default: {
  750. luaX_syntaxerror(ls, "unexpected symbol");
  751. return;
  752. }
  753. }
  754. }
  755. static void primaryexp (LexState *ls, expdesc *v) {
  756. /* primaryexp ->
  757. prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
  758. FuncState *fs = ls->fs;
  759. int line = ls->linenumber;
  760. prefixexp(ls, v);
  761. for (;;) {
  762. switch (ls->t.token) {
  763. case '.': { /* fieldsel */
  764. fieldsel(ls, v);
  765. break;
  766. }
  767. case '[': { /* `[' exp1 `]' */
  768. expdesc key;
  769. luaK_exp2anyregup(fs, v);
  770. yindex(ls, &key);
  771. luaK_indexed(fs, v, &key);
  772. break;
  773. }
  774. case ':': { /* `:' NAME funcargs */
  775. expdesc key;
  776. luaX_next(ls);
  777. checkname(ls, &key);
  778. luaK_self(fs, v, &key);
  779. funcargs(ls, v, line);
  780. break;
  781. }
  782. case '(': case TK_STRING: case '{': { /* funcargs */
  783. luaK_exp2nextreg(fs, v);
  784. funcargs(ls, v, line);
  785. break;
  786. }
  787. default: return;
  788. }
  789. }
  790. }
  791. static void simpleexp (LexState *ls, expdesc *v) {
  792. /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
  793. constructor | FUNCTION body | primaryexp */
  794. switch (ls->t.token) {
  795. case TK_NUMBER: {
  796. init_exp(v, VKNUM, 0);
  797. v->u.nval = ls->t.seminfo.r;
  798. break;
  799. }
  800. case TK_STRING: {
  801. codestring(ls, v, ls->t.seminfo.ts);
  802. break;
  803. }
  804. case TK_NIL: {
  805. init_exp(v, VNIL, 0);
  806. break;
  807. }
  808. case TK_TRUE: {
  809. init_exp(v, VTRUE, 0);
  810. break;
  811. }
  812. case TK_FALSE: {
  813. init_exp(v, VFALSE, 0);
  814. break;
  815. }
  816. case TK_DOTS: { /* vararg */
  817. FuncState *fs = ls->fs;
  818. check_condition(ls, fs->f->is_vararg,
  819. "cannot use " LUA_QL("...") " outside a vararg function");
  820. init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
  821. break;
  822. }
  823. case '{': { /* constructor */
  824. constructor(ls, v);
  825. return;
  826. }
  827. case TK_FUNCTION: {
  828. luaX_next(ls);
  829. body(ls, v, 0, ls->linenumber);
  830. return;
  831. }
  832. default: {
  833. primaryexp(ls, v);
  834. return;
  835. }
  836. }
  837. luaX_next(ls);
  838. }
  839. static UnOpr getunopr (int op) {
  840. switch (op) {
  841. case TK_NOT: return OPR_NOT;
  842. case '-': return OPR_MINUS;
  843. case '#': return OPR_LEN;
  844. default: return OPR_NOUNOPR;
  845. }
  846. }
  847. static BinOpr getbinopr (int op) {
  848. switch (op) {
  849. case '+': return OPR_ADD;
  850. case '-': return OPR_SUB;
  851. case '*': return OPR_MUL;
  852. case '/': return OPR_DIV;
  853. case '%': return OPR_MOD;
  854. case '^': return OPR_POW;
  855. case TK_CONCAT: return OPR_CONCAT;
  856. case TK_NE: return OPR_NE;
  857. case TK_EQ: return OPR_EQ;
  858. case '<': return OPR_LT;
  859. case TK_LE: return OPR_LE;
  860. case '>': return OPR_GT;
  861. case TK_GE: return OPR_GE;
  862. case TK_AND: return OPR_AND;
  863. case TK_OR: return OPR_OR;
  864. default: return OPR_NOBINOPR;
  865. }
  866. }
  867. static const struct {
  868. lu_byte left; /* left priority for each binary operator */
  869. lu_byte right; /* right priority */
  870. } priority[] = { /* ORDER OPR */
  871. {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `*' `/' `%' */
  872. {10, 9}, {5, 4}, /* ^, .. (right associative) */
  873. {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
  874. {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
  875. {2, 2}, {1, 1} /* and, or */
  876. };
  877. #define UNARY_PRIORITY 8 /* priority for unary operators */
  878. /*
  879. ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
  880. ** where `binop' is any binary operator with a priority higher than `limit'
  881. */
  882. static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) {
  883. BinOpr op;
  884. UnOpr uop;
  885. enterlevel(ls);
  886. uop = getunopr(ls->t.token);
  887. if (uop != OPR_NOUNOPR) {
  888. int line = ls->linenumber;
  889. luaX_next(ls);
  890. subexpr(ls, v, UNARY_PRIORITY);
  891. luaK_prefix(ls->fs, uop, v, line);
  892. }
  893. else simpleexp(ls, v);
  894. /* expand while operators have priorities higher than `limit' */
  895. op = getbinopr(ls->t.token);
  896. while (op != OPR_NOBINOPR && priority[op].left > limit) {
  897. expdesc v2;
  898. BinOpr nextop;
  899. int line = ls->linenumber;
  900. luaX_next(ls);
  901. luaK_infix(ls->fs, op, v);
  902. /* read sub-expression with higher priority */
  903. nextop = subexpr(ls, &v2, priority[op].right);
  904. luaK_posfix(ls->fs, op, v, &v2, line);
  905. op = nextop;
  906. }
  907. leavelevel(ls);
  908. return op; /* return first untreated operator */
  909. }
  910. static void expr (LexState *ls, expdesc *v) {
  911. subexpr(ls, v, 0);
  912. }
  913. /* }==================================================================== */
  914. /*
  915. ** {======================================================================
  916. ** Rules for Statements
  917. ** =======================================================================
  918. */
  919. /*
  920. ** check whether current token is in the follow set of a block.
  921. ** 'until' closes syntactical blocks, but do not close scope,
  922. ** so it handled in separate.
  923. */
  924. static int block_follow (LexState *ls, int withuntil) {
  925. switch (ls->t.token) {
  926. case TK_ELSE: case TK_ELSEIF:
  927. case TK_END: case TK_EOS:
  928. return 1;
  929. case TK_UNTIL: return withuntil;
  930. default: return 0;
  931. }
  932. }
  933. static void block (LexState *ls) {
  934. /* block -> statlist */
  935. FuncState *fs = ls->fs;
  936. BlockCnt bl;
  937. enterblock(fs, &bl, 0);
  938. statlist(ls);
  939. leaveblock(fs);
  940. }
  941. /*
  942. ** structure to chain all variables in the left-hand side of an
  943. ** assignment
  944. */
  945. struct LHS_assign {
  946. struct LHS_assign *prev;
  947. expdesc v; /* variable (global, local, upvalue, or indexed) */
  948. };
  949. /*
  950. ** check whether, in an assignment to a local variable, the local variable
  951. ** is needed in a previous assignment (to a table). If so, save original
  952. ** local value in a safe place and use this safe copy in the previous
  953. ** assignment.
  954. */
  955. static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
  956. FuncState *fs = ls->fs;
  957. int extra = fs->freereg; /* eventual position to save local variable */
  958. int conflict = 0;
  959. for (; lh; lh = lh->prev) {
  960. /* conflict in table 't'? */
  961. if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {
  962. conflict = 1;
  963. lh->v.u.ind.vt = VLOCAL;
  964. lh->v.u.ind.t = extra; /* previous assignment will use safe copy */
  965. }
  966. /* conflict in index 'idx'? */
  967. if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {
  968. conflict = 1;
  969. lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
  970. }
  971. }
  972. if (conflict) {
  973. OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
  974. luaK_codeABC(fs, op, fs->freereg, v->u.info, 0); /* make copy */
  975. luaK_reserveregs(fs, 1);
  976. }
  977. }
  978. static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
  979. expdesc e;
  980. check_condition(ls, vkisvar(lh->v.k), "syntax error");
  981. if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */
  982. struct LHS_assign nv;
  983. nv.prev = lh;
  984. primaryexp(ls, &nv.v);
  985. if (nv.v.k != VINDEXED)
  986. check_conflict(ls, lh, &nv.v);
  987. checklimit(ls->fs, nvars, LUAI_MAXCCALLS - G(ls->L)->nCcalls,
  988. "variable names");
  989. assignment(ls, &nv, nvars+1);
  990. }
  991. else { /* assignment -> `=' explist1 */
  992. int nexps;
  993. checknext(ls, '=');
  994. nexps = explist1(ls, &e);
  995. if (nexps != nvars) {
  996. adjust_assign(ls, nvars, nexps, &e);
  997. if (nexps > nvars)
  998. ls->fs->freereg -= nexps - nvars; /* remove extra values */
  999. }
  1000. else {
  1001. luaK_setoneret(ls->fs, &e); /* close last expression */
  1002. luaK_storevar(ls->fs, &lh->v, &e);
  1003. return; /* avoid default */
  1004. }
  1005. }
  1006. init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
  1007. luaK_storevar(ls->fs, &lh->v, &e);
  1008. }
  1009. static int cond (LexState *ls) {
  1010. /* cond -> exp */
  1011. expdesc v;
  1012. expr(ls, &v); /* read condition */
  1013. if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */
  1014. luaK_goiftrue(ls->fs, &v);
  1015. return v.f;
  1016. }
  1017. static void gotostat (LexState *ls, TString *label, int line) {
  1018. /* create new entry for this goto */
  1019. int g = newlabelentry(ls, &ls->dyd->gt, label, line, luaK_jump(ls->fs));
  1020. findlabel(ls, g);
  1021. }
  1022. static void labelstat (LexState *ls, TString *label) {
  1023. /* label -> '@' NAME ':' */
  1024. FuncState *fs = ls->fs;
  1025. int l; /* index of new label being created */
  1026. Labeldesc *lb;
  1027. checknext(ls, ':');
  1028. /* create new entry for this label */
  1029. l = newlabelentry(ls, &ls->dyd->label, label, 0, fs->pc);
  1030. lb = &ls->dyd->label.arr[l];
  1031. while (testnext(ls, ';')) ; /* skip trailing semicolons */
  1032. if (block_follow(ls, 0)) { /* label is last statement in the block? */
  1033. /* assume that locals are already out of scope */
  1034. lb->nactvar = fs->bl->nactvar;
  1035. }
  1036. findgotos(ls, lb);
  1037. }
  1038. static void whilestat (LexState *ls, int line) {
  1039. /* whilestat -> WHILE cond DO block END */
  1040. FuncState *fs = ls->fs;
  1041. int whileinit;
  1042. int condexit;
  1043. BlockCnt bl;
  1044. luaX_next(ls); /* skip WHILE */
  1045. whileinit = luaK_getlabel(fs);
  1046. condexit = cond(ls);
  1047. enterblock(fs, &bl, 1);
  1048. checknext(ls, TK_DO);
  1049. block(ls);
  1050. luaK_jumpto(fs, whileinit);
  1051. check_match(ls, TK_END, TK_WHILE, line);
  1052. leaveblock(fs);
  1053. luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
  1054. }
  1055. static void repeatstat (LexState *ls, int line) {
  1056. /* repeatstat -> REPEAT block UNTIL cond */
  1057. int condexit;
  1058. FuncState *fs = ls->fs;
  1059. int repeat_init = luaK_getlabel(fs);
  1060. BlockCnt bl1, bl2;
  1061. enterblock(fs, &bl1, 1); /* loop block */
  1062. enterblock(fs, &bl2, 0); /* scope block */
  1063. luaX_next(ls); /* skip REPEAT */
  1064. statlist(ls);
  1065. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  1066. condexit = cond(ls); /* read condition (inside scope block) */
  1067. if (bl2.upval) /* upvalues? */
  1068. luaK_patchclose(fs, condexit, bl2.nactvar);
  1069. leaveblock(fs); /* finish scope */
  1070. luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
  1071. leaveblock(fs); /* finish loop */
  1072. }
  1073. static int exp1 (LexState *ls) {
  1074. expdesc e;
  1075. int reg;
  1076. expr(ls, &e);
  1077. luaK_exp2nextreg(ls->fs, &e);
  1078. lua_assert(e.k == VNONRELOC);
  1079. reg = e.u.info;
  1080. return reg;
  1081. }
  1082. static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
  1083. /* forbody -> DO block */
  1084. BlockCnt bl;
  1085. FuncState *fs = ls->fs;
  1086. int prep, endfor;
  1087. adjustlocalvars(ls, 3); /* control variables */
  1088. checknext(ls, TK_DO);
  1089. prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
  1090. enterblock(fs, &bl, 0); /* scope for declared variables */
  1091. adjustlocalvars(ls, nvars);
  1092. luaK_reserveregs(fs, nvars);
  1093. block(ls);
  1094. leaveblock(fs); /* end of scope for declared variables */
  1095. luaK_patchtohere(fs, prep);
  1096. if (isnum) /* numeric for? */
  1097. endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
  1098. else { /* generic for */
  1099. luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
  1100. luaK_fixline(fs, line);
  1101. endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
  1102. }
  1103. luaK_patchlist(fs, endfor, prep + 1);
  1104. luaK_fixline(fs, line);
  1105. }
  1106. static void fornum (LexState *ls, TString *varname, int line) {
  1107. /* fornum -> NAME = exp1,exp1[,exp1] forbody */
  1108. FuncState *fs = ls->fs;
  1109. int base = fs->freereg;
  1110. new_localvarliteral(ls, "(for index)");
  1111. new_localvarliteral(ls, "(for limit)");
  1112. new_localvarliteral(ls, "(for step)");
  1113. new_localvar(ls, varname);
  1114. checknext(ls, '=');
  1115. exp1(ls); /* initial value */
  1116. checknext(ls, ',');
  1117. exp1(ls); /* limit */
  1118. if (testnext(ls, ','))
  1119. exp1(ls); /* optional step */
  1120. else { /* default step = 1 */
  1121. luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1));
  1122. luaK_reserveregs(fs, 1);
  1123. }
  1124. forbody(ls, base, line, 1, 1);
  1125. }
  1126. static void forlist (LexState *ls, TString *indexname) {
  1127. /* forlist -> NAME {,NAME} IN explist1 forbody */
  1128. FuncState *fs = ls->fs;
  1129. expdesc e;
  1130. int nvars = 4; /* gen, state, control, plus at least one declared var */
  1131. int line;
  1132. int base = fs->freereg;
  1133. /* create control variables */
  1134. new_localvarliteral(ls, "(for generator)");
  1135. new_localvarliteral(ls, "(for state)");
  1136. new_localvarliteral(ls, "(for control)");
  1137. /* create declared variables */
  1138. new_localvar(ls, indexname);
  1139. while (testnext(ls, ',')) {
  1140. new_localvar(ls, str_checkname(ls));
  1141. nvars++;
  1142. }
  1143. checknext(ls, TK_IN);
  1144. line = ls->linenumber;
  1145. adjust_assign(ls, 3, explist1(ls, &e), &e);
  1146. luaK_checkstack(fs, 3); /* extra space to call generator */
  1147. forbody(ls, base, line, nvars - 3, 0);
  1148. }
  1149. static void forstat (LexState *ls, int line) {
  1150. /* forstat -> FOR (fornum | forlist) END */
  1151. FuncState *fs = ls->fs;
  1152. TString *varname;
  1153. BlockCnt bl;
  1154. enterblock(fs, &bl, 1); /* scope for loop and control variables */
  1155. luaX_next(ls); /* skip `for' */
  1156. varname = str_checkname(ls); /* first variable name */
  1157. switch (ls->t.token) {
  1158. case '=': fornum(ls, varname, line); break;
  1159. case ',': case TK_IN: forlist(ls, varname); break;
  1160. default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
  1161. }
  1162. check_match(ls, TK_END, TK_FOR, line);
  1163. leaveblock(fs); /* loop scope (`break' jumps to this point) */
  1164. }
  1165. static int test_then_block (LexState *ls) {
  1166. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  1167. int condexit;
  1168. luaX_next(ls); /* skip IF or ELSEIF */
  1169. condexit = cond(ls);
  1170. checknext(ls, TK_THEN);
  1171. block(ls); /* `then' part */
  1172. return condexit;
  1173. }
  1174. static void ifstat (LexState *ls, int line) {
  1175. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  1176. FuncState *fs = ls->fs;
  1177. int flist;
  1178. int escapelist = NO_JUMP;
  1179. flist = test_then_block(ls); /* IF cond THEN block */
  1180. while (ls->t.token == TK_ELSEIF) {
  1181. luaK_concat(fs, &escapelist, luaK_jump(fs));
  1182. luaK_patchtohere(fs, flist);
  1183. flist = test_then_block(ls); /* ELSEIF cond THEN block */
  1184. }
  1185. if (ls->t.token == TK_ELSE) {
  1186. luaK_concat(fs, &escapelist, luaK_jump(fs));
  1187. luaK_patchtohere(fs, flist);
  1188. luaX_next(ls); /* skip ELSE (after patch, for correct line info) */
  1189. block(ls); /* `else' part */
  1190. }
  1191. else
  1192. luaK_concat(fs, &escapelist, flist);
  1193. luaK_patchtohere(fs, escapelist);
  1194. check_match(ls, TK_END, TK_IF, line);
  1195. }
  1196. static void localfunc (LexState *ls) {
  1197. expdesc b;
  1198. new_localvar(ls, str_checkname(ls)); /* new local variable */
  1199. adjustlocalvars(ls, 1); /* enter its scope */
  1200. body(ls, &b, 0, ls->linenumber); /* function created in next register */
  1201. }
  1202. static void localstat (LexState *ls) {
  1203. /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
  1204. int nvars = 0;
  1205. int nexps;
  1206. expdesc e;
  1207. do {
  1208. new_localvar(ls, str_checkname(ls));
  1209. nvars++;
  1210. } while (testnext(ls, ','));
  1211. if (testnext(ls, '='))
  1212. nexps = explist1(ls, &e);
  1213. else {
  1214. e.k = VVOID;
  1215. nexps = 0;
  1216. }
  1217. adjust_assign(ls, nvars, nexps, &e);
  1218. adjustlocalvars(ls, nvars);
  1219. }
  1220. static int funcname (LexState *ls, expdesc *v) {
  1221. /* funcname -> NAME {fieldsel} [`:' NAME] */
  1222. int ismethod = 0;
  1223. singlevar(ls, v);
  1224. while (ls->t.token == '.')
  1225. fieldsel(ls, v);
  1226. if (ls->t.token == ':') {
  1227. ismethod = 1;
  1228. fieldsel(ls, v);
  1229. }
  1230. return ismethod;
  1231. }
  1232. static void funcstat (LexState *ls, int line) {
  1233. /* funcstat -> FUNCTION funcname body */
  1234. int ismethod;
  1235. expdesc v, b;
  1236. luaX_next(ls); /* skip FUNCTION */
  1237. ismethod = funcname(ls, &v);
  1238. body(ls, &b, ismethod, line);
  1239. luaK_storevar(ls->fs, &v, &b);
  1240. luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
  1241. }
  1242. static void exprstat (LexState *ls) {
  1243. /* stat -> func | assignment */
  1244. FuncState *fs = ls->fs;
  1245. struct LHS_assign v;
  1246. primaryexp(ls, &v.v);
  1247. if (v.v.k == VCALL) /* stat -> func */
  1248. SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
  1249. else { /* stat -> assignment */
  1250. v.prev = NULL;
  1251. assignment(ls, &v, 1);
  1252. }
  1253. }
  1254. static void retstat (LexState *ls) {
  1255. /* stat -> RETURN explist */
  1256. FuncState *fs = ls->fs;
  1257. expdesc e;
  1258. int first, nret; /* registers with returned values */
  1259. if (block_follow(ls, 1) || ls->t.token == ';')
  1260. first = nret = 0; /* return no values */
  1261. else {
  1262. nret = explist1(ls, &e); /* optional return values */
  1263. if (hasmultret(e.k)) {
  1264. luaK_setmultret(fs, &e);
  1265. if (e.k == VCALL && nret == 1) { /* tail call? */
  1266. SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
  1267. lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
  1268. }
  1269. first = fs->nactvar;
  1270. nret = LUA_MULTRET; /* return all values */
  1271. }
  1272. else {
  1273. if (nret == 1) /* only one single value? */
  1274. first = luaK_exp2anyreg(fs, &e);
  1275. else {
  1276. luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
  1277. first = fs->nactvar; /* return all `active' values */
  1278. lua_assert(nret == fs->freereg - first);
  1279. }
  1280. }
  1281. }
  1282. luaK_ret(fs, first, nret);
  1283. }
  1284. static int statement (LexState *ls) {
  1285. int line = ls->linenumber; /* may be needed for error messages */
  1286. switch (ls->t.token) {
  1287. case ';': { /* stat -> ';' (empty statement) */
  1288. luaX_next(ls); /* skip ';' */
  1289. return 0;
  1290. }
  1291. case TK_IF: { /* stat -> ifstat */
  1292. ifstat(ls, line);
  1293. return 0;
  1294. }
  1295. case TK_WHILE: { /* stat -> whilestat */
  1296. whilestat(ls, line);
  1297. return 0;
  1298. }
  1299. case TK_DO: { /* stat -> DO block END */
  1300. luaX_next(ls); /* skip DO */
  1301. block(ls);
  1302. check_match(ls, TK_END, TK_DO, line);
  1303. return 0;
  1304. }
  1305. case TK_FOR: { /* stat -> forstat */
  1306. forstat(ls, line);
  1307. return 0;
  1308. }
  1309. case TK_REPEAT: { /* stat -> repeatstat */
  1310. repeatstat(ls, line);
  1311. return 0;
  1312. }
  1313. case TK_FUNCTION: { /* stat -> funcstat */
  1314. funcstat(ls, line);
  1315. return 0;
  1316. }
  1317. case TK_LOCAL: { /* stat -> localstat */
  1318. luaX_next(ls); /* skip LOCAL */
  1319. if (testnext(ls, TK_FUNCTION)) /* local function? */
  1320. localfunc(ls);
  1321. else
  1322. localstat(ls);
  1323. return 0;
  1324. }
  1325. case '@': { /* stat -> label */
  1326. luaX_next(ls); /* skip '@' */
  1327. labelstat(ls, str_checkname(ls));
  1328. return 0;
  1329. }
  1330. case TK_RETURN: { /* stat -> retstat */
  1331. luaX_next(ls); /* skip RETURN */
  1332. retstat(ls);
  1333. return 1; /* must be last statement */
  1334. }
  1335. case TK_BREAK: { /* stat -> breakstat */
  1336. luaX_next(ls); /* skip BREAK */
  1337. /* code it as "goto 'break'" */
  1338. gotostat(ls, luaS_new(ls->L, "break"), line);
  1339. return 1; /* must be last statement */
  1340. }
  1341. case TK_GOTO: { /* stat -> 'goto' NAME */
  1342. luaX_next(ls); /* skip GOTO */
  1343. gotostat(ls, str_checkname(ls), line);
  1344. return 0;
  1345. }
  1346. default: { /* stat -> func | assignment */
  1347. exprstat(ls);
  1348. return 0;
  1349. }
  1350. }
  1351. }
  1352. static void statlist (LexState *ls) {
  1353. /* statlist -> { stat [`;'] } */
  1354. int islast = 0;
  1355. enterlevel(ls);
  1356. while (!islast && !block_follow(ls, 1)) {
  1357. islast = statement(ls);
  1358. if (islast)
  1359. testnext(ls, ';');
  1360. lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
  1361. ls->fs->freereg >= ls->fs->nactvar);
  1362. ls->fs->freereg = ls->fs->nactvar; /* free registers */
  1363. }
  1364. leavelevel(ls);
  1365. }
  1366. /* }====================================================================== */