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("round".into(), Function::from(number::round));
63 inner.insert("contains".into(), Function::from(list::contains));
64 Self { inner }
65 }
66
67 pub fn insert(&mut self, ident: impl Into<String>, f: impl Into<Function>) -> Result<(), Error> {
68 let key = ident.into();
69 if self.inner.contains_key(&key) {
70 return Err(Error::FunctionAlreadyRegistered(key));
71 }
72 self.inner.insert(key, f.into());
73 Ok(())
74 }
75
76 pub fn lookup(&self, ident: &str) -> Option<&Function> {
77 self.inner.get(ident)
78 }
79}
80
81#[cfg(test)]
82mod test {
83 use crate::ValueKind;
84
85 pub(crate) fn list<T, U>(items: T) -> ValueKind<'static>
86 where
87 U: Into<ValueKind<'static>>,
88 T: IntoIterator<Item = U>,
89 {
90 let inner = items.into_iter().map(Into::into).collect::<Box<[ValueKind<'_>]>>();
91
92 ValueKind::List(inner)
93 }
94
95 pub(crate) fn value<T>(val: T) -> ValueKind<'static>
96 where
97 T: Into<ValueKind<'static>>,
98 {
99 val.into()
100 }
101}