interp.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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(&ast[s.item].to_string()),
  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: Box<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<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. let sym = s.ast.borrow_mut().add_string(&builtin.name);
  186. s.root_scope
  187. .borrow_mut()
  188. .insert(sym, Thunk::Builtin(BuiltinRef { idx }));
  189. s.builtins.push(builtin);
  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. let sym = s.ast.borrow_mut().add_string(&builtin.name);
  207. s.root_scope
  208. .borrow_mut()
  209. .insert(sym, Thunk::Builtin(BuiltinRef { idx }));
  210. s.builtins.push(builtin);
  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
  373. .borrow_mut()
  374. .insert(name.item, Thunk::Value(Value::Lit(Literal::Str(str))));
  375. return Ok(());
  376. }
  377. let choices: Vec<Choice> = strs
  378. .iter()
  379. .map(|s| {
  380. let str = self.ast.borrow()[s.item].to_string();
  381. Choice {
  382. weight: None,
  383. value: Located {
  384. file: s.file,
  385. span: s.span,
  386. item: self.ast.borrow_mut().add_expr(Expr::Lit(Literal::Str(str))),
  387. },
  388. }
  389. })
  390. .collect();
  391. let choices = Located {
  392. file: choices.first().unwrap().value.file,
  393. span: Span {
  394. start: choices.first().unwrap().value.span.start,
  395. end: choices.last().unwrap().value.span.end,
  396. },
  397. item: self.ast.borrow_mut().add_expr(Expr::Chc(choices)),
  398. };
  399. self.root_scope
  400. .borrow_mut()
  401. .insert(name.item, Thunk::Expr(choices, None));
  402. }
  403. }
  404. Ok(())
  405. }
  406. /// Given a value, force it recursively.
  407. fn force(&self, val: Value) -> Result<Value, Error> {
  408. match val {
  409. Value::Tup(values) => Ok(Value::Tup(
  410. values
  411. .into_iter()
  412. .map(|t| {
  413. let v = self.hnf(&t)?;
  414. let v = self.force(v)?;
  415. Ok(Thunk::Value(v))
  416. })
  417. .collect::<Result<Vec<Thunk>, Error>>()?,
  418. )),
  419. _ => Ok(val),
  420. }
  421. }
  422. /// Given a thunk, force it to WHNF.
  423. pub fn hnf(&self, thunk: &Thunk) -> Result<Value, Error> {
  424. match thunk {
  425. Thunk::Expr(expr, env) => self.eval(*expr, env),
  426. Thunk::Value(val) => Ok(val.clone()),
  427. Thunk::Builtin(b) => Ok(Value::Builtin(*b)),
  428. }
  429. }
  430. /// Given an `ExprRef` and an environment, fetch that expression
  431. /// and then evalute it in that environment
  432. pub fn eval(&self, expr_ref: ExprRef, env: &Env) -> Result<Value, Error> {
  433. let expr = &self.ast.borrow()[expr_ref.item];
  434. match expr {
  435. // literals should be mostly cheap-ish to copy, so a
  436. // literal evaluates to a `Value` that's a copy of the
  437. // literal
  438. Expr::Lit(l) => Ok(Value::Lit(l.clone())),
  439. // `Nil` evalutes to `Nil`
  440. Expr::Nil => Ok(Value::Nil),
  441. // When a variable is used, we should look it up and
  442. // evaluate it to WHNF
  443. Expr::Var(v) => self.hnf(&self.lookup(env, *v)?),
  444. // for a catenation, we should fully evaluate all the
  445. // expressions, convert them to strings, and concatenate
  446. // them all.
  447. Expr::Cat(cat) => {
  448. // if we ever have a catentation of one, then don't
  449. // bother with the string: just evaluate the
  450. // expression.
  451. if cat.len() == 1 {
  452. self.eval(cat[0], env)
  453. } else {
  454. let mut buf = String::new();
  455. for expr in cat {
  456. let val = self.eval(*expr, env)?;
  457. let val = self.force(val)?;
  458. buf.push_str(&val.to_string(&self.ast.borrow()));
  459. }
  460. Ok(Value::Lit(Literal::Str(buf)))
  461. }
  462. }
  463. // for choices, we should choose one with the appropriate
  464. // frequency and then evaluate it
  465. Expr::Chc(choices) => {
  466. // if we ever have only one choice, well, choose it:
  467. if choices.len() == 1 {
  468. self.eval(choices[0].value, env)
  469. } else {
  470. self.choose(choices, env)
  471. }
  472. }
  473. // for a tuple, we return a tuple of thunks to begin with,
  474. // to make sure that the values contained within are
  475. // appropriately lazy
  476. Expr::Tup(values) => Ok(Value::Tup(
  477. values
  478. .iter()
  479. .map(|v| Thunk::Expr(*v, env.clone()))
  480. .collect::<Vec<Thunk>>(),
  481. )),
  482. // for a range, choose randomly between the start and end
  483. // expressions
  484. Expr::Range(from, to) => {
  485. let from = self.eval(*from, env)?.as_num(&self.ast.borrow())?;
  486. let to = self.eval(*to, env)?.as_num(&self.ast.borrow())?;
  487. Ok(Value::Lit(Literal::Num(
  488. self.rand.borrow_mut().gen_range_i64(from, to + 1),
  489. )))
  490. }
  491. // for a function, return a closure (i.e. the function
  492. // body paired with the current environment)
  493. Expr::Fun(_) => Ok(Value::Closure(Closure {
  494. func: expr_ref,
  495. scope: env.clone(),
  496. })),
  497. // for application, make sure the thing we're applying is
  498. // either a closure (i.e. the result of evaluating a
  499. // function) or a builtin, and then handle it
  500. // appropriately
  501. Expr::Ap(func, vals) => match self.eval(*func, env)? {
  502. Value::Closure(c) => {
  503. let scruts = vals.iter().map(|v| Thunk::Expr(*v, env.clone())).collect();
  504. self.eval_closure(&c, scruts)
  505. }
  506. Value::Builtin(b) => {
  507. let builtin = &self.builtins[b.idx];
  508. (builtin.callback)(self, vals, env)
  509. }
  510. _ => bail!("Bad function: {:?}", func),
  511. },
  512. // for a let-expression, create a new scope, add the new
  513. // name to it (optionally forcing it if `fixed`) and then
  514. // evaluate the body within that scope.
  515. Expr::Let(fixed, name, val, body) => {
  516. let mut new_scope = HashMap::new();
  517. if *fixed {
  518. let val = self.eval(*val, env)?;
  519. let val = self.force(val)?;
  520. new_scope.insert(name.item, Thunk::Value(val));
  521. } else {
  522. new_scope.insert(name.item, Thunk::Expr(*val, env.clone()));
  523. };
  524. let new_scope = Rc::new(Scope {
  525. vars: new_scope,
  526. parent: env.clone(),
  527. });
  528. self.eval(*body, &Some(new_scope))
  529. }
  530. Expr::Case(scrut, _) => {
  531. let closure = Closure {
  532. func: expr_ref,
  533. scope: env.clone(),
  534. };
  535. self.eval_closure(&closure, vec![Thunk::Expr(*scrut, env.clone())])
  536. }
  537. }
  538. }
  539. /// Evaluate a closure as applied to a given argument.
  540. ///
  541. /// There's a very subtle thing going on here: when we apply a
  542. /// closure to an expression, we should evaluate that expression
  543. /// _as far as we need to and no further_. That's why the `scrut`
  544. /// argument here is mutable: to start with, it'll be a
  545. /// `Thunk::Expr`. If the function uses a wildcard or variable
  546. /// match, it'll stay that way, but if we start matching against
  547. /// it, we'll evaluate it at least to WHNF to find out whether it
  548. /// maches, and _sometimes_ a little further.
  549. ///
  550. /// Here's where it gets tricky: we need to maintain that
  551. /// evaluation between branches so that we don't get Schrödinger's
  552. /// patterns. An example where that might work poorly if we're not
  553. /// careful is here:
  554. ///
  555. /// ```ignore
  556. /// {[Foo] => "1"; [Foo] => "2"; _ => "..."}[Foo | Bar]
  557. /// ```
  558. ///
  559. /// It should be impossible to get `"2"` in this case. That means
  560. /// that we need to force the argument _and keep branching against
  561. /// the forced argument_. But we also want the following to still
  562. /// contain non-determinism:
  563. ///
  564. /// ```ignore
  565. /// {[<Foo, x>] => x x "!"; [<Bar, x>] => x x "?"}[<Foo | Bar, "a" | "b">]
  566. /// ```
  567. ///
  568. /// The above program should print one of "aa!", "bb!", "aa?", or
  569. /// "bb?". That means it needs to
  570. /// 1. force the argument first to `<_, _>`, to make sure it's a
  571. /// two-element tuple
  572. /// 2. force the first element of the tuple to `Foo` or `Bar` to
  573. /// discriminate on it, but
  574. /// 3. _not_ force the second element of the tuple, because we
  575. /// want it to vary from invocation to invocation.
  576. ///
  577. /// So the way we do this is, we start by representing the
  578. /// argument as a `Thunk::Expr`, but allow the pattern-matching
  579. /// function to mutably replace it with progressively more
  580. /// evaluated versions of the same expression, and then that's the
  581. /// thing we put into scope in the body of the function.
  582. pub fn eval_closure(&self, closure: &Closure, mut scruts: Vec<Thunk>) -> Result<Value, Error> {
  583. let ast = self.ast.borrow();
  584. let cases = match &ast[closure.func] {
  585. Expr::Fun(cases) => cases,
  586. Expr::Case(_, cases) => cases,
  587. // see the note attached to the definition of `Closure`
  588. _ => bail!("INVARIANT FAILED"),
  589. };
  590. // for each case
  591. 'cases: for c in cases {
  592. // build a set of potential bindings, which `match_pat`
  593. // will update if it finds matching variables
  594. let mut bindings = Vec::new();
  595. if scruts.len() != c.pats.len() {
  596. continue;
  597. }
  598. for (scrut, pat) in scruts.iter_mut().zip(c.pats.iter()) {
  599. if !self.match_pat(&pat, scrut, &mut bindings)? {
  600. // if we didn't match, we don't care about any
  601. // bindings we've found: simply skip it
  602. continue 'cases;
  603. }
  604. }
  605. // build a new scope from the bindings discovered
  606. let mut new_scope = HashMap::new();
  607. for (name, binding) in bindings {
  608. new_scope.insert(name.item, binding);
  609. }
  610. let new_scope = Rc::new(Scope {
  611. vars: new_scope,
  612. parent: closure.scope.clone(),
  613. });
  614. // and now evaluate the chosen branch body in the
  615. // newly-created scope
  616. return self.eval(c.expr, &Some(new_scope));
  617. }
  618. // we couldn't find a matching pattern, so throw an error
  619. bail!("No pattern in {:?} matched {:?}", cases, scruts);
  620. }
  621. /// attempt to match the thunk `scrut` against the pattern
  622. /// `pat`. If it matched, then it'll return `Ok(true)`, if it
  623. /// didn't, it'll return `Ok(false)`, and (because it might need
  624. /// to do incremental evaluation to check if the pattern matches)
  625. /// it'll return an error if forcing parts of the expression
  626. /// returns an error. The `bindings` vector will be filled with
  627. /// name-thunk pairs based on the pattern: if this returns
  628. /// `Ok(true)`, then those are the thunks that should be bound to
  629. /// names in the context, but otherwise those bindings can be
  630. /// safely ignored.
  631. fn match_pat(
  632. &self,
  633. pat: &Pat,
  634. scrut: &mut Thunk,
  635. bindings: &mut Vec<(Name, Thunk)>,
  636. ) -> Result<bool, Error> {
  637. if let Pat::Var(v) = pat {
  638. bindings.push((*v, scrut.clone()));
  639. return Ok(true);
  640. }
  641. if let Pat::Wildcard = pat {
  642. return Ok(true);
  643. }
  644. // if it's not just a variable, then we'll need to make sure
  645. // we've evaluated `scrut` at least one level from here
  646. if let Thunk::Expr(e, env) = scrut {
  647. *scrut = Thunk::Value(self.eval(*e, env)?)
  648. };
  649. // now we can match deeper patterns, at least a little
  650. match pat {
  651. // literals match if the thunk is an identical literal
  652. Pat::Lit(lhs) => {
  653. if let Thunk::Value(Value::Lit(rhs)) = scrut {
  654. Ok(lhs == rhs)
  655. } else {
  656. Ok(false)
  657. }
  658. }
  659. // tuples match if the thunk evaluates to a tuple of the
  660. // same size, and if all the patterns in the tuple match
  661. // the thunks in the expression
  662. Pat::Tup(pats) => {
  663. if let Thunk::Value(Value::Tup(thunks)) = scrut {
  664. if pats.len() != thunks.len() {
  665. return Ok(false);
  666. }
  667. for (p, t) in pats.iter().zip(thunks) {
  668. if !self.match_pat(p, t, bindings)? {
  669. return Ok(false);
  670. }
  671. }
  672. Ok(true)
  673. } else {
  674. Ok(false)
  675. }
  676. }
  677. // otherwise, Does Not Match
  678. _ => Ok(false),
  679. }
  680. }
  681. // this chooses an expressino from a choice, taking into account
  682. // the weights
  683. fn choose(&self, choices: &[Choice], env: &Env) -> Result<Value, Error> {
  684. let max = choices.iter().map(Choice::weight).sum();
  685. let mut choice = self.rand.borrow_mut().gen_range_i64(0, max);
  686. for ch in choices {
  687. if choice < ch.weight() {
  688. return self.eval(ch.value, env);
  689. }
  690. choice -= ch.weight();
  691. }
  692. // if we got here, it means our math was wrong
  693. bail!("unreachable")
  694. }
  695. }