lparser.c 31 KB

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