lparser.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. /*
  2. ** $Id: lparser.c,v 1.139 2001/02/23 17:17:25 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 n = 1; /* at least one element */
  387. recfield(ls);
  388. while (ls->t.token == l_c(',')) {
  389. next(ls);
  390. if (ls->t.token == l_c(';') || ls->t.token == l_c('}'))
  391. break;
  392. recfield(ls);
  393. n++;
  394. if (n%RFIELDS_PER_FLUSH == 0)
  395. luaK_code1(fs, OP_SETMAP, RFIELDS_PER_FLUSH);
  396. }
  397. luaK_code1(fs, OP_SETMAP, n%RFIELDS_PER_FLUSH);
  398. return n;
  399. }
  400. static int listfields (LexState *ls) {
  401. /* listfields -> exp1 { `,' exp1 } [`,'] */
  402. FuncState *fs = ls->fs;
  403. int n = 1; /* at least one element */
  404. exp1(ls);
  405. while (ls->t.token == l_c(',')) {
  406. next(ls);
  407. if (ls->t.token == l_c(';') || ls->t.token == l_c('}'))
  408. break;
  409. exp1(ls);
  410. n++;
  411. luaX_checklimit(ls, n/LFIELDS_PER_FLUSH, MAXARG_A,
  412. l_s("`item groups' in a list initializer"));
  413. if (n%LFIELDS_PER_FLUSH == 0)
  414. luaK_code2(fs, OP_SETLIST, n/LFIELDS_PER_FLUSH - 1, LFIELDS_PER_FLUSH);
  415. }
  416. luaK_code2(fs, OP_SETLIST, n/LFIELDS_PER_FLUSH, n%LFIELDS_PER_FLUSH);
  417. return n;
  418. }
  419. static void constructor_part (LexState *ls, Constdesc *cd) {
  420. switch (ls->t.token) {
  421. case l_c(';'): case l_c('}'): { /* constructor_part -> empty */
  422. cd->n = 0;
  423. cd->k = ls->t.token;
  424. break;
  425. }
  426. case TK_NAME: { /* may be listfields or recfields */
  427. lookahead(ls);
  428. if (ls->lookahead.token != l_c('=')) /* expression? */
  429. goto case_default;
  430. /* else go through to recfields */
  431. }
  432. case l_c('['): { /* constructor_part -> recfields */
  433. cd->n = recfields(ls);
  434. cd->k = 1; /* record */
  435. break;
  436. }
  437. default: { /* constructor_part -> listfields */
  438. case_default:
  439. cd->n = listfields(ls);
  440. cd->k = 0; /* list */
  441. break;
  442. }
  443. }
  444. }
  445. static void constructor (LexState *ls) {
  446. /* constructor -> `{' constructor_part [`;' constructor_part] `}' */
  447. FuncState *fs = ls->fs;
  448. int line = ls->linenumber;
  449. int pc = luaK_code1(fs, OP_CREATETABLE, 0);
  450. int nelems;
  451. Constdesc cd;
  452. check(ls, l_c('{'));
  453. constructor_part(ls, &cd);
  454. nelems = cd.n;
  455. if (optional(ls, l_c(';'))) {
  456. Constdesc other_cd;
  457. constructor_part(ls, &other_cd);
  458. check_condition(ls, (cd.k != other_cd.k), l_s("invalid constructor syntax"));
  459. nelems += other_cd.n;
  460. }
  461. check_match(ls, l_c('}'), l_c('{'), line);
  462. luaX_checklimit(ls, nelems, MAXARG_U, l_s("elements in a table constructor"));
  463. SETARG_U(fs->f->code[pc], nelems); /* set initial table size */
  464. }
  465. /* }====================================================================== */
  466. /*
  467. ** {======================================================================
  468. ** Expression parsing
  469. ** =======================================================================
  470. */
  471. static void primaryexp (LexState *ls, expdesc *v) {
  472. FuncState *fs = ls->fs;
  473. switch (ls->t.token) {
  474. case TK_NUMBER: {
  475. lua_Number r = ls->t.seminfo.r;
  476. next(ls);
  477. luaK_number(fs, r);
  478. break;
  479. }
  480. case TK_STRING: {
  481. code_string(ls, ls->t.seminfo.ts); /* must use `seminfo' before `next' */
  482. next(ls);
  483. break;
  484. }
  485. case TK_NIL: {
  486. luaK_adjuststack(fs, -1);
  487. next(ls);
  488. break;
  489. }
  490. case l_c('{'): { /* constructor */
  491. constructor(ls);
  492. break;
  493. }
  494. case TK_FUNCTION: {
  495. next(ls);
  496. body(ls, 0, ls->linenumber);
  497. break;
  498. }
  499. case l_c('('): {
  500. next(ls);
  501. expr(ls, v);
  502. check(ls, l_c(')'));
  503. return;
  504. }
  505. case TK_NAME: {
  506. singlevar(ls, str_checkname(ls), v);
  507. return;
  508. }
  509. case l_c('%'): {
  510. next(ls); /* skip `%' */
  511. pushupvalue(ls, str_checkname(ls));
  512. break;
  513. }
  514. default: {
  515. luaK_error(ls, l_s("unexpected symbol"));
  516. return;
  517. }
  518. }
  519. v->k = VEXP;
  520. v->u.l.t = v->u.l.f = NO_JUMP;
  521. }
  522. static void simpleexp (LexState *ls, expdesc *v) {
  523. /* simpleexp ->
  524. primaryexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
  525. primaryexp(ls, v);
  526. for (;;) {
  527. switch (ls->t.token) {
  528. case l_c('.'): { /* `.' NAME */
  529. next(ls);
  530. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  531. luaK_kstr(ls, checkname(ls));
  532. v->k = VINDEXED;
  533. break;
  534. }
  535. case l_c('['): { /* `[' exp1 `]' */
  536. next(ls);
  537. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  538. v->k = VINDEXED;
  539. exp1(ls);
  540. check(ls, l_c(']'));
  541. break;
  542. }
  543. case l_c(':'): { /* `:' NAME funcargs */
  544. next(ls);
  545. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  546. luaK_code1(ls->fs, OP_PUSHSELF, checkname(ls));
  547. funcargs(ls, 1);
  548. v->k = VEXP;
  549. v->u.l.t = v->u.l.f = NO_JUMP;
  550. break;
  551. }
  552. case l_c('('): case TK_STRING: case l_c('{'): { /* funcargs */
  553. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  554. funcargs(ls, 0);
  555. v->k = VEXP;
  556. v->u.l.t = v->u.l.f = NO_JUMP;
  557. break;
  558. }
  559. default: return; /* should be follow... */
  560. }
  561. }
  562. }
  563. static UnOpr getunopr (int op) {
  564. switch (op) {
  565. case TK_NOT: return OPR_NOT;
  566. case l_c('-'): return OPR_MINUS;
  567. default: return OPR_NOUNOPR;
  568. }
  569. }
  570. static BinOpr getbinopr (int op) {
  571. switch (op) {
  572. case l_c('+'): return OPR_ADD;
  573. case l_c('-'): return OPR_SUB;
  574. case l_c('*'): return OPR_MULT;
  575. case l_c('/'): return OPR_DIV;
  576. case l_c('^'): return OPR_POW;
  577. case TK_CONCAT: return OPR_CONCAT;
  578. case TK_NE: return OPR_NE;
  579. case TK_EQ: return OPR_EQ;
  580. case l_c('<'): return OPR_LT;
  581. case TK_LE: return OPR_LE;
  582. case l_c('>'): return OPR_GT;
  583. case TK_GE: return OPR_GE;
  584. case TK_AND: return OPR_AND;
  585. case TK_OR: return OPR_OR;
  586. default: return OPR_NOBINOPR;
  587. }
  588. }
  589. static const struct {
  590. lu_byte left; /* left priority for each binary operator */
  591. lu_byte right; /* right priority */
  592. } priority[] = { /* ORDER OPR */
  593. {5, 5}, {5, 5}, {6, 6}, {6, 6}, /* arithmetic */
  594. {9, 8}, {4, 3}, /* power and concat (right associative) */
  595. {2, 2}, {2, 2}, /* equality */
  596. {2, 2}, {2, 2}, {2, 2}, {2, 2}, /* order */
  597. {1, 1}, {1, 1} /* logical */
  598. };
  599. #define UNARY_PRIORITY 7 /* priority for unary operators */
  600. /*
  601. ** subexpr -> (simplexep | unop subexpr) { binop subexpr }
  602. ** where `binop' is any binary operator with a priority higher than `limit'
  603. */
  604. static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
  605. BinOpr op;
  606. UnOpr uop = getunopr(ls->t.token);
  607. if (uop != OPR_NOUNOPR) {
  608. next(ls);
  609. subexpr(ls, v, UNARY_PRIORITY);
  610. luaK_prefix(ls, uop, v);
  611. }
  612. else simpleexp(ls, v);
  613. /* expand while operators have priorities higher than `limit' */
  614. op = getbinopr(ls->t.token);
  615. while (op != OPR_NOBINOPR && (int)priority[op].left > limit) {
  616. expdesc v2;
  617. BinOpr nextop;
  618. next(ls);
  619. luaK_infix(ls, op, v);
  620. /* read sub-expression with higher priority */
  621. nextop = subexpr(ls, &v2, (int)priority[op].right);
  622. luaK_posfix(ls, op, v, &v2);
  623. op = nextop;
  624. }
  625. return op; /* return first untreated operator */
  626. }
  627. static void expr (LexState *ls, expdesc *v) {
  628. subexpr(ls, v, -1);
  629. }
  630. static void exp1 (LexState *ls) {
  631. expdesc v;
  632. expr(ls, &v);
  633. luaK_tostack(ls, &v, 1);
  634. }
  635. /* }==================================================================== */
  636. /*
  637. ** {======================================================================
  638. ** Rules for Statements
  639. ** =======================================================================
  640. */
  641. static int block_follow (int token) {
  642. switch (token) {
  643. case TK_ELSE: case TK_ELSEIF: case TK_END:
  644. case TK_UNTIL: case TK_EOS:
  645. return 1;
  646. default: return 0;
  647. }
  648. }
  649. static void block (LexState *ls) {
  650. /* block -> chunk */
  651. FuncState *fs = ls->fs;
  652. int nactloc = fs->nactloc;
  653. chunk(ls);
  654. luaK_adjuststack(fs, fs->nactloc - nactloc); /* remove local variables */
  655. removelocalvars(ls, fs->nactloc - nactloc);
  656. }
  657. static int assignment (LexState *ls, expdesc *v, int nvars) {
  658. int left = 0; /* number of values left in the stack after assignment */
  659. luaX_checklimit(ls, nvars, MAXVARSLH, l_s("variables in a multiple assignment"));
  660. if (ls->t.token == l_c(',')) { /* assignment -> `,' simpleexp assignment */
  661. expdesc nv;
  662. next(ls);
  663. simpleexp(ls, &nv);
  664. check_condition(ls, (nv.k != VEXP), l_s("syntax error"));
  665. left = assignment(ls, &nv, nvars+1);
  666. }
  667. else { /* assignment -> `=' explist1 */
  668. int nexps;
  669. check(ls, l_c('='));
  670. nexps = explist1(ls);
  671. adjust_mult_assign(ls, nvars, nexps);
  672. }
  673. if (v->k != VINDEXED)
  674. luaK_storevar(ls, v);
  675. else { /* there may be garbage between table-index and value */
  676. luaK_code2(ls->fs, OP_SETTABLE, left+nvars+2, 1);
  677. left += 2;
  678. }
  679. return left;
  680. }
  681. static void cond (LexState *ls, expdesc *v) {
  682. /* cond -> exp */
  683. expr(ls, v); /* read condition */
  684. luaK_goiftrue(ls->fs, v, 0);
  685. }
  686. static void whilestat (LexState *ls, int line) {
  687. /* whilestat -> WHILE cond DO block END */
  688. FuncState *fs = ls->fs;
  689. int while_init = luaK_getlabel(fs);
  690. expdesc v;
  691. Breaklabel bl;
  692. enterbreak(fs, &bl);
  693. next(ls);
  694. cond(ls, &v);
  695. check(ls, TK_DO);
  696. block(ls);
  697. luaK_patchlist(fs, luaK_jump(fs), while_init);
  698. luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
  699. check_match(ls, TK_END, TK_WHILE, line);
  700. leavebreak(fs, &bl);
  701. }
  702. static void repeatstat (LexState *ls, int line) {
  703. /* repeatstat -> REPEAT block UNTIL cond */
  704. FuncState *fs = ls->fs;
  705. int repeat_init = luaK_getlabel(fs);
  706. expdesc v;
  707. Breaklabel bl;
  708. enterbreak(fs, &bl);
  709. next(ls);
  710. block(ls);
  711. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  712. cond(ls, &v);
  713. luaK_patchlist(fs, v.u.l.f, repeat_init);
  714. leavebreak(fs, &bl);
  715. }
  716. static void forbody (LexState *ls, int nvar, OpCode prepfor, OpCode loopfor) {
  717. /* forbody -> DO block END */
  718. FuncState *fs = ls->fs;
  719. int prep = luaK_code1(fs, prepfor, NO_JUMP);
  720. int blockinit = luaK_getlabel(fs);
  721. check(ls, TK_DO);
  722. adjustlocalvars(ls, nvar); /* scope for control variables */
  723. block(ls);
  724. luaK_patchlist(fs, luaK_code1(fs, loopfor, NO_JUMP), blockinit);
  725. luaK_fixfor(fs, prep, luaK_getlabel(fs));
  726. removelocalvars(ls, nvar);
  727. }
  728. static void fornum (LexState *ls, TString *varname) {
  729. /* fornum -> NAME = exp1,exp1[,exp1] forbody */
  730. FuncState *fs = ls->fs;
  731. check(ls, l_c('='));
  732. exp1(ls); /* initial value */
  733. check(ls, l_c(','));
  734. exp1(ls); /* limit */
  735. if (optional(ls, l_c(',')))
  736. exp1(ls); /* optional step */
  737. else
  738. luaK_code1(fs, OP_PUSHINT, 1); /* default step */
  739. new_localvar(ls, varname, 0);
  740. new_localvarstr(ls, l_s("(limit)"), 1);
  741. new_localvarstr(ls, l_s("(step)"), 2);
  742. forbody(ls, 3, OP_FORPREP, OP_FORLOOP);
  743. }
  744. static void forlist (LexState *ls, TString *indexname) {
  745. /* forlist -> NAME,NAME IN exp1 forbody */
  746. TString *valname;
  747. check(ls, l_c(','));
  748. valname = str_checkname(ls);
  749. /* next test is dirty, but avoids `in' being a reserved word */
  750. check_condition(ls,
  751. (ls->t.token == TK_NAME &&
  752. ls->t.seminfo.ts == luaS_newliteral(ls->L, l_s("in"))),
  753. l_s("`in' expected"));
  754. next(ls); /* skip `in' */
  755. exp1(ls); /* table */
  756. new_localvarstr(ls, l_s("(table)"), 0);
  757. new_localvarstr(ls, l_s("(index)"), 1);
  758. new_localvar(ls, indexname, 2);
  759. new_localvar(ls, valname, 3);
  760. forbody(ls, 4, 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 l_c('='): fornum(ls, varname); break;
  772. case l_c(','): forlist(ls, varname); break;
  773. default: luaK_error(ls, l_s("`=' 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 == l_c(','));
  815. if (optional(ls, l_c('=')))
  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. while (ls->t.token == l_c('.')) {
  827. next(ls);
  828. luaK_tostack(ls, v, 1);
  829. luaK_kstr(ls, checkname(ls));
  830. v->k = VINDEXED;
  831. }
  832. if (ls->t.token == l_c(':')) {
  833. needself = 1;
  834. next(ls);
  835. luaK_tostack(ls, v, 1);
  836. luaK_kstr(ls, checkname(ls));
  837. v->k = VINDEXED;
  838. }
  839. return needself;
  840. }
  841. static void funcstat (LexState *ls, int line) {
  842. /* funcstat -> FUNCTION funcname body */
  843. int needself;
  844. expdesc v;
  845. next(ls); /* skip FUNCTION */
  846. needself = funcname(ls, &v);
  847. body(ls, needself, line);
  848. luaK_storevar(ls, &v);
  849. }
  850. static void namestat (LexState *ls) {
  851. /* stat -> func | assignment */
  852. FuncState *fs = ls->fs;
  853. expdesc v;
  854. simpleexp(ls, &v);
  855. if (v.k == VEXP) { /* stat -> func */
  856. check_condition(ls, luaK_lastisopen(fs), l_s("syntax error")); /* an upvalue? */
  857. luaK_setcallreturns(fs, 0); /* call statement uses no results */
  858. }
  859. else { /* stat -> assignment */
  860. int left = assignment(ls, &v, 1);
  861. luaK_adjuststack(fs, left); /* remove eventual garbage left on stack */
  862. }
  863. }
  864. static void retstat (LexState *ls) {
  865. /* stat -> RETURN explist */
  866. FuncState *fs = ls->fs;
  867. next(ls); /* skip RETURN */
  868. if (!block_follow(ls->t.token) && ls->t.token != l_c(';'))
  869. explist1(ls); /* optional return values */
  870. luaK_code1(fs, OP_RETURN, ls->fs->nactloc);
  871. fs->stacklevel = fs->nactloc; /* removes all temp values */
  872. }
  873. static void breakstat (LexState *ls) {
  874. /* stat -> BREAK [NAME] */
  875. FuncState *fs = ls->fs;
  876. int currentlevel = fs->stacklevel;
  877. Breaklabel *bl = fs->bl;
  878. if (!bl)
  879. luaK_error(ls, l_s("no loop to break"));
  880. next(ls); /* skip BREAK */
  881. luaK_adjuststack(fs, currentlevel - bl->stacklevel);
  882. luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
  883. /* correct stack for compiler and symbolic execution */
  884. luaK_adjuststack(fs, bl->stacklevel - currentlevel);
  885. }
  886. static int statement (LexState *ls) {
  887. int line = ls->linenumber; /* may be needed for error messages */
  888. switch (ls->t.token) {
  889. case TK_IF: { /* stat -> ifstat */
  890. ifstat(ls, line);
  891. return 0;
  892. }
  893. case TK_WHILE: { /* stat -> whilestat */
  894. whilestat(ls, line);
  895. return 0;
  896. }
  897. case TK_DO: { /* stat -> DO block END */
  898. next(ls); /* skip DO */
  899. block(ls);
  900. check_match(ls, TK_END, TK_DO, line);
  901. return 0;
  902. }
  903. case TK_FOR: { /* stat -> forstat */
  904. forstat(ls, line);
  905. return 0;
  906. }
  907. case TK_REPEAT: { /* stat -> repeatstat */
  908. repeatstat(ls, line);
  909. return 0;
  910. }
  911. case TK_FUNCTION: { /* stat -> funcstat */
  912. funcstat(ls, line);
  913. return 0;
  914. }
  915. case TK_LOCAL: { /* stat -> localstat */
  916. localstat(ls);
  917. return 0;
  918. }
  919. case TK_RETURN: { /* stat -> retstat */
  920. retstat(ls);
  921. return 1; /* must be last statement */
  922. }
  923. case TK_BREAK: { /* stat -> breakstat */
  924. breakstat(ls);
  925. return 1; /* must be last statement */
  926. }
  927. default: {
  928. namestat(ls);
  929. return 0; /* to avoid warnings */
  930. }
  931. }
  932. }
  933. static void parlist (LexState *ls) {
  934. /* parlist -> [ param { `,' param } ] */
  935. int nparams = 0;
  936. short dots = 0;
  937. if (ls->t.token != l_c(')')) { /* is `parlist' not empty? */
  938. do {
  939. switch (ls->t.token) {
  940. case TK_DOTS: next(ls); dots = 1; break;
  941. case TK_NAME: new_localvar(ls, str_checkname(ls), nparams++); break;
  942. default: luaK_error(ls, l_s("<name> or `...' expected"));
  943. }
  944. } while (!dots && optional(ls, l_c(',')));
  945. }
  946. code_params(ls, nparams, dots);
  947. }
  948. static void body (LexState *ls, int needself, int line) {
  949. /* body -> `(' parlist `)' chunk END */
  950. FuncState new_fs;
  951. open_func(ls, &new_fs);
  952. new_fs.f->lineDefined = line;
  953. check(ls, l_c('('));
  954. if (needself) {
  955. new_localvarstr(ls, l_s("self"), 0);
  956. adjustlocalvars(ls, 1);
  957. }
  958. parlist(ls);
  959. check(ls, l_c(')'));
  960. chunk(ls);
  961. check_match(ls, TK_END, TK_FUNCTION, line);
  962. close_func(ls);
  963. pushclosure(ls, &new_fs);
  964. }
  965. /* }====================================================================== */
  966. static void chunk (LexState *ls) {
  967. /* chunk -> { stat [`;'] } */
  968. int islast = 0;
  969. while (!islast && !block_follow(ls->t.token)) {
  970. islast = statement(ls);
  971. optional(ls, l_c(';'));
  972. lua_assert(ls->fs->stacklevel == ls->fs->nactloc);
  973. }
  974. }