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 maybe_value = vector.get(index_int as usize);
1413                    if let Some(found_value) = maybe_value {
1414                        found_value.borrow().clone()
1415                    } else {
1416                        return Err(
1417                            self.create_err(RuntimeErrorKind::VecSubscriptNonExisting, node)
1418                        );
1419                    }
1420                }
1421                _ => {
1422                    return Err(self.create_err(RuntimeErrorKind::OperationRequiresArray, node))?;
1423                }
1424            },
1425
1426            IntrinsicFunction::VecLen => match &mut *value_ref.borrow_mut() {
1427                Value::Vec(_type_id, vector) => {
1428                    let length = vector.len();
1429                    Value::Int(length as i32)
1430                }
1431                _ => Err(self.create_err(RuntimeErrorKind::OperationRequiresArray, node))?,
1432            },
1433
1434            IntrinsicFunction::VecIsEmpty => match &mut *value_ref.borrow_mut() {
1435                Value::Vec(_type_id, vector) => Value::Bool(vector.len() == 0),
1436                _ => Err(self.create_err(RuntimeErrorKind::OperationRequiresArray, node))?,
1437            },
1438
1439            IntrinsicFunction::VecPop => match &mut *value_ref.borrow_mut() {
1440                Value::Vec(_type_id, vector) => {
1441                    let maybe_val = vector.pop();
1442                    if let Some(found_value) = maybe_val {
1443                        found_value.borrow().clone()
1444                    } else {
1445                        return Err(self.create_err(RuntimeErrorKind::StackCouldNotBePopped, node));
1446                    }
1447                }
1448                _ => Err(self.create_err(RuntimeErrorKind::OperationRequiresArray, node))?,
1449            },
1450
1451            IntrinsicFunction::MapFromSlicePair => {
1452                let borrow = value_ref.borrow();
1453                let (slice_pair_type, seq_map) = borrow.expect_slice_pair()?;
1454                Value::Map(slice_pair_type, seq_map.clone())
1455            }
1456
1457            IntrinsicFunction::MapHas => {
1458                let index_val = self.evaluate_expression(&arguments[0])?;
1459
1460                match value_ref.borrow().clone() {
1461                    Value::Map(_key_type, ref seq_map) => {
1462                        let has_key = seq_map.contains_key(&index_val);
1463                        Value::Bool(has_key)
1464                    }
1465                    _ => {
1466                        return Err(self.create_err(RuntimeErrorKind::NotAMap, node));
1467                    }
1468                }
1469            }
1470
1471            IntrinsicFunction::MapLen => match value_ref.borrow().clone() {
1472                Value::Map(_key_type, ref seq_map) => Value::Int(seq_map.len() as i32),
1473                _ => {
1474                    return Err(self.create_err(RuntimeErrorKind::NotAMap, node));
1475                }
1476            },
1477
1478            IntrinsicFunction::MapIsEmpty => match &mut *value_ref.borrow_mut() {
1479                Value::Vec(_type_id, seq_map) => Value::Bool(seq_map.len() == 0),
1480                _ => Err(self.create_err(RuntimeErrorKind::OperationRequiresArray, node))?,
1481            },
1482
1483            IntrinsicFunction::MapSubscript => match value_ref.borrow().clone() {
1484                Value::Map(_type_id, seq_map) => {
1485                    let key_value = self.evaluate_expression(&arguments[0])?;
1486                    let maybe_value = seq_map.get(&key_value);
1487                    if let Some(found_value) = maybe_value {
1488                        found_value.borrow().clone()
1489                    } else {
1490                        return Err(self.create_err(RuntimeErrorKind::MapKeyNonExisting, node));
1491                    }
1492                }
1493                _ => {
1494                    return Err(self.create_err(RuntimeErrorKind::OperationRequiresArray, node))?;
1495                }
1496            },
1497
1498            IntrinsicFunction::MapRemove => {
1499                let index_val = self.evaluate_expression(&arguments[0])?;
1500
1501                let result = {
1502                    let mut borrowed = value_ref.borrow_mut();
1503                    match &mut *borrowed {
1504                        Value::Map(_key_type, seq_map) => {
1505                            seq_map.remove(&index_val);
1506                            /*
1507                            let x =
1508                            x.map_or_else(
1509                                || Value::Option(None),
1510                                |v| Value::Option(Some(v.clone())),
1511                            )
1512
1513                             */
1514                            Value::Unit
1515                        }
1516                        _ => {
1517                            return Err(self.create_err(RuntimeErrorKind::NotAMap, node));
1518                        }
1519                    }
1520                };
1521                result
1522            }
1523
1524            IntrinsicFunction::SparseAdd => {
1525                let mut borrowed = value_ref.borrow_mut();
1526
1527                match &mut *borrowed {
1528                    Value::Sparse(_type, found) => {
1529                        let resolved_value = self.evaluate_expression(&arguments[0])?;
1530                        let id_value = found.add(resolved_value);
1531
1532                        id_value
1533                    }
1534                    _ => {
1535                        return Err(self.create_err(RuntimeErrorKind::NotSparseValue, node));
1536                    }
1537                }
1538            }
1539
1540            IntrinsicFunction::SparseRemove => {
1541                let mut borrowed = value_ref.borrow_mut();
1542
1543                match &mut *borrowed {
1544                    Value::Sparse(_type, found) => {
1545                        let id_value = self.evaluate_expression(&arguments[0])?;
1546                        match id_value.downcast_rust::<SparseValueId>() {
1547                            Some(found_id) => {
1548                                found.remove(&found_id.borrow());
1549                            }
1550                            _ => {
1551                                return Err(self.create_err(RuntimeErrorKind::NotSparseValue, node));
1552                            }
1553                        }
1554                    }
1555                    _ => {
1556                        return Err(self.create_err(RuntimeErrorKind::NotSparseValue, node));
1557                    }
1558                }
1559
1560                Value::Unit
1561            }
1562            IntrinsicFunction::SparseSubscript => {
1563                let borrowed = value_ref.borrow();
1564
1565                match &*borrowed {
1566                    Value::Sparse(_type, found) => {
1567                        let id_value = self.evaluate_expression(&arguments[0])?; // id
1568                        match id_value.downcast_rust::<SparseValueId>() {
1569                            Some(found_id) => match found.get(&found_id.borrow()) {
1570                                Some(found_value) => Value::Option(Some(found_value.clone())),
1571                                _ => Value::Option(None),
1572                            },
1573                            _ => {
1574                                return Err(self.create_err(RuntimeErrorKind::NotSparseId, node));
1575                            }
1576                        }
1577                    }
1578                    _ => {
1579                        return Err(self.create_err(RuntimeErrorKind::NotSparseId, node));
1580                    }
1581                }
1582            }
1583
1584            IntrinsicFunction::FloatRound => match value_ref.borrow().clone() {
1585                Value::Float(f) => Value::Int(f.round().into()),
1586                _ => {
1587                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1588                }
1589            },
1590            IntrinsicFunction::FloatFloor => match value_ref.borrow().clone() {
1591                Value::Float(f) => Value::Int(f.floor().into()),
1592                _ => {
1593                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1594                }
1595            },
1596
1597            IntrinsicFunction::FloatSign => match value_ref.borrow().clone() {
1598                Value::Float(f) => {
1599                    let signum = if f.inner() < 0 {
1600                        -1
1601                    } else if f.inner() > 0 {
1602                        1
1603                    } else {
1604                        0
1605                    };
1606                    Value::Float(Fp::from(signum as i16))
1607                }
1608                _ => {
1609                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1610                }
1611            },
1612            IntrinsicFunction::FloatAbs => match value_ref.borrow().clone() {
1613                Value::Float(f) => Value::Float(f.abs()),
1614                _ => {
1615                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1616                }
1617            },
1618
1619            IntrinsicFunction::FloatCos => match value_ref.borrow().clone() {
1620                Value::Float(f) => Value::Float(f.cos()),
1621                _ => {
1622                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1623                }
1624            },
1625
1626            IntrinsicFunction::FloatAcos => match value_ref.borrow().clone() {
1627                Value::Float(f) => Value::Float(f.acos()),
1628                _ => {
1629                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1630                }
1631            },
1632
1633            IntrinsicFunction::FloatSin => match value_ref.borrow().clone() {
1634                Value::Float(f) => Value::Float(f.sin()),
1635                _ => {
1636                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1637                }
1638            },
1639
1640            IntrinsicFunction::FloatAsin => match value_ref.borrow().clone() {
1641                Value::Float(f) => Value::Float(f.asin()),
1642                _ => {
1643                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1644                }
1645            },
1646
1647            IntrinsicFunction::FloatSqrt => match value_ref.borrow().clone() {
1648                Value::Float(f) => Value::Float(f.sqrt()),
1649                _ => {
1650                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1651                }
1652            },
1653
1654            IntrinsicFunction::FloatMin => {
1655                let min_value = self.evaluate_expression(&arguments[0])?;
1656                match (value_ref.borrow().clone(), min_value) {
1657                    (Value::Float(f), Value::Float(min_f)) => Value::Float(f.min(min_f)),
1658                    _ => {
1659                        return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1660                    }
1661                }
1662            }
1663
1664            IntrinsicFunction::FloatMax => {
1665                let max_value = self.evaluate_expression(&arguments[0])?;
1666                match (value_ref.borrow().clone(), max_value) {
1667                    (Value::Float(f), Value::Float(max_f)) => Value::Float(f.max(max_f)),
1668                    _ => {
1669                        return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1670                    }
1671                }
1672            }
1673
1674            IntrinsicFunction::FloatAtan2 => {
1675                let x_value = self.evaluate_expression(&arguments[0])?;
1676                match (value_ref.borrow().clone(), x_value) {
1677                    (Value::Float(_y_f), Value::Float(_x_f)) => {
1678                        Value::Float(Fp::from(-9999)) //y_f.atan2(x_f)) // TODO: Implement atan2
1679                    }
1680                    _ => {
1681                        return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1682                    }
1683                }
1684            }
1685
1686            IntrinsicFunction::FloatClamp => {
1687                let min_value = self.evaluate_expression(&arguments[0])?;
1688                let max_value = self.evaluate_expression(&arguments[1])?;
1689                match (value_ref.borrow().clone(), min_value, max_value) {
1690                    (Value::Float(f), Value::Float(min_f), Value::Float(max_f)) => {
1691                        Value::Float(f.clamp(min_f, max_f))
1692                    }
1693                    _ => {
1694                        return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1695                    }
1696                }
1697            }
1698
1699            IntrinsicFunction::FloatRnd => match value_ref.borrow().clone() {
1700                Value::Float(f) => {
1701                    let new_raw = squirrel_prng::squirrel_noise5(f.inner() as u32, 0);
1702                    Value::Int(new_raw as i32)
1703                }
1704                _ => {
1705                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1706                }
1707            },
1708
1709            IntrinsicFunction::IntAbs => match value_ref.borrow().clone() {
1710                Value::Int(i) => Value::Int(i.abs()),
1711                _ => {
1712                    return Err(self.create_err(RuntimeErrorKind::ExpectedFloat, node));
1713                }
1714            },
1715
1716            IntrinsicFunction::IntClamp => {
1717                let min_value = self.evaluate_expression(&arguments[0])?;
1718                let max_value = self.evaluate_expression(&arguments[1])?;
1719                match (value_ref.borrow().clone(), min_value, max_value) {
1720                    (Value::Int(i), Value::Int(min_i), Value::Int(max_i)) => {
1721                        Value::Int(i.clamp(min_i, max_i))
1722                    }
1723                    _ => {
1724                        return Err(self.create_err(RuntimeErrorKind::ExpectedInt, node));
1725                    }
1726                }
1727            }
1728
1729            IntrinsicFunction::IntMin => {
1730                let max_value = self.evaluate_expression(&arguments[0])?;
1731                match (value_ref.borrow().clone(), max_value) {
1732                    (Value::Int(i), Value::Int(min_i)) => Value::Int(i.min(min_i)),
1733                    _ => {
1734                        return Err(self.create_err(RuntimeErrorKind::ExpectedInt, node));
1735                    }
1736                }
1737            }
1738
1739            IntrinsicFunction::IntMax => {
1740                let max_value = self.evaluate_expression(&arguments[0])?;
1741                match (value_ref.borrow().clone(), max_value) {
1742                    (Value::Int(i), Value::Int(max_i)) => Value::Int(i.max(max_i)),
1743                    _ => {
1744                        return Err(self.create_err(RuntimeErrorKind::ExpectedInt, node));
1745                    }
1746                }
1747            }
1748
1749            IntrinsicFunction::IntRnd => match value_ref.borrow().clone() {
1750                Value::Int(i) => Value::Int(squirrel_prng::squirrel_noise5(i as u32, 0) as i32),
1751                _ => {
1752                    return Err(self.create_err(RuntimeErrorKind::ExpectedInt, node));
1753                }
1754            },
1755
1756            IntrinsicFunction::IntToFloat => match value_ref.borrow().clone() {
1757                Value::Int(i) => Value::Float(Fp::from(i as i16)),
1758                _ => {
1759                    return Err(self.create_err(RuntimeErrorKind::ExpectedInt, node));
1760                }
1761            },
1762
1763            IntrinsicFunction::StringLen => match value_ref.borrow().clone() {
1764                Value::String(s) => Value::Int(s.len().try_into().expect("string len overflow")),
1765                _ => {
1766                    return Err(self.create_err(RuntimeErrorKind::ExpectedString, node));
1767                }
1768            },
1769
1770            IntrinsicFunction::Float2Magnitude => match value_ref.borrow().clone() {
1771                Value::Tuple(_tuple_ref, values) => {
1772                    if values.len() != 2 {
1773                        return Err(self.create_err(
1774                            RuntimeErrorKind::WrongNumberOfArguments(2, values.len()),
1775                            &node,
1776                        ));
1777                    }
1778                    match (
1779                        values[0].as_ref().borrow().clone(),
1780                        values[1].as_ref().borrow().clone(),
1781                    ) {
1782                        (Value::Float(a), Value::Float(b)) => {
1783                            let a_raw: i64 = a.inner() as i64;
1784                            let b_raw: i64 = b.inner() as i64;
1785
1786                            let i64_magnitude = i64_sqrt(a_raw * a_raw + b_raw * b_raw);
1787
1788                            let new_fp = Fp::from_raw(
1789                                i32::try_from(i64_magnitude).expect("wrong with i64_sqrt"),
1790                            );
1791                            Value::Float(new_fp)
1792                        }
1793                        _ => {
1794                            return Err(
1795                                self.create_err(RuntimeErrorKind::ExpectedTwoFloatTuple, node)
1796                            );
1797                        }
1798                    }
1799                }
1800                _ => {
1801                    return Err(self.create_err(RuntimeErrorKind::ExpectedTwoFloatTuple, node));
1802                }
1803            },
1804
1805            _ => todo!("{intrinsic_function:?} not implemented"),
1806        };
1807
1808        Ok(val)
1809    }
1810
1811    #[allow(clippy::too_many_lines)]
1812    fn eval_chain(
1813        &mut self,
1814        node: &Node,
1815        start: &Expression,
1816        parts: &[Postfix],
1817    ) -> Result<ValueRef, RuntimeError> {
1818        let (mut val_ref, mut is_mutable) = match &start.kind {
1819            ExpressionKind::VariableAccess(start_var) => {
1820                let start_variable_value = self.current_block_scopes.get_var(&start_var);
1821
1822                match start_variable_value {
1823                    VariableValue::Value(value) => {
1824                        assert_ne!(*value, Value::Unit);
1825                        (Rc::new(RefCell::new(value.clone())), false)
1826                    }
1827                    VariableValue::Reference(value_ref) => {
1828                        assert_ne!(value_ref.borrow().clone(), Value::Unit);
1829                        (value_ref.clone(), true)
1830                    }
1831                }
1832            }
1833            _ => (
1834                Rc::new(RefCell::new(self.evaluate_expression(start)?)),
1835                false,
1836            ),
1837        };
1838
1839        let mut is_uncertain = false;
1840        let mut is_undefined = false;
1841
1842        for part in parts {
1843            if let PostfixKind::NoneCoalesce(default_expression) = &part.kind {
1844                val_ref = {
1845                    let borrowed = val_ref.borrow();
1846
1847                    match borrowed.clone() {
1848                        Value::Option(found_option) => match found_option {
1849                            Some(some_value) => some_value,
1850                            _ => {
1851                                let default_value = self.evaluate_expression(default_expression)?;
1852                                Rc::new(RefCell::new(default_value))
1853                            }
1854                        },
1855                        _ => {
1856                            return Err(
1857                                self.create_err(RuntimeErrorKind::ExpectedOptional, &part.node)
1858                            );
1859                        }
1860                    }
1861                };
1862
1863                is_mutable = false;
1864                is_uncertain = false;
1865                is_undefined = false;
1866            } else if is_undefined {
1867                continue;
1868            }
1869            match &part.kind {
1870                PostfixKind::NoneCoalesce(_default_expression) => {
1871                    // Handled earlier
1872                }
1873
1874                PostfixKind::StructField(expected_struct_type, index) => {
1875                    let (encountered_struct_type, fields) = {
1876                        let brw = val_ref.borrow();
1877                        let (struct_ref, fields_ref) = brw.expect_anon_struct().map_err(|_| {
1878                            self.create_err(RuntimeErrorKind::PostfixChainError, &part.node)
1879                        })?;
1880                        (struct_ref.clone(), fields_ref.clone())
1881                    };
1882
1883                    assert!(same_anon_struct_ref(
1884                        &encountered_struct_type,
1885                        expected_struct_type
1886                    ));
1887                    val_ref = fields[*index].clone();
1888                }
1889
1890                PostfixKind::MemberCall(function_ref, arguments) => {
1891                    let val =
1892                        self.eval_member_call(node, &val_ref, is_mutable, function_ref, arguments)?;
1893
1894                    val_ref = Rc::new(RefCell::new(val));
1895                    is_mutable = false;
1896                }
1897                PostfixKind::FunctionCall(arguments) => {
1898                    let val = self.eval_function_call(node, &val_ref, arguments)?;
1899
1900                    val_ref = Rc::new(RefCell::new(val));
1901                    is_mutable = false;
1902                }
1903
1904                PostfixKind::OptionUnwrap => {
1905                    val_ref = {
1906                        let borrowed = val_ref.borrow();
1907
1908                        match borrowed.clone() {
1909                            Value::Option(found_option) => match found_option {
1910                                Some(some_value) => some_value,
1911                                _ => {
1912                                    is_undefined = true;
1913
1914                                    Rc::new(RefCell::new(Value::Option(None)))
1915                                }
1916                            },
1917                            _ => {
1918                                return Err(
1919                                    self.create_err(RuntimeErrorKind::ExpectedOptional, &part.node)
1920                                );
1921                            }
1922                        }
1923                    };
1924
1925                    is_mutable = false;
1926                    is_uncertain = true;
1927                }
1928                _ => {}
1929            }
1930        }
1931
1932        if is_uncertain {
1933            let binding = val_ref.borrow().clone();
1934            match binding {
1935                Value::Option(_) => {}
1936                _ => {
1937                    val_ref = Rc::new(RefCell::new(Value::Option(Some(val_ref))));
1938                }
1939            }
1940        }
1941
1942        Ok(val_ref)
1943    }
1944
1945    fn eval_function_call(
1946        &mut self,
1947        node: &Node,
1948        function_val: &ValueRef,
1949        arguments: &[ArgumentExpressionOrLocation],
1950    ) -> Result<Value, RuntimeError> {
1951        let resolved_fn = match function_val.borrow().clone() {
1952            Value::InternalFunction(x) => Function::Internal(x.clone()),
1953            Value::ExternalFunction(external_fn) => Function::External(external_fn.clone()),
1954            _ => panic!("no function to call"),
1955        };
1956
1957        let parameters = &resolved_fn.signature().parameters;
1958        // Check total number of parameters (including self)
1959        assert_eq!(
1960            arguments.len(),
1961            parameters.len(),
1962            "wrong number of arguments"
1963        );
1964
1965        let resolved_arguments = self.evaluate_args(&arguments)?;
1966
1967        let result_val = match &resolved_fn {
1968            Function::Internal(internal_function) => {
1969                self.push_function_scope();
1970
1971                self.bind_parameters(node, &parameters, &resolved_arguments)?;
1972                let result = self.evaluate_expression(&internal_function.body)?;
1973                self.pop_function_scope();
1974
1975                result
1976            }
1977            Function::External(external_func) => {
1978                let mut func = self
1979                    .externals
1980                    .external_functions_by_id
1981                    .get(&external_func.id)
1982                    .expect("member call: external function missing")
1983                    .borrow_mut();
1984                (func.func)(&resolved_arguments, self.context)?
1985            }
1986        };
1987
1988        Ok(result_val)
1989    }
1990
1991    #[inline]
1992    fn eval_member_call(
1993        &mut self,
1994        node: &Node,
1995        self_value_ref: &ValueRef,
1996        is_mutable: bool,
1997        function_ref: &FunctionRef,
1998        arguments: &[ArgumentExpressionOrLocation],
1999    ) -> Result<Value, RuntimeError> {
2000        let parameters = &function_ref.signature().parameters;
2001
2002        let self_var_value = if parameters[0].is_mutable {
2003            if !is_mutable {
2004                return Err(self.create_err(RuntimeErrorKind::ArgumentIsNotMutable, &node));
2005            }
2006            VariableValue::Reference(self_value_ref.clone())
2007        } else {
2008            VariableValue::Value(self_value_ref.borrow().clone())
2009        };
2010
2011        let mut member_call_arguments = Vec::new();
2012        member_call_arguments.push(self_var_value); // Add self as first argument
2013        member_call_arguments.extend(self.evaluate_args(&arguments)?);
2014
2015        // Check total number of parameters (including self)
2016        if member_call_arguments.len() != parameters.len() {
2017            panic!("wrong number of arguments")
2018        }
2019
2020        let result_val = match &**function_ref {
2021            Function::Internal(internal_function) => {
2022                self.push_function_scope();
2023                self.bind_parameters(node, &parameters, &member_call_arguments)?;
2024                let result = self.evaluate_expression(&internal_function.body)?;
2025                self.pop_function_scope();
2026
2027                result
2028            }
2029            Function::External(external_func) => {
2030                let mut func = self
2031                    .externals
2032                    .external_functions_by_id
2033                    .get(&external_func.id)
2034                    .expect("member call: external function missing")
2035                    .borrow_mut();
2036                (func.func)(&member_call_arguments, self.context)?
2037            }
2038        };
2039
2040        Ok(result_val)
2041    }
2042
2043    fn eval_guard(&mut self, node: &Node, guards: &[Guard]) -> Result<Value, RuntimeError> {
2044        for guard in guards {
2045            let should_evaluate = if let Some(found_clause) = &guard.condition {
2046                self.evaluate_expression(&found_clause.expression)?
2047                    .is_truthy()?
2048            } else {
2049                true
2050            };
2051
2052            if should_evaluate {
2053                return self.evaluate_expression(&guard.result);
2054            }
2055        }
2056
2057        Err(self.create_err(RuntimeErrorKind::MustHaveGuardArmThatMatches, &node))
2058    }
2059
2060    #[inline(always)]
2061    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
2062    fn eval_match(&mut self, resolved_match: &Match) -> Result<Value, RuntimeError> {
2063        let actual_value = self.evaluate_mut_or_immutable_expression(&resolved_match.expression)?;
2064        let value_ref = actual_value.to_value_ref();
2065
2066        for arm in &resolved_match.arms {
2067            match &arm.pattern {
2068                Pattern::Wildcard(_node) => return self.evaluate_expression(&arm.expression),
2069                Pattern::Normal(normal_pattern, maybe_guard) => {
2070                    if let Some(found_guard) = maybe_guard {
2071                        if !self
2072                            .evaluate_expression(&found_guard.expression)?
2073                            .is_truthy()?
2074                        // TODO: ERROR HANDLING
2075                        {
2076                            continue;
2077                        }
2078                    }
2079
2080                    let immutable_value = actual_value.to_value();
2081
2082                    match &normal_pattern {
2083                        NormalPattern::PatternList(elements) => {
2084                            return Ok(self.eval_normal_pattern_list(
2085                                elements,
2086                                &arm.expression,
2087                                value_ref.clone(),
2088                            )?);
2089                        }
2090                        NormalPattern::EnumPattern(enum_variant_ref, pattern_elements) => {
2091                            let maybe_found_match = self.eval_normal_pattern_enum(
2092                                pattern_elements.as_ref(),
2093                                &arm.expression,
2094                                enum_variant_ref,
2095                                value_ref.clone(),
2096                            )?;
2097
2098                            if let Some(found_match) = maybe_found_match {
2099                                return Ok(found_match);
2100                            }
2101                        }
2102
2103                        NormalPattern::Literal(lit) => match (lit, &immutable_value) {
2104                            (Literal::IntLiteral(a), Value::Int(b)) if a == b => {
2105                                return self.evaluate_expression(&arm.expression);
2106                            }
2107                            (Literal::FloatLiteral(a), Value::Float(b)) if a == b => {
2108                                return self.evaluate_expression(&arm.expression);
2109                            }
2110                            (Literal::StringLiteral(a), Value::String(b)) if *a == *b => {
2111                                return self.evaluate_expression(&arm.expression);
2112                            }
2113                            (Literal::BoolLiteral(a), Value::Bool(b)) if a == b => {
2114                                return self.evaluate_expression(&arm.expression);
2115                            }
2116                            (
2117                                Literal::TupleLiteral(_a_type_ref, a_values),
2118                                Value::Tuple(_b_type_ref, b_values),
2119                            ) if self.expressions_equal_to_values(&a_values, &b_values)? => {
2120                                return self.evaluate_expression(&arm.expression);
2121                            }
2122                            _ => {}
2123                        },
2124                    }
2125                }
2126            }
2127        }
2128
2129        panic!("must match one of the match arms!");
2130    }
2131
2132    fn eval_normal_pattern_list(
2133        &mut self,
2134        elements: &[PatternElement],
2135        expression_to_evaluate: &Expression,
2136        value_ref: ValueRef,
2137    ) -> Result<Value, RuntimeError> {
2138        // Handle single variable/wildcard patterns that match any value
2139        if elements.len() == 1 {
2140            return match &elements[0] {
2141                PatternElement::Variable(var_ref)
2142                | PatternElement::VariableWithFieldIndex(var_ref, _) => {
2143                    self.push_block_scope();
2144                    self.current_block_scopes
2145                        .initialize_var_mut(var_ref, value_ref);
2146                    let result = self.evaluate_expression(expression_to_evaluate);
2147                    self.pop_block_scope();
2148                    result
2149                }
2150                PatternElement::Wildcard(_) => {
2151                    // Wildcard matches anything
2152                    self.evaluate_expression(expression_to_evaluate)
2153                }
2154            };
2155        }
2156
2157        if let Value::Tuple(_tuple_type_ref, values) = value_ref.borrow_mut().clone() {
2158            assert_eq!(
2159                elements.len(),
2160                values.len(),
2161                "must use all elements in tuple"
2162            );
2163            self.push_block_scope();
2164
2165            for (element, _inside_value) in elements.iter().zip(values.iter()) {
2166                match element {
2167                    PatternElement::Variable(var_ref) => {
2168                        self.current_block_scopes
2169                            .initialize_var_mut(var_ref, value_ref.clone());
2170                    }
2171                    PatternElement::VariableWithFieldIndex(var_ref, _) => {
2172                        self.current_block_scopes
2173                            .initialize_var_mut(var_ref, value_ref.clone());
2174                    }
2175                    PatternElement::Wildcard(_) => {
2176                        // Skip wildcards
2177                        continue;
2178                    }
2179                }
2180            }
2181
2182            let result = self.evaluate_expression(expression_to_evaluate);
2183            self.pop_block_scope();
2184
2185            return result;
2186        }
2187        panic!("should not get here")
2188    }
2189
2190    fn eval_normal_pattern_enum(
2191        &mut self,
2192        maybe_elements: Option<&Vec<PatternElement>>,
2193        expression_to_evaluate: &Expression,
2194        variant_ref: &EnumVariantType,
2195        value_ref: ValueRef,
2196    ) -> Result<Option<Value>, RuntimeError> {
2197        match value_ref.borrow_mut().clone() {
2198            Value::EnumVariantTuple(value_tuple_type, values) => {
2199                // First check if the variant types match
2200                if variant_ref.common().container_index != value_tuple_type.common.container_index {
2201                    return Ok(None); // Try next pattern
2202                }
2203
2204                if let Some(elements) = maybe_elements {
2205                    assert_eq!(elements.len(), values.len());
2206                    self.push_block_scope();
2207
2208                    for (element, value) in elements.iter().zip(values.iter()) {
2209                        match element {
2210                            PatternElement::Variable(var_ref) => {
2211                                self.current_block_scopes
2212                                    .initialize_var_mut(var_ref, value.clone());
2213                            }
2214                            PatternElement::VariableWithFieldIndex(var_ref, _) => {
2215                                self.current_block_scopes
2216                                    .initialize_var_mut(var_ref, value.clone());
2217                            }
2218                            PatternElement::Wildcard(_) => continue,
2219                        }
2220                    }
2221
2222                    let result = self.evaluate_expression(&expression_to_evaluate);
2223                    self.pop_block_scope();
2224                    return Ok(Option::from(result?));
2225                } else {
2226                    panic!("not work");
2227                }
2228            }
2229            Value::EnumVariantStruct(value_enum_struct_type, values) => {
2230                info!(
2231                    ?value_enum_struct_type,
2232                    ?variant_ref,
2233                    "comparing enum variant struct match arm"
2234                );
2235                if value_enum_struct_type.common.container_index
2236                    == variant_ref.common().container_index
2237                {
2238                    info!(?value_enum_struct_type, ?variant_ref, "FOUND!");
2239                    if let Some(elements) = maybe_elements {
2240                        self.push_block_scope();
2241
2242                        for element in elements {
2243                            if let PatternElement::VariableWithFieldIndex(var_ref, field_index) =
2244                                element
2245                            {
2246                                let value = &values[*field_index];
2247                                info!(?value, "setting match arm variable");
2248                                self.current_block_scopes.init_var_ref(var_ref, value);
2249                            }
2250                        }
2251
2252                        let result = self.evaluate_expression(&expression_to_evaluate);
2253                        self.pop_block_scope();
2254                        return Ok(Some(result?));
2255                    }
2256                }
2257            }
2258
2259            Value::EnumVariantSimple(value_variant_ref) => {
2260                if value_variant_ref.common.container_index == variant_ref.common().container_index
2261                    && maybe_elements.is_none()
2262                {
2263                    return Ok(Some(self.evaluate_expression(&expression_to_evaluate)?));
2264                }
2265            }
2266            _ => {
2267                panic!("could not find enum variant, serious error")
2268            }
2269        }
2270
2271        Ok(None)
2272    }
2273
2274    #[inline(always)]
2275    const fn modulo(a: i32, b: i32) -> i32 {
2276        ((a % b) + b) % b
2277    }
2278
2279    #[inline(always)]
2280    const fn modulo_fp(a: Fp, b: Fp) -> Fp {
2281        let raw = ((a.inner() % b.inner()) + b.inner()) % b.inner();
2282        Fp::from_raw(raw)
2283    }
2284
2285    #[allow(clippy::too_many_lines)]
2286    fn evaluate_binary_op(
2287        &self,
2288        node: &Node,
2289        left_val: Value,
2290        op: &BinaryOperatorKind,
2291        right_val: Value,
2292    ) -> Result<Value, RuntimeError> {
2293        let result: Value = match (&left_val, op, &right_val) {
2294            // Integer operations
2295            (Value::Int(a), BinaryOperatorKind::Add, Value::Int(b)) => Value::Int(a + b),
2296            (Value::Int(a), BinaryOperatorKind::Subtract, Value::Int(b)) => Value::Int(a - b),
2297            (Value::Int(a), BinaryOperatorKind::Multiply, Value::Int(b)) => Value::Int(a * b),
2298            (Value::Int(a), BinaryOperatorKind::Divide, Value::Int(b)) => {
2299                if *b == 0 {
2300                    return Err(self.create_err(RuntimeErrorKind::DivideByZero, node));
2301                }
2302                Value::Int(a / b)
2303            }
2304            (Value::Int(a), BinaryOperatorKind::Modulo, Value::Int(b)) => {
2305                Value::Int(Self::modulo(*a, *b))
2306            }
2307            (Value::Int(a), BinaryOperatorKind::Equal, Value::Int(b)) => Value::Bool(a == b),
2308            (Value::Int(a), BinaryOperatorKind::NotEqual, Value::Int(b)) => Value::Bool(a != b),
2309            (Value::Int(a), BinaryOperatorKind::LessThan, Value::Int(b)) => Value::Bool(a < b),
2310            (Value::Int(a), BinaryOperatorKind::GreaterThan, Value::Int(b)) => Value::Bool(a > b),
2311            (Value::Int(a), BinaryOperatorKind::LessEqual, Value::Int(b)) => Value::Bool(a <= b),
2312            (Value::Int(a), BinaryOperatorKind::GreaterEqual, Value::Int(b)) => Value::Bool(a >= b),
2313
2314            // Float operations
2315            (Value::Float(a), BinaryOperatorKind::Equal, Value::Float(b)) => Value::Bool(a == b),
2316            (Value::Float(a), BinaryOperatorKind::NotEqual, Value::Float(b)) => Value::Bool(a != b),
2317
2318            (Value::Float(a), BinaryOperatorKind::Add, Value::Float(b)) => Value::Float(*a + *b),
2319            (Value::Float(a), BinaryOperatorKind::Subtract, Value::Float(b)) => {
2320                Value::Float(*a - *b)
2321            }
2322            (Value::Float(a), BinaryOperatorKind::Multiply, Value::Float(b)) => {
2323                Value::Float(*a * *b)
2324            }
2325            (Value::Float(a), BinaryOperatorKind::Divide, Value::Float(b)) => {
2326                if b.abs().inner() <= 400 {
2327                    return Err(self.create_err(RuntimeErrorKind::DivideByZero, node));
2328                }
2329                Value::Float(*a / *b)
2330            }
2331            (Value::Float(a), BinaryOperatorKind::Modulo, Value::Float(b)) => {
2332                Value::Float(Self::modulo_fp(*a, *b))
2333            }
2334
2335            (Value::Float(a), BinaryOperatorKind::GreaterThan, Value::Float(b)) => {
2336                Value::Bool(a > b)
2337            }
2338            (Value::Float(a), BinaryOperatorKind::GreaterEqual, Value::Float(b)) => {
2339                Value::Bool(a >= b)
2340            }
2341            (Value::Float(a), BinaryOperatorKind::LessThan, Value::Float(b)) => Value::Bool(a < b),
2342            (Value::Float(a), BinaryOperatorKind::LessEqual, Value::Float(b)) => {
2343                Value::Bool(a <= b)
2344            }
2345
2346            // Boolean operations
2347            (Value::Bool(a), BinaryOperatorKind::LogicalAnd, Value::Bool(b)) => {
2348                Value::Bool(*a && *b)
2349            }
2350            (Value::Bool(a), BinaryOperatorKind::LogicalOr, Value::Bool(b)) => {
2351                Value::Bool(*a || *b)
2352            }
2353
2354            // Comparison operations
2355
2356            // RustType
2357            (Value::RustValue(_, left), BinaryOperatorKind::Equal, Value::RustValue(_, right)) => {
2358                let left_borrow = left.borrow();
2359                let right_borrow = right.borrow();
2360                let equal = left_borrow.eq_dyn(&**right_borrow);
2361                Value::Bool(equal)
2362            }
2363            (
2364                Value::RustValue(_, left),
2365                BinaryOperatorKind::NotEqual,
2366                Value::RustValue(_, right),
2367            ) => {
2368                let left_borrow = left.borrow();
2369                let right_borrow = right.borrow();
2370                let equal = left_borrow.eq_dyn(&**right_borrow);
2371                Value::Bool(!equal)
2372            }
2373
2374            // String operations
2375            (Value::String(a), BinaryOperatorKind::Add, Value::String(b)) => {
2376                Value::String(a.to_owned() + b)
2377            }
2378            (Value::String(a), BinaryOperatorKind::Equal, Value::String(b)) => Value::Bool(a == b),
2379
2380            (Value::String(a), BinaryOperatorKind::Add, Value::Int(b)) => {
2381                Value::String(a.to_owned() + &(*b).to_string())
2382            }
2383            (Value::Int(a), BinaryOperatorKind::Add, Value::String(b)) => {
2384                Value::String(a.to_string() + b)
2385            }
2386
2387            // Enum
2388            (
2389                Value::EnumVariantSimple(a),
2390                BinaryOperatorKind::Equal,
2391                Value::EnumVariantSimple(b),
2392            ) => Value::Bool(a == b),
2393            (
2394                Value::EnumVariantSimple(a),
2395                BinaryOperatorKind::NotEqual,
2396                Value::EnumVariantSimple(b),
2397            ) => Value::Bool(a != b),
2398
2399            // Bool
2400            (Value::Bool(a), BinaryOperatorKind::Equal, Value::Bool(b)) => Value::Bool(a == b),
2401            (Value::Bool(a), BinaryOperatorKind::NotEqual, Value::Bool(b)) => Value::Bool(a != b),
2402
2403            (Value::Option(a), BinaryOperatorKind::Equal, Value::Option(b)) => Value::Bool(a == b),
2404
2405            _ => {
2406                error!(?op, "invalid binary operation!!");
2407                panic!("invalid binary operation"); // TODO: improve error handling
2408            }
2409        };
2410
2411        Ok(result)
2412    }
2413
2414    fn evaluate_unary_op(
2415        &self,
2416        node: &Node,
2417        op: &UnaryOperatorKind,
2418        val: Value,
2419    ) -> Result<Value, RuntimeError> {
2420        match (op, val) {
2421            (UnaryOperatorKind::Negate, Value::Int(n)) => Ok(Value::Int(-n)),
2422            (UnaryOperatorKind::Negate, Value::Float(n)) => Ok(Value::Float(-n)),
2423            (UnaryOperatorKind::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
2424            _ => Err(self.create_err(RuntimeErrorKind::DivideByZero, node)),
2425        }
2426    }
2427
2428    fn expressions_equal_to_values(
2429        &mut self,
2430        p0: &[Expression],
2431        p1: &[ValueRef],
2432    ) -> Result<bool, RuntimeError> {
2433        for (a, b_value) in p0.iter().zip(p1.iter()) {
2434            let a_value = self.evaluate_expression(a)?;
2435
2436            if a_value != *b_value.borrow() {
2437                return Ok(false);
2438            }
2439        }
2440
2441        Ok(true)
2442    }
2443
2444    #[inline(always)]
2445    fn apply_compound_operator(
2446        &self,
2447        node: &Node,
2448        target: &mut Value,
2449        operator: &CompoundOperatorKind,
2450        source: &Value,
2451    ) -> Result<(), RuntimeError> {
2452        match operator {
2453            CompoundOperatorKind::Mul => {
2454                *target = self.evaluate_binary_op(
2455                    node,
2456                    target.clone(),
2457                    &BinaryOperatorKind::Multiply,
2458                    source.clone(),
2459                )?;
2460            }
2461            CompoundOperatorKind::Div => {
2462                *target = self.evaluate_binary_op(
2463                    node,
2464                    target.clone(),
2465                    &BinaryOperatorKind::Divide,
2466                    source.clone(),
2467                )?;
2468            }
2469            CompoundOperatorKind::Add => {
2470                *target = self.evaluate_binary_op(
2471                    node,
2472                    target.clone(),
2473                    &BinaryOperatorKind::Add,
2474                    source.clone(),
2475                )?;
2476            }
2477            CompoundOperatorKind::Sub => {
2478                *target = self.evaluate_binary_op(
2479                    node,
2480                    target.clone(),
2481                    &BinaryOperatorKind::Subtract,
2482                    source.clone(),
2483                )?;
2484            }
2485            CompoundOperatorKind::Modulo => {
2486                *target = self.evaluate_binary_op(
2487                    node,
2488                    target.clone(),
2489                    &BinaryOperatorKind::Modulo,
2490                    source.clone(),
2491                )?;
2492            }
2493        }
2494        Ok(())
2495    }
2496
2497    fn create_err(&self, kind: RuntimeErrorKind, node: &Node) -> RuntimeError {
2498        RuntimeError {
2499            node: node.clone(),
2500            kind,
2501        }
2502    }
2503
2504    fn evaluate_intrinsic_mut(
2505        &mut self,
2506        node: &Node,
2507        intrinsic_fn: &IntrinsicFunction,
2508        location: &SingleMutLocationExpression,
2509        arguments: &Vec<Expression>,
2510    ) -> Result<Value, RuntimeError> {
2511        let val = match intrinsic_fn {
2512            IntrinsicFunction::VecSelfPush => {
2513                let source_val = self.evaluate_expression(&arguments[0])?;
2514                let array_val_ref = self.evaluate_location(&location.0)?;
2515
2516                match &mut *array_val_ref.borrow_mut() {
2517                    Value::Vec(_type_id, vector) => {
2518                        vector.push(Rc::new(RefCell::new(source_val)));
2519                    }
2520                    _ => {
2521                        Err(self.create_err(RuntimeErrorKind::OperationRequiresArray, &node))?;
2522                    }
2523                }
2524                //array_val_ref.borrow().clone()
2525                Value::Unit
2526            }
2527            IntrinsicFunction::VecSelfExtend => {
2528                let source_val = self.evaluate_expression(&arguments[0])?;
2529
2530                let array_val_ref = self.evaluate_location(&location.0)?;
2531                match &mut *array_val_ref.borrow_mut() {
2532                    Value::Vec(_type_id, vector) => match source_val {
2533                        Value::Vec(_, items) => {
2534                            vector.extend(items);
2535                        }
2536                        _ => {
2537                            Err(self.create_err(RuntimeErrorKind::OperationRequiresArray, &node))?;
2538                        }
2539                    },
2540                    _ => {
2541                        todo!("handle error")
2542                    }
2543                }
2544
2545                // array_val_ref.borrow().clone()
2546                Value::Unit
2547            }
2548            _ => return Err(self.create_err(RuntimeErrorKind::UnknownMutIntrinsic, &node)),
2549        };
2550
2551        Ok(val)
2552    }
2553}
2554
2555#[inline]
2556#[must_use]
2557pub fn i64_sqrt(v: i64) -> i64 {
2558    assert!(v >= 0, "negative numbers are undefined for sqrt() {v}");
2559
2560    if v == 0 {
2561        return v;
2562    }
2563
2564    const MAX_ITERATIONS: usize = 40;
2565    const TOLERANCE: i64 = 2;
2566
2567    let mut guess = v / 2;
2568
2569    for _ in 0..MAX_ITERATIONS {
2570        let next_guess = (guess + v / guess) / 2;
2571
2572        // Check if the change is within the tolerance level
2573        if (next_guess - guess).abs() <= TOLERANCE {
2574            return next_guess;
2575        }
2576
2577        guess = next_guess;
2578    }
2579
2580    guess // Return the last guess if convergence wasn't fully reached
2581}
2582
2583#[allow(unused)]
2584pub fn values_to_value_refs(values: &[Value]) -> Vec<ValueRef> {
2585    let mut items = Vec::new();
2586
2587    for x in values.iter().cloned() {
2588        items.push(Rc::new(RefCell::new(x)));
2589    }
2590
2591    items
2592}
2593
2594pub fn values_to_value_refs_owned(values: Vec<Value>) -> Vec<ValueRef> {
2595    values
2596        .into_iter()
2597        .map(|x| Rc::new(RefCell::new(x)))
2598        .collect()
2599}
2600
2601pub fn wrap_in_option(maybe: Option<&ValueRef>) -> ValueRef {
2602    match maybe {
2603        None => Rc::new(RefCell::new(Value::Option(None))),
2604        Some(x) => Rc::new(RefCell::new(Value::Option(Some(x.clone())))),
2605    }
2606}