interp.rs 28 KB

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