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