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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
//! Dynamic variables and function calls can be provided by an [`Environment`].

use std::{collections::HashMap, rc::Rc};

use crate::{
    stdlib::{NativeError, NativeFunction, NativeResult},
    value::Value,
};

/// An enum signaling if a matching function is provided by a [`ValidateEnvironment`].
pub enum FunctionResult {
    /// A matching function was found.
    Exists,
    /// No function with was found matching the supplied name.
    NotFound,
    /// A function with a matching name, but an incompatible arity was found.
    WrongArity(usize, usize),
}

/// An environment used by the interpreter when executing an [`Expression`](crate::Expression).
/// It provides access to variables and native function calls.
pub trait Environment {
    /// Get a variable [`Value`] from the Environment.
    fn variable(&self, name: &str) -> Option<Rc<Value>>;

    /// Call a [`Function`] and may return a [`Value`].
    fn call(&self, name: &str, params: &[Value]) -> NativeResult;
}

/// An environment used during **validation** of the [`Expression`](crate::Expression).
pub trait ValidateEnvironment {
    /// Checks if a variable with a matching name exists.
    fn variable_exists(&self, name: &str) -> bool;

    /// Checks if a function with a matchinbg name and compatible arity exists.
    fn function_exists(&self, name: &str, arity: usize) -> FunctionResult;
}

/// The [Arity](https://en.wikipedia.org/wiki/Arity) of a [`NativeFunction`].
#[derive(Clone, Copy)]
pub enum Arity {
    Polyadic { required: usize, optional: usize },
    Variadic,
    None,
}

impl Arity {
    /// Declares an Arity with some required but no optional parameters.
    #[must_use]
    pub const fn required(required: usize) -> Self {
        Self::Polyadic {
            required,
            optional: 0,
        }
    }

    /// Declares an Arity with required and optional parameters.
    #[must_use]
    pub const fn optional(required: usize, optional: usize) -> Self {
        Self::Polyadic { required, optional }
    }
}

/// A wrapper to hold the [`NativeFunction`] and its arity.
#[derive(Clone)]
pub struct Function {
    pub name: String,
    pub func: NativeFunction,
    pub arity: Arity,
    pub params: String,
}

impl Function {
    /// Creates a new `Function` from  a declaration.
    /// Example: "max(left: Number, right: Number): Number")
    ///
    /// # Remarks
    ///
    /// If the declaration does not contain an opening brace, the whole string
    /// is used as name and the params are left empty.
    #[must_use]
    pub fn new(func: NativeFunction, arity: Arity, declaration: &str) -> Self {
        let (name, params) = declaration
            .split_once('(')
            .map(|(name, param)| (name, format!("({param}")))
            .unwrap_or((declaration, String::new()));

        Self {
            name: name.trim().to_string(),
            func,
            arity,
            params,
        }
    }
}

/// An [`Environment`] implementation in which all variables and functions are
/// known ahead of execution. All variable and function names treated as *case-insensitive*.
#[derive(Default)]
pub struct StaticEnvironment {
    variables: HashMap<String, Rc<Value>>,
    functions: HashMap<String, Rc<Function>>,
}

/// Transforms all variable and function names to lowercase for case-insensitive lookup.
fn get_env_key(name: &str) -> String {
    name.to_lowercase()
}

impl StaticEnvironment {
    /// Adds or updates a single variable.
    pub fn add_variable(&mut self, name: &str, value: Value) {
        self.variables.insert(get_env_key(name), Rc::new(value));
    }

    /// Removes a variable and return its [`Rc<Value>`] if it existed.
    pub fn remove_variable(&mut self, name: &str) -> Option<Rc<Value>> {
        self.variables.remove(&get_env_key(name))
    }

    /// Clears all variables.
    pub fn clear_variables(&mut self) {
        self.variables.clear();
    }

    /// Adds or updates a [`NativeFunction`].
    pub fn add_function(&mut self, func: Function) {
        self.functions
            .insert(get_env_key(&func.name), Rc::new(func));
    }

    /// Calls `add_function` for a `Vec<Function>`.
    pub fn add_functions(&mut self, functions: Vec<Function>) {
        for func in functions {
            self.add_function(func);
        }
    }

    /// Removes a [`NativeFunction`] and return its [`Function`] if it existed.
    pub fn remove_function(&mut self, name: &str) -> Option<Rc<Function>> {
        self.functions.remove(&get_env_key(name))
    }

    /// Output all currently registered [`Function`] structs as [`Rc`].
    #[must_use]
    pub fn list_functions(&self) -> Vec<Rc<Function>> {
        self.functions.values().cloned().collect()
    }
}

impl Environment for StaticEnvironment {
    fn variable(&self, name: &str) -> Option<Rc<Value>> {
        self.variables.get(&get_env_key(name)).cloned()
    }

    fn call(&self, name: &str, params: &[Value]) -> NativeResult {
        let function = self
            .functions
            .get(&get_env_key(name))
            .ok_or(NativeError::FunctionNotFound(name.to_string()))?;

        let call = function.func;
        call(params)
    }
}

impl ValidateEnvironment for StaticEnvironment {
    fn variable_exists(&self, name: &str) -> bool {
        self.variables.contains_key(&get_env_key(name))
    }

    fn function_exists(&self, name: &str, param_count: usize) -> FunctionResult {
        if let Some(function) = self.functions.get(&get_env_key(name)) {
            match function.arity {
                Arity::Polyadic { required, optional } => {
                    let lower = required;
                    let upper = required + optional;

                    if param_count < lower {
                        FunctionResult::WrongArity(param_count, lower)
                    } else if param_count > upper {
                        FunctionResult::WrongArity(param_count, upper)
                    } else {
                        FunctionResult::Exists
                    }
                }
                Arity::Variadic => FunctionResult::Exists,
                Arity::None => FunctionResult::WrongArity(param_count, 0),
            }
        } else {
            FunctionResult::NotFound
        }
    }
}

#[cfg(test)]
mod test {

    use super::*;
    use crate::{compile, execute};

    #[test]
    fn static_variables() {
        let mut env = StaticEnvironment::default();

        env.add_variable("some_var", Value::Number(42.0));
        let ast = compile("some_var = 42").unwrap();
        assert_eq!(Ok(Value::Boolean(true)), execute(&env, &ast));

        env.remove_variable("some_var");
        assert_eq!(Ok(Value::Boolean(false)), execute(&env, &ast));

        env.add_variable("some_var", Value::Number(42.0));
        let ast = compile("some_var = 42").unwrap();
        assert_eq!(Ok(Value::Boolean(true)), execute(&env, &ast));

        env.clear_variables();
        assert_eq!(Ok(Value::Boolean(false)), execute(&env, &ast));
    }

    #[test]
    fn static_functions() {
        fn test_func(_params: &[Value]) -> NativeResult {
            unreachable!()
        }
        let mut env = StaticEnvironment::default();

        env.add_function(Function::new(test_func, Arity::Variadic, "test(...)"));

        let registered = env.list_functions();
        assert_eq!(1, registered.len());
        assert_eq!("test", registered.first().unwrap().name);
        let removed = env.remove_function("test").unwrap();

        assert_eq!(removed.name, registered.first().unwrap().name);
    }

    #[test]
    fn new_function() {
        fn test_func(_params: &[Value]) -> NativeResult {
            unreachable!()
        }

        let func = Function::new(test_func, Arity::None, "some_name(param: Number): Number");
        assert_eq!("some_name", func.name);
        assert_eq!("(param: Number): Number", func.params);

        let func = Function::new(test_func, Arity::None, "only_name");
        assert_eq!("only_name", func.name);
        assert_eq!("", func.params);
    }
}