lparser.c 36 KB

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