2
0

lparser.c 32 KB

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