rhai/src/engine.rs

887 lines
32 KiB
Rust
Raw Normal View History

2017-12-20 12:16:14 +01:00
use std::any::TypeId;
use std::borrow::Borrow;
use std::cmp::{PartialEq, PartialOrd};
2016-02-29 22:43:45 +01:00
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
2017-12-31 19:58:50 +01:00
use std::sync::Arc;
2017-12-20 12:16:14 +01:00
use std::ops::{Add, BitAnd, BitOr, BitXor, Deref, Div, Mul, Neg, Rem, Shl, Shr, Sub};
2016-02-29 22:43:45 +01:00
2017-12-20 12:16:14 +01:00
use any::{Any, AnyExt};
use fn_register::{Mut, RegisterFn};
use parser::{lex, parse, Expr, FnDef, Stmt};
2017-12-20 22:16:53 +01:00
use call::FunArgs;
2016-02-29 22:43:45 +01:00
#[derive(Debug)]
pub enum EvalAltResult {
ErrorFunctionNotFound(String),
ErrorFunctionArgMismatch,
ErrorFunctionCallNotSupported,
2016-03-26 18:46:28 +01:00
ErrorIndexMismatch,
ErrorIfGuardMismatch,
ErrorVariableNotFound(String),
ErrorFunctionArityNotSupported,
ErrorAssignmentToUnknownLHS,
2016-03-16 23:32:05 +01:00
ErrorMismatchOutputType,
2016-03-17 13:45:48 +01:00
ErrorCantOpenScriptFile,
InternalErrorMalformedDotExpression,
LoopBreak,
Return(Box<Any>),
2016-02-29 22:43:45 +01:00
}
impl EvalAltResult {
fn as_str(&self) -> Option<&str> {
match *self {
EvalAltResult::ErrorVariableNotFound(ref s) => Some(s.as_str()),
EvalAltResult::ErrorFunctionNotFound(ref s) => Some(s.as_str()),
_ => None
}
}
}
2017-12-20 21:09:53 +01:00
impl PartialEq for EvalAltResult {
fn eq(&self, other: &Self) -> bool {
use EvalAltResult::*;
match (self, other) {
(&ErrorFunctionNotFound(ref a), &ErrorFunctionNotFound(ref b)) => a == b,
2017-12-20 21:09:53 +01:00
(&ErrorFunctionArgMismatch, &ErrorFunctionArgMismatch) => true,
(&ErrorFunctionCallNotSupported, &ErrorFunctionCallNotSupported) => true,
(&ErrorIndexMismatch, &ErrorIndexMismatch) => true,
(&ErrorIfGuardMismatch, &ErrorIfGuardMismatch) => true,
(&ErrorVariableNotFound(ref a), &ErrorVariableNotFound(ref b)) => a == b,
(&ErrorFunctionArityNotSupported, &ErrorFunctionArityNotSupported) => true,
(&ErrorAssignmentToUnknownLHS, &ErrorAssignmentToUnknownLHS) => true,
(&ErrorMismatchOutputType, &ErrorMismatchOutputType) => true,
(&ErrorCantOpenScriptFile, &ErrorCantOpenScriptFile) => true,
(&InternalErrorMalformedDotExpression, &InternalErrorMalformedDotExpression) => true,
(&LoopBreak, &LoopBreak) => true,
_ => false,
}
}
}
impl Error for EvalAltResult {
2016-02-29 22:43:45 +01:00
fn description(&self) -> &str {
match *self {
EvalAltResult::ErrorFunctionNotFound(_) => "Function not found",
EvalAltResult::ErrorFunctionArgMismatch => "Function argument types do not match",
EvalAltResult::ErrorFunctionCallNotSupported => {
"Function call with > 2 argument not supported"
}
2016-03-26 18:46:28 +01:00
EvalAltResult::ErrorIndexMismatch => "Index does not match array",
EvalAltResult::ErrorIfGuardMismatch => "If guards expect boolean expression",
2016-03-10 22:19:56 +01:00
EvalAltResult::ErrorVariableNotFound(_) => "Variable not found",
EvalAltResult::ErrorFunctionArityNotSupported => {
"Functions of more than 3 parameters are not yet supported"
}
EvalAltResult::ErrorAssignmentToUnknownLHS => {
"Assignment to an unsupported left-hand side"
}
2016-03-16 23:32:05 +01:00
EvalAltResult::ErrorMismatchOutputType => "Cast of output failed",
2016-03-17 13:45:48 +01:00
EvalAltResult::ErrorCantOpenScriptFile => "Cannot open script file",
EvalAltResult::InternalErrorMalformedDotExpression => {
"[Internal error] Unexpected expression in dot expression"
}
EvalAltResult::LoopBreak => "Loop broken before completion (not an error)",
EvalAltResult::Return(_) => "Function returned value (not an error)",
2016-02-29 22:43:45 +01:00
}
}
fn cause(&self) -> Option<&Error> {
None
}
}
impl fmt::Display for EvalAltResult {
2016-02-29 22:43:45 +01:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(s) = self.as_str() {
write!(f, "{}: {}", self.description(), s)
} else {
write!(f, "{}", self.description())
}
2016-02-29 22:43:45 +01:00
}
}
2017-12-20 12:16:14 +01:00
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct FnSpec {
ident: String,
args: Option<Vec<TypeId>>,
}
2017-10-30 16:08:44 +01:00
/// Rhai's engine type. This is what you use to run Rhai scripts
///
/// ```rust
/// extern crate rhai;
/// use rhai::Engine;
///
/// fn main() {
/// let mut engine = Engine::new();
///
/// if let Ok(result) = engine.eval::<i64>("40 + 2") {
/// println!("Answer: {}", result); // prints 42
/// }
/// }
/// ```
2017-12-31 19:58:50 +01:00
#[derive(Clone)]
2016-02-29 22:43:45 +01:00
pub struct Engine {
2017-12-31 19:58:50 +01:00
/// A hashmap containing all functions known to the engine
pub fns: HashMap<FnSpec, Arc<FnIntExt>>,
2017-12-20 12:16:14 +01:00
}
pub enum FnIntExt {
Ext(Box<FnAny>),
Int(FnDef),
2016-02-29 22:43:45 +01:00
}
2017-12-20 21:52:26 +01:00
pub type FnAny = Fn(Vec<&mut Any>) -> Result<Box<Any>, EvalAltResult>;
2017-12-20 12:16:14 +01:00
2017-10-30 16:08:44 +01:00
/// A type containing information about current scope.
/// Useful for keeping state between `Engine` runs
///
/// ```rust
/// use rhai::{Engine, Scope};
///
/// let mut engine = Engine::new();
/// let mut my_scope = Scope::new();
///
/// assert!(engine.eval_with_scope::<()>(&mut my_scope, "let x = 5;").is_ok());
/// assert_eq!(engine.eval_with_scope::<i64>(&mut my_scope, "x + 1").unwrap(), 6);
/// ```
///
/// Between runs, `Engine` only remembers functions when not using own `Scope`.
pub type Scope = Vec<(String, Box<Any>)>;
2016-02-29 22:43:45 +01:00
impl Engine {
2017-12-20 22:16:53 +01:00
pub fn call_fn<'a, I, A, T>(&self, ident: I, args: A) -> Result<T, EvalAltResult>
where
I: Into<String>,
A: FunArgs<'a>,
T: Any + Clone,
{
self.call_fn_raw(ident.into(), args.into_vec())
.and_then(|b| {
b.downcast()
.map(|b| *b)
.map_err(|_| EvalAltResult::ErrorMismatchOutputType)
})
}
2017-10-30 16:08:44 +01:00
/// Universal method for calling functions, that are either
/// registered with the `Engine` or written in Rhai
2017-12-20 12:16:14 +01:00
pub fn call_fn_raw(
&self,
ident: String,
2017-12-20 21:52:26 +01:00
args: Vec<&mut Any>,
2017-12-20 12:16:14 +01:00
) -> Result<Box<Any>, EvalAltResult> {
debug_println!(
2017-12-20 21:09:53 +01:00
"Trying to call function {:?} with args {:?}",
ident,
2017-12-20 21:52:26 +01:00
args.iter().map(|x| (&**x).type_id()).collect::<Vec<_>>()
2017-12-20 21:09:53 +01:00
);
2017-12-20 12:16:14 +01:00
let spec = FnSpec {
2017-12-20 14:35:44 +01:00
ident: ident.clone(),
2017-12-20 22:16:53 +01:00
args: Some(args.iter().map(|a| <Any as Any>::type_id(&**a)).collect()),
2017-12-20 12:16:14 +01:00
};
2017-12-20 12:16:14 +01:00
self.fns
.get(&spec)
.or_else(|| {
let spec1 = FnSpec { ident: ident.clone(), args: None };
self.fns.get(&spec1)
})
.ok_or_else(|| {
let typenames = args.iter().map(|x| self.nice_type_name((&**x).box_clone())).collect::<Vec<_>>();
EvalAltResult::ErrorFunctionNotFound(format!("{} ({})", ident, typenames.join(",")))
})
2017-12-31 19:58:50 +01:00
.and_then(move |f| match **f {
2017-12-20 12:16:14 +01:00
FnIntExt::Ext(ref f) => f(args),
2017-12-20 21:09:53 +01:00
FnIntExt::Int(ref f) => {
let mut scope = Scope::new();
scope.extend(
f.params
.iter()
.cloned()
2017-12-20 21:52:26 +01:00
.zip(args.iter().map(|x| (&**x).box_clone())),
2017-12-20 21:09:53 +01:00
);
match self.eval_stmt(&mut scope, &*f.body) {
Err(EvalAltResult::Return(x)) => Ok(x),
other => other,
}
}
2017-12-20 12:16:14 +01:00
})
}
2017-12-20 14:35:44 +01:00
pub fn register_fn_raw(&mut self, ident: String, args: Option<Vec<TypeId>>, f: Box<FnAny>) {
debug_println!("Register; {:?} with args {:?}", ident, args);
2017-12-20 21:09:53 +01:00
2017-12-20 14:35:44 +01:00
let spec = FnSpec { ident, args };
2017-12-31 19:58:50 +01:00
self.fns.insert(spec, Arc::new(FnIntExt::Ext(f)));
}
2017-10-30 16:08:44 +01:00
/// Register a type for use with Engine. Keep in mind that
/// your type must implement Clone.
2017-12-20 12:16:14 +01:00
pub fn register_type<T: Any>(&mut self) {
// currently a no-op, exists for future extensibility
2016-02-29 22:43:45 +01:00
}
2017-10-30 16:08:44 +01:00
/// Register a get function for a member of a registered type
pub fn register_get<T: Clone + Any, U: Clone + Any, F>(&mut self, name: &str, get_fn: F)
2017-12-20 12:16:14 +01:00
where
F: 'static + Fn(&mut T) -> U,
{
let get_name = "get$".to_string() + name;
2016-03-17 13:45:48 +01:00
self.register_fn(&get_name, get_fn);
}
2017-10-30 16:08:44 +01:00
/// Register a set function for a member of a registered type
pub fn register_set<T: Clone + Any, U: Clone + Any, F>(&mut self, name: &str, set_fn: F)
2017-12-20 12:16:14 +01:00
where
F: 'static + Fn(&mut T, U) -> (),
{
let set_name = "set$".to_string() + name;
2016-03-17 13:45:48 +01:00
self.register_fn(&set_name, set_fn);
}
2017-10-30 16:08:44 +01:00
/// Shorthand for registering both getters and setters
2017-12-20 12:16:14 +01:00
pub fn register_get_set<T: Clone + Any, U: Clone + Any, F, G>(
&mut self,
name: &str,
get_fn: F,
set_fn: G,
) where
F: 'static + Fn(&mut T) -> U,
G: 'static + Fn(&mut T, U) -> (),
{
2016-03-17 13:45:48 +01:00
self.register_get(name, get_fn);
self.register_set(name, set_fn);
}
2017-12-20 12:16:14 +01:00
fn get_dot_val_helper(
&self,
scope: &mut Scope,
2017-12-20 21:52:26 +01:00
this_ptr: &mut Any,
2017-12-20 12:16:14 +01:00
dot_rhs: &Expr,
) -> Result<Box<Any>, EvalAltResult> {
use std::iter::once;
match *dot_rhs {
Expr::FnCall(ref fn_name, ref args) => {
2017-12-20 21:52:26 +01:00
let mut args: Vec<Box<Any>> = args.iter()
2017-12-20 12:16:14 +01:00
.map(|arg| self.eval_expr(scope, arg))
.collect::<Result<Vec<_>, _>>()?;
2017-12-20 22:16:53 +01:00
let args = once(this_ptr)
.chain(args.iter_mut().map(|b| b.as_mut()))
.collect();
2017-12-20 12:16:14 +01:00
self.call_fn_raw(fn_name.to_owned(), args)
}
Expr::Identifier(ref id) => {
let get_fn_name = "get$".to_string() + id;
2017-12-20 12:16:14 +01:00
self.call_fn_raw(get_fn_name, vec![this_ptr])
}
Expr::Index(ref id, ref idx_raw) => {
let idx = self.eval_expr(scope, idx_raw)?;
let get_fn_name = "get$".to_string() + id;
2017-12-20 12:16:14 +01:00
let mut val = self.call_fn_raw(get_fn_name, vec![this_ptr])?;
((*val).downcast_mut() as Option<&mut Vec<Box<Any>>>)
.and_then(|arr| idx.downcast_ref::<i64>().map(|idx| (arr, *idx as usize)))
2017-12-20 14:35:44 +01:00
.map(|(arr, idx)| arr[idx].clone())
2017-12-20 12:16:14 +01:00
.ok_or(EvalAltResult::ErrorIndexMismatch)
}
2017-12-20 12:16:14 +01:00
Expr::Dot(ref inner_lhs, ref inner_rhs) => match **inner_lhs {
Expr::Identifier(ref id) => {
let get_fn_name = "get$".to_string() + id;
self.call_fn_raw(get_fn_name, vec![this_ptr])
2017-12-20 21:52:26 +01:00
.and_then(|mut v| self.get_dot_val_helper(scope, v.as_mut(), inner_rhs))
}
2017-12-20 12:16:14 +01:00
_ => Err(EvalAltResult::InternalErrorMalformedDotExpression),
},
_ => Err(EvalAltResult::InternalErrorMalformedDotExpression),
}
}
2017-12-20 17:37:12 +01:00
fn search_scope<'a, F, T>(
scope: &'a mut Scope,
id: &str,
map: F,
) -> Result<(usize, T), EvalAltResult>
where
2017-12-20 21:52:26 +01:00
F: FnOnce(&'a mut Any) -> Result<T, EvalAltResult>,
2017-12-20 17:37:12 +01:00
{
scope
.iter_mut()
.enumerate()
.rev()
.find(|&(_, &mut (ref name, _))| *id == *name)
.ok_or_else(|| EvalAltResult::ErrorVariableNotFound(id.to_owned()))
2017-12-20 21:52:26 +01:00
.and_then(move |(idx, &mut (_, ref mut val))| map(val.as_mut()).map(|val| (idx, val)))
2017-12-20 17:37:12 +01:00
}
2017-12-20 21:09:53 +01:00
fn array_value(
&self,
scope: &mut Scope,
id: &str,
idx: &Expr,
) -> Result<(usize, usize, Box<Any>), EvalAltResult> {
2017-12-20 17:37:12 +01:00
let idx_boxed = self.eval_expr(scope, idx)?
.downcast::<i64>()
.map_err(|_| EvalAltResult::ErrorIndexMismatch)?;
let idx = *idx_boxed as usize;
let (idx_sc, val) = Self::search_scope(scope, id, |val| {
((*val).downcast_mut() as Option<&mut Vec<Box<Any>>>)
.map(|arr| arr[idx].clone())
.ok_or(EvalAltResult::ErrorIndexMismatch)
})?;
Ok((idx_sc, idx, val))
}
2017-12-20 12:16:14 +01:00
fn get_dot_val(
&self,
scope: &mut Scope,
dot_lhs: &Expr,
dot_rhs: &Expr,
) -> Result<Box<Any>, EvalAltResult> {
match *dot_lhs {
Expr::Identifier(ref id) => {
2017-12-20 21:52:26 +01:00
let (sc_idx, mut target) = Self::search_scope(scope, id, |x| Ok(x.box_clone()))?;
let value = self.get_dot_val_helper(scope, target.as_mut(), dot_rhs);
2017-12-20 17:37:12 +01:00
// In case the expression mutated `target`, we need to reassign it because
// of the above `clone`.
scope[sc_idx].1 = target;
value
}
Expr::Index(ref id, ref idx_raw) => {
2017-12-20 17:37:12 +01:00
let (sc_idx, idx, mut target) = self.array_value(scope, id, idx_raw)?;
2017-12-20 21:52:26 +01:00
let value = self.get_dot_val_helper(scope, target.as_mut(), dot_rhs);
2017-12-20 17:37:12 +01:00
// In case the expression mutated `target`, we need to reassign it because
// of the above `clone`.
scope[sc_idx].1.downcast_mut::<Vec<Box<Any>>>().unwrap()[idx] = target;
value
}
_ => Err(EvalAltResult::InternalErrorMalformedDotExpression),
}
}
2017-12-20 12:16:14 +01:00
fn set_dot_val_helper(
&self,
2017-12-20 21:52:26 +01:00
this_ptr: &mut Any,
2017-12-20 12:16:14 +01:00
dot_rhs: &Expr,
mut source_val: Box<Any>,
) -> Result<Box<Any>, EvalAltResult> {
match *dot_rhs {
Expr::Identifier(ref id) => {
let set_fn_name = "set$".to_string() + id;
2017-12-20 21:52:26 +01:00
self.call_fn_raw(set_fn_name, vec![this_ptr, source_val.as_mut()])
}
2017-12-20 12:16:14 +01:00
Expr::Dot(ref inner_lhs, ref inner_rhs) => match **inner_lhs {
Expr::Identifier(ref id) => {
let get_fn_name = "get$".to_string() + id;
self.call_fn_raw(get_fn_name, vec![this_ptr])
2017-12-20 21:09:53 +01:00
.and_then(|mut v| {
2017-12-20 21:52:26 +01:00
self.set_dot_val_helper(v.as_mut(), inner_rhs, source_val)
2017-12-20 21:09:53 +01:00
.map(|_| v) // Discard Ok return value
})
2017-12-20 12:16:14 +01:00
.and_then(|mut v| {
let set_fn_name = "set$".to_string() + id;
2017-12-20 21:52:26 +01:00
self.call_fn_raw(set_fn_name, vec![this_ptr, v.as_mut()])
2017-12-20 12:16:14 +01:00
})
}
2017-12-20 12:16:14 +01:00
_ => Err(EvalAltResult::InternalErrorMalformedDotExpression),
},
_ => Err(EvalAltResult::InternalErrorMalformedDotExpression),
}
}
2017-12-20 12:16:14 +01:00
fn set_dot_val(
&self,
scope: &mut Scope,
dot_lhs: &Expr,
dot_rhs: &Expr,
source_val: Box<Any>,
) -> Result<Box<Any>, EvalAltResult> {
match *dot_lhs {
Expr::Identifier(ref id) => {
2017-12-20 21:52:26 +01:00
let (sc_idx, mut target) = Self::search_scope(scope, id, |x| Ok(x.box_clone()))?;
let value = self.set_dot_val_helper(target.as_mut(), dot_rhs, source_val);
2017-12-20 17:37:12 +01:00
// In case the expression mutated `target`, we need to reassign it because
// of the above `clone`.
scope[sc_idx].1 = target;
2017-12-20 17:37:12 +01:00
value
}
Expr::Index(ref id, ref idx_raw) => {
2017-12-20 17:37:12 +01:00
let (sc_idx, idx, mut target) = self.array_value(scope, id, idx_raw)?;
2017-12-20 21:52:26 +01:00
let value = self.set_dot_val_helper(target.as_mut(), dot_rhs, source_val);
2017-12-20 17:37:12 +01:00
// In case the expression mutated `target`, we need to reassign it because
// of the above `clone`.
scope[sc_idx].1.downcast_mut::<Vec<Box<Any>>>().unwrap()[idx] = target;
2017-12-20 17:37:12 +01:00
value
}
_ => Err(EvalAltResult::InternalErrorMalformedDotExpression),
}
}
fn eval_expr(&self, scope: &mut Scope, expr: &Expr) -> Result<Box<Any>, EvalAltResult> {
2016-02-29 22:43:45 +01:00
match *expr {
Expr::IntConst(i) => Ok(Box::new(i)),
2017-10-28 05:30:12 +02:00
Expr::FloatConst(i) => Ok(Box::new(i)),
Expr::StringConst(ref s) => Ok(Box::new(s.clone())),
2017-10-02 23:44:45 +02:00
Expr::CharConst(ref c) => Ok(Box::new(*c)),
2016-02-29 22:43:45 +01:00
Expr::Identifier(ref id) => {
for &mut (ref name, ref mut val) in &mut scope.iter_mut().rev() {
if *id == *name {
2017-12-20 14:35:44 +01:00
return Ok(val.clone());
2016-02-29 22:43:45 +01:00
}
}
Err(EvalAltResult::ErrorVariableNotFound(id.clone()))
2016-02-29 22:43:45 +01:00
}
2016-03-26 18:46:28 +01:00
Expr::Index(ref id, ref idx_raw) => {
2017-12-20 17:37:12 +01:00
self.array_value(scope, id, idx_raw).map(|(_, _, x)| x)
2016-03-26 18:46:28 +01:00
}
2016-02-29 22:43:45 +01:00
Expr::Assignment(ref id, ref rhs) => {
let rhs_val = self.eval_expr(scope, rhs)?;
2016-03-26 18:46:28 +01:00
2016-02-29 22:43:45 +01:00
match **id {
Expr::Identifier(ref n) => {
for &mut (ref name, ref mut val) in &mut scope.iter_mut().rev() {
2016-02-29 22:43:45 +01:00
if *n == *name {
*val = rhs_val;
return Ok(Box::new(()));
}
}
Err(EvalAltResult::ErrorVariableNotFound(n.clone()))
2016-02-29 22:43:45 +01:00
}
2016-03-26 18:46:28 +01:00
Expr::Index(ref id, ref idx_raw) => {
let idx = self.eval_expr(scope, idx_raw)?;
2016-03-26 18:46:28 +01:00
for &mut (ref name, ref mut val) in &mut scope.iter_mut().rev() {
if *id == *name {
2017-12-20 12:16:14 +01:00
if let Some(i) = idx.downcast_ref::<i64>() {
if let Some(arr_typed) =
2017-12-20 12:16:14 +01:00
(*val).downcast_mut() as Option<&mut Vec<Box<Any>>>
{
2016-03-26 18:46:28 +01:00
arr_typed[*i as usize] = rhs_val;
return Ok(Box::new(()));
} else {
2016-03-26 18:46:28 +01:00
return Err(EvalAltResult::ErrorIndexMismatch);
}
} else {
2016-03-26 18:46:28 +01:00
return Err(EvalAltResult::ErrorIndexMismatch);
}
}
}
Err(EvalAltResult::ErrorVariableNotFound(id.clone()))
2016-03-26 18:46:28 +01:00
}
Expr::Dot(ref dot_lhs, ref dot_rhs) => {
self.set_dot_val(scope, dot_lhs, dot_rhs, rhs_val)
}
_ => Err(EvalAltResult::ErrorAssignmentToUnknownLHS),
2016-02-29 22:43:45 +01:00
}
}
Expr::Dot(ref lhs, ref rhs) => self.get_dot_val(scope, lhs, rhs),
2016-03-26 18:46:28 +01:00
Expr::Array(ref contents) => {
let mut arr = Vec::new();
2017-10-02 23:44:45 +02:00
for item in &(*contents) {
let arg = self.eval_expr(scope, item)?;
2016-03-26 18:46:28 +01:00
arr.push(arg);
}
Ok(Box::new(arr))
}
2017-12-20 12:16:14 +01:00
Expr::FnCall(ref fn_name, ref args) => self.call_fn_raw(
fn_name.to_owned(),
args.iter()
.map(|ex| self.eval_expr(scope, ex))
2017-12-20 21:52:26 +01:00
.collect::<Result<Vec<Box<Any>>, _>>()?
2017-12-20 12:16:14 +01:00
.iter_mut()
2017-12-20 21:52:26 +01:00
.map(|b| b.as_mut())
2017-12-20 12:16:14 +01:00
.collect(),
),
Expr::True => Ok(Box::new(true)),
Expr::False => Ok(Box::new(false)),
2018-05-23 01:44:41 +02:00
Expr::Unit => Ok(Box::new(())),
2016-02-29 22:43:45 +01:00
}
}
fn eval_stmt(&self, scope: &mut Scope, stmt: &Stmt) -> Result<Box<Any>, EvalAltResult> {
2016-02-29 22:43:45 +01:00
match *stmt {
Stmt::Expr(ref e) => self.eval_expr(scope, e),
2016-02-29 22:43:45 +01:00
Stmt::Block(ref b) => {
let prev_len = scope.len();
let mut last_result: Result<Box<Any>, EvalAltResult> = Ok(Box::new(()));
2016-02-29 22:43:45 +01:00
for s in b.iter() {
last_result = self.eval_stmt(scope, s);
2017-10-02 23:44:45 +02:00
if let Err(x) = last_result {
last_result = Err(x);
break;
}
2016-02-29 22:43:45 +01:00
}
while scope.len() > prev_len {
scope.pop();
2016-02-29 22:43:45 +01:00
}
2017-10-02 23:44:45 +02:00
last_result
2016-02-29 22:43:45 +01:00
}
Stmt::If(ref guard, ref body) => {
let guard_result = self.eval_expr(scope, guard)?;
2016-02-29 22:43:45 +01:00
match guard_result.downcast::<bool>() {
Ok(g) => {
if *g {
self.eval_stmt(scope, body)
} else {
2016-02-29 22:43:45 +01:00
Ok(Box::new(()))
}
}
Err(_) => Err(EvalAltResult::ErrorIfGuardMismatch),
2016-02-29 22:43:45 +01:00
}
}
2016-03-03 14:20:55 +01:00
Stmt::IfElse(ref guard, ref body, ref else_body) => {
let guard_result = self.eval_expr(scope, guard)?;
2016-03-03 14:20:55 +01:00
match guard_result.downcast::<bool>() {
Ok(g) => {
if *g {
self.eval_stmt(scope, body)
} else {
2016-03-03 14:20:55 +01:00
self.eval_stmt(scope, else_body)
}
}
Err(_) => Err(EvalAltResult::ErrorIfGuardMismatch),
2016-03-03 14:20:55 +01:00
}
}
2017-12-20 12:16:14 +01:00
Stmt::While(ref guard, ref body) => loop {
let guard_result = self.eval_expr(scope, guard)?;
match guard_result.downcast::<bool>() {
Ok(g) => {
if *g {
match self.eval_stmt(scope, body) {
2017-12-21 12:28:59 +01:00
Err(EvalAltResult::LoopBreak) => return Ok(Box::new(())),
Err(x) => return Err(x),
2017-12-20 12:16:14 +01:00
_ => (),
2016-02-29 22:43:45 +01:00
}
2017-12-20 12:16:14 +01:00
} else {
return Ok(Box::new(()));
2016-02-29 22:43:45 +01:00
}
}
2017-12-20 12:16:14 +01:00
Err(_) => return Err(EvalAltResult::ErrorIfGuardMismatch),
2016-02-29 22:43:45 +01:00
}
2017-12-20 12:16:14 +01:00
},
Stmt::Loop(ref body) => loop {
match self.eval_stmt(scope, body) {
2017-12-21 12:28:59 +01:00
Err(EvalAltResult::LoopBreak) => return Ok(Box::new(())),
Err(x) => return Err(x),
2017-12-20 12:16:14 +01:00
_ => (),
2017-10-30 16:08:44 +01:00
}
2017-12-20 12:16:14 +01:00
},
2017-10-02 23:44:45 +02:00
Stmt::Break => Err(EvalAltResult::LoopBreak),
Stmt::Return => Err(EvalAltResult::Return(Box::new(()))),
Stmt::ReturnWithVal(ref a) => {
let result = self.eval_expr(scope, a)?;
2017-10-02 23:44:45 +02:00
Err(EvalAltResult::Return(result))
}
2016-02-29 22:43:45 +01:00
Stmt::Var(ref name, ref init) => {
2017-10-02 23:44:45 +02:00
match *init {
Some(ref v) => {
let i = self.eval_expr(scope, v)?;
scope.push((name.clone(), i));
}
2017-12-21 12:28:59 +01:00
None => scope.push((name.clone(), Box::new(()))),
2016-02-29 22:43:45 +01:00
};
Ok(Box::new(()))
}
}
}
fn nice_type_name(&self, b: Box<Any>) -> String {
if b.is::<String>() {
"string".into()
} else
if b.is::<i64>() {
"integer".into()
} else
if b.is::<f64>() {
"float".into()
} else
if b.is::<Vec<Box<Any>>>() {
"array".into()
} else {
format!("<unknown> {:?}", b.type_id())
}
}
2017-10-30 16:08:44 +01:00
/// Evaluate a file
pub fn eval_file<T: Any + Clone>(&mut self, fname: &str) -> Result<T, EvalAltResult> {
2016-03-17 13:45:48 +01:00
use std::fs::File;
use std::io::prelude::*;
2017-10-02 23:44:45 +02:00
if let Ok(mut f) = File::open(fname) {
2016-03-17 13:45:48 +01:00
let mut contents = String::new();
2017-10-02 23:44:45 +02:00
if f.read_to_string(&mut contents).is_ok() {
2016-03-17 13:45:48 +01:00
self.eval::<T>(&contents)
} else {
2016-03-17 13:45:48 +01:00
Err(EvalAltResult::ErrorCantOpenScriptFile)
}
} else {
2016-03-17 13:45:48 +01:00
Err(EvalAltResult::ErrorCantOpenScriptFile)
}
2016-03-17 13:45:48 +01:00
}
2017-10-30 16:08:44 +01:00
/// Evaluate a string
pub fn eval<T: Any + Clone>(&mut self, input: &str) -> Result<T, EvalAltResult> {
let mut scope: Scope = Vec::new();
self.eval_with_scope(&mut scope, input)
}
2017-10-30 16:08:44 +01:00
/// Evaluate with own scope
2017-12-20 12:16:14 +01:00
pub fn eval_with_scope<T: Any + Clone>(
&mut self,
scope: &mut Scope,
input: &str,
) -> Result<T, EvalAltResult> {
let tokens = lex(input);
2016-02-29 22:43:45 +01:00
let mut peekables = tokens.peekable();
let tree = parse(&mut peekables);
match tree {
Ok((ref os, ref fns)) => {
let mut x: Result<Box<Any>, EvalAltResult> = Ok(Box::new(()));
for f in fns {
let name = f.name.clone();
let local_f = f.clone();
2017-12-20 12:16:14 +01:00
let spec = FnSpec {
ident: name,
args: None,
};
2017-12-31 19:58:50 +01:00
self.fns.insert(spec, Arc::new(FnIntExt::Int(local_f)));
}
2016-02-29 22:43:45 +01:00
for o in os {
2017-10-02 23:44:45 +02:00
x = match self.eval_stmt(scope, o) {
2016-03-16 23:32:05 +01:00
Ok(v) => Ok(v),
Err(e) => return Err(e),
2016-03-16 23:32:05 +01:00
}
}
2017-12-20 14:35:44 +01:00
let x = x?;
match x.downcast::<T>() {
Ok(out) => Ok(*out),
Err(_) => Err(EvalAltResult::ErrorMismatchOutputType),
2016-02-29 22:43:45 +01:00
}
}
Err(_) => Err(EvalAltResult::ErrorFunctionArgMismatch),
2016-02-29 22:43:45 +01:00
}
}
2017-10-30 16:08:44 +01:00
/// Evaluate a file, but only return errors, if there are any.
/// Useful for when you don't need the result, but still need
/// to keep track of possible errors
2017-10-15 17:50:39 +02:00
pub fn consume_file(&mut self, fname: &str) -> Result<(), EvalAltResult> {
use std::fs::File;
use std::io::prelude::*;
if let Ok(mut f) = File::open(fname) {
let mut contents = String::new();
if f.read_to_string(&mut contents).is_ok() {
if let e @ Err(_) = self.consume(&contents) {
2017-12-21 12:28:59 +01:00
e
2017-12-20 12:16:14 +01:00
} else {
2017-12-21 12:28:59 +01:00
Ok(())
2017-12-20 12:16:14 +01:00
}
2017-10-15 17:50:39 +02:00
} else {
Err(EvalAltResult::ErrorCantOpenScriptFile)
}
} else {
Err(EvalAltResult::ErrorCantOpenScriptFile)
}
}
2017-10-30 16:08:44 +01:00
/// Evaluate a string, but only return errors, if there are any.
/// Useful for when you don't need the result, but still need
/// to keep track of possible errors
2017-10-15 17:50:39 +02:00
pub fn consume(&mut self, input: &str) -> Result<(), EvalAltResult> {
2017-12-31 19:58:50 +01:00
self.consume_with_scope(&mut Scope::new(), input)
2017-10-15 17:50:39 +02:00
}
2017-10-30 16:08:44 +01:00
/// Evaluate a string with own scoppe, but only return errors, if there are any.
/// Useful for when you don't need the result, but still need
/// to keep track of possible errors
2017-12-20 12:16:14 +01:00
pub fn consume_with_scope(
&mut self,
scope: &mut Scope,
input: &str,
) -> Result<(), EvalAltResult> {
2017-10-15 17:50:39 +02:00
let tokens = lex(input);
let mut peekables = tokens.peekable();
let tree = parse(&mut peekables);
match tree {
Ok((ref os, ref fns)) => {
for f in fns {
if f.params.len() > 6 {
return Ok(());
}
let name = f.name.clone();
let local_f = f.clone();
2017-12-20 12:16:14 +01:00
let spec = FnSpec {
ident: name,
args: None,
};
2017-12-31 19:58:50 +01:00
self.fns.insert(spec, Arc::new(FnIntExt::Int(local_f)));
2017-10-15 17:50:39 +02:00
}
for o in os {
if let Err(e) = self.eval_stmt(scope, o) {
return Err(e);
}
}
Ok(())
2017-12-20 12:16:14 +01:00
}
2017-10-15 17:50:39 +02:00
Err(_) => Err(EvalAltResult::ErrorFunctionArgMismatch),
}
}
2017-10-30 16:08:44 +01:00
/// Register the default library. That means, numberic types, char, bool
/// String, arithmetics and string concatenations.
2016-03-01 15:40:48 +01:00
pub fn register_default_lib(engine: &mut Engine) {
engine.register_type::<i32>();
engine.register_type::<u32>();
engine.register_type::<i64>();
engine.register_type::<u64>();
engine.register_type::<f32>();
engine.register_type::<f64>();
engine.register_type::<String>();
engine.register_type::<char>();
engine.register_type::<bool>();
macro_rules! reg_op {
($engine:expr, $x:expr, $op:expr, $( $y:ty ),*) => (
$(
$engine.register_fn($x, ($op as fn(x: $y, y: $y)->$y));
2016-03-01 15:40:48 +01:00
)*
)
}
2017-10-30 16:08:44 +01:00
macro_rules! reg_un {
($engine:expr, $x:expr, $op:expr, $( $y:ty ),*) => (
$(
$engine.register_fn($x, ($op as fn(x: $y)->$y));
)*
)
}
2016-03-01 15:40:48 +01:00
macro_rules! reg_cmp {
($engine:expr, $x:expr, $op:expr, $( $y:ty ),*) => (
$(
$engine.register_fn($x, ($op as fn(x: $y, y: $y)->bool));
2016-03-01 15:40:48 +01:00
)*
)
}
2017-12-21 12:28:59 +01:00
fn add<T: Add>(x: T, y: T) -> <T as Add>::Output { x + y }
fn sub<T: Sub>(x: T, y: T) -> <T as Sub>::Output { x - y }
fn mul<T: Mul>(x: T, y: T) -> <T as Mul>::Output { x * y }
fn div<T: Div>(x: T, y: T) -> <T as Div>::Output { x / y }
fn neg<T: Neg>(x: T) -> <T as Neg>::Output { -x }
fn lt<T: PartialOrd>(x: T, y: T) -> bool { x < y }
fn lte<T: PartialOrd>(x: T, y: T) -> bool { x <= y }
fn gt<T: PartialOrd>(x: T, y: T) -> bool { x > y }
fn gte<T: PartialOrd>(x: T, y: T) -> bool { x >= y }
fn eq<T: PartialEq>(x: T, y: T) -> bool { x == y }
fn ne<T: PartialEq>(x: T, y: T) -> bool { x != y }
fn and(x: bool, y: bool) -> bool { x && y }
fn or(x: bool, y: bool) -> bool { x || y }
fn not(x: bool) -> bool { !x }
fn concat(x: String, y: String) -> String { x + &y }
fn binary_and<T: BitAnd>(x: T, y: T) -> <T as BitAnd>::Output { x & y }
fn binary_or<T: BitOr>(x: T, y: T) -> <T as BitOr>::Output { x | y }
fn binary_xor<T: BitXor>(x: T, y: T) -> <T as BitXor>::Output { x ^ y }
fn left_shift<T: Shl<T>>(x: T, y: T) -> <T as Shl<T>>::Output { x.shl(y) }
fn right_shift<T: Shr<T>>(x: T, y: T) -> <T as Shr<T>>::Output { x.shr(y) }
fn modulo<T: Rem<T>>(x: T, y: T) -> <T as Rem<T>>::Output { x % y }
fn pow_i64_i64(x: i64, y: i64) -> i64 { x.pow(y as u32) }
fn pow_f64_f64(x: f64, y: f64) -> f64 { x.powf(y) }
fn pow_f64_i64(x: f64, y: i64) -> f64 { x.powi(y as i32) }
2018-05-23 01:44:41 +02:00
fn unit_eq(a: (), b: ()) -> bool { true }
2016-03-01 15:40:48 +01:00
reg_op!(engine, "+", add, i32, i64, u32, u64, f32, f64);
reg_op!(engine, "-", sub, i32, i64, u32, u64, f32, f64);
reg_op!(engine, "*", mul, i32, i64, u32, u64, f32, f64);
reg_op!(engine, "/", div, i32, i64, u32, u64, f32, f64);
2017-10-28 05:30:12 +02:00
reg_cmp!(engine, "<", lt, i32, i64, u32, u64, String, f64);
reg_cmp!(engine, "<=", lte, i32, i64, u32, u64, String, f64);
reg_cmp!(engine, ">", gt, i32, i64, u32, u64, String, f64);
reg_cmp!(engine, ">=", gte, i32, i64, u32, u64, String, f64);
reg_cmp!(engine, "==", eq, i32, i64, u32, u64, bool, String, f64);
reg_cmp!(engine, "!=", ne, i32, i64, u32, u64, bool, String, f64);
2016-03-01 15:40:48 +01:00
reg_op!(engine, "||", or, bool);
reg_op!(engine, "&&", and, bool);
reg_op!(engine, "|", binary_or, i32, i64, u32, u64);
reg_op!(engine, "|", or, bool);
reg_op!(engine, "&", binary_and, i32, i64, u32, u64);
reg_op!(engine, "&", and, bool);
reg_op!(engine, "^", binary_xor, i32, i64, u32, u64);
reg_op!(engine, "<<", left_shift, i32, i64, u32, u64);
reg_op!(engine, ">>", right_shift, i32, i64, u32, u64);
reg_op!(engine, "%", modulo, i32, i64, u32, u64);
2017-11-24 08:56:22 +01:00
engine.register_fn("~", pow_i64_i64);
engine.register_fn("~", pow_f64_f64);
engine.register_fn("~", pow_f64_i64);
2016-03-26 18:46:28 +01:00
2017-10-30 16:08:44 +01:00
reg_un!(engine, "-", neg, i32, i64, f32, f64);
reg_un!(engine, "!", not, bool);
2016-08-18 03:33:31 +02:00
engine.register_fn("+", concat);
2018-05-23 01:44:41 +02:00
engine.register_fn("==", unit_eq);
2016-08-18 03:33:31 +02:00
// engine.register_fn("[]", idx);
// FIXME? Registering array lookups are a special case because we want to return boxes
2017-10-02 23:44:45 +02:00
// directly let ent = engine.fns.entry("[]".to_string()).or_insert_with(Vec::new);
// (*ent).push(FnType::ExternalFn2(Box::new(idx)));
2016-03-01 15:40:48 +01:00
}
2017-10-30 16:08:44 +01:00
/// Make a new engine
2016-02-29 22:43:45 +01:00
pub fn new() -> Engine {
2017-12-20 12:16:14 +01:00
let mut engine = Engine {
fns: HashMap::new(),
};
2016-03-01 15:40:48 +01:00
2017-12-20 16:39:03 +01:00
Engine::register_default_lib(&mut engine);
2016-03-01 15:40:48 +01:00
engine
}
}