lparser.c 29 KB

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