-
Notifications
You must be signed in to change notification settings - Fork 168
/
chaining.rs
1243 lines (1102 loc) · 54.2 KB
/
chaining.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Types to support chaining operations (i.e. indexing and dotting).
#![cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
use super::{Caches, GlobalRuntimeState, Target};
use crate::ast::{ASTFlags, BinaryExpr, Expr, OpAssignment};
use crate::engine::{FN_IDX_GET, FN_IDX_SET};
use crate::types::dynamic::Union;
use crate::{
calc_fn_hash, Dynamic, Engine, ExclusiveRange, FnArgsVec, InclusiveRange, OnceCell, Position,
RhaiResult, RhaiResultOf, Scope, ERR,
};
use std::hash::Hash;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
/// Function call hashes to index getters and setters.
static INDEXER_HASHES: OnceCell<(u64, u64)> = OnceCell::new();
/// Get the pre-calculated index getter/setter hashes.
#[inline]
#[must_use]
fn hash_idx() -> (u64, u64) {
*INDEXER_HASHES.get_or_init(|| {
#[allow(clippy::useless_conversion)]
(
calc_fn_hash(None, FN_IDX_GET, 2),
calc_fn_hash(None, FN_IDX_SET, 3),
)
.into()
})
}
/// 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(always)]
fn from(expr: &Expr) -> Self {
match expr {
#[cfg(not(feature = "no_index"))]
Expr::Index(..) => Self::Indexing,
#[cfg(not(feature = "no_object"))]
Expr::Dot(..) => Self::Dotting,
expr => unreachable!("Expr::Index or Expr::Dot expected but gets {:?}", expr),
}
}
}
impl Engine {
/// Call a get indexer.
#[inline]
fn call_indexer_get(
&self,
global: &mut GlobalRuntimeState,
caches: &mut Caches,
target: &mut Dynamic,
idx: &mut Dynamic,
pos: Position,
) -> RhaiResultOf<Dynamic> {
defer! { let orig_level = global.level; global.level += 1 }
let hash = hash_idx().0;
let args = &mut [target, idx];
self.exec_native_fn_call(
global, caches, FN_IDX_GET, None, hash, args, true, false, pos,
)
.map(|(r, ..)| r)
}
/// Call a set indexer.
#[inline]
fn call_indexer_set(
&self,
global: &mut GlobalRuntimeState,
caches: &mut Caches,
target: &mut Dynamic,
idx: &mut Dynamic,
new_val: &mut Dynamic,
is_ref_mut: bool,
pos: Position,
) -> RhaiResultOf<(Dynamic, bool)> {
defer! { let orig_level = global.level; global.level += 1 }
let hash = hash_idx().1;
let args = &mut [target, idx, new_val];
self.exec_native_fn_call(
global, caches, FN_IDX_SET, None, hash, args, is_ref_mut, false, pos,
)
}
/// Get the value at the indexed position of a base type.
///
/// # Panics
///
/// Panics if the target object is shared.
///
/// Shared objects should be handled (dereferenced) before calling this method.
fn get_indexed_mut<'t>(
&self,
global: &mut GlobalRuntimeState,
caches: &mut Caches,
_scope: &mut Scope,
_this_ptr: Option<&mut Dynamic>,
target: &'t mut Dynamic,
idx: &mut Dynamic,
idx_pos: Position,
op_pos: Position,
_add_if_not_found: bool,
use_indexers: bool,
) -> RhaiResultOf<Target<'t>> {
self.track_operation(global, Position::NONE)?;
match target {
#[cfg(not(feature = "no_index"))]
Dynamic(Union::Array(arr, ..)) => {
// val_array[idx]
let index = idx
.as_int()
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, idx_pos))?;
let len = arr.len();
let arr_idx = match super::calc_index(len, index, true, || {
ERR::ErrorArrayBounds(len, index, idx_pos).into()
}) {
Ok(idx) => idx,
Err(err) => {
#[cfg(not(feature = "no_index"))]
#[cfg(feature = "internals")]
if let Some(ref cb) = self.invalid_array_index {
let context =
super::EvalContext::new(self, global, caches, _scope, _this_ptr);
return cb(arr, index, context)
.map_err(|err| err.fill_position(idx_pos));
}
return Err(err);
}
};
Ok(arr.get_mut(arr_idx).map(Target::from).unwrap())
}
#[cfg(not(feature = "no_index"))]
Dynamic(Union::Blob(arr, ..)) => {
// val_blob[idx]
let index = idx
.as_int()
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, idx_pos))?;
let len = arr.len();
let arr_idx = super::calc_index(len, index, true, || {
ERR::ErrorArrayBounds(len, index, idx_pos).into()
})?;
let value = arr.get(arr_idx).map(|&v| (v as crate::INT).into()).unwrap();
Ok(Target::BlobByte {
source: target,
value,
index: arr_idx,
})
}
#[cfg(not(feature = "no_object"))]
Dynamic(Union::Map(map, ..)) => {
// val_map[idx]
let index = idx.read_lock::<crate::ImmutableString>().ok_or_else(|| {
self.make_type_mismatch_err::<crate::ImmutableString>(idx.type_name(), idx_pos)
})?;
#[cfg(not(feature = "no_object"))]
#[cfg(feature = "internals")]
if let Some(ref cb) = self.missing_map_property {
if !map.contains_key(index.as_str()) {
let context =
super::EvalContext::new(self, global, caches, _scope, _this_ptr);
return cb(map, index.as_str(), context)
.map_err(|err| err.fill_position(idx_pos));
}
}
if _add_if_not_found && (map.is_empty() || !map.contains_key(index.as_str())) {
map.insert(index.clone().into(), Dynamic::UNIT);
}
if let Some(value) = map.get_mut(index.as_str()) {
Ok(Target::from(value))
} else if self.fail_on_invalid_map_property() {
Err(ERR::ErrorPropertyNotFound(index.to_string(), idx_pos).into())
} else {
Ok(Target::from(Dynamic::UNIT))
}
}
#[cfg(not(feature = "no_index"))]
Dynamic(Union::Int(value, ..))
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 = if range.end == crate::INT::MAX {
crate::INT_BITS as crate::INT
} else {
range.end
};
let start = super::calc_index(crate::INT_BITS, start, false, || {
ERR::ErrorBitFieldBounds(crate::INT_BITS, start, idx_pos).into()
})?;
let end = super::calc_index(crate::INT_BITS, end, false, || {
if end >= 0
&& end < crate::MAX_USIZE_INT
&& (end as usize) <= crate::INT_BITS
{
// Handle largest value
Ok(end as usize)
} else {
ERR::ErrorBitFieldBounds(crate::INT_BITS, end, idx_pos).into()
}
})?;
#[allow(clippy::cast_possible_truncation)]
if end <= start {
(0, 0)
} else if end == crate::INT_BITS && start == 0 {
// -1 = all bits set
(0, -1)
} else {
(
start as u8,
// 2^bits - 1
(((2 as crate::UNSIGNED_INT).pow((end - start) as u32) - 1)
as crate::INT)
<< start,
)
}
} else if let Some(range) = idx.read_lock::<crate::InclusiveRange>() {
let start = *range.start();
let end = if *range.end() == crate::INT::MAX {
(crate::INT_BITS - 1) as crate::INT
} else {
*range.end()
};
let start = super::calc_index(crate::INT_BITS, start, false, || {
ERR::ErrorBitFieldBounds(crate::INT_BITS, start, idx_pos).into()
})?;
let end = super::calc_index(crate::INT_BITS, end, false, || {
ERR::ErrorBitFieldBounds(crate::INT_BITS, end, idx_pos).into()
})?;
#[allow(clippy::cast_possible_truncation)]
if end < start {
(0, 0)
} else if end == crate::INT_BITS - 1 && start == 0 {
// -1 = all bits set
(0, -1)
} else {
(
start as u8,
// 2^bits - 1
(((2 as crate::UNSIGNED_INT).pow((end - start + 1) as u32) - 1)
as crate::INT)
<< 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"))]
Dynamic(Union::Int(value, ..)) => {
// val_int[idx]
let index = idx
.as_int()
.map_err(|typ| self.make_type_mismatch_err::<crate::INT>(typ, idx_pos))?;
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;
#[allow(clippy::cast_possible_truncation)]
let bit = bit as u8;
Ok(Target::Bit {
source: target,
value: bit_value.into(),
bit,
})
}
#[cfg(not(feature = "no_index"))]
Dynamic(Union::Str(s, ..)) => {
match idx.as_int() {
Ok(index) => {
let (ch, offset) = if index >= 0 {
#[allow(clippy::absurd_extreme_comparisons)]
if index >= crate::MAX_USIZE_INT {
return Err(ERR::ErrorStringBounds(
s.chars().count(),
index,
idx_pos,
)
.into());
}
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
let offset = index as usize;
(
s.chars().nth(offset).ok_or_else(|| {
ERR::ErrorStringBounds(s.chars().count(), index, idx_pos)
})?,
offset,
)
} else {
let abs_index = index.unsigned_abs();
#[allow(clippy::unnecessary_cast)]
if abs_index as u64 > usize::MAX as u64 {
return Err(ERR::ErrorStringBounds(
s.chars().count(),
index,
idx_pos,
)
.into());
}
#[allow(clippy::cast_possible_truncation)]
let offset = abs_index as usize;
(
// Count from end if negative
s.chars().rev().nth(offset - 1).ok_or_else(|| {
ERR::ErrorStringBounds(s.chars().count(), index, idx_pos)
})?,
offset,
)
};
Ok(Target::StringChar {
source: target,
value: ch.into(),
index: offset,
})
}
Err(typ) if typ == std::any::type_name::<ExclusiveRange>() => {
// val_str[range]
let idx = idx.read_lock::<ExclusiveRange>().unwrap();
let range = &*idx;
let chars_count = s.chars().count();
let start = if range.start >= 0 {
range.start as usize
} else {
super::calc_index(chars_count, range.start, true, || {
ERR::ErrorStringBounds(chars_count, range.start, idx_pos).into()
})?
};
let end = if range.end >= 0 {
range.end as usize
} else {
super::calc_index(chars_count, range.end, true, || {
ERR::ErrorStringBounds(chars_count, range.end, idx_pos).into()
})
.unwrap_or(0)
};
let take = if end > start { end - start } else { 0 };
let value = s.chars().skip(start).take(take).collect::<String>();
Ok(Target::StringSlice {
source: target,
value: value.into(),
start: start,
end: end,
exclusive: true,
})
}
Err(typ) if typ == std::any::type_name::<InclusiveRange>() => {
// val_str[range]
let idx = idx.read_lock::<InclusiveRange>().unwrap();
let range = &*idx;
let chars_count = s.chars().count();
let start = if *range.start() >= 0 {
*range.start() as usize
} else {
super::calc_index(chars_count, *range.start(), true, || {
ERR::ErrorStringBounds(chars_count, *range.start(), idx_pos).into()
})?
};
let end = if *range.end() >= 0 {
*range.end() as usize
} else {
super::calc_index(chars_count, *range.end(), true, || {
ERR::ErrorStringBounds(chars_count, *range.end(), idx_pos).into()
})
.unwrap_or(0)
};
let take = if end > start { end - start + 1 } else { 0 };
let value = s.chars().skip(start).take(take).collect::<String>();
Ok(Target::StringSlice {
source: target,
value: value.into(),
start,
end,
exclusive: false,
})
}
Err(typ) => Err(self.make_type_mismatch_err::<crate::INT>(typ, idx_pos)),
}
}
#[cfg(not(feature = "no_closure"))]
Dynamic(Union::Shared(..)) => {
unreachable!("`get_indexed_mut` cannot handle shared values")
}
_ if use_indexers => self
.call_indexer_get(global, caches, target, idx, op_pos)
.map(Into::into),
_ => Err(ERR::ErrorIndexingType(
format!(
"{} [{}]",
self.map_type_name(target.type_name()),
self.map_type_name(idx.type_name())
),
op_pos,
)
.into()),
}
}
/// Evaluate a dot/index chain.
pub(crate) fn eval_dot_index_chain(
&self,
global: &mut GlobalRuntimeState,
caches: &mut Caches,
scope: &mut Scope,
mut this_ptr: Option<&mut Dynamic>,
expr: &Expr,
new_val: Option<(Dynamic, &OpAssignment)>,
) -> RhaiResult {
let BinaryExpr { lhs, rhs } = match expr {
#[cfg(not(feature = "no_index"))]
Expr::Index(x, ..) => &**x,
#[cfg(not(feature = "no_object"))]
Expr::Dot(x, ..) => &**x,
expr => unreachable!("Expr::Index or Expr::Dot expected but gets {:?}", expr),
};
let idx_values = &mut FnArgsVec::new_const();
match (rhs, ChainType::from(expr)) {
// Short-circuit for simple property access: {expr}.prop
#[cfg(not(feature = "no_object"))]
(Expr::Property(..), ChainType::Dotting) => (),
#[cfg(not(feature = "no_object"))]
#[cfg(not(feature = "no_index"))]
(Expr::Property(..), ChainType::Indexing) => {
unreachable!("unexpected Expr::Property for indexing")
}
// Short-circuit for indexing with literal: {expr}[1]
#[cfg(not(feature = "no_index"))]
(_, ChainType::Indexing) if rhs.is_constant() => {
idx_values.push(rhs.get_literal_value().unwrap())
}
#[cfg(not(feature = "no_index"))]
(Expr::FnCall(fnc, _), ChainType::Indexing)
if fnc.op_token == Some(crate::tokenizer::Token::InclusiveRange)
|| fnc.op_token == Some(crate::tokenizer::Token::ExclusiveRange) =>
{
idx_values.push(rhs.get_literal_value().unwrap())
}
// Short-circuit for simple method call: {expr}.func()
#[cfg(not(feature = "no_object"))]
(Expr::MethodCall(x, ..), ChainType::Dotting) if x.args.is_empty() => (),
// All other patterns - evaluate the arguments chain
_ => self.eval_dot_index_chain_arguments(
global,
caches,
scope,
this_ptr.as_deref_mut(),
expr,
rhs,
idx_values,
)?,
}
match (lhs, new_val) {
// this.??? or this[???]
(Expr::ThisPtr(var_pos), new_val) => {
self.track_operation(global, *var_pos)?;
#[cfg(feature = "debugging")]
self.dbg(global, caches, scope, this_ptr.as_deref_mut(), lhs)?;
this_ptr.map_or_else(
|| Err(ERR::ErrorUnboundThis(*var_pos).into()),
|this_ptr| {
let target = &mut this_ptr.into();
let scope = Some(scope);
self.eval_dot_index_chain_raw(
global, caches, scope, None, lhs, expr, target, rhs, idx_values,
new_val,
)
},
)
}
// id.??? or id[???]
(Expr::Variable(.., var_pos), new_val) => {
self.track_operation(global, *var_pos)?;
#[cfg(feature = "debugging")]
self.dbg(global, caches, scope, this_ptr.as_deref_mut(), lhs)?;
let target = &mut self.search_namespace(global, caches, scope, this_ptr, lhs)?;
self.eval_dot_index_chain_raw(
global, caches, None, None, lhs, expr, target, rhs, idx_values, new_val,
)
}
// {expr}.??? = ??? or {expr}[???] = ???
(_, Some(..)) => unreachable!("cannot assign to an expression"),
// {expr}.??? or {expr}[???]
(lhs_expr, None) => {
let value = self
.eval_expr(global, caches, scope, this_ptr.as_deref_mut(), lhs_expr)?
.flatten();
let item_ptr = &mut value.into();
let scope = Some(scope);
self.eval_dot_index_chain_raw(
global, caches, scope, this_ptr, lhs_expr, expr, item_ptr, rhs, idx_values,
None,
)
}
}
.map(|(v, ..)| v)
}
/// Evaluate a chain of indexes and store the results in a [`FnArgsVec`].
fn eval_dot_index_chain_arguments(
&self,
global: &mut GlobalRuntimeState,
caches: &mut Caches,
scope: &mut Scope,
mut this_ptr: Option<&mut Dynamic>,
parent: &Expr,
expr: &Expr,
idx_values: &mut FnArgsVec<Dynamic>,
) -> RhaiResultOf<()> {
self.track_operation(global, expr.position())?;
match (expr, ChainType::from(parent)) {
#[cfg(not(feature = "no_object"))]
(Expr::MethodCall(x, ..), ChainType::Dotting) => {
#[cfg(not(feature = "no_module"))]
debug_assert!(
!x.is_qualified(),
"method call in dot chain should not be namespace-qualified"
);
for expr in &*x.args {
let arg_value =
self.get_arg_value(global, caches, scope, this_ptr.as_deref_mut(), expr)?;
idx_values.push(arg_value.0.flatten());
}
}
#[cfg(not(feature = "no_object"))]
(Expr::Property(..), ChainType::Dotting) => (),
(Expr::Index(x, ..) | Expr::Dot(x, ..), chain_type)
if !parent.options().intersects(ASTFlags::BREAK) =>
{
let BinaryExpr { lhs, rhs, .. } = &**x;
let mut _arg_values = FnArgsVec::new_const();
// Evaluate in left-to-right order
match (lhs, chain_type) {
#[cfg(not(feature = "no_object"))]
(Expr::Property(..), ChainType::Dotting) => (),
#[cfg(not(feature = "no_object"))]
(Expr::MethodCall(x, ..), ChainType::Dotting) => {
#[cfg(not(feature = "no_module"))]
debug_assert!(
!x.is_qualified(),
"method call in dot chain should not be namespace-qualified"
);
for expr in &*x.args {
let tp = this_ptr.as_deref_mut();
let arg_value = self.get_arg_value(global, caches, scope, tp, expr)?;
_arg_values.push(arg_value.0.flatten());
}
}
#[cfg(not(feature = "no_index"))]
(_, ChainType::Indexing) => {
_arg_values.push(
self.eval_expr(global, caches, scope, this_ptr.as_deref_mut(), lhs)?
.flatten(),
);
}
#[allow(unreachable_patterns)]
(expr, chain_type) => {
unreachable!("unknown {:?} expression: {:?}", chain_type, expr)
}
}
// Push in reverse order
self.eval_dot_index_chain_arguments(
global, caches, scope, this_ptr, expr, rhs, idx_values,
)?;
idx_values.extend(_arg_values);
}
#[cfg(not(feature = "no_index"))]
(_, ChainType::Indexing) => idx_values.push(
self.eval_expr(global, caches, scope, this_ptr, expr)?
.flatten(),
),
#[allow(unreachable_patterns)]
(expr, chain_type) => unreachable!("unknown {:?} expression: {:?}", chain_type, expr),
}
Ok(())
}
/// Chain-evaluate a dot/index chain.
fn eval_dot_index_chain_raw(
&self,
global: &mut GlobalRuntimeState,
caches: &mut Caches,
scope: Option<&mut Scope>,
mut this_ptr: Option<&mut Dynamic>,
root: &Expr,
parent: &Expr,
target: &mut Target,
rhs: &Expr,
idx_values: &mut FnArgsVec<Dynamic>,
new_val: Option<(Dynamic, &OpAssignment)>,
) -> RhaiResultOf<(Dynamic, bool)> {
let mut b;
let mut s = scope;
macro_rules! x {
($var:ident, $base:ident) => {{
if $var.is_none() {
$base = Scope::new();
$var = Some(&mut $base);
}
$var.as_deref_mut().unwrap()
}};
}
let is_ref_mut = target.is_ref();
let op_pos = parent.position();
match ChainType::from(parent) {
#[cfg(not(feature = "no_index"))]
ChainType::Indexing => {
// Check for existence with the null conditional operator
if parent.options().intersects(ASTFlags::NEGATED) && target.as_ref().is_unit() {
return Ok((Dynamic::UNIT, false));
}
let pos = rhs.start_position();
match (rhs, new_val) {
// xxx[idx].expr... | xxx[idx][expr]...
(Expr::Dot(x, ..) | Expr::Index(x, ..), new_val)
if !parent.options().intersects(ASTFlags::BREAK) =>
{
#[cfg(feature = "debugging")]
self.dbg(global, caches, x!(s, b), this_ptr.as_deref_mut(), parent)?;
let idx_val = &mut idx_values.pop().unwrap();
let mut idx_val_for_setter = idx_val.clone();
let idx_pos = x.lhs.start_position();
let (try_setter, result) = {
let obj = target.as_mut();
#[cfg(not(feature = "no_closure"))]
let mut target_guard;
#[cfg(not(feature = "no_closure"))]
let obj = if obj.is_shared() {
target_guard = obj.write_lock::<Dynamic>().unwrap();
&mut *target_guard
} else {
obj
};
let tp = this_ptr.as_deref_mut();
let new_scope = x!(s, b);
let mut item = self.get_indexed_mut(
global, caches, new_scope, tp, obj, idx_val, idx_pos, op_pos,
false, true,
)?;
let is_item_temp_val = item.is_temp_value();
let item_ptr = &mut item;
match self.eval_dot_index_chain_raw(
global, caches, s, this_ptr, root, rhs, item_ptr, &x.rhs,
idx_values, new_val,
) {
Ok((result, true)) if is_item_temp_val => {
(Some(item.take_or_clone()), (result, true))
}
Ok(result) => (None, result),
Err(err) => return Err(err),
}
};
if let Some(mut new_val) = try_setter {
// Try to call index setter if value is changed
let target = target.as_mut();
let idx = &mut idx_val_for_setter;
let new_val = &mut new_val;
// The return value of a indexer setter (usually `()`) is thrown away and not used.
let _ = self
.call_indexer_set(
global, caches, target, idx, new_val, is_ref_mut, op_pos,
)
.or_else(|e| match *e {
ERR::ErrorIndexingType(..) => Ok((Dynamic::UNIT, false)),
_ => Err(e),
})?;
}
Ok(result)
}
// xxx[rhs] op= new_val
(_, Some((new_val, op_info))) => {
#[cfg(feature = "debugging")]
self.dbg(global, caches, x!(s, b), this_ptr.as_deref_mut(), parent)?;
let obj = target.as_mut();
#[cfg(not(feature = "no_closure"))]
let mut target_guard;
#[cfg(not(feature = "no_closure"))]
let obj = if obj.is_shared() {
target_guard = obj.write_lock::<Dynamic>().unwrap();
&mut *target_guard
} else {
obj
};
let new_scope = x!(s, b);
let idx_val = &mut idx_values.pop().unwrap();
let idx = &mut idx_val.clone();
let try_setter = match self.get_indexed_mut(
global, caches, new_scope, this_ptr, obj, idx, pos, op_pos, true, false,
) {
// Indexed value is not a temp value - update directly
Ok(ref mut item_ptr) => {
self.eval_op_assignment(
global, caches, op_info, root, item_ptr, new_val,
)?;
self.check_data_size(item_ptr.as_ref(), op_info.position())?;
None
}
// Indexed value cannot be referenced - use indexer
#[cfg(not(feature = "no_index"))]
Err(err) if matches!(*err, ERR::ErrorIndexingType(..)) => Some(new_val),
// Any other error
Err(err) => return Err(err),
};
if let Some(mut new_val) = try_setter {
// Is this an op-assignment?
if op_info.is_op_assignment() {
let idx = &mut idx_val.clone();
// Call the index getter to get the current value
if let Ok(val) =
self.call_indexer_get(global, caches, obj, idx, op_pos)
{
let mut val = val.into();
// Run the op-assignment
self.eval_op_assignment(
global, caches, op_info, root, &mut val, new_val,
)?;
// Replace new value
new_val = val.take_or_clone();
self.check_data_size(&new_val, op_info.position())?;
}
}
// Try to call index setter
let new_val = &mut new_val;
// The return value of a indexer setter (usually `()`) is thrown away and not used.
let _ = self.call_indexer_set(
global, caches, obj, idx_val, new_val, is_ref_mut, op_pos,
)?;
}
Ok((Dynamic::UNIT, true))
}
// xxx[rhs]
(_, None) => {
#[cfg(feature = "debugging")]
self.dbg(global, caches, x!(s, b), this_ptr.as_deref_mut(), parent)?;
let obj = target.as_mut();
#[cfg(not(feature = "no_closure"))]
let mut target_guard;
#[cfg(not(feature = "no_closure"))]
let obj = if obj.is_shared() {
target_guard = obj.write_lock::<Dynamic>().unwrap();
&mut *target_guard
} else {
obj
};
let new_scope = x!(s, b);
let idx_val = &mut idx_values.pop().unwrap();
self.get_indexed_mut(
global, caches, new_scope, this_ptr, obj, idx_val, pos, op_pos, false,
true,
)
.map(|v| (v.take_or_clone(), false))
}
}
}
#[cfg(not(feature = "no_object"))]
ChainType::Dotting => {
// Check for existence with the Elvis operator
if parent.options().intersects(ASTFlags::NEGATED) && target.as_ref().is_unit() {
return Ok((Dynamic::UNIT, false));
}
match (rhs, new_val, target.as_ref().is_map()) {
// xxx.fn_name(...) = ???
(Expr::MethodCall(..), Some(..), ..) => {
unreachable!("method call cannot be assigned to")
}
// xxx.fn_name(arg_expr_list)
(Expr::MethodCall(x, pos), None, ..) => {
#[cfg(not(feature = "no_module"))]
debug_assert!(
!x.is_qualified(),
"method call in dot chain should not be namespace-qualified"
);
#[cfg(feature = "debugging")]
let reset = self.dbg_reset(global, caches, x!(s, b), this_ptr, rhs)?;
#[cfg(feature = "debugging")]
defer! { global if Some(reset) => move |g| g.debugger_mut().reset_status(reset) }
let crate::ast::FnCallExpr {
name, hashes, args, ..
} = &**x;
// Truncate the index values upon exit
defer! { idx_values => truncate; let offset = idx_values.len() - args.len(); }
let call_args = &mut idx_values[offset..];
let arg1_pos = args.first().map_or(Position::NONE, Expr::position);
self.make_method_call(
global, caches, name, *hashes, target, call_args, arg1_pos, *pos,
)
}
// {xxx:map}.id op= ???
(Expr::Property(x, pos), Some((new_val, op_info)), true) => {
#[cfg(feature = "debugging")]
self.dbg(global, caches, x!(s, b), this_ptr.as_deref_mut(), rhs)?;
let index = &mut x.2.clone().into();
{
let obj = target.as_mut();
#[cfg(not(feature = "no_closure"))]
let mut target_guard;
#[cfg(not(feature = "no_closure"))]
let obj = if obj.is_shared() {
target_guard = obj.write_lock::<Dynamic>().unwrap();
&mut *target_guard
} else {
obj
};
let new_scope = x!(s, b);
let item = &mut self.get_indexed_mut(
global, caches, new_scope, this_ptr, obj, index, *pos, op_pos,
true, false,
)?;
self.eval_op_assignment(global, caches, op_info, root, item, new_val)?;
}
self.check_data_size(target.source(), op_info.position())?;
Ok((Dynamic::UNIT, true))
}
// {xxx:map}.id
(Expr::Property(x, pos), None, true) => {
#[cfg(feature = "debugging")]
self.dbg(global, caches, x!(s, b), this_ptr.as_deref_mut(), rhs)?;
let obj = target.as_mut();
#[cfg(not(feature = "no_closure"))]
let mut target_guard;
#[cfg(not(feature = "no_closure"))]
let obj = if obj.is_shared() {
target_guard = obj.write_lock::<Dynamic>().unwrap();
&mut *target_guard
} else {
obj
};
let index = &mut x.2.clone().into();
let new_scope = x!(s, b);
let item = self.get_indexed_mut(
global, caches, new_scope, this_ptr, obj, index, *pos, op_pos, false,
false,
)?;
Ok((item.take_or_clone(), false))
}
// xxx.id op= ???
(Expr::Property(x, pos), Some((mut new_val, op_info)), false) => {
#[cfg(feature = "debugging")]
self.dbg(global, caches, x!(s, b), this_ptr, rhs)?;
let ((getter, hash_get), (setter, hash_set), name) = &**x;
if op_info.is_op_assignment() {
let args = &mut [target.as_mut()];
let (mut orig_val, ..) = self
.exec_native_fn_call(
global, caches, getter, None, *hash_get, args, is_ref_mut,
false, *pos,
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
ERR::ErrorDotExpr(..) => {
let target = target.as_mut();
let mut prop = name.into();
self.call_indexer_get(
global, caches, target, &mut prop, op_pos,
)
.map(|r| (r, false))
.map_err(|e| {
match *e {
ERR::ErrorIndexingType(..) => err,
_ => e,
}
})
}
_ => Err(err),
})?;
{
let orig_val = &mut (&mut orig_val).into();
self.eval_op_assignment(
global, caches, op_info, root, orig_val, new_val,
)?;
}
new_val = orig_val;
}
let args = &mut [target.as_mut(), &mut new_val];
self.exec_native_fn_call(
global, caches, setter, None, *hash_set, args, is_ref_mut, false, *pos,
)
.or_else(|err| match *err {
// Try an indexer if property does not exist
ERR::ErrorDotExpr(..) => {
let target = target.as_mut();