ombre: Implement simple module system for lisp
b8116e9601fa6e4e5df48fc63a529d6bf1cea2fb
1 parent
0e3fdcfc
ombre/src/lisp/evaluator.rs
+192 -34
| 1 | 1 | //! Expression evaluator. |
|
| 2 | 2 | use std::cell::RefCell; |
|
| 3 | + | use std::collections::HashSet; |
|
| 3 | 4 | use std::fmt; |
|
| 4 | 5 | use std::ops::{Deref, DerefMut}; |
|
| 5 | 6 | use std::rc::Rc; |
|
| 6 | 7 | use std::result; |
|
| 7 | 8 | use std::{collections::HashMap, iter::Peekable}; |
| 19 | 20 | pub enum Error { |
|
| 20 | 21 | /// Error coming from parsing stage. |
|
| 21 | 22 | Parser(Box<dyn std::error::Error>), |
|
| 22 | 23 | /// Undefined symbol. |
|
| 23 | 24 | UndefinedSymbol(Symbol), |
|
| 25 | + | /// Module not found when importing. |
|
| 26 | + | ModuleNotFound(Symbol), |
|
| 24 | 27 | /// Expected value of a certain type. |
|
| 25 | 28 | ExpectedValue(&'static str), |
|
| 26 | 29 | /// Expected value for named argument. |
|
| 27 | 30 | ExpectedNamedValue(Symbol), |
|
| 28 | 31 | /// Unexpected value. |
| 45 | 48 | impl fmt::Display for Error { |
|
| 46 | 49 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
|
| 47 | 50 | match self { |
|
| 48 | 51 | Error::Parser(e) => write!(f, "parser: {e}"), |
|
| 49 | 52 | Error::UndefinedSymbol(s) => write!(f, "undefined symbol: {s}"), |
|
| 53 | + | Error::ModuleNotFound(s) => write!(f, "module not found: {s}"), |
|
| 50 | 54 | Error::ExpectedValue(s) => write!(f, "expected value: {s}"), |
|
| 51 | 55 | Error::ExpectedNamedValue(s) => write!(f, "expected named value: {s}"), |
|
| 52 | 56 | Error::UnexpectedValue(e) => write!(f, "unexpected value: {e:?}"), |
|
| 53 | 57 | Error::UnexpectedNamedArgument(s) => write!(f, "unexpected named argument: {s}"), |
|
| 54 | 58 | Error::WrongArgumentCount { expected, actual } => { |
| 95 | 99 | }; |
|
| 96 | 100 | Ok(key) |
|
| 97 | 101 | } |
|
| 98 | 102 | } |
|
| 99 | 103 | ||
| 104 | + | /// A code module. Defines a namespace with bindings that can be imported. |
|
| 105 | + | #[derive(Debug, Clone, PartialEq)] |
|
| 106 | + | pub struct Module { |
|
| 107 | + | name: Symbol, |
|
| 108 | + | docstr: Option<String>, |
|
| 109 | + | env: Env<'static>, |
|
| 110 | + | } |
|
| 111 | + | ||
| 112 | + | /// The global module registry. |
|
| 113 | + | #[derive(Debug, Clone, PartialEq, Default)] |
|
| 114 | + | pub struct ModuleRegistry { |
|
| 115 | + | modules: HashMap<Symbol, Module>, |
|
| 116 | + | } |
|
| 117 | + | ||
| 118 | + | impl ModuleRegistry { |
|
| 119 | + | /// Lookup a module in the registry. |
|
| 120 | + | fn lookup(&self, name: &Symbol) -> Option<&Module> { |
|
| 121 | + | self.modules.get(name) |
|
| 122 | + | } |
|
| 123 | + | ||
| 124 | + | /// Register a new module. |
|
| 125 | + | fn register(&mut self, name: Symbol, module: Module) { |
|
| 126 | + | self.modules.insert(name, module); |
|
| 127 | + | } |
|
| 128 | + | } |
|
| 129 | + | ||
| 100 | 130 | /// Expression in the language. |
|
| 101 | 131 | #[derive(Debug, Clone, PartialEq)] |
|
| 102 | 132 | pub enum Expr { |
|
| 103 | 133 | /// Eg. (1 2 3) |
|
| 104 | 134 | List(List<Expr>), |
| 250 | 280 | Expr::Function(Function::Closure(f.clone())), |
|
| 251 | 281 | )]) |
|
| 252 | 282 | } else { |
|
| 253 | 283 | HashMap::new() |
|
| 254 | 284 | }, |
|
| 285 | + | exports: HashSet::new(), |
|
| 255 | 286 | docs: HashMap::new(), |
|
| 256 | 287 | parent: None, |
|
| 257 | 288 | }; |
|
| 258 | 289 | let result = f.call(args, &env)?; |
|
| 259 | 290 |
| 337 | 368 | } |
|
| 338 | 369 | ||
| 339 | 370 | let mut env = Env { |
|
| 340 | 371 | local, |
|
| 341 | 372 | docs: HashMap::new(), |
|
| 373 | + | exports: HashSet::new(), |
|
| 342 | 374 | parent: Some(env), |
|
| 343 | 375 | }; |
|
| 344 | 376 | eval_iter(self.body.clone(), &mut env) |
|
| 345 | 377 | } |
|
| 346 | 378 | } |
| 376 | 408 | local: HashMap<Symbol, Expr>, |
|
| 377 | 409 | /// Docstrings for bindings. |
|
| 378 | 410 | docs: HashMap<Symbol, String>, |
|
| 379 | 411 | /// Parent environment. |
|
| 380 | 412 | parent: Option<&'a Env<'a>>, |
|
| 413 | + | /// Exported bindings. |
|
| 414 | + | exports: HashSet<Symbol>, |
|
| 381 | 415 | } |
|
| 382 | 416 | ||
| 383 | 417 | impl<'a> Env<'a> { |
|
| 384 | 418 | /// Add intrinsics to this evaluator. Returns a new evaluator with the specified |
|
| 385 | 419 | /// intrinsics. |
| 406 | 440 | } |
|
| 407 | 441 | None |
|
| 408 | 442 | } |
|
| 409 | 443 | ||
| 410 | 444 | /// Get the docstring for a symbol. |
|
| 411 | - | #[allow(dead_code)] |
|
| 412 | 445 | pub fn lookup_doc(&self, name: &str) -> Option<&str> { |
|
| 413 | 446 | self.docs |
|
| 414 | 447 | .get(name) |
|
| 415 | 448 | .map(String::as_str) |
|
| 416 | 449 | .or_else(|| self.parent.and_then(|p| p.lookup_doc(name))) |
| 423 | 456 | env.extend(p.flatten()); |
|
| 424 | 457 | } |
|
| 425 | 458 | env |
|
| 426 | 459 | } |
|
| 427 | 460 | ||
| 461 | + | /// Import a module into this environemnt. |
|
| 462 | + | pub fn import(&mut self, module: &Module) { |
|
| 463 | + | let namespace = &module.name; |
|
| 464 | + | for sym in &module.env.exports { |
|
| 465 | + | if let Some(value) = module.env.lookup(sym) { |
|
| 466 | + | let docs = module.env.lookup_doc(sym); |
|
| 467 | + | self.binding(format!("{namespace}/{sym}").as_str(), docs, value.clone()); |
|
| 468 | + | } else { |
|
| 469 | + | panic!("Env::import: missing module binding `{sym}` in module `{namespace}`"); |
|
| 470 | + | } |
|
| 471 | + | } |
|
| 472 | + | } |
|
| 473 | + | ||
| 474 | + | /// Export a binding from this module's environemnt. |
|
| 475 | + | pub fn export(&mut self, binding: Symbol) { |
|
| 476 | + | self.exports.insert(binding); |
|
| 477 | + | } |
|
| 478 | + | ||
| 428 | 479 | /// Define an intrinsic. |
|
| 429 | 480 | pub fn intrinsic( |
|
| 430 | 481 | &mut self, |
|
| 431 | 482 | name: &str, |
|
| 432 | 483 | docstr: &str, |
| 448 | 499 | pub fn from_parent(parent: &'a Env<'_>) -> Env<'a> { |
|
| 449 | 500 | Env { |
|
| 450 | 501 | parent: Some(parent), |
|
| 451 | 502 | local: HashMap::new(), |
|
| 452 | 503 | docs: HashMap::new(), |
|
| 504 | + | exports: HashSet::new(), |
|
| 453 | 505 | } |
|
| 454 | 506 | } |
|
| 455 | 507 | ||
| 456 | 508 | /// Return a new env with the given bindings. |
|
| 457 | 509 | pub fn with(&'a self, kvs: impl IntoIterator<Item = (Symbol, Expr)>) -> Env<'a> { |
|
| 458 | 510 | Env { |
|
| 459 | 511 | local: kvs.into_iter().collect(), |
|
| 460 | 512 | docs: HashMap::new(), |
|
| 461 | 513 | parent: Some(self), |
|
| 514 | + | exports: HashSet::new(), |
|
| 462 | 515 | } |
|
| 463 | 516 | } |
|
| 464 | 517 | } |
|
| 465 | 518 | ||
| 466 | 519 | impl Deref for Env<'_> { |
| 481 | 534 | fn default() -> Self { |
|
| 482 | 535 | let mut env = Env { |
|
| 483 | 536 | local: HashMap::default(), |
|
| 484 | 537 | docs: HashMap::default(), |
|
| 485 | 538 | parent: None, |
|
| 539 | + | exports: HashSet::default(), |
|
| 486 | 540 | }; |
|
| 487 | 541 | env.intrinsic("+", "Add two or more numbers", intrinsic::add); |
|
| 488 | 542 | env.intrinsic( |
|
| 489 | 543 | "-", |
|
| 490 | 544 | "Subtract numbers or negate a single number", |
| 627 | 681 | pub struct Evaluator<T, E> |
|
| 628 | 682 | where |
|
| 629 | 683 | T: IntoIterator<Item = Result<Expr, E>>, |
|
| 630 | 684 | E: std::error::Error + 'static, |
|
| 631 | 685 | { |
|
| 686 | + | modules: ModuleRegistry, |
|
| 632 | 687 | exprs: Peekable<T::IntoIter>, |
|
| 633 | 688 | } |
|
| 634 | 689 | ||
| 635 | 690 | impl<T, E> Evaluator<T, E> |
|
| 636 | 691 | where |
| 638 | 693 | E: std::error::Error + 'static, |
|
| 639 | 694 | { |
|
| 640 | 695 | /// Create a new evaluator. |
|
| 641 | 696 | pub fn new(exprs: T) -> Self { |
|
| 642 | 697 | Self { |
|
| 698 | + | modules: ModuleRegistry::default(), |
|
| 643 | 699 | exprs: exprs.into_iter().peekable(), |
|
| 644 | 700 | } |
|
| 645 | 701 | } |
|
| 646 | 702 | ||
| 647 | 703 | /// Evaluate expressions one by one and return the result of the last one. |
|
| 648 | - | pub fn eval(self, env: &mut Env<'_>) -> Result<Expr, Error> { |
|
| 704 | + | pub fn eval(mut self, env: &mut Env<'_>) -> Result<Expr, Error> { |
|
| 649 | 705 | let mut result = Expr::nil(); |
|
| 650 | 706 | ||
| 651 | 707 | for expr in self.exprs { |
|
| 652 | 708 | let expr = expr.map_err(|e| Error::Parser(Box::new(e)))?; |
|
| 653 | - | result = eval(expr, env)?; |
|
| 709 | + | result = eval_module(expr, env, &mut self.modules)?; |
|
| 654 | 710 | } |
|
| 655 | 711 | Ok(result) |
|
| 656 | 712 | } |
|
| 657 | 713 | } |
|
| 658 | 714 | ||
| 715 | + | /// Evaluate a module definition. Modules can only exist at the root, or at the top level of |
|
| 716 | + | /// another module. |
|
| 717 | + | pub fn eval_module(expr: Expr, env: &mut Env<'_>, mods: &mut ModuleRegistry) -> Result<Expr> { |
|
| 718 | + | let Expr::List(list) = expr else { |
|
| 719 | + | return eval(expr, env); |
|
| 720 | + | }; |
|
| 721 | + | let Some(Expr::Symbol(ref head)) = list.head() else { |
|
| 722 | + | return eval_list(list, env); |
|
| 723 | + | }; |
|
| 724 | + | let tail = list.tail(); |
|
| 725 | + | ||
| 726 | + | match head.deref() { |
|
| 727 | + | "def" => { |
|
| 728 | + | let mut items = tail.iter().cloned(); // TODO: Can we avoid cloning here? |
|
| 729 | + | let sym = items.next().ok_or(Error::ExpectedValue("symbol"))?; |
|
| 730 | + | let Expr::Symbol(name) = sym else { |
|
| 731 | + | return Err(Error::UnexpectedValue(sym)); |
|
| 732 | + | }; |
|
| 733 | + | let (docstr, value) = match (items.next(), items.next()) { |
|
| 734 | + | (Some(Expr::Str(docstr)), Some(value)) => (Some(docstr), value), |
|
| 735 | + | (Some(value), None) => (None, value), |
|
| 736 | + | ||
| 737 | + | _ => return Err(Error::ExpectedValue("expression")), |
|
| 738 | + | }; |
|
| 739 | + | ||
| 740 | + | match eval(value, env)? { |
|
| 741 | + | Expr::Function(Function::Closure(mut closure)) => { |
|
| 742 | + | if closure.name.is_none() { |
|
| 743 | + | if let Some(closure) = Rc::get_mut(&mut closure) { |
|
| 744 | + | closure.name = Some(Rc::clone(&name)); |
|
| 745 | + | } |
|
| 746 | + | } |
|
| 747 | + | env.binding( |
|
| 748 | + | &name, |
|
| 749 | + | docstr.as_deref(), |
|
| 750 | + | Expr::Function(Function::Closure(closure)), |
|
| 751 | + | ); |
|
| 752 | + | } |
|
| 753 | + | other => { |
|
| 754 | + | env.binding(&name, docstr.as_deref(), other); |
|
| 755 | + | } |
|
| 756 | + | } |
|
| 757 | + | Ok(Expr::nil()) |
|
| 758 | + | } |
|
| 759 | + | "module" => { |
|
| 760 | + | let mut items = tail.iter().cloned().peekable(); |
|
| 761 | + | let Some(Expr::Symbol(name)) = items.next() else { |
|
| 762 | + | return Err(Error::ExpectedValue("symbol")); |
|
| 763 | + | }; |
|
| 764 | + | // Get optional doc string. |
|
| 765 | + | let docstr = if let Some(Expr::Str(ref docstr)) = items.peek().cloned() { |
|
| 766 | + | items.next(); |
|
| 767 | + | Some(docstr.to_owned()) |
|
| 768 | + | } else { |
|
| 769 | + | None |
|
| 770 | + | }; |
|
| 771 | + | // Create new env for the module. Modules do not capture their environment. |
|
| 772 | + | let mut env = Env::default(); |
|
| 773 | + | // Evaluate module body. |
|
| 774 | + | for expr in items { |
|
| 775 | + | eval_module(expr, &mut env, mods)?; |
|
| 776 | + | } |
|
| 777 | + | mods.register(name.clone(), Module { name, docstr, env }); |
|
| 778 | + | ||
| 779 | + | Ok(Expr::nil()) |
|
| 780 | + | } |
|
| 781 | + | "import" => { |
|
| 782 | + | let mut items = tail.iter().cloned(); |
|
| 783 | + | let Some(Expr::Symbol(name)) = items.next() else { |
|
| 784 | + | return Err(Error::ExpectedValue("symbol")); |
|
| 785 | + | }; |
|
| 786 | + | let module = mods |
|
| 787 | + | .lookup(&name) |
|
| 788 | + | .ok_or_else(|| Error::ModuleNotFound(name.clone()))?; |
|
| 789 | + | ||
| 790 | + | env.import(module); |
|
| 791 | + | ||
| 792 | + | Ok(Expr::nil()) |
|
| 793 | + | } |
|
| 794 | + | "export" => { |
|
| 795 | + | if tail.is_empty() { |
|
| 796 | + | return Err(Error::WrongArgumentCount { |
|
| 797 | + | expected: 1, |
|
| 798 | + | actual: 0, |
|
| 799 | + | }); |
|
| 800 | + | } |
|
| 801 | + | for s in tail.iter().cloned() { |
|
| 802 | + | let Expr::Symbol(s) = s else { |
|
| 803 | + | return Err(Error::UnexpectedValue(s)); |
|
| 804 | + | }; |
|
| 805 | + | env.export(s); |
|
| 806 | + | } |
|
| 807 | + | Ok(Expr::nil()) |
|
| 808 | + | } |
|
| 809 | + | _ => eval_list(list, env), |
|
| 810 | + | } |
|
| 811 | + | } |
|
| 812 | + | ||
| 659 | 813 | /// Evaluate a "let" expression. |
|
| 660 | 814 | fn eval_let(assignments: Vec<Expr>, body: Vec<Expr>, env: &mut Env<'_>) -> Result<Expr> { |
|
| 661 | 815 | let mut kvs = Vec::new(); |
|
| 662 | 816 | for (k, v) in pairs(assignments)? { |
|
| 663 | 817 | let Expr::Symbol(k) = k else { |
| 695 | 849 | named, |
|
| 696 | 850 | body, |
|
| 697 | 851 | env: Env { |
|
| 698 | 852 | local, |
|
| 699 | 853 | docs: HashMap::new(), |
|
| 854 | + | exports: HashSet::new(), |
|
| 700 | 855 | parent: None, |
|
| 701 | 856 | }, |
|
| 702 | 857 | } |
|
| 703 | 858 | .into()) |
|
| 704 | 859 | } |
| 719 | 874 | let Some(head) = items.next() else { |
|
| 720 | 875 | return Ok(Expr::nil()); |
|
| 721 | 876 | }; |
|
| 722 | 877 | if let Expr::Symbol(ref name) = head { |
|
| 723 | 878 | match name.deref() { |
|
| 724 | - | "def" => { |
|
| 725 | - | let sym = items.next().ok_or(Error::ExpectedValue("symbol"))?; |
|
| 726 | - | let Expr::Symbol(name) = sym else { |
|
| 727 | - | return Err(Error::UnexpectedValue(sym)); |
|
| 728 | - | }; |
|
| 729 | - | let (docstr, value) = match (items.next(), items.next()) { |
|
| 730 | - | (Some(Expr::Str(docstr)), Some(value)) => (Some(docstr), value), |
|
| 731 | - | (Some(value), None) => (None, value), |
|
| 732 | - | ||
| 733 | - | _ => return Err(Error::ExpectedValue("expression")), |
|
| 734 | - | }; |
|
| 735 | - | ||
| 736 | - | match eval(value, env)? { |
|
| 737 | - | Expr::Function(Function::Closure(mut closure)) => { |
|
| 738 | - | if closure.name.is_none() { |
|
| 739 | - | if let Some(closure) = Rc::get_mut(&mut closure) { |
|
| 740 | - | closure.name = Some(Rc::clone(&name)); |
|
| 741 | - | } |
|
| 742 | - | } |
|
| 743 | - | env.binding( |
|
| 744 | - | &name, |
|
| 745 | - | docstr.as_deref(), |
|
| 746 | - | Expr::Function(Function::Closure(closure)), |
|
| 747 | - | ); |
|
| 748 | - | } |
|
| 749 | - | other => { |
|
| 750 | - | env.binding(&name, docstr.as_deref(), other); |
|
| 751 | - | } |
|
| 752 | - | } |
|
| 753 | - | Ok(Expr::nil()) |
|
| 754 | - | } |
|
| 755 | 879 | "do" => eval_iter(items, env), |
|
| 756 | 880 | "eval" => { |
|
| 757 | 881 | let Some(expr) = items.next() else { |
|
| 758 | 882 | return Err(Error::ExpectedValue("expression")); |
|
| 759 | 883 | }; |
| 2113 | 2237 | )]); |
|
| 2114 | 2238 | ||
| 2115 | 2239 | let result = Evaluator::new(parser).eval(&mut env).unwrap(); |
|
| 2116 | 2240 | assert_eq!(result, Expr::Str("ecila".to_owned())); |
|
| 2117 | 2241 | } |
|
| 2242 | + | ||
| 2243 | + | #[test] |
|
| 2244 | + | fn test_modules() { |
|
| 2245 | + | expect( |
|
| 2246 | + | &[ |
|
| 2247 | + | "(module math", |
|
| 2248 | + | " \"Math functions\"", |
|
| 2249 | + | " (export plus minus)", |
|
| 2250 | + | " (def plus (fn [x y] (+ x y)))", |
|
| 2251 | + | " (def minus (fn [x y] (- x y))))", |
|
| 2252 | + | "(import math)", |
|
| 2253 | + | "(math/minus (math/plus 4 3) 1)", |
|
| 2254 | + | ], |
|
| 2255 | + | Expr::Integer(6), |
|
| 2256 | + | ); |
|
| 2257 | + | } |
|
| 2258 | + | ||
| 2259 | + | #[test] |
|
| 2260 | + | #[ignore = "not implemented yet"] |
|
| 2261 | + | fn test_modules_nested() { |
|
| 2262 | + | expect( |
|
| 2263 | + | &[ |
|
| 2264 | + | "(module math", |
|
| 2265 | + | " (export basic)", |
|
| 2266 | + | " (module basic", |
|
| 2267 | + | " (export plus minus)", |
|
| 2268 | + | " (def plus (fn [x y] (+ x y)))", |
|
| 2269 | + | " (def minus (fn [x y] (- x y)))))", |
|
| 2270 | + | "(import math)", |
|
| 2271 | + | "(math/basic/minus (math/basic/plus 4 3) 1)", |
|
| 2272 | + | ], |
|
| 2273 | + | Expr::Integer(6), |
|
| 2274 | + | ); |
|
| 2275 | + | } |
|
| 2118 | 2276 | } |