lparser.c 29 KB

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