lparser.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. /*
  2. ** $Id: lparser.c,v 1.1 2001/11/29 22:14:34 rieru Exp rieru $
  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. ** Constructors descriptor:
  21. ** `n' indicates number of elements, and `k' signals whether
  22. ** it is a list constructor (k = 0) or a record constructor (k = 1)
  23. ** or empty (k = `;' or `}')
  24. */
  25. typedef struct Constdesc {
  26. int narray;
  27. int nhash;
  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. char buff[30], t[TOKEN_LEN];
  60. luaX_token2str(token, t);
  61. sprintf(buff, "`%.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 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. char buff[70];
  85. char t_what[TOKEN_LEN], t_who[TOKEN_LEN];
  86. luaX_token2str(what, t_what);
  87. luaX_token2str(who, t_who);
  88. sprintf(buff, "`%.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), "<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, "");
  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, "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 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, "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, "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, "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, "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, 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. "<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, ']');
  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 == ',') {
  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 '(': { /* funcargs -> `(' [ explist1 ] `)' */
  343. int line = ls->linenumber;
  344. if (line != ls->lastline)
  345. luaK_error(ls, "ambiguous syntax (function call x new statement)");
  346. next(ls);
  347. if (ls->t.token == ')') /* 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, ')', '(', line);
  354. break;
  355. }
  356. case '{': { /* 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, "function arguments expected");
  367. return;
  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 '[': {
  399. luaY_index(ls, &key);
  400. break;
  401. }
  402. default: luaK_error(ls, "<name> or `[' expected");
  403. }
  404. check(ls, '=');
  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 != ',') return 0;
  414. next(ls); /* skip the comma */
  415. return (ls->t.token != ';' && ls->t.token != '}');
  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. luaX_checklimit(ls, n, MAX_INT, "items in a constructor");
  423. n++;
  424. } while (anotherfield(ls));
  425. return n;
  426. }
  427. static int listfields (LexState *ls, expdesc *t) {
  428. /* listfields -> exp1 { `,' exp1 } [`,'] */
  429. expdesc v;
  430. FuncState *fs = ls->fs;
  431. int n = 1; /* at least one element */
  432. int reg;
  433. reg = fs->freereg;
  434. expr(ls, &v);
  435. while (anotherfield(ls)) {
  436. luaK_exp2nextreg(fs, &v);
  437. luaX_checklimit(ls, n, MAXARG_Bc, "items in a constructor");
  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 ';': case '}': { /* constructor_part -> empty */
  459. cd->narray = cd->nhash = 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 != '=') /* expression? */
  466. goto case_default;
  467. /* else go through to recfields */
  468. }
  469. case '[': { /* constructor_part -> recfields */
  470. cd->nhash = recfields(ls, t);
  471. cd->narray = 0;
  472. cd->k = 1; /* record */
  473. break;
  474. }
  475. default: { /* constructor_part -> listfields */
  476. case_default:
  477. cd->narray = listfields(ls, t);
  478. cd->nhash = 0;
  479. cd->k = 0; /* list */
  480. break;
  481. }
  482. }
  483. }
  484. static void constructor (LexState *ls, expdesc *t) {
  485. /* constructor -> `{' constructor_part [`;' constructor_part] `}' */
  486. FuncState *fs = ls->fs;
  487. int line = ls->linenumber;
  488. int na, nh;
  489. int pc;
  490. Constdesc cd;
  491. pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  492. init_exp(t, VRELOCABLE, pc);
  493. luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */
  494. check(ls, '{');
  495. constructor_part(ls, t, &cd);
  496. na = cd.narray;
  497. nh = cd.nhash;
  498. if (optional(ls, ';')) {
  499. Constdesc other_cd;
  500. constructor_part(ls, t, &other_cd);
  501. check_condition(ls,(cd.k != other_cd.k), "invalid constructor syntax");
  502. na += other_cd.narray;
  503. nh += other_cd.nhash;
  504. }
  505. check_match(ls, '}', '{', line);
  506. if (na > 0)
  507. SETARG_B(fs->f->code[pc], luaO_log2(na-1)+2); /* set initial table size */
  508. SETARG_C(fs->f->code[pc], luaO_log2(nh)+1); /* set initial table size */
  509. }
  510. /* }====================================================================== */
  511. /*
  512. ** {======================================================================
  513. ** Expression parsing
  514. ** =======================================================================
  515. */
  516. static void prefixexp (LexState *ls, expdesc *v) {
  517. /* prefixexp -> NAME | '(' expr ')' */
  518. switch (ls->t.token) {
  519. case '(': {
  520. next(ls);
  521. expr(ls, v);
  522. check(ls, ')');
  523. luaK_dischargevars(ls->fs, v);
  524. return;
  525. }
  526. case TK_NAME: {
  527. singlevar(ls->fs, str_checkname(ls), v, 1);
  528. next(ls);
  529. return;
  530. }
  531. case '%': { /* for compatibility only */
  532. next(ls); /* skip `%' */
  533. singlevar(ls->fs, str_checkname(ls), v, 1);
  534. check_condition(ls, v->k == VUPVAL, "global upvalues are obsolete");
  535. next(ls);
  536. return;
  537. }
  538. default: {
  539. luaK_error(ls, "unexpected symbol");
  540. return;
  541. }
  542. }
  543. }
  544. static void primaryexp (LexState *ls, expdesc *v) {
  545. /* primaryexp ->
  546. prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
  547. FuncState *fs = ls->fs;
  548. prefixexp(ls, v);
  549. for (;;) {
  550. switch (ls->t.token) {
  551. case '.': { /* field */
  552. luaY_field(ls, v);
  553. break;
  554. }
  555. case '[': { /* `[' exp1 `]' */
  556. expdesc key;
  557. luaK_exp2anyreg(fs, v);
  558. luaY_index(ls, &key);
  559. luaK_indexed(fs, v, &key);
  560. break;
  561. }
  562. case ':': { /* `:' NAME funcargs */
  563. expdesc key;
  564. next(ls);
  565. checkname(ls, &key);
  566. luaK_self(fs, v, &key);
  567. funcargs(ls, v);
  568. break;
  569. }
  570. case '(': case TK_STRING: case '{': { /* funcargs */
  571. luaK_exp2nextreg(fs, v);
  572. funcargs(ls, v);
  573. break;
  574. }
  575. default: return;
  576. }
  577. }
  578. }
  579. static void simpleexp (LexState *ls, expdesc *v) {
  580. /* simpleexp -> NUMBER | STRING | NIL | constructor | FUNCTION body
  581. | primaryexp */
  582. switch (ls->t.token) {
  583. case TK_NUMBER: {
  584. init_exp(v, VNUMBER, 0);
  585. v->u.n = ls->t.seminfo.r;
  586. next(ls); /* must use `seminfo' before `next' */
  587. break;
  588. }
  589. case TK_STRING: {
  590. codestring(ls, v, ls->t.seminfo.ts);
  591. next(ls); /* must use `seminfo' before `next' */
  592. break;
  593. }
  594. case TK_NIL: {
  595. init_exp(v, VNIL, 0);
  596. next(ls);
  597. break;
  598. }
  599. case TK_TRUE: {
  600. init_exp(v, VTRUE, 0);
  601. next(ls);
  602. break;
  603. }
  604. case TK_FALSE: {
  605. init_exp(v, VFALSE, 0);
  606. next(ls);
  607. break;
  608. }
  609. case '{': { /* constructor */
  610. constructor(ls, v);
  611. break;
  612. }
  613. case TK_FUNCTION: {
  614. next(ls);
  615. body(ls, v, 0, ls->linenumber);
  616. break;
  617. }
  618. default: {
  619. primaryexp(ls, v);
  620. break;
  621. }
  622. }
  623. }
  624. static UnOpr getunopr (int op) {
  625. switch (op) {
  626. case TK_NOT: return OPR_NOT;
  627. case '-': return OPR_MINUS;
  628. default: return OPR_NOUNOPR;
  629. }
  630. }
  631. static BinOpr getbinopr (int op) {
  632. switch (op) {
  633. case '+': return OPR_ADD;
  634. case '-': return OPR_SUB;
  635. case '*': return OPR_MULT;
  636. case '/': return OPR_DIV;
  637. case '^': return OPR_POW;
  638. case TK_CONCAT: return OPR_CONCAT;
  639. case TK_NE: return OPR_NE;
  640. case TK_EQ: return OPR_EQ;
  641. case '<': return OPR_LT;
  642. case TK_LE: return OPR_LE;
  643. case '>': return OPR_GT;
  644. case TK_GE: return OPR_GE;
  645. case TK_AND: return OPR_AND;
  646. case TK_OR: return OPR_OR;
  647. default: return OPR_NOBINOPR;
  648. }
  649. }
  650. static const struct {
  651. lu_byte left; /* left priority for each binary operator */
  652. lu_byte right; /* right priority */
  653. } priority[] = { /* ORDER OPR */
  654. {5, 5}, {5, 5}, {6, 6}, {6, 6}, /* arithmetic */
  655. {9, 8}, {4, 3}, /* power and concat (right associative) */
  656. {2, 2}, {2, 2}, /* equality */
  657. {2, 2}, {2, 2}, {2, 2}, {2, 2}, /* order */
  658. {1, 1}, {1, 1} /* logical */
  659. };
  660. #define UNARY_PRIORITY 7 /* priority for unary operators */
  661. /*
  662. ** subexpr -> (simplexep | unop subexpr) { binop subexpr }
  663. ** where `binop' is any binary operator with a priority higher than `limit'
  664. */
  665. static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
  666. BinOpr op;
  667. UnOpr uop = getunopr(ls->t.token);
  668. if (uop != OPR_NOUNOPR) {
  669. next(ls);
  670. subexpr(ls, v, UNARY_PRIORITY);
  671. luaK_prefix(ls->fs, uop, v);
  672. }
  673. else simpleexp(ls, v);
  674. /* expand while operators have priorities higher than `limit' */
  675. op = getbinopr(ls->t.token);
  676. while (op != OPR_NOBINOPR && cast(int, priority[op].left) > limit) {
  677. expdesc v2;
  678. BinOpr nextop;
  679. next(ls);
  680. luaK_infix(ls->fs, op, v);
  681. /* read sub-expression with higher priority */
  682. nextop = subexpr(ls, &v2, cast(int, priority[op].right));
  683. luaK_posfix(ls->fs, op, v, &v2);
  684. op = nextop;
  685. }
  686. return op; /* return first untreated operator */
  687. }
  688. static void expr (LexState *ls, expdesc *v) {
  689. subexpr(ls, v, -1);
  690. }
  691. /* }==================================================================== */
  692. /*
  693. ** {======================================================================
  694. ** Rules for Statements
  695. ** =======================================================================
  696. */
  697. static int block_follow (int token) {
  698. switch (token) {
  699. case TK_ELSE: case TK_ELSEIF: case TK_END:
  700. case TK_UNTIL: case TK_EOS:
  701. return 1;
  702. default: return 0;
  703. }
  704. }
  705. static void block (LexState *ls) {
  706. /* block -> chunk */
  707. FuncState *fs = ls->fs;
  708. int nactloc = fs->nactloc;
  709. chunk(ls);
  710. removelocalvars(ls, fs->nactloc - nactloc, 1);
  711. fs->freereg = nactloc; /* free registers used by locals */
  712. }
  713. /*
  714. ** structure to chain all variables in the left-hand side of an
  715. ** assignment
  716. */
  717. struct LHS_assign {
  718. struct LHS_assign *prev;
  719. expdesc v; /* variable (global, local, upvalue, or indexed) */
  720. };
  721. /*
  722. ** check whether, in an assignment to a local variable, the local variable
  723. ** is needed in a previous assignment (to a table). If so, save original
  724. ** local value in a safe place and use this safe copy in the previous
  725. ** assignment.
  726. */
  727. static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
  728. FuncState *fs = ls->fs;
  729. int extra = fs->freereg; /* eventual position to save local variable */
  730. int conflict = 0;
  731. for (; lh; lh = lh->prev) {
  732. if (lh->v.k == VINDEXED) {
  733. if (lh->v.u.i.info == v->u.i.info) { /* conflict? */
  734. conflict = 1;
  735. lh->v.u.i.info = extra; /* previous assignment will use safe copy */
  736. }
  737. if (lh->v.u.i.aux == v->u.i.info) { /* conflict? */
  738. conflict = 1;
  739. lh->v.u.i.aux = extra; /* previous assignment will use safe copy */
  740. }
  741. }
  742. }
  743. if (conflict) {
  744. luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.i.info, 0); /* make copy */
  745. luaK_reserveregs(fs, 1);
  746. }
  747. }
  748. static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
  749. expdesc e;
  750. check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
  751. "syntax error!");
  752. if (ls->t.token == ',') { /* assignment -> `,' primaryexp assignment */
  753. struct LHS_assign nv;
  754. nv.prev = lh;
  755. next(ls);
  756. primaryexp(ls, &nv.v);
  757. if (nv.v.k == VLOCAL)
  758. check_conflict(ls, lh, &nv.v);
  759. assignment(ls, &nv, nvars+1);
  760. }
  761. else { /* assignment -> `=' explist1 */
  762. int nexps;
  763. check(ls, '=');
  764. nexps = explist1(ls, &e);
  765. if (nexps != nvars) {
  766. adjust_assign(ls, nvars, nexps, &e);
  767. if (nexps > nvars)
  768. ls->fs->freereg -= nexps - nvars; /* remove extra values */
  769. }
  770. else {
  771. luaK_storevar(ls->fs, &lh->v, &e);
  772. return; /* avoid default */
  773. }
  774. }
  775. init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
  776. luaK_storevar(ls->fs, &lh->v, &e);
  777. }
  778. static void cond (LexState *ls, expdesc *v) {
  779. /* cond -> exp */
  780. expr(ls, v); /* read condition */
  781. luaK_goiftrue(ls->fs, v);
  782. }
  783. static void whilestat (LexState *ls, int line) {
  784. /* whilestat -> WHILE cond DO block END */
  785. FuncState *fs = ls->fs;
  786. int while_init = luaK_getlabel(fs);
  787. expdesc v;
  788. Breaklabel bl;
  789. enterbreak(fs, &bl);
  790. next(ls);
  791. cond(ls, &v);
  792. check(ls, TK_DO);
  793. block(ls);
  794. luaK_patchlist(fs, luaK_jump(fs), while_init);
  795. luaK_patchlist(fs, v.f, luaK_getlabel(fs));
  796. check_match(ls, TK_END, TK_WHILE, line);
  797. leavebreak(fs, &bl);
  798. }
  799. static void repeatstat (LexState *ls, int line) {
  800. /* repeatstat -> REPEAT block UNTIL cond */
  801. FuncState *fs = ls->fs;
  802. int repeat_init = luaK_getlabel(fs);
  803. expdesc v;
  804. Breaklabel bl;
  805. enterbreak(fs, &bl);
  806. next(ls);
  807. block(ls);
  808. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  809. cond(ls, &v);
  810. luaK_patchlist(fs, v.f, repeat_init);
  811. leavebreak(fs, &bl);
  812. }
  813. static void exp1 (LexState *ls) {
  814. expdesc e;
  815. expr(ls, &e);
  816. luaK_exp2nextreg(ls->fs, &e);
  817. }
  818. static void forbody (LexState *ls, int nvar, OpCode prepfor, OpCode loopfor) {
  819. /* forbody -> DO block END */
  820. FuncState *fs = ls->fs;
  821. int basereg = fs->freereg - nvar;
  822. int prep = luaK_codeAsBc(fs, prepfor, basereg, NO_JUMP);
  823. int blockinit = luaK_getlabel(fs);
  824. check(ls, TK_DO);
  825. adjustlocalvars(ls, nvar); /* scope for control variables */
  826. block(ls);
  827. luaK_patchlist(fs, luaK_codeAsBc(fs, loopfor, basereg, NO_JUMP), blockinit);
  828. luaK_fixfor(fs, prep, luaK_getlabel(fs));
  829. removelocalvars(ls, nvar, 1);
  830. }
  831. static void fornum (LexState *ls, TString *varname) {
  832. /* fornum -> NAME = exp1,exp1[,exp1] forbody */
  833. FuncState *fs = ls->fs;
  834. check(ls, '=');
  835. exp1(ls); /* initial value */
  836. check(ls, ',');
  837. exp1(ls); /* limit */
  838. if (optional(ls, ','))
  839. exp1(ls); /* optional step */
  840. else {
  841. luaK_codeAsBc(fs, OP_LOADINT, fs->freereg, 1); /* default step */
  842. luaK_reserveregs(fs, 1);
  843. }
  844. new_localvar(ls, varname, 0);
  845. new_localvarstr(ls, "(limit)", 1);
  846. new_localvarstr(ls, "(step)", 2);
  847. forbody(ls, 3, OP_FORPREP, OP_FORLOOP);
  848. }
  849. static void forlist (LexState *ls, TString *indexname) {
  850. /* forlist -> NAME,NAME IN exp1 forbody */
  851. TString *valname;
  852. check(ls, ',');
  853. valname = str_checkname(ls);
  854. next(ls); /* skip var name */
  855. check(ls, TK_IN);
  856. exp1(ls); /* table */
  857. new_localvarstr(ls, "(table)", 0);
  858. new_localvarstr(ls, "(index)", 1);
  859. new_localvar(ls, indexname, 2);
  860. new_localvar(ls, valname, 3);
  861. luaK_reserveregs(ls->fs, 3); /* registers for control, index and val */
  862. forbody(ls, 4, OP_TFORPREP, OP_TFORLOOP);
  863. }
  864. static void forstat (LexState *ls, int line) {
  865. /* forstat -> fornum | forlist */
  866. FuncState *fs = ls->fs;
  867. TString *varname;
  868. Breaklabel bl;
  869. enterbreak(fs, &bl);
  870. next(ls); /* skip `for' */
  871. varname = str_checkname(ls); /* first variable name */
  872. next(ls); /* skip var name */
  873. switch (ls->t.token) {
  874. case '=': fornum(ls, varname); break;
  875. case ',': forlist(ls, varname); break;
  876. default: luaK_error(ls, "`=' or `,' expected");
  877. }
  878. check_match(ls, TK_END, TK_FOR, line);
  879. leavebreak(fs, &bl);
  880. }
  881. static void test_then_block (LexState *ls, expdesc *v) {
  882. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  883. next(ls); /* skip IF or ELSEIF */
  884. cond(ls, v);
  885. check(ls, TK_THEN);
  886. block(ls); /* `then' part */
  887. }
  888. static void ifstat (LexState *ls, int line) {
  889. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  890. FuncState *fs = ls->fs;
  891. expdesc v;
  892. int escapelist = NO_JUMP;
  893. test_then_block(ls, &v); /* IF cond THEN block */
  894. while (ls->t.token == TK_ELSEIF) {
  895. luaK_concat(fs, &escapelist, luaK_jump(fs));
  896. luaK_patchlist(fs, v.f, luaK_getlabel(fs));
  897. test_then_block(ls, &v); /* ELSEIF cond THEN block */
  898. }
  899. if (ls->t.token == TK_ELSE) {
  900. luaK_concat(fs, &escapelist, luaK_jump(fs));
  901. luaK_patchlist(fs, v.f, luaK_getlabel(fs));
  902. next(ls); /* skip ELSE */
  903. block(ls); /* `else' part */
  904. }
  905. else
  906. luaK_concat(fs, &escapelist, v.f);
  907. luaK_patchlist(fs, escapelist, luaK_getlabel(fs));
  908. check_match(ls, TK_END, TK_IF, line);
  909. }
  910. static void localstat (LexState *ls) {
  911. /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
  912. int nvars = 0;
  913. int nexps;
  914. expdesc e;
  915. do {
  916. next(ls); /* skip LOCAL or `,' */
  917. new_localvar(ls, str_checkname(ls), nvars++);
  918. next(ls); /* skip var name */
  919. } while (ls->t.token == ',');
  920. if (optional(ls, '='))
  921. nexps = explist1(ls, &e);
  922. else {
  923. e.k = VVOID;
  924. nexps = 0;
  925. }
  926. adjust_assign(ls, nvars, nexps, &e);
  927. adjustlocalvars(ls, nvars);
  928. }
  929. static int funcname (LexState *ls, expdesc *v) {
  930. /* funcname -> NAME {field} [`:' NAME] */
  931. int needself = 0;
  932. singlevar(ls->fs, str_checkname(ls), v, 1);
  933. next(ls); /* skip var name */
  934. while (ls->t.token == '.') {
  935. luaY_field(ls, v);
  936. }
  937. if (ls->t.token == ':') {
  938. needself = 1;
  939. luaY_field(ls, v);
  940. }
  941. return needself;
  942. }
  943. static void funcstat (LexState *ls, int line) {
  944. /* funcstat -> FUNCTION funcname body */
  945. int needself;
  946. expdesc v, b;
  947. next(ls); /* skip FUNCTION */
  948. needself = funcname(ls, &v);
  949. body(ls, &b, needself, line);
  950. luaK_storevar(ls->fs, &v, &b);
  951. }
  952. static void exprstat (LexState *ls) {
  953. /* stat -> func | assignment */
  954. FuncState *fs = ls->fs;
  955. struct LHS_assign v;
  956. primaryexp(ls, &v.v);
  957. if (v.v.k == VCALL) { /* stat -> func */
  958. luaK_setcallreturns(fs, &v.v, 0); /* call statement uses no results */
  959. }
  960. else { /* stat -> assignment */
  961. v.prev = NULL;
  962. assignment(ls, &v, 1);
  963. }
  964. }
  965. static void retstat (LexState *ls) {
  966. /* stat -> RETURN explist */
  967. FuncState *fs = ls->fs;
  968. expdesc e;
  969. int first, nret; /* registers with returned values */
  970. next(ls); /* skip RETURN */
  971. if (block_follow(ls->t.token) || ls->t.token == ';')
  972. first = nret = 0; /* return no values */
  973. else {
  974. explist1(ls, &e); /* optional return values */
  975. if (e.k == VCALL) {
  976. luaK_setcallreturns(fs, &e, LUA_MULTRET);
  977. first = fs->nactloc;
  978. nret = NO_REG; /* return all values */
  979. }
  980. else {
  981. luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
  982. first = fs->nactloc;
  983. nret = fs->freereg - first; /* return all `active' values */
  984. }
  985. }
  986. luaK_codeABC(fs, OP_RETURN, first, nret, 0);
  987. fs->freereg = fs->nactloc; /* removes all temp values */
  988. }
  989. static void breakstat (LexState *ls) {
  990. /* stat -> BREAK [NAME] */
  991. FuncState *fs = ls->fs;
  992. Breaklabel *bl = fs->bl;
  993. if (!bl)
  994. luaK_error(ls, "no loop to break");
  995. next(ls); /* skip BREAK */
  996. closelevel(ls, bl->nactloc);
  997. luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
  998. }
  999. static int statement (LexState *ls) {
  1000. int line = ls->linenumber; /* may be needed for error messages */
  1001. switch (ls->t.token) {
  1002. case TK_IF: { /* stat -> ifstat */
  1003. ifstat(ls, line);
  1004. return 0;
  1005. }
  1006. case TK_WHILE: { /* stat -> whilestat */
  1007. whilestat(ls, line);
  1008. return 0;
  1009. }
  1010. case TK_DO: { /* stat -> DO block END */
  1011. next(ls); /* skip DO */
  1012. block(ls);
  1013. check_match(ls, TK_END, TK_DO, line);
  1014. return 0;
  1015. }
  1016. case TK_FOR: { /* stat -> forstat */
  1017. forstat(ls, line);
  1018. return 0;
  1019. }
  1020. case TK_REPEAT: { /* stat -> repeatstat */
  1021. repeatstat(ls, line);
  1022. return 0;
  1023. }
  1024. case TK_FUNCTION: {
  1025. funcstat(ls, line); /* stat -> funcstat */
  1026. return 0;
  1027. }
  1028. case TK_LOCAL: { /* stat -> localstat */
  1029. localstat(ls);
  1030. return 0;
  1031. }
  1032. case TK_RETURN: { /* stat -> retstat */
  1033. retstat(ls);
  1034. return 1; /* must be last statement */
  1035. }
  1036. case TK_BREAK: { /* stat -> breakstat */
  1037. breakstat(ls);
  1038. return 1; /* must be last statement */
  1039. }
  1040. default: {
  1041. exprstat(ls);
  1042. return 0; /* to avoid warnings */
  1043. }
  1044. }
  1045. }
  1046. static void parlist (LexState *ls) {
  1047. /* parlist -> [ param { `,' param } ] */
  1048. int nparams = 0;
  1049. short dots = 0;
  1050. if (ls->t.token != ')') { /* is `parlist' not empty? */
  1051. do {
  1052. switch (ls->t.token) {
  1053. case TK_DOTS: dots = 1; break;
  1054. case TK_NAME: new_localvar(ls, str_checkname(ls), nparams++); break;
  1055. default: luaK_error(ls, "<name> or `...' expected");
  1056. }
  1057. next(ls);
  1058. } while (!dots && optional(ls, ','));
  1059. }
  1060. code_params(ls, nparams, dots);
  1061. }
  1062. static void body (LexState *ls, expdesc *e, int needself, int line) {
  1063. /* body -> `(' parlist `)' chunk END */
  1064. FuncState new_fs;
  1065. open_func(ls, &new_fs);
  1066. new_fs.f->lineDefined = line;
  1067. check(ls, '(');
  1068. if (needself) {
  1069. new_localvarstr(ls, "self", 0);
  1070. adjustlocalvars(ls, 1);
  1071. }
  1072. parlist(ls);
  1073. check(ls, ')');
  1074. chunk(ls);
  1075. check_match(ls, TK_END, TK_FUNCTION, line);
  1076. close_func(ls);
  1077. pushclosure(ls, &new_fs, e);
  1078. }
  1079. /* }====================================================================== */
  1080. static void chunk (LexState *ls) {
  1081. /* chunk -> { stat [`;'] } */
  1082. int islast = 0;
  1083. while (!islast && !block_follow(ls->t.token)) {
  1084. islast = statement(ls);
  1085. optional(ls, ';');
  1086. lua_assert(ls->fs->freereg >= ls->fs->nactloc);
  1087. ls->fs->freereg = ls->fs->nactloc; /* free registers */
  1088. }
  1089. }