2020-03-08 12:54:02 +01:00
|
|
|
//! Main module defining the script evaluation `Engine`.
|
2016-02-29 22:43:45 +01:00
|
|
|
|
2020-04-12 17:00:06 +02:00
|
|
|
use crate::any::{Dynamic, Union};
|
2020-04-21 17:01:10 +02:00
|
|
|
use crate::calc_fn_hash;
|
2020-04-07 07:23:06 +02:00
|
|
|
use crate::error::ParseErrorType;
|
2020-05-05 06:24:13 +02:00
|
|
|
use crate::module::Module;
|
2020-04-10 06:16:39 +02:00
|
|
|
use crate::optimize::OptimizationLevel;
|
2020-04-20 18:11:25 +02:00
|
|
|
use crate::packages::{CorePackage, Package, PackageLibrary, StandardPackage};
|
2020-05-05 09:00:10 +02:00
|
|
|
use crate::parser::{Expr, FnDef, ModuleRef, ReturnType, Stmt, AST};
|
2020-03-04 15:00:01 +01:00
|
|
|
use crate::result::EvalAltResult;
|
2020-04-27 16:49:09 +02:00
|
|
|
use crate::scope::{EntryType as ScopeEntryType, Scope};
|
2020-04-15 16:21:23 +02:00
|
|
|
use crate::token::Position;
|
2020-05-05 06:24:13 +02:00
|
|
|
use crate::utils::{calc_fn_def, StaticVec};
|
2020-03-11 06:28:12 +01:00
|
|
|
|
2020-03-17 19:26:11 +01:00
|
|
|
use crate::stdlib::{
|
2020-04-12 17:00:06 +02:00
|
|
|
any::TypeId,
|
2020-03-17 19:26:11 +01:00
|
|
|
boxed::Box,
|
2020-04-24 06:39:24 +02:00
|
|
|
collections::HashMap,
|
2020-03-17 19:26:11 +01:00
|
|
|
format,
|
2020-03-10 03:07:44 +01:00
|
|
|
iter::once,
|
2020-04-26 12:04:07 +02:00
|
|
|
mem,
|
2020-05-04 17:07:42 +02:00
|
|
|
num::NonZeroUsize,
|
2020-04-04 16:00:44 +02:00
|
|
|
ops::{Deref, DerefMut},
|
|
|
|
rc::Rc,
|
2020-03-17 19:26:11 +01:00
|
|
|
string::{String, ToString},
|
2020-03-10 03:07:44 +01:00
|
|
|
sync::Arc,
|
2020-03-17 19:26:11 +01:00
|
|
|
vec::Vec,
|
2020-03-10 03:07:44 +01:00
|
|
|
};
|
2020-02-23 15:48:46 +01:00
|
|
|
|
2020-03-04 15:00:01 +01:00
|
|
|
/// An dynamic array of `Dynamic` values.
|
2020-04-03 13:42:01 +02:00
|
|
|
///
|
|
|
|
/// Not available under the `no_index` feature.
|
2020-02-25 08:02:27 +01:00
|
|
|
pub type Array = Vec<Dynamic>;
|
2020-03-04 15:00:01 +01:00
|
|
|
|
2020-04-03 13:42:01 +02:00
|
|
|
/// An dynamic hash map of `Dynamic` values with `String` keys.
|
|
|
|
///
|
|
|
|
/// Not available under the `no_object` feature.
|
2020-03-29 17:53:35 +02:00
|
|
|
pub type Map = HashMap<String, Dynamic>;
|
|
|
|
|
2020-04-12 17:00:06 +02:00
|
|
|
pub type FnCallArgs<'a> = [&'a mut Dynamic];
|
2016-02-29 22:43:45 +01:00
|
|
|
|
2020-04-03 11:17:00 +02:00
|
|
|
#[cfg(feature = "sync")]
|
2020-04-17 18:14:33 +02:00
|
|
|
pub type FnAny =
|
|
|
|
dyn Fn(&mut FnCallArgs, Position) -> Result<Dynamic, Box<EvalAltResult>> + Send + Sync;
|
2020-04-03 11:17:00 +02:00
|
|
|
#[cfg(not(feature = "sync"))]
|
2020-04-17 18:14:33 +02:00
|
|
|
pub type FnAny = dyn Fn(&mut FnCallArgs, Position) -> Result<Dynamic, Box<EvalAltResult>>;
|
2020-03-08 12:54:02 +01:00
|
|
|
|
2020-04-03 11:17:00 +02:00
|
|
|
#[cfg(feature = "sync")]
|
2020-04-24 16:54:56 +02:00
|
|
|
pub type IteratorFn = dyn Fn(Dynamic) -> Box<dyn Iterator<Item = Dynamic>> + Send + Sync;
|
2020-04-03 11:17:00 +02:00
|
|
|
#[cfg(not(feature = "sync"))]
|
2020-04-24 16:54:56 +02:00
|
|
|
pub type IteratorFn = dyn Fn(Dynamic) -> Box<dyn Iterator<Item = Dynamic>>;
|
2020-03-08 12:54:02 +01:00
|
|
|
|
2020-04-07 17:13:47 +02:00
|
|
|
#[cfg(debug_assertions)]
|
2020-04-17 13:00:52 +02:00
|
|
|
pub const MAX_CALL_STACK_DEPTH: usize = 28;
|
2020-04-07 17:13:47 +02:00
|
|
|
|
|
|
|
#[cfg(not(debug_assertions))]
|
|
|
|
pub const MAX_CALL_STACK_DEPTH: usize = 256;
|
|
|
|
|
2020-04-27 14:25:20 +02:00
|
|
|
#[cfg(not(feature = "only_i32"))]
|
|
|
|
#[cfg(not(feature = "only_i64"))]
|
|
|
|
const FUNCTIONS_COUNT: usize = 512;
|
|
|
|
|
|
|
|
#[cfg(any(feature = "only_i32", feature = "only_i64"))]
|
|
|
|
const FUNCTIONS_COUNT: usize = 256;
|
|
|
|
|
2020-04-01 03:51:33 +02:00
|
|
|
pub const KEYWORD_PRINT: &str = "print";
|
|
|
|
pub const KEYWORD_DEBUG: &str = "debug";
|
|
|
|
pub const KEYWORD_TYPE_OF: &str = "type_of";
|
|
|
|
pub const KEYWORD_EVAL: &str = "eval";
|
|
|
|
pub const FUNC_TO_STRING: &str = "to_string";
|
|
|
|
pub const FUNC_GETTER: &str = "get$";
|
|
|
|
pub const FUNC_SETTER: &str = "set$";
|
2020-03-03 10:28:38 +01:00
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
/// A type that encapsulates a mutation target for an expression with side effects.
|
|
|
|
enum Target<'a> {
|
|
|
|
/// The target is a mutable reference to a `Dynamic` value somewhere.
|
|
|
|
Ref(&'a mut Dynamic),
|
|
|
|
/// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects).
|
2020-04-26 13:37:32 +02:00
|
|
|
Value(Box<Dynamic>),
|
2020-04-26 12:04:07 +02:00
|
|
|
/// The target is a character inside a String.
|
2020-04-27 14:25:20 +02:00
|
|
|
/// This is necessary because directly pointing to a char inside a String is impossible.
|
2020-04-26 12:04:07 +02:00
|
|
|
StringChar(Box<(&'a mut Dynamic, usize, Dynamic)>),
|
2020-03-30 16:19:37 +02:00
|
|
|
}
|
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
impl Target<'_> {
|
|
|
|
/// Get the value of the `Target` as a `Dynamic`.
|
2020-04-30 16:52:36 +02:00
|
|
|
pub fn clone_into_dynamic(self) -> Dynamic {
|
2020-03-30 16:19:37 +02:00
|
|
|
match self {
|
2020-04-26 12:04:07 +02:00
|
|
|
Target::Ref(r) => r.clone(),
|
2020-04-26 13:37:32 +02:00
|
|
|
Target::Value(v) => *v,
|
2020-04-26 12:04:07 +02:00
|
|
|
Target::StringChar(s) => s.2,
|
2020-03-30 16:19:37 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
/// Update the value of the `Target`.
|
|
|
|
pub fn set_value(&mut self, new_val: Dynamic, pos: Position) -> Result<(), Box<EvalAltResult>> {
|
2020-03-30 16:19:37 +02:00
|
|
|
match self {
|
2020-04-26 12:04:07 +02:00
|
|
|
Target::Ref(r) => **r = new_val,
|
|
|
|
Target::Value(_) => {
|
|
|
|
return Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(pos)))
|
|
|
|
}
|
|
|
|
Target::StringChar(x) => match x.0 {
|
|
|
|
Dynamic(Union::Str(s)) => {
|
|
|
|
// Replace the character at the specified index position
|
|
|
|
let new_ch = new_val
|
|
|
|
.as_char()
|
|
|
|
.map_err(|_| EvalAltResult::ErrorCharMismatch(pos))?;
|
|
|
|
|
|
|
|
let mut chars: Vec<char> = s.chars().collect();
|
2020-04-30 16:52:36 +02:00
|
|
|
let ch = chars[x.1];
|
2020-04-26 12:04:07 +02:00
|
|
|
|
|
|
|
// See if changed - if so, update the String
|
|
|
|
if ch != new_ch {
|
|
|
|
chars[x.1] = new_ch;
|
|
|
|
s.clear();
|
|
|
|
chars.iter().for_each(|&ch| s.push(ch));
|
|
|
|
}
|
|
|
|
}
|
2020-05-04 11:43:54 +02:00
|
|
|
_ => unreachable!(),
|
2020-04-26 12:04:07 +02:00
|
|
|
},
|
2020-03-30 16:19:37 +02:00
|
|
|
}
|
2020-04-26 12:04:07 +02:00
|
|
|
|
|
|
|
Ok(())
|
2020-03-30 16:19:37 +02:00
|
|
|
}
|
2020-03-05 13:28:03 +01:00
|
|
|
}
|
|
|
|
|
2020-04-16 04:24:30 +02:00
|
|
|
impl<'a> From<&'a mut Dynamic> for Target<'a> {
|
|
|
|
fn from(value: &'a mut Dynamic) -> Self {
|
2020-04-26 12:04:07 +02:00
|
|
|
Self::Ref(value)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl<T: Into<Dynamic>> From<T> for Target<'_> {
|
|
|
|
fn from(value: T) -> Self {
|
2020-04-26 13:37:32 +02:00
|
|
|
Self::Value(Box::new(value.into()))
|
2020-04-16 04:24:30 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-28 17:05:03 +02:00
|
|
|
/// A type that holds all the current states of the Engine.
|
2020-05-05 06:24:13 +02:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
2020-04-28 17:05:03 +02:00
|
|
|
pub struct State {
|
|
|
|
/// Normally, access to variables are parsed with a relative offset into the scope to avoid a lookup.
|
|
|
|
/// In some situation, e.g. after running an `eval` statement, subsequent offsets may become mis-aligned.
|
|
|
|
/// When that happens, this flag is turned on to force a scope lookup by name.
|
|
|
|
pub always_search: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl State {
|
2020-04-29 10:11:54 +02:00
|
|
|
/// Create a new `State`.
|
2020-04-28 17:05:03 +02:00
|
|
|
pub fn new() -> Self {
|
|
|
|
Self {
|
|
|
|
always_search: false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-21 17:01:10 +02:00
|
|
|
/// A type that holds a library (`HashMap`) of script-defined functions.
|
2020-03-26 13:26:05 +01:00
|
|
|
///
|
|
|
|
/// Since script-defined functions have `Dynamic` parameters, functions with the same name
|
|
|
|
/// and number of parameters are considered equivalent.
|
|
|
|
///
|
2020-04-21 17:01:10 +02:00
|
|
|
/// The key of the `HashMap` is a `u64` hash calculated by the function `calc_fn_def`.
|
2020-05-05 09:00:10 +02:00
|
|
|
#[derive(Debug, Clone, Default)]
|
2020-04-04 16:00:44 +02:00
|
|
|
pub struct FunctionsLib(
|
2020-04-16 17:58:57 +02:00
|
|
|
#[cfg(feature = "sync")] HashMap<u64, Arc<FnDef>>,
|
|
|
|
#[cfg(not(feature = "sync"))] HashMap<u64, Rc<FnDef>>,
|
2020-04-04 16:00:44 +02:00
|
|
|
);
|
2020-03-26 13:26:05 +01:00
|
|
|
|
|
|
|
impl FunctionsLib {
|
|
|
|
/// Create a new `FunctionsLib`.
|
|
|
|
pub fn new() -> Self {
|
2020-05-05 09:00:10 +02:00
|
|
|
Default::default()
|
2020-03-26 13:26:05 +01:00
|
|
|
}
|
2020-04-04 16:00:44 +02:00
|
|
|
/// Create a new `FunctionsLib` from a collection of `FnDef`.
|
|
|
|
pub fn from_vec(vec: Vec<FnDef>) -> Self {
|
2020-04-16 17:58:57 +02:00
|
|
|
FunctionsLib(
|
|
|
|
vec.into_iter()
|
|
|
|
.map(|f| {
|
|
|
|
let hash = calc_fn_def(&f.name, f.params.len());
|
|
|
|
|
|
|
|
#[cfg(feature = "sync")]
|
|
|
|
{
|
|
|
|
(hash, Arc::new(f))
|
|
|
|
}
|
|
|
|
#[cfg(not(feature = "sync"))]
|
|
|
|
{
|
|
|
|
(hash, Rc::new(f))
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect(),
|
|
|
|
)
|
2020-04-04 16:00:44 +02:00
|
|
|
}
|
2020-03-26 13:26:05 +01:00
|
|
|
/// Does a certain function exist in the `FunctionsLib`?
|
|
|
|
pub fn has_function(&self, name: &str, params: usize) -> bool {
|
2020-04-16 17:58:57 +02:00
|
|
|
self.contains_key(&calc_fn_def(name, params))
|
2020-03-26 13:26:05 +01:00
|
|
|
}
|
|
|
|
/// Get a function definition from the `FunctionsLib`.
|
2020-04-04 16:00:44 +02:00
|
|
|
pub fn get_function(&self, name: &str, params: usize) -> Option<&FnDef> {
|
2020-04-16 17:58:57 +02:00
|
|
|
self.get(&calc_fn_def(name, params)).map(|f| f.as_ref())
|
2020-03-26 13:26:05 +01:00
|
|
|
}
|
2020-04-04 16:00:44 +02:00
|
|
|
/// Merge another `FunctionsLib` into this `FunctionsLib`.
|
|
|
|
pub fn merge(&self, other: &Self) -> Self {
|
|
|
|
if self.is_empty() {
|
|
|
|
other.clone()
|
|
|
|
} else if other.is_empty() {
|
|
|
|
self.clone()
|
|
|
|
} else {
|
|
|
|
let mut functions = self.clone();
|
2020-04-19 07:40:11 +02:00
|
|
|
functions.extend(other.iter().map(|(hash, fn_def)| (*hash, fn_def.clone())));
|
2020-04-04 16:00:44 +02:00
|
|
|
functions
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Deref for FunctionsLib {
|
|
|
|
#[cfg(feature = "sync")]
|
2020-04-16 17:58:57 +02:00
|
|
|
type Target = HashMap<u64, Arc<FnDef>>;
|
2020-04-04 16:00:44 +02:00
|
|
|
#[cfg(not(feature = "sync"))]
|
2020-04-16 17:58:57 +02:00
|
|
|
type Target = HashMap<u64, Rc<FnDef>>;
|
2020-04-04 16:00:44 +02:00
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DerefMut for FunctionsLib {
|
|
|
|
#[cfg(feature = "sync")]
|
2020-04-16 17:58:57 +02:00
|
|
|
fn deref_mut(&mut self) -> &mut HashMap<u64, Arc<FnDef>> {
|
2020-04-04 16:00:44 +02:00
|
|
|
&mut self.0
|
|
|
|
}
|
|
|
|
#[cfg(not(feature = "sync"))]
|
2020-04-16 17:58:57 +02:00
|
|
|
fn deref_mut(&mut self) -> &mut HashMap<u64, Rc<FnDef>> {
|
2020-04-04 16:00:44 +02:00
|
|
|
&mut self.0
|
|
|
|
}
|
2020-03-26 13:26:05 +01:00
|
|
|
}
|
|
|
|
|
2020-03-04 15:00:01 +01:00
|
|
|
/// Rhai main scripting engine.
|
2017-10-30 16:08:44 +01:00
|
|
|
///
|
2020-03-19 06:52:10 +01:00
|
|
|
/// ```
|
2020-04-21 17:25:12 +02:00
|
|
|
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
|
2017-10-30 16:08:44 +01:00
|
|
|
/// use rhai::Engine;
|
|
|
|
///
|
2020-04-07 07:23:06 +02:00
|
|
|
/// let engine = Engine::new();
|
2017-10-30 16:08:44 +01:00
|
|
|
///
|
2020-03-09 14:57:07 +01:00
|
|
|
/// let result = engine.eval::<i64>("40 + 2")?;
|
|
|
|
///
|
|
|
|
/// println!("Answer: {}", result); // prints 42
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
2017-10-30 16:08:44 +01:00
|
|
|
/// ```
|
2020-04-03 13:42:01 +02:00
|
|
|
///
|
|
|
|
/// Currently, `Engine` is neither `Send` nor `Sync`. Turn on the `sync` feature to make it `Send + Sync`.
|
2020-04-16 17:31:48 +02:00
|
|
|
pub struct Engine {
|
2020-04-20 18:11:25 +02:00
|
|
|
/// A collection of all library packages loaded into the engine.
|
|
|
|
pub(crate) packages: Vec<PackageLibrary>,
|
2020-04-21 17:01:10 +02:00
|
|
|
/// A `HashMap` containing all compiled functions known to the engine.
|
|
|
|
///
|
|
|
|
/// The key of the `HashMap` is a `u64` hash calculated by the function `crate::calc_fn_hash`.
|
2020-04-19 07:40:11 +02:00
|
|
|
pub(crate) functions: HashMap<u64, Box<FnAny>>,
|
2020-04-04 16:00:44 +02:00
|
|
|
|
2020-03-27 07:34:01 +01:00
|
|
|
/// A hashmap containing all iterators known to the engine.
|
2020-04-19 07:40:11 +02:00
|
|
|
pub(crate) type_iterators: HashMap<TypeId, Box<IteratorFn>>,
|
2020-03-27 07:34:01 +01:00
|
|
|
/// A hashmap mapping type names to pretty-print names.
|
2020-04-27 15:28:31 +02:00
|
|
|
pub(crate) type_names: HashMap<String, String>,
|
2020-03-02 07:28:42 +01:00
|
|
|
|
2020-03-30 16:19:37 +02:00
|
|
|
/// Closure for implementing the `print` command.
|
2020-04-03 11:17:00 +02:00
|
|
|
#[cfg(feature = "sync")]
|
2020-04-27 15:28:31 +02:00
|
|
|
pub(crate) print: Box<dyn Fn(&str) + Send + Sync + 'static>,
|
2020-04-04 16:00:44 +02:00
|
|
|
/// Closure for implementing the `print` command.
|
2020-04-03 11:17:00 +02:00
|
|
|
#[cfg(not(feature = "sync"))]
|
2020-04-27 15:28:31 +02:00
|
|
|
pub(crate) print: Box<dyn Fn(&str) + 'static>,
|
2020-04-03 11:17:00 +02:00
|
|
|
|
2020-03-30 16:19:37 +02:00
|
|
|
/// Closure for implementing the `debug` command.
|
2020-04-03 11:17:00 +02:00
|
|
|
#[cfg(feature = "sync")]
|
2020-04-27 15:28:31 +02:00
|
|
|
pub(crate) debug: Box<dyn Fn(&str) + Send + Sync + 'static>,
|
2020-04-04 16:00:44 +02:00
|
|
|
/// Closure for implementing the `debug` command.
|
2020-04-03 11:17:00 +02:00
|
|
|
#[cfg(not(feature = "sync"))]
|
2020-04-27 15:28:31 +02:00
|
|
|
pub(crate) debug: Box<dyn Fn(&str) + 'static>,
|
2020-03-27 07:34:01 +01:00
|
|
|
|
|
|
|
/// Optimize the AST after compilation.
|
|
|
|
pub(crate) optimization_level: OptimizationLevel,
|
|
|
|
|
|
|
|
/// Maximum levels of call-stack to prevent infinite recursion.
|
2020-04-07 17:13:47 +02:00
|
|
|
///
|
2020-04-17 18:14:33 +02:00
|
|
|
/// Defaults to 28 for debug builds and 256 for non-debug builds.
|
2020-03-27 07:34:01 +01:00
|
|
|
pub(crate) max_call_stack_depth: usize,
|
2017-12-20 12:16:14 +01:00
|
|
|
}
|
|
|
|
|
2020-04-16 17:31:48 +02:00
|
|
|
impl Default for Engine {
|
2020-03-25 04:27:18 +01:00
|
|
|
fn default() -> Self {
|
2020-03-09 14:57:07 +01:00
|
|
|
// Create the new scripting Engine
|
2020-04-20 18:11:25 +02:00
|
|
|
let mut engine = Self {
|
2020-05-05 09:00:10 +02:00
|
|
|
packages: Default::default(),
|
2020-04-19 07:40:11 +02:00
|
|
|
functions: HashMap::with_capacity(FUNCTIONS_COUNT),
|
2020-05-05 09:00:10 +02:00
|
|
|
type_iterators: Default::default(),
|
|
|
|
type_names: Default::default(),
|
2020-04-08 04:19:03 +02:00
|
|
|
|
|
|
|
// default print/debug implementations
|
2020-04-27 15:28:31 +02:00
|
|
|
print: Box::new(default_print),
|
|
|
|
debug: Box::new(default_print),
|
2020-03-16 05:40:42 +01:00
|
|
|
|
2020-04-08 04:19:03 +02:00
|
|
|
// optimization level
|
2020-04-10 06:16:39 +02:00
|
|
|
#[cfg(feature = "no_optimize")]
|
|
|
|
optimization_level: OptimizationLevel::None,
|
|
|
|
|
2020-03-16 05:40:42 +01:00
|
|
|
#[cfg(not(feature = "no_optimize"))]
|
|
|
|
#[cfg(not(feature = "optimize_full"))]
|
|
|
|
optimization_level: OptimizationLevel::Simple,
|
|
|
|
|
|
|
|
#[cfg(not(feature = "no_optimize"))]
|
|
|
|
#[cfg(feature = "optimize_full")]
|
|
|
|
optimization_level: OptimizationLevel::Full,
|
2020-03-27 07:34:01 +01:00
|
|
|
|
|
|
|
max_call_stack_depth: MAX_CALL_STACK_DEPTH,
|
2020-03-09 14:57:07 +01:00
|
|
|
};
|
|
|
|
|
2020-04-20 18:11:25 +02:00
|
|
|
#[cfg(feature = "no_stdlib")]
|
|
|
|
engine.load_package(CorePackage::new().get());
|
2020-03-09 14:57:07 +01:00
|
|
|
|
|
|
|
#[cfg(not(feature = "no_stdlib"))]
|
2020-04-20 18:11:25 +02:00
|
|
|
engine.load_package(StandardPackage::new().get());
|
2020-03-09 14:57:07 +01:00
|
|
|
|
|
|
|
engine
|
|
|
|
}
|
2020-03-25 04:27:18 +01:00
|
|
|
}
|
|
|
|
|
2020-03-30 10:10:50 +02:00
|
|
|
/// Make getter function
|
|
|
|
pub fn make_getter(id: &str) -> String {
|
|
|
|
format!("{}{}", FUNC_GETTER, id)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Extract the property name from a getter function name.
|
|
|
|
fn extract_prop_from_getter(fn_name: &str) -> Option<&str> {
|
2020-04-10 06:16:39 +02:00
|
|
|
#[cfg(not(feature = "no_object"))]
|
|
|
|
{
|
|
|
|
if fn_name.starts_with(FUNC_GETTER) {
|
|
|
|
Some(&fn_name[FUNC_GETTER.len()..])
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
#[cfg(feature = "no_object")]
|
|
|
|
{
|
2020-03-30 10:10:50 +02:00
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Make setter function
|
|
|
|
pub fn make_setter(id: &str) -> String {
|
|
|
|
format!("{}{}", FUNC_SETTER, id)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Extract the property name from a setter function name.
|
|
|
|
fn extract_prop_from_setter(fn_name: &str) -> Option<&str> {
|
2020-04-10 06:16:39 +02:00
|
|
|
#[cfg(not(feature = "no_object"))]
|
|
|
|
{
|
|
|
|
if fn_name.starts_with(FUNC_SETTER) {
|
|
|
|
Some(&fn_name[FUNC_SETTER.len()..])
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
#[cfg(feature = "no_object")]
|
|
|
|
{
|
2020-03-30 10:10:50 +02:00
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-19 12:33:02 +02:00
|
|
|
/// Print/debug to stdout
|
|
|
|
fn default_print(s: &str) {
|
|
|
|
#[cfg(not(feature = "no_std"))]
|
|
|
|
println!("{}", s);
|
|
|
|
}
|
|
|
|
|
2020-05-04 17:07:42 +02:00
|
|
|
/// Search for a variable within the scope
|
2020-05-05 04:39:12 +02:00
|
|
|
fn search_scope<'a>(
|
2020-04-27 03:36:31 +02:00
|
|
|
scope: &'a mut Scope,
|
2020-04-27 14:43:55 +02:00
|
|
|
name: &str,
|
2020-05-05 06:24:13 +02:00
|
|
|
modules: &ModuleRef,
|
2020-05-04 17:07:42 +02:00
|
|
|
index: Option<NonZeroUsize>,
|
2020-05-04 11:43:54 +02:00
|
|
|
pos: Position,
|
2020-04-27 03:36:31 +02:00
|
|
|
) -> Result<(&'a mut Dynamic, ScopeEntryType), Box<EvalAltResult>> {
|
2020-05-05 04:39:12 +02:00
|
|
|
if let Some(modules) = modules {
|
2020-05-05 09:00:10 +02:00
|
|
|
let (id, root_pos) = modules.get(0); // First module
|
2020-05-05 04:39:12 +02:00
|
|
|
|
2020-05-05 09:00:10 +02:00
|
|
|
let module = if let Some(index) = index {
|
2020-05-05 04:39:12 +02:00
|
|
|
scope
|
|
|
|
.get_mut(scope.len() - index.get())
|
|
|
|
.0
|
|
|
|
.downcast_mut::<Module>()
|
|
|
|
.unwrap()
|
|
|
|
} else {
|
|
|
|
scope
|
|
|
|
.find_module(id)
|
|
|
|
.ok_or_else(|| Box::new(EvalAltResult::ErrorModuleNotFound(id.into(), *root_pos)))?
|
|
|
|
};
|
2020-05-04 17:07:42 +02:00
|
|
|
|
2020-05-05 09:00:10 +02:00
|
|
|
Ok((
|
|
|
|
module.get_qualified_variable_mut(name, modules.as_ref(), pos)?,
|
|
|
|
// Module variables are constant
|
|
|
|
ScopeEntryType::Constant,
|
|
|
|
))
|
2020-05-04 17:07:42 +02:00
|
|
|
} else {
|
2020-05-05 04:39:12 +02:00
|
|
|
let index = if let Some(index) = index {
|
|
|
|
scope.len() - index.get()
|
|
|
|
} else {
|
|
|
|
scope
|
|
|
|
.get_index(name)
|
|
|
|
.ok_or_else(|| Box::new(EvalAltResult::ErrorVariableNotFound(name.into(), pos)))?
|
|
|
|
.0
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok(scope.get_mut(index))
|
2020-05-04 11:43:54 +02:00
|
|
|
}
|
2020-04-19 12:33:02 +02:00
|
|
|
}
|
|
|
|
|
2020-04-16 17:31:48 +02:00
|
|
|
impl Engine {
|
2020-03-25 04:27:18 +01:00
|
|
|
/// Create a new `Engine`
|
|
|
|
pub fn new() -> Self {
|
|
|
|
Default::default()
|
|
|
|
}
|
2020-03-09 14:57:07 +01:00
|
|
|
|
2020-04-20 18:11:25 +02:00
|
|
|
/// Create a new `Engine` with _no_ built-in functions.
|
|
|
|
/// Use the `load_package` method to load packages of functions.
|
2020-04-04 07:05:20 +02:00
|
|
|
pub fn new_raw() -> Self {
|
2020-04-20 18:11:25 +02:00
|
|
|
Self {
|
2020-05-05 09:00:10 +02:00
|
|
|
packages: Default::default(),
|
2020-04-19 07:40:11 +02:00
|
|
|
functions: HashMap::with_capacity(FUNCTIONS_COUNT / 2),
|
2020-05-05 09:00:10 +02:00
|
|
|
type_iterators: Default::default(),
|
|
|
|
type_names: Default::default(),
|
2020-04-27 15:28:31 +02:00
|
|
|
print: Box::new(|_| {}),
|
|
|
|
debug: Box::new(|_| {}),
|
2020-04-04 07:05:20 +02:00
|
|
|
|
2020-04-10 06:16:39 +02:00
|
|
|
#[cfg(feature = "no_optimize")]
|
|
|
|
optimization_level: OptimizationLevel::None,
|
|
|
|
|
2020-04-04 07:05:20 +02:00
|
|
|
#[cfg(not(feature = "no_optimize"))]
|
|
|
|
#[cfg(not(feature = "optimize_full"))]
|
|
|
|
optimization_level: OptimizationLevel::Simple,
|
|
|
|
|
|
|
|
#[cfg(not(feature = "no_optimize"))]
|
|
|
|
#[cfg(feature = "optimize_full")]
|
|
|
|
optimization_level: OptimizationLevel::Full,
|
|
|
|
|
|
|
|
max_call_stack_depth: MAX_CALL_STACK_DEPTH,
|
2020-04-20 18:11:25 +02:00
|
|
|
}
|
|
|
|
}
|
2020-04-04 07:05:20 +02:00
|
|
|
|
2020-04-21 17:01:10 +02:00
|
|
|
/// Load a new package into the `Engine`.
|
|
|
|
///
|
|
|
|
/// When searching for functions, packages loaded later are preferred.
|
|
|
|
/// In other words, loaded packages are searched in reverse order.
|
2020-04-20 18:11:25 +02:00
|
|
|
pub fn load_package(&mut self, package: PackageLibrary) {
|
2020-04-21 17:01:10 +02:00
|
|
|
// Push the package to the top - packages are searched in reverse order
|
2020-04-20 18:11:25 +02:00
|
|
|
self.packages.insert(0, package);
|
2020-04-04 07:05:20 +02:00
|
|
|
}
|
|
|
|
|
2020-03-15 15:39:58 +01:00
|
|
|
/// Control whether and how the `Engine` will optimize an AST after compilation
|
2020-04-03 13:42:01 +02:00
|
|
|
///
|
|
|
|
/// Not available under the `no_optimize` feature.
|
2020-03-15 15:39:58 +01:00
|
|
|
#[cfg(not(feature = "no_optimize"))]
|
|
|
|
pub fn set_optimization_level(&mut self, optimization_level: OptimizationLevel) {
|
|
|
|
self.optimization_level = optimization_level
|
|
|
|
}
|
|
|
|
|
2020-03-27 07:34:01 +01:00
|
|
|
/// Set the maximum levels of function calls allowed for a script in order to avoid
|
|
|
|
/// infinite recursion and stack overflows.
|
|
|
|
pub fn set_max_call_levels(&mut self, levels: usize) {
|
|
|
|
self.max_call_stack_depth = levels
|
|
|
|
}
|
|
|
|
|
2020-04-01 03:51:33 +02:00
|
|
|
/// Universal method for calling functions either registered with the `Engine` or written in Rhai
|
2020-05-05 04:39:12 +02:00
|
|
|
// TODO - handle moduled function call
|
2020-03-04 15:00:01 +01:00
|
|
|
pub(crate) fn call_fn_raw(
|
2020-04-07 07:23:06 +02:00
|
|
|
&self,
|
2020-04-05 06:17:31 +02:00
|
|
|
scope: Option<&mut Scope>,
|
2020-04-27 14:43:55 +02:00
|
|
|
fn_lib: &FunctionsLib,
|
2020-03-04 15:00:01 +01:00
|
|
|
fn_name: &str,
|
2020-05-05 04:39:12 +02:00
|
|
|
modules: &ModuleRef,
|
2020-03-26 03:56:28 +01:00
|
|
|
args: &mut FnCallArgs,
|
2020-03-08 12:54:02 +01:00
|
|
|
def_val: Option<&Dynamic>,
|
2020-03-02 15:13:14 +01:00
|
|
|
pos: Position,
|
2020-03-27 07:34:01 +01:00
|
|
|
level: usize,
|
2020-04-17 18:14:33 +02:00
|
|
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
2020-04-07 17:13:47 +02:00
|
|
|
// Check for stack overflow
|
|
|
|
if level > self.max_call_stack_depth {
|
2020-04-17 18:14:33 +02:00
|
|
|
return Err(Box::new(EvalAltResult::ErrorStackOverflow(pos)));
|
2020-04-07 17:13:47 +02:00
|
|
|
}
|
|
|
|
|
2020-03-11 16:43:04 +01:00
|
|
|
// First search in script-defined functions (can override built-in)
|
2020-04-27 14:43:55 +02:00
|
|
|
if let Some(fn_def) = fn_lib.get_function(fn_name, args.len()) {
|
2020-04-24 06:39:24 +02:00
|
|
|
return self.call_fn_from_lib(scope, fn_lib, fn_def, args, pos, level);
|
2020-03-19 12:53:42 +01:00
|
|
|
}
|
|
|
|
|
2020-03-15 15:39:58 +01:00
|
|
|
// Search built-in's and external functions
|
2020-04-21 17:01:10 +02:00
|
|
|
let fn_spec = calc_fn_hash(fn_name, args.iter().map(|a| a.type_id()));
|
2020-04-16 17:31:48 +02:00
|
|
|
|
2020-04-20 18:11:25 +02:00
|
|
|
if let Some(func) = self.functions.get(&fn_spec).or_else(|| {
|
|
|
|
self.packages
|
|
|
|
.iter()
|
2020-04-21 17:01:10 +02:00
|
|
|
.find(|pkg| pkg.functions.contains_key(&fn_spec))
|
|
|
|
.and_then(|pkg| pkg.functions.get(&fn_spec))
|
2020-04-20 18:11:25 +02:00
|
|
|
}) {
|
2020-04-11 12:09:03 +02:00
|
|
|
// Run external function
|
|
|
|
let result = func(args, pos)?;
|
|
|
|
|
|
|
|
// See if the function match print/debug (which requires special processing)
|
2020-04-22 08:55:40 +02:00
|
|
|
return Ok(match fn_name {
|
2020-04-27 15:28:31 +02:00
|
|
|
KEYWORD_PRINT => (self.print)(result.as_str().map_err(|type_name| {
|
|
|
|
Box::new(EvalAltResult::ErrorMismatchOutputType(
|
|
|
|
type_name.into(),
|
|
|
|
pos,
|
|
|
|
))
|
|
|
|
})?)
|
|
|
|
.into(),
|
|
|
|
KEYWORD_DEBUG => (self.debug)(result.as_str().map_err(|type_name| {
|
|
|
|
Box::new(EvalAltResult::ErrorMismatchOutputType(
|
|
|
|
type_name.into(),
|
|
|
|
pos,
|
|
|
|
))
|
|
|
|
})?)
|
|
|
|
.into(),
|
2020-04-22 08:55:40 +02:00
|
|
|
_ => result,
|
|
|
|
});
|
2020-03-11 16:43:04 +01:00
|
|
|
}
|
2020-03-03 16:31:16 +01:00
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
// Getter function not found?
|
2020-03-30 10:10:50 +02:00
|
|
|
if let Some(prop) = extract_prop_from_getter(fn_name) {
|
2020-04-23 04:21:02 +02:00
|
|
|
return Err(Box::new(EvalAltResult::ErrorDotExpr(
|
|
|
|
format!("- property '{}' unknown or write-only", prop),
|
|
|
|
pos,
|
|
|
|
)));
|
2020-03-11 16:43:04 +01:00
|
|
|
}
|
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
// Setter function not found?
|
2020-03-30 10:10:50 +02:00
|
|
|
if let Some(prop) = extract_prop_from_setter(fn_name) {
|
2020-04-23 04:21:02 +02:00
|
|
|
return Err(Box::new(EvalAltResult::ErrorDotExpr(
|
|
|
|
format!("- property '{}' unknown or read-only", prop),
|
|
|
|
pos,
|
|
|
|
)));
|
2020-03-11 16:43:04 +01:00
|
|
|
}
|
2020-03-02 07:28:42 +01:00
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
// Return default value (if any)
|
2020-03-11 16:43:04 +01:00
|
|
|
if let Some(val) = def_val {
|
|
|
|
return Ok(val.clone());
|
2020-03-02 07:28:42 +01:00
|
|
|
}
|
2020-03-11 16:43:04 +01:00
|
|
|
|
|
|
|
// Raise error
|
2020-03-26 03:56:28 +01:00
|
|
|
let types_list: Vec<_> = args
|
2020-03-11 16:43:04 +01:00
|
|
|
.iter()
|
2020-04-27 14:25:20 +02:00
|
|
|
.map(|name| self.map_type_name(name.type_name()))
|
2020-03-26 03:56:28 +01:00
|
|
|
.collect();
|
2020-03-11 16:43:04 +01:00
|
|
|
|
2020-04-17 18:14:33 +02:00
|
|
|
Err(Box::new(EvalAltResult::ErrorFunctionNotFound(
|
2020-03-15 15:39:58 +01:00
|
|
|
format!("{} ({})", fn_name, types_list.join(", ")),
|
2020-03-11 16:43:04 +01:00
|
|
|
pos,
|
2020-04-17 18:14:33 +02:00
|
|
|
)))
|
2017-12-20 12:16:14 +01:00
|
|
|
}
|
2016-03-03 15:31:42 +01:00
|
|
|
|
2020-04-24 06:39:24 +02:00
|
|
|
/// Call a script-defined function.
|
|
|
|
pub(crate) fn call_fn_from_lib(
|
|
|
|
&self,
|
|
|
|
scope: Option<&mut Scope>,
|
2020-04-27 14:43:55 +02:00
|
|
|
fn_lib: &FunctionsLib,
|
2020-04-24 06:39:24 +02:00
|
|
|
fn_def: &FnDef,
|
|
|
|
args: &mut FnCallArgs,
|
|
|
|
pos: Position,
|
|
|
|
level: usize,
|
|
|
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
|
|
|
match scope {
|
|
|
|
// Extern scope passed in which is not empty
|
|
|
|
Some(scope) if scope.len() > 0 => {
|
|
|
|
let scope_len = scope.len();
|
2020-04-28 17:05:03 +02:00
|
|
|
let mut state = State::new();
|
2020-04-24 06:39:24 +02:00
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
// Put arguments into scope as variables - variable name is copied
|
2020-04-24 06:39:24 +02:00
|
|
|
scope.extend(
|
|
|
|
fn_def
|
|
|
|
.params
|
|
|
|
.iter()
|
2020-05-04 04:41:58 +02:00
|
|
|
.zip(
|
|
|
|
// Actually consume the arguments instead of cloning them
|
2020-05-05 09:00:10 +02:00
|
|
|
args.into_iter().map(|v| mem::take(*v)),
|
2020-05-04 04:41:58 +02:00
|
|
|
)
|
2020-04-24 06:39:24 +02:00
|
|
|
.map(|(name, value)| (name.clone(), ScopeEntryType::Normal, value)),
|
|
|
|
);
|
|
|
|
|
|
|
|
// Evaluate the function at one higher level of call depth
|
|
|
|
let result = self
|
2020-04-28 17:05:03 +02:00
|
|
|
.eval_stmt(scope, &mut state, fn_lib, &fn_def.body, level + 1)
|
2020-04-24 06:39:24 +02:00
|
|
|
.or_else(|err| match *err {
|
|
|
|
// Convert return statement to return value
|
|
|
|
EvalAltResult::Return(x, _) => Ok(x),
|
|
|
|
_ => Err(EvalAltResult::set_position(err, pos)),
|
|
|
|
});
|
|
|
|
|
|
|
|
scope.rewind(scope_len);
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
// No new scope - create internal scope
|
|
|
|
_ => {
|
|
|
|
let mut scope = Scope::new();
|
2020-04-28 17:05:03 +02:00
|
|
|
let mut state = State::new();
|
2020-04-24 06:39:24 +02:00
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
// Put arguments into scope as variables
|
2020-04-24 06:39:24 +02:00
|
|
|
scope.extend(
|
|
|
|
fn_def
|
|
|
|
.params
|
|
|
|
.iter()
|
2020-05-04 04:41:58 +02:00
|
|
|
.zip(
|
|
|
|
// Actually consume the arguments instead of cloning them
|
2020-05-05 09:00:10 +02:00
|
|
|
args.into_iter().map(|v| mem::take(*v)),
|
2020-05-04 04:41:58 +02:00
|
|
|
)
|
2020-04-24 06:39:24 +02:00
|
|
|
.map(|(name, value)| (name, ScopeEntryType::Normal, value)),
|
|
|
|
);
|
|
|
|
|
|
|
|
// Evaluate the function at one higher level of call depth
|
|
|
|
return self
|
2020-04-28 17:05:03 +02:00
|
|
|
.eval_stmt(&mut scope, &mut state, fn_lib, &fn_def.body, level + 1)
|
2020-04-24 06:39:24 +02:00
|
|
|
.or_else(|err| match *err {
|
|
|
|
// Convert return statement to return value
|
|
|
|
EvalAltResult::Return(x, _) => Ok(x),
|
|
|
|
_ => Err(EvalAltResult::set_position(err, pos)),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-23 04:21:02 +02:00
|
|
|
// Has a system function an override?
|
2020-04-27 14:43:55 +02:00
|
|
|
fn has_override(&self, fn_lib: &FunctionsLib, name: &str) -> bool {
|
2020-04-27 14:25:20 +02:00
|
|
|
let hash = calc_fn_hash(name, once(TypeId::of::<String>()));
|
2020-04-23 04:21:02 +02:00
|
|
|
|
|
|
|
// First check registered functions
|
2020-04-27 14:25:20 +02:00
|
|
|
self.functions.contains_key(&hash)
|
2020-04-23 04:21:02 +02:00
|
|
|
// Then check packages
|
2020-04-27 14:25:20 +02:00
|
|
|
|| self.packages.iter().any(|p| p.functions.contains_key(&hash))
|
2020-04-23 04:21:02 +02:00
|
|
|
// Then check script-defined functions
|
2020-04-27 14:43:55 +02:00
|
|
|
|| fn_lib.has_function(name, 1)
|
2020-04-23 04:21:02 +02:00
|
|
|
}
|
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
// Perform an actual function call, taking care of special functions
|
2020-04-23 04:21:02 +02:00
|
|
|
fn exec_fn_call(
|
|
|
|
&self,
|
2020-04-27 14:43:55 +02:00
|
|
|
fn_lib: &FunctionsLib,
|
2020-04-23 04:21:02 +02:00
|
|
|
fn_name: &str,
|
2020-05-05 04:39:12 +02:00
|
|
|
modules: &ModuleRef,
|
2020-05-03 10:54:24 +02:00
|
|
|
args: &mut FnCallArgs,
|
2020-04-23 04:21:02 +02:00
|
|
|
def_val: Option<&Dynamic>,
|
|
|
|
pos: Position,
|
|
|
|
level: usize,
|
|
|
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
|
|
|
match fn_name {
|
|
|
|
// type_of
|
2020-05-05 04:39:12 +02:00
|
|
|
KEYWORD_TYPE_OF
|
|
|
|
if modules.is_none()
|
|
|
|
&& args.len() == 1
|
|
|
|
&& !self.has_override(fn_lib, KEYWORD_TYPE_OF) =>
|
|
|
|
{
|
2020-04-23 04:21:02 +02:00
|
|
|
Ok(self.map_type_name(args[0].type_name()).to_string().into())
|
|
|
|
}
|
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
// eval - reaching this point it must be a method-style call
|
2020-05-05 04:39:12 +02:00
|
|
|
KEYWORD_EVAL
|
|
|
|
if modules.is_none()
|
|
|
|
&& args.len() == 1
|
|
|
|
&& !self.has_override(fn_lib, KEYWORD_EVAL) =>
|
|
|
|
{
|
2020-04-23 07:22:28 +02:00
|
|
|
Err(Box::new(EvalAltResult::ErrorRuntime(
|
|
|
|
"'eval' should not be called in method style. Try eval(...);".into(),
|
|
|
|
pos,
|
|
|
|
)))
|
|
|
|
}
|
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
// Normal method call
|
2020-05-05 04:39:12 +02:00
|
|
|
_ => self.call_fn_raw(None, fn_lib, fn_name, modules, args, def_val, pos, level),
|
2020-04-23 04:21:02 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-24 06:39:24 +02:00
|
|
|
/// Evaluate a text string as a script - used primarily for 'eval'.
|
|
|
|
fn eval_script_expr(
|
|
|
|
&self,
|
|
|
|
scope: &mut Scope,
|
2020-04-27 14:43:55 +02:00
|
|
|
fn_lib: &FunctionsLib,
|
2020-04-24 06:39:24 +02:00
|
|
|
script: &Dynamic,
|
|
|
|
pos: Position,
|
|
|
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
|
|
|
let script = script
|
|
|
|
.as_str()
|
|
|
|
.map_err(|type_name| EvalAltResult::ErrorMismatchOutputType(type_name.into(), pos))?;
|
|
|
|
|
|
|
|
// Compile the script text
|
|
|
|
// No optimizations because we only run it once
|
|
|
|
let mut ast = self.compile_with_scope_and_optimization_level(
|
|
|
|
&Scope::new(),
|
|
|
|
script,
|
|
|
|
OptimizationLevel::None,
|
|
|
|
)?;
|
|
|
|
|
|
|
|
// If new functions are defined within the eval string, it is an error
|
2020-05-05 09:00:10 +02:00
|
|
|
if ast.fn_lib().len() > 0 {
|
2020-04-24 06:39:24 +02:00
|
|
|
return Err(Box::new(EvalAltResult::ErrorParsing(
|
|
|
|
ParseErrorType::WrongFnDefinition.into_err(pos),
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
|
2020-05-05 09:00:10 +02:00
|
|
|
let statements = mem::take(ast.statements_mut());
|
|
|
|
ast = AST::new(statements, fn_lib.clone());
|
2020-04-24 06:39:24 +02:00
|
|
|
|
|
|
|
// Evaluate the AST
|
|
|
|
self.eval_ast_with_scope_raw(scope, &ast)
|
|
|
|
.map_err(|err| EvalAltResult::set_position(err, pos))
|
|
|
|
}
|
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
/// Chain-evaluate a dot/index chain.
|
|
|
|
fn eval_dot_index_chain_helper(
|
2020-04-07 07:23:06 +02:00
|
|
|
&self,
|
2020-04-27 14:43:55 +02:00
|
|
|
fn_lib: &FunctionsLib,
|
2020-04-26 12:04:07 +02:00
|
|
|
mut target: Target,
|
|
|
|
rhs: &Expr,
|
2020-04-30 16:52:36 +02:00
|
|
|
idx_values: &mut StaticVec<Dynamic>,
|
2020-04-26 12:04:07 +02:00
|
|
|
is_index: bool,
|
|
|
|
op_pos: Position,
|
2020-03-27 07:34:01 +01:00
|
|
|
level: usize,
|
2020-04-26 12:04:07 +02:00
|
|
|
mut new_val: Option<Dynamic>,
|
|
|
|
) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
|
|
|
|
// Get a reference to the mutation target Dynamic
|
|
|
|
let obj = match target {
|
|
|
|
Target::Ref(r) => r,
|
2020-04-26 13:37:32 +02:00
|
|
|
Target::Value(ref mut r) => r.as_mut(),
|
2020-04-26 12:04:07 +02:00
|
|
|
Target::StringChar(ref mut x) => &mut x.2,
|
|
|
|
};
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
// Pop the last index value
|
2020-04-27 14:25:20 +02:00
|
|
|
let mut idx_val = idx_values.pop();
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
if is_index {
|
|
|
|
match rhs {
|
|
|
|
// xxx[idx].dot_rhs...
|
|
|
|
Expr::Dot(idx, idx_rhs, pos) |
|
|
|
|
// xxx[idx][dot_rhs]...
|
|
|
|
Expr::Index(idx, idx_rhs, pos) => {
|
|
|
|
let is_index = matches!(rhs, Expr::Index(_,_,_));
|
|
|
|
|
|
|
|
let indexed_val = self.get_indexed_mut(obj, idx_val, idx.position(), op_pos, false)?;
|
|
|
|
self.eval_dot_index_chain_helper(
|
2020-04-27 14:25:20 +02:00
|
|
|
fn_lib, indexed_val, idx_rhs.as_ref(), idx_values, is_index, *pos, level, new_val
|
2020-04-26 12:04:07 +02:00
|
|
|
)
|
|
|
|
}
|
|
|
|
// xxx[rhs] = new_val
|
|
|
|
_ if new_val.is_some() => {
|
|
|
|
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())?;
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok((Default::default(), true))
|
2020-04-26 12:04:07 +02:00
|
|
|
}
|
|
|
|
// xxx[rhs]
|
|
|
|
_ => self
|
|
|
|
.get_indexed_mut(obj, idx_val, rhs.position(), op_pos, false)
|
2020-04-30 16:52:36 +02:00
|
|
|
.map(|v| (v.clone_into_dynamic(), false))
|
2020-04-26 12:04:07 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
match rhs {
|
|
|
|
// xxx.fn_name(arg_expr_list)
|
2020-05-04 11:43:54 +02:00
|
|
|
Expr::FnCall(fn_name, None,_, def_val, pos) => {
|
2020-04-27 14:25:20 +02:00
|
|
|
let mut args: Vec<_> = once(obj)
|
2020-04-26 12:04:07 +02:00
|
|
|
.chain(idx_val.downcast_mut::<Array>().unwrap().iter_mut())
|
2020-04-27 14:25:20 +02:00
|
|
|
.collect();
|
2020-04-28 17:05:03 +02:00
|
|
|
let def_val = def_val.as_deref();
|
2020-04-26 12:04:07 +02:00
|
|
|
// A function call is assumed to have side effects, so the value is changed
|
2020-04-26 13:37:32 +02:00
|
|
|
// TODO - Remove assumption of side effects by checking whether the first parameter is &mut
|
2020-05-05 04:39:12 +02:00
|
|
|
self.exec_fn_call(fn_lib, fn_name, &None, &mut args, def_val, *pos, 0).map(|v| (v, true))
|
2020-04-26 12:04:07 +02:00
|
|
|
}
|
2020-05-04 13:36:58 +02:00
|
|
|
// xxx.module::fn_name(...) - syntax error
|
2020-05-04 11:43:54 +02:00
|
|
|
Expr::FnCall(_,_,_,_,_) => unreachable!(),
|
2020-04-26 15:48:49 +02:00
|
|
|
// {xxx:map}.id = ???
|
|
|
|
Expr::Property(id, pos) if obj.is::<Map>() && new_val.is_some() => {
|
2020-04-27 14:25:20 +02:00
|
|
|
let mut indexed_val =
|
2020-04-26 15:48:49 +02:00
|
|
|
self.get_indexed_mut(obj, id.to_string().into(), *pos, op_pos, true)?;
|
|
|
|
indexed_val.set_value(new_val.unwrap(), rhs.position())?;
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok((Default::default(), true))
|
2020-04-26 15:48:49 +02:00
|
|
|
}
|
2020-04-26 12:04:07 +02:00
|
|
|
// {xxx:map}.id
|
|
|
|
Expr::Property(id, pos) if obj.is::<Map>() => {
|
2020-04-27 14:25:20 +02:00
|
|
|
let indexed_val =
|
2020-04-26 15:48:49 +02:00
|
|
|
self.get_indexed_mut(obj, id.to_string().into(), *pos, op_pos, false)?;
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok((indexed_val.clone_into_dynamic(), false))
|
2020-04-26 12:04:07 +02:00
|
|
|
}
|
2020-05-03 16:17:28 +02:00
|
|
|
// xxx.id = ??? a
|
2020-04-26 12:04:07 +02:00
|
|
|
Expr::Property(id, pos) if new_val.is_some() => {
|
|
|
|
let fn_name = make_setter(id);
|
|
|
|
let mut args = [obj, new_val.as_mut().unwrap()];
|
2020-05-05 04:39:12 +02:00
|
|
|
self.exec_fn_call(fn_lib, &fn_name, &None, &mut args, None, *pos, 0).map(|v| (v, true))
|
2020-04-26 12:04:07 +02:00
|
|
|
}
|
|
|
|
// xxx.id
|
2020-03-13 11:12:41 +01:00
|
|
|
Expr::Property(id, pos) => {
|
2020-04-23 04:21:02 +02:00
|
|
|
let fn_name = make_getter(id);
|
2020-04-26 12:04:07 +02:00
|
|
|
let mut args = [obj];
|
2020-05-05 04:39:12 +02:00
|
|
|
self.exec_fn_call(fn_lib, &fn_name, &None, &mut args, None, *pos, 0).map(|v| (v, false))
|
2020-03-01 06:30:22 +01:00
|
|
|
}
|
2020-04-26 12:04:07 +02:00
|
|
|
// {xxx:map}.idx_lhs[idx_expr]
|
|
|
|
Expr::Index(dot_lhs, dot_rhs, pos) |
|
|
|
|
// {xxx:map}.dot_lhs.rhs
|
|
|
|
Expr::Dot(dot_lhs, dot_rhs, pos) if obj.is::<Map>() => {
|
|
|
|
let is_index = matches!(rhs, Expr::Index(_,_,_));
|
|
|
|
|
|
|
|
let indexed_val = if let Expr::Property(id, pos) = dot_lhs.as_ref() {
|
|
|
|
self.get_indexed_mut(obj, id.to_string().into(), *pos, op_pos, false)?
|
|
|
|
} else {
|
2020-03-07 16:57:01 +01:00
|
|
|
// Syntax error
|
2020-04-26 12:04:07 +02:00
|
|
|
return Err(Box::new(EvalAltResult::ErrorDotExpr(
|
|
|
|
"".to_string(),
|
|
|
|
rhs.position(),
|
|
|
|
)));
|
2020-03-05 13:28:03 +01:00
|
|
|
};
|
2020-04-26 12:04:07 +02:00
|
|
|
self.eval_dot_index_chain_helper(
|
2020-04-27 14:25:20 +02:00
|
|
|
fn_lib, indexed_val, dot_rhs, idx_values, is_index, *pos, level, new_val
|
2020-04-26 12:04:07 +02:00
|
|
|
)
|
|
|
|
}
|
|
|
|
// xxx.idx_lhs[idx_expr]
|
|
|
|
Expr::Index(dot_lhs, dot_rhs, pos) |
|
|
|
|
// xxx.dot_lhs.rhs
|
|
|
|
Expr::Dot(dot_lhs, dot_rhs, pos) => {
|
|
|
|
let is_index = matches!(rhs, Expr::Index(_,_,_));
|
2020-04-30 16:52:36 +02:00
|
|
|
let mut args = [obj, &mut Default::default()];
|
2020-04-26 12:04:07 +02:00
|
|
|
|
2020-04-26 15:48:49 +02:00
|
|
|
let indexed_val = &mut (if let Expr::Property(id, pos) = dot_lhs.as_ref() {
|
2020-04-26 12:04:07 +02:00
|
|
|
let fn_name = make_getter(id);
|
2020-05-05 04:39:12 +02:00
|
|
|
self.exec_fn_call(fn_lib, &fn_name, &None, &mut args[..1], None, *pos, 0)?
|
2020-04-26 12:04:07 +02:00
|
|
|
} else {
|
|
|
|
// Syntax error
|
|
|
|
return Err(Box::new(EvalAltResult::ErrorDotExpr(
|
|
|
|
"".to_string(),
|
|
|
|
rhs.position(),
|
|
|
|
)));
|
2020-04-26 15:48:49 +02:00
|
|
|
});
|
2020-04-30 16:52:36 +02:00
|
|
|
let (result, may_be_changed) = self.eval_dot_index_chain_helper(
|
2020-04-27 14:25:20 +02:00
|
|
|
fn_lib, indexed_val.into(), dot_rhs, idx_values, is_index, *pos, level, new_val
|
2020-04-26 12:04:07 +02:00
|
|
|
)?;
|
2020-03-05 13:28:03 +01:00
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
// Feed the value back via a setter just in case it has been updated
|
2020-04-30 16:52:36 +02:00
|
|
|
if may_be_changed {
|
2020-04-26 12:04:07 +02:00
|
|
|
if let Expr::Property(id, pos) = dot_lhs.as_ref() {
|
|
|
|
let fn_name = make_setter(id);
|
2020-05-04 13:36:58 +02:00
|
|
|
// Re-use args because the first &mut parameter will not be consumed
|
2020-04-26 15:48:49 +02:00
|
|
|
args[1] = indexed_val;
|
2020-05-05 04:39:12 +02:00
|
|
|
self.exec_fn_call(fn_lib, &fn_name, &None, &mut args, None, *pos, 0).or_else(|err| match *err {
|
2020-05-04 12:06:09 +02:00
|
|
|
// If there is no setter, no need to feed it back because the property is read-only
|
|
|
|
EvalAltResult::ErrorDotExpr(_,_) => Ok(Default::default()),
|
|
|
|
err => Err(Box::new(err))
|
|
|
|
})?;
|
2020-04-26 12:04:07 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok((result, may_be_changed))
|
2016-03-10 20:21:36 +01:00
|
|
|
}
|
2020-03-05 18:05:02 +01:00
|
|
|
// Syntax error
|
2020-04-17 18:14:33 +02:00
|
|
|
_ => Err(Box::new(EvalAltResult::ErrorDotExpr(
|
2020-03-07 16:57:01 +01:00
|
|
|
"".to_string(),
|
2020-04-26 12:04:07 +02:00
|
|
|
rhs.position(),
|
2020-04-17 18:14:33 +02:00
|
|
|
))),
|
2020-04-26 12:04:07 +02:00
|
|
|
}
|
2016-03-07 21:39:02 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-26 15:48:49 +02:00
|
|
|
/// Evaluate a dot/index chain.
|
2020-04-26 12:04:07 +02:00
|
|
|
fn eval_dot_index_chain(
|
2020-04-07 07:23:06 +02:00
|
|
|
&self,
|
2020-03-07 16:57:01 +01:00
|
|
|
scope: &mut Scope,
|
2020-04-28 17:05:03 +02:00
|
|
|
state: &mut State,
|
2020-04-27 14:43:55 +02:00
|
|
|
fn_lib: &FunctionsLib,
|
2020-03-07 16:57:01 +01:00
|
|
|
dot_lhs: &Expr,
|
|
|
|
dot_rhs: &Expr,
|
2020-04-26 12:04:07 +02:00
|
|
|
is_index: bool,
|
|
|
|
op_pos: Position,
|
2020-03-27 07:34:01 +01:00
|
|
|
level: usize,
|
2020-04-26 12:04:07 +02:00
|
|
|
new_val: Option<Dynamic>,
|
2020-04-17 18:14:33 +02:00
|
|
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
2020-04-27 14:25:20 +02:00
|
|
|
let idx_values = &mut StaticVec::new();
|
2020-03-25 04:27:18 +01:00
|
|
|
|
2020-04-28 17:05:03 +02:00
|
|
|
self.eval_indexed_chain(scope, state, fn_lib, dot_rhs, idx_values, 0, level)?;
|
2020-04-11 10:06:57 +02:00
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
match dot_lhs {
|
|
|
|
// id.??? or id[???]
|
2020-05-04 13:36:58 +02:00
|
|
|
Expr::Variable(id, modules, index, pos) => {
|
2020-05-04 17:07:42 +02:00
|
|
|
let index = if state.always_search { None } else { *index };
|
2020-05-05 04:39:12 +02:00
|
|
|
let (target, typ) = search_scope(scope, id, modules, index, *pos)?;
|
2020-04-26 12:04:07 +02:00
|
|
|
|
|
|
|
// Constants cannot be modified
|
|
|
|
match typ {
|
2020-05-05 04:39:12 +02:00
|
|
|
ScopeEntryType::Module => unreachable!(),
|
2020-04-26 12:04:07 +02:00
|
|
|
ScopeEntryType::Constant if new_val.is_some() => {
|
|
|
|
return Err(Box::new(EvalAltResult::ErrorAssignmentToConstant(
|
|
|
|
id.to_string(),
|
|
|
|
*pos,
|
|
|
|
)));
|
2020-03-14 12:46:44 +01:00
|
|
|
}
|
2020-05-04 17:07:42 +02:00
|
|
|
ScopeEntryType::Constant | ScopeEntryType::Normal => (),
|
2020-03-07 16:57:01 +01:00
|
|
|
}
|
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
let this_ptr = target.into();
|
2020-04-26 12:04:07 +02:00
|
|
|
self.eval_dot_index_chain_helper(
|
2020-04-30 16:52:36 +02:00
|
|
|
fn_lib, this_ptr, dot_rhs, idx_values, is_index, op_pos, level, new_val,
|
2020-04-26 12:04:07 +02:00
|
|
|
)
|
|
|
|
.map(|(v, _)| v)
|
2020-03-07 16:57:01 +01:00
|
|
|
}
|
2020-04-26 12:04:07 +02:00
|
|
|
// {expr}.??? = ??? or {expr}[???] = ???
|
|
|
|
expr if new_val.is_some() => {
|
|
|
|
return Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(
|
|
|
|
expr.position(),
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
// {expr}.??? or {expr}[???]
|
2020-03-07 16:57:01 +01:00
|
|
|
expr => {
|
2020-04-28 17:05:03 +02:00
|
|
|
let val = self.eval_expr(scope, state, fn_lib, expr, level)?;
|
2020-04-30 16:52:36 +02:00
|
|
|
let this_ptr = val.into();
|
2020-04-26 12:04:07 +02:00
|
|
|
self.eval_dot_index_chain_helper(
|
2020-04-30 16:52:36 +02:00
|
|
|
fn_lib, this_ptr, dot_rhs, idx_values, is_index, op_pos, level, new_val,
|
2020-04-26 12:04:07 +02:00
|
|
|
)
|
|
|
|
.map(|(v, _)| v)
|
2020-03-07 16:57:01 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-26 15:48:49 +02:00
|
|
|
/// Evaluate a chain of indexes and store the results in a list.
|
|
|
|
/// The first few results are stored in the array `list` which is of fixed length.
|
|
|
|
/// Any spill-overs are stored in `more`, which is dynamic.
|
|
|
|
/// The fixed length array is used to avoid an allocation in the overwhelming cases of just a few levels of indexing.
|
|
|
|
/// The total number of values is returned.
|
2020-04-26 12:04:07 +02:00
|
|
|
fn eval_indexed_chain(
|
2020-04-07 07:23:06 +02:00
|
|
|
&self,
|
2020-03-05 18:05:02 +01:00
|
|
|
scope: &mut Scope,
|
2020-04-28 17:05:03 +02:00
|
|
|
state: &mut State,
|
2020-04-27 14:43:55 +02:00
|
|
|
fn_lib: &FunctionsLib,
|
2020-04-26 12:04:07 +02:00
|
|
|
expr: &Expr,
|
2020-04-30 16:52:36 +02:00
|
|
|
idx_values: &mut StaticVec<Dynamic>,
|
2020-04-26 12:04:07 +02:00
|
|
|
size: usize,
|
2020-03-27 07:34:01 +01:00
|
|
|
level: usize,
|
2020-04-27 14:25:20 +02:00
|
|
|
) -> Result<(), Box<EvalAltResult>> {
|
2020-04-26 15:48:49 +02:00
|
|
|
match expr {
|
2020-05-04 11:43:54 +02:00
|
|
|
Expr::FnCall(_, None, arg_exprs, _, _) => {
|
2020-04-26 12:04:07 +02:00
|
|
|
let arg_values = arg_exprs
|
|
|
|
.iter()
|
2020-04-28 17:05:03 +02:00
|
|
|
.map(|arg_expr| self.eval_expr(scope, state, fn_lib, arg_expr, level))
|
2020-04-26 12:04:07 +02:00
|
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
|
|
|
2020-04-27 14:25:20 +02:00
|
|
|
idx_values.push(arg_values)
|
2020-04-26 12:04:07 +02:00
|
|
|
}
|
2020-05-04 11:43:54 +02:00
|
|
|
Expr::FnCall(_, _, _, _, _) => unreachable!(),
|
2020-04-30 16:52:36 +02:00
|
|
|
Expr::Property(_, _) => idx_values.push(()), // Store a placeholder - no need to copy the property name
|
2020-04-26 12:04:07 +02:00
|
|
|
Expr::Index(lhs, rhs, _) | Expr::Dot(lhs, rhs, _) => {
|
|
|
|
// Evaluate in left-to-right order
|
|
|
|
let lhs_val = match lhs.as_ref() {
|
2020-04-30 16:52:36 +02:00
|
|
|
Expr::Property(_, _) => Default::default(), // Store a placeholder in case of a property
|
2020-04-28 17:05:03 +02:00
|
|
|
_ => self.eval_expr(scope, state, fn_lib, lhs, level)?,
|
2020-04-26 12:04:07 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
// Push in reverse order
|
2020-04-28 17:05:03 +02:00
|
|
|
self.eval_indexed_chain(scope, state, fn_lib, rhs, idx_values, size, level)?;
|
2020-04-26 12:04:07 +02:00
|
|
|
|
2020-04-27 14:25:20 +02:00
|
|
|
idx_values.push(lhs_val);
|
2020-04-26 12:04:07 +02:00
|
|
|
}
|
2020-04-28 17:05:03 +02:00
|
|
|
_ => idx_values.push(self.eval_expr(scope, state, fn_lib, expr, level)?),
|
2020-04-26 15:48:49 +02:00
|
|
|
}
|
2020-04-27 14:25:20 +02:00
|
|
|
|
|
|
|
Ok(())
|
2020-04-26 12:04:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the value at the indexed position of a base type
|
|
|
|
fn get_indexed_mut<'a>(
|
|
|
|
&self,
|
|
|
|
val: &'a mut Dynamic,
|
|
|
|
idx: Dynamic,
|
|
|
|
idx_pos: Position,
|
|
|
|
op_pos: Position,
|
|
|
|
create: bool,
|
|
|
|
) -> Result<Target<'a>, Box<EvalAltResult>> {
|
2020-04-16 04:24:30 +02:00
|
|
|
let type_name = self.map_type_name(val.type_name());
|
2020-03-05 18:05:02 +01:00
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
match val {
|
|
|
|
Dynamic(Union::Array(arr)) => {
|
2020-04-16 04:24:30 +02:00
|
|
|
// val_array[idx]
|
2020-04-26 12:04:07 +02:00
|
|
|
let index = idx
|
2020-04-16 04:24:30 +02:00
|
|
|
.as_int()
|
2020-04-26 12:04:07 +02:00
|
|
|
.map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_pos))?;
|
2020-04-16 04:24:30 +02:00
|
|
|
|
2020-04-19 12:33:02 +02:00
|
|
|
let arr_len = arr.len();
|
|
|
|
|
2020-04-16 06:08:28 +02:00
|
|
|
if index >= 0 {
|
2020-04-26 12:04:07 +02:00
|
|
|
arr.get_mut(index as usize)
|
|
|
|
.map(Target::from)
|
2020-04-17 18:14:33 +02:00
|
|
|
.ok_or_else(|| {
|
2020-04-19 12:33:02 +02:00
|
|
|
Box::new(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos))
|
2020-04-17 18:14:33 +02:00
|
|
|
})
|
2020-04-16 04:24:30 +02:00
|
|
|
} else {
|
2020-04-17 18:14:33 +02:00
|
|
|
Err(Box::new(EvalAltResult::ErrorArrayBounds(
|
2020-04-19 12:33:02 +02:00
|
|
|
arr_len, index, idx_pos,
|
2020-04-17 18:14:33 +02:00
|
|
|
)))
|
2020-04-16 06:08:28 +02:00
|
|
|
}
|
2020-04-16 04:24:30 +02:00
|
|
|
}
|
2020-03-29 17:53:35 +02:00
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
Dynamic(Union::Map(map)) => {
|
2020-04-16 04:24:30 +02:00
|
|
|
// val_map[idx]
|
2020-04-26 12:04:07 +02:00
|
|
|
let index = idx
|
2020-04-16 04:24:30 +02:00
|
|
|
.take_string()
|
2020-04-26 12:04:07 +02:00
|
|
|
.map_err(|_| EvalAltResult::ErrorStringIndexExpr(idx_pos))?;
|
|
|
|
|
|
|
|
Ok(if create {
|
2020-04-30 16:52:36 +02:00
|
|
|
map.entry(index).or_insert(Default::default()).into()
|
2020-04-26 12:04:07 +02:00
|
|
|
} else {
|
2020-04-27 14:25:20 +02:00
|
|
|
map.get_mut(&index)
|
|
|
|
.map(Target::from)
|
|
|
|
.unwrap_or_else(|| Target::from(()))
|
2020-04-26 12:04:07 +02:00
|
|
|
})
|
2020-04-16 04:24:30 +02:00
|
|
|
}
|
2020-04-10 06:16:39 +02:00
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
Dynamic(Union::Str(s)) => {
|
2020-04-16 04:24:30 +02:00
|
|
|
// val_string[idx]
|
2020-04-26 12:04:07 +02:00
|
|
|
let index = idx
|
2020-04-16 04:24:30 +02:00
|
|
|
.as_int()
|
2020-04-26 12:04:07 +02:00
|
|
|
.map_err(|_| EvalAltResult::ErrorNumericIndexExpr(idx_pos))?;
|
2020-04-16 04:24:30 +02:00
|
|
|
|
2020-04-16 06:08:28 +02:00
|
|
|
if index >= 0 {
|
2020-05-01 17:39:55 +02:00
|
|
|
let ch = s.chars().nth(index as usize).ok_or_else(|| {
|
|
|
|
Box::new(EvalAltResult::ErrorStringBounds(
|
|
|
|
s.chars().count(),
|
|
|
|
index,
|
|
|
|
idx_pos,
|
|
|
|
))
|
|
|
|
})?;
|
|
|
|
|
|
|
|
Ok(Target::StringChar(Box::new((
|
|
|
|
val,
|
|
|
|
index as usize,
|
|
|
|
ch.into(),
|
|
|
|
))))
|
2020-04-16 04:24:30 +02:00
|
|
|
} else {
|
2020-04-17 18:14:33 +02:00
|
|
|
Err(Box::new(EvalAltResult::ErrorStringBounds(
|
2020-05-01 17:39:55 +02:00
|
|
|
s.chars().count(),
|
|
|
|
index,
|
|
|
|
idx_pos,
|
2020-04-17 18:14:33 +02:00
|
|
|
)))
|
2020-04-16 06:08:28 +02:00
|
|
|
}
|
2020-04-16 04:24:30 +02:00
|
|
|
}
|
2020-03-29 17:53:35 +02:00
|
|
|
|
2020-04-16 04:24:30 +02:00
|
|
|
// Error - cannot be indexed
|
2020-04-17 18:14:33 +02:00
|
|
|
_ => Err(Box::new(EvalAltResult::ErrorIndexingType(
|
2020-04-16 04:24:30 +02:00
|
|
|
type_name.to_string(),
|
|
|
|
op_pos,
|
2020-04-17 18:14:33 +02:00
|
|
|
))),
|
2020-03-04 15:00:01 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-06 11:47:34 +02:00
|
|
|
// Evaluate an 'in' expression
|
|
|
|
fn eval_in_expr(
|
2020-04-07 07:23:06 +02:00
|
|
|
&self,
|
2020-04-06 11:47:34 +02:00
|
|
|
scope: &mut Scope,
|
2020-04-28 17:05:03 +02:00
|
|
|
state: &mut State,
|
2020-04-27 14:43:55 +02:00
|
|
|
fn_lib: &FunctionsLib,
|
2020-04-06 11:47:34 +02:00
|
|
|
lhs: &Expr,
|
|
|
|
rhs: &Expr,
|
|
|
|
level: usize,
|
2020-04-17 18:14:33 +02:00
|
|
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
2020-04-28 17:05:03 +02:00
|
|
|
let mut lhs_value = self.eval_expr(scope, state, fn_lib, lhs, level)?;
|
|
|
|
let rhs_value = self.eval_expr(scope, state, fn_lib, rhs, level)?;
|
2020-04-06 11:47:34 +02:00
|
|
|
|
2020-04-12 17:00:06 +02:00
|
|
|
match rhs_value {
|
|
|
|
Dynamic(Union::Array(mut rhs_value)) => {
|
2020-04-22 06:12:13 +02:00
|
|
|
let def_value = false.into();
|
2020-04-12 17:00:06 +02:00
|
|
|
|
|
|
|
// Call the '==' operator to compare each value
|
|
|
|
for value in rhs_value.iter_mut() {
|
|
|
|
let args = &mut [&mut lhs_value, value];
|
|
|
|
let def_value = Some(&def_value);
|
2020-05-05 04:39:12 +02:00
|
|
|
let pos = rhs.position();
|
2020-04-30 16:52:36 +02:00
|
|
|
|
2020-04-12 17:00:06 +02:00
|
|
|
if self
|
2020-05-05 04:39:12 +02:00
|
|
|
.call_fn_raw(None, fn_lib, "==", &None, args, def_value, pos, level)?
|
2020-04-12 17:00:06 +02:00
|
|
|
.as_bool()
|
|
|
|
.unwrap_or(false)
|
|
|
|
{
|
2020-04-30 16:52:36 +02:00
|
|
|
return Ok(true.into());
|
2020-04-12 17:00:06 +02:00
|
|
|
}
|
2020-04-06 11:47:34 +02:00
|
|
|
}
|
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok(false.into())
|
2020-04-10 06:16:39 +02:00
|
|
|
}
|
2020-04-30 16:52:36 +02:00
|
|
|
Dynamic(Union::Map(rhs_value)) => match lhs_value {
|
2020-04-12 17:00:06 +02:00
|
|
|
// Only allows String or char
|
2020-04-30 16:52:36 +02:00
|
|
|
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()),
|
|
|
|
_ => Err(Box::new(EvalAltResult::ErrorInExpr(lhs.position()))),
|
|
|
|
},
|
|
|
|
Dynamic(Union::Str(rhs_value)) => match lhs_value {
|
2020-04-12 17:00:06 +02:00
|
|
|
// Only allows String or char
|
2020-04-30 16:52:36 +02:00
|
|
|
Dynamic(Union::Str(s)) => Ok(rhs_value.contains(s.as_ref()).into()),
|
|
|
|
Dynamic(Union::Char(c)) => Ok(rhs_value.contains(c).into()),
|
|
|
|
_ => Err(Box::new(EvalAltResult::ErrorInExpr(lhs.position()))),
|
|
|
|
},
|
2020-04-17 18:14:33 +02:00
|
|
|
_ => Err(Box::new(EvalAltResult::ErrorInExpr(rhs.position()))),
|
2020-04-06 11:47:34 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-05 18:05:02 +01:00
|
|
|
/// Evaluate an expression
|
2020-03-27 07:34:01 +01:00
|
|
|
fn eval_expr(
|
2020-04-07 07:23:06 +02:00
|
|
|
&self,
|
2020-03-27 07:34:01 +01:00
|
|
|
scope: &mut Scope,
|
2020-04-28 17:05:03 +02:00
|
|
|
state: &mut State,
|
2020-04-27 14:43:55 +02:00
|
|
|
fn_lib: &FunctionsLib,
|
2020-03-27 07:34:01 +01:00
|
|
|
expr: &Expr,
|
|
|
|
level: usize,
|
2020-04-17 18:14:33 +02:00
|
|
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
2020-02-29 10:10:51 +01:00
|
|
|
match expr {
|
2020-04-22 06:12:13 +02:00
|
|
|
Expr::IntegerConstant(i, _) => Ok((*i).into()),
|
2020-04-12 17:00:06 +02:00
|
|
|
#[cfg(not(feature = "no_float"))]
|
2020-04-22 06:12:13 +02:00
|
|
|
Expr::FloatConstant(f, _) => Ok((*f).into()),
|
|
|
|
Expr::StringConstant(s, _) => Ok(s.to_string().into()),
|
|
|
|
Expr::CharConstant(c, _) => Ok((*c).into()),
|
2020-05-04 17:07:42 +02:00
|
|
|
Expr::Variable(id, modules, index, pos) => {
|
|
|
|
let index = if state.always_search { None } else { *index };
|
2020-05-05 04:39:12 +02:00
|
|
|
let val = search_scope(scope, id, modules, index, *pos)?;
|
2020-05-04 17:07:42 +02:00
|
|
|
Ok(val.0.clone())
|
2020-05-04 11:43:54 +02:00
|
|
|
}
|
|
|
|
Expr::Property(_, _) => unreachable!(),
|
2020-03-07 03:39:00 +01:00
|
|
|
|
|
|
|
// Statement block
|
2020-04-28 17:05:03 +02:00
|
|
|
Expr::Stmt(stmt, _) => self.eval_stmt(scope, state, fn_lib, stmt, level),
|
2020-03-07 03:39:00 +01:00
|
|
|
|
2020-03-05 18:05:02 +01:00
|
|
|
// lhs = rhs
|
2020-03-13 11:12:41 +01:00
|
|
|
Expr::Assignment(lhs, rhs, op_pos) => {
|
2020-04-28 17:05:03 +02:00
|
|
|
let rhs_val = self.eval_expr(scope, state, fn_lib, rhs, level)?;
|
2016-03-26 18:46:28 +01:00
|
|
|
|
2020-03-05 13:28:03 +01:00
|
|
|
match lhs.as_ref() {
|
2020-03-05 18:05:02 +01:00
|
|
|
// name = rhs
|
2020-05-04 17:07:42 +02:00
|
|
|
Expr::Variable(name, modules, index, pos) => {
|
|
|
|
let index = if state.always_search { None } else { *index };
|
2020-05-05 04:39:12 +02:00
|
|
|
match search_scope(scope, name, modules, index, *pos)? {
|
2020-05-04 11:43:54 +02:00
|
|
|
(_, ScopeEntryType::Constant) => Err(Box::new(
|
|
|
|
EvalAltResult::ErrorAssignmentToConstant(name.to_string(), *op_pos),
|
|
|
|
)),
|
|
|
|
(value_ptr, ScopeEntryType::Normal) => {
|
|
|
|
*value_ptr = rhs_val;
|
|
|
|
Ok(Default::default())
|
|
|
|
}
|
2020-05-05 04:39:12 +02:00
|
|
|
// End variable cannot be a module
|
|
|
|
(_, ScopeEntryType::Module) => unreachable!(),
|
2020-04-11 10:06:57 +02:00
|
|
|
}
|
2020-05-04 11:43:54 +02:00
|
|
|
}
|
2020-03-05 18:05:02 +01:00
|
|
|
// idx_lhs[idx_expr] = rhs
|
2020-03-10 10:10:33 +01:00
|
|
|
#[cfg(not(feature = "no_index"))]
|
2020-03-20 12:27:02 +01:00
|
|
|
Expr::Index(idx_lhs, idx_expr, op_pos) => {
|
2020-04-26 12:04:07 +02:00
|
|
|
let new_val = Some(rhs_val);
|
|
|
|
self.eval_dot_index_chain(
|
2020-04-28 17:05:03 +02:00
|
|
|
scope, state, fn_lib, idx_lhs, idx_expr, true, *op_pos, level, new_val,
|
2020-04-26 12:04:07 +02:00
|
|
|
)
|
2016-03-26 18:46:28 +01:00
|
|
|
}
|
2020-03-05 18:05:02 +01:00
|
|
|
// dot_lhs.dot_rhs = rhs
|
2020-03-29 11:15:12 +02:00
|
|
|
#[cfg(not(feature = "no_object"))]
|
2020-04-07 07:23:06 +02:00
|
|
|
Expr::Dot(dot_lhs, dot_rhs, _) => {
|
2020-04-26 12:04:07 +02:00
|
|
|
let new_val = Some(rhs_val);
|
|
|
|
self.eval_dot_index_chain(
|
2020-04-28 17:05:03 +02:00
|
|
|
scope, state, fn_lib, dot_lhs, dot_rhs, false, *op_pos, level, new_val,
|
2020-04-19 07:40:11 +02:00
|
|
|
)
|
2020-04-07 07:23:06 +02:00
|
|
|
}
|
2020-03-13 11:12:41 +01:00
|
|
|
// Error assignment to constant
|
2020-04-17 18:14:33 +02:00
|
|
|
expr if expr.is_constant() => {
|
|
|
|
Err(Box::new(EvalAltResult::ErrorAssignmentToConstant(
|
|
|
|
expr.get_constant_str(),
|
|
|
|
lhs.position(),
|
|
|
|
)))
|
|
|
|
}
|
2020-03-05 18:05:02 +01:00
|
|
|
// Syntax error
|
2020-04-17 18:14:33 +02:00
|
|
|
_ => Err(Box::new(EvalAltResult::ErrorAssignmentToUnknownLHS(
|
|
|
|
lhs.position(),
|
|
|
|
))),
|
2016-02-29 22:43:45 +01:00
|
|
|
}
|
|
|
|
}
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-04-10 06:16:39 +02:00
|
|
|
// lhs[idx_expr]
|
|
|
|
#[cfg(not(feature = "no_index"))]
|
2020-04-28 17:05:03 +02:00
|
|
|
Expr::Index(lhs, idx_expr, op_pos) => self.eval_dot_index_chain(
|
|
|
|
scope, state, fn_lib, lhs, idx_expr, true, *op_pos, level, None,
|
|
|
|
),
|
2020-04-10 06:16:39 +02:00
|
|
|
|
2020-04-26 12:04:07 +02:00
|
|
|
// lhs.dot_rhs
|
2020-03-29 11:15:12 +02:00
|
|
|
#[cfg(not(feature = "no_object"))]
|
2020-04-28 17:05:03 +02:00
|
|
|
Expr::Dot(lhs, dot_rhs, op_pos) => self.eval_dot_index_chain(
|
|
|
|
scope, state, fn_lib, lhs, dot_rhs, false, *op_pos, level, None,
|
|
|
|
),
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-03-10 10:10:33 +01:00
|
|
|
#[cfg(not(feature = "no_index"))]
|
2020-04-30 16:52:36 +02:00
|
|
|
Expr::Array(contents, _) => Ok(Dynamic(Union::Array(Box::new(
|
|
|
|
contents
|
2020-05-03 10:54:24 +02:00
|
|
|
.iter()
|
2020-04-30 16:52:36 +02:00
|
|
|
.map(|item| self.eval_expr(scope, state, fn_lib, item, level))
|
|
|
|
.collect::<Result<Vec<_>, _>>()?,
|
|
|
|
)))),
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-03-29 17:53:35 +02:00
|
|
|
#[cfg(not(feature = "no_object"))]
|
2020-04-30 16:52:36 +02:00
|
|
|
Expr::Map(contents, _) => Ok(Dynamic(Union::Map(Box::new(
|
|
|
|
contents
|
2020-05-03 10:54:24 +02:00
|
|
|
.iter()
|
2020-04-30 16:52:36 +02:00
|
|
|
.map(|(key, expr, _)| {
|
2020-05-03 10:54:24 +02:00
|
|
|
self.eval_expr(scope, state, fn_lib, expr, level)
|
2020-04-30 16:52:36 +02:00
|
|
|
.map(|val| (key.clone(), val))
|
|
|
|
})
|
|
|
|
.collect::<Result<HashMap<_, _>, _>>()?,
|
|
|
|
)))),
|
2020-03-29 17:53:35 +02:00
|
|
|
|
2020-05-04 13:36:58 +02:00
|
|
|
Expr::FnCall(fn_name, modules, arg_exprs, def_val, pos) => {
|
2020-04-23 04:21:02 +02:00
|
|
|
let mut arg_values = arg_exprs
|
|
|
|
.iter()
|
2020-04-28 17:05:03 +02:00
|
|
|
.map(|expr| self.eval_expr(scope, state, fn_lib, expr, level))
|
2020-04-23 04:21:02 +02:00
|
|
|
.collect::<Result<Vec<_>, _>>()?;
|
2020-03-11 04:39:15 +01:00
|
|
|
|
2020-04-23 04:21:02 +02:00
|
|
|
let mut args: Vec<_> = arg_values.iter_mut().collect();
|
|
|
|
|
|
|
|
// eval - only in function call style
|
2020-05-01 11:32:39 +02:00
|
|
|
if fn_name.as_ref() == KEYWORD_EVAL
|
2020-05-05 04:39:12 +02:00
|
|
|
&& modules.is_none()
|
2020-04-23 04:21:02 +02:00
|
|
|
&& args.len() == 1
|
|
|
|
&& !self.has_override(fn_lib, KEYWORD_EVAL)
|
|
|
|
{
|
2020-04-29 10:11:54 +02:00
|
|
|
let prev_len = scope.len();
|
|
|
|
|
2020-04-24 06:39:24 +02:00
|
|
|
// Evaluate the text string as a script
|
2020-04-28 17:05:03 +02:00
|
|
|
let result =
|
|
|
|
self.eval_script_expr(scope, fn_lib, args[0], arg_exprs[0].position());
|
|
|
|
|
2020-04-29 10:11:54 +02:00
|
|
|
if scope.len() != prev_len {
|
|
|
|
// IMPORTANT! If the eval defines new variables in the current scope,
|
|
|
|
// all variable offsets from this point on will be mis-aligned.
|
|
|
|
state.always_search = true;
|
|
|
|
}
|
2020-04-28 17:05:03 +02:00
|
|
|
|
|
|
|
return result;
|
2020-03-20 12:27:02 +01:00
|
|
|
}
|
2020-04-23 04:21:02 +02:00
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
// Normal function call - except for eval (handled above)
|
2020-05-05 04:39:12 +02:00
|
|
|
let def_value = def_val.as_deref();
|
|
|
|
self.exec_fn_call(fn_lib, fn_name, modules, &mut args, def_value, *pos, level)
|
2020-03-04 15:00:01 +01:00
|
|
|
}
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-04-07 07:23:06 +02:00
|
|
|
Expr::In(lhs, rhs, _) => {
|
2020-04-28 17:05:03 +02:00
|
|
|
self.eval_in_expr(scope, state, fn_lib, lhs.as_ref(), rhs.as_ref(), level)
|
2020-04-07 07:23:06 +02:00
|
|
|
}
|
2020-04-06 11:47:34 +02:00
|
|
|
|
2020-04-22 06:12:13 +02:00
|
|
|
Expr::And(lhs, rhs, _) => Ok((self
|
2020-04-28 17:05:03 +02:00
|
|
|
.eval_expr(scope, state, fn_lib, lhs.as_ref(), level)?
|
2020-04-12 17:00:06 +02:00
|
|
|
.as_bool()
|
2020-03-02 15:13:14 +01:00
|
|
|
.map_err(|_| {
|
|
|
|
EvalAltResult::ErrorBooleanArgMismatch("AND".into(), lhs.position())
|
|
|
|
})?
|
2020-03-05 18:05:02 +01:00
|
|
|
&& // Short-circuit using &&
|
2020-04-02 06:35:44 +02:00
|
|
|
self
|
2020-04-28 17:05:03 +02:00
|
|
|
.eval_expr(scope, state, fn_lib, rhs.as_ref(), level)?
|
2020-04-12 17:00:06 +02:00
|
|
|
.as_bool()
|
2020-03-05 18:05:02 +01:00
|
|
|
.map_err(|_| {
|
|
|
|
EvalAltResult::ErrorBooleanArgMismatch("AND".into(), rhs.position())
|
2020-04-22 06:12:13 +02:00
|
|
|
})?)
|
|
|
|
.into()),
|
2020-03-02 05:08:03 +01:00
|
|
|
|
2020-04-22 06:12:13 +02:00
|
|
|
Expr::Or(lhs, rhs, _) => Ok((self
|
2020-04-28 17:05:03 +02:00
|
|
|
.eval_expr(scope, state, fn_lib, lhs.as_ref(), level)?
|
2020-04-12 17:00:06 +02:00
|
|
|
.as_bool()
|
2020-03-02 15:13:14 +01:00
|
|
|
.map_err(|_| {
|
|
|
|
EvalAltResult::ErrorBooleanArgMismatch("OR".into(), lhs.position())
|
|
|
|
})?
|
2020-03-05 18:05:02 +01:00
|
|
|
|| // Short-circuit using ||
|
2020-04-02 06:35:44 +02:00
|
|
|
self
|
2020-04-28 17:05:03 +02:00
|
|
|
.eval_expr(scope, state, fn_lib, rhs.as_ref(), level)?
|
2020-04-12 17:00:06 +02:00
|
|
|
.as_bool()
|
2020-03-05 18:05:02 +01:00
|
|
|
.map_err(|_| {
|
|
|
|
EvalAltResult::ErrorBooleanArgMismatch("OR".into(), rhs.position())
|
2020-04-22 06:12:13 +02:00
|
|
|
})?)
|
|
|
|
.into()),
|
2020-03-02 05:08:03 +01:00
|
|
|
|
2020-04-22 06:12:13 +02:00
|
|
|
Expr::True(_) => Ok(true.into()),
|
|
|
|
Expr::False(_) => Ok(false.into()),
|
|
|
|
Expr::Unit(_) => Ok(().into()),
|
2020-04-10 06:16:39 +02:00
|
|
|
|
2020-05-04 11:43:54 +02:00
|
|
|
_ => unreachable!(),
|
2016-02-29 22:43:45 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-05 18:05:02 +01:00
|
|
|
/// Evaluate a statement
|
2020-03-02 07:28:42 +01:00
|
|
|
pub(crate) fn eval_stmt(
|
2020-04-07 07:23:06 +02:00
|
|
|
&self,
|
2020-03-02 07:28:42 +01:00
|
|
|
scope: &mut Scope,
|
2020-04-28 17:05:03 +02:00
|
|
|
state: &mut State,
|
2020-04-27 14:43:55 +02:00
|
|
|
fn_lib: &FunctionsLib,
|
2020-03-02 07:28:42 +01:00
|
|
|
stmt: &Stmt,
|
2020-03-27 07:34:01 +01:00
|
|
|
level: usize,
|
2020-04-17 18:14:33 +02:00
|
|
|
) -> Result<Dynamic, Box<EvalAltResult>> {
|
2020-02-29 10:10:51 +01:00
|
|
|
match stmt {
|
2020-03-09 14:57:07 +01:00
|
|
|
// No-op
|
2020-04-30 16:52:36 +02:00
|
|
|
Stmt::Noop(_) => Ok(Default::default()),
|
2020-03-09 14:57:07 +01:00
|
|
|
|
2020-03-06 16:49:52 +01:00
|
|
|
// Expression as statement
|
2020-03-14 04:51:45 +01:00
|
|
|
Stmt::Expr(expr) => {
|
2020-04-28 17:05:03 +02:00
|
|
|
let result = self.eval_expr(scope, state, fn_lib, expr, level)?;
|
2020-03-14 04:51:45 +01:00
|
|
|
|
2020-04-23 07:22:28 +02:00
|
|
|
Ok(if let Expr::Assignment(_, _, _) = *expr.as_ref() {
|
2020-03-14 04:51:45 +01:00
|
|
|
// If it is an assignment, erase the result at the root
|
2020-04-30 16:52:36 +02:00
|
|
|
Default::default()
|
2020-04-23 07:22:28 +02:00
|
|
|
} else {
|
|
|
|
result
|
2020-03-14 04:51:45 +01:00
|
|
|
})
|
|
|
|
}
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-03-06 16:49:52 +01:00
|
|
|
// Block scope
|
2020-03-09 14:57:07 +01:00
|
|
|
Stmt::Block(block, _) => {
|
2016-03-02 02:45:02 +01:00
|
|
|
let prev_len = scope.len();
|
2016-02-29 22:43:45 +01:00
|
|
|
|
2020-04-30 16:52:36 +02:00
|
|
|
let result = block.iter().try_fold(Default::default(), |_, stmt| {
|
2020-04-28 17:05:03 +02:00
|
|
|
self.eval_stmt(scope, state, fn_lib, stmt, level)
|
2020-03-27 07:34:01 +01:00
|
|
|
});
|
2016-02-29 22:43:45 +01:00
|
|
|
|
2020-03-06 16:49:52 +01:00
|
|
|
scope.rewind(prev_len);
|
2016-02-29 22:43:45 +01:00
|
|
|
|
2020-04-28 17:05:03 +02:00
|
|
|
// The impact of an eval statement goes away at the end of a block
|
|
|
|
// because any new variables introduced will go out of scope
|
|
|
|
state.always_search = false;
|
|
|
|
|
2020-03-16 16:51:32 +01:00
|
|
|
result
|
2016-02-29 22:43:45 +01:00
|
|
|
}
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-03-06 16:49:52 +01:00
|
|
|
// If-else statement
|
2020-03-22 03:18:16 +01:00
|
|
|
Stmt::IfThenElse(guard, if_body, else_body) => self
|
2020-04-28 17:05:03 +02:00
|
|
|
.eval_expr(scope, state, fn_lib, guard, level)?
|
2020-04-12 17:00:06 +02:00
|
|
|
.as_bool()
|
2020-04-17 18:14:33 +02:00
|
|
|
.map_err(|_| Box::new(EvalAltResult::ErrorLogicGuard(guard.position())))
|
2020-03-01 06:30:22 +01:00
|
|
|
.and_then(|guard_val| {
|
2020-04-02 06:35:44 +02:00
|
|
|
if guard_val {
|
2020-04-28 17:05:03 +02:00
|
|
|
self.eval_stmt(scope, state, fn_lib, if_body, level)
|
2020-03-05 18:05:02 +01:00
|
|
|
} else if let Some(stmt) = else_body {
|
2020-04-28 17:05:03 +02:00
|
|
|
self.eval_stmt(scope, state, fn_lib, stmt.as_ref(), level)
|
2020-03-01 06:30:22 +01:00
|
|
|
} else {
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok(Default::default())
|
2016-03-03 14:20:55 +01:00
|
|
|
}
|
2020-03-01 06:30:22 +01:00
|
|
|
}),
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-03-06 16:49:52 +01:00
|
|
|
// While loop
|
2020-02-29 10:10:51 +01:00
|
|
|
Stmt::While(guard, body) => loop {
|
2020-04-28 17:05:03 +02:00
|
|
|
match self
|
|
|
|
.eval_expr(scope, state, fn_lib, guard, level)?
|
|
|
|
.as_bool()
|
|
|
|
{
|
|
|
|
Ok(true) => match self.eval_stmt(scope, state, fn_lib, body, level) {
|
2020-04-17 18:14:33 +02:00
|
|
|
Ok(_) => (),
|
|
|
|
Err(err) => match *err {
|
|
|
|
EvalAltResult::ErrorLoopBreak(false, _) => (),
|
2020-04-30 16:52:36 +02:00
|
|
|
EvalAltResult::ErrorLoopBreak(true, _) => return Ok(Default::default()),
|
2020-04-17 18:14:33 +02:00
|
|
|
_ => return Err(err),
|
|
|
|
},
|
|
|
|
},
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok(false) => return Ok(Default::default()),
|
2020-04-17 18:14:33 +02:00
|
|
|
Err(_) => {
|
|
|
|
return Err(Box::new(EvalAltResult::ErrorLogicGuard(guard.position())))
|
2020-04-07 07:23:06 +02:00
|
|
|
}
|
2016-02-29 22:43:45 +01:00
|
|
|
}
|
2017-12-20 12:16:14 +01:00
|
|
|
},
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-03-06 16:49:52 +01:00
|
|
|
// Loop statement
|
2020-02-29 10:10:51 +01:00
|
|
|
Stmt::Loop(body) => loop {
|
2020-04-28 17:05:03 +02:00
|
|
|
match self.eval_stmt(scope, state, fn_lib, body, level) {
|
2020-04-17 18:14:33 +02:00
|
|
|
Ok(_) => (),
|
|
|
|
Err(err) => match *err {
|
|
|
|
EvalAltResult::ErrorLoopBreak(false, _) => (),
|
2020-04-30 16:52:36 +02:00
|
|
|
EvalAltResult::ErrorLoopBreak(true, _) => return Ok(Default::default()),
|
2020-04-17 18:14:33 +02:00
|
|
|
_ => return Err(err),
|
|
|
|
},
|
2017-10-30 16:08:44 +01:00
|
|
|
}
|
2017-12-20 12:16:14 +01:00
|
|
|
},
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-03-06 16:49:52 +01:00
|
|
|
// For loop
|
2020-02-29 10:10:51 +01:00
|
|
|
Stmt::For(name, expr, body) => {
|
2020-04-28 17:05:03 +02:00
|
|
|
let arr = self.eval_expr(scope, state, fn_lib, expr, level)?;
|
2020-04-12 17:00:06 +02:00
|
|
|
let tid = arr.type_id();
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-04-20 18:11:25 +02:00
|
|
|
if let Some(iter_fn) = self.type_iterators.get(&tid).or_else(|| {
|
|
|
|
self.packages
|
|
|
|
.iter()
|
2020-04-21 17:01:10 +02:00
|
|
|
.find(|pkg| pkg.type_iterators.contains_key(&tid))
|
|
|
|
.and_then(|pkg| pkg.type_iterators.get(&tid))
|
2020-04-20 18:11:25 +02:00
|
|
|
}) {
|
2020-04-24 16:54:56 +02:00
|
|
|
// Add the loop variable
|
2020-05-01 11:32:39 +02:00
|
|
|
let var_name = name.as_ref().clone();
|
|
|
|
scope.push(var_name, ());
|
2020-04-27 16:49:09 +02:00
|
|
|
let index = scope.len() - 1;
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-04-24 16:54:56 +02:00
|
|
|
for a in iter_fn(arr) {
|
2020-04-28 17:05:03 +02:00
|
|
|
*scope.get_mut(index).0 = a;
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-04-28 17:05:03 +02:00
|
|
|
match self.eval_stmt(scope, state, fn_lib, body, level) {
|
2020-04-17 18:14:33 +02:00
|
|
|
Ok(_) => (),
|
|
|
|
Err(err) => match *err {
|
|
|
|
EvalAltResult::ErrorLoopBreak(false, _) => (),
|
|
|
|
EvalAltResult::ErrorLoopBreak(true, _) => break,
|
|
|
|
_ => return Err(err),
|
|
|
|
},
|
2020-02-23 15:48:46 +01:00
|
|
|
}
|
2020-04-04 07:05:20 +02:00
|
|
|
}
|
2020-04-11 12:09:03 +02:00
|
|
|
|
|
|
|
scope.rewind(scope.len() - 1);
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok(Default::default())
|
2020-02-23 15:48:46 +01:00
|
|
|
} else {
|
2020-04-17 18:14:33 +02:00
|
|
|
Err(Box::new(EvalAltResult::ErrorFor(expr.position())))
|
2020-02-23 15:48:46 +01:00
|
|
|
}
|
|
|
|
}
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-04-01 10:22:18 +02:00
|
|
|
// Continue statement
|
2020-04-17 18:14:33 +02:00
|
|
|
Stmt::Continue(pos) => Err(Box::new(EvalAltResult::ErrorLoopBreak(false, *pos))),
|
2020-04-01 10:22:18 +02:00
|
|
|
|
2020-03-06 16:49:52 +01:00
|
|
|
// Break statement
|
2020-04-17 18:14:33 +02:00
|
|
|
Stmt::Break(pos) => Err(Box::new(EvalAltResult::ErrorLoopBreak(true, *pos))),
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-03-03 11:15:20 +01:00
|
|
|
// Empty return
|
2020-03-11 16:43:04 +01:00
|
|
|
Stmt::ReturnWithVal(None, ReturnType::Return, pos) => {
|
2020-04-30 16:52:36 +02:00
|
|
|
Err(Box::new(EvalAltResult::Return(Default::default(), *pos)))
|
2020-03-03 11:15:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Return value
|
2020-04-17 18:14:33 +02:00
|
|
|
Stmt::ReturnWithVal(Some(a), ReturnType::Return, pos) => Err(Box::new(
|
2020-04-28 17:05:03 +02:00
|
|
|
EvalAltResult::Return(self.eval_expr(scope, state, fn_lib, a, level)?, *pos),
|
2020-03-27 07:34:01 +01:00
|
|
|
)),
|
2020-03-03 11:15:20 +01:00
|
|
|
|
|
|
|
// Empty throw
|
2020-03-11 16:43:04 +01:00
|
|
|
Stmt::ReturnWithVal(None, ReturnType::Exception, pos) => {
|
2020-04-17 18:14:33 +02:00
|
|
|
Err(Box::new(EvalAltResult::ErrorRuntime("".into(), *pos)))
|
2020-03-03 11:15:20 +01:00
|
|
|
}
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-03-03 11:15:20 +01:00
|
|
|
// Throw value
|
2020-03-11 16:43:04 +01:00
|
|
|
Stmt::ReturnWithVal(Some(a), ReturnType::Exception, pos) => {
|
2020-04-28 17:05:03 +02:00
|
|
|
let val = self.eval_expr(scope, state, fn_lib, a, level)?;
|
2020-04-17 18:14:33 +02:00
|
|
|
Err(Box::new(EvalAltResult::ErrorRuntime(
|
2020-04-12 17:00:06 +02:00
|
|
|
val.take_string().unwrap_or_else(|_| "".to_string()),
|
2020-03-03 11:15:20 +01:00
|
|
|
*pos,
|
2020-04-17 18:14:33 +02:00
|
|
|
)))
|
2016-03-03 15:31:42 +01:00
|
|
|
}
|
2020-03-01 17:11:00 +01:00
|
|
|
|
2020-03-06 16:49:52 +01:00
|
|
|
// Let statement
|
2020-03-11 16:43:04 +01:00
|
|
|
Stmt::Let(name, Some(expr), _) => {
|
2020-04-28 17:05:03 +02:00
|
|
|
let val = self.eval_expr(scope, state, fn_lib, expr, level)?;
|
2020-04-05 11:44:48 +02:00
|
|
|
// TODO - avoid copying variable name in inner block?
|
2020-05-01 11:32:39 +02:00
|
|
|
let var_name = name.as_ref().clone();
|
|
|
|
scope.push_dynamic_value(var_name, ScopeEntryType::Normal, val, false);
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok(Default::default())
|
2020-03-11 16:43:04 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
Stmt::Let(name, None, _) => {
|
2020-04-05 11:44:48 +02:00
|
|
|
// TODO - avoid copying variable name in inner block?
|
2020-05-01 11:32:39 +02:00
|
|
|
let var_name = name.as_ref().clone();
|
|
|
|
scope.push(var_name, ());
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok(Default::default())
|
2016-02-29 22:43:45 +01:00
|
|
|
}
|
2020-03-13 11:12:41 +01:00
|
|
|
|
|
|
|
// Const statement
|
|
|
|
Stmt::Const(name, expr, _) if expr.is_constant() => {
|
2020-04-28 17:05:03 +02:00
|
|
|
let val = self.eval_expr(scope, state, fn_lib, expr, level)?;
|
2020-04-05 11:44:48 +02:00
|
|
|
// TODO - avoid copying variable name in inner block?
|
2020-05-01 11:32:39 +02:00
|
|
|
let var_name = name.as_ref().clone();
|
|
|
|
scope.push_dynamic_value(var_name, ScopeEntryType::Constant, val, true);
|
2020-04-30 16:52:36 +02:00
|
|
|
Ok(Default::default())
|
2020-03-13 11:12:41 +01:00
|
|
|
}
|
|
|
|
|
2020-05-04 11:43:54 +02:00
|
|
|
// Const expression not constant
|
|
|
|
Stmt::Const(_, _, _) => unreachable!(),
|
2020-05-04 13:36:58 +02:00
|
|
|
|
|
|
|
// Import statement
|
|
|
|
Stmt::Import(expr, name, _) => {
|
|
|
|
if let Some(path) = self
|
|
|
|
.eval_expr(scope, state, fn_lib, expr, level)?
|
|
|
|
.try_cast::<String>()
|
|
|
|
{
|
2020-05-05 04:39:12 +02:00
|
|
|
let mut module = Module::new();
|
2020-05-05 09:00:10 +02:00
|
|
|
module.set_variable("kitty", "foo".to_string());
|
|
|
|
module.set_variable("path", path);
|
2020-05-04 13:36:58 +02:00
|
|
|
|
|
|
|
// TODO - avoid copying module name in inner block?
|
|
|
|
let mod_name = name.as_ref().clone();
|
2020-05-05 04:39:12 +02:00
|
|
|
scope.push_module(mod_name, module);
|
2020-05-04 13:36:58 +02:00
|
|
|
Ok(Default::default())
|
|
|
|
} else {
|
|
|
|
Err(Box::new(EvalAltResult::ErrorImportExpr(expr.position())))
|
|
|
|
}
|
|
|
|
}
|
2016-02-29 22:43:45 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-05 18:05:02 +01:00
|
|
|
/// Map a type_name into a pretty-print name
|
2020-03-03 09:24:03 +01:00
|
|
|
pub(crate) fn map_type_name<'a>(&'a self, name: &'a str) -> &'a str {
|
2020-04-11 12:09:03 +02:00
|
|
|
self.type_names
|
2020-04-27 15:28:31 +02:00
|
|
|
.get(name)
|
|
|
|
.map(String::as_str)
|
2020-04-11 12:09:03 +02:00
|
|
|
.unwrap_or(name)
|
2020-03-02 16:16:19 +01:00
|
|
|
}
|
2016-03-01 15:40:48 +01:00
|
|
|
}
|