lparser.c 50 KB

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