2
0

lparser.c 36 KB

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