lparser.c 32 KB

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