lparser.c 29 KB

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