lparser.c 29 KB

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