lparser.c 31 KB

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