lparser.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. /*
  2. ** $Id: lparser.c,v 1.128 2001/01/31 13:13:17 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. next(ls); /* skip comma */
  313. luaK_tostack(ls, &v, 1); /* gets only 1 value from previous expression */
  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. next(ls);
  376. luaK_tostack(ls, v, 1); /* `v' must be on stack */
  377. luaK_code1(ls->fs, OP_PUSHSELF, checkname(ls));
  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. lua_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. unsigned char left; /* left priority for each binary operator */
  595. unsigned 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 && (int)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, (int)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 nactloc = fs->nactloc;
  652. chunk(ls);
  653. luaK_adjuststack(fs, fs->nactloc - nactloc); /* remove local variables */
  654. removelocalvars(ls, fs->nactloc - nactloc);
  655. }
  656. static int assignment (LexState *ls, expdesc *v, int nvars) {
  657. int left = 0; /* number of values left in the stack after assignment */
  658. luaX_checklimit(ls, nvars, MAXVARSLH, "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, luaK_code1(fs, loopfor, NO_JUMP), blockinit);
  724. luaK_fixfor(fs, prep, luaK_getlabel(fs));
  725. removelocalvars(ls, nvar);
  726. }
  727. static void fornum (LexState *ls, TString *varname) {
  728. /* fornum -> NAME = exp1,exp1[,exp1] forbody */
  729. FuncState *fs = ls->fs;
  730. check(ls, '=');
  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 &&
  751. ls->t.seminfo.ts == luaS_newliteral(ls->L, "in")),
  752. "`in' expected");
  753. next(ls); /* skip `in' */
  754. exp1(ls); /* table */
  755. new_localvarstr(ls, "(table)", 0);
  756. new_localvarstr(ls, "(index)", 1);
  757. new_localvar(ls, indexname, 2);
  758. new_localvar(ls, valname, 3);
  759. forbody(ls, 4, OP_LFORPREP, OP_LFORLOOP);
  760. }
  761. static void forstat (LexState *ls, int line) {
  762. /* forstat -> fornum | forlist */
  763. FuncState *fs = ls->fs;
  764. TString *varname;
  765. Breaklabel bl;
  766. enterbreak(fs, &bl);
  767. next(ls); /* skip `for' */
  768. varname = str_checkname(ls); /* first variable name */
  769. switch (ls->t.token) {
  770. case '=': fornum(ls, varname); break;
  771. case ',': forlist(ls, varname); break;
  772. default: luaK_error(ls, "`=' or `,' expected");
  773. }
  774. check_match(ls, TK_END, TK_FOR, line);
  775. leavebreak(fs, &bl);
  776. }
  777. static void test_then_block (LexState *ls, expdesc *v) {
  778. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  779. next(ls); /* skip IF or ELSEIF */
  780. cond(ls, v);
  781. check(ls, TK_THEN);
  782. block(ls); /* `then' part */
  783. }
  784. static void ifstat (LexState *ls, int line) {
  785. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  786. FuncState *fs = ls->fs;
  787. expdesc v;
  788. int escapelist = NO_JUMP;
  789. test_then_block(ls, &v); /* IF cond THEN block */
  790. while (ls->t.token == TK_ELSEIF) {
  791. luaK_concat(fs, &escapelist, luaK_jump(fs));
  792. luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
  793. test_then_block(ls, &v); /* ELSEIF cond THEN block */
  794. }
  795. if (ls->t.token == TK_ELSE) {
  796. luaK_concat(fs, &escapelist, luaK_jump(fs));
  797. luaK_patchlist(fs, v.u.l.f, luaK_getlabel(fs));
  798. next(ls); /* skip ELSE */
  799. block(ls); /* `else' part */
  800. }
  801. else
  802. luaK_concat(fs, &escapelist, v.u.l.f);
  803. luaK_patchlist(fs, escapelist, luaK_getlabel(fs));
  804. check_match(ls, TK_END, TK_IF, line);
  805. }
  806. static void localstat (LexState *ls) {
  807. /* stat -> LOCAL NAME {',' NAME} ['=' explist1] */
  808. int nvars = 0;
  809. int nexps;
  810. do {
  811. next(ls); /* skip LOCAL or ',' */
  812. new_localvar(ls, str_checkname(ls), nvars++);
  813. } while (ls->t.token == ',');
  814. if (optional(ls, '='))
  815. nexps = explist1(ls);
  816. else
  817. nexps = 0;
  818. adjust_mult_assign(ls, nvars, nexps);
  819. adjustlocalvars(ls, nvars);
  820. }
  821. static int funcname (LexState *ls, expdesc *v) {
  822. /* funcname -> NAME {'.' NAME} [':' NAME] */
  823. int needself = 0;
  824. singlevar(ls, str_checkname(ls), v);
  825. while (ls->t.token == '.') {
  826. next(ls);
  827. luaK_tostack(ls, v, 1);
  828. luaK_kstr(ls, checkname(ls));
  829. v->k = VINDEXED;
  830. }
  831. if (ls->t.token == ':') {
  832. needself = 1;
  833. next(ls);
  834. luaK_tostack(ls, v, 1);
  835. luaK_kstr(ls, checkname(ls));
  836. v->k = VINDEXED;
  837. }
  838. return needself;
  839. }
  840. static void funcstat (LexState *ls, int line) {
  841. /* funcstat -> FUNCTION funcname body */
  842. int needself;
  843. expdesc v;
  844. next(ls); /* skip FUNCTION */
  845. needself = funcname(ls, &v);
  846. body(ls, needself, line);
  847. luaK_storevar(ls, &v);
  848. }
  849. static void namestat (LexState *ls) {
  850. /* stat -> func | ['%'] NAME assignment */
  851. FuncState *fs = ls->fs;
  852. expdesc v;
  853. var_or_func(ls, &v);
  854. if (v.k == VEXP) { /* stat -> func */
  855. check_condition(ls, luaK_lastisopen(fs), "syntax error"); /* an upvalue? */
  856. luaK_setcallreturns(fs, 0); /* call statement uses no results */
  857. }
  858. else { /* stat -> ['%'] NAME assignment */
  859. int left = assignment(ls, &v, 1);
  860. luaK_adjuststack(fs, left); /* remove eventual garbage left on stack */
  861. }
  862. }
  863. static void retstat (LexState *ls) {
  864. /* stat -> RETURN explist */
  865. FuncState *fs = ls->fs;
  866. next(ls); /* skip RETURN */
  867. if (!block_follow(ls->t.token) && ls->t.token != ';')
  868. explist1(ls); /* optional return values */
  869. luaK_code1(fs, OP_RETURN, ls->fs->nactloc);
  870. fs->stacklevel = fs->nactloc; /* removes all temp values */
  871. }
  872. static void breakstat (LexState *ls) {
  873. /* stat -> BREAK [NAME] */
  874. FuncState *fs = ls->fs;
  875. int currentlevel = fs->stacklevel;
  876. Breaklabel *bl = fs->bl;
  877. if (!bl)
  878. luaK_error(ls, "no loop to break");
  879. next(ls); /* skip BREAK */
  880. luaK_adjuststack(fs, currentlevel - bl->stacklevel);
  881. luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
  882. /* correct stack for compiler and symbolic execution */
  883. luaK_adjuststack(fs, bl->stacklevel - currentlevel);
  884. }
  885. static int stat (LexState *ls) {
  886. int line = ls->linenumber; /* may be needed for error messages */
  887. switch (ls->t.token) {
  888. case TK_IF: { /* stat -> ifstat */
  889. ifstat(ls, line);
  890. return 0;
  891. }
  892. case TK_WHILE: { /* stat -> whilestat */
  893. whilestat(ls, line);
  894. return 0;
  895. }
  896. case TK_DO: { /* stat -> DO block END */
  897. next(ls); /* skip DO */
  898. block(ls);
  899. check_match(ls, TK_END, TK_DO, line);
  900. return 0;
  901. }
  902. case TK_FOR: { /* stat -> forstat */
  903. forstat(ls, line);
  904. return 0;
  905. }
  906. case TK_REPEAT: { /* stat -> repeatstat */
  907. repeatstat(ls, line);
  908. return 0;
  909. }
  910. case TK_FUNCTION: { /* stat -> funcstat */
  911. funcstat(ls, line);
  912. return 0;
  913. }
  914. case TK_LOCAL: { /* stat -> localstat */
  915. localstat(ls);
  916. return 0;
  917. }
  918. case TK_NAME: case '%': { /* stat -> namestat */
  919. namestat(ls);
  920. return 0;
  921. }
  922. case TK_RETURN: { /* stat -> retstat */
  923. retstat(ls);
  924. return 1; /* must be last statement */
  925. }
  926. case TK_BREAK: { /* stat -> breakstat */
  927. breakstat(ls);
  928. return 1; /* must be last statement */
  929. }
  930. default: {
  931. luaK_error(ls, "<statement> expected");
  932. return 0; /* to avoid warnings */
  933. }
  934. }
  935. }
  936. static void parlist (LexState *ls) {
  937. /* parlist -> [ param { ',' param } ] */
  938. int nparams = 0;
  939. int dots = 0;
  940. if (ls->t.token != ')') { /* is `parlist' not empty? */
  941. do {
  942. switch (ls->t.token) {
  943. case TK_DOTS: next(ls); dots = 1; break;
  944. case TK_NAME: new_localvar(ls, str_checkname(ls), nparams++); break;
  945. default: luaK_error(ls, "<name> or `...' expected");
  946. }
  947. } while (!dots && optional(ls, ','));
  948. }
  949. code_params(ls, nparams, dots);
  950. }
  951. static void body (LexState *ls, int needself, int line) {
  952. /* body -> '(' parlist ')' chunk END */
  953. FuncState new_fs;
  954. open_func(ls, &new_fs);
  955. new_fs.f->lineDefined = line;
  956. check(ls, '(');
  957. if (needself) {
  958. new_localvarstr(ls, "self", 0);
  959. adjustlocalvars(ls, 1);
  960. }
  961. parlist(ls);
  962. check(ls, ')');
  963. chunk(ls);
  964. check_match(ls, TK_END, TK_FUNCTION, line);
  965. close_func(ls);
  966. pushclosure(ls, &new_fs);
  967. }
  968. /* }====================================================================== */
  969. static void chunk (LexState *ls) {
  970. /* chunk -> { stat [';'] } */
  971. int islast = 0;
  972. while (!islast && !block_follow(ls->t.token)) {
  973. islast = stat(ls);
  974. optional(ls, ';');
  975. lua_assert(ls->fs->stacklevel == ls->fs->nactloc);
  976. }
  977. }