lparser.c 45 KB

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