rhai/src/engine.rs

1331 lines
48 KiB
Rust
Raw Normal View History

2017-12-20 12:16:14 +01:00
use std::any::TypeId;
use std::cmp::{PartialEq, PartialOrd};
2016-02-29 22:43:45 +01:00
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
2019-09-18 12:21:07 +02:00
use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub};
2020-03-01 06:30:22 +01:00
use std::sync::Arc;
2016-02-29 22:43:45 +01:00
use crate::any::{Any, AnyExt, Dynamic, Variant};
2019-09-18 12:21:07 +02:00
use crate::call::FunArgs;
use crate::fn_register::{RegisterDynamicFn, RegisterFn};
use crate::parser::{lex, parse, Expr, FnDef, ParseError, Stmt, AST};
use fmt::{Debug, Display};
pub type Array = Vec<Dynamic>;
pub type FnCallArgs<'a> = Vec<&'a mut Variant>;
2016-02-29 22:43:45 +01:00
#[derive(Debug, Clone)]
pub enum EvalAltResult {
ErrorParseError(ParseError),
ErrorFunctionNotFound(String),
ErrorFunctionArgMismatch,
2020-03-01 06:30:22 +01:00
ErrorArrayBounds(usize, i64),
ErrorStringBounds(usize, i64),
ErrorIndexing,
ErrorIndexExpr,
ErrorIfGuard,
ErrorFor,
ErrorVariableNotFound(String),
ErrorAssignmentToUnknownLHS,
ErrorMismatchOutputType(String),
ErrorCantOpenScriptFile(String),
2020-03-01 06:30:22 +01:00
ErrorDotExpr,
LoopBreak,
Return(Dynamic),
2016-02-29 22:43:45 +01:00
}
impl EvalAltResult {
fn as_str(&self) -> Option<&str> {
Some(match self {
EvalAltResult::ErrorCantOpenScriptFile(ref s)
| EvalAltResult::ErrorVariableNotFound(ref s)
| EvalAltResult::ErrorFunctionNotFound(ref s)
| EvalAltResult::ErrorMismatchOutputType(ref s) => s,
_ => return None,
})
}
}
2017-12-20 21:09:53 +01:00
impl PartialEq for EvalAltResult {
fn eq(&self, other: &Self) -> bool {
use EvalAltResult::*;
match (self, other) {
(ErrorParseError(ref a), ErrorParseError(ref b)) => a == b,
(ErrorFunctionNotFound(ref a), ErrorFunctionNotFound(ref b)) => a == b,
(ErrorFunctionArgMismatch, ErrorFunctionArgMismatch) => true,
2020-03-01 06:30:22 +01:00
(ErrorIndexExpr, ErrorIndexExpr) => true,
(ErrorIndexing, ErrorIndexing) => true,
(ErrorArrayBounds(max1, index1), ErrorArrayBounds(max2, index2)) => {
max1 == max2 && index1 == index2
}
2020-03-01 06:30:22 +01:00
(ErrorStringBounds(max1, index1), ErrorStringBounds(max2, index2)) => {
max1 == max2 && index1 == index2
}
(ErrorIfGuard, ErrorIfGuard) => true,
(ErrorFor, ErrorFor) => true,
(ErrorVariableNotFound(ref a), ErrorVariableNotFound(ref b)) => a == b,
(ErrorAssignmentToUnknownLHS, ErrorAssignmentToUnknownLHS) => true,
(ErrorMismatchOutputType(ref a), ErrorMismatchOutputType(ref b)) => a == b,
(ErrorCantOpenScriptFile(ref a), ErrorCantOpenScriptFile(ref b)) => a == b,
2020-03-01 06:30:22 +01:00
(ErrorDotExpr, ErrorDotExpr) => true,
(LoopBreak, LoopBreak) => true,
2017-12-20 21:09:53 +01:00
_ => false,
}
}
}
impl Error for EvalAltResult {
2016-02-29 22:43:45 +01:00
fn description(&self) -> &str {
match self {
2020-03-01 06:30:22 +01:00
Self::ErrorParseError(ref p) => p.description(),
Self::ErrorFunctionNotFound(_) => "Function not found",
Self::ErrorFunctionArgMismatch => "Function argument types do not match",
Self::ErrorIndexExpr => "Indexing into an array or string expects an integer index",
Self::ErrorIndexing => "Indexing can only be performed on an array or a string",
Self::ErrorArrayBounds(_, ref index) if *index < 0 => {
"Array access expects non-negative index"
}
2020-03-01 06:30:22 +01:00
Self::ErrorArrayBounds(ref max, _) if *max == 0 => "Access of empty array",
Self::ErrorArrayBounds(_, _) => "Array index out of bounds",
Self::ErrorStringBounds(_, ref index) if *index < 0 => {
"Indexing a string expects a non-negative index"
}
2020-03-01 06:30:22 +01:00
Self::ErrorStringBounds(ref max, _) if *max == 0 => "Indexing of empty string",
Self::ErrorStringBounds(_, _) => "String index out of bounds",
Self::ErrorIfGuard => "If guards expect boolean expression",
Self::ErrorFor => "For loops expect array",
Self::ErrorVariableNotFound(_) => "Variable not found",
Self::ErrorAssignmentToUnknownLHS => {
"Assignment to an unsupported left-hand side expression"
}
2020-03-01 06:30:22 +01:00
Self::ErrorMismatchOutputType(_) => "Output type is incorrect",
Self::ErrorCantOpenScriptFile(_) => "Cannot open script file",
Self::ErrorDotExpr => "Malformed dot expression",
Self::LoopBreak => "[Not Error] Breaks out of loop",
Self::Return(_) => "[Not Error] Function returns value",
2016-02-29 22:43:45 +01:00
}
}
2019-09-18 12:21:07 +02:00
fn cause(&self) -> Option<&dyn Error> {
2016-02-29 22:43:45 +01:00
None
}
}
impl fmt::Display for EvalAltResult {
2019-09-18 12:21:07 +02:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(s) = self.as_str() {
write!(f, "{}: {}", self.description(), s)
} else {
match self {
EvalAltResult::ErrorParseError(ref p) => write!(f, "Syntax error: {}", p),
2020-03-01 06:30:22 +01:00
EvalAltResult::ErrorArrayBounds(_, index) if *index < 0 => {
write!(f, "{}: {} < 0", self.description(), index)
}
EvalAltResult::ErrorArrayBounds(max, _) if *max == 0 => {
write!(f, "{}", self.description())
}
EvalAltResult::ErrorArrayBounds(max, index) => {
write!(f, "{} (max {}): {}", self.description(), max - 1, index)
}
EvalAltResult::ErrorStringBounds(_, index) if *index < 0 => {
write!(f, "{}: {} < 0", self.description(), index)
}
2020-03-01 06:30:22 +01:00
EvalAltResult::ErrorStringBounds(max, _) if *max == 0 => {
write!(f, "{}", self.description())
}
2020-03-01 06:30:22 +01:00
EvalAltResult::ErrorStringBounds(max, index) => {
write!(f, "{} (max {}): {}", self.description(), max - 1, index)
}
err => write!(f, "{}", err.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>>,
}
type IteratorFn = dyn Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>>;
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
/// }
/// }
/// ```
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>>,
pub type_iterators: HashMap<TypeId, Arc<IteratorFn>>,
2020-02-25 03:40:48 +01:00
on_print: Box<dyn Fn(&str)>,
on_debug: Box<dyn Fn(&str)>,
2017-12-20 12:16:14 +01:00
}
pub enum FnIntExt {
Ext(Box<FnAny>),
Int(FnDef),
2016-02-29 22:43:45 +01:00
}
pub type FnAny = dyn Fn(FnCallArgs) -> Result<Dynamic, 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, Dynamic)>;
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)
2019-09-30 19:57:21 +02:00
.map_err(|a| EvalAltResult::ErrorMismatchOutputType((*a).type_name()))
2017-12-20 22:16:53 +01:00
})
}
2017-10-30 16:08:44 +01:00
/// Universal method for calling functions, that are either
/// registered with the `Engine` or written in Rhai
pub fn call_fn_raw(&self, ident: String, args: FnCallArgs) -> Result<Dynamic, EvalAltResult> {
debug_println!(
2017-12-20 21:09:53 +01:00
"Trying to call function {:?} with args {:?}",
ident,
args.iter()
.map(|x| Any::type_name(&**x))
.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(),
args: Some(args.iter().map(|a| 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(|| {
2019-09-18 12:21:07 +02:00
let spec1 = FnSpec {
ident: ident.clone(),
args: None,
};
self.fns.get(&spec1)
})
.ok_or_else(|| {
2020-03-01 06:30:22 +01:00
let type_names = args
2019-09-18 12:21:07 +02:00
.iter()
.map(|x| (*(&**x).into_dynamic()).type_name())
2019-09-18 12:21:07 +02:00
.collect::<Vec<_>>();
EvalAltResult::ErrorFunctionNotFound(format!(
"{} ({})",
ident,
2020-03-01 06:30:22 +01:00
type_names.join(", ")
))
})
2017-12-31 19:58:50 +01:00
.and_then(move |f| match **f {
2020-02-25 03:40:48 +01:00
FnIntExt::Ext(ref f) => {
let r = f(args);
if r.is_err() {
return r;
}
let callback = match ident.as_str() {
"print" => &self.on_print,
"debug" => &self.on_debug,
_ => return r,
};
Ok(Box::new(callback(
r.unwrap()
.downcast::<String>()
.map(|x| *x)
.unwrap_or("error: not a string".into())
.as_str(),
)))
}
2017-12-20 21:09:53 +01:00
FnIntExt::Int(ref f) => {
let mut scope = Scope::new();
scope.extend(
f.params
.iter()
.cloned()
.zip(args.iter().map(|x| (&**x).into_dynamic())),
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
}
/// Register an iterator adapter for a type.
pub fn register_iterator<T: Any, F>(&mut self, f: F)
where
F: 'static + Fn(&Dynamic) -> Box<dyn Iterator<Item = Dynamic>>,
{
self.type_iterators.insert(TypeId::of::<T>(), Arc::new(f));
}
2017-10-30 16:08:44 +01:00
/// Register a get function for a member of a registered type
pub fn register_get<T: Any + Clone, U: Any + Clone, 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: Any + Clone, U: Any + Clone, 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
pub fn register_get_set<T: Any + Clone, U: Any + Clone, F, G>(
2017-12-20 12:16:14 +01:00
&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,
this_ptr: &mut Variant,
2017-12-20 12:16:14 +01:00
dot_rhs: &Expr,
) -> Result<Dynamic, EvalAltResult> {
2017-12-20 12:16:14 +01:00
use std::iter::once;
match dot_rhs {
Expr::FunctionCall(fn_name, args) => {
let mut args: Array = args
2019-09-18 12:21:07 +02:00
.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(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(id, idx_raw) => {
2020-03-01 06:30:22 +01:00
let idx = self
.eval_expr(scope, idx_raw)?
.downcast_ref::<i64>()
.map(|i| *i)
.ok_or(EvalAltResult::ErrorIndexExpr)?;
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])?;
2020-03-01 06:30:22 +01:00
if let Some(arr) = (*val).downcast_mut() as Option<&mut Array> {
if idx < 0 {
Err(EvalAltResult::ErrorArrayBounds(arr.len(), idx))
} else {
arr.get(idx as usize)
.cloned()
2020-03-01 06:30:22 +01:00
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr.len(), idx))
}
} else if let Some(s) = (*val).downcast_mut() as Option<&mut String> {
if idx < 0 {
Err(EvalAltResult::ErrorStringBounds(s.chars().count(), idx))
} else {
s.chars()
.nth(idx as usize)
.map(|ch| Box::new(ch) as Dynamic)
.ok_or_else(|| EvalAltResult::ErrorStringBounds(s.chars().count(), idx))
}
} else {
Err(EvalAltResult::ErrorIndexing)
}
}
Expr::Dot(inner_lhs, inner_rhs) => match **inner_lhs {
2017-12-20 12:16:14 +01:00
Expr::Identifier(ref id) => {
let get_fn_name = "get$".to_string() + id;
2020-03-01 06:30:22 +01:00
let value = self
.call_fn_raw(get_fn_name, vec![this_ptr])
.and_then(|mut v| self.get_dot_val_helper(scope, v.as_mut(), inner_rhs))?;
// TODO - Should propagate changes back in this scenario:
//
// fn update(p) { p = something_else; }
// obj.prop.update();
//
// Right now, a copy of the object's property value is mutated, but not propagated
// back to the property via $set.
Ok(value)
}
Expr::Index(_, _) => {
// TODO - Handle Expr::Index for these scenarios:
//
// let x = obj.prop[2].x;
// obj.prop[3] = 42;
//
Err(EvalAltResult::ErrorDotExpr)
}
2020-03-01 06:30:22 +01:00
_ => Err(EvalAltResult::ErrorDotExpr),
2017-12-20 12:16:14 +01:00
},
2020-03-01 06:30:22 +01:00
_ => Err(EvalAltResult::ErrorDotExpr),
}
}
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
F: FnOnce(&'a mut Variant) -> Result<T, EvalAltResult>,
2017-12-20 17:37:12 +01:00
{
scope
.iter_mut()
.enumerate()
.rev()
.find(|&(_, &mut (ref name, _))| id == name)
2017-12-20 17:37:12 +01:00
.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
}
2020-03-01 06:30:22 +01:00
fn indexed_value(
2017-12-20 21:09:53 +01:00
&self,
scope: &mut Scope,
id: &str,
idx: &Expr,
2020-03-01 06:30:22 +01:00
) -> Result<(bool, usize, usize, Dynamic), EvalAltResult> {
let idx = *self
2019-09-18 12:21:07 +02:00
.eval_expr(scope, idx)?
2017-12-20 17:37:12 +01:00
.downcast::<i64>()
2020-03-01 06:30:22 +01:00
.map_err(|_| EvalAltResult::ErrorIndexExpr)?;
let mut is_array = false;
Self::search_scope(scope, id, |val| {
if let Some(arr) = (*val).downcast_mut() as Option<&mut Array> {
is_array = true;
return if idx < 0 {
Err(EvalAltResult::ErrorArrayBounds(arr.len(), idx))
} else {
arr.get(idx as usize)
.cloned()
2020-03-01 06:30:22 +01:00
.ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr.len(), idx))
};
}
if let Some(s) = (*val).downcast_mut() as Option<&mut String> {
is_array = false;
return if idx < 0 {
Err(EvalAltResult::ErrorStringBounds(s.chars().count(), idx))
} else {
s.chars()
.nth(idx as usize)
.map(|ch| Box::new(ch) as Dynamic)
.ok_or_else(|| EvalAltResult::ErrorStringBounds(s.chars().count(), idx))
};
}
Err(EvalAltResult::ErrorIndexing)
})
.map(|(idx_sc, val)| (is_array, idx_sc, idx as usize, val))
}
fn str_replace_char(s: &mut String, idx: usize, new_ch: char) {
// The new character
let ch = s.chars().nth(idx).unwrap();
// See if changed - if so, update the String
if ch == new_ch {
return;
}
2017-12-20 17:37:12 +01:00
2020-03-01 06:30:22 +01:00
// Collect all the characters after the index
let mut chars: Vec<char> = s.chars().collect();
chars[idx] = new_ch;
s.truncate(0);
chars.iter().for_each(|&ch| s.push(ch));
2017-12-20 17:37:12 +01:00
}
2017-12-20 12:16:14 +01:00
fn get_dot_val(
&self,
scope: &mut Scope,
dot_lhs: &Expr,
dot_rhs: &Expr,
) -> Result<Dynamic, EvalAltResult> {
match dot_lhs {
Expr::Identifier(id) => {
let (sc_idx, mut target) = Self::search_scope(scope, id, |x| Ok(x.into_dynamic()))?;
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 = target;
value
}
Expr::Index(id, idx_raw) => {
2020-03-01 06:30:22 +01:00
let (is_array, sc_idx, idx, mut target) = self.indexed_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`.
2020-03-01 06:30:22 +01:00
if is_array {
scope[sc_idx].1.downcast_mut::<Array>().unwrap()[idx] = target;
} else {
// Target should be a char
let new_ch = *target.downcast::<char>().unwrap();
// Root should be a String
let s = scope[sc_idx].1.downcast_mut::<String>().unwrap();
Self::str_replace_char(s, idx, new_ch);
}
2017-12-20 17:37:12 +01:00
value
}
2020-03-01 06:30:22 +01:00
_ => Err(EvalAltResult::ErrorDotExpr),
}
}
2017-12-20 12:16:14 +01:00
fn set_dot_val_helper(
&self,
this_ptr: &mut Variant,
2017-12-20 12:16:14 +01:00
dot_rhs: &Expr,
mut source_val: Dynamic,
) -> Result<Dynamic, EvalAltResult> {
match dot_rhs {
Expr::Identifier(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()])
}
Expr::Dot(inner_lhs, inner_rhs) => match **inner_lhs {
2017-12-20 12:16:14 +01:00
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
})
}
2020-03-01 06:30:22 +01:00
_ => Err(EvalAltResult::ErrorDotExpr),
2017-12-20 12:16:14 +01:00
},
2020-03-01 06:30:22 +01:00
_ => Err(EvalAltResult::ErrorDotExpr),
}
}
2017-12-20 12:16:14 +01:00
fn set_dot_val(
&self,
scope: &mut Scope,
dot_lhs: &Expr,
dot_rhs: &Expr,
source_val: Dynamic,
) -> Result<Dynamic, EvalAltResult> {
match dot_lhs {
Expr::Identifier(id) => {
let (sc_idx, mut target) = Self::search_scope(scope, id, |x| Ok(x.into_dynamic()))?;
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 = target;
2017-12-20 17:37:12 +01:00
value
}
Expr::Index(id, idx_raw) => {
2020-03-01 06:30:22 +01:00
let (is_array, sc_idx, idx, mut target) = self.indexed_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`.
2020-03-01 06:30:22 +01:00
if is_array {
scope[sc_idx].1.downcast_mut::<Array>().unwrap()[idx] = target;
} else {
// Target should be a char
let new_ch = *target.downcast::<char>().unwrap();
// Root should be a String
let s = scope[sc_idx].1.downcast_mut::<String>().unwrap();
Self::str_replace_char(s, idx, new_ch);
}
2017-12-20 17:37:12 +01:00
value
}
2020-03-01 06:30:22 +01:00
_ => Err(EvalAltResult::ErrorDotExpr),
}
}
fn eval_expr(&self, scope: &mut Scope, expr: &Expr) -> Result<Dynamic, EvalAltResult> {
match expr {
Expr::IntegerConstant(i) => Ok(Box::new(*i)),
Expr::FloatConstant(i) => Ok(Box::new(*i)),
Expr::StringConstant(s) => Ok(Box::new(s.clone())),
Expr::CharConstant(c) => Ok(Box::new(*c)),
Expr::Identifier(id) => {
2020-03-01 06:30:22 +01:00
match scope.iter().rev().filter(|(name, _)| id == name).next() {
Some((_, val)) => Ok(val.clone()),
_ => Err(EvalAltResult::ErrorVariableNotFound(id.clone())),
2016-02-29 22:43:45 +01:00
}
}
2020-03-01 06:30:22 +01:00
Expr::Index(id, idx_raw) => {
self.indexed_value(scope, id, idx_raw).map(|(_, _, _, x)| x)
}
Expr::Assignment(ref id, 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) => {
2020-03-01 06:30:22 +01:00
match scope.iter_mut().rev().filter(|(name, _)| n == name).next() {
Some((_, val)) => {
2016-02-29 22:43:45 +01:00
*val = rhs_val;
2020-03-01 06:30:22 +01:00
Ok(Box::new(()))
2016-02-29 22:43:45 +01:00
}
2020-03-01 06:30:22 +01:00
_ => 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) => {
2020-03-01 06:30:22 +01:00
let idx = *match self.eval_expr(scope, &idx_raw)?.downcast_ref::<i64>() {
Some(x) => x,
_ => return Err(EvalAltResult::ErrorIndexExpr),
};
let variable = &mut scope
.iter_mut()
.rev()
.filter(|(name, _)| id == name)
.map(|(_, val)| val)
.next();
let val = match variable {
Some(v) => v,
_ => return Err(EvalAltResult::ErrorVariableNotFound(id.clone())),
};
if let Some(arr) = val.downcast_mut() as Option<&mut Array> {
return if idx < 0 {
Err(EvalAltResult::ErrorArrayBounds(arr.len(), idx))
} else if idx as usize >= arr.len() {
Err(EvalAltResult::ErrorArrayBounds(arr.len(), idx))
} else {
arr[idx as usize] = rhs_val;
Ok(Box::new(()))
};
2016-03-26 18:46:28 +01:00
}
2020-03-01 06:30:22 +01:00
if let Some(s) = val.downcast_mut() as Option<&mut String> {
let s_len = s.chars().count();
return if idx < 0 {
Err(EvalAltResult::ErrorStringBounds(s_len, idx))
} else if idx as usize >= s_len {
Err(EvalAltResult::ErrorStringBounds(s_len, idx))
} else {
// Should be a char
let new_ch = *rhs_val.downcast::<char>().unwrap();
Self::str_replace_char(s, idx as usize, new_ch);
Ok(Box::new(()))
};
}
return Err(EvalAltResult::ErrorIndexExpr);
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(lhs, rhs) => self.get_dot_val(scope, lhs, rhs),
Expr::Array(contents) => {
2016-03-26 18:46:28 +01:00
let mut arr = Vec::new();
2020-03-01 06:30:22 +01:00
contents.iter().try_for_each(|item| {
let arg = self.eval_expr(scope, item)?;
2016-03-26 18:46:28 +01:00
arr.push(arg);
2020-03-01 06:30:22 +01:00
Ok(())
})?;
2016-03-26 18:46:28 +01:00
Ok(Box::new(arr))
}
Expr::FunctionCall(fn_name, args) => self.call_fn_raw(
2017-12-20 12:16:14 +01:00
fn_name.to_owned(),
args.iter()
.map(|ex| self.eval_expr(scope, ex))
.collect::<Result<Array, _>>()?
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<Dynamic, EvalAltResult> {
match stmt {
2020-03-01 06:30:22 +01:00
Stmt::Expr(expr) => self.eval_expr(scope, expr),
Stmt::Block(block) => {
let prev_len = scope.len();
let mut last_result: Result<Dynamic, EvalAltResult> = Ok(Box::new(()));
2016-02-29 22:43:45 +01:00
2020-03-01 06:30:22 +01:00
for block_stmt in block.iter() {
last_result = self.eval_stmt(scope, block_stmt);
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
}
2020-03-01 06:30:22 +01:00
Stmt::If(guard, body) => self
.eval_expr(scope, guard)?
.downcast::<bool>()
.map_err(|_| EvalAltResult::ErrorIfGuard)
.and_then(|guard_val| {
if *guard_val {
self.eval_stmt(scope, body)
} else {
Ok(Box::new(()))
2016-02-29 22:43:45 +01:00
}
2020-03-01 06:30:22 +01:00
}),
Stmt::IfElse(guard, body, else_body) => self
.eval_expr(scope, guard)?
.downcast::<bool>()
.map_err(|_| EvalAltResult::ErrorIfGuard)
.and_then(|guard_val| {
if *guard_val {
self.eval_stmt(scope, body)
} else {
self.eval_stmt(scope, else_body)
2016-03-03 14:20:55 +01:00
}
2020-03-01 06:30:22 +01:00
}),
Stmt::While(guard, body) => loop {
2020-03-01 06:30:22 +01:00
match self.eval_expr(scope, guard)?.downcast::<bool>() {
Ok(guard_val) => {
if *guard_val {
2017-12-20 12:16:14 +01:00
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
}
}
2020-03-01 06:30:22 +01:00
Err(_) => return Err(EvalAltResult::ErrorIfGuard),
2016-02-29 22:43:45 +01:00
}
2017-12-20 12:16:14 +01:00
},
Stmt::Loop(body) => loop {
2017-12-20 12:16:14 +01:00
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
},
Stmt::For(name, expr, body) => {
let arr = self.eval_expr(scope, expr)?;
let tid = Any::type_id(&*arr);
if let Some(iter_fn) = self.type_iterators.get(&tid) {
scope.push((name.clone(), Box::new(())));
let idx = scope.len() - 1;
for a in iter_fn(&arr) {
scope[idx].1 = a;
match self.eval_stmt(scope, body) {
Err(EvalAltResult::LoopBreak) => break,
Err(x) => return Err(x),
_ => (),
}
}
scope.remove(idx);
Ok(Box::new(()))
} else {
2020-03-01 06:30:22 +01:00
return Err(EvalAltResult::ErrorFor);
}
}
2017-10-02 23:44:45 +02:00
Stmt::Break => Err(EvalAltResult::LoopBreak),
Stmt::Return => Err(EvalAltResult::Return(Box::new(()))),
Stmt::ReturnWithVal(a) => {
let result = self.eval_expr(scope, a)?;
2017-10-02 23:44:45 +02:00
Err(EvalAltResult::Return(result))
}
Stmt::Let(name, init) => {
2020-03-01 06:30:22 +01:00
if let Some(v) = init {
let i = self.eval_expr(scope, v)?;
scope.push((name.clone(), i));
} else {
scope.push((name.clone(), Box::new(())));
}
2016-02-29 22:43:45 +01:00
Ok(Box::new(()))
}
}
}
/// Compile a string into an AST
pub fn compile(input: &str) -> Result<AST, ParseError> {
let tokens = lex(input);
let mut peekables = tokens.peekable();
let tree = parse(&mut peekables);
tree
}
/// Compile a file into an AST
2020-03-01 06:30:22 +01:00
pub fn compile_file(filename: &str) -> Result<AST, EvalAltResult> {
use std::fs::File;
use std::io::prelude::*;
2020-03-01 06:30:22 +01:00
if let Ok(mut f) = File::open(filename) {
let mut contents = String::new();
if f.read_to_string(&mut contents).is_ok() {
Self::compile(&contents).map_err(|err| EvalAltResult::ErrorParseError(err))
} else {
2020-03-01 06:30:22 +01:00
Err(EvalAltResult::ErrorCantOpenScriptFile(filename.to_owned()))
}
} else {
2020-03-01 06:30:22 +01:00
Err(EvalAltResult::ErrorCantOpenScriptFile(filename.to_owned()))
}
}
2017-10-30 16:08:44 +01:00
/// Evaluate a file
2020-03-01 06:30:22 +01:00
pub fn eval_file<T: Any + Clone>(&mut self, filename: &str) -> Result<T, EvalAltResult> {
2016-03-17 13:45:48 +01:00
use std::fs::File;
use std::io::prelude::*;
2020-03-01 06:30:22 +01:00
if let Ok(mut f) = File::open(filename) {
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 {
2020-03-01 06:30:22 +01:00
Err(EvalAltResult::ErrorCantOpenScriptFile(filename.to_owned()))
}
} else {
2020-03-01 06:30:22 +01:00
Err(EvalAltResult::ErrorCantOpenScriptFile(filename.to_owned()))
}
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> {
2019-09-18 12:21:07 +02:00
let mut scope = Scope::new();
self.eval_with_scope(&mut scope, input)
}
/// Evaluate a string 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 ast = Self::compile(input).map_err(|err| EvalAltResult::ErrorParseError(err))?;
self.eval_ast_with_scope(scope, &ast)
}
2016-02-29 22:43:45 +01:00
/// Evaluate an AST
pub fn eval_ast<T: Any + Clone>(&mut self, ast: &AST) -> Result<T, EvalAltResult> {
let mut scope = Scope::new();
self.eval_ast_with_scope(&mut scope, ast)
}
2016-02-29 22:43:45 +01:00
/// Evaluate an AST with own scope
pub fn eval_ast_with_scope<T: Any + Clone>(
&mut self,
scope: &mut Scope,
ast: &AST,
) -> Result<T, EvalAltResult> {
let AST(os, fns) = ast;
let mut x: Result<Dynamic, 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-20 12:16:14 +01:00
self.fns.insert(spec, Arc::new(FnIntExt::Int(local_f)));
}
for o in os {
x = match self.eval_stmt(scope, o) {
Ok(v) => Ok(v),
Err(e) => return Err(e),
}
}
2016-03-16 23:32:05 +01:00
let x = x?;
2017-12-20 14:35:44 +01:00
match x.downcast::<T>() {
Ok(out) => Ok(*out),
Err(a) => Err(EvalAltResult::ErrorMismatchOutputType((*a).type_name())),
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
2020-03-01 06:30:22 +01:00
pub fn consume_file(&mut self, filename: &str) -> Result<(), EvalAltResult> {
2017-10-15 17:50:39 +02:00
use std::fs::File;
use std::io::prelude::*;
2020-03-01 06:30:22 +01:00
if let Ok(mut f) = File::open(filename) {
2017-10-15 17:50:39 +02:00
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 {
2020-03-01 06:30:22 +01:00
Err(EvalAltResult::ErrorCantOpenScriptFile(filename.to_owned()))
2017-10-15 17:50:39 +02:00
}
} else {
2020-03-01 06:30:22 +01:00
Err(EvalAltResult::ErrorCantOpenScriptFile(filename.to_owned()))
2017-10-15 17:50:39 +02:00
}
}
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
}
/// Evaluate a string with own scope, but only return errors, if there are any.
2017-10-30 16:08:44 +01:00
/// 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(AST(ref os, ref fns)) => {
2017-10-15 17:50:39 +02:00
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),
}
}
/// Register the default library. That means, numeric types, char, bool
2017-10-30 16:08:44 +01:00
/// String, arithmetics and string concatenations.
2016-03-01 15:40:48 +01:00
pub fn register_default_lib(engine: &mut Engine) {
macro_rules! reg_op {
($engine:expr, $x:expr, $op:expr, $( $y:ty ),*) => (
$(
2019-09-18 12:21:07 +02:00
$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 ),*) => (
$(
2019-09-18 12:21:07 +02:00
$engine.register_fn($x, $op as fn(x: $y)->$y);
2017-10-30 16:08:44 +01:00
)*
)
}
2016-03-01 15:40:48 +01:00
macro_rules! reg_cmp {
($engine:expr, $x:expr, $op:expr, $( $y:ty ),*) => (
$(
2019-09-18 12:21:07 +02:00
$engine.register_fn($x, $op as fn(x: $y, y: $y)->bool);
2016-03-01 15:40:48 +01:00
)*
)
}
macro_rules! reg_func1 {
($engine:expr, $x:expr, $op:expr, $r:ty, $( $y:ty ),*) => (
$(
$engine.register_fn($x, $op as fn(x: $y)->$r);
)*
)
}
macro_rules! reg_func2x {
($engine:expr, $x:expr, $op:expr, $v:ty, $r:ty, $( $y:ty ),*) => (
$(
$engine.register_fn($x, $op as fn(x: $v, y: $y)->$r);
)*
)
}
macro_rules! reg_func2y {
($engine:expr, $x:expr, $op:expr, $v:ty, $r:ty, $( $y:ty ),*) => (
$(
$engine.register_fn($x, $op as fn(y: $y, x: $v)->$r);
)*
)
}
2020-02-25 09:23:59 +01:00
macro_rules! reg_func3 {
($engine:expr, $x:expr, $op:expr, $v:ty, $w:ty, $r:ty, $( $y:ty ),*) => (
$(
$engine.register_fn($x, $op as fn(x: $v, y: $w, z: $y)->$r);
)*
)
}
2019-09-18 12:21:07 +02: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)
}
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);
2020-03-01 06:30:22 +01:00
reg_cmp!(engine, "<", lt, i32, i64, u32, u64, String, char, f32, f64);
reg_cmp!(engine, "<=", lte, i32, i64, u32, u64, String, char, f32, f64);
reg_cmp!(engine, ">", gt, i32, i64, u32, u64, String, char, f32, f64);
reg_cmp!(engine, ">=", gte, i32, i64, u32, u64, String, char, f32, f64);
reg_cmp!(engine, "==", eq, i32, i64, u32, u64, bool, String, char, f32, f64);
reg_cmp!(engine, "!=", ne, i32, i64, u32, u64, bool, String, char, f32, 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)));
// Register conversion functions
engine.register_fn("to_float", |x: i32| x as f64);
engine.register_fn("to_float", |x: u32| x as f64);
engine.register_fn("to_float", |x: i64| x as f64);
engine.register_fn("to_float", |x: u64| x as f64);
engine.register_fn("to_float", |x: f32| x as f64);
engine.register_fn("to_int", |x: i32| x as i64);
engine.register_fn("to_int", |x: u32| x as i64);
engine.register_fn("to_int", |x: u64| x as i64);
engine.register_fn("to_int", |x: f32| x as i64);
engine.register_fn("to_int", |x: f64| x as i64);
2020-03-01 06:30:22 +01:00
engine.register_fn("to_int", |ch: char| ch as i64);
// Register print and debug
2020-02-25 03:40:48 +01:00
fn print_debug<T: Debug>(x: T) -> String {
format!("{:?}", x)
}
2020-02-25 03:40:48 +01:00
fn print<T: Display>(x: T) -> String {
format!("{}", x)
}
2020-02-25 03:40:48 +01:00
reg_func1!(engine, "print", print, String, i32, i64, u32, u64);
2020-03-01 06:30:22 +01:00
reg_func1!(engine, "print", print, String, f32, f64, bool, char, String);
2020-02-25 03:40:48 +01:00
reg_func1!(engine, "print", print_debug, String, Array);
engine.register_fn("print", |_: ()| println!());
2020-02-25 03:40:48 +01:00
reg_func1!(engine, "debug", print_debug, String, i32, i64, u32, u64);
2020-03-01 06:30:22 +01:00
reg_func1!(engine, "debug", print_debug, String, f32, f64, bool, char);
reg_func1!(engine, "debug", print_debug, String, String, Array, ());
2020-03-01 06:30:22 +01:00
// Register array utility functions
2020-02-25 09:23:59 +01:00
fn push<T: Any>(list: &mut Array, item: T) {
list.push(Box::new(item));
}
2020-02-25 09:23:59 +01:00
fn pad<T: Any + Clone>(list: &mut Array, len: i64, item: T) {
if len >= 0 {
while list.len() < len as usize {
push(list, item.clone());
}
}
}
reg_func2x!(engine, "push", push, &mut Array, (), i32, i64, u32, u64);
2020-03-01 06:30:22 +01:00
reg_func2x!(engine, "push", push, &mut Array, (), f32, f64, bool, char);
reg_func2x!(engine, "push", push, &mut Array, (), String, Array, ());
2020-03-01 06:30:22 +01:00
reg_func3!(engine, "pad", pad, &mut Array, i64, (), i32, u32, f32);
reg_func3!(engine, "pad", pad, &mut Array, i64, (), i64, u64, f64);
reg_func3!(engine, "pad", pad, &mut Array, i64, (), bool, char);
2020-02-25 09:23:59 +01:00
reg_func3!(engine, "pad", pad, &mut Array, i64, (), String, Array, ());
engine.register_dynamic_fn("pop", |list: &mut Array| list.pop().unwrap_or(Box::new(())));
engine.register_dynamic_fn("shift", |list: &mut Array| {
if list.len() > 0 {
list.remove(0)
} else {
Box::new(())
}
});
2020-03-01 06:30:22 +01:00
engine.register_fn("len", |list: &mut Array| -> i64 { list.len() as i64 });
2020-02-25 09:23:59 +01:00
engine.register_fn("truncate", |list: &mut Array, len: i64| {
if len >= 0 {
list.truncate(len as usize);
}
});
// Register string concatenate functions
fn prepend<T: Display>(x: T, y: String) -> String {
format!("{}{}", x, y)
}
fn append<T: Display>(x: String, y: T) -> String {
format!("{}{}", x, y)
}
2020-03-01 06:30:22 +01:00
reg_func2x!(engine, "+", append, String, String, i32, i64, u32, u64, f32, f64, bool, char);
engine.register_fn("+", |x: String, y: Array| format!("{}{:?}", x, y));
engine.register_fn("+", |x: String, _: ()| format!("{}", x));
2020-03-01 06:30:22 +01:00
reg_func2y!(engine, "+", prepend, String, String, i32, i64, u32, u64, f32, f64, bool, char);
engine.register_fn("+", |x: Array, y: String| format!("{:?}{}", x, y));
engine.register_fn("+", |_: (), y: String| format!("{}", y));
2020-03-01 06:30:22 +01:00
// Register string utility functions
engine.register_fn("len", |s: &mut String| -> i64 { s.chars().count() as i64 });
engine.register_fn("truncate", |s: &mut String, len: i64| {
if len >= 0 {
s.truncate(len as usize);
}
});
engine.register_fn("pad", |s: &mut String, len: i64, ch: char| {
let gap = s.chars().count() - len as usize;
for _ in 0..gap {
s.push(ch);
}
});
engine.register_fn(
"replace",
|s: &mut String, pattern: String, replace: String| {
let new_str = s.replace(&pattern, &replace);
s.truncate(0);
s.push_str(&new_str);
},
);
// Register array iterator
engine.register_iterator::<Array, _>(|a| {
Box::new(a.downcast_ref::<Array>().unwrap().clone().into_iter())
});
// Register range function
use std::ops::Range;
engine.register_iterator::<Range<i64>, _>(|a| {
Box::new(
a.downcast_ref::<Range<i64>>()
.unwrap()
.clone()
.map(|n| Box::new(n) as Dynamic),
)
});
engine.register_fn("range", |i1: i64, i2: i64| (i1..i2));
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 {
2019-09-30 19:58:01 +02:00
fns: HashMap::new(),
type_iterators: HashMap::new(),
2020-02-25 03:40:48 +01:00
on_print: Box::new(|x: &str| println!("{}", x)),
on_debug: Box::new(|x: &str| println!("{}", x)),
2017-12-20 12:16:14 +01:00
};
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
}
2020-02-25 03:40:48 +01:00
/// Overrides `on_print`
pub fn on_print(&mut self, callback: impl Fn(&str) + 'static) {
self.on_print = Box::new(callback);
}
/// Overrides `on_debug`
pub fn on_debug(&mut self, callback: impl Fn(&str) + 'static) {
self.on_debug = Box::new(callback);
}
2016-03-01 15:40:48 +01:00
}