2
0

lparser.c 30 KB

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