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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
//! Traits used in function wrapper.

use core::{cmp, fmt};

use crate::{
    alloc::{vec, String, Vec},
    CallContext, Error, ErrorKind, Function, Number, Object, Tuple, Value, ValueType,
};

/// Error raised when a value cannot be converted to the expected type when using
/// [`FnWrapper`](crate::fns::FnWrapper).
#[derive(Debug, Clone)]
pub struct FromValueError {
    kind: FromValueErrorKind,
    arg_index: usize,
    location: Vec<FromValueErrorLocation>,
}

impl FromValueError {
    pub(crate) fn invalid_type<T>(expected: ValueType, actual_value: &Value<T>) -> Self {
        Self {
            kind: FromValueErrorKind::InvalidType {
                expected,
                actual: actual_value.value_type(),
            },
            arg_index: 0,
            location: vec![],
        }
    }

    fn add_location(mut self, location: FromValueErrorLocation) -> Self {
        self.location.push(location);
        self
    }

    #[doc(hidden)] // necessary for `wrap_fn` macro
    pub fn set_arg_index(&mut self, index: usize) {
        self.arg_index = index;
        self.location.reverse();
    }

    /// Returns the error kind.
    pub fn kind(&self) -> &FromValueErrorKind {
        &self.kind
    }

    /// Returns the zero-based index of the argument where the error has occurred.
    pub fn arg_index(&self) -> usize {
        self.arg_index
    }

    /// Returns the error location, starting from the outermost one.
    pub fn location(&self) -> &[FromValueErrorLocation] {
        &self.location
    }
}

impl fmt::Display for FromValueError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{}. Error location: arg{}",
            self.kind, self.arg_index
        )?;
        for location_element in &self.location {
            match location_element {
                FromValueErrorLocation::Tuple { index, .. } => write!(formatter, ".{index}")?,
                FromValueErrorLocation::Array { index, .. } => write!(formatter, "[{index}]")?,
            }
        }
        Ok(())
    }
}

#[cfg(feature = "std")]
impl std::error::Error for FromValueError {}

/// Error kinds for [`FromValueError`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FromValueErrorKind {
    /// Mismatch between expected and actual value type.
    InvalidType {
        /// Expected value type.
        expected: ValueType,
        /// Actual value type.
        actual: ValueType,
    },
}

impl fmt::Display for FromValueErrorKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidType { expected, actual } => {
                write!(formatter, "Cannot convert {actual} to {expected}")
            }
        }
    }
}

/// Element of the [`FromValueError`] location.
///
/// Note that the distinction between tuples and arrays is determined by the [`FnWrapper`].
/// If the corresponding type in the wrapper is defined as a tuple, then
/// a [`Tuple`](FromValueErrorLocation::Tuple) element will be added to the location; otherwise,
/// an [`Array`](FromValueErrorLocation::Array) will be added.
///
/// [`FnWrapper`]: crate::fns::FnWrapper
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FromValueErrorLocation {
    /// Location within a tuple.
    Tuple {
        /// Tuple size.
        size: usize,
        /// Zero-based index of the erroneous element.
        index: usize,
    },
    /// Location within an array.
    Array {
        /// Factual array size.
        size: usize,
        /// Zero-based index of the erroneous element.
        index: usize,
    },
}

/// Fallible conversion from `Value` to a function argument.
///
/// This trait is implemented for base value types (such as [`Number`]s, [`Function`]s, [`Value`]s),
/// and for two container types: vectors and tuples.
pub trait TryFromValue<T>: Sized {
    /// Attempts to convert `value` to a type supported by the function.
    fn try_from_value(value: Value<T>) -> Result<Self, FromValueError>;
}

impl<T: Number> TryFromValue<T> for T {
    fn try_from_value(value: Value<T>) -> Result<Self, FromValueError> {
        match value {
            Value::Prim(number) => Ok(number),
            _ => Err(FromValueError::invalid_type(ValueType::Prim, &value)),
        }
    }
}

impl<T> TryFromValue<T> for bool {
    fn try_from_value(value: Value<T>) -> Result<Self, FromValueError> {
        match value {
            Value::Bool(flag) => Ok(flag),
            _ => Err(FromValueError::invalid_type(ValueType::Bool, &value)),
        }
    }
}

impl<T> TryFromValue<T> for Value<T> {
    fn try_from_value(value: Value<T>) -> Result<Self, FromValueError> {
        Ok(value)
    }
}

impl<T> TryFromValue<T> for Function<T> {
    fn try_from_value(value: Value<T>) -> Result<Self, FromValueError> {
        match value {
            Value::Function(function) => Ok(function),
            _ => Err(FromValueError::invalid_type(ValueType::Function, &value)),
        }
    }
}

impl<T> TryFromValue<T> for Tuple<T> {
    fn try_from_value(value: Value<T>) -> Result<Self, FromValueError> {
        match value {
            Value::Tuple(tuple) => Ok(tuple),
            _ => Err(FromValueError::invalid_type(ValueType::Array, &value)),
        }
    }
}

impl<T> TryFromValue<T> for Object<T> {
    fn try_from_value(value: Value<T>) -> Result<Self, FromValueError> {
        match value {
            Value::Object(object) => Ok(object),
            _ => Err(FromValueError::invalid_type(ValueType::Object, &value)),
        }
    }
}

impl<U, T> TryFromValue<T> for Vec<U>
where
    U: TryFromValue<T>,
{
    fn try_from_value(value: Value<T>) -> Result<Self, FromValueError> {
        match value {
            Value::Tuple(values) => {
                let tuple_len = values.len();
                let mut collected = Vec::with_capacity(tuple_len);

                for (index, element) in values.into_iter().enumerate() {
                    let converted = U::try_from_value(element).map_err(|err| {
                        err.add_location(FromValueErrorLocation::Array {
                            size: tuple_len,
                            index,
                        })
                    })?;
                    collected.push(converted);
                }
                Ok(collected)
            }
            _ => Err(FromValueError::invalid_type(ValueType::Array, &value)),
        }
    }
}

macro_rules! try_from_value_for_tuple {
    ($size:expr => $($var:ident : $ty:ident),+) => {
        impl<Num, $($ty,)+> TryFromValue<Num> for ($($ty,)+)
        where
            $($ty: TryFromValue<Num>,)+
        {
            #[allow(clippy::shadow_unrelated)] // makes it easier to write macro
            fn try_from_value(value: Value<Num>) -> Result<Self, FromValueError> {
                const EXPECTED_TYPE: ValueType = ValueType::Tuple($size);

                match value {
                    Value::Tuple(values) if values.len() == $size => {
                        let mut values_iter = values.into_iter().enumerate();
                        $(
                            let (index, $var) = values_iter.next().unwrap();
                            let $var = $ty::try_from_value($var).map_err(|err| {
                                err.add_location(FromValueErrorLocation::Tuple {
                                    size: $size,
                                    index,
                                })
                            })?;
                        )+
                        Ok(($($var,)+))
                    }
                    _ => Err(FromValueError::invalid_type(EXPECTED_TYPE, &value)),
                }
            }
        }
    };
}

try_from_value_for_tuple!(1 => x0: T);
try_from_value_for_tuple!(2 => x0: T, x1: U);
try_from_value_for_tuple!(3 => x0: T, x1: U, x2: V);
try_from_value_for_tuple!(4 => x0: T, x1: U, x2: V, x3: W);
try_from_value_for_tuple!(5 => x0: T, x1: U, x2: V, x3: W, x4: X);
try_from_value_for_tuple!(6 => x0: T, x1: U, x2: V, x3: W, x4: X, x5: Y);
try_from_value_for_tuple!(7 => x0: T, x1: U, x2: V, x3: W, x4: X, x5: Y, x6: Z);
try_from_value_for_tuple!(8 => x0: T, x1: U, x2: V, x3: W, x4: X, x5: Y, x6: Z, x7: A);
try_from_value_for_tuple!(9 => x0: T, x1: U, x2: V, x3: W, x4: X, x5: Y, x6: Z, x7: A, x8: B);
try_from_value_for_tuple!(10 => x0: T, x1: U, x2: V, x3: W, x4: X, x5: Y, x6: Z, x7: A, x8: B, x9: C);

/// Generic error output encompassing all error types supported by
/// [wrapped functions](crate::fns::FnWrapper).
#[derive(Debug)]
#[non_exhaustive]
pub enum ErrorOutput {
    /// Error together with the defined span(s).
    Spanned(Error),
    /// Error message. The error span will be defined as the call span of the native function.
    Message(String),
}

impl ErrorOutput {
    #[doc(hidden)] // necessary for `wrap_fn` macro
    pub fn into_spanned<A>(self, context: &CallContext<'_, A>) -> Error {
        match self {
            Self::Spanned(err) => err,
            Self::Message(message) => context.call_site_error(ErrorKind::native(message)),
        }
    }
}

/// Converts type into `Value` or an error. This is used to convert the return type
/// of [wrapped functions](crate::fns::FnWrapper) to the result expected by
/// [`NativeFn`](crate::NativeFn).
///
/// Unlike with `TryInto` trait from the standard library, the erroneous result here does not
/// mean that the conversion *itself* is impossible. Rather, it means that the function evaluation
/// has failed for the provided args.
///
///
/// This trait is implemented for base value types (such as [`Number`]s, [`Function`]s, [`Value`]s),
/// for two container types: vectors and tuples, and for `Result`s with the error type
/// convertible to [`ErrorOutput`].
pub trait IntoEvalResult<T> {
    /// Performs the conversion.
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput>;
}

impl<T, U> IntoEvalResult<T> for Result<U, String>
where
    U: IntoEvalResult<T>,
{
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        self.map_err(ErrorOutput::Message)
            .and_then(U::into_eval_result)
    }
}

impl<T, U> IntoEvalResult<T> for Result<U, Error>
where
    U: IntoEvalResult<T>,
{
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        self.map_err(ErrorOutput::Spanned)
            .and_then(U::into_eval_result)
    }
}

impl<T: Number> IntoEvalResult<T> for T {
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        Ok(Value::Prim(self))
    }
}

impl<T> IntoEvalResult<T> for () {
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        Ok(Value::void())
    }
}

impl<T> IntoEvalResult<T> for bool {
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        Ok(Value::Bool(self))
    }
}

impl<T> IntoEvalResult<T> for cmp::Ordering {
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        Ok(Value::opaque_ref(self))
    }
}

impl<T> IntoEvalResult<T> for Value<T> {
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        Ok(self)
    }
}

impl<T> IntoEvalResult<T> for Function<T> {
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        Ok(Value::Function(self))
    }
}

impl<T> IntoEvalResult<T> for Tuple<T> {
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        Ok(Value::Tuple(self))
    }
}

impl<T> IntoEvalResult<T> for Object<T> {
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        Ok(Value::Object(self))
    }
}

impl<U, T> IntoEvalResult<T> for Vec<U>
where
    U: IntoEvalResult<T>,
{
    fn into_eval_result(self) -> Result<Value<T>, ErrorOutput> {
        let values = self
            .into_iter()
            .map(U::into_eval_result)
            .collect::<Result<Tuple<_>, _>>()?;
        Ok(Value::Tuple(values))
    }
}

macro_rules! into_value_for_tuple {
    ($($i:tt : $ty:ident),+) => {
        impl<Num, $($ty,)+> IntoEvalResult<Num> for ($($ty,)+)
        where
            $($ty: IntoEvalResult<Num>,)+
        {
            fn into_eval_result(self) -> Result<Value<Num>, ErrorOutput> {
                Ok(Value::from(vec![$(self.$i.into_eval_result()?,)+]))
            }
        }
    };
}

into_value_for_tuple!(0: T);
into_value_for_tuple!(0: T, 1: U);
into_value_for_tuple!(0: T, 1: U, 2: V);
into_value_for_tuple!(0: T, 1: U, 2: V, 3: W);
into_value_for_tuple!(0: T, 1: U, 2: V, 3: W, 4: X);
into_value_for_tuple!(0: T, 1: U, 2: V, 3: W, 4: X, 5: Y);
into_value_for_tuple!(0: T, 1: U, 2: V, 3: W, 4: X, 5: Y, 6: Z);
into_value_for_tuple!(0: T, 1: U, 2: V, 3: W, 4: X, 5: Y, 6: Z, 7: A);
into_value_for_tuple!(0: T, 1: U, 2: V, 3: W, 4: X, 5: Y, 6: Z, 7: A, 8: B);
into_value_for_tuple!(0: T, 1: U, 2: V, 3: W, 4: X, 5: Y, 6: Z, 7: A, 8: B, 9: C);