interp.rs 30 KB

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