Add top-level wrappers.

This commit is contained in:
Stephen Chung 2022-08-08 09:10:15 +08:00
parent 862de2049b
commit 47f02b96d7
5 changed files with 204 additions and 21 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.
### Top-level functions
* Crate-level functions `rhai::eval`, `rhai::run`, `rhai::eval_file`, `rhai::run_file` are added as convenient wrappers.
Enhancements
------------

View File

@ -11,7 +11,7 @@ use std::any::type_name;
use std::prelude::v1::*;
impl Engine {
/// Evaluate a string.
/// Evaluate a string as a script, returning the result value or an error.
///
/// # Example
///
@ -29,7 +29,7 @@ impl Engine {
pub fn eval<T: Variant + Clone>(&self, script: &str) -> RhaiResultOf<T> {
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
///
@ -71,7 +71,7 @@ impl Engine {
)?;
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
///
@ -89,7 +89,7 @@ impl Engine {
pub fn eval_expression<T: Variant + Clone>(&self, script: &str) -> RhaiResultOf<T> {
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
///
@ -130,7 +130,7 @@ impl Engine {
self.eval_ast_with_scope(scope, &ast)
}
/// Evaluate an [`AST`].
/// Evaluate an [`AST`], returning the result value or an error.
///
/// # Example
///
@ -152,7 +152,7 @@ impl Engine {
pub fn eval_ast<T: Variant + Clone>(&self, ast: &AST) -> RhaiResultOf<T> {
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
///
@ -162,9 +162,6 @@ impl Engine {
///
/// 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
/// let mut scope = Scope::new();
/// scope.push("x", 40_i64);
@ -209,7 +206,7 @@ impl Engine {
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]
pub(crate) fn eval_ast_with_scope_raw<'a>(
&self,
@ -274,3 +271,20 @@ impl Engine {
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> {
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`.
///
@ -123,7 +123,7 @@ impl Engine {
pub fn eval_file<T: Variant + Clone>(&self, path: PathBuf) -> RhaiResultOf<T> {
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`.
///
@ -159,14 +159,28 @@ impl Engine {
) -> RhaiResultOf<T> {
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`.
///
/// # 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]
pub fn run_file(&self, path: PathBuf) -> RhaiResultOf<()> {
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`.
///
@ -176,8 +190,66 @@ impl Engine {
/// the scope are propagated throughout the script _including_ functions.
///
/// 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]
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))
}
}
/// 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::*;
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::<i64>("print(40 + 2);")?;
/// # Ok(())
/// # }
/// ```
#[inline(always)]
pub fn run(&self, script: &str) -> RhaiResultOf<()> {
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
///
/// If not [`OptimizationLevel::None`][crate::OptimizationLevel::None], constants defined within
/// the scope are propagated throughout the script _including_ functions. This allows functions
/// to be optimized based on dynamic global constants.
/// the scope are propagated throughout the script _including_ functions.
///
/// 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"), 44);
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn run_with_scope(&self, scope: &mut Scope, script: &str) -> RhaiResultOf<()> {
let scripts = [script];
@ -28,12 +62,53 @@ impl Engine {
let ast = self.parse(&mut stream.peekable(), &mut state, self.optimization_level)?;
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)]
pub fn run_ast(&self, ast: &AST) -> RhaiResultOf<()> {
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"), 44);
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn run_ast_with_scope(&self, scope: &mut Scope, ast: &AST) -> RhaiResultOf<()> {
let caches = &mut Caches::new();
@ -73,3 +148,18 @@ impl Engine {
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,7 +166,10 @@ type ExclusiveRange = std::ops::Range<INT>;
/// An inclusive integer range.
type InclusiveRange = std::ops::RangeInclusive<INT>;
pub use api::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 engine::{Engine, OP_CONTAINS, OP_EQUALS};
pub use eval::EvalContext;