9
3

lparser.c 45 KB

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