simple_expressions/types/
function.rs1use crate::types::error::{Error, Result};
2use crate::types::object::Object;
3use crate::types::value::Value;
4use std::any::Any;
5use std::rc::Rc;
6
7pub type Callable = Rc<dyn Fn(&[Value]) -> Result<Value>>;
8
9pub fn new(callable: Callable) -> Value {
10 Value::Object(Rc::new(Function::new(callable)))
11}
12
13pub struct Function {
14 callable: Callable,
15}
16
17impl Function {
18 pub fn new(callable: Callable) -> Self {
19 Self { callable }
20 }
21}
22
23impl Object for Function {
24 fn type_name(&self) -> &'static str {
25 "function"
26 }
27
28 fn call(&self, args: &[Value]) -> Result<Value> {
29 self.callable.as_ref()(args)
30 }
31
32 fn as_any(&self) -> &dyn Any {
33 self
34 }
35
36 fn as_any_mut(&mut self) -> &mut dyn Any {
37 self
38 }
39}
40
41pub fn method0<F>(f: F) -> Value
42where
43 F: Fn() -> Result<Value> + 'static,
44{
45 new(Rc::new(move |args: &[Value]| {
46 if !args.is_empty() {
47 return Err(Error::EvaluationFailed("expected 0 args".into()));
48 }
49 f()
50 }))
51}
52
53pub fn method1<F>(f: F) -> Value
54where
55 F: Fn(&Value) -> Result<Value> + 'static,
56{
57 new(Rc::new(move |args: &[Value]| {
58 if args.len() != 1 {
59 return Err(Error::EvaluationFailed("expected 1 arg".into()));
60 }
61 f(&args[0])
62 }))
63}