lparser.c 30 KB

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