lparser.c 37 KB

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