rhai/src/eval/expr.rs

478 lines
19 KiB
Rust
Raw Normal View History

2022-01-07 11:43:47 +08:00
//! Module defining functions for evaluating an expression.
2022-04-16 16:36:53 +08:00
use super::{Caches, EvalContext, GlobalRuntimeState, Target};
2022-10-30 18:43:18 +08:00
use crate::ast::{Expr, OpAssignment};
2022-01-07 12:19:01 +08:00
use crate::engine::{KEYWORD_THIS, OP_CONCAT};
use crate::types::dynamic::AccessMode;
use crate::{Dynamic, Engine, Module, Position, RhaiResult, RhaiResultOf, Scope, Shared, ERR};
use std::num::NonZeroUsize;
2022-01-07 11:43:47 +08:00
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
impl Engine {
/// Search for a module within an imports stack.
2022-01-29 11:09:43 +08:00
#[cfg(not(feature = "no_module"))]
2022-01-07 11:43:47 +08:00
#[inline]
#[must_use]
pub(crate) fn search_imports(
&self,
global: &GlobalRuntimeState,
2022-03-05 17:57:23 +08:00
namespace: &crate::ast::Namespace,
) -> Option<Shared<Module>> {
2022-03-05 17:57:23 +08:00
assert!(!namespace.is_empty());
2022-03-03 13:02:57 +08:00
let root = namespace.root();
2022-01-07 11:43:47 +08:00
2022-04-16 16:36:53 +08:00
let index = if global.always_search_scope {
2022-01-07 11:43:47 +08:00
None
} else {
namespace.index()
};
2022-10-14 14:04:54 +08:00
// Qualified - check if the root module is directly indexed
2022-01-07 11:43:47 +08:00
if let Some(index) = index {
let offset = global.num_imports() - index.get();
if let m @ Some(_) = global.get_shared_import(offset) {
return m;
}
2022-01-07 11:43:47 +08:00
}
// Do a text-match search if the index doesn't work
global.find_import(root).map_or_else(
|| self.global_sub_modules.get(root).cloned(),
|offset| global.get_shared_import(offset),
)
2022-01-07 11:43:47 +08:00
}
/// Search for a variable within the scope or within imports,
/// depending on whether the variable name is namespace-qualified.
pub(crate) fn search_namespace<'s>(
&self,
global: &mut GlobalRuntimeState,
2022-11-04 21:47:09 +08:00
caches: &mut Caches,
lib: &[Shared<Module>],
2022-11-04 21:47:09 +08:00
level: usize,
scope: &'s mut Scope,
2022-01-07 11:43:47 +08:00
this_ptr: &'s mut Option<&mut Dynamic>,
expr: &Expr,
) -> RhaiResultOf<(Target<'s>, Position)> {
match expr {
2022-03-05 17:57:23 +08:00
Expr::Variable(_, Some(_), _) => {
2022-11-04 21:47:09 +08:00
self.search_scope_only(global, caches, lib, level, scope, this_ptr, expr)
2022-01-07 11:43:47 +08:00
}
2022-07-05 16:26:38 +08:00
Expr::Variable(v, None, _var_pos) => match &**v {
2022-01-07 11:43:47 +08:00
// Normal variable access
2022-01-29 11:09:43 +08:00
#[cfg(not(feature = "no_module"))]
2022-03-05 17:57:23 +08:00
(_, ns, ..) if ns.is_empty() => {
2022-11-04 21:47:09 +08:00
self.search_scope_only(global, caches, lib, level, scope, this_ptr, expr)
2022-02-04 22:16:12 +08:00
}
2022-01-29 11:09:43 +08:00
#[cfg(feature = "no_module")]
2022-11-04 22:00:21 +08:00
(_, (), ..) => {
self.search_scope_only(global, caches, lib, level, scope, this_ptr, expr)
}
2022-01-07 11:43:47 +08:00
// Qualified variable access
#[cfg(not(feature = "no_module"))]
2022-03-05 17:57:23 +08:00
(_, namespace, hash_var, var_name) => {
2022-01-28 18:59:18 +08:00
// foo:bar::baz::VARIABLE
2022-04-16 16:36:53 +08:00
if let Some(module) = self.search_imports(global, namespace) {
2022-08-27 16:26:41 +08:00
return module.get_qualified_var(*hash_var).map_or_else(
|| {
let sep = crate::tokenizer::Token::DoubleColon.literal_syntax();
Err(ERR::ErrorVariableNotFound(
format!("{namespace}{sep}{var_name}"),
namespace.position(),
)
.into())
},
|mut target| {
// Module variables are constant
target.set_access_mode(AccessMode::ReadOnly);
Ok((target.into(), *_var_pos))
},
);
2022-01-07 11:43:47 +08:00
}
2022-01-28 18:59:18 +08:00
// global::VARIABLE
2022-01-07 11:43:47 +08:00
#[cfg(not(feature = "no_function"))]
2022-03-03 13:02:57 +08:00
if namespace.len() == 1 && namespace.root() == crate::engine::KEYWORD_GLOBAL {
2022-01-28 22:07:49 +08:00
if let Some(ref constants) = global.constants {
2022-01-28 22:37:59 +08:00
if let Some(value) =
2022-08-13 18:07:42 +08:00
crate::func::locked_write(constants).get_mut(var_name.as_str())
2022-01-28 22:37:59 +08:00
{
2022-01-28 22:07:49 +08:00
let mut target: Target = value.clone().into();
// Module variables are constant
target.set_access_mode(AccessMode::ReadOnly);
2022-07-20 21:28:17 +09:00
return Ok((target, *_var_pos));
2022-01-28 22:07:49 +08:00
}
2022-01-07 11:43:47 +08:00
}
2022-03-03 13:02:57 +08:00
let sep = crate::tokenizer::Token::DoubleColon.literal_syntax();
2022-01-07 11:43:47 +08:00
return Err(ERR::ErrorVariableNotFound(
2022-08-11 19:01:23 +08:00
format!("{namespace}{sep}{var_name}"),
2022-03-03 13:02:57 +08:00
namespace.position(),
2022-01-07 11:43:47 +08:00
)
.into());
}
2022-03-03 13:02:57 +08:00
Err(
ERR::ErrorModuleNotFound(namespace.to_string(), namespace.position())
.into(),
)
2022-01-07 11:43:47 +08:00
}
},
_ => unreachable!("Expr::Variable expected but gets {:?}", expr),
}
}
/// Search for a variable within the scope
///
/// # Panics
///
/// Panics if `expr` is not [`Expr::Variable`].
pub(crate) fn search_scope_only<'s>(
&self,
global: &mut GlobalRuntimeState,
2022-11-04 21:47:09 +08:00
caches: &mut Caches,
lib: &[Shared<Module>],
2022-11-04 21:47:09 +08:00
level: usize,
scope: &'s mut Scope,
2022-01-07 11:43:47 +08:00
this_ptr: &'s mut Option<&mut Dynamic>,
expr: &Expr,
) -> RhaiResultOf<(Target<'s>, Position)> {
// Make sure that the pointer indirection is taken only when absolutely necessary.
let (index, var_pos) = match expr {
// Check if the variable is `this`
2022-03-05 17:57:23 +08:00
Expr::Variable(v, None, pos) if v.0.is_none() && v.3 == KEYWORD_THIS => {
2022-08-29 14:27:05 +08:00
return this_ptr.as_mut().map_or_else(
|| Err(ERR::ErrorUnboundThis(*pos).into()),
|val| Ok(((*val).into(), *pos)),
)
2022-01-07 11:43:47 +08:00
}
2022-04-16 16:36:53 +08:00
_ if global.always_search_scope => (0, expr.start_position()),
2022-03-05 17:57:23 +08:00
Expr::Variable(.., Some(i), pos) => (i.get() as usize, *pos),
2022-08-05 23:30:44 +08:00
// Scripted function with the same name
#[cfg(not(feature = "no_function"))]
Expr::Variable(v, None, pos)
if lib
.iter()
.flat_map(|m| m.iter_script_fn())
2022-08-13 18:07:42 +08:00
.any(|(_, _, f, ..)| f == v.3.as_str()) =>
2022-08-05 23:30:44 +08:00
{
let val: Dynamic =
crate::FnPtr::new_unchecked(v.3.as_str(), Default::default()).into();
return Ok((val.into(), *pos));
}
2022-07-27 18:04:59 +08:00
Expr::Variable(v, None, pos) => (v.0.map_or(0, NonZeroUsize::get), *pos),
2022-01-07 11:43:47 +08:00
_ => unreachable!("Expr::Variable expected but gets {:?}", expr),
};
// Check the variable resolver, if any
if let Some(ref resolve_var) = self.resolve_var {
2022-11-04 21:47:09 +08:00
let context = EvalContext::new(self, global, Some(caches), lib, level, scope, this_ptr);
let var_name = expr.get_variable_name(true).expect("`Expr::Variable`");
2022-05-02 00:03:45 +08:00
match resolve_var(var_name, index, context) {
2022-01-07 11:43:47 +08:00
Ok(Some(mut result)) => {
result.set_access_mode(AccessMode::ReadOnly);
return Ok((result.into(), var_pos));
}
Ok(None) => (),
Err(err) => return Err(err.fill_position(var_pos)),
}
}
let index = if index > 0 {
scope.len() - index
} else {
// Find the variable in the scope
let var_name = expr.get_variable_name(true).expect("`Expr::Variable`");
2022-10-25 10:05:31 +08:00
match scope.search(var_name) {
2022-10-25 08:31:13 +08:00
Some(index) => index,
None => {
return match self.global_modules.iter().find_map(|m| m.get_var(var_name)) {
Some(val) => Ok((val.into(), var_pos)),
None => {
Err(ERR::ErrorVariableNotFound(var_name.to_string(), var_pos).into())
}
}
}
}
2022-01-07 11:43:47 +08:00
};
let val = scope.get_mut_by_index(index);
Ok((val.into(), var_pos))
}
/// Evaluate an expression.
2022-01-24 17:04:40 +08:00
//
// # Implementation Notes
//
// Do not use the `?` operator within the main body as it makes this function return early,
// possibly by-passing important cleanup tasks at the end.
//
// Errors that are not recoverable, such as system errors or safety errors, can use `?`.
2022-01-07 11:43:47 +08:00
pub(crate) fn eval_expr(
&self,
global: &mut GlobalRuntimeState,
2022-04-16 16:36:53 +08:00
caches: &mut Caches,
lib: &[Shared<Module>],
2022-11-04 21:47:09 +08:00
level: usize,
scope: &mut Scope,
2022-01-07 11:43:47 +08:00
this_ptr: &mut Option<&mut Dynamic>,
expr: &Expr,
) -> RhaiResult {
// Coded this way for better branch prediction.
// Popular branches are lifted out of the `match` statement into their own branches.
// Function calls should account for a relatively larger portion of expressions because
// binary operators are also function calls.
2022-10-30 18:43:18 +08:00
if let Expr::FnCall(x, pos) = expr {
2022-01-25 12:24:30 +08:00
#[cfg(feature = "debugging")]
2022-02-03 11:56:08 +08:00
let reset_debugger =
2022-11-04 21:47:09 +08:00
self.run_debugger_with_reset(global, caches, lib, level, scope, this_ptr, expr)?;
2022-01-25 12:24:30 +08:00
2022-10-05 15:07:54 +08:00
self.track_operation(global, expr.position())?;
2022-01-07 11:43:47 +08:00
2022-01-24 17:04:40 +08:00
let result =
2022-11-04 21:47:09 +08:00
self.eval_fn_call_expr(global, caches, lib, level, scope, this_ptr, x, *pos);
2022-01-24 17:04:40 +08:00
#[cfg(feature = "debugging")]
2022-01-25 12:24:30 +08:00
global.debugger.reset_status(reset_debugger);
2022-01-24 17:04:40 +08:00
return result;
2022-01-07 11:43:47 +08:00
}
// Then variable access.
// We shouldn't do this for too many variants because, soon or later, the added comparisons
// will cost more than the mis-predicted `match` branch.
2022-03-05 17:57:23 +08:00
if let Expr::Variable(x, index, var_pos) = expr {
2022-01-25 12:24:30 +08:00
#[cfg(feature = "debugging")]
2022-11-04 21:47:09 +08:00
self.run_debugger(global, caches, lib, level, scope, this_ptr, expr)?;
2022-01-25 12:24:30 +08:00
2022-10-05 15:07:54 +08:00
self.track_operation(global, expr.position())?;
2022-01-07 11:43:47 +08:00
2022-03-05 17:57:23 +08:00
return if index.is_none() && x.0.is_none() && x.3 == KEYWORD_THIS {
2022-01-07 11:43:47 +08:00
this_ptr
.as_deref()
.cloned()
.ok_or_else(|| ERR::ErrorUnboundThis(*var_pos).into())
} else {
2022-11-04 21:47:09 +08:00
self.search_namespace(global, caches, lib, level, scope, this_ptr, expr)
2022-02-08 09:02:15 +08:00
.map(|(val, ..)| val.take_or_clone())
2022-01-07 11:43:47 +08:00
};
}
2022-01-25 12:24:30 +08:00
#[cfg(feature = "debugging")]
2022-02-03 11:56:08 +08:00
let reset_debugger =
2022-11-04 21:47:09 +08:00
self.run_debugger_with_reset(global, caches, lib, level, scope, this_ptr, expr)?;
2022-01-25 12:24:30 +08:00
2022-10-05 15:07:54 +08:00
self.track_operation(global, expr.position())?;
2022-01-07 11:43:47 +08:00
2022-01-24 17:04:40 +08:00
let result = match expr {
2022-01-07 11:43:47 +08:00
// Constants
2022-02-08 09:02:15 +08:00
Expr::DynamicConstant(x, ..) => Ok(x.as_ref().clone()),
Expr::IntegerConstant(x, ..) => Ok((*x).into()),
2022-01-07 11:43:47 +08:00
#[cfg(not(feature = "no_float"))]
2022-02-08 09:02:15 +08:00
Expr::FloatConstant(x, ..) => Ok((*x).into()),
Expr::StringConstant(x, ..) => Ok(x.clone().into()),
Expr::CharConstant(x, ..) => Ok((*x).into()),
Expr::BoolConstant(x, ..) => Ok((*x).into()),
2022-02-08 09:46:14 +08:00
Expr::Unit(..) => Ok(Dynamic::UNIT),
2022-01-07 11:43:47 +08:00
// `... ${...} ...`
2022-02-10 17:55:32 +08:00
Expr::InterpolatedString(x, _) => {
2022-08-12 16:34:57 +08:00
let mut concat = self.get_interned_string("").into();
2022-04-18 23:12:47 +08:00
let target = &mut concat;
2022-01-07 11:43:47 +08:00
2022-04-18 23:12:47 +08:00
let mut op_info = OpAssignment::new_op_assignment(OP_CONCAT, Position::NONE);
let root = ("", Position::NONE);
2022-10-18 15:44:24 +08:00
let result = x
.iter()
.try_for_each(|expr| {
let item =
2022-11-04 21:47:09 +08:00
self.eval_expr(global, caches, lib, level, scope, this_ptr, expr)?;
2022-01-07 11:43:47 +08:00
2022-10-18 15:44:24 +08:00
op_info.pos = expr.start_position();
2022-04-18 23:12:47 +08:00
2022-10-18 15:44:24 +08:00
self.eval_op_assignment(
2022-11-04 21:47:09 +08:00
global, caches, lib, level, &op_info, target, root, item,
2022-10-18 15:44:24 +08:00
)
})
.map(|_| concat.take_or_clone());
2022-01-07 11:43:47 +08:00
2022-10-18 15:44:24 +08:00
self.check_return_value(result, expr.start_position())
2022-01-07 11:43:47 +08:00
}
#[cfg(not(feature = "no_index"))]
2022-02-08 09:02:15 +08:00
Expr::Array(x, ..) => {
2022-01-07 11:43:47 +08:00
#[cfg(not(feature = "unchecked"))]
2022-10-05 15:07:54 +08:00
let mut total_data_sizes = (0, 0, 0);
2022-01-07 11:43:47 +08:00
2022-10-18 15:44:24 +08:00
x.iter()
.try_fold(
crate::Array::with_capacity(x.len()),
|mut array, item_expr| {
let value = self
2022-11-04 21:47:09 +08:00
.eval_expr(global, caches, lib, level, scope, this_ptr, item_expr)?
2022-10-18 15:44:24 +08:00
.flatten();
#[cfg(not(feature = "unchecked"))]
if self.has_data_size_limit() {
let val_sizes = Self::calc_data_sizes(&value, true);
total_data_sizes = (
total_data_sizes.0 + val_sizes.0,
total_data_sizes.1 + val_sizes.1,
total_data_sizes.2 + val_sizes.2,
);
2022-10-20 11:38:54 +08:00
self.raise_err_if_over_data_size_limit(total_data_sizes)
.map_err(|err| err.fill_position(item_expr.position()))?;
2022-10-18 15:44:24 +08:00
}
2022-10-05 15:07:54 +08:00
2022-10-18 15:44:24 +08:00
array.push(value);
2022-01-07 11:43:47 +08:00
2022-10-18 15:44:24 +08:00
Ok(array)
},
)
.map(Into::into)
2022-01-07 11:43:47 +08:00
}
#[cfg(not(feature = "no_object"))]
2022-02-08 09:02:15 +08:00
Expr::Map(x, ..) => {
2022-01-07 11:43:47 +08:00
#[cfg(not(feature = "unchecked"))]
2022-10-05 15:07:54 +08:00
let mut total_data_sizes = (0, 0, 0);
2022-01-07 11:43:47 +08:00
2022-10-18 15:44:24 +08:00
x.0.iter()
.try_fold(x.1.clone(), |mut map, (key, value_expr)| {
let value = self
2022-11-04 21:47:09 +08:00
.eval_expr(global, caches, lib, level, scope, this_ptr, value_expr)?
2022-10-18 15:44:24 +08:00
.flatten();
#[cfg(not(feature = "unchecked"))]
if self.has_data_size_limit() {
let delta = Self::calc_data_sizes(&value, true);
total_data_sizes = (
total_data_sizes.0 + delta.0,
total_data_sizes.1 + delta.1,
total_data_sizes.2 + delta.2,
);
2022-10-20 11:38:54 +08:00
self.raise_err_if_over_data_size_limit(total_data_sizes)
.map_err(|err| err.fill_position(value_expr.position()))?;
2022-01-24 17:04:40 +08:00
}
2022-10-05 15:07:54 +08:00
2022-10-18 15:44:24 +08:00
*map.get_mut(key.as_str()).unwrap() = value;
2022-01-07 11:43:47 +08:00
2022-10-18 15:44:24 +08:00
Ok(map)
})
.map(Into::into)
2022-01-07 11:43:47 +08:00
}
2022-02-08 09:02:15 +08:00
Expr::And(x, ..) => {
2022-01-24 17:04:40 +08:00
let lhs = self
2022-11-04 21:47:09 +08:00
.eval_expr(global, caches, lib, level, scope, this_ptr, &x.lhs)
2022-01-24 17:04:40 +08:00
.and_then(|v| {
v.as_bool().map_err(|typ| {
self.make_type_mismatch_err::<bool>(typ, x.lhs.position())
})
});
2022-10-18 15:44:24 +08:00
match lhs {
Ok(true) => self
2022-11-04 21:47:09 +08:00
.eval_expr(global, caches, lib, level, scope, this_ptr, &x.rhs)
2022-01-24 17:04:40 +08:00
.and_then(|v| {
v.as_bool()
.map_err(|typ| {
self.make_type_mismatch_err::<bool>(typ, x.rhs.position())
})
.map(Into::into)
2022-10-18 15:44:24 +08:00
}),
_ => lhs.map(Into::into),
2022-01-24 17:04:40 +08:00
}
2022-01-07 11:43:47 +08:00
}
2022-02-08 09:02:15 +08:00
Expr::Or(x, ..) => {
2022-01-24 17:04:40 +08:00
let lhs = self
2022-11-04 21:47:09 +08:00
.eval_expr(global, caches, lib, level, scope, this_ptr, &x.lhs)
2022-01-24 17:04:40 +08:00
.and_then(|v| {
v.as_bool().map_err(|typ| {
self.make_type_mismatch_err::<bool>(typ, x.lhs.position())
})
});
2022-10-18 15:44:24 +08:00
match lhs {
Ok(false) => self
2022-11-04 21:47:09 +08:00
.eval_expr(global, caches, lib, level, scope, this_ptr, &x.rhs)
2022-01-24 17:04:40 +08:00
.and_then(|v| {
v.as_bool()
.map_err(|typ| {
self.make_type_mismatch_err::<bool>(typ, x.rhs.position())
})
.map(Into::into)
2022-10-18 15:44:24 +08:00
}),
_ => lhs.map(Into::into),
2022-01-24 17:04:40 +08:00
}
2022-01-07 11:43:47 +08:00
}
2022-06-10 11:22:33 +08:00
Expr::Coalesce(x, ..) => {
2022-11-04 21:47:09 +08:00
let lhs = self.eval_expr(global, caches, lib, level, scope, this_ptr, &x.lhs);
2022-06-10 11:22:33 +08:00
match lhs {
Ok(value) if value.is::<()>() => {
2022-11-04 21:47:09 +08:00
self.eval_expr(global, caches, lib, level, scope, this_ptr, &x.rhs)
2022-06-10 11:22:33 +08:00
}
2022-10-18 15:44:24 +08:00
_ => lhs,
2022-06-10 11:22:33 +08:00
}
}
2022-07-05 22:59:03 +08:00
#[cfg(not(feature = "no_custom_syntax"))]
2022-01-11 11:33:54 +08:00
Expr::Custom(custom, pos) => {
2022-07-05 22:59:03 +08:00
let expressions: crate::StaticVec<_> =
custom.inputs.iter().map(Into::into).collect();
2022-01-11 11:33:54 +08:00
// The first token acts as the custom syntax's key
2022-01-07 11:43:47 +08:00
let key_token = custom.tokens.first().unwrap();
2022-01-11 11:33:54 +08:00
// The key should exist, unless the AST is compiled in a different Engine
2022-08-13 18:07:42 +08:00
let custom_def = self.custom_syntax.get(key_token.as_str()).ok_or_else(|| {
2022-01-11 11:33:54 +08:00
Box::new(ERR::ErrorCustomSyntax(
2022-08-11 19:01:23 +08:00
format!("Invalid custom syntax prefix: {key_token}"),
2022-07-27 18:04:59 +08:00
custom.tokens.iter().map(<_>::to_string).collect(),
2022-01-11 11:33:54 +08:00
*pos,
2022-01-10 20:08:03 +08:00
))
})?;
2022-05-17 16:21:17 +08:00
let mut context =
2022-11-04 21:47:09 +08:00
EvalContext::new(self, global, Some(caches), lib, level, scope, this_ptr);
2022-01-07 11:43:47 +08:00
2022-09-12 12:03:32 +08:00
let result = (custom_def.func)(&mut context, &expressions, &custom.state);
2022-01-07 11:43:47 +08:00
2022-02-04 12:04:33 +08:00
self.check_return_value(result, expr.start_position())
2022-01-07 11:43:47 +08:00
}
Expr::Stmt(x) if x.is_empty() => Ok(Dynamic::UNIT),
Expr::Stmt(x) => {
2022-11-04 21:47:09 +08:00
self.eval_stmt_block(global, caches, lib, level, scope, this_ptr, x, true)
2022-01-07 11:43:47 +08:00
}
#[cfg(not(feature = "no_index"))]
2022-09-27 23:04:22 +08:00
Expr::Index(..) => self
2022-11-04 21:47:09 +08:00
.eval_dot_index_chain(global, caches, lib, level, scope, this_ptr, expr, &mut None),
2022-01-07 11:43:47 +08:00
#[cfg(not(feature = "no_object"))]
2022-09-27 23:04:22 +08:00
Expr::Dot(..) => self
2022-11-04 21:47:09 +08:00
.eval_dot_index_chain(global, caches, lib, level, scope, this_ptr, expr, &mut None),
2022-01-07 11:43:47 +08:00
_ => unreachable!("expression cannot be evaluated: {:?}", expr),
2022-01-24 17:04:40 +08:00
};
#[cfg(feature = "debugging")]
2022-01-25 12:24:30 +08:00
global.debugger.reset_status(reset_debugger);
2022-01-24 17:04:40 +08:00
2022-07-20 21:38:50 +09:00
result
2022-01-07 11:43:47 +08:00
}
}