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_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 Ok(value_with_signal.try_into().map_err(|_| ExecuteError {
169 node: Default::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_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::Struct(
927 struct_instantiation.struct_type_ref.clone(),
928 convert_vec_to_rc_refcell(field_values),
929 )
930 }
931
932 ExpressionKind::Range(start, end, range_mode) => {
933 let start_val = self.evaluate_expression(start)?;
934 let end_val = self.evaluate_expression(end)?;
935 match (start_val, end_val) {
936 (Value::Int(s), Value::Int(e)) => {
937 Value::Range(Box::new(s), Box::new(e), range_mode.clone())
938 }
939 _ => Err(self.create_err(ExecuteErrorKind::RangeItemMustBeInt, &expr.node))?,
940 }
941 }
942
943 ExpressionKind::VariableDefinition(target_var, source_expr) => {
945 let source_value_or_reference =
946 self.evaluate_mut_or_immutable_expression(source_expr)?;
947
948 self.current_block_scopes
949 .initialize_var_mem(target_var, source_value_or_reference.clone())?;
950
951 source_value_or_reference.to_value().clone()
952 }
953
954 ExpressionKind::VariableReassignment(variable_ref, source_expr) => {
955 let new_value = self.evaluate_mut_or_immutable_expression(source_expr)?;
956
957 let value_ref = self
958 .current_block_scopes
959 .lookup_variable_mut_ref(variable_ref)?;
960
961 let mut was_assigned = false;
962 if let Value::Option(inner_value) = &*value_ref.borrow() {
963 if let Some(inner) = inner_value {
964 *inner.borrow_mut() = new_value.to_value();
965 was_assigned = true;
966 }
967 }
968
969 if !was_assigned {
970 self.current_block_scopes
971 .overwrite_existing_var_mem(variable_ref, new_value.clone())?;
972 }
973
974 Value::Unit
975 }
976
977 ExpressionKind::IntrinsicCallMut(intrinsic, location, arguments) => {
978 self.evaluate_intrinsic_mut(&expr.node, intrinsic, location, arguments)?
979 }
980
981 ExpressionKind::MapAssignment(map, index, value) => {
982 let map_val = self.evaluate_location(&map.0)?;
983 let index_val = self.evaluate_expression(index)?;
984 let new_val = self.evaluate_expression(value)?;
985
986 match &mut *map_val.borrow_mut() {
987 Value::Map(_type_id, elements) => {
988 elements
989 .insert(index_val, Rc::new(RefCell::new(new_val)))
990 .map_err(|_| {
991 self.create_err(ExecuteErrorKind::MapKeyAlreadyExists, &expr.node)
992 })?;
993 }
994 _ => {
995 Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &expr.node))?;
996 }
997 }
998
999 Value::Unit
1000 }
1001
1002 ExpressionKind::ConstantAccess(constant) => {
1004 self.constants.lookup_constant_value(constant.id).clone()
1005 }
1006
1007 ExpressionKind::AssignmentSlice(_mut_location, _source) => todo!(),
1008
1009 ExpressionKind::Assignment(mut_location_expr, source_expr) => {
1010 let value_ref = self.evaluate_location(&mut_location_expr.0)?;
1011 let source_value = self.evaluate_expression(source_expr)?;
1012
1013 *value_ref.borrow_mut() = source_value;
1014
1015 Value::Unit
1016 }
1017
1018 ExpressionKind::CompoundAssignment(mut_location_expr, op, source_expr) => {
1019 let value_ref = self.evaluate_location(&mut_location_expr.0)?;
1020 let source_value = self.evaluate_expression(source_expr)?;
1021
1022 self.apply_compound_operator(
1023 &expr.node,
1024 &mut value_ref.borrow_mut(),
1025 op,
1026 &source_value,
1027 )?;
1028
1029 Value::Unit
1030 }
1031
1032 ExpressionKind::BinaryOp(binary_operator) => {
1034 let left_val = self.evaluate_expression(&binary_operator.left)?;
1035 let right_val = self.evaluate_expression(&binary_operator.right)?;
1036 self.evaluate_binary_op(&expr.node, left_val, &binary_operator.kind, right_val)?
1037 }
1038
1039 ExpressionKind::UnaryOp(unary_operator) => {
1040 let left_val = self.evaluate_expression(&unary_operator.left)?;
1041 self.evaluate_unary_op(&expr.node, &unary_operator.kind, left_val)?
1042 }
1043
1044 ExpressionKind::FunctionCall(_signature, expr, arguments) => {
1046 self.evaluate_function_call(expr, arguments)?
1047 }
1048
1049 ExpressionKind::MemberCall(resolved_member_call) => {
1050 let parameters = match &*resolved_member_call.function {
1051 Function::Internal(function_data) => &function_data.signature.parameters,
1052 Function::External(external_data) => &external_data.signature.parameters,
1053 };
1054
1055 let mut member_call_arguments = Vec::new();
1056 member_call_arguments.extend(self.evaluate_args(&resolved_member_call.arguments)?);
1057
1058 if member_call_arguments.len() != parameters.len() {
1060 return Err(self.create_err(
1061 ExecuteErrorKind::WrongNumberOfArguments(
1062 parameters.len(),
1063 member_call_arguments.len(),
1064 ),
1065 &expr.node,
1066 ));
1067 }
1068
1069 match &*resolved_member_call.function {
1070 Function::Internal(internal_function) => {
1071 self.push_function_scope();
1072 self.bind_parameters(
1073 &expr.node,
1074 &internal_function.signature.parameters,
1075 &member_call_arguments,
1076 )?;
1077 let result = self.evaluate_expression(&internal_function.body)?;
1078 self.pop_function_scope();
1079
1080 result
1081 }
1082 Function::External(external_func) => {
1083 let mut func = self
1084 .externals
1085 .external_functions_by_id
1086 .get(&external_func.id)
1087 .expect("member call: external function missing")
1088 .borrow_mut();
1089 (func.func)(&member_call_arguments, self.context)?
1090 }
1091 }
1092 }
1093
1094 ExpressionKind::Block(statements) => {
1095 self.evaluate_block(statements)?.try_into().unwrap() }
1097
1098 ExpressionKind::InterpolatedString(parts) => {
1099 let mut result = String::new();
1100
1101 for part in parts {
1102 match part {
1103 StringPart::Literal(_resolved_node, text) => {
1104 result.push_str(text);
1105 }
1106 StringPart::Interpolation(expr, format_spec) => {
1107 let value = self.evaluate_expression(expr)?;
1108 let formatted = match format_spec {
1109 Some(spec) => format_value(&value, &spec.kind).unwrap(), None => value.convert_to_string_if_needed(),
1111 };
1112 result.push_str(&formatted);
1113 }
1114 }
1115 }
1116
1117 Value::String(result)
1118 }
1119
1120 ExpressionKind::Match(resolved_match) => self.eval_match(resolved_match)?,
1121 ExpressionKind::Guard(guards) => self.eval_guard(&expr.node, guards)?,
1122
1123 ExpressionKind::InternalFunctionAccess(fetch_function) => {
1124 Value::InternalFunction(fetch_function.clone())
1125 }
1126
1127 ExpressionKind::ExternalFunctionAccess(fetch_function) => {
1128 self.externals
1129 .external_functions_by_id
1130 .get(&fetch_function.id)
1131 .expect("should have external function ref");
1132 Value::ExternalFunction(fetch_function.clone())
1133 }
1134
1135 ExpressionKind::Tuple(_) => todo!(),
1137 ExpressionKind::Option(inner) => match inner {
1138 None => Value::Option(None),
1139 Some(expression) => {
1140 let v = self.evaluate_expression(expression)?;
1141 match v {
1142 Value::Option(_) => {
1143 panic!("unnecessary wrap!, should be investigated");
1144 }
1145 _ => Value::Option(Some(Rc::new(RefCell::new(v)))),
1146 }
1147 }
1148 },
1149
1150 ExpressionKind::SparseNew(sparse_id_rust_type_ref, resolved_value_item_type) => {
1152 let sparse_value_map = SparseValueMap::new(
1153 sparse_id_rust_type_ref.clone(),
1154 resolved_value_item_type.clone(),
1155 );
1156 to_rust_value(sparse_id_rust_type_ref.clone(), sparse_value_map)
1157 }
1158
1159 ExpressionKind::CoerceOptionToBool(expression) => {
1160 let value = self.evaluate_expression(expression)?;
1161 match value {
1162 Value::Option(inner) => Value::Bool(inner.is_some()),
1163 _ => {
1164 return Err(
1165 self.create_err(ExecuteErrorKind::CoerceOptionToBoolFailed, &expr.node)
1166 );
1167 }
1168 }
1169 }
1170
1171 ExpressionKind::If(condition, consequences, optional_alternative) => {
1172 let cond_value = self.evaluate_expression(&condition.expression)?;
1173 if cond_value.is_truthy().unwrap() {
1174 self.evaluate_expression(consequences)?
1176 } else if let Some(alternative) = optional_alternative {
1177 self.evaluate_expression(alternative)?
1178 } else {
1179 Value::Unit
1180 }
1181 }
1182
1183 ExpressionKind::When(bindings, true_block, maybe_else_block) => {
1184 let mut all_are_some = true;
1185 let mut all_expressions = Vec::new();
1186 for binding in bindings {
1187 let source = self.evaluate_mut_or_immutable_expression(&binding.expr)?;
1188 match source.to_value() {
1189 Value::Option(boxed_val) => match boxed_val {
1190 Some(found_val) => {
1191 all_expressions.push(found_val.borrow().clone());
1192 }
1193 _ => {
1194 all_are_some = false;
1195 break;
1196 }
1197 },
1198 _ => {
1199 return Err(self
1200 .create_err(ExecuteErrorKind::ExpectedOptional, &true_block.node));
1201 }
1202 }
1203 }
1204
1205 if all_are_some {
1206 self.push_block_scope();
1207
1208 for (binding, value) in bindings.iter().zip(all_expressions) {
1209 info!(var=?binding.variable, "binding as mutable");
1210 self.current_block_scopes.initialize_var(
1211 binding.variable.scope_index,
1212 binding.variable.variable_index,
1213 value,
1214 binding.variable.is_mutable(),
1215 );
1216 }
1217
1218 let result = self.evaluate_expression(true_block)?;
1219 self.pop_block_scope();
1220
1221 result
1222 } else if let Some(else_block) = maybe_else_block {
1223 self.evaluate_expression(else_block)?
1224 } else {
1225 Value::Unit
1226 }
1227 }
1228
1229 ExpressionKind::TupleDestructuring(variable_refs, _, expr) => {
1230 let value = self.evaluate_expression(expr)?;
1231 if let Value::Tuple(_tuple_ref, values) = value {
1232 if variable_refs.len() > values.len() {
1233 return Err(self.create_err(ExecuteErrorKind::NotAnArray, &expr.node));
1234 }
1235 for (index, variable_ref) in variable_refs.iter().enumerate() {
1236 let value = &values[index].borrow().clone();
1237 self.current_block_scopes.initialize_var(
1238 variable_ref.scope_index,
1239 variable_ref.variable_index,
1240 value.clone(),
1241 false,
1242 );
1243 }
1244 }
1245 Value::Unit
1246 }
1247 ExpressionKind::VariableAccess(variable_ref) => {
1248 let temp = self.current_block_scopes.lookup_var_value(variable_ref);
1249 assert_ne!(temp, Value::Unit);
1250 temp
1251 }
1252 ExpressionKind::FieldAccess(expr, index) => {
1253 let resolved_expr = self.evaluate_expression(expr)?;
1254 let (_struct_type, values) = resolved_expr
1255 .expect_struct()
1256 .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedStruct, &expr.node))?;
1257
1258 let x = values[*index].borrow().clone();
1259 x
1260 }
1261
1262 ExpressionKind::ArrayAccess(expr, _array, index_expr) => {
1263 let resolved_expr = self.evaluate_expression(expr)?;
1264 let (_array_type, values) = resolved_expr
1265 .expect_array()
1266 .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedArray, &expr.node))?;
1267
1268 let index = self
1269 .evaluate_expression(index_expr)?
1270 .expect_int()
1271 .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedInt, &expr.node))?
1272 as usize;
1273
1274 let x = values[index].borrow().clone();
1275 x
1276 }
1277
1278 ExpressionKind::MapIndexAccess(expr, _map_type_ref, key_expr) => {
1279 let resolved_expr = self.evaluate_expression(expr)?;
1280 let (_map_type, seq_map) = resolved_expr
1281 .expect_map()
1282 .map_err(|_| self.create_err(ExecuteErrorKind::ExpectedMap, &expr.node))?;
1283
1284 let key_val = self.evaluate_expression(key_expr)?;
1285
1286 let value_val_maybe = seq_map.get(&key_val);
1287 Value::Option(value_val_maybe.cloned())
1288 }
1289 ExpressionKind::StringRangeAccess(_, _) => todo!(),
1290 ExpressionKind::ArrayRangeAccess(_, _) => todo!(),
1291 ExpressionKind::PostfixChain(start, parts) => {
1292 let value_ref = self.eval_chain(&expr.node, start, parts)?;
1293 let x = value_ref.borrow().clone();
1294 x
1295 }
1296 };
1297
1298 self.depth -= 1;
1299 Ok(value)
1302 }
1303
1304 fn evaluate_literal(&mut self, node: &Node, lit: &Literal) -> Result<Value, ExecuteError> {
1305 let v = match lit {
1306 Literal::IntLiteral(n) => Value::Int(*n),
1307 Literal::FloatLiteral(f) => Value::Float(*f),
1308 Literal::StringLiteral(s) => Value::String(s.clone()),
1309 Literal::BoolLiteral(b) => Value::Bool(*b),
1310
1311 Literal::EnumVariantLiteral(enum_variant_type, data) => {
1312 let variant_container_value: Value = match &**enum_variant_type {
1313 EnumVariantType::Tuple(tuple_type) => match data {
1314 EnumLiteralData::Tuple(tuple_expressions) => {
1315 let eval_expressions = self.evaluate_expressions(tuple_expressions)?;
1316 let value_refs = values_to_value_refs_owned(eval_expressions);
1317 Value::EnumVariantTuple(tuple_type.clone(), value_refs)
1318 }
1319 _ => panic!("wrong container type"),
1320 },
1321
1322 EnumVariantType::Struct(struct_type_ref) => match data {
1323 EnumLiteralData::Struct(source_order_field_values) => {
1324 let mut field_values =
1325 Vec::with_capacity(source_order_field_values.len());
1326 field_values
1327 .resize_with(source_order_field_values.len(), Default::default);
1328 for (index, resolved_expression) in source_order_field_values {
1329 let value = self.evaluate_expression(resolved_expression)?;
1330 field_values[*index] = Rc::new(RefCell::new(value));
1331 }
1332 Value::EnumVariantStruct(struct_type_ref.clone(), field_values)
1333 }
1334 _ => panic!("wrong container type"),
1335 },
1336
1337 EnumVariantType::Nothing(data) => Value::EnumVariantSimple(data.clone()),
1338 };
1339 variant_container_value
1340 }
1341
1342 Literal::TupleLiteral(tuple_type, resolved_expressions) => {
1343 let values = self.evaluate_expressions(resolved_expressions)?;
1344 Value::Tuple(tuple_type.clone(), convert_vec_to_rc_refcell(values))
1345 }
1346
1347 Literal::Array(array_type, expressions) => {
1348 let values = self.evaluate_expressions(expressions)?;
1349 Value::Array(array_type.clone(), convert_vec_to_rc_refcell(values))
1350 }
1351 Literal::Map(map_type_ref, expressions) => {
1352 let mut items = SeqMap::new();
1353 for (key, value) in expressions {
1354 let key_val = self.evaluate_expression(key)?;
1355 let value_val = self.evaluate_expression(value)?;
1356 items
1357 .insert(key_val, Rc::new(RefCell::new(value_val)))
1358 .map_err(|_err| {
1359 self.create_err(
1360 ExecuteErrorKind::NonUniqueKeysInMapLiteralDetected,
1361 &node,
1362 )
1363 })?;
1364 }
1365 Value::Map(map_type_ref.clone(), items)
1366 }
1367 Literal::NoneLiteral => Value::Option(None),
1368 };
1369 Ok(v)
1370 }
1371
1372 #[allow(clippy::too_many_lines)]
1373 fn eval_intrinsic_postfix(
1374 &mut self,
1375 node: &Node,
1376 value_ref: &ValueRef,
1377 intrinsic_function: &IntrinsicFunction,
1379 arguments: &[Expression],
1380 ) -> Result<Value, ExecuteError> {
1381 let val = match &intrinsic_function {
1383 IntrinsicFunction::VecRemoveIndex => {
1384 let index_val = self.evaluate_expression(&arguments[0])?;
1385 let Value::Int(index) = index_val else {
1386 return Err(self.create_err(ExecuteErrorKind::ArgumentIsNotMutable, node));
1387 };
1388
1389 match &mut *value_ref.borrow_mut() {
1390 Value::Array(_type_id, vector) => {
1391 vector.remove(index as usize);
1392 }
1393 _ => {
1394 Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?;
1395 }
1396 }
1397
1398 value_ref.borrow().clone()
1399 }
1400
1401 IntrinsicFunction::VecClear => {
1402 match &mut *value_ref.borrow_mut() {
1403 Value::Array(_type_id, vector) => {
1404 vector.clear();
1405 }
1406 _ => {
1407 Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?;
1408 }
1409 }
1410 Value::Unit
1411 }
1412
1413 IntrinsicFunction::VecPush => {
1414 match &mut *value_ref.borrow_mut() {
1415 Value::Array(_type_id, vector) => {
1416 let value_to_add = self.evaluate_expression(&arguments[0])?;
1417 vector.push(Rc::new(RefCell::new(value_to_add)));
1418 }
1419 _ => {
1420 Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?;
1421 }
1422 }
1423 Value::Unit
1424 }
1425
1426 IntrinsicFunction::VecLen => match &mut *value_ref.borrow_mut() {
1427 Value::Array(_type_id, vector) => {
1428 let length = vector.len();
1429 Value::Int(length as i32)
1430 }
1431 _ => Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?,
1432 },
1433
1434 IntrinsicFunction::VecPop => match &mut *value_ref.borrow_mut() {
1435 Value::Array(_type_id, vector) => {
1436 let maybe_val = vector.pop();
1437 Value::Option(maybe_val)
1438 }
1439 _ => Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, node))?,
1440 },
1441
1442 IntrinsicFunction::MapHas => {
1443 let index_val = self.evaluate_expression(&arguments[0])?;
1444
1445 match value_ref.borrow().clone() {
1446 Value::Map(_type_id, ref seq_map) => {
1447 let has_key = seq_map.contains_key(&index_val);
1448 Value::Bool(has_key)
1449 }
1450 _ => {
1451 return Err(self.create_err(ExecuteErrorKind::NotAMap, node));
1452 }
1453 }
1454 }
1455
1456 IntrinsicFunction::MapRemove => {
1457 let index_val = self.evaluate_expression(&arguments[0])?;
1458
1459 let result = {
1460 let mut borrowed = value_ref.borrow_mut();
1461 match &mut *borrowed {
1462 Value::Map(_type_id, seq_map) => {
1463 let x = seq_map.remove(&index_val);
1464 x.map_or_else(
1465 || Value::Option(None),
1466 |v| Value::Option(Some(v.clone())),
1467 )
1468 }
1469 _ => {
1470 return Err(self.create_err(ExecuteErrorKind::NotAMap, node));
1471 }
1472 }
1473 };
1474 result
1475 }
1476
1477 IntrinsicFunction::SparseAdd => {
1478 let borrowed = value_ref.borrow();
1479
1480 let sparse_value_map = borrowed.downcast_rust::<SparseValueMap>();
1481 match sparse_value_map {
1482 Some(found) => {
1483 let resolved_value = self.evaluate_expression(&arguments[0])?;
1484 let id_value = found.borrow_mut().add(resolved_value);
1485
1486 id_value
1487 }
1488 _ => {
1489 return Err(self.create_err(ExecuteErrorKind::NotSparseValue, node));
1490 }
1491 }
1492 }
1493
1494 IntrinsicFunction::SparseRemove => {
1495 let borrowed = value_ref.borrow();
1496
1497 let sparse_value_map = borrowed.downcast_rust::<SparseValueMap>();
1498 if let Some(found) = sparse_value_map {
1499 let id_value = self.evaluate_expression(&arguments[0])?;
1500 match id_value.downcast_rust::<SparseValueId>() {
1501 Some(found_id) => {
1502 found.borrow_mut().remove(&found_id.borrow());
1503 }
1504 _ => {
1505 return Err(self.create_err(ExecuteErrorKind::NotSparseValue, node));
1506 }
1507 }
1508 }
1509
1510 Value::Unit
1511 }
1512 IntrinsicFunction::SparseSubscript => {
1513 let sparse_value_map = value_ref.borrow_mut().downcast_rust::<SparseValueMap>();
1514 match sparse_value_map {
1515 Some(found) => {
1516 let id_value = self.evaluate_expression(&arguments[0])?; match id_value.downcast_rust::<SparseValueId>() {
1518 Some(found_id) => match found.borrow_mut().get(&found_id.borrow()) {
1519 Some(found_value) => Value::Option(Some(found_value.clone())),
1520 _ => Value::Option(None),
1521 },
1522 _ => {
1523 return Err(self.create_err(ExecuteErrorKind::NotSparseId, node));
1524 }
1525 }
1526 }
1527 _ => {
1528 return Err(self.create_err(ExecuteErrorKind::NotSparseId, node));
1529 }
1530 }
1531 }
1532
1533 IntrinsicFunction::FloatRound => match value_ref.borrow().clone() {
1534 Value::Float(f) => Value::Int(f.round().into()),
1535 _ => {
1536 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1537 }
1538 },
1539 IntrinsicFunction::FloatFloor => match value_ref.borrow().clone() {
1540 Value::Float(f) => Value::Int(f.floor().into()),
1541 _ => {
1542 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1543 }
1544 },
1545
1546 IntrinsicFunction::FloatSign => match value_ref.borrow().clone() {
1547 Value::Float(f) => {
1548 let signum = if f.inner() < 0 {
1549 -1
1550 } else if f.inner() > 0 {
1551 1
1552 } else {
1553 0
1554 };
1555 Value::Float(Fp::from(signum as i16))
1556 }
1557 _ => {
1558 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1559 }
1560 },
1561 IntrinsicFunction::FloatAbs => match value_ref.borrow().clone() {
1562 Value::Float(f) => Value::Float(f.abs()),
1563 _ => {
1564 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1565 }
1566 },
1567
1568 IntrinsicFunction::FloatCos => match value_ref.borrow().clone() {
1569 Value::Float(f) => Value::Float(f.cos()),
1570 _ => {
1571 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1572 }
1573 },
1574
1575 IntrinsicFunction::FloatAcos => match value_ref.borrow().clone() {
1576 Value::Float(f) => Value::Float(f.acos()),
1577 _ => {
1578 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1579 }
1580 },
1581
1582 IntrinsicFunction::FloatSin => match value_ref.borrow().clone() {
1583 Value::Float(f) => Value::Float(f.sin()),
1584 _ => {
1585 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1586 }
1587 },
1588
1589 IntrinsicFunction::FloatAsin => match value_ref.borrow().clone() {
1590 Value::Float(f) => Value::Float(f.asin()),
1591 _ => {
1592 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1593 }
1594 },
1595
1596 IntrinsicFunction::FloatSqrt => match value_ref.borrow().clone() {
1597 Value::Float(f) => Value::Float(f.sqrt()),
1598 _ => {
1599 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1600 }
1601 },
1602
1603 IntrinsicFunction::FloatMin => {
1604 let min_value = self.evaluate_expression(&arguments[0])?;
1605 match (value_ref.borrow().clone(), min_value) {
1606 (Value::Float(f), Value::Float(min_f)) => Value::Float(f.min(min_f)),
1607 _ => {
1608 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1609 }
1610 }
1611 }
1612
1613 IntrinsicFunction::FloatMax => {
1614 let max_value = self.evaluate_expression(&arguments[0])?;
1615 match (value_ref.borrow().clone(), max_value) {
1616 (Value::Float(f), Value::Float(max_f)) => Value::Float(f.max(max_f)),
1617 _ => {
1618 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1619 }
1620 }
1621 }
1622
1623 IntrinsicFunction::FloatAtan2 => {
1624 let x_value = self.evaluate_expression(&arguments[0])?;
1625 match (value_ref.borrow().clone(), x_value) {
1626 (Value::Float(_y_f), Value::Float(_x_f)) => {
1627 Value::Float(Fp::from(-9999)) }
1629 _ => {
1630 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1631 }
1632 }
1633 }
1634
1635 IntrinsicFunction::FloatClamp => {
1636 let min_value = self.evaluate_expression(&arguments[0])?;
1637 let max_value = self.evaluate_expression(&arguments[1])?;
1638 match (value_ref.borrow().clone(), min_value, max_value) {
1639 (Value::Float(f), Value::Float(min_f), Value::Float(max_f)) => {
1640 Value::Float(f.clamp(min_f, max_f))
1641 }
1642 _ => {
1643 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1644 }
1645 }
1646 }
1647
1648 IntrinsicFunction::FloatRnd => match value_ref.borrow().clone() {
1649 Value::Float(f) => {
1650 let new_raw = squirrel_prng::squirrel_noise5(f.inner() as u32, 0);
1651 Value::Int(new_raw as i32)
1652 }
1653 _ => {
1654 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1655 }
1656 },
1657
1658 IntrinsicFunction::IntAbs => match value_ref.borrow().clone() {
1659 Value::Int(i) => Value::Int(i.abs()),
1660 _ => {
1661 return Err(self.create_err(ExecuteErrorKind::ExpectedFloat, node));
1662 }
1663 },
1664
1665 IntrinsicFunction::IntClamp => {
1666 let min_value = self.evaluate_expression(&arguments[0])?;
1667 let max_value = self.evaluate_expression(&arguments[1])?;
1668 match (value_ref.borrow().clone(), min_value, max_value) {
1669 (Value::Int(i), Value::Int(min_i), Value::Int(max_i)) => {
1670 Value::Int(i.clamp(min_i, max_i))
1671 }
1672 _ => {
1673 return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1674 }
1675 }
1676 }
1677
1678 IntrinsicFunction::IntMin => {
1679 let max_value = self.evaluate_expression(&arguments[0])?;
1680 match (value_ref.borrow().clone(), max_value) {
1681 (Value::Int(i), Value::Int(min_i)) => Value::Int(i.min(min_i)),
1682 _ => {
1683 return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1684 }
1685 }
1686 }
1687
1688 IntrinsicFunction::IntMax => {
1689 let max_value = self.evaluate_expression(&arguments[0])?;
1690 match (value_ref.borrow().clone(), max_value) {
1691 (Value::Int(i), Value::Int(max_i)) => Value::Int(i.max(max_i)),
1692 _ => {
1693 return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1694 }
1695 }
1696 }
1697
1698 IntrinsicFunction::IntRnd => match value_ref.borrow().clone() {
1699 Value::Int(i) => Value::Int(squirrel_prng::squirrel_noise5(i as u32, 0) as i32),
1700 _ => {
1701 return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1702 }
1703 },
1704
1705 IntrinsicFunction::IntToFloat => match value_ref.borrow().clone() {
1706 Value::Int(i) => Value::Float(Fp::from(i as i16)),
1707 _ => {
1708 return Err(self.create_err(ExecuteErrorKind::ExpectedInt, node));
1709 }
1710 },
1711
1712 IntrinsicFunction::StringLen => match value_ref.borrow().clone() {
1713 Value::String(s) => Value::Int(s.len().try_into().expect("string len overflow")),
1714 _ => {
1715 return Err(self.create_err(ExecuteErrorKind::ExpectedString, node));
1716 }
1717 },
1718
1719 IntrinsicFunction::Float2Magnitude => match value_ref.borrow().clone() {
1720 Value::Tuple(_tuple_ref, values) => {
1721 if values.len() != 2 {
1722 return Err(self.create_err(
1723 ExecuteErrorKind::WrongNumberOfArguments(2, values.len()),
1724 &node,
1725 ));
1726 }
1727 match (
1728 values[0].as_ref().borrow().clone(),
1729 values[1].as_ref().borrow().clone(),
1730 ) {
1731 (Value::Float(a), Value::Float(b)) => {
1732 let a_raw: i64 = a.inner() as i64;
1733 let b_raw: i64 = b.inner() as i64;
1734
1735 let i64_magnitude = i64_sqrt(a_raw * a_raw + b_raw * b_raw);
1736
1737 let new_fp = Fp::from_raw(
1738 i32::try_from(i64_magnitude).expect("wrong with i64_sqrt"),
1739 );
1740 Value::Float(new_fp)
1741 }
1742 _ => {
1743 return Err(
1744 self.create_err(ExecuteErrorKind::ExpectedTwoFloatTuple, node)
1745 );
1746 }
1747 }
1748 }
1749 _ => {
1750 return Err(self.create_err(ExecuteErrorKind::ExpectedTwoFloatTuple, node));
1751 }
1752 },
1753
1754 _ => todo!("{intrinsic_function:?} not implemented"),
1755 };
1756
1757 Ok(val)
1758 }
1759
1760 #[allow(clippy::too_many_lines)]
1761 fn eval_chain(
1762 &mut self,
1763 node: &Node,
1764 start: &Expression,
1765 parts: &[Postfix],
1766 ) -> Result<ValueRef, ExecuteError> {
1767 let (mut val_ref, mut is_mutable) = match &start.kind {
1768 ExpressionKind::VariableAccess(start_var) => {
1769 let start_variable_value = self.current_block_scopes.get_var(&start_var);
1770
1771 match start_variable_value {
1772 VariableValue::Value(value) => {
1773 assert_ne!(*value, Value::Unit);
1774 (Rc::new(RefCell::new(value.clone())), false)
1775 }
1776 VariableValue::Reference(value_ref) => {
1777 assert_ne!(value_ref.borrow().clone(), Value::Unit);
1778 (value_ref.clone(), true)
1779 }
1780 }
1781 }
1782 _ => (
1783 Rc::new(RefCell::new(self.evaluate_expression(start)?)),
1784 false,
1785 ),
1786 };
1787
1788 let mut is_uncertain = false;
1789 let mut is_undefined = false;
1790
1791 for part in parts {
1792 if let PostfixKind::NoneCoalesce(default_expression) = &part.kind {
1793 val_ref = {
1794 let borrowed = val_ref.borrow();
1795
1796 match borrowed.clone() {
1797 Value::Option(found_option) => match found_option {
1798 Some(some_value) => some_value,
1799 _ => {
1800 let default_value = self.evaluate_expression(default_expression)?;
1801 Rc::new(RefCell::new(default_value))
1802 }
1803 },
1804 _ => {
1805 return Err(
1806 self.create_err(ExecuteErrorKind::ExpectedOptional, &part.node)
1807 );
1808 }
1809 }
1810 };
1811
1812 is_mutable = false;
1813 is_uncertain = false;
1814 is_undefined = false;
1815 } else if is_undefined {
1816 continue;
1817 }
1818 match &part.kind {
1819 PostfixKind::NoneCoalesce(_default_expression) => {
1820 }
1822 PostfixKind::StructField(expected_struct_type, index) => {
1823 let (encountered_struct_type, fields) = {
1824 let brw = val_ref.borrow();
1825 let (struct_ref, fields_ref) = brw.expect_struct().map_err(|_| {
1826 self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1827 })?;
1828 (struct_ref.clone(), fields_ref.clone())
1829 };
1830
1831 assert!(same_struct_ref(
1832 &encountered_struct_type,
1833 expected_struct_type
1834 ));
1835 val_ref = fields[*index].clone();
1836 }
1837 PostfixKind::ArrayIndex(expected_array_type, index_expr) => {
1838 let (encountered_array_type, fields) = {
1839 let brw = val_ref.borrow();
1840 let (array_ref, fields_ref) = brw.expect_array().map_err(|_| {
1841 self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1842 })?;
1843 (array_ref.clone(), fields_ref.clone())
1844 };
1845 assert!(same_array_ref(&encountered_array_type, expected_array_type));
1846
1847 let index =
1848 self.evaluate_expression(index_expr)?
1849 .expect_int()
1850 .map_err(|_| {
1851 self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1852 })? as usize;
1853 if index >= fields.len() {
1854 return Err(self.create_err(ExecuteErrorKind::IndexOutOfBounds, &part.node));
1855 }
1856 val_ref = fields[index].clone();
1857 }
1858 PostfixKind::MapIndex(_expected_map_type_ref, key_expr) => {
1859 let (_encountered_map_type, seq_map) = {
1860 let brw = val_ref.borrow();
1861 let (array_ref, seq_map) = brw.expect_map().map_err(|_| {
1862 self.create_err(ExecuteErrorKind::PostfixChainError, &part.node)
1863 })?;
1864 (array_ref.clone(), seq_map.clone())
1865 };
1866 let key_val = self.evaluate_expression(key_expr)?;
1867
1868 val_ref = Rc::new(RefCell::new(Value::Option(seq_map.get(&key_val).cloned())));
1869 }
1870 PostfixKind::ExternalTypeIndexRef(_rust_type_ref, map_expr) => {
1871 let key_expr_value = self.evaluate_expression(map_expr)?;
1872 val_ref = {
1873 match key_expr_value.downcast_rust::<SparseValueId>() {
1874 Some(found_sparse_id) => {
1875 match val_ref.borrow_mut().downcast_rust::<SparseValueMap>() {
1876 Some(sparse_value_map) => wrap_in_option(
1877 sparse_value_map
1878 .borrow_mut()
1879 .get(&found_sparse_id.borrow()),
1880 ),
1881 _ => {
1882 panic!("internal error");
1883 }
1884 }
1885 }
1886 _ => {
1887 panic!("todo");
1888 }
1889 }
1890 };
1891 }
1892 PostfixKind::MemberCall(function_ref, arguments) => {
1893 let val =
1894 self.eval_member_call(node, &val_ref, is_mutable, function_ref, arguments)?;
1895
1896 val_ref = Rc::new(RefCell::new(val));
1897 is_mutable = false;
1898 }
1899 PostfixKind::FunctionCall(arguments) => {
1900 let val = self.eval_function_call(node, &val_ref, arguments)?;
1901
1902 val_ref = Rc::new(RefCell::new(val));
1903 is_mutable = false;
1904 }
1905 PostfixKind::OptionUnwrap => {
1906 val_ref = {
1907 let borrowed = val_ref.borrow();
1908
1909 match borrowed.clone() {
1910 Value::Option(found_option) => match found_option {
1911 Some(some_value) => some_value,
1912 _ => {
1913 is_undefined = true;
1914
1915 Rc::new(RefCell::new(Value::Option(None)))
1916 }
1917 },
1918 _ => {
1919 return Err(
1920 self.create_err(ExecuteErrorKind::ExpectedOptional, &part.node)
1921 );
1922 }
1923 }
1924 };
1925
1926 is_mutable = false;
1927 is_uncertain = true;
1928 }
1929 PostfixKind::IntrinsicCall(intrinsic_fn, arguments) => {
1930 val_ref = Rc::new(RefCell::new(self.eval_intrinsic_postfix(
1931 &part.node,
1932 &val_ref,
1933 intrinsic_fn,
1934 arguments,
1935 )?));
1936 is_mutable = false;
1937 }
1938 PostfixKind::IntrinsicCallEx(_intrinsic_fn, _arguments) => {
1939 is_mutable = false;
1941 }
1942 _ => {}
1943 }
1944 }
1945
1946 if is_uncertain {
1947 let binding = val_ref.borrow().clone();
1948 match binding {
1949 Value::Option(_) => {}
1950 _ => {
1951 val_ref = Rc::new(RefCell::new(Value::Option(Some(val_ref))));
1952 }
1953 }
1954 }
1955
1956 Ok(val_ref)
1957 }
1958
1959 fn eval_function_call(
1960 &mut self,
1961 node: &Node,
1962 function_val: &ValueRef,
1963 arguments: &[ArgumentExpressionOrLocation],
1964 ) -> Result<Value, ExecuteError> {
1965 let resolved_fn = match function_val.borrow().clone() {
1966 Value::InternalFunction(x) => Function::Internal(x.clone()),
1967 Value::ExternalFunction(external_fn) => Function::External(external_fn.clone()),
1968 _ => panic!("no function to call"),
1969 };
1970
1971 let parameters = &resolved_fn.signature().parameters;
1972 assert_eq!(
1974 arguments.len(),
1975 parameters.len(),
1976 "wrong number of arguments"
1977 );
1978
1979 let resolved_arguments = self.evaluate_args(&arguments)?;
1980
1981 let result_val = match &resolved_fn {
1982 Function::Internal(internal_function) => {
1983 self.push_function_scope();
1984
1985 self.bind_parameters(node, ¶meters, &resolved_arguments)?;
1986 let result = self.evaluate_expression(&internal_function.body)?;
1987 self.pop_function_scope();
1988
1989 result
1990 }
1991 Function::External(external_func) => {
1992 let mut func = self
1993 .externals
1994 .external_functions_by_id
1995 .get(&external_func.id)
1996 .expect("member call: external function missing")
1997 .borrow_mut();
1998 (func.func)(&resolved_arguments, self.context)?
1999 }
2000 };
2001
2002 Ok(result_val)
2003 }
2004
2005 #[inline]
2006 fn eval_member_call(
2007 &mut self,
2008 node: &Node,
2009 self_value_ref: &ValueRef,
2010 is_mutable: bool,
2011 function_ref: &FunctionRef,
2012 arguments: &[ArgumentExpressionOrLocation],
2013 ) -> Result<Value, ExecuteError> {
2014 let parameters = &function_ref.signature().parameters;
2015
2016 let self_var_value = if parameters[0].is_mutable {
2017 if !is_mutable {
2018 return Err(self.create_err(ExecuteErrorKind::ArgumentIsNotMutable, &node));
2019 }
2020 VariableValue::Reference(self_value_ref.clone())
2021 } else {
2022 VariableValue::Value(self_value_ref.borrow().clone())
2023 };
2024
2025 let mut member_call_arguments = Vec::new();
2026 member_call_arguments.push(self_var_value); member_call_arguments.extend(self.evaluate_args(&arguments)?);
2028
2029 if member_call_arguments.len() != parameters.len() {
2031 panic!("wrong number of arguments")
2032 }
2033
2034 let result_val = match &**function_ref {
2035 Function::Internal(internal_function) => {
2036 self.push_function_scope();
2037 self.bind_parameters(node, ¶meters, &member_call_arguments)?;
2038 let result = self.evaluate_expression(&internal_function.body)?;
2039 self.pop_function_scope();
2040
2041 result
2042 }
2043 Function::External(external_func) => {
2044 let mut func = self
2045 .externals
2046 .external_functions_by_id
2047 .get(&external_func.id)
2048 .expect("member call: external function missing")
2049 .borrow_mut();
2050 (func.func)(&member_call_arguments, self.context)?
2051 }
2052 };
2053
2054 Ok(result_val)
2055 }
2056
2057 fn eval_guard(&mut self, node: &Node, guards: &[Guard]) -> Result<Value, ExecuteError> {
2058 for guard in guards {
2059 let should_evaluate = if let Some(found_clause) = &guard.condition {
2060 self.evaluate_expression(&found_clause.expression)?
2061 .is_truthy()?
2062 } else {
2063 true
2064 };
2065
2066 if should_evaluate {
2067 return self.evaluate_expression(&guard.result);
2068 }
2069 }
2070
2071 Err(self.create_err(ExecuteErrorKind::MustHaveGuardArmThatMatches, &node))
2072 }
2073
2074 #[inline(always)]
2075 #[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
2076 fn eval_match(&mut self, resolved_match: &Match) -> Result<Value, ExecuteError> {
2077 let actual_value = self.evaluate_mut_or_immutable_expression(&resolved_match.expression)?;
2078 let value_ref = actual_value.to_value_ref();
2079
2080 for arm in &resolved_match.arms {
2081 match &arm.pattern {
2082 Pattern::Wildcard(_node) => return self.evaluate_expression(&arm.expression),
2083 Pattern::Normal(normal_pattern, maybe_guard) => {
2084 if let Some(found_guard) = maybe_guard {
2085 if !self
2086 .evaluate_expression(&found_guard.expression)?
2087 .is_truthy()?
2088 {
2090 continue;
2091 }
2092 }
2093
2094 let immutable_value = actual_value.to_value();
2095
2096 match &normal_pattern {
2097 NormalPattern::PatternList(elements) => {
2098 return Ok(self.eval_normal_pattern_list(
2099 elements,
2100 &arm.expression,
2101 value_ref.clone(),
2102 )?);
2103 }
2104 NormalPattern::EnumPattern(enum_variant_ref, pattern_elements) => {
2105 let maybe_found_match = self.eval_normal_pattern_enum(
2106 pattern_elements.as_ref(),
2107 &arm.expression,
2108 enum_variant_ref,
2109 value_ref.clone(),
2110 )?;
2111
2112 if let Some(found_match) = maybe_found_match {
2113 return Ok(found_match);
2114 }
2115 }
2116
2117 NormalPattern::Literal(lit) => match (lit, &immutable_value) {
2118 (Literal::IntLiteral(a), Value::Int(b)) if a == b => {
2119 return self.evaluate_expression(&arm.expression);
2120 }
2121 (Literal::FloatLiteral(a), Value::Float(b)) if a == b => {
2122 return self.evaluate_expression(&arm.expression);
2123 }
2124 (Literal::StringLiteral(a), Value::String(b)) if *a == *b => {
2125 return self.evaluate_expression(&arm.expression);
2126 }
2127 (Literal::BoolLiteral(a), Value::Bool(b)) if a == b => {
2128 return self.evaluate_expression(&arm.expression);
2129 }
2130 (
2131 Literal::TupleLiteral(_a_type_ref, a_values),
2132 Value::Tuple(_b_type_ref, b_values),
2133 ) if self.expressions_equal_to_values(&a_values, &b_values)? => {
2134 return self.evaluate_expression(&arm.expression);
2135 }
2136 _ => {}
2137 },
2138 }
2139 }
2140 }
2141 }
2142
2143 panic!("must match one of the match arms!");
2144 }
2145
2146 fn eval_normal_pattern_list(
2147 &mut self,
2148 elements: &[PatternElement],
2149 expression_to_evaluate: &Expression,
2150 value_ref: ValueRef,
2151 ) -> Result<Value, ExecuteError> {
2152 if elements.len() == 1 {
2154 return match &elements[0] {
2155 PatternElement::Variable(var_ref)
2156 | PatternElement::VariableWithFieldIndex(var_ref, _) => {
2157 self.push_block_scope();
2158 self.current_block_scopes
2159 .initialize_var_mut(var_ref, value_ref);
2160 let result = self.evaluate_expression(expression_to_evaluate);
2161 self.pop_block_scope();
2162 result
2163 }
2164 PatternElement::Wildcard(_) => {
2165 self.evaluate_expression(expression_to_evaluate)
2167 }
2168 };
2169 }
2170
2171 if let Value::Tuple(_tuple_type_ref, values) = value_ref.borrow_mut().clone() {
2172 assert_eq!(
2173 elements.len(),
2174 values.len(),
2175 "must use all elements in tuple"
2176 );
2177 self.push_block_scope();
2178
2179 for (element, _inside_value) in elements.iter().zip(values.iter()) {
2180 match element {
2181 PatternElement::Variable(var_ref) => {
2182 self.current_block_scopes
2183 .initialize_var_mut(var_ref, value_ref.clone());
2184 }
2185 PatternElement::VariableWithFieldIndex(var_ref, _) => {
2186 self.current_block_scopes
2187 .initialize_var_mut(var_ref, value_ref.clone());
2188 }
2189 PatternElement::Wildcard(_) => {
2190 continue;
2192 }
2193 }
2194 }
2195
2196 let result = self.evaluate_expression(expression_to_evaluate);
2197 self.pop_block_scope();
2198
2199 return result;
2200 }
2201 panic!("should not get here")
2202 }
2203
2204 fn eval_normal_pattern_enum(
2205 &mut self,
2206 maybe_elements: Option<&Vec<PatternElement>>,
2207 expression_to_evaluate: &Expression,
2208 variant_ref: &EnumVariantTypeRef,
2209 value_ref: ValueRef,
2210 ) -> Result<Option<Value>, ExecuteError> {
2211 match value_ref.borrow_mut().clone() {
2212 Value::EnumVariantTuple(value_tuple_type, values) => {
2213 if variant_ref.common().number != value_tuple_type.common.number {
2215 return Ok(None); }
2217
2218 if let Some(elements) = maybe_elements {
2219 assert_eq!(elements.len(), values.len());
2220 self.push_block_scope();
2221
2222 for (element, value) in elements.iter().zip(values.iter()) {
2223 match element {
2224 PatternElement::Variable(var_ref) => {
2225 self.current_block_scopes
2226 .initialize_var_mut(var_ref, value.clone());
2227 }
2228 PatternElement::VariableWithFieldIndex(var_ref, _) => {
2229 self.current_block_scopes
2230 .initialize_var_mut(var_ref, value.clone());
2231 }
2232 PatternElement::Wildcard(_) => continue,
2233 }
2234 }
2235
2236 let result = self.evaluate_expression(&expression_to_evaluate);
2237 self.pop_block_scope();
2238 return Ok(Option::from(result?));
2239 } else {
2240 panic!("not work");
2241 }
2242 }
2243 Value::EnumVariantStruct(value_enum_struct_type, values) => {
2244 info!(
2245 ?value_enum_struct_type,
2246 ?variant_ref,
2247 "comparing enum variant struct match arm"
2248 );
2249 if value_enum_struct_type.common.number == variant_ref.common().number {
2250 info!(?value_enum_struct_type, ?variant_ref, "FOUND!");
2251 if let Some(elements) = maybe_elements {
2252 self.push_block_scope();
2253
2254 for element in elements {
2255 if let PatternElement::VariableWithFieldIndex(var_ref, field_index) =
2256 element
2257 {
2258 let value = &values[*field_index];
2259 info!(?value, "setting match arm variable");
2260 self.current_block_scopes.init_var_ref(var_ref, value);
2261 }
2262 }
2263
2264 let result = self.evaluate_expression(&expression_to_evaluate);
2265 self.pop_block_scope();
2266 return Ok(Some(result?));
2267 }
2268 }
2269 }
2270
2271 Value::EnumVariantSimple(value_variant_ref) => {
2272 if value_variant_ref.common.number == variant_ref.common().number
2273 && maybe_elements.is_none()
2274 {
2275 return Ok(Some(self.evaluate_expression(&expression_to_evaluate)?));
2276 }
2277 }
2278 _ => {
2279 panic!("could not find it")
2280 }
2281 }
2282
2283 Ok(None)
2284 }
2285
2286 #[inline(always)]
2287 const fn modulo(a: i32, b: i32) -> i32 {
2288 ((a % b) + b) % b
2289 }
2290
2291 #[inline(always)]
2292 const fn modulo_fp(a: Fp, b: Fp) -> Fp {
2293 let raw = ((a.inner() % b.inner()) + b.inner()) % b.inner();
2294 Fp::from_raw(raw)
2295 }
2296
2297 #[allow(clippy::too_many_lines)]
2298 fn evaluate_binary_op(
2299 &self,
2300 node: &Node,
2301 left_val: Value,
2302 op: &BinaryOperatorKind,
2303 right_val: Value,
2304 ) -> Result<Value, ExecuteError> {
2305 let result: Value = match (&left_val, op, &right_val) {
2306 (Value::Int(a), BinaryOperatorKind::Add, Value::Int(b)) => Value::Int(a + b),
2308 (Value::Int(a), BinaryOperatorKind::Subtract, Value::Int(b)) => Value::Int(a - b),
2309 (Value::Int(a), BinaryOperatorKind::Multiply, Value::Int(b)) => Value::Int(a * b),
2310 (Value::Int(a), BinaryOperatorKind::Divide, Value::Int(b)) => {
2311 if *b == 0 {
2312 return Err(self.create_err(ExecuteErrorKind::DivideByZero, node));
2313 }
2314 Value::Int(a / b)
2315 }
2316 (Value::Int(a), BinaryOperatorKind::Modulo, Value::Int(b)) => {
2317 Value::Int(Self::modulo(*a, *b))
2318 }
2319 (Value::Int(a), BinaryOperatorKind::Equal, Value::Int(b)) => Value::Bool(a == b),
2320 (Value::Int(a), BinaryOperatorKind::NotEqual, Value::Int(b)) => Value::Bool(a != b),
2321 (Value::Int(a), BinaryOperatorKind::LessThan, Value::Int(b)) => Value::Bool(a < b),
2322 (Value::Int(a), BinaryOperatorKind::GreaterThan, Value::Int(b)) => Value::Bool(a > b),
2323 (Value::Int(a), BinaryOperatorKind::LessEqual, Value::Int(b)) => Value::Bool(a <= b),
2324 (Value::Int(a), BinaryOperatorKind::GreaterEqual, Value::Int(b)) => Value::Bool(a >= b),
2325
2326 (Value::Float(a), BinaryOperatorKind::Equal, Value::Float(b)) => Value::Bool(a == b),
2328 (Value::Float(a), BinaryOperatorKind::NotEqual, Value::Float(b)) => Value::Bool(a != b),
2329
2330 (Value::Float(a), BinaryOperatorKind::Add, Value::Float(b)) => Value::Float(*a + *b),
2331 (Value::Float(a), BinaryOperatorKind::Subtract, Value::Float(b)) => {
2332 Value::Float(*a - *b)
2333 }
2334 (Value::Float(a), BinaryOperatorKind::Multiply, Value::Float(b)) => {
2335 Value::Float(*a * *b)
2336 }
2337 (Value::Float(a), BinaryOperatorKind::Divide, Value::Float(b)) => {
2338 if b.abs().inner() <= 400 {
2339 return Err(self.create_err(ExecuteErrorKind::DivideByZero, node));
2340 }
2341 Value::Float(*a / *b)
2342 }
2343 (Value::Float(a), BinaryOperatorKind::Modulo, Value::Float(b)) => {
2344 Value::Float(Self::modulo_fp(*a, *b))
2345 }
2346
2347 (Value::Float(a), BinaryOperatorKind::GreaterThan, Value::Float(b)) => {
2348 Value::Bool(a > b)
2349 }
2350 (Value::Float(a), BinaryOperatorKind::GreaterEqual, Value::Float(b)) => {
2351 Value::Bool(a >= b)
2352 }
2353 (Value::Float(a), BinaryOperatorKind::LessThan, Value::Float(b)) => Value::Bool(a < b),
2354 (Value::Float(a), BinaryOperatorKind::LessEqual, Value::Float(b)) => {
2355 Value::Bool(a <= b)
2356 }
2357
2358 (Value::Bool(a), BinaryOperatorKind::LogicalAnd, Value::Bool(b)) => {
2360 Value::Bool(*a && *b)
2361 }
2362 (Value::Bool(a), BinaryOperatorKind::LogicalOr, Value::Bool(b)) => {
2363 Value::Bool(*a || *b)
2364 }
2365
2366 (Value::RustValue(_, left), BinaryOperatorKind::Equal, Value::RustValue(_, right)) => {
2370 let left_borrow = left.borrow();
2371 let right_borrow = right.borrow();
2372 let equal = left_borrow.eq_dyn(&**right_borrow);
2373 Value::Bool(equal)
2374 }
2375 (
2376 Value::RustValue(_, left),
2377 BinaryOperatorKind::NotEqual,
2378 Value::RustValue(_, right),
2379 ) => {
2380 let left_borrow = left.borrow();
2381 let right_borrow = right.borrow();
2382 let equal = left_borrow.eq_dyn(&**right_borrow);
2383 Value::Bool(!equal)
2384 }
2385
2386 (Value::String(a), BinaryOperatorKind::Add, Value::String(b)) => {
2388 Value::String(a.to_owned() + b)
2389 }
2390 (Value::String(a), BinaryOperatorKind::Equal, Value::String(b)) => Value::Bool(a == b),
2391
2392 (Value::String(a), BinaryOperatorKind::Add, Value::Int(b)) => {
2393 Value::String(a.to_owned() + &(*b).to_string())
2394 }
2395 (Value::Int(a), BinaryOperatorKind::Add, Value::String(b)) => {
2396 Value::String(a.to_string() + b)
2397 }
2398
2399 (
2401 Value::EnumVariantSimple(a),
2402 BinaryOperatorKind::Equal,
2403 Value::EnumVariantSimple(b),
2404 ) => Value::Bool(a == b),
2405 (
2406 Value::EnumVariantSimple(a),
2407 BinaryOperatorKind::NotEqual,
2408 Value::EnumVariantSimple(b),
2409 ) => Value::Bool(a != b),
2410
2411 (Value::Bool(a), BinaryOperatorKind::Equal, Value::Bool(b)) => Value::Bool(a == b),
2413 (Value::Bool(a), BinaryOperatorKind::NotEqual, Value::Bool(b)) => Value::Bool(a != b),
2414
2415 (Value::Option(a), BinaryOperatorKind::Equal, Value::Option(b)) => Value::Bool(a == b),
2416
2417 _ => {
2418 error!(?op, "invalid binary operation!!");
2419 panic!("invalid binary operation"); }
2421 };
2422
2423 Ok(result)
2424 }
2425
2426 fn evaluate_unary_op(
2427 &self,
2428 node: &Node,
2429 op: &UnaryOperatorKind,
2430 val: Value,
2431 ) -> Result<Value, ExecuteError> {
2432 match (op, val) {
2433 (UnaryOperatorKind::Negate, Value::Int(n)) => Ok(Value::Int(-n)),
2434 (UnaryOperatorKind::Negate, Value::Float(n)) => Ok(Value::Float(-n)),
2435 (UnaryOperatorKind::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
2436 _ => Err(self.create_err(ExecuteErrorKind::DivideByZero, node)),
2437 }
2438 }
2439
2440 fn expressions_equal_to_values(
2441 &mut self,
2442 p0: &[Expression],
2443 p1: &[ValueRef],
2444 ) -> Result<bool, ExecuteError> {
2445 for (a, b_value) in p0.iter().zip(p1.iter()) {
2446 let a_value = self.evaluate_expression(a)?;
2447
2448 if a_value != *b_value.borrow() {
2449 return Ok(false);
2450 }
2451 }
2452
2453 Ok(true)
2454 }
2455
2456 #[inline(always)]
2457 fn apply_compound_operator(
2458 &self,
2459 node: &Node,
2460 target: &mut Value,
2461 operator: &CompoundOperatorKind,
2462 source: &Value,
2463 ) -> Result<(), ExecuteError> {
2464 match operator {
2465 CompoundOperatorKind::Mul => {
2466 *target = self.evaluate_binary_op(
2467 node,
2468 target.clone(),
2469 &BinaryOperatorKind::Multiply,
2470 source.clone(),
2471 )?;
2472 }
2473 CompoundOperatorKind::Div => {
2474 *target = self.evaluate_binary_op(
2475 node,
2476 target.clone(),
2477 &BinaryOperatorKind::Divide,
2478 source.clone(),
2479 )?;
2480 }
2481 CompoundOperatorKind::Add => {
2482 *target = self.evaluate_binary_op(
2483 node,
2484 target.clone(),
2485 &BinaryOperatorKind::Add,
2486 source.clone(),
2487 )?;
2488 }
2489 CompoundOperatorKind::Sub => {
2490 *target = self.evaluate_binary_op(
2491 node,
2492 target.clone(),
2493 &BinaryOperatorKind::Subtract,
2494 source.clone(),
2495 )?;
2496 }
2497 CompoundOperatorKind::Modulo => {
2498 *target = self.evaluate_binary_op(
2499 node,
2500 target.clone(),
2501 &BinaryOperatorKind::Modulo,
2502 source.clone(),
2503 )?;
2504 }
2505 }
2506 Ok(())
2507 }
2508
2509 fn create_err(&self, kind: ExecuteErrorKind, node: &Node) -> ExecuteError {
2617 ExecuteError {
2618 node: node.clone(),
2619 kind,
2620 }
2621 }
2622
2623 fn evaluate_intrinsic_mut(
2624 &mut self,
2625 node: &Node,
2626 intrinsic_fn: &IntrinsicFunction,
2627 location: &SingleMutLocationExpression,
2628 arguments: &Vec<Expression>,
2629 ) -> Result<Value, ExecuteError> {
2630 let val = match intrinsic_fn {
2631 IntrinsicFunction::VecSelfPush => {
2632 let source_val = self.evaluate_expression(&arguments[0])?;
2633 let array_val_ref = self.evaluate_location(&location.0)?;
2634
2635 match &mut *array_val_ref.borrow_mut() {
2636 Value::Array(_type_id, vector) => {
2637 vector.push(Rc::new(RefCell::new(source_val)));
2638 }
2639 _ => {
2640 Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &node))?;
2641 }
2642 }
2643 Value::Unit
2645 }
2646 IntrinsicFunction::VecSelfExtend => {
2647 let source_val = self.evaluate_expression(&arguments[0])?;
2648
2649 let array_val_ref = self.evaluate_location(&location.0)?;
2650 match &mut *array_val_ref.borrow_mut() {
2651 Value::Array(_type_id, vector) => match source_val {
2652 Value::Array(_, items) => {
2653 vector.extend(items);
2654 }
2655 _ => {
2656 Err(self.create_err(ExecuteErrorKind::OperationRequiresArray, &node))?;
2657 }
2658 },
2659 _ => {
2660 todo!("handle error")
2661 }
2662 }
2663
2664 Value::Unit
2666 }
2667 _ => return Err(self.create_err(ExecuteErrorKind::UnknownMutIntrinsic, &node)),
2668 };
2669
2670 Ok(val)
2671 }
2672}
2673
2674#[inline]
2675#[must_use]
2676pub fn i64_sqrt(v: i64) -> i64 {
2677 assert!(v >= 0, "negative numbers are undefined for sqrt() {v}");
2678
2679 if v == 0 {
2680 return v;
2681 }
2682
2683 const MAX_ITERATIONS: usize = 40;
2684 const TOLERANCE: i64 = 2;
2685
2686 let mut guess = v / 2;
2687
2688 for _ in 0..MAX_ITERATIONS {
2689 let next_guess = (guess + v / guess) / 2;
2690
2691 if (next_guess - guess).abs() <= TOLERANCE {
2693 return next_guess;
2694 }
2695
2696 guess = next_guess;
2697 }
2698
2699 guess }
2701
2702#[allow(unused)]
2703pub fn values_to_value_refs(values: &[Value]) -> Vec<ValueRef> {
2704 let mut items = Vec::new();
2705
2706 for x in values.iter().cloned() {
2707 items.push(Rc::new(RefCell::new(x)));
2708 }
2709
2710 items
2711}
2712
2713pub fn values_to_value_refs_owned(values: Vec<Value>) -> Vec<ValueRef> {
2714 values
2715 .into_iter()
2716 .map(|x| Rc::new(RefCell::new(x)))
2717 .collect()
2718}
2719
2720pub fn wrap_in_option(maybe: Option<&ValueRef>) -> ValueRef {
2721 match maybe {
2722 None => Rc::new(RefCell::new(Value::Option(None))),
2723 Some(x) => Rc::new(RefCell::new(Value::Option(Some(x.clone())))),
2724 }
2725}