lparser.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. /*
  2. ** $Id: lparser.c,v 1.111 2000/08/31 14:08:27 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. #include "lua.h"
  9. #include "lcode.h"
  10. #include "lfunc.h"
  11. #include "llex.h"
  12. #include "lmem.h"
  13. #include "lobject.h"
  14. #include "lopcodes.h"
  15. #include "lparser.h"
  16. #include "lstate.h"
  17. #include "lstring.h"
  18. /*
  19. ** Constructors descriptor:
  20. ** `n' indicates number of elements, and `k' signals whether
  21. ** it is a list constructor (k = 0) or a record constructor (k = 1)
  22. ** or empty (k = ';' or '}')
  23. */
  24. typedef struct Constdesc {
  25. int n;
  26. int k;
  27. } Constdesc;
  28. typedef struct Breaklabel {
  29. struct Breaklabel *previous; /* chain */
  30. int breaklist;
  31. int stacklevel;
  32. } Breaklabel;
  33. /*
  34. ** prototypes for recursive non-terminal functions
  35. */
  36. static void body (LexState *ls, int needself, int line);
  37. static void chunk (LexState *ls);
  38. static void constructor (LexState *ls);
  39. static void expr (LexState *ls, expdesc *v);
  40. static void exp1 (LexState *ls);
  41. static void next (LexState *ls) {
  42. ls->lastline = ls->linenumber;
  43. if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
  44. ls->t = ls->lookahead; /* use this one */
  45. ls->lookahead.token = TK_EOS; /* and discharge it */
  46. }
  47. else
  48. ls->t.token = luaX_lex(ls); /* read next token */
  49. }
  50. static void lookahead (LexState *ls) {
  51. LUA_ASSERT(ls->lookahead.token == TK_EOS, "two look-aheads");
  52. ls->lookahead.token = luaX_lex(ls);
  53. }
  54. static void error_expected (LexState *ls, int token) {
  55. char buff[100], t[TOKEN_LEN];
  56. luaX_token2str(token, t);
  57. sprintf(buff, "`%.20s' expected", t);
  58. luaK_error(ls, buff);
  59. }
  60. static void check (LexState *ls, int c) {
  61. if (ls->t.token != c)
  62. error_expected(ls, c);
  63. next(ls);
  64. }
  65. static void check_condition (LexState *ls, int c, const char *msg) {
  66. if (!c) luaK_error(ls, msg);
  67. }
  68. static int optional (LexState *ls, int c) {
  69. if (ls->t.token == c) {
  70. next(ls);
  71. return 1;
  72. }
  73. else return 0;
  74. }
  75. static void check_match (LexState *ls, int what, int who, int where) {
  76. if (ls->t.token != what) {
  77. if (where == ls->linenumber)
  78. error_expected(ls, what);
  79. else {
  80. char buff[100];
  81. char t_what[TOKEN_LEN], t_who[TOKEN_LEN];
  82. luaX_token2str(what, t_what);
  83. luaX_token2str(who, t_who);
  84. sprintf(buff, "`%.20s' expected (to close `%.20s' at line %d)",
  85. t_what, t_who, where);
  86. luaK_error(ls, buff);
  87. }
  88. }
  89. next(ls);
  90. }
  91. static int string_constant (FuncState *fs, TString *s) {
  92. Proto *f = fs->f;
  93. int c = s->u.s.constindex;
  94. if (c >= f->nkstr || f->kstr[c] != s) {
  95. luaM_growvector(fs->L, f->kstr, f->nkstr, 1, TString *,
  96. "constant table overflow", MAXARG_U);
  97. c = f->nkstr++;
  98. f->kstr[c] = s;
  99. s->u.s.constindex = c; /* hint for next time */
  100. }
  101. return c;
  102. }
  103. static void code_string (LexState *ls, TString *s) {
  104. luaK_kstr(ls, string_constant(ls->fs, s));
  105. }
  106. static TString *str_checkname (LexState *ls) {
  107. TString *ts;
  108. check_condition(ls, (ls->t.token == TK_NAME), "<name> expected");
  109. ts = ls->t.seminfo.ts;
  110. next(ls);
  111. return ts;
  112. }
  113. static int checkname (LexState *ls) {
  114. return string_constant(ls->fs, str_checkname(ls));
  115. }
  116. static int luaI_registerlocalvar (LexState *ls, TString *varname) {
  117. Proto *f = ls->fs->f;
  118. luaM_growvector(ls->L, f->locvars, f->nlocvars, 1, LocVar, "", MAX_INT);
  119. f->locvars[f->nlocvars].varname = varname;
  120. return f->nlocvars++;
  121. }
  122. static void new_localvar (LexState *ls, TString *name, int n) {
  123. FuncState *fs = ls->fs;
  124. luaX_checklimit(ls, fs->nactloc+n+1, MAXLOCALS, "local variables");
  125. fs->actloc[fs->nactloc+n] = luaI_registerlocalvar(ls, name);
  126. }
  127. static void adjustlocalvars (LexState *ls, int nvars) {
  128. FuncState *fs = ls->fs;
  129. while (nvars--)
  130. fs->f->locvars[fs->actloc[fs->nactloc++]].startpc = fs->pc;
  131. }
  132. static void removelocalvars (LexState *ls, int nvars) {
  133. FuncState *fs = ls->fs;
  134. while (nvars--)
  135. fs->f->locvars[fs->actloc[--fs->nactloc]].endpc = fs->pc;
  136. }
  137. static void new_localvarstr (LexState *ls, const char *name, int n) {
  138. new_localvar(ls, luaS_newfixed(ls->L, name), n);
  139. }
  140. static int search_local (LexState *ls, TString *n, expdesc *var) {
  141. FuncState *fs;
  142. int level = 0;
  143. for (fs=ls->fs; fs; fs=fs->prev) {
  144. int i;
  145. for (i=fs->nactloc-1; i >= 0; i--) {
  146. if (n == fs->f->locvars[fs->actloc[i]].varname) {
  147. var->k = VLOCAL;
  148. var->u.index = i;
  149. return level;
  150. }
  151. }
  152. level++; /* `var' not found; check outer level */
  153. }
  154. var->k = VGLOBAL; /* not found in any level; must be global */
  155. return -1;
  156. }
  157. static void singlevar (LexState *ls, TString *n, expdesc *var) {
  158. int level = search_local(ls, n, var);
  159. if (level >= 1) /* neither local (0) nor global (-1)? */
  160. luaX_syntaxerror(ls, "cannot access a variable in outer scope", n->str);
  161. else if (level == -1) /* global? */
  162. var->u.index = string_constant(ls->fs, n);
  163. }
  164. static int indexupvalue (LexState *ls, expdesc *v) {
  165. FuncState *fs = ls->fs;
  166. int i;
  167. for (i=0; i<fs->nupvalues; i++) {
  168. if (fs->upvalues[i].k == v->k && fs->upvalues[i].u.index == v->u.index)
  169. return i;
  170. }
  171. /* new one */
  172. luaX_checklimit(ls, fs->nupvalues+1, MAXUPVALUES, "upvalues");
  173. fs->upvalues[fs->nupvalues] = *v;
  174. return fs->nupvalues++;
  175. }
  176. static void pushupvalue (LexState *ls, TString *n) {
  177. FuncState *fs = ls->fs;
  178. expdesc v;
  179. int level = search_local(ls, n, &v);
  180. if (level == -1) { /* global? */
  181. if (fs->prev == NULL)
  182. luaX_syntaxerror(ls, "cannot access upvalue in main", n->str);
  183. v.u.index = string_constant(fs->prev, n);
  184. }
  185. else if (level != 1)
  186. luaX_syntaxerror(ls,
  187. "upvalue must be global or local to immediately outer scope", n->str);
  188. luaK_code1(fs, OP_PUSHUPVALUE, indexupvalue(ls, &v));
  189. }
  190. static void adjust_mult_assign (LexState *ls, int nvars, int nexps) {
  191. FuncState *fs = ls->fs;
  192. int diff = nexps - nvars;
  193. if (nexps > 0 && luaK_lastisopen(fs)) { /* list ends in a function call */
  194. diff--; /* do not count function call itself */
  195. if (diff <= 0) { /* more variables than values? */
  196. luaK_setcallreturns(fs, -diff); /* function call provide extra values */
  197. diff = 0; /* no more difference */
  198. }
  199. else /* more values than variables */
  200. luaK_setcallreturns(fs, 0); /* call should provide no value */
  201. }
  202. /* push or pop eventual difference between list lengths */
  203. luaK_adjuststack(fs, diff);
  204. }
  205. static void code_params (LexState *ls, int nparams, int dots) {
  206. FuncState *fs = ls->fs;
  207. adjustlocalvars(ls, nparams);
  208. luaX_checklimit(ls, fs->nactloc, MAXPARAMS, "parameters");
  209. fs->f->numparams = fs->nactloc; /* `self' could be there already */
  210. fs->f->is_vararg = dots;
  211. if (dots) {
  212. new_localvarstr(ls, "arg", 0);
  213. adjustlocalvars(ls, 1);
  214. }
  215. luaK_deltastack(fs, fs->nactloc); /* count parameters in the stack */
  216. }
  217. static void enterbreak (FuncState *fs, Breaklabel *bl) {
  218. bl->stacklevel = fs->stacklevel;
  219. bl->breaklist = NO_JUMP;
  220. bl->previous = fs->bl;
  221. fs->bl = bl;
  222. }
  223. static void leavebreak (FuncState *fs, Breaklabel *bl) {
  224. fs->bl = bl->previous;
  225. LUA_ASSERT(bl->stacklevel == fs->stacklevel, "wrong levels");
  226. luaK_patchlist(fs, bl->breaklist, luaK_getlabel(fs));
  227. }
  228. static void pushclosure (LexState *ls, FuncState *func) {
  229. FuncState *fs = ls->fs;
  230. Proto *f = fs->f;
  231. int i;
  232. for (i=0; i<func->nupvalues; i++)
  233. luaK_tostack(ls, &func->upvalues[i], 1);
  234. luaM_growvector(ls->L, f->kproto, f->nkproto, 1, Proto *,
  235. "constant table overflow", MAXARG_A);
  236. f->kproto[f->nkproto++] = func->f;
  237. luaK_code2(fs, OP_CLOSURE, f->nkproto-1, func->nupvalues);
  238. }
  239. static void open_func (LexState *ls, FuncState *fs) {
  240. Proto *f = luaF_newproto(ls->L);
  241. fs->prev = ls->fs; /* linked list of funcstates */
  242. fs->ls = ls;
  243. fs->L = ls->L;
  244. ls->fs = fs;
  245. fs->stacklevel = 0;
  246. fs->nactloc = 0;
  247. fs->nupvalues = 0;
  248. fs->bl = NULL;
  249. fs->f = f;
  250. f->source = ls->source;
  251. fs->pc = 0;
  252. fs->lasttarget = 0;
  253. fs->nlineinfo = 0;
  254. fs->lastline = 0;
  255. fs->jlt = NO_JUMP;
  256. f->code = NULL;
  257. f->maxstacksize = 0;
  258. f->numparams = 0; /* default for main chunk */
  259. f->is_vararg = 0; /* default for main chunk */
  260. }
  261. static void close_func (LexState *ls) {
  262. lua_State *L = ls->L;
  263. FuncState *fs = ls->fs;
  264. Proto *f = fs->f;
  265. luaK_code0(fs, OP_END);
  266. luaK_getlabel(fs); /* close eventual list of pending jumps */
  267. luaM_reallocvector(L, f->code, fs->pc, Instruction);
  268. luaM_reallocvector(L, f->kstr, f->nkstr, TString *);
  269. luaM_reallocvector(L, f->knum, f->nknum, Number);
  270. luaM_reallocvector(L, f->kproto, f->nkproto, Proto *);
  271. removelocalvars(ls, fs->nactloc);
  272. luaM_reallocvector(L, f->locvars, f->nlocvars, LocVar);
  273. luaM_reallocvector(L, f->lineinfo, fs->nlineinfo+1, int);
  274. f->lineinfo[fs->nlineinfo] = MAX_INT; /* end flag */
  275. ls->fs = fs->prev;
  276. LUA_ASSERT(fs->bl == NULL, "wrong list end");
  277. }
  278. Proto *luaY_parser (lua_State *L, ZIO *z) {
  279. struct LexState lexstate;
  280. struct FuncState funcstate;
  281. luaX_setinput(L, &lexstate, z, luaS_new(L, zname(z)));
  282. open_func(&lexstate, &funcstate);
  283. next(&lexstate); /* read first token */
  284. chunk(&lexstate);
  285. check_condition(&lexstate, (lexstate.t.token == TK_EOS), "<eof> expected");
  286. close_func(&lexstate);
  287. LUA_ASSERT(funcstate.prev == NULL, "wrong list end");
  288. LUA_ASSERT(funcstate.nupvalues == 0, "no upvalues in main");
  289. return funcstate.f;
  290. }
  291. /*============================================================*/
  292. /* GRAMMAR RULES */
  293. /*============================================================*/
  294. static int explist1 (LexState *ls) {
  295. /* explist1 -> expr { ',' expr } */
  296. int n = 1; /* at least one expression */
  297. expdesc v;
  298. expr(ls, &v);
  299. while (ls->t.token == ',') {
  300. luaK_tostack(ls, &v, 1); /* gets only 1 value from previous expression */
  301. next(ls); /* skip comma */
  302. expr(ls, &v);
  303. n++;
  304. }
  305. luaK_tostack(ls, &v, 0); /* keep open number of values of last expression */
  306. return n;
  307. }
  308. static void funcargs (LexState *ls, int slf) {
  309. FuncState *fs = ls->fs;
  310. int slevel = fs->stacklevel - slf - 1; /* where is func in the stack */
  311. switch (ls->t.token) {
  312. case '(': { /* funcargs -> '(' [ explist1 ] ')' */
  313. int line = ls->linenumber;
  314. int nargs = 0;
  315. next(ls);
  316. if (ls->t.token != ')') /* arg list not empty? */
  317. nargs = explist1(ls);
  318. check_match(ls, ')', '(', line);
  319. #ifdef LUA_COMPAT_ARGRET
  320. if (nargs > 0) /* arg list is not empty? */
  321. luaK_setcallreturns(fs, 1); /* last call returns only 1 value */
  322. #else
  323. UNUSED(nargs); /* to avoid warnings */
  324. #endif
  325. break;
  326. }
  327. case '{': { /* funcargs -> constructor */
  328. constructor(ls);
  329. break;
  330. }
  331. case TK_STRING: { /* funcargs -> STRING */
  332. code_string(ls, ls->t.seminfo.ts); /* must use `seminfo' before `next' */
  333. next(ls);
  334. break;
  335. }
  336. default: {
  337. luaK_error(ls, "function arguments expected");
  338. break;
  339. }
  340. }
  341. fs->stacklevel = slevel; /* call will remove function and arguments */
  342. luaK_code2(fs, OP_CALL, slevel, MULT_RET);
  343. }
  344. static void var_or_func_tail (LexState *ls, expdesc *v) {
  345. for (;;) {
  346. switch (ls->t.token) {
  347. case '.': { /* var_or_func_tail -> '.' NAME */
  348. next(ls);
  349. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  350. luaK_kstr(ls, checkname(ls));
  351. v->k = VINDEXED;
  352. break;
  353. }
  354. case '[': { /* var_or_func_tail -> '[' exp1 ']' */
  355. next(ls);
  356. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  357. v->k = VINDEXED;
  358. exp1(ls);
  359. check(ls, ']');
  360. break;
  361. }
  362. case ':': { /* var_or_func_tail -> ':' NAME funcargs */
  363. int name;
  364. next(ls);
  365. name = checkname(ls);
  366. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  367. luaK_code1(ls->fs, OP_PUSHSELF, name);
  368. funcargs(ls, 1);
  369. v->k = VEXP;
  370. v->u.l.t = v->u.l.f = NO_JUMP;
  371. break;
  372. }
  373. case '(': case TK_STRING: case '{': { /* var_or_func_tail -> funcargs */
  374. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  375. funcargs(ls, 0);
  376. v->k = VEXP;
  377. v->u.l.t = v->u.l.f = NO_JUMP;
  378. break;
  379. }
  380. default: return; /* should be follow... */
  381. }
  382. }
  383. }
  384. static void var_or_func (LexState *ls, expdesc *v) {
  385. /* var_or_func -> ['%'] NAME var_or_func_tail */
  386. if (optional(ls, '%')) { /* upvalue? */
  387. pushupvalue(ls, str_checkname(ls));
  388. v->k = VEXP;
  389. v->u.l.t = v->u.l.f = NO_JUMP;
  390. }
  391. else /* variable name */
  392. singlevar(ls, str_checkname(ls), v);
  393. var_or_func_tail(ls, v);
  394. }
  395. /*
  396. ** {======================================================================
  397. ** Rules for Constructors
  398. ** =======================================================================
  399. */
  400. static void recfield (LexState *ls) {
  401. /* recfield -> (NAME | '['exp1']') = exp1 */
  402. switch (ls->t.token) {
  403. case TK_NAME: {
  404. luaK_kstr(ls, checkname(ls));
  405. break;
  406. }
  407. case '[': {
  408. next(ls);
  409. exp1(ls);
  410. check(ls, ']');
  411. break;
  412. }
  413. default: luaK_error(ls, "<name> or `[' expected");
  414. }
  415. check(ls, '=');
  416. exp1(ls);
  417. }
  418. static int recfields (LexState *ls) {
  419. /* recfields -> recfield { ',' recfield } [','] */
  420. FuncState *fs = ls->fs;
  421. int n = 1; /* at least one element */
  422. recfield(ls);
  423. while (ls->t.token == ',') {
  424. next(ls);
  425. if (ls->t.token == ';' || ls->t.token == '}')
  426. break;
  427. recfield(ls);
  428. n++;
  429. if (n%RFIELDS_PER_FLUSH == 0)
  430. luaK_code1(fs, OP_SETMAP, RFIELDS_PER_FLUSH);
  431. }
  432. luaK_code1(fs, OP_SETMAP, n%RFIELDS_PER_FLUSH);
  433. return n;
  434. }
  435. static int listfields (LexState *ls) {
  436. /* listfields -> exp1 { ',' exp1 } [','] */
  437. FuncState *fs = ls->fs;
  438. int n = 1; /* at least one element */
  439. exp1(ls);
  440. while (ls->t.token == ',') {
  441. next(ls);
  442. if (ls->t.token == ';' || ls->t.token == '}')
  443. break;
  444. exp1(ls);
  445. n++;
  446. luaX_checklimit(ls, n/LFIELDS_PER_FLUSH, MAXARG_A,
  447. "`item groups' in a list initializer");
  448. if (n%LFIELDS_PER_FLUSH == 0)
  449. luaK_code2(fs, OP_SETLIST, n/LFIELDS_PER_FLUSH - 1, LFIELDS_PER_FLUSH);
  450. }
  451. luaK_code2(fs, OP_SETLIST, n/LFIELDS_PER_FLUSH, n%LFIELDS_PER_FLUSH);
  452. return n;
  453. }
  454. static void constructor_part (LexState *ls, Constdesc *cd) {
  455. switch (ls->t.token) {
  456. case ';': case '}': { /* constructor_part -> empty */
  457. cd->n = 0;
  458. cd->k = ls->t.token;
  459. break;
  460. }
  461. case TK_NAME: { /* may be listfields or recfields */
  462. lookahead(ls);
  463. if (ls->lookahead.token != '=') /* expression? */
  464. goto case_default;
  465. /* else go through to recfields */
  466. }
  467. case '[': { /* constructor_part -> recfields */
  468. cd->n = recfields(ls);
  469. cd->k = 1; /* record */
  470. break;
  471. }
  472. default: { /* constructor_part -> listfields */
  473. case_default:
  474. cd->n = listfields(ls);
  475. cd->k = 0; /* list */
  476. break;
  477. }
  478. }
  479. }
  480. static void constructor (LexState *ls) {
  481. /* constructor -> '{' constructor_part [';' constructor_part] '}' */
  482. FuncState *fs = ls->fs;
  483. int line = ls->linenumber;
  484. int pc = luaK_code1(fs, OP_CREATETABLE, 0);
  485. int nelems;
  486. Constdesc cd;
  487. check(ls, '{');
  488. constructor_part(ls, &cd);
  489. nelems = cd.n;
  490. if (optional(ls, ';')) {
  491. Constdesc other_cd;
  492. constructor_part(ls, &other_cd);
  493. check_condition(ls, (cd.k != other_cd.k), "invalid constructor syntax");
  494. nelems += other_cd.n;
  495. }
  496. check_match(ls, '}', '{', line);
  497. luaX_checklimit(ls, nelems, MAXARG_U, "elements in a table constructor");
  498. SETARG_U(fs->f->code[pc], nelems); /* set initial table size */
  499. }
  500. /* }====================================================================== */
  501. /*
  502. ** {======================================================================
  503. ** Expression parsing
  504. ** =======================================================================
  505. */
  506. static void simpleexp (LexState *ls, expdesc *v) {
  507. FuncState *fs = ls->fs;
  508. switch (ls->t.token) {
  509. case TK_NUMBER: { /* simpleexp -> NUMBER */
  510. Number r = ls->t.seminfo.r;
  511. next(ls);
  512. luaK_number(fs, r);
  513. break;
  514. }
  515. case TK_STRING: { /* simpleexp -> STRING */
  516. code_string(ls, ls->t.seminfo.ts); /* must use `seminfo' before `next' */
  517. next(ls);
  518. break;
  519. }
  520. case TK_NIL: { /* simpleexp -> NIL */
  521. luaK_adjuststack(fs, -1);
  522. next(ls);
  523. break;
  524. }
  525. case '{': { /* simpleexp -> constructor */
  526. constructor(ls);
  527. break;
  528. }
  529. case TK_FUNCTION: { /* simpleexp -> FUNCTION body */
  530. next(ls);
  531. body(ls, 0, ls->linenumber);
  532. break;
  533. }
  534. case '(': { /* simpleexp -> '(' expr ')' */
  535. next(ls);
  536. expr(ls, v);
  537. check(ls, ')');
  538. return;
  539. }
  540. case TK_NAME: case '%': {
  541. var_or_func(ls, v);
  542. return;
  543. }
  544. default: {
  545. luaK_error(ls, "<expression> expected");
  546. return;
  547. }
  548. }
  549. v->k = VEXP;
  550. v->u.l.t = v->u.l.f = NO_JUMP;
  551. }
  552. static void exp1 (LexState *ls) {
  553. expdesc v;
  554. expr(ls, &v);
  555. luaK_tostack(ls, &v, 1);
  556. }
  557. static UnOpr getunopr (int op) {
  558. switch (op) {
  559. case TK_NOT: return OPR_NOT;
  560. case '-': return OPR_MINUS;
  561. default: return OPR_NOUNOPR;
  562. }
  563. }
  564. static BinOpr getbinopr (int op) {
  565. switch (op) {
  566. case '+': return OPR_ADD;
  567. case '-': return OPR_SUB;
  568. case '*': return OPR_MULT;
  569. case '/': return OPR_DIV;
  570. case '^': return OPR_POW;
  571. case TK_CONCAT: return OPR_CONCAT;
  572. case TK_NE: return OPR_NE;
  573. case TK_EQ: return OPR_EQ;
  574. case '<': return OPR_LT;
  575. case TK_LE: return OPR_LE;
  576. case '>': return OPR_GT;
  577. case TK_GE: return OPR_GE;
  578. case TK_AND: return OPR_AND;
  579. case TK_OR: return OPR_OR;
  580. default: return OPR_NOBINOPR;
  581. }
  582. }
  583. static const struct {
  584. char left; /* left priority for each binary operator */
  585. char right; /* right priority */
  586. } priority[] = { /* ORDER OPR */
  587. {5, 5}, {5, 5}, {6, 6}, {6, 6}, /* arithmetic */
  588. {9, 8}, {4, 3}, /* power and concat (right associative) */
  589. {2, 2}, {2, 2}, /* equality */
  590. {2, 2}, {2, 2}, {2, 2}, {2, 2}, /* order */
  591. {1, 1}, {1, 1} /* logical */
  592. };
  593. #define UNARY_PRIORITY 7 /* priority for unary operators */
  594. /*
  595. ** subexpr -> (simplexep | unop subexpr) { binop subexpr }
  596. ** where `binop' is any binary operator with a priority higher than `limit'
  597. */
  598. static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
  599. BinOpr op;
  600. UnOpr uop = getunopr(ls->t.token);
  601. if (uop != OPR_NOUNOPR) {
  602. next(ls);
  603. subexpr(ls, v, UNARY_PRIORITY);
  604. luaK_prefix(ls, uop, v);
  605. }
  606. else simpleexp(ls, v);
  607. /* expand while operators have priorities higher than `limit' */
  608. op = getbinopr(ls->t.token);
  609. while (op != OPR_NOBINOPR && priority[op].left > limit) {
  610. expdesc v2;
  611. BinOpr nextop;
  612. next(ls);
  613. luaK_infix(ls, op, v);
  614. /* read sub-expression with higher priority */
  615. nextop = subexpr(ls, &v2, priority[op].right);
  616. luaK_posfix(ls, op, v, &v2);
  617. op = nextop;
  618. }
  619. return op; /* return first untreated operator */
  620. }
  621. static void expr (LexState *ls, expdesc *v) {
  622. subexpr(ls, v, -1);
  623. }
  624. /* }==================================================================== */
  625. /*
  626. ** {======================================================================
  627. ** Rules for Statements
  628. ** =======================================================================
  629. */
  630. static int block_follow (int token) {
  631. switch (token) {
  632. case TK_ELSE: case TK_ELSEIF: case TK_END:
  633. case TK_UNTIL: case TK_EOS:
  634. return 1;
  635. default: return 0;
  636. }
  637. }
  638. static void block (LexState *ls) {
  639. /* block -> chunk */
  640. FuncState *fs = ls->fs;
  641. int nactloc = fs->nactloc;
  642. chunk(ls);
  643. luaK_adjuststack(fs, fs->nactloc - nactloc); /* remove local variables */
  644. removelocalvars(ls, fs->nactloc - nactloc);
  645. }
  646. static int assignment (LexState *ls, expdesc *v, int nvars) {
  647. int left = 0; /* number of values left in the stack after assignment */
  648. luaX_checklimit(ls, nvars, MAXVARSLH, "variables in a multiple assignment");
  649. if (ls->t.token == ',') { /* assignment -> ',' NAME assignment */
  650. expdesc nv;
  651. next(ls);
  652. var_or_func(ls, &nv);
  653. check_condition(ls, (nv.k != VEXP), "syntax error");
  654. left = assignment(ls, &nv, nvars+1);
  655. }
  656. else { /* assignment -> '=' explist1 */
  657. int nexps;
  658. check(ls, '=');
  659. nexps = explist1(ls);
  660. adjust_mult_assign(ls, nvars, nexps);
  661. }
  662. if (v->k != VINDEXED)
  663. luaK_storevar(ls, v);
  664. else { /* there may be garbage between table-index and value */
  665. luaK_code2(ls->fs, OP_SETTABLE, left+nvars+2, 1);
  666. left += 2;
  667. }
  668. return left;
  669. }
  670. static void cond (LexState *ls, expdesc *v) {
  671. /* cond -> exp */
  672. expr(ls, v); /* read condition */
  673. luaK_goiftrue(ls->fs, v, 0);
  674. }
  675. static void whilestat (LexState *ls, int line) {
  676. /* whilestat -> WHILE cond DO block END */
  677. FuncState *fs = ls->fs;
  678. int while_init = luaK_getlabel(fs);
  679. expdesc v;
  680. Breaklabel bl;
  681. enterbreak(fs, &bl);
  682. next(ls);
  683. cond(ls, &v);
  684. check(ls, TK_DO);
  685. block(ls);
  686. luaK_patchlist(fs, luaK_jump(fs), while_init);
  687. luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
  688. check_match(ls, TK_END, TK_WHILE, line);
  689. leavebreak(fs, &bl);
  690. }
  691. static void repeatstat (LexState *ls, int line) {
  692. /* repeatstat -> REPEAT block UNTIL cond */
  693. FuncState *fs = ls->fs;
  694. int repeat_init = luaK_getlabel(fs);
  695. expdesc v;
  696. Breaklabel bl;
  697. enterbreak(fs, &bl);
  698. next(ls);
  699. block(ls);
  700. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  701. cond(ls, &v);
  702. luaK_patchlist(fs, v.u.l.f, repeat_init);
  703. leavebreak(fs, &bl);
  704. }
  705. static void forbody (LexState *ls, int nvar, OpCode prepfor, OpCode loopfor) {
  706. /* forbody -> DO block END */
  707. FuncState *fs = ls->fs;
  708. int prep = luaK_code1(fs, prepfor, NO_JUMP);
  709. int blockinit = luaK_getlabel(fs);
  710. check(ls, TK_DO);
  711. adjustlocalvars(ls, nvar); /* scope for control variables */
  712. block(ls);
  713. luaK_patchlist(fs, luaK_code1(fs, loopfor, NO_JUMP), blockinit);
  714. luaK_patchlist(fs, prep, luaK_getlabel(fs));
  715. removelocalvars(ls, nvar);
  716. }
  717. static void fornum (LexState *ls, TString *varname) {
  718. /* fornum -> NAME = exp1,exp1[,exp1] forbody */
  719. FuncState *fs = ls->fs;
  720. check(ls, '=');
  721. exp1(ls); /* initial value */
  722. check(ls, ',');
  723. exp1(ls); /* limit */
  724. if (optional(ls, ','))
  725. exp1(ls); /* optional step */
  726. else
  727. luaK_code1(fs, OP_PUSHINT, 1); /* default step */
  728. new_localvar(ls, varname, 0);
  729. new_localvarstr(ls, "*limit*", 1);
  730. new_localvarstr(ls, "*step*", 2);
  731. forbody(ls, 3, OP_FORPREP, OP_FORLOOP);
  732. }
  733. static void forlist (LexState *ls, TString *indexname) {
  734. /* forlist -> NAME,NAME IN exp1 forbody */
  735. TString *valname;
  736. check(ls, ',');
  737. valname = str_checkname(ls);
  738. /* next test is dirty, but avoids `in' being a reserved word */
  739. check_condition(ls,
  740. (ls->t.token == TK_NAME && ls->t.seminfo.ts == luaS_new(ls->L, "in")),
  741. "`in' expected");
  742. next(ls); /* skip `in' */
  743. exp1(ls); /* table */
  744. new_localvarstr(ls, "*table*", 0);
  745. new_localvar(ls, indexname, 1);
  746. new_localvar(ls, valname, 2);
  747. forbody(ls, 3, OP_LFORPREP, OP_LFORLOOP);
  748. }
  749. static void forstat (LexState *ls, int line) {
  750. /* forstat -> fornum | forlist */
  751. FuncState *fs = ls->fs;
  752. TString *varname;
  753. Breaklabel bl;
  754. enterbreak(fs, &bl);
  755. next(ls); /* skip `for' */
  756. varname = str_checkname(ls); /* first variable name */
  757. switch (ls->t.token) {
  758. case '=': fornum(ls, varname); break;
  759. case ',': forlist(ls, varname); break;
  760. default: luaK_error(ls, "`=' or `,' expected");
  761. }
  762. check_match(ls, TK_END, TK_FOR, line);
  763. leavebreak(fs, &bl);
  764. }
  765. static void test_then_block (LexState *ls, expdesc *v) {
  766. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  767. next(ls); /* skip IF or ELSEIF */
  768. cond(ls, v);
  769. check(ls, TK_THEN);
  770. block(ls); /* `then' part */
  771. }
  772. static void ifstat (LexState *ls, int line) {
  773. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  774. FuncState *fs = ls->fs;
  775. expdesc v;
  776. int escapelist = NO_JUMP;
  777. test_then_block(ls, &v); /* IF cond THEN block */
  778. while (ls->t.token == TK_ELSEIF) {
  779. luaK_concat(fs, &escapelist, luaK_jump(fs));
  780. luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
  781. test_then_block(ls, &v); /* ELSEIF cond THEN block */
  782. }
  783. if (ls->t.token == TK_ELSE) {
  784. luaK_concat(fs, &escapelist, luaK_jump(fs));
  785. luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
  786. next(ls); /* skip ELSE */
  787. block(ls); /* `else' part */
  788. }
  789. else
  790. luaK_concat(fs, &escapelist, v.u.l.f);
  791. luaK_patchlist(fs, escapelist, luaK_getlabel(fs));
  792. check_match(ls, TK_END, TK_IF, line);
  793. }
  794. static void localstat (LexState *ls) {
  795. /* stat -> LOCAL NAME {',' NAME} ['=' explist1] */
  796. int nvars = 0;
  797. int nexps;
  798. do {
  799. next(ls); /* skip LOCAL or ',' */
  800. new_localvar(ls, str_checkname(ls), nvars++);
  801. } while (ls->t.token == ',');
  802. if (optional(ls, '='))
  803. nexps = explist1(ls);
  804. else
  805. nexps = 0;
  806. adjust_mult_assign(ls, nvars, nexps);
  807. adjustlocalvars(ls, nvars);
  808. }
  809. static int funcname (LexState *ls, expdesc *v) {
  810. /* funcname -> NAME [':' NAME | '.' NAME] */
  811. int needself = 0;
  812. singlevar(ls, str_checkname(ls), v);
  813. if (ls->t.token == ':' || ls->t.token == '.') {
  814. needself = (ls->t.token == ':');
  815. next(ls);
  816. luaK_tostack(ls, v, 1);
  817. luaK_kstr(ls, checkname(ls));
  818. v->k = VINDEXED;
  819. }
  820. return needself;
  821. }
  822. static void funcstat (LexState *ls, int line) {
  823. /* funcstat -> FUNCTION funcname body */
  824. int needself;
  825. expdesc v;
  826. next(ls); /* skip FUNCTION */
  827. needself = funcname(ls, &v);
  828. body(ls, needself, line);
  829. luaK_storevar(ls, &v);
  830. }
  831. static void namestat (LexState *ls) {
  832. /* stat -> func | ['%'] NAME assignment */
  833. FuncState *fs = ls->fs;
  834. expdesc v;
  835. var_or_func(ls, &v);
  836. if (v.k == VEXP) { /* stat -> func */
  837. check_condition(ls, luaK_lastisopen(fs), "syntax error"); /* an upvalue? */
  838. luaK_setcallreturns(fs, 0); /* call statement uses no results */
  839. }
  840. else { /* stat -> ['%'] NAME assignment */
  841. int left = assignment(ls, &v, 1);
  842. luaK_adjuststack(fs, left); /* remove eventual garbage left on stack */
  843. }
  844. }
  845. static void retstat (LexState *ls) {
  846. /* stat -> RETURN explist */
  847. FuncState *fs = ls->fs;
  848. next(ls); /* skip RETURN */
  849. if (!block_follow(ls->t.token))
  850. explist1(ls); /* optional return values */
  851. luaK_code1(fs, OP_RETURN, ls->fs->nactloc);
  852. fs->stacklevel = fs->nactloc; /* removes all temp values */
  853. }
  854. static void breakstat (LexState *ls) {
  855. /* stat -> BREAK [NAME] */
  856. FuncState *fs = ls->fs;
  857. int currentlevel = fs->stacklevel;
  858. Breaklabel *bl = fs->bl;
  859. if (!bl)
  860. luaK_error(ls, "no loop to break");
  861. next(ls); /* skip BREAK */
  862. luaK_adjuststack(fs, currentlevel - bl->stacklevel);
  863. luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
  864. /* correct stack for compiler and symbolic execution */
  865. luaK_adjuststack(fs, bl->stacklevel - currentlevel);
  866. }
  867. static int stat (LexState *ls) {
  868. int line = ls->linenumber; /* may be needed for error messages */
  869. switch (ls->t.token) {
  870. case TK_IF: { /* stat -> ifstat */
  871. ifstat(ls, line);
  872. return 0;
  873. }
  874. case TK_WHILE: { /* stat -> whilestat */
  875. whilestat(ls, line);
  876. return 0;
  877. }
  878. case TK_DO: { /* stat -> DO block END */
  879. next(ls); /* skip DO */
  880. block(ls);
  881. check_match(ls, TK_END, TK_DO, line);
  882. return 0;
  883. }
  884. case TK_FOR: { /* stat -> forstat */
  885. forstat(ls, line);
  886. return 0;
  887. }
  888. case TK_REPEAT: { /* stat -> repeatstat */
  889. repeatstat(ls, line);
  890. return 0;
  891. }
  892. case TK_FUNCTION: { /* stat -> funcstat */
  893. funcstat(ls, line);
  894. return 0;
  895. }
  896. case TK_LOCAL: { /* stat -> localstat */
  897. localstat(ls);
  898. return 0;
  899. }
  900. case TK_NAME: case '%': { /* stat -> namestat */
  901. namestat(ls);
  902. return 0;
  903. }
  904. case TK_RETURN: { /* stat -> retstat */
  905. retstat(ls);
  906. return 1; /* must be last statement */
  907. }
  908. case TK_BREAK: { /* stat -> breakstat */
  909. breakstat(ls);
  910. return 1; /* must be last statement */
  911. }
  912. default: {
  913. luaK_error(ls, "<statement> expected");
  914. return 0; /* to avoid warnings */
  915. }
  916. }
  917. }
  918. static void parlist (LexState *ls) {
  919. /* parlist -> [ param { ',' param } ] */
  920. int nparams = 0;
  921. int dots = 0;
  922. if (ls->t.token != ')') { /* is `parlist' not empty? */
  923. do {
  924. switch (ls->t.token) {
  925. case TK_DOTS: next(ls); dots = 1; break;
  926. case TK_NAME: new_localvar(ls, str_checkname(ls), nparams++); break;
  927. default: luaK_error(ls, "<name> or `...' expected");
  928. }
  929. } while (!dots && optional(ls, ','));
  930. }
  931. code_params(ls, nparams, dots);
  932. }
  933. static void body (LexState *ls, int needself, int line) {
  934. /* body -> '(' parlist ')' chunk END */
  935. FuncState new_fs;
  936. open_func(ls, &new_fs);
  937. new_fs.f->lineDefined = line;
  938. check(ls, '(');
  939. if (needself) {
  940. new_localvarstr(ls, "self", 0);
  941. adjustlocalvars(ls, 1);
  942. }
  943. parlist(ls);
  944. check(ls, ')');
  945. chunk(ls);
  946. check_match(ls, TK_END, TK_FUNCTION, line);
  947. close_func(ls);
  948. pushclosure(ls, &new_fs);
  949. }
  950. /* }====================================================================== */
  951. static void chunk (LexState *ls) {
  952. /* chunk -> { stat [';'] } */
  953. int islast = 0;
  954. while (!islast && !block_follow(ls->t.token)) {
  955. islast = stat(ls);
  956. optional(ls, ';');
  957. LUA_ASSERT(ls->fs->stacklevel == ls->fs->nactloc,
  958. "stack size != # local vars");
  959. }
  960. }