From 8408c190dc9af6003abe24fc0c72215aa9bde8e9 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Tue, 9 Aug 2022 18:18:41 +0800 Subject: [PATCH 1/2] Add with_iterator to TypeBuilder. --- examples/custom_types.rs | 18 +++++++++++ src/api/build_type.rs | 66 ++++++++++++++++++++++++++-------------- tests/build_type.rs | 10 ++++++ 3 files changed, 71 insertions(+), 23 deletions(-) diff --git a/examples/custom_types.rs b/examples/custom_types.rs index 86888c8f..eb84992e 100644 --- a/examples/custom_types.rs +++ b/examples/custom_types.rs @@ -32,6 +32,15 @@ fn main() -> Result<(), Box> { } } + impl IntoIterator for TestStruct { + type Item = i64; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + vec![self.x - 1, self.x, self.x + 1].into_iter() + } + } + impl CustomType for TestStruct { fn build(mut builder: TypeBuilder) { #[allow(deprecated)] // The TypeBuilder api is volatile. @@ -40,6 +49,7 @@ fn main() -> Result<(), Box> { .with_fn("new_ts", Self::new) .with_fn("update", Self::update) .with_fn("calc", Self::calculate) + .with_iterator() .with_get_set("x", Self::get_x, Self::set_x); } } @@ -63,8 +73,16 @@ fn main() -> Result<(), Box> { let result = engine.eval::( " let x = new_ts(); + x.x = 42; + + for n in x { + x.x += n; + print(`n = ${n}, total = ${x.x}`); + } + x.update(); + x.calc(x.x) ", )?; diff --git a/src/api/build_type.rs b/src/api/build_type.rs index 02a5b3cd..e26c85bc 100644 --- a/src/api/build_type.rs +++ b/src/api/build_type.rs @@ -1,17 +1,18 @@ //! Trait to build a custom type for use with [`Engine`]. #![allow(deprecated)] -use crate::{ - func::SendSync, types::dynamic::Variant, Engine, Identifier, RegisterNativeFunction, - RhaiResultOf, -}; +use crate::{types::dynamic::Variant, Engine, Identifier, RegisterNativeFunction, RhaiResultOf}; use std::marker::PhantomData; #[cfg(feature = "no_std")] use std::prelude::v1::*; -/// Trait to build a custom type for use with an [`Engine`] +/// Trait to build the API of a custom type for use with an [`Engine`] /// (i.e. register the type and its getters, setters, methods, etc.). /// +/// # WARNING - Volatile Trait +/// +/// This API is volatile and may change in the future. +/// /// # Example /// /// ``` @@ -71,9 +72,13 @@ pub trait CustomType: Variant + Clone { } impl Engine { - /// Build a custom type for use with the [`Engine`]. + /// Build the API of a custom type for use with the [`Engine`]. /// /// The custom type must implement [`CustomType`]. + /// + /// # WARNING - Unstable API + /// + /// This API is volatile and may change in the future. #[inline] pub fn build_type(&mut self) -> &mut Self { T::build(TypeBuilder::new(self)); @@ -81,15 +86,15 @@ impl Engine { } } -/// Builder to build a custom type for use with an [`Engine`]. +/// Builder to build the API of a custom type for use with an [`Engine`]. /// /// The type is automatically registered when this builder is dropped. /// -/// ## Pretty name +/// ## Pretty-Print Name /// -/// By default the type is registered with [`Engine::register_type`] (i.e. without a pretty name). +/// By default the type is registered with [`Engine::register_type`] (i.e. without a pretty-print name). /// -/// To define a pretty name, call [`with_name`][`TypeBuilder::with_name`], +/// To define a pretty-print name, call [`with_name`][`TypeBuilder::with_name`], /// to use [`Engine::register_type_with_name`] instead. #[deprecated = "This type is NOT deprecated, but it is considered volatile and may change in the future."] pub struct TypeBuilder<'a, T: Variant + Clone> { @@ -99,6 +104,7 @@ pub struct TypeBuilder<'a, T: Variant + Clone> { } impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { + /// Create a [`TypeBuilder`] linked to a particular [`Engine`] instance. #[inline(always)] fn new(engine: &'a mut Engine) -> Self { Self { @@ -110,7 +116,7 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { } impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { - /// Sets a pretty-print name for the `type_of` function. + /// Set a pretty-print name for the `type_of` function. #[inline(always)] pub fn with_name(&mut self, name: &'static str) -> &mut Self { self.name = Some(name); @@ -140,6 +146,20 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { } } +impl<'a, T> TypeBuilder<'a, T> +where + T: Variant + Clone + IntoIterator, + ::Item: Variant + Clone, +{ + /// Register a type iterator. + /// This is an advanced API. + #[inline(always)] + pub fn with_iterator(&mut self) -> &mut Self { + self.engine.register_iterator::(); + self + } +} + #[cfg(not(feature = "no_object"))] impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { /// Register a getter function. @@ -151,7 +171,7 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { pub fn with_get( &mut self, name: impl AsRef, - get_fn: impl Fn(&mut T) -> V + SendSync + 'static, + get_fn: impl Fn(&mut T) -> V + crate::func::SendSync + 'static, ) -> &mut Self { self.engine.register_get(name, get_fn); self @@ -166,7 +186,7 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { pub fn with_get_result( &mut self, name: impl AsRef, - get_fn: impl Fn(&mut T) -> RhaiResultOf + SendSync + 'static, + get_fn: impl Fn(&mut T) -> RhaiResultOf + crate::func::SendSync + 'static, ) -> &mut Self { self.engine.register_get_result(name, get_fn); self @@ -179,7 +199,7 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { pub fn with_set( &mut self, name: impl AsRef, - set_fn: impl Fn(&mut T, V) + SendSync + 'static, + set_fn: impl Fn(&mut T, V) + crate::func::SendSync + 'static, ) -> &mut Self { self.engine.register_set(name, set_fn); self @@ -192,7 +212,7 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { pub fn with_set_result( &mut self, name: impl AsRef, - set_fn: impl Fn(&mut T, V) -> RhaiResultOf<()> + SendSync + 'static, + set_fn: impl Fn(&mut T, V) -> RhaiResultOf<()> + crate::func::SendSync + 'static, ) -> &mut Self { self.engine.register_set_result(name, set_fn); self @@ -207,8 +227,8 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { pub fn with_get_set( &mut self, name: impl AsRef, - get_fn: impl Fn(&mut T) -> V + SendSync + 'static, - set_fn: impl Fn(&mut T, V) + SendSync + 'static, + get_fn: impl Fn(&mut T) -> V + crate::func::SendSync + 'static, + set_fn: impl Fn(&mut T, V) + crate::func::SendSync + 'static, ) -> &mut Self { self.engine.register_get_set(name, get_fn, set_fn); self @@ -225,7 +245,7 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { #[inline(always)] pub fn with_indexer_get( &mut self, - get_fn: impl Fn(&mut T, X) -> V + SendSync + 'static, + get_fn: impl Fn(&mut T, X) -> V + crate::func::SendSync + 'static, ) -> &mut Self { self.engine.register_indexer_get(get_fn); self @@ -239,7 +259,7 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { #[inline(always)] pub fn with_indexer_get_result( &mut self, - get_fn: impl Fn(&mut T, X) -> RhaiResultOf + SendSync + 'static, + get_fn: impl Fn(&mut T, X) -> RhaiResultOf + crate::func::SendSync + 'static, ) -> &mut Self { self.engine.register_indexer_get_result(get_fn); self @@ -251,7 +271,7 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { #[inline(always)] pub fn with_indexer_set( &mut self, - set_fn: impl Fn(&mut T, X, V) + SendSync + 'static, + set_fn: impl Fn(&mut T, X, V) + crate::func::SendSync + 'static, ) -> &mut Self { self.engine.register_indexer_set(set_fn); self @@ -263,7 +283,7 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { #[inline(always)] pub fn with_indexer_set_result( &mut self, - set_fn: impl Fn(&mut T, X, V) -> RhaiResultOf<()> + SendSync + 'static, + set_fn: impl Fn(&mut T, X, V) -> RhaiResultOf<()> + crate::func::SendSync + 'static, ) -> &mut Self { self.engine.register_indexer_set_result(set_fn); self @@ -275,8 +295,8 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> { #[inline(always)] pub fn with_indexer_get_set( &mut self, - get_fn: impl Fn(&mut T, X) -> V + SendSync + 'static, - set_fn: impl Fn(&mut T, X, V) + SendSync + 'static, + get_fn: impl Fn(&mut T, X) -> V + crate::func::SendSync + 'static, + set_fn: impl Fn(&mut T, X, V) + crate::func::SendSync + 'static, ) -> &mut Self { self.engine.register_indexer_get_set(get_fn, set_fn); self diff --git a/tests/build_type.rs b/tests/build_type.rs index 9f8924d4..c4f2c3bd 100644 --- a/tests/build_type.rs +++ b/tests/build_type.rs @@ -45,11 +45,21 @@ fn build_type() -> Result<(), Box> { } } + impl IntoIterator for Vec3 { + type Item = INT; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + vec![self.x, self.y, self.z].into_iter() + } + } + impl CustomType for Vec3 { fn build(mut builder: TypeBuilder) { builder .with_name("Vec3") .with_fn("vec3", Self::new) + .with_iterator() .with_get_set("x", Self::get_x, Self::set_x) .with_get_set("y", Self::get_y, Self::set_y) .with_get_set("z", Self::get_z, Self::set_z); From ac93a0bbbc36c9ab57f0cb8cc0b4b412ca3141c0 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Tue, 9 Aug 2022 21:35:45 +0800 Subject: [PATCH 2/2] Fix bug in namespace searching. --- CHANGELOG.md | 5 +++++ src/parser.rs | 28 +++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b532505..fa2858b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ Bug fixes * Fixes concatenation of BLOB's and strings, where the BLOB's should be interpreted as UTF-8 encoded strings. * Capturing an unknown variable in a closure no longer panics. * Fixes panic in interpolated strings with constant expressions. +* Using `call_fn_raw` on a function without evaluating the AST no longer panics on namespace-qualified function calls due to `import` statements not run. New features ------------ @@ -38,6 +39,10 @@ New features * Crate-level functions `rhai::eval`, `rhai::run`, `rhai::eval_file`, `rhai::run_file` are added as convenient wrappers. +### CustomType trait and TypeBuilder + +* A new volatile API, `Engine::build_type`, enables registration of the entire API of a custom type in one go, provided that the custom type implements the `CustomType` trait (which uses `TypeBuilder` to register the API functions). + Enhancements ------------ diff --git a/src/parser.rs b/src/parser.rs index 16065b48..dfedd301 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -72,6 +72,9 @@ pub struct ParseState<'e> { /// Encapsulates a local stack with imported [module][crate::Module] names. #[cfg(not(feature = "no_module"))] pub imports: StaticVec, + /// List of globally-imported [module][crate::Module] names. + #[cfg(not(feature = "no_module"))] + pub global_imports: StaticVec, /// Maximum levels of expression nesting (0 for unlimited). #[cfg(not(feature = "unchecked"))] pub max_expr_depth: usize, @@ -91,7 +94,8 @@ impl fmt::Debug for ParseState<'_> { f.field("external_vars", &self.external_vars) .field("allow_capture", &self.allow_capture); #[cfg(not(feature = "no_module"))] - f.field("imports", &self.imports); + f.field("imports", &self.imports) + .field("global_imports", &self.global_imports); #[cfg(not(feature = "unchecked"))] f.field("max_expr_depth", &self.max_expr_depth); f.finish() @@ -117,6 +121,8 @@ impl<'e> ParseState<'e> { block_stack_len: 0, #[cfg(not(feature = "no_module"))] imports: StaticVec::new_const(), + #[cfg(not(feature = "no_module"))] + global_imports: StaticVec::new_const(), #[cfg(not(feature = "unchecked"))] max_expr_depth: engine.max_expr_depth(), } @@ -557,6 +563,7 @@ impl Engine { if settings.options.contains(LangOptions::STRICT_VAR) && index.is_none() && !is_global + && !state.global_imports.iter().any(|m| m == root) && !self.global_sub_modules.contains_key(root) { return Err( @@ -624,6 +631,7 @@ impl Engine { if settings.options.contains(LangOptions::STRICT_VAR) && index.is_none() && !is_global + && !state.global_imports.iter().any(|m| m == root) && !self.global_sub_modules.contains_key(root) { return Err(PERR::ModuleUndefined(root.to_string()) @@ -1351,7 +1359,10 @@ impl Engine { ParseState::new(self, state.scope, state.tokenizer_control.clone()); #[cfg(not(feature = "no_module"))] - new_state.imports.clone_from(&state.imports); + { + new_state.imports.clone_from(&state.imports); + new_state.global_imports.clone_from(&state.global_imports); + } #[cfg(not(feature = "unchecked"))] { @@ -1789,6 +1800,7 @@ impl Engine { if settings.options.contains(LangOptions::STRICT_VAR) && index.is_none() && !is_global + && !state.global_imports.iter().any(|m| m == root) && !self.global_sub_modules.contains_key(root) { return Err( @@ -3204,7 +3216,17 @@ impl Engine { ParseState::new(self, state.scope, state.tokenizer_control.clone()); #[cfg(not(feature = "no_module"))] - new_state.imports.clone_from(&state.imports); + { + // Do not allow storing an index to a globally-imported module + // just in case the function is separated from this `AST`. + // + // Keep them in `global_imports` instead so that strict variables + // mode will not complain. + new_state.global_imports.clone_from(&state.global_imports); + new_state + .global_imports + .extend(state.imports.iter().cloned()); + } #[cfg(not(feature = "unchecked"))] {