1use 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 SourceMapLookup, Value, convert_vec_to_rc_refcell, format_value, to_rust_value,
17};
18use swamp_script_semantic::prelude::*;
19use swamp_script_semantic::{ArgumentExpressionOrLocation, LocationAccess, LocationAccessKind};
20use swamp_script_semantic::{
21 BinaryOperatorKind, CompoundOperatorKind, ConstantId, ForPattern, Function,
22 MutOrImmutableExpression, NormalPattern, PatternElement, PostfixKind, SingleLocationExpression,
23 SingleLocationExpressionKind, UnaryOperatorKind, same_anon_struct_ref,
24};
25use swamp_script_semantic::{Postfix, SingleMutLocationExpression, same_array_ref};
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_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 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 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 {
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 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 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 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 for (key, value) in iterator_value.into_iter_pairs().unwrap() {
733 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 }
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 VariableValue::Value(found_val.borrow().clone())
826 }
827 VariableValue::Reference(_var_ref) => {
828 VariableValue::Reference(found_val)
830 }
831 };
832 all_expressions.push(variable_value);
833 }
834 _ => {
835 all_are_some = false;
836 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 #[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 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 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 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 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 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 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 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 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 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 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 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() }
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(), 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::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 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 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 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 intrinsic_function: &IntrinsicFunction,
1400 arguments: &[Expression],
1401 ) -> Result<Value, ExecuteError> {
1402 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])?; 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)) }
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 }
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!(same_array_ref(&encountered_array_type, expected_array_type));
1867
1868 let index =
1869 self.evaluate_expression(index_expr)?
1870 .expect_int()
1871 .map_err(|_| {
1872 self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1873 })? as usize;
1874 if index >= fields.len() {
1875 return Err(self.create_err(ExecuteErrorKind::IndexOutOfBounds, &part.node));
1876 }
1877 val_ref = fields[index].clone();
1878 }
1879 PostfixKind::MapIndex(_expected_map_type_ref, key_expr) => {
1880 let (_encountered_map_type, seq_map) = {
1881 let brw = val_ref.borrow();
1882 let (array_ref, seq_map) = brw.expect_map().map_err(|_| {
1883 self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1884 })?;
1885 (array_ref.clone(), seq_map.clone())
1886 };
1887 let key_val = self.evaluate_expression(key_expr)?;
1888
1889 val_ref = Rc::new(RefCell::new(Value::Option(seq_map.get(&key_val).cloned())));
1890 }
1891 PostfixKind::ExternalTypeIndexRef(_rust_type_ref, map_expr) => {
1892 let key_expr_value = self.evaluate_expression(map_expr)?;
1893 val_ref = {
1894 match key_expr_value.downcast_rust::<SparseValueId>() {
1895 Some(found_sparse_id) => {
1896 match val_ref.borrow_mut().downcast_rust::<SparseValueMap>() {
1897 Some(sparse_value_map) => wrap_in_option(
1898 sparse_value_map
1899 .borrow_mut()
1900 .get(&found_sparse_id.borrow()),
1901 ),
1902 _ => {
1903 panic!("internal error");
1904 }
1905 }
1906 }
1907 _ => {
1908 panic!("todo");
1909 }
1910 }
1911 };
1912 }
1913 PostfixKind::MemberCall(function_ref, arguments) => {
1914 let val =
1915 self.eval_member_call(node, &val_ref, is_mutable, function_ref, arguments)?;
1916
1917 val_ref = Rc::new(RefCell::new(val));
1918 is_mutable = false;
1919 }
1920 PostfixKind::FunctionCall(arguments) => {
1921 let val = self.eval_function_call(node, &val_ref, arguments)?;
1922
1923 val_ref = Rc::new(RefCell::new(val));
1924 is_mutable = false;
1925 }
1926 PostfixKind::OptionUnwrap => {
1927 val_ref = {
1928 let borrowed = val_ref.borrow();
1929
1930 match borrowed.clone() {
1931 Value::Option(found_option) => match found_option {
1932 Some(some_value) => some_value,
1933 _ => {
1934 is_undefined = true;
1935
1936 Rc::new(RefCell::new(Value::Option(None)))
1937 }
1938 },
1939 _ => {
1940 return Err(
1941 self.create_err(ExecuteErrorKind::ExpectedOptional, &part.node)
1942 );
1943 }
1944 }
1945 };
1946
1947 is_mutable = false;
1948 is_uncertain = true;
1949 }
1950 PostfixKind::IntrinsicCall(intrinsic_fn, arguments) => {
1951 val_ref = Rc::new(RefCell::new(self.eval_intrinsic_postfix(
1952 &part.node,
1953 &val_ref,
1954 intrinsic_fn,
1955 arguments,
1956 )?));
1957 is_mutable = false;
1958 }
1959 PostfixKind::IntrinsicCallEx(_intrinsic_fn, _arguments) => {
1960 is_mutable = false;
1962 }
1963 _ => {}
1964 }
1965 }
1966
1967 if is_uncertain {
1968 let binding = val_ref.borrow().clone();
1969 match binding {
1970 Value::Option(_) => {}
1971 _ => {
1972 val_ref = Rc::new(RefCell::new(Value::Option(Some(val_ref))));
1973 }
1974 }
1975 }
1976
1977 Ok(val_ref)
1978 }
1979
1980 fn eval_function_call(
1981 &mut self,
1982 node: &Node,
1983 function_val: &ValueRef,
1984 arguments: &[ArgumentExpressionOrLocation],
1985 ) -> Result<Value, ExecuteError> {
1986 let resolved_fn = match function_val.borrow().clone() {
1987 Value::InternalFunction(x) => Function::Internal(x.clone()),
1988 Value::ExternalFunction(external_fn) => Function::External(external_fn.clone()),
1989 _ => panic!("no function to call"),
1990 };
1991
1992 let parameters = &resolved_fn.signature().parameters;
1993 assert_eq!(
1995 arguments.len(),
1996 parameters.len(),
1997 "wrong number of arguments"
1998 );
1999
2000 let resolved_arguments = self.evaluate_args(&arguments)?;
2001
2002 let result_val = match &resolved_fn {
2003 Function::Internal(internal_function) => {
2004 self.push_function_scope();
2005
2006 self.bind_parameters(node, ¶meters, &resolved_arguments)?;
2007 let result = self.evaluate_expression(&internal_function.body)?;
2008 self.pop_function_scope();
2009
2010 result
2011 }
2012 Function::External(external_func) => {
2013 let mut func = self
2014 .externals
2015 .external_functions_by_id
2016 .get(&external_func.id)
2017 .expect("member call: external function missing")
2018 .borrow_mut();
2019 (func.func)(&resolved_arguments, self.context)?
2020 }
2021 };
2022
2023 Ok(result_val)
2024 }
2025
2026 #[inline]
2027 fn eval_member_call(
2028 &mut self,
2029 node: &Node,
2030 self_value_ref: &ValueRef,
2031 is_mutable: bool,
2032 function_ref: &FunctionRef,
2033 arguments: &[ArgumentExpressionOrLocation],
2034 ) -> Result<Value, ExecuteError> {
2035 let parameters = &function_ref.signature().parameters;
2036
2037 let self_var_value = if parameters[0].is_mutable {
2038 if !is_mutable {
2039 return Err(self.create_err(ExecuteErrorKind::ArgumentIsNotMutable, &node));
2040 }
2041 VariableValue::Reference(self_value_ref.clone())
2042 } else {
2043 VariableValue::Value(self_value_ref.borrow().clone())
2044 };
2045
2046 let mut member_call_arguments = Vec::new();
2047 member_call_arguments.push(self_var_value); member_call_arguments.extend(self.evaluate_args(&arguments)?);
2049
2050 if member_call_arguments.len() != parameters.len() {
2052 panic!("wrong number of arguments")
2053 }
2054
2055 let result_val = match &**function_ref {
2056 Function::Internal(internal_function) => {
2057 self.push_function_scope();
2058 self.bind_parameters(node, ¶meters, &member_call_arguments)?;
2059 let result = self.evaluate_expression(&internal_function.body)?;
2060 self.pop_function_scope();
2061
2062 result
2063 }
2064 Function::External(external_func) => {
2065 let mut func = self
2066 .externals
2067 .external_functions_by_id
2068 .get(&external_func.id)
2069 .expect("member call: external function missing")
2070 .borrow_mut();
2071 (func.func)(&member_call_arguments, self.context)?
2072 }
2073 };
2074
2075 Ok(result_val)
2076 }
2077
2078 fn eval_guard(&mut self, node: &Node, guards: &[Guard]) -> Result<Value, ExecuteError> {
2079 for guard in guards {
2080 let should_evaluate = if let Some(found_clause) = &guard.condition {
2081 self.evaluate_expression(&found_clause.expression)?
2082 .is_truthy()?
2083 } else {
2084 true
2085 };
2086
2087 if should_evaluate {
2088 return self.evaluate_expression(&guard.result);
2089 }
2090 }
2091
2092 Err(self.create_err(ExecuteErrorKind::MustHaveGuardArmThatMatches, &node))
2093 }
2094
2095 #[inline(always)]
2096 #[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
2097 fn eval_match(&mut self, resolved_match: &Match) -> Result<Value, ExecuteError> {
2098 let actual_value = self.evaluate_mut_or_immutable_expression(&resolved_match.expression)?;
2099 let value_ref = actual_value.to_value_ref();
2100
2101 for arm in &resolved_match.arms {
2102 match &arm.pattern {
2103 Pattern::Wildcard(_node) => return self.evaluate_expression(&arm.expression),
2104 Pattern::Normal(normal_pattern, maybe_guard) => {
2105 if let Some(found_guard) = maybe_guard {
2106 if !self
2107 .evaluate_expression(&found_guard.expression)?
2108 .is_truthy()?
2109 {
2111 continue;
2112 }
2113 }
2114
2115 let immutable_value = actual_value.to_value();
2116
2117 match &normal_pattern {
2118 NormalPattern::PatternList(elements) => {
2119 return Ok(self.eval_normal_pattern_list(
2120 elements,
2121 &arm.expression,
2122 value_ref.clone(),
2123 )?);
2124 }
2125 NormalPattern::EnumPattern(enum_variant_ref, pattern_elements) => {
2126 let maybe_found_match = self.eval_normal_pattern_enum(
2127 pattern_elements.as_ref(),
2128 &arm.expression,
2129 enum_variant_ref,
2130 value_ref.clone(),
2131 )?;
2132
2133 if let Some(found_match) = maybe_found_match {
2134 return Ok(found_match);
2135 }
2136 }
2137
2138 NormalPattern::Literal(lit) => match (lit, &immutable_value) {
2139 (Literal::IntLiteral(a), Value::Int(b)) if a == b => {
2140 return self.evaluate_expression(&arm.expression);
2141 }
2142 (Literal::FloatLiteral(a), Value::Float(b)) if a == b => {
2143 return self.evaluate_expression(&arm.expression);
2144 }
2145 (Literal::StringLiteral(a), Value::String(b)) if *a == *b => {
2146 return self.evaluate_expression(&arm.expression);
2147 }
2148 (Literal::BoolLiteral(a), Value::Bool(b)) if a == b => {
2149 return self.evaluate_expression(&arm.expression);
2150 }
2151 (
2152 Literal::TupleLiteral(_a_type_ref, a_values),
2153 Value::Tuple(_b_type_ref, b_values),
2154 ) if self.expressions_equal_to_values(&a_values, &b_values)? => {
2155 return self.evaluate_expression(&arm.expression);
2156 }
2157 _ => {}
2158 },
2159 }
2160 }
2161 }
2162 }
2163
2164 panic!("must match one of the match arms!");
2165 }
2166
2167 fn eval_normal_pattern_list(
2168 &mut self,
2169 elements: &[PatternElement],
2170 expression_to_evaluate: &Expression,
2171 value_ref: ValueRef,
2172 ) -> Result<Value, ExecuteError> {
2173 if elements.len() == 1 {
2175 return match &elements[0] {
2176 PatternElement::Variable(var_ref)
2177 | PatternElement::VariableWithFieldIndex(var_ref, _) => {
2178 self.push_block_scope();
2179 self.current_block_scopes
2180 .initialize_var_mut(var_ref, value_ref);
2181 let result = self.evaluate_expression(expression_to_evaluate);
2182 self.pop_block_scope();
2183 result
2184 }
2185 PatternElement::Wildcard(_) => {
2186 self.evaluate_expression(expression_to_evaluate)
2188 }
2189 };
2190 }
2191
2192 if let Value::Tuple(_tuple_type_ref, values) = value_ref.borrow_mut().clone() {
2193 assert_eq!(
2194 elements.len(),
2195 values.len(),
2196 "must use all elements in tuple"
2197 );
2198 self.push_block_scope();
2199
2200 for (element, _inside_value) in elements.iter().zip(values.iter()) {
2201 match element {
2202 PatternElement::Variable(var_ref) => {
2203 self.current_block_scopes
2204 .initialize_var_mut(var_ref, value_ref.clone());
2205 }
2206 PatternElement::VariableWithFieldIndex(var_ref, _) => {
2207 self.current_block_scopes
2208 .initialize_var_mut(var_ref, value_ref.clone());
2209 }
2210 PatternElement::Wildcard(_) => {
2211 continue;
2213 }
2214 }
2215 }
2216
2217 let result = self.evaluate_expression(expression_to_evaluate);
2218 self.pop_block_scope();
2219
2220 return result;
2221 }
2222 panic!("should not get here")
2223 }
2224
2225 fn eval_normal_pattern_enum(
2226 &mut self,
2227 maybe_elements: Option<&Vec<PatternElement>>,
2228 expression_to_evaluate: &Expression,
2229 variant_ref: &EnumVariantTypeRef,
2230 value_ref: ValueRef,
2231 ) -> Result<Option<Value>, ExecuteError> {
2232 match value_ref.borrow_mut().clone() {
2233 Value::EnumVariantTuple(value_tuple_type, values) => {
2234 if variant_ref.common().number != value_tuple_type.common.number {
2236 return Ok(None); }
2238
2239 if let Some(elements) = maybe_elements {
2240 assert_eq!(elements.len(), values.len());
2241 self.push_block_scope();
2242
2243 for (element, value) in elements.iter().zip(values.iter()) {
2244 match element {
2245 PatternElement::Variable(var_ref) => {
2246 self.current_block_scopes
2247 .initialize_var_mut(var_ref, value.clone());
2248 }
2249 PatternElement::VariableWithFieldIndex(var_ref, _) => {
2250 self.current_block_scopes
2251 .initialize_var_mut(var_ref, value.clone());
2252 }
2253 PatternElement::Wildcard(_) => continue,
2254 }
2255 }
2256
2257 let result = self.evaluate_expression(&expression_to_evaluate);
2258 self.pop_block_scope();
2259 return Ok(Option::from(result?));
2260 } else {
2261 panic!("not work");
2262 }
2263 }
2264 Value::EnumVariantStruct(value_enum_struct_type, values) => {
2265 info!(
2266 ?value_enum_struct_type,
2267 ?variant_ref,
2268 "comparing enum variant struct match arm"
2269 );
2270 if value_enum_struct_type.common.number == variant_ref.common().number {
2271 info!(?value_enum_struct_type, ?variant_ref, "FOUND!");
2272 if let Some(elements) = maybe_elements {
2273 self.push_block_scope();
2274
2275 for element in elements {
2276 if let PatternElement::VariableWithFieldIndex(var_ref, field_index) =
2277 element
2278 {
2279 let value = &values[*field_index];
2280 info!(?value, "setting match arm variable");
2281 self.current_block_scopes.init_var_ref(var_ref, value);
2282 }
2283 }
2284
2285 let result = self.evaluate_expression(&expression_to_evaluate);
2286 self.pop_block_scope();
2287 return Ok(Some(result?));
2288 }
2289 }
2290 }
2291
2292 Value::EnumVariantSimple(value_variant_ref) => {
2293 if value_variant_ref.common.number == variant_ref.common().number
2294 && maybe_elements.is_none()
2295 {
2296 return Ok(Some(self.evaluate_expression(&expression_to_evaluate)?));
2297 }
2298 }
2299 _ => {
2300 panic!("could not find it")
2301 }
2302 }
2303
2304 Ok(None)
2305 }
2306
2307 #[inline(always)]
2308 const fn modulo(a: i32, b: i32) -> i32 {
2309 ((a % b) + b) % b
2310 }
2311
2312 #[inline(always)]
2313 const fn modulo_fp(a: Fp, b: Fp) -> Fp {
2314 let raw = ((a.inner() % b.inner()) + b.inner()) % b.inner();
2315 Fp::from_raw(raw)
2316 }
2317
2318 #[allow(clippy::too_many_lines)]
2319 fn evaluate_binary_op(
2320 &self,
2321 node: &Node,
2322 left_val: Value,
2323 op: &BinaryOperatorKind,
2324 right_val: Value,
2325 ) -> Result<Value, ExecuteError> {
2326 let result: Value = match (&left_val, op, &right_val) {
2327 (Value::Int(a), BinaryOperatorKind::Add, Value::Int(b)) => Value::Int(a + b),
2329 (Value::Int(a), BinaryOperatorKind::Subtract, Value::Int(b)) => Value::Int(a - b),
2330 (Value::Int(a), BinaryOperatorKind::Multiply, Value::Int(b)) => Value::Int(a * b),
2331 (Value::Int(a), BinaryOperatorKind::Divide, Value::Int(b)) => {
2332 if *b == 0 {
2333 return Err(self.create_err(ExecuteErrorKind::DivideByZero, node));
2334 }
2335 Value::Int(a / b)
2336 }
2337 (Value::Int(a), BinaryOperatorKind::Modulo, Value::Int(b)) => {
2338 Value::Int(Self::modulo(*a, *b))
2339 }
2340 (Value::Int(a), BinaryOperatorKind::Equal, Value::Int(b)) => Value::Bool(a == b),
2341 (Value::Int(a), BinaryOperatorKind::NotEqual, Value::Int(b)) => Value::Bool(a != b),
2342 (Value::Int(a), BinaryOperatorKind::LessThan, Value::Int(b)) => Value::Bool(a < b),
2343 (Value::Int(a), BinaryOperatorKind::GreaterThan, Value::Int(b)) => Value::Bool(a > b),
2344 (Value::Int(a), BinaryOperatorKind::LessEqual, Value::Int(b)) => Value::Bool(a <= b),
2345 (Value::Int(a), BinaryOperatorKind::GreaterEqual, Value::Int(b)) => Value::Bool(a >= b),
2346
2347 (Value::Float(a), BinaryOperatorKind::Equal, Value::Float(b)) => Value::Bool(a == b),
2349 (Value::Float(a), BinaryOperatorKind::NotEqual, Value::Float(b)) => Value::Bool(a != b),
2350
2351 (Value::Float(a), BinaryOperatorKind::Add, Value::Float(b)) => Value::Float(*a + *b),
2352 (Value::Float(a), BinaryOperatorKind::Subtract, Value::Float(b)) => {
2353 Value::Float(*a - *b)
2354 }
2355 (Value::Float(a), BinaryOperatorKind::Multiply, Value::Float(b)) => {
2356 Value::Float(*a * *b)
2357 }
2358 (Value::Float(a), BinaryOperatorKind::Divide, Value::Float(b)) => {
2359 if b.abs().inner() <= 400 {
2360 return Err(self.create_err(ExecuteErrorKind::DivideByZero, node));
2361 }
2362 Value::Float(*a / *b)
2363 }
2364 (Value::Float(a), BinaryOperatorKind::Modulo, Value::Float(b)) => {
2365 Value::Float(Self::modulo_fp(*a, *b))
2366 }
2367
2368 (Value::Float(a), BinaryOperatorKind::GreaterThan, Value::Float(b)) => {
2369 Value::Bool(a > b)
2370 }
2371 (Value::Float(a), BinaryOperatorKind::GreaterEqual, Value::Float(b)) => {
2372 Value::Bool(a >= b)
2373 }
2374 (Value::Float(a), BinaryOperatorKind::LessThan, Value::Float(b)) => Value::Bool(a < b),
2375 (Value::Float(a), BinaryOperatorKind::LessEqual, Value::Float(b)) => {
2376 Value::Bool(a <= b)
2377 }
2378
2379 (Value::Bool(a), BinaryOperatorKind::LogicalAnd, Value::Bool(b)) => {
2381 Value::Bool(*a && *b)
2382 }
2383 (Value::Bool(a), BinaryOperatorKind::LogicalOr, Value::Bool(b)) => {
2384 Value::Bool(*a || *b)
2385 }
2386
2387 (Value::RustValue(_, left), BinaryOperatorKind::Equal, Value::RustValue(_, right)) => {
2391 let left_borrow = left.borrow();
2392 let right_borrow = right.borrow();
2393 let equal = left_borrow.eq_dyn(&**right_borrow);
2394 Value::Bool(equal)
2395 }
2396 (
2397 Value::RustValue(_, left),
2398 BinaryOperatorKind::NotEqual,
2399 Value::RustValue(_, right),
2400 ) => {
2401 let left_borrow = left.borrow();
2402 let right_borrow = right.borrow();
2403 let equal = left_borrow.eq_dyn(&**right_borrow);
2404 Value::Bool(!equal)
2405 }
2406
2407 (Value::String(a), BinaryOperatorKind::Add, Value::String(b)) => {
2409 Value::String(a.to_owned() + b)
2410 }
2411 (Value::String(a), BinaryOperatorKind::Equal, Value::String(b)) => Value::Bool(a == b),
2412
2413 (Value::String(a), BinaryOperatorKind::Add, Value::Int(b)) => {
2414 Value::String(a.to_owned() + &(*b).to_string())
2415 }
2416 (Value::Int(a), BinaryOperatorKind::Add, Value::String(b)) => {
2417 Value::String(a.to_string() + b)
2418 }
2419
2420 (
2422 Value::EnumVariantSimple(a),
2423 BinaryOperatorKind::Equal,
2424 Value::EnumVariantSimple(b),
2425 ) => Value::Bool(a == b),
2426 (
2427 Value::EnumVariantSimple(a),
2428 BinaryOperatorKind::NotEqual,
2429 Value::EnumVariantSimple(b),
2430 ) => Value::Bool(a != b),
2431
2432 (Value::Bool(a), BinaryOperatorKind::Equal, Value::Bool(b)) => Value::Bool(a == b),
2434 (Value::Bool(a), BinaryOperatorKind::NotEqual, Value::Bool(b)) => Value::Bool(a != b),
2435
2436 (Value::Option(a), BinaryOperatorKind::Equal, Value::Option(b)) => Value::Bool(a == b),
2437
2438 _ => {
2439 error!(?op, "invalid binary operation!!");
2440 panic!("invalid binary operation"); }
2442 };
2443
2444 Ok(result)
2445 }
2446
2447 fn evaluate_unary_op(
2448 &self,
2449 node: &Node,
2450 op: &UnaryOperatorKind,
2451 val: Value,
2452 ) -> Result<Value, ExecuteError> {
2453 match (op, val) {
2454 (UnaryOperatorKind::Negate, Value::Int(n)) => Ok(Value::Int(-n)),
2455 (UnaryOperatorKind::Negate, Value::Float(n)) => Ok(Value::Float(-n)),
2456 (UnaryOperatorKind::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
2457 _ => Err(self.create_err(ExecuteErrorKind::DivideByZero, node)),
2458 }
2459 }
2460
2461 fn expressions_equal_to_values(
2462 &mut self,
2463 p0: &[Expression],
2464 p1: &[ValueRef],
2465 ) -> Result<bool, ExecuteError> {
2466 for (a, b_value) in p0.iter().zip(p1.iter()) {
2467 let a_value = self.evaluate_expression(a)?;
2468
2469 if a_value != *b_value.borrow() {
2470 return Ok(false);
2471 }
2472 }
2473
2474 Ok(true)
2475 }
2476
2477 #[inline(always)]
2478 fn apply_compound_operator(
2479 &self,
2480 node: &Node,
2481 target: &mut Value,
2482 operator: &CompoundOperatorKind,
2483 source: &Value,
2484 ) -> Result<(), ExecuteError> {
2485 match operator {
2486 CompoundOperatorKind::Mul => {
2487 *target = self.evaluate_binary_op(
2488 node,
2489 target.clone(),
2490 &BinaryOperatorKind::Multiply,
2491 source.clone(),
2492 )?;
2493 }
2494 CompoundOperatorKind::Div => {
2495 *target = self.evaluate_binary_op(
2496 node,
2497 target.clone(),
2498 &BinaryOperatorKind::Divide,
2499 source.clone(),
2500 )?;
2501 }
2502 CompoundOperatorKind::Add => {
2503 *target = self.evaluate_binary_op(
2504 node,
2505 target.clone(),
2506 &BinaryOperatorKind::Add,
2507 source.clone(),
2508 )?;
2509 }
2510 CompoundOperatorKind::Sub => {
2511 *target = self.evaluate_binary_op(
2512 node,
2513 target.clone(),
2514 &BinaryOperatorKind::Subtract,
2515 source.clone(),
2516 )?;
2517 }
2518 CompoundOperatorKind::Modulo => {
2519 *target = self.evaluate_binary_op(
2520 node,
2521 target.clone(),
2522 &BinaryOperatorKind::Modulo,
2523 source.clone(),
2524 )?;
2525 }
2526 }
2527 Ok(())
2528 }
2529
2530 fn create_err(&self, kind: ExecuteErrorKind, node: &Node) -> ExecuteError {
2638 ExecuteError {
2639 node: node.clone(),
2640 kind,
2641 }
2642 }
2643
2644 fn evaluate_intrinsic_mut(
2645 &mut self,
2646 node: &Node,
2647 intrinsic_fn: &IntrinsicFunction,
2648 location: &SingleMutLocationExpression,
2649 arguments: &Vec<Expression>,
2650 ) -> Result<Value, ExecuteError> {
2651 let val = match intrinsic_fn {
2652 IntrinsicFunction::VecSelfPush => {
2653 let source_val = self.evaluate_expression(&arguments[0])?;
2654 let array_val_ref = self.evaluate_location(&location.0)?;
2655
2656 match &mut *array_val_ref.borrow_mut() {
2657 Value::Array(_type_id, vector) => {
2658 vector.push(Rc::new(RefCell::new(source_val)));
2659 }
2660 _ => {
2661 Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &node))?;
2662 }
2663 }
2664 Value::Unit
2666 }
2667 IntrinsicFunction::VecSelfExtend => {
2668 let source_val = self.evaluate_expression(&arguments[0])?;
2669
2670 let array_val_ref = self.evaluate_location(&location.0)?;
2671 match &mut *array_val_ref.borrow_mut() {
2672 Value::Array(_type_id, vector) => match source_val {
2673 Value::Array(_, items) => {
2674 vector.extend(items);
2675 }
2676 _ => {
2677 Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &node))?;
2678 }
2679 },
2680 _ => {
2681 todo!("handle error")
2682 }
2683 }
2684
2685 Value::Unit
2687 }
2688 _ => return Err(self.create_err(ExecuteErrorKind::UnknownMutIntrinsic, &node)),
2689 };
2690
2691 Ok(val)
2692 }
2693}
2694
2695#[inline]
2696#[must_use]
2697pub fn i64_sqrt(v: i64) -> i64 {
2698 assert!(v >= 0, "negative numbers are undefined for sqrt() {v}");
2699
2700 if v == 0 {
2701 return v;
2702 }
2703
2704 const MAX_ITERATIONS: usize = 40;
2705 const TOLERANCE: i64 = 2;
2706
2707 let mut guess = v / 2;
2708
2709 for _ in 0..MAX_ITERATIONS {
2710 let next_guess = (guess + v / guess) / 2;
2711
2712 if (next_guess - guess).abs() <= TOLERANCE {
2714 return next_guess;
2715 }
2716
2717 guess = next_guess;
2718 }
2719
2720 guess }
2722
2723#[allow(unused)]
2724pub fn values_to_value_refs(values: &[Value]) -> Vec<ValueRef> {
2725 let mut items = Vec::new();
2726
2727 for x in values.iter().cloned() {
2728 items.push(Rc::new(RefCell::new(x)));
2729 }
2730
2731 items
2732}
2733
2734pub fn values_to_value_refs_owned(values: Vec<Value>) -> Vec<ValueRef> {
2735 values
2736 .into_iter()
2737 .map(|x| Rc::new(RefCell::new(x)))
2738 .collect()
2739}
2740
2741pub fn wrap_in_option(maybe: Option<&ValueRef>) -> ValueRef {
2742 match maybe {
2743 None => Rc::new(RefCell::new(Value::Option(None))),
2744 Some(x) => Rc::new(RefCell::new(Value::Option(Some(x.clone())))),
2745 }
2746}