lparser.c 40 KB

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