lparser.c 36 KB

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