lparser.c 27 KB

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