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