rune 0.12.0

An embeddable dynamic programming language for Rust.
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
//! Crate used for definint native *modules*.
//!
//! A native module is one that provides rune with functions and types through
//! native code.

use crate::collections::{HashMap, HashSet};
use crate::compile::{ContextError, IntoComponent, Item, Named};
use crate::macros::{MacroContext, TokenStream};
use crate::runtime::{
    ConstValue, FromValue, FunctionHandler, Future, GeneratorState, MacroHandler, Protocol, Stack,
    StaticType, ToValue, TypeCheck, TypeInfo, TypeOf, UnsafeFromValue, Value, VmError, VmErrorKind,
};
use crate::{Hash, InstFnInfo, InstFnKind, InstFnName};
use std::fmt;
use std::future;
use std::sync::Arc;

/// Trait to handle the installation of auxilliary functions for a type
/// installed into a module.
pub trait InstallWith {
    /// Hook to install more things into the module.
    fn install_with(_: &mut Module) -> Result<(), ContextError> {
        Ok(())
    }
}

/// The static hash and diagnostical information about a type.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AssocType {
    /// Hash of the type.
    pub hash: Hash,
    /// Type information of the instance function.
    pub type_info: TypeInfo,
}

/// Specialized information on `Option` types.
pub(crate) struct UnitType {
    /// Item of the unit type.
    pub(crate) name: Box<str>,
}

/// Specialized information on `GeneratorState` types.
pub(crate) struct InternalEnum {
    /// The name of the internal enum.
    pub(crate) name: &'static str,
    /// The result type.
    pub(crate) base_type: Item,
    /// The static type of the enum.
    pub(crate) static_type: &'static StaticType,
    /// Internal variants.
    pub(crate) variants: Vec<InternalVariant>,
}

impl InternalEnum {
    /// Construct a new handler for an internal enum.
    fn new<N>(name: &'static str, base_type: N, static_type: &'static StaticType) -> Self
    where
        N: IntoIterator,
        N::Item: IntoComponent,
    {
        InternalEnum {
            name,
            base_type: Item::with_item(base_type),
            static_type,
            variants: Vec::new(),
        }
    }

    /// Register a new variant.
    fn variant<C, Args>(&mut self, name: &'static str, type_check: TypeCheck, constructor: C)
    where
        C: Function<Args>,
    {
        let constructor: Arc<FunctionHandler> =
            Arc::new(move |stack, args| constructor.fn_call(stack, args));

        self.variants.push(InternalVariant {
            name,
            type_check,
            args: C::args(),
            constructor,
        });
    }
}

/// Internal variant.
pub(crate) struct InternalVariant {
    /// The name of the variant.
    pub(crate) name: &'static str,
    /// Type check for the variant.
    pub(crate) type_check: TypeCheck,
    /// Arguments for the variant.
    pub(crate) args: usize,
    /// The constructor of the variant.
    pub(crate) constructor: Arc<FunctionHandler>,
}

/// Data for an opaque type. If `spec` is set, indicates things which are known
/// about that type.
pub(crate) struct Type {
    /// The name of the installed type which will be the final component in the
    /// item it will constitute.
    pub(crate) name: Box<str>,
    /// Type information for the installed type.
    pub(crate) type_info: TypeInfo,
    /// The specification for the type.
    pub(crate) spec: Option<TypeSpecification>,
}

/// Metadata about a variant.
pub struct Variant {
    /// Variant metadata.
    pub(crate) kind: VariantKind,
    /// Handler to use if this variant can be constructed through a regular function call.
    pub(crate) constructor: Option<Arc<FunctionHandler>>,
}

impl fmt::Debug for Variant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Variant")
            .field("kind", &self.kind)
            .field("constructor", &self.constructor.is_some())
            .finish()
    }
}

/// The kind of the variant.
#[derive(Debug)]
pub(crate) enum VariantKind {
    /// Variant is a Tuple variant.
    Tuple(Tuple),
    /// Variant is a Struct variant.
    Struct(Struct),
    /// Variant is a Unit variant.
    Unit,
}

impl Variant {
    /// Construct metadata for a tuple variant.
    #[inline]
    pub fn tuple(args: usize) -> Self {
        Self {
            kind: VariantKind::Tuple(Tuple { args }),
            constructor: None,
        }
    }

    /// Construct metadata for a tuple variant.
    #[inline]
    pub fn st<const N: usize>(fields: [&'static str; N]) -> Self {
        Self {
            kind: VariantKind::Struct(Struct {
                fields: fields.into_iter().map(Box::<str>::from).collect(),
            }),
            constructor: None,
        }
    }

    /// Construct metadata for a unit variant.
    #[inline]
    pub fn unit() -> Self {
        Self {
            kind: VariantKind::Unit,
            constructor: None,
        }
    }
}

/// Metadata about a tuple or tuple variant.
#[derive(Debug)]
pub struct Tuple {
    /// The number of fields.
    pub(crate) args: usize,
}

/// The type specification for a native struct.
#[derive(Debug)]
pub(crate) struct Struct {
    /// The names of the struct fields known at compile time.
    pub(crate) fields: HashSet<Box<str>>,
}

/// The type specification for a native enum.
pub(crate) struct Enum {
    /// The variants.
    pub(crate) variants: Vec<(Box<str>, Variant)>,
}

/// A type specification.
pub(crate) enum TypeSpecification {
    Struct(Struct),
    Enum(Enum),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum AssocKind {
    IndexFn(Protocol),
    FieldFn(Protocol),
    Instance,
}

impl AssocKind {
    /// Convert the kind into a hash function.
    pub(crate) fn hash(self, instance_type: Hash, key: Hash) -> Hash {
        match self {
            Self::IndexFn(protocol) => Hash::index_fn(protocol, instance_type, key),
            Self::FieldFn(protocol) => Hash::field_fn(protocol, instance_type, key),
            Self::Instance => Hash::instance_function(instance_type, key),
        }
    }
}

pub(crate) struct AssocFn {
    pub(crate) handler: Arc<FunctionHandler>,
    pub(crate) args: Option<usize>,
    pub(crate) type_info: TypeInfo,
    pub(crate) name: InstFnKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct AssocKey {
    pub(crate) type_hash: Hash,
    pub(crate) hash: Hash,
    pub(crate) parameters: Hash,
    pub(crate) kind: AssocKind,
}

pub(crate) struct ModuleFn {
    pub(crate) handler: Arc<FunctionHandler>,
    pub(crate) args: Option<usize>,
}

pub(crate) struct Macro {
    pub(crate) handler: Arc<MacroHandler>,
}

/// A [Module] that is a collection of native functions and types.
///
/// Needs to be installed into a [Context][crate::compile::Context] using
/// [Context::install][crate::compile::Context::install].
#[derive(Default)]
pub struct Module {
    /// The name of the module.
    pub(crate) item: Item,
    /// Free functions.
    pub(crate) functions: HashMap<Item, ModuleFn>,
    /// MacroHandler handlers.
    pub(crate) macros: HashMap<Item, Macro>,
    /// Constant values.
    pub(crate) constants: HashMap<Item, ConstValue>,
    /// Instance functions.
    pub(crate) associated_functions: HashMap<AssocKey, AssocFn>,
    /// Registered types.
    pub(crate) types: HashMap<Hash, Type>,
    /// Registered unit type.
    pub(crate) unit_type: Option<UnitType>,
    /// Registered generator state type.
    pub(crate) internal_enums: Vec<InternalEnum>,
}

impl Module {
    /// Create an empty module for the root path.
    pub fn new() -> Self {
        Self::default()
    }

    /// Construct a new module for the given item.
    pub fn with_item<I>(iter: I) -> Self
    where
        I: IntoIterator,
        I::Item: IntoComponent,
    {
        Self::inner_new(Item::with_item(iter))
    }

    /// Construct a new module for the given crate.
    pub fn with_crate(name: &str) -> Self {
        Self::inner_new(Item::with_crate(name))
    }

    /// Construct a new module for the given crate.
    pub fn with_crate_item<I>(name: &str, iter: I) -> Self
    where
        I: IntoIterator,
        I::Item: IntoComponent,
    {
        Self::inner_new(Item::with_crate_item(name, iter))
    }

    fn inner_new(item: Item) -> Self {
        Self {
            item,
            functions: Default::default(),
            macros: Default::default(),
            associated_functions: Default::default(),
            types: Default::default(),
            unit_type: None,
            internal_enums: Vec::new(),
            constants: Default::default(),
        }
    }

    /// Register a type. Registering a type is mandatory in order to register
    /// instance functions using that type.
    ///
    /// This will allow the type to be used within scripts, using the item named
    /// here.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::Any;
    ///
    /// #[derive(Any)]
    /// struct MyBytes {
    ///     queue: Vec<String>,
    /// }
    ///
    /// impl MyBytes {
    ///     fn len(&self) -> usize {
    ///         self.queue.len()
    ///     }
    /// }
    ///
    /// # fn main() -> rune::Result<()> {
    /// // Register `len` without registering a type.
    /// let mut module = rune::Module::default();
    /// // Note: cannot do this until we have registered a type.
    /// module.inst_fn("len", MyBytes::len)?;
    ///
    /// let mut context = rune::Context::new();
    /// assert!(context.install(&module).is_err());
    ///
    /// // Register `len` properly.
    /// let mut module = rune::Module::default();
    ///
    /// module.ty::<MyBytes>()?;
    /// module.inst_fn("len", MyBytes::len)?;
    ///
    /// let mut context = rune::Context::new();
    /// assert!(context.install(&module).is_ok());
    /// # Ok(()) }
    /// ```
    pub fn ty<T>(&mut self) -> Result<(), ContextError>
    where
        T: Named + TypeOf + InstallWith,
    {
        let type_hash = T::type_hash();
        let type_info = T::type_info();

        let ty = Type {
            name: T::full_name(),
            type_info,
            spec: None,
        };

        if let Some(old) = self.types.insert(type_hash, ty) {
            return Err(ContextError::ConflictingType {
                item: Item::with_item(&[T::full_name()]),
                type_info: old.type_info,
            });
        }

        T::install_with(self)?;
        Ok(())
    }

    /// Register that the given type is a struct, and that it has the given
    /// compile-time metadata. This implies that each field has a
    /// [Protocol::GET] field function.
    ///
    /// This is typically not used directly, but is used automatically with the
    /// [Any][crate::Any] derive.
    pub fn struct_meta<T, const N: usize>(
        &mut self,
        fields: [&'static str; N],
    ) -> Result<(), ContextError>
    where
        T: Named + TypeOf,
    {
        let type_hash = T::type_hash();

        let ty = match self.types.get_mut(&type_hash) {
            Some(ty) => ty,
            None => {
                return Err(ContextError::MissingType {
                    item: Item::with_item(&[T::full_name()]),
                    type_info: T::type_info(),
                });
            }
        };

        let old = ty.spec.replace(TypeSpecification::Struct(Struct {
            fields: fields.into_iter().map(Box::<str>::from).collect(),
        }));

        if old.is_some() {
            return Err(ContextError::ConflictingTypeMeta {
                item: Item::with_item(&[T::full_name()]),
                type_info: ty.type_info.clone(),
            });
        }

        Ok(())
    }

    /// Register enum metadata for the given type `T`. This allows an enum to be
    /// used in limited ways in Rune.
    pub fn enum_meta<T, const N: usize>(
        &mut self,
        variants: [(&'static str, Variant); N],
    ) -> Result<(), ContextError>
    where
        T: Named + TypeOf,
    {
        let type_hash = T::type_hash();

        let ty = match self.types.get_mut(&type_hash) {
            Some(ty) => ty,
            None => {
                return Err(ContextError::MissingType {
                    item: Item::with_item(&[T::full_name()]),
                    type_info: T::type_info(),
                });
            }
        };

        let old = ty.spec.replace(TypeSpecification::Enum(Enum {
            variants: variants
                .into_iter()
                .map(|(name, variant)| (Box::from(name), variant))
                .collect(),
        }));

        if old.is_some() {
            return Err(ContextError::ConflictingTypeMeta {
                item: Item::with_item(&[T::full_name()]),
                type_info: ty.type_info.clone(),
            });
        }

        Ok(())
    }

    /// Register a variant constructor for type `T`.
    pub fn variant_constructor<Func, Args, T>(
        &mut self,
        index: usize,
        constructor: Func,
    ) -> Result<(), ContextError>
    where
        T: Named + TypeOf,
        Func: Function<Args, Return = T>,
    {
        let type_hash = T::type_hash();

        let ty = match self.types.get_mut(&type_hash) {
            Some(ty) => ty,
            None => {
                return Err(ContextError::MissingType {
                    item: Item::with_item(&[T::full_name()]),
                    type_info: T::type_info(),
                });
            }
        };

        let en = match &mut ty.spec {
            Some(TypeSpecification::Enum(en)) => en,
            _ => {
                return Err(ContextError::MissingEnum {
                    item: Item::with_item(&[T::full_name()]),
                    type_info: T::type_info(),
                });
            }
        };

        let variant = match en.variants.get_mut(index) {
            Some((_, variant)) => variant,
            _ => {
                return Err(ContextError::MissingVariant {
                    type_info: T::type_info(),
                    index,
                });
            }
        };

        if variant.constructor.is_some() {
            return Err(ContextError::VariantConstructorConflict {
                type_info: T::type_info(),
                index,
            });
        }

        variant.constructor = Some(Arc::new(move |stack, args| {
            constructor.fn_call(stack, args)
        }));

        Ok(())
    }

    /// Construct type information for the `unit` type.
    ///
    /// Registering this allows the given type to be used in Rune scripts when
    /// referring to the `unit` type.
    ///
    /// # Examples
    ///
    /// This shows how to register the unit type `()` as `nonstd::unit`.
    ///
    /// ```
    /// use rune::Module;
    ///
    /// # fn main() -> rune::Result<()> {
    /// let mut module = Module::with_item(&["nonstd"]);
    /// module.unit("unit")?;
    /// # Ok(()) }
    pub fn unit<N>(&mut self, name: N) -> Result<(), ContextError>
    where
        N: AsRef<str>,
    {
        if self.unit_type.is_some() {
            return Err(ContextError::UnitAlreadyPresent);
        }

        self.unit_type = Some(UnitType {
            name: <Box<str>>::from(name.as_ref()),
        });

        Ok(())
    }

    /// Construct the type information for the `GeneratorState` type.
    ///
    /// Registering this allows the given type to be used in Rune scripts when
    /// referring to the `GeneratorState` type.
    ///
    /// # Examples
    ///
    /// This shows how to register the `GeneratorState` as
    /// `nonstd::generator::GeneratorState`.
    ///
    /// ```
    /// use rune::Module;
    ///
    /// # fn main() -> rune::Result<()> {
    /// let mut module = Module::with_crate_item("nonstd", &["generator"]);
    /// module.generator_state(&["GeneratorState"])?;
    /// # Ok(()) }
    pub fn generator_state<N>(&mut self, name: N) -> Result<(), ContextError>
    where
        N: IntoIterator,
        N::Item: IntoComponent,
    {
        let mut enum_ =
            InternalEnum::new("GeneratorState", name, crate::runtime::GENERATOR_STATE_TYPE);

        // Note: these numeric variants are magic, and must simply match up with
        // what's being used in the virtual machine implementation for these
        // types.
        enum_.variant(
            "Complete",
            TypeCheck::GeneratorState(0),
            GeneratorState::Complete,
        );
        enum_.variant(
            "Yielded",
            TypeCheck::GeneratorState(1),
            GeneratorState::Yielded,
        );

        self.internal_enums.push(enum_);
        Ok(())
    }
    /// Construct type information for the `Option` type.
    ///
    /// Registering this allows the given type to be used in Rune scripts when
    /// referring to the `Option` type.
    ///
    /// # Examples
    ///
    /// This shows how to register the `Option` as `nonstd::option::Option`.
    ///
    /// ```
    /// use rune::Module;
    ///
    /// # fn main() -> rune::Result<()> {
    /// let mut module = Module::with_crate_item("nonstd", &["option"]);
    /// module.option(&["Option"])?;
    /// # Ok(()) }
    pub fn option<N>(&mut self, name: N) -> Result<(), ContextError>
    where
        N: IntoIterator,
        N::Item: IntoComponent,
    {
        let mut enum_ = InternalEnum::new("Option", name, crate::runtime::OPTION_TYPE);

        // Note: these numeric variants are magic, and must simply match up with
        // what's being used in the virtual machine implementation for these
        // types.
        enum_.variant("Some", TypeCheck::Option(0), Option::<Value>::Some);
        enum_.variant("None", TypeCheck::Option(1), || Option::<Value>::None);
        self.internal_enums.push(enum_);
        Ok(())
    }

    /// Construct type information for the internal `Result` type.
    ///
    /// Registering this allows the given type to be used in Rune scripts when
    /// referring to the `Result` type.
    ///
    /// # Examples
    ///
    /// This shows how to register the `Result` as `nonstd::result::Result`.
    ///
    /// ```
    /// use rune::Module;
    ///
    /// # fn main() -> rune::Result<()> {
    /// let mut module = Module::with_crate_item("nonstd", &["result"]);
    /// module.result(&["Result"])?;
    /// # Ok(()) }
    pub fn result<N>(&mut self, name: N) -> Result<(), ContextError>
    where
        N: IntoIterator,
        N::Item: IntoComponent,
    {
        let mut enum_ = InternalEnum::new("Result", name, crate::runtime::RESULT_TYPE);

        // Note: these numeric variants are magic, and must simply match up with
        // what's being used in the virtual machine implementation for these
        // types.
        enum_.variant("Ok", TypeCheck::Result(0), Result::<Value, Value>::Ok);
        enum_.variant("Err", TypeCheck::Result(1), Result::<Value, Value>::Err);
        self.internal_enums.push(enum_);
        Ok(())
    }

    /// Register a function that cannot error internally.
    ///
    /// # Examples
    ///
    /// ```
    /// fn add_ten(value: i64) -> i64 {
    ///     value + 10
    /// }
    ///
    /// # fn main() -> rune::Result<()> {
    /// let mut module = rune::Module::default();
    ///
    /// module.function(&["add_ten"], add_ten)?;
    /// module.function(&["empty"], || Ok::<_, rune::Error>(()))?;
    /// module.function(&["string"], |a: String| Ok::<_, rune::Error>(()))?;
    /// module.function(&["optional"], |a: Option<String>| Ok::<_, rune::Error>(()))?;
    /// # Ok(()) }
    /// ```
    pub fn function<Func, Args, N>(&mut self, name: N, f: Func) -> Result<(), ContextError>
    where
        Func: Function<Args>,
        N: IntoIterator,
        N::Item: IntoComponent,
    {
        let name = Item::with_item(name);

        if self.functions.contains_key(&name) {
            return Err(ContextError::ConflictingFunctionName { name });
        }

        self.functions.insert(
            name,
            ModuleFn {
                handler: Arc::new(move |stack, args| f.fn_call(stack, args)),
                args: Some(Func::args()),
            },
        );

        Ok(())
    }

    /// Register a constant value, at a crate, module or associated level.
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// # fn main() -> rune::Result<()> {
    /// let mut module = rune::Module::default();
    ///
    /// module.constant(&["TEN"], 10)?; // a global TEN value
    /// module.constant(&["MyType", "TEN"], 10)?; // looks like an associated value
    ///
    /// # Ok(()) }
    /// ```
    pub fn constant<N, V>(&mut self, name: N, value: V) -> Result<(), ContextError>
    where
        N: IntoIterator,
        N::Item: IntoComponent,
        V: ToValue,
    {
        let name = Item::with_item(name);

        if self.constants.contains_key(&name) {
            return Err(ContextError::ConflictingConstantName { name });
        }

        let value = match value.to_value() {
            Ok(v) => v,
            Err(e) => return Err(ContextError::ValueError { error: e }),
        };

        let constant_value = match <ConstValue as FromValue>::from_value(value) {
            Ok(v) => v,
            Err(e) => return Err(ContextError::ValueError { error: e }),
        };

        self.constants.insert(name, constant_value);

        Ok(())
    }

    /// Register a native macro handler.
    pub fn macro_<N, M>(&mut self, name: N, f: M) -> Result<(), ContextError>
    where
        M: 'static
            + Send
            + Sync
            + Fn(&mut MacroContext<'_>, &TokenStream) -> crate::Result<TokenStream>,
        N: IntoIterator,
        N::Item: IntoComponent,
    {
        let name = Item::with_item(name);

        if self.macros.contains_key(&name) {
            return Err(ContextError::ConflictingFunctionName { name });
        }

        let handler: Arc<MacroHandler> = Arc::new(f);
        self.macros.insert(name, Macro { handler });
        Ok(())
    }

    /// Register a function.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> rune::Result<()> {
    /// let mut module = rune::Module::default();
    ///
    /// module.async_function(&["empty"], || async { () })?;
    /// module.async_function(&["empty_fallible"], || async { Ok::<_, rune::Error>(()) })?;
    /// module.async_function(&["string"], |a: String| async { Ok::<_, rune::Error>(()) })?;
    /// module.async_function(&["optional"], |a: Option<String>| async { Ok::<_, rune::Error>(()) })?;
    /// # Ok(()) }
    /// ```
    pub fn async_function<Func, Args, N>(&mut self, name: N, f: Func) -> Result<(), ContextError>
    where
        Func: AsyncFunction<Args>,
        N: IntoIterator,
        N::Item: IntoComponent,
    {
        let name = Item::with_item(name);

        if self.functions.contains_key(&name) {
            return Err(ContextError::ConflictingFunctionName { name });
        }

        self.functions.insert(
            name,
            ModuleFn {
                handler: Arc::new(move |stack, args| f.fn_call(stack, args)),
                args: Some(Func::args()),
            },
        );

        Ok(())
    }

    /// Register a raw function which interacts directly with the virtual
    /// machine.
    pub fn raw_fn<F, N>(&mut self, name: N, f: F) -> Result<(), ContextError>
    where
        F: 'static + Fn(&mut Stack, usize) -> Result<(), VmError> + Send + Sync,
        N: IntoIterator,
        N::Item: IntoComponent,
    {
        let name = Item::with_item(name);

        if self.functions.contains_key(&name) {
            return Err(ContextError::ConflictingFunctionName { name });
        }

        self.functions.insert(
            name,
            ModuleFn {
                handler: Arc::new(move |stack, args| f(stack, args)),
                args: None,
            },
        );

        Ok(())
    }

    /// Register an instance function.
    ///
    /// # Examples
    ///
    /// ```
    /// use rune::Any;
    ///
    /// #[derive(Any)]
    /// struct MyBytes {
    ///     queue: Vec<String>,
    /// }
    ///
    /// impl MyBytes {
    ///     fn new() -> Self {
    ///         Self {
    ///             queue: Vec::new(),
    ///         }
    ///     }
    ///
    ///     fn len(&self) -> usize {
    ///         self.queue.len()
    ///     }
    /// }
    ///
    /// # fn main() -> rune::Result<()> {
    /// let mut module = rune::Module::default();
    ///
    /// module.ty::<MyBytes>()?;
    /// module.function(&["MyBytes", "new"], MyBytes::new)?;
    /// module.inst_fn("len", MyBytes::len)?;
    ///
    /// let mut context = rune::Context::new();
    /// context.install(&module)?;
    /// # Ok(()) }
    /// ```
    pub fn inst_fn<N, Func, Args>(&mut self, name: N, f: Func) -> Result<(), ContextError>
    where
        N: InstFnName,
        Func: InstFn<Args>,
    {
        let name = name.info();
        let handler: Arc<FunctionHandler> = Arc::new(move |stack, args| f.fn_call(stack, args));
        let ty = Func::ty();
        let args = Some(Func::args());
        self.assoc_fn(name, handler, ty, args, AssocKind::Instance)
    }

    /// Install a protocol function that interacts with the given field.
    pub fn field_fn<N, Func, Args>(
        &mut self,
        protocol: Protocol,
        name: N,
        f: Func,
    ) -> Result<(), ContextError>
    where
        N: InstFnName,
        Func: InstFn<Args>,
    {
        let name = name.info();
        let handler: Arc<FunctionHandler> = Arc::new(move |stack, args| f.fn_call(stack, args));
        let ty = Func::ty();
        let args = Some(Func::args());
        self.assoc_fn(name, handler, ty, args, AssocKind::FieldFn(protocol))
    }

    /// Install a protocol function that interacts with the given index.
    ///
    /// An index can either be a field inside a tuple, or a variant inside of an
    /// enum as configured with [Module::enum_meta].
    pub fn index_fn<Func, Args>(
        &mut self,
        protocol: Protocol,
        index: usize,
        f: Func,
    ) -> Result<(), ContextError>
    where
        Func: InstFn<Args>,
    {
        let name = InstFnInfo::index(protocol, index);
        let handler: Arc<FunctionHandler> = Arc::new(move |stack, args| f.fn_call(stack, args));
        let ty = Func::ty();
        let args = Some(Func::args());
        self.assoc_fn(name, handler, ty, args, AssocKind::IndexFn(protocol))
    }

    /// Register an instance function.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::sync::atomic::AtomicU32;
    /// use std::sync::Arc;
    /// use rune::Any;
    ///
    /// #[derive(Clone, Debug, Any)]
    /// struct MyType {
    ///     value: Arc<AtomicU32>,
    /// }
    ///
    /// impl MyType {
    ///     async fn test(&self) -> rune::Result<()> {
    ///         Ok(())
    ///     }
    /// }
    ///
    /// # fn main() -> rune::Result<()> {
    /// let mut module = rune::Module::default();
    ///
    /// module.ty::<MyType>()?;
    /// module.async_inst_fn("test", MyType::test)?;
    /// # Ok(()) }
    /// ```
    pub fn async_inst_fn<N, Func, Args>(&mut self, name: N, f: Func) -> Result<(), ContextError>
    where
        N: InstFnName,
        Func: AsyncInstFn<Args>,
    {
        let name = name.info();
        let handler: Arc<FunctionHandler> = Arc::new(move |stack, args| f.fn_call(stack, args));
        let ty = Func::ty();
        let args = Some(Func::args());
        self.assoc_fn(name, handler, ty, args, AssocKind::Instance)
    }

    /// Install an associated function.
    fn assoc_fn(
        &mut self,
        name: InstFnInfo,
        handler: Arc<FunctionHandler>,
        ty: AssocType,
        args: Option<usize>,
        kind: AssocKind,
    ) -> Result<(), ContextError> {
        let key = AssocKey {
            type_hash: ty.hash,
            hash: name.hash,
            kind,
            parameters: name.parameters,
        };

        if self.associated_functions.contains_key(&key) {
            return Err(match name.kind {
                InstFnKind::Protocol(protocol) => ContextError::ConflictingProtocolFunction {
                    type_info: ty.type_info,
                    name: protocol.name.into(),
                },
                InstFnKind::Instance(name) => ContextError::ConflictingInstanceFunction {
                    type_info: ty.type_info,
                    name,
                },
                InstFnKind::Hash(hash) => ContextError::ConflictingInstanceFunctionHash {
                    type_info: ty.type_info,
                    hash,
                },
            });
        }

        let assoc_fn = AssocFn {
            handler,
            args,
            type_info: ty.type_info,
            name: name.kind,
        };

        self.associated_functions.insert(key, assoc_fn);
        Ok(())
    }
}

/// Trait used to provide the [function][Module::function] function.
pub trait Function<Args>: 'static + Send + Sync {
    /// The return type of the function.
    type Return;

    /// Get the number of arguments.
    fn args() -> usize;

    /// Perform the vm call.
    fn fn_call(&self, stack: &mut Stack, args: usize) -> Result<(), VmError>;
}

/// Trait used to provide the [async_function][Module::async_function] function.
pub trait AsyncFunction<Args>: 'static + Send + Sync {
    /// The return type of the function.
    type Return;

    /// Get the number of arguments.
    fn args() -> usize;

    /// Perform the vm call.
    fn fn_call(&self, stack: &mut Stack, args: usize) -> Result<(), VmError>;
}

/// Trait used to provide the [inst_fn][Module::inst_fn] function.
pub trait InstFn<Args>: 'static + Send + Sync {
    /// The type of the instance.
    type Instance;
    /// The return type of the function.
    type Return;

    /// Get the number of arguments.
    fn args() -> usize;

    /// Access static information on the instance type with the associated
    /// function.
    fn ty() -> AssocType;

    /// Perform the vm call.
    fn fn_call(&self, stack: &mut Stack, args: usize) -> Result<(), VmError>;
}

/// Trait used to provide the [async_inst_fn][Module::async_inst_fn] function.
pub trait AsyncInstFn<Args>: 'static + Send + Sync {
    /// The type of the instance.
    type Instance;
    /// The return type of the function.
    type Return;

    /// Get the number of arguments.
    fn args() -> usize;

    /// Access static information on the instance type with the associated
    /// function.
    fn ty() -> AssocType;

    /// Perform the vm call.
    fn fn_call(&self, stack: &mut Stack, args: usize) -> Result<(), VmError>;
}

macro_rules! impl_register {
    () => {
        impl_register!{@impl 0,}
    };

    ({$ty:ident, $var:ident, $num:expr}, $({$l_ty:ident, $l_var:ident, $l_num:expr},)*) => {
        impl_register!{@impl $num, {$ty, $var, $num}, $({$l_ty, $l_var, $l_num},)*}
        impl_register!{$({$l_ty, $l_var, $l_num},)*}
    };

    (@impl $count:expr, $({$ty:ident, $var:ident, $num:expr},)*) => {
        impl<Func, Return, $($ty,)*> Function<($($ty,)*)> for Func
        where
            Func: 'static + Send + Sync + Fn($($ty,)*) -> Return,
            Return: ToValue,
            $($ty: UnsafeFromValue,)*
        {
            type Return = Return;

            fn args() -> usize {
                $count
            }

            fn fn_call(&self, stack: &mut Stack, args: usize) -> Result<(), VmError> {
                impl_register!{@check-args $count, args}

                #[allow(unused_mut)]
                let mut it = stack.drain($count)?;
                $(let $var = it.next().unwrap();)*
                drop(it);

                // Safety: We hold a reference to the stack, so we can
                // guarantee that it won't be modified.
                //
                // The scope is also necessary, since we mutably access `stack`
                // when we return below.
                #[allow(unused)]
                let ret = unsafe {
                    impl_register!{@unsafe-vars $count, $($ty, $var, $num,)*}
                    let ret = self($(<$ty>::unsafe_coerce($var.0),)*);
                    impl_register!{@drop-stack-guards $($var),*}
                    ret
                };

                impl_register!{@return stack, ret, Return}
                Ok(())
            }
        }

        impl<Func, Return, $($ty,)*> AsyncFunction<($($ty,)*)> for Func
        where
            Func: 'static + Send + Sync + Fn($($ty,)*) -> Return,
            Return: 'static + future::Future,
            Return::Output: ToValue,
            $($ty: 'static + UnsafeFromValue,)*
        {
            type Return = Return;

            fn args() -> usize {
                $count
            }

            fn fn_call(&self, stack: &mut Stack, args: usize) -> Result<(), VmError> {
                impl_register!{@check-args $count, args}

                #[allow(unused_mut)]
                let mut it = stack.drain($count)?;
                $(let $var = it.next().unwrap();)*
                drop(it);

                // Safety: Future is owned and will only be called within the
                // context of the virtual machine, which will provide
                // exclusive thread-local access to itself while the future is
                // being polled.
                #[allow(unused_unsafe)]
                let ret = unsafe {
                    impl_register!{@unsafe-vars $count, $($ty, $var, $num,)*}

                    let fut = self($(<$ty>::unsafe_coerce($var.0),)*);

                    Future::new(async move {
                        let output = fut.await;
                        impl_register!{@drop-stack-guards $($var),*}
                        let value = output.to_value()?;
                        Ok(value)
                    })
                };

                impl_register!{@return stack, ret, Return}
                Ok(())
            }
        }

        impl<Func, Return, Instance, $($ty,)*> InstFn<(Instance, $($ty,)*)> for Func
        where
            Func: 'static + Send + Sync + Fn(Instance $(, $ty)*) -> Return,
            Return: ToValue,
            Instance: UnsafeFromValue + TypeOf,
            $($ty: UnsafeFromValue,)*
        {
            type Instance = Instance;
            type Return = Return;

            fn args() -> usize {
                $count + 1
            }

            fn ty() -> AssocType {
                AssocType {
                    hash: Instance::type_hash(),
                    type_info: Instance::type_info(),
                }
            }

            fn fn_call(&self, stack: &mut Stack, args: usize) -> Result<(), VmError> {
                impl_register!{@check-args ($count + 1), args}

                #[allow(unused_mut)]
                let mut it = stack.drain($count + 1)?;
                let inst = it.next().unwrap();
                $(let $var = it.next().unwrap();)*
                drop(it);

                // Safety: We hold a reference to the stack, so we can
                // guarantee that it won't be modified.
                //
                // The scope is also necessary, since we mutably access `stack`
                // when we return below.
                #[allow(unused)]
                let ret = unsafe {
                    impl_register!{@unsafe-inst-vars inst, $count, $($ty, $var, $num,)*}
                    let ret = self(Instance::unsafe_coerce(inst.0), $(<$ty>::unsafe_coerce($var.0),)*);
                    impl_register!{@drop-stack-guards inst, $($var),*}
                    ret
                };

                impl_register!{@return stack, ret, Return}
                Ok(())
            }
        }

        impl<Func, Return, Instance, $($ty,)*> AsyncInstFn<(Instance, $($ty,)*)> for Func
        where
            Func: 'static + Send + Sync + Fn(Instance $(, $ty)*) -> Return,
            Return: 'static + future::Future,
            Return::Output: ToValue,
            Instance: UnsafeFromValue + TypeOf,
            $($ty: UnsafeFromValue,)*
        {
            type Instance = Instance;
            type Return = Return;

            fn args() -> usize {
                $count + 1
            }

            fn ty() -> AssocType {
                AssocType {
                    hash: Instance::type_hash(),
                    type_info: Instance::type_info(),
                }
            }

            fn fn_call(&self, stack: &mut Stack, args: usize) -> Result<(), VmError> {
                impl_register!{@check-args ($count + 1), args}

                #[allow(unused_mut)]
                let mut it = stack.drain($count + 1)?;
                let inst = it.next().unwrap();
                $(let $var = it.next().unwrap();)*
                drop(it);

                // Safety: Future is owned and will only be called within the
                // context of the virtual machine, which will provide
                // exclusive thread-local access to itself while the future is
                // being polled.
                #[allow(unused)]
                let ret = unsafe {
                    impl_register!{@unsafe-inst-vars inst, $count, $($ty, $var, $num,)*}

                    let fut = self(Instance::unsafe_coerce(inst.0), $(<$ty>::unsafe_coerce($var.0),)*);

                    Future::new(async move {
                        let output = fut.await;
                        impl_register!{@drop-stack-guards inst, $($var),*}
                        let value = output.to_value()?;
                        Ok(value)
                    })
                };

                impl_register!{@return stack, ret, Return}
                Ok(())
            }
        }
    };

    (@return $stack:ident, $ret:ident, $ty:ty) => {
        let $ret = match $ret.to_value() {
            Ok($ret) => $ret,
            Err(e) => return Err(VmError::from(e.unpack_critical()?)),
        };

        $stack.push($ret);
    };

    // Expand to function variable bindings.
    (@unsafe-vars $count:expr, $($ty:ty, $var:ident, $num:expr,)*) => {
        $(
            let $var = match <$ty>::from_value($var) {
                Ok(v) => v,
                Err(e) => return Err(VmError::from(VmErrorKind::BadArgument {
                    error: e.unpack_critical()?,
                    arg: $count - $num,
                })),
            };
        )*
    };

    // Expand to instance variable bindings.
    (@unsafe-inst-vars $inst:ident, $count:expr, $($ty:ty, $var:ident, $num:expr,)*) => {
        let $inst = match Instance::from_value($inst) {
            Ok(v) => v,
            Err(e) => return Err(VmError::from(VmErrorKind::BadArgument {
                error: e.unpack_critical()?,
                arg: 0,
            })),
        };

        $(
            let $var = match <$ty>::from_value($var) {
                Ok(v) => v,
                Err(e) => return Err(VmError::from(VmErrorKind::BadArgument {
                    error: e.unpack_critical()?,
                    arg: 1 + $count - $num,
                })),
            };
        )*
    };

    // Helper variation to drop all stack guards associated with the specified variables.
    (@drop-stack-guards $($var:ident),* $(,)?) => {{
        $(drop(($var.1));)*
    }};

    (@check-args $expected:expr, $actual:expr) => {
        if $actual != $expected {
            return Err(VmError::from(VmErrorKind::BadArgumentCount {
                actual: $actual,
                expected: $expected,
            }));
        }
    };
}

repeat_macro!(impl_register);