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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
//! `Function` and closely related types.

use core::fmt;

use arithmetic_parser::{Location, LvalueLen};

use crate::{
    alloc::{Arc, HashMap, String, ToOwned, Vec},
    arith::OrdArithmetic,
    error::{Backtrace, Error, ErrorKind, LocationInModule},
    exec::{ExecutableFn, ModuleId, Operations},
    fns::ValueCell,
    Environment, EvalResult, SpannedValue, Value,
};

/// Context for native function calls.
#[derive(Debug)]
pub struct CallContext<'r, T> {
    call_location: LocationInModule,
    backtrace: Option<&'r mut Backtrace>,
    operations: Operations<'r, T>,
}

impl<'r, T> CallContext<'r, T> {
    /// Creates a mock call context with the specified module ID and call span.
    /// The provided [`Environment`] is used to extract an [`OrdArithmetic`] implementation.
    pub fn mock<ID: ModuleId>(module_id: ID, location: Location, env: &'r Environment<T>) -> Self {
        Self {
            call_location: LocationInModule::new(Arc::new(module_id), location),
            backtrace: None,
            operations: env.operations(),
        }
    }

    pub(crate) fn new(
        call_location: LocationInModule,
        backtrace: Option<&'r mut Backtrace>,
        operations: Operations<'r, T>,
    ) -> Self {
        Self {
            call_location,
            backtrace,
            operations,
        }
    }

    #[allow(clippy::needless_option_as_deref)] // false positive
    pub(crate) fn backtrace(&mut self) -> Option<&mut Backtrace> {
        self.backtrace.as_deref_mut()
    }

    pub(crate) fn arithmetic(&self) -> &'r dyn OrdArithmetic<T> {
        self.operations.arithmetic
    }

    /// Returns the call location of the currently executing function.
    pub fn call_location(&self) -> &LocationInModule {
        &self.call_location
    }

    /// Applies the call span to the specified `value`.
    pub fn apply_call_location<U>(&self, value: U) -> Location<U> {
        self.call_location.in_module().copy_with_extra(value)
    }

    /// Creates an error spanning the call site.
    pub fn call_site_error(&self, error: ErrorKind) -> Error {
        Error::from_parts(self.call_location.clone(), error)
    }

    /// Checks argument count and returns an error if it doesn't match.
    pub fn check_args_count(
        &self,
        args: &[SpannedValue<T>],
        expected_count: impl Into<LvalueLen>,
    ) -> Result<(), Error> {
        let expected_count = expected_count.into();
        if expected_count.matches(args.len()) {
            Ok(())
        } else {
            Err(self.call_site_error(ErrorKind::ArgsLenMismatch {
                def: expected_count,
                call: args.len(),
            }))
        }
    }
}

/// Function on zero or more [`Value`]s.
///
/// Native functions are defined in the Rust code and then can be used from the interpreted
/// code. See [`fns`](crate::fns) module docs for different ways to define native functions.
pub trait NativeFn<T> {
    /// Executes the function on the specified arguments.
    fn evaluate(
        &self,
        args: Vec<SpannedValue<T>>,
        context: &mut CallContext<'_, T>,
    ) -> EvalResult<T>;
}

impl<T, F> NativeFn<T> for F
where
    F: 'static + Fn(Vec<SpannedValue<T>>, &mut CallContext<'_, T>) -> EvalResult<T>,
{
    fn evaluate(
        &self,
        args: Vec<SpannedValue<T>>,
        context: &mut CallContext<'_, T>,
    ) -> EvalResult<T> {
        self(args, context)
    }
}

impl<T> fmt::Debug for dyn NativeFn<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_tuple("NativeFn").finish()
    }
}

impl<T> dyn NativeFn<T> {
    /// Extracts a data pointer from this trait object reference.
    pub(crate) fn data_ptr(&self) -> *const () {
        // `*const dyn Trait as *const ()` extracts the data pointer,
        // see https://github.com/rust-lang/rust/issues/27751. This is seemingly
        // the simplest way to extract the data pointer; `TraitObject` in `std::raw` is
        // a more future-proof alternative, but it is unstable.
        (self as *const dyn NativeFn<T>).cast()
    }
}

/// Function defined within the interpreter.
#[derive(Debug, Clone)]
pub struct InterpretedFn<T> {
    definition: Arc<ExecutableFn<T>>,
    captures: Vec<Value<T>>,
    capture_names: Vec<String>,
}

impl<T> InterpretedFn<T> {
    pub(crate) fn new(
        definition: Arc<ExecutableFn<T>>,
        captures: Vec<Value<T>>,
        capture_names: Vec<String>,
    ) -> Self {
        Self {
            definition,
            captures,
            capture_names,
        }
    }

    /// Returns ID of the module defining this function.
    pub fn module_id(&self) -> &Arc<dyn ModuleId> {
        self.definition.inner.id()
    }

    /// Returns the number of arguments for this function.
    pub fn arg_count(&self) -> LvalueLen {
        self.definition.arg_count
    }

    /// Returns values captured by this function.
    pub fn captures(&self) -> HashMap<&str, &Value<T>> {
        self.capture_names
            .iter()
            .zip(&self.captures)
            .map(|(name, val)| (name.as_str(), val))
            .collect()
    }
}

impl<T: 'static + Clone> InterpretedFn<T> {
    /// Evaluates this function with the provided arguments and the execution context.
    pub fn evaluate(
        &self,
        args: Vec<SpannedValue<T>>,
        ctx: &mut CallContext<'_, T>,
    ) -> EvalResult<T> {
        if !self.arg_count().matches(args.len()) {
            let err = ErrorKind::ArgsLenMismatch {
                def: self.arg_count(),
                call: args.len(),
            };
            return Err(ctx.call_site_error(err));
        }

        let args = args.into_iter().map(|arg| arg.extra).collect();
        let captures: Result<Vec<_>, _> = self
            .captures
            .iter()
            .zip(&self.capture_names)
            .map(|(capture, name)| Self::deref_capture(capture, name))
            .collect();
        let captures = captures.map_err(|err| ctx.call_site_error(err))?;

        self.definition.inner.call_function(captures, args, ctx)
    }

    fn deref_capture(capture: &Value<T>, name: &str) -> Result<Value<T>, ErrorKind> {
        Ok(match capture {
            Value::Ref(opaque_ref) => {
                if let Some(cell) = opaque_ref.downcast_ref::<ValueCell<T>>() {
                    cell.get()
                        .cloned()
                        .ok_or_else(|| ErrorKind::Uninitialized(name.to_owned()))?
                } else {
                    capture.clone()
                }
            }
            _ => capture.clone(),
        })
    }
}

/// Function definition. Functions can be either native (defined in the Rust code) or defined
/// in the interpreter.
#[derive(Debug)]
pub enum Function<T> {
    /// Native function.
    Native(Arc<dyn NativeFn<T>>),
    /// Interpreted function.
    Interpreted(Arc<InterpretedFn<T>>),
}

impl<T> Clone for Function<T> {
    fn clone(&self) -> Self {
        match self {
            Self::Native(function) => Self::Native(Arc::clone(function)),
            Self::Interpreted(function) => Self::Interpreted(Arc::clone(function)),
        }
    }
}

impl<T: fmt::Display> fmt::Display for Function<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Native(_) => formatter.write_str("(native fn)"),
            Self::Interpreted(function) => {
                formatter.write_str("(interpreted fn @ ")?;
                let location = LocationInModule::new(
                    function.module_id().clone(),
                    function.definition.def_location,
                );
                location.fmt_location(formatter)?;
                formatter.write_str(")")
            }
        }
    }
}

impl<T: PartialEq> PartialEq for Function<T> {
    fn eq(&self, other: &Self) -> bool {
        self.is_same_function(other)
    }
}

impl<T> Function<T> {
    /// Creates a native function.
    pub fn native(function: impl NativeFn<T> + 'static) -> Self {
        Self::Native(Arc::new(function))
    }

    /// Checks if the provided function is the same as this one.
    pub fn is_same_function(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Native(this), Self::Native(other)) => this.data_ptr() == other.data_ptr(),
            (Self::Interpreted(this), Self::Interpreted(other)) => Arc::ptr_eq(this, other),
            _ => false,
        }
    }

    pub(crate) fn def_location(&self) -> Option<LocationInModule> {
        match self {
            Self::Native(_) => None,
            Self::Interpreted(function) => Some(LocationInModule::new(
                function.module_id().clone(),
                function.definition.def_location,
            )),
        }
    }
}

impl<T: 'static + Clone> Function<T> {
    /// Evaluates the function on the specified arguments.
    pub fn evaluate(
        &self,
        args: Vec<SpannedValue<T>>,
        ctx: &mut CallContext<'_, T>,
    ) -> EvalResult<T> {
        match self {
            Self::Native(function) => function.evaluate(args, ctx),
            Self::Interpreted(function) => function.evaluate(args, ctx),
        }
    }
}