side effects?

This commit is contained in:
numzero 2025-04-11 20:44:52 +03:00
parent 985822b03f
commit 380b7b26a3

View File

@ -6,22 +6,9 @@ use crate::{
}; };
#[derive(Clone)] #[derive(Clone)]
pub struct Function { struct Function {
name: String, name: &'static str,
inner: Rc<dyn Fn(Vec<Value>) -> Value>, inner: Rc<dyn Fn(&mut Scope, Vec<Value>) -> Value>,
}
impl Function {
pub fn new(name: String, func: impl Fn(Vec<Value>) -> Value + 'static) -> Self {
Self {
name,
inner: Rc::new(func),
}
}
pub fn call(&self, args: Vec<Value>) -> Value {
(self.inner)(args)
}
} }
impl Debug for Function { impl Debug for Function {
@ -33,7 +20,7 @@ impl Debug for Function {
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct Scope { pub struct Scope {
variables: HashMap<String, ValueInner>, variables: HashMap<String, ValueInner>,
functions: HashMap<String, Function>, functions: HashMap<&'static str, Function>,
} }
impl Scope { impl Scope {
@ -49,9 +36,18 @@ impl Scope {
} }
} }
pub fn add_fn(&mut self, name: &'static str, f: impl Fn(Vec<Value>) -> Value + 'static) { pub fn add_fn(
self.functions &mut self,
.insert(name.into(), Function::new(name.into(), f)); name: &'static str,
f: impl Fn(&mut Scope, Vec<Value>) -> Value + 'static,
) {
self.functions.insert(
name,
Function {
name: name,
inner: Rc::new(f),
},
);
} }
} }
@ -95,10 +91,11 @@ impl Eval for Expression {
Expression::Constant(inner) => inner.eval(scope), Expression::Constant(inner) => inner.eval(scope),
Expression::Variable(inner) => inner.eval(scope), Expression::Variable(inner) => inner.eval(scope),
Expression::Call { callee, args } => { Expression::Call { callee, args } => {
let Some(function) = scope.functions.get(callee).cloned() else { let Some(function) = scope.functions.get(callee.as_str()).cloned() else {
panic!("attempt to call non-existent function {callee}") panic!("attempt to call non-existent function {callee}")
}; };
function.call(args.into_iter().map(|arg| arg.eval(scope)).collect()) let args = args.into_iter().map(|arg| arg.eval(scope)).collect();
(function.inner)(scope, args)
} }
} }
} }
@ -197,7 +194,7 @@ mod tests {
#[test] #[test]
fn test_call() { fn test_call() {
let mut scope = Scope::default(); let mut scope = Scope::default();
scope.add_fn("sqr", |args| { scope.add_fn("sqr", |_, args| {
let [arg] = args.as_slice() else { let [arg] = args.as_slice() else {
panic!("exactly one argument expected"); panic!("exactly one argument expected");
}; };