interp.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. use crate::ast::*;
  2. use crate::errors::MatzoError;
  3. use crate::lexer;
  4. use crate::lexer::Span;
  5. use crate::rand::*;
  6. use anyhow::{anyhow, bail, Error};
  7. use std::cell::RefCell;
  8. use std::collections::HashMap;
  9. use std::fmt;
  10. use std::io;
  11. use std::io::Write;
  12. use std::rc::Rc;
  13. /// A `Value` is a representation of the result of evaluation. Note
  14. /// that a `Value` is a representation of something in _weak head
  15. /// normal form_: i.e. for compound expressions (right now just
  16. /// tuples) it might contain other values but it might contain
  17. /// unevaluated expressions as well.
  18. #[derive(Debug, Clone)]
  19. pub enum Value {
  20. Lit(Literal),
  21. Tup(Vec<Thunk>),
  22. Builtin(BuiltinRef),
  23. Closure(Closure),
  24. Nil,
  25. }
  26. #[derive(Debug, Clone, Copy)]
  27. pub struct BuiltinRef {
  28. name: &'static str,
  29. idx: usize,
  30. }
  31. impl Value {
  32. fn to_string(&self, ast: &ASTArena) -> String {
  33. self.with_str(ast, |s| s.to_string())
  34. }
  35. }
  36. impl Value {
  37. /// Convert this value to a Rust integer, failing otherwise
  38. pub fn as_num(&self, ast: &ASTArena) -> Result<i64, Error> {
  39. match self {
  40. Value::Lit(Literal::Num(n)) => Ok(*n),
  41. _ => self.with_str(ast, |s| bail!("Expected number, got {}", s)),
  42. }
  43. }
  44. /// Convert this value to a Rust string, failing otherwise
  45. pub fn as_str(&self, ast: &ASTArena) -> Result<&str, Error> {
  46. match self {
  47. Value::Lit(Literal::Str(s)) => Ok(s),
  48. _ => self.with_str(ast, |s| bail!("Expected string, got {}", s)),
  49. }
  50. }
  51. /// Convert this value to a Rust slice, failing otherwise
  52. pub fn as_tup(&self, ast: &ASTArena) -> Result<&[Thunk], Error> {
  53. match self {
  54. Value::Tup(vals) => Ok(vals),
  55. _ => self.with_str(ast, |s| bail!("Expected tuple, got {}", s)),
  56. }
  57. }
  58. /// Convert this value to a closure, failing otherwise
  59. pub fn as_closure(&self, ast: &ASTArena) -> Result<&Closure, Error> {
  60. match self {
  61. Value::Closure(closure) => Ok(closure),
  62. _ => self.with_str(ast, |s| bail!("Expected closure, got {}", s)),
  63. }
  64. }
  65. /// Call the provided function with the string representation of
  66. /// this value. Note that this _will not force the value_ if it's
  67. /// not completely forced already: indeed, this can't, since it
  68. /// doesn't have access to the `State`. Unevaluated fragments of
  69. /// the value will be printed as `#<unevaluated>`.
  70. pub fn with_str<U>(&self, ast: &ASTArena, f: impl FnOnce(&str) -> U) -> U {
  71. match self {
  72. Value::Nil => f(""),
  73. Value::Lit(Literal::Str(s)) => f(s),
  74. Value::Lit(Literal::Atom(s)) => f(&ast[s.item].to_string()),
  75. Value::Lit(Literal::Num(n)) => f(&format!("{}", n)),
  76. Value::Tup(values) => {
  77. let mut buf = String::new();
  78. buf.push('<');
  79. for (i, val) in values.iter().enumerate() {
  80. if i > 0 {
  81. buf.push_str(", ");
  82. }
  83. match val {
  84. Thunk::Value(v) => buf.push_str(&v.to_string(ast)),
  85. Thunk::Expr(..) => buf.push_str("#<unevaluated>"),
  86. Thunk::Builtin(func) => buf.push_str(&format!("#<builtin {}>", func.idx)),
  87. }
  88. }
  89. buf.push('>');
  90. f(&buf)
  91. }
  92. Value::Builtin(func) => f(&format!("#<builtin {}>", func.name)),
  93. Value::Closure(_) => f("#<lambda ...>"),
  94. }
  95. }
  96. }
  97. type Callback = Box<dyn Fn(&State, &[ExprRef], &Env) -> Result<Value, Error>>;
  98. /// A representation of a builtin function implemented in Rust. This
  99. /// will be inserted into the global scope under the name provided as
  100. /// `name`.
  101. pub struct BuiltinFunc {
  102. /// The name of the builtin: this is used in error messages, in
  103. /// printing the value (e.g. in the case of `puts some-builtin`),
  104. /// and as the Matzo identifier used for this function.
  105. pub name: &'static str,
  106. /// The callback here is the Rust implementation of the function,
  107. /// where the provided `ExprRef` is the argument to the function.
  108. pub callback: Callback,
  109. }
  110. impl fmt::Debug for BuiltinFunc {
  111. fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
  112. writeln!(fmt, "BuiltinFunc {{ name: {:?}, ... }}", self.name)
  113. }
  114. }
  115. /// The name `Thunk` is a bit of a misnomer here: this is
  116. /// _potentially_ a `Thunk`, but represents anything that can be
  117. /// stored in a variable: it might be an unevaluated expression (along
  118. /// with the environment where it should be evaluated), or it might be
  119. /// a partially- or fully-forced value, or it might be a builtin
  120. /// function.
  121. #[derive(Debug, Clone)]
  122. pub enum Thunk {
  123. Expr(ExprRef, Env),
  124. Value(Value),
  125. Builtin(BuiltinRef),
  126. }
  127. /// An environment is either `None` (i.e. in the root scope) or `Some`
  128. /// of some reference-counted scope (since those scopes might be
  129. /// shared in several places, e.g. as pointers in thunks or closures).
  130. pub type Env = Option<Rc<Scope>>;
  131. /// A `Scope` represents a _non-root_ scope (since the root scope is
  132. /// treated in a special way) and contains a map from variables to
  133. /// `Thunk`s, along with a parent pointer.
  134. #[derive(Debug)]
  135. pub struct Scope {
  136. vars: HashMap<StrRef, Thunk>,
  137. parent: Env,
  138. }
  139. /// A `Closure` is a pointer to the expression that represents a
  140. /// function implementation along with the scope in which it was
  141. /// defined.
  142. ///
  143. /// IMPORTANT INVARIANT: the `func` here should be an `ExprRef` which
  144. /// references a `Func`. The reason we don't copy the `Func` in is
  145. /// because, well, that'd be copying, and we can bypass that, but we
  146. /// have to maintain that invariant explicitly, otherwise we'll panic.
  147. #[derive(Debug, Clone)]
  148. pub struct Closure {
  149. func: ExprRef,
  150. scope: Env,
  151. }
  152. /// A `State` contains all the interpreter state needed to run a
  153. /// `Matzo` program.
  154. pub struct State {
  155. /// An `ASTArena` that contains all the packed information that
  156. /// results from parsing a program.
  157. pub ast: RefCell<ASTArena>,
  158. /// The root scope of the program, which contains all the
  159. /// top-level definitions and builtins.
  160. root_scope: RefCell<HashMap<StrRef, Thunk>>,
  161. /// The set of builtin (i.e. implemented-in-Rust) functions
  162. builtins: Vec<BuiltinFunc>,
  163. /// The thread-local RNG.
  164. rand: RefCell<Box<dyn MatzoRand>>,
  165. /// The instantiated parser used to parse Matzo programs
  166. parser: crate::grammar::StmtsParser,
  167. /// The instantiated parser used to parse Matzo programs
  168. expr_parser: crate::grammar::ExprRefParser,
  169. }
  170. impl Default for State {
  171. fn default() -> State {
  172. Self::new()
  173. }
  174. }
  175. impl State {
  176. /// This initializes a new `State` and adds all the builtin
  177. /// functions to the root scope
  178. fn new_with_rand(rand: Box<dyn MatzoRand>) -> State {
  179. let mut s = State {
  180. root_scope: RefCell::new(HashMap::new()),
  181. rand: RefCell::new(rand),
  182. parser: crate::grammar::StmtsParser::new(),
  183. expr_parser: crate::grammar::ExprRefParser::new(),
  184. ast: RefCell::new(ASTArena::new()),
  185. builtins: Vec::new(),
  186. };
  187. for builtin in crate::builtins::builtins() {
  188. let idx = s.builtins.len();
  189. let sym = s.ast.borrow_mut().add_string(builtin.name);
  190. s.root_scope.borrow_mut().insert(
  191. sym,
  192. Thunk::Builtin(BuiltinRef {
  193. idx,
  194. name: builtin.name,
  195. }),
  196. );
  197. s.builtins.push(builtin);
  198. }
  199. s
  200. }
  201. /// This initializes a new `State` and adds all the builtin
  202. /// functions to the root scope
  203. pub fn new() -> State {
  204. State::new_with_rand(Box::new(DefaultRNG::new()))
  205. }
  206. /// This initializes a new `State` and adds all the builtin
  207. /// functions to the root scope
  208. pub fn new_from_seed(seed: u64) -> State {
  209. State::new_with_rand(Box::new(SeededRNG::from_seed(seed)))
  210. }
  211. /// Get the underlying AST. (This is mostly useful for testing
  212. /// purposes, where we don't want to have a function do the
  213. /// parsing and evaluating for us at the same time.)
  214. pub fn get_ast(&self) -> &RefCell<ASTArena> {
  215. &self.ast
  216. }
  217. /// Look up a `Name` in the provided `Env`. This will result in
  218. /// either a `Thunk` (i.e. the named value) or an error that
  219. /// indicates the missing name.
  220. fn lookup(&self, env: &Env, name: Name) -> Result<Thunk, Error> {
  221. if let Some(env) = env {
  222. if let Some(ne) = env.vars.get(&name.item) {
  223. Ok(ne.clone())
  224. } else {
  225. self.lookup(&env.parent, name)
  226. }
  227. } else {
  228. match self.root_scope.borrow().get(&name.item) {
  229. None => {
  230. let span = self.ast.borrow().get_line(name.file, name.span);
  231. bail!("no such thing: {}\n{}", &self.ast.borrow()[name.item], span)
  232. }
  233. Some(ne) => Ok(ne.clone()),
  234. }
  235. }
  236. }
  237. /// Evaluate this string as a standalone program, writing the
  238. /// results to stdout.
  239. pub fn run(&self, src: &str) -> Result<(), Error> {
  240. let file = self.ast.borrow_mut().add_file(src.to_string());
  241. if let Err(mtz) = self.run_file(src, file) {
  242. let mut buf = String::new();
  243. buf.push_str(&mtz.message);
  244. buf.push('\n');
  245. buf.push_str(&self.ast.borrow().get_line(file, mtz.span));
  246. for ctx in mtz.context {
  247. buf.push('\n');
  248. buf.push_str(&ctx.message);
  249. buf.push_str(&self.ast.borrow().get_line(file, ctx.span));
  250. }
  251. bail!("{}", buf);
  252. }
  253. Ok(())
  254. }
  255. fn run_file(&self, src: &str, file: FileRef) -> Result<(), MatzoError> {
  256. let lexed = crate::lexer::tokens(src);
  257. let stmts = self
  258. .parser
  259. .parse(&mut self.ast.borrow_mut(), file, lexed);
  260. let stmts = stmts
  261. .map_err(MatzoError::from_parse_error)?;
  262. let mut stdout = io::stdout();
  263. for stmt in stmts {
  264. self.execute(&stmt, &mut stdout)
  265. .map_err(|err| MatzoError::new(Span::empty(), format!("{:?}", err)))?;
  266. }
  267. Ok(())
  268. }
  269. /// Evaluate this string as a standalone program, writing the
  270. /// results to the provided writer.
  271. pub fn run_with_writer(&self, src: &str, w: &mut impl std::io::Write) -> Result<(), Error> {
  272. let lexed = crate::lexer::tokens(src);
  273. let file = self.ast.borrow_mut().add_file(src.to_string());
  274. let stmts = self
  275. .parser
  276. .parse(&mut self.ast.borrow_mut(), file, lexed)
  277. .map_err(|err| anyhow!("Got {:?}", err))?;
  278. for stmt in stmts {
  279. self.execute(&stmt, &mut *w)?;
  280. }
  281. Ok(())
  282. }
  283. /// Evaluate this string as a fragment in a REPL, writing the
  284. /// results to stdout. One way this differs from the standalone
  285. /// program is that it actually tries parsing twice: first it
  286. /// tries parsing the fragment normally, and then if that doesn't
  287. /// work it tries adding a `puts` ahead of it: this is hacky, but
  288. /// it allows the REPL to respond by printing values when someone
  289. /// simply types an expression.
  290. pub fn run_repl(&self, src: &str) -> Result<(), Error> {
  291. let lexed = crate::lexer::tokens(src);
  292. let file = self.ast.borrow_mut().add_file(src.to_string());
  293. let stmts = {
  294. let mut ast = self.ast.borrow_mut();
  295. self.parser.parse(&mut ast, file, lexed)
  296. };
  297. match stmts {
  298. Ok(stmts) => {
  299. for stmt in stmts {
  300. self.execute(&stmt, io::stdout())?;
  301. }
  302. }
  303. Err(err) => {
  304. let lexed = crate::lexer::tokens(src);
  305. let expr = {
  306. let mut ast = self.ast.borrow_mut();
  307. self.expr_parser.parse(&mut ast, file, lexed)
  308. };
  309. if let Ok(expr) = expr {
  310. let val = self.eval(expr, &None)?;
  311. let val = self.force(val)?;
  312. writeln!(io::stdout(), "{}", val.to_string(&self.ast.borrow()))?;
  313. } else {
  314. bail!("{:?}", err);
  315. }
  316. }
  317. };
  318. Ok(())
  319. }
  320. /// Autocomplete this name. This doesn't make use of any
  321. /// contextual information (e.g. like function arguments or
  322. /// `let`-bound names) but instead tries to complete based
  323. /// entirely on the things in root scope.
  324. pub fn autocomplete(&self, fragment: &str, at_beginning: bool) -> Vec<String> {
  325. let mut possibilities = Vec::new();
  326. for name in self.root_scope.borrow().keys() {
  327. if self.ast.borrow()[*name].starts_with(fragment) {
  328. possibilities.push(self.ast.borrow()[*name].to_string());
  329. }
  330. }
  331. if at_beginning && "puts".starts_with(fragment) {
  332. possibilities.push("puts ".to_owned());
  333. }
  334. possibilities
  335. }
  336. /// Execute this statement, writing any output to the provided
  337. /// output writer. Right now, this will always start in root
  338. /// scope: there are no statements within functions.
  339. pub fn execute(&self, stmt: &Stmt, mut output: impl io::Write) -> Result<(), Error> {
  340. match stmt {
  341. // Evaluate the provided expression _all the way_
  342. // (i.e. recurisvely, not to WHNF) and write its
  343. // representation to the output.
  344. Stmt::Puts(expr) => {
  345. let val = self.eval(*expr, &None)?;
  346. let val = self.force(val)?;
  347. writeln!(output, "{}", val.to_string(&self.ast.borrow())).unwrap();
  348. }
  349. // Look up the provided name, and if it's not already
  350. // forced completely, then force it completely and
  351. // re-insert this name with the forced version.
  352. Stmt::Fix(name) => {
  353. let val = match self.lookup(&None, *name)? {
  354. Thunk::Expr(e, env) => self.eval(e, &env)?,
  355. // we need to handle this case in case it's
  356. // already in WHNF (e.g. a tuple whose elements
  357. // are not yet values)
  358. Thunk::Value(v) => v,
  359. // if it's not an expr or val, then our work here
  360. // is done
  361. _ => return Ok(()),
  362. };
  363. let val = self.force(val)?;
  364. self.root_scope
  365. .borrow_mut()
  366. .insert(name.item, Thunk::Value(val));
  367. }
  368. // assign a given expression to a name, forcing it to a
  369. // value if the assignment is `fixed`.
  370. Stmt::Assn(fixed, name, expr) => {
  371. let thunk = if *fixed {
  372. let val = self.eval(*expr, &None)?;
  373. let val = self.force(val)?;
  374. Thunk::Value(val)
  375. } else {
  376. Thunk::Expr(*expr, None)
  377. };
  378. self.root_scope.borrow_mut().insert(name.item, thunk);
  379. }
  380. // assign a simple disjunction of strings to a name,
  381. // forcing it to a value if the assignment is `fixed`.
  382. Stmt::LitAssn(fixed, name, strs) => {
  383. if *fixed {
  384. let choice = &strs[self.rand.borrow_mut().gen_range_usize(0, strs.len())];
  385. let str = self.ast.borrow()[choice.item].to_string();
  386. self.root_scope
  387. .borrow_mut()
  388. .insert(name.item, Thunk::Value(Value::Lit(Literal::Str(str))));
  389. return Ok(());
  390. }
  391. let choices: Vec<Choice> = strs
  392. .iter()
  393. .map(|s| {
  394. let str = self.ast.borrow()[s.item].to_string();
  395. Choice {
  396. weight: None,
  397. value: Located {
  398. file: s.file,
  399. span: s.span,
  400. item: self.ast.borrow_mut().add_expr(Expr::Lit(Literal::Str(str))),
  401. },
  402. }
  403. })
  404. .collect();
  405. let choices = Located {
  406. file: choices.first().unwrap().value.file,
  407. span: Span {
  408. start: choices.first().unwrap().value.span.start,
  409. end: choices.last().unwrap().value.span.end,
  410. },
  411. item: self.ast.borrow_mut().add_expr(Expr::Chc(choices)),
  412. };
  413. self.root_scope
  414. .borrow_mut()
  415. .insert(name.item, Thunk::Expr(choices, None));
  416. }
  417. }
  418. Ok(())
  419. }
  420. /// Given a value, force it recursively.
  421. fn force(&self, val: Value) -> Result<Value, Error> {
  422. match val {
  423. Value::Tup(values) => Ok(Value::Tup(
  424. values
  425. .into_iter()
  426. .map(|t| {
  427. let v = self.hnf(&t)?;
  428. let v = self.force(v)?;
  429. Ok(Thunk::Value(v))
  430. })
  431. .collect::<Result<Vec<Thunk>, Error>>()?,
  432. )),
  433. _ => Ok(val),
  434. }
  435. }
  436. /// Given a thunk, force it to WHNF.
  437. pub fn hnf(&self, thunk: &Thunk) -> Result<Value, Error> {
  438. match thunk {
  439. Thunk::Expr(expr, env) => self.eval(*expr, env),
  440. Thunk::Value(val) => Ok(val.clone()),
  441. Thunk::Builtin(b) => Ok(Value::Builtin(*b)),
  442. }
  443. }
  444. /// Given an `ExprRef` and an environment, fetch that expression
  445. /// and then evalute it in that environment
  446. pub fn eval(&self, expr_ref: ExprRef, env: &Env) -> Result<Value, Error> {
  447. let expr = &self.ast.borrow()[expr_ref.item];
  448. match expr {
  449. // literals should be mostly cheap-ish to copy, so a
  450. // literal evaluates to a `Value` that's a copy of the
  451. // literal
  452. Expr::Lit(l) => Ok(Value::Lit(l.clone())),
  453. // `Nil` evalutes to `Nil`
  454. Expr::Nil => Ok(Value::Nil),
  455. // When a variable is used, we should look it up and
  456. // evaluate it to WHNF
  457. Expr::Var(v) => self.hnf(&self.lookup(env, *v)?),
  458. // for a catenation, we should fully evaluate all the
  459. // expressions, convert them to strings, and concatenate
  460. // them all.
  461. Expr::Cat(cat) => {
  462. // if we ever have a catentation of one, then don't
  463. // bother with the string: just evaluate the
  464. // expression.
  465. if cat.len() == 1 {
  466. self.eval(cat[0], env)
  467. } else {
  468. let mut buf = String::new();
  469. for expr in cat {
  470. let val = self.eval(*expr, env)?;
  471. let val = self.force(val)?;
  472. buf.push_str(&val.to_string(&self.ast.borrow()));
  473. }
  474. Ok(Value::Lit(Literal::Str(buf)))
  475. }
  476. }
  477. // for choices, we should choose one with the appropriate
  478. // frequency and then evaluate it
  479. Expr::Chc(choices) => {
  480. // if we ever have only one choice, well, choose it:
  481. if choices.len() == 1 {
  482. self.eval(choices[0].value, env)
  483. } else {
  484. self.choose(choices, env)
  485. }
  486. }
  487. // for a tuple, we return a tuple of thunks to begin with,
  488. // to make sure that the values contained within are
  489. // appropriately lazy
  490. Expr::Tup(values) => Ok(Value::Tup(
  491. values
  492. .iter()
  493. .map(|v| Thunk::Expr(*v, env.clone()))
  494. .collect::<Vec<Thunk>>(),
  495. )),
  496. // for a range, choose randomly between the start and end
  497. // expressions
  498. Expr::Range(from, to) => {
  499. let from = self.eval(*from, env)?.as_num(&self.ast.borrow())?;
  500. let to = self.eval(*to, env)?.as_num(&self.ast.borrow())?;
  501. Ok(Value::Lit(Literal::Num(
  502. self.rand.borrow_mut().gen_range_i64(from, to + 1),
  503. )))
  504. }
  505. // for a function, return a closure (i.e. the function
  506. // body paired with the current environment)
  507. Expr::Fun(_) => Ok(Value::Closure(Closure {
  508. func: expr_ref,
  509. scope: env.clone(),
  510. })),
  511. // for application, make sure the thing we're applying is
  512. // either a closure (i.e. the result of evaluating a
  513. // function) or a builtin, and then handle it
  514. // appropriately
  515. Expr::Ap(func, vals) => match self.eval(*func, env)? {
  516. Value::Closure(c) => {
  517. let scruts = vals.iter().map(|v| Thunk::Expr(*v, env.clone())).collect();
  518. self.eval_closure(&c, scruts)
  519. }
  520. Value::Builtin(b) => {
  521. let builtin = &self.builtins[b.idx];
  522. (builtin.callback)(self, vals, env)
  523. }
  524. _ => bail!("Bad function: {:?}", func),
  525. },
  526. // for a let-expression, create a new scope, add the new
  527. // name to it (optionally forcing it if `fixed`) and then
  528. // evaluate the body within that scope.
  529. Expr::Let(fixed, name, val, body) => {
  530. let mut new_scope = HashMap::new();
  531. if *fixed {
  532. let val = self.eval(*val, env)?;
  533. let val = self.force(val)?;
  534. new_scope.insert(name.item, Thunk::Value(val));
  535. } else {
  536. new_scope.insert(name.item, Thunk::Expr(*val, env.clone()));
  537. };
  538. let new_scope = Rc::new(Scope {
  539. vars: new_scope,
  540. parent: env.clone(),
  541. });
  542. self.eval(*body, &Some(new_scope))
  543. }
  544. Expr::Case(scrut, _) => {
  545. let closure = Closure {
  546. func: expr_ref,
  547. scope: env.clone(),
  548. };
  549. self.eval_closure(&closure, vec![Thunk::Expr(*scrut, env.clone())])
  550. }
  551. }
  552. }
  553. /// Evaluate a closure as applied to a given argument.
  554. ///
  555. /// There's a very subtle thing going on here: when we apply a
  556. /// closure to an expression, we should evaluate that expression
  557. /// _as far as we need to and no further_. That's why the `scrut`
  558. /// argument here is mutable: to start with, it'll be a
  559. /// `Thunk::Expr`. If the function uses a wildcard or variable
  560. /// match, it'll stay that way, but if we start matching against
  561. /// it, we'll evaluate it at least to WHNF to find out whether it
  562. /// maches, and _sometimes_ a little further.
  563. ///
  564. /// Here's where it gets tricky: we need to maintain that
  565. /// evaluation between branches so that we don't get Schrödinger's
  566. /// patterns. An example where that might work poorly if we're not
  567. /// careful is here:
  568. ///
  569. /// ```ignore
  570. /// {[Foo] => "1"; [Foo] => "2"; _ => "..."}[Foo | Bar]
  571. /// ```
  572. ///
  573. /// It should be impossible to get `"2"` in this case. That means
  574. /// that we need to force the argument _and keep branching against
  575. /// the forced argument_. But we also want the following to still
  576. /// contain non-determinism:
  577. ///
  578. /// ```ignore
  579. /// {[<Foo, x>] => x x "!"; [<Bar, x>] => x x "?"}[<Foo | Bar, "a" | "b">]
  580. /// ```
  581. ///
  582. /// The above program should print one of "aa!", "bb!", "aa?", or
  583. /// "bb?". That means it needs to
  584. /// 1. force the argument first to `<_, _>`, to make sure it's a
  585. /// two-element tuple
  586. /// 2. force the first element of the tuple to `Foo` or `Bar` to
  587. /// discriminate on it, but
  588. /// 3. _not_ force the second element of the tuple, because we
  589. /// want it to vary from invocation to invocation.
  590. ///
  591. /// So the way we do this is, we start by representing the
  592. /// argument as a `Thunk::Expr`, but allow the pattern-matching
  593. /// function to mutably replace it with progressively more
  594. /// evaluated versions of the same expression, and then that's the
  595. /// thing we put into scope in the body of the function.
  596. pub fn eval_closure(&self, closure: &Closure, mut scruts: Vec<Thunk>) -> Result<Value, Error> {
  597. let ast = self.ast.borrow();
  598. let cases = match &ast[closure.func] {
  599. Expr::Fun(cases) => cases,
  600. Expr::Case(_, cases) => cases,
  601. // see the note attached to the definition of `Closure`
  602. _ => bail!("INVARIANT FAILED"),
  603. };
  604. // for each case
  605. 'cases: for c in cases {
  606. // build a set of potential bindings, which `match_pat`
  607. // will update if it finds matching variables
  608. let mut bindings = Vec::new();
  609. if scruts.len() != c.pats.len() {
  610. continue;
  611. }
  612. for (scrut, pat) in scruts.iter_mut().zip(c.pats.iter()) {
  613. if !self.match_pat(pat, scrut, &mut bindings)? {
  614. // if we didn't match, we don't care about any
  615. // bindings we've found: simply skip it
  616. continue 'cases;
  617. }
  618. }
  619. // build a new scope from the bindings discovered
  620. let mut new_scope = HashMap::new();
  621. for (name, binding) in bindings {
  622. new_scope.insert(name.item, binding);
  623. }
  624. let new_scope = Rc::new(Scope {
  625. vars: new_scope,
  626. parent: closure.scope.clone(),
  627. });
  628. // and now evaluate the chosen branch body in the
  629. // newly-created scope
  630. return self.eval(c.expr, &Some(new_scope));
  631. }
  632. // we couldn't find a matching pattern, so throw an error
  633. bail!("No pattern in {:?} matched {:?}", cases, scruts);
  634. }
  635. /// attempt to match the thunk `scrut` against the pattern
  636. /// `pat`. If it matched, then it'll return `Ok(true)`, if it
  637. /// didn't, it'll return `Ok(false)`, and (because it might need
  638. /// to do incremental evaluation to check if the pattern matches)
  639. /// it'll return an error if forcing parts of the expression
  640. /// returns an error. The `bindings` vector will be filled with
  641. /// name-thunk pairs based on the pattern: if this returns
  642. /// `Ok(true)`, then those are the thunks that should be bound to
  643. /// names in the context, but otherwise those bindings can be
  644. /// safely ignored.
  645. fn match_pat(
  646. &self,
  647. pat: &Pat,
  648. scrut: &mut Thunk,
  649. bindings: &mut Vec<(Name, Thunk)>,
  650. ) -> Result<bool, Error> {
  651. if let Pat::Var(v) = pat {
  652. bindings.push((*v, scrut.clone()));
  653. return Ok(true);
  654. }
  655. if let Pat::Wildcard = pat {
  656. return Ok(true);
  657. }
  658. // if it's not just a variable, then we'll need to make sure
  659. // we've evaluated `scrut` at least one level from here
  660. if let Thunk::Expr(e, env) = scrut {
  661. *scrut = Thunk::Value(self.eval(*e, env)?)
  662. };
  663. // now we can match deeper patterns, at least a little
  664. match pat {
  665. // literals match if the thunk is an identical literal
  666. Pat::Lit(lhs) => {
  667. if let Thunk::Value(Value::Lit(rhs)) = scrut {
  668. Ok(lhs == rhs)
  669. } else {
  670. Ok(false)
  671. }
  672. }
  673. // tuples match if the thunk evaluates to a tuple of the
  674. // same size, and if all the patterns in the tuple match
  675. // the thunks in the expression
  676. Pat::Tup(pats) => {
  677. if let Thunk::Value(Value::Tup(thunks)) = scrut {
  678. if pats.len() != thunks.len() {
  679. return Ok(false);
  680. }
  681. for (p, t) in pats.iter().zip(thunks) {
  682. if !self.match_pat(p, t, bindings)? {
  683. return Ok(false);
  684. }
  685. }
  686. Ok(true)
  687. } else {
  688. Ok(false)
  689. }
  690. }
  691. // otherwise, Does Not Match
  692. _ => Ok(false),
  693. }
  694. }
  695. // this chooses an expressino from a choice, taking into account
  696. // the weights
  697. fn choose(&self, choices: &[Choice], env: &Env) -> Result<Value, Error> {
  698. let max = choices.iter().map(Choice::weight).sum();
  699. let mut choice = self.rand.borrow_mut().gen_range_i64(0, max);
  700. for ch in choices {
  701. if choice < ch.weight() {
  702. return self.eval(ch.value, env);
  703. }
  704. choice -= ch.weight();
  705. }
  706. // if we got here, it means our math was wrong
  707. bail!("unreachable")
  708. }
  709. }