Add Engine::register_type_with_name_raw.

This commit is contained in:
Stephen Chung 2021-12-09 12:49:12 +08:00
parent 4421f33b2c
commit d9d44a9683
6 changed files with 29 additions and 13 deletions

View File

@ -24,6 +24,7 @@ New features
Enhancements Enhancements
------------ ------------
* Added `Engine::register_type_with_name_raw` to register a custom type based on a fully-qualified type path.
* Added `into_array` and `into_typed_array` for `Dynamic`. * Added `into_array` and `into_typed_array` for `Dynamic`.
* Added `FnPtr::call` and `FnPtr::call_within_context` to simplify calling a function pointer. * Added `FnPtr::call` and `FnPtr::call_within_context` to simplify calling a function pointer.
* A function's hashes are included in its JSON metadata to assist in debugging. Each function's `hashBase` field in the JSON object should map directly to the pre-calculated hash in the function call. * A function's hashes are included in its JSON metadata to assist in debugging. Each function's `hashBase` field in the JSON object should map directly to the pre-calculated hash in the function call.

View File

@ -4,6 +4,7 @@ use crate::func::{FnCallArgs, RegisterNativeFunction, SendSync};
use crate::types::dynamic::Variant; use crate::types::dynamic::Variant;
use crate::{ use crate::{
Engine, EvalAltResult, FnAccess, FnNamespace, Identifier, Module, NativeCallContext, Shared, Engine, EvalAltResult, FnAccess, FnNamespace, Identifier, Module, NativeCallContext, Shared,
SmartString,
}; };
use std::any::{type_name, TypeId}; use std::any::{type_name, TypeId};
#[cfg(feature = "no_std")] #[cfg(feature = "no_std")]
@ -146,11 +147,12 @@ impl Engine {
/// ///
/// # WARNING - Low Level API /// # 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. /// This function is very low level. It takes a list of [`TypeId`][std::any::TypeId]'s
/// indicating the actual types of the parameters.
/// ///
/// ## Arguments /// ## Arguments
/// ///
/// Arguments are simply passed in as a mutable array of [`&mut Dynamic`][crate::Dynamic], /// Arguments are simply passed in as a mutable array of [`&mut Dynamic`][crate::Dynamic].
/// The arguments are guaranteed to be of the correct types matching the [`TypeId`][std::any::TypeId]'s. /// The arguments are guaranteed to be of the correct types matching the [`TypeId`][std::any::TypeId]'s.
/// ///
/// To access a primary argument value (i.e. cloning is cheap), use: `args[n].as_xxx().unwrap()` /// To access a primary argument value (i.e. cloning is cheap), use: `args[n].as_xxx().unwrap()`
@ -263,9 +265,23 @@ impl Engine {
/// ``` /// ```
#[inline(always)] #[inline(always)]
pub fn register_type_with_name<T: Variant + Clone>(&mut self, name: &str) -> &mut Self { pub fn register_type_with_name<T: Variant + Clone>(&mut self, name: &str) -> &mut Self {
self.register_type_with_name_raw(type_name::<T>(), name)
}
/// Register a custom type for use with the [`Engine`], with a pretty-print name
/// for the `type_of` function. The type must implement [`Clone`].
///
/// # WARNING - Low Level API
///
/// This function is low level.
#[inline(always)]
pub fn register_type_with_name_raw(
&mut self,
fully_qualified_type_path: impl Into<SmartString>,
name: impl Into<SmartString>,
) -> &mut Self {
// Add the pretty-print type name into the map // Add the pretty-print type name into the map
self.type_names self.type_names
.insert(type_name::<T>().into(), Box::new(name.into())); .insert(fully_qualified_type_path.into(), name.into());
self self
} }
/// Register an type iterator for an iterable type with the [`Engine`]. /// Register an type iterator for an iterable type with the [`Engine`].

View File

@ -936,7 +936,7 @@ pub struct Engine {
pub(crate) module_resolver: Option<Box<dyn crate::ModuleResolver>>, pub(crate) module_resolver: Option<Box<dyn crate::ModuleResolver>>,
/// A map mapping type names to pretty-print names. /// A map mapping type names to pretty-print names.
pub(crate) type_names: BTreeMap<Identifier, Box<Identifier>>, pub(crate) type_names: BTreeMap<Identifier, Identifier>,
/// An empty [`ImmutableString`] for cloning purposes. /// An empty [`ImmutableString`] for cloning purposes.
pub(crate) empty_string: ImmutableString, pub(crate) empty_string: ImmutableString,

View File

@ -31,7 +31,7 @@ pub trait ModuleResolver: SendSync {
/// Returns [`None`] (default) if such resolution is not supported /// Returns [`None`] (default) if such resolution is not supported
/// (e.g. if the module is Rust-based). /// (e.g. if the module is Rust-based).
/// ///
/// ## Low-Level API /// # WARNING - Low Level API
/// ///
/// Override the default implementation of this method if the module resolver /// Override the default implementation of this method if the module resolver
/// serves modules based on compiled Rhai scripts. /// serves modules based on compiled Rhai scripts.

View File

@ -37,10 +37,11 @@ pub use time_basic::BasicTimePackage;
/// Trait that all packages must implement. /// Trait that all packages must implement.
pub trait Package { pub trait Package {
/// Register all the functions in a package into a store. /// Initialize the package.
fn init(lib: &mut Module); /// Functions should be registered into `module` here.
fn init(module: &mut Module);
/// Retrieve the generic package library from this package. /// Get a reference to a shared module from this package.
#[must_use] #[must_use]
fn as_shared_module(&self) -> Shared<Module>; fn as_shared_module(&self) -> Shared<Module>;
} }
@ -60,10 +61,10 @@ pub trait Package {
/// ///
/// fn add(x: i64, y: i64) -> Result<i64, Box<EvalAltResult>> { Ok(x + y) } /// fn add(x: i64, y: i64) -> Result<i64, Box<EvalAltResult>> { Ok(x + y) }
/// ///
/// def_package!(rhai:MyPackage:"My super-duper package", lib, /// def_package!(rhai:MyPackage:"My super-duper package", module,
/// { /// {
/// // Load a binary function with all value parameters. /// // Load a binary function with all value parameters.
/// lib.set_native_fn("my_add", add); /// module.set_native_fn("my_add", add);
/// }); /// });
/// ``` /// ```
#[macro_export] #[macro_export]
@ -76,7 +77,6 @@ macro_rules! def_package {
fn as_shared_module(&self) -> $root::Shared<$root::Module> { fn as_shared_module(&self) -> $root::Shared<$root::Module> {
self.0.clone() self.0.clone()
} }
fn init($lib: &mut $root::Module) { fn init($lib: &mut $root::Module) {
$block $block
} }

View File

@ -16,8 +16,7 @@ use std::{
/// The system immutable string type. /// The system immutable string type.
/// ///
/// An [`ImmutableString`] wraps an [`Rc`][std::rc::Rc]`<`[`SmartString`][smartstring::SmartString]`>` /// An [`ImmutableString`] wraps an `Rc<SmartString>` (or `Arc<SmartString>` under the `sync` feature)
/// (or [`Arc`][std::sync::Arc]`<`[`SmartString`][smartstring::SmartString]`>` under the `sync` feature)
/// so that it can be simply shared and not cloned. /// so that it can be simply shared and not cloned.
/// ///
/// # Example /// # Example