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