swamp_script_eval/
lib.rs

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