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