lparser.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. /*
  2. ** $Id: lparser.c,v 1.160 2001/10/25 19:14:14 roberto Exp $
  3. ** Lua Parser
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include "lua.h"
  9. #include "lcode.h"
  10. #include "ldebug.h"
  11. #include "lfunc.h"
  12. #include "llex.h"
  13. #include "lmem.h"
  14. #include "lobject.h"
  15. #include "lopcodes.h"
  16. #include "lparser.h"
  17. #include "lstate.h"
  18. #include "lstring.h"
  19. /*
  20. ** 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. break;
  368. }
  369. }
  370. lua_assert(f->k == VNONRELOC);
  371. base = f->u.i.info; /* base register for call */
  372. if (args.k == VCALL)
  373. nparams = NO_REG; /* open call */
  374. else {
  375. if (args.k != VVOID)
  376. luaK_exp2nextreg(fs, &args); /* close last argument */
  377. nparams = fs->freereg - (base+1);
  378. }
  379. init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams, 1));
  380. fs->freereg = base+1; /* call remove function and arguments and leaves
  381. (unless changed) one result */
  382. }
  383. /*
  384. ** {======================================================================
  385. ** Rules for Constructors
  386. ** =======================================================================
  387. */
  388. static void recfield (LexState *ls, expdesc *t) {
  389. /* recfield -> (NAME | `['exp1`]') = exp1 */
  390. FuncState *fs = ls->fs;
  391. int reg = ls->fs->freereg;
  392. expdesc key, val;
  393. switch (ls->t.token) {
  394. case TK_NAME: {
  395. checkname(ls, &key);
  396. break;
  397. }
  398. case '[': {
  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 '{': { /* constructor */
  600. constructor(ls, v);
  601. break;
  602. }
  603. case TK_FUNCTION: {
  604. next(ls);
  605. body(ls, v, 0, ls->linenumber);
  606. break;
  607. }
  608. default: {
  609. primaryexp(ls, v);
  610. break;
  611. }
  612. }
  613. }
  614. static UnOpr getunopr (int op) {
  615. switch (op) {
  616. case TK_NOT: return OPR_NOT;
  617. case '-': return OPR_MINUS;
  618. default: return OPR_NOUNOPR;
  619. }
  620. }
  621. static BinOpr getbinopr (int op) {
  622. switch (op) {
  623. case '+': return OPR_ADD;
  624. case '-': return OPR_SUB;
  625. case '*': return OPR_MULT;
  626. case '/': return OPR_DIV;
  627. case '^': return OPR_POW;
  628. case TK_CONCAT: return OPR_CONCAT;
  629. case TK_NE: return OPR_NE;
  630. case TK_EQ: return OPR_EQ;
  631. case '<': return OPR_LT;
  632. case TK_LE: return OPR_LE;
  633. case '>': return OPR_GT;
  634. case TK_GE: return OPR_GE;
  635. case TK_AND: return OPR_AND;
  636. case TK_OR: return OPR_OR;
  637. default: return OPR_NOBINOPR;
  638. }
  639. }
  640. static const struct {
  641. lu_byte left; /* left priority for each binary operator */
  642. lu_byte right; /* right priority */
  643. } priority[] = { /* ORDER OPR */
  644. {5, 5}, {5, 5}, {6, 6}, {6, 6}, /* arithmetic */
  645. {9, 8}, {4, 3}, /* power and concat (right associative) */
  646. {2, 2}, {2, 2}, /* equality */
  647. {2, 2}, {2, 2}, {2, 2}, {2, 2}, /* order */
  648. {1, 1}, {1, 1} /* logical */
  649. };
  650. #define UNARY_PRIORITY 7 /* priority for unary operators */
  651. /*
  652. ** subexpr -> (simplexep | unop subexpr) { binop subexpr }
  653. ** where `binop' is any binary operator with a priority higher than `limit'
  654. */
  655. static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
  656. BinOpr op;
  657. UnOpr uop = getunopr(ls->t.token);
  658. if (uop != OPR_NOUNOPR) {
  659. next(ls);
  660. subexpr(ls, v, UNARY_PRIORITY);
  661. luaK_prefix(ls->fs, uop, v);
  662. }
  663. else simpleexp(ls, v);
  664. /* expand while operators have priorities higher than `limit' */
  665. op = getbinopr(ls->t.token);
  666. while (op != OPR_NOBINOPR && cast(int, priority[op].left) > limit) {
  667. expdesc v2;
  668. BinOpr nextop;
  669. next(ls);
  670. luaK_infix(ls->fs, op, v);
  671. /* read sub-expression with higher priority */
  672. nextop = subexpr(ls, &v2, cast(int, priority[op].right));
  673. luaK_posfix(ls->fs, op, v, &v2);
  674. op = nextop;
  675. }
  676. return op; /* return first untreated operator */
  677. }
  678. static void expr (LexState *ls, expdesc *v) {
  679. subexpr(ls, v, -1);
  680. }
  681. /* }==================================================================== */
  682. /*
  683. ** {======================================================================
  684. ** Rules for Statements
  685. ** =======================================================================
  686. */
  687. static int block_follow (int token) {
  688. switch (token) {
  689. case TK_ELSE: case TK_ELSEIF: case TK_END:
  690. case TK_UNTIL: case TK_EOS:
  691. return 1;
  692. default: return 0;
  693. }
  694. }
  695. static void block (LexState *ls) {
  696. /* block -> chunk */
  697. FuncState *fs = ls->fs;
  698. int nactloc = fs->nactloc;
  699. chunk(ls);
  700. removelocalvars(ls, fs->nactloc - nactloc, 1);
  701. fs->freereg = nactloc; /* free registers used by locals */
  702. }
  703. /*
  704. ** structure to chain all variables in the left-hand side of an
  705. ** assignment
  706. */
  707. struct LHS_assign {
  708. struct LHS_assign *prev;
  709. expdesc v; /* variable (global, local, upvalue, or indexed) */
  710. };
  711. /*
  712. ** check whether, in an assignment to a local variable, the local variable
  713. ** is needed in a previous assignment (to a table). If so, save original
  714. ** local value in a safe place and use this safe copy in the previous
  715. ** assignment.
  716. */
  717. static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
  718. FuncState *fs = ls->fs;
  719. int extra = fs->freereg; /* eventual position to save local variable */
  720. int conflict = 0;
  721. for (; lh; lh = lh->prev) {
  722. if (lh->v.k == VINDEXED) {
  723. if (lh->v.u.i.info == v->u.i.info) { /* conflict? */
  724. conflict = 1;
  725. lh->v.u.i.info = extra; /* previous assignment will use safe copy */
  726. }
  727. if (lh->v.u.i.aux == v->u.i.info) { /* conflict? */
  728. conflict = 1;
  729. lh->v.u.i.aux = extra; /* previous assignment will use safe copy */
  730. }
  731. }
  732. }
  733. if (conflict) {
  734. luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.i.info, 0); /* make copy */
  735. luaK_reserveregs(fs, 1);
  736. }
  737. }
  738. static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
  739. expdesc e;
  740. check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
  741. "syntax error!");
  742. if (ls->t.token == ',') { /* assignment -> `,' primaryexp assignment */
  743. struct LHS_assign nv;
  744. nv.prev = lh;
  745. next(ls);
  746. primaryexp(ls, &nv.v);
  747. if (nv.v.k == VLOCAL)
  748. check_conflict(ls, lh, &nv.v);
  749. assignment(ls, &nv, nvars+1);
  750. }
  751. else { /* assignment -> `=' explist1 */
  752. int nexps;
  753. check(ls, '=');
  754. nexps = explist1(ls, &e);
  755. if (nexps != nvars) {
  756. adjust_assign(ls, nvars, nexps, &e);
  757. if (nexps > nvars)
  758. ls->fs->freereg -= nexps - nvars; /* remove extra values */
  759. }
  760. else {
  761. luaK_storevar(ls->fs, &lh->v, &e);
  762. return; /* avoid default */
  763. }
  764. }
  765. init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
  766. luaK_storevar(ls->fs, &lh->v, &e);
  767. }
  768. static void cond (LexState *ls, expdesc *v) {
  769. /* cond -> exp */
  770. expr(ls, v); /* read condition */
  771. luaK_goiftrue(ls->fs, v);
  772. }
  773. static void whilestat (LexState *ls, int line) {
  774. /* whilestat -> WHILE cond DO block END */
  775. FuncState *fs = ls->fs;
  776. int while_init = luaK_getlabel(fs);
  777. expdesc v;
  778. Breaklabel bl;
  779. enterbreak(fs, &bl);
  780. next(ls);
  781. cond(ls, &v);
  782. check(ls, TK_DO);
  783. block(ls);
  784. luaK_patchlist(fs, luaK_jump(fs), while_init);
  785. luaK_patchlist(fs, v.f, luaK_getlabel(fs));
  786. check_match(ls, TK_END, TK_WHILE, line);
  787. leavebreak(fs, &bl);
  788. }
  789. static void repeatstat (LexState *ls, int line) {
  790. /* repeatstat -> REPEAT block UNTIL cond */
  791. FuncState *fs = ls->fs;
  792. int repeat_init = luaK_getlabel(fs);
  793. expdesc v;
  794. Breaklabel bl;
  795. enterbreak(fs, &bl);
  796. next(ls);
  797. block(ls);
  798. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  799. cond(ls, &v);
  800. luaK_patchlist(fs, v.f, repeat_init);
  801. leavebreak(fs, &bl);
  802. }
  803. static void exp1 (LexState *ls) {
  804. expdesc e;
  805. expr(ls, &e);
  806. luaK_exp2nextreg(ls->fs, &e);
  807. }
  808. static void forbody (LexState *ls, int nvar, OpCode prepfor, OpCode loopfor) {
  809. /* forbody -> DO block END */
  810. FuncState *fs = ls->fs;
  811. int basereg = fs->freereg - nvar;
  812. int prep = luaK_codeAsBc(fs, prepfor, basereg, NO_JUMP);
  813. int blockinit = luaK_getlabel(fs);
  814. check(ls, TK_DO);
  815. adjustlocalvars(ls, nvar); /* scope for control variables */
  816. block(ls);
  817. luaK_patchlist(fs, luaK_codeAsBc(fs, loopfor, basereg, NO_JUMP), blockinit);
  818. luaK_fixfor(fs, prep, luaK_getlabel(fs));
  819. removelocalvars(ls, nvar, 1);
  820. }
  821. static void fornum (LexState *ls, TString *varname) {
  822. /* fornum -> NAME = exp1,exp1[,exp1] forbody */
  823. FuncState *fs = ls->fs;
  824. check(ls, '=');
  825. exp1(ls); /* initial value */
  826. check(ls, ',');
  827. exp1(ls); /* limit */
  828. if (optional(ls, ','))
  829. exp1(ls); /* optional step */
  830. else {
  831. luaK_codeAsBc(fs, OP_LOADINT, fs->freereg, 1); /* default step */
  832. luaK_reserveregs(fs, 1);
  833. }
  834. new_localvar(ls, varname, 0);
  835. new_localvarstr(ls, "(limit)", 1);
  836. new_localvarstr(ls, "(step)", 2);
  837. forbody(ls, 3, OP_FORPREP, OP_FORLOOP);
  838. }
  839. static void forlist (LexState *ls, TString *indexname) {
  840. /* forlist -> NAME,NAME IN exp1 forbody */
  841. TString *valname;
  842. check(ls, ',');
  843. valname = str_checkname(ls);
  844. next(ls); /* skip var name */
  845. check(ls, TK_IN);
  846. exp1(ls); /* table */
  847. new_localvarstr(ls, "(table)", 0);
  848. new_localvarstr(ls, "(index)", 1);
  849. new_localvar(ls, indexname, 2);
  850. new_localvar(ls, valname, 3);
  851. luaK_reserveregs(ls->fs, 3); /* registers for control, index and val */
  852. forbody(ls, 4, OP_TFORPREP, OP_TFORLOOP);
  853. }
  854. static void forstat (LexState *ls, int line) {
  855. /* forstat -> fornum | forlist */
  856. FuncState *fs = ls->fs;
  857. TString *varname;
  858. Breaklabel bl;
  859. enterbreak(fs, &bl);
  860. next(ls); /* skip `for' */
  861. varname = str_checkname(ls); /* first variable name */
  862. next(ls); /* skip var name */
  863. switch (ls->t.token) {
  864. case '=': fornum(ls, varname); break;
  865. case ',': forlist(ls, varname); break;
  866. default: luaK_error(ls, "`=' or `,' expected");
  867. }
  868. check_match(ls, TK_END, TK_FOR, line);
  869. leavebreak(fs, &bl);
  870. }
  871. static void test_then_block (LexState *ls, expdesc *v) {
  872. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  873. next(ls); /* skip IF or ELSEIF */
  874. cond(ls, v);
  875. check(ls, TK_THEN);
  876. block(ls); /* `then' part */
  877. }
  878. static void ifstat (LexState *ls, int line) {
  879. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  880. FuncState *fs = ls->fs;
  881. expdesc v;
  882. int escapelist = NO_JUMP;
  883. test_then_block(ls, &v); /* IF cond THEN block */
  884. while (ls->t.token == TK_ELSEIF) {
  885. luaK_concat(fs, &escapelist, luaK_jump(fs));
  886. luaK_patchlist(fs, v.f, luaK_getlabel(fs));
  887. test_then_block(ls, &v); /* ELSEIF cond THEN block */
  888. }
  889. if (ls->t.token == TK_ELSE) {
  890. luaK_concat(fs, &escapelist, luaK_jump(fs));
  891. luaK_patchlist(fs, v.f, luaK_getlabel(fs));
  892. next(ls); /* skip ELSE */
  893. block(ls); /* `else' part */
  894. }
  895. else
  896. luaK_concat(fs, &escapelist, v.f);
  897. luaK_patchlist(fs, escapelist, luaK_getlabel(fs));
  898. check_match(ls, TK_END, TK_IF, line);
  899. }
  900. static void localstat (LexState *ls) {
  901. /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
  902. int nvars = 0;
  903. int nexps;
  904. expdesc e;
  905. do {
  906. next(ls); /* skip LOCAL or `,' */
  907. new_localvar(ls, str_checkname(ls), nvars++);
  908. next(ls); /* skip var name */
  909. } while (ls->t.token == ',');
  910. if (optional(ls, '='))
  911. nexps = explist1(ls, &e);
  912. else {
  913. e.k = VVOID;
  914. nexps = 0;
  915. }
  916. adjust_assign(ls, nvars, nexps, &e);
  917. adjustlocalvars(ls, nvars);
  918. }
  919. static int funcname (LexState *ls, expdesc *v) {
  920. /* funcname -> NAME {field} [`:' NAME] */
  921. int needself = 0;
  922. singlevar(ls->fs, str_checkname(ls), v, 1);
  923. next(ls); /* skip var name */
  924. while (ls->t.token == '.') {
  925. luaY_field(ls, v);
  926. }
  927. if (ls->t.token == ':') {
  928. needself = 1;
  929. luaY_field(ls, v);
  930. }
  931. return needself;
  932. }
  933. static void funcstat (LexState *ls, int line) {
  934. /* funcstat -> FUNCTION funcname body */
  935. int needself;
  936. expdesc v, b;
  937. next(ls); /* skip FUNCTION */
  938. needself = funcname(ls, &v);
  939. body(ls, &b, needself, line);
  940. luaK_storevar(ls->fs, &v, &b);
  941. }
  942. static void exprstat (LexState *ls) {
  943. /* stat -> func | assignment */
  944. FuncState *fs = ls->fs;
  945. struct LHS_assign v;
  946. primaryexp(ls, &v.v);
  947. if (v.v.k == VCALL) { /* stat -> func */
  948. luaK_setcallreturns(fs, &v.v, 0); /* call statement uses no results */
  949. }
  950. else { /* stat -> assignment */
  951. v.prev = NULL;
  952. assignment(ls, &v, 1);
  953. }
  954. }
  955. static void retstat (LexState *ls) {
  956. /* stat -> RETURN explist */
  957. FuncState *fs = ls->fs;
  958. expdesc e;
  959. int first, nret; /* registers with returned values */
  960. next(ls); /* skip RETURN */
  961. if (block_follow(ls->t.token) || ls->t.token == ';')
  962. first = nret = 0; /* return no values */
  963. else {
  964. explist1(ls, &e); /* optional return values */
  965. if (e.k == VCALL) {
  966. luaK_setcallreturns(fs, &e, LUA_MULTRET);
  967. first = fs->nactloc;
  968. nret = NO_REG; /* return all values */
  969. }
  970. else {
  971. luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
  972. first = fs->nactloc;
  973. nret = fs->freereg - first; /* return all `active' values */
  974. }
  975. }
  976. luaK_codeABC(fs, OP_RETURN, first, nret, 0);
  977. fs->freereg = fs->nactloc; /* removes all temp values */
  978. }
  979. static void breakstat (LexState *ls) {
  980. /* stat -> BREAK [NAME] */
  981. FuncState *fs = ls->fs;
  982. Breaklabel *bl = fs->bl;
  983. if (!bl)
  984. luaK_error(ls, "no loop to break");
  985. next(ls); /* skip BREAK */
  986. closelevel(ls, bl->nactloc);
  987. luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
  988. }
  989. static int statement (LexState *ls) {
  990. int line = ls->linenumber; /* may be needed for error messages */
  991. switch (ls->t.token) {
  992. case TK_IF: { /* stat -> ifstat */
  993. ifstat(ls, line);
  994. return 0;
  995. }
  996. case TK_WHILE: { /* stat -> whilestat */
  997. whilestat(ls, line);
  998. return 0;
  999. }
  1000. case TK_DO: { /* stat -> DO block END */
  1001. next(ls); /* skip DO */
  1002. block(ls);
  1003. check_match(ls, TK_END, TK_DO, line);
  1004. return 0;
  1005. }
  1006. case TK_FOR: { /* stat -> forstat */
  1007. forstat(ls, line);
  1008. return 0;
  1009. }
  1010. case TK_REPEAT: { /* stat -> repeatstat */
  1011. repeatstat(ls, line);
  1012. return 0;
  1013. }
  1014. case TK_FUNCTION: {
  1015. funcstat(ls, line); /* stat -> funcstat */
  1016. return 0;
  1017. }
  1018. case TK_LOCAL: { /* stat -> localstat */
  1019. localstat(ls);
  1020. return 0;
  1021. }
  1022. case TK_RETURN: { /* stat -> retstat */
  1023. retstat(ls);
  1024. return 1; /* must be last statement */
  1025. }
  1026. case TK_BREAK: { /* stat -> breakstat */
  1027. breakstat(ls);
  1028. return 1; /* must be last statement */
  1029. }
  1030. default: {
  1031. exprstat(ls);
  1032. return 0; /* to avoid warnings */
  1033. }
  1034. }
  1035. }
  1036. static void parlist (LexState *ls) {
  1037. /* parlist -> [ param { `,' param } ] */
  1038. int nparams = 0;
  1039. short dots = 0;
  1040. if (ls->t.token != ')') { /* is `parlist' not empty? */
  1041. do {
  1042. switch (ls->t.token) {
  1043. case TK_DOTS: dots = 1; break;
  1044. case TK_NAME: new_localvar(ls, str_checkname(ls), nparams++); break;
  1045. default: luaK_error(ls, "<name> or `...' expected");
  1046. }
  1047. next(ls);
  1048. } while (!dots && optional(ls, ','));
  1049. }
  1050. code_params(ls, nparams, dots);
  1051. }
  1052. static void body (LexState *ls, expdesc *e, int needself, int line) {
  1053. /* body -> `(' parlist `)' chunk END */
  1054. FuncState new_fs;
  1055. open_func(ls, &new_fs);
  1056. new_fs.f->lineDefined = line;
  1057. check(ls, '(');
  1058. if (needself) {
  1059. new_localvarstr(ls, "self", 0);
  1060. adjustlocalvars(ls, 1);
  1061. }
  1062. parlist(ls);
  1063. check(ls, ')');
  1064. chunk(ls);
  1065. check_match(ls, TK_END, TK_FUNCTION, line);
  1066. close_func(ls);
  1067. pushclosure(ls, &new_fs, e);
  1068. }
  1069. /* }====================================================================== */
  1070. static void chunk (LexState *ls) {
  1071. /* chunk -> { stat [`;'] } */
  1072. int islast = 0;
  1073. while (!islast && !block_follow(ls->t.token)) {
  1074. islast = statement(ls);
  1075. optional(ls, ';');
  1076. lua_assert(ls->fs->freereg >= ls->fs->nactloc);
  1077. ls->fs->freereg = ls->fs->nactloc; /* free registers */
  1078. }
  1079. }