interp.rs 28 KB

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