lparser.c 32 KB

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