lparser.c 29 KB

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