Merge pull request #611 from schungx/master

Test and feature fixes.
This commit is contained in:
Stephen Chung 2022-08-09 17:43:55 +08:00 committed by GitHub
commit ba84b12612
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 292 additions and 133 deletions

View File

@ -34,6 +34,10 @@ New features
* Using a script-defined function's name (in place of a variable) implicitly creates a function pointer to the function. * Using a script-defined function's name (in place of a variable) implicitly creates a function pointer to the function.
### Top-level functions
* Crate-level functions `rhai::eval`, `rhai::run`, `rhai::eval_file`, `rhai::run_file` are added as convenient wrappers.
Enhancements Enhancements
------------ ------------

View File

@ -1,12 +1,16 @@
use core::marker::PhantomData; //! Trait to build a custom type for use with [`Engine`].
#![allow(deprecated)]
use crate::{ use crate::{
func::SendSync, types::dynamic::Variant, Engine, Identifier, RegisterNativeFunction, func::SendSync, types::dynamic::Variant, Engine, Identifier, RegisterNativeFunction,
RhaiResultOf, RhaiResultOf,
}; };
use std::marker::PhantomData;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
/// Trait to build a custom type for use with the [`Engine`]. /// Trait to build a custom type for use with an [`Engine`]
/// i.e. register the type and its getters, setters, methods, etc... /// (i.e. register the type and its getters, setters, methods, etc.).
/// ///
/// # Example /// # Example
/// ///
@ -55,53 +59,47 @@ use crate::{
/// engine.eval::<TestStruct>("let x = new_ts(); x.update(41); x")?, /// engine.eval::<TestStruct>("let x = new_ts(); x.update(41); x")?,
/// TestStruct { field: 42 } /// TestStruct { field: 42 }
/// ); /// );
///
/// # Ok(()) /// # Ok(())
/// # } /// # }
/// ``` /// ```
#[deprecated = "This trait is NOT deprecated, but it is considered volatile and may change in the future."]
pub trait CustomType: Variant + Clone { pub trait CustomType: Variant + Clone {
/// Builds the custom type for use with the [`Engine`]. /// Builds the custom type for use with the [`Engine`].
/// i.e. register the type, getters, setters, methods, etc... ///
/// Methods, property getters/setters, indexers etc. should be registered in this function.
fn build(builder: TypeBuilder<Self>); fn build(builder: TypeBuilder<Self>);
} }
impl Engine { impl Engine {
/// Build a custom type for use with the [`Engine`]. /// Build a custom type for use with the [`Engine`].
/// i.e. register the type and its getters, setters, methods, etc...
/// ///
/// See [`CustomType`]. /// The custom type must implement [`CustomType`].
#[inline] #[inline]
pub fn build_type<T>(&mut self) -> &mut Self pub fn build_type<T: CustomType>(&mut self) -> &mut Self {
where
T: CustomType,
{
T::build(TypeBuilder::new(self)); T::build(TypeBuilder::new(self));
self self
} }
} }
/// Builder to build a custom type i.e. register this type and its getters, setters, methods, etc... /// Builder to build a custom type for use with an [`Engine`].
/// ///
/// The type is automatically registered when this builder is dropped. /// The type is automatically registered when this builder is dropped.
/// ///
/// ## Pretty name /// ## Pretty name
/// By default the type is registered with [`Engine::register_type`] i.e. without a pretty name.
/// ///
/// To define a pretty name call `.with_name`, in this case [`Engine::register_type_with_name`] will be used. /// By default the type is registered with [`Engine::register_type`] (i.e. without a pretty name).
pub struct TypeBuilder<'a, T> ///
where /// To define a pretty name, call [`with_name`][`TypeBuilder::with_name`],
T: Variant + Clone, /// 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> {
engine: &'a mut Engine, engine: &'a mut Engine,
name: Option<&'static str>, name: Option<&'static str>,
_marker: PhantomData<T>, _marker: PhantomData<T>,
} }
impl<'a, T> TypeBuilder<'a, T> impl<'a, T: Variant + Clone> TypeBuilder<'a, T> {
where #[inline(always)]
T: Variant + Clone,
{
#[inline]
fn new(engine: &'a mut Engine) -> Self { fn new(engine: &'a mut Engine) -> Self {
Self { Self {
engine, engine,
@ -111,21 +109,16 @@ where
} }
} }
impl<'a, T> TypeBuilder<'a, T> impl<'a, T: Variant + Clone> TypeBuilder<'a, T> {
where
T: Variant + Clone,
{
/// Sets a pretty-print name for the `type_of` function. /// Sets a pretty-print name for the `type_of` function.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_name(&mut self, name: &'static str) -> &mut Self { pub fn with_name(&mut self, name: &'static str) -> &mut Self {
self.name = Some(name); self.name = Some(name);
self self
} }
/// Register a custom function. /// Register a custom function.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_fn<N, A, F>(&mut self, name: N, method: F) -> &mut Self pub fn with_fn<N, A, F>(&mut self, name: N, method: F) -> &mut Self
where where
N: AsRef<str> + Into<Identifier>, N: AsRef<str> + Into<Identifier>,
@ -136,8 +129,7 @@ where
} }
/// Register a custom fallible function. /// Register a custom fallible function.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_result_fn<N, A, F, R>(&mut self, name: N, method: F) -> &mut Self pub fn with_result_fn<N, A, F, R>(&mut self, name: N, method: F) -> &mut Self
where where
N: AsRef<str> + Into<Identifier>, N: AsRef<str> + Into<Identifier>,
@ -149,17 +141,13 @@ where
} }
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
impl<'a, T> TypeBuilder<'a, T> impl<'a, T: Variant + Clone> TypeBuilder<'a, T> {
where
T: Variant + Clone,
{
/// Register a getter function. /// Register a getter function.
/// ///
/// The function signature must start with `&mut self` and not `&self`. /// The function signature must start with `&mut self` and not `&self`.
/// ///
/// Not available under `no_object`. /// Not available under `no_object`.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_get<V: Variant + Clone>( pub fn with_get<V: Variant + Clone>(
&mut self, &mut self,
name: impl AsRef<str>, name: impl AsRef<str>,
@ -174,8 +162,7 @@ where
/// The function signature must start with `&mut self` and not `&self`. /// The function signature must start with `&mut self` and not `&self`.
/// ///
/// Not available under `no_object`. /// Not available under `no_object`.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_get_result<V: Variant + Clone>( pub fn with_get_result<V: Variant + Clone>(
&mut self, &mut self,
name: impl AsRef<str>, name: impl AsRef<str>,
@ -188,8 +175,7 @@ where
/// Register a setter function. /// Register a setter function.
/// ///
/// Not available under `no_object`. /// Not available under `no_object`.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_set<V: Variant + Clone>( pub fn with_set<V: Variant + Clone>(
&mut self, &mut self,
name: impl AsRef<str>, name: impl AsRef<str>,
@ -202,8 +188,7 @@ where
/// Register a fallible setter function. /// Register a fallible setter function.
/// ///
/// Not available under `no_object`. /// Not available under `no_object`.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_set_result<V: Variant + Clone>( pub fn with_set_result<V: Variant + Clone>(
&mut self, &mut self,
name: impl AsRef<str>, name: impl AsRef<str>,
@ -218,8 +203,7 @@ where
/// All function signatures must start with `&mut self` and not `&self`. /// All function signatures must start with `&mut self` and not `&self`.
/// ///
/// Not available under `no_object`. /// Not available under `no_object`.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_get_set<V: Variant + Clone>( pub fn with_get_set<V: Variant + Clone>(
&mut self, &mut self,
name: impl AsRef<str>, name: impl AsRef<str>,
@ -232,17 +216,13 @@ where
} }
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))] #[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
impl<'a, T> TypeBuilder<'a, T> impl<'a, T: Variant + Clone> TypeBuilder<'a, T> {
where
T: Variant + Clone,
{
/// Register an index getter. /// Register an index getter.
/// ///
/// The function signature must start with `&mut self` and not `&self`. /// The function signature must start with `&mut self` and not `&self`.
/// ///
/// Not available under both `no_index` and `no_object`. /// Not available under both `no_index` and `no_object`.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_indexer_get<X: Variant + Clone, V: Variant + Clone>( pub fn with_indexer_get<X: Variant + Clone, V: Variant + Clone>(
&mut self, &mut self,
get_fn: impl Fn(&mut T, X) -> V + SendSync + 'static, get_fn: impl Fn(&mut T, X) -> V + SendSync + 'static,
@ -256,8 +236,7 @@ where
/// The function signature must start with `&mut self` and not `&self`. /// The function signature must start with `&mut self` and not `&self`.
/// ///
/// Not available under both `no_index` and `no_object`. /// Not available under both `no_index` and `no_object`.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_indexer_get_result<X: Variant + Clone, V: Variant + Clone>( pub fn with_indexer_get_result<X: Variant + Clone, V: Variant + Clone>(
&mut self, &mut self,
get_fn: impl Fn(&mut T, X) -> RhaiResultOf<V> + SendSync + 'static, get_fn: impl Fn(&mut T, X) -> RhaiResultOf<V> + SendSync + 'static,
@ -269,8 +248,7 @@ where
/// Register an index setter. /// Register an index setter.
/// ///
/// Not available under both `no_index` and `no_object`. /// Not available under both `no_index` and `no_object`.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_indexer_set<X: Variant + Clone, V: Variant + Clone>( pub fn with_indexer_set<X: Variant + Clone, V: Variant + Clone>(
&mut self, &mut self,
set_fn: impl Fn(&mut T, X, V) + SendSync + 'static, set_fn: impl Fn(&mut T, X, V) + SendSync + 'static,
@ -282,8 +260,7 @@ where
/// Register an fallible index setter. /// Register an fallible index setter.
/// ///
/// Not available under both `no_index` and `no_object`. /// Not available under both `no_index` and `no_object`.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_indexer_set_result<X: Variant + Clone, V: Variant + Clone>( pub fn with_indexer_set_result<X: Variant + Clone, V: Variant + Clone>(
&mut self, &mut self,
set_fn: impl Fn(&mut T, X, V) -> RhaiResultOf<()> + SendSync + 'static, set_fn: impl Fn(&mut T, X, V) -> RhaiResultOf<()> + SendSync + 'static,
@ -295,8 +272,7 @@ where
/// Short-hand for registering both index getter and setter functions. /// Short-hand for registering both index getter and setter functions.
/// ///
/// Not available under both `no_index` and `no_object`. /// Not available under both `no_index` and `no_object`.
#[deprecated = "This API is NOT deprecated, but it is considered volatile and may change in the future."] #[inline(always)]
#[inline]
pub fn with_indexer_get_set<X: Variant + Clone, V: Variant + Clone>( pub fn with_indexer_get_set<X: Variant + Clone, V: Variant + Clone>(
&mut self, &mut self,
get_fn: impl Fn(&mut T, X) -> V + SendSync + 'static, get_fn: impl Fn(&mut T, X) -> V + SendSync + 'static,
@ -307,10 +283,7 @@ where
} }
} }
impl<'a, T> Drop for TypeBuilder<'a, T> impl<'a, T: Variant + Clone> Drop for TypeBuilder<'a, T> {
where
T: Variant + Clone,
{
#[inline] #[inline]
fn drop(&mut self) { fn drop(&mut self) {
if let Some(name) = self.name { if let Some(name) = self.name {

View File

@ -11,7 +11,7 @@ use std::any::type_name;
use std::prelude::v1::*; use std::prelude::v1::*;
impl Engine { impl Engine {
/// Evaluate a string. /// Evaluate a string as a script, returning the result value or an error.
/// ///
/// # Example /// # Example
/// ///
@ -29,7 +29,7 @@ impl Engine {
pub fn eval<T: Variant + Clone>(&self, script: &str) -> RhaiResultOf<T> { pub fn eval<T: Variant + Clone>(&self, script: &str) -> RhaiResultOf<T> {
self.eval_with_scope(&mut Scope::new(), script) self.eval_with_scope(&mut Scope::new(), script)
} }
/// Evaluate a string with own scope. /// Evaluate a string as a script with own scope, returning the result value or an error.
/// ///
/// ## Constants Propagation /// ## Constants Propagation
/// ///
@ -71,7 +71,7 @@ impl Engine {
)?; )?;
self.eval_ast_with_scope(scope, &ast) self.eval_ast_with_scope(scope, &ast)
} }
/// Evaluate a string containing an expression. /// Evaluate a string containing an expression, returning the result value or an error.
/// ///
/// # Example /// # Example
/// ///
@ -89,7 +89,7 @@ impl Engine {
pub fn eval_expression<T: Variant + Clone>(&self, script: &str) -> RhaiResultOf<T> { pub fn eval_expression<T: Variant + Clone>(&self, script: &str) -> RhaiResultOf<T> {
self.eval_expression_with_scope(&mut Scope::new(), script) self.eval_expression_with_scope(&mut Scope::new(), script)
} }
/// Evaluate a string containing an expression with own scope. /// Evaluate a string containing an expression with own scope, returning the result value or an error.
/// ///
/// # Example /// # Example
/// ///
@ -130,7 +130,7 @@ impl Engine {
self.eval_ast_with_scope(scope, &ast) self.eval_ast_with_scope(scope, &ast)
} }
/// Evaluate an [`AST`]. /// Evaluate an [`AST`], returning the result value or an error.
/// ///
/// # Example /// # Example
/// ///
@ -152,7 +152,7 @@ impl Engine {
pub fn eval_ast<T: Variant + Clone>(&self, ast: &AST) -> RhaiResultOf<T> { pub fn eval_ast<T: Variant + Clone>(&self, ast: &AST) -> RhaiResultOf<T> {
self.eval_ast_with_scope(&mut Scope::new(), ast) self.eval_ast_with_scope(&mut Scope::new(), ast)
} }
/// Evaluate an [`AST`] with own scope. /// Evaluate an [`AST`] with own scope, returning the result value or an error.
/// ///
/// # Example /// # Example
/// ///
@ -162,9 +162,6 @@ impl Engine {
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
/// ///
/// // Compile a script to an AST and store it for later evaluation
/// let ast = engine.compile("x + 2")?;
///
/// // Create initialized scope /// // Create initialized scope
/// let mut scope = Scope::new(); /// let mut scope = Scope::new();
/// scope.push("x", 40_i64); /// scope.push("x", 40_i64);
@ -209,7 +206,7 @@ impl Engine {
ERR::ErrorMismatchOutputType(t, typ.into(), Position::NONE).into() ERR::ErrorMismatchOutputType(t, typ.into(), Position::NONE).into()
}) })
} }
/// Evaluate an [`AST`] with own scope. /// Evaluate an [`AST`] with own scope, returning the result value or an error.
#[inline] #[inline]
pub(crate) fn eval_ast_with_scope_raw<'a>( pub(crate) fn eval_ast_with_scope_raw<'a>(
&self, &self,
@ -274,3 +271,20 @@ impl Engine {
self.eval_global_statements(scope, global, caches, statements, lib, level) self.eval_global_statements(scope, global, caches, statements, lib, level)
} }
} }
/// Evaluate a string as a script, returning the result value or an error.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// let result: i64 = rhai::eval("40 + 2")?;
///
/// assert_eq!(result, 42);
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub fn eval<T: Variant + Clone>(script: &str) -> RhaiResultOf<T> {
Engine::new().eval(script)
}

View File

@ -102,7 +102,7 @@ impl Engine {
pub fn compile_file_with_scope(&self, scope: &Scope, path: PathBuf) -> RhaiResultOf<AST> { pub fn compile_file_with_scope(&self, scope: &Scope, path: PathBuf) -> RhaiResultOf<AST> {
Self::read_file(path).and_then(|contents| Ok(self.compile_with_scope(scope, &contents)?)) Self::read_file(path).and_then(|contents| Ok(self.compile_with_scope(scope, &contents)?))
} }
/// Evaluate a script file. /// Evaluate a script file, returning the result value or an error.
/// ///
/// Not available under `no_std` or `WASM`. /// Not available under `no_std` or `WASM`.
/// ///
@ -123,7 +123,7 @@ impl Engine {
pub fn eval_file<T: Variant + Clone>(&self, path: PathBuf) -> RhaiResultOf<T> { pub fn eval_file<T: Variant + Clone>(&self, path: PathBuf) -> RhaiResultOf<T> {
Self::read_file(path).and_then(|contents| self.eval::<T>(&contents)) Self::read_file(path).and_then(|contents| self.eval::<T>(&contents))
} }
/// Evaluate a script file with own scope. /// Evaluate a script file with own scope, returning the result value or an error.
/// ///
/// Not available under `no_std` or `WASM`. /// Not available under `no_std` or `WASM`.
/// ///
@ -159,14 +159,28 @@ impl Engine {
) -> RhaiResultOf<T> { ) -> RhaiResultOf<T> {
Self::read_file(path).and_then(|contents| self.eval_with_scope(scope, &contents)) Self::read_file(path).and_then(|contents| self.eval_with_scope(scope, &contents))
} }
/// Evaluate a file, returning any error (if any). /// Evaluate a file.
/// ///
/// Not available under `no_std` or `WASM`. /// Not available under `no_std` or `WASM`.
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// // Notice that a PathBuf is required which can easily be constructed from a string.
/// engine.run_file("script.rhai".into())?;
/// # Ok(())
/// # }
/// ```
#[inline] #[inline]
pub fn run_file(&self, path: PathBuf) -> RhaiResultOf<()> { pub fn run_file(&self, path: PathBuf) -> RhaiResultOf<()> {
Self::read_file(path).and_then(|contents| self.run(&contents)) Self::read_file(path).and_then(|contents| self.run(&contents))
} }
/// Evaluate a file with own scope, returning any error (if any). /// Evaluate a file with own scope.
/// ///
/// Not available under `no_std` or `WASM`. /// Not available under `no_std` or `WASM`.
/// ///
@ -176,8 +190,66 @@ impl Engine {
/// the scope are propagated throughout the script _including_ functions. /// the scope are propagated throughout the script _including_ functions.
/// ///
/// This allows functions to be optimized based on dynamic global constants. /// This allows functions to be optimized based on dynamic global constants.
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Scope};
///
/// let engine = Engine::new();
///
/// // Create initialized scope
/// let mut scope = Scope::new();
/// scope.push("x", 42_i64);
///
/// // Notice that a PathBuf is required which can easily be constructed from a string.
/// engine.run_file_with_scope(&mut scope, "script.rhai".into())?;
/// # Ok(())
/// # }
/// ```
#[inline] #[inline]
pub fn run_file_with_scope(&self, scope: &mut Scope, path: PathBuf) -> RhaiResultOf<()> { pub fn run_file_with_scope(&self, scope: &mut Scope, path: PathBuf) -> RhaiResultOf<()> {
Self::read_file(path).and_then(|contents| self.run_with_scope(scope, &contents)) Self::read_file(path).and_then(|contents| self.run_with_scope(scope, &contents))
} }
} }
/// Evaluate a script file.
///
/// Not available under `no_std` or `WASM`.
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// // Notice that a PathBuf is required which can easily be constructed from a string.
/// let result: i64 = rhai::eval_file("script.rhai".into())?;
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn eval_file<T: Variant + Clone>(path: PathBuf) -> RhaiResultOf<T> {
Engine::read_file(path).and_then(|contents| Engine::new().eval::<T>(&contents))
}
/// Evaluate a file.
///
/// Not available under `no_std` or `WASM`.
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// // Notice that a PathBuf is required which can easily be constructed from a string.
/// rhai::run_file("script.rhai".into())?;
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn run_file(path: PathBuf) -> RhaiResultOf<()> {
Engine::read_file(path).and_then(|contents| Engine::new().run(&contents))
}

View File

@ -7,18 +7,52 @@ use crate::{Engine, Module, RhaiResultOf, Scope, AST};
use std::prelude::v1::*; use std::prelude::v1::*;
impl Engine { impl Engine {
/// Evaluate a script, returning any error (if any). /// Evaluate a string as a script.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// engine.run("print(40 + 2);")?;
/// # Ok(())
/// # }
/// ```
#[inline(always)] #[inline(always)]
pub fn run(&self, script: &str) -> RhaiResultOf<()> { pub fn run(&self, script: &str) -> RhaiResultOf<()> {
self.run_with_scope(&mut Scope::new(), script) self.run_with_scope(&mut Scope::new(), script)
} }
/// Evaluate a script with own scope, returning any error (if any). /// Evaluate a string as a script with own scope.
/// ///
/// ## Constants Propagation /// ## Constants Propagation
/// ///
/// If not [`OptimizationLevel::None`][crate::OptimizationLevel::None], constants defined within /// If not [`OptimizationLevel::None`][crate::OptimizationLevel::None], constants defined within
/// the scope are propagated throughout the script _including_ functions. This allows functions /// the scope are propagated throughout the script _including_ functions.
/// to be optimized based on dynamic global constants. ///
/// This allows functions to be optimized based on dynamic global constants.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Scope};
///
/// let engine = Engine::new();
///
/// // Create initialized scope
/// let mut scope = Scope::new();
/// scope.push("x", 40_i64);
///
/// engine.run_with_scope(&mut scope, "x += 2; print(x);")?;
///
/// // The variable in the scope is modified
/// assert_eq!(scope.get_value::<i64>("x").expect("variable x should exist"), 42);
/// # Ok(())
/// # }
/// ```
#[inline] #[inline]
pub fn run_with_scope(&self, scope: &mut Scope, script: &str) -> RhaiResultOf<()> { pub fn run_with_scope(&self, scope: &mut Scope, script: &str) -> RhaiResultOf<()> {
let scripts = [script]; let scripts = [script];
@ -28,12 +62,53 @@ impl Engine {
let ast = self.parse(&mut stream.peekable(), &mut state, self.optimization_level)?; let ast = self.parse(&mut stream.peekable(), &mut state, self.optimization_level)?;
self.run_ast_with_scope(scope, &ast) self.run_ast_with_scope(scope, &ast)
} }
/// Evaluate an [`AST`], returning any error (if any). /// Evaluate an [`AST`].
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// // Compile a script to an AST and store it for later evaluation
/// let ast = engine.compile("print(40 + 2);")?;
///
/// // Evaluate it
/// engine.run_ast(&ast)?;
/// # Ok(())
/// # }
/// ```
#[inline(always)] #[inline(always)]
pub fn run_ast(&self, ast: &AST) -> RhaiResultOf<()> { pub fn run_ast(&self, ast: &AST) -> RhaiResultOf<()> {
self.run_ast_with_scope(&mut Scope::new(), ast) self.run_ast_with_scope(&mut Scope::new(), ast)
} }
/// Evaluate an [`AST`] with own scope, returning any error (if any). /// Evaluate an [`AST`] with own scope.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Scope};
///
/// let engine = Engine::new();
///
/// // Create initialized scope
/// let mut scope = Scope::new();
/// scope.push("x", 40_i64);
///
/// // Compile a script to an AST and store it for later evaluation
/// let ast = engine.compile("x += 2; x")?;
///
/// // Evaluate it
/// engine.run_ast_with_scope(&mut scope, &ast)?;
///
/// // The variable in the scope is modified
/// assert_eq!(scope.get_value::<i64>("x").expect("variable x should exist"), 42);
/// # Ok(())
/// # }
/// ```
#[inline] #[inline]
pub fn run_ast_with_scope(&self, scope: &mut Scope, ast: &AST) -> RhaiResultOf<()> { pub fn run_ast_with_scope(&self, scope: &mut Scope, ast: &AST) -> RhaiResultOf<()> {
let caches = &mut Caches::new(); let caches = &mut Caches::new();
@ -73,3 +148,18 @@ impl Engine {
Ok(()) Ok(())
} }
} }
/// Evaluate a string as a script.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// rhai::run("print(40 + 2);")?;
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub fn run(script: &str) -> RhaiResultOf<()> {
Engine::new().run(script)
}

View File

@ -166,10 +166,12 @@ type ExclusiveRange = std::ops::Range<INT>;
/// An inclusive integer range. /// An inclusive integer range.
type InclusiveRange = std::ops::RangeInclusive<INT>; type InclusiveRange = std::ops::RangeInclusive<INT>;
pub use api::{ #[allow(deprecated)]
build_type::{CustomType, TypeBuilder}, pub use api::build_type::{CustomType, TypeBuilder};
events::VarDefInfo, #[cfg(not(feature = "no_std"))]
}; #[cfg(not(target_family = "wasm"))]
pub use api::files::{eval_file, run_file};
pub use api::{eval::eval, events::VarDefInfo, run::run};
pub use ast::{FnAccess, AST}; pub use ast::{FnAccess, AST};
pub use engine::{Engine, OP_CONTAINS, OP_EQUALS}; pub use engine::{Engine, OP_CONTAINS, OP_EQUALS};
pub use eval::EvalContext; pub use eval::EvalContext;

View File

@ -1,37 +1,38 @@
use rhai::{CustomType, Engine, EvalAltResult, Position, TypeBuilder}; #![cfg(not(feature = "no_object"))]
use rhai::{CustomType, Engine, EvalAltResult, Position, TypeBuilder, INT};
#[test] #[test]
fn build_type() -> Result<(), Box<EvalAltResult>> { fn build_type() -> Result<(), Box<EvalAltResult>> {
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
struct Vec3 { struct Vec3 {
x: i64, x: INT,
y: i64, y: INT,
z: i64, z: INT,
} }
impl Vec3 { impl Vec3 {
fn new(x: i64, y: i64, z: i64) -> Self { fn new(x: INT, y: INT, z: INT) -> Self {
Self { x, y, z } Self { x, y, z }
} }
fn get_x(&mut self) -> i64 { fn get_x(&mut self) -> INT {
self.x self.x
} }
fn set_x(&mut self, x: i64) { fn set_x(&mut self, x: INT) {
self.x = x self.x = x
} }
fn get_y(&mut self) -> i64 { fn get_y(&mut self) -> INT {
self.y self.y
} }
fn set_y(&mut self, y: i64) { fn set_y(&mut self, y: INT) {
self.y = y self.y = y
} }
fn get_z(&mut self) -> i64 { fn get_z(&mut self) -> INT {
self.z self.z
} }
fn set_z(&mut self, z: i64) { fn set_z(&mut self, z: INT) {
self.z = z self.z = z
} }
fn get_component(&mut self, idx: i64) -> Result<i64, Box<EvalAltResult>> { fn get_component(&mut self, idx: INT) -> Result<INT, Box<EvalAltResult>> {
match idx { match idx {
0 => Ok(self.x), 0 => Ok(self.x),
1 => Ok(self.y), 1 => Ok(self.y),
@ -51,8 +52,10 @@ fn build_type() -> Result<(), Box<EvalAltResult>> {
.with_fn("vec3", Self::new) .with_fn("vec3", Self::new)
.with_get_set("x", Self::get_x, Self::set_x) .with_get_set("x", Self::get_x, Self::set_x)
.with_get_set("y", Self::get_y, Self::set_y) .with_get_set("y", Self::get_y, Self::set_y)
.with_get_set("z", Self::get_z, Self::set_z) .with_get_set("z", Self::get_z, Self::set_z);
.with_indexer_get_result(Self::get_component);
#[cfg(not(feature = "no_index"))]
builder.with_indexer_get_result(Self::get_component);
} }
} }
@ -61,55 +64,56 @@ fn build_type() -> Result<(), Box<EvalAltResult>> {
assert_eq!( assert_eq!(
engine.eval::<Vec3>( engine.eval::<Vec3>(
r#" "
let v = vec3(1, 2, 3); let v = vec3(1, 2, 3);
v v
"#, ",
)?, )?,
Vec3::new(1, 2, 3), Vec3::new(1, 2, 3),
); );
assert_eq!( assert_eq!(
engine.eval::<i64>( engine.eval::<INT>(
r#" "
let v = vec3(1, 2, 3); let v = vec3(1, 2, 3);
v.x v.x
"#, ",
)?, )?,
1, 1,
); );
assert_eq!( assert_eq!(
engine.eval::<i64>( engine.eval::<INT>(
r#" "
let v = vec3(1, 2, 3); let v = vec3(1, 2, 3);
v.y v.y
"#, ",
)?, )?,
2, 2,
); );
assert_eq!( assert_eq!(
engine.eval::<i64>( engine.eval::<INT>(
r#" "
let v = vec3(1, 2, 3); let v = vec3(1, 2, 3);
v.z v.z
"#, ",
)?, )?,
3, 3,
); );
#[cfg(not(feature = "no_index"))]
assert!(engine.eval::<bool>( assert!(engine.eval::<bool>(
r#" "
let v = vec3(1, 2, 3); let v = vec3(1, 2, 3);
v.x == v[0] && v.y == v[1] && v.z == v[2] v.x == v[0] && v.y == v[1] && v.z == v[2]
"#, ",
)?); )?);
assert_eq!( assert_eq!(
engine.eval::<Vec3>( engine.eval::<Vec3>(
r#" "
let v = vec3(1, 2, 3); let v = vec3(1, 2, 3);
v.x = 5; v.x = 5;
v.y = 6; v.y = 6;
v.z = 7; v.z = 7;
v v
"#, ",
)?, )?,
Vec3::new(5, 6, 7), Vec3::new(5, 6, 7),
); );