lparser.c 32 KB

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