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