swamp_script_eval/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/script
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5use crate::block::BlockScopes;
6use crate::err::ExecuteErrorKind;
7use crate::prelude::{ValueReference, VariableValue};
8use err::ExecuteError;
9use seq_map::SeqMap;
10use std::fmt::Debug;
11use std::{cell::RefCell, collections::HashMap, rc::Rc};
12use swamp_script_core_extra::extra::{SparseValueId, SparseValueMap};
13use swamp_script_core_extra::prelude::ValueError;
14use swamp_script_core_extra::value::ValueRef;
15use swamp_script_core_extra::value::{
16    SourceMapLookup, Value, convert_vec_to_rc_refcell, format_value, to_rust_value,
17};
18use swamp_script_node::Node;
19use swamp_script_semantic::prelude::*;
20use swamp_script_semantic::{ArgumentExpressionOrLocation, LocationAccess, LocationAccessKind};
21use swamp_script_semantic::{
22    BinaryOperatorKind, CompoundOperatorKind, ConstantId, ForPattern, Function,
23    MutOrImmutableExpression, NormalPattern, PatternElement, PostfixKind, SingleLocationExpression,
24    SingleLocationExpressionKind, UnaryOperatorKind,
25};
26use swamp_script_semantic::{ExternalFunctionId, Postfix, SingleMutLocationExpression};
27use swamp_script_types::{
28    EnumVariantType, EnumVariantTypeRef, TypeForParameter, same_anon_struct_ref,
29};
30use tracing::{error, info};
31
32pub mod err;
33
34mod block;
35pub mod prelude;
36pub mod value_both;
37pub mod value_ref;
38
39impl From<ValueError> for ExecuteError {
40    fn from(value: ValueError) -> Self {
41        Self {
42            kind: ExecuteErrorKind::ValueError(value),
43            node: Default::default(),
44        }
45    }
46}
47
48type RawFunctionFn<C> = dyn FnMut(&[VariableValue], &mut C) -> Result<Value, ExecuteError>;
49
50type FunctionFn<C> = Box<RawFunctionFn<C>>;
51
52#[derive(Debug)]
53pub enum FunctionData {
54    Internal(InternalFunctionDefinitionRef),
55    External(ExternalFunctionId),
56}
57
58pub struct EvalExternalFunction<C> {
59    pub func: FunctionFn<C>,
60    pub id: ExternalFunctionId,
61}
62
63impl<C> Debug for EvalExternalFunction<C> {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        write!(f, "external_fn {}", self.id)
66    }
67}
68
69pub type EvalExternalFunctionRef<C> = Rc<RefCell<EvalExternalFunction<C>>>;
70
71#[derive(Debug)]
72pub enum ValueWithSignal {
73    Value(Value),
74    Return(Value),
75    Break,
76    Continue,
77}
78
79impl TryFrom<ValueWithSignal> for Value {
80    type Error = String;
81
82    fn try_from(value: ValueWithSignal) -> Result<Self, Self::Error> {
83        match value {
84            ValueWithSignal::Value(v) => Ok(v),
85            ValueWithSignal::Return(v) => Ok(v),
86            ValueWithSignal::Break => Err("break can not be converted".to_string()),
87            ValueWithSignal::Continue => Err("continue can not be converted".to_string()),
88        }
89    }
90}
91
92#[derive(Default)]
93struct FunctionScope {
94    saved_block_scope: BlockScopes,
95}
96
97#[derive(Debug, Default)]
98pub struct ExternalFunctions<C> {
99    //    external_functions: HashMap<String, EvalExternalFunctionRef<C>>,
100    external_functions_by_id: HashMap<ExternalFunctionId, EvalExternalFunctionRef<C>>,
101}
102
103#[derive(Debug)]
104pub struct Constants {
105    pub values: Vec<Value>,
106}
107
108impl Default for Constants {
109    fn default() -> Self {
110        Self::new()
111    }
112}
113
114impl Constants {
115    #[must_use]
116    pub fn lookup_constant_value(&self, id: ConstantId) -> &Value {
117        let x = &self.values[id as usize];
118        assert_ne!(*x, Value::Unit, "illegal constant");
119        x
120    }
121
122    pub fn set(&mut self, id: ConstantId, value: Value) {
123        self.values[id as usize] = value;
124    }
125
126    #[must_use]
127    pub fn new() -> Self {
128        let arr: [Value; 1024] = core::array::from_fn(|_| Value::Unit);
129        Self {
130            values: arr.to_vec(),
131        }
132    }
133}
134
135impl<C> ExternalFunctions<C> {
136    #[must_use]
137    pub fn new() -> Self {
138        Self {
139            external_functions_by_id: HashMap::new(),
140        }
141    }
142
143    pub fn register_external_function(
144        &mut self,
145        function_id: ExternalFunctionId,
146        handler: impl FnMut(&[VariableValue], &mut C) -> Result<Value, ExecuteError> + 'static,
147    ) -> Result<(), String> {
148        let external_func = EvalExternalFunction {
149            func: Box::new(handler),
150            id: function_id,
151        };
152
153        let external_func_ref = Rc::new(RefCell::new(external_func));
154
155        self.external_functions_by_id
156            .insert(function_id, external_func_ref.clone());
157
158        Ok(())
159    }
160}
161
162pub fn eval_module<C>(
163    externals: &ExternalFunctions<C>,
164    constants: &Constants,
165    root_expression: &Expression,
166    debug_source_map: Option<&dyn SourceMapLookup>,
167    context: &mut C,
168) -> Result<Value, ExecuteError> {
169    let mut interpreter = Interpreter::<C>::new(externals, constants, context);
170    interpreter.debug_source_map = debug_source_map;
171    let value_with_signal = interpreter.evaluate_expression_with_signal(root_expression)?;
172    value_with_signal.try_into().map_err(|_| ExecuteError {
173        node: Node::default(),
174        kind: ExecuteErrorKind::CouldNotConvertFromSignal,
175    })
176}
177
178pub fn eval_constants<C>(
179    externals: &ExternalFunctions<C>,
180    eval_constants: &mut Constants,
181    program_state: &ProgramState,
182    context: &mut C,
183) -> Result<(), ExecuteError> {
184    for constant in &program_state.constants_in_dependency_order {
185        let mut interpreter = Interpreter::<C>::new(externals, eval_constants, context);
186        let value = interpreter.evaluate_expression(&constant.expr)?;
187        eval_constants.set(constant.id, value);
188    }
189
190    Ok(())
191}
192
193pub fn util_execute_function<C>(
194    externals: &ExternalFunctions<C>,
195    constants: &Constants,
196    func: &InternalFunctionDefinitionRef,
197    arguments: &[VariableValue],
198    context: &mut C,
199    debug_source_map: Option<&dyn SourceMapLookup>,
200) -> Result<Value, ExecuteError> {
201    let mut interpreter = Interpreter::<C>::new(externals, constants, context);
202    interpreter.debug_source_map = debug_source_map;
203    interpreter.bind_parameters(&func.body.node, &func.signature.parameters, &arguments)?;
204    let value = interpreter.evaluate_expression(&func.body)?;
205    interpreter.current_block_scopes.clear();
206    interpreter.function_scope_stack.clear();
207    Ok(value)
208}
209
210pub fn util_execute_expression<C>(
211    externals: &ExternalFunctions<C>,
212    constants: &Constants,
213    expr: &Expression,
214    context: &mut C,
215    debug_source_map: Option<&dyn SourceMapLookup>,
216) -> Result<Value, ExecuteError> {
217    let mut interpreter = Interpreter::<C>::new(externals, constants, context);
218    interpreter.debug_source_map = debug_source_map;
219    let value = interpreter.evaluate_expression(expr)?;
220    interpreter.current_block_scopes.clear();
221    interpreter.function_scope_stack.clear();
222    Ok(value)
223}
224
225pub fn util_execute_member_function_mut<C>(
226    externals: &ExternalFunctions<C>,
227    constants: &Constants,
228    fn_def: &InternalFunctionDefinitionRef,
229    self_value_ref: ValueRef,
230    arguments: &[Value],
231    context: &mut C,
232    debug_source_map: Option<&dyn SourceMapLookup>,
233) -> Result<Value, ExecuteError> {
234    let mut complete_arguments = Vec::new();
235    complete_arguments.push(VariableValue::Reference(self_value_ref));
236    for arg in arguments {
237        complete_arguments.push(VariableValue::Value(arg.clone()));
238    }
239
240    let value = util_execute_function(
241        externals,
242        constants,
243        fn_def,
244        &complete_arguments,
245        context,
246        debug_source_map,
247    )?;
248
249    Ok(value)
250}
251
252pub struct Interpreter<'a, C> {
253    function_scope_stack: Vec<FunctionScope>,
254    current_block_scopes: BlockScopes,
255    constants: &'a Constants,
256    externals: &'a ExternalFunctions<C>,
257    context: &'a mut C,
258    debug_source_map: Option<&'a dyn SourceMapLookup>,
259    depth: usize,
260}
261
262impl<'a, C> Interpreter<'a, C> {
263    pub fn new(
264        externals: &'a ExternalFunctions<C>,
265        constants: &'a Constants,
266        context: &'a mut C,
267    ) -> Self {
268        Self {
269            function_scope_stack: vec![FunctionScope::default()],
270            current_block_scopes: BlockScopes::default(),
271            externals,
272            context,
273            debug_source_map: None,
274            constants,
275            depth: 0,
276        }
277    }
278
279    #[inline]
280    fn push_function_scope(&mut self) {
281        self.function_scope_stack.push(FunctionScope {
282            saved_block_scope: self.current_block_scopes.clone(),
283        });
284
285        self.current_block_scopes.clear();
286        self.push_block_scope();
287    }
288
289    #[inline]
290    fn push_block_scope(&mut self) {
291        self.current_block_scopes.push();
292    }
293
294    #[inline]
295    fn pop_block_scope(&mut self) {
296        self.current_block_scopes.pop();
297    }
298
299    #[inline]
300    fn pop_function_scope(&mut self) {
301        assert_ne!(self.function_scope_stack.len(), 1, "you popped too far");
302        let last_one = self.function_scope_stack.pop().expect("pop function scope");
303        self.current_block_scopes = last_one.saved_block_scope;
304    }
305
306    fn bind_parameters(
307        &mut self,
308        node: &Node,
309        params: &[TypeForParameter],
310        args: &[VariableValue],
311    ) -> Result<(), ExecuteError> {
312        for (index, (param, arg)) in params.iter().zip(args).enumerate() {
313            let complete_value = if param.is_mutable {
314                match arg {
315                    VariableValue::Reference(_r) => {
316                        // For mutable parameters, use the SAME reference
317                        arg.clone()
318                    }
319                    _ => return Err(self.create_err(ExecuteErrorKind::ArgumentIsNotMutable, node)),
320                }
321            } else {
322                match arg {
323                    VariableValue::Reference(r) => VariableValue::Value(r.borrow().clone()),
324                    VariableValue::Value(v) => VariableValue::Value(v.clone()),
325                }
326            };
327
328            self.current_block_scopes
329                .set_local_var_ex(index, complete_value, param.is_mutable)?;
330        }
331
332        Ok(())
333    }
334    fn evaluate_function_call(
335        &mut self,
336        function_expression: &Expression,
337        arguments: &[ArgumentExpressionOrLocation],
338    ) -> Result<Value, ExecuteError> {
339        let func_val = self.evaluate_expression(function_expression)?;
340        let evaluated_args = self.evaluate_args(arguments)?;
341
342        match &func_val {
343            Value::InternalFunction(internal_func_ref) => {
344                self.push_function_scope();
345
346                self.bind_parameters(
347                    &internal_func_ref.body.node,
348                    &internal_func_ref.signature.parameters,
349                    &evaluated_args,
350                )?;
351
352                let result = self.evaluate_expression(&internal_func_ref.body)?;
353
354                self.pop_function_scope();
355
356                Ok(result)
357            }
358
359            Value::ExternalFunction(external_function_ref) => {
360                let external_function_id = &external_function_ref.id;
361                let mut func = self
362                    .externals
363                    .external_functions_by_id
364                    .get(&external_function_id)
365                    .ok_or(self.create_err(
366                        ExecuteErrorKind::MissingExternalFunction(*external_function_id),
367                        &function_expression.node,
368                    ))?
369                    .borrow_mut();
370
371                (func.func)(&evaluated_args, self.context)
372            }
373            _ => Err(self.create_err(
374                ExecuteErrorKind::ExpectedFunction,
375                &function_expression.node,
376            )),
377        }
378    }
379
380    fn evaluate_location_chain(
381        &mut self,
382        node: &Node,
383        start_value_reference: ValueRef,
384        chain_items: &Vec<LocationAccess>,
385    ) -> Result<ValueRef, ExecuteError> {
386        let mut value_ref = start_value_reference;
387        for chain in chain_items {
388            value_ref = {
389                match &chain.kind {
390                    LocationAccessKind::FieldIndex(_resolved_node, index) => {
391                        let borrowed = value_ref.borrow();
392
393                        let (_struct_ref, fields) = borrowed
394                            .expect_anon_struct()
395                            .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedStruct, node))?;
396                        fields[*index].clone()
397                    }
398                    LocationAccessKind::ArrayIndex(_array_type_ref, index_expr) => {
399                        let index = self
400                            .evaluate_expression(index_expr)?
401                            .expect_int()
402                            .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedArray, node))?;
403
404                        let borrowed = value_ref.borrow();
405
406                        let (_array_ref, fields) = borrowed
407                            .expect_array()
408                            .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedArray, node))?;
409                        fields[index as usize].clone()
410                    }
411
412                    LocationAccessKind::ArrayRange(_, _) => todo!(),
413                    LocationAccessKind::StringIndex(_) => todo!(),
414                    LocationAccessKind::StringRange(_) => todo!(),
415
416                    LocationAccessKind::MapIndex(_map_type_ref, _value_type, key_expr) => {
417                        let key_expr_value = self.evaluate_expression(key_expr)?;
418
419                        let borrowed = value_ref.borrow();
420
421                        let (_map_type_ref, _value_type, seq_map) = borrowed
422                            .expect_map()
423                            .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedMap, node))?;
424
425                        let maybe_found = seq_map.get(&key_expr_value);
426
427                        wrap_in_option(maybe_found)
428                    }
429
430                    LocationAccessKind::MapIndexInsertIfNonExisting(
431                        _map_type_ref,
432                        _value_type,
433                        key_expr,
434                    ) => {
435                        let key_expr_value = self.evaluate_expression(key_expr)?;
436                        let key = key_expr_value.clone();
437                        let mut borrowed_mut = value_ref.borrow_mut();
438                        let found_memory = {
439                            let (_, _, seq_map_mutable) =
440                                borrowed_mut.expect_map_mut().map_err(|_| {
441                                    self.create_err(ExecuteErrorKind::ExpectedMap, node)
442                                })?;
443                            seq_map_mutable.get(&key).cloned()
444                        };
445                        match found_memory {
446                            Some(found) => found,
447                            _ => {
448                                let (_, _, seq_map_mutable) =
449                                    borrowed_mut.expect_map_mut().map_err(|_| {
450                                        self.create_err(ExecuteErrorKind::ExpectedMap, node)
451                                    })?;
452                                let default_value = Rc::new(RefCell::new(Value::Unit));
453                                seq_map_mutable
454                                    .insert(key, default_value.clone())
455                                    .expect("insert should work");
456                                default_value
457                            }
458                        }
459                    }
460
461                    LocationAccessKind::ExternalTypeIndex(_rust_type_ref, key_expr) => {
462                        let key_expr_value = self.evaluate_expression(key_expr)?;
463                        match key_expr_value.downcast_rust::<SparseValueId>() {
464                            Some(found_sparse_id) => {
465                                match value_ref.borrow_mut().downcast_rust::<SparseValueMap>() {
466                                    Some(sparse_value_map) => {
467                                        let inner_map = sparse_value_map.borrow_mut();
468                                        wrap_in_option(
469                                            inner_map.get(&found_sparse_id.borrow()).clone(),
470                                        )
471                                    }
472                                    _ => {
473                                        return Err(
474                                            self.create_err(ExecuteErrorKind::ExpectedArray, node)
475                                        )?;
476                                    }
477                                }
478                            }
479                            _ => {
480                                return Err(self.create_err(ExecuteErrorKind::ExpectedArray, node))?;
481                            }
482                        }
483                    }
484                }
485            };
486        }
487
488        Ok(value_ref)
489    }
490
491    fn evaluate_location(
492        &mut self,
493        found_location_expr: &SingleLocationExpression,
494    ) -> Result<ValueRef, ExecuteError> {
495        let variable_ref = self
496            .current_block_scopes
497            .lookup_variable_mut_ref(&found_location_expr.starting_variable)?;
498
499        let value_ref = self.evaluate_location_chain(
500            &found_location_expr.node,
501            variable_ref.clone(),
502            &found_location_expr.access_chain,
503        )?;
504
505        let converted_value_ref = match &found_location_expr.kind {
506            SingleLocationExpressionKind::MutVariableRef => value_ref,
507            SingleLocationExpressionKind::MutStructFieldRef(_base_expression, _resolved_access) => {
508                value_ref
509            }
510            SingleLocationExpressionKind::MutArrayIndexRef(_resolved_array_ref) => {
511                //info!(?base_expression, "base expression for field access");
512                let (_struct, _values) = value_ref.borrow().expect_array().map_err(|_| {
513                    self.create_err(ExecuteErrorKind::ExpectedArray, &found_location_expr.node)
514                })?;
515                value_ref
516            }
517            _ => {
518                panic!("not sure what this is")
519            }
520        };
521
522        Ok(converted_value_ref)
523    }
524
525    fn evaluate_mut_or_immutable_expression(
526        &mut self,
527        expr: &MutOrImmutableExpression,
528    ) -> Result<VariableValue, ExecuteError> {
529        let var_value = match &expr.expression_or_location {
530            ArgumentExpressionOrLocation::Location(loc) => {
531                VariableValue::Reference(self.evaluate_location(loc)?)
532            }
533            ArgumentExpressionOrLocation::Expression(expr) => {
534                VariableValue::Value(self.evaluate_expression(expr)?)
535            }
536        };
537        Ok(var_value)
538    }
539
540    fn evaluate_argument(
541        &mut self,
542        expr: &ArgumentExpressionOrLocation,
543    ) -> Result<VariableValue, ExecuteError> {
544        let var_value = match expr {
545            ArgumentExpressionOrLocation::Location(mutable_location) => {
546                VariableValue::Reference(self.evaluate_location(mutable_location)?)
547            }
548            ArgumentExpressionOrLocation::Expression(expr) => {
549                let value = self.evaluate_expression(expr)?;
550                VariableValue::Value(value)
551            }
552        };
553
554        Ok(var_value)
555    }
556
557    fn evaluate_args(
558        &mut self,
559        args: &[ArgumentExpressionOrLocation],
560    ) -> Result<Vec<VariableValue>, ExecuteError> {
561        let mut evaluated = Vec::with_capacity(args.len());
562
563        for argument_expression in args {
564            let mem_value = self.evaluate_argument(argument_expression)?;
565            evaluated.push(mem_value);
566        }
567
568        Ok(evaluated)
569    }
570
571    fn evaluate_expressions(&mut self, exprs: &[Expression]) -> Result<Vec<Value>, ExecuteError> {
572        let mut values = vec![];
573        for expr in exprs {
574            let value = self.evaluate_expression(expr)?;
575            values.push(value);
576        }
577
578        Ok(values)
579    }
580
581    fn evaluate_while_loop(
582        &mut self,
583        condition: &BooleanExpression,
584        body: &Expression,
585    ) -> Result<ValueWithSignal, ExecuteError> {
586        let mut result = Value::Unit;
587        while self
588            .evaluate_expression(&condition.expression)?
589            .is_truthy()
590            .unwrap()
591        // TODO: improve error handling
592        {
593            match self.evaluate_expression_with_signal(body) {
594                Err(e) => return Err(e),
595                Ok(signal) => match signal {
596                    ValueWithSignal::Value(v) => result = v,
597                    ValueWithSignal::Break => {
598                        break;
599                    }
600                    ValueWithSignal::Return(v) => return Ok(ValueWithSignal::Return(v)),
601                    ValueWithSignal::Continue => {}
602                },
603            }
604        }
605
606        Ok(ValueWithSignal::Value(result))
607    }
608
609    fn evaluate_block(
610        &mut self,
611        expressions: &Vec<Expression>,
612    ) -> Result<ValueWithSignal, ExecuteError> {
613        let mut result = Value::Unit;
614
615        self.push_block_scope();
616        for expression in expressions {
617            match self.evaluate_expression_with_signal(&expression)? {
618                ValueWithSignal::Value(v) => result = v,
619                ValueWithSignal::Return(v) => return Ok(ValueWithSignal::Return(v)),
620                ValueWithSignal::Break => return Ok(ValueWithSignal::Break),
621                ValueWithSignal::Continue => return Ok(ValueWithSignal::Continue),
622            }
623        }
624        self.pop_block_scope();
625        Ok(ValueWithSignal::Value(result))
626    }
627
628    fn evaluate_for_loop_mutable(
629        &mut self,
630        pattern: &ForPattern,
631        iterator_expr: &Iterable,
632        body: &Box<Expression>,
633    ) -> Result<ValueWithSignal, ExecuteError> {
634        let mut result = Value::Unit;
635
636        let iterator_value_mem =
637            self.evaluate_mut_or_immutable_expression(&iterator_expr.resolved_expression)?;
638        let iterator_value = match iterator_value_mem {
639            VariableValue::Value(_) => {
640                return Err(self.create_err(ExecuteErrorKind::ArgumentIsNotMutable, &body.node));
641            }
642            VariableValue::Reference(value_ref) => value_ref,
643        };
644
645        match pattern {
646            ForPattern::Single(var_ref) => {
647                self.push_block_scope();
648
649                for value in ValueReference(iterator_value).into_iter_mut().unwrap() {
650                    // TODO: Improve error handling
651                    self.current_block_scopes.initialize_var_mut(var_ref, value);
652
653                    match self.evaluate_expression_with_signal(body)? {
654                        ValueWithSignal::Value(v) => result = v,
655                        ValueWithSignal::Return(v) => return Ok(ValueWithSignal::Return(v)),
656                        ValueWithSignal::Break => break,
657                        ValueWithSignal::Continue => continue,
658                    }
659                }
660
661                self.pop_block_scope();
662            }
663
664            ForPattern::Pair(first_ref, second_ref) => {
665                self.push_block_scope();
666
667                for (key, value_reference) in ValueReference(iterator_value)
668                    .into_iter_mut_pairs()
669                    .unwrap()
670                {
671                    // TODO: error handling
672                    // Set both variables
673                    self.current_block_scopes.initialize_var(
674                        first_ref.scope_index,
675                        first_ref.variable_index,
676                        key,
677                        false,
678                    );
679                    self.current_block_scopes
680                        .initialize_var_mut(second_ref, value_reference.0);
681
682                    match self.evaluate_expression_with_signal(body)? {
683                        ValueWithSignal::Value(v) => result = v,
684                        ValueWithSignal::Return(v) => return Ok(ValueWithSignal::Return(v)),
685                        ValueWithSignal::Break => break,
686                        ValueWithSignal::Continue => continue,
687                    }
688                }
689
690                self.pop_block_scope();
691            }
692        }
693
694        Ok(ValueWithSignal::Value(result))
695    }
696
697    fn evaluate_for_loop(
698        &mut self,
699        pattern: &ForPattern,
700        iterator_expr: &Iterable,
701        body: &Box<Expression>,
702    ) -> Result<ValueWithSignal, ExecuteError> {
703        let mut result = Value::Unit;
704
705        let iterator_value =
706            self.evaluate_mut_or_immutable_expression(&iterator_expr.resolved_expression)?;
707
708        match pattern {
709            ForPattern::Single(var_ref) => {
710                self.push_block_scope();
711
712                for value in iterator_value.into_iter().unwrap() {
713                    // TODO: Error handling
714                    self.current_block_scopes.initialize_var(
715                        var_ref.scope_index,
716                        var_ref.variable_index,
717                        value,
718                        var_ref.is_mutable(),
719                    );
720
721                    match self.evaluate_expression_with_signal(body)? {
722                        ValueWithSignal::Value(v) => result = v,
723                        ValueWithSignal::Return(v) => {
724                            self.pop_block_scope();
725                            return Ok(ValueWithSignal::Return(v));
726                        }
727                        ValueWithSignal::Break => break,
728                        ValueWithSignal::Continue => continue,
729                    }
730                }
731
732                self.pop_block_scope();
733            }
734
735            ForPattern::Pair(first_ref, second_ref) => {
736                self.push_block_scope();
737
738                // iterator_expr.is_mutable() should select reference
739
740                for (key, value) in iterator_value.into_iter_pairs().unwrap() {
741                    // TODO: Error handling
742                    // Set both variables
743                    self.current_block_scopes.initialize_var(
744                        first_ref.scope_index,
745                        first_ref.variable_index,
746                        key,
747                        false,
748                    );
749                    self.current_block_scopes.initialize_var(
750                        second_ref.scope_index,
751                        second_ref.variable_index,
752                        value,
753                        false,
754                    );
755
756                    match self.evaluate_expression_with_signal(body)? {
757                        ValueWithSignal::Value(v) => result = v,
758                        ValueWithSignal::Return(v) => return Ok(ValueWithSignal::Return(v)),
759                        ValueWithSignal::Break => break,
760                        ValueWithSignal::Continue => continue,
761                    }
762                }
763
764                self.pop_block_scope();
765            }
766        }
767
768        Ok(ValueWithSignal::Value(result))
769    }
770
771    #[allow(unused)]
772    fn debug_expr(&self, expr: &Expression) {
773        if let Some(debug_source_map) = self.debug_source_map {
774            let source_line = debug_source_map.get_text(&expr.node);
775            eprintln!("{:?}:\n  {}", expr.kind, source_line);
776            //io::stderr().flush().expect("Failed to flush stdout");
777        }
778    }
779
780    #[inline]
781    #[allow(clippy::too_many_lines)]
782    fn evaluate_expression_with_signal(
783        &mut self,
784        expr: &Expression,
785    ) -> Result<ValueWithSignal, ExecuteError> {
786        match &expr.kind {
787            ExpressionKind::Break => Ok(ValueWithSignal::Break),
788            ExpressionKind::Continue => Ok(ValueWithSignal::Continue),
789
790            ExpressionKind::Return(maybe_expr) => {
791                let value = match maybe_expr {
792                    None => Value::Unit,
793                    Some(expr) => self.evaluate_expression(expr)?,
794                };
795                Ok(ValueWithSignal::Return(value))
796            }
797
798            ExpressionKind::WhileLoop(condition, body) => self.evaluate_while_loop(condition, body),
799
800            ExpressionKind::ForLoop(pattern, iterator_expr, body) => {
801                if pattern.is_mutable() {
802                    self.evaluate_for_loop_mutable(pattern, iterator_expr, body)
803                } else {
804                    self.evaluate_for_loop(pattern, iterator_expr, body)
805                }
806            }
807
808            ExpressionKind::If(condition, consequences, optional_alternative) => {
809                let cond_value = self.evaluate_expression(&condition.expression)?;
810                if cond_value.is_truthy()? {
811                    self.evaluate_expression_with_signal(consequences)
812                } else if let Some(alternative) = optional_alternative {
813                    self.evaluate_expression_with_signal(alternative)
814                } else {
815                    Ok(ValueWithSignal::Value(Value::Unit))
816                }
817            }
818
819            ExpressionKind::Block(expressions) => self.evaluate_block(expressions),
820
821            ExpressionKind::When(bindings, true_block, maybe_else_block) => {
822                let mut all_are_some = true;
823                let mut all_expressions = Vec::new();
824                for binding in bindings {
825                    let source = self.evaluate_mut_or_immutable_expression(&binding.expr)?;
826                    match source.to_value() {
827                        Value::Option(boxed_val) => {
828                            match boxed_val {
829                                Some(found_val) => {
830                                    let variable_value = match source {
831                                        VariableValue::Value(_) => {
832                                            // Source was not created mut, so copy value
833                                            VariableValue::Value(found_val.borrow().clone())
834                                        }
835                                        VariableValue::Reference(_var_ref) => {
836                                            // It was `mut`
837                                            VariableValue::Reference(found_val)
838                                        }
839                                    };
840                                    all_expressions.push(variable_value);
841                                }
842                                _ => {
843                                    all_are_some = false;
844                                    //warn!(?source, "Not ALL ARE SOME!");
845                                    break;
846                                }
847                            }
848                        }
849                        _ => {
850                            return Err(self
851                                .create_err(ExecuteErrorKind::ExpectedOptional, &true_block.node));
852                        }
853                    }
854                }
855
856                if all_are_some {
857                    self.push_block_scope();
858
859                    for (binding, value) in bindings.iter().zip(all_expressions) {
860                        self.current_block_scopes
861                            .initialize_var_mem(&binding.variable, value)?;
862                    }
863
864                    let result = self.evaluate_expression_with_signal(true_block)?;
865                    self.pop_block_scope();
866
867                    Ok(result)
868                } else if let Some(else_block) = maybe_else_block {
869                    self.evaluate_expression_with_signal(else_block)
870                } else {
871                    Ok(ValueWithSignal::Value(Value::Unit))
872                }
873            }
874
875            _ => Ok(ValueWithSignal::Value(self.evaluate_expression(expr)?)),
876        }
877    }
878
879    // ---------------
880    #[allow(clippy::too_many_lines)]
881    #[inline]
882    fn evaluate_expression(&mut self, expr: &Expression) -> Result<Value, ExecuteError> {
883        self.depth += 1;
884        let value = match &expr.kind {
885            // Illegal in this context
886            ExpressionKind::Continue => {
887                return Err(self.create_err(ExecuteErrorKind::ContinueNotAllowedHere, &expr.node));
888            }
889            ExpressionKind::Break => {
890                return Err(self.create_err(ExecuteErrorKind::BreakNotAllowedHere, &expr.node));
891            }
892            ExpressionKind::Return(_maybe_expr) => {
893                return Err(self.create_err(ExecuteErrorKind::ReturnNotAllowedHere, &expr.node));
894            }
895
896            ExpressionKind::WhileLoop(_condition, _body) => {
897                panic!("should have been handled earlier")
898            }
899
900            ExpressionKind::ForLoop(_pattern, _iterator_expr, _body) => {
901                panic!("should have been handled earlier")
902            }
903
904            // Constructing
905            ExpressionKind::Literal(lit) => self.evaluate_literal(&expr.node, lit)?,
906
907            ExpressionKind::Array(array_instantiation) => {
908                let mut values = Vec::new();
909                for element in &array_instantiation.expressions {
910                    values.push(self.evaluate_expression(element)?);
911                }
912
913                Value::Vec(
914                    array_instantiation.array_type_ref.clone(),
915                    convert_vec_to_rc_refcell(values),
916                )
917            }
918
919            ExpressionKind::StructInstantiation(struct_instantiation) => {
920                // Evaluate all field expressions and validate types
921                let mut field_values =
922                    Vec::with_capacity(struct_instantiation.source_order_expressions.len());
923                field_values.resize_with(
924                    struct_instantiation.source_order_expressions.len(),
925                    Default::default,
926                );
927
928                // They are evaluated in source order, but an array_index is provided for the definition order
929                for (array_index, field_expr) in &struct_instantiation.source_order_expressions {
930                    let value = self.evaluate_expression(field_expr)?;
931                    field_values[*array_index] = value;
932                }
933
934                Value::NamedStruct(
935                    struct_instantiation.struct_type_ref.clone(),
936                    convert_vec_to_rc_refcell(field_values),
937                )
938            }
939
940            ExpressionKind::AnonymousStructLiteral(struct_instantiation) => {
941                // Evaluate all field expressions and validate types
942                let mut field_values =
943                    Vec::with_capacity(struct_instantiation.source_order_expressions.len());
944                field_values.resize_with(
945                    struct_instantiation.source_order_expressions.len(),
946                    Default::default,
947                );
948
949                // They are evaluated in source order, but an array_index is provided for the definition order
950                for (array_index, field_expr) in &struct_instantiation.source_order_expressions {
951                    let value = self.evaluate_expression(field_expr)?;
952                    field_values[*array_index] = value;
953                }
954
955                Value::AnonymousStruct(
956                    struct_instantiation.anonymous_struct_type.clone(),
957                    convert_vec_to_rc_refcell(field_values),
958                )
959            }
960
961            ExpressionKind::Range(start, end, range_mode) => {
962                let start_val = self.evaluate_expression(start)?;
963                let end_val = self.evaluate_expression(end)?;
964                match (start_val, end_val) {
965                    (Value::Int(s), Value::Int(e)) => {
966                        Value::Range(Box::new(s), Box::new(e), range_mode.clone())
967                    }
968                    _ => Err(self.create_err(ExecuteErrorKind::RangeItemMustBeInt, &expr.node))?,
969                }
970            }
971
972            // ==================== ASSIGNMENT ====================
973            ExpressionKind::VariableDefinition(target_var, source_expr) => {
974                let source_value_or_reference =
975                    self.evaluate_mut_or_immutable_expression(source_expr)?;
976
977                self.current_block_scopes
978                    .initialize_var_mem(target_var, source_value_or_reference.clone())?;
979
980                source_value_or_reference.to_value().clone()
981            }
982
983            ExpressionKind::VariableReassignment(variable_ref, source_expr) => {
984                let new_value = self.evaluate_mut_or_immutable_expression(source_expr)?;
985
986                let value_ref = self
987                    .current_block_scopes
988                    .lookup_variable_mut_ref(variable_ref)?;
989
990                let mut was_assigned = false;
991                if let Value::Option(inner_value) = &*value_ref.borrow() {
992                    if let Some(inner) = inner_value {
993                        *inner.borrow_mut() = new_value.to_value();
994                        was_assigned = true;
995                    }
996                }
997
998                if !was_assigned {
999                    self.current_block_scopes
1000                        .overwrite_existing_var_mem(variable_ref, new_value.clone())?;
1001                }
1002
1003                Value::Unit
1004            }
1005
1006            ExpressionKind::IntrinsicCallMut(intrinsic, location, arguments) => {
1007                self.evaluate_intrinsic_mut(&expr.node, intrinsic, location, arguments)?
1008            }
1009
1010            ExpressionKind::MapAssignment(map, index, value) => {
1011                let map_val = self.evaluate_location(&map.0)?;
1012                let index_val = self.evaluate_expression(index)?;
1013                let new_val = self.evaluate_expression(value)?;
1014
1015                match &mut *map_val.borrow_mut() {
1016                    Value::Map(_key_type, _value_type, elements) => {
1017                        elements
1018                            .insert(index_val, Rc::new(RefCell::new(new_val)))
1019                            .map_err(|_| {
1020                                self.create_err(ExecuteErrorKind::MapKeyAlreadyExists, &expr.node)
1021                            })?;
1022                    }
1023                    _ => {
1024                        Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &expr.node))?;
1025                    }
1026                }
1027
1028                Value::Unit
1029            }
1030
1031            // ------------- LOOKUP ---------------------
1032            ExpressionKind::ConstantAccess(constant) => {
1033                self.constants.lookup_constant_value(constant.id).clone()
1034            }
1035
1036            ExpressionKind::AssignmentSlice(_mut_location, _source) => todo!(),
1037
1038            ExpressionKind::Assignment(mut_location_expr, source_expr) => {
1039                let value_ref = self.evaluate_location(&mut_location_expr.0)?;
1040                let source_value = self.evaluate_expression(source_expr)?;
1041
1042                *value_ref.borrow_mut() = source_value;
1043
1044                Value::Unit
1045            }
1046
1047            ExpressionKind::CompoundAssignment(mut_location_expr, op, source_expr) => {
1048                let value_ref = self.evaluate_location(&mut_location_expr.0)?;
1049                let source_value = self.evaluate_expression(source_expr)?;
1050
1051                self.apply_compound_operator(
1052                    &expr.node,
1053                    &mut value_ref.borrow_mut(),
1054                    op,
1055                    &source_value,
1056                )?;
1057
1058                Value::Unit
1059            }
1060
1061            // Operators
1062            ExpressionKind::BinaryOp(binary_operator) => {
1063                let left_val = self.evaluate_expression(&binary_operator.left)?;
1064                let right_val = self.evaluate_expression(&binary_operator.right)?;
1065                self.evaluate_binary_op(&expr.node, left_val, &binary_operator.kind, right_val)?
1066            }
1067
1068            ExpressionKind::UnaryOp(unary_operator) => {
1069                let left_val = self.evaluate_expression(&unary_operator.left)?;
1070                self.evaluate_unary_op(&expr.node, &unary_operator.kind, left_val)?
1071            }
1072
1073            // Calling
1074            ExpressionKind::FunctionCall(_signature, expr, arguments) => {
1075                self.evaluate_function_call(expr, arguments)?
1076            }
1077
1078            ExpressionKind::MemberCall(resolved_member_call) => {
1079                let parameters = match &*resolved_member_call.function {
1080                    Function::Internal(function_data) => &function_data.signature.parameters,
1081                    Function::External(external_data) => &external_data.signature.parameters,
1082                };
1083
1084                let mut member_call_arguments = Vec::new();
1085                member_call_arguments.extend(self.evaluate_args(&resolved_member_call.arguments)?);
1086
1087                // Check total number of parameters (including self)
1088                if member_call_arguments.len() != parameters.len() {
1089                    return Err(self.create_err(
1090                        ExecuteErrorKind::WrongNumberOfArguments(
1091                            parameters.len(),
1092                            member_call_arguments.len(),
1093                        ),
1094                        &expr.node,
1095                    ));
1096                }
1097
1098                match &*resolved_member_call.function {
1099                    Function::Internal(internal_function) => {
1100                        self.push_function_scope();
1101                        self.bind_parameters(
1102                            &expr.node,
1103                            &internal_function.signature.parameters,
1104                            &member_call_arguments,
1105                        )?;
1106                        let result = self.evaluate_expression(&internal_function.body)?;
1107                        self.pop_function_scope();
1108
1109                        result
1110                    }
1111                    Function::External(external_func) => {
1112                        let mut func = self
1113                            .externals
1114                            .external_functions_by_id
1115                            .get(&external_func.id)
1116                            .expect("member call: external function missing")
1117                            .borrow_mut();
1118                        (func.func)(&member_call_arguments, self.context)?
1119                    }
1120                }
1121            }
1122
1123            ExpressionKind::Block(statements) => {
1124                self.evaluate_block(statements)?.try_into().unwrap() // TODO: Error handling
1125            }
1126
1127            ExpressionKind::InterpolatedString(parts) => {
1128                let mut result = String::new();
1129
1130                for part in parts {
1131                    match part {
1132                        StringPart::Literal(_resolved_node, text) => {
1133                            result.push_str(text);
1134                        }
1135                        StringPart::Interpolation(expr, format_spec) => {
1136                            let value = self.evaluate_expression(expr)?;
1137                            let formatted = match format_spec {
1138                                Some(spec) => format_value(&value, &spec.kind).unwrap(), // TODO: Error handling
1139                                None => value.convert_to_string_if_needed(),
1140                            };
1141                            result.push_str(&formatted);
1142                        }
1143                    }
1144                }
1145
1146                Value::String(result)
1147            }
1148
1149            ExpressionKind::Match(resolved_match) => self.eval_match(resolved_match)?,
1150            ExpressionKind::Guard(guards) => self.eval_guard(&expr.node, guards)?,
1151
1152            ExpressionKind::InternalFunctionAccess(fetch_function) => {
1153                Value::InternalFunction(fetch_function.clone())
1154            }
1155
1156            ExpressionKind::ExternalFunctionAccess(fetch_function) => {
1157                self.externals
1158                    .external_functions_by_id
1159                    .get(&fetch_function.id)
1160                    .expect("should have external function ref");
1161                Value::ExternalFunction(fetch_function.clone())
1162            }
1163
1164            //ExpressionKind::MutMemberCall(_, _) => todo!(),
1165            ExpressionKind::Tuple(_) => todo!(),
1166            ExpressionKind::Option(inner) => match inner {
1167                None => Value::Option(None),
1168                Some(expression) => {
1169                    let v = self.evaluate_expression(expression)?;
1170                    match v {
1171                        Value::Option(_) => {
1172                            panic!("unnecessary wrap!, should be investigated");
1173                        }
1174                        _ => Value::Option(Some(Rc::new(RefCell::new(v)))),
1175                    }
1176                }
1177            },
1178
1179            // --------------- SPECIAL FUNCTIONS
1180            ExpressionKind::SparseNew(sparse_id_rust_type_ref, resolved_value_item_type) => {
1181                let sparse_value_map = SparseValueMap::new(
1182                    sparse_id_rust_type_ref.clone(),
1183                    resolved_value_item_type.clone(),
1184                );
1185                to_rust_value(sparse_id_rust_type_ref.clone(), sparse_value_map)
1186            }
1187
1188            ExpressionKind::CoerceOptionToBool(expression) => {
1189                let value = self.evaluate_expression(expression)?;
1190                match value {
1191                    Value::Option(inner) => Value::Bool(inner.is_some()),
1192                    _ => {
1193                        return Err(
1194                            self.create_err(ExecuteErrorKind::CoerceOptionToBoolFailed, &expr.node)
1195                        );
1196                    }
1197                }
1198            }
1199
1200            ExpressionKind::If(condition, consequences, optional_alternative) => {
1201                let cond_value = self.evaluate_expression(&condition.expression)?;
1202                if cond_value.is_truthy().unwrap() {
1203                    // TODO: ERROR HANDLING
1204                    self.evaluate_expression(consequences)?
1205                } else if let Some(alternative) = optional_alternative {
1206                    self.evaluate_expression(alternative)?
1207                } else {
1208                    Value::Unit
1209                }
1210            }
1211
1212            ExpressionKind::When(bindings, true_block, maybe_else_block) => {
1213                let mut all_are_some = true;
1214                let mut all_expressions = Vec::new();
1215                for binding in bindings {
1216                    let source = self.evaluate_mut_or_immutable_expression(&binding.expr)?;
1217                    match source.to_value() {
1218                        Value::Option(boxed_val) => match boxed_val {
1219                            Some(found_val) => {
1220                                all_expressions.push(found_val.borrow().clone());
1221                            }
1222                            _ => {
1223                                all_are_some = false;
1224                                break;
1225                            }
1226                        },
1227                        _ => {
1228                            return Err(self
1229                                .create_err(ExecuteErrorKind::ExpectedOptional, &true_block.node));
1230                        }
1231                    }
1232                }
1233
1234                if all_are_some {
1235                    self.push_block_scope();
1236
1237                    for (binding, value) in bindings.iter().zip(all_expressions) {
1238                        info!(var=?binding.variable, "binding as mutable");
1239                        self.current_block_scopes.initialize_var(
1240                            binding.variable.scope_index,
1241                            binding.variable.variable_index,
1242                            value,
1243                            binding.variable.is_mutable(),
1244                        );
1245                    }
1246
1247                    let result = self.evaluate_expression(true_block)?;
1248                    self.pop_block_scope();
1249
1250                    result
1251                } else if let Some(else_block) = maybe_else_block {
1252                    self.evaluate_expression(else_block)?
1253                } else {
1254                    Value::Unit
1255                }
1256            }
1257
1258            ExpressionKind::TupleDestructuring(variable_refs, _, expr) => {
1259                let value = self.evaluate_expression(expr)?;
1260                if let Value::Tuple(_tuple_ref, values) = value {
1261                    if variable_refs.len() > values.len() {
1262                        return Err(self.create_err(ExecuteErrorKind::NotAnArray, &expr.node));
1263                    }
1264                    for (index, variable_ref) in variable_refs.iter().enumerate() {
1265                        let value = &values[index].borrow().clone();
1266                        self.current_block_scopes.initialize_var(
1267                            variable_ref.scope_index,
1268                            variable_ref.variable_index,
1269                            value.clone(),
1270                            false,
1271                        );
1272                    }
1273                }
1274                Value::Unit
1275            }
1276            ExpressionKind::VariableAccess(variable_ref) => {
1277                let temp = self.current_block_scopes.lookup_var_value(variable_ref);
1278                assert_ne!(temp, Value::Unit);
1279                temp
1280            }
1281            ExpressionKind::FieldAccess(expr, index) => {
1282                let resolved_expr = self.evaluate_expression(expr)?;
1283                let (_struct_type, values) = resolved_expr
1284                    .expect_struct()
1285                    .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedStruct, &expr.node))?;
1286
1287                let x = values[*index].borrow().clone();
1288                x
1289            }
1290
1291            ExpressionKind::ArrayAccess(expr, _array, index_expr) => {
1292                let resolved_expr = self.evaluate_expression(expr)?;
1293                let (_array_type, values) = resolved_expr
1294                    .expect_array()
1295                    .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedArray, &expr.node))?;
1296
1297                let index = self
1298                    .evaluate_expression(index_expr)?
1299                    .expect_int()
1300                    .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedInt, &expr.node))?
1301                    as usize;
1302
1303                let x = values[index].borrow().clone();
1304                x
1305            }
1306
1307            ExpressionKind::MapIndexAccess(expr, _map_type_ref, _value_type, key_expr) => {
1308                let resolved_expr = self.evaluate_expression(expr)?;
1309                let (_map_type, _value_type, seq_map) = resolved_expr
1310                    .expect_map()
1311                    .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedMap, &expr.node))?;
1312
1313                let key_val = self.evaluate_expression(key_expr)?;
1314
1315                let value_val_maybe = seq_map.get(&key_val);
1316                Value::Option(value_val_maybe.cloned())
1317            }
1318            ExpressionKind::StringRangeAccess(_, _) => todo!(),
1319            ExpressionKind::ArrayRangeAccess(_, _) => todo!(),
1320            ExpressionKind::PostfixChain(start, parts) => {
1321                let value_ref = self.eval_chain(&expr.node, start, parts)?;
1322                let x = value_ref.borrow().clone();
1323                x
1324            }
1325        };
1326
1327        self.depth -= 1;
1328        //self.debug_expr(expr);
1329        //info!(?value, "resulted in value");
1330        Ok(value)
1331    }
1332
1333    fn evaluate_literal(&mut self, node: &Node, lit: &Literal) -> Result<Value, ExecuteError> {
1334        let v = match lit {
1335            Literal::IntLiteral(n) => Value::Int(*n),
1336            Literal::FloatLiteral(f) => Value::Float(*f),
1337            Literal::StringLiteral(s) => Value::String(s.clone()),
1338            Literal::BoolLiteral(b) => Value::Bool(*b),
1339
1340            Literal::EnumVariantLiteral(enum_variant_type, data) => {
1341                let variant_container_value: Value = match &**enum_variant_type {
1342                    EnumVariantType::Tuple(tuple_type) => match data {
1343                        EnumLiteralData::Tuple(tuple_expressions) => {
1344                            let eval_expressions = self.evaluate_expressions(tuple_expressions)?;
1345                            let value_refs = values_to_value_refs_owned(eval_expressions);
1346                            Value::EnumVariantTuple(tuple_type.clone(), value_refs)
1347                        }
1348                        _ => panic!("wrong container type"),
1349                    },
1350
1351                    EnumVariantType::Struct(struct_type_ref) => match data {
1352                        EnumLiteralData::Struct(source_order_field_values) => {
1353                            let mut field_values =
1354                                Vec::with_capacity(source_order_field_values.len());
1355                            field_values
1356                                .resize_with(source_order_field_values.len(), Default::default);
1357                            for (index, resolved_expression) in source_order_field_values {
1358                                let value = self.evaluate_expression(resolved_expression)?;
1359                                field_values[*index] = Rc::new(RefCell::new(value));
1360                            }
1361                            Value::EnumVariantStruct(struct_type_ref.clone(), field_values)
1362                        }
1363                        _ => panic!("wrong container type"),
1364                    },
1365
1366                    EnumVariantType::Nothing(data) => Value::EnumVariantSimple(data.clone()),
1367                };
1368                variant_container_value
1369            }
1370
1371            Literal::TupleLiteral(tuple_type, resolved_expressions) => {
1372                let values = self.evaluate_expressions(resolved_expressions)?;
1373                Value::Tuple(tuple_type.clone(), convert_vec_to_rc_refcell(values))
1374            }
1375
1376            Literal::Vec(array_type, expressions) => {
1377                let values = self.evaluate_expressions(expressions)?;
1378                Value::Vec(array_type.clone(), convert_vec_to_rc_refcell(values))
1379            }
1380
1381            Literal::Slice(element_type, expressions) => {
1382                let values = self.evaluate_expressions(expressions)?;
1383                Value::Slice(element_type.clone(), convert_vec_to_rc_refcell(values))
1384            }
1385
1386            Literal::Map(key_type, value_type, expressions) => {
1387                let mut items = SeqMap::new();
1388                for (key, value) in expressions {
1389                    let key_val = self.evaluate_expression(key)?;
1390                    let value_val = self.evaluate_expression(value)?;
1391                    items
1392                        .insert(key_val, Rc::new(RefCell::new(value_val)))
1393                        .map_err(|_err| {
1394                            self.create_err(
1395                                ExecuteErrorKind::NonUniqueKeysInMapLiteralDetected,
1396                                &node,
1397                            )
1398                        })?;
1399                }
1400                Value::Map(key_type.clone(), value_type.clone(), items)
1401            }
1402
1403            Literal::SlicePair(key_type, value_type, expressions) => {
1404                let mut items = SeqMap::new();
1405                for (key, value) in expressions {
1406                    let key_val = self.evaluate_expression(key)?;
1407                    let value_val = self.evaluate_expression(value)?;
1408                    items
1409                        .insert(key_val, Rc::new(RefCell::new(value_val)))
1410                        .map_err(|_err| {
1411                            self.create_err(
1412                                ExecuteErrorKind::NonUniqueKeysInMapLiteralDetected,
1413                                &node,
1414                            )
1415                        })?;
1416                }
1417                Value::SlicePair(key_type.clone(), value_type.clone(), items)
1418            }
1419
1420            Literal::NoneLiteral => Value::Option(None),
1421        };
1422        Ok(v)
1423    }
1424
1425    #[allow(clippy::too_many_lines)]
1426    fn eval_intrinsic_postfix(
1427        &mut self,
1428        node: &Node,
1429        value_ref: &ValueRef,
1430        //        resolved_postfix: &Postfix,
1431        intrinsic_function: &IntrinsicFunction,
1432        arguments: &[Expression],
1433    ) -> Result<Value, ExecuteError> {
1434        //let node = &resolved_postfix.node;
1435        let val = match &intrinsic_function {
1436            IntrinsicFunction::VecRemoveIndex => {
1437                let index_val = self.evaluate_expression(&arguments[0])?;
1438                let Value::Int(index) = index_val else {
1439                    return Err(self.create_err(ExecuteErrorKind::ArgumentIsNotMutable, node));
1440                };
1441
1442                match &mut *value_ref.borrow_mut() {
1443                    Value::Vec(_type_id, vector) => {
1444                        vector.remove(index as usize);
1445                    }
1446                    _ => {
1447                        Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?;
1448                    }
1449                }
1450
1451                value_ref.borrow().clone()
1452            }
1453
1454            IntrinsicFunction::VecClear => {
1455                match &mut *value_ref.borrow_mut() {
1456                    Value::Vec(_type_id, vector) => {
1457                        vector.clear();
1458                    }
1459                    _ => {
1460                        Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?;
1461                    }
1462                }
1463                Value::Unit
1464            }
1465
1466            IntrinsicFunction::VecPush => {
1467                match &mut *value_ref.borrow_mut() {
1468                    Value::Vec(_type_id, vector) => {
1469                        let value_to_add = self.evaluate_expression(&arguments[0])?;
1470                        vector.push(Rc::new(RefCell::new(value_to_add)));
1471                    }
1472                    _ => {
1473                        Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?;
1474                    }
1475                }
1476                Value::Unit
1477            }
1478
1479            IntrinsicFunction::VecLen => match &mut *value_ref.borrow_mut() {
1480                Value::Vec(_type_id, vector) => {
1481                    let length = vector.len();
1482                    Value::Int(length as i32)
1483                }
1484                _ => Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?,
1485            },
1486
1487            IntrinsicFunction::VecPop => match &mut *value_ref.borrow_mut() {
1488                Value::Vec(_type_id, vector) => {
1489                    let maybe_val = vector.pop();
1490                    Value::Option(maybe_val)
1491                }
1492                _ => Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?,
1493            },
1494
1495            IntrinsicFunction::MapHas => {
1496                let index_val = self.evaluate_expression(&arguments[0])?;
1497
1498                match value_ref.borrow().clone() {
1499                    Value::Map(_key_type, _value_type, ref seq_map) => {
1500                        let has_key = seq_map.contains_key(&index_val);
1501                        Value::Bool(has_key)
1502                    }
1503                    _ => {
1504                        return Err(self.create_err(ExecuteErrorKind::NotAMap, node));
1505                    }
1506                }
1507            }
1508
1509            IntrinsicFunction::MapRemove => {
1510                let index_val = self.evaluate_expression(&arguments[0])?;
1511
1512                let result = {
1513                    let mut borrowed = value_ref.borrow_mut();
1514                    match &mut *borrowed {
1515                        Value::Map(_key_type, _value_type, seq_map) => {
1516                            let x = seq_map.remove(&index_val);
1517                            x.map_or_else(
1518                                || Value::Option(None),
1519                                |v| Value::Option(Some(v.clone())),
1520                            )
1521                        }
1522                        _ => {
1523                            return Err(self.create_err(ExecuteErrorKind::NotAMap, node));
1524                        }
1525                    }
1526                };
1527                result
1528            }
1529
1530            IntrinsicFunction::SparseAdd => {
1531                let borrowed = value_ref.borrow();
1532
1533                let sparse_value_map = borrowed.downcast_rust::<SparseValueMap>();
1534                match sparse_value_map {
1535                    Some(found) => {
1536                        let resolved_value = self.evaluate_expression(&arguments[0])?;
1537                        let id_value = found.borrow_mut().add(resolved_value);
1538
1539                        id_value
1540                    }
1541                    _ => {
1542                        return Err(self.create_err(ExecuteErrorKind::NotSparseValue, node));
1543                    }
1544                }
1545            }
1546
1547            IntrinsicFunction::SparseRemove => {
1548                let borrowed = value_ref.borrow();
1549
1550                let sparse_value_map = borrowed.downcast_rust::<SparseValueMap>();
1551                if let Some(found) = sparse_value_map {
1552                    let id_value = self.evaluate_expression(&arguments[0])?;
1553                    match id_value.downcast_rust::<SparseValueId>() {
1554                        Some(found_id) => {
1555                            found.borrow_mut().remove(&found_id.borrow());
1556                        }
1557                        _ => {
1558                            return Err(self.create_err(ExecuteErrorKind::NotSparseValue, node));
1559                        }
1560                    }
1561                }
1562
1563                Value::Unit
1564            }
1565            IntrinsicFunction::SparseSubscript => {
1566                let sparse_value_map = value_ref.borrow_mut().downcast_rust::<SparseValueMap>();
1567                match sparse_value_map {
1568                    Some(found) => {
1569                        let id_value = self.evaluate_expression(&arguments[0])?; // id
1570                        match id_value.downcast_rust::<SparseValueId>() {
1571                            Some(found_id) => match found.borrow_mut().get(&found_id.borrow()) {
1572                                Some(found_value) => Value::Option(Some(found_value.clone())),
1573                                _ => Value::Option(None),
1574                            },
1575                            _ => {
1576                                return Err(self.create_err(ExecuteErrorKind::NotSparseId, node));
1577                            }
1578                        }
1579                    }
1580                    _ => {
1581                        return Err(self.create_err(ExecuteErrorKind::NotSparseId, node));
1582                    }
1583                }
1584            }
1585
1586            IntrinsicFunction::FloatRound => match value_ref.borrow().clone() {
1587                Value::Float(f) => Value::Int(f.round().into()),
1588                _ => {
1589                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1590                }
1591            },
1592            IntrinsicFunction::FloatFloor => match value_ref.borrow().clone() {
1593                Value::Float(f) => Value::Int(f.floor().into()),
1594                _ => {
1595                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1596                }
1597            },
1598
1599            IntrinsicFunction::FloatSign => match value_ref.borrow().clone() {
1600                Value::Float(f) => {
1601                    let signum = if f.inner() < 0 {
1602                        -1
1603                    } else if f.inner() > 0 {
1604                        1
1605                    } else {
1606                        0
1607                    };
1608                    Value::Float(Fp::from(signum as i16))
1609                }
1610                _ => {
1611                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1612                }
1613            },
1614            IntrinsicFunction::FloatAbs => match value_ref.borrow().clone() {
1615                Value::Float(f) => Value::Float(f.abs()),
1616                _ => {
1617                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1618                }
1619            },
1620
1621            IntrinsicFunction::FloatCos => match value_ref.borrow().clone() {
1622                Value::Float(f) => Value::Float(f.cos()),
1623                _ => {
1624                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1625                }
1626            },
1627
1628            IntrinsicFunction::FloatAcos => match value_ref.borrow().clone() {
1629                Value::Float(f) => Value::Float(f.acos()),
1630                _ => {
1631                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1632                }
1633            },
1634
1635            IntrinsicFunction::FloatSin => match value_ref.borrow().clone() {
1636                Value::Float(f) => Value::Float(f.sin()),
1637                _ => {
1638                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1639                }
1640            },
1641
1642            IntrinsicFunction::FloatAsin => match value_ref.borrow().clone() {
1643                Value::Float(f) => Value::Float(f.asin()),
1644                _ => {
1645                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1646                }
1647            },
1648
1649            IntrinsicFunction::FloatSqrt => match value_ref.borrow().clone() {
1650                Value::Float(f) => Value::Float(f.sqrt()),
1651                _ => {
1652                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1653                }
1654            },
1655
1656            IntrinsicFunction::FloatMin => {
1657                let min_value = self.evaluate_expression(&arguments[0])?;
1658                match (value_ref.borrow().clone(), min_value) {
1659                    (Value::Float(f), Value::Float(min_f)) => Value::Float(f.min(min_f)),
1660                    _ => {
1661                        return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1662                    }
1663                }
1664            }
1665
1666            IntrinsicFunction::FloatMax => {
1667                let max_value = self.evaluate_expression(&arguments[0])?;
1668                match (value_ref.borrow().clone(), max_value) {
1669                    (Value::Float(f), Value::Float(max_f)) => Value::Float(f.max(max_f)),
1670                    _ => {
1671                        return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1672                    }
1673                }
1674            }
1675
1676            IntrinsicFunction::FloatAtan2 => {
1677                let x_value = self.evaluate_expression(&arguments[0])?;
1678                match (value_ref.borrow().clone(), x_value) {
1679                    (Value::Float(_y_f), Value::Float(_x_f)) => {
1680                        Value::Float(Fp::from(-9999)) //y_f.atan2(x_f)) // TODO: Implement atan2
1681                    }
1682                    _ => {
1683                        return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1684                    }
1685                }
1686            }
1687
1688            IntrinsicFunction::FloatClamp => {
1689                let min_value = self.evaluate_expression(&arguments[0])?;
1690                let max_value = self.evaluate_expression(&arguments[1])?;
1691                match (value_ref.borrow().clone(), min_value, max_value) {
1692                    (Value::Float(f), Value::Float(min_f), Value::Float(max_f)) => {
1693                        Value::Float(f.clamp(min_f, max_f))
1694                    }
1695                    _ => {
1696                        return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1697                    }
1698                }
1699            }
1700
1701            IntrinsicFunction::FloatRnd => match value_ref.borrow().clone() {
1702                Value::Float(f) => {
1703                    let new_raw = squirrel_prng::squirrel_noise5(f.inner() as u32, 0);
1704                    Value::Int(new_raw as i32)
1705                }
1706                _ => {
1707                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1708                }
1709            },
1710
1711            IntrinsicFunction::IntAbs => match value_ref.borrow().clone() {
1712                Value::Int(i) => Value::Int(i.abs()),
1713                _ => {
1714                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1715                }
1716            },
1717
1718            IntrinsicFunction::IntClamp => {
1719                let min_value = self.evaluate_expression(&arguments[0])?;
1720                let max_value = self.evaluate_expression(&arguments[1])?;
1721                match (value_ref.borrow().clone(), min_value, max_value) {
1722                    (Value::Int(i), Value::Int(min_i), Value::Int(max_i)) => {
1723                        Value::Int(i.clamp(min_i, max_i))
1724                    }
1725                    _ => {
1726                        return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1727                    }
1728                }
1729            }
1730
1731            IntrinsicFunction::IntMin => {
1732                let max_value = self.evaluate_expression(&arguments[0])?;
1733                match (value_ref.borrow().clone(), max_value) {
1734                    (Value::Int(i), Value::Int(min_i)) => Value::Int(i.min(min_i)),
1735                    _ => {
1736                        return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1737                    }
1738                }
1739            }
1740
1741            IntrinsicFunction::IntMax => {
1742                let max_value = self.evaluate_expression(&arguments[0])?;
1743                match (value_ref.borrow().clone(), max_value) {
1744                    (Value::Int(i), Value::Int(max_i)) => Value::Int(i.max(max_i)),
1745                    _ => {
1746                        return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1747                    }
1748                }
1749            }
1750
1751            IntrinsicFunction::IntRnd => match value_ref.borrow().clone() {
1752                Value::Int(i) => Value::Int(squirrel_prng::squirrel_noise5(i as u32, 0) as i32),
1753                _ => {
1754                    return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1755                }
1756            },
1757
1758            IntrinsicFunction::IntToFloat => match value_ref.borrow().clone() {
1759                Value::Int(i) => Value::Float(Fp::from(i as i16)),
1760                _ => {
1761                    return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1762                }
1763            },
1764
1765            IntrinsicFunction::StringLen => match value_ref.borrow().clone() {
1766                Value::String(s) => Value::Int(s.len().try_into().expect("string len overflow")),
1767                _ => {
1768                    return Err(self.create_err(ExecuteErrorKind::ExpectedString, node));
1769                }
1770            },
1771
1772            IntrinsicFunction::Float2Magnitude => match value_ref.borrow().clone() {
1773                Value::Tuple(_tuple_ref, values) => {
1774                    if values.len() != 2 {
1775                        return Err(self.create_err(
1776                            ExecuteErrorKind::WrongNumberOfArguments(2, values.len()),
1777                            &node,
1778                        ));
1779                    }
1780                    match (
1781                        values[0].as_ref().borrow().clone(),
1782                        values[1].as_ref().borrow().clone(),
1783                    ) {
1784                        (Value::Float(a), Value::Float(b)) => {
1785                            let a_raw: i64 = a.inner() as i64;
1786                            let b_raw: i64 = b.inner() as i64;
1787
1788                            let i64_magnitude = i64_sqrt(a_raw * a_raw + b_raw * b_raw);
1789
1790                            let new_fp = Fp::from_raw(
1791                                i32::try_from(i64_magnitude).expect("wrong with i64_sqrt"),
1792                            );
1793                            Value::Float(new_fp)
1794                        }
1795                        _ => {
1796                            return Err(
1797                                self.create_err(ExecuteErrorKind::ExpectedTwoFloatTuple, node)
1798                            );
1799                        }
1800                    }
1801                }
1802                _ => {
1803                    return Err(self.create_err(ExecuteErrorKind::ExpectedTwoFloatTuple, node));
1804                }
1805            },
1806
1807            _ => todo!("{intrinsic_function:?} not implemented"),
1808        };
1809
1810        Ok(val)
1811    }
1812
1813    #[allow(clippy::too_many_lines)]
1814    fn eval_chain(
1815        &mut self,
1816        node: &Node,
1817        start: &Expression,
1818        parts: &[Postfix],
1819    ) -> Result<ValueRef, ExecuteError> {
1820        let (mut val_ref, mut is_mutable) = match &start.kind {
1821            ExpressionKind::VariableAccess(start_var) => {
1822                let start_variable_value = self.current_block_scopes.get_var(&start_var);
1823
1824                match start_variable_value {
1825                    VariableValue::Value(value) => {
1826                        assert_ne!(*value, Value::Unit);
1827                        (Rc::new(RefCell::new(value.clone())), false)
1828                    }
1829                    VariableValue::Reference(value_ref) => {
1830                        assert_ne!(value_ref.borrow().clone(), Value::Unit);
1831                        (value_ref.clone(), true)
1832                    }
1833                }
1834            }
1835            _ => (
1836                Rc::new(RefCell::new(self.evaluate_expression(start)?)),
1837                false,
1838            ),
1839        };
1840
1841        let mut is_uncertain = false;
1842        let mut is_undefined = false;
1843
1844        for part in parts {
1845            if let PostfixKind::NoneCoalesce(default_expression) = &part.kind {
1846                val_ref = {
1847                    let borrowed = val_ref.borrow();
1848
1849                    match borrowed.clone() {
1850                        Value::Option(found_option) => match found_option {
1851                            Some(some_value) => some_value,
1852                            _ => {
1853                                let default_value = self.evaluate_expression(default_expression)?;
1854                                Rc::new(RefCell::new(default_value))
1855                            }
1856                        },
1857                        _ => {
1858                            return Err(
1859                                self.create_err(ExecuteErrorKind::ExpectedOptional, &part.node)
1860                            );
1861                        }
1862                    }
1863                };
1864
1865                is_mutable = false;
1866                is_uncertain = false;
1867                is_undefined = false;
1868            } else if is_undefined {
1869                continue;
1870            }
1871            match &part.kind {
1872                PostfixKind::NoneCoalesce(_default_expression) => {
1873                    // Handled earlier
1874                }
1875                PostfixKind::StructField(expected_struct_type, index) => {
1876                    let (encountered_struct_type, fields) = {
1877                        let brw = val_ref.borrow();
1878                        let (struct_ref, fields_ref) = brw.expect_anon_struct().map_err(|_| {
1879                            self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1880                        })?;
1881                        (struct_ref.clone(), fields_ref.clone())
1882                    };
1883
1884                    assert!(same_anon_struct_ref(
1885                        &encountered_struct_type,
1886                        expected_struct_type
1887                    ));
1888                    val_ref = fields[*index].clone();
1889                }
1890                PostfixKind::ArrayIndex(expected_element_type, index_expr) => {
1891                    let (encountered_element_type, fields) = {
1892                        let brw = val_ref.borrow();
1893                        let (array_ref, fields_ref) = brw.expect_array().map_err(|_| {
1894                            self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1895                        })?;
1896                        (array_ref.clone(), fields_ref.clone())
1897                    };
1898                    assert!(expected_element_type.compatible_with(&encountered_element_type));
1899
1900                    let index =
1901                        self.evaluate_expression(index_expr)?
1902                            .expect_int()
1903                            .map_err(|_| {
1904                                self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1905                            })? as usize;
1906                    if index >= fields.len() {
1907                        return Err(self.create_err(ExecuteErrorKind::IndexOutOfBounds, &part.node));
1908                    }
1909                    val_ref = fields[index].clone();
1910                }
1911                PostfixKind::MapIndex(_key_type, _value_type, key_expr) => {
1912                    let seq_map = {
1913                        let brw = val_ref.borrow();
1914                        let (key_type, value_type, seq_map) = brw.expect_map().map_err(|_| {
1915                            self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1916                        })?;
1917                        seq_map.clone()
1918                    };
1919                    let key_val = self.evaluate_expression(key_expr)?;
1920
1921                    val_ref = Rc::new(RefCell::new(Value::Option(seq_map.get(&key_val).cloned())));
1922                }
1923                PostfixKind::ExternalTypeIndexRef(_rust_type_ref, map_expr) => {
1924                    let key_expr_value = self.evaluate_expression(map_expr)?;
1925                    val_ref = {
1926                        match key_expr_value.downcast_rust::<SparseValueId>() {
1927                            Some(found_sparse_id) => {
1928                                match val_ref.borrow_mut().downcast_rust::<SparseValueMap>() {
1929                                    Some(sparse_value_map) => wrap_in_option(
1930                                        sparse_value_map
1931                                            .borrow_mut()
1932                                            .get(&found_sparse_id.borrow()),
1933                                    ),
1934                                    _ => {
1935                                        panic!("internal error");
1936                                    }
1937                                }
1938                            }
1939                            _ => {
1940                                panic!("todo");
1941                            }
1942                        }
1943                    };
1944                }
1945                PostfixKind::MemberCall(function_ref, arguments) => {
1946                    let val =
1947                        self.eval_member_call(node, &val_ref, is_mutable, function_ref, arguments)?;
1948
1949                    val_ref = Rc::new(RefCell::new(val));
1950                    is_mutable = false;
1951                }
1952                PostfixKind::FunctionCall(arguments) => {
1953                    let val = self.eval_function_call(node, &val_ref, arguments)?;
1954
1955                    val_ref = Rc::new(RefCell::new(val));
1956                    is_mutable = false;
1957                }
1958                PostfixKind::OptionUnwrap => {
1959                    val_ref = {
1960                        let borrowed = val_ref.borrow();
1961
1962                        match borrowed.clone() {
1963                            Value::Option(found_option) => match found_option {
1964                                Some(some_value) => some_value,
1965                                _ => {
1966                                    is_undefined = true;
1967
1968                                    Rc::new(RefCell::new(Value::Option(None)))
1969                                }
1970                            },
1971                            _ => {
1972                                return Err(
1973                                    self.create_err(ExecuteErrorKind::ExpectedOptional, &part.node)
1974                                );
1975                            }
1976                        }
1977                    };
1978
1979                    is_mutable = false;
1980                    is_uncertain = true;
1981                }
1982                PostfixKind::IntrinsicCall(intrinsic_fn, arguments) => {
1983                    val_ref = Rc::new(RefCell::new(self.eval_intrinsic_postfix(
1984                        &part.node,
1985                        &val_ref,
1986                        intrinsic_fn,
1987                        arguments,
1988                    )?));
1989                    is_mutable = false;
1990                }
1991                PostfixKind::IntrinsicCallEx(_intrinsic_fn, _arguments) => {
1992                    //val_ref = Rc::new(RefCell::new(self.eval_intrinsic_postfix_ex(&val_ref, part, intrinsic_fn, arguments)?));
1993                    is_mutable = false;
1994                }
1995                _ => {}
1996            }
1997        }
1998
1999        if is_uncertain {
2000            let binding = val_ref.borrow().clone();
2001            match binding {
2002                Value::Option(_) => {}
2003                _ => {
2004                    val_ref = Rc::new(RefCell::new(Value::Option(Some(val_ref))));
2005                }
2006            }
2007        }
2008
2009        Ok(val_ref)
2010    }
2011
2012    fn eval_function_call(
2013        &mut self,
2014        node: &Node,
2015        function_val: &ValueRef,
2016        arguments: &[ArgumentExpressionOrLocation],
2017    ) -> Result<Value, ExecuteError> {
2018        let resolved_fn = match function_val.borrow().clone() {
2019            Value::InternalFunction(x) => Function::Internal(x.clone()),
2020            Value::ExternalFunction(external_fn) => Function::External(external_fn.clone()),
2021            _ => panic!("no function to call"),
2022        };
2023
2024        let parameters = &resolved_fn.signature().parameters;
2025        // Check total number of parameters (including self)
2026        assert_eq!(
2027            arguments.len(),
2028            parameters.len(),
2029            "wrong number of arguments"
2030        );
2031
2032        let resolved_arguments = self.evaluate_args(&arguments)?;
2033
2034        let result_val = match &resolved_fn {
2035            Function::Internal(internal_function) => {
2036                self.push_function_scope();
2037
2038                self.bind_parameters(node, &parameters, &resolved_arguments)?;
2039                let result = self.evaluate_expression(&internal_function.body)?;
2040                self.pop_function_scope();
2041
2042                result
2043            }
2044            Function::External(external_func) => {
2045                let mut func = self
2046                    .externals
2047                    .external_functions_by_id
2048                    .get(&external_func.id)
2049                    .expect("member call: external function missing")
2050                    .borrow_mut();
2051                (func.func)(&resolved_arguments, self.context)?
2052            }
2053        };
2054
2055        Ok(result_val)
2056    }
2057
2058    #[inline]
2059    fn eval_member_call(
2060        &mut self,
2061        node: &Node,
2062        self_value_ref: &ValueRef,
2063        is_mutable: bool,
2064        function_ref: &FunctionRef,
2065        arguments: &[ArgumentExpressionOrLocation],
2066    ) -> Result<Value, ExecuteError> {
2067        let parameters = &function_ref.signature().parameters;
2068
2069        let self_var_value = if parameters[0].is_mutable {
2070            if !is_mutable {
2071                return Err(self.create_err(ExecuteErrorKind::ArgumentIsNotMutable, &node));
2072            }
2073            VariableValue::Reference(self_value_ref.clone())
2074        } else {
2075            VariableValue::Value(self_value_ref.borrow().clone())
2076        };
2077
2078        let mut member_call_arguments = Vec::new();
2079        member_call_arguments.push(self_var_value); // Add self as first argument
2080        member_call_arguments.extend(self.evaluate_args(&arguments)?);
2081
2082        // Check total number of parameters (including self)
2083        if member_call_arguments.len() != parameters.len() {
2084            panic!("wrong number of arguments")
2085        }
2086
2087        let result_val = match &**function_ref {
2088            Function::Internal(internal_function) => {
2089                self.push_function_scope();
2090                self.bind_parameters(node, &parameters, &member_call_arguments)?;
2091                let result = self.evaluate_expression(&internal_function.body)?;
2092                self.pop_function_scope();
2093
2094                result
2095            }
2096            Function::External(external_func) => {
2097                let mut func = self
2098                    .externals
2099                    .external_functions_by_id
2100                    .get(&external_func.id)
2101                    .expect("member call: external function missing")
2102                    .borrow_mut();
2103                (func.func)(&member_call_arguments, self.context)?
2104            }
2105        };
2106
2107        Ok(result_val)
2108    }
2109
2110    fn eval_guard(&mut self, node: &Node, guards: &[Guard]) -> Result<Value, ExecuteError> {
2111        for guard in guards {
2112            let should_evaluate = if let Some(found_clause) = &guard.condition {
2113                self.evaluate_expression(&found_clause.expression)?
2114                    .is_truthy()?
2115            } else {
2116                true
2117            };
2118
2119            if should_evaluate {
2120                return self.evaluate_expression(&guard.result);
2121            }
2122        }
2123
2124        Err(self.create_err(ExecuteErrorKind::MustHaveGuardArmThatMatches, &node))
2125    }
2126
2127    #[inline(always)]
2128    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
2129    fn eval_match(&mut self, resolved_match: &Match) -> Result<Value, ExecuteError> {
2130        let actual_value = self.evaluate_mut_or_immutable_expression(&resolved_match.expression)?;
2131        let value_ref = actual_value.to_value_ref();
2132
2133        for arm in &resolved_match.arms {
2134            match &arm.pattern {
2135                Pattern::Wildcard(_node) => return self.evaluate_expression(&arm.expression),
2136                Pattern::Normal(normal_pattern, maybe_guard) => {
2137                    if let Some(found_guard) = maybe_guard {
2138                        if !self
2139                            .evaluate_expression(&found_guard.expression)?
2140                            .is_truthy()?
2141                        // TODO: ERROR HANDLING
2142                        {
2143                            continue;
2144                        }
2145                    }
2146
2147                    let immutable_value = actual_value.to_value();
2148
2149                    match &normal_pattern {
2150                        NormalPattern::PatternList(elements) => {
2151                            return Ok(self.eval_normal_pattern_list(
2152                                elements,
2153                                &arm.expression,
2154                                value_ref.clone(),
2155                            )?);
2156                        }
2157                        NormalPattern::EnumPattern(enum_variant_ref, pattern_elements) => {
2158                            let maybe_found_match = self.eval_normal_pattern_enum(
2159                                pattern_elements.as_ref(),
2160                                &arm.expression,
2161                                enum_variant_ref,
2162                                value_ref.clone(),
2163                            )?;
2164
2165                            if let Some(found_match) = maybe_found_match {
2166                                return Ok(found_match);
2167                            }
2168                        }
2169
2170                        NormalPattern::Literal(lit) => match (lit, &immutable_value) {
2171                            (Literal::IntLiteral(a), Value::Int(b)) if a == b => {
2172                                return self.evaluate_expression(&arm.expression);
2173                            }
2174                            (Literal::FloatLiteral(a), Value::Float(b)) if a == b => {
2175                                return self.evaluate_expression(&arm.expression);
2176                            }
2177                            (Literal::StringLiteral(a), Value::String(b)) if *a == *b => {
2178                                return self.evaluate_expression(&arm.expression);
2179                            }
2180                            (Literal::BoolLiteral(a), Value::Bool(b)) if a == b => {
2181                                return self.evaluate_expression(&arm.expression);
2182                            }
2183                            (
2184                                Literal::TupleLiteral(_a_type_ref, a_values),
2185                                Value::Tuple(_b_type_ref, b_values),
2186                            ) if self.expressions_equal_to_values(&a_values, &b_values)? => {
2187                                return self.evaluate_expression(&arm.expression);
2188                            }
2189                            _ => {}
2190                        },
2191                    }
2192                }
2193            }
2194        }
2195
2196        panic!("must match one of the match arms!");
2197    }
2198
2199    fn eval_normal_pattern_list(
2200        &mut self,
2201        elements: &[PatternElement],
2202        expression_to_evaluate: &Expression,
2203        value_ref: ValueRef,
2204    ) -> Result<Value, ExecuteError> {
2205        // Handle single variable/wildcard patterns that match any value
2206        if elements.len() == 1 {
2207            return match &elements[0] {
2208                PatternElement::Variable(var_ref)
2209                | PatternElement::VariableWithFieldIndex(var_ref, _) => {
2210                    self.push_block_scope();
2211                    self.current_block_scopes
2212                        .initialize_var_mut(var_ref, value_ref);
2213                    let result = self.evaluate_expression(expression_to_evaluate);
2214                    self.pop_block_scope();
2215                    result
2216                }
2217                PatternElement::Wildcard(_) => {
2218                    // Wildcard matches anything
2219                    self.evaluate_expression(expression_to_evaluate)
2220                }
2221            };
2222        }
2223
2224        if let Value::Tuple(_tuple_type_ref, values) = value_ref.borrow_mut().clone() {
2225            assert_eq!(
2226                elements.len(),
2227                values.len(),
2228                "must use all elements in tuple"
2229            );
2230            self.push_block_scope();
2231
2232            for (element, _inside_value) in elements.iter().zip(values.iter()) {
2233                match element {
2234                    PatternElement::Variable(var_ref) => {
2235                        self.current_block_scopes
2236                            .initialize_var_mut(var_ref, value_ref.clone());
2237                    }
2238                    PatternElement::VariableWithFieldIndex(var_ref, _) => {
2239                        self.current_block_scopes
2240                            .initialize_var_mut(var_ref, value_ref.clone());
2241                    }
2242                    PatternElement::Wildcard(_) => {
2243                        // Skip wildcards
2244                        continue;
2245                    }
2246                }
2247            }
2248
2249            let result = self.evaluate_expression(expression_to_evaluate);
2250            self.pop_block_scope();
2251
2252            return result;
2253        }
2254        panic!("should not get here")
2255    }
2256
2257    fn eval_normal_pattern_enum(
2258        &mut self,
2259        maybe_elements: Option<&Vec<PatternElement>>,
2260        expression_to_evaluate: &Expression,
2261        variant_ref: &EnumVariantTypeRef,
2262        value_ref: ValueRef,
2263    ) -> Result<Option<Value>, ExecuteError> {
2264        match value_ref.borrow_mut().clone() {
2265            Value::EnumVariantTuple(value_tuple_type, values) => {
2266                // First check if the variant types match
2267                if variant_ref.common().number != value_tuple_type.common.number {
2268                    return Ok(None); // Try next pattern
2269                }
2270
2271                if let Some(elements) = maybe_elements {
2272                    assert_eq!(elements.len(), values.len());
2273                    self.push_block_scope();
2274
2275                    for (element, value) in elements.iter().zip(values.iter()) {
2276                        match element {
2277                            PatternElement::Variable(var_ref) => {
2278                                self.current_block_scopes
2279                                    .initialize_var_mut(var_ref, value.clone());
2280                            }
2281                            PatternElement::VariableWithFieldIndex(var_ref, _) => {
2282                                self.current_block_scopes
2283                                    .initialize_var_mut(var_ref, value.clone());
2284                            }
2285                            PatternElement::Wildcard(_) => continue,
2286                        }
2287                    }
2288
2289                    let result = self.evaluate_expression(&expression_to_evaluate);
2290                    self.pop_block_scope();
2291                    return Ok(Option::from(result?));
2292                } else {
2293                    panic!("not work");
2294                }
2295            }
2296            Value::EnumVariantStruct(value_enum_struct_type, values) => {
2297                info!(
2298                    ?value_enum_struct_type,
2299                    ?variant_ref,
2300                    "comparing enum variant struct match arm"
2301                );
2302                if value_enum_struct_type.common.number == variant_ref.common().number {
2303                    info!(?value_enum_struct_type, ?variant_ref, "FOUND!");
2304                    if let Some(elements) = maybe_elements {
2305                        self.push_block_scope();
2306
2307                        for element in elements {
2308                            if let PatternElement::VariableWithFieldIndex(var_ref, field_index) =
2309                                element
2310                            {
2311                                let value = &values[*field_index];
2312                                info!(?value, "setting match arm variable");
2313                                self.current_block_scopes.init_var_ref(var_ref, value);
2314                            }
2315                        }
2316
2317                        let result = self.evaluate_expression(&expression_to_evaluate);
2318                        self.pop_block_scope();
2319                        return Ok(Some(result?));
2320                    }
2321                }
2322            }
2323
2324            Value::EnumVariantSimple(value_variant_ref) => {
2325                if value_variant_ref.common.number == variant_ref.common().number
2326                    && maybe_elements.is_none()
2327                {
2328                    return Ok(Some(self.evaluate_expression(&expression_to_evaluate)?));
2329                }
2330            }
2331            _ => {
2332                panic!("could not find it")
2333            }
2334        }
2335
2336        Ok(None)
2337    }
2338
2339    #[inline(always)]
2340    const fn modulo(a: i32, b: i32) -> i32 {
2341        ((a % b) + b) % b
2342    }
2343
2344    #[inline(always)]
2345    const fn modulo_fp(a: Fp, b: Fp) -> Fp {
2346        let raw = ((a.inner() % b.inner()) + b.inner()) % b.inner();
2347        Fp::from_raw(raw)
2348    }
2349
2350    #[allow(clippy::too_many_lines)]
2351    fn evaluate_binary_op(
2352        &self,
2353        node: &Node,
2354        left_val: Value,
2355        op: &BinaryOperatorKind,
2356        right_val: Value,
2357    ) -> Result<Value, ExecuteError> {
2358        let result: Value = match (&left_val, op, &right_val) {
2359            // Integer operations
2360            (Value::Int(a), BinaryOperatorKind::Add, Value::Int(b)) => Value::Int(a + b),
2361            (Value::Int(a), BinaryOperatorKind::Subtract, Value::Int(b)) => Value::Int(a - b),
2362            (Value::Int(a), BinaryOperatorKind::Multiply, Value::Int(b)) => Value::Int(a * b),
2363            (Value::Int(a), BinaryOperatorKind::Divide, Value::Int(b)) => {
2364                if *b == 0 {
2365                    return Err(self.create_err(ExecuteErrorKind::DivideByZero, node));
2366                }
2367                Value::Int(a / b)
2368            }
2369            (Value::Int(a), BinaryOperatorKind::Modulo, Value::Int(b)) => {
2370                Value::Int(Self::modulo(*a, *b))
2371            }
2372            (Value::Int(a), BinaryOperatorKind::Equal, Value::Int(b)) => Value::Bool(a == b),
2373            (Value::Int(a), BinaryOperatorKind::NotEqual, Value::Int(b)) => Value::Bool(a != b),
2374            (Value::Int(a), BinaryOperatorKind::LessThan, Value::Int(b)) => Value::Bool(a < b),
2375            (Value::Int(a), BinaryOperatorKind::GreaterThan, Value::Int(b)) => Value::Bool(a > b),
2376            (Value::Int(a), BinaryOperatorKind::LessEqual, Value::Int(b)) => Value::Bool(a <= b),
2377            (Value::Int(a), BinaryOperatorKind::GreaterEqual, Value::Int(b)) => Value::Bool(a >= b),
2378
2379            // Float operations
2380            (Value::Float(a), BinaryOperatorKind::Equal, Value::Float(b)) => Value::Bool(a == b),
2381            (Value::Float(a), BinaryOperatorKind::NotEqual, Value::Float(b)) => Value::Bool(a != b),
2382
2383            (Value::Float(a), BinaryOperatorKind::Add, Value::Float(b)) => Value::Float(*a + *b),
2384            (Value::Float(a), BinaryOperatorKind::Subtract, Value::Float(b)) => {
2385                Value::Float(*a - *b)
2386            }
2387            (Value::Float(a), BinaryOperatorKind::Multiply, Value::Float(b)) => {
2388                Value::Float(*a * *b)
2389            }
2390            (Value::Float(a), BinaryOperatorKind::Divide, Value::Float(b)) => {
2391                if b.abs().inner() <= 400 {
2392                    return Err(self.create_err(ExecuteErrorKind::DivideByZero, node));
2393                }
2394                Value::Float(*a / *b)
2395            }
2396            (Value::Float(a), BinaryOperatorKind::Modulo, Value::Float(b)) => {
2397                Value::Float(Self::modulo_fp(*a, *b))
2398            }
2399
2400            (Value::Float(a), BinaryOperatorKind::GreaterThan, Value::Float(b)) => {
2401                Value::Bool(a > b)
2402            }
2403            (Value::Float(a), BinaryOperatorKind::GreaterEqual, Value::Float(b)) => {
2404                Value::Bool(a >= b)
2405            }
2406            (Value::Float(a), BinaryOperatorKind::LessThan, Value::Float(b)) => Value::Bool(a < b),
2407            (Value::Float(a), BinaryOperatorKind::LessEqual, Value::Float(b)) => {
2408                Value::Bool(a <= b)
2409            }
2410
2411            // Boolean operations
2412            (Value::Bool(a), BinaryOperatorKind::LogicalAnd, Value::Bool(b)) => {
2413                Value::Bool(*a && *b)
2414            }
2415            (Value::Bool(a), BinaryOperatorKind::LogicalOr, Value::Bool(b)) => {
2416                Value::Bool(*a || *b)
2417            }
2418
2419            // Comparison operations
2420
2421            // RustType
2422            (Value::RustValue(_, left), BinaryOperatorKind::Equal, Value::RustValue(_, right)) => {
2423                let left_borrow = left.borrow();
2424                let right_borrow = right.borrow();
2425                let equal = left_borrow.eq_dyn(&**right_borrow);
2426                Value::Bool(equal)
2427            }
2428            (
2429                Value::RustValue(_, left),
2430                BinaryOperatorKind::NotEqual,
2431                Value::RustValue(_, right),
2432            ) => {
2433                let left_borrow = left.borrow();
2434                let right_borrow = right.borrow();
2435                let equal = left_borrow.eq_dyn(&**right_borrow);
2436                Value::Bool(!equal)
2437            }
2438
2439            // String operations
2440            (Value::String(a), BinaryOperatorKind::Add, Value::String(b)) => {
2441                Value::String(a.to_owned() + b)
2442            }
2443            (Value::String(a), BinaryOperatorKind::Equal, Value::String(b)) => Value::Bool(a == b),
2444
2445            (Value::String(a), BinaryOperatorKind::Add, Value::Int(b)) => {
2446                Value::String(a.to_owned() + &(*b).to_string())
2447            }
2448            (Value::Int(a), BinaryOperatorKind::Add, Value::String(b)) => {
2449                Value::String(a.to_string() + b)
2450            }
2451
2452            // Enum
2453            (
2454                Value::EnumVariantSimple(a),
2455                BinaryOperatorKind::Equal,
2456                Value::EnumVariantSimple(b),
2457            ) => Value::Bool(a == b),
2458            (
2459                Value::EnumVariantSimple(a),
2460                BinaryOperatorKind::NotEqual,
2461                Value::EnumVariantSimple(b),
2462            ) => Value::Bool(a != b),
2463
2464            // Bool
2465            (Value::Bool(a), BinaryOperatorKind::Equal, Value::Bool(b)) => Value::Bool(a == b),
2466            (Value::Bool(a), BinaryOperatorKind::NotEqual, Value::Bool(b)) => Value::Bool(a != b),
2467
2468            (Value::Option(a), BinaryOperatorKind::Equal, Value::Option(b)) => Value::Bool(a == b),
2469
2470            _ => {
2471                error!(?op, "invalid binary operation!!");
2472                panic!("invalid binary operation"); // TODO: improve error handling
2473            }
2474        };
2475
2476        Ok(result)
2477    }
2478
2479    fn evaluate_unary_op(
2480        &self,
2481        node: &Node,
2482        op: &UnaryOperatorKind,
2483        val: Value,
2484    ) -> Result<Value, ExecuteError> {
2485        match (op, val) {
2486            (UnaryOperatorKind::Negate, Value::Int(n)) => Ok(Value::Int(-n)),
2487            (UnaryOperatorKind::Negate, Value::Float(n)) => Ok(Value::Float(-n)),
2488            (UnaryOperatorKind::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
2489            _ => Err(self.create_err(ExecuteErrorKind::DivideByZero, node)),
2490        }
2491    }
2492
2493    fn expressions_equal_to_values(
2494        &mut self,
2495        p0: &[Expression],
2496        p1: &[ValueRef],
2497    ) -> Result<bool, ExecuteError> {
2498        for (a, b_value) in p0.iter().zip(p1.iter()) {
2499            let a_value = self.evaluate_expression(a)?;
2500
2501            if a_value != *b_value.borrow() {
2502                return Ok(false);
2503            }
2504        }
2505
2506        Ok(true)
2507    }
2508
2509    #[inline(always)]
2510    fn apply_compound_operator(
2511        &self,
2512        node: &Node,
2513        target: &mut Value,
2514        operator: &CompoundOperatorKind,
2515        source: &Value,
2516    ) -> Result<(), ExecuteError> {
2517        match operator {
2518            CompoundOperatorKind::Mul => {
2519                *target = self.evaluate_binary_op(
2520                    node,
2521                    target.clone(),
2522                    &BinaryOperatorKind::Multiply,
2523                    source.clone(),
2524                )?;
2525            }
2526            CompoundOperatorKind::Div => {
2527                *target = self.evaluate_binary_op(
2528                    node,
2529                    target.clone(),
2530                    &BinaryOperatorKind::Divide,
2531                    source.clone(),
2532                )?;
2533            }
2534            CompoundOperatorKind::Add => {
2535                *target = self.evaluate_binary_op(
2536                    node,
2537                    target.clone(),
2538                    &BinaryOperatorKind::Add,
2539                    source.clone(),
2540                )?;
2541            }
2542            CompoundOperatorKind::Sub => {
2543                *target = self.evaluate_binary_op(
2544                    node,
2545                    target.clone(),
2546                    &BinaryOperatorKind::Subtract,
2547                    source.clone(),
2548                )?;
2549            }
2550            CompoundOperatorKind::Modulo => {
2551                *target = self.evaluate_binary_op(
2552                    node,
2553                    target.clone(),
2554                    &BinaryOperatorKind::Modulo,
2555                    source.clone(),
2556                )?;
2557            }
2558        }
2559        Ok(())
2560    }
2561
2562    /*
2563        fn evaluate_range(
2564            &mut self,
2565            min_expr: &Expression,
2566            max_expr: &Expression,
2567        ) -> Result<(i32, i32), ExecuteError> {
2568            let min_value = self.evaluate_expression_int(&min_expr)?;
2569            let max_value = self.evaluate_expression_int(&max_expr)?;
2570
2571            Ok((min_value, max_value))
2572        }
2573
2574        fn calculate_range(
2575            start_val: i32,
2576            end_val: i32,
2577            len: usize,
2578            mode: &RangeMode,
2579        ) -> (usize, usize) {
2580            let adjusted_min = if start_val < 0 {
2581                len + start_val as usize
2582            } else {
2583                start_val as usize
2584            };
2585
2586            let mut adjusted_max = if end_val < 0 {
2587                len + end_val as usize
2588            } else {
2589                end_val as usize
2590            };
2591            if RangeMode::Inclusive == mode.clone() {
2592                adjusted_max += 1;
2593            }
2594
2595            (adjusted_min, adjusted_max)
2596        }
2597
2598        fn evaluate_and_calculate_range(
2599            &mut self,
2600            min_expr: &Expression,
2601            max_expr: &Expression,
2602            mode: &RangeMode,
2603            len: usize,
2604        ) -> Result<(usize, usize), ExecuteError> {
2605            let (start_val, end_val) = self.evaluate_range(min_expr, max_expr)?;
2606
2607            Ok(Self::calculate_range(start_val, end_val, len, mode))
2608        }
2609
2610        #[inline]
2611        fn evaluate_array_range_access(
2612            &mut self,
2613            base_expr: &Expression,
2614            array_type_ref: &ArrayTypeRef,
2615            min_expr: &Expression,
2616            max_expr: &Expression,
2617            mode: &RangeMode,
2618        ) -> Result<Value, ExecuteError> {
2619            let array_value = self.evaluate_expression(base_expr)?;
2620
2621            if let Value::Vec(_, values) = array_value {
2622                let (adjusted_start, adjusted_end) =
2623                    self.evaluate_and_calculate_range(min_expr, max_expr, mode, values.len())?;
2624
2625                let slice = &values.as_slice()[adjusted_start..adjusted_end];
2626                Ok(Value::Vec(array_type_ref.clone(), Vec::from(slice)))
2627            } else {
2628                Err(self.create_err(ExecuteErrorKind::NotAnArray, &base_expr.node))
2629            }
2630        }
2631
2632        fn evaluate_expression_int(
2633            &mut self,
2634            int_expr: &Expression,
2635        ) -> Result<i32, ExecuteError> {
2636            let v = self.evaluate_expression(&int_expr)?;
2637
2638            if let Value::Int(i) = v {
2639                Ok(i)
2640            } else {
2641                Err(self.create_err(ExecuteErrorKind::ExpectedInt, &int_expr.node))
2642            }
2643        }
2644    */
2645
2646    /*
2647    fn evaluate_string_range_access(
2648        &mut self,
2649        string_expr: &Expression,
2650        start_expr: &Expression,
2651        end_expr: &Expression,
2652        mode: &RangeMode,
2653    ) -> Result<Value, ExecuteError> {
2654        let string_value = self.evaluate_expression(string_expr)?;
2655
2656        if let Value::String(string) = string_value {
2657            let (adjusted_start, adjusted_end) =
2658                self.evaluate_and_calculate_range(start_expr, end_expr, mode, string.len())?;
2659            Ok(Value::String(
2660                string[adjusted_start..adjusted_end].to_string(),
2661            ))
2662        } else {
2663            Err(self.create_err(ExecuteErrorKind::ExpectedString, &string_expr.node))
2664        }
2665    }
2666
2667     */
2668
2669    fn create_err(&self, kind: ExecuteErrorKind, node: &Node) -> ExecuteError {
2670        ExecuteError {
2671            node: node.clone(),
2672            kind,
2673        }
2674    }
2675
2676    fn evaluate_intrinsic_mut(
2677        &mut self,
2678        node: &Node,
2679        intrinsic_fn: &IntrinsicFunction,
2680        location: &SingleMutLocationExpression,
2681        arguments: &Vec<Expression>,
2682    ) -> Result<Value, ExecuteError> {
2683        let val = match intrinsic_fn {
2684            IntrinsicFunction::VecSelfPush => {
2685                let source_val = self.evaluate_expression(&arguments[0])?;
2686                let array_val_ref = self.evaluate_location(&location.0)?;
2687
2688                match &mut *array_val_ref.borrow_mut() {
2689                    Value::Vec(_type_id, vector) => {
2690                        vector.push(Rc::new(RefCell::new(source_val)));
2691                    }
2692                    _ => {
2693                        Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &node))?;
2694                    }
2695                }
2696                //array_val_ref.borrow().clone()
2697                Value::Unit
2698            }
2699            IntrinsicFunction::VecSelfExtend => {
2700                let source_val = self.evaluate_expression(&arguments[0])?;
2701
2702                let array_val_ref = self.evaluate_location(&location.0)?;
2703                match &mut *array_val_ref.borrow_mut() {
2704                    Value::Vec(_type_id, vector) => match source_val {
2705                        Value::Vec(_, items) => {
2706                            vector.extend(items);
2707                        }
2708                        _ => {
2709                            Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &node))?;
2710                        }
2711                    },
2712                    _ => {
2713                        todo!("handle error")
2714                    }
2715                }
2716
2717                // array_val_ref.borrow().clone()
2718                Value::Unit
2719            }
2720            _ => return Err(self.create_err(ExecuteErrorKind::UnknownMutIntrinsic, &node)),
2721        };
2722
2723        Ok(val)
2724    }
2725}
2726
2727#[inline]
2728#[must_use]
2729pub fn i64_sqrt(v: i64) -> i64 {
2730    assert!(v >= 0, "negative numbers are undefined for sqrt() {v}");
2731
2732    if v == 0 {
2733        return v;
2734    }
2735
2736    const MAX_ITERATIONS: usize = 40;
2737    const TOLERANCE: i64 = 2;
2738
2739    let mut guess = v / 2;
2740
2741    for _ in 0..MAX_ITERATIONS {
2742        let next_guess = (guess + v / guess) / 2;
2743
2744        // Check if the change is within the tolerance level
2745        if (next_guess - guess).abs() <= TOLERANCE {
2746            return next_guess;
2747        }
2748
2749        guess = next_guess;
2750    }
2751
2752    guess // Return the last guess if convergence wasn't fully reached
2753}
2754
2755#[allow(unused)]
2756pub fn values_to_value_refs(values: &[Value]) -> Vec<ValueRef> {
2757    let mut items = Vec::new();
2758
2759    for x in values.iter().cloned() {
2760        items.push(Rc::new(RefCell::new(x)));
2761    }
2762
2763    items
2764}
2765
2766pub fn values_to_value_refs_owned(values: Vec<Value>) -> Vec<ValueRef> {
2767    values
2768        .into_iter()
2769        .map(|x| Rc::new(RefCell::new(x)))
2770        .collect()
2771}
2772
2773pub fn wrap_in_option(maybe: Option<&ValueRef>) -> ValueRef {
2774    match maybe {
2775        None => Rc::new(RefCell::new(Value::Option(None))),
2776        Some(x) => Rc::new(RefCell::new(Value::Option(Some(x.clone())))),
2777    }
2778}