lparser.c 32 KB

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