interp.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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. type Callback = Box<dyn Fn(&State, &[ExprRef], &Env) -> Result<Value, Error>>;
  95. /// A representation of a builtin function implemented in Rust. This
  96. /// will be inserted into the global scope under the name provided as
  97. /// `name`.
  98. pub struct BuiltinFunc {
  99. /// The name of the builtin: this is used in error messages, in
  100. /// printing the value (e.g. in the case of `puts some-builtin`),
  101. /// and as the Matzo identifier used for this function.
  102. pub name: &'static str,
  103. /// The callback here is the Rust implementation of the function,
  104. /// where the provided `ExprRef` is the argument to the function.
  105. pub callback: Callback,
  106. }
  107. impl fmt::Debug for BuiltinFunc {
  108. fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
  109. writeln!(fmt, "BuiltinFunc {{ name: {:?}, ... }}", self.name)
  110. }
  111. }
  112. /// The name `Thunk` is a bit of a misnomer here: this is
  113. /// _potentially_ a `Thunk`, but represents anything that can be
  114. /// stored in a variable: it might be an unevaluated expression (along
  115. /// with the environment where it should be evaluated), or it might be
  116. /// a partially- or fully-forced value, or it might be a builtin
  117. /// function.
  118. #[derive(Debug, Clone)]
  119. pub enum Thunk {
  120. Expr(ExprRef, Env),
  121. Value(Value),
  122. Builtin(BuiltinRef),
  123. }
  124. /// An environment is either `None` (i.e. in the root scope) or `Some`
  125. /// of some reference-counted scope (since those scopes might be
  126. /// shared in several places, e.g. as pointers in thunks or closures).
  127. pub type Env = Option<Rc<Scope>>;
  128. /// A `Scope` represents a _non-root_ scope (since the root scope is
  129. /// treated in a special way) and contains a map from variables to
  130. /// `Thunk`s, along with a parent pointer.
  131. #[derive(Debug)]
  132. pub struct Scope {
  133. vars: HashMap<StrRef, Thunk>,
  134. parent: Env,
  135. }
  136. /// A `Closure` is a pointer to the expression that represents a
  137. /// function implementation along with the scope in which it was
  138. /// defined.
  139. ///
  140. /// IMPORTANT INVARIANT: the `func` here should be an `ExprRef` which
  141. /// references a `Func`. The reason we don't copy the `Func` in is
  142. /// because, well, that'd be copying, and we can bypass that, but we
  143. /// have to maintain that invariant explicitly, otherwise we'll panic.
  144. #[derive(Debug, Clone)]
  145. pub struct Closure {
  146. func: ExprRef,
  147. scope: Env,
  148. }
  149. /// A `State` contains all the interpreter state needed to run a
  150. /// `Matzo` program.
  151. pub struct State {
  152. /// An `ASTArena` that contains all the packed information that
  153. /// results from parsing a program.
  154. pub ast: RefCell<ASTArena>,
  155. /// The root scope of the program, which contains all the
  156. /// top-level definitions and builtins.
  157. root_scope: RefCell<HashMap<StrRef, Thunk>>,
  158. /// The set of builtin (i.e. implemented-in-Rust) functions
  159. builtins: Vec<BuiltinFunc>,
  160. /// The thread-local RNG.
  161. rand: RefCell<Box<dyn MatzoRand>>,
  162. /// The instantiated parser used to parse Matzo programs
  163. parser: crate::grammar::StmtsParser,
  164. /// The instantiated parser used to parse Matzo programs
  165. expr_parser: crate::grammar::ExprRefParser,
  166. }
  167. impl Default for State {
  168. fn default() -> State {
  169. Self::new()
  170. }
  171. }
  172. impl State {
  173. /// This initializes a new `State` and adds all the builtin
  174. /// functions to the root scope
  175. pub fn new() -> State {
  176. let mut s = State {
  177. root_scope: RefCell::new(HashMap::new()),
  178. rand: RefCell::new(Box::new(DefaultRNG::new())),
  179. parser: crate::grammar::StmtsParser::new(),
  180. expr_parser: crate::grammar::ExprRefParser::new(),
  181. ast: RefCell::new(ASTArena::new()),
  182. builtins: Vec::new(),
  183. };
  184. for builtin in crate::builtins::builtins() {
  185. let idx = s.builtins.len();
  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. s.builtins.push(builtin);
  191. }
  192. s
  193. }
  194. /// This initializes a new `State` and adds all the builtin
  195. /// functions to the root scope
  196. pub fn new_from_seed(seed: u64) -> State {
  197. let mut s = State {
  198. root_scope: RefCell::new(HashMap::new()),
  199. rand: RefCell::new(Box::new(SeededRNG::from_seed(seed))),
  200. parser: crate::grammar::StmtsParser::new(),
  201. expr_parser: crate::grammar::ExprRefParser::new(),
  202. ast: RefCell::new(ASTArena::new()),
  203. builtins: Vec::new(),
  204. };
  205. for builtin in crate::builtins::builtins() {
  206. let idx = s.builtins.len();
  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. s.builtins.push(builtin);
  212. }
  213. s
  214. }
  215. /// Get the underlying AST. (This is mostly useful for testing
  216. /// purposes, where we don't want to have a function do the
  217. /// parsing and evaluating for us at the same time.)
  218. pub fn get_ast(&self) -> &RefCell<ASTArena> {
  219. &self.ast
  220. }
  221. /// Look up a `Name` in the provided `Env`. This will result in
  222. /// either a `Thunk` (i.e. the named value) or an error that
  223. /// indicates the missing name.
  224. fn lookup(&self, env: &Env, name: Name) -> Result<Thunk, Error> {
  225. if let Some(env) = env {
  226. if let Some(ne) = env.vars.get(&name.item) {
  227. Ok(ne.clone())
  228. } else {
  229. self.lookup(&env.parent, name)
  230. }
  231. } else {
  232. match self.root_scope.borrow().get(&name.item) {
  233. None => {
  234. let span = self.ast.borrow().get_line(name.file, name.span);
  235. bail!("no such thing: {}\n{}", &self.ast.borrow()[name.item], span)
  236. }
  237. Some(ne) => Ok(ne.clone()),
  238. }
  239. }
  240. }
  241. /// Evaluate this string as a standalone program, writing the
  242. /// results to stdout.
  243. pub fn run(&self, src: &str) -> Result<(), Error> {
  244. let lexed = crate::lexer::tokens(src);
  245. let file = self.ast.borrow_mut().add_file(src.to_string());
  246. let stmts = self
  247. .parser
  248. .parse(&mut self.ast.borrow_mut(), file, lexed)
  249. .map_err(|err| anyhow!("Got {:?}", err))?;
  250. let mut stdout = io::stdout();
  251. for stmt in stmts {
  252. self.execute(&stmt, &mut stdout)?;
  253. }
  254. Ok(())
  255. }
  256. /// Evaluate this string as a standalone program, writing the
  257. /// results to the provided writer.
  258. pub fn run_with_writer(&self, src: &str, w: &mut impl std::io::Write) -> Result<(), Error> {
  259. let lexed = crate::lexer::tokens(src);
  260. let file = self.ast.borrow_mut().add_file(src.to_string());
  261. let stmts = self
  262. .parser
  263. .parse(&mut self.ast.borrow_mut(), file, lexed)
  264. .map_err(|err| anyhow!("Got {:?}", err))?;
  265. for stmt in stmts {
  266. self.execute(&stmt, &mut *w)?;
  267. }
  268. Ok(())
  269. }
  270. /// Evaluate this string as a fragment in a REPL, writing the
  271. /// results to stdout. One way this differs from the standalone
  272. /// program is that it actually tries parsing twice: first it
  273. /// tries parsing the fragment normally, and then if that doesn't
  274. /// work it tries adding a `puts` ahead of it: this is hacky, but
  275. /// it allows the REPL to respond by printing values when someone
  276. /// simply types an expression.
  277. pub fn run_repl(&self, src: &str) -> Result<(), Error> {
  278. let lexed = crate::lexer::tokens(src);
  279. let file = self.ast.borrow_mut().add_file(src.to_string());
  280. let stmts = {
  281. let mut ast = self.ast.borrow_mut();
  282. self.parser.parse(&mut ast, file, lexed)
  283. };
  284. match stmts {
  285. Ok(stmts) => {
  286. for stmt in stmts {
  287. self.execute(&stmt, io::stdout())?;
  288. }
  289. }
  290. Err(err) => {
  291. let lexed = crate::lexer::tokens(src);
  292. let expr = {
  293. let mut ast = self.ast.borrow_mut();
  294. self.expr_parser.parse(&mut ast, file, lexed)
  295. };
  296. if let Ok(expr) = expr {
  297. let val = self.eval(expr, &None)?;
  298. let val = self.force(val)?;
  299. writeln!(io::stdout(), "{}", val.to_string(&self.ast.borrow()))?;
  300. } else {
  301. bail!("{:?}", err);
  302. }
  303. }
  304. };
  305. Ok(())
  306. }
  307. /// Autocomplete this name. This doesn't make use of any
  308. /// contextual information (e.g. like function arguments or
  309. /// `let`-bound names) but instead tries to complete based
  310. /// entirely on the things in root scope.
  311. pub fn autocomplete(&self, fragment: &str, at_beginning: bool) -> Vec<String> {
  312. let mut possibilities = Vec::new();
  313. for name in self.root_scope.borrow().keys() {
  314. if self.ast.borrow()[*name].starts_with(fragment) {
  315. possibilities.push(self.ast.borrow()[*name].to_string());
  316. }
  317. }
  318. if at_beginning && "puts".starts_with(fragment) {
  319. possibilities.push("puts ".to_owned());
  320. }
  321. possibilities
  322. }
  323. /// Execute this statement, writing any output to the provided
  324. /// output writer. Right now, this will always start in root
  325. /// scope: there are no statements within functions.
  326. pub fn execute(&self, stmt: &Stmt, mut output: impl io::Write) -> Result<(), Error> {
  327. match stmt {
  328. // Evaluate the provided expression _all the way_
  329. // (i.e. recurisvely, not to WHNF) and write its
  330. // representation to the output.
  331. Stmt::Puts(expr) => {
  332. let val = self.eval(*expr, &None)?;
  333. let val = self.force(val)?;
  334. writeln!(output, "{}", val.to_string(&self.ast.borrow())).unwrap();
  335. }
  336. // Look up the provided name, and if it's not already
  337. // forced completely, then force it completely and
  338. // re-insert this name with the forced version.
  339. Stmt::Fix(name) => {
  340. let val = match self.lookup(&None, *name)? {
  341. Thunk::Expr(e, env) => self.eval(e, &env)?,
  342. // we need to handle this case in case it's
  343. // already in WHNF (e.g. a tuple whose elements
  344. // are not yet values)
  345. Thunk::Value(v) => v,
  346. // if it's not an expr or val, then our work here
  347. // is done
  348. _ => return Ok(()),
  349. };
  350. let val = self.force(val)?;
  351. self.root_scope
  352. .borrow_mut()
  353. .insert(name.item, Thunk::Value(val));
  354. }
  355. // assign a given expression to a name, forcing it to a
  356. // value if the assignment is `fixed`.
  357. Stmt::Assn(fixed, name, expr) => {
  358. let thunk = if *fixed {
  359. let val = self.eval(*expr, &None)?;
  360. let val = self.force(val)?;
  361. Thunk::Value(val)
  362. } else {
  363. Thunk::Expr(*expr, None)
  364. };
  365. self.root_scope.borrow_mut().insert(name.item, thunk);
  366. }
  367. // assign a simple disjunction of strings to a name,
  368. // forcing it to a value if the assignment is `fixed`.
  369. Stmt::LitAssn(fixed, name, strs) => {
  370. if *fixed {
  371. let choice = &strs[self.rand.borrow_mut().gen_range_usize(0, strs.len())];
  372. let str = self.ast.borrow()[choice.item].to_string();
  373. self.root_scope
  374. .borrow_mut()
  375. .insert(name.item, Thunk::Value(Value::Lit(Literal::Str(str))));
  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, vals) => match self.eval(*func, env)? {
  503. Value::Closure(c) => {
  504. let scruts = vals.iter().map(|v| Thunk::Expr(*v, env.clone())).collect();
  505. self.eval_closure(&c, scruts)
  506. }
  507. Value::Builtin(b) => {
  508. let builtin = &self.builtins[b.idx];
  509. (builtin.callback)(self, vals, 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, vec![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 scruts: Vec<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. 'cases: 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 scruts.len() != c.pats.len() {
  597. continue;
  598. }
  599. for (scrut, pat) in scruts.iter_mut().zip(c.pats.iter()) {
  600. if !self.match_pat(pat, scrut, &mut bindings)? {
  601. // if we didn't match, we don't care about any
  602. // bindings we've found: simply skip it
  603. continue 'cases;
  604. }
  605. }
  606. // build a new scope from the bindings discovered
  607. let mut new_scope = HashMap::new();
  608. for (name, binding) in bindings {
  609. new_scope.insert(name.item, binding);
  610. }
  611. let new_scope = Rc::new(Scope {
  612. vars: new_scope,
  613. parent: closure.scope.clone(),
  614. });
  615. // and now evaluate the chosen branch body in the
  616. // newly-created scope
  617. return self.eval(c.expr, &Some(new_scope));
  618. }
  619. // we couldn't find a matching pattern, so throw an error
  620. bail!("No pattern in {:?} matched {:?}", cases, scruts);
  621. }
  622. /// attempt to match the thunk `scrut` against the pattern
  623. /// `pat`. If it matched, then it'll return `Ok(true)`, if it
  624. /// didn't, it'll return `Ok(false)`, and (because it might need
  625. /// to do incremental evaluation to check if the pattern matches)
  626. /// it'll return an error if forcing parts of the expression
  627. /// returns an error. The `bindings` vector will be filled with
  628. /// name-thunk pairs based on the pattern: if this returns
  629. /// `Ok(true)`, then those are the thunks that should be bound to
  630. /// names in the context, but otherwise those bindings can be
  631. /// safely ignored.
  632. fn match_pat(
  633. &self,
  634. pat: &Pat,
  635. scrut: &mut Thunk,
  636. bindings: &mut Vec<(Name, Thunk)>,
  637. ) -> Result<bool, Error> {
  638. if let Pat::Var(v) = pat {
  639. bindings.push((*v, scrut.clone()));
  640. return Ok(true);
  641. }
  642. if let Pat::Wildcard = pat {
  643. return Ok(true);
  644. }
  645. // if it's not just a variable, then we'll need to make sure
  646. // we've evaluated `scrut` at least one level from here
  647. if let Thunk::Expr(e, env) = scrut {
  648. *scrut = Thunk::Value(self.eval(*e, env)?)
  649. };
  650. // now we can match deeper patterns, at least a little
  651. match pat {
  652. // literals match if the thunk is an identical literal
  653. Pat::Lit(lhs) => {
  654. if let Thunk::Value(Value::Lit(rhs)) = scrut {
  655. Ok(lhs == rhs)
  656. } else {
  657. Ok(false)
  658. }
  659. }
  660. // tuples match if the thunk evaluates to a tuple of the
  661. // same size, and if all the patterns in the tuple match
  662. // the thunks in the expression
  663. Pat::Tup(pats) => {
  664. if let Thunk::Value(Value::Tup(thunks)) = scrut {
  665. if pats.len() != thunks.len() {
  666. return Ok(false);
  667. }
  668. for (p, t) in pats.iter().zip(thunks) {
  669. if !self.match_pat(p, t, bindings)? {
  670. return Ok(false);
  671. }
  672. }
  673. Ok(true)
  674. } else {
  675. Ok(false)
  676. }
  677. }
  678. // otherwise, Does Not Match
  679. _ => Ok(false),
  680. }
  681. }
  682. // this chooses an expressino from a choice, taking into account
  683. // the weights
  684. fn choose(&self, choices: &[Choice], env: &Env) -> Result<Value, Error> {
  685. let max = choices.iter().map(Choice::weight).sum();
  686. let mut choice = self.rand.borrow_mut().gen_range_i64(0, max);
  687. for ch in choices {
  688. if choice < ch.weight() {
  689. return self.eval(ch.value, env);
  690. }
  691. choice -= ch.weight();
  692. }
  693. // if we got here, it means our math was wrong
  694. bail!("unreachable")
  695. }
  696. }