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