roto 0.10.0

a statically-typed, compiled, embedded 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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
use std::any::TypeId;

use crate::value::TypeDescription;
use crate::{
    Location, Value,
    ast::Identifier,
    runtime::{
        CloneDrop, ConstantValue, Movability, RegistrationError, Rt,
        extern_clone, extern_drop,
        func::{FunctionDescription, RegisterableFn},
        layout::Layout,
    },
};

/// A registerable item
///
/// <div class="warning">
///
/// This type is usually constructed by the [`library!`](crate::library) macro
///
/// </div>
#[derive(Clone, Debug)]
pub enum Item {
    /// A function
    Function(Function),

    /// A type
    Type(Type),

    /// A module
    Module(Module),

    /// A constant
    Constant(Constant),

    /// An impl block
    Impl(Impl),

    /// A use statement
    Use(Use),
}

/// Trait implemented by items that can be registered into the [`Runtime`].
///
/// In practice, implementors of this trait can be passed to [`Runtime::add`] and
/// [`Runtime::from_lib`].
///
/// [`Runtime`]: super::Runtime
/// [`Runtime::add`]: super::Runtime
/// [`Runtime::from_lib`]: super::Runtime
pub trait Registerable: Sized {
    /// Create a library containing this item.
    fn into_lib(self) -> Library {
        let mut lib = Library::new();
        self.add_to_lib(&mut lib);
        lib
    }

    /// Add this item to an existing library.
    fn add_to_lib(self, lib: &mut Library);
}

/// A collection of registerable items.
///
/// <div class="warning">
///
/// This type can be constructed manually via [`Library::new`] and
/// [`Library::add`] or via the [`library!`](crate::library) macro.
///
/// </div>
#[derive(Clone, Debug)]
pub struct Library {
    pub(crate) items: Vec<Item>,
}

impl Default for Library {
    fn default() -> Self {
        Self::new()
    }
}

impl Library {
    /// Create a new [`Library`].
    pub fn new() -> Self {
        Self { items: Vec::new() }
    }

    /// Add an item to the [`Library`].
    pub fn add(&mut self, item: Item) {
        self.items.push(item);
    }
}

impl Registerable for Library {
    fn into_lib(self) -> Library {
        self
    }

    fn add_to_lib(self, lib: &mut Library) {
        lib.items.extend(self.items);
    }
}

impl From<Vec<Item>> for Library {
    fn from(value: Vec<Item>) -> Self {
        Self { items: value }
    }
}

impl Registerable for Item {
    fn add_to_lib(self, lib: &mut Library) {
        lib.add(self)
    }
}

impl<const N: usize, T: Registerable> Registerable for [T; N] {
    fn add_to_lib(self, lib: &mut Library) {
        for el in self {
            el.add_to_lib(lib);
        }
    }
}

impl<T: Registerable> Registerable for Vec<T> {
    fn add_to_lib(self, lib: &mut Library) {
        for el in self {
            el.add_to_lib(lib);
        }
    }
}

/// A module containing other items
///
/// <div class="warning">
///
/// Usually, this type is not constructed directly, but created by the
/// [`library!`](crate::library) macro
///
/// </div>
#[derive(Clone, Debug)]
pub struct Module {
    pub(crate) ident: Identifier,
    pub(crate) doc: String,
    pub(crate) children: Vec<Item>,
    pub(crate) location: Location,
}

impl Module {
    /// Construct a new [`Module`].
    ///
    /// Items can be added to this module with [`Module::add`].
    ///
    /// The `name` must be a valid Rust identifier. The `doc` parameter is the
    /// docstring that will be displayed in the documentation that Roto can
    /// generate. The `location` is used for error reporting while registering
    /// this item. You should generally pass `roto::location!()` to get a correct
    /// value.
    pub fn new(
        name: impl Into<Identifier>,
        doc: impl AsRef<str>,
        location: Location,
    ) -> Result<Self, RegistrationError> {
        let name = name.into();
        Rt::check_name(&location, name)?;

        Ok(Self {
            ident: name,
            doc: doc.as_ref().to_string(),
            children: Vec::new(),
            location,
        })
    }

    /// Add items to this module.
    pub fn add(&mut self, items: impl Registerable) {
        self.children.extend(items.into_lib().items)
    }
}

impl Registerable for Module {
    fn add_to_lib(self, lib: &mut Library) {
        lib.add(self.into())
    }
}

impl From<Module> for Item {
    fn from(value: Module) -> Self {
        Item::Module(value)
    }
}

/// A Roto type
///
/// This type will be cloned and dropped many times, so make sure to have
/// a cheap [`Clone`] and [`Drop`] implementations, for example an
/// [`Rc`](std::rc::Rc) or an [`Arc`](std::sync::Arc).
///
/// Use one of the [`Type::clone`] or [`Type::copy`] constructors to construct
/// this type. [`Type::copy`] will generally be more performant than
/// [`Type::clone`], so you should prefer that if the type implements [`Copy`].
///
/// <div class="warning">
///
/// Usually, this type is not constructed directly, but created by the
/// [`library!`](crate::library) macro
///
/// </div>
#[derive(Clone, Debug)]
pub struct Type {
    pub(crate) ident: Identifier,
    pub(crate) rust_name: &'static str,
    pub(crate) doc: String,
    pub(crate) type_id: TypeId,
    pub(crate) layout: Layout,
    pub(crate) movability: Movability,
    pub(crate) location: Location,
}

impl Type {
    /// A type implementing `Clone`.
    ///
    /// The `name` must be a valid Rust identifier. The `doc` parameter is the
    /// docstring that will be displayed in the documentation that Roto can
    /// generate. The `location` is used for error reporting while registering
    /// this item. You should generally pass `roto::location!()` to get a correct
    /// value.
    ///
    /// ```rust
    /// use roto::{Type, Val, location};
    ///
    /// #[derive(Clone)]
    /// struct Foo(i32);
    ///
    /// Type::clone::<Val<Foo>>("Foo", "This is a foo!", location!()).unwrap();
    /// ```
    pub fn clone<T: Value + Clone>(
        name: impl Into<Identifier>,
        doc: impl AsRef<str>,
        location: Location,
    ) -> Result<Self, RegistrationError> {
        let movability = Movability::CloneDrop(CloneDrop {
            clone: extern_clone::<T> as _,
            drop: extern_drop::<T> as _,
        });
        Self::new::<T>(name, doc, movability, location)
    }

    /// A type implementing `Copy`.
    ///
    /// The `name` must be a valid Roto identifier. The `doc` parameter is the
    /// docstring that will be displayed in the documentation that Roto can
    /// generate. The `location` is used for error reporting while registering
    /// this item. You should generally pass [`roto::location!()`] to get a correct
    /// value.
    ///
    /// ```rust
    /// use roto::{Type, Val, location};
    ///
    /// #[derive(Clone, Copy)]
    /// struct Foo(i32);
    ///
    /// Type::copy::<Val<Foo>>("Foo", "This is a foo!", location!()).unwrap();
    /// ```
    pub fn copy<T: Value + Copy>(
        name: impl Into<Identifier>,
        doc: impl AsRef<str>,
        location: Location,
    ) -> Result<Self, RegistrationError> {
        Self::new::<T>(name, doc, Movability::Copy, location)
    }

    /// For internal use only, might lead to unexpected behaviour if used incorrectly
    pub(crate) fn value<T: Value + Copy>(
        name: impl Into<Identifier>,
        doc: impl AsRef<str>,
        location: Location,
    ) -> Result<Self, RegistrationError> {
        Self::new::<T>(name, doc, Movability::Value, location)
    }

    fn new<T: Value>(
        name: impl Into<Identifier>,
        doc: impl AsRef<str>,
        movability: Movability,
        location: Location,
    ) -> Result<Self, RegistrationError> {
        let name = name.into();
        Rt::check_name(&location, name)?;

        let ty = T::resolve();

        let is_allowed = match ty.description {
            TypeDescription::Leaf => true,
            TypeDescription::Val(_) => true,
            TypeDescription::Option(_) => false,
            TypeDescription::Verdict(_, _) => false,
            TypeDescription::List(_) => false,
        };

        if !is_allowed {
            return Err(RegistrationError {
                message: format!(
                    "Cannot register the type `{}`. Only `Val<T>` types can be registered",
                    ty.rust_name
                ),
                location,
            });
        }

        Ok(Self {
            ident: name,
            rust_name: std::any::type_name::<T>(),
            doc: doc.as_ref().into(),
            type_id: ty.type_id,
            layout: ty.layout,
            movability,
            location,
        })
    }
}

impl Registerable for Type {
    fn add_to_lib(self, lib: &mut Library) {
        lib.add(self.into())
    }
}

impl From<Type> for Item {
    fn from(value: Type) -> Self {
        Item::Type(value)
    }
}

/// A function that can be registered.
///
/// <div class="warning">
///
/// Usually, this type is not constructed directly, but created by the
/// [`library!`](crate::library) macro
///
/// </div>
#[derive(Clone, Debug)]
pub struct Function {
    pub(crate) ident: Identifier,
    pub(crate) doc: String,
    pub(crate) params: Vec<Identifier>,
    pub(crate) func: FunctionDescription,
    pub(crate) sig: Option<String>,
    pub(crate) location: Location,
    pub(crate) vtables: Vec<Identifier>,
}

impl Function {
    /// Construct a new [`Function`].
    ///
    /// The function to be registered is passed as `func` and must implement
    /// [`RegisterableFn`].
    ///
    /// The `name` must be a valid Roto identifier. The `doc` parameter is the
    /// docstring that will be displayed in the documentation that Roto can
    /// generate. With `params`, you can pass the names for each of the
    /// parameters of the function, this is also used for generating
    /// documentation. The `location` is used for error reporting while
    /// registering this item. You should generally pass [`roto::location!()`]
    /// to get a correct value.
    ///
    /// ```rust
    /// use roto::{Function, location};
    ///
    /// fn double(x: i32) -> i32 {
    ///     2 * x
    /// }
    ///
    /// Function::new(
    ///     "double",
    ///     "Double this value.",
    ///     vec!["x"],
    ///     double,
    ///     location!(),
    /// ).unwrap();
    /// ```
    pub fn new<F, A, R, O>(
        name: impl Into<Identifier>,
        doc: impl AsRef<str>,
        mut params: Vec<&str>,
        func: F,
        location: Location,
    ) -> Result<Self, RegistrationError>
    where
        F: RegisterableFn<A, R, O>,
    {
        let name = name.into();
        Rt::check_name(&location, name)?;

        if F::HAS_OUT_PTR {
            params.remove(0);
        }

        let func = FunctionDescription::of(func);

        Ok(Self {
            ident: name,
            doc: doc.as_ref().into(),
            params: params.into_iter().map(|p| p.into()).collect(),
            sig: None,
            func,
            vtables: Vec::new(),
            location,
        })
    }

    /// Create a new generic Roto function
    ///
    /// This is very dangerous, since the generic signature must match up with the given
    /// function. At the moment, there are not enough guard rails in place to expose this
    /// functionality to downstream users, so this function is kept private.
    pub(crate) unsafe fn new_generic<F, A, R, O>(
        name: impl Into<Identifier>,
        doc: impl AsRef<str>,
        mut params: Vec<&str>,
        func: F,
        sig: &str,
        vtables: Vec<&str>,
        location: Location,
    ) -> Result<Self, RegistrationError>
    where
        F: RegisterableFn<A, R, O>,
    {
        let name = name.into();
        Rt::check_name(&location, name)?;

        if F::HAS_OUT_PTR {
            params.remove(0);
        }

        let func = FunctionDescription::of(func);

        Ok(Self {
            ident: name,
            doc: doc.as_ref().into(),
            params: params.into_iter().map(|p| p.into()).collect(),
            sig: Some(sig.to_owned()),
            func,
            vtables: vtables.into_iter().map(|p| p.into()).collect(),
            location,
        })
    }
}

impl Registerable for Function {
    fn add_to_lib(self, lib: &mut Library) {
        lib.add(self.into())
    }
}

impl From<Function> for Item {
    fn from(value: Function) -> Self {
        Item::Function(value)
    }
}

/// A constant value
///
/// <div class="warning">
///
/// Usually, this type is not constructed directly, but created by the
/// [`library!`](crate::library) macro
///
/// </div>
#[derive(Clone, Debug)]
pub struct Constant {
    pub(crate) ident: Identifier,
    pub(crate) type_id: TypeId,
    pub(crate) doc: String,
    pub(crate) value: ConstantValue,
    pub(crate) location: Location,
}

impl Constant {
    /// Construct a new [`Constant`].
    ///
    /// The value to be registered is passed as `val` and must implement
    /// [`Value`], like any registerable type.
    ///
    /// The `name` must be a valid Roto identifier. The `doc` parameter is the
    /// docstring that will be displayed in the documentation that Roto can
    /// generate. The `location` is used for error reporting while
    /// registering this item. You should generally pass [`roto::location!()`]
    /// to get a correct value.
    ///
    /// ```rust
    /// use roto::{Constant, Val, location};
    ///
    /// Constant::new(
    ///     "PI",
    ///     "The value of pi as f32",
    ///     3.14f32,
    ///     location!(),
    /// ).unwrap();
    /// ```
    pub fn new<T: Value>(
        name: impl Into<Identifier>,
        doc: impl AsRef<str>,
        val: T,
        location: Location,
    ) -> Result<Self, RegistrationError>
    where
        T::Transformed: Send + Sync + 'static,
    {
        let name = name.into();
        Rt::check_name(&location, name)?;

        let ty = T::resolve();

        Ok(Self {
            ident: name,
            doc: doc.as_ref().into(),
            type_id: ty.type_id,
            value: ConstantValue::new(val.transform()),
            location,
        })
    }
}

impl Registerable for Constant {
    fn add_to_lib(self, lib: &mut Library) {
        lib.add(self.into())
    }
}

impl From<Constant> for Item {
    fn from(value: Constant) -> Self {
        Item::Constant(value)
    }
}

/// An impl block, which adds methods to a type.
///
/// <div class="warning">
///
/// Usually, this type is not constructed directly, but created by the
/// [`library!`](crate::library) macro
///
/// </div>
#[derive(Clone, Debug)]
pub struct Impl {
    pub(crate) ty: TypeId,
    pub(crate) children: Vec<Item>,
    pub(crate) location: Location,
}

impl Impl {
    /// Construct a new [`Impl`] block for a given type `T`.
    ///
    /// The `location` is used for error reporting while registering this item.
    /// You should generally pass [`roto::location!()`] to get a correct value.
    ///
    /// ```rust
    /// use roto::{Impl, location, library};
    ///
    /// let mut impl_u32 = Impl::new::<u32>(location!());
    /// impl_u32.add(library! { /* more items */ });
    /// ```
    pub fn new<T: Value>(location: Location) -> Self {
        let ty = T::resolve();
        Self {
            ty: ty.type_id,
            children: Vec::new(),
            location,
        }
    }

    /// Add more registerable items to this [`Impl`] block.
    pub fn add(&mut self, items: impl Registerable) {
        self.children.extend(items.into_lib().items)
    }
}

impl Registerable for Impl {
    fn add_to_lib(self, lib: &mut Library) {
        lib.add(self.into())
    }
}

impl From<Impl> for Item {
    fn from(value: Impl) -> Self {
        Item::Impl(value)
    }
}

/// A use item, representing an import of items.
///
/// <div class="warning">
///
/// Usually, this type is not constructed directly, but created by the
/// [`library!`](crate::library) macro
///
/// </div>
#[derive(Clone, Debug)]
pub struct Use {
    pub(crate) imports: Vec<Vec<String>>,
    pub(crate) location: Location,
}

impl Use {
    /// Construct a new [`Use`].
    ///
    /// Each element of `imports` represents a path to an item to import.
    ///
    /// The `location` is used for error reporting while registering this item.
    /// You should generally pass [`roto::location!()`] to get a correct value.
    ///
    /// ```rust
    /// use roto::{Use, location};
    ///
    /// Use::new(
    ///     vec![
    ///         vec!["Verdict".into(), "Accept".into()],
    ///         vec!["Verdict".into(), "Reject".into()],
    ///     ],
    ///     location!(),
    /// );
    pub fn new(imports: Vec<Vec<String>>, location: Location) -> Self {
        Self { imports, location }
    }
}

impl Registerable for Use {
    fn add_to_lib(self, lib: &mut Library) {
        lib.add(self.into())
    }
}

impl From<Use> for Item {
    fn from(value: Use) -> Self {
        Item::Use(value)
    }
}