raton 0.1.0-alpha.9

ratón is a tiny, modular, embeddable scripting language
Documentation
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// For macro.
#![allow(unused_braces)]

use super::{Extern, RuntimeError, RuntimeValue, Type};
use crate::Value;
use std::any::TypeId;

/// Type-erased function, callable by a script.
pub(crate) struct ErasedFunction<'data, 'func> {
    // TODO: SmallBox?
    #[allow(clippy::type_complexity)]
    inner: Box<
        dyn FnMut(&mut [RuntimeValue<'data>]) -> Result<RuntimeValue<'data>, RuntimeError> + 'func,
    >,
}

impl<'data, 'func> ErasedFunction<'data, 'func> {
    /// Erase the type of a function.
    pub(crate) fn new<A, R, F: Function<'data, A, R> + 'func>(mut inner: F) -> Self {
        Self {
            inner: Box::new(move |arguments| inner.call(arguments)),
        }
    }

    /// Call the type-erased function.
    pub(crate) fn call(
        &mut self,
        arguments: &mut [RuntimeValue<'data>],
    ) -> Result<RuntimeValue<'data>, RuntimeError> {
        (self.inner)(arguments)
    }
}

/// A Rust function callable by a script.
pub trait Function<'a, A, R>: Send + Sync {
    /// The number of arguments.
    const ARGS: usize;

    /// Get the [`TypeId`] of the receiver, if this is a method.
    fn receiver_type_id_extern_type() -> Option<(TypeId, Option<Type>)>;

    /// Call the function.
    fn call(
        &mut self,
        arguments: &mut [RuntimeValue<'a>],
    ) -> Result<RuntimeValue<'a>, RuntimeError>;
}

/// Types that can be converted to a [`RuntimeValue`], allowing them to
/// be passed as arguments from the host to a script function.
pub trait ToRuntimeValue<'a>: Sized {
    /// Perform the conversion.
    fn to_value(self) -> RuntimeValue<'a>;
}

/// Types that can be converted from a [`RuntimeValue`], allowing them to
/// be passed as arguments from a script function to the host.
pub trait FromRuntimeValue<'a>: Sized {
    /// The specific type this is looking for, if any. This is used to
    /// improve errors.
    const TYPE: Option<Type> = None;

    /// If this is eventually used in a [`Receiver`], the relevant type.
    ///
    /// Must compute this before creating a non-`'static` reference, which
    /// wouldn't support `TypeId` without `unsafe` code.
    ///
    /// Only `None` for `RuntimeValue<'_>`.
    fn type_id() -> Option<TypeId>;

    /// Perform the conversion, returning [`None`] if the [`RuntimeValue`]
    /// is of an incompatible type.
    fn from_value(value: &mut RuntimeValue<'a>) -> Option<Self>;
}

impl<'a> ToRuntimeValue<'a> for RuntimeValue<'a> {
    fn to_value(self) -> RuntimeValue<'a> {
        self
    }
}

impl<'a> FromRuntimeValue<'a> for RuntimeValue<'a> {
    fn type_id() -> Option<TypeId> {
        None
    }

    fn from_value(value: &mut RuntimeValue<'a>) -> Option<Self> {
        Some(std::mem::take(value))
    }
}

macro_rules! both_ways {
    ($v:ident, $t:path, $typeid:tt) => {
        impl<'a> ToRuntimeValue<'a> for $t {
            fn to_value(self) -> RuntimeValue<'a> {
                RuntimeValue::$v(self)
            }
        }

        impl<'a, 'b> FromRuntimeValue<'a> for $t {
            fn type_id() -> Option<TypeId> {
                $typeid
            }

            fn from_value(value: &mut RuntimeValue<'a>) -> Option<Self> {
                if let RuntimeValue::$v(v) = std::mem::take(value) {
                    Some(v)
                } else {
                    None
                }
            }
        }
    };
}

both_ways!(Value, Value, { Some(TypeId::of::<Value>()) });
both_ways!(Extern, Extern<'a>, None);

/// A shared [`std::rc::Rc`]-reference to a host value, which may be cheaply copied in a script.
///
/// Since [`std::rc::Rc`] is heap-allocated, requiring no value to reference it's easier to
/// create this type of extern value in a host function called by the script.
#[cfg(feature = "extern_value_type")]
pub struct ExternValue<T>(pub std::rc::Rc<T>);

/// An immutable reference to a host value, which may be freely copied in a script.
pub struct ExternRef<'a, T>(pub &'a T);

/// A mutable reference to a host value, which is taken when used in a script.
pub struct ExternMut<'a, T>(pub &'a mut T);

/// Wrap the first function argument in this to indicate it is a receiver, such that
/// two functions with the same name can be disambiguated by which type they are
/// called on.
#[cfg(feature = "method_call_expression")]
pub struct Receiver<'a, 'b, T>
where
    'a: 'b,
{
    borrow: &'b mut RuntimeValue<'a>,
    _spooky: std::marker::PhantomData<&'b T>,
}

#[cfg(feature = "method_call_expression")]
impl<'a, 'b> std::ops::Deref for Receiver<'a, 'b, Value> {
    type Target = Value;

    fn deref(&self) -> &Self::Target {
        match &*self.borrow {
            RuntimeValue::Value(v) => v,
            // Wrong receiver chosen.
            _ => unreachable!(),
        }
    }
}

#[cfg(feature = "method_call_expression")]
impl<'a, 'b> std::ops::DerefMut for Receiver<'a, 'b, Value> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        match self.borrow {
            RuntimeValue::Value(v) => v,
            // Wrong receiver chosen.
            _ => unreachable!(),
        }
    }
}

#[cfg(all(feature = "method_call_expression", feature = "extern_value_type"))]
impl<'a, 'b, T: 'static> std::ops::Deref for Receiver<'a, 'b, ExternValue<T>> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        match &*self.borrow {
            RuntimeValue::Extern(Extern::Value(v)) => (**v).downcast_ref().unwrap(),
            // Wrong receiver chosen.
            _ => unreachable!(),
        }
    }
}

#[cfg(feature = "method_call_expression")]
impl<'b, 'a: 'b, 'c, T: 'static> std::ops::Deref for Receiver<'a, 'b, ExternRef<'c, T>> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        match &*self.borrow {
            RuntimeValue::Extern(Extern::Ref(v)) => (**v).downcast_ref().unwrap(),
            // Wrong receiver chosen.
            _ => unreachable!(),
        }
    }
}

#[cfg(feature = "method_call_expression")]
impl<'b, 'a: 'b, 'c, T: 'static> std::ops::Deref for Receiver<'a, 'b, ExternMut<'c, T>> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        match &*self.borrow {
            RuntimeValue::Extern(Extern::Mut(v)) => (**v).downcast_ref().unwrap(),
            // Wrong receiver chosen.
            _ => unreachable!(),
        }
    }
}

#[cfg(feature = "method_call_expression")]
impl<'b, 'a: 'b, 'c, T: 'static> std::ops::DerefMut for Receiver<'a, 'b, ExternMut<'c, T>> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        match self.borrow {
            RuntimeValue::Extern(Extern::Mut(v)) => (**v).downcast_mut().unwrap(),
            // Wrong receiver chosen.
            _ => unreachable!(),
        }
    }
}

#[cfg(feature = "extern_value_type")]
impl<'a, T: 'static> ToRuntimeValue<'a> for ExternValue<T> {
    fn to_value(self) -> RuntimeValue<'a> {
        RuntimeValue::Extern(Extern::Value(self.0))
    }
}

#[cfg(feature = "extern_value_type")]
impl<'a, T: 'static> FromRuntimeValue<'a> for ExternValue<T> {
    const TYPE: Option<Type> = Some(Type::ExternValue);

    fn type_id() -> Option<TypeId> {
        Some(TypeId::of::<T>())
    }

    fn from_value(value: &mut RuntimeValue<'a>) -> Option<Self> {
        if let RuntimeValue::Extern(Extern::Value(value)) = std::mem::take(value) {
            value.downcast().ok().map(ExternValue)
        } else {
            None
        }
    }
}

impl<'a, T: 'static> ToRuntimeValue<'a> for ExternRef<'a, T> {
    fn to_value(self) -> RuntimeValue<'a> {
        RuntimeValue::Extern(Extern::Ref(self.0))
    }
}

impl<'a, T: 'static> FromRuntimeValue<'a> for ExternRef<'a, T> {
    const TYPE: Option<Type> = Some(Type::ExternRef);

    fn type_id() -> Option<TypeId> {
        Some(TypeId::of::<T>())
    }

    fn from_value(value: &mut RuntimeValue<'a>) -> Option<Self> {
        if let RuntimeValue::Extern(Extern::Ref(value)) = std::mem::take(value) {
            value.downcast_ref().map(ExternRef)
        } else {
            None
        }
    }
}

impl<'a, T: 'static> ToRuntimeValue<'a> for ExternMut<'a, T> {
    fn to_value(self) -> RuntimeValue<'a> {
        RuntimeValue::Extern(Extern::Mut(self.0))
    }
}

impl<'a, T: 'static> FromRuntimeValue<'a> for ExternMut<'a, T> {
    const TYPE: Option<Type> = Some(Type::ExternMut);

    fn type_id() -> Option<TypeId> {
        Some(TypeId::of::<T>())
    }

    fn from_value(value: &mut RuntimeValue<'a>) -> Option<Self> {
        if let RuntimeValue::Extern(Extern::Mut(value)) = std::mem::take(value) {
            value.downcast_mut().map(ExternMut)
        } else {
            None
        }
    }
}

#[allow(unused)]
macro_rules! impl_convert_argument {
    ($v:ident, $t:ident) => {
        impl<'a> ToRuntimeValue<'a> for $t {
            fn to_value(self) -> RuntimeValue<'a> {
                RuntimeValue::Value(Value::$v(self))
            }
        }

        impl<'a, 'b> FromRuntimeValue<'a> for $t {
            const TYPE: Option<Type> = Some(Type::$v);

            fn type_id() -> Option<TypeId> {
                Some(TypeId::of::<Value>())
            }

            fn from_value(value: &mut RuntimeValue<'a>) -> Option<Self> {
                if let RuntimeValue::Value(Value::$v(v)) = std::mem::take(value) {
                    Some(v)
                } else {
                    None
                }
            }
        }
    };
}

#[cfg(feature = "bool_type")]
impl_convert_argument!(Bool, bool);
#[cfg(feature = "i32_type")]
impl_convert_argument!(I32, i32);
#[cfg(feature = "f32_type")]
impl_convert_argument!(F32, f32);
#[cfg(feature = "string_type")]
impl_convert_argument!(String, String);

/*
fn assert_arg<'a, T>()
where
    for<'b> Receiver<'a, 'b, T>: FromRuntimeValue<'a>
{}
//fn assert_arg<'a, A: for<'b> FromRuntimeValue<'a>>() {}
fn _test(){
    assert_arg::<Receiver<ExternValue<()>>>();//
}
*/

macro_rules! impl_function {
    ($($a: ident),*) => {
        impl<'a, $($a,)* R, FUNC: FnMut($($a),*) -> Result<R, RuntimeError> + Send + Sync> Function<'a, ((), ($($a,)*)), R> for FUNC
            where $($a: FromRuntimeValue<'a> + 'a,)*
                R: ToRuntimeValue<'a> {
            const ARGS: usize = 0 $(
                + {
                    let _ = std::mem::size_of::<$a>();
                    1
                }
            )*;

            fn receiver_type_id_extern_type() -> Option<(TypeId, Option<Type>)> {
                None
            }

            fn call(
                    &mut self,
                    mut _arguments: &mut [RuntimeValue<'a>],
                ) -> Result<RuntimeValue<'a>, RuntimeError> {
                if _arguments.len() != Self::ARGS {
                    return Err(RuntimeError::WrongNumberOfArguments{expected: Self::ARGS as u16, actual: _arguments.len() as u16});
                }
                let mut _i = 0;
                (self)($({
                    let (first, rest) = _arguments.split_at_mut(1);
                    _arguments = rest;
                    let arg = &mut first[0];
                    let type_of = arg.type_of();
                    <$a>::from_value(arg).ok_or(RuntimeError::InvalidArgument{
                        expected: $a::TYPE,
                        actual: type_of
                    })?
                }),*).map(move |v| v.to_value())
            }
        }
    };
}

// it took 4 days to figure out the lifetimes (╯°□°)╯︵ ┻━┻
#[cfg(feature = "method_call_expression")]
macro_rules! impl_method {
    ($($a: ident),*) => {
        impl<'a, RECEIVER, $($a,)* R: 'a, FUNC: for<'b> FnMut(Receiver<'a, 'b, RECEIVER>, $($a),*) -> Result<R, RuntimeError> + Send + Sync> Function<'a, (RECEIVER, (), ($($a,)*)), R> for FUNC
            where RECEIVER: FromRuntimeValue<'a> + 'a,
                $($a: FromRuntimeValue<'a>,)*
                R: ToRuntimeValue<'a> {
            const ARGS: usize = 1 $(
                + {
                    let _ = std::mem::size_of::<$a>();
                    1
                }
            )*;

            fn receiver_type_id_extern_type() -> Option<(TypeId, Option<Type>)> {
                <RECEIVER>::type_id().map(|type_id| (type_id, RECEIVER::TYPE.filter(|t| {
                    match t {
                        Type::ExternRef | Type::ExternMut => true,
                        #[cfg(feature = "extern_value_type")]
                        Type::ExternValue => true,
                        _ => false,
                    }
                })))
            }

            fn call(
                    &mut self,
                    mut _arguments: &mut [RuntimeValue<'a>],
                ) -> Result<RuntimeValue<'a>, RuntimeError> {
                if _arguments.len() != Self::ARGS {
                    return Err(RuntimeError::WrongNumberOfArguments{expected: Self::ARGS as u16, actual: _arguments.len() as u16});
                }
                let mut _i = 0;
                (self)(
                    {
                        let (first, rest) = _arguments.split_at_mut(1);
                        _arguments = rest;
                        let arg = &mut first[0];
                        Receiver{
                            borrow: arg,
                            _spooky: std::marker::PhantomData,
                        }
                    },
                $({
                    let (first, rest) = _arguments.split_at_mut(1);
                    _arguments = rest;
                    let arg = &mut first[0];
                    let type_of = arg.type_of();
                    <$a>::from_value(arg).ok_or(RuntimeError::InvalidArgument{
                        expected: $a::TYPE,
                        actual: type_of
                    })?
                }),*).map(move |v| v.to_value())
            }
        }
    };
}

macro_rules! impl_function_and_method {
    ($($a: ident),*) => {
        impl_function!($($a),*);
        #[cfg(feature = "method_call_expression")]
        impl_method!($($a),*);
    }
}

impl_function_and_method!();
impl_function_and_method!(A);
impl_function_and_method!(A, B);
impl_function_and_method!(A, B, C);
impl_function_and_method!(A, B, C, D);
impl_function_and_method!(A, B, C, D, E);
impl_function_and_method!(A, B, C, D, E, F);
impl_function_and_method!(A, B, C, D, E, F, G);
impl_function_and_method!(A, B, C, D, E, F, G, H);
impl_function_and_method!(A, B, C, D, E, F, G, H, I);
impl_function_and_method!(A, B, C, D, E, F, G, H, I, J);