1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::fmt;
use value::Value;
use error::{ RuntimeResult, TemplateResult };
use mold::Staging;
use instructions::CompiledExpression;

pub enum Arg {
    Anon,
    Named(&'static str),
}

/// Callable implementation.
pub enum Callable {
    /// Executable at runtime.
    Dynamic(Box<
        for<'e> Fn(&'e [Value]) -> RuntimeResult<Value>
    >),
    /// Inlined into instructions at compile time.
    Static {
        arguments: Vec<Arg>,
        compile: Box<
            for<'c> Fn(&mut Staging<'c, Value>) -> TemplateResult<CompiledExpression>
        >
    }
}

/// Represents environment function.
pub struct Function {
    pub name: &'static str,
    pub callable: Callable,
}

impl Function {
    pub fn new_dynamic<F: 'static>(
        name: &'static str,
        callable: F
    )
        -> Function
    where
        F: for<'e> Fn(&'e [Value]) -> RuntimeResult<Value>
    {
        Function {
            name: name,
            callable: Callable::Dynamic(Box::new(callable)),
        }
    }

    pub fn new_static<F: 'static, I: IntoIterator<Item=Arg>>(
        name: &'static str,
        arguments: I,
        compile: F
    )
        -> Function
    where
        F: for<'c> Fn(&mut Staging<'c, Value>) -> TemplateResult<CompiledExpression>
    {
        Function {
            name: name,
            callable: Callable::Static {
                arguments: arguments.into_iter().collect(),
                compile: Box::new(compile)
            },
        }
    }
}

impl fmt::Debug for Function {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}()", self.name)
    }
}