rhai/src/eval/chaining.rs

1069 lines
47 KiB
Rust
Raw Normal View History

2022-01-07 04:43:47 +01:00
//! Types to support chaining operations (i.e. indexing and dotting).
#![cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
2022-04-16 10:36:53 +02:00
use super::{Caches, GlobalRuntimeState, Target};
2022-02-25 04:42:59 +01:00
use crate::ast::{ASTFlags, Expr, OpAssignment};
2022-01-07 05:19:01 +01:00
use crate::types::dynamic::Union;
2022-02-09 06:12:43 +01:00
use crate::{Dynamic, Engine, Module, Position, RhaiResult, RhaiResultOf, Scope, StaticVec, ERR};
2022-01-07 04:43:47 +01:00
use std::hash::Hash;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
/// Method of chaining.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum ChainType {
/// Indexing.
#[cfg(not(feature = "no_index"))]
Indexing,
/// Dotting.
#[cfg(not(feature = "no_object"))]
Dotting,
}
impl From<&Expr> for ChainType {
#[inline]
fn from(expr: &Expr) -> Self {
match expr {
#[cfg(not(feature = "no_index"))]
2022-02-08 02:02:15 +01:00
Expr::Index(..) => Self::Indexing,
2022-01-07 04:43:47 +01:00
#[cfg(not(feature = "no_object"))]
2022-02-08 02:02:15 +01:00
Expr::Dot(..) => Self::Dotting,
2022-01-07 04:43:47 +01:00
expr => unreachable!("Expr::Index or Expr::Dot expected but gets {:?}", expr),
}
}
}
/// Value of a chaining argument.
#[derive(Debug, Clone, Hash)]
pub enum ChainArgument {
/// Dot-property access.
#[cfg(not(feature = "no_object"))]
Property(Position),
/// Arguments to a dot method call.
/// Wrapped values are the arguments plus the [position][Position] of the first argument.
///
/// Since many dotted function calls have no arguments (e.g. `string.len()`), it is better to
/// reduce the size of [`ChainArgument`] by using a boxed slice.
#[cfg(not(feature = "no_object"))]
2022-03-06 09:37:27 +01:00
MethodCallArgs(Box<[Dynamic]>, Position),
2022-01-07 04:43:47 +01:00
/// Index value and [position][Position].
#[cfg(not(feature = "no_index"))]
IndexValue(Dynamic, Position),
}
impl ChainArgument {
/// Return the index value.
#[inline(always)]
#[cfg(not(feature = "no_index"))]
#[must_use]
pub fn into_index_value(self) -> Option<Dynamic> {
match self {
2022-02-08 02:02:15 +01:00
Self::IndexValue(value, ..) => Some(value),
2022-01-07 04:43:47 +01:00
#[cfg(not(feature = "no_object"))]
_ => None,
}
}
/// Return the list of method call arguments.
///
/// # Panics
///
/// Panics if the [`ChainArgument`] is not [`MethodCallArgs`][ChainArgument::MethodCallArgs].
#[inline(always)]
#[cfg(not(feature = "no_object"))]
#[must_use]
pub fn into_fn_call_args(self) -> (crate::FnArgsVec<Dynamic>, Position) {
match self {
2022-03-06 09:37:27 +01:00
Self::MethodCallArgs(values, pos) if values.is_empty() => {
(crate::FnArgsVec::new_const(), pos)
}
Self::MethodCallArgs(mut values, pos) => {
2022-01-07 04:43:47 +01:00
(values.iter_mut().map(std::mem::take).collect(), pos)
}
x => unreachable!("ChainArgument::MethodCallArgs expected but gets {:?}", x),
}
}
/// Return the [position][Position].
#[inline(always)]
#[must_use]
#[allow(dead_code)]
pub const fn position(&self) -> Position {
match self {
#[cfg(not(feature = "no_object"))]
ChainArgument::Property(pos) => *pos,
#[cfg(not(feature = "no_object"))]
2022-02-08 02:02:15 +01:00
ChainArgument::MethodCallArgs(.., pos) => *pos,
2022-01-07 04:43:47 +01:00
#[cfg(not(feature = "no_index"))]
2022-02-08 02:02:15 +01:00
ChainArgument::IndexValue(.., pos) => *pos,
2022-01-07 04:43:47 +01:00
}
}
/// Create n [`MethodCallArgs`][ChainArgument::MethodCallArgs].
#[inline(always)]
#[cfg(not(feature = "no_object"))]
#[must_use]
pub fn from_fn_call_args(values: crate::FnArgsVec<Dynamic>, pos: Position) -> Self {
if values.is_empty() {
2022-03-06 09:37:27 +01:00
Self::MethodCallArgs(Box::default(), pos)
2022-01-07 04:43:47 +01:00
} else {
2022-03-06 09:37:27 +01:00
Self::MethodCallArgs(values.into_boxed_slice(), pos)
2022-01-07 04:43:47 +01:00
}
}
/// Create an [`IndexValue`][ChainArgument::IndexValue].
#[inline(always)]
#[cfg(not(feature = "no_index"))]
#[must_use]
pub const fn from_index_value(value: Dynamic, pos: Position) -> Self {
Self::IndexValue(value, pos)
}
}
2022-01-07 05:19:01 +01:00
impl Engine {
/// Chain-evaluate a dot/index chain.
/// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and must be set afterwards.
fn eval_dot_index_chain_helper(
&self,
global: &mut GlobalRuntimeState,
2022-04-16 10:36:53 +02:00
caches: &mut Caches,
2022-01-07 05:19:01 +01:00
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
target: &mut Target,
root: (&str, Position),
2022-04-11 10:29:16 +02:00
_parent: &Expr,
2022-01-07 05:19:01 +01:00
rhs: &Expr,
2022-04-11 10:29:16 +02:00
_parent_options: ASTFlags,
2022-04-18 17:12:47 +02:00
idx_values: &mut StaticVec<ChainArgument>,
2022-01-07 05:19:01 +01:00
chain_type: ChainType,
level: usize,
2022-04-18 17:12:47 +02:00
new_val: Option<(Dynamic, OpAssignment)>,
2022-01-07 05:19:01 +01:00
) -> RhaiResultOf<(Dynamic, bool)> {
let is_ref_mut = target.is_ref();
// Pop the last index value
let idx_val = idx_values.pop().unwrap();
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
let scope = &mut Scope::new();
2022-01-07 05:19:01 +01:00
match chain_type {
#[cfg(not(feature = "no_index"))]
ChainType::Indexing => {
2022-02-04 05:04:33 +01:00
let pos = rhs.start_position();
2022-01-07 05:19:01 +01:00
let idx_val = idx_val.into_index_value().expect("`ChainType::Index`");
match rhs {
// xxx[idx].expr... | xxx[idx][expr]...
2022-02-25 04:42:59 +01:00
Expr::Dot(x, options, x_pos) | Expr::Index(x, options, x_pos)
if !_parent_options.contains(ASTFlags::BREAK) =>
2022-01-07 05:19:01 +01:00
{
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
self.run_debugger(scope, global, lib, this_ptr, _parent, level)?;
2022-01-25 05:24:30 +01:00
2022-01-07 05:19:01 +01:00
let mut idx_val_for_setter = idx_val.clone();
2022-02-04 05:04:33 +01:00
let idx_pos = x.lhs.start_position();
2022-01-07 05:19:01 +01:00
let rhs_chain = rhs.into();
let (try_setter, result) = {
let mut obj = self.get_indexed_mut(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, idx_val, idx_pos, false, true, level,
2022-01-07 05:19:01 +01:00
)?;
let is_obj_temp_val = obj.is_temp_value();
let obj_ptr = &mut obj;
match self.eval_dot_index_chain_helper(
2022-04-16 10:36:53 +02:00
global, caches, lib, this_ptr, obj_ptr, root, rhs, &x.rhs,
*options, idx_values, rhs_chain, level, new_val,
2022-01-07 05:19:01 +01:00
) {
Ok((result, true)) if is_obj_temp_val => {
(Some(obj.take_or_clone()), (result, true))
}
Ok(result) => (None, result),
Err(err) => return Err(err.fill_position(*x_pos)),
}
};
if let Some(mut new_val) = try_setter {
// Try to call index setter if value is changed
2022-02-09 06:12:43 +01:00
let idx = &mut idx_val_for_setter;
let new_val = &mut new_val;
self.call_indexer_set(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, idx, new_val, is_ref_mut, level,
2022-02-09 06:12:43 +01:00
)
2022-02-24 03:36:20 +01:00
.or_else(|e| match *e {
2022-02-09 06:12:43 +01:00
ERR::ErrorIndexingType(..) => Ok((Dynamic::UNIT, false)),
2022-02-24 03:36:20 +01:00
_ => Err(e),
2022-02-09 06:12:43 +01:00
})?;
2022-01-07 05:19:01 +01:00
}
Ok(result)
}
// xxx[rhs] op= new_val
_ if new_val.is_some() => {
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
self.run_debugger(scope, global, lib, this_ptr, _parent, level)?;
2022-01-25 05:24:30 +01:00
2022-04-18 17:12:47 +02:00
let (new_val, op_info) = new_val.expect("`Some`");
let mut idx_val2 = idx_val.clone();
2022-01-07 05:19:01 +01:00
let try_setter = match self.get_indexed_mut(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, idx_val, pos, true, false, level,
2022-01-07 05:19:01 +01:00
) {
// Indexed value is not a temp value - update directly
2022-01-07 05:19:01 +01:00
Ok(ref mut obj_ptr) => {
self.eval_op_assignment(
2022-04-18 17:12:47 +02:00
global, caches, lib, op_info, obj_ptr, root, new_val, level,
)?;
2022-01-07 05:19:01 +01:00
#[cfg(not(feature = "unchecked"))]
2022-04-18 17:12:47 +02:00
self.check_data_size(obj_ptr, op_info.pos)?;
2022-01-07 05:19:01 +01:00
None
}
// Indexed value cannot be referenced - use indexer
2022-01-07 05:19:01 +01:00
#[cfg(not(feature = "no_index"))]
2022-02-08 02:02:15 +01:00
Err(err) if matches!(*err, ERR::ErrorIndexingType(..)) => Some(new_val),
2022-01-07 05:19:01 +01:00
// Any other error
Err(err) => return Err(err),
};
if let Some(mut new_val) = try_setter {
let idx = &mut idx_val2;
// Is this an op-assignment?
2022-04-18 17:12:47 +02:00
if op_info.is_op_assignment() {
let idx = &mut idx.clone();
// Call the index getter to get the current value
if let Ok(val) =
2022-04-16 10:36:53 +02:00
self.call_indexer_get(global, caches, lib, target, idx, level)
{
let mut res = val.into();
// Run the op-assignment
self.eval_op_assignment(
2022-04-18 17:12:47 +02:00
global, caches, lib, op_info, &mut res, root, new_val,
level,
)?;
// Replace new value
new_val = res.take_or_clone();
#[cfg(not(feature = "unchecked"))]
2022-04-18 17:12:47 +02:00
self.check_data_size(&new_val, op_info.pos)?;
}
}
2022-01-07 05:19:01 +01:00
// Try to call index setter
2022-02-09 06:12:43 +01:00
let new_val = &mut new_val;
self.call_indexer_set(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, idx, new_val, is_ref_mut, level,
2022-02-10 10:55:32 +01:00
)?;
2022-01-07 05:19:01 +01:00
}
Ok((Dynamic::UNIT, true))
}
// xxx[rhs]
2022-01-25 05:24:30 +01:00
_ => {
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
self.run_debugger(scope, global, lib, this_ptr, _parent, level)?;
2022-01-25 05:24:30 +01:00
self.get_indexed_mut(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, idx_val, pos, false, true, level,
2022-01-07 05:19:01 +01:00
)
2022-01-25 05:24:30 +01:00
.map(|v| (v.take_or_clone(), false))
}
2022-01-07 05:19:01 +01:00
}
}
#[cfg(not(feature = "no_object"))]
ChainType::Dotting => {
match rhs {
// xxx.fn_name(arg_expr_list)
Expr::MethodCall(x, pos) if !x.is_qualified() && new_val.is_none() => {
2022-01-07 05:19:01 +01:00
let crate::ast::FnCallExpr { name, hashes, .. } = x.as_ref();
let call_args = &mut idx_val.into_fn_call_args();
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
let reset_debugger =
self.run_debugger_with_reset(scope, global, lib, this_ptr, rhs, level)?;
2022-01-25 05:24:30 +01:00
let result = self.make_method_call(
2022-04-16 10:36:53 +02:00
global, caches, lib, name, *hashes, target, call_args, *pos, level,
2022-01-25 05:24:30 +01:00
);
#[cfg(feature = "debugging")]
global.debugger.reset_status(reset_debugger);
result
2022-01-07 05:19:01 +01:00
}
// xxx.fn_name(...) = ???
Expr::MethodCall(..) if new_val.is_some() => {
2022-01-07 05:19:01 +01:00
unreachable!("method call cannot be assigned to")
}
// xxx.module::fn_name(...) - syntax error
Expr::MethodCall(..) => {
2022-01-07 05:19:01 +01:00
unreachable!("function call in dot chain should not be namespace-qualified")
}
// {xxx:map}.id op= ???
Expr::Property(x, pos) if target.is::<crate::Map>() && new_val.is_some() => {
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
2022-01-25 05:24:30 +01:00
let index = x.2.clone().into();
2022-04-18 17:12:47 +02:00
let (new_val, op_info) = new_val.expect("`Some`");
2022-01-07 05:19:01 +01:00
{
let val_target = &mut self.get_indexed_mut(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, index, *pos, true, false, level,
2022-01-07 05:19:01 +01:00
)?;
self.eval_op_assignment(
2022-04-18 17:12:47 +02:00
global, caches, lib, op_info, val_target, root, new_val, level,
)?;
2022-01-07 05:19:01 +01:00
}
#[cfg(not(feature = "unchecked"))]
2022-04-18 17:12:47 +02:00
self.check_data_size(target.source(), op_info.pos)?;
2022-01-07 05:19:01 +01:00
Ok((Dynamic::UNIT, true))
}
// {xxx:map}.id
Expr::Property(x, pos) if target.is::<crate::Map>() => {
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
2022-01-25 05:24:30 +01:00
let index = x.2.clone().into();
2022-01-07 05:19:01 +01:00
let val = self.get_indexed_mut(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, index, *pos, false, false, level,
2022-01-07 05:19:01 +01:00
)?;
Ok((val.take_or_clone(), false))
}
// xxx.id op= ???
Expr::Property(x, pos) if new_val.is_some() => {
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
2022-01-25 05:24:30 +01:00
let ((getter, hash_get), (setter, hash_set), name) = x.as_ref();
2022-04-18 17:12:47 +02:00
let (mut new_val, op_info) = new_val.expect("`Some`");
2022-01-07 05:19:01 +01:00
2022-04-18 17:12:47 +02:00
if op_info.is_op_assignment() {
2022-01-07 05:19:01 +01:00
let args = &mut [target.as_mut()];
2022-02-08 02:02:15 +01:00
let (mut orig_val, ..) = self
2022-05-19 08:36:58 +02:00
.call_native_fn(
global, caches, lib, getter, *hash_get, args, is_ref_mut,
false, *pos, level,
2022-01-07 05:19:01 +01:00
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
2022-02-08 02:02:15 +01:00
ERR::ErrorDotExpr(..) => {
2022-02-09 06:12:43 +01:00
let mut prop = name.into();
self.call_indexer_get(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, &mut prop, level,
2022-01-07 05:19:01 +01:00
)
.map(|r| (r, false))
2022-02-24 03:36:20 +01:00
.map_err(|e| {
match *e {
2022-02-08 02:02:15 +01:00
ERR::ErrorIndexingType(..) => err,
2022-02-24 03:36:20 +01:00
_ => e,
}
})
2022-01-07 05:19:01 +01:00
}
_ => Err(err),
})?;
2022-02-24 03:36:20 +01:00
{
let orig_val = &mut (&mut orig_val).into();
self.eval_op_assignment(
2022-04-18 17:12:47 +02:00
global, caches, lib, op_info, orig_val, root, new_val, level,
)?;
2022-02-24 03:36:20 +01:00
}
2022-01-07 05:19:01 +01:00
new_val = orig_val;
}
let args = &mut [target.as_mut(), &mut new_val];
2022-05-19 08:36:58 +02:00
self.call_native_fn(
global, caches, lib, setter, *hash_set, args, is_ref_mut, false, *pos,
2022-01-07 05:19:01 +01:00
level,
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
2022-02-08 02:02:15 +01:00
ERR::ErrorDotExpr(..) => {
2022-02-09 06:12:43 +01:00
let idx = &mut name.into();
let new_val = &mut new_val;
self.call_indexer_set(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, idx, new_val, is_ref_mut, level,
2022-01-07 05:19:01 +01:00
)
2022-02-24 03:36:20 +01:00
.map_err(|e| match *e {
ERR::ErrorIndexingType(..) => err,
_ => e,
})
2022-01-07 05:19:01 +01:00
}
_ => Err(err),
})
}
// xxx.id
Expr::Property(x, pos) => {
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
self.run_debugger(scope, global, lib, this_ptr, rhs, level)?;
2022-01-25 05:24:30 +01:00
let ((getter, hash_get), _, name) = x.as_ref();
2022-01-07 05:19:01 +01:00
let args = &mut [target.as_mut()];
2022-05-19 08:36:58 +02:00
self.call_native_fn(
global, caches, lib, getter, *hash_get, args, is_ref_mut, false, *pos,
2022-01-07 05:19:01 +01:00
level,
)
.map_or_else(
|err| match *err {
// Try an indexer if property does not exist
2022-02-08 02:02:15 +01:00
ERR::ErrorDotExpr(..) => {
2022-02-09 06:12:43 +01:00
let mut prop = name.into();
self.call_indexer_get(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, &mut prop, level,
2022-01-07 05:19:01 +01:00
)
.map(|r| (r, false))
2022-02-24 03:36:20 +01:00
.map_err(|e| match *e {
ERR::ErrorIndexingType(..) => err,
_ => e,
2022-01-07 05:19:01 +01:00
})
}
_ => Err(err),
},
// Assume getters are always pure
2022-02-08 02:02:15 +01:00
|(v, ..)| Ok((v, false)),
2022-01-07 05:19:01 +01:00
)
}
// {xxx:map}.sub_lhs[expr] | {xxx:map}.sub_lhs.expr
2022-02-25 04:42:59 +01:00
Expr::Index(x, options, x_pos) | Expr::Dot(x, options, x_pos)
2022-01-07 05:19:01 +01:00
if target.is::<crate::Map>() =>
{
2022-01-25 07:32:14 +01:00
let _node = &x.lhs;
2022-01-25 05:24:30 +01:00
2022-01-07 05:19:01 +01:00
let val_target = &mut match x.lhs {
Expr::Property(ref p, pos) => {
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
self.run_debugger(scope, global, lib, this_ptr, _node, level)?;
2022-01-25 05:24:30 +01:00
let index = p.2.clone().into();
2022-01-07 05:19:01 +01:00
self.get_indexed_mut(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, index, pos, false, true, level,
2022-01-07 05:19:01 +01:00
)?
}
// {xxx:map}.fn_name(arg_expr_list)[expr] | {xxx:map}.fn_name(arg_expr_list).expr
Expr::MethodCall(ref x, pos) if !x.is_qualified() => {
2022-01-07 05:19:01 +01:00
let crate::ast::FnCallExpr { name, hashes, .. } = x.as_ref();
let call_args = &mut idx_val.into_fn_call_args();
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-02-03 04:56:08 +01:00
let reset_debugger = self.run_debugger_with_reset(
2022-04-16 17:32:14 +02:00
scope, global, lib, this_ptr, _node, level,
2022-02-03 04:56:08 +01:00
)?;
2022-01-25 05:24:30 +01:00
let result = self.make_method_call(
2022-04-16 10:36:53 +02:00
global, caches, lib, name, *hashes, target, call_args, pos,
2022-01-07 05:19:01 +01:00
level,
2022-01-25 05:24:30 +01:00
);
#[cfg(feature = "debugging")]
global.debugger.reset_status(reset_debugger);
result?.0.into()
2022-01-07 05:19:01 +01:00
}
// {xxx:map}.module::fn_name(...) - syntax error
Expr::MethodCall(..) => unreachable!(
2022-01-07 05:19:01 +01:00
"function call in dot chain should not be namespace-qualified"
),
// Others - syntax error
ref expr => unreachable!("invalid dot expression: {:?}", expr),
};
let rhs_chain = rhs.into();
self.eval_dot_index_chain_helper(
2022-04-16 10:36:53 +02:00
global, caches, lib, this_ptr, val_target, root, rhs, &x.rhs, *options,
2022-01-07 05:19:01 +01:00
idx_values, rhs_chain, level, new_val,
)
.map_err(|err| err.fill_position(*x_pos))
}
// xxx.sub_lhs[expr] | xxx.sub_lhs.expr
2022-02-25 04:42:59 +01:00
Expr::Index(x, options, x_pos) | Expr::Dot(x, options, x_pos) => {
2022-01-25 07:32:14 +01:00
let _node = &x.lhs;
2022-01-25 05:24:30 +01:00
2022-01-07 05:19:01 +01:00
match x.lhs {
// xxx.prop[expr] | xxx.prop.expr
Expr::Property(ref p, pos) => {
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
self.run_debugger(scope, global, lib, this_ptr, _node, level)?;
2022-01-25 05:24:30 +01:00
let ((getter, hash_get), (setter, hash_set), name) = p.as_ref();
2022-01-07 05:19:01 +01:00
let rhs_chain = rhs.into();
let mut arg_values = [target.as_mut(), &mut Dynamic::UNIT.clone()];
let args = &mut arg_values[..1];
// Assume getters are always pure
2022-02-08 02:02:15 +01:00
let (mut val, ..) = self
2022-05-19 08:36:58 +02:00
.call_native_fn(
global, caches, lib, getter, *hash_get, args, is_ref_mut,
false, pos, level,
2022-01-07 05:19:01 +01:00
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
2022-02-08 02:02:15 +01:00
ERR::ErrorDotExpr(..) => {
2022-02-09 06:12:43 +01:00
let mut prop = name.into();
self.call_indexer_get(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, &mut prop, level,
2022-01-07 05:19:01 +01:00
)
.map(|r| (r, false))
2022-01-07 05:19:01 +01:00
.map_err(
2022-02-24 03:36:20 +01:00
|e| match *e {
2022-02-08 02:02:15 +01:00
ERR::ErrorIndexingType(..) => err,
2022-02-24 03:36:20 +01:00
_ => e,
2022-01-07 05:19:01 +01:00
},
)
}
_ => Err(err),
})?;
2022-02-24 03:36:20 +01:00
let val = &mut (&mut val).into();
2022-01-07 05:19:01 +01:00
let (result, may_be_changed) = self
.eval_dot_index_chain_helper(
2022-04-16 10:36:53 +02:00
global, caches, lib, this_ptr, val, root, rhs, &x.rhs,
2022-02-25 04:42:59 +01:00
*options, idx_values, rhs_chain, level, new_val,
2022-01-07 05:19:01 +01:00
)
.map_err(|err| err.fill_position(*x_pos))?;
// Feed the value back via a setter just in case it has been updated
if may_be_changed {
// Re-use args because the first &mut parameter will not be consumed
2022-02-24 03:36:20 +01:00
let mut arg_values = [target.as_mut(), val.as_mut()];
2022-01-07 05:19:01 +01:00
let args = &mut arg_values;
2022-05-19 08:36:58 +02:00
self.call_native_fn(
global, caches, lib, setter, *hash_set, args, is_ref_mut,
false, pos, level,
2022-01-07 05:19:01 +01:00
)
.or_else(
|err| match *err {
// Try an indexer if property does not exist
2022-02-08 02:02:15 +01:00
ERR::ErrorDotExpr(..) => {
2022-02-09 06:12:43 +01:00
let idx = &mut name.into();
let new_val = val;
self.call_indexer_set(
2022-04-16 10:36:53 +02:00
global, caches, lib, target, idx, new_val,
2022-02-09 06:12:43 +01:00
is_ref_mut, level,
2022-01-07 05:19:01 +01:00
)
2022-02-24 03:36:20 +01:00
.or_else(|e| match *e {
2022-02-10 10:55:32 +01:00
// If there is no setter, no need to feed it
// back because the property is read-only
2022-02-08 02:02:15 +01:00
ERR::ErrorIndexingType(..) => {
2022-01-07 05:19:01 +01:00
Ok((Dynamic::UNIT, false))
}
2022-02-24 03:36:20 +01:00
_ => Err(e),
2022-01-07 05:19:01 +01:00
})
}
_ => Err(err),
},
)?;
}
Ok((result, may_be_changed))
}
// xxx.fn_name(arg_expr_list)[expr] | xxx.fn_name(arg_expr_list).expr
Expr::MethodCall(ref f, pos) if !f.is_qualified() => {
2022-01-07 05:19:01 +01:00
let crate::ast::FnCallExpr { name, hashes, .. } = f.as_ref();
let rhs_chain = rhs.into();
let args = &mut idx_val.into_fn_call_args();
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-02-03 04:56:08 +01:00
let reset_debugger = self.run_debugger_with_reset(
2022-04-16 17:32:14 +02:00
scope, global, lib, this_ptr, _node, level,
2022-02-03 04:56:08 +01:00
)?;
2022-01-25 05:24:30 +01:00
let result = self.make_method_call(
2022-04-16 10:36:53 +02:00
global, caches, lib, name, *hashes, target, args, pos, level,
2022-01-25 05:24:30 +01:00
);
#[cfg(feature = "debugging")]
global.debugger.reset_status(reset_debugger);
2022-02-24 03:36:20 +01:00
let (val, _) = &mut result?;
let val = &mut val.into();
2022-01-07 05:19:01 +01:00
self.eval_dot_index_chain_helper(
2022-04-16 10:36:53 +02:00
global, caches, lib, this_ptr, val, root, rhs, &x.rhs,
*options, idx_values, rhs_chain, level, new_val,
2022-01-07 05:19:01 +01:00
)
.map_err(|err| err.fill_position(pos))
}
// xxx.module::fn_name(...) - syntax error
Expr::MethodCall(..) => unreachable!(
2022-01-07 05:19:01 +01:00
"function call in dot chain should not be namespace-qualified"
),
// Others - syntax error
ref expr => unreachable!("invalid dot expression: {:?}", expr),
}
}
// Syntax error
2022-02-04 05:04:33 +01:00
_ => Err(ERR::ErrorDotExpr("".into(), rhs.start_position()).into()),
2022-01-07 05:19:01 +01:00
}
}
}
}
/// Evaluate a dot/index chain.
pub(crate) fn eval_dot_index_chain(
&self,
scope: &mut Scope,
global: &mut GlobalRuntimeState,
2022-04-16 10:36:53 +02:00
caches: &mut Caches,
2022-01-07 05:19:01 +01:00
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
expr: &Expr,
level: usize,
2022-04-18 17:12:47 +02:00
new_val: Option<(Dynamic, OpAssignment)>,
2022-01-07 05:19:01 +01:00
) -> RhaiResult {
2022-02-25 04:42:59 +01:00
let (crate::ast::BinaryExpr { lhs, rhs }, chain_type, options, op_pos) = match expr {
2022-01-07 05:19:01 +01:00
#[cfg(not(feature = "no_index"))]
2022-02-25 04:42:59 +01:00
Expr::Index(x, options, pos) => (x.as_ref(), ChainType::Indexing, *options, *pos),
2022-01-07 05:19:01 +01:00
#[cfg(not(feature = "no_object"))]
2022-02-25 04:42:59 +01:00
Expr::Dot(x, options, pos) => (x.as_ref(), ChainType::Dotting, *options, *pos),
2022-01-07 05:19:01 +01:00
expr => unreachable!("Expr::Index or Expr::Dot expected but gets {:?}", expr),
};
let idx_values = &mut StaticVec::new_const();
self.eval_dot_index_chain_arguments(
2022-04-16 10:36:53 +02:00
scope, global, caches, lib, this_ptr, rhs, options, chain_type, idx_values, 0, level,
2022-01-07 05:19:01 +01:00
)?;
let is_assignment = new_val.is_some();
match lhs {
// id.??? or id[???]
2022-03-05 10:57:23 +01:00
Expr::Variable(x, .., var_pos) => {
2022-01-25 05:24:30 +01:00
#[cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
self.run_debugger(scope, global, lib, this_ptr, lhs, level)?;
2022-01-25 05:24:30 +01:00
2022-01-07 05:19:01 +01:00
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, *var_pos)?;
2022-02-08 02:02:15 +01:00
let (mut target, ..) =
2022-04-16 17:32:14 +02:00
self.search_namespace(scope, global, lib, this_ptr, lhs, level)?;
2022-01-07 05:19:01 +01:00
let obj_ptr = &mut target;
2022-03-05 10:57:23 +01:00
let root = (x.3.as_str(), *var_pos);
2022-01-07 05:19:01 +01:00
self.eval_dot_index_chain_helper(
2022-04-16 10:36:53 +02:00
global, caches, lib, &mut None, obj_ptr, root, expr, rhs, options, idx_values,
2022-01-07 05:19:01 +01:00
chain_type, level, new_val,
)
2022-02-08 02:02:15 +01:00
.map(|(v, ..)| v)
2022-01-07 05:19:01 +01:00
.map_err(|err| err.fill_position(op_pos))
}
// {expr}.??? = ??? or {expr}[???] = ???
_ if is_assignment => unreachable!("cannot assign to an expression"),
// {expr}.??? or {expr}[???]
expr => {
let value = self
.eval_expr(scope, global, caches, lib, this_ptr, expr, level)?
.flatten();
2022-01-07 05:19:01 +01:00
let obj_ptr = &mut value.into();
2022-02-04 05:04:33 +01:00
let root = ("", expr.start_position());
2022-01-07 05:19:01 +01:00
self.eval_dot_index_chain_helper(
2022-04-16 10:36:53 +02:00
global, caches, lib, this_ptr, obj_ptr, root, expr, rhs, options, idx_values,
2022-01-25 05:24:30 +01:00
chain_type, level, new_val,
2022-01-07 05:19:01 +01:00
)
2022-02-08 02:02:15 +01:00
.map(|(v, ..)| if is_assignment { Dynamic::UNIT } else { v })
2022-01-07 05:19:01 +01:00
.map_err(|err| err.fill_position(op_pos))
}
}
}
/// Evaluate a chain of indexes and store the results in a [`StaticVec`].
/// [`StaticVec`] is used to avoid an allocation in the overwhelming cases of
/// just a few levels of indexing.
fn eval_dot_index_chain_arguments(
&self,
scope: &mut Scope,
global: &mut GlobalRuntimeState,
2022-04-16 10:36:53 +02:00
caches: &mut Caches,
2022-01-07 05:19:01 +01:00
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
expr: &Expr,
2022-02-25 04:42:59 +01:00
parent_options: ASTFlags,
2022-04-11 10:29:16 +02:00
_parent_chain_type: ChainType,
2022-04-18 17:12:47 +02:00
idx_values: &mut StaticVec<ChainArgument>,
2022-01-07 05:19:01 +01:00
size: usize,
level: usize,
) -> RhaiResultOf<()> {
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, expr.position())?;
match expr {
#[cfg(not(feature = "no_object"))]
Expr::MethodCall(x, ..)
2022-02-08 02:46:14 +01:00
if _parent_chain_type == ChainType::Dotting && !x.is_qualified() =>
{
let crate::ast::FnCallExpr { args, .. } = x.as_ref();
2022-01-07 05:19:01 +01:00
let (values, pos) = args.iter().try_fold(
(crate::FnArgsVec::with_capacity(args.len()), Position::NONE),
2022-02-08 14:28:15 +01:00
|(mut values, mut pos), expr| {
let (value, arg_pos) =
2022-04-16 10:36:53 +02:00
self.get_arg_value(scope, global, caches, lib, this_ptr, expr, level)?;
2022-01-07 05:19:01 +01:00
if values.is_empty() {
pos = arg_pos;
}
values.push(value.flatten());
2022-02-09 06:12:43 +01:00
Ok::<_, crate::RhaiError>((values, pos))
2022-01-07 05:19:01 +01:00
},
)?;
2022-04-18 17:12:47 +02:00
idx_values.push(ChainArgument::from_fn_call_args(values, pos));
2022-01-07 05:19:01 +01:00
}
#[cfg(not(feature = "no_object"))]
Expr::MethodCall(..) if _parent_chain_type == ChainType::Dotting => {
2022-01-07 05:19:01 +01:00
unreachable!("function call in dot chain should not be namespace-qualified")
}
#[cfg(not(feature = "no_object"))]
2022-02-08 02:02:15 +01:00
Expr::Property(.., pos) if _parent_chain_type == ChainType::Dotting => {
2022-04-18 17:12:47 +02:00
idx_values.push(ChainArgument::Property(*pos))
2022-01-07 05:19:01 +01:00
}
2022-02-08 02:02:15 +01:00
Expr::Property(..) => unreachable!("unexpected Expr::Property for indexing"),
2022-01-07 05:19:01 +01:00
2022-02-25 04:42:59 +01:00
Expr::Index(x, options, ..) | Expr::Dot(x, options, ..)
if !parent_options.contains(ASTFlags::BREAK) =>
{
2022-01-07 05:19:01 +01:00
let crate::ast::BinaryExpr { lhs, rhs, .. } = x.as_ref();
// Evaluate in left-to-right order
let lhs_arg_val = match lhs {
#[cfg(not(feature = "no_object"))]
2022-02-08 02:02:15 +01:00
Expr::Property(.., pos) if _parent_chain_type == ChainType::Dotting => {
2022-04-18 17:12:47 +02:00
ChainArgument::Property(*pos)
2022-01-07 05:19:01 +01:00
}
2022-02-08 02:02:15 +01:00
Expr::Property(..) => unreachable!("unexpected Expr::Property for indexing"),
2022-01-07 05:19:01 +01:00
#[cfg(not(feature = "no_object"))]
Expr::MethodCall(x, ..)
2022-01-07 05:19:01 +01:00
if _parent_chain_type == ChainType::Dotting && !x.is_qualified() =>
{
let crate::ast::FnCallExpr { args, .. } = x.as_ref();
2022-01-07 05:19:01 +01:00
let (values, pos) = args.iter().try_fold(
(crate::FnArgsVec::with_capacity(args.len()), Position::NONE),
2022-02-08 14:28:15 +01:00
|(mut values, mut pos), expr| {
2022-01-07 05:19:01 +01:00
let (value, arg_pos) = self.get_arg_value(
2022-04-16 10:36:53 +02:00
scope, global, caches, lib, this_ptr, expr, level,
2022-01-07 05:19:01 +01:00
)?;
if values.is_empty() {
pos = arg_pos
}
values.push(value.flatten());
2022-02-09 06:12:43 +01:00
Ok::<_, crate::RhaiError>((values, pos))
2022-01-07 05:19:01 +01:00
},
)?;
2022-04-18 17:12:47 +02:00
ChainArgument::from_fn_call_args(values, pos)
2022-01-07 05:19:01 +01:00
}
#[cfg(not(feature = "no_object"))]
Expr::MethodCall(..) if _parent_chain_type == ChainType::Dotting => {
2022-01-07 05:19:01 +01:00
unreachable!("function call in dot chain should not be namespace-qualified")
}
#[cfg(not(feature = "no_object"))]
expr if _parent_chain_type == ChainType::Dotting => {
unreachable!("invalid dot expression: {:?}", expr);
}
#[cfg(not(feature = "no_index"))]
_ if _parent_chain_type == ChainType::Indexing => self
2022-04-16 10:36:53 +02:00
.eval_expr(scope, global, caches, lib, this_ptr, lhs, level)
2022-01-07 05:19:01 +01:00
.map(|v| {
2022-04-18 17:12:47 +02:00
ChainArgument::from_index_value(v.flatten(), lhs.start_position())
2022-01-07 05:19:01 +01:00
})?,
expr => unreachable!("unknown chained expression: {:?}", expr),
};
// Push in reverse order
let chain_type = expr.into();
self.eval_dot_index_chain_arguments(
2022-04-16 10:36:53 +02:00
scope, global, caches, lib, this_ptr, rhs, *options, chain_type, idx_values,
2022-02-25 04:42:59 +01:00
size, level,
2022-01-07 05:19:01 +01:00
)?;
idx_values.push(lhs_arg_val);
}
#[cfg(not(feature = "no_object"))]
_ if _parent_chain_type == ChainType::Dotting => {
unreachable!("invalid dot expression: {:?}", expr);
}
#[cfg(not(feature = "no_index"))]
_ if _parent_chain_type == ChainType::Indexing => idx_values.push(
2022-04-16 10:36:53 +02:00
self.eval_expr(scope, global, caches, lib, this_ptr, expr, level)
2022-04-18 17:12:47 +02:00
.map(|v| ChainArgument::from_index_value(v.flatten(), expr.start_position()))?,
2022-01-07 05:19:01 +01:00
),
_ => unreachable!("unknown chained expression: {:?}", expr),
}
Ok(())
}
2022-02-09 06:12:43 +01:00
/// Call a get indexer.
/// [`Position`] in [`EvalAltResult`] may be [`NONE`][Position::NONE] and should be set afterwards.
#[inline(always)]
fn call_indexer_get(
&self,
global: &mut GlobalRuntimeState,
2022-04-16 10:36:53 +02:00
caches: &mut Caches,
2022-02-09 06:12:43 +01:00
lib: &[&Module],
target: &mut Dynamic,
idx: &mut Dynamic,
level: usize,
) -> RhaiResultOf<Dynamic> {
2022-02-09 06:12:43 +01:00
let args = &mut [target, idx];
2022-05-19 08:36:58 +02:00
let hash = global.hash_idx_get();
2022-02-09 06:12:43 +01:00
let fn_name = crate::engine::FN_IDX_GET;
let pos = Position::NONE;
2022-05-19 08:36:58 +02:00
let level = level + 1;
2022-02-09 06:12:43 +01:00
2022-05-19 08:36:58 +02:00
self.call_native_fn(
global, caches, lib, fn_name, hash, args, true, false, pos, level,
2022-02-09 06:12:43 +01:00
)
.map(|(r, ..)| r)
2022-02-09 06:12:43 +01:00
}
/// Call a set indexer.
/// [`Position`] in [`EvalAltResult`] may be [`NONE`][Position::NONE] and should be set afterwards.
#[inline(always)]
fn call_indexer_set(
&self,
global: &mut GlobalRuntimeState,
2022-04-16 10:36:53 +02:00
caches: &mut Caches,
2022-02-09 06:12:43 +01:00
lib: &[&Module],
target: &mut Dynamic,
idx: &mut Dynamic,
new_val: &mut Dynamic,
is_ref_mut: bool,
level: usize,
) -> RhaiResultOf<(Dynamic, bool)> {
2022-05-19 08:36:58 +02:00
let hash = global.hash_idx_set();
2022-02-09 06:12:43 +01:00
let args = &mut [target, idx, new_val];
let fn_name = crate::engine::FN_IDX_SET;
let pos = Position::NONE;
2022-05-19 08:36:58 +02:00
let level = level + 1;
2022-02-09 06:12:43 +01:00
2022-05-19 08:36:58 +02:00
self.call_native_fn(
global, caches, lib, fn_name, hash, args, is_ref_mut, false, pos, level,
2022-02-09 06:12:43 +01:00
)
}
2022-01-07 05:19:01 +01:00
/// Get the value at the indexed position of a base type.
/// [`Position`] in [`EvalAltResult`] may be [`NONE`][Position::NONE] and should be set afterwards.
fn get_indexed_mut<'t>(
&self,
global: &mut GlobalRuntimeState,
2022-04-16 10:36:53 +02:00
caches: &mut Caches,
2022-01-07 05:19:01 +01:00
lib: &[&Module],
target: &'t mut Dynamic,
2022-04-11 10:29:16 +02:00
mut idx: Dynamic,
2022-02-10 10:55:32 +01:00
idx_pos: Position,
2022-04-11 10:29:16 +02:00
_add_if_not_found: bool,
2022-01-07 05:19:01 +01:00
use_indexers: bool,
level: usize,
) -> RhaiResultOf<Target<'t>> {
#[cfg(not(feature = "unchecked"))]
self.inc_operations(&mut global.num_operations, Position::NONE)?;
match target {
#[cfg(not(feature = "no_index"))]
2022-02-08 02:02:15 +01:00
Dynamic(Union::Array(arr, ..)) => {
2022-01-07 05:19:01 +01:00
// val_array[idx]
let index = idx
.as_int()
2022-02-10 10:55:32 +01:00
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, idx_pos))?;
let len = arr.len();
2022-01-16 15:54:28 +01:00
let arr_idx = super::calc_index(len, index, true, || {
2022-02-10 10:55:32 +01:00
ERR::ErrorArrayBounds(len, index, idx_pos).into()
2022-01-15 03:24:08 +01:00
})?;
2022-01-07 05:19:01 +01:00
Ok(arr.get_mut(arr_idx).map(Target::from).unwrap())
2022-01-07 05:19:01 +01:00
}
#[cfg(not(feature = "no_index"))]
2022-02-08 02:02:15 +01:00
Dynamic(Union::Blob(arr, ..)) => {
2022-01-07 05:19:01 +01:00
// val_blob[idx]
let index = idx
.as_int()
2022-02-10 10:55:32 +01:00
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, idx_pos))?;
let len = arr.len();
2022-01-16 15:54:28 +01:00
let arr_idx = super::calc_index(len, index, true, || {
2022-02-10 10:55:32 +01:00
ERR::ErrorArrayBounds(len, index, idx_pos).into()
2022-01-15 03:24:08 +01:00
})?;
2022-01-07 05:19:01 +01:00
let value = arr.get(arr_idx).map(|&v| (v as crate::INT).into()).unwrap();
2022-01-07 05:19:01 +01:00
Ok(Target::BlobByte {
source: target,
value,
index: arr_idx,
})
}
#[cfg(not(feature = "no_object"))]
2022-02-08 02:02:15 +01:00
Dynamic(Union::Map(map, ..)) => {
2022-01-07 05:19:01 +01:00
// val_map[idx]
let index = idx.read_lock::<crate::ImmutableString>().ok_or_else(|| {
2022-02-10 10:55:32 +01:00
self.make_type_mismatch_err::<crate::ImmutableString>(idx.type_name(), idx_pos)
2022-01-07 05:19:01 +01:00
})?;
2022-03-03 06:02:57 +01:00
if _add_if_not_found && (map.is_empty() || !map.contains_key(index.as_str())) {
2022-01-07 05:19:01 +01:00
map.insert(index.clone().into(), Dynamic::UNIT);
}
2022-02-09 06:12:43 +01:00
if let Some(value) = map.get_mut(index.as_str()) {
Ok(Target::from(value))
} else if self.fail_on_invalid_map_property() {
2022-02-10 10:55:32 +01:00
Err(ERR::ErrorPropertyNotFound(index.to_string(), idx_pos).into())
2022-02-09 06:12:43 +01:00
} else {
Ok(Target::from(Dynamic::UNIT))
}
2022-01-07 05:19:01 +01:00
}
#[cfg(not(feature = "no_index"))]
2022-02-08 02:02:15 +01:00
Dynamic(Union::Int(value, ..))
2022-01-07 05:19:01 +01:00
if idx.is::<crate::ExclusiveRange>() || idx.is::<crate::InclusiveRange>() =>
{
// val_int[range]
let (shift, mask) = if let Some(range) = idx.read_lock::<crate::ExclusiveRange>() {
let start = range.start;
let end = range.end;
2022-03-09 02:25:55 +01:00
let start = super::calc_index(crate::INT_BITS, start, false, || {
ERR::ErrorBitFieldBounds(crate::INT_BITS, start, idx_pos).into()
})?;
2022-03-09 02:25:55 +01:00
let end = super::calc_index(crate::INT_BITS, end, false, || {
ERR::ErrorBitFieldBounds(crate::INT_BITS, end, idx_pos).into()
})?;
if end <= start {
2022-01-07 05:19:01 +01:00
(0, 0)
2022-03-09 02:25:55 +01:00
} else if end == crate::INT_BITS && start == 0 {
2022-01-07 05:19:01 +01:00
// -1 = all bits set
(0, -1)
} else {
(
start as u8,
// 2^bits - 1
2022-01-13 15:51:56 +01:00
(((2 as crate::UNSIGNED_INT).pow((end - start) as u32) - 1)
as crate::INT)
<< start,
2022-01-07 05:19:01 +01:00
)
}
} else if let Some(range) = idx.read_lock::<crate::InclusiveRange>() {
let start = *range.start();
let end = *range.end();
2022-03-09 02:25:55 +01:00
let start = super::calc_index(crate::INT_BITS, start, false, || {
ERR::ErrorBitFieldBounds(crate::INT_BITS, start, idx_pos).into()
})?;
2022-03-09 02:25:55 +01:00
let end = super::calc_index(crate::INT_BITS, end, false, || {
ERR::ErrorBitFieldBounds(crate::INT_BITS, end, idx_pos).into()
})?;
if end < start {
2022-01-07 05:19:01 +01:00
(0, 0)
2022-03-09 02:25:55 +01:00
} else if end == crate::INT_BITS - 1 && start == 0 {
2022-01-07 05:19:01 +01:00
// -1 = all bits set
(0, -1)
} else {
(
start as u8,
// 2^bits - 1
2022-01-13 15:51:56 +01:00
(((2 as crate::UNSIGNED_INT).pow((end - start + 1) as u32) - 1)
as crate::INT)
2022-01-07 05:19:01 +01:00
<< start,
)
}
} else {
unreachable!("Range or RangeInclusive expected but gets {:?}", idx);
};
let field_value = (*value & mask) >> shift;
Ok(Target::BitField {
source: target,
value: field_value.into(),
mask,
shift,
})
}
#[cfg(not(feature = "no_index"))]
2022-02-08 02:02:15 +01:00
Dynamic(Union::Int(value, ..)) => {
2022-01-07 05:19:01 +01:00
// val_int[idx]
let index = idx
.as_int()
2022-02-10 10:55:32 +01:00
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, idx_pos))?;
2022-01-07 05:19:01 +01:00
2022-03-09 02:25:55 +01:00
let bit = super::calc_index(crate::INT_BITS, index, true, || {
ERR::ErrorBitFieldBounds(crate::INT_BITS, index, idx_pos).into()
})?;
let bit_value = (*value & (1 << bit)) != 0;
2022-01-07 05:19:01 +01:00
Ok(Target::Bit {
source: target,
value: bit_value.into(),
bit: bit as u8,
2022-01-07 05:19:01 +01:00
})
}
#[cfg(not(feature = "no_index"))]
2022-02-08 02:02:15 +01:00
Dynamic(Union::Str(s, ..)) => {
2022-01-07 05:19:01 +01:00
// val_string[idx]
let index = idx
.as_int()
2022-02-10 10:55:32 +01:00
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, idx_pos))?;
2022-01-07 05:19:01 +01:00
let (ch, offset) = if index >= 0 {
let offset = index as usize;
(
s.chars().nth(offset).ok_or_else(|| {
let chars_len = s.chars().count();
2022-02-10 10:55:32 +01:00
ERR::ErrorStringBounds(chars_len, index, idx_pos)
2022-01-07 05:19:01 +01:00
})?,
offset,
)
} else if let Some(abs_index) = index.checked_abs() {
let offset = abs_index as usize;
(
// Count from end if negative
s.chars().rev().nth(offset - 1).ok_or_else(|| {
let chars_len = s.chars().count();
2022-02-10 10:55:32 +01:00
ERR::ErrorStringBounds(chars_len, index, idx_pos)
2022-01-07 05:19:01 +01:00
})?,
offset,
)
} else {
let chars_len = s.chars().count();
2022-02-10 10:55:32 +01:00
return Err(ERR::ErrorStringBounds(chars_len, index, idx_pos).into());
2022-01-07 05:19:01 +01:00
};
Ok(Target::StringChar {
source: target,
value: ch.into(),
index: offset,
})
}
#[cfg(not(feature = "no_closure"))]
Dynamic(Union::Shared(..)) => {
unreachable!("`get_indexed_mut` cannot handle shared values")
}
2022-02-09 06:12:43 +01:00
_ if use_indexers => self
2022-04-16 10:36:53 +02:00
.call_indexer_get(global, caches, lib, target, &mut idx, level)
.map(Into::into),
2022-01-07 05:19:01 +01:00
_ => Err(ERR::ErrorIndexingType(
format!(
"{} [{}]",
self.map_type_name(target.type_name()),
self.map_type_name(idx.type_name())
),
Position::NONE,
)
.into()),
}
}
}