lparser.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. /*
  2. ** $Id: lparser.c,v 1.1 2001/11/29 22:14:34 rieru Exp rieru $
  3. ** Lua Parser
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include "lua.h"
  9. #include "lcode.h"
  10. #include "ldebug.h"
  11. #include "lfunc.h"
  12. #include "llex.h"
  13. #include "lmem.h"
  14. #include "lobject.h"
  15. #include "lopcodes.h"
  16. #include "lparser.h"
  17. #include "lstate.h"
  18. #include "lstring.h"
  19. /*
  20. ** Constructors descriptor:
  21. ** `n' indicates number of elements, and `k' signals whether
  22. ** it is a list constructor (k = 0) or a record constructor (k = 1)
  23. ** or empty (k = `;' or `}')
  24. */
  25. typedef struct Constdesc {
  26. int narray;
  27. int nhash;
  28. int k;
  29. } Constdesc;
  30. /*
  31. ** nodes for break list (list of active breakable loops)
  32. */
  33. typedef struct Breaklabel {
  34. struct Breaklabel *previous; /* chain */
  35. int breaklist; /* list of jumps out of this loop */
  36. int nactloc; /* # of active local variables outside the breakable structure */
  37. } Breaklabel;
  38. /*
  39. ** prototypes for recursive non-terminal functions
  40. */
  41. static void body (LexState *ls, expdesc *v, int needself, int line);
  42. static void chunk (LexState *ls);
  43. static void constructor (LexState *ls, expdesc *v);
  44. static void expr (LexState *ls, expdesc *v);
  45. static void next (LexState *ls) {
  46. ls->lastline = ls->linenumber;
  47. if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
  48. ls->t = ls->lookahead; /* use this one */
  49. ls->lookahead.token = TK_EOS; /* and discharge it */
  50. }
  51. else
  52. ls->t.token = luaX_lex(ls, &ls->t.seminfo); /* read next token */
  53. }
  54. static void lookahead (LexState *ls) {
  55. lua_assert(ls->lookahead.token == TK_EOS);
  56. ls->lookahead.token = luaX_lex(ls, &ls->lookahead.seminfo);
  57. }
  58. static void error_expected (LexState *ls, int token) {
  59. char buff[30], t[TOKEN_LEN];
  60. luaX_token2str(token, t);
  61. sprintf(buff, "`%.10s' expected", t);
  62. luaK_error(ls, buff);
  63. }
  64. static void check (LexState *ls, int c) {
  65. if (ls->t.token != c)
  66. error_expected(ls, c);
  67. next(ls);
  68. }
  69. static void check_condition (LexState *ls, int c, const char *msg) {
  70. if (!c) luaK_error(ls, msg);
  71. }
  72. static int optional (LexState *ls, int c) {
  73. if (ls->t.token == c) {
  74. next(ls);
  75. return 1;
  76. }
  77. else return 0;
  78. }
  79. static void check_match (LexState *ls, int what, int who, int where) {
  80. if (ls->t.token != what) {
  81. if (where == ls->linenumber)
  82. error_expected(ls, what);
  83. else {
  84. char buff[70];
  85. char t_what[TOKEN_LEN], t_who[TOKEN_LEN];
  86. luaX_token2str(what, t_what);
  87. luaX_token2str(who, t_who);
  88. sprintf(buff, "`%.10s' expected (to close `%.10s' at line %d)",
  89. t_what, t_who, where);
  90. luaK_error(ls, buff);
  91. }
  92. }
  93. next(ls);
  94. }
  95. static TString *str_checkname (LexState *ls) {
  96. check_condition(ls, (ls->t.token == TK_NAME), "<name> expected");
  97. return ls->t.seminfo.ts;
  98. }
  99. static void init_exp (expdesc *e, expkind k, int i) {
  100. e->f = e->t = NO_JUMP;
  101. e->k = k;
  102. e->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].info == v->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->info = luaK_stringK(fs, n); /* info points to global name */
  181. }
  182. else { /* local variable in some upper level? */
  183. var->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, 1, 0); /* final return */
  273. luaK_getlabel(fs); /* close eventual list of pending jumps */
  274. lua_assert(G(L)->roottable == fs->h);
  275. G(L)->roottable = fs->h->next;
  276. luaH_free(L, fs->h);
  277. luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
  278. f->sizecode = fs->pc;
  279. luaM_reallocvector(L, f->k, f->sizek, fs->nk, TObject);
  280. f->sizek = fs->nk;
  281. luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
  282. f->sizep = fs->np;
  283. luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
  284. f->sizelocvars = fs->nlocvars;
  285. luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->nlineinfo+1, int);
  286. f->lineinfo[fs->nlineinfo++] = MAX_INT; /* end flag */
  287. f->sizelineinfo = fs->nlineinfo;
  288. lua_assert(luaG_checkcode(f));
  289. lua_assert(fs->bl == NULL);
  290. ls->fs = fs->prev;
  291. }
  292. Proto *luaY_parser (lua_State *L, ZIO *z) {
  293. struct LexState lexstate;
  294. struct FuncState funcstate;
  295. luaX_setinput(L, &lexstate, z, luaS_new(L, zname(z)));
  296. open_func(&lexstate, &funcstate);
  297. next(&lexstate); /* read first token */
  298. chunk(&lexstate);
  299. check_condition(&lexstate, (lexstate.t.token == TK_EOS),
  300. "<eof> expected");
  301. close_func(&lexstate);
  302. lua_assert(funcstate.prev == NULL);
  303. lua_assert(funcstate.f->nupvalues == 0);
  304. return funcstate.f;
  305. }
  306. /*============================================================*/
  307. /* GRAMMAR RULES */
  308. /*============================================================*/
  309. static void luaY_field (LexState *ls, expdesc *v) {
  310. /* field -> ['.' | ':'] NAME */
  311. FuncState *fs = ls->fs;
  312. expdesc key;
  313. luaK_exp2anyreg(fs, v);
  314. next(ls); /* skip the dot or colon */
  315. checkname(ls, &key);
  316. luaK_indexed(fs, v, &key);
  317. }
  318. static void luaY_index (LexState *ls, expdesc *v) {
  319. /* index -> '[' expr ']' */
  320. next(ls); /* skip the '[' */
  321. expr(ls, v);
  322. luaK_exp2val(ls->fs, v);
  323. check(ls, ']');
  324. }
  325. static int explist1 (LexState *ls, expdesc *v) {
  326. /* explist1 -> expr { `,' expr } */
  327. int n = 1; /* at least one expression */
  328. expr(ls, v);
  329. while (ls->t.token == ',') {
  330. next(ls); /* skip comma */
  331. luaK_exp2nextreg(ls->fs, v);
  332. expr(ls, v);
  333. n++;
  334. }
  335. return n;
  336. }
  337. static void funcargs (LexState *ls, expdesc *f) {
  338. FuncState *fs = ls->fs;
  339. expdesc args;
  340. int base, nparams;
  341. switch (ls->t.token) {
  342. case '(': { /* funcargs -> `(' [ explist1 ] `)' */
  343. int line = ls->linenumber;
  344. if (line != ls->lastline)
  345. luaK_error(ls, "ambiguous syntax (function call x new statement)");
  346. next(ls);
  347. if (ls->t.token == ')') /* arg list is empty? */
  348. args.k = VVOID;
  349. else {
  350. explist1(ls, &args);
  351. luaK_setcallreturns(fs, &args, LUA_MULTRET);
  352. }
  353. check_match(ls, ')', '(', line);
  354. break;
  355. }
  356. case '{': { /* funcargs -> constructor */
  357. constructor(ls, &args);
  358. break;
  359. }
  360. case TK_STRING: { /* funcargs -> STRING */
  361. codestring(ls, &args, ls->t.seminfo.ts);
  362. next(ls); /* must use `seminfo' before `next' */
  363. break;
  364. }
  365. default: {
  366. luaK_error(ls, "function arguments expected");
  367. return;
  368. }
  369. }
  370. lua_assert(f->k == VNONRELOC);
  371. base = f->info; /* base register for call */
  372. if (args.k == VCALL)
  373. nparams = LUA_MULTRET; /* 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, 2));
  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.info, t->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->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->info, n-1);
  448. }
  449. else {
  450. luaK_exp2nextreg(fs, &v);
  451. luaK_codeABc(fs, OP_SETLIST, t->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, VK, luaK_numberK(ls->fs, ls->t.seminfo.r));
  585. next(ls); /* must use `seminfo' before `next' */
  586. break;
  587. }
  588. case TK_STRING: {
  589. codestring(ls, v, ls->t.seminfo.ts);
  590. next(ls); /* must use `seminfo' before `next' */
  591. break;
  592. }
  593. case TK_NIL: {
  594. init_exp(v, VNIL, 0);
  595. next(ls);
  596. break;
  597. }
  598. case TK_TRUE: {
  599. init_exp(v, VTRUE, 0);
  600. next(ls);
  601. break;
  602. }
  603. case TK_FALSE: {
  604. init_exp(v, VFALSE, 0);
  605. next(ls);
  606. break;
  607. }
  608. case '{': { /* constructor */
  609. constructor(ls, v);
  610. break;
  611. }
  612. case TK_FUNCTION: {
  613. next(ls);
  614. body(ls, v, 0, ls->linenumber);
  615. break;
  616. }
  617. default: {
  618. primaryexp(ls, v);
  619. break;
  620. }
  621. }
  622. }
  623. static UnOpr getunopr (int op) {
  624. switch (op) {
  625. case TK_NOT: return OPR_NOT;
  626. case '-': return OPR_MINUS;
  627. default: return OPR_NOUNOPR;
  628. }
  629. }
  630. static BinOpr getbinopr (int op) {
  631. switch (op) {
  632. case '+': return OPR_ADD;
  633. case '-': return OPR_SUB;
  634. case '*': return OPR_MULT;
  635. case '/': return OPR_DIV;
  636. case '^': return OPR_POW;
  637. case TK_CONCAT: return OPR_CONCAT;
  638. case TK_NE: return OPR_NE;
  639. case TK_EQ: return OPR_EQ;
  640. case '<': return OPR_LT;
  641. case TK_LE: return OPR_LE;
  642. case '>': return OPR_GT;
  643. case TK_GE: return OPR_GE;
  644. case TK_AND: return OPR_AND;
  645. case TK_OR: return OPR_OR;
  646. default: return OPR_NOBINOPR;
  647. }
  648. }
  649. static const struct {
  650. lu_byte left; /* left priority for each binary operator */
  651. lu_byte right; /* right priority */
  652. } priority[] = { /* ORDER OPR */
  653. {5, 5}, {5, 5}, {6, 6}, {6, 6}, /* arithmetic */
  654. {9, 8}, {4, 3}, /* power and concat (right associative) */
  655. {2, 2}, {2, 2}, /* equality */
  656. {2, 2}, {2, 2}, {2, 2}, {2, 2}, /* order */
  657. {1, 1}, {1, 1} /* logical */
  658. };
  659. #define UNARY_PRIORITY 7 /* priority for unary operators */
  660. /*
  661. ** subexpr -> (simplexep | unop subexpr) { binop subexpr }
  662. ** where `binop' is any binary operator with a priority higher than `limit'
  663. */
  664. static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
  665. BinOpr op;
  666. UnOpr uop = getunopr(ls->t.token);
  667. if (uop != OPR_NOUNOPR) {
  668. next(ls);
  669. subexpr(ls, v, UNARY_PRIORITY);
  670. luaK_prefix(ls->fs, uop, v);
  671. }
  672. else simpleexp(ls, v);
  673. /* expand while operators have priorities higher than `limit' */
  674. op = getbinopr(ls->t.token);
  675. while (op != OPR_NOBINOPR && cast(int, priority[op].left) > limit) {
  676. expdesc v2;
  677. BinOpr nextop;
  678. next(ls);
  679. luaK_infix(ls->fs, op, v);
  680. /* read sub-expression with higher priority */
  681. nextop = subexpr(ls, &v2, cast(int, priority[op].right));
  682. luaK_posfix(ls->fs, op, v, &v2);
  683. op = nextop;
  684. }
  685. return op; /* return first untreated operator */
  686. }
  687. static void expr (LexState *ls, expdesc *v) {
  688. subexpr(ls, v, -1);
  689. }
  690. /* }==================================================================== */
  691. /*
  692. ** {======================================================================
  693. ** Rules for Statements
  694. ** =======================================================================
  695. */
  696. static int block_follow (int token) {
  697. switch (token) {
  698. case TK_ELSE: case TK_ELSEIF: case TK_END:
  699. case TK_UNTIL: case TK_EOS:
  700. return 1;
  701. default: return 0;
  702. }
  703. }
  704. static void block (LexState *ls) {
  705. /* block -> chunk */
  706. FuncState *fs = ls->fs;
  707. int nactloc = fs->nactloc;
  708. chunk(ls);
  709. removelocalvars(ls, fs->nactloc - nactloc, 1);
  710. fs->freereg = nactloc; /* free registers used by locals */
  711. }
  712. /*
  713. ** structure to chain all variables in the left-hand side of an
  714. ** assignment
  715. */
  716. struct LHS_assign {
  717. struct LHS_assign *prev;
  718. expdesc v; /* variable (global, local, upvalue, or indexed) */
  719. };
  720. /*
  721. ** check whether, in an assignment to a local variable, the local variable
  722. ** is needed in a previous assignment (to a table). If so, save original
  723. ** local value in a safe place and use this safe copy in the previous
  724. ** assignment.
  725. */
  726. static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
  727. FuncState *fs = ls->fs;
  728. int extra = fs->freereg; /* eventual position to save local variable */
  729. int conflict = 0;
  730. for (; lh; lh = lh->prev) {
  731. if (lh->v.k == VINDEXED) {
  732. if (lh->v.info == v->info) { /* conflict? */
  733. conflict = 1;
  734. lh->v.info = extra; /* previous assignment will use safe copy */
  735. }
  736. if (lh->v.aux == v->info) { /* conflict? */
  737. conflict = 1;
  738. lh->v.aux = extra; /* previous assignment will use safe copy */
  739. }
  740. }
  741. }
  742. if (conflict) {
  743. luaK_codeABC(fs, OP_MOVE, fs->freereg, v->info, 0); /* make copy */
  744. luaK_reserveregs(fs, 1);
  745. }
  746. }
  747. static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
  748. expdesc e;
  749. check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
  750. "syntax error!");
  751. if (ls->t.token == ',') { /* assignment -> `,' primaryexp assignment */
  752. struct LHS_assign nv;
  753. nv.prev = lh;
  754. next(ls);
  755. primaryexp(ls, &nv.v);
  756. if (nv.v.k == VLOCAL)
  757. check_conflict(ls, lh, &nv.v);
  758. assignment(ls, &nv, nvars+1);
  759. }
  760. else { /* assignment -> `=' explist1 */
  761. int nexps;
  762. check(ls, '=');
  763. nexps = explist1(ls, &e);
  764. if (nexps != nvars) {
  765. adjust_assign(ls, nvars, nexps, &e);
  766. if (nexps > nvars)
  767. ls->fs->freereg -= nexps - nvars; /* remove extra values */
  768. }
  769. else {
  770. luaK_storevar(ls->fs, &lh->v, &e);
  771. return; /* avoid default */
  772. }
  773. }
  774. init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
  775. luaK_storevar(ls->fs, &lh->v, &e);
  776. }
  777. static void cond (LexState *ls, expdesc *v) {
  778. /* cond -> exp */
  779. expr(ls, v); /* read condition */
  780. luaK_goiftrue(ls->fs, v);
  781. }
  782. static void whilestat (LexState *ls, int line) {
  783. /* whilestat -> WHILE cond DO block END */
  784. FuncState *fs = ls->fs;
  785. int while_init = luaK_getlabel(fs);
  786. expdesc v;
  787. Breaklabel bl;
  788. enterbreak(fs, &bl);
  789. next(ls);
  790. cond(ls, &v);
  791. check(ls, TK_DO);
  792. block(ls);
  793. luaK_patchlist(fs, luaK_jump(fs), while_init);
  794. luaK_patchlist(fs, v.f, luaK_getlabel(fs));
  795. check_match(ls, TK_END, TK_WHILE, line);
  796. leavebreak(fs, &bl);
  797. }
  798. static void repeatstat (LexState *ls, int line) {
  799. /* repeatstat -> REPEAT block UNTIL cond */
  800. FuncState *fs = ls->fs;
  801. int repeat_init = luaK_getlabel(fs);
  802. expdesc v;
  803. Breaklabel bl;
  804. enterbreak(fs, &bl);
  805. next(ls);
  806. block(ls);
  807. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  808. cond(ls, &v);
  809. luaK_patchlist(fs, v.f, repeat_init);
  810. leavebreak(fs, &bl);
  811. }
  812. static void exp1 (LexState *ls) {
  813. expdesc e;
  814. expr(ls, &e);
  815. luaK_exp2nextreg(ls->fs, &e);
  816. }
  817. static void forbody (LexState *ls, int nvar, OpCode loopfor) {
  818. /* forbody -> DO block END */
  819. FuncState *fs = ls->fs;
  820. int basereg = fs->freereg - nvar;
  821. int prep = luaK_jump(fs);
  822. int blockinit = luaK_getlabel(fs);
  823. check(ls, TK_DO);
  824. adjustlocalvars(ls, nvar); /* scope for control variables */
  825. block(ls);
  826. luaK_patchlist(fs, prep, luaK_getlabel(fs));
  827. luaK_patchlist(fs, luaK_codeAsBc(fs, loopfor, basereg, NO_JUMP), blockinit);
  828. removelocalvars(ls, nvar, 1);
  829. }
  830. static void fornum (LexState *ls, TString *varname) {
  831. /* fornum -> NAME = exp1,exp1[,exp1] forbody */
  832. FuncState *fs = ls->fs;
  833. check(ls, '=');
  834. exp1(ls); /* initial value */
  835. check(ls, ',');
  836. exp1(ls); /* limit */
  837. if (optional(ls, ','))
  838. exp1(ls); /* optional step */
  839. else { /* default step = 1 */
  840. luaK_codeABc(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1));
  841. luaK_reserveregs(fs, 1);
  842. }
  843. new_localvar(ls, varname, 0);
  844. new_localvarstr(ls, "(limit)", 1);
  845. new_localvarstr(ls, "(step)", 2);
  846. luaK_codeABC(fs, OP_SUB, fs->freereg - 3, fs->freereg - 3, fs->freereg - 1);
  847. forbody(ls, 3, OP_FORLOOP);
  848. }
  849. static void forlist (LexState *ls, TString *indexname) {
  850. /* forlist -> NAME,NAME IN exp1 forbody */
  851. TString *valname;
  852. FuncState *fs = ls->fs;
  853. check(ls, ',');
  854. valname = str_checkname(ls);
  855. next(ls); /* skip var name */
  856. check(ls, TK_IN);
  857. exp1(ls); /* table */
  858. new_localvarstr(ls, "(table)", 0);
  859. new_localvarstr(ls, "(index)", 1);
  860. new_localvar(ls, indexname, 2);
  861. new_localvar(ls, valname, 3);
  862. luaK_reserveregs(fs, 3); /* registers for control, index and val */
  863. luaK_codeABc(fs, OP_LOADK, fs->freereg - 3, luaK_numberK(fs, -1));
  864. forbody(ls, 4, OP_TFORLOOP);
  865. }
  866. static void forstat (LexState *ls, int line) {
  867. /* forstat -> fornum | forlist */
  868. FuncState *fs = ls->fs;
  869. TString *varname;
  870. Breaklabel bl;
  871. enterbreak(fs, &bl);
  872. next(ls); /* skip `for' */
  873. varname = str_checkname(ls); /* first variable name */
  874. next(ls); /* skip var name */
  875. switch (ls->t.token) {
  876. case '=': fornum(ls, varname); break;
  877. case ',': forlist(ls, varname); break;
  878. default: luaK_error(ls, "`=' or `,' expected");
  879. }
  880. check_match(ls, TK_END, TK_FOR, line);
  881. leavebreak(fs, &bl);
  882. }
  883. static void test_then_block (LexState *ls, expdesc *v) {
  884. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  885. next(ls); /* skip IF or ELSEIF */
  886. cond(ls, v);
  887. check(ls, TK_THEN);
  888. block(ls); /* `then' part */
  889. }
  890. static void ifstat (LexState *ls, int line) {
  891. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  892. FuncState *fs = ls->fs;
  893. expdesc v;
  894. int escapelist = NO_JUMP;
  895. test_then_block(ls, &v); /* IF cond THEN block */
  896. while (ls->t.token == TK_ELSEIF) {
  897. luaK_concat(fs, &escapelist, luaK_jump(fs));
  898. luaK_patchlist(fs, v.f, luaK_getlabel(fs));
  899. test_then_block(ls, &v); /* ELSEIF cond THEN block */
  900. }
  901. if (ls->t.token == TK_ELSE) {
  902. luaK_concat(fs, &escapelist, luaK_jump(fs));
  903. luaK_patchlist(fs, v.f, luaK_getlabel(fs));
  904. next(ls); /* skip ELSE */
  905. block(ls); /* `else' part */
  906. }
  907. else
  908. luaK_concat(fs, &escapelist, v.f);
  909. luaK_patchlist(fs, escapelist, luaK_getlabel(fs));
  910. check_match(ls, TK_END, TK_IF, line);
  911. }
  912. static void localstat (LexState *ls) {
  913. /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
  914. int nvars = 0;
  915. int nexps;
  916. expdesc e;
  917. do {
  918. next(ls); /* skip LOCAL or `,' */
  919. new_localvar(ls, str_checkname(ls), nvars++);
  920. next(ls); /* skip var name */
  921. } while (ls->t.token == ',');
  922. if (optional(ls, '='))
  923. nexps = explist1(ls, &e);
  924. else {
  925. e.k = VVOID;
  926. nexps = 0;
  927. }
  928. adjust_assign(ls, nvars, nexps, &e);
  929. adjustlocalvars(ls, nvars);
  930. }
  931. static int funcname (LexState *ls, expdesc *v) {
  932. /* funcname -> NAME {field} [`:' NAME] */
  933. int needself = 0;
  934. singlevar(ls->fs, str_checkname(ls), v, 1);
  935. next(ls); /* skip var name */
  936. while (ls->t.token == '.') {
  937. luaY_field(ls, v);
  938. }
  939. if (ls->t.token == ':') {
  940. needself = 1;
  941. luaY_field(ls, v);
  942. }
  943. return needself;
  944. }
  945. static void funcstat (LexState *ls, int line) {
  946. /* funcstat -> FUNCTION funcname body */
  947. int needself;
  948. expdesc v, b;
  949. next(ls); /* skip FUNCTION */
  950. needself = funcname(ls, &v);
  951. body(ls, &b, needself, line);
  952. luaK_storevar(ls->fs, &v, &b);
  953. }
  954. static void exprstat (LexState *ls) {
  955. /* stat -> func | assignment */
  956. FuncState *fs = ls->fs;
  957. struct LHS_assign v;
  958. primaryexp(ls, &v.v);
  959. if (v.v.k == VCALL) { /* stat -> func */
  960. luaK_setcallreturns(fs, &v.v, 0); /* call statement uses no results */
  961. }
  962. else { /* stat -> assignment */
  963. v.prev = NULL;
  964. assignment(ls, &v, 1);
  965. }
  966. }
  967. static void retstat (LexState *ls) {
  968. /* stat -> RETURN explist */
  969. FuncState *fs = ls->fs;
  970. expdesc e;
  971. int first, nret; /* registers with returned values */
  972. next(ls); /* skip RETURN */
  973. if (block_follow(ls->t.token) || ls->t.token == ';')
  974. first = nret = 0; /* return no values */
  975. else {
  976. explist1(ls, &e); /* optional return values */
  977. if (e.k == VCALL) {
  978. luaK_setcallreturns(fs, &e, LUA_MULTRET);
  979. first = fs->nactloc;
  980. nret = LUA_MULTRET; /* return all values */
  981. }
  982. else {
  983. luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
  984. first = fs->nactloc;
  985. nret = fs->freereg - first; /* return all `active' values */
  986. }
  987. }
  988. luaK_codeABC(fs, OP_RETURN, first, nret+1, 0);
  989. fs->freereg = fs->nactloc; /* removes all temp values */
  990. }
  991. static void breakstat (LexState *ls) {
  992. /* stat -> BREAK [NAME] */
  993. FuncState *fs = ls->fs;
  994. Breaklabel *bl = fs->bl;
  995. if (!bl)
  996. luaK_error(ls, "no loop to break");
  997. next(ls); /* skip BREAK */
  998. closelevel(ls, bl->nactloc);
  999. luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
  1000. }
  1001. static int statement (LexState *ls) {
  1002. int line = ls->linenumber; /* may be needed for error messages */
  1003. switch (ls->t.token) {
  1004. case TK_IF: { /* stat -> ifstat */
  1005. ifstat(ls, line);
  1006. return 0;
  1007. }
  1008. case TK_WHILE: { /* stat -> whilestat */
  1009. whilestat(ls, line);
  1010. return 0;
  1011. }
  1012. case TK_DO: { /* stat -> DO block END */
  1013. next(ls); /* skip DO */
  1014. block(ls);
  1015. check_match(ls, TK_END, TK_DO, line);
  1016. return 0;
  1017. }
  1018. case TK_FOR: { /* stat -> forstat */
  1019. forstat(ls, line);
  1020. return 0;
  1021. }
  1022. case TK_REPEAT: { /* stat -> repeatstat */
  1023. repeatstat(ls, line);
  1024. return 0;
  1025. }
  1026. case TK_FUNCTION: {
  1027. funcstat(ls, line); /* stat -> funcstat */
  1028. return 0;
  1029. }
  1030. case TK_LOCAL: { /* stat -> localstat */
  1031. localstat(ls);
  1032. return 0;
  1033. }
  1034. case TK_RETURN: { /* stat -> retstat */
  1035. retstat(ls);
  1036. return 1; /* must be last statement */
  1037. }
  1038. case TK_BREAK: { /* stat -> breakstat */
  1039. breakstat(ls);
  1040. return 1; /* must be last statement */
  1041. }
  1042. default: {
  1043. exprstat(ls);
  1044. return 0; /* to avoid warnings */
  1045. }
  1046. }
  1047. }
  1048. static void parlist (LexState *ls) {
  1049. /* parlist -> [ param { `,' param } ] */
  1050. int nparams = 0;
  1051. short dots = 0;
  1052. if (ls->t.token != ')') { /* is `parlist' not empty? */
  1053. do {
  1054. switch (ls->t.token) {
  1055. case TK_DOTS: dots = 1; break;
  1056. case TK_NAME: new_localvar(ls, str_checkname(ls), nparams++); break;
  1057. default: luaK_error(ls, "<name> or `...' expected");
  1058. }
  1059. next(ls);
  1060. } while (!dots && optional(ls, ','));
  1061. }
  1062. code_params(ls, nparams, dots);
  1063. }
  1064. static void body (LexState *ls, expdesc *e, int needself, int line) {
  1065. /* body -> `(' parlist `)' chunk END */
  1066. FuncState new_fs;
  1067. open_func(ls, &new_fs);
  1068. new_fs.f->lineDefined = line;
  1069. check(ls, '(');
  1070. if (needself) {
  1071. new_localvarstr(ls, "self", 0);
  1072. adjustlocalvars(ls, 1);
  1073. }
  1074. parlist(ls);
  1075. check(ls, ')');
  1076. chunk(ls);
  1077. check_match(ls, TK_END, TK_FUNCTION, line);
  1078. close_func(ls);
  1079. pushclosure(ls, &new_fs, e);
  1080. }
  1081. /* }====================================================================== */
  1082. static void chunk (LexState *ls) {
  1083. /* chunk -> { stat [`;'] } */
  1084. int islast = 0;
  1085. while (!islast && !block_follow(ls->t.token)) {
  1086. islast = statement(ls);
  1087. optional(ls, ';');
  1088. lua_assert(ls->fs->freereg >= ls->fs->nactloc);
  1089. ls->fs->freereg = ls->fs->nactloc; /* free registers */
  1090. }
  1091. }