interp.rs 29 KB

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