closure bump

This commit is contained in:
2026-09-12 14:44:08 +02:00
parent 5c5c81325d
commit 762ed3c478
9 changed files with 172 additions and 14 deletions
+25 -1
View File
@@ -1,5 +1,5 @@
use super::{expression::Expression, prelude::mk_prelude};
use std::{cell::RefCell, collections::HashMap, rc::Rc};
use std::{cell::RefCell, collections::HashMap, fmt::Display, rc::Rc};
#[derive(PartialEq, Clone, Debug)]
/// A Environment is a stack of `EnvironmentLayer`s. Each `EnvironmentLayer` is a mapping from
@@ -136,6 +136,30 @@ impl Default for Environment<'_> {
}
}
impl Display for Environment<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(x) = &self.outer {
write!(f, "{}<{}", self.layer, x)
} else {
write!(f, "")
}
}
}
impl Display for EnvironmentLayer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{{{}}}",
self.symbols
.iter()
.map(|(k, v)| format!("{}={}", k, v))
.collect::<Vec<_>>()
.join(", ")
)
}
}
#[test]
fn test_environment() {
let mut env = Environment::new();
+13 -1
View File
@@ -97,12 +97,23 @@ fn dispatch_anonymous_function(
}
for (arg, symbol) in args.iter_mut().zip(argument_symbols.iter()) {
overlay.set(symbol.to_owned(), eval(env, arg.to_owned())?);
overlay.set(symbol.to_owned(), eval(&env, arg.to_owned())?);
}
eval(&env.overlay(overlay), body)
}
/// Dispatch a closure. Evaluates `body` in `env` overlayed with the `layer`
fn dispatch_closure(
env: &Environment,
layer: EnvironmentLayer,
body: Expression,
) -> Result<Expression, EvalError> {
println!("Dispatching closure: {} -> {}", &layer, &body);
let env = env.overlay(layer);
eval(&env, body)
}
/// Evaluate an expression inside an environment
pub fn eval(env: &Environment, expr: Expression) -> Result<Expression, EvalError> {
match expr {
@@ -114,6 +125,7 @@ pub fn eval(env: &Environment, expr: Expression) -> Result<Expression, EvalError
} => dispatch_anonymous_function(env, argument_symbols, *body, *rhs),
a => Err(EvalError::NotAFunction(a)),
},
Expression::Closure { layer, body } => dispatch_closure(env, layer, *body),
Expression::Quote(e) => Ok(*e),
Expression::Symbol(s) => env.get(&s).ok_or(EvalError::SymbolNotBound(s)),
x => Ok(x),
+12
View File
@@ -7,6 +7,7 @@ use std::ops::DerefMut;
use as_any::AsAny;
use super::environment::Environment;
use super::environment::EnvironmentLayer;
use super::eval::CellIterator;
use super::eval::EvalError;
@@ -128,6 +129,10 @@ pub enum Expression {
Cell(Box<Expression>, Box<Expression>),
/// A function expression pointing to native code.
Function(fn(&Environment, Expression) -> Result<Expression, EvalError>),
Closure {
layer: EnvironmentLayer,
body: Box<Expression>,
},
/// A anonymous function expression consisting of bound symbols and a body expression.
AnonymousFunction {
argument_symbols: Vec<String>,
@@ -169,7 +174,9 @@ impl PartialEq for Expression {
(ForeignExpression(f1), ForeignExpression(f2)) => PartialEq::eq(f1, f2),
(Quote(e1), Quote(e2)) => PartialEq::eq(e1, e2),
(Symbol(s1), Symbol(s2)) => PartialEq::eq(s1, s2),
(Integer(i1), Integer(i2)) => PartialEq::eq(i1, i2),
(Float(f1), Float(f2)) => PartialEq::eq(f1, f2),
(String(s1), String(s2)) => PartialEq::eq(s1, s2),
(Nil, Nil) => true,
(True, True) => true,
_ => false,
@@ -198,6 +205,8 @@ impl PartialOrd for Expression {
(Quote(e1), Quote(e2)) => e1.partial_cmp(e2),
(Symbol(s1), Symbol(s2)) => s1.partial_cmp(s2),
(Float(f1), Float(f2)) => f1.partial_cmp(f2),
(Integer(i1), Integer(i2)) => i1.partial_cmp(i2),
(String(s1), String(s2)) => s1.partial_cmp(s2),
(Nil, Nil) => Some(std::cmp::Ordering::Equal),
(True, True) => Some(std::cmp::Ordering::Equal),
_ => None,
@@ -407,6 +416,9 @@ impl Display for Expression {
}
}
Expression::Function(_) => write!(f, "<function>"),
Expression::Closure { layer, body } => {
write!(f, "(closure captured={}, body={})", layer, body)
}
Expression::AnonymousFunction {
argument_symbols,
body,
+14 -3
View File
@@ -148,13 +148,18 @@ pub fn prelude_let(env: &Environment, expr: Expression) -> Result<Expression, Ev
})
.collect::<Result<HashMap<String, Expression>, EvalError>>()?;
eval(&env.overlay(bindings.into()), body)
Ok(Expression::Closure {
layer: bindings.into(),
body: Box::new(body),
})
}
pub fn prelude_if(env: &Environment, expr: Expression) -> Result<Expression, EvalError> {
let [predicate, e_then, e_else] = expr.try_into()?;
let [predicate, e_then, e_else]: [Expression; 3] = expr.try_into()?;
match eval(env, predicate)? {
let val = eval(env, predicate.clone())?;
match val {
Expression::Nil => eval(env, e_else),
_ => eval(env, e_then),
}
@@ -348,18 +353,24 @@ pub fn prelude_include(env: &Environment, expr: Expression) -> Result<Expression
let [expr] = expr.try_into()?;
let lisp_file: String = eval(env, expr)?.try_into()?;
println!("From File: {}", env.get("FILE").unwrap());
// Try to resolve as relative to FILE
let resolved_lisp_file: PathBuf = PathBuf::from(
env.get("FILE")
.map(|x| x.try_into())
.unwrap_or(Ok(String::new()))?,
)
.canonicalize()
.map_err(|x| EvalError::RuntimeError(x.to_string()))?
.parent()
.ok_or(EvalError::RuntimeError(
"Could not get parent of current file.".to_string(),
))?
.join(&lisp_file);
println!("Loading {}", resolved_lisp_file.display());
let lisp_string = std::fs::read_to_string(&resolved_lisp_file)
.map_err(|e| EvalError::RuntimeError(e.to_string()))?;
+2
View File
@@ -11,6 +11,7 @@ pub enum ParserError {
UnexpectedToken(Token),
TokenizerError(TokenizerError),
UnexpectedEndOfInput,
RuntimeError(String),
}
impl From<TokenizerError> for ParserError {
@@ -25,6 +26,7 @@ impl Display for ParserError {
ParserError::TokenizerError(t) => write!(f, "Tokenizer Error: {}", t),
ParserError::UnexpectedToken(t) => write!(f, "Unexpecte Token: {}", t),
ParserError::UnexpectedEndOfInput => write!(f, "Unexpected end of input."),
ParserError::RuntimeError(s) => write!(f, "{}", s),
}
}
}