lparser.c 32 KB

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