swamp_script_eval/
lib.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
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
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
/*
 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/script
 * Licensed under the MIT License. See LICENSE in the project root for license information.
 */
use crate::err::ConversionError;
use crate::extra::{SparseValueId, SparseValueMap};
use crate::value::{to_rust_value, Value};
use err::ExecuteError;
use seq_map::SeqMap;
use std::fmt::Debug;
use std::{cell::RefCell, collections::HashMap, rc::Rc};
pub use swamp_script_semantic::ns::ResolvedModuleNamespace;
use swamp_script_semantic::prelude::*;
use swamp_script_semantic::{
    ResolvedForPattern, ResolvedFunction, ResolvedPatternElement, ResolvedStaticCall,
};
use tracing::{debug, error, info, trace, warn};
use value::format_value;

pub mod err;
mod extra;
mod idx_gen;
pub mod prelude;
pub mod value;

type RawFunctionFn<C> = dyn FnMut(&[Value], &mut C) -> Result<Value, ExecuteError>;

type FunctionFn<C> = Box<RawFunctionFn<C>>;

pub struct EvalExternalFunction<C> {
    pub name: String,
    pub func: FunctionFn<C>,
    pub id: ExternalFunctionId,
}

impl<C> Debug for EvalExternalFunction<C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "external_fn {} {}", self.id, self.name)
    }
}

pub type EvalExternalFunctionRef<C> = Rc<RefCell<EvalExternalFunction<C>>>;

#[derive(Debug)]
pub enum ValueWithSignal {
    Value(Value),
    Return(Value),
    Break,    // Value is not defined
    Continue, // No value, it is a signal
}

impl From<String> for ExecuteError {
    fn from(err: String) -> Self {
        Self::Error(err)
    }
}

impl From<ConversionError> for ExecuteError {
    fn from(err: ConversionError) -> Self {
        Self::ConversionError(err)
    }
}

#[derive(Debug, Clone)]
struct BlockScope {
    variables: Vec<Value>,
}

#[derive(Default)]
struct FunctionScope {
    saved_block_scope: Vec<BlockScope>,
}

fn create_fixed_vec(capacity: usize) -> Vec<Value> {
    let mut items = Vec::with_capacity(capacity);
    items.extend((0..capacity).map(|_| Value::Unit));
    items
}
impl Default for BlockScope {
    fn default() -> Self {
        Self {
            variables: create_fixed_vec(64),
        }
    }
}

#[derive(Default)]
pub struct ExternalFunctions<C> {
    external_functions: HashMap<String, EvalExternalFunctionRef<C>>,
    external_functions_by_id: HashMap<ExternalFunctionId, EvalExternalFunctionRef<C>>,
}

impl<C> ExternalFunctions<C> {
    pub fn new() -> Self {
        Self {
            external_functions: HashMap::new(),
            external_functions_by_id: HashMap::new(),
        }
    }

    pub fn register_external_function(
        &mut self,
        name: &str,
        function_id: ExternalFunctionId,
        handler: impl FnMut(&[Value], &mut C) -> Result<Value, ExecuteError> + 'static,
    ) -> Result<(), String> {
        let external_func = EvalExternalFunction {
            name: name.to_string().clone(),
            func: Box::new(handler),
            id: function_id,
        };

        let external_func_ref = Rc::new(RefCell::new(external_func));

        self.external_functions_by_id
            .insert(function_id, external_func_ref.clone());
        self.external_functions
            .insert(name.to_string(), external_func_ref);

        Ok(())
    }
}

pub fn eval_module<C>(
    externals: &ExternalFunctions<C>,
    module: &ResolvedModule,
    context: &mut C,
) -> Result<Value, ExecuteError> {
    let mut interpreter = Interpreter::<C>::new(externals, context);
    let signal = interpreter.execute_statements(&module.statements)?;
    Ok(signal.try_into()?)
}

pub fn util_execute_function<C>(
    //&mut self,
    externals: &ExternalFunctions<C>,
    func: &ResolvedInternalFunctionDefinitionRef,
    arguments: &[Value],
    context: &mut C,
) -> Result<Value, ExecuteError> {
    let mut interpreter = Interpreter::<C>::new(externals, context);
    interpreter.bind_parameters(&func.signature.parameters, arguments)?;
    let with_signal = interpreter.execute_statements(&func.statements)?;
    interpreter.current_block_scopes.clear();
    interpreter.function_scope_stack.clear();
    Ok(Value::try_from(with_signal)?)
}

pub struct Interpreter<'a, C> {
    function_scope_stack: Vec<FunctionScope>,
    current_block_scopes: Vec<BlockScope>,
    externals: &'a ExternalFunctions<C>,
    context: &'a mut C,
}

impl<'a, C> Interpreter<'a, C> {
    pub fn new(externals: &'a ExternalFunctions<C>, context: &'a mut C) -> Self {
        Self {
            function_scope_stack: vec![FunctionScope::default()],
            current_block_scopes: vec![BlockScope::default()],
            externals,
            context,
        }
    }

    fn push_function_scope(&mut self, debug_str: &str) {
        debug!(debug_str=%debug_str, "push function scope");
        self.function_scope_stack.push(FunctionScope {
            saved_block_scope: self.current_block_scopes.clone(),
        });
        trace!(len=%self.current_block_scopes.len(), "saved block len");

        self.current_block_scopes.clear();
        self.push_block_scope("default function scope");
    }

    fn push_block_scope(&mut self, debug_str: &str) {
        debug!(debug_str = %debug_str, "push block scope");
        info!(
            "EVAL: pushing scope '{}', current depth: {}",
            debug_str,
            self.current_block_scopes.len()
        );
        self.current_block_scopes.push(BlockScope::default());
    }

    fn pop_block_scope(&mut self, debug_str: &str) {
        debug!(debug_str=%debug_str, "pop block scope");
        let old_len = self.current_block_scopes.len();
        info!(
            "EVAL: popping scope '{}', new depth: {}",
            debug_str,
            old_len - 1
        );
        self.current_block_scopes.pop();
    }

    fn pop_function_scope(&mut self, debug_str: &str) {
        debug!(debug_str=%debug_str, "pop function scope");
        if self.function_scope_stack.len() == 1 {
            error!("you popped too far");
            panic!("you popped too far");
        }
        let last_one = self.function_scope_stack.pop().expect("pop function scope");
        self.current_block_scopes = last_one.saved_block_scope;

        trace!(
            len = self.current_block_scopes.len(),
            "restored block scope"
        );
    }

    fn bind_parameters(
        &mut self,
        params: &[ResolvedParameter],
        args: &[Value],
    ) -> Result<(), ExecuteError> {
        for (index, (param, arg)) in params.iter().zip(args).enumerate() {
            let value = if param.is_mutable {
                match arg {
                    Value::Reference(r) => {
                        // For mutable parameters, use the SAME reference
                        Value::Reference(r.clone())
                    }
                    _ => return Err(ExecuteError::ArgumentIsNotMutable), //v => Value::Reference(Rc::new(RefCell::new(v))),
                }
            } else {
                match arg {
                    Value::Reference(r) => r.borrow().clone(),
                    v => v.clone(),
                }
            };

            self.set_local_var(index, value, param.is_mutable, &param.resolved_type)?;
        }

        Ok(())
    }

    fn evaluate_static_function_call(
        &mut self,
        static_call: &ResolvedStaticCall,
    ) -> Result<Value, ExecuteError> {
        // First evaluate the arguments
        let evaluated_args = self.evaluate_args(&static_call.arguments)?;

        match &*static_call.function {
            ResolvedFunction::Internal(function_data) => {
                self.push_function_scope("static function call");
                self.bind_parameters(&function_data.signature.parameters, &evaluated_args)?;
                let result = self.execute_statements(&function_data.statements)?;

                let v = match result {
                    ValueWithSignal::Value(v) => v,
                    ValueWithSignal::Return(v) => v,
                    ValueWithSignal::Break => Value::Unit,
                    ValueWithSignal::Continue => Value::Unit,
                };
                self.pop_function_scope("static function call");
                Ok(v)
            }
            ResolvedFunction::External(external) => {
                let mut func = self
                    .externals
                    .external_functions_by_id
                    .get(&external.id)
                    .expect("external function missing")
                    .borrow_mut();
                (func.func)(&evaluated_args, &mut self.context)
            }
        }
    }

    fn evaluate_external_function_call(
        &mut self,
        call: &ResolvedExternalFunctionCall,
    ) -> Result<Value, ExecuteError> {
        let evaluated_args = self.evaluate_args(&call.arguments)?;
        let mut func = self
            .externals
            .external_functions_by_id
            .get(&call.function_definition.id)
            .expect("external function missing")
            .borrow_mut();
        let v = (func.func)(&evaluated_args, &mut self.context)?;
        Ok(v)
    }

    fn evaluate_internal_function_call(
        &mut self,
        call: &ResolvedInternalFunctionCall,
    ) -> Result<Value, ExecuteError> {
        let func_val = self.evaluate_expression(&call.function_expression)?;
        match &func_val {
            Value::InternalFunction(internal_func_ref) => {
                info!("internal func: {internal_func_ref}")
            }
            _ => {
                return Err(ExecuteError::Error(
                    "internal error, can only execute internal function".to_owned(),
                ))
            }
        }

        let evaluated_args = self.evaluate_args(&call.arguments)?;
        debug!("call {:?}", func_val);

        self.push_function_scope(&format!("{func_val}"));

        // Bind parameters before executing body
        self.bind_parameters(
            &call.function_definition.signature.parameters,
            &evaluated_args,
        )?;

        debug!(args=?evaluated_args, name=%call.function_definition.name, "call function with arguments");

        let result = self.execute_statements(&call.function_definition.statements)?;

        self.pop_function_scope(&format!("{func_val}"));

        // Since signals can not propagate from the function call, we just return a normal Value
        let v = match result {
            ValueWithSignal::Value(v) => v,
            ValueWithSignal::Return(v) => v,
            ValueWithSignal::Break => Value::Unit,
            ValueWithSignal::Continue => Value::Unit,
        };

        debug!(value=%v, name=%call.function_definition.name, "function returned");

        Ok(v)
    }

    fn tabs(&self) -> String {
        "..".repeat(self.function_scope_stack.len() - 1)
    }

    fn evaluate_args(&mut self, args: &[ResolvedExpression]) -> Result<Vec<Value>, ExecuteError> {
        let mut evaluated = Vec::with_capacity(args.len());

        for arg in args {
            match arg {
                ResolvedExpression::MutRef(var_ref) => {
                    match self.lookup_var(
                        var_ref.variable_ref.scope_index,
                        var_ref.variable_ref.variable_index,
                    )? {
                        Value::Reference(r) => evaluated.push(Value::Reference(r.clone())),
                        _ => {
                            Err("Can only take mutable reference of mutable variable".to_string())?
                        }
                    }
                }
                expr => {
                    let value = self.evaluate_expression(expr)?;
                    evaluated.push(value);
                }
            }
        }

        Ok(evaluated)
    }

    fn evaluate_expressions(
        &mut self,
        exprs: &[ResolvedExpression],
    ) -> Result<Vec<Value>, ExecuteError> {
        let mut values = vec![];
        for expr in exprs {
            let value = self.evaluate_expression(expr)?;
            values.push(value);
        }

        Ok(values)
    }

    // Variables / Registers ----------------------------------------
    #[inline]
    fn overwrite_existing_var(
        &mut self,
        relative_scope_index: usize,
        variable_index: usize,
        new_value: Value,
    ) -> Result<(), ExecuteError> {
        trace!(
            "VAR: overwrite_existing_var {relative_scope_index}:{variable_index} = {new_value:?}"
        );
        let existing_var =
            &mut self.current_block_scopes[relative_scope_index].variables[variable_index];

        match existing_var {
            Value::Reference(r) => {
                *r.borrow_mut() = new_value.clone();
                Ok(())
            }
            _ => Err(format!("Cannot assign to immutable variable: {:?}", variable_index).into()),
        }
    }

    /// Initializes a variable for the first time
    #[inline]
    fn initialize_var(
        &mut self,
        relative_scope_index: usize,
        variable_index: usize,
        value: Value,
        is_mutable: bool,
    ) -> Result<(), ExecuteError> {
        debug!(value=%value, "VAR: set var mut:{is_mutable} {relative_scope_index}:{variable_index} = {value:?}");

        if is_mutable {
            // TODO: Check that we are not overwriting an existing used variables (debug)
            self.current_block_scopes[relative_scope_index].variables[variable_index] =
                Value::Reference(Rc::new(RefCell::new(value)));
        } else {
            // If it is immutable, just store normal values
            self.current_block_scopes[relative_scope_index].variables[variable_index] = value
        }

        Ok(())
    }

    fn lookup_variable(&self, variable: &ResolvedVariableRef) -> Result<&Value, ExecuteError> {
        self.lookup_var(variable.scope_index, variable.variable_index)
    }

    #[inline]
    fn lookup_var(
        &self,
        relative_scope_index: usize,
        variable_index: usize,
    ) -> Result<&Value, ExecuteError> {
        if relative_scope_index >= self.current_block_scopes.len() {
            panic!(
                "illegal scope index {relative_scope_index} of {}",
                self.current_block_scopes.len()
            );
        }

        let variables = &self.current_block_scopes[relative_scope_index].variables;
        if variable_index >= variables.len() {
            panic!("illegal index");
        }
        let existing_var = &variables[variable_index];

        trace!("VAR: lookup {relative_scope_index}:{variable_index} > {existing_var:?}");
        Ok(existing_var)
    }

    #[inline]
    fn lookup_mut_var(
        &self,
        relative_scope_index: usize,
        variable_index: usize,
    ) -> Result<&Rc<RefCell<Value>>, ExecuteError> {
        if relative_scope_index >= self.current_block_scopes.len() {
            panic!(
                "illegal scope index {relative_scope_index} of {}",
                self.current_block_scopes.len()
            );
        }

        let variables = &self.current_block_scopes[relative_scope_index].variables;
        if variable_index >= variables.len() {
            panic!("illegal index");
        }
        let existing_var = &variables[variable_index];

        Ok(match existing_var {
            Value::Reference(reference) => reference,
            _ => return Err(ExecuteError::VariableWasNotMutable),
        })
    }

    #[inline]
    fn lookup_mut_variable(
        &self,
        variable: &ResolvedVariableRef,
    ) -> Result<&Rc<RefCell<Value>>, ExecuteError> {
        self.lookup_mut_var(variable.scope_index, variable.variable_index)
    }

    fn assign_value(target_type: &ResolvedType, value: Value) -> Value {
        match value {
            Value::Struct(struct_ref, fields, _) => {
                // Use the target's display type instead of the value's type
                Value::Struct(struct_ref, fields, target_type.clone())
            }
            _ => value,
        }
    }

    #[inline]
    fn set_local_var(
        &mut self,
        variable_index: usize,
        value: Value,
        _is_mutable: bool,
        var_type: &ResolvedType,
    ) -> Result<(), ExecuteError> {
        let last_scope_index = self.current_block_scopes.len() - 1;
        let assigned = Self::assign_value(var_type, value);
        trace!("VAR: set_local_var {last_scope_index}:{variable_index} = {assigned:?}");

        self.current_block_scopes[last_scope_index].variables[variable_index] = assigned;
        Ok(())
    }

    // ---------------
    fn evaluate_expression(&mut self, expr: &ResolvedExpression) -> Result<Value, ExecuteError> {
        debug!(expr=%expr, "evaluate expression");
        let value = match expr {
            // Constructing
            ResolvedExpression::Literal(lit) => match lit {
                ResolvedLiteral::IntLiteral(n, _) => Value::Int(*n),
                ResolvedLiteral::FloatLiteral(f, _) => Value::Float(*f),
                ResolvedLiteral::StringLiteral(s, _) => Value::String(s.0.clone()),
                ResolvedLiteral::BoolLiteral(b, _) => Value::Bool(*b),
                ResolvedLiteral::EnumVariantLiteral(enum_variant_type, data) => {
                    let variant_container_value: Value = match &enum_variant_type.data {
                        ResolvedEnumVariantContainerType::Tuple(tuple_type) => match data {
                            ResolvedEnumLiteralData::Tuple(tuple_expressions) => {
                                let eval_expressions =
                                    self.evaluate_expressions(tuple_expressions)?;
                                Value::EnumVariantTuple(tuple_type.clone(), eval_expressions)
                            }
                            _ => return Err("wrong container type".to_string())?,
                        },

                        ResolvedEnumVariantContainerType::Struct(struct_type_ref) => match data {
                            ResolvedEnumLiteralData::Struct(resolved_field_values) => {
                                let mut values = Vec::with_capacity(resolved_field_values.len());
                                for resolved_expression in resolved_field_values {
                                    let value = self.evaluate_expression(resolved_expression)?;
                                    values.push(value);
                                }
                                Value::EnumVariantStruct(struct_type_ref.clone(), values)
                            }
                            _ => return Err("wrong container type".to_string())?,
                        },

                        ResolvedEnumVariantContainerType::Nothing => {
                            Value::EnumVariantSimple(enum_variant_type.clone())
                        }
                    };
                    variant_container_value
                }

                ResolvedLiteral::TupleLiteral(tuple_type, resolved_expressions) => {
                    let values = self.evaluate_expressions(resolved_expressions)?;
                    Value::Tuple(tuple_type.clone(), values)
                }

                ResolvedLiteral::UnitLiteral(_) => Value::Unit,
                ResolvedLiteral::Array(array_type, expressions) => {
                    let values = self.evaluate_expressions(expressions)?;
                    Value::Array(array_type.clone(), values)
                }
                ResolvedLiteral::Map(map_type_ref, expressions) => {
                    let mut items = SeqMap::new();
                    for (key, value) in expressions {
                        let key_val = self.evaluate_expression(key)?;
                        let value_val = self.evaluate_expression(value)?;
                        items
                            .insert(key_val, value_val)
                            .map_err(|_err| ExecuteError::NonUniqueKeysInMapLiteralDetected)?;
                    }
                    Value::Map(map_type_ref.clone(), items)
                }
                ResolvedLiteral::NoneLiteral => Value::Option(None),
            },

            ResolvedExpression::Array(array_instantiation) => {
                let mut values = Vec::new();
                for element in &array_instantiation.expressions {
                    values.push(self.evaluate_expression(element)?);
                }

                Value::Array(array_instantiation.array_type_ref.clone(), values)
            }

            ResolvedExpression::StructInstantiation(struct_instantiation) => {
                // Evaluate all field expressions and validate types
                let mut field_values = Vec::new();
                for field_expr in &struct_instantiation.expressions_in_order {
                    let value = self.evaluate_expression(field_expr)?;
                    field_values.push(value);
                }

                Value::Struct(
                    struct_instantiation.struct_type_ref.clone(),
                    field_values,
                    struct_instantiation.display_type_ref.clone(),
                )
            }

            ResolvedExpression::ExclusiveRange(_resolved_type_ref, start, end) => {
                let start_val = self.evaluate_expression(start)?;
                let end_val = self.evaluate_expression(end)?;
                match (start_val, end_val) {
                    (Value::Int(s), Value::Int(e)) => {
                        Value::ExclusiveRange(Box::new(s), Box::new(e))
                    }
                    _ => Err("Range bounds must be integers".to_string())?,
                }
            }

            // ==================== ASSIGNMENT ====================
            ResolvedExpression::InitializeVariable(var_assignment) => {
                let new_value = self.evaluate_expression(&var_assignment.expression)?;

                // Initialize all variables (single or multiple)
                for variable_ref in &var_assignment.variable_refs {
                    self.initialize_var(
                        variable_ref.scope_index,
                        variable_ref.variable_index,
                        new_value.clone(),
                        variable_ref.is_mutable(),
                    )?;
                }

                new_value
            }

            ResolvedExpression::ReassignVariable(var_assignment) => {
                let new_value = self.evaluate_expression(&var_assignment.expression)?;

                // Reassign all variables (single or multiple)
                for variable_ref in &var_assignment.variable_refs {
                    self.overwrite_existing_var(
                        variable_ref.scope_index,
                        variable_ref.variable_index,
                        new_value.clone(),
                    )?;
                }

                new_value
            }

            ResolvedExpression::VariableCompoundAssignment(var_assignment) => {
                let modifier_value = self.evaluate_expression(&var_assignment.expression)?;
                let current_value = self.lookup_mut_variable(&var_assignment.variable_ref)?;

                // Only int first
                let int_mod = modifier_value.expect_int()?;
                let current_int = current_value.borrow().expect_int()?;

                let new_result = match var_assignment.ast_operator {
                    CompoundOperator::Add => current_int + int_mod,
                    CompoundOperator::Sub => current_int - int_mod,
                    CompoundOperator::Mul => current_int * int_mod,
                    CompoundOperator::Div => current_int / int_mod,
                };

                let new_value = Value::Int(new_result);
                {
                    let mut mutated = current_value.borrow_mut();
                    *mutated = new_value.clone();
                }
                new_value
            }

            ResolvedExpression::ArrayExtend(variable_ref, source_expression) => {
                let source_val = self.evaluate_expression(source_expression)?;

                let array_val = self.lookup_variable(variable_ref)?;
                match array_val {
                    Value::Reference(r) => {
                        if let Value::Array(_type_id, ref mut vector) = &mut *r.borrow_mut() {
                            if let Value::Array(_, items) = source_val {
                                vector.extend(items);
                            } else {
                                Err("Cannot extend non-array reference".to_string())?
                            }
                        } else {
                            Err("Cannot extend non-array reference".to_string())?
                        }
                    }
                    _ => Err(ExecuteError::NotAnArray)?,
                }
                array_val.clone()
            }

            ResolvedExpression::ArrayPush(variable_ref, source_expression) => {
                let source_val = self.evaluate_expression(source_expression)?;
                let array_val = self.lookup_variable(variable_ref)?;
                match &array_val {
                    Value::Reference(r) => {
                        if let Value::Array(_type_id, ref mut vector) = &mut *r.borrow_mut() {
                            vector.push(source_val);
                        } else {
                            Err("Cannot extend non-array reference".to_string())?
                        }
                    }
                    _ => Err(ExecuteError::NotAnArray)?,
                }
                array_val.clone()
            }

            ResolvedExpression::ArrayRemoveIndex(variable_ref, usize_index_expression) => {
                let index_val = self.evaluate_expression(usize_index_expression)?;
                let index = match index_val {
                    Value::Int(x) => x,
                    _ => return Err(ExecuteError::ArgumentIsNotMutable),
                };
                let array_val = self.lookup_variable(variable_ref)?;

                match &array_val {
                    Value::Reference(r) => {
                        if let Value::Array(_type_id, ref mut vector) = &mut *r.borrow_mut() {
                            vector.remove(index as usize);
                        } else {
                            Err("Cannot extend non-array reference".to_string())?
                        }
                    }
                    _ => Err(ExecuteError::NotAnArray)?,
                }
                array_val.clone()
            }

            ResolvedExpression::ArrayClear(variable_ref) => {
                let array_val = self.lookup_variable(variable_ref)?;
                match &array_val {
                    Value::Reference(r) => {
                        if let Value::Array(_type_id, ref mut vector) = &mut *r.borrow_mut() {
                            vector.clear();
                        } else {
                            Err("Cannot extend non-array reference".to_string())?
                        }
                    }
                    _ => Err(ExecuteError::NotAnArray)?,
                }
                array_val.clone()
            }

            ResolvedExpression::ArrayAssignment(array, index, value) => {
                let array_val = self.evaluate_expression(&array.expression)?;
                let index_val = self.evaluate_expression(&index.expression)?;
                let new_val = self.evaluate_expression(value)?;

                match (array_val, index_val) {
                    (Value::Reference(r), Value::Int(i)) => {
                        if let Value::Array(_type_id, ref mut elements) = &mut *r.borrow_mut() {
                            if i < 0 || i >= elements.len() as i32 {
                                return Err(format!("Array index out of bounds: {}", i))?;
                            }
                            elements[i as usize] = new_val.clone();
                        } else {
                            Err("Cannot index into non-array reference".to_string())?
                        }
                    }
                    (arr, idx) => Err(format!(
                        "Invalid array assignment: cannot index {:?} with {:?}",
                        arr, idx
                    ))?,
                }

                new_val
            }

            ResolvedExpression::MapAssignment(array, index, value) => {
                let map_val = self.evaluate_expression(&array.expression)?;
                let index_val = self.evaluate_expression(&index.expression)?;
                let new_val = self.evaluate_expression(value)?;

                match map_val {
                    Value::Reference(r) => {
                        if let Value::Map(_type_id, ref mut elements) = &mut *r.borrow_mut() {
                            elements
                                .insert(index_val, new_val.clone())
                                .expect("todo: improve error handling");
                        } else {
                            Err("Cannot index into non-array reference".to_string())?
                        }
                    }
                    _ => Err(format!("Invalid map assignment: must be mutable"))?,
                }

                new_val
            }

            ResolvedExpression::StructFieldAssignment(
                resolved_struct_field_ref,
                source_expression,
            ) => {
                let target_struct_value =
                    self.evaluate_expression(&resolved_struct_field_ref.inner.struct_expression)?;
                let value = self.evaluate_expression(source_expression)?;

                match target_struct_value {
                    Value::Reference(r) => {
                        let mut borrowed = r.borrow_mut();
                        // We know it must be a struct because references can only point to structs
                        match &mut *borrowed {
                            Value::Struct(struct_type, fields, _) => {
                                if let Some(field) =
                                    fields.get_mut(resolved_struct_field_ref.inner.index)
                                {
                                    let struct_ref = struct_type.borrow();
                                    let field_type = struct_ref
                                        .fields
                                        .values()
                                        .nth(resolved_struct_field_ref.inner.index)
                                        .ok_or_else(|| "Field index out of bounds".to_string())?
                                        .clone(); // Clone the type to extend its lifetime

                                    let assign = Self::assign_value(&field_type, value);
                                    *field = assign.clone();
                                    assign
                                } else {
                                    Err(format!(
                                        "Field '{}' not found in struct '{:?}'",
                                        resolved_struct_field_ref.inner.index, struct_type
                                    ))?
                                }
                            }
                            _ => {
                                Err("Internal error: reference contains non-struct value"
                                    .to_string())?
                            }
                        }
                    }
                    Value::Struct(_, _, _) => {
                        Err("Cannot assign to field of non-mutable struct".to_string())?
                    }
                    _ => Err(format!(
                        "Cannot access field assignment '{}' on non-struct value",
                        resolved_struct_field_ref.inner.index
                    ))?,
                }
            }

            ResolvedExpression::FieldCompoundAssignment(_) => todo!(),

            // ------------- LOOKUP ---------------------
            ResolvedExpression::VariableAccess(var) => {
                let value = self.lookup_var(var.scope_index, var.variable_index)?;
                value.clone()
            }

            ResolvedExpression::ArrayAccess(array_item_ref) => {
                let array_val = self.evaluate_expression(&array_item_ref.array_expression)?;
                let index_val = self.evaluate_expression(&array_item_ref.int_expression)?;

                match (array_val, index_val) {
                    (Value::Array(_type_id, elements), Value::Int(i)) => {
                        if i < 0 || i >= elements.len() as i32 {
                            return Err(format!("Array index out of bounds: {}", i))?;
                        }
                        elements[i as usize].clone()
                    }
                    (Value::Reference(r), Value::Int(i)) => {
                        if let Value::Array(_type_id, elements) = &*r.borrow() {
                            if i < 0 || i >= elements.len() as i32 {
                                return Err(format!("Array index out of bounds: {}", i))?;
                            }
                            elements[i as usize].clone()
                        } else {
                            Err("Cannot index into non-array reference".to_string())?
                        }
                    }
                    (arr, idx) => Err(format!(
                        "Invalid array access: cannot index {:?} with {:?}",
                        arr, idx
                    ))?,
                }
            }

            ResolvedExpression::MapIndexAccess(ref map_lookup) => {
                let map_val = self.evaluate_expression(&map_lookup.map_expression)?;
                let index_val = self.evaluate_expression(&map_lookup.index_expression)?;

                match (map_val, index_val) {
                    (Value::Map(_type_id, elements), v) => {
                        let x = elements.get(&v);
                        match x {
                            None => Value::Option(None),
                            Some(v) => Value::Option(Some(Box::from(v.clone()))),
                        }
                    }
                    (Value::Reference(r), v) => {
                        if let Value::Map(_type_id, elements) = &*r.borrow() {
                            let x = elements.get(&v);
                            match x {
                                None => Value::Option(None),
                                Some(v) => Value::Option(Some(Box::from(v.clone()))),
                            }
                        } else {
                            Err("Cannot index into non-map reference".to_string())?
                        }
                    }
                    (arr, idx) => Err(format!(
                        "Invalid map access: cannot index {:?} with {:?}",
                        arr, idx
                    ))?,
                }
            }

            ResolvedExpression::FieldAccess(struct_field_access) => {
                let struct_expression =
                    self.evaluate_expression(&struct_field_access.struct_expression)?;

                match struct_expression {
                    Value::Struct(_struct_type, fields, _) => {
                        fields[struct_field_access.index].clone()
                    }
                    Value::Reference(r) => {
                        // If it's a reference, dereference and try field access
                        let value = r.borrow();
                        match &*value {
                            Value::Struct(_struct_type, fields, _) => {
                                fields[struct_field_access.index].clone()
                            }
                            _ => Err(format!(
                                "Cannot access field reference '{}' on non-struct value",
                                struct_field_access.index
                            ))?,
                        }
                    }
                    _ => Err(format!(
                        "Cannot access field '{}' on non-struct value",
                        struct_field_access.index
                    ))?,
                }
            }

            ResolvedExpression::MutRef(var_ref) => {
                let value = self.lookup_var(
                    var_ref.variable_ref.scope_index,
                    var_ref.variable_ref.variable_index,
                )?;

                match value {
                    Value::Reference(r) => Value::Reference(r.clone()),
                    _ => Err("Can only take mutable reference of mutable variable".to_string())?,
                }
            }

            // Operators
            ResolvedExpression::BinaryOp(binary_operator) => {
                let left_val = self.evaluate_expression(&binary_operator.left)?;
                let right_val = self.evaluate_expression(&binary_operator.right)?;
                self.evaluate_binary_op(left_val, &binary_operator.ast_operator_type, right_val)?
            }

            ResolvedExpression::UnaryOp(unary_operator) => {
                let left_val = self.evaluate_expression(&unary_operator.left)?;
                self.evaluate_unary_op(&unary_operator.ast_operator_type, left_val)?
            }

            ResolvedExpression::PostfixOp(postfix_operator) => {
                let left_val = self.evaluate_expression(&postfix_operator.left)?;
                self.evaluate_postfix_op(&postfix_operator.ast_operator_type, left_val)?
            }

            // Calling
            ResolvedExpression::FunctionInternalCall(resolved_internal_call) => {
                self.evaluate_internal_function_call(resolved_internal_call)?
            }

            ResolvedExpression::FunctionExternalCall(resolved_external_call) => {
                self.evaluate_external_function_call(resolved_external_call)?
            }

            ResolvedExpression::StaticCall(static_call) => {
                self.evaluate_static_function_call(static_call)?
            }

            ResolvedExpression::StaticCallGeneric(static_call_generic) => {
                let evaluated_args = self.evaluate_args(&static_call_generic.arguments)?;
                match &*static_call_generic.function {
                    ResolvedFunction::Internal(function_data) => {
                        self.push_function_scope("static generic function call");
                        self.bind_parameters(&function_data.signature.parameters, &evaluated_args)?;
                        let result = self.execute_statements(&function_data.statements)?;
                        self.pop_function_scope("static generic function call");
                        match result {
                            ValueWithSignal::Value(v) | ValueWithSignal::Return(v) => Ok(v),
                            _ => Ok(Value::Unit),
                        }
                    }
                    ResolvedFunction::External(external) => {
                        let mut func = self
                            .externals
                            .external_functions_by_id
                            .get(&external.id)
                            .expect("external function missing")
                            .borrow_mut();
                        (func.func)(&evaluated_args, &mut self.context)
                    }
                }?
            }

            ResolvedExpression::MemberCall(resolved_member_call) => {
                let member_value =
                    self.evaluate_expression(&resolved_member_call.self_expression)?;

                trace!("{} > member call {:?}", self.tabs(), member_value);

                let parameters = match &*resolved_member_call.function {
                    ResolvedFunction::Internal(function_data) => {
                        &function_data.signature.parameters
                    }
                    ResolvedFunction::External(external_data) => {
                        &external_data.signature.parameters
                    }
                };

                let mut member_call_arguments = Vec::new();
                member_call_arguments.push(member_value.clone()); // Add self as first argument
                for arg in &resolved_member_call.arguments {
                    member_call_arguments.push(self.evaluate_expression(arg)?);
                }

                // Check total number of parameters (including self)
                if member_call_arguments.len() != parameters.len() {
                    return Err(ExecuteError::Error(format!(
                        "wrong number of arguments: expected {}, got {}",
                        parameters.len(),
                        member_call_arguments.len()
                    )));
                }

                match &*resolved_member_call.function {
                    ResolvedFunction::Internal(internal_function) => {
                        self.push_function_scope(&format!("member_call {member_value}"));
                        self.bind_parameters(parameters, &member_call_arguments)?;
                        let result = self.execute_statements(&internal_function.statements)?;
                        self.pop_function_scope(&format!("member_call {resolved_member_call}"));

                        match result {
                            ValueWithSignal::Value(v) => v,
                            ValueWithSignal::Return(v) => v,
                            ValueWithSignal::Break => {
                                Err("break not allowed in member calls".to_string())?
                            }
                            ValueWithSignal::Continue => {
                                Err("continue not allowed in member calls".to_string())?
                            }
                        }
                    }
                    ResolvedFunction::External(external_func) => {
                        let mut func = self
                            .externals
                            .external_functions_by_id
                            .get(&external_func.id)
                            .expect("external function missing")
                            .borrow_mut();
                        (func.func)(&member_call_arguments, &mut self.context)?
                    }
                }
            }

            ResolvedExpression::Block(statements) => {
                self.push_block_scope("block statements");
                let result = self.execute_statements(statements)?;
                self.pop_block_scope("block_statements");
                match result {
                    ValueWithSignal::Value(v) => v,
                    ValueWithSignal::Return(_) => {
                        Err("return is not allowed in expressions".to_string())?
                    }
                    ValueWithSignal::Break => {
                        Err("break is not allowed in expressions".to_string())?
                    }
                    ValueWithSignal::Continue => {
                        Err("continue is not allowed in expressions".to_string())?
                    }
                }
            }

            ResolvedExpression::InterpolatedString(_string_type_ref, parts) => {
                let mut result = String::new();

                for part in parts {
                    match part {
                        ResolvedStringPart::Literal(text) => {
                            result.push_str(text);
                        }
                        ResolvedStringPart::Interpolation(expr, format_spec) => {
                            let value = self.evaluate_expression(expr)?;
                            let formatted = match format_spec {
                                Some(spec) => format_value(&value, spec)?,
                                None => value.to_string(),
                            };
                            result.push_str(&formatted);
                        }
                    }
                }

                Value::String(result)
            }

            // Comparing
            ResolvedExpression::IfElse(condition, then_expr, else_expr) => {
                self.push_block_scope("if_else");
                let cond_value = self.evaluate_expression(&condition.expression)?;
                let result = if cond_value.is_truthy()? {
                    self.evaluate_expression(then_expr)?
                } else {
                    self.evaluate_expression(else_expr)?
                };

                self.pop_block_scope("if_else");
                result
            }

            ResolvedExpression::IfElseOnlyVariable {
                variable,
                optional_expr,
                true_block,
                false_block,
            } => {
                let value = self.evaluate_expression(optional_expr)?;
                match value {
                    Value::Option(Some(inner_value)) => {
                        self.push_block_scope("if else only variable");
                        self.initialize_var(
                            variable.scope_index,
                            variable.variable_index,
                            *inner_value,
                            variable.is_mutable(),
                        )?;
                        let result = self.evaluate_expression(true_block)?;
                        self.pop_block_scope("if else only variable");
                        result
                    }
                    Value::Option(None) => self.evaluate_expression(false_block)?,
                    _ => return Err(ExecuteError::ExpectedOptional),
                }
            }

            ResolvedExpression::IfElseAssignExpression {
                variable,
                optional_expr,
                true_block,
                false_block,
            } => {
                let value = self.evaluate_expression(optional_expr)?;
                match value {
                    Value::Option(Some(inner_value)) => {
                        self.push_block_scope("if else assign expression");
                        self.initialize_var(
                            variable.scope_index,
                            variable.variable_index,
                            *inner_value,
                            variable.is_mutable(),
                        )?;
                        let result = self.evaluate_expression(true_block)?;
                        self.pop_block_scope("if else assign expression");
                        result
                    }
                    Value::Option(None) => self.evaluate_expression(false_block)?,
                    _ => return Err(ExecuteError::ExpectedOptional),
                }
            }

            ResolvedExpression::Match(resolved_match) => self.eval_match(resolved_match)?,
            ResolvedExpression::InternalFunctionAccess(fetch_function) => {
                Value::InternalFunction(fetch_function.clone())
            }
            ResolvedExpression::ExternalFunctionAccess(fetch_function) => {
                let external_ref = self
                    .externals
                    .external_functions_by_id
                    .get(&fetch_function.id)
                    .expect("should have external function ref");
                Value::ExternalFunction(external_ref.borrow().id)
            }
            ResolvedExpression::MutMemberCall(_, _) => todo!(),
            ResolvedExpression::Tuple(_) => todo!(),
            ResolvedExpression::LetVar(_, _) => todo!(),
            ResolvedExpression::Option(inner) => match inner {
                None => Value::Option(None),
                Some(expression) => {
                    let v = self.evaluate_expression(expression)?;
                    match v {
                        Value::Option(_) => {
                            warn!("unnecessary wrap!, should be investigated"); // TODO: Is there a case where this is ok?
                            v
                        }
                        _ => Value::Option(Some(Box::from(v))),
                    }
                }
            },

            // --------------- SPECIAL FUNCTIONS
            ResolvedExpression::SparseNew(rust_type_ref, generic_type) => {
                let sparse_value_map = SparseValueMap::new(generic_type.clone());
                to_rust_value(rust_type_ref.clone(), sparse_value_map)
            }

            ResolvedExpression::SparseAdd(sparse_rust, value_expression) => {
                let resolved_sparse_value = self.evaluate_expression(sparse_rust)?;

                let sparse_value_map = resolved_sparse_value.downcast_rust_mut::<SparseValueMap>();
                if let Some(found) = sparse_value_map {
                    let resolved_value = self.evaluate_expression(value_expression)?;
                    let id_value = found.borrow_mut().add(resolved_value);

                    id_value
                } else {
                    return Err(ExecuteError::NotSparseValue);
                }
            }
            ResolvedExpression::SparseRemove(sparse_rust, id_expression) => {
                let resolved_sparse_value = self.evaluate_expression(sparse_rust)?;
                let sparse_value_map = resolved_sparse_value.downcast_rust_mut::<SparseValueMap>();
                if let Some(found) = sparse_value_map {
                    let id_value = self.evaluate_expression(id_expression)?;
                    if let Some(found_id) = id_value.downcast_rust::<SparseValueId>() {
                        found.borrow_mut().remove(&**found_id.borrow());
                    } else {
                        return Err(ExecuteError::Error(
                            "was not a sparse slot. can not remove".to_string(),
                        ));
                    }
                }

                resolved_sparse_value
            }
            ResolvedExpression::CoerceOptionToBool(expression) => {
                let value = self.evaluate_expression(expression)?;
                match value {
                    Value::Option(inner) => Value::Bool(inner.is_some()),
                    _ => return Err(ExecuteError::CoerceOptionToBoolFailed),
                }
            }
        };

        Ok(value)
    }

    #[inline]
    pub fn execute_statements(
        &mut self,
        statements: &Vec<ResolvedStatement>,
    ) -> Result<ValueWithSignal, ExecuteError> {
        let mut return_value = Value::Unit;

        for statement in statements {
            trace!("{} exec {statement:?}", self.tabs());

            // First handle signal aware statements
            match statement {
                ResolvedStatement::Continue => {
                    return Ok(ValueWithSignal::Continue);
                }
                ResolvedStatement::Break => return Ok(ValueWithSignal::Break),
                ResolvedStatement::Return(expr) => {
                    return Ok(ValueWithSignal::Return(self.evaluate_expression(expr)?));
                }

                ResolvedStatement::WhileLoop(condition, body) => {
                    while self
                        .evaluate_expression(&condition.expression)?
                        .is_truthy()?
                    {
                        match self.execute_statements(body) {
                            Err(e) => return Err(e),
                            Ok(signal) => match signal {
                                ValueWithSignal::Value(_v) => {} // Just discard normal values
                                ValueWithSignal::Break => {
                                    break;
                                }
                                ValueWithSignal::Return(v) => {
                                    return Ok(ValueWithSignal::Return(v))
                                }
                                ValueWithSignal::Continue => {}
                            },
                        }
                    }
                    continue;
                }

                ResolvedStatement::If(condition, consequences, optional_alternative) => {
                    let cond_value = self.evaluate_expression(&condition.expression)?;
                    if cond_value.is_truthy()? {
                        match self.execute_statements(consequences)? {
                            ValueWithSignal::Value(v) => return_value = v, // Store the value
                            ValueWithSignal::Break => return Ok(ValueWithSignal::Break),
                            ValueWithSignal::Return(v) => return Ok(ValueWithSignal::Return(v)),
                            ValueWithSignal::Continue => return Ok(ValueWithSignal::Continue),
                        }
                    } else {
                        if let Some(alternative) = optional_alternative {
                            match self.execute_statements(alternative)? {
                                ValueWithSignal::Value(v) => return_value = v, // Store the value
                                ValueWithSignal::Break => return Ok(ValueWithSignal::Break),
                                ValueWithSignal::Return(v) => {
                                    return Ok(ValueWithSignal::Return(v))
                                }
                                ValueWithSignal::Continue => return Ok(ValueWithSignal::Continue),
                            }
                        }
                    }
                    continue;
                }

                ResolvedStatement::IfOnlyVariable {
                    variable,
                    optional_expr,
                    true_block,
                    false_block,
                } => {
                    let condition_value = self.evaluate_expression(optional_expr)?;
                    match condition_value {
                        Value::Option(Some(inner_value)) => {
                            self.push_block_scope("if only variable");
                            info!(value=%inner_value.clone(), "shadow variable");
                            self.initialize_var(
                                variable.scope_index,
                                variable.variable_index,
                                *inner_value,
                                variable.is_mutable(),
                            )?;

                            let result = self.execute_statements(&true_block)?;

                            self.pop_block_scope("if only variable");

                            match result {
                                ValueWithSignal::Value(v) => return_value = v,
                                signal => return Ok(signal),
                            }
                        }
                        Value::Option(None) => {
                            if let Some(else_block) = false_block {
                                match self.execute_statements(&else_block)? {
                                    ValueWithSignal::Value(_v) => return_value = condition_value,
                                    signal => return Ok(signal),
                                }
                            }
                        }
                        _ => return Err(ExecuteError::ExpectedOptional),
                    }
                    continue;
                }

                ResolvedStatement::Expression(expr) => {
                    let result = self.evaluate_expression(expr);
                    if result.is_err() {
                        return Err(result.unwrap_err());
                    }
                    return_value = result?
                }

                ResolvedStatement::IfAssignExpression {
                    variable,
                    optional_expr,
                    true_block,
                    false_block,
                } => {
                    let value = self.evaluate_expression(optional_expr)?;
                    match value {
                        Value::Option(Some(inner_value)) => {
                            self.push_block_scope("if assign expression");
                            self.initialize_var(
                                variable.scope_index,
                                variable.variable_index,
                                *inner_value,
                                variable.is_mutable(),
                            )?;

                            let result = self.execute_statements(&true_block)?;
                            self.pop_block_scope("if assign expression");

                            match result {
                                ValueWithSignal::Value(v) => return_value = v,
                                signal => return Ok(signal),
                            }
                        }
                        Value::Option(None) => {
                            if let Some(else_block) = false_block {
                                match self.execute_statements(&else_block)? {
                                    ValueWithSignal::Value(v) => return_value = v,
                                    signal => return Ok(signal),
                                }
                            }
                        }
                        _ => return Err(ExecuteError::ExpectedOptional),
                    }
                    continue;
                }

                ResolvedStatement::ForLoop(pattern, iterator_expr, body) => {
                    let iterator_value =
                        self.evaluate_expression(&iterator_expr.resolved_expression)?;

                    match pattern {
                        ResolvedForPattern::Single(var_ref) => {
                            self.push_block_scope(&format!("for_loop single {:?}", var_ref));

                            for value in iterator_value.into_iter()? {
                                self.initialize_var(
                                    var_ref.scope_index,
                                    var_ref.variable_index,
                                    value,
                                    false,
                                )?;

                                match self.execute_statements(body)? {
                                    ValueWithSignal::Value(_) => {}
                                    ValueWithSignal::Return(v) => {
                                        return Ok(ValueWithSignal::Return(v))
                                    }
                                    ValueWithSignal::Break => break,
                                    ValueWithSignal::Continue => continue,
                                }
                            }

                            self.pop_block_scope("for loop single");
                        }

                        ResolvedForPattern::Pair(first_ref, second_ref) => {
                            self.push_block_scope("for_loop pair");

                            for (key, value) in iterator_value.into_iter_pairs()? {
                                // Set both variables
                                self.initialize_var(
                                    first_ref.scope_index,
                                    first_ref.variable_index,
                                    key,
                                    false,
                                )?;
                                self.initialize_var(
                                    second_ref.scope_index,
                                    second_ref.variable_index,
                                    value,
                                    false,
                                )?;

                                match self.execute_statements(body)? {
                                    ValueWithSignal::Value(_) => {}
                                    ValueWithSignal::Return(v) => {
                                        return Ok(ValueWithSignal::Return(v))
                                    }
                                    ValueWithSignal::Break => break,
                                    ValueWithSignal::Continue => continue,
                                }
                            }

                            self.pop_block_scope("for loop pair");
                        }
                    }

                    continue;
                }

                ResolvedStatement::Block(body) => {
                    match self.execute_statements(body)? {
                        ValueWithSignal::Value(_v) => {} // ignore normal values
                        ValueWithSignal::Return(v) => return Ok(ValueWithSignal::Return(v)), //  Value::Void?
                        ValueWithSignal::Break => return Ok(ValueWithSignal::Break),
                        ValueWithSignal::Continue => return Ok(ValueWithSignal::Continue),
                    }
                }
            }
        }

        Ok(ValueWithSignal::Value(return_value))
    }

    #[inline(always)]
    fn eval_match(&mut self, resolved_match: &ResolvedMatch) -> Result<Value, ExecuteError> {
        let cond_value = self.evaluate_expression(&resolved_match.expression)?;
        // Dereference if we got a reference
        let actual_value = match &cond_value {
            Value::Reference(r) => r.borrow().clone(),
            _ => cond_value.clone(),
        };

        for arm in &resolved_match.arms {
            match &arm.pattern {
                ResolvedPattern::PatternList(elements) => {
                    // Handle single variable/wildcard patterns that match any value
                    if elements.len() == 1 {
                        match &elements[0] {
                            ResolvedPatternElement::Variable(var_ref)
                            | ResolvedPatternElement::VariableWithFieldIndex(var_ref, _) => {
                                self.push_block_scope("pattern variable");
                                self.set_local_var(
                                    var_ref.variable_index,
                                    actual_value.clone(),
                                    false,
                                    &var_ref.resolved_type,
                                )?;
                                let result = self.evaluate_expression(&arm.expression);
                                self.pop_block_scope("pattern variable");
                                return result;
                            }
                            ResolvedPatternElement::Wildcard => {
                                // Wildcard matches anything
                                return self.evaluate_expression(&arm.expression);
                            }
                        }
                    }

                    match &actual_value {
                        Value::Tuple(_tuple_type_ref, values) => {
                            if elements.len() == values.len() {
                                self.push_block_scope("pattern list");

                                for (element, value) in elements.iter().zip(values.iter()) {
                                    match element {
                                        ResolvedPatternElement::Variable(var_ref) => {
                                            self.set_local_var(
                                                var_ref.variable_index,
                                                value.clone(),
                                                false,
                                                &var_ref.resolved_type,
                                            )?;
                                        }
                                        ResolvedPatternElement::VariableWithFieldIndex(
                                            var_ref,
                                            _,
                                        ) => {
                                            self.set_local_var(
                                                var_ref.variable_index,
                                                value.clone(),
                                                false,
                                                &var_ref.resolved_type,
                                            )?;
                                        }
                                        ResolvedPatternElement::Wildcard => {
                                            // Skip wildcards
                                            continue;
                                        }
                                    }
                                }

                                let result = self.evaluate_expression(&arm.expression);
                                self.pop_block_scope("pattern list");
                                return result;
                            }
                        }
                        _ => continue,
                    }
                }

                ResolvedPattern::EnumPattern(variant_ref, maybe_elements) => {
                    let value_to_match = match &actual_value {
                        Value::Reference(value_ref) => value_ref.borrow().clone(),
                        _ => actual_value.clone(),
                    };

                    match &value_to_match {
                        Value::EnumVariantTuple(value_tuple_type, values) => {
                            // First check if the variant types match
                            if variant_ref.number != value_tuple_type.common.number {
                                continue; // Try next pattern
                            }

                            if let Some(elements) = maybe_elements {
                                if elements.len() == values.len() {
                                    self.push_block_scope("enum tuple pattern");

                                    for (element, value) in elements.iter().zip(values.iter()) {
                                        match element {
                                            ResolvedPatternElement::Variable(var_ref) => {
                                                self.set_local_var(
                                                    var_ref.variable_index,
                                                    value.clone(),
                                                    false,
                                                    &var_ref.resolved_type,
                                                )?;
                                            }
                                            ResolvedPatternElement::VariableWithFieldIndex(
                                                var_ref,
                                                _,
                                            ) => {
                                                self.set_local_var(
                                                    var_ref.variable_index,
                                                    value.clone(),
                                                    false,
                                                    &var_ref.resolved_type,
                                                )?;
                                            }
                                            ResolvedPatternElement::Wildcard => continue,
                                        }
                                    }

                                    let result = self.evaluate_expression(&arm.expression);
                                    self.pop_block_scope("enum tuple pattern");
                                    return result;
                                }
                            }
                        }
                        Value::EnumVariantStruct(value_struct_type, values) => {
                            if value_struct_type.common.number == variant_ref.number {
                                if let Some(elements) = maybe_elements {
                                    self.push_block_scope("enum struct pattern");

                                    for element in elements {
                                        if let ResolvedPatternElement::VariableWithFieldIndex(
                                            var_ref,
                                            field_index,
                                        ) = element
                                        {
                                            let value = &values[*field_index];
                                            self.set_local_var(
                                                var_ref.variable_index,
                                                value.clone(),
                                                false,
                                                &var_ref.resolved_type,
                                            )?;
                                        }
                                    }

                                    let result = self.evaluate_expression(&arm.expression);
                                    self.pop_block_scope("enum struct pattern");
                                    return result;
                                }
                            }
                        }

                        Value::EnumVariantSimple(value_variant_ref) => {
                            if value_variant_ref.number == variant_ref.number
                                && maybe_elements.is_none()
                            {
                                return self.evaluate_expression(&arm.expression);
                            }
                        }
                        _ => continue,
                    }
                }

                ResolvedPattern::Literal(lit) => match (lit, &actual_value) {
                    (ResolvedLiteral::IntLiteral(a, _), Value::Int(b)) if a == b => {
                        return self.evaluate_expression(&arm.expression);
                    }
                    (ResolvedLiteral::FloatLiteral(a, _), Value::Float(b)) if a == b => {
                        return self.evaluate_expression(&arm.expression);
                    }
                    (ResolvedLiteral::StringLiteral(a, _), Value::String(b)) if a.0 == *b => {
                        return self.evaluate_expression(&arm.expression);
                    }
                    (ResolvedLiteral::BoolLiteral(a, _), Value::Bool(b)) if a == b => {
                        return self.evaluate_expression(&arm.expression);
                    }
                    (
                        ResolvedLiteral::TupleLiteral(_a_type_ref, a_values),
                        Value::Tuple(_b_type_ref, b_values),
                    ) if self.expressions_equal_to_values(a_values, b_values)? => {
                        return self.evaluate_expression(&arm.expression);
                    }
                    _ => continue,
                },
            }
        }

        Err(ExecuteError::Error(
            "must match one of the match arms!".to_string(),
        ))
    }

    fn evaluate_binary_op(
        &self,
        left: Value,
        op: &BinaryOperator,
        right: Value,
    ) -> Result<Value, ExecuteError> {
        // Get the actual values, but keep track if left was a reference
        let left_val = match left {
            Value::Reference(r) => r.borrow().clone(),
            v => v,
        };

        let right_val = match right {
            Value::Reference(r) => r.borrow().clone(),
            v => v,
        };

        trace!(
            "{} > binary op {left_val:?} {op:?} {right_val:?}",
            self.tabs()
        );

        let result: Value = match (left_val, op, right_val) {
            // Integer operations
            (Value::Int(a), BinaryOperator::Add, Value::Int(b)) => Value::Int(a + b),
            (Value::Int(a), BinaryOperator::Subtract, Value::Int(b)) => Value::Int(a - b),
            (Value::Int(a), BinaryOperator::Multiply, Value::Int(b)) => Value::Int(a * b),
            (Value::Int(a), BinaryOperator::Divide, Value::Int(b)) => {
                if b == 0 {
                    return Err("Division by zero".to_string())?;
                }
                Value::Int(a / b)
            }
            (Value::Int(a), BinaryOperator::Modulo, Value::Int(b)) => Value::Int(a % b),

            // Float operations
            (Value::Float(a), BinaryOperator::Add, Value::Float(b)) => Value::Float(a + b),
            (Value::Float(a), BinaryOperator::Subtract, Value::Float(b)) => Value::Float(a - b),
            (Value::Float(a), BinaryOperator::Multiply, Value::Float(b)) => Value::Float(a * b),
            (Value::Float(a), BinaryOperator::Divide, Value::Float(b)) => {
                if b.abs().inner() <= 400 {
                    return Err("Division by zero".to_string())?;
                }
                Value::Float(a / b)
            }
            (Value::Float(a), BinaryOperator::Modulo, Value::Float(b)) => Value::Float(a % b),

            // Boolean operations
            (Value::Bool(a), BinaryOperator::LogicalAnd, Value::Bool(b)) => Value::Bool(a && b),
            (Value::Bool(a), BinaryOperator::LogicalOr, Value::Bool(b)) => Value::Bool(a || b),

            // Comparison operations
            (Value::Int(a), BinaryOperator::Equal, Value::Int(b)) => Value::Bool(a == b),
            (Value::Int(a), BinaryOperator::NotEqual, Value::Int(b)) => Value::Bool(a != b),
            (Value::Int(a), BinaryOperator::LessThan, Value::Int(b)) => Value::Bool(a < b),
            (Value::Int(a), BinaryOperator::GreaterThan, Value::Int(b)) => Value::Bool(a > b),
            (Value::Int(a), BinaryOperator::LessThanOrEqual, Value::Int(b)) => Value::Bool(a <= b),
            (Value::Int(a), BinaryOperator::GreaterThanOrEqual, Value::Int(b)) => {
                Value::Bool(a >= b)
            }

            // String operations
            (Value::String(a), BinaryOperator::Add, Value::String(b)) => Value::String(a + &b),
            (Value::String(a), BinaryOperator::Equal, Value::String(b)) => Value::Bool(a == b),

            (Value::String(a), BinaryOperator::Add, Value::Int(b)) => {
                Value::String(a + &b.to_string())
            }
            (Value::Int(a), BinaryOperator::Add, Value::String(b)) => {
                Value::String(a.to_string() + &b)
            }

            (Value::Bool(a), BinaryOperator::Equal, Value::Bool(b)) => Value::Bool(a == b),
            (Value::Bool(a), BinaryOperator::NotEqual, Value::Bool(b)) => Value::Bool(a != b),

            _ => return Err(format!("Invalid binary operation {op:?} ").into()),
        };

        Ok(result)
    }

    fn evaluate_unary_op(&self, op: &UnaryOperator, val: Value) -> Result<Value, ExecuteError> {
        match (op, val) {
            (UnaryOperator::Negate, Value::Int(n)) => Ok(Value::Int(-n)),
            (UnaryOperator::Negate, Value::Float(n)) => Ok(Value::Float(-n)),
            (UnaryOperator::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
            _ => Err(format!("Invalid unary operation"))?,
        }
    }

    fn evaluate_postfix_op(&self, op: &PostfixOperator, val: Value) -> Result<Value, ExecuteError> {
        match op {
            PostfixOperator::Unwrap => self.evaluate_unwrap_op(val),
        }
    }

    #[inline]
    fn evaluate_unwrap_op(&self, val: Value) -> Result<Value, ExecuteError> {
        match val {
            Value::Option(ref unwrapped_boxed_opt) => match unwrapped_boxed_opt {
                Some(value) => Ok(*value.clone()),
                None => Ok(val),
            },
            _ => Err(ExecuteError::CanNotUnwrap),
        }
    }

    fn expressions_equal_to_values(
        &mut self,
        p0: &[ResolvedExpression],
        p1: &[Value],
    ) -> Result<bool, ExecuteError> {
        for (a, b_value) in p0.iter().zip(p1.iter()) {
            let a_value = self.evaluate_expression(a)?;

            if a_value != *b_value {
                return Ok(false);
            }
        }

        Ok(true)
    }
}