Merge branch 'master' into plugins

This commit is contained in:
Stephen Chung 2020-05-02 11:57:45 +08:00
commit 3f9c4c32da
8 changed files with 302 additions and 275 deletions

View File

@ -376,7 +376,7 @@ The follow packages are available:
| Package | Description | In `CorePackage` | In `StandardPackage` | | Package | Description | In `CorePackage` | In `StandardPackage` |
| ------------------------ | ----------------------------------------------- | :--------------: | :------------------: | | ------------------------ | ----------------------------------------------- | :--------------: | :------------------: |
| `BasicArithmeticPackage` | Arithmetic operators (e.g. `+`, `-`, `*`, `/`) | Yes | Yes | | `ArithmeticPackage` | Arithmetic operators (e.g. `+`, `-`, `*`, `/`) | Yes | Yes |
| `BasicIteratorPackage` | Numeric ranges (e.g. `range(1, 10)`) | Yes | Yes | | `BasicIteratorPackage` | Numeric ranges (e.g. `range(1, 10)`) | Yes | Yes |
| `LogicPackage` | Logic and comparison operators (e.g. `==`, `>`) | Yes | Yes | | `LogicPackage` | Logic and comparison operators (e.g. `==`, `>`) | Yes | Yes |
| `BasicStringPackage` | Basic string functions | Yes | Yes | | `BasicStringPackage` | Basic string functions | Yes | Yes |
@ -1979,17 +1979,20 @@ engine.on_print(|x| println!("hello: {}", x));
engine.on_debug(|x| println!("DEBUG: {}", x)); engine.on_debug(|x| println!("DEBUG: {}", x));
// Example: quick-'n-dirty logging // Example: quick-'n-dirty logging
let mut log: Vec<String> = Vec::new(); let logbook = Arc::new(RwLock::new(Vec::<String>::new()));
// Redirect print/debug output to 'log' // Redirect print/debug output to 'log'
engine.on_print(|s| log.push(format!("entry: {}", s))); let log = logbook.clone();
engine.on_debug(|s| log.push(format!("DEBUG: {}", s))); engine.on_print(move |s| log.write().unwrap().push(format!("entry: {}", s)));
let log = logbook.clone();
engine.on_debug(move |s| log.write().unwrap().push(format!("DEBUG: {}", s)));
// Evaluate script // Evaluate script
engine.eval::<()>(script)?; engine.eval::<()>(script)?;
// 'log' captures all the 'print' and 'debug' output // 'logbook' captures all the 'print' and 'debug' output
for entry in log { for entry in logbook.read().unwrap().iter() {
println!("{}", entry); println!("{}", entry);
} }
``` ```

View File

@ -252,6 +252,12 @@ impl Clone for Dynamic {
} }
} }
impl Default for Dynamic {
fn default() -> Self {
Self(Union::Unit(()))
}
}
/// Cast a Boxed type into another type. /// Cast a Boxed type into another type.
fn cast_box<X: Variant, T: Variant>(item: Box<X>) -> Result<T, Box<X>> { fn cast_box<X: Variant, T: Variant>(item: Box<X>) -> Result<T, Box<X>> {
// Only allow casting to the exact same type // Only allow casting to the exact same type
@ -359,22 +365,16 @@ impl Dynamic {
return cast_box::<_, T>(Box::new(self)).ok(); return cast_box::<_, T>(Box::new(self)).ok();
} }
match &self.0 { match self.0 {
Union::Unit(value) => (value as &dyn Variant).downcast_ref::<T>().cloned(), Union::Unit(ref value) => (value as &dyn Variant).downcast_ref::<T>().cloned(),
Union::Bool(value) => (value as &dyn Variant).downcast_ref::<T>().cloned(), Union::Bool(ref value) => (value as &dyn Variant).downcast_ref::<T>().cloned(),
Union::Str(value) => (value.as_ref() as &dyn Variant) Union::Str(value) => cast_box::<_, T>(value).ok(),
.downcast_ref::<T>() Union::Char(ref value) => (value as &dyn Variant).downcast_ref::<T>().cloned(),
.cloned(), Union::Int(ref value) => (value as &dyn Variant).downcast_ref::<T>().cloned(),
Union::Char(value) => (value as &dyn Variant).downcast_ref::<T>().cloned(),
Union::Int(value) => (value as &dyn Variant).downcast_ref::<T>().cloned(),
#[cfg(not(feature = "no_float"))] #[cfg(not(feature = "no_float"))]
Union::Float(value) => (value as &dyn Variant).downcast_ref::<T>().cloned(), Union::Float(ref value) => (value as &dyn Variant).downcast_ref::<T>().cloned(),
Union::Array(value) => (value.as_ref() as &dyn Variant) Union::Array(value) => cast_box::<_, T>(value).ok(),
.downcast_ref::<T>() Union::Map(value) => cast_box::<_, T>(value).ok(),
.cloned(),
Union::Map(value) => (value.as_ref() as &dyn Variant)
.downcast_ref::<T>()
.cloned(),
Union::Variant(value) => value.as_ref().as_ref().downcast_ref::<T>().cloned(), Union::Variant(value) => value.as_ref().as_ref().downcast_ref::<T>().cloned(),
} }
} }

View File

@ -88,7 +88,7 @@ enum Target<'a> {
impl Target<'_> { impl Target<'_> {
/// Get the value of the `Target` as a `Dynamic`. /// Get the value of the `Target` as a `Dynamic`.
pub fn into_dynamic(self) -> Dynamic { pub fn clone_into_dynamic(self) -> Dynamic {
match self { match self {
Target::Ref(r) => r.clone(), Target::Ref(r) => r.clone(),
Target::Value(v) => *v, Target::Value(v) => *v,
@ -111,7 +111,7 @@ impl Target<'_> {
.map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?; .map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?;
let mut chars: Vec<char> = s.chars().collect(); let mut chars: Vec<char> = s.chars().collect();
let ch = *chars.get(x.1).expect("string index out of bounds"); let ch = chars[x.1];
// See if changed - if so, update the String // See if changed - if so, update the String
if ch != new_ch { if ch != new_ch {
@ -141,26 +141,31 @@ impl<T: Into<Dynamic>> From<T> for Target<'_> {
/// A type to hold a number of `Dynamic` values in static storage for speed, /// A type to hold a number of `Dynamic` values in static storage for speed,
/// and any spill-overs in a `Vec`. /// and any spill-overs in a `Vec`.
struct StaticVec { struct StaticVec<T: Default> {
/// Total number of values held. /// Total number of values held.
len: usize, len: usize,
/// Static storage. /// Static storage. 4 slots should be enough for most cases - i.e. four levels of indirection.
list: [Dynamic; 4], list: [T; 4],
/// Dynamic storage. /// Dynamic storage. For spill-overs.
more: Vec<Dynamic>, more: Vec<T>,
} }
impl StaticVec { impl<T: Default> StaticVec<T> {
/// Create a new `StaticVec`. /// Create a new `StaticVec`.
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
len: 0, len: 0,
list: [().into(), ().into(), ().into(), ().into()], list: [
Default::default(),
Default::default(),
Default::default(),
Default::default(),
],
more: Vec::new(), more: Vec::new(),
} }
} }
/// Push a new value to the end of this `StaticVec`. /// Push a new value to the end of this `StaticVec`.
pub fn push<T: Into<Dynamic>>(&mut self, value: T) { pub fn push<X: Into<T>>(&mut self, value: X) {
if self.len >= self.list.len() { if self.len >= self.list.len() {
self.more.push(value.into()); self.more.push(value.into());
} else { } else {
@ -173,11 +178,11 @@ impl StaticVec {
/// # Panics /// # Panics
/// ///
/// Panics if the `StaticVec` is empty. /// Panics if the `StaticVec` is empty.
pub fn pop(&mut self) -> Dynamic { pub fn pop(&mut self) -> T {
let result = if self.len <= 0 { let result = if self.len <= 0 {
panic!("nothing to pop!") panic!("nothing to pop!")
} else if self.len <= self.list.len() { } else if self.len <= self.list.len() {
mem::replace(self.list.get_mut(self.len - 1).unwrap(), ().into()) mem::replace(self.list.get_mut(self.len - 1).unwrap(), Default::default())
} else { } else {
self.more.pop().unwrap() self.more.pop().unwrap()
}; };
@ -572,24 +577,24 @@ impl Engine {
}); });
} }
// Getter function not found?
if let Some(prop) = extract_prop_from_getter(fn_name) { if let Some(prop) = extract_prop_from_getter(fn_name) {
// Getter function not found
return Err(Box::new(EvalAltResult::ErrorDotExpr( return Err(Box::new(EvalAltResult::ErrorDotExpr(
format!("- property '{}' unknown or write-only", prop), format!("- property '{}' unknown or write-only", prop),
pos, pos,
))); )));
} }
// Setter function not found?
if let Some(prop) = extract_prop_from_setter(fn_name) { if let Some(prop) = extract_prop_from_setter(fn_name) {
// Setter function not found
return Err(Box::new(EvalAltResult::ErrorDotExpr( return Err(Box::new(EvalAltResult::ErrorDotExpr(
format!("- property '{}' unknown or read-only", prop), format!("- property '{}' unknown or read-only", prop),
pos, pos,
))); )));
} }
// Return default value (if any)
if let Some(val) = def_val { if let Some(val) = def_val {
// Return default value
return Ok(val.clone()); return Ok(val.clone());
} }
@ -621,8 +626,8 @@ impl Engine {
let scope_len = scope.len(); let scope_len = scope.len();
let mut state = State::new(); let mut state = State::new();
scope.extend(
// Put arguments into scope as variables - variable name is copied // Put arguments into scope as variables - variable name is copied
scope.extend(
// TODO - avoid copying variable name // TODO - avoid copying variable name
fn_def fn_def
.params .params
@ -649,8 +654,8 @@ impl Engine {
let mut scope = Scope::new(); let mut scope = Scope::new();
let mut state = State::new(); let mut state = State::new();
scope.extend(
// Put arguments into scope as variables // Put arguments into scope as variables
scope.extend(
fn_def fn_def
.params .params
.iter() .iter()
@ -698,7 +703,7 @@ impl Engine {
Ok(self.map_type_name(args[0].type_name()).to_string().into()) Ok(self.map_type_name(args[0].type_name()).to_string().into())
} }
// eval // eval - reaching this point it must be a method-style call
KEYWORD_EVAL if args.len() == 1 && !self.has_override(fn_lib, KEYWORD_EVAL) => { KEYWORD_EVAL if args.len() == 1 && !self.has_override(fn_lib, KEYWORD_EVAL) => {
Err(Box::new(EvalAltResult::ErrorRuntime( Err(Box::new(EvalAltResult::ErrorRuntime(
"'eval' should not be called in method style. Try eval(...);".into(), "'eval' should not be called in method style. Try eval(...);".into(),
@ -706,6 +711,7 @@ impl Engine {
))) )))
} }
// Normal method call
_ => self.call_fn_raw(None, fn_lib, fn_name, args, def_val, pos, level), _ => self.call_fn_raw(None, fn_lib, fn_name, args, def_val, pos, level),
} }
} }
@ -757,7 +763,7 @@ impl Engine {
fn_lib: &FunctionsLib, fn_lib: &FunctionsLib,
mut target: Target, mut target: Target,
rhs: &Expr, rhs: &Expr,
idx_values: &mut StaticVec, idx_values: &mut StaticVec<Dynamic>,
is_index: bool, is_index: bool,
op_pos: Position, op_pos: Position,
level: usize, level: usize,
@ -790,17 +796,17 @@ impl Engine {
_ if new_val.is_some() => { _ if new_val.is_some() => {
let mut indexed_val = self.get_indexed_mut(obj, idx_val, rhs.position(), op_pos, true)?; let mut indexed_val = self.get_indexed_mut(obj, idx_val, rhs.position(), op_pos, true)?;
indexed_val.set_value(new_val.unwrap(), rhs.position())?; indexed_val.set_value(new_val.unwrap(), rhs.position())?;
Ok((().into(), true)) Ok((Default::default(), true))
} }
// xxx[rhs] // xxx[rhs]
_ => self _ => self
.get_indexed_mut(obj, idx_val, rhs.position(), op_pos, false) .get_indexed_mut(obj, idx_val, rhs.position(), op_pos, false)
.map(|v| (v.into_dynamic(), false)) .map(|v| (v.clone_into_dynamic(), false))
} }
} else { } else {
match rhs { match rhs {
// xxx.fn_name(arg_expr_list) // xxx.fn_name(arg_expr_list)
Expr::FunctionCall(fn_name, _, def_val, pos) => { Expr::FnCall(fn_name, _, def_val, pos) => {
let mut args: Vec<_> = once(obj) let mut args: Vec<_> = once(obj)
.chain(idx_val.downcast_mut::<Array>().unwrap().iter_mut()) .chain(idx_val.downcast_mut::<Array>().unwrap().iter_mut())
.collect(); .collect();
@ -814,13 +820,13 @@ impl Engine {
let mut indexed_val = let mut indexed_val =
self.get_indexed_mut(obj, id.to_string().into(), *pos, op_pos, true)?; self.get_indexed_mut(obj, id.to_string().into(), *pos, op_pos, true)?;
indexed_val.set_value(new_val.unwrap(), rhs.position())?; indexed_val.set_value(new_val.unwrap(), rhs.position())?;
Ok((().into(), true)) Ok((Default::default(), true))
} }
// {xxx:map}.id // {xxx:map}.id
Expr::Property(id, pos) if obj.is::<Map>() => { Expr::Property(id, pos) if obj.is::<Map>() => {
let indexed_val = let indexed_val =
self.get_indexed_mut(obj, id.to_string().into(), *pos, op_pos, false)?; self.get_indexed_mut(obj, id.to_string().into(), *pos, op_pos, false)?;
Ok((indexed_val.into_dynamic(), false)) Ok((indexed_val.clone_into_dynamic(), false))
} }
// xxx.id = ??? // xxx.id = ???
Expr::Property(id, pos) if new_val.is_some() => { Expr::Property(id, pos) if new_val.is_some() => {
@ -858,8 +864,7 @@ impl Engine {
// xxx.dot_lhs.rhs // xxx.dot_lhs.rhs
Expr::Dot(dot_lhs, dot_rhs, pos) => { Expr::Dot(dot_lhs, dot_rhs, pos) => {
let is_index = matches!(rhs, Expr::Index(_,_,_)); let is_index = matches!(rhs, Expr::Index(_,_,_));
let mut buf: Dynamic = ().into(); let mut args = [obj, &mut Default::default()];
let mut args = [obj, &mut buf];
let indexed_val = &mut (if let Expr::Property(id, pos) = dot_lhs.as_ref() { let indexed_val = &mut (if let Expr::Property(id, pos) = dot_lhs.as_ref() {
let fn_name = make_getter(id); let fn_name = make_getter(id);
@ -871,12 +876,12 @@ impl Engine {
rhs.position(), rhs.position(),
))); )));
}); });
let (result, changed) = self.eval_dot_index_chain_helper( let (result, may_be_changed) = self.eval_dot_index_chain_helper(
fn_lib, indexed_val.into(), dot_rhs, idx_values, is_index, *pos, level, new_val fn_lib, indexed_val.into(), dot_rhs, idx_values, is_index, *pos, level, new_val
)?; )?;
// Feed the value back via a setter just in case it has been updated // Feed the value back via a setter just in case it has been updated
if changed { if may_be_changed {
if let Expr::Property(id, pos) = dot_lhs.as_ref() { if let Expr::Property(id, pos) = dot_lhs.as_ref() {
let fn_name = make_setter(id); let fn_name = make_setter(id);
args[1] = indexed_val; args[1] = indexed_val;
@ -884,7 +889,7 @@ impl Engine {
} }
} }
Ok((result, changed)) Ok((result, may_be_changed))
} }
// Syntax error // Syntax error
_ => Err(Box::new(EvalAltResult::ErrorDotExpr( _ => Err(Box::new(EvalAltResult::ErrorDotExpr(
@ -931,15 +936,9 @@ impl Engine {
_ => (), _ => (),
} }
let this_ptr = target.into();
self.eval_dot_index_chain_helper( self.eval_dot_index_chain_helper(
fn_lib, fn_lib, this_ptr, dot_rhs, idx_values, is_index, op_pos, level, new_val,
target.into(),
dot_rhs,
idx_values,
is_index,
op_pos,
level,
new_val,
) )
.map(|(v, _)| v) .map(|(v, _)| v)
} }
@ -952,16 +951,9 @@ impl Engine {
// {expr}.??? or {expr}[???] // {expr}.??? or {expr}[???]
expr => { expr => {
let val = self.eval_expr(scope, state, fn_lib, expr, level)?; let val = self.eval_expr(scope, state, fn_lib, expr, level)?;
let this_ptr = val.into();
self.eval_dot_index_chain_helper( self.eval_dot_index_chain_helper(
fn_lib, fn_lib, this_ptr, dot_rhs, idx_values, is_index, op_pos, level, new_val,
val.into(),
dot_rhs,
idx_values,
is_index,
op_pos,
level,
new_val,
) )
.map(|(v, _)| v) .map(|(v, _)| v)
} }
@ -979,12 +971,12 @@ impl Engine {
state: &mut State, state: &mut State,
fn_lib: &FunctionsLib, fn_lib: &FunctionsLib,
expr: &Expr, expr: &Expr,
idx_values: &mut StaticVec, idx_values: &mut StaticVec<Dynamic>,
size: usize, size: usize,
level: usize, level: usize,
) -> Result<(), Box<EvalAltResult>> { ) -> Result<(), Box<EvalAltResult>> {
match expr { match expr {
Expr::FunctionCall(_, arg_exprs, _, _) => { Expr::FnCall(_, arg_exprs, _, _) => {
let arg_values = arg_exprs let arg_values = arg_exprs
.iter() .iter()
.map(|arg_expr| self.eval_expr(scope, state, fn_lib, arg_expr, level)) .map(|arg_expr| self.eval_expr(scope, state, fn_lib, arg_expr, level))
@ -992,12 +984,11 @@ impl Engine {
idx_values.push(arg_values) idx_values.push(arg_values)
} }
// Store a placeholder - no need to copy the property name Expr::Property(_, _) => idx_values.push(()), // Store a placeholder - no need to copy the property name
Expr::Property(_, _) => idx_values.push(()),
Expr::Index(lhs, rhs, _) | Expr::Dot(lhs, rhs, _) => { Expr::Index(lhs, rhs, _) | Expr::Dot(lhs, rhs, _) => {
// Evaluate in left-to-right order // Evaluate in left-to-right order
let lhs_val = match lhs.as_ref() { let lhs_val = match lhs.as_ref() {
Expr::Property(_, _) => ().into(), // Store a placeholder in case of a property Expr::Property(_, _) => Default::default(), // Store a placeholder in case of a property
_ => self.eval_expr(scope, state, fn_lib, lhs, level)?, _ => self.eval_expr(scope, state, fn_lib, lhs, level)?,
}; };
@ -1052,7 +1043,7 @@ impl Engine {
.map_err(|_| EvalAltResult::ErrorStringIndexExpr(idx_pos))?; .map_err(|_| EvalAltResult::ErrorStringIndexExpr(idx_pos))?;
Ok(if create { Ok(if create {
map.entry(index).or_insert(().into()).into() map.entry(index).or_insert(Default::default()).into()
} else { } else {
map.get_mut(&index) map.get_mut(&index)
.map(Target::from) .map(Target::from)
@ -1066,15 +1057,25 @@ impl Engine {
.as_int() .as_int()
.map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_pos))?; .map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_pos))?;
let num_chars = s.chars().count();
if index >= 0 { if index >= 0 {
let index = index as usize; let ch = s.chars().nth(index as usize).ok_or_else(|| {
let ch = s.chars().nth(index).unwrap(); Box::new(EvalAltResult::ErrorStringBounds(
Ok(Target::StringChar(Box::new((val, index, ch.into())))) s.chars().count(),
index,
idx_pos,
))
})?;
Ok(Target::StringChar(Box::new((
val,
index as usize,
ch.into(),
))))
} else { } else {
Err(Box::new(EvalAltResult::ErrorStringBounds( Err(Box::new(EvalAltResult::ErrorStringBounds(
num_chars, index, idx_pos, s.chars().count(),
index,
idx_pos,
))) )))
} }
} }
@ -1103,40 +1104,35 @@ impl Engine {
match rhs_value { match rhs_value {
Dynamic(Union::Array(mut rhs_value)) => { Dynamic(Union::Array(mut rhs_value)) => {
let def_value = false.into(); let def_value = false.into();
let mut result = false;
// Call the '==' operator to compare each value // Call the '==' operator to compare each value
for value in rhs_value.iter_mut() { for value in rhs_value.iter_mut() {
let args = &mut [&mut lhs_value, value]; let args = &mut [&mut lhs_value, value];
let def_value = Some(&def_value); let def_value = Some(&def_value);
if self if self
.call_fn_raw(None, fn_lib, "==", args, def_value, rhs.position(), level)? .call_fn_raw(None, fn_lib, "==", args, def_value, rhs.position(), level)?
.as_bool() .as_bool()
.unwrap_or(false) .unwrap_or(false)
{ {
result = true; return Ok(true.into());
break;
} }
} }
Ok(result.into()) Ok(false.into())
} }
Dynamic(Union::Map(rhs_value)) => { Dynamic(Union::Map(rhs_value)) => match lhs_value {
// Only allows String or char // Only allows String or char
match lhs_value {
Dynamic(Union::Str(s)) => Ok(rhs_value.contains_key(s.as_ref()).into()), Dynamic(Union::Str(s)) => Ok(rhs_value.contains_key(s.as_ref()).into()),
Dynamic(Union::Char(c)) => Ok(rhs_value.contains_key(&c.to_string()).into()), Dynamic(Union::Char(c)) => Ok(rhs_value.contains_key(&c.to_string()).into()),
_ => Err(Box::new(EvalAltResult::ErrorInExpr(lhs.position()))), _ => Err(Box::new(EvalAltResult::ErrorInExpr(lhs.position()))),
} },
} Dynamic(Union::Str(rhs_value)) => match lhs_value {
Dynamic(Union::Str(rhs_value)) => {
// Only allows String or char // Only allows String or char
match lhs_value {
Dynamic(Union::Str(s)) => Ok(rhs_value.contains(s.as_ref()).into()), Dynamic(Union::Str(s)) => Ok(rhs_value.contains(s.as_ref()).into()),
Dynamic(Union::Char(c)) => Ok(rhs_value.contains(c).into()), Dynamic(Union::Char(c)) => Ok(rhs_value.contains(c).into()),
_ => Err(Box::new(EvalAltResult::ErrorInExpr(lhs.position()))), _ => Err(Box::new(EvalAltResult::ErrorInExpr(lhs.position()))),
} },
}
_ => Err(Box::new(EvalAltResult::ErrorInExpr(rhs.position()))), _ => Err(Box::new(EvalAltResult::ErrorInExpr(rhs.position()))),
} }
} }
@ -1178,18 +1174,14 @@ impl Engine {
*pos, *pos,
))) )))
} }
Some((index, ScopeEntryType::Normal)) => {
// Avoid referencing scope which is used below as mut
*scope.get_mut(index).0 = rhs_val.clone();
Ok(rhs_val)
}
Some((_, ScopeEntryType::Constant)) => Err(Box::new( Some((_, ScopeEntryType::Constant)) => Err(Box::new(
EvalAltResult::ErrorAssignmentToConstant(name.to_string(), *op_pos), EvalAltResult::ErrorAssignmentToConstant(name.to_string(), *op_pos),
)), )),
Some((index, ScopeEntryType::Normal)) => {
*scope.get_mut(index).0 = rhs_val;
Ok(Default::default())
}
}, },
// idx_lhs[idx_expr] = rhs // idx_lhs[idx_expr] = rhs
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Expr::Index(idx_lhs, idx_expr, op_pos) => { Expr::Index(idx_lhs, idx_expr, op_pos) => {
@ -1213,7 +1205,6 @@ impl Engine {
lhs.position(), lhs.position(),
))) )))
} }
// Syntax error // Syntax error
_ => Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS( _ => Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(
lhs.position(), lhs.position(),
@ -1234,32 +1225,25 @@ impl Engine {
), ),
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
Expr::Array(contents, _) => { Expr::Array(contents, _) => Ok(Dynamic(Union::Array(Box::new(
let mut arr = Array::new(); contents
.into_iter()
contents.into_iter().try_for_each(|item| { .map(|item| self.eval_expr(scope, state, fn_lib, item, level))
self.eval_expr(scope, state, fn_lib, item, level) .collect::<Result<Vec<_>, _>>()?,
.map(|val| arr.push(val)) )))),
})?;
Ok(Dynamic(Union::Array(Box::new(arr))))
}
#[cfg(not(feature = "no_object"))] #[cfg(not(feature = "no_object"))]
Expr::Map(contents, _) => { Expr::Map(contents, _) => Ok(Dynamic(Union::Map(Box::new(
let mut map = Map::new(); contents
.into_iter()
contents.into_iter().try_for_each(|(key, expr, _)| { .map(|(key, expr, _)| {
self.eval_expr(scope, state, fn_lib, &expr, level) self.eval_expr(scope, state, fn_lib, &expr, level)
.map(|val| { .map(|val| (key.clone(), val))
map.insert(key.clone(), val);
}) })
})?; .collect::<Result<HashMap<_, _>, _>>()?,
)))),
Ok(Dynamic(Union::Map(Box::new(map)))) Expr::FnCall(fn_name, arg_exprs, def_val, pos) => {
}
Expr::FunctionCall(fn_name, arg_exprs, def_val, pos) => {
let mut arg_values = arg_exprs let mut arg_values = arg_exprs
.iter() .iter()
.map(|expr| self.eval_expr(scope, state, fn_lib, expr, level)) .map(|expr| self.eval_expr(scope, state, fn_lib, expr, level))
@ -1268,7 +1252,7 @@ impl Engine {
let mut args: Vec<_> = arg_values.iter_mut().collect(); let mut args: Vec<_> = arg_values.iter_mut().collect();
// eval - only in function call style // eval - only in function call style
if fn_name == KEYWORD_EVAL if fn_name.as_ref() == KEYWORD_EVAL
&& args.len() == 1 && args.len() == 1
&& !self.has_override(fn_lib, KEYWORD_EVAL) && !self.has_override(fn_lib, KEYWORD_EVAL)
{ {
@ -1287,9 +1271,8 @@ impl Engine {
return result; return result;
} }
// Normal function call // Normal function call - except for eval (handled above)
let def_val = def_val.as_deref(); self.exec_fn_call(fn_lib, fn_name, &mut args, def_val.as_deref(), *pos, level)
self.exec_fn_call(fn_lib, fn_name, &mut args, def_val, *pos, level)
} }
Expr::In(lhs, rhs, _) => { Expr::In(lhs, rhs, _) => {
@ -1345,7 +1328,7 @@ impl Engine {
) -> Result<Dynamic, Box<EvalAltResult>> { ) -> Result<Dynamic, Box<EvalAltResult>> {
match stmt { match stmt {
// No-op // No-op
Stmt::Noop(_) => Ok(().into()), Stmt::Noop(_) => Ok(Default::default()),
// Expression as statement // Expression as statement
Stmt::Expr(expr) => { Stmt::Expr(expr) => {
@ -1353,7 +1336,7 @@ impl Engine {
Ok(if let Expr::Assignment(_, _, _) = *expr.as_ref() { Ok(if let Expr::Assignment(_, _, _) = *expr.as_ref() {
// If it is an assignment, erase the result at the root // If it is an assignment, erase the result at the root
().into() Default::default()
} else { } else {
result result
}) })
@ -1363,7 +1346,7 @@ impl Engine {
Stmt::Block(block, _) => { Stmt::Block(block, _) => {
let prev_len = scope.len(); let prev_len = scope.len();
let result = block.iter().try_fold(().into(), |_, stmt| { let result = block.iter().try_fold(Default::default(), |_, stmt| {
self.eval_stmt(scope, state, fn_lib, stmt, level) self.eval_stmt(scope, state, fn_lib, stmt, level)
}); });
@ -1387,7 +1370,7 @@ impl Engine {
} else if let Some(stmt) = else_body { } else if let Some(stmt) = else_body {
self.eval_stmt(scope, state, fn_lib, stmt.as_ref(), level) self.eval_stmt(scope, state, fn_lib, stmt.as_ref(), level)
} else { } else {
Ok(().into()) Ok(Default::default())
} }
}), }),
@ -1401,11 +1384,11 @@ impl Engine {
Ok(_) => (), Ok(_) => (),
Err(err) => match *err { Err(err) => match *err {
EvalAltResult::ErrorLoopBreak(false, _) => (), EvalAltResult::ErrorLoopBreak(false, _) => (),
EvalAltResult::ErrorLoopBreak(true, _) => return Ok(().into()), EvalAltResult::ErrorLoopBreak(true, _) => return Ok(Default::default()),
_ => return Err(err), _ => return Err(err),
}, },
}, },
Ok(false) => return Ok(().into()), Ok(false) => return Ok(Default::default()),
Err(_) => { Err(_) => {
return Err(Box::new(EvalAltResult::ErrorLogicGuard(guard.position()))) return Err(Box::new(EvalAltResult::ErrorLogicGuard(guard.position())))
} }
@ -1418,7 +1401,7 @@ impl Engine {
Ok(_) => (), Ok(_) => (),
Err(err) => match *err { Err(err) => match *err {
EvalAltResult::ErrorLoopBreak(false, _) => (), EvalAltResult::ErrorLoopBreak(false, _) => (),
EvalAltResult::ErrorLoopBreak(true, _) => return Ok(().into()), EvalAltResult::ErrorLoopBreak(true, _) => return Ok(Default::default()),
_ => return Err(err), _ => return Err(err),
}, },
} }
@ -1436,7 +1419,8 @@ impl Engine {
.and_then(|pkg| pkg.type_iterators.get(&tid)) .and_then(|pkg| pkg.type_iterators.get(&tid))
}) { }) {
// Add the loop variable // Add the loop variable
scope.push(name.clone(), ()); let var_name = name.as_ref().clone();
scope.push(var_name, ());
let index = scope.len() - 1; let index = scope.len() - 1;
for a in iter_fn(arr) { for a in iter_fn(arr) {
@ -1453,7 +1437,7 @@ impl Engine {
} }
scope.rewind(scope.len() - 1); scope.rewind(scope.len() - 1);
Ok(().into()) Ok(Default::default())
} else { } else {
Err(Box::new(EvalAltResult::ErrorFor(expr.position()))) Err(Box::new(EvalAltResult::ErrorFor(expr.position())))
} }
@ -1467,7 +1451,7 @@ impl Engine {
// Empty return // Empty return
Stmt::ReturnWithVal(None, ReturnType::Return, pos) => { Stmt::ReturnWithVal(None, ReturnType::Return, pos) => {
Err(Box::new(EvalAltResult::Return(().into(), *pos))) Err(Box::new(EvalAltResult::Return(Default::default(), *pos)))
} }
// Return value // Return value
@ -1493,22 +1477,25 @@ impl Engine {
Stmt::Let(name, Some(expr), _) => { Stmt::Let(name, Some(expr), _) => {
let val = self.eval_expr(scope, state, fn_lib, expr, level)?; let val = self.eval_expr(scope, state, fn_lib, expr, level)?;
// TODO - avoid copying variable name in inner block? // TODO - avoid copying variable name in inner block?
scope.push_dynamic_value(name.clone(), ScopeEntryType::Normal, val, false); let var_name = name.as_ref().clone();
Ok(().into()) scope.push_dynamic_value(var_name, ScopeEntryType::Normal, val, false);
Ok(Default::default())
} }
Stmt::Let(name, None, _) => { Stmt::Let(name, None, _) => {
// TODO - avoid copying variable name in inner block? // TODO - avoid copying variable name in inner block?
scope.push(name.clone(), ()); let var_name = name.as_ref().clone();
Ok(().into()) scope.push(var_name, ());
Ok(Default::default())
} }
// Const statement // Const statement
Stmt::Const(name, expr, _) if expr.is_constant() => { Stmt::Const(name, expr, _) if expr.is_constant() => {
let val = self.eval_expr(scope, state, fn_lib, expr, level)?; let val = self.eval_expr(scope, state, fn_lib, expr, level)?;
// TODO - avoid copying variable name in inner block? // TODO - avoid copying variable name in inner block?
scope.push_dynamic_value(name.clone(), ScopeEntryType::Constant, val, true); let var_name = name.as_ref().clone();
Ok(().into()) scope.push_dynamic_value(var_name, ScopeEntryType::Constant, val, true);
Ok(Default::default())
} }
Stmt::Const(_, _, _) => panic!("constant expression not constant!"), Stmt::Const(_, _, _) => panic!("constant expression not constant!"),

View File

@ -435,9 +435,7 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr {
.unwrap_or_else(|| Expr::Unit(pos)) .unwrap_or_else(|| Expr::Unit(pos))
} }
// string[int] // string[int]
(Expr::StringConstant(s, pos), Expr::IntegerConstant(i, _)) (Expr::StringConstant(s, pos), Expr::IntegerConstant(i, _)) if i >= 0 && (i as usize) < s.chars().count() => {
if i >= 0 && (i as usize) < s.chars().count() =>
{
// String literal indexing - get the character // String literal indexing - get the character
state.set_dirty(); state.set_dirty();
Expr::CharConstant(s.chars().nth(i as usize).expect("should get char"), pos) Expr::CharConstant(s.chars().nth(i as usize).expect("should get char"), pos)
@ -550,26 +548,22 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr {
optimize_expr(lhs, state) optimize_expr(lhs, state)
} }
// lhs || rhs // lhs || rhs
(lhs, rhs) => Expr::Or( (lhs, rhs) => Expr::Or(Box::new(optimize_expr(lhs, state)), Box::new(optimize_expr(rhs, state)), pos),
Box::new(optimize_expr(lhs, state)),
Box::new(optimize_expr(rhs, state)),
pos
),
}, },
// Do not call some special keywords // Do not call some special keywords
Expr::FunctionCall(id, args, def_value, pos) if DONT_EVAL_KEYWORDS.contains(&id.as_ref())=> Expr::FnCall(id, args, def_value, pos) if DONT_EVAL_KEYWORDS.contains(&id.as_ref().as_ref())=>
Expr::FunctionCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos), Expr::FnCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos),
// Eagerly call functions // Eagerly call functions
Expr::FunctionCall(id, args, def_value, pos) Expr::FnCall(id, args, def_value, pos)
if state.optimization_level == OptimizationLevel::Full // full optimizations if state.optimization_level == OptimizationLevel::Full // full optimizations
&& args.iter().all(|expr| expr.is_constant()) // all arguments are constants && args.iter().all(|expr| expr.is_constant()) // all arguments are constants
=> { => {
// First search in script-defined functions (can override built-in) // First search in script-defined functions (can override built-in)
if state.fn_lib.iter().find(|(name, len)| name == &id && *len == args.len()).is_some() { if state.fn_lib.iter().find(|(name, len)| name == id.as_ref() && *len == args.len()).is_some() {
// A script-defined function overrides the built-in function - do not make the call // A script-defined function overrides the built-in function - do not make the call
return Expr::FunctionCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos); return Expr::FnCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos);
} }
let mut arg_values: Vec<_> = args.iter().map(Expr::get_constant_value).collect(); let mut arg_values: Vec<_> = args.iter().map(Expr::get_constant_value).collect();
@ -577,7 +571,7 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr {
// Save the typename of the first argument if it is `type_of()` // Save the typename of the first argument if it is `type_of()`
// This is to avoid `call_args` being passed into the closure // This is to avoid `call_args` being passed into the closure
let arg_for_type_of = if id == KEYWORD_TYPE_OF && call_args.len() == 1 { let arg_for_type_of = if *id == KEYWORD_TYPE_OF && call_args.len() == 1 {
state.engine.map_type_name(call_args[0].type_name()) state.engine.map_type_name(call_args[0].type_name())
} else { } else {
"" ""
@ -600,13 +594,13 @@ fn optimize_expr<'a>(expr: Expr, state: &mut State<'a>) -> Expr {
}) })
).unwrap_or_else(|| ).unwrap_or_else(||
// Optimize function call arguments // Optimize function call arguments
Expr::FunctionCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos) Expr::FnCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos)
) )
} }
// id(args ..) -> optimize function call arguments // id(args ..) -> optimize function call arguments
Expr::FunctionCall(id, args, def_value, pos) => Expr::FnCall(id, args, def_value, pos) =>
Expr::FunctionCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos), Expr::FnCall(id, Box::new(args.into_iter().map(|a| optimize_expr(a, state)).collect()), def_value, pos),
// constant-name // constant-name
Expr::Variable(name, _, pos) if state.contains_constant(&name) => { Expr::Variable(name, _, pos) if state.contains_constant(&name) => {

View File

@ -1,8 +1,7 @@
use super::{reg_binary, reg_trinary, reg_unary_mut, PackageStore}; use super::{reg_binary, reg_trinary, PackageStore};
use crate::any::{Dynamic, Union, Variant}; use crate::any::{Dynamic, Variant};
use crate::def_package; use crate::def_package;
use crate::engine::{Array, Map};
use crate::fn_register::map_dynamic as map; use crate::fn_register::map_dynamic as map;
use crate::parser::INT; use crate::parser::INT;

View File

@ -239,44 +239,6 @@ pub fn reg_unary_mut<T: Variant + Clone, R>(
lib.functions.insert(hash, f); lib.functions.insert(hash, f);
} }
#[cfg(not(feature = "sync"))]
pub(crate) fn reg_test<'a, A: Variant + Clone, B: Variant + Clone, X, R>(
lib: &mut PackageStore,
fn_name: &'static str,
#[cfg(not(feature = "sync"))] func: impl Fn(X, B) -> R + 'static,
#[cfg(feature = "sync")] func: impl Fn(X, B) -> R + Send + Sync + 'static,
map: impl Fn(&mut A) -> X + 'static,
#[cfg(not(feature = "sync"))] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
+ 'static,
#[cfg(feature = "sync")] map_result: impl Fn(R, Position) -> Result<Dynamic, Box<EvalAltResult>>
+ Send
+ Sync
+ 'static,
) {
//println!("register {}({}, {})", fn_name, crate::std::any::type_name::<A>(), crate::std::any::type_name::<B>());
let hash = calc_fn_hash(
fn_name,
[TypeId::of::<A>(), TypeId::of::<B>()].iter().cloned(),
);
let f = Box::new(move |args: &mut FnCallArgs, pos: Position| {
check_num_args(fn_name, 2, args, pos)?;
let mut drain = args.iter_mut();
let x: X = map(drain.next().unwrap().downcast_mut::<A>().unwrap());
let y: B = drain.next().unwrap().downcast_mut::<B>().unwrap().clone();
let r = func(x, y);
map_result(r, pos)
});
lib.functions.insert(hash, f);
}
/// Add a function with two parameters to the package. /// Add a function with two parameters to the package.
/// ///
/// `map_result` is a function that maps the return type of the function to `Result<Dynamic, EvalAltResult>`. /// `map_result` is a function that maps the return type of the function to `Result<Dynamic, EvalAltResult>`.

View File

@ -231,11 +231,11 @@ pub enum Stmt {
/// loop { stmt } /// loop { stmt }
Loop(Box<Stmt>), Loop(Box<Stmt>),
/// for id in expr { stmt } /// for id in expr { stmt }
For(String, Box<Expr>, Box<Stmt>), For(Box<String>, Box<Expr>, Box<Stmt>),
/// let id = expr /// let id = expr
Let(String, Option<Box<Expr>>, Position), Let(Box<String>, Option<Box<Expr>>, Position),
/// const id = expr /// const id = expr
Const(String, Box<Expr>, Position), Const(Box<String>, Box<Expr>, Position),
/// { stmt; ... } /// { stmt; ... }
Block(Vec<Stmt>, Position), Block(Vec<Stmt>, Position),
/// { stmt } /// { stmt }
@ -317,7 +317,7 @@ pub enum Expr {
/// String constant. /// String constant.
StringConstant(String, Position), StringConstant(String, Position),
/// Variable access. /// Variable access.
Variable(String, Option<NonZeroUsize>, Position), Variable(Box<String>, Option<NonZeroUsize>, Position),
/// Property access. /// Property access.
Property(String, Position), Property(String, Position),
/// { stmt } /// { stmt }
@ -325,8 +325,8 @@ pub enum Expr {
/// func(expr, ... ) /// func(expr, ... )
/// Use `Cow<'static, str>` because a lot of operators (e.g. `==`, `>=`) are implemented as function calls /// Use `Cow<'static, str>` because a lot of operators (e.g. `==`, `>=`) are implemented as function calls
/// and the function names are predictable, so no need to allocate a new `String`. /// and the function names are predictable, so no need to allocate a new `String`.
FunctionCall( FnCall(
Cow<'static, str>, Box<Cow<'static, str>>,
Box<Vec<Expr>>, Box<Vec<Expr>>,
Option<Box<Dynamic>>, Option<Box<Dynamic>>,
Position, Position,
@ -427,7 +427,7 @@ impl Expr {
| Self::Variable(_, _, pos) | Self::Variable(_, _, pos)
| Self::Property(_, pos) | Self::Property(_, pos)
| Self::Stmt(_, pos) | Self::Stmt(_, pos)
| Self::FunctionCall(_, _, _, pos) | Self::FnCall(_, _, _, pos)
| Self::And(_, _, pos) | Self::And(_, _, pos)
| Self::Or(_, _, pos) | Self::Or(_, _, pos)
| Self::In(_, _, pos) | Self::In(_, _, pos)
@ -453,7 +453,7 @@ impl Expr {
| Self::Variable(_, _, pos) | Self::Variable(_, _, pos)
| Self::Property(_, pos) | Self::Property(_, pos)
| Self::Stmt(_, pos) | Self::Stmt(_, pos)
| Self::FunctionCall(_, _, _, pos) | Self::FnCall(_, _, _, pos)
| Self::And(_, _, pos) | Self::And(_, _, pos)
| Self::Or(_, _, pos) | Self::Or(_, _, pos)
| Self::In(_, _, pos) | Self::In(_, _, pos)
@ -530,7 +530,7 @@ impl Expr {
Self::StringConstant(_, _) Self::StringConstant(_, _)
| Self::Stmt(_, _) | Self::Stmt(_, _)
| Self::FunctionCall(_, _, _, _) | Self::FnCall(_, _, _, _)
| Self::Assignment(_, _, _) | Self::Assignment(_, _, _)
| Self::Dot(_, _, _) | Self::Dot(_, _, _)
| Self::Index(_, _, _) | Self::Index(_, _, _)
@ -550,7 +550,7 @@ impl Expr {
/// Convert a `Variable` into a `Property`. All other variants are untouched. /// Convert a `Variable` into a `Property`. All other variants are untouched.
pub(crate) fn into_property(self) -> Self { pub(crate) fn into_property(self) -> Self {
match self { match self {
Self::Variable(id, _, pos) => Self::Property(id, pos), Self::Variable(id, _, pos) => Self::Property(*id, pos),
_ => self, _ => self,
} }
} }
@ -633,7 +633,12 @@ fn parse_call_expr<'a>(
// id() // id()
(Token::RightParen, _) => { (Token::RightParen, _) => {
eat_token(input, Token::RightParen); eat_token(input, Token::RightParen);
return Ok(Expr::FunctionCall(id.into(), Box::new(args), None, begin)); return Ok(Expr::FnCall(
Box::new(id.into()),
Box::new(args),
None,
begin,
));
} }
// id... // id...
_ => (), _ => (),
@ -645,7 +650,12 @@ fn parse_call_expr<'a>(
match input.peek().unwrap() { match input.peek().unwrap() {
(Token::RightParen, _) => { (Token::RightParen, _) => {
eat_token(input, Token::RightParen); eat_token(input, Token::RightParen);
return Ok(Expr::FunctionCall(id.into(), Box::new(args), None, begin)); return Ok(Expr::FnCall(
Box::new(id.into()),
Box::new(args),
None,
begin,
));
} }
(Token::Comma, _) => { (Token::Comma, _) => {
eat_token(input, Token::Comma); eat_token(input, Token::Comma);
@ -968,7 +978,7 @@ fn parse_primary<'a>(
Token::StringConst(s) => Expr::StringConstant(s, pos), Token::StringConst(s) => Expr::StringConstant(s, pos),
Token::Identifier(s) => { Token::Identifier(s) => {
let index = stack.find(&s); let index = stack.find(&s);
Expr::Variable(s, index, pos) Expr::Variable(Box::new(s), index, pos)
} }
Token::LeftParen => parse_paren_expr(input, stack, pos, allow_stmt_expr)?, Token::LeftParen => parse_paren_expr(input, stack, pos, allow_stmt_expr)?,
#[cfg(not(feature = "no_index"))] #[cfg(not(feature = "no_index"))]
@ -995,8 +1005,10 @@ fn parse_primary<'a>(
root_expr = match (root_expr, token) { root_expr = match (root_expr, token) {
// Function call // Function call
(Expr::Variable(id, _, pos), Token::LeftParen) (Expr::Variable(id, _, pos), Token::LeftParen) => {
| (Expr::Property(id, pos), Token::LeftParen) => { parse_call_expr(input, stack, *id, pos, allow_stmt_expr)?
}
(Expr::Property(id, pos), Token::LeftParen) => {
parse_call_expr(input, stack, id, pos, allow_stmt_expr)? parse_call_expr(input, stack, id, pos, allow_stmt_expr)?
} }
// Indexing // Indexing
@ -1055,7 +1067,12 @@ fn parse_unary<'a>(
Expr::FloatConstant(f, pos) => Ok(Expr::FloatConstant(-f, pos)), Expr::FloatConstant(f, pos) => Ok(Expr::FloatConstant(-f, pos)),
// Call negative function // Call negative function
e => Ok(Expr::FunctionCall("-".into(), Box::new(vec![e]), None, pos)), e => Ok(Expr::FnCall(
Box::new("-".into()),
Box::new(vec![e]),
None,
pos,
)),
} }
} }
// +expr // +expr
@ -1066,8 +1083,8 @@ fn parse_unary<'a>(
// !expr // !expr
(Token::Bang, _) => { (Token::Bang, _) => {
let pos = eat_token(input, Token::Bang); let pos = eat_token(input, Token::Bang);
Ok(Expr::FunctionCall( Ok(Expr::FnCall(
"!".into(), Box::new("!".into()),
Box::new(vec![parse_primary(input, stack, allow_stmt_expr)?]), Box::new(vec![parse_primary(input, stack, allow_stmt_expr)?]),
Some(Box::new(false.into())), // NOT operator, when operating on invalid operand, defaults to false Some(Box::new(false.into())), // NOT operator, when operating on invalid operand, defaults to false
pos, pos,
@ -1120,7 +1137,8 @@ fn parse_op_assignment_stmt<'a>(
let rhs = parse_expr(input, stack, allow_stmt_expr)?; let rhs = parse_expr(input, stack, allow_stmt_expr)?;
// lhs op= rhs -> lhs = op(lhs, rhs) // lhs op= rhs -> lhs = op(lhs, rhs)
let rhs_expr = Expr::FunctionCall(op.into(), Box::new(vec![lhs_copy, rhs]), None, pos); let args = vec![lhs_copy, rhs];
let rhs_expr = Expr::FnCall(Box::new(op.into()), Box::new(args), None, pos);
Ok(Expr::Assignment(Box::new(lhs), Box::new(rhs_expr), pos)) Ok(Expr::Assignment(Box::new(lhs), Box::new(rhs_expr), pos))
} }
@ -1337,65 +1355,89 @@ fn parse_binary_op<'a>(
let cmp_default = Some(Box::new(false.into())); let cmp_default = Some(Box::new(false.into()));
current_lhs = match op_token { current_lhs = match op_token {
Token::Plus => { Token::Plus => Expr::FnCall(
Expr::FunctionCall("+".into(), Box::new(vec![current_lhs, rhs]), None, pos) Box::new("+".into()),
} Box::new(vec![current_lhs, rhs]),
Token::Minus => { None,
Expr::FunctionCall("-".into(), Box::new(vec![current_lhs, rhs]), None, pos) pos,
} ),
Token::Multiply => { Token::Minus => Expr::FnCall(
Expr::FunctionCall("*".into(), Box::new(vec![current_lhs, rhs]), None, pos) Box::new("-".into()),
} Box::new(vec![current_lhs, rhs]),
Token::Divide => { None,
Expr::FunctionCall("/".into(), Box::new(vec![current_lhs, rhs]), None, pos) pos,
} ),
Token::Multiply => Expr::FnCall(
Box::new("*".into()),
Box::new(vec![current_lhs, rhs]),
None,
pos,
),
Token::Divide => Expr::FnCall(
Box::new("/".into()),
Box::new(vec![current_lhs, rhs]),
None,
pos,
),
Token::LeftShift => { Token::LeftShift => Expr::FnCall(
Expr::FunctionCall("<<".into(), Box::new(vec![current_lhs, rhs]), None, pos) Box::new("<<".into()),
} Box::new(vec![current_lhs, rhs]),
Token::RightShift => { None,
Expr::FunctionCall(">>".into(), Box::new(vec![current_lhs, rhs]), None, pos) pos,
} ),
Token::Modulo => { Token::RightShift => Expr::FnCall(
Expr::FunctionCall("%".into(), Box::new(vec![current_lhs, rhs]), None, pos) Box::new(">>".into()),
} Box::new(vec![current_lhs, rhs]),
Token::PowerOf => { None,
Expr::FunctionCall("~".into(), Box::new(vec![current_lhs, rhs]), None, pos) pos,
} ),
Token::Modulo => Expr::FnCall(
Box::new("%".into()),
Box::new(vec![current_lhs, rhs]),
None,
pos,
),
Token::PowerOf => Expr::FnCall(
Box::new("~".into()),
Box::new(vec![current_lhs, rhs]),
None,
pos,
),
// Comparison operators default to false when passed invalid operands // Comparison operators default to false when passed invalid operands
Token::EqualsTo => Expr::FunctionCall( Token::EqualsTo => Expr::FnCall(
"==".into(), Box::new("==".into()),
Box::new(vec![current_lhs, rhs]), Box::new(vec![current_lhs, rhs]),
cmp_default, cmp_default,
pos, pos,
), ),
Token::NotEqualsTo => Expr::FunctionCall( Token::NotEqualsTo => Expr::FnCall(
"!=".into(), Box::new("!=".into()),
Box::new(vec![current_lhs, rhs]), Box::new(vec![current_lhs, rhs]),
cmp_default, cmp_default,
pos, pos,
), ),
Token::LessThan => Expr::FunctionCall( Token::LessThan => Expr::FnCall(
"<".into(), Box::new("<".into()),
Box::new(vec![current_lhs, rhs]), Box::new(vec![current_lhs, rhs]),
cmp_default, cmp_default,
pos, pos,
), ),
Token::LessThanEqualsTo => Expr::FunctionCall( Token::LessThanEqualsTo => Expr::FnCall(
"<=".into(), Box::new("<=".into()),
Box::new(vec![current_lhs, rhs]), Box::new(vec![current_lhs, rhs]),
cmp_default, cmp_default,
pos, pos,
), ),
Token::GreaterThan => Expr::FunctionCall( Token::GreaterThan => Expr::FnCall(
">".into(), Box::new(">".into()),
Box::new(vec![current_lhs, rhs]), Box::new(vec![current_lhs, rhs]),
cmp_default, cmp_default,
pos, pos,
), ),
Token::GreaterThanEqualsTo => Expr::FunctionCall( Token::GreaterThanEqualsTo => Expr::FnCall(
">=".into(), Box::new(">=".into()),
Box::new(vec![current_lhs, rhs]), Box::new(vec![current_lhs, rhs]),
cmp_default, cmp_default,
pos, pos,
@ -1403,15 +1445,24 @@ fn parse_binary_op<'a>(
Token::Or => Expr::Or(Box::new(current_lhs), Box::new(rhs), pos), Token::Or => Expr::Or(Box::new(current_lhs), Box::new(rhs), pos),
Token::And => Expr::And(Box::new(current_lhs), Box::new(rhs), pos), Token::And => Expr::And(Box::new(current_lhs), Box::new(rhs), pos),
Token::Ampersand => { Token::Ampersand => Expr::FnCall(
Expr::FunctionCall("&".into(), Box::new(vec![current_lhs, rhs]), None, pos) Box::new("&".into()),
} Box::new(vec![current_lhs, rhs]),
Token::Pipe => { None,
Expr::FunctionCall("|".into(), Box::new(vec![current_lhs, rhs]), None, pos) pos,
} ),
Token::XOr => { Token::Pipe => Expr::FnCall(
Expr::FunctionCall("^".into(), Box::new(vec![current_lhs, rhs]), None, pos) Box::new("|".into()),
} Box::new(vec![current_lhs, rhs]),
None,
pos,
),
Token::XOr => Expr::FnCall(
Box::new("^".into()),
Box::new(vec![current_lhs, rhs]),
None,
pos,
),
Token::In => make_in_expr(current_lhs, rhs, pos)?, Token::In => make_in_expr(current_lhs, rhs, pos)?,
@ -1590,7 +1641,7 @@ fn parse_for<'a>(
stack.rewind(prev_len); stack.rewind(prev_len);
Ok(Stmt::For(name, Box::new(expr), Box::new(body))) Ok(Stmt::For(Box::new(name), Box::new(expr), Box::new(body)))
} }
/// Parse a variable definition statement. /// Parse a variable definition statement.
@ -1619,12 +1670,12 @@ fn parse_let<'a>(
// let name = expr // let name = expr
ScopeEntryType::Normal => { ScopeEntryType::Normal => {
stack.push(name.clone()); stack.push(name.clone());
Ok(Stmt::Let(name, Some(Box::new(init_value)), pos)) Ok(Stmt::Let(Box::new(name), Some(Box::new(init_value)), pos))
} }
// const name = { expr:constant } // const name = { expr:constant }
ScopeEntryType::Constant if init_value.is_constant() => { ScopeEntryType::Constant if init_value.is_constant() => {
stack.push(name.clone()); stack.push(name.clone());
Ok(Stmt::Const(name, Box::new(init_value), pos)) Ok(Stmt::Const(Box::new(name), Box::new(init_value), pos))
} }
// const name = expr - error // const name = expr - error
ScopeEntryType::Constant => { ScopeEntryType::Constant => {
@ -1633,7 +1684,7 @@ fn parse_let<'a>(
} }
} else { } else {
// let name // let name
Ok(Stmt::Let(name, None, pos)) Ok(Stmt::Let(Box::new(name), None, pos))
} }
} }

31
tests/print.rs Normal file
View File

@ -0,0 +1,31 @@
use rhai::{Engine, EvalAltResult};
use std::sync::{Arc, RwLock};
#[test]
fn test_print() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
let logbook = Arc::new(RwLock::new(Vec::<String>::new()));
// Redirect print/debug output to 'log'
let log = logbook.clone();
engine.on_print(move |s| log.write().unwrap().push(format!("entry: {}", s)));
let log = logbook.clone();
engine.on_debug(move |s| log.write().unwrap().push(format!("DEBUG: {}", s)));
// Evaluate script
engine.eval::<()>("print(40 + 2)")?;
engine.eval::<()>(r#"debug("hello!")"#)?;
// 'logbook' captures all the 'print' and 'debug' output
assert_eq!(logbook.read().unwrap().len(), 2);
assert_eq!(logbook.read().unwrap()[0], "entry: 42");
assert_eq!(logbook.read().unwrap()[1], r#"DEBUG: "hello!""#);
for entry in logbook.read().unwrap().iter() {
println!("{}", entry);
}
Ok(())
}