interp.rs 30 KB

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