interp.rs 28 KB

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