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