General code cleanup.
This commit is contained in:
parent
bb56a7a843
commit
ba2aac4960
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "rhai"
|
name = "rhai"
|
||||||
version = "0.10.1"
|
version = "0.10.2"
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung"]
|
authors = ["Jonathan Turner", "Lukáš Hozda", "Stephen Chung"]
|
||||||
description = "Embedded scripting for Rust"
|
description = "Embedded scripting for Rust"
|
||||||
|
35
src/api.rs
35
src/api.rs
@ -31,7 +31,8 @@ impl<'a> Engine<'a> {
|
|||||||
args,
|
args,
|
||||||
};
|
};
|
||||||
|
|
||||||
self.fns.insert(spec, Arc::new(FnIntExt::Ext(f)));
|
self.external_functions
|
||||||
|
.insert(spec, Arc::new(FnIntExt::Ext(f)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register a custom type for use with the `Engine`.
|
/// Register a custom type for use with the `Engine`.
|
||||||
@ -62,20 +63,20 @@ impl<'a> Engine<'a> {
|
|||||||
pub fn register_get<T: Any + Clone, U: Any + Clone>(
|
pub fn register_get<T: Any + Clone, U: Any + Clone>(
|
||||||
&mut self,
|
&mut self,
|
||||||
name: &str,
|
name: &str,
|
||||||
get_fn: impl Fn(&mut T) -> U + 'static,
|
callback: impl Fn(&mut T) -> U + 'static,
|
||||||
) {
|
) {
|
||||||
let get_name = "get$".to_string() + name;
|
let get_name = "get$".to_string() + name;
|
||||||
self.register_fn(&get_name, get_fn);
|
self.register_fn(&get_name, callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register a setter function for a member of a registered type with the `Engine`.
|
/// Register a setter function for a member of a registered type with the `Engine`.
|
||||||
pub fn register_set<T: Any + Clone, U: Any + Clone>(
|
pub fn register_set<T: Any + Clone, U: Any + Clone>(
|
||||||
&mut self,
|
&mut self,
|
||||||
name: &str,
|
name: &str,
|
||||||
set_fn: impl Fn(&mut T, U) -> () + 'static,
|
callback: impl Fn(&mut T, U) -> () + 'static,
|
||||||
) {
|
) {
|
||||||
let set_name = "set$".to_string() + name;
|
let set_name = "set$".to_string() + name;
|
||||||
self.register_fn(&set_name, set_fn);
|
self.register_fn(&set_name, callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shorthand for registering both getter and setter functions
|
/// Shorthand for registering both getter and setter functions
|
||||||
@ -154,10 +155,10 @@ impl<'a> Engine<'a> {
|
|||||||
scope: &mut Scope,
|
scope: &mut Scope,
|
||||||
ast: &AST,
|
ast: &AST,
|
||||||
) -> Result<T, EvalAltResult> {
|
) -> Result<T, EvalAltResult> {
|
||||||
let AST(os, fns) = ast;
|
let AST(statements, functions) = ast;
|
||||||
|
|
||||||
fns.iter().for_each(|f| {
|
functions.iter().for_each(|f| {
|
||||||
self.script_fns.insert(
|
self.script_functions.insert(
|
||||||
FnSpec {
|
FnSpec {
|
||||||
name: f.name.clone().into(),
|
name: f.name.clone().into(),
|
||||||
args: None,
|
args: None,
|
||||||
@ -166,11 +167,11 @@ impl<'a> Engine<'a> {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
let result = os
|
let result = statements
|
||||||
.iter()
|
.iter()
|
||||||
.try_fold(().into_dynamic(), |_, o| self.eval_stmt(scope, o));
|
.try_fold(().into_dynamic(), |_, o| self.eval_stmt(scope, o));
|
||||||
|
|
||||||
self.script_fns.clear(); // Clean up engine
|
self.script_functions.clear(); // Clean up engine
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Err(EvalAltResult::Return(out, pos)) => out.downcast::<T>().map(|v| *v).map_err(|a| {
|
Err(EvalAltResult::Return(out, pos)) => out.downcast::<T>().map(|v| *v).map_err(|a| {
|
||||||
@ -227,9 +228,9 @@ impl<'a> Engine<'a> {
|
|||||||
|
|
||||||
parse(&mut tokens.peekable())
|
parse(&mut tokens.peekable())
|
||||||
.map_err(|err| EvalAltResult::ErrorParsing(err))
|
.map_err(|err| EvalAltResult::ErrorParsing(err))
|
||||||
.and_then(|AST(ref os, ref fns)| {
|
.and_then(|AST(ref statements, ref functions)| {
|
||||||
for f in fns {
|
for f in functions {
|
||||||
self.script_fns.insert(
|
self.script_functions.insert(
|
||||||
FnSpec {
|
FnSpec {
|
||||||
name: f.name.clone().into(),
|
name: f.name.clone().into(),
|
||||||
args: None,
|
args: None,
|
||||||
@ -238,12 +239,12 @@ impl<'a> Engine<'a> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let val = os
|
let val = statements
|
||||||
.iter()
|
.iter()
|
||||||
.try_fold(().into_dynamic(), |_, o| self.eval_stmt(scope, o))
|
.try_fold(().into_dynamic(), |_, o| self.eval_stmt(scope, o))
|
||||||
.map(|_| ());
|
.map(|_| ());
|
||||||
|
|
||||||
self.script_fns.clear(); // Clean up engine
|
self.script_functions.clear(); // Clean up engine
|
||||||
|
|
||||||
val
|
val
|
||||||
})
|
})
|
||||||
@ -275,7 +276,7 @@ impl<'a> Engine<'a> {
|
|||||||
let pos = Default::default();
|
let pos = Default::default();
|
||||||
|
|
||||||
ast.1.iter().for_each(|f| {
|
ast.1.iter().for_each(|f| {
|
||||||
self.script_fns.insert(
|
self.script_functions.insert(
|
||||||
FnSpec {
|
FnSpec {
|
||||||
name: f.name.clone().into(),
|
name: f.name.clone().into(),
|
||||||
args: None,
|
args: None,
|
||||||
@ -295,7 +296,7 @@ impl<'a> Engine<'a> {
|
|||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
self.script_fns.clear(); // Clean up engine
|
self.script_functions.clear(); // Clean up engine
|
||||||
|
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
@ -41,9 +41,9 @@ type IteratorFn = dyn Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>>;
|
|||||||
/// ```
|
/// ```
|
||||||
pub struct Engine<'a> {
|
pub struct Engine<'a> {
|
||||||
/// A hashmap containing all compiled functions known to the engine
|
/// A hashmap containing all compiled functions known to the engine
|
||||||
pub(crate) fns: HashMap<FnSpec<'a>, Arc<FnIntExt>>,
|
pub(crate) external_functions: HashMap<FnSpec<'a>, Arc<FnIntExt>>,
|
||||||
/// A hashmap containing all script-defined functions
|
/// A hashmap containing all script-defined functions
|
||||||
pub(crate) script_fns: HashMap<FnSpec<'a>, Arc<FnIntExt>>,
|
pub(crate) script_functions: HashMap<FnSpec<'a>, Arc<FnIntExt>>,
|
||||||
/// A hashmap containing all iterators known to the engine
|
/// A hashmap containing all iterators known to the engine
|
||||||
pub(crate) type_iterators: HashMap<TypeId, Arc<IteratorFn>>,
|
pub(crate) type_iterators: HashMap<TypeId, Arc<IteratorFn>>,
|
||||||
pub(crate) type_names: HashMap<String, String>,
|
pub(crate) type_names: HashMap<String, String>,
|
||||||
@ -87,11 +87,11 @@ impl Engine<'_> {
|
|||||||
// First search in script-defined functions (can override built-in),
|
// First search in script-defined functions (can override built-in),
|
||||||
// then in built-in's
|
// then in built-in's
|
||||||
let fn_def = self
|
let fn_def = self
|
||||||
.script_fns
|
.script_functions
|
||||||
.get(&spec)
|
.get(&spec)
|
||||||
.or_else(|| {
|
.or_else(|| {
|
||||||
spec.args = Some(args.iter().map(|a| Any::type_id(&**a)).collect());
|
spec.args = Some(args.iter().map(|a| Any::type_id(&**a)).collect());
|
||||||
self.fns.get(&spec)
|
self.external_functions.get(&spec)
|
||||||
})
|
})
|
||||||
.map(|f| f.clone());
|
.map(|f| f.clone());
|
||||||
|
|
||||||
@ -741,8 +741,8 @@ impl Engine<'_> {
|
|||||||
|
|
||||||
// Create the new scripting Engine
|
// Create the new scripting Engine
|
||||||
let mut engine = Engine {
|
let mut engine = Engine {
|
||||||
fns: HashMap::new(),
|
external_functions: HashMap::new(),
|
||||||
script_fns: HashMap::new(),
|
script_functions: HashMap::new(),
|
||||||
type_iterators: HashMap::new(),
|
type_iterators: HashMap::new(),
|
||||||
type_names,
|
type_names,
|
||||||
on_print: Box::new(|x| println!("{}", x)), // default print/debug implementations
|
on_print: Box::new(|x| println!("{}", x)), // default print/debug implementations
|
||||||
|
@ -61,8 +61,8 @@ pub struct Ref<A>(A);
|
|||||||
pub struct Mut<A>(A);
|
pub struct Mut<A>(A);
|
||||||
|
|
||||||
macro_rules! count_args {
|
macro_rules! count_args {
|
||||||
() => {0usize};
|
() => { 0_usize };
|
||||||
($head:ident $($tail:ident)*) => {1usize + count_args!($($tail)*)};
|
( $head:ident $($tail:ident)* ) => { 1_usize + count_args!($($tail)*) };
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! def_register {
|
macro_rules! def_register {
|
||||||
@ -80,8 +80,7 @@ macro_rules! def_register {
|
|||||||
let fn_name = name.to_string();
|
let fn_name = name.to_string();
|
||||||
|
|
||||||
let fun = move |mut args: FnCallArgs, pos: Position| {
|
let fun = move |mut args: FnCallArgs, pos: Position| {
|
||||||
// Check for length at the beginning to avoid
|
// Check for length at the beginning to avoid per-element bound checks.
|
||||||
// per-element bound checks.
|
|
||||||
const NUM_ARGS: usize = count_args!($($par)*);
|
const NUM_ARGS: usize = count_args!($($par)*);
|
||||||
|
|
||||||
if args.len() != NUM_ARGS {
|
if args.len() != NUM_ARGS {
|
||||||
@ -113,8 +112,7 @@ macro_rules! def_register {
|
|||||||
let fn_name = name.to_string();
|
let fn_name = name.to_string();
|
||||||
|
|
||||||
let fun = move |mut args: FnCallArgs, pos: Position| {
|
let fun = move |mut args: FnCallArgs, pos: Position| {
|
||||||
// Check for length at the beginning to avoid
|
// Check for length at the beginning to avoid per-element bound checks.
|
||||||
// per-element bound checks.
|
|
||||||
const NUM_ARGS: usize = count_args!($($par)*);
|
const NUM_ARGS: usize = count_args!($($par)*);
|
||||||
|
|
||||||
if args.len() != NUM_ARGS {
|
if args.len() != NUM_ARGS {
|
||||||
|
@ -51,11 +51,8 @@ impl Position {
|
|||||||
/// Panics if already at beginning of a line - cannot rewind to a previous line.
|
/// Panics if already at beginning of a line - cannot rewind to a previous line.
|
||||||
///
|
///
|
||||||
pub(crate) fn rewind(&mut self) {
|
pub(crate) fn rewind(&mut self) {
|
||||||
if self.pos == 0 {
|
assert!(self.pos > 0, "cannot rewind at position 0");
|
||||||
panic!("cannot rewind at position 0");
|
self.pos -= 1;
|
||||||
} else {
|
|
||||||
self.pos -= 1;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Advance to the next line.
|
/// Advance to the next line.
|
||||||
@ -159,7 +156,9 @@ impl Expr {
|
|||||||
| Expr::False(pos)
|
| Expr::False(pos)
|
||||||
| Expr::Unit(pos) => *pos,
|
| Expr::Unit(pos) => *pos,
|
||||||
|
|
||||||
Expr::Assignment(_, _) | Expr::Dot(_, _) | Expr::And(_, _) | Expr::Or(_, _) => panic!(),
|
Expr::Assignment(e, _) | Expr::Dot(e, _) | Expr::And(e, _) | Expr::Or(e, _) => {
|
||||||
|
e.position()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
18
src/scope.rs
18
src/scope.rs
@ -61,8 +61,8 @@ impl Scope {
|
|||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.rev() // Always search a Scope in reverse order
|
.rev() // Always search a Scope in reverse order
|
||||||
.find(|(_, (n, _))| n == key)
|
.find(|(_, (name, _))| name == key)
|
||||||
.map(|(i, (n, v))| (i, n.clone(), v.clone()))
|
.map(|(i, (name, value))| (i, name.clone(), value.clone()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the value of a variable in the Scope, starting from the last.
|
/// Get the value of a variable in the Scope, starting from the last.
|
||||||
@ -71,18 +71,16 @@ impl Scope {
|
|||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.rev() // Always search a Scope in reverse order
|
.rev() // Always search a Scope in reverse order
|
||||||
.find(|(_, (n, _))| n == key)
|
.find(|(_, (name, _))| name == key)
|
||||||
.and_then(|(_, (_, v))| v.downcast_ref::<T>())
|
.and_then(|(_, (_, value))| value.downcast_ref::<T>())
|
||||||
.map(|v| v.clone())
|
.map(|value| value.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a mutable reference to a variable in the Scope.
|
/// Get a mutable reference to a variable in the Scope.
|
||||||
pub(crate) fn get_mut(&mut self, key: &str, index: usize) -> &mut Dynamic {
|
pub(crate) fn get_mut(&mut self, key: &str, index: usize) -> &mut Dynamic {
|
||||||
let entry = self.0.get_mut(index).expect("invalid index in Scope");
|
let entry = self.0.get_mut(index).expect("invalid index in Scope");
|
||||||
|
|
||||||
if entry.0 != key {
|
assert_eq!(entry.0, key, "incorrect key at Scope entry");
|
||||||
panic!("incorrect key at Scope entry");
|
|
||||||
}
|
|
||||||
|
|
||||||
&mut entry.1
|
&mut entry.1
|
||||||
}
|
}
|
||||||
@ -92,7 +90,7 @@ impl Scope {
|
|||||||
self.0
|
self.0
|
||||||
.iter()
|
.iter()
|
||||||
.rev() // Always search a Scope in reverse order
|
.rev() // Always search a Scope in reverse order
|
||||||
.map(|(key, val)| (key.as_str(), val))
|
.map(|(key, value)| (key.as_str(), value))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a mutable iterator to variables in the Scope.
|
/// Get a mutable iterator to variables in the Scope.
|
||||||
@ -100,7 +98,7 @@ impl Scope {
|
|||||||
self.0
|
self.0
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.rev() // Always search a Scope in reverse order
|
.rev() // Always search a Scope in reverse order
|
||||||
.map(|(key, val)| (key.as_str(), val))
|
.map(|(key, value)| (key.as_str(), value))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user