twig/function/
mod.rs

1use std::fmt;
2use value::Value;
3use error::{ RuntimeResult, TemplateResult };
4use mold::Staging;
5use instructions::CompiledExpression;
6
7pub enum Arg {
8    Anon,
9    Named(&'static str),
10}
11
12/// Callable implementation.
13pub enum Callable {
14    /// Executable at runtime.
15    Dynamic(Box<
16        for<'e> Fn(&'e [Value]) -> RuntimeResult<Value>
17    >),
18    /// Inlined into instructions at compile time.
19    Static {
20        arguments: Vec<Arg>,
21        compile: Box<
22            for<'c> Fn(&mut Staging<'c, Value>) -> TemplateResult<CompiledExpression>
23        >
24    }
25}
26
27/// Represents environment function.
28pub struct Function {
29    pub name: &'static str,
30    pub callable: Callable,
31}
32
33impl Function {
34    pub fn new_dynamic<F: 'static>(
35        name: &'static str,
36        callable: F
37    )
38        -> Function
39    where
40        F: for<'e> Fn(&'e [Value]) -> RuntimeResult<Value>
41    {
42        Function {
43            name: name,
44            callable: Callable::Dynamic(Box::new(callable)),
45        }
46    }
47
48    pub fn new_static<F: 'static, I: IntoIterator<Item=Arg>>(
49        name: &'static str,
50        arguments: I,
51        compile: F
52    )
53        -> Function
54    where
55        F: for<'c> Fn(&mut Staging<'c, Value>) -> TemplateResult<CompiledExpression>
56    {
57        Function {
58            name: name,
59            callable: Callable::Static {
60                arguments: arguments.into_iter().collect(),
61                compile: Box::new(compile)
62            },
63        }
64    }
65}
66
67impl fmt::Debug for Function {
68    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69        write!(f, "{}()", self.name)
70    }
71}