lparser.c 36 KB

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