-
Notifications
You must be signed in to change notification settings - Fork 168
/
mod.rs
2621 lines (2430 loc) · 87.3 KB
/
mod.rs
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
//! Module defining external-loaded modules for Rhai.
#[cfg(feature = "metadata")]
use crate::api::formatting::format_param_type_for_display;
use crate::ast::FnAccess;
use crate::func::{
shared_take_or_clone, FnIterator, RhaiFunc, RhaiNativeFunc, SendSync, StraightHashMap,
};
use crate::types::{dynamic::Variant, BloomFilterU64, CustomTypeInfo, CustomTypesCollection};
use crate::{
calc_fn_hash, calc_fn_hash_full, Dynamic, Engine, FnArgsVec, Identifier, ImmutableString,
RhaiResultOf, Shared, SharedModule, SmartString,
};
use bitflags::bitflags;
#[cfg(feature = "no_std")]
use hashbrown::hash_map::Entry;
#[cfg(not(feature = "no_std"))]
use std::collections::hash_map::Entry;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
any::{type_name, TypeId},
collections::BTreeMap,
fmt,
ops::{Add, AddAssign},
};
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
use crate::func::register::Mut;
/// Initial capacity of the hashmap for functions.
const FN_MAP_SIZE: usize = 16;
/// A type representing the namespace of a function.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(
feature = "metadata",
derive(serde::Serialize, serde::Deserialize),
serde(rename_all = "camelCase")
)]
#[non_exhaustive]
pub enum FnNamespace {
/// Module namespace only.
///
/// Ignored under `no_module`.
Internal,
/// Expose to global namespace.
Global,
}
impl FnNamespace {
/// Is this a module namespace?
#[inline(always)]
#[must_use]
pub const fn is_module_namespace(self) -> bool {
match self {
Self::Internal => true,
Self::Global => false,
}
}
/// Is this a global namespace?
#[inline(always)]
#[must_use]
pub const fn is_global_namespace(self) -> bool {
match self {
Self::Internal => false,
Self::Global => true,
}
}
}
/// A type containing the metadata of a single registered function.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub struct FuncMetadata {
/// Hash value.
pub hash: u64,
/// Function namespace.
pub namespace: FnNamespace,
/// Function access mode.
pub access: FnAccess,
/// Function name.
pub name: Identifier,
/// Number of parameters.
pub num_params: usize,
/// Parameter types (if applicable).
pub param_types: FnArgsVec<TypeId>,
/// Parameter names and types (if available).
#[cfg(feature = "metadata")]
pub params_info: FnArgsVec<Identifier>,
/// Return type name.
#[cfg(feature = "metadata")]
pub return_type: Identifier,
/// Comments.
#[cfg(feature = "metadata")]
pub comments: crate::StaticVec<SmartString>,
}
impl FuncMetadata {
/// _(metadata)_ Generate a signature of the function.
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
#[must_use]
pub fn gen_signature<'a>(
&'a self,
type_mapper: impl Fn(&'a str) -> std::borrow::Cow<'a, str>,
) -> String {
let mut signature = format!("{}(", self.name);
let return_type = format_param_type_for_display(&self.return_type, true);
if self.params_info.is_empty() {
for x in 0..self.num_params {
signature.push('_');
if x < self.num_params - 1 {
signature.push_str(", ");
}
}
} else {
let params = self
.params_info
.iter()
.map(|param| {
let mut segment = param.splitn(2, ':');
let name = match segment.next().unwrap().trim() {
"" => "_".into(),
s => s,
};
let result: std::borrow::Cow<_> = segment.next().map_or_else(
|| name.into(),
|typ| {
format!(
"{name}: {}",
format_param_type_for_display(&type_mapper(typ), false)
)
.into()
},
);
result
})
.collect::<crate::FnArgsVec<_>>();
signature.push_str(¶ms.join(", "));
}
signature.push(')');
if !return_type.is_empty() {
signature.push_str(" -> ");
signature.push_str(&return_type);
}
signature
}
}
/// _(internals)_ Calculate a [`u64`] hash key from a namespace-qualified function name and parameter types.
/// Exported under the `internals` feature only.
///
/// Module names are passed in via `&str` references from an iterator.
/// Parameter types are passed in via [`TypeId`] values from an iterator.
///
/// # Note
///
/// The first module name is skipped. Hashing starts from the _second_ module in the chain.
#[inline]
pub fn calc_native_fn_hash<'a>(
modules: impl IntoIterator<Item = &'a str, IntoIter = impl ExactSizeIterator<Item = &'a str>>,
fn_name: &str,
params: &[TypeId],
) -> u64 {
calc_fn_hash_full(
calc_fn_hash(modules, fn_name, params.len()),
params.iter().copied(),
)
}
/// Type for fine-tuned module function registration.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct FuncRegistration {
/// Function metadata.
metadata: FuncMetadata,
/// Is the function pure?
purity: Option<bool>,
/// Is the function volatile?
volatility: Option<bool>,
}
impl FuncRegistration {
/// Create a new [`FuncRegistration`].
///
/// # Defaults
///
/// * **Accessibility**: The function namespace is [`FnNamespace::Internal`].
///
/// * **Purity**: The function is assumed to be _pure_ unless it is a property setter or an index setter.
///
/// * **Volatility**: The function is assumed to be _non-volatile_ -- i.e. it guarantees the same result for the same input(s).
///
/// * **Metadata**: No metadata for the function is registered.
///
/// ```
/// # use rhai::{Module, FuncRegistration, FnNamespace};
/// let mut module = Module::new();
///
/// fn inc(x: i64) -> i64 { x + 1 }
///
/// let f = FuncRegistration::new("inc")
/// .with_namespace(FnNamespace::Global)
/// .set_into_module(&mut module, inc);
///
/// let hash = f.hash;
///
/// assert!(module.contains_fn(hash));
/// ```
pub fn new(name: impl Into<Identifier>) -> Self {
Self {
metadata: FuncMetadata {
hash: 0,
name: name.into(),
namespace: FnNamespace::Internal,
access: FnAccess::Public,
num_params: 0,
param_types: <_>::default(),
#[cfg(feature = "metadata")]
params_info: <_>::default(),
#[cfg(feature = "metadata")]
return_type: "".into(),
#[cfg(feature = "metadata")]
comments: <_>::default(),
},
purity: None,
volatility: None,
}
}
/// Create a new [`FuncRegistration`] for a property getter.
///
/// Not available under `no_object`.
///
/// # Defaults
///
/// * **Accessibility**: The function namespace is [`FnNamespace::Global`].
///
/// * **Purity**: The function is assumed to be _pure_.
///
/// * **Volatility**: The function is assumed to be _non-volatile_ -- i.e. it guarantees the same result for the same input(s).
///
/// * **Metadata**: No metadata for the function is registered.
#[cfg(not(feature = "no_object"))]
#[inline(always)]
pub fn new_getter(prop: impl AsRef<str>) -> Self {
Self::new(crate::engine::make_getter(prop.as_ref())).with_namespace(FnNamespace::Global)
}
/// Create a new [`FuncRegistration`] for a property setter.
///
/// Not available under `no_object`.
///
/// # Defaults
///
/// * **Accessibility**: The function namespace is [`FnNamespace::Global`].
///
/// * **Purity**: The function is assumed to be _no-pure_.
///
/// * **Volatility**: The function is assumed to be _non-volatile_ -- i.e. it guarantees the same result for the same input(s).
///
/// * **Metadata**: No metadata for the function is registered.
#[cfg(not(feature = "no_object"))]
#[inline(always)]
pub fn new_setter(prop: impl AsRef<str>) -> Self {
Self::new(crate::engine::make_setter(prop.as_ref()))
.with_namespace(FnNamespace::Global)
.with_purity(false)
}
/// Create a new [`FuncRegistration`] for an index getter.
///
/// Not available under both `no_index` and `no_object`.
///
/// # Defaults
///
/// * **Accessibility**: The function namespace is [`FnNamespace::Global`].
///
/// * **Purity**: The function is assumed to be _pure_.
///
/// * **Volatility**: The function is assumed to be _non-volatile_ -- i.e. it guarantees the same result for the same input(s).
///
/// * **Metadata**: No metadata for the function is registered.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[inline(always)]
pub fn new_index_getter() -> Self {
Self::new(crate::engine::FN_IDX_GET).with_namespace(FnNamespace::Global)
}
/// Create a new [`FuncRegistration`] for an index setter.
///
/// Not available under both `no_index` and `no_object`.
///
/// # Defaults
///
/// * **Accessibility**: The function namespace is [`FnNamespace::Global`].
///
/// * **Purity**: The function is assumed to be _no-pure_.
///
/// * **Volatility**: The function is assumed to be _non-volatile_ -- i.e. it guarantees the same result for the same input(s).
///
/// * **Metadata**: No metadata for the function is registered.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[inline(always)]
pub fn new_index_setter() -> Self {
Self::new(crate::engine::FN_IDX_SET)
.with_namespace(FnNamespace::Global)
.with_purity(false)
}
/// Set the [namespace][`FnNamespace`] of the function.
pub fn with_namespace(mut self, namespace: FnNamespace) -> Self {
self.metadata.namespace = namespace;
self
}
/// Set whether the function is _pure_.
/// A pure function has no side effects.
pub fn with_purity(mut self, pure: bool) -> Self {
self.purity = Some(pure);
self
}
/// Set whether the function is _volatile_.
/// A volatile function does not guarantee the same result for the same input(s).
pub fn with_volatility(mut self, volatile: bool) -> Self {
self.volatility = Some(volatile);
self
}
/// _(metadata)_ Set the function's parameter names and/or types.
/// Exported under the `metadata` feature only.
///
/// The input is a list of strings, each of which is either a parameter name or a parameter name/type pair.
///
/// The _last_ string should be the _type_ of the return value.
///
/// # Parameter Examples
///
/// `"foo: &str"` <- parameter name = `foo`, type = `&str`
/// `"bar"` <- parameter name = `bar`, type unknown
/// `"_: i64"` <- parameter name unknown, type = `i64`
/// `"MyType"` <- parameter name unknown, type = `MyType`
#[cfg(feature = "metadata")]
pub fn with_params_info<S: AsRef<str>>(mut self, params: impl IntoIterator<Item = S>) -> Self {
self.metadata.params_info = params.into_iter().map(|s| s.as_ref().into()).collect();
self
}
/// _(metadata)_ Set the function's doc-comments.
/// Exported under the `metadata` feature only.
///
/// The input is a list of strings, each of which is either a block of single-line doc-comments
/// or a single block doc-comment.
///
/// ## Comments
///
/// Single-line doc-comments typically start with `///` and should be merged, with line-breaks,
/// into a single string without a final termination line-break.
///
/// Block doc-comments typically start with `/**` and end with `*/` and should be kept in a
/// separate string.
///
/// Leading white-spaces should be stripped, and each string should always start with the
/// corresponding doc-comment leader: `///` or `/**`.
///
/// Each line in non-block doc-comments should start with `///`.
#[cfg(feature = "metadata")]
pub fn with_comments<S: AsRef<str>>(mut self, comments: impl IntoIterator<Item = S>) -> Self {
self.metadata.comments = comments.into_iter().map(|s| s.as_ref().into()).collect();
self
}
/// Register the function into the specified [`Engine`].
#[inline]
pub fn register_into_engine<A: 'static, const N: usize, const X: bool, R, const F: bool, FUNC>(
self,
engine: &mut Engine,
func: FUNC,
) -> &FuncMetadata
where
R: Variant + Clone,
FUNC: RhaiNativeFunc<A, N, X, R, F> + SendSync + 'static,
{
self.with_namespace(FnNamespace::Global)
.set_into_module(engine.global_namespace_mut(), func)
}
/// Register the function into the specified [`Module`].
#[inline]
pub fn set_into_module<A: 'static, const N: usize, const X: bool, R, const F: bool, FUNC>(
self,
module: &mut Module,
func: FUNC,
) -> &FuncMetadata
where
R: Variant + Clone,
FUNC: RhaiNativeFunc<A, N, X, R, F> + SendSync + 'static,
{
let is_pure = self.purity.unwrap_or_else(|| {
// default to pure unless specified
let is_pure = true;
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
let is_pure = is_pure
&& (FUNC::num_params() != 3 || self.metadata.name != crate::engine::FN_IDX_SET);
#[cfg(not(feature = "no_object"))]
let is_pure = is_pure
&& (FUNC::num_params() != 2
|| !self.metadata.name.starts_with(crate::engine::FN_SET));
is_pure
});
let is_volatile = self.volatility.unwrap_or(false);
let func = func.into_rhai_function(is_pure, is_volatile);
// Clear flags
let mut reg = self;
reg.purity = None;
reg.volatility = None;
reg.set_into_module_raw(module, FUNC::param_types(), func)
}
/// Register the function into the specified [`Module`].
///
/// # WARNING - Low Level API
///
/// This function is very low level. It takes a list of [`TypeId`][std::any::TypeId]'s
/// indicating the actual types of the parameters.
///
/// # Panics
///
/// Panics if the type of the first parameter is [`Array`][crate::Array], [`Map`][crate::Map],
/// [`String`], [`ImmutableString`][crate::ImmutableString], `&str` or [`INT`][crate::INT] and
/// the function name indicates that it is an index getter or setter.
///
/// Indexers for arrays, object maps, strings and integers cannot be registered.
#[inline]
pub fn set_into_module_raw(
self,
module: &mut Module,
arg_types: impl AsRef<[TypeId]>,
func: RhaiFunc,
) -> &FuncMetadata {
// Make sure that conflicting flags should not be set.
debug_assert!(self.purity.is_none());
debug_assert!(self.volatility.is_none());
let mut f = self.metadata;
f.num_params = arg_types.as_ref().len();
f.param_types.extend(arg_types.as_ref().iter().copied());
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
if (f.name == crate::engine::FN_IDX_GET && f.num_params == 2)
|| (f.name == crate::engine::FN_IDX_SET && f.num_params == 3)
{
if let Some(&type_id) = f.param_types.first() {
#[cfg(not(feature = "no_index"))]
assert!(
type_id != TypeId::of::<crate::Array>(),
"Cannot register indexer for arrays."
);
#[cfg(not(feature = "no_object"))]
assert!(
type_id != TypeId::of::<crate::Map>(),
"Cannot register indexer for object maps."
);
assert!(
type_id != TypeId::of::<String>()
&& type_id != TypeId::of::<&str>()
&& type_id != TypeId::of::<crate::ImmutableString>(),
"Cannot register indexer for strings."
);
assert!(
type_id != TypeId::of::<crate::INT>(),
"Cannot register indexer for integers."
);
}
}
let is_method = func.is_method();
f.param_types
.iter_mut()
.enumerate()
.for_each(|(i, type_id)| *type_id = Module::map_type(!is_method || i > 0, *type_id));
let is_dynamic = f
.param_types
.iter()
.any(|&type_id| type_id == TypeId::of::<Dynamic>());
#[cfg(feature = "metadata")]
if f.params_info.len() > f.param_types.len() {
f.return_type = f.params_info.pop().unwrap();
}
let hash_base = calc_fn_hash(None, &f.name, f.param_types.len());
let hash_fn = calc_fn_hash_full(hash_base, f.param_types.iter().copied());
f.hash = hash_fn;
// Catch hash collisions in testing environment only.
#[cfg(feature = "testing-environ")]
if let Some(fx) = module.functions.as_ref().and_then(|f| f.get(&hash_base)) {
unreachable!(
"Hash {} already exists when registering function {}:\n{:#?}",
hash_base, f.name, fx
);
}
if is_dynamic {
module.dynamic_functions_filter.mark(hash_base);
}
module
.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
let entry = match module
.functions
.get_or_insert_with(|| new_hash_map(FN_MAP_SIZE))
.entry(hash_fn)
{
Entry::Occupied(mut entry) => {
entry.insert((func, f.into()));
entry.into_mut()
}
Entry::Vacant(entry) => entry.insert((func, f.into())),
};
&*entry.1
}
}
bitflags! {
/// Bit-flags containing all status for [`Module`].
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
pub struct ModuleFlags: u8 {
/// Is the [`Module`] internal?
const INTERNAL = 0b0000_0001;
/// Is the [`Module`] part of a standard library?
const STANDARD_LIB = 0b0000_0010;
/// Is the [`Module`] indexed?
const INDEXED = 0b0000_0100;
/// Does the [`Module`] contain indexed functions that have been exposed to the global namespace?
const INDEXED_GLOBAL_FUNCTIONS = 0b0000_1000;
}
}
/// A module which may contain variables, sub-modules, external Rust functions,
/// and/or script-defined functions.
#[derive(Clone)]
pub struct Module {
/// ID identifying the module.
id: Option<ImmutableString>,
/// Module documentation.
#[cfg(feature = "metadata")]
doc: SmartString,
/// Custom types.
custom_types: CustomTypesCollection,
/// Sub-modules.
modules: BTreeMap<Identifier, SharedModule>,
/// [`Module`] variables.
variables: BTreeMap<Identifier, Dynamic>,
/// Flattened collection of all [`Module`] variables, including those in sub-modules.
all_variables: Option<StraightHashMap<Dynamic>>,
/// Functions (both native Rust and scripted).
functions: Option<StraightHashMap<(RhaiFunc, Box<FuncMetadata>)>>,
/// Flattened collection of all functions, native Rust and scripted.
/// including those in sub-modules.
all_functions: Option<StraightHashMap<RhaiFunc>>,
/// Bloom filter on native Rust functions (in scripted hash format) that contain [`Dynamic`] parameters.
dynamic_functions_filter: BloomFilterU64,
/// Iterator functions, keyed by the type producing the iterator.
type_iterators: BTreeMap<TypeId, Shared<FnIterator>>,
/// Flattened collection of iterator functions, including those in sub-modules.
all_type_iterators: BTreeMap<TypeId, Shared<FnIterator>>,
/// Flags.
pub(crate) flags: ModuleFlags,
}
impl Default for Module {
#[inline(always)]
#[must_use]
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Module {
#[cold]
#[inline(never)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("Module");
d.field("id", &self.id)
.field(
"custom_types",
&self.custom_types.iter().map(|(k, _)| k).collect::<Vec<_>>(),
)
.field(
"modules",
&self
.modules
.keys()
.map(SmartString::as_str)
.collect::<Vec<_>>(),
)
.field("vars", &self.variables)
.field(
"functions",
&self
.iter_fn()
.map(|(_f, _m)| {
#[cfg(not(feature = "metadata"))]
return _f.to_string();
#[cfg(feature = "metadata")]
return _m.gen_signature(|s| s.into());
})
.collect::<Vec<_>>(),
)
.field("flags", &self.flags);
#[cfg(feature = "metadata")]
d.field("doc", &self.doc);
d.finish()
}
}
#[cfg(not(feature = "no_function"))]
impl<T: IntoIterator<Item = Shared<crate::ast::ScriptFuncDef>>> From<T> for Module {
fn from(iter: T) -> Self {
let mut module = Self::new();
iter.into_iter().for_each(|fn_def| {
module.set_script_fn(fn_def);
});
module
}
}
impl<M: AsRef<Module>> Add<M> for &Module {
type Output = Module;
#[inline]
fn add(self, rhs: M) -> Self::Output {
let mut module = self.clone();
module.merge(rhs.as_ref());
module
}
}
impl<M: AsRef<Self>> Add<M> for Module {
type Output = Self;
#[inline(always)]
fn add(mut self, rhs: M) -> Self::Output {
self.merge(rhs.as_ref());
self
}
}
impl<M: Into<Self>> AddAssign<M> for Module {
#[inline(always)]
fn add_assign(&mut self, rhs: M) {
self.combine(rhs.into());
}
}
#[inline(always)]
fn new_hash_map<T>(size: usize) -> StraightHashMap<T> {
StraightHashMap::with_capacity_and_hasher(size, <_>::default())
}
impl Module {
/// Create a new [`Module`].
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_var("answer", 42_i64);
/// assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);
/// ```
#[inline(always)]
#[must_use]
pub const fn new() -> Self {
Self {
id: None,
#[cfg(feature = "metadata")]
doc: SmartString::new_const(),
custom_types: CustomTypesCollection::new(),
modules: BTreeMap::new(),
variables: BTreeMap::new(),
all_variables: None,
functions: None,
all_functions: None,
dynamic_functions_filter: BloomFilterU64::new(),
type_iterators: BTreeMap::new(),
all_type_iterators: BTreeMap::new(),
flags: ModuleFlags::INDEXED,
}
}
/// Get the ID of the [`Module`], if any.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_id("hello");
/// assert_eq!(module.id(), Some("hello"));
/// ```
#[inline]
#[must_use]
pub fn id(&self) -> Option<&str> {
self.id.as_deref()
}
/// Get the ID of the [`Module`] as an [`Identifier`], if any.
#[inline(always)]
#[must_use]
pub(crate) const fn id_raw(&self) -> Option<&ImmutableString> {
self.id.as_ref()
}
/// Set the ID of the [`Module`].
///
/// If the string is empty, it is equivalent to clearing the ID.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_id("hello");
/// assert_eq!(module.id(), Some("hello"));
/// ```
#[inline(always)]
pub fn set_id(&mut self, id: impl Into<ImmutableString>) -> &mut Self {
let id = id.into();
self.id = (!id.is_empty()).then_some(id);
self
}
/// Clear the ID of the [`Module`].
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_id("hello");
/// assert_eq!(module.id(), Some("hello"));
/// module.clear_id();
/// assert_eq!(module.id(), None);
/// ```
#[inline(always)]
pub fn clear_id(&mut self) -> &mut Self {
self.id = None;
self
}
/// Get the documentation of the [`Module`], if any.
/// Exported under the `metadata` feature only.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_doc("//! This is my special module.");
/// assert_eq!(module.doc(), "//! This is my special module.");
/// ```
#[cfg(feature = "metadata")]
#[inline(always)]
#[must_use]
pub fn doc(&self) -> &str {
&self.doc
}
/// Set the documentation of the [`Module`].
/// Exported under the `metadata` feature only.
///
/// If the string is empty, it is equivalent to clearing the documentation.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_doc("//! This is my special module.");
/// assert_eq!(module.doc(), "//! This is my special module.");
/// ```
#[cfg(feature = "metadata")]
#[inline(always)]
pub fn set_doc(&mut self, doc: impl Into<crate::SmartString>) -> &mut Self {
self.doc = doc.into();
self
}
/// Clear the documentation of the [`Module`].
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_doc("//! This is my special module.");
/// assert_eq!(module.doc(), "//! This is my special module.");
/// module.clear_doc();
/// assert_eq!(module.doc(), "");
/// ```
#[cfg(feature = "metadata")]
#[inline(always)]
pub fn clear_doc(&mut self) -> &mut Self {
self.doc.clear();
self
}
/// Clear the [`Module`].
#[inline(always)]
pub fn clear(&mut self) {
#[cfg(feature = "metadata")]
self.doc.clear();
self.custom_types.clear();
self.modules.clear();
self.variables.clear();
self.all_variables = None;
self.functions = None;
self.all_functions = None;
self.dynamic_functions_filter.clear();
self.type_iterators.clear();
self.all_type_iterators.clear();
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
}
/// Map a custom type to a friendly display name.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// #[derive(Clone)]
/// struct TestStruct;
///
/// let name = std::any::type_name::<TestStruct>();
///
/// let mut module = Module::new();
///
/// module.set_custom_type::<TestStruct>("MyType");
///
/// assert_eq!(module.get_custom_type_display_by_name(name), Some("MyType"));
/// ```
#[inline(always)]
pub fn set_custom_type<T>(&mut self, name: &str) -> &mut Self {
self.custom_types.add_type::<T>(name);
self
}
/// Map a custom type to a friendly display name.
/// Exported under the `metadata` feature only.
///
/// ## Comments
///
/// Block doc-comments should be kept in a separate string slice.
///
/// Line doc-comments should be merged, with line-breaks, into a single string slice without a final termination line-break.
///
/// Leading white-spaces should be stripped, and each string slice always starts with the corresponding
/// doc-comment leader: `///` or `/**`.
///
/// Each line in non-block doc-comments should start with `///`.
#[cfg(feature = "metadata")]
#[inline(always)]
pub fn set_custom_type_with_comments<T>(&mut self, name: &str, comments: &[&str]) -> &mut Self {
self.custom_types
.add_type_with_comments::<T>(name, comments);
self
}
/// Map a custom type to a friendly display name.
///
/// ```
/// # use rhai::Module;
/// #[derive(Clone)]
/// struct TestStruct;
///
/// let name = std::any::type_name::<TestStruct>();
///
/// let mut module = Module::new();
///
/// module.set_custom_type_raw(name, "MyType");
///
/// assert_eq!(module.get_custom_type_display_by_name(name), Some("MyType"));
/// ```
#[inline(always)]
pub fn set_custom_type_raw(
&mut self,
type_name: impl Into<Identifier>,
display_name: impl Into<Identifier>,
) -> &mut Self {
self.custom_types.add(type_name, display_name);
self
}
/// Map a custom type to a friendly display name.
/// Exported under the `metadata` feature only.
///
/// ## Comments
///
/// Block doc-comments should be kept in a separate string slice.
///
/// Line doc-comments should be merged, with line-breaks, into a single string slice without a final termination line-break.
///
/// Leading white-spaces should be stripped, and each string slice always starts with the corresponding
/// doc-comment leader: `///` or `/**`.
///
/// Each line in non-block doc-comments should start with `///`.
#[cfg(feature = "metadata")]
#[inline(always)]
pub fn set_custom_type_with_comments_raw<C: Into<SmartString>>(
&mut self,
type_name: impl Into<Identifier>,
display_name: impl Into<Identifier>,
comments: impl IntoIterator<Item = C>,
) -> &mut Self {
self.custom_types
.add_with_comments(type_name, display_name, comments);
self
}
/// Get the display name of a registered custom type.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// #[derive(Clone)]
/// struct TestStruct;
///
/// let name = std::any::type_name::<TestStruct>();
///
/// let mut module = Module::new();
///
/// module.set_custom_type::<TestStruct>("MyType");
///
/// assert_eq!(module.get_custom_type_display_by_name(name), Some("MyType"));
/// ```
#[inline]
#[must_use]
pub fn get_custom_type_display_by_name(&self, type_name: &str) -> Option<&str> {
self.get_custom_type_by_name_raw(type_name)
.map(|typ| typ.display_name.as_str())
}
/// Get the display name of a registered custom type.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// #[derive(Clone)]
/// struct TestStruct;
///
/// let name = std::any::type_name::<TestStruct>();
///
/// let mut module = Module::new();
///
/// module.set_custom_type::<TestStruct>("MyType");
///
/// assert_eq!(module.get_custom_type_display::<TestStruct>(), Some("MyType"));
/// ```
#[inline(always)]
#[must_use]
pub fn get_custom_type_display<T>(&self) -> Option<&str> {
self.get_custom_type_display_by_name(type_name::<T>())
}
/// _(internals)_ Get a registered custom type .
/// Exported under the `internals` feature only.
#[cfg(feature = "internals")]
#[inline(always)]
#[must_use]
pub fn get_custom_type_raw<T>(&self) -> Option<&CustomTypeInfo> {
self.get_custom_type_by_name_raw(type_name::<T>())
}
/// Get a registered custom type .
#[cfg(not(feature = "internals"))]
#[inline(always)]
#[must_use]
pub fn get_custom_type_raw<T>(&self) -> Option<&CustomTypeInfo> {
self.get_custom_type_by_name_raw(type_name::<T>())
}
/// _(internals)_ Get a registered custom type by its type name.
/// Exported under the `internals` feature only.
#[cfg(feature = "internals")]
#[inline(always)]
#[must_use]
pub fn get_custom_type_by_name_raw(&self, type_name: &str) -> Option<&CustomTypeInfo> {
self.custom_types.get(type_name)
}
/// Get a registered custom type by its type name.
#[cfg(not(feature = "internals"))]
#[inline(always)]