prints/
runtime.rs

1#![allow(dead_code)]
2
3use crate::{expr::Environment, value::Value, Error};
4use std::collections::HashMap;
5
6struct Function {
7    func_impl: Box<dyn Fn(&[Value]) -> Value>,
8}
9
10impl Function {
11    fn new<F>(f: F) -> Self
12    where
13        F: Fn(&[Value]) -> Value + 'static,
14    {
15        Function {
16            func_impl: Box::new(f),
17        }
18    }
19
20    fn eval(&self, args: &[Value]) -> Result<Value, Error> {
21        Ok((self.func_impl)(args))
22    }
23}
24
25pub struct SimpleRuntime {
26    functions: HashMap<String, Function>,
27}
28
29impl SimpleRuntime {
30    pub fn new() -> Self {
31        SimpleRuntime {
32            functions: HashMap::new(),
33        }
34    }
35
36    pub fn register_func<F>(&mut self, name: &str, f: F)
37    where
38        F: Fn(&[Value]) -> Value + 'static,
39    {
40        self.functions.insert(name.to_string(), Function::new(f));
41    }
42}
43
44impl Environment for SimpleRuntime {
45    fn eval_func(&self, name: &str, args: &[Value]) -> Result<Value, Error> {
46        let func = self
47            .functions
48            .get(name)
49            .ok_or_else(|| Error::UndefinedFunctionError(name.to_string()))?;
50        func.eval(args)
51    }
52}