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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::cmp::PartialEq;
use std::collections::HashMap;
use std::fmt;
use thiserror::Error;

#[doc(inline)]
pub use crate::number::Number;

#[derive(Debug, Error)]
pub enum FuncError {
    #[error("unable to convert argument from value")]
    UnableToConvertFromValue,
    #[error("{0} requires at least {1} argument(s)")]
    AtLeastXArgs(String, usize),
    #[error("{0} requires exactly {1} argument(s)")]
    ExactlyXArgs(String, usize),
    #[error("{0}")]
    Generic(String),
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

/// Function type supported by `gtmpl_value`.
pub type Func = fn(&[Value]) -> Result<Value, FuncError>;

/// Wrapper struct for `Func`.
#[derive(Clone)]
pub struct Function {
    pub f: Func,
}

impl PartialEq for Function {
    fn eq(&self, other: &Function) -> bool {
        self.f as fn(_) -> _ == other.f as fn(_) -> _
    }
}

impl fmt::Debug for Function {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Funtion")
    }
}

impl fmt::Display for Function {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Funtion")
    }
}

/// Represents a gtmpl value.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    NoValue,
    Nil,
    Bool(bool),
    String(String),
    Object(HashMap<String, Value>),
    Map(HashMap<String, Value>),
    Array(Vec<Value>),
    Function(Function),
    Number(Number),
}

impl Value {
    pub fn from<T>(t: T) -> Self
    where
        T: Into<Value>,
    {
        t.into()
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Value::NoValue => write!(f, "<no value>"),
            Value::Nil => write!(f, "nil"),
            Value::Bool(ref b) => write!(f, "{}", b),
            Value::String(ref s) => write!(f, "{}", s),
            Value::Function(ref func) => write!(f, "{}", func),
            Value::Number(ref n) => write!(f, "{}", n),
            Value::Array(ref a) => write!(f, "{:?}", a),
            Value::Object(ref o) => write!(f, "{:?}", o),
            Value::Map(ref m) => write!(f, "{:?}", m),
        }
    }
}