lparser.c 38 KB

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