ruchy 4.2.0

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
//! Control flow implementation module
//!
//! This module handles loops (for, while, loop), match expressions,
//! pattern matching, and assignment operations.
//! Extracted from interpreter.rs for maintainability.

#![allow(clippy::unused_self)]
#![allow(clippy::only_used_in_recursion)]
#![allow(clippy::uninlined_format_args)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::expect_used)]
#![allow(clippy::cast_possible_truncation)]

use crate::frontend::ast::{BinaryOp as AstBinaryOp, Expr, ExprKind, Literal, MatchArm, Pattern};
use crate::runtime::interpreter::{Interpreter, LoopControlOrError};
use crate::runtime::{InterpreterError, Value};
use std::sync::Arc;

impl Interpreter {
    /// Evaluate a for loop
    pub(crate) fn eval_for_loop(
        &mut self,
        label: Option<&String>,
        var: &str,
        _pattern: Option<&Pattern>,
        iter: &Expr,
        body: &Expr,
    ) -> Result<Value, InterpreterError> {
        let iter_value = self.eval_expr(iter)?;

        match iter_value {
            Value::Array(ref arr) => self.eval_for_array_iteration(label, var, arr, body),
            Value::Range {
                ref start,
                ref end,
                inclusive,
            } => self.eval_for_range_iteration(label, var, start, end, inclusive, body),
            _ => Err(InterpreterError::TypeError(
                "For loop requires an iterable".to_string(),
            )),
        }
    }

    /// Evaluate for loop iteration over an array
    /// Complexity: ≤8
    pub(crate) fn eval_for_array_iteration(
        &mut self,
        label: Option<&String>,
        loop_var: &str,
        arr: &[Value],
        body: &Expr,
    ) -> Result<Value, InterpreterError> {
        let mut last_value = Value::nil();

        for item in arr {
            self.set_variable(loop_var, item.clone());
            match self.eval_loop_body_with_control_flow(body) {
                Ok(value) => last_value = value,
                Err(LoopControlOrError::Break(break_label, break_val)) => {
                    // If break has no label or matches this loop's label, break here
                    if break_label.is_none() || break_label.as_deref() == label.map(String::as_str)
                    {
                        return Ok(break_val);
                    }
                    // Otherwise, propagate to outer loop
                    return Err(InterpreterError::Break(break_label, break_val));
                }
                Err(LoopControlOrError::Continue(continue_label)) => {
                    // If continue has no label or matches this loop's label, continue here
                    if continue_label.is_none()
                        || continue_label.as_deref() == label.map(String::as_str)
                    {
                        continue;
                    }
                    // Otherwise, propagate to outer loop
                    return Err(InterpreterError::Continue(continue_label));
                }
                Err(LoopControlOrError::Return(return_val)) => {
                    return Err(InterpreterError::Return(return_val))
                }
                Err(LoopControlOrError::Error(e)) => return Err(e),
            }
        }

        Ok(last_value)
    }

    /// Evaluate for loop iteration over a range
    /// Complexity: ≤9
    pub(crate) fn eval_for_range_iteration(
        &mut self,
        label: Option<&String>,
        loop_var: &str,
        start: &Value,
        end: &Value,
        inclusive: bool,
        body: &Expr,
    ) -> Result<Value, InterpreterError> {
        let (start_val, end_val) = self.extract_range_bounds(start, end)?;
        let mut last_value = Value::nil();

        for i in self.create_range_iterator(start_val, end_val, inclusive) {
            self.set_variable(loop_var, Value::Integer(i));
            match self.eval_loop_body_with_control_flow(body) {
                Ok(value) => last_value = value,
                Err(LoopControlOrError::Break(break_label, break_val)) => {
                    if break_label.is_none() || break_label.as_deref() == label.map(String::as_str)
                    {
                        return Ok(break_val);
                    }
                    return Err(InterpreterError::Break(break_label, break_val));
                }
                Err(LoopControlOrError::Continue(continue_label)) => {
                    if continue_label.is_none()
                        || continue_label.as_deref() == label.map(String::as_str)
                    {
                        continue;
                    }
                    return Err(InterpreterError::Continue(continue_label));
                }
                Err(LoopControlOrError::Return(return_val)) => {
                    return Err(InterpreterError::Return(return_val))
                }
                Err(LoopControlOrError::Error(e)) => return Err(e),
            }
        }

        Ok(last_value)
    }

    /// Extract integer bounds from range values
    /// Complexity: ≤3
    pub(crate) fn extract_range_bounds(
        &self,
        start: &Value,
        end: &Value,
    ) -> Result<(i64, i64), InterpreterError> {
        match (start, end) {
            (Value::Integer(s), Value::Integer(e)) => Ok((*s, *e)),
            _ => Err(InterpreterError::TypeError(
                "Range bounds must be integers".to_string(),
            )),
        }
    }

    /// Create range iterator based on inclusive flag
    /// Complexity: ≤2
    pub(crate) fn create_range_iterator(
        &self,
        start: i64,
        end: i64,
        inclusive: bool,
    ) -> Box<dyn Iterator<Item = i64>> {
        if inclusive {
            Box::new(start..=end)
        } else {
            Box::new(start..end)
        }
    }

    /// Evaluate loop body with control flow handling
    /// Complexity: ≤5
    pub(crate) fn eval_loop_body_with_control_flow(
        &mut self,
        body: &Expr,
    ) -> Result<Value, LoopControlOrError> {
        match self.eval_expr(body) {
            Ok(value) => Ok(value),
            Err(InterpreterError::Break(label, val)) => Err(LoopControlOrError::Break(label, val)),
            Err(InterpreterError::Continue(label)) => Err(LoopControlOrError::Continue(label)),
            Err(InterpreterError::Return(val)) => Err(LoopControlOrError::Return(val)),
            Err(e) => Err(LoopControlOrError::Error(e)),
        }
    }

    /// Evaluate a while loop
    pub(crate) fn eval_while_loop(
        &mut self,
        label: Option<&String>,
        condition: &Expr,
        body: &Expr,
    ) -> Result<Value, InterpreterError> {
        let mut last_value = Value::Nil;
        loop {
            let cond_value = self.eval_expr(condition)?;
            if !matches!(cond_value, Value::Bool(true)) && cond_value != Value::Integer(1) {
                break;
            }

            match self.eval_loop_body_with_control_flow(body) {
                Ok(value) => last_value = value,
                Err(LoopControlOrError::Break(break_label, break_val)) => {
                    if break_label.is_none() || break_label.as_deref() == label.map(String::as_str)
                    {
                        return Ok(break_val);
                    }
                    return Err(InterpreterError::Break(break_label, break_val));
                }
                Err(LoopControlOrError::Continue(continue_label)) => {
                    if continue_label.is_none()
                        || continue_label.as_deref() == label.map(String::as_str)
                    {
                        continue;
                    }
                    return Err(InterpreterError::Continue(continue_label));
                }
                Err(LoopControlOrError::Return(return_val)) => {
                    return Err(InterpreterError::Return(return_val))
                }
                Err(LoopControlOrError::Error(e)) => return Err(e),
            }
        }
        Ok(last_value)
    }

    /// Evaluate an infinite loop (loop { ... })
    pub(crate) fn eval_loop(
        &mut self,
        label: Option<&String>,
        body: &Expr,
    ) -> Result<Value, InterpreterError> {
        loop {
            match self.eval_loop_body_with_control_flow(body) {
                Ok(_) => {}
                Err(LoopControlOrError::Break(break_label, break_val)) => {
                    if break_label.is_none() || break_label.as_deref() == label.map(String::as_str)
                    {
                        return Ok(break_val);
                    }
                    return Err(InterpreterError::Break(break_label, break_val));
                }
                Err(LoopControlOrError::Continue(continue_label)) => {
                    if continue_label.is_none()
                        || continue_label.as_deref() == label.map(String::as_str)
                    {
                        continue;
                    }
                    return Err(InterpreterError::Continue(continue_label));
                }
                Err(LoopControlOrError::Return(return_val)) => {
                    return Err(InterpreterError::Return(return_val))
                }
                Err(LoopControlOrError::Error(e)) => return Err(e),
            }
        }
    }

    /// Evaluate a match expression
    pub fn eval_match(
        &mut self,
        expr: &Expr,
        arms: &[MatchArm],
    ) -> Result<Value, InterpreterError> {
        let value = self.eval_expr(expr)?;

        for arm in arms {
            // First check if pattern matches
            if let Some(bindings) = self.try_pattern_match(&arm.pattern, &value)? {
                // Create new scope for pattern bindings
                self.push_scope();

                // Bind pattern variables
                for (name, val) in bindings {
                    self.env_set(name, val);
                }

                // Check guard condition if present
                let guard_passed = if let Some(guard) = &arm.guard {
                    match self.eval_expr(guard)? {
                        Value::Bool(true) => true,
                        Value::Bool(false) => false,
                        _ => {
                            self.pop_scope();
                            return Err(InterpreterError::RuntimeError(
                                "Guard condition must evaluate to a boolean".to_string(),
                            ));
                        }
                    }
                } else {
                    true // No guard means always pass
                };

                if guard_passed {
                    // Evaluate body with bindings in scope
                    let result = self.eval_expr(&arm.body);
                    self.pop_scope();
                    return result;
                }
                // Guard failed, restore scope and try next arm
                self.pop_scope();
            }
        }

        Err(InterpreterError::RuntimeError(
            "No match arm matched the value".to_string(),
        ))
    }

    /// Evaluate a let pattern expression (array/tuple destructuring)
    /// Extract names of identifiers marked as mutable in a pattern
    /// Complexity: 4 (within Toyota Way limits)
    pub(crate) fn extract_mut_names(pattern: &Pattern) -> std::collections::HashSet<String> {
        let mut mut_names = std::collections::HashSet::new();

        fn walk_pattern(
            p: &Pattern,
            mut_names: &mut std::collections::HashSet<String>,
            is_mut: bool,
        ) {
            match p {
                Pattern::Mut(inner) => walk_pattern(inner, mut_names, true),
                Pattern::Identifier(name) if is_mut => {
                    mut_names.insert(name.clone());
                }
                Pattern::Tuple(patterns) | Pattern::List(patterns) => {
                    for pat in patterns {
                        walk_pattern(pat, mut_names, is_mut);
                    }
                }
                Pattern::Struct { fields, .. } => {
                    for field in fields {
                        if let Some(ref pat) = field.pattern {
                            walk_pattern(pat, mut_names, is_mut);
                        }
                    }
                }
                Pattern::AtBinding { pattern, .. } => walk_pattern(pattern, mut_names, is_mut),
                _ => {}
            }
        }

        walk_pattern(pattern, &mut mut_names, false);
        mut_names
    }

    /// Evaluate let pattern with support for mut destructuring
    /// Complexity: 6 (within Toyota Way limits)
    pub(crate) fn eval_let_pattern(
        &mut self,
        pattern: &Pattern,
        value: &Expr,
        body: &Expr,
    ) -> Result<Value, InterpreterError> {
        // Evaluate the right-hand side value
        let rhs_value = self.eval_expr(value)?;

        // Extract names marked as mutable in the pattern
        let mut_names = Self::extract_mut_names(pattern);

        // Try to match the pattern against the value
        if let Some(bindings) = self.try_pattern_match(pattern, &rhs_value)? {
            // Bind pattern variables, using mutable binding for names wrapped in Pattern::Mut
            for (name, val) in bindings {
                if mut_names.contains(&name) {
                    self.env_set_mut(name.clone(), val);
                } else {
                    self.env_set(name, val);
                }
            }

            // If body is unit (empty), return the value like REPL does
            // This makes `let [a, b] = [1, 2]` return [1, 2] instead of nil
            match &body.kind {
                ExprKind::Literal(Literal::Unit) => Ok(rhs_value),
                _ => self.eval_expr(body),
            }
        } else {
            Err(InterpreterError::RuntimeError(
                "Pattern did not match the value".to_string(),
            ))
        }
    }

    /// Evaluate an assignment
    /// Evaluates assignment expressions including field assignments.
    ///
    /// This method handles variable assignments (`x = value`) and field assignments (`obj.field = value`).
    /// For field assignments, it creates a new object with the updated field value.
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::frontend::parser::Parser;
    /// use ruchy::runtime::interpreter::{Interpreter, Value};
    ///
    /// let mut interpreter = Interpreter::new();
    /// let code = r#"
    ///     class Point {
    ///         x: i32,
    ///         y: i32
    ///
    ///         new(x: i32, y: i32) {
    ///             self.x = x
    ///             self.y = y
    ///         }
    ///     }
    ///
    ///     fn main() {
    ///         let p = Point::new(10, 20)
    ///         p.x
    ///     }
    /// "#;
    ///
    /// let mut parser = Parser::new(code);
    /// let expr = parser.parse().expect("parse should succeed in doctest");
    /// interpreter.eval_expr(&expr).expect("eval_expr should succeed in doctest");
    /// let main_call = Parser::new("main()").parse().expect("parse should succeed in doctest");
    /// let result = interpreter.eval_expr(&main_call).expect("eval_expr should succeed in doctest");
    /// assert!(matches!(result, Value::Integer(10)));
    /// ```
    pub(crate) fn eval_assign(
        &mut self,
        target: &Expr,
        value: &Expr,
    ) -> Result<Value, InterpreterError> {
        let val = self.eval_expr(value)?;

        // Handle different assignment targets
        match &target.kind {
            ExprKind::Identifier(name) => {
                self.set_variable(name, val.clone());
                Ok(val)
            }
            ExprKind::FieldAccess { object, field } => {
                // Handle field assignment like: obj.field = value
                // We need to get the object, update it, and reassign it
                match &object.kind {
                    ExprKind::Identifier(obj_name) => {
                        // Get the object
                        let obj = self.lookup_variable(obj_name)?;

                        // Update the field based on object type
                        match obj {
                            Value::Object(ref map) => {
                                // Immutable object: create new copy with updated field
                                let mut new_map = (**map).clone();
                                new_map.insert(field.clone(), val.clone());
                                let new_obj = Value::Object(Arc::new(new_map));

                                // Update the variable with the modified object
                                self.set_variable(obj_name, new_obj);
                                Ok(val)
                            }
                            Value::ObjectMut(ref cell) => {
                                // Mutable object: update in place via RefCell
                                cell.lock()
                                    .expect("Mutex poisoned: object lock is corrupted")
                                    .insert(field.clone(), val.clone());
                                Ok(val)
                            }
                            Value::Class { ref fields, .. } => {
                                // Class: update field in place via RwLock
                                let mut fields_write = fields
                                    .write()
                                    .expect("RwLock poisoned: class fields lock is corrupted");
                                fields_write.insert(field.clone(), val.clone());
                                Ok(val)
                            }
                            Value::Struct {
                                ref name,
                                ref fields,
                            } => {
                                // Struct: create new copy with updated field (value semantics)
                                let mut new_fields = (**fields).clone();
                                new_fields.insert(field.clone(), val.clone());
                                let new_struct = Value::Struct {
                                    name: name.clone(),
                                    fields: Arc::new(new_fields),
                                };

                                // Update the variable with the modified struct
                                self.set_variable(obj_name, new_struct);
                                Ok(val)
                            }
                            _ => Err(InterpreterError::RuntimeError(format!(
                                "Cannot access field '{}' on non-object",
                                field
                            ))),
                        }
                    }
                    _ => Err(InterpreterError::RuntimeError(
                        "Complex assignment targets not yet supported".to_string(),
                    )),
                }
            }
            // BUG-003: Support array index assignment (arr[i] = value)
            ExprKind::IndexAccess { object, index } => self.eval_index_assign(object, index, val),
            _ => Err(InterpreterError::RuntimeError(
                "Invalid assignment target".to_string(),
            )),
        }
    }

    /// BUG-003: Evaluate array/vector index assignment (arr[i] = value, matrix[i][j] = value)
    ///
    /// Handles both simple (arr[0] = 99) and nested (matrix[0][1] = 99) index assignment.
    /// Complexity: 8 (≤10 target)
    pub(crate) fn eval_index_assign(
        &mut self,
        object: &Expr,
        index: &Expr,
        val: Value,
    ) -> Result<Value, InterpreterError> {
        match &object.kind {
            ExprKind::Identifier(arr_name) => {
                // Simple case: arr[i] = value
                let idx_val = self.eval_expr(index)?;
                let idx = match idx_val {
                    Value::Integer(i) => i as usize,
                    _ => {
                        return Err(InterpreterError::RuntimeError(
                            "Array index must be an integer".to_string(),
                        ))
                    }
                };

                let arr = self.lookup_variable(arr_name)?;
                match arr {
                    Value::Array(ref vec) => {
                        let mut new_vec = vec.to_vec();
                        if idx < new_vec.len() {
                            new_vec[idx] = val.clone();
                            self.set_variable(arr_name, Value::Array(Arc::from(new_vec)));
                            Ok(val)
                        } else {
                            Err(InterpreterError::RuntimeError(format!(
                                "Index {} out of bounds for array of length {}",
                                idx,
                                new_vec.len()
                            )))
                        }
                    }
                    _ => Err(InterpreterError::RuntimeError(
                        "Cannot index non-array value".to_string(),
                    )),
                }
            }
            ExprKind::IndexAccess {
                object: nested_obj,
                index: nested_idx,
            } => {
                // Nested case: matrix[i][j] = value
                // Get the outer index first
                let outer_idx_val = self.eval_expr(nested_idx)?;
                let outer_idx = match outer_idx_val {
                    Value::Integer(i) => i as usize,
                    _ => {
                        return Err(InterpreterError::RuntimeError(
                            "Array index must be an integer".to_string(),
                        ))
                    }
                };

                // Get the root array name (only handle Identifier for now)
                if let ExprKind::Identifier(arr_name) = &nested_obj.kind {
                    let arr = self.lookup_variable(arr_name)?;

                    // Get inner array and update it
                    if let Value::Array(ref outer_vec) = arr {
                        let mut new_outer = outer_vec.to_vec();
                        if outer_idx < new_outer.len() {
                            // Get inner array
                            if let Value::Array(ref inner_vec) = new_outer[outer_idx] {
                                let inner_idx_val = self.eval_expr(index)?;
                                let inner_idx = match inner_idx_val {
                                    Value::Integer(i) => i as usize,
                                    _ => {
                                        return Err(InterpreterError::RuntimeError(
                                            "Array index must be an integer".to_string(),
                                        ))
                                    }
                                };

                                let mut new_inner = inner_vec.to_vec();
                                if inner_idx < new_inner.len() {
                                    new_inner[inner_idx] = val.clone();
                                    new_outer[outer_idx] = Value::Array(Arc::from(new_inner));
                                    self.set_variable(arr_name, Value::Array(Arc::from(new_outer)));
                                    Ok(val)
                                } else {
                                    Err(InterpreterError::RuntimeError(format!(
                                        "Inner index {} out of bounds",
                                        inner_idx
                                    )))
                                }
                            } else {
                                Err(InterpreterError::RuntimeError(
                                    "Cannot index non-array value".to_string(),
                                ))
                            }
                        } else {
                            Err(InterpreterError::RuntimeError(format!(
                                "Outer index {} out of bounds",
                                outer_idx
                            )))
                        }
                    } else {
                        Err(InterpreterError::RuntimeError(
                            "Cannot index non-array value".to_string(),
                        ))
                    }
                } else {
                    Err(InterpreterError::RuntimeError(
                        "Complex nested index assignment not yet supported".to_string(),
                    ))
                }
            }
            _ => Err(InterpreterError::RuntimeError(
                "Complex array assignment targets not yet supported".to_string(),
            )),
        }
    }

    /// Evaluate a compound assignment
    /// Complexity: 6
    pub(crate) fn eval_compound_assign(
        &mut self,
        target: &Expr,
        op: AstBinaryOp,
        value: &Expr,
    ) -> Result<Value, InterpreterError> {
        // Get current value
        let current = match &target.kind {
            ExprKind::Identifier(name) => self.lookup_variable(name)?,
            ExprKind::FieldAccess { object, field } => self.eval_field_access(object, field)?,
            _ => {
                return Err(InterpreterError::RuntimeError(
                    "Invalid compound assignment target".to_string(),
                ))
            }
        };

        // Compute new value
        let rhs = self.eval_expr(value)?;
        let new_val = self.apply_binary_op(&current, op, &rhs)?;

        // Assign back
        match &target.kind {
            ExprKind::Identifier(name) => {
                self.set_variable(name, new_val.clone());
            }
            ExprKind::FieldAccess { object, field } => {
                // Same pattern as regular field assignment (lines 3924-3960)
                match &object.kind {
                    ExprKind::Identifier(obj_name) => {
                        let obj = self.lookup_variable(obj_name)?;
                        match obj {
                            Value::Object(ref map) => {
                                let mut new_map = (**map).clone();
                                new_map.insert(field.clone(), new_val.clone());
                                let new_obj = Value::Object(Arc::new(new_map));
                                self.set_variable(obj_name, new_obj);
                            }
                            Value::Struct { name, fields } => {
                                let mut new_fields = fields.as_ref().clone();
                                new_fields.insert(field.clone(), new_val.clone());
                                let new_struct = Value::Struct {
                                    name,
                                    fields: Arc::new(new_fields),
                                };
                                self.set_variable(obj_name, new_struct);
                            }
                            _ => {
                                return Err(InterpreterError::RuntimeError(format!(
                                    "Cannot assign to field of non-object type: {:?}",
                                    obj
                                )))
                            }
                        }
                    }
                    _ => {
                        return Err(InterpreterError::RuntimeError(
                            "Complex field access not supported in compound assignment".to_string(),
                        ))
                    }
                }
            }
            _ => unreachable!(),
        }

        Ok(new_val)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::frontend::ast::{Span, Type, TypeKind};
    use std::collections::HashMap;

    fn make_interpreter() -> Interpreter {
        Interpreter::new()
    }

    fn make_expr(kind: ExprKind) -> Expr {
        Expr::new(kind, Span::default())
    }

    fn make_type(name: &str) -> Type {
        Type {
            kind: TypeKind::Named(name.to_string()),
            span: Span::default(),
        }
    }

    fn make_match_arm(pattern: Pattern, guard: Option<Expr>, body: Expr) -> MatchArm {
        MatchArm {
            pattern,
            guard: guard.map(Box::new),
            body: Box::new(body),
            span: Span::default(),
        }
    }

    // =========================================================================
    // Range extraction and iteration tests
    // =========================================================================

    #[test]
    fn test_extract_range_bounds_success() {
        let interp = make_interpreter();
        let start = Value::Integer(0);
        let end = Value::Integer(10);
        let result = interp.extract_range_bounds(&start, &end).unwrap();
        assert_eq!(result, (0, 10));
    }

    #[test]
    fn test_extract_range_bounds_negative() {
        let interp = make_interpreter();
        let start = Value::Integer(-5);
        let end = Value::Integer(5);
        let result = interp.extract_range_bounds(&start, &end).unwrap();
        assert_eq!(result, (-5, 5));
    }

    #[test]
    fn test_extract_range_bounds_non_integer() {
        let interp = make_interpreter();
        let start = Value::Float(0.0);
        let end = Value::Integer(10);
        let result = interp.extract_range_bounds(&start, &end);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("integers"));
    }

    #[test]
    fn test_create_range_iterator_exclusive() {
        let interp = make_interpreter();
        let iter = interp.create_range_iterator(0, 5, false);
        let collected: Vec<i64> = iter.collect();
        assert_eq!(collected, vec![0, 1, 2, 3, 4]);
    }

    #[test]
    fn test_create_range_iterator_inclusive() {
        let interp = make_interpreter();
        let iter = interp.create_range_iterator(0, 5, true);
        let collected: Vec<i64> = iter.collect();
        assert_eq!(collected, vec![0, 1, 2, 3, 4, 5]);
    }

    // =========================================================================
    // For loop array iteration tests
    // =========================================================================

    #[test]
    fn test_eval_for_array_iteration_empty() {
        let mut interp = make_interpreter();
        let body = make_expr(ExprKind::Literal(Literal::Integer(42, None)));

        let result = interp
            .eval_for_array_iteration(None, "x", &[], &body)
            .unwrap();
        assert_eq!(result, Value::nil());
    }

    #[test]
    fn test_eval_for_array_iteration_simple() {
        let mut interp = make_interpreter();
        interp.set_variable("count", Value::Integer(0));

        let arr = vec![Value::Integer(1), Value::Integer(2), Value::Integer(3)];
        // Just return the loop variable - this tests iteration works
        let body = make_expr(ExprKind::Identifier("x".to_string()));

        let result = interp
            .eval_for_array_iteration(None, "x", &arr, &body)
            .unwrap();
        // Last value is 3
        assert_eq!(result, Value::Integer(3));
    }

    // =========================================================================
    // For loop range iteration tests
    // =========================================================================

    #[test]
    fn test_eval_for_range_iteration_simple() {
        let mut interp = make_interpreter();

        let start = Value::Integer(0);
        let end = Value::Integer(3);
        let body = make_expr(ExprKind::Identifier("i".to_string()));

        let result = interp
            .eval_for_range_iteration(None, "i", &start, &end, false, &body)
            .unwrap();
        // Last value is 2 (exclusive)
        assert_eq!(result, Value::Integer(2));
    }

    #[test]
    fn test_eval_for_range_iteration_inclusive() {
        let mut interp = make_interpreter();

        let start = Value::Integer(0);
        let end = Value::Integer(3);
        let body = make_expr(ExprKind::Identifier("i".to_string()));

        let result = interp
            .eval_for_range_iteration(None, "i", &start, &end, true, &body)
            .unwrap();
        // Last value is 3 (inclusive)
        assert_eq!(result, Value::Integer(3));
    }

    #[test]
    fn test_eval_for_loop_non_iterable() {
        let mut interp = make_interpreter();

        let non_iterable = make_expr(ExprKind::Literal(Literal::Integer(42, None)));
        let body = make_expr(ExprKind::Literal(Literal::Unit));

        let result = interp.eval_for_loop(None, "x", None, &non_iterable, &body);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("iterable"));
    }

    // =========================================================================
    // While loop tests
    // =========================================================================

    #[test]
    fn test_eval_while_loop_false_condition() {
        let mut interp = make_interpreter();

        // while false { ... } - never executes
        let condition = make_expr(ExprKind::Literal(Literal::Bool(false)));
        let body = make_expr(ExprKind::Literal(Literal::Integer(999, None)));

        let result = interp.eval_while_loop(None, &condition, &body).unwrap();
        assert_eq!(result, Value::Nil); // Never executed, returns Nil
    }

    // =========================================================================
    // Loop body control flow tests
    // =========================================================================

    #[test]
    fn test_eval_loop_body_with_control_flow_ok() {
        let mut interp = make_interpreter();
        let body = make_expr(ExprKind::Literal(Literal::Integer(42, None)));

        let result = interp.eval_loop_body_with_control_flow(&body).unwrap();
        assert_eq!(result, Value::Integer(42));
    }

    #[test]
    fn test_eval_loop_body_with_control_flow_break() {
        let mut interp = make_interpreter();
        let body = make_expr(ExprKind::Break {
            label: None,
            value: Some(Box::new(make_expr(ExprKind::Literal(Literal::Integer(
                99, None,
            ))))),
        });

        let result = interp.eval_loop_body_with_control_flow(&body);
        match result {
            Err(LoopControlOrError::Break(None, Value::Integer(99))) => {}
            _ => panic!("Expected Break with value 99"),
        }
    }

    #[test]
    fn test_eval_loop_body_with_control_flow_continue() {
        let mut interp = make_interpreter();
        let body = make_expr(ExprKind::Continue { label: None });

        let result = interp.eval_loop_body_with_control_flow(&body);
        match result {
            Err(LoopControlOrError::Continue(None)) => {}
            _ => panic!("Expected Continue"),
        }
    }

    #[test]
    fn test_eval_loop_body_with_control_flow_return() {
        let mut interp = make_interpreter();
        let body = make_expr(ExprKind::Return {
            value: Some(Box::new(make_expr(ExprKind::Literal(Literal::Integer(
                42, None,
            ))))),
        });

        let result = interp.eval_loop_body_with_control_flow(&body);
        match result {
            Err(LoopControlOrError::Return(Value::Integer(42))) => {}
            _ => panic!("Expected Return with value 42"),
        }
    }

    // =========================================================================
    // Match expression tests
    // =========================================================================

    #[test]
    fn test_eval_match_literal() {
        let mut interp = make_interpreter();

        // match 1 { 1 => "one", _ => "other" }
        let expr = make_expr(ExprKind::Literal(Literal::Integer(1, None)));
        let arms = vec![
            make_match_arm(
                Pattern::Literal(Literal::Integer(1, None)),
                None,
                make_expr(ExprKind::Literal(Literal::String("one".to_string()))),
            ),
            make_match_arm(
                Pattern::Wildcard,
                None,
                make_expr(ExprKind::Literal(Literal::String("other".to_string()))),
            ),
        ];

        let result = interp.eval_match(&expr, &arms).unwrap();
        assert_eq!(result, Value::from_string("one".to_string()));
    }

    #[test]
    fn test_eval_match_wildcard() {
        let mut interp = make_interpreter();

        let expr = make_expr(ExprKind::Literal(Literal::Integer(999, None)));
        let arms = vec![
            make_match_arm(
                Pattern::Literal(Literal::Integer(1, None)),
                None,
                make_expr(ExprKind::Literal(Literal::String("one".to_string()))),
            ),
            make_match_arm(
                Pattern::Wildcard,
                None,
                make_expr(ExprKind::Literal(Literal::String("other".to_string()))),
            ),
        ];

        let result = interp.eval_match(&expr, &arms).unwrap();
        assert_eq!(result, Value::from_string("other".to_string()));
    }

    #[test]
    fn test_eval_match_with_binding() {
        let mut interp = make_interpreter();

        // match 42 { x => x }
        let expr = make_expr(ExprKind::Literal(Literal::Integer(42, None)));
        let arms = vec![make_match_arm(
            Pattern::Identifier("x".to_string()),
            None,
            make_expr(ExprKind::Identifier("x".to_string())),
        )];

        let result = interp.eval_match(&expr, &arms).unwrap();
        assert_eq!(result, Value::Integer(42));
    }

    #[test]
    fn test_eval_match_with_guard() {
        let mut interp = make_interpreter();

        // match 5 { x if x > 3 => "big", _ => "small" }
        let expr = make_expr(ExprKind::Literal(Literal::Integer(5, None)));
        let arms = vec![
            make_match_arm(
                Pattern::Identifier("x".to_string()),
                Some(make_expr(ExprKind::Binary {
                    left: Box::new(make_expr(ExprKind::Identifier("x".to_string()))),
                    op: AstBinaryOp::Greater,
                    right: Box::new(make_expr(ExprKind::Literal(Literal::Integer(3, None)))),
                })),
                make_expr(ExprKind::Literal(Literal::String("big".to_string()))),
            ),
            make_match_arm(
                Pattern::Wildcard,
                None,
                make_expr(ExprKind::Literal(Literal::String("small".to_string()))),
            ),
        ];

        let result = interp.eval_match(&expr, &arms).unwrap();
        assert_eq!(result, Value::from_string("big".to_string()));
    }

    #[test]
    fn test_eval_match_guard_fails() {
        let mut interp = make_interpreter();

        // match 2 { x if x > 3 => "big", _ => "small" }
        let expr = make_expr(ExprKind::Literal(Literal::Integer(2, None)));
        let arms = vec![
            make_match_arm(
                Pattern::Identifier("x".to_string()),
                Some(make_expr(ExprKind::Binary {
                    left: Box::new(make_expr(ExprKind::Identifier("x".to_string()))),
                    op: AstBinaryOp::Greater,
                    right: Box::new(make_expr(ExprKind::Literal(Literal::Integer(3, None)))),
                })),
                make_expr(ExprKind::Literal(Literal::String("big".to_string()))),
            ),
            make_match_arm(
                Pattern::Wildcard,
                None,
                make_expr(ExprKind::Literal(Literal::String("small".to_string()))),
            ),
        ];

        let result = interp.eval_match(&expr, &arms).unwrap();
        assert_eq!(result, Value::from_string("small".to_string()));
    }

    #[test]
    fn test_eval_match_no_match() {
        let mut interp = make_interpreter();

        let expr = make_expr(ExprKind::Literal(Literal::Integer(42, None)));
        let arms = vec![make_match_arm(
            Pattern::Literal(Literal::Integer(1, None)),
            None,
            make_expr(ExprKind::Literal(Literal::Integer(0, None))),
        )];

        let result = interp.eval_match(&expr, &arms);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("No match arm matched"));
    }

    // =========================================================================
    // Extract mut names tests
    // =========================================================================

    #[test]
    fn test_extract_mut_names_simple() {
        let pattern = Pattern::Mut(Box::new(Pattern::Identifier("x".to_string())));
        let mut_names = Interpreter::extract_mut_names(&pattern);
        assert!(mut_names.contains("x"));
    }

    #[test]
    fn test_extract_mut_names_tuple() {
        // (mut a, b, mut c)
        let pattern = Pattern::Tuple(vec![
            Pattern::Mut(Box::new(Pattern::Identifier("a".to_string()))),
            Pattern::Identifier("b".to_string()),
            Pattern::Mut(Box::new(Pattern::Identifier("c".to_string()))),
        ]);
        let mut_names = Interpreter::extract_mut_names(&pattern);
        assert!(mut_names.contains("a"));
        assert!(!mut_names.contains("b"));
        assert!(mut_names.contains("c"));
    }

    #[test]
    fn test_extract_mut_names_list() {
        // [mut x, y]
        let pattern = Pattern::List(vec![
            Pattern::Mut(Box::new(Pattern::Identifier("x".to_string()))),
            Pattern::Identifier("y".to_string()),
        ]);
        let mut_names = Interpreter::extract_mut_names(&pattern);
        assert!(mut_names.contains("x"));
        assert!(!mut_names.contains("y"));
    }

    #[test]
    fn test_extract_mut_names_no_mut() {
        let pattern = Pattern::Identifier("x".to_string());
        let mut_names = Interpreter::extract_mut_names(&pattern);
        assert!(mut_names.is_empty());
    }

    // =========================================================================
    // Let pattern tests
    // =========================================================================

    #[test]
    fn test_eval_let_pattern_simple() {
        let mut interp = make_interpreter();

        // let x = 42; body returns x
        let pattern = Pattern::Identifier("x".to_string());
        let value = make_expr(ExprKind::Literal(Literal::Integer(42, None)));
        let body = make_expr(ExprKind::Identifier("x".to_string()));

        let result = interp.eval_let_pattern(&pattern, &value, &body).unwrap();
        assert_eq!(result, Value::Integer(42));
    }

    #[test]
    fn test_eval_let_pattern_tuple() {
        let mut interp = make_interpreter();

        // let (a, b) = (1, 2); body returns a + b
        let pattern = Pattern::Tuple(vec![
            Pattern::Identifier("a".to_string()),
            Pattern::Identifier("b".to_string()),
        ]);
        let value = make_expr(ExprKind::Tuple(vec![
            make_expr(ExprKind::Literal(Literal::Integer(1, None))),
            make_expr(ExprKind::Literal(Literal::Integer(2, None))),
        ]));
        let body = make_expr(ExprKind::Binary {
            left: Box::new(make_expr(ExprKind::Identifier("a".to_string()))),
            op: AstBinaryOp::Add,
            right: Box::new(make_expr(ExprKind::Identifier("b".to_string()))),
        });

        let result = interp.eval_let_pattern(&pattern, &value, &body).unwrap();
        assert_eq!(result, Value::Integer(3));
    }

    #[test]
    fn test_eval_let_pattern_unit_body() {
        let mut interp = make_interpreter();

        // let x = 42; () - should return the value like REPL
        let pattern = Pattern::Identifier("x".to_string());
        let value = make_expr(ExprKind::Literal(Literal::Integer(42, None)));
        let body = make_expr(ExprKind::Literal(Literal::Unit));

        let result = interp.eval_let_pattern(&pattern, &value, &body).unwrap();
        assert_eq!(result, Value::Integer(42));
    }

    // =========================================================================
    // Assignment tests
    // =========================================================================

    #[test]
    fn test_eval_assign_identifier() {
        let mut interp = make_interpreter();
        interp.set_variable("x", Value::Integer(0));

        let target = make_expr(ExprKind::Identifier("x".to_string()));
        let value = make_expr(ExprKind::Literal(Literal::Integer(42, None)));

        let result = interp.eval_assign(&target, &value).unwrap();
        assert_eq!(result, Value::Integer(42));
        assert_eq!(interp.lookup_variable("x").unwrap(), Value::Integer(42));
    }

    #[test]
    fn test_eval_assign_object_field() {
        let mut interp = make_interpreter();

        // Create an object with a field
        let mut obj = HashMap::new();
        obj.insert("x".to_string(), Value::Integer(0));
        interp.set_variable("point", Value::Object(Arc::new(obj)));

        // point.x = 42
        let target = make_expr(ExprKind::FieldAccess {
            object: Box::new(make_expr(ExprKind::Identifier("point".to_string()))),
            field: "x".to_string(),
        });
        let value = make_expr(ExprKind::Literal(Literal::Integer(42, None)));

        let result = interp.eval_assign(&target, &value).unwrap();
        assert_eq!(result, Value::Integer(42));

        let updated_point = interp.lookup_variable("point").unwrap();
        if let Value::Object(obj) = updated_point {
            assert_eq!(obj.get("x"), Some(&Value::Integer(42)));
        } else {
            panic!("Expected Object");
        }
    }

    #[test]
    fn test_eval_assign_struct_field() {
        let mut interp = make_interpreter();

        // Create a struct with a field
        let mut fields = HashMap::new();
        fields.insert("x".to_string(), Value::Integer(0));
        interp.set_variable(
            "point",
            Value::Struct {
                name: "Point".to_string(),
                fields: Arc::new(fields),
            },
        );

        // point.x = 42
        let target = make_expr(ExprKind::FieldAccess {
            object: Box::new(make_expr(ExprKind::Identifier("point".to_string()))),
            field: "x".to_string(),
        });
        let value = make_expr(ExprKind::Literal(Literal::Integer(42, None)));

        let result = interp.eval_assign(&target, &value).unwrap();
        assert_eq!(result, Value::Integer(42));

        let updated_point = interp.lookup_variable("point").unwrap();
        if let Value::Struct { fields, .. } = updated_point {
            assert_eq!(fields.get("x"), Some(&Value::Integer(42)));
        } else {
            panic!("Expected Struct");
        }
    }

    #[test]
    fn test_eval_assign_invalid_target() {
        let mut interp = make_interpreter();

        // 42 = 0 - invalid target
        let target = make_expr(ExprKind::Literal(Literal::Integer(42, None)));
        let value = make_expr(ExprKind::Literal(Literal::Integer(0, None)));

        let result = interp.eval_assign(&target, &value);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid assignment target"));
    }

    // =========================================================================
    // Index assignment tests
    // =========================================================================

    #[test]
    fn test_eval_index_assign_simple() {
        let mut interp = make_interpreter();

        // arr = [1, 2, 3]
        interp.set_variable(
            "arr",
            Value::Array(Arc::from(vec![
                Value::Integer(1),
                Value::Integer(2),
                Value::Integer(3),
            ])),
        );

        // arr[1] = 99
        let object = make_expr(ExprKind::Identifier("arr".to_string()));
        let index = make_expr(ExprKind::Literal(Literal::Integer(1, None)));

        let result = interp
            .eval_index_assign(&object, &index, Value::Integer(99))
            .unwrap();
        assert_eq!(result, Value::Integer(99));

        let updated_arr = interp.lookup_variable("arr").unwrap();
        if let Value::Array(arr) = updated_arr {
            assert_eq!(arr[1], Value::Integer(99));
        } else {
            panic!("Expected Array");
        }
    }

    #[test]
    fn test_eval_index_assign_out_of_bounds() {
        let mut interp = make_interpreter();

        interp.set_variable(
            "arr",
            Value::Array(Arc::from(vec![Value::Integer(1), Value::Integer(2)])),
        );

        let object = make_expr(ExprKind::Identifier("arr".to_string()));
        let index = make_expr(ExprKind::Literal(Literal::Integer(10, None)));

        let result = interp.eval_index_assign(&object, &index, Value::Integer(99));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("out of bounds"));
    }

    #[test]
    fn test_eval_index_assign_non_integer_index() {
        let mut interp = make_interpreter();

        interp.set_variable("arr", Value::Array(Arc::from(vec![Value::Integer(1)])));

        let object = make_expr(ExprKind::Identifier("arr".to_string()));
        let index = make_expr(ExprKind::Literal(Literal::String("key".to_string())));

        let result = interp.eval_index_assign(&object, &index, Value::Integer(99));
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("must be an integer"));
    }

    #[test]
    fn test_eval_index_assign_non_array() {
        let mut interp = make_interpreter();

        interp.set_variable("x", Value::Integer(42));

        let object = make_expr(ExprKind::Identifier("x".to_string()));
        let index = make_expr(ExprKind::Literal(Literal::Integer(0, None)));

        let result = interp.eval_index_assign(&object, &index, Value::Integer(99));
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Cannot index non-array"));
    }

    #[test]
    fn test_eval_index_assign_nested() {
        let mut interp = make_interpreter();

        // matrix = [[1, 2], [3, 4]]
        interp.set_variable(
            "matrix",
            Value::Array(Arc::from(vec![
                Value::Array(Arc::from(vec![Value::Integer(1), Value::Integer(2)])),
                Value::Array(Arc::from(vec![Value::Integer(3), Value::Integer(4)])),
            ])),
        );

        // matrix[0][1] = 99
        let nested_obj = make_expr(ExprKind::Identifier("matrix".to_string()));
        let outer_idx = make_expr(ExprKind::Literal(Literal::Integer(0, None)));
        let object = make_expr(ExprKind::IndexAccess {
            object: Box::new(nested_obj),
            index: Box::new(outer_idx),
        });
        let inner_idx = make_expr(ExprKind::Literal(Literal::Integer(1, None)));

        let result = interp
            .eval_index_assign(&object, &inner_idx, Value::Integer(99))
            .unwrap();
        assert_eq!(result, Value::Integer(99));

        let updated = interp.lookup_variable("matrix").unwrap();
        if let Value::Array(outer) = updated {
            if let Value::Array(inner) = &outer[0] {
                assert_eq!(inner[1], Value::Integer(99));
            } else {
                panic!("Expected inner array");
            }
        } else {
            panic!("Expected Array");
        }
    }

    // =========================================================================
    // Compound assignment tests
    // =========================================================================

    #[test]
    fn test_eval_compound_assign_add() {
        let mut interp = make_interpreter();
        interp.set_variable("x", Value::Integer(10));

        // x += 5
        let target = make_expr(ExprKind::Identifier("x".to_string()));
        let value = make_expr(ExprKind::Literal(Literal::Integer(5, None)));

        let result = interp
            .eval_compound_assign(&target, AstBinaryOp::Add, &value)
            .unwrap();
        assert_eq!(result, Value::Integer(15));
        assert_eq!(interp.lookup_variable("x").unwrap(), Value::Integer(15));
    }

    #[test]
    fn test_eval_compound_assign_sub() {
        let mut interp = make_interpreter();
        interp.set_variable("x", Value::Integer(10));

        // x -= 3
        let target = make_expr(ExprKind::Identifier("x".to_string()));
        let value = make_expr(ExprKind::Literal(Literal::Integer(3, None)));

        let result = interp
            .eval_compound_assign(&target, AstBinaryOp::Subtract, &value)
            .unwrap();
        assert_eq!(result, Value::Integer(7));
    }

    #[test]
    fn test_eval_compound_assign_mul() {
        let mut interp = make_interpreter();
        interp.set_variable("x", Value::Integer(10));

        // x *= 2
        let target = make_expr(ExprKind::Identifier("x".to_string()));
        let value = make_expr(ExprKind::Literal(Literal::Integer(2, None)));

        let result = interp
            .eval_compound_assign(&target, AstBinaryOp::Multiply, &value)
            .unwrap();
        assert_eq!(result, Value::Integer(20));
    }

    #[test]
    fn test_eval_compound_assign_field() {
        let mut interp = make_interpreter();

        let mut obj = HashMap::new();
        obj.insert("count".to_string(), Value::Integer(5));
        interp.set_variable("counter", Value::Object(Arc::new(obj)));

        // counter.count += 1
        let target = make_expr(ExprKind::FieldAccess {
            object: Box::new(make_expr(ExprKind::Identifier("counter".to_string()))),
            field: "count".to_string(),
        });
        let value = make_expr(ExprKind::Literal(Literal::Integer(1, None)));

        let result = interp
            .eval_compound_assign(&target, AstBinaryOp::Add, &value)
            .unwrap();
        assert_eq!(result, Value::Integer(6));
    }

    #[test]
    fn test_eval_compound_assign_invalid_target() {
        let mut interp = make_interpreter();

        // 42 += 1 - invalid target
        let target = make_expr(ExprKind::Literal(Literal::Integer(42, None)));
        let value = make_expr(ExprKind::Literal(Literal::Integer(1, None)));

        let result = interp.eval_compound_assign(&target, AstBinaryOp::Add, &value);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Invalid compound assignment target"));
    }
}