Remove unnecessary traits and types.

This commit is contained in:
Stephen Chung 2020-05-21 17:11:01 +08:00
parent 80fcc40710
commit 800a7bf283
4 changed files with 69 additions and 188 deletions

View File

@ -13,6 +13,8 @@ New features
------------
* Set limits on maximum level of nesting expressions and statements to avoid panics during parsing.
* New `EvalPackage` to disable `eval`.
* More benchmarks.
Version 0.14.1

View File

@ -4,7 +4,7 @@ use crate::any::{Dynamic, Variant};
use crate::engine::{make_getter, make_setter, Engine, State, FUNC_INDEXER};
use crate::error::ParseError;
use crate::fn_call::FuncArgs;
use crate::fn_native::{IteratorFn, ObjectGetCallback, ObjectIndexerCallback, ObjectSetCallback};
use crate::fn_native::{IteratorFn, SendSync};
use crate::fn_register::RegisterFn;
use crate::optimize::{optimize_into_ast, OptimizationLevel};
use crate::parser::{parse, parse_global_expr, AST};
@ -162,11 +162,13 @@ impl Engine {
/// # }
/// ```
#[cfg(not(feature = "no_object"))]
pub fn register_get<T, U, F>(&mut self, name: &str, callback: F)
where
pub fn register_get<T, U>(
&mut self,
name: &str,
callback: impl Fn(&mut T) -> U + SendSync + 'static,
) where
T: Variant + Clone,
U: Variant + Clone,
F: ObjectGetCallback<T, U>,
{
self.register_fn(&make_getter(name), callback);
}
@ -208,11 +210,13 @@ impl Engine {
/// # }
/// ```
#[cfg(not(feature = "no_object"))]
pub fn register_set<T, U, F>(&mut self, name: &str, callback: F)
where
pub fn register_set<T, U>(
&mut self,
name: &str,
callback: impl Fn(&mut T, U) + SendSync + 'static,
) where
T: Variant + Clone,
U: Variant + Clone,
F: ObjectSetCallback<T, U>,
{
self.register_fn(&make_setter(name), callback);
}
@ -256,12 +260,14 @@ impl Engine {
/// # }
/// ```
#[cfg(not(feature = "no_object"))]
pub fn register_get_set<T, U, G, S>(&mut self, name: &str, get_fn: G, set_fn: S)
where
pub fn register_get_set<T, U>(
&mut self,
name: &str,
get_fn: impl Fn(&mut T) -> U + SendSync + 'static,
set_fn: impl Fn(&mut T, U) + SendSync + 'static,
) where
T: Variant + Clone,
U: Variant + Clone,
G: ObjectGetCallback<T, U>,
S: ObjectSetCallback<T, U>,
{
self.register_get(name, get_fn);
self.register_set(name, set_fn);
@ -305,12 +311,13 @@ impl Engine {
/// ```
#[cfg(not(feature = "no_object"))]
#[cfg(not(feature = "no_index"))]
pub fn register_indexer<T, X, U, F>(&mut self, callback: F)
where
pub fn register_indexer<T, X, U>(
&mut self,
callback: impl Fn(&mut T, X) -> U + SendSync + 'static,
) where
T: Variant + Clone,
U: Variant + Clone,
X: Variant + Clone,
F: ObjectIndexerCallback<T, X, U>,
{
self.register_fn(FUNC_INDEXER, callback);
}
@ -1118,47 +1125,7 @@ impl Engine {
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "sync")]
pub fn on_progress(&mut self, callback: impl Fn(u64) -> bool + Send + Sync + 'static) {
self.progress = Some(Box::new(callback));
}
/// Register a callback for script evaluation progress.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # use std::cell::Cell;
/// # use std::rc::Rc;
/// use rhai::Engine;
///
/// let result = Rc::new(Cell::new(0_u64));
/// let logger = result.clone();
///
/// let mut engine = Engine::new();
///
/// engine.on_progress(move |ops| {
/// if ops > 10000 {
/// false
/// } else if ops % 800 == 0 {
/// logger.set(ops);
/// true
/// } else {
/// true
/// }
/// });
///
/// engine.consume("for x in range(0, 50000) {}")
/// .expect_err("should error");
///
/// assert_eq!(result.get(), 9600);
///
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "sync"))]
pub fn on_progress(&mut self, callback: impl Fn(u64) -> bool + 'static) {
pub fn on_progress(&mut self, callback: impl Fn(u64) -> bool + SendSync + 'static) {
self.progress = Some(Box::new(callback));
}
@ -1186,36 +1153,7 @@ impl Engine {
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "sync")]
pub fn on_print(&mut self, callback: impl Fn(&str) + Send + Sync + 'static) {
self.print = Box::new(callback);
}
/// Override default action of `print` (print to stdout using `println!`)
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # use std::cell::RefCell;
/// # use std::rc::Rc;
/// use rhai::Engine;
///
/// let result = Rc::new(RefCell::new(String::from("")));
///
/// let mut engine = Engine::new();
///
/// // Override action of 'print' function
/// let logger = result.clone();
/// engine.on_print(move |s| logger.borrow_mut().push_str(s));
///
/// engine.consume("print(40 + 2);")?;
///
/// assert_eq!(*result.borrow(), "42");
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "sync"))]
pub fn on_print(&mut self, callback: impl Fn(&str) + 'static) {
pub fn on_print(&mut self, callback: impl Fn(&str) + SendSync + 'static) {
self.print = Box::new(callback);
}
@ -1243,36 +1181,7 @@ impl Engine {
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "sync")]
pub fn on_debug(&mut self, callback: impl Fn(&str) + Send + Sync + 'static) {
self.debug = Box::new(callback);
}
/// Override default action of `debug` (print to stdout using `println!`)
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// # use std::cell::RefCell;
/// # use std::rc::Rc;
/// use rhai::Engine;
///
/// let result = Rc::new(RefCell::new(String::from("")));
///
/// let mut engine = Engine::new();
///
/// // Override action of 'print' function
/// let logger = result.clone();
/// engine.on_debug(move |s| logger.borrow_mut().push_str(s));
///
/// engine.consume(r#"debug("hello");"#)?;
///
/// assert_eq!(*result.borrow(), r#""hello""#);
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "sync"))]
pub fn on_debug(&mut self, callback: impl Fn(&str) + 'static) {
pub fn on_debug(&mut self, callback: impl Fn(&str) + SendSync + 'static) {
self.debug = Box::new(callback);
}
}

View File

@ -3,7 +3,7 @@
use crate::any::{Dynamic, Union};
use crate::calc_fn_hash;
use crate::error::ParseErrorType;
use crate::fn_native::{FnCallArgs, PrintCallback, ProgressCallback, SharedFnDef};
use crate::fn_native::{FnCallArgs, Shared};
use crate::module::Module;
use crate::optimize::OptimizationLevel;
use crate::packages::{CorePackage, Package, PackageLibrary, PackagesCollection, StandardPackage};
@ -217,7 +217,7 @@ impl<'a> State<'a> {
///
/// The key of the `HashMap` is a `u64` hash calculated by the function `calc_fn_hash`.
#[derive(Debug, Clone, Default)]
pub struct FunctionsLib(HashMap<u64, SharedFnDef>);
pub struct FunctionsLib(HashMap<u64, Shared<FnDef>>);
impl FunctionsLib {
/// Create a new `FunctionsLib` from a collection of `FnDef`.
@ -275,17 +275,14 @@ impl FunctionsLib {
}
}
impl From<Vec<(u64, SharedFnDef)>> for FunctionsLib {
fn from(values: Vec<(u64, SharedFnDef)>) -> Self {
impl From<Vec<(u64, Shared<FnDef>)>> for FunctionsLib {
fn from(values: Vec<(u64, Shared<FnDef>)>) -> Self {
FunctionsLib(values.into_iter().collect())
}
}
impl Deref for FunctionsLib {
#[cfg(feature = "sync")]
type Target = HashMap<u64, Arc<FnDef>>;
#[cfg(not(feature = "sync"))]
type Target = HashMap<u64, Rc<FnDef>>;
type Target = HashMap<u64, Shared<FnDef>>;
fn deref(&self) -> &Self::Target {
&self.0
@ -293,12 +290,7 @@ impl Deref for FunctionsLib {
}
impl DerefMut for FunctionsLib {
#[cfg(feature = "sync")]
fn deref_mut(&mut self) -> &mut HashMap<u64, Arc<FnDef>> {
&mut self.0
}
#[cfg(not(feature = "sync"))]
fn deref_mut(&mut self) -> &mut HashMap<u64, Rc<FnDef>> {
fn deref_mut(&mut self) -> &mut HashMap<u64, Shared<FnDef>> {
&mut self.0
}
}
@ -333,11 +325,25 @@ pub struct Engine {
pub(crate) type_names: HashMap<String, String>,
/// Closure for implementing the `print` command.
pub(crate) print: Box<PrintCallback>,
#[cfg(not(feature = "sync"))]
pub(crate) print: Box<dyn Fn(&str) + 'static>,
/// Closure for implementing the `print` command.
#[cfg(feature = "sync")]
pub(crate) print: Box<dyn Fn(&str) + Send + Sync + 'static>,
/// Closure for implementing the `debug` command.
pub(crate) debug: Box<PrintCallback>,
#[cfg(not(feature = "sync"))]
pub(crate) debug: Box<dyn Fn(&str) + 'static>,
/// Closure for implementing the `debug` command.
#[cfg(feature = "sync")]
pub(crate) debug: Box<dyn Fn(&str) + Send + Sync + 'static>,
/// Closure for progress reporting.
pub(crate) progress: Option<Box<ProgressCallback>>,
#[cfg(not(feature = "sync"))]
pub(crate) progress: Option<Box<dyn Fn(u64) -> bool + 'static>>,
/// Closure for progress reporting.
#[cfg(feature = "sync")]
pub(crate) progress: Option<Box<dyn Fn(u64) -> bool + Send + Sync + 'static>>,
/// Optimize the AST after compilation.
pub(crate) optimization_level: OptimizationLevel,

View File

@ -4,78 +4,42 @@ use crate::result::EvalAltResult;
use crate::stdlib::{boxed::Box, rc::Rc, sync::Arc};
#[cfg(feature = "sync")]
pub trait SendSync: Send + Sync {}
#[cfg(feature = "sync")]
impl<T: Send + Sync> SendSync for T {}
#[cfg(not(feature = "sync"))]
pub trait SendSync {}
#[cfg(not(feature = "sync"))]
impl<T> SendSync for T {}
#[cfg(not(feature = "sync"))]
pub type Shared<T> = Rc<T>;
#[cfg(feature = "sync")]
pub type Shared<T> = Arc<T>;
pub type FnCallArgs<'a> = [&'a mut Dynamic];
#[cfg(feature = "sync")]
pub type FnAny = dyn Fn(&mut FnCallArgs) -> Result<Dynamic, Box<EvalAltResult>> + Send + Sync;
#[cfg(not(feature = "sync"))]
pub type FnAny = dyn Fn(&mut FnCallArgs) -> Result<Dynamic, Box<EvalAltResult>>;
#[cfg(feature = "sync")]
pub type FnAny = dyn Fn(&mut FnCallArgs) -> Result<Dynamic, Box<EvalAltResult>> + Send + Sync;
pub type IteratorFn = fn(Dynamic) -> Box<dyn Iterator<Item = Dynamic>>;
#[cfg(feature = "sync")]
pub type PrintCallback = dyn Fn(&str) + Send + Sync + 'static;
#[cfg(not(feature = "sync"))]
pub type PrintCallback = dyn Fn(&str) + 'static;
#[cfg(feature = "sync")]
pub type ProgressCallback = dyn Fn(u64) -> bool + Send + Sync + 'static;
#[cfg(not(feature = "sync"))]
pub type ProgressCallback = dyn Fn(u64) -> bool + 'static;
// Define callback function types
#[cfg(feature = "sync")]
pub trait ObjectGetCallback<T, U>: Fn(&mut T) -> U + Send + Sync + 'static {}
#[cfg(feature = "sync")]
impl<F: Fn(&mut T) -> U + Send + Sync + 'static, T, U> ObjectGetCallback<T, U> for F {}
#[cfg(not(feature = "sync"))]
pub trait ObjectGetCallback<T, U>: Fn(&mut T) -> U + 'static {}
#[cfg(not(feature = "sync"))]
impl<F: Fn(&mut T) -> U + 'static, T, U> ObjectGetCallback<T, U> for F {}
#[cfg(feature = "sync")]
pub trait ObjectSetCallback<T, U>: Fn(&mut T, U) + Send + Sync + 'static {}
#[cfg(feature = "sync")]
impl<F: Fn(&mut T, U) + Send + Sync + 'static, T, U> ObjectSetCallback<T, U> for F {}
#[cfg(not(feature = "sync"))]
pub trait ObjectSetCallback<T, U>: Fn(&mut T, U) + 'static {}
#[cfg(not(feature = "sync"))]
impl<F: Fn(&mut T, U) + 'static, T, U> ObjectSetCallback<T, U> for F {}
#[cfg(feature = "sync")]
pub trait ObjectIndexerCallback<T, X, U>: Fn(&mut T, X) -> U + Send + Sync + 'static {}
#[cfg(feature = "sync")]
impl<F: Fn(&mut T, X) -> U + Send + Sync + 'static, T, X, U> ObjectIndexerCallback<T, X, U> for F {}
#[cfg(not(feature = "sync"))]
pub trait ObjectIndexerCallback<T, X, U>: Fn(&mut T, X) -> U + 'static {}
#[cfg(not(feature = "sync"))]
impl<F: Fn(&mut T, X) -> U + 'static, T, X, U> ObjectIndexerCallback<T, X, U> for F {}
#[cfg(not(feature = "sync"))]
pub type SharedNativeFunction = Rc<FnAny>;
#[cfg(feature = "sync")]
pub type SharedNativeFunction = Arc<FnAny>;
#[cfg(feature = "sync")]
pub type SharedFnDef = Arc<FnDef>;
#[cfg(not(feature = "sync"))]
pub type SharedFnDef = Rc<FnDef>;
/// A type encapsulating a function callable by Rhai.
#[derive(Clone)]
pub enum CallableFunction {
/// A pure native Rust function with all arguments passed by value.
Pure(SharedNativeFunction),
Pure(Shared<FnAny>),
/// A native Rust object method with the first argument passed by reference,
/// and the rest passed by value.
Method(SharedNativeFunction),
Method(Shared<FnAny>),
/// An iterator function.
Iterator(IteratorFn),
/// A script-defined function.
Script(SharedFnDef),
Script(Shared<FnDef>),
}
impl CallableFunction {