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