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::{SPARSE_ID_TYPE_ID, SPARSE_TYPE_ID, 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, ExternalType, Type, 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::IntrinsicCallGeneric(intrinsic, type_parameters, arguments) => {
1011                self.evaluate_intrinsic_generic(&expr.node, intrinsic, type_parameters, arguments)?
1012            }
1013
1014            ExpressionKind::MapAssignment(map, index, value) => {
1015                let map_val = self.evaluate_location(&map.0)?;
1016                let index_val = self.evaluate_expression(index)?;
1017                let new_val = self.evaluate_expression(value)?;
1018
1019                match &mut *map_val.borrow_mut() {
1020                    Value::Map(_key_type, _value_type, elements) => {
1021                        elements
1022                            .insert(index_val, Rc::new(RefCell::new(new_val)))
1023                            .map_err(|_| {
1024                                self.create_err(ExecuteErrorKind::MapKeyAlreadyExists, &expr.node)
1025                            })?;
1026                    }
1027                    _ => {
1028                        Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &expr.node))?;
1029                    }
1030                }
1031
1032                Value::Unit
1033            }
1034
1035            // ------------- LOOKUP ---------------------
1036            ExpressionKind::ConstantAccess(constant) => {
1037                self.constants.lookup_constant_value(constant.id).clone()
1038            }
1039
1040            ExpressionKind::AssignmentSlice(_mut_location, _source) => todo!(),
1041
1042            ExpressionKind::Assignment(mut_location_expr, source_expr) => {
1043                let value_ref = self.evaluate_location(&mut_location_expr.0)?;
1044                let source_value = self.evaluate_expression(source_expr)?;
1045
1046                *value_ref.borrow_mut() = source_value;
1047
1048                Value::Unit
1049            }
1050
1051            ExpressionKind::CompoundAssignment(mut_location_expr, op, source_expr) => {
1052                let value_ref = self.evaluate_location(&mut_location_expr.0)?;
1053                let source_value = self.evaluate_expression(source_expr)?;
1054
1055                self.apply_compound_operator(
1056                    &expr.node,
1057                    &mut value_ref.borrow_mut(),
1058                    op,
1059                    &source_value,
1060                )?;
1061
1062                Value::Unit
1063            }
1064
1065            // Operators
1066            ExpressionKind::BinaryOp(binary_operator) => {
1067                let left_val = self.evaluate_expression(&binary_operator.left)?;
1068                let right_val = self.evaluate_expression(&binary_operator.right)?;
1069                self.evaluate_binary_op(&expr.node, left_val, &binary_operator.kind, right_val)?
1070            }
1071
1072            ExpressionKind::UnaryOp(unary_operator) => {
1073                let left_val = self.evaluate_expression(&unary_operator.left)?;
1074                self.evaluate_unary_op(&expr.node, &unary_operator.kind, left_val)?
1075            }
1076
1077            // Calling
1078            ExpressionKind::FunctionCall(_signature, expr, arguments) => {
1079                self.evaluate_function_call(expr, arguments)?
1080            }
1081
1082            ExpressionKind::MemberCall(resolved_member_call) => {
1083                let parameters = match &*resolved_member_call.function {
1084                    Function::Internal(function_data) => &function_data.signature.parameters,
1085                    Function::External(external_data) => &external_data.signature.parameters,
1086                };
1087
1088                let mut member_call_arguments = Vec::new();
1089                member_call_arguments.extend(self.evaluate_args(&resolved_member_call.arguments)?);
1090
1091                // Check total number of parameters (including self)
1092                if member_call_arguments.len() != parameters.len() {
1093                    return Err(self.create_err(
1094                        ExecuteErrorKind::WrongNumberOfArguments(
1095                            parameters.len(),
1096                            member_call_arguments.len(),
1097                        ),
1098                        &expr.node,
1099                    ));
1100                }
1101
1102                match &*resolved_member_call.function {
1103                    Function::Internal(internal_function) => {
1104                        self.push_function_scope();
1105                        self.bind_parameters(
1106                            &expr.node,
1107                            &internal_function.signature.parameters,
1108                            &member_call_arguments,
1109                        )?;
1110                        let result = self.evaluate_expression(&internal_function.body)?;
1111                        self.pop_function_scope();
1112
1113                        result
1114                    }
1115                    Function::External(external_func) => {
1116                        let mut func = self
1117                            .externals
1118                            .external_functions_by_id
1119                            .get(&external_func.id)
1120                            .expect("member call: external function missing")
1121                            .borrow_mut();
1122                        (func.func)(&member_call_arguments, self.context)?
1123                    }
1124                }
1125            }
1126
1127            ExpressionKind::Block(statements) => {
1128                self.evaluate_block(statements)?.try_into().unwrap() // TODO: Error handling
1129            }
1130
1131            ExpressionKind::InterpolatedString(parts) => {
1132                let mut result = String::new();
1133
1134                for part in parts {
1135                    match part {
1136                        StringPart::Literal(_resolved_node, text) => {
1137                            result.push_str(text);
1138                        }
1139                        StringPart::Interpolation(expr, format_spec) => {
1140                            let value = self.evaluate_expression(expr)?;
1141                            let formatted = match format_spec {
1142                                Some(spec) => format_value(&value, &spec.kind).unwrap(), // TODO: Error handling
1143                                None => value.convert_to_string_if_needed(),
1144                            };
1145                            result.push_str(&formatted);
1146                        }
1147                    }
1148                }
1149
1150                Value::String(result)
1151            }
1152
1153            ExpressionKind::Match(resolved_match) => self.eval_match(resolved_match)?,
1154            ExpressionKind::Guard(guards) => self.eval_guard(&expr.node, guards)?,
1155
1156            ExpressionKind::InternalFunctionAccess(fetch_function) => {
1157                Value::InternalFunction(fetch_function.clone())
1158            }
1159
1160            ExpressionKind::ExternalFunctionAccess(fetch_function) => {
1161                self.externals
1162                    .external_functions_by_id
1163                    .get(&fetch_function.id)
1164                    .expect("should have external function ref");
1165                Value::ExternalFunction(fetch_function.clone())
1166            }
1167
1168            //ExpressionKind::MutMemberCall(_, _) => todo!(),
1169            ExpressionKind::Tuple(_) => todo!(),
1170            ExpressionKind::Option(inner) => match inner {
1171                None => Value::Option(None),
1172                Some(expression) => {
1173                    let v = self.evaluate_expression(expression)?;
1174                    match v {
1175                        Value::Option(_) => {
1176                            panic!("unnecessary wrap!, should be investigated");
1177                        }
1178                        _ => Value::Option(Some(Rc::new(RefCell::new(v)))),
1179                    }
1180                }
1181            },
1182
1183            // --------------- SPECIAL FUNCTIONS
1184            ExpressionKind::CoerceOptionToBool(expression) => {
1185                let value = self.evaluate_expression(expression)?;
1186                match value {
1187                    Value::Option(inner) => Value::Bool(inner.is_some()),
1188                    _ => {
1189                        return Err(
1190                            self.create_err(ExecuteErrorKind::CoerceOptionToBoolFailed, &expr.node)
1191                        );
1192                    }
1193                }
1194            }
1195
1196            ExpressionKind::If(condition, consequences, optional_alternative) => {
1197                let cond_value = self.evaluate_expression(&condition.expression)?;
1198                if cond_value.is_truthy().unwrap() {
1199                    // TODO: ERROR HANDLING
1200                    self.evaluate_expression(consequences)?
1201                } else if let Some(alternative) = optional_alternative {
1202                    self.evaluate_expression(alternative)?
1203                } else {
1204                    Value::Unit
1205                }
1206            }
1207
1208            ExpressionKind::When(bindings, true_block, maybe_else_block) => {
1209                let mut all_are_some = true;
1210                let mut all_expressions = Vec::new();
1211                for binding in bindings {
1212                    let source = self.evaluate_mut_or_immutable_expression(&binding.expr)?;
1213                    match source.to_value() {
1214                        Value::Option(boxed_val) => match boxed_val {
1215                            Some(found_val) => {
1216                                all_expressions.push(found_val.borrow().clone());
1217                            }
1218                            _ => {
1219                                all_are_some = false;
1220                                break;
1221                            }
1222                        },
1223                        _ => {
1224                            return Err(self
1225                                .create_err(ExecuteErrorKind::ExpectedOptional, &true_block.node));
1226                        }
1227                    }
1228                }
1229
1230                if all_are_some {
1231                    self.push_block_scope();
1232
1233                    for (binding, value) in bindings.iter().zip(all_expressions) {
1234                        info!(var=?binding.variable, "binding as mutable");
1235                        self.current_block_scopes.initialize_var(
1236                            binding.variable.scope_index,
1237                            binding.variable.variable_index,
1238                            value,
1239                            binding.variable.is_mutable(),
1240                        );
1241                    }
1242
1243                    let result = self.evaluate_expression(true_block)?;
1244                    self.pop_block_scope();
1245
1246                    result
1247                } else if let Some(else_block) = maybe_else_block {
1248                    self.evaluate_expression(else_block)?
1249                } else {
1250                    Value::Unit
1251                }
1252            }
1253
1254            ExpressionKind::TupleDestructuring(variable_refs, _, expr) => {
1255                let value = self.evaluate_expression(expr)?;
1256                if let Value::Tuple(_tuple_ref, values) = value {
1257                    if variable_refs.len() > values.len() {
1258                        return Err(self.create_err(ExecuteErrorKind::NotAnArray, &expr.node));
1259                    }
1260                    for (index, variable_ref) in variable_refs.iter().enumerate() {
1261                        let value = &values[index].borrow().clone();
1262                        self.current_block_scopes.initialize_var(
1263                            variable_ref.scope_index,
1264                            variable_ref.variable_index,
1265                            value.clone(),
1266                            false,
1267                        );
1268                    }
1269                }
1270                Value::Unit
1271            }
1272            ExpressionKind::VariableAccess(variable_ref) => {
1273                let temp = self.current_block_scopes.lookup_var_value(variable_ref);
1274                assert_ne!(temp, Value::Unit);
1275                temp
1276            }
1277            ExpressionKind::FieldAccess(expr, index) => {
1278                let resolved_expr = self.evaluate_expression(expr)?;
1279                let (_struct_type, values) = resolved_expr
1280                    .expect_struct()
1281                    .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedStruct, &expr.node))?;
1282
1283                let x = values[*index].borrow().clone();
1284                x
1285            }
1286
1287            ExpressionKind::ArrayAccess(expr, _array, index_expr) => {
1288                let resolved_expr = self.evaluate_expression(expr)?;
1289                let (_array_type, values) = resolved_expr
1290                    .expect_array()
1291                    .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedArray, &expr.node))?;
1292
1293                let index = self
1294                    .evaluate_expression(index_expr)?
1295                    .expect_int()
1296                    .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedInt, &expr.node))?
1297                    as usize;
1298
1299                let x = values[index].borrow().clone();
1300                x
1301            }
1302
1303            ExpressionKind::MapIndexAccess(expr, _map_type_ref, _value_type, key_expr) => {
1304                let resolved_expr = self.evaluate_expression(expr)?;
1305                let (_map_type, _value_type, seq_map) = resolved_expr
1306                    .expect_map()
1307                    .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedMap, &expr.node))?;
1308
1309                let key_val = self.evaluate_expression(key_expr)?;
1310
1311                let value_val_maybe = seq_map.get(&key_val);
1312                Value::Option(value_val_maybe.cloned())
1313            }
1314            ExpressionKind::StringRangeAccess(_, _) => todo!(),
1315            ExpressionKind::ArrayRangeAccess(_, _) => todo!(),
1316            ExpressionKind::PostfixChain(start, parts) => {
1317                let value_ref = self.eval_chain(&expr.node, start, parts)?;
1318                let x = value_ref.borrow().clone();
1319                x
1320            }
1321        };
1322
1323        self.depth -= 1;
1324        //self.debug_expr(expr);
1325        //info!(?value, "resulted in value");
1326        Ok(value)
1327    }
1328
1329    fn evaluate_literal(&mut self, node: &Node, lit: &Literal) -> Result<Value, ExecuteError> {
1330        let v = match lit {
1331            Literal::IntLiteral(n) => Value::Int(*n),
1332            Literal::FloatLiteral(f) => Value::Float(*f),
1333            Literal::StringLiteral(s) => Value::String(s.clone()),
1334            Literal::BoolLiteral(b) => Value::Bool(*b),
1335
1336            Literal::EnumVariantLiteral(enum_variant_type, data) => {
1337                let variant_container_value: Value = match &**enum_variant_type {
1338                    EnumVariantType::Tuple(tuple_type) => match data {
1339                        EnumLiteralData::Tuple(tuple_expressions) => {
1340                            let eval_expressions = self.evaluate_expressions(tuple_expressions)?;
1341                            let value_refs = values_to_value_refs_owned(eval_expressions);
1342                            Value::EnumVariantTuple(tuple_type.clone(), value_refs)
1343                        }
1344                        _ => panic!("wrong container type"),
1345                    },
1346
1347                    EnumVariantType::Struct(struct_type_ref) => match data {
1348                        EnumLiteralData::Struct(source_order_field_values) => {
1349                            let mut field_values =
1350                                Vec::with_capacity(source_order_field_values.len());
1351                            field_values
1352                                .resize_with(source_order_field_values.len(), Default::default);
1353                            for (index, resolved_expression) in source_order_field_values {
1354                                let value = self.evaluate_expression(resolved_expression)?;
1355                                field_values[*index] = Rc::new(RefCell::new(value));
1356                            }
1357                            Value::EnumVariantStruct(struct_type_ref.clone(), field_values)
1358                        }
1359                        _ => panic!("wrong container type"),
1360                    },
1361
1362                    EnumVariantType::Nothing(data) => Value::EnumVariantSimple(data.clone()),
1363                };
1364                variant_container_value
1365            }
1366
1367            Literal::TupleLiteral(tuple_type, resolved_expressions) => {
1368                let values = self.evaluate_expressions(resolved_expressions)?;
1369                Value::Tuple(tuple_type.clone(), convert_vec_to_rc_refcell(values))
1370            }
1371
1372            Literal::Vec(array_type, expressions) => {
1373                let values = self.evaluate_expressions(expressions)?;
1374                Value::Vec(array_type.clone(), convert_vec_to_rc_refcell(values))
1375            }
1376
1377            Literal::Slice(element_type, expressions) => {
1378                let values = self.evaluate_expressions(expressions)?;
1379                Value::Slice(element_type.clone(), convert_vec_to_rc_refcell(values))
1380            }
1381
1382            Literal::Map(key_type, value_type, expressions) => {
1383                let mut items = SeqMap::new();
1384                for (key, value) in expressions {
1385                    let key_val = self.evaluate_expression(key)?;
1386                    let value_val = self.evaluate_expression(value)?;
1387                    items
1388                        .insert(key_val, Rc::new(RefCell::new(value_val)))
1389                        .map_err(|_err| {
1390                            self.create_err(
1391                                ExecuteErrorKind::NonUniqueKeysInMapLiteralDetected,
1392                                &node,
1393                            )
1394                        })?;
1395                }
1396                Value::Map(key_type.clone(), value_type.clone(), items)
1397            }
1398
1399            Literal::SlicePair(key_type, value_type, expressions) => {
1400                let mut items = SeqMap::new();
1401                for (key, value) in expressions {
1402                    let key_val = self.evaluate_expression(key)?;
1403                    let value_val = self.evaluate_expression(value)?;
1404                    items
1405                        .insert(key_val, Rc::new(RefCell::new(value_val)))
1406                        .map_err(|_err| {
1407                            self.create_err(
1408                                ExecuteErrorKind::NonUniqueKeysInMapLiteralDetected,
1409                                &node,
1410                            )
1411                        })?;
1412                }
1413                Value::SlicePair(key_type.clone(), value_type.clone(), items)
1414            }
1415
1416            Literal::NoneLiteral => Value::Option(None),
1417        };
1418        Ok(v)
1419    }
1420
1421    #[allow(clippy::too_many_lines)]
1422    fn eval_intrinsic_postfix(
1423        &mut self,
1424        node: &Node,
1425        value_ref: &ValueRef,
1426        //        resolved_postfix: &Postfix,
1427        intrinsic_function: &IntrinsicFunction,
1428        arguments: &[Expression],
1429    ) -> Result<Value, ExecuteError> {
1430        //let node = &resolved_postfix.node;
1431        let val = match &intrinsic_function {
1432            IntrinsicFunction::VecRemoveIndex => {
1433                let index_val = self.evaluate_expression(&arguments[0])?;
1434                let Value::Int(index) = index_val else {
1435                    return Err(self.create_err(ExecuteErrorKind::ArgumentIsNotMutable, node));
1436                };
1437
1438                match &mut *value_ref.borrow_mut() {
1439                    Value::Vec(_type_id, vector) => {
1440                        vector.remove(index as usize);
1441                    }
1442                    _ => {
1443                        Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?;
1444                    }
1445                }
1446
1447                value_ref.borrow().clone()
1448            }
1449
1450            IntrinsicFunction::VecClear => {
1451                match &mut *value_ref.borrow_mut() {
1452                    Value::Vec(_type_id, vector) => {
1453                        vector.clear();
1454                    }
1455                    _ => {
1456                        Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?;
1457                    }
1458                }
1459                Value::Unit
1460            }
1461
1462            IntrinsicFunction::VecPush => {
1463                match &mut *value_ref.borrow_mut() {
1464                    Value::Vec(_type_id, vector) => {
1465                        let value_to_add = self.evaluate_expression(&arguments[0])?;
1466                        vector.push(Rc::new(RefCell::new(value_to_add)));
1467                    }
1468                    _ => {
1469                        Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?;
1470                    }
1471                }
1472                Value::Unit
1473            }
1474
1475            IntrinsicFunction::VecLen => match &mut *value_ref.borrow_mut() {
1476                Value::Vec(_type_id, vector) => {
1477                    let length = vector.len();
1478                    Value::Int(length as i32)
1479                }
1480                _ => Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?,
1481            },
1482
1483            IntrinsicFunction::VecPop => match &mut *value_ref.borrow_mut() {
1484                Value::Vec(_type_id, vector) => {
1485                    let maybe_val = vector.pop();
1486                    Value::Option(maybe_val)
1487                }
1488                _ => Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?,
1489            },
1490
1491            IntrinsicFunction::MapHas => {
1492                let index_val = self.evaluate_expression(&arguments[0])?;
1493
1494                match value_ref.borrow().clone() {
1495                    Value::Map(_key_type, _value_type, ref seq_map) => {
1496                        let has_key = seq_map.contains_key(&index_val);
1497                        Value::Bool(has_key)
1498                    }
1499                    _ => {
1500                        return Err(self.create_err(ExecuteErrorKind::NotAMap, node));
1501                    }
1502                }
1503            }
1504
1505            IntrinsicFunction::MapRemove => {
1506                let index_val = self.evaluate_expression(&arguments[0])?;
1507
1508                let result = {
1509                    let mut borrowed = value_ref.borrow_mut();
1510                    match &mut *borrowed {
1511                        Value::Map(_key_type, _value_type, seq_map) => {
1512                            let x = seq_map.remove(&index_val);
1513                            x.map_or_else(
1514                                || Value::Option(None),
1515                                |v| Value::Option(Some(v.clone())),
1516                            )
1517                        }
1518                        _ => {
1519                            return Err(self.create_err(ExecuteErrorKind::NotAMap, node));
1520                        }
1521                    }
1522                };
1523                result
1524            }
1525
1526            IntrinsicFunction::MapLen => match &mut *value_ref.borrow_mut() {
1527                Value::Map(_key_type, _value_type, seq_map) => {
1528                    let length = seq_map.len();
1529                    Value::Int(length as i32)
1530                }
1531                _ => Err(self.create_err(ExecuteErrorKind::NotAMap, node))?,
1532            },
1533
1534            IntrinsicFunction::SparseAdd => {
1535                let borrowed = value_ref.borrow();
1536
1537                let sparse_value_map = borrowed.downcast_rust::<SparseValueMap>();
1538                match sparse_value_map {
1539                    Some(found) => {
1540                        let resolved_value = self.evaluate_expression(&arguments[0])?;
1541                        let id_value = found.borrow_mut().add(resolved_value);
1542
1543                        id_value
1544                    }
1545                    _ => {
1546                        return Err(self.create_err(ExecuteErrorKind::NotSparseValue, node));
1547                    }
1548                }
1549            }
1550
1551            IntrinsicFunction::SparseRemove => {
1552                let borrowed = value_ref.borrow();
1553
1554                let sparse_value_map = borrowed.downcast_rust::<SparseValueMap>();
1555                if let Some(found) = sparse_value_map {
1556                    let id_value = self.evaluate_expression(&arguments[0])?;
1557                    match id_value.downcast_rust::<SparseValueId>() {
1558                        Some(found_id) => {
1559                            found.borrow_mut().remove(&found_id.borrow());
1560                        }
1561                        _ => {
1562                            return Err(self.create_err(ExecuteErrorKind::NotSparseValue, node));
1563                        }
1564                    }
1565                }
1566
1567                Value::Unit
1568            }
1569            IntrinsicFunction::SparseSubscript => {
1570                let sparse_value_map = value_ref.borrow_mut().downcast_rust::<SparseValueMap>();
1571                match sparse_value_map {
1572                    Some(found) => {
1573                        let id_value = self.evaluate_expression(&arguments[0])?; // id
1574                        match id_value.downcast_rust::<SparseValueId>() {
1575                            Some(found_id) => match found.borrow_mut().get(&found_id.borrow()) {
1576                                Some(found_value) => Value::Option(Some(found_value.clone())),
1577                                _ => Value::Option(None),
1578                            },
1579                            _ => {
1580                                return Err(self.create_err(ExecuteErrorKind::NotSparseId, node));
1581                            }
1582                        }
1583                    }
1584                    _ => {
1585                        return Err(self.create_err(ExecuteErrorKind::NotSparseId, node));
1586                    }
1587                }
1588            }
1589
1590            IntrinsicFunction::FloatRound => match value_ref.borrow().clone() {
1591                Value::Float(f) => Value::Int(f.round().into()),
1592                _ => {
1593                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1594                }
1595            },
1596            IntrinsicFunction::FloatFloor => match value_ref.borrow().clone() {
1597                Value::Float(f) => Value::Int(f.floor().into()),
1598                _ => {
1599                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1600                }
1601            },
1602
1603            IntrinsicFunction::FloatSign => match value_ref.borrow().clone() {
1604                Value::Float(f) => {
1605                    let signum = if f.inner() < 0 {
1606                        -1
1607                    } else if f.inner() > 0 {
1608                        1
1609                    } else {
1610                        0
1611                    };
1612                    Value::Float(Fp::from(signum as i16))
1613                }
1614                _ => {
1615                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1616                }
1617            },
1618            IntrinsicFunction::FloatAbs => match value_ref.borrow().clone() {
1619                Value::Float(f) => Value::Float(f.abs()),
1620                _ => {
1621                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1622                }
1623            },
1624
1625            IntrinsicFunction::FloatCos => match value_ref.borrow().clone() {
1626                Value::Float(f) => Value::Float(f.cos()),
1627                _ => {
1628                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1629                }
1630            },
1631
1632            IntrinsicFunction::FloatAcos => match value_ref.borrow().clone() {
1633                Value::Float(f) => Value::Float(f.acos()),
1634                _ => {
1635                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1636                }
1637            },
1638
1639            IntrinsicFunction::FloatSin => match value_ref.borrow().clone() {
1640                Value::Float(f) => Value::Float(f.sin()),
1641                _ => {
1642                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1643                }
1644            },
1645
1646            IntrinsicFunction::FloatAsin => match value_ref.borrow().clone() {
1647                Value::Float(f) => Value::Float(f.asin()),
1648                _ => {
1649                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1650                }
1651            },
1652
1653            IntrinsicFunction::FloatSqrt => match value_ref.borrow().clone() {
1654                Value::Float(f) => Value::Float(f.sqrt()),
1655                _ => {
1656                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1657                }
1658            },
1659
1660            IntrinsicFunction::FloatMin => {
1661                let min_value = self.evaluate_expression(&arguments[0])?;
1662                match (value_ref.borrow().clone(), min_value) {
1663                    (Value::Float(f), Value::Float(min_f)) => Value::Float(f.min(min_f)),
1664                    _ => {
1665                        return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1666                    }
1667                }
1668            }
1669
1670            IntrinsicFunction::FloatMax => {
1671                let max_value = self.evaluate_expression(&arguments[0])?;
1672                match (value_ref.borrow().clone(), max_value) {
1673                    (Value::Float(f), Value::Float(max_f)) => Value::Float(f.max(max_f)),
1674                    _ => {
1675                        return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1676                    }
1677                }
1678            }
1679
1680            IntrinsicFunction::FloatAtan2 => {
1681                let x_value = self.evaluate_expression(&arguments[0])?;
1682                match (value_ref.borrow().clone(), x_value) {
1683                    (Value::Float(_y_f), Value::Float(_x_f)) => {
1684                        Value::Float(Fp::from(-9999)) //y_f.atan2(x_f)) // TODO: Implement atan2
1685                    }
1686                    _ => {
1687                        return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1688                    }
1689                }
1690            }
1691
1692            IntrinsicFunction::FloatClamp => {
1693                let min_value = self.evaluate_expression(&arguments[0])?;
1694                let max_value = self.evaluate_expression(&arguments[1])?;
1695                match (value_ref.borrow().clone(), min_value, max_value) {
1696                    (Value::Float(f), Value::Float(min_f), Value::Float(max_f)) => {
1697                        Value::Float(f.clamp(min_f, max_f))
1698                    }
1699                    _ => {
1700                        return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1701                    }
1702                }
1703            }
1704
1705            IntrinsicFunction::FloatRnd => match value_ref.borrow().clone() {
1706                Value::Float(f) => {
1707                    let new_raw = squirrel_prng::squirrel_noise5(f.inner() as u32, 0);
1708                    Value::Int(new_raw as i32)
1709                }
1710                _ => {
1711                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1712                }
1713            },
1714
1715            IntrinsicFunction::IntAbs => match value_ref.borrow().clone() {
1716                Value::Int(i) => Value::Int(i.abs()),
1717                _ => {
1718                    return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1719                }
1720            },
1721
1722            IntrinsicFunction::IntClamp => {
1723                let min_value = self.evaluate_expression(&arguments[0])?;
1724                let max_value = self.evaluate_expression(&arguments[1])?;
1725                match (value_ref.borrow().clone(), min_value, max_value) {
1726                    (Value::Int(i), Value::Int(min_i), Value::Int(max_i)) => {
1727                        Value::Int(i.clamp(min_i, max_i))
1728                    }
1729                    _ => {
1730                        return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1731                    }
1732                }
1733            }
1734
1735            IntrinsicFunction::IntMin => {
1736                let max_value = self.evaluate_expression(&arguments[0])?;
1737                match (value_ref.borrow().clone(), max_value) {
1738                    (Value::Int(i), Value::Int(min_i)) => Value::Int(i.min(min_i)),
1739                    _ => {
1740                        return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1741                    }
1742                }
1743            }
1744
1745            IntrinsicFunction::IntMax => {
1746                let max_value = self.evaluate_expression(&arguments[0])?;
1747                match (value_ref.borrow().clone(), max_value) {
1748                    (Value::Int(i), Value::Int(max_i)) => Value::Int(i.max(max_i)),
1749                    _ => {
1750                        return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1751                    }
1752                }
1753            }
1754
1755            IntrinsicFunction::IntRnd => match value_ref.borrow().clone() {
1756                Value::Int(i) => Value::Int(squirrel_prng::squirrel_noise5(i as u32, 0) as i32),
1757                _ => {
1758                    return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1759                }
1760            },
1761
1762            IntrinsicFunction::IntToFloat => match value_ref.borrow().clone() {
1763                Value::Int(i) => Value::Float(Fp::from(i as i16)),
1764                _ => {
1765                    return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1766                }
1767            },
1768
1769            IntrinsicFunction::StringLen => match value_ref.borrow().clone() {
1770                Value::String(s) => Value::Int(s.len().try_into().expect("string len overflow")),
1771                _ => {
1772                    return Err(self.create_err(ExecuteErrorKind::ExpectedString, node));
1773                }
1774            },
1775
1776            IntrinsicFunction::Float2Magnitude => match value_ref.borrow().clone() {
1777                Value::Tuple(_tuple_ref, values) => {
1778                    if values.len() != 2 {
1779                        return Err(self.create_err(
1780                            ExecuteErrorKind::WrongNumberOfArguments(2, values.len()),
1781                            &node,
1782                        ));
1783                    }
1784                    match (
1785                        values[0].as_ref().borrow().clone(),
1786                        values[1].as_ref().borrow().clone(),
1787                    ) {
1788                        (Value::Float(a), Value::Float(b)) => {
1789                            let a_raw: i64 = a.inner() as i64;
1790                            let b_raw: i64 = b.inner() as i64;
1791
1792                            let i64_magnitude = i64_sqrt(a_raw * a_raw + b_raw * b_raw);
1793
1794                            let new_fp = Fp::from_raw(
1795                                i32::try_from(i64_magnitude).expect("wrong with i64_sqrt"),
1796                            );
1797                            Value::Float(new_fp)
1798                        }
1799                        _ => {
1800                            return Err(
1801                                self.create_err(ExecuteErrorKind::ExpectedTwoFloatTuple, node)
1802                            );
1803                        }
1804                    }
1805                }
1806                _ => {
1807                    return Err(self.create_err(ExecuteErrorKind::ExpectedTwoFloatTuple, node));
1808                }
1809            },
1810
1811            _ => todo!("{intrinsic_function:?} not implemented"),
1812        };
1813
1814        Ok(val)
1815    }
1816
1817    #[allow(clippy::too_many_lines)]
1818    fn eval_chain(
1819        &mut self,
1820        node: &Node,
1821        start: &Expression,
1822        parts: &[Postfix],
1823    ) -> Result<ValueRef, ExecuteError> {
1824        let (mut val_ref, mut is_mutable) = match &start.kind {
1825            ExpressionKind::VariableAccess(start_var) => {
1826                let start_variable_value = self.current_block_scopes.get_var(&start_var);
1827
1828                match start_variable_value {
1829                    VariableValue::Value(value) => {
1830                        assert_ne!(*value, Value::Unit);
1831                        (Rc::new(RefCell::new(value.clone())), false)
1832                    }
1833                    VariableValue::Reference(value_ref) => {
1834                        assert_ne!(value_ref.borrow().clone(), Value::Unit);
1835                        (value_ref.clone(), true)
1836                    }
1837                }
1838            }
1839            _ => (
1840                Rc::new(RefCell::new(self.evaluate_expression(start)?)),
1841                false,
1842            ),
1843        };
1844
1845        let mut is_uncertain = false;
1846        let mut is_undefined = false;
1847
1848        for part in parts {
1849            if let PostfixKind::NoneCoalesce(default_expression) = &part.kind {
1850                val_ref = {
1851                    let borrowed = val_ref.borrow();
1852
1853                    match borrowed.clone() {
1854                        Value::Option(found_option) => match found_option {
1855                            Some(some_value) => some_value,
1856                            _ => {
1857                                let default_value = self.evaluate_expression(default_expression)?;
1858                                Rc::new(RefCell::new(default_value))
1859                            }
1860                        },
1861                        _ => {
1862                            return Err(
1863                                self.create_err(ExecuteErrorKind::ExpectedOptional, &part.node)
1864                            );
1865                        }
1866                    }
1867                };
1868
1869                is_mutable = false;
1870                is_uncertain = false;
1871                is_undefined = false;
1872            } else if is_undefined {
1873                continue;
1874            }
1875            match &part.kind {
1876                PostfixKind::NoneCoalesce(_default_expression) => {
1877                    // Handled earlier
1878                }
1879                PostfixKind::StructField(expected_struct_type, index) => {
1880                    let (encountered_struct_type, fields) = {
1881                        let brw = val_ref.borrow();
1882                        let (struct_ref, fields_ref) = brw.expect_anon_struct().map_err(|_| {
1883                            self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1884                        })?;
1885                        (struct_ref.clone(), fields_ref.clone())
1886                    };
1887
1888                    assert!(same_anon_struct_ref(
1889                        &encountered_struct_type,
1890                        expected_struct_type
1891                    ));
1892                    val_ref = fields[*index].clone();
1893                }
1894                PostfixKind::ArrayIndex(expected_element_type, index_expr) => {
1895                    let (encountered_element_type, fields) = {
1896                        let brw = val_ref.borrow();
1897                        let (array_ref, fields_ref) = brw.expect_array().map_err(|_| {
1898                            self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1899                        })?;
1900                        (array_ref.clone(), fields_ref.clone())
1901                    };
1902                    assert!(expected_element_type.compatible_with(&encountered_element_type));
1903
1904                    let index =
1905                        self.evaluate_expression(index_expr)?
1906                            .expect_int()
1907                            .map_err(|_| {
1908                                self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1909                            })? as usize;
1910                    if index >= fields.len() {
1911                        return Err(self.create_err(ExecuteErrorKind::IndexOutOfBounds, &part.node));
1912                    }
1913                    val_ref = fields[index].clone();
1914                }
1915                PostfixKind::MapIndex(_key_type, _value_type, key_expr) => {
1916                    let seq_map = {
1917                        let brw = val_ref.borrow();
1918                        let (key_type, value_type, seq_map) = brw.expect_map().map_err(|_| {
1919                            self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1920                        })?;
1921                        seq_map.clone()
1922                    };
1923                    let key_val = self.evaluate_expression(key_expr)?;
1924
1925                    val_ref = Rc::new(RefCell::new(Value::Option(seq_map.get(&key_val).cloned())));
1926                }
1927                PostfixKind::ExternalTypeIndexRef(_rust_type_ref, map_expr) => {
1928                    let key_expr_value = self.evaluate_expression(map_expr)?;
1929                    val_ref = {
1930                        match key_expr_value.downcast_rust::<SparseValueId>() {
1931                            Some(found_sparse_id) => {
1932                                match val_ref.borrow_mut().downcast_rust::<SparseValueMap>() {
1933                                    Some(sparse_value_map) => wrap_in_option(
1934                                        sparse_value_map
1935                                            .borrow_mut()
1936                                            .get(&found_sparse_id.borrow()),
1937                                    ),
1938                                    _ => {
1939                                        panic!("internal error");
1940                                    }
1941                                }
1942                            }
1943                            _ => {
1944                                panic!("todo");
1945                            }
1946                        }
1947                    };
1948                }
1949                PostfixKind::MemberCall(function_ref, arguments) => {
1950                    let val =
1951                        self.eval_member_call(node, &val_ref, is_mutable, function_ref, arguments)?;
1952
1953                    val_ref = Rc::new(RefCell::new(val));
1954                    is_mutable = false;
1955                }
1956                PostfixKind::FunctionCall(arguments) => {
1957                    let val = self.eval_function_call(node, &val_ref, arguments)?;
1958
1959                    val_ref = Rc::new(RefCell::new(val));
1960                    is_mutable = false;
1961                }
1962                PostfixKind::OptionUnwrap => {
1963                    val_ref = {
1964                        let borrowed = val_ref.borrow();
1965
1966                        match borrowed.clone() {
1967                            Value::Option(found_option) => match found_option {
1968                                Some(some_value) => some_value,
1969                                _ => {
1970                                    is_undefined = true;
1971
1972                                    Rc::new(RefCell::new(Value::Option(None)))
1973                                }
1974                            },
1975                            _ => {
1976                                return Err(
1977                                    self.create_err(ExecuteErrorKind::ExpectedOptional, &part.node)
1978                                );
1979                            }
1980                        }
1981                    };
1982
1983                    is_mutable = false;
1984                    is_uncertain = true;
1985                }
1986                PostfixKind::IntrinsicCall(intrinsic_fn, arguments) => {
1987                    val_ref = Rc::new(RefCell::new(self.eval_intrinsic_postfix(
1988                        &part.node,
1989                        &val_ref,
1990                        intrinsic_fn,
1991                        arguments,
1992                    )?));
1993                    is_mutable = false;
1994                }
1995                PostfixKind::IntrinsicCallEx(_intrinsic_fn, _arguments) => {
1996                    //val_ref = Rc::new(RefCell::new(self.eval_intrinsic_postfix_ex(&val_ref, part, intrinsic_fn, arguments)?));
1997                    is_mutable = false;
1998                }
1999
2000                _ => {}
2001            }
2002        }
2003
2004        if is_uncertain {
2005            let binding = val_ref.borrow().clone();
2006            match binding {
2007                Value::Option(_) => {}
2008                _ => {
2009                    val_ref = Rc::new(RefCell::new(Value::Option(Some(val_ref))));
2010                }
2011            }
2012        }
2013
2014        Ok(val_ref)
2015    }
2016
2017    fn eval_function_call(
2018        &mut self,
2019        node: &Node,
2020        function_val: &ValueRef,
2021        arguments: &[ArgumentExpressionOrLocation],
2022    ) -> Result<Value, ExecuteError> {
2023        let resolved_fn = match function_val.borrow().clone() {
2024            Value::InternalFunction(x) => Function::Internal(x.clone()),
2025            Value::ExternalFunction(external_fn) => Function::External(external_fn.clone()),
2026            _ => panic!("no function to call"),
2027        };
2028
2029        let parameters = &resolved_fn.signature().parameters;
2030        // Check total number of parameters (including self)
2031        assert_eq!(
2032            arguments.len(),
2033            parameters.len(),
2034            "wrong number of arguments"
2035        );
2036
2037        let resolved_arguments = self.evaluate_args(&arguments)?;
2038
2039        let result_val = match &resolved_fn {
2040            Function::Internal(internal_function) => {
2041                self.push_function_scope();
2042
2043                self.bind_parameters(node, &parameters, &resolved_arguments)?;
2044                let result = self.evaluate_expression(&internal_function.body)?;
2045                self.pop_function_scope();
2046
2047                result
2048            }
2049            Function::External(external_func) => {
2050                let mut func = self
2051                    .externals
2052                    .external_functions_by_id
2053                    .get(&external_func.id)
2054                    .expect("member call: external function missing")
2055                    .borrow_mut();
2056                (func.func)(&resolved_arguments, self.context)?
2057            }
2058        };
2059
2060        Ok(result_val)
2061    }
2062
2063    #[inline]
2064    fn eval_member_call(
2065        &mut self,
2066        node: &Node,
2067        self_value_ref: &ValueRef,
2068        is_mutable: bool,
2069        function_ref: &FunctionRef,
2070        arguments: &[ArgumentExpressionOrLocation],
2071    ) -> Result<Value, ExecuteError> {
2072        let parameters = &function_ref.signature().parameters;
2073
2074        let self_var_value = if parameters[0].is_mutable {
2075            if !is_mutable {
2076                return Err(self.create_err(ExecuteErrorKind::ArgumentIsNotMutable, &node));
2077            }
2078            VariableValue::Reference(self_value_ref.clone())
2079        } else {
2080            VariableValue::Value(self_value_ref.borrow().clone())
2081        };
2082
2083        let mut member_call_arguments = Vec::new();
2084        member_call_arguments.push(self_var_value); // Add self as first argument
2085        member_call_arguments.extend(self.evaluate_args(&arguments)?);
2086
2087        // Check total number of parameters (including self)
2088        if member_call_arguments.len() != parameters.len() {
2089            panic!("wrong number of arguments")
2090        }
2091
2092        let result_val = match &**function_ref {
2093            Function::Internal(internal_function) => {
2094                self.push_function_scope();
2095                self.bind_parameters(node, &parameters, &member_call_arguments)?;
2096                let result = self.evaluate_expression(&internal_function.body)?;
2097                self.pop_function_scope();
2098
2099                result
2100            }
2101            Function::External(external_func) => {
2102                let mut func = self
2103                    .externals
2104                    .external_functions_by_id
2105                    .get(&external_func.id)
2106                    .expect("member call: external function missing")
2107                    .borrow_mut();
2108                (func.func)(&member_call_arguments, self.context)?
2109            }
2110        };
2111
2112        Ok(result_val)
2113    }
2114
2115    fn eval_guard(&mut self, node: &Node, guards: &[Guard]) -> Result<Value, ExecuteError> {
2116        for guard in guards {
2117            let should_evaluate = if let Some(found_clause) = &guard.condition {
2118                self.evaluate_expression(&found_clause.expression)?
2119                    .is_truthy()?
2120            } else {
2121                true
2122            };
2123
2124            if should_evaluate {
2125                return self.evaluate_expression(&guard.result);
2126            }
2127        }
2128
2129        Err(self.create_err(ExecuteErrorKind::MustHaveGuardArmThatMatches, &node))
2130    }
2131
2132    #[inline(always)]
2133    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
2134    fn eval_match(&mut self, resolved_match: &Match) -> Result<Value, ExecuteError> {
2135        let actual_value = self.evaluate_mut_or_immutable_expression(&resolved_match.expression)?;
2136        let value_ref = actual_value.to_value_ref();
2137
2138        for arm in &resolved_match.arms {
2139            match &arm.pattern {
2140                Pattern::Wildcard(_node) => return self.evaluate_expression(&arm.expression),
2141                Pattern::Normal(normal_pattern, maybe_guard) => {
2142                    if let Some(found_guard) = maybe_guard {
2143                        if !self
2144                            .evaluate_expression(&found_guard.expression)?
2145                            .is_truthy()?
2146                        // TODO: ERROR HANDLING
2147                        {
2148                            continue;
2149                        }
2150                    }
2151
2152                    let immutable_value = actual_value.to_value();
2153
2154                    match &normal_pattern {
2155                        NormalPattern::PatternList(elements) => {
2156                            return Ok(self.eval_normal_pattern_list(
2157                                elements,
2158                                &arm.expression,
2159                                value_ref.clone(),
2160                            )?);
2161                        }
2162                        NormalPattern::EnumPattern(enum_variant_ref, pattern_elements) => {
2163                            let maybe_found_match = self.eval_normal_pattern_enum(
2164                                pattern_elements.as_ref(),
2165                                &arm.expression,
2166                                enum_variant_ref,
2167                                value_ref.clone(),
2168                            )?;
2169
2170                            if let Some(found_match) = maybe_found_match {
2171                                return Ok(found_match);
2172                            }
2173                        }
2174
2175                        NormalPattern::Literal(lit) => match (lit, &immutable_value) {
2176                            (Literal::IntLiteral(a), Value::Int(b)) if a == b => {
2177                                return self.evaluate_expression(&arm.expression);
2178                            }
2179                            (Literal::FloatLiteral(a), Value::Float(b)) if a == b => {
2180                                return self.evaluate_expression(&arm.expression);
2181                            }
2182                            (Literal::StringLiteral(a), Value::String(b)) if *a == *b => {
2183                                return self.evaluate_expression(&arm.expression);
2184                            }
2185                            (Literal::BoolLiteral(a), Value::Bool(b)) if a == b => {
2186                                return self.evaluate_expression(&arm.expression);
2187                            }
2188                            (
2189                                Literal::TupleLiteral(_a_type_ref, a_values),
2190                                Value::Tuple(_b_type_ref, b_values),
2191                            ) if self.expressions_equal_to_values(&a_values, &b_values)? => {
2192                                return self.evaluate_expression(&arm.expression);
2193                            }
2194                            _ => {}
2195                        },
2196                    }
2197                }
2198            }
2199        }
2200
2201        panic!("must match one of the match arms!");
2202    }
2203
2204    fn eval_normal_pattern_list(
2205        &mut self,
2206        elements: &[PatternElement],
2207        expression_to_evaluate: &Expression,
2208        value_ref: ValueRef,
2209    ) -> Result<Value, ExecuteError> {
2210        // Handle single variable/wildcard patterns that match any value
2211        if elements.len() == 1 {
2212            return match &elements[0] {
2213                PatternElement::Variable(var_ref)
2214                | PatternElement::VariableWithFieldIndex(var_ref, _) => {
2215                    self.push_block_scope();
2216                    self.current_block_scopes
2217                        .initialize_var_mut(var_ref, value_ref);
2218                    let result = self.evaluate_expression(expression_to_evaluate);
2219                    self.pop_block_scope();
2220                    result
2221                }
2222                PatternElement::Wildcard(_) => {
2223                    // Wildcard matches anything
2224                    self.evaluate_expression(expression_to_evaluate)
2225                }
2226            };
2227        }
2228
2229        if let Value::Tuple(_tuple_type_ref, values) = value_ref.borrow_mut().clone() {
2230            assert_eq!(
2231                elements.len(),
2232                values.len(),
2233                "must use all elements in tuple"
2234            );
2235            self.push_block_scope();
2236
2237            for (element, _inside_value) in elements.iter().zip(values.iter()) {
2238                match element {
2239                    PatternElement::Variable(var_ref) => {
2240                        self.current_block_scopes
2241                            .initialize_var_mut(var_ref, value_ref.clone());
2242                    }
2243                    PatternElement::VariableWithFieldIndex(var_ref, _) => {
2244                        self.current_block_scopes
2245                            .initialize_var_mut(var_ref, value_ref.clone());
2246                    }
2247                    PatternElement::Wildcard(_) => {
2248                        // Skip wildcards
2249                        continue;
2250                    }
2251                }
2252            }
2253
2254            let result = self.evaluate_expression(expression_to_evaluate);
2255            self.pop_block_scope();
2256
2257            return result;
2258        }
2259        panic!("should not get here")
2260    }
2261
2262    fn eval_normal_pattern_enum(
2263        &mut self,
2264        maybe_elements: Option<&Vec<PatternElement>>,
2265        expression_to_evaluate: &Expression,
2266        variant_ref: &EnumVariantTypeRef,
2267        value_ref: ValueRef,
2268    ) -> Result<Option<Value>, ExecuteError> {
2269        match value_ref.borrow_mut().clone() {
2270            Value::EnumVariantTuple(value_tuple_type, values) => {
2271                // First check if the variant types match
2272                if variant_ref.common().number != value_tuple_type.common.number {
2273                    return Ok(None); // Try next pattern
2274                }
2275
2276                if let Some(elements) = maybe_elements {
2277                    assert_eq!(elements.len(), values.len());
2278                    self.push_block_scope();
2279
2280                    for (element, value) in elements.iter().zip(values.iter()) {
2281                        match element {
2282                            PatternElement::Variable(var_ref) => {
2283                                self.current_block_scopes
2284                                    .initialize_var_mut(var_ref, value.clone());
2285                            }
2286                            PatternElement::VariableWithFieldIndex(var_ref, _) => {
2287                                self.current_block_scopes
2288                                    .initialize_var_mut(var_ref, value.clone());
2289                            }
2290                            PatternElement::Wildcard(_) => continue,
2291                        }
2292                    }
2293
2294                    let result = self.evaluate_expression(&expression_to_evaluate);
2295                    self.pop_block_scope();
2296                    return Ok(Option::from(result?));
2297                } else {
2298                    panic!("not work");
2299                }
2300            }
2301            Value::EnumVariantStruct(value_enum_struct_type, values) => {
2302                info!(
2303                    ?value_enum_struct_type,
2304                    ?variant_ref,
2305                    "comparing enum variant struct match arm"
2306                );
2307                if value_enum_struct_type.common.number == variant_ref.common().number {
2308                    info!(?value_enum_struct_type, ?variant_ref, "FOUND!");
2309                    if let Some(elements) = maybe_elements {
2310                        self.push_block_scope();
2311
2312                        for element in elements {
2313                            if let PatternElement::VariableWithFieldIndex(var_ref, field_index) =
2314                                element
2315                            {
2316                                let value = &values[*field_index];
2317                                info!(?value, "setting match arm variable");
2318                                self.current_block_scopes.init_var_ref(var_ref, value);
2319                            }
2320                        }
2321
2322                        let result = self.evaluate_expression(&expression_to_evaluate);
2323                        self.pop_block_scope();
2324                        return Ok(Some(result?));
2325                    }
2326                }
2327            }
2328
2329            Value::EnumVariantSimple(value_variant_ref) => {
2330                if value_variant_ref.common.number == variant_ref.common().number
2331                    && maybe_elements.is_none()
2332                {
2333                    return Ok(Some(self.evaluate_expression(&expression_to_evaluate)?));
2334                }
2335            }
2336            _ => {
2337                panic!("could not find it")
2338            }
2339        }
2340
2341        Ok(None)
2342    }
2343
2344    #[inline(always)]
2345    const fn modulo(a: i32, b: i32) -> i32 {
2346        ((a % b) + b) % b
2347    }
2348
2349    #[inline(always)]
2350    const fn modulo_fp(a: Fp, b: Fp) -> Fp {
2351        let raw = ((a.inner() % b.inner()) + b.inner()) % b.inner();
2352        Fp::from_raw(raw)
2353    }
2354
2355    #[allow(clippy::too_many_lines)]
2356    fn evaluate_binary_op(
2357        &self,
2358        node: &Node,
2359        left_val: Value,
2360        op: &BinaryOperatorKind,
2361        right_val: Value,
2362    ) -> Result<Value, ExecuteError> {
2363        let result: Value = match (&left_val, op, &right_val) {
2364            // Integer operations
2365            (Value::Int(a), BinaryOperatorKind::Add, Value::Int(b)) => Value::Int(a + b),
2366            (Value::Int(a), BinaryOperatorKind::Subtract, Value::Int(b)) => Value::Int(a - b),
2367            (Value::Int(a), BinaryOperatorKind::Multiply, Value::Int(b)) => Value::Int(a * b),
2368            (Value::Int(a), BinaryOperatorKind::Divide, Value::Int(b)) => {
2369                if *b == 0 {
2370                    return Err(self.create_err(ExecuteErrorKind::DivideByZero, node));
2371                }
2372                Value::Int(a / b)
2373            }
2374            (Value::Int(a), BinaryOperatorKind::Modulo, Value::Int(b)) => {
2375                Value::Int(Self::modulo(*a, *b))
2376            }
2377            (Value::Int(a), BinaryOperatorKind::Equal, Value::Int(b)) => Value::Bool(a == b),
2378            (Value::Int(a), BinaryOperatorKind::NotEqual, Value::Int(b)) => Value::Bool(a != b),
2379            (Value::Int(a), BinaryOperatorKind::LessThan, Value::Int(b)) => Value::Bool(a < b),
2380            (Value::Int(a), BinaryOperatorKind::GreaterThan, Value::Int(b)) => Value::Bool(a > b),
2381            (Value::Int(a), BinaryOperatorKind::LessEqual, Value::Int(b)) => Value::Bool(a <= b),
2382            (Value::Int(a), BinaryOperatorKind::GreaterEqual, Value::Int(b)) => Value::Bool(a >= b),
2383
2384            // Float operations
2385            (Value::Float(a), BinaryOperatorKind::Equal, Value::Float(b)) => Value::Bool(a == b),
2386            (Value::Float(a), BinaryOperatorKind::NotEqual, Value::Float(b)) => Value::Bool(a != b),
2387
2388            (Value::Float(a), BinaryOperatorKind::Add, Value::Float(b)) => Value::Float(*a + *b),
2389            (Value::Float(a), BinaryOperatorKind::Subtract, Value::Float(b)) => {
2390                Value::Float(*a - *b)
2391            }
2392            (Value::Float(a), BinaryOperatorKind::Multiply, Value::Float(b)) => {
2393                Value::Float(*a * *b)
2394            }
2395            (Value::Float(a), BinaryOperatorKind::Divide, Value::Float(b)) => {
2396                if b.abs().inner() <= 400 {
2397                    return Err(self.create_err(ExecuteErrorKind::DivideByZero, node));
2398                }
2399                Value::Float(*a / *b)
2400            }
2401            (Value::Float(a), BinaryOperatorKind::Modulo, Value::Float(b)) => {
2402                Value::Float(Self::modulo_fp(*a, *b))
2403            }
2404
2405            (Value::Float(a), BinaryOperatorKind::GreaterThan, Value::Float(b)) => {
2406                Value::Bool(a > b)
2407            }
2408            (Value::Float(a), BinaryOperatorKind::GreaterEqual, Value::Float(b)) => {
2409                Value::Bool(a >= b)
2410            }
2411            (Value::Float(a), BinaryOperatorKind::LessThan, Value::Float(b)) => Value::Bool(a < b),
2412            (Value::Float(a), BinaryOperatorKind::LessEqual, Value::Float(b)) => {
2413                Value::Bool(a <= b)
2414            }
2415
2416            // Boolean operations
2417            (Value::Bool(a), BinaryOperatorKind::LogicalAnd, Value::Bool(b)) => {
2418                Value::Bool(*a && *b)
2419            }
2420            (Value::Bool(a), BinaryOperatorKind::LogicalOr, Value::Bool(b)) => {
2421                Value::Bool(*a || *b)
2422            }
2423
2424            // Comparison operations
2425
2426            // RustType
2427            (Value::RustValue(_, left), BinaryOperatorKind::Equal, Value::RustValue(_, right)) => {
2428                let left_borrow = left.borrow();
2429                let right_borrow = right.borrow();
2430                let equal = left_borrow.eq_dyn(&**right_borrow);
2431                Value::Bool(equal)
2432            }
2433            (
2434                Value::RustValue(_, left),
2435                BinaryOperatorKind::NotEqual,
2436                Value::RustValue(_, right),
2437            ) => {
2438                let left_borrow = left.borrow();
2439                let right_borrow = right.borrow();
2440                let equal = left_borrow.eq_dyn(&**right_borrow);
2441                Value::Bool(!equal)
2442            }
2443
2444            // String operations
2445            (Value::String(a), BinaryOperatorKind::Add, Value::String(b)) => {
2446                Value::String(a.to_owned() + b)
2447            }
2448            (Value::String(a), BinaryOperatorKind::Equal, Value::String(b)) => Value::Bool(a == b),
2449
2450            (Value::String(a), BinaryOperatorKind::Add, Value::Int(b)) => {
2451                Value::String(a.to_owned() + &(*b).to_string())
2452            }
2453            (Value::Int(a), BinaryOperatorKind::Add, Value::String(b)) => {
2454                Value::String(a.to_string() + b)
2455            }
2456
2457            // Enum
2458            (
2459                Value::EnumVariantSimple(a),
2460                BinaryOperatorKind::Equal,
2461                Value::EnumVariantSimple(b),
2462            ) => Value::Bool(a == b),
2463            (
2464                Value::EnumVariantSimple(a),
2465                BinaryOperatorKind::NotEqual,
2466                Value::EnumVariantSimple(b),
2467            ) => Value::Bool(a != b),
2468
2469            // Bool
2470            (Value::Bool(a), BinaryOperatorKind::Equal, Value::Bool(b)) => Value::Bool(a == b),
2471            (Value::Bool(a), BinaryOperatorKind::NotEqual, Value::Bool(b)) => Value::Bool(a != b),
2472
2473            (Value::Option(a), BinaryOperatorKind::Equal, Value::Option(b)) => Value::Bool(a == b),
2474
2475            _ => {
2476                error!(?op, "invalid binary operation!!");
2477                panic!("invalid binary operation"); // TODO: improve error handling
2478            }
2479        };
2480
2481        Ok(result)
2482    }
2483
2484    fn evaluate_unary_op(
2485        &self,
2486        node: &Node,
2487        op: &UnaryOperatorKind,
2488        val: Value,
2489    ) -> Result<Value, ExecuteError> {
2490        match (op, val) {
2491            (UnaryOperatorKind::Negate, Value::Int(n)) => Ok(Value::Int(-n)),
2492            (UnaryOperatorKind::Negate, Value::Float(n)) => Ok(Value::Float(-n)),
2493            (UnaryOperatorKind::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
2494            _ => Err(self.create_err(ExecuteErrorKind::DivideByZero, node)),
2495        }
2496    }
2497
2498    fn expressions_equal_to_values(
2499        &mut self,
2500        p0: &[Expression],
2501        p1: &[ValueRef],
2502    ) -> Result<bool, ExecuteError> {
2503        for (a, b_value) in p0.iter().zip(p1.iter()) {
2504            let a_value = self.evaluate_expression(a)?;
2505
2506            if a_value != *b_value.borrow() {
2507                return Ok(false);
2508            }
2509        }
2510
2511        Ok(true)
2512    }
2513
2514    #[inline(always)]
2515    fn apply_compound_operator(
2516        &self,
2517        node: &Node,
2518        target: &mut Value,
2519        operator: &CompoundOperatorKind,
2520        source: &Value,
2521    ) -> Result<(), ExecuteError> {
2522        match operator {
2523            CompoundOperatorKind::Mul => {
2524                *target = self.evaluate_binary_op(
2525                    node,
2526                    target.clone(),
2527                    &BinaryOperatorKind::Multiply,
2528                    source.clone(),
2529                )?;
2530            }
2531            CompoundOperatorKind::Div => {
2532                *target = self.evaluate_binary_op(
2533                    node,
2534                    target.clone(),
2535                    &BinaryOperatorKind::Divide,
2536                    source.clone(),
2537                )?;
2538            }
2539            CompoundOperatorKind::Add => {
2540                *target = self.evaluate_binary_op(
2541                    node,
2542                    target.clone(),
2543                    &BinaryOperatorKind::Add,
2544                    source.clone(),
2545                )?;
2546            }
2547            CompoundOperatorKind::Sub => {
2548                *target = self.evaluate_binary_op(
2549                    node,
2550                    target.clone(),
2551                    &BinaryOperatorKind::Subtract,
2552                    source.clone(),
2553                )?;
2554            }
2555            CompoundOperatorKind::Modulo => {
2556                *target = self.evaluate_binary_op(
2557                    node,
2558                    target.clone(),
2559                    &BinaryOperatorKind::Modulo,
2560                    source.clone(),
2561                )?;
2562            }
2563        }
2564        Ok(())
2565    }
2566
2567    /*
2568        fn evaluate_range(
2569            &mut self,
2570            min_expr: &Expression,
2571            max_expr: &Expression,
2572        ) -> Result<(i32, i32), ExecuteError> {
2573            let min_value = self.evaluate_expression_int(&min_expr)?;
2574            let max_value = self.evaluate_expression_int(&max_expr)?;
2575
2576            Ok((min_value, max_value))
2577        }
2578
2579        fn calculate_range(
2580            start_val: i32,
2581            end_val: i32,
2582            len: usize,
2583            mode: &RangeMode,
2584        ) -> (usize, usize) {
2585            let adjusted_min = if start_val < 0 {
2586                len + start_val as usize
2587            } else {
2588                start_val as usize
2589            };
2590
2591            let mut adjusted_max = if end_val < 0 {
2592                len + end_val as usize
2593            } else {
2594                end_val as usize
2595            };
2596            if RangeMode::Inclusive == mode.clone() {
2597                adjusted_max += 1;
2598            }
2599
2600            (adjusted_min, adjusted_max)
2601        }
2602
2603        fn evaluate_and_calculate_range(
2604            &mut self,
2605            min_expr: &Expression,
2606            max_expr: &Expression,
2607            mode: &RangeMode,
2608            len: usize,
2609        ) -> Result<(usize, usize), ExecuteError> {
2610            let (start_val, end_val) = self.evaluate_range(min_expr, max_expr)?;
2611
2612            Ok(Self::calculate_range(start_val, end_val, len, mode))
2613        }
2614
2615        #[inline]
2616        fn evaluate_array_range_access(
2617            &mut self,
2618            base_expr: &Expression,
2619            array_type_ref: &ArrayTypeRef,
2620            min_expr: &Expression,
2621            max_expr: &Expression,
2622            mode: &RangeMode,
2623        ) -> Result<Value, ExecuteError> {
2624            let array_value = self.evaluate_expression(base_expr)?;
2625
2626            if let Value::Vec(_, values) = array_value {
2627                let (adjusted_start, adjusted_end) =
2628                    self.evaluate_and_calculate_range(min_expr, max_expr, mode, values.len())?;
2629
2630                let slice = &values.as_slice()[adjusted_start..adjusted_end];
2631                Ok(Value::Vec(array_type_ref.clone(), Vec::from(slice)))
2632            } else {
2633                Err(self.create_err(ExecuteErrorKind::NotAnArray, &base_expr.node))
2634            }
2635        }
2636
2637        fn evaluate_expression_int(
2638            &mut self,
2639            int_expr: &Expression,
2640        ) -> Result<i32, ExecuteError> {
2641            let v = self.evaluate_expression(&int_expr)?;
2642
2643            if let Value::Int(i) = v {
2644                Ok(i)
2645            } else {
2646                Err(self.create_err(ExecuteErrorKind::ExpectedInt, &int_expr.node))
2647            }
2648        }
2649    */
2650
2651    /*
2652    fn evaluate_string_range_access(
2653        &mut self,
2654        string_expr: &Expression,
2655        start_expr: &Expression,
2656        end_expr: &Expression,
2657        mode: &RangeMode,
2658    ) -> Result<Value, ExecuteError> {
2659        let string_value = self.evaluate_expression(string_expr)?;
2660
2661        if let Value::String(string) = string_value {
2662            let (adjusted_start, adjusted_end) =
2663                self.evaluate_and_calculate_range(start_expr, end_expr, mode, string.len())?;
2664            Ok(Value::String(
2665                string[adjusted_start..adjusted_end].to_string(),
2666            ))
2667        } else {
2668            Err(self.create_err(ExecuteErrorKind::ExpectedString, &string_expr.node))
2669        }
2670    }
2671
2672     */
2673
2674    fn create_err(&self, kind: ExecuteErrorKind, node: &Node) -> ExecuteError {
2675        ExecuteError {
2676            node: node.clone(),
2677            kind,
2678        }
2679    }
2680
2681    fn evaluate_intrinsic_mut(
2682        &mut self,
2683        node: &Node,
2684        intrinsic_fn: &IntrinsicFunction,
2685        location: &SingleMutLocationExpression,
2686        arguments: &Vec<Expression>,
2687    ) -> Result<Value, ExecuteError> {
2688        let val = match intrinsic_fn {
2689            IntrinsicFunction::VecSelfPush => {
2690                let source_val = self.evaluate_expression(&arguments[0])?;
2691                let array_val_ref = self.evaluate_location(&location.0)?;
2692
2693                match &mut *array_val_ref.borrow_mut() {
2694                    Value::Vec(_type_id, vector) => {
2695                        vector.push(Rc::new(RefCell::new(source_val)));
2696                    }
2697                    _ => {
2698                        Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &node))?;
2699                    }
2700                }
2701                //array_val_ref.borrow().clone()
2702                Value::Unit
2703            }
2704            IntrinsicFunction::VecSelfExtend => {
2705                let source_val = self.evaluate_expression(&arguments[0])?;
2706
2707                let array_val_ref = self.evaluate_location(&location.0)?;
2708                match &mut *array_val_ref.borrow_mut() {
2709                    Value::Vec(_type_id, vector) => match source_val {
2710                        Value::Vec(_, items) => {
2711                            vector.extend(items);
2712                        }
2713                        _ => {
2714                            Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &node))?;
2715                        }
2716                    },
2717                    _ => {
2718                        todo!("handle error")
2719                    }
2720                }
2721
2722                // array_val_ref.borrow().clone()
2723                Value::Unit
2724            }
2725            _ => return Err(self.create_err(ExecuteErrorKind::UnknownMutIntrinsic, &node)),
2726        };
2727
2728        Ok(val)
2729    }
2730
2731    fn evaluate_intrinsic_generic(
2732        &self,
2733        node: &Node,
2734        intrinsic: &IntrinsicFunction,
2735        type_parameters: &Vec<Type>,
2736        arguments: &Vec<Expression>,
2737    ) -> Result<Value, ExecuteError> {
2738        let value = match intrinsic {
2739            IntrinsicFunction::SparseNew => {
2740                let sparse_id_external = ExternalType {
2741                    type_name: "SparseId".to_string(), // To identify the specific Rust type
2742                    number: SPARSE_ID_TYPE_ID,
2743                };
2744                let sparse_value_map =
2745                    SparseValueMap::new(sparse_id_external.into(), type_parameters[0].clone());
2746                let sparse_external = ExternalType {
2747                    type_name: "Sparse".to_string(), // To identify the specific Rust type
2748                    number: SPARSE_TYPE_ID,
2749                };
2750                to_rust_value(sparse_external.into(), sparse_value_map)
2751            }
2752            _ => return Err(self.create_err(ExecuteErrorKind::UnknownGenericIntrinsic, &node)),
2753        };
2754
2755        Ok(value)
2756    }
2757}
2758
2759#[inline]
2760#[must_use]
2761pub fn i64_sqrt(v: i64) -> i64 {
2762    assert!(v >= 0, "negative numbers are undefined for sqrt() {v}");
2763
2764    if v == 0 {
2765        return v;
2766    }
2767
2768    const MAX_ITERATIONS: usize = 40;
2769    const TOLERANCE: i64 = 2;
2770
2771    let mut guess = v / 2;
2772
2773    for _ in 0..MAX_ITERATIONS {
2774        let next_guess = (guess + v / guess) / 2;
2775
2776        // Check if the change is within the tolerance level
2777        if (next_guess - guess).abs() <= TOLERANCE {
2778            return next_guess;
2779        }
2780
2781        guess = next_guess;
2782    }
2783
2784    guess // Return the last guess if convergence wasn't fully reached
2785}
2786
2787#[allow(unused)]
2788pub fn values_to_value_refs(values: &[Value]) -> Vec<ValueRef> {
2789    let mut items = Vec::new();
2790
2791    for x in values.iter().cloned() {
2792        items.push(Rc::new(RefCell::new(x)));
2793    }
2794
2795    items
2796}
2797
2798pub fn values_to_value_refs_owned(values: Vec<Value>) -> Vec<ValueRef> {
2799    values
2800        .into_iter()
2801        .map(|x| Rc::new(RefCell::new(x)))
2802        .collect()
2803}
2804
2805pub fn wrap_in_option(maybe: Option<&ValueRef>) -> ValueRef {
2806    match maybe {
2807        None => Rc::new(RefCell::new(Value::Option(None))),
2808        Some(x) => Rc::new(RefCell::new(Value::Option(Some(x.clone())))),
2809    }
2810}