anathema_value_resolver/functions/
mod.rs1use std::collections::HashMap;
2use std::fmt::{Debug, Display};
3
4use crate::ValueKind;
5
6mod list;
7mod number;
8mod string;
9
10#[derive(Debug)]
11pub enum Error {
12 FunctionAlreadyRegistered(String),
13}
14
15impl Display for Error {
16 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17 match self {
18 Error::FunctionAlreadyRegistered(name) => write!(f, "function `{name}` is already registered"),
19 }
20 }
21}
22
23impl std::error::Error for Error {}
24
25pub struct Function {
26 inner: Box<dyn for<'bp> Fn(&[ValueKind<'bp>]) -> ValueKind<'bp>>,
27}
28
29impl Function {
30 pub(crate) fn invoke<'bp>(&self, args: &[ValueKind<'bp>]) -> ValueKind<'bp> {
31 (self.inner)(args)
32 }
33}
34
35impl Debug for Function {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 write!(f, "<fun>")
38 }
39}
40
41impl<T> From<T> for Function
42where
43 T: 'static,
44 T: for<'bp> Fn(&[ValueKind<'bp>]) -> ValueKind<'bp>,
45{
46 fn from(value: T) -> Self {
47 Self { inner: Box::new(value) }
48 }
49}
50
51pub struct FunctionTable {
52 inner: HashMap<String, Function>,
53}
54
55impl FunctionTable {
56 pub fn new() -> Self {
57 let mut inner = HashMap::new();
58 inner.insert("to_upper".into(), Function::from(string::to_upper));
59 inner.insert("to_lower".into(), Function::from(string::to_lower));
60 inner.insert("to_str".into(), Function::from(string::to_str));
61 inner.insert("to_int".into(), Function::from(number::to_int));
62 inner.insert("to_float".into(), Function::from(number::to_float));
63 inner.insert("round".into(), Function::from(number::round));
64 inner.insert("contains".into(), Function::from(list::contains));
65 Self { inner }
66 }
67
68 pub fn insert(&mut self, ident: impl Into<String>, f: impl Into<Function>) -> Result<(), Error> {
69 let key = ident.into();
70 if self.inner.contains_key(&key) {
71 return Err(Error::FunctionAlreadyRegistered(key));
72 }
73 self.inner.insert(key, f.into());
74 Ok(())
75 }
76
77 pub fn lookup(&self, ident: &str) -> Option<&Function> {
78 self.inner.get(ident)
79 }
80}
81
82#[cfg(test)]
83mod test {
84 use crate::ValueKind;
85
86 pub(crate) fn list<T, U>(items: T) -> ValueKind<'static>
87 where
88 U: Into<ValueKind<'static>>,
89 T: IntoIterator<Item = U>,
90 {
91 let inner = items.into_iter().map(Into::into).collect::<Box<[ValueKind<'_>]>>();
92
93 ValueKind::List(inner)
94 }
95
96 pub(crate) fn value<T>(val: T) -> ValueKind<'static>
97 where
98 T: Into<ValueKind<'static>>,
99 {
100 val.into()
101 }
102}