1mod lang_vars;
2mod predefined_functions;
3
4pub mod module;
5pub mod module_manager;
6pub mod regex;
7pub mod data;
8pub mod conversions;
9pub mod operators;
10pub mod lii;
11pub mod platform;
12pub mod lang_test;
13
14use std::cell::{Ref, RefCell, RefMut};
15use std::cmp::Ordering;
16use std::collections::{HashMap, HashSet, VecDeque};
17use std::collections::hash_map::Entry;
18use std::fmt::{Display, Formatter};
19use std::ops::Deref;
20use std::{ptr, str};
21use std::rc::Rc;
22use std::str::FromStr;
23use ahash::AHashMap;
24use gc::Gc;
25use include_dir::{include_dir, Dir};
26use rand::rngs::SmallRng;
27use rand::{thread_rng, SeedableRng};
28use crate::interpreter::module::Module;
29use crate::interpreter::platform::{PlatformAPI};
30use crate::interpreter::data::{
31 DataObject,
32 DataObjectRef,
33 DataType,
34 DataTypeConstraint,
35 ErrorObject,
36 FunctionPointerObjectRef,
37 LangObjectRef,
38 OptionDataObjectRef,
39 OptionLangObjectRef,
40 StructObject,
41 Visibility,
42};
43use crate::interpreter::data::function::{
44 Function,
45 FunctionData,
46 FunctionMetadata,
47 FunctionPointerObject,
48 InternalFunction,
49 NormalFunction,
50 ParameterMetadata,
51 ParameterType,
52};
53use crate::interpreter::data::function::native::NativeError;
54use crate::interpreter::data::object::{LangObject, MemberDefinition};
55use crate::interpreter::lang_test::{AssertResult, LangTest};
56use crate::lexer::CodePosition;
57use crate::terminal_io::{Level, TerminalIO};
58use crate::parser::ast::{Node, NodeData, Operator, OperatorType, AST};
59use crate::parser::{Parser, ParsingError};
60use crate::utils;
61
62#[cfg(not(feature = "wasm"))]
63use std::time::Instant;
64#[cfg(feature = "wasm")]
65use web_time::Instant;
66
67#[derive(Debug)]
68pub struct Interpreter {
69 parser: Parser,
70
71 modules: HashMap<Box<str>, Rc<Module>>,
72
73 is_initializing_lang_standard_implementation: bool,
74 scope_id: isize,
75 current_call_stack_element: StackElement,
76 call_stack: Vec<StackElement>,
77
78 term: Option<TerminalIO>,
79 platform_api: Box<dyn PlatformAPI>,
80 origin_time: Instant,
81 ran: SmallRng,
82
83 lang_test_store: LangTest,
85 lang_test_expected_throw_value: Option<InterpretingError>,
86 lang_test_expected_return_value: OptionDataObjectRef,
87 lang_test_expected_no_return_value: bool,
88 lang_test_message_for_last_test_result: Option<Box<str>>,
89 lang_test_expected_return_value_scope_id: isize,
90
91 execution_state: ExecutionState,
93 execution_flags: ExecutionFlags,
94
95 data: Vec<Rc<RefCell<Data>>>,
97
98 standard_types: AHashMap<Box<str>, DataObjectRef>,
100
101 funcs: AHashMap<Box<str>, FunctionPointerObjectRef>,
103}
104
105impl Interpreter {
106 pub const LOG_TAG: &'static str = "LangInterpreter";
107
108 pub const VERSION: &'static str = "v1.0.0";
109
110 const RESOURCES_DIR: Dir<'static> = include_dir!("resources");
111
112 pub fn new(
113 lang_path: &str,
114 lang_file: Option<&str>,
115 term: Option<TerminalIO>,
116 platform_api: Box<dyn PlatformAPI>,
117 lang_args: Option<Vec<Box<str>>>,
118 ) -> Self {
119 let mut interpreter = Self {
120 parser: Parser::new(),
121
122 modules: HashMap::new(),
123
124 is_initializing_lang_standard_implementation: true,
125 scope_id: -1,
126 current_call_stack_element: StackElement::new(
127 lang_path,
128 lang_file,
129 None,
130 None,
131 None,
132 None,
133 ),
134 call_stack: Vec::new(),
135
136 term,
137 platform_api,
138 origin_time: Instant::now(),
139 ran: SmallRng::from_rng(thread_rng()).unwrap(),
140
141 lang_test_store: LangTest::new(),
142 lang_test_expected_throw_value: None,
143 lang_test_expected_return_value: None,
144 lang_test_expected_no_return_value: false,
145 lang_test_message_for_last_test_result: None,
146 lang_test_expected_return_value_scope_id: -1,
147
148 execution_state: ExecutionState::new(),
149 execution_flags: ExecutionFlags::new(),
150
151 data: Vec::new(),
152
153 standard_types: AHashMap::new(),
154
155 funcs: AHashMap::new(),
156 };
157
158 interpreter.init_lang_standard();
159 interpreter.enter_scope(lang_args);
160
161 interpreter
162 }
163
164 pub fn parse_lines(&mut self, lines: impl Into<String>) -> Option<AST> {
165 self.parser.parse_lines(lines)
166 }
167
168 pub fn interpret_lines(&mut self, lines: impl Into<String>) -> OptionDataObjectRef {
169 let ast = self.parse_lines(lines)?;
170
171 self.interpret_ast(&ast)
172 }
173
174 pub fn interpret_ast(&mut self, ast: &AST) -> OptionDataObjectRef {
175 let mut ret = None;
180 for node in ast.nodes() {
181 if self.execution_state.stop_execution_flag {
182 return None;
183 }
184
185 ret = self.interpret_node(None, node);
186 }
187
188 ret
189 }
190
191 pub fn lang_test_store(&self) -> &LangTest {
192 &self.lang_test_store
193 }
194
195 fn data(&self) -> &Rc<RefCell<Data>> {
196 let scope_id = self.scope_id as usize;
197
198 &self.data[scope_id]
199 }
200
201 pub fn data_ref(&self) -> Ref<'_, Data> {
202 let scope_id = self.scope_id as usize;
203
204 self.data[scope_id].borrow()
205 }
206
207 pub fn data_mut(&mut self) -> RefMut<'_, Data> {
208 let scope_id = self.scope_id as usize;
209
210 self.data[scope_id].borrow_mut()
211 }
212
213 pub fn current_call_stack_element(&self) -> &StackElement {
225 &self.current_call_stack_element
226 }
227
228 fn call_stack_elements(&self) -> &[StackElement] {
229 &self.call_stack
230 }
231
232 fn push_stack_element(&mut self, stack_element: StackElement, parent_pos: CodePosition) {
233 self.call_stack.push(self.current_call_stack_element.copy_with_pos(parent_pos));
234 self.current_call_stack_element = stack_element;
235 }
236
237 fn pop_stack_element(&mut self) -> Option<&StackElement> {
238 self.current_call_stack_element = self.call_stack.pop()?;
239 self.current_call_stack_element.pos = CodePosition::EMPTY;
240
241 Some(&self.current_call_stack_element)
242 }
243
244 fn print_stack_trace(&self, pos: CodePosition) -> String {
245 let mut builder = String::new();
246
247 builder += &self.current_call_stack_element.copy_with_pos(pos).to_string();
248
249 for ele in self.call_stack.iter().rev() {
250 builder += "\n";
251 builder += &ele.to_string();
252 }
253
254 builder
255 }
256
257 fn parser_line_number(&self) -> usize {
258 self.parser.line_number()
259 }
260
261 fn set_parser_line_number(&mut self, line_number: usize) {
262 self.parser.set_line_number(line_number);
263 }
264
265 fn reset_parser_positional_vars(&mut self) {
266 self.parser.reset_position_vars();
267 }
268
269 fn interpret_node(&mut self, composite_type: OptionDataObjectRef, node: &Node) -> OptionDataObjectRef {
270 match node.node_data() {
275 NodeData::UnprocessedVariableName(..) => {
276 let node = self.process_unprocessed_variable_name_node(composite_type.clone(), node);
277
278 self.interpret_node(composite_type, &node)
279 },
280
281 NodeData::FunctionCallPreviousNodeValue {..} => {
282 let node = self.process_function_call_previous_node_value_node(node, None);
283
284 self.interpret_node(composite_type, &node)
285 },
286
287 NodeData::List => {
288 self.interpret_list_node(composite_type, node)
289 },
290
291 NodeData::CharValue(..) |
292 NodeData::TextValue(..) |
293 NodeData::IntValue(..) |
294 NodeData::LongValue(..) |
295 NodeData::FloatValue(..) |
296 NodeData::DoubleValue(..) |
297 NodeData::NullValue |
298 NodeData::VoidValue => {
299 Some(self.interpret_value_node(node))
300 },
301
302 NodeData::ParsingError {..} => {
303 Some(self.interpret_parsing_error_node(node))
304 },
305
306 NodeData::IfStatement => {
307 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
308 data_object.set_bool(self.interpret_if_statement_node(node))
309 }).unwrap()))
310 },
311
312 NodeData::IfStatementPartIf {..} |
313 NodeData::IfStatementPartElse(..) => {
314 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
315 data_object.set_bool(self.interpret_if_statement_part_node(node))
316 }).unwrap()))
317 },
318
319 NodeData::LoopStatement => {
320 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
321 data_object.set_bool(self.interpret_loop_statement_node(node))
322 }).unwrap()))
323 },
324
325 NodeData::LoopStatementPartWhile {..} |
326 NodeData::LoopStatementPartUntil {..} |
327 NodeData::LoopStatementPartRepeat {..} |
328 NodeData::LoopStatementPartForEach {..} |
329 NodeData::LoopStatementPartLoop(..) |
330 NodeData::LoopStatementPartElse(..) => {
331 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
332 data_object.set_bool(self.interpret_loop_statement_part_node(node))
333 }).unwrap()))
334 },
335
336 NodeData::ContinueBreakStatement {..} => {
337 self.interpret_loop_statement_continue_break(node);
338
339 None
340 },
341
342 NodeData::TryStatement => {
343 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
344 data_object.set_bool(self.interpret_try_statement_node(node))
345 }).unwrap()))
346 },
347
348 NodeData::TryStatementPartTry {..} |
349 NodeData::TryStatementPartSoftTry {..} |
350 NodeData::TryStatementPartNonTry {..} |
351 NodeData::TryStatementPartCatch {..} |
352 NodeData::TryStatementPartElse(..) |
353 NodeData::TryStatementPartFinally(..) => {
354 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
355 data_object.set_bool(self.interpret_try_statement_part_node(node))
356 }).unwrap()))
357 },
358
359 NodeData::Operation(..) |
360 NodeData::Math(..) |
361 NodeData::Condition(..) => {
362 self.interpret_operation_node(node)
363 },
364
365 NodeData::Return => {
366 self.interpret_return_node(node);
367
368 None
369 },
370
371 NodeData::Throw => {
372 self.interpret_throw_node(node);
373
374 None
375 },
376
377 NodeData::Assignment => {
378 self.interpret_assigment_node(node)
379 },
380
381 NodeData::VariableName {..} => {
382 self.interpret_variable_name_node(composite_type, node)
383 },
384
385 NodeData::EscapeSequence(..) => {
386 self.interpret_escape_sequence_node(node)
387 },
388
389 NodeData::UnicodeEscapeSequence(..) => {
390 Some(self.interpret_unicode_escape_sequence_node(node))
391 },
392
393 NodeData::ArgumentSeparator(..) => {
394 Some(self.interpret_argument_separator_node(node))
395 },
396
397 NodeData::FunctionCall(..) => {
398 self.interpret_function_call_node(composite_type, node)
399 },
400
401 NodeData::FunctionDefinition(..) => {
402 self.interpret_function_definition_node(node)
403 },
404
405 NodeData::ArrayValue => {
406 Some(self.interpret_array_node(node))
407 },
408
409 NodeData::StructDefinition(..) => {
410 self.interpret_struct_definition_node(node)
411 },
412
413 NodeData::ClassDefinition(..) => {
414 self.interpret_class_definition_node(node)
415 },
416 }
417 }
418
419 fn convert_variable_name_to_variable_name_node_or_composition(
426 &mut self,
427 module_name: Option<Box<str>>,
428 variable_name: String,
429 variable_names: Box<[Rc<str>]>,
430 variable_prefix_append_after_search: &str,
431 supports_pointer_dereferencing_and_referencing: bool,
432 pos: CodePosition,
433 ) -> Node {
434 let variable_names = if let Some(module_name) = &module_name {
435 let module = self.modules.get(module_name);
436 if let Some(module) = module {
437 Box::from_iter(module.exported_variables().borrow().keys().cloned())
438 }else {
439 self.set_errno(InterpretingError::ModuleLoadUnloadErr, Some(&format!(
440 "The module \"{module_name}\" is not loaded!",
441 )), pos);
442
443 return Node::new_text_value_node(pos, format!(
444 "[[{module_name}]]::{variable_prefix_append_after_search}{variable_name}",
445 ));
446 }
447 }else {
448 variable_names
449 };
450
451 let returned_variable_name = variable_names.iter().
453 filter(|name| variable_name.starts_with(&***name)).
454 max_by_key(|name| name.len());
455
456 if let Some(returned_variable_name) = returned_variable_name {
457 if returned_variable_name.len() == variable_name.len() {
458 return Node::new_variable_name_node(pos, if let Some(module_name) = &module_name {
459 format!("[[{module_name}]]::{variable_prefix_append_after_search}{variable_name}")
460 }else {
461 format!("{variable_prefix_append_after_search}{variable_name}")
462 }, None);
463 }
464
465 return Node::new_list_node(vec![
467 Node::new_variable_name_node(pos, if let Some(module_name) = &module_name {
469 format!("[[{module_name}]]::{variable_prefix_append_after_search}{returned_variable_name}")
470 }else {
471 format!("{variable_prefix_append_after_search}{returned_variable_name}")
472 }, None),
473
474 Node::new_text_value_node(pos, &variable_name[returned_variable_name.len()..]),
476 ]);
477 }
478
479 if supports_pointer_dereferencing_and_referencing {
480 let mut dereferences = None;
481 let mut start_index = None;
482 let mut modified_variable_name = variable_name.clone();
483 let mut returned_node = None;
484 let mut text = None;
485
486 if variable_name.contains("*") {
487 start_index = variable_name.find("*");
488 let end_index = variable_name.rfind("*").unwrap() + 1;
489 if end_index >= variable_name.len() {
490 return Node::new_text_value_node(pos, if let Some(module_name) = &module_name {
491 format!("[[{module_name}]]::{variable_prefix_append_after_search}{variable_name}")
492 }else {
493 format!("{variable_prefix_append_after_search}{variable_name}")
494 });
495 }
496
497 let start_index = start_index.unwrap();
498 dereferences = Some(&variable_name[start_index..end_index]);
499 modified_variable_name = String::new() + &variable_name[..start_index] +
500 &variable_name[end_index..];
501
502 if !modified_variable_name.contains("[") && !modified_variable_name.contains("]") {
503 returned_node = Some(self.convert_variable_name_to_variable_name_node_or_composition(
504 module_name.clone(),
505 modified_variable_name.clone(),
506 variable_names.clone(),
507 "",
508 supports_pointer_dereferencing_and_referencing,
509 pos,
510 ));
511 }
512 }
513
514 if modified_variable_name.contains("[") && modified_variable_name.contains("]") {
516 let index_opening_bracket = modified_variable_name.find("[").unwrap();
517 let index_matching_bracket = utils::get_index_of_matching_bracket_str(
518 &modified_variable_name, index_opening_bracket,
519 usize::MAX, b'[', b']',
520 );
521
522 if let Some(index_matching_bracket) = index_matching_bracket {
523 let mut current_index = index_opening_bracket + 1;
525 let mut current_index_matching_bracket = index_matching_bracket - 1;
526
527 while modified_variable_name.as_bytes()[current_index] == b'[' &&
528 modified_variable_name.as_bytes()[current_index_matching_bracket] == b']' {
529 current_index += 1;
530 current_index_matching_bracket -= 1;
531 }
532
533 if index_matching_bracket != modified_variable_name.len() - 1 {
534 text = Some(modified_variable_name[index_matching_bracket + 1..].to_string());
535 modified_variable_name = modified_variable_name[..index_matching_bracket + 1].to_string();
536 }
537
538 if !modified_variable_name[current_index..].contains("[") {
539 returned_node = Some(self.convert_variable_name_to_variable_name_node_or_composition(
540 module_name.clone(),
541 String::new() + &modified_variable_name[..index_opening_bracket] +
542 &modified_variable_name[current_index..current_index_matching_bracket + 1],
543 variable_names,
544 "",
545 supports_pointer_dereferencing_and_referencing,
546 pos,
547 ));
548 }
549 }
550 }
551
552 if let Some(returned_node) = returned_node {
553 if let Some(dereferences) = dereferences {
554 let start_index = start_index.unwrap();
555
556 modified_variable_name = String::new() + &modified_variable_name[..start_index] +
557 dereferences + &modified_variable_name[start_index..];
558 }
559
560 match returned_node.node_data() {
561 NodeData::VariableName { .. } => {
563 let Some(text) = text else {
564 return Node::new_variable_name_node(pos, if let Some(module_name) = &module_name {
565 format!("[[{module_name}]]::{variable_prefix_append_after_search}{variable_name}")
566 }else {
567 format!("{variable_prefix_append_after_search}{variable_name}")
568 }, None);
569 };
570
571 return Node::new_list_node(vec![
573 Node::new_variable_name_node(pos, if let Some(module_name) = &module_name {
574 format!("[[{module_name}]]::{variable_prefix_append_after_search}{modified_variable_name}")
575 }else {
576 format!("{variable_prefix_append_after_search}{modified_variable_name}")
577 }, None),
578 Node::new_text_value_node(pos, text),
579 ]);
580 },
581
582 NodeData::List |
583 NodeData::TextValue(..) => {
584 return Node::new_text_value_node(pos, if let Some(module_name) = &module_name {
588 format!("[[{module_name}]]::{variable_prefix_append_after_search}{variable_name}")
589 }else {
590 format!("{variable_prefix_append_after_search}{variable_name}")
591 });
592 },
593
594 _ => panic!("Invalid node"),
595 }
596 }
597 }
598
599 Node::new_text_value_node(pos, if let Some(module_name) = &module_name {
600 format!("[[{module_name}]]::{variable_prefix_append_after_search}{variable_name}")
601 }else {
602 format!("{variable_prefix_append_after_search}{variable_name}")
603 })
604 }
605
606 fn process_unprocessed_variable_name_node(&mut self, composite_type: OptionDataObjectRef, node: &Node) -> Node {
607 let NodeData::UnprocessedVariableName(variable_name) = node.node_data() else {
608 panic!("Invalid AST node");
609 };
610
611 if self.execution_flags.raw_variable_names {
612 return Node::new_variable_name_node(node.pos(), variable_name.clone(), None);
613 }
614
615 let mut variable_name = variable_name.to_string();
616
617 let is_module_variable = variable_name.starts_with("[[");
618 let mut module_name = None;
619 if is_module_variable {
620 let index_module_identifier_end = variable_name.find("]]::");
621 let Some(index_module_identifier_end) = index_module_identifier_end else {
622 self.set_errno(InterpretingError::InvalidAstNode, Some("Invalid variable name"), node.pos());
623
624 return Node::new_text_value_node(node.pos(), variable_name);
625 };
626
627 let module_name_local = &variable_name[2..index_module_identifier_end];
628 if !Self::is_alpha_numeric_with_underline(module_name_local) {
629 self.set_errno(InterpretingError::InvalidAstNode, Some("Invalid module name"), node.pos());
630
631 return Node::new_text_value_node(node.pos(), variable_name);
632 }
633 module_name = Some(Box::from(module_name_local));
634 variable_name = variable_name[index_module_identifier_end + 4..].to_string();
635 }
636
637 if let Some(composite_type) = &composite_type
638 && let Some(object_data) = composite_type.object_value() {
639 if variable_name.starts_with("mp.") && !object_data.borrow().is_class() {
640 let variable_names = object_data.borrow().methods().
641 keys().
642 filter(|key| key.starts_with("mp.")).
643 map(|key| Rc::from(&**key)).
644 collect::<Box<_>>();
645
646 return self.convert_variable_name_to_variable_name_node_or_composition(
647 module_name,
648 variable_name,
649 variable_names,
650 "",
651 false,
652 node.pos(),
653 );
654 }
655
656 if variable_name.starts_with("op:") && !object_data.borrow().is_class() {
657 let variable_names = object_data.borrow().methods().
658 keys().
659 filter(|key| key.starts_with("op:")).
660 map(|key| Rc::from(&**key)).
661 collect::<Box<_>>();
662
663 return self.convert_variable_name_to_variable_name_node_or_composition(
664 module_name,
665 variable_name,
666 variable_names,
667 "",
668 false,
669 node.pos(),
670 );
671 }
672
673 if variable_name.starts_with("to:") && !object_data.borrow().is_class() {
674 let variable_names = object_data.borrow().methods().
675 keys().
676 filter(|key| key.starts_with("to:")).
677 map(|key| Rc::from(&**key)).
678 collect::<Box<_>>();
679
680 return self.convert_variable_name_to_variable_name_node_or_composition(
681 module_name,
682 variable_name,
683 variable_names,
684 "",
685 false,
686 node.pos(),
687 );
688 }
689 }
690
691 if variable_name.starts_with("$") || variable_name.starts_with("&") ||
692 variable_name.starts_with("fp.") {
693 let variable_names = if let Some(composite_type) = &composite_type {
694 if composite_type.error_value().is_some() {
695 Box::from([
696 Rc::from("$text"),
697 Rc::from("$code"),
698 Rc::from("$message"),
699 ])
700 }else if let Some(struct_data) = composite_type.struct_value() {
701 Box::from_iter(struct_data.member_names().into_iter().
702 map(Rc::from))
703 }else if let Some(object_data) = composite_type.object_value() {
704 let mut variable_names = object_data.borrow().static_members().iter().
705 filter_map(|data_object| data_object.variable_name()).
706 map(Rc::from).
707 collect::<Vec<_>>();
708
709 if !object_data.borrow().is_class()
710 && let Some(members) = object_data.borrow().members() {
711 variable_names.extend(members.iter().
712 filter_map(|data_object| data_object.
713 variable_name().
714 map(Rc::from)));
715 }
716
717 variable_names.into_boxed_slice()
718 }else {
719 self.set_errno(InterpretingError::InvalidArguments, Some("Invalid composite type"), node.pos());
720
721 return Node::new_text_value_node(node.pos(), variable_name);
722 }
723 }else {
724 self.data_ref().var.keys().
725 cloned().
726 collect::<Box<_>>()
727 };
728
729 let supports_pointer_dereferencing_rand_referencing = variable_name.starts_with("$");
730 return self.convert_variable_name_to_variable_name_node_or_composition(
731 module_name,
732 variable_name,
733 variable_names,
734 "",
735 supports_pointer_dereferencing_rand_referencing,
736 node.pos(),
737 );
738 }
739
740 if composite_type.is_some() {
741 self.set_errno(InterpretingError::InvalidAstNode, Some(&format!(
742 "Invalid composite type member name: \"{variable_name}\"",
743 )), node.pos());
744
745 return Node::new_text_value_node(node.pos(), variable_name);
746 }
747
748 let is_linker_function;
749 let prefix;
750
751 if !is_module_variable && variable_name.starts_with("func.") {
752 is_linker_function = false;
753 prefix = "func.";
754
755 variable_name = variable_name[5..].to_string();
756 }else if !is_module_variable && variable_name.starts_with("fn.") {
757 is_linker_function = false;
758 prefix = "fn.";
759
760 variable_name = variable_name[3..].to_string();
761 }else if !is_module_variable && variable_name.starts_with("linker.") {
762 is_linker_function = true;
763 prefix = "linker.";
764
765 variable_name = variable_name[7..].to_string();
766 }else if !is_module_variable && variable_name.starts_with("ln.") {
767 is_linker_function = true;
768 prefix = "ln.";
769
770 variable_name = variable_name[3..].to_string();
771 }else {
772 self.set_errno(InterpretingError::InvalidAstNode, Some("Invalid variable name"), node.pos());
773
774 return Node::new_text_value_node(node.pos(), variable_name);
775 }
776
777 let variable_names = self.funcs.iter().
778 filter(|(_, func)| func.linker_function() == is_linker_function).
779 map(|(func_name, _)| Rc::from(&**func_name)).
780 collect::<Box<_>>();
781
782 self.convert_variable_name_to_variable_name_node_or_composition(
783 None,
784 variable_name,
785 variable_names,
786 prefix,
787 false,
788 node.pos(),
789 )
790 }
791
792 fn process_function_call_previous_node_value_node(&mut self, node: &Node, previous_value: OptionDataObjectRef) -> Node {
793 let NodeData::FunctionCallPreviousNodeValue {
794 leading_whitespace,
795 trailing_whitespace,
796 } = node.node_data() else {
797 panic!("Invalid AST node");
798 };
799
800 if let Some(previous_value) = previous_value {
801 if previous_value.function_pointer_value().is_some() || previous_value.type_value().is_some() {
802 return node.clone();
803 }
804
805 if let Some(struct_value) = previous_value.struct_value()
806 && struct_value.is_definition() {
807 return node.clone();
808 }
809
810 if let Some(object_value) = previous_value.object_value()
811 && (object_value.borrow().is_class() || object_value.borrow().methods().contains_key("op:call")) {
812 return node.clone();
813 }
814 }
815
816 let mut nodes = Vec::with_capacity(2 + node.child_nodes().len());
818 nodes.push(Node::new_text_value_node(node.pos(), format!("({leading_whitespace}")));
819 nodes.append(&mut node.child_nodes().to_vec());
820 nodes.push(Node::new_text_value_node(node.pos(), format!("{trailing_whitespace})")));
821
822 Node::new_list_node(nodes)
823 }
824
825 fn interpret_list_node(&mut self, mut composite_type: OptionDataObjectRef, node: &Node) -> OptionDataObjectRef {
826 let NodeData::List = node.node_data() else {
827 panic!("Invalid AST node");
828 };
829
830 let mut data_objects = Vec::with_capacity(node.child_nodes().len());
831 let mut previous_data_object = None;
832
833 for child_node in node.child_nodes() {
834 if matches!(child_node.node_data(), NodeData::FunctionCallPreviousNodeValue {..}) &&
835 previous_data_object.is_some() {
836 let ret = self.process_function_call_previous_node_value_node(
837 child_node,
838 previous_data_object.clone(),
839 );
840
841 if matches!(ret.node_data(), NodeData::FunctionCallPreviousNodeValue {..}) {
842 data_objects.pop();
844 data_objects.push(self.interpret_function_call_previous_node(&ret, previous_data_object.unwrap()));
845 }else {
846 data_objects.push(self.interpret_node(None, &ret).unwrap());
847 }
848
849 previous_data_object = Some(data_objects[data_objects.len() - 1].clone());
850
851 continue;
852 }
853
854 let ret = self.interpret_node(composite_type.take(), child_node);
855 if let Some(ret) = &ret {
856 data_objects.push(ret.clone());
857 }
858
859 previous_data_object.clone_from(&ret);
860 }
861
862 utils::combine_data_objects(
863 &data_objects,
864 self,
865 node.pos(),
866 )
867 }
868
869 fn interpret_value_node(&mut self, node: &Node) -> DataObjectRef {
870 match node.node_data() {
871 NodeData::CharValue(value) => {
872 DataObjectRef::new(DataObject::with_update(|data_object| {
873 data_object.set_char(*value)
874 }).unwrap())
875 },
876
877 NodeData::TextValue(value) => {
878 DataObjectRef::new(DataObject::with_update(|data_object| {
879 data_object.set_text(&**value)
880 }).unwrap())
881 },
882
883 NodeData::IntValue(value) => {
884 DataObjectRef::new(DataObject::with_update(|data_object| {
885 data_object.set_int(*value)
886 }).unwrap())
887 },
888
889 NodeData::LongValue(value) => {
890 DataObjectRef::new(DataObject::with_update(|data_object| {
891 data_object.set_long(*value)
892 }).unwrap())
893 },
894
895 NodeData::FloatValue(value) => {
896 DataObjectRef::new(DataObject::with_update(|data_object| {
897 data_object.set_float(*value)
898 }).unwrap())
899 },
900
901 NodeData::DoubleValue(value) => {
902 DataObjectRef::new(DataObject::with_update(|data_object| {
903 data_object.set_double(*value)
904 }).unwrap())
905 },
906
907 NodeData::NullValue => {
908 DataObjectRef::new(DataObject::new())
909 },
910
911 NodeData::VoidValue => {
912 DataObjectRef::new(DataObject::new_void())
913 },
914
915 _ => {
916 DataObjectRef::new(DataObject::with_update(|data_object| {
917 data_object.set_error(Gc::new(ErrorObject::new(
918 InterpretingError::InvalidAstNode,
919 None,
920 )))
921 }).unwrap())
922 },
923 }
924 }
925
926 fn interpret_parsing_error_node(&mut self, node: &Node) -> DataObjectRef {
927 let NodeData::ParsingError {
928 error,
929 message,
930 } = node.node_data() else {
931 panic!("Invalid AST node");
932 };
933
934 let error = match error {
935 ParsingError::BracketMismatch => InterpretingError::BracketMismatch,
936
937 ParsingError::ContFlowArgMissing => InterpretingError::ContFlowArgMissing,
938
939 ParsingError::Eof => InterpretingError::Eof,
940
941 ParsingError::InvalidConPart => InterpretingError::InvalidConPart,
942
943 ParsingError::InvalidAssignment => InterpretingError::InvalidAssignment,
944
945 ParsingError::InvalidParameter |
946 ParsingError::LexerError => InterpretingError::InvalidAstNode,
947 };
948
949 self.set_errno_error_object(
950 error,
951 Some(message),
952 node.pos(),
953 )
954 }
955
956 fn interpret_if_statement_node(&mut self, node: &Node) -> bool {
960 let NodeData::IfStatement = node.node_data() else {
961 panic!("Invalid AST node");
962 };
963
964 let nodes = node.child_nodes();
965 if nodes.is_empty() {
966 self.set_errno(
967 InterpretingError::InvalidAstNode,
968 Some("Empty if statement"),
969 node.pos(),
970 );
971
972 return false;
973 }
974
975 for node in nodes {
976 if self.interpret_if_statement_part_node(node) {
977 return true;
978 }
979 }
980
981 false
982 }
983
984 fn interpret_if_statement_part_node(&mut self, node: &Node) -> bool {
988 match node.node_data() {
989 NodeData::IfStatementPartIf {
990 if_body,
991 condition,
992 } => {
993 let condition = self.interpret_operation_node(
994 condition.node(),
995 ).unwrap();
996
997 let condition = conversions::to_bool(self, &condition, node.pos());
998 if condition {
999 self.interpret_ast(if_body);
1000 }
1001
1002 condition
1003 },
1004
1005 NodeData::IfStatementPartElse(if_body) => {
1006 self.interpret_ast(if_body);
1007
1008 true
1009 },
1010
1011 _ => panic!("Invalid AST node"),
1012 }
1013 }
1014
1015 fn interpret_loop_statement_node(&mut self, node: &Node) -> bool {
1019 let NodeData::LoopStatement = node.node_data() else {
1020 panic!("Invalid AST node");
1021 };
1022
1023 let nodes = node.child_nodes();
1024 if nodes.is_empty() {
1025 self.set_errno(
1026 InterpretingError::InvalidAstNode,
1027 Some("Empty loop statement"),
1028 node.pos(),
1029 );
1030
1031 return false;
1032 }
1033
1034 for node in nodes {
1035 if self.interpret_loop_statement_part_node(node) {
1036 return true;
1037 }
1038 }
1039
1040 false
1041 }
1042
1043 fn should_break_current_loop_iteration(&mut self) -> bool {
1048 if self.execution_state.stop_execution_flag {
1049 if self.execution_state.break_continue_count == 0 {
1050 return true;
1051 }
1052
1053 self.execution_state.break_continue_count -= 1;
1055 if self.execution_state.break_continue_count > 0 {
1056 return true;
1057 }
1058
1059 self.execution_state.stop_execution_flag = false;
1060
1061 return !self.execution_state.is_continue_statement;
1062 }
1063
1064 false
1065 }
1066
1067 fn interpret_loop_statement_part_node(&mut self, node: &Node) -> bool {
1071 let mut flag = false;
1072
1073 let ret = 'error: {
1074 match node.node_data() {
1075 NodeData::LoopStatementPartLoop(loop_body) => {
1076 loop {
1077 self.interpret_ast(loop_body);
1078 if self.should_break_current_loop_iteration() {
1079 return true;
1080 }
1081 }
1082 },
1083
1084 NodeData::LoopStatementPartWhile {
1085 loop_body,
1086 condition,
1087 } => {
1088 loop {
1089 let condition = self.interpret_operation_node(
1090 condition.node(),
1091 ).unwrap();
1092
1093 let condition = conversions::to_bool(self, &condition, node.pos());
1094 if !condition {
1095 break;
1096 }
1097
1098 flag = true;
1099
1100 self.interpret_ast(loop_body);
1101 if self.should_break_current_loop_iteration() {
1102 return true;
1103 }
1104 }
1105
1106 Ok(())
1107 },
1108
1109 NodeData::LoopStatementPartUntil {
1110 loop_body,
1111 condition,
1112 } => {
1113 loop {
1114 let condition = self.interpret_operation_node(
1115 condition.node(),
1116 ).unwrap();
1117
1118 let condition = conversions::to_bool(self, &condition, node.pos());
1119 if condition {
1120 break;
1121 }
1122
1123 flag = true;
1124
1125 self.interpret_ast(loop_body);
1126 if self.should_break_current_loop_iteration() {
1127 return true;
1128 }
1129 }
1130
1131 Ok(())
1132 },
1133
1134 NodeData::LoopStatementPartRepeat {
1135 loop_body,
1136 var_pointer_node,
1137 repeat_count_node,
1138 } => {
1139 let var_pointer = self.interpret_node(None, var_pointer_node).unwrap();
1140 let var = {
1141 if !matches!(var_pointer.data_type(), DataType::VAR_POINTER | DataType::NULL) {
1142 self.set_errno(
1143 InterpretingError::IncompatibleDataType,
1144 Some("con.repeat needs a variablePointer or a null value for the current iteration variable"),
1145 node.pos(),
1146 );
1147
1148 return false;
1149 }
1150
1151 var_pointer.var_pointer_value()
1152 };
1153
1154 let iterations = self.interpret_node(None, repeat_count_node).
1155 and_then(|data_object| {
1156 conversions::to_number(self, &data_object, node.pos())
1157 });
1158 let Some(iterations) = iterations else {
1159 self.set_errno(
1160 InterpretingError::IncompatibleDataType,
1161 Some("con.repeat needs a repeat count value"),
1162 node.pos(),
1163 );
1164
1165 return false;
1166 };
1167
1168 let iterations = iterations.int_value();
1169 if iterations < 0 {
1170 self.set_errno(
1171 InterpretingError::IncompatibleDataType,
1172 Some("con.repeat repeat count can not be less than 0"),
1173 node.pos(),
1174 );
1175
1176 return false;
1177 }
1178
1179 for i in 0..iterations {
1180 flag = true;
1181
1182 if let Some(var) = &var {
1183 if var.is_final_data() || var.is_lang_var() {
1184 self.set_errno(
1185 InterpretingError::FinalVarChange,
1186 Some("con.repeat current iteration value can not be set"),
1187 node.pos(),
1188 );
1189 }else {
1190 let mut var = var.borrow_mut();
1191
1192 let ret = var.set_int(i);
1193 if ret.is_err() {
1194 self.set_errno(
1195 InterpretingError::IncompatibleDataType,
1196 Some("con.repeat current iteration value can not be set"),
1197 node.pos(),
1198 );
1199 }
1200 }
1201 }
1202
1203 self.interpret_ast(loop_body);
1204 if self.should_break_current_loop_iteration() {
1205 return true;
1206 }
1207 }
1208
1209 Ok(())
1210 },
1211
1212 NodeData::LoopStatementPartForEach {
1213 loop_body,
1214 var_pointer_node,
1215 composite_or_text_node,
1216 } => {
1217 let var_pointer = self.interpret_node(None, var_pointer_node).unwrap();
1218 let var = {
1219 if let Some(var_pointer_value) = var_pointer.var_pointer_value() {
1220 var_pointer_value
1221 }else {
1222 self.set_errno(
1223 InterpretingError::IncompatibleDataType,
1224 Some("con.foreach needs a variablePointer for the current element variable"),
1225 node.pos(),
1226 );
1227
1228 return false;
1229 }
1230 };
1231
1232 let pos = composite_or_text_node.pos();
1233 let composition_or_text = self.interpret_node(None, composite_or_text_node).unwrap();
1234 let iterator = operators::op_iter(self, &composition_or_text, pos);
1235 let Some(iterator) = iterator else {
1236 self.set_errno(
1237 InterpretingError::IncompatibleDataType,
1238 Some("The provided value to con.foreach does not support iteration"),
1239 node.pos(),
1240 );
1241
1242 return false;
1243 };
1244
1245 loop {
1246 let has_next = operators::op_has_next(self, &iterator, pos);
1247 let Some(has_next) = has_next else {
1248 self.set_errno(
1249 InterpretingError::IncompatibleDataType,
1250 Some("Invalid iterator implementation for value provided to con.foreach"),
1251 node.pos(),
1252 );
1253
1254 return false;
1255 };
1256
1257 if !conversions::to_bool(self, &has_next, pos) {
1258 break;
1259 }
1260
1261 let next = operators::op_next(self, &iterator, pos);
1262 let Some(next) = next else {
1263 self.set_errno(
1264 InterpretingError::IncompatibleDataType,
1265 Some("Invalid iterator implementation for value provided to con.foreach"),
1266 node.pos(),
1267 );
1268
1269 return false;
1270 };
1271
1272 flag = true;
1273
1274 {
1275 if var.is_final_data() || var.is_lang_var() {
1276 self.set_errno(
1277 InterpretingError::FinalVarChange,
1278 Some("con.foreach current element value can not be set"),
1279 node.pos(),
1280 );
1281 }else {
1282 let mut var = var.borrow_mut();
1283
1284 let ret = var.set_data(&next.borrow());
1285 if ret.is_err() {
1286 break 'error ret.map(|_| ());
1287 }
1288 }
1289 }
1290
1291 self.interpret_ast(loop_body);
1292 if self.should_break_current_loop_iteration() {
1293 return true;
1294 }
1295 }
1296
1297 Ok(())
1298 },
1299
1300 NodeData::LoopStatementPartElse(loop_body) => {
1301 flag = true;
1302 self.interpret_ast(loop_body);
1303
1304 Ok(())
1305 },
1306
1307 _ => panic!("Invalid AST node"),
1308 }
1309 };
1310 if let Err(e) = ret {
1311 self.set_errno(
1312 InterpretingError::IncompatibleDataType,
1313 Some(e.message()),
1314 node.pos(),
1315 );
1316
1317 return false;
1318 }
1319
1320 flag
1321 }
1322
1323 fn interpret_loop_statement_continue_break(&mut self, node: &Node) {
1324 let NodeData::ContinueBreakStatement {
1325 continue_node,
1326 number_node,
1327 } = node.node_data() else {
1328 panic!("Invalid AST node");
1329 };
1330
1331 if let Some(number_node) = number_node {
1332 let level = self.interpret_node(None, number_node).
1333 and_then(|data_object| {
1334 conversions::to_number(self, &data_object, node.pos())
1335 });
1336 let Some(level) = level else {
1337 self.set_errno(
1338 InterpretingError::IncompatibleDataType,
1339 Some(&format!(
1340 "con.{} needs either non value or a level number",
1341 if *continue_node {
1342 "continue"
1343 }else {
1344 "break"
1345 }
1346 )),
1347 node.pos(),
1348 );
1349
1350 return;
1351 };
1352
1353 let level = level.int_value();
1354 if level < 1 {
1355 self.execution_state.break_continue_count = 0;
1356
1357 self.set_errno(
1358 InterpretingError::InvalidArguments,
1359 Some(&format!(
1360 "con.{} the level must be > 0",
1361 if *continue_node {
1362 "continue"
1363 }else {
1364 "break"
1365 }
1366 )),
1367 node.pos(),
1368 );
1369
1370 return;
1371 }
1372
1373 self.execution_state.break_continue_count = level as u32;
1374 }else {
1375 self.execution_state.break_continue_count = 1;
1376 }
1377
1378 self.execution_state.is_continue_statement = *continue_node;
1379 self.execution_state.stop_execution_flag = true;
1380 }
1381
1382 fn save_execution_stop_state_to_var_and_reset(&mut self, saved_execution_state: &mut ExecutionState) {
1383 saved_execution_state.stop_execution_flag = self.execution_state.stop_execution_flag;
1384 saved_execution_state.returned_or_thrown_value = self.execution_state.returned_or_thrown_value.take();
1385 saved_execution_state.is_thrown_value = self.execution_state.is_thrown_value;
1386 saved_execution_state.return_or_throw_statement_pos = self.execution_state.return_or_throw_statement_pos;
1387 saved_execution_state.break_continue_count = self.execution_state.break_continue_count;
1388 saved_execution_state.is_continue_statement = self.execution_state.is_continue_statement;
1389 self.execution_state.stop_execution_flag = false;
1390 self.execution_state.is_thrown_value = false;
1392 self.execution_state.return_or_throw_statement_pos = CodePosition::EMPTY;
1393 self.execution_state.break_continue_count = 0;
1394 self.execution_state.is_continue_statement = false;
1395 }
1396 fn interpret_try_statement_node(&mut self, node: &Node) -> bool {
1400 let NodeData::TryStatement = node.node_data() else {
1401 panic!("Invalid AST node");
1402 };
1403
1404 let nodes = node.child_nodes();
1405 if nodes.is_empty() {
1406 self.set_errno(
1407 InterpretingError::InvalidAstNode,
1408 Some("Empty try statement"),
1409 node.pos(),
1410 );
1411
1412 return false;
1413 }
1414
1415 let mut saved_execution_state = ExecutionState::new();
1416
1417 let try_part = &nodes[0];
1418 if !matches!(try_part.node_data(), NodeData::TryStatementPartTry(..) | NodeData::TryStatementPartSoftTry(..) |
1419 NodeData::TryStatementPartNonTry(..)) {
1420 self.set_errno(
1421 InterpretingError::InvalidAstNode,
1422 Some("First part of try statement was no try nor soft try nor non try part"),
1423 node.pos(),
1424 );
1425
1426 return false;
1427 }
1428 self.interpret_try_statement_part_node(try_part);
1429
1430 if self.execution_state.stop_execution_flag {
1431 self.save_execution_stop_state_to_var_and_reset(&mut saved_execution_state);
1432 }
1433
1434 let mut flag = false;
1435 if saved_execution_state.stop_execution_flag && self.execution_state.try_thrown_error.is_some() {
1436 let catch_parts = nodes.iter().
1437 skip(1).
1438 take_while(|node| matches!(node.node_data(), NodeData::TryStatementPartCatch {..}));
1439
1440 for node in catch_parts {
1441 flag = self.interpret_try_statement_part_node(node);
1442 if flag {
1443 if self.execution_state.stop_execution_flag {
1444 self.save_execution_stop_state_to_var_and_reset(&mut saved_execution_state);
1445 }else {
1446 saved_execution_state = ExecutionState::new();
1448 self.execution_state.try_thrown_error = None;
1449
1450 self.get_and_clear_errno_error_object();
1452 }
1453
1454 break;
1455 }
1456 }
1457 }
1458
1459 let saved_stop_execution_flag_for_else_block = saved_execution_state.stop_execution_flag;
1460
1461 if saved_execution_state.stop_execution_flag && (saved_execution_state.try_thrown_error.is_none() || saved_execution_state.try_block_level == 0 ||
1463 (saved_execution_state.is_soft_try && saved_execution_state.try_body_scope_id != self.scope_id)) {
1464 saved_execution_state.stop_execution_flag = false;
1465 }
1466
1467 if !flag && !saved_stop_execution_flag_for_else_block && nodes.len() > 1 {
1468 let mut node = None;
1469
1470 if matches!(nodes[nodes.len() - 2].node_data(), NodeData::TryStatementPartElse(..)) {
1471 node = Some(&nodes[nodes.len() - 2]);
1472 }else if matches!(nodes[nodes.len() - 1].node_data(), NodeData::TryStatementPartElse(..)) {
1473 node = Some(&nodes[nodes.len() - 1]);
1474 }
1475
1476 if let Some(node) = node {
1477 flag = self.interpret_try_statement_part_node(node);
1478
1479 if self.execution_state.stop_execution_flag {
1480 self.save_execution_stop_state_to_var_and_reset(&mut saved_execution_state);
1481 }
1482 }
1483 }
1484
1485 if nodes.len() > 1 && matches!(nodes[nodes.len() - 1].node_data(), NodeData::TryStatementPartFinally(..)) {
1486 self.interpret_try_statement_part_node(&nodes[nodes.len() - 1]);
1487 }
1488
1489 if !self.execution_state.stop_execution_flag {
1491 self.execution_state.stop_execution_flag = saved_execution_state.stop_execution_flag;
1492 self.execution_state.returned_or_thrown_value = saved_execution_state.returned_or_thrown_value;
1493 self.execution_state.is_thrown_value = saved_execution_state.is_thrown_value;
1494 self.execution_state.return_or_throw_statement_pos = saved_execution_state.return_or_throw_statement_pos;
1495 self.execution_state.break_continue_count = saved_execution_state.break_continue_count;
1496 self.execution_state.is_continue_statement = saved_execution_state.is_continue_statement;
1497 }
1498
1499 flag
1500 }
1501
1502 fn interpret_try_statement_part_node(&mut self, node: &Node) -> bool {
1506 let mut flag = false;
1507
1508 match node.node_data() {
1509 NodeData::TryStatementPartTry(try_body) |
1510 NodeData::TryStatementPartSoftTry(try_body) => {
1511 self.execution_state.try_thrown_error = None;
1512 self.execution_state.try_block_level += 1;
1513 let is_old_soft_try_old = self.execution_state.is_soft_try;
1514 self.execution_state.is_soft_try = matches!(node.node_data(), NodeData::TryStatementPartSoftTry(..));
1515 let old_try_block_scope_id = self.execution_state.try_body_scope_id;
1516 self.execution_state.try_body_scope_id = self.scope_id;
1517
1518 self.interpret_ast(try_body);
1519
1520 self.execution_state.try_block_level -= 1;
1521 self.execution_state.is_soft_try = is_old_soft_try_old;
1522 self.execution_state.try_body_scope_id = old_try_block_scope_id;
1523 },
1524
1525 NodeData::TryStatementPartNonTry(try_body) => {
1526 self.execution_state.try_thrown_error = None;
1527 let old_try_block_level = self.execution_state.try_block_level;
1528 self.execution_state.try_block_level = 0;
1529 let is_old_soft_try_old = self.execution_state.is_soft_try;
1530 self.execution_state.is_soft_try = false;
1531 let old_try_block_scope_id = self.execution_state.try_body_scope_id;
1532 self.execution_state.try_body_scope_id = 0;
1533
1534 self.interpret_ast(try_body);
1535
1536 self.execution_state.try_block_level = old_try_block_level;
1537 self.execution_state.is_soft_try = is_old_soft_try_old;
1538 self.execution_state.try_body_scope_id = old_try_block_scope_id;
1539 },
1540
1541 NodeData::TryStatementPartCatch {
1542 try_body,
1543 errors,
1544 } => {
1545 let Some(try_thrown_error) = self.execution_state.try_thrown_error else {
1546 return false;
1547 };
1548
1549 if let Some(errors) = errors {
1550 if errors.is_empty() {
1551 self.set_errno(
1552 InterpretingError::InvalidAstNode,
1553 Some(
1554 "Empty catch part \"catch()\" is not allowed!\n\
1555 For checking all warnings \"catch\" without \"()\" should be used",
1556 ),
1557 node.pos(),
1558 );
1559
1560 return false;
1561 }
1562
1563 let mut data_objects = Vec::new();
1564 let mut found_error = false;
1565 let mut previous_data_object = None;
1566 for child_node in errors {
1567 if matches!(child_node.node_data(), NodeData::FunctionCallPreviousNodeValue {..}) &&
1568 previous_data_object.is_some() {
1569 let ret = self.process_function_call_previous_node_value_node(
1570 child_node,
1571 previous_data_object.clone(),
1572 );
1573
1574 if matches!(ret.node_data(), NodeData::FunctionCallPreviousNodeValue {..}) {
1575 data_objects.pop();
1577 data_objects.push(self.interpret_function_call_previous_node(&ret, previous_data_object.unwrap()));
1578 }else {
1579 data_objects.push(self.interpret_node(None, &ret).unwrap());
1580 }
1581
1582 previous_data_object = Some(data_objects[data_objects.len() - 1].clone());
1583
1584 continue;
1585 }
1586
1587 let ret = self.interpret_node(None, child_node);
1588 if let Some(ret) = &ret {
1589 data_objects.push(ret.clone());
1590 }
1591
1592 previous_data_object = ret;
1593 }
1594
1595 let error_list = utils::combine_arguments_without_argument_separators(
1596 &data_objects, self, node.pos(),
1597 );
1598
1599 for data_object in error_list {
1600 let Some(error_value) = data_object.error_value() else {
1601 self.set_errno(
1602 InterpretingError::InvalidArguments,
1603 Some(&format!(
1604 "Variable with type other than {} in catch statement",
1605 DataType::ERROR,
1606 )),
1607 node.pos(),
1608 );
1609
1610 continue;
1611 };
1612
1613 if error_value.err() == try_thrown_error {
1614 found_error = true;
1615 }
1616 }
1617
1618 if !found_error {
1619 return false;
1620 }
1621 }
1622
1623 flag = true;
1624
1625 self.interpret_ast(try_body);
1626 },
1627
1628 NodeData::TryStatementPartElse(try_body) => {
1629 if self.execution_state.try_thrown_error.is_some() {
1630 return false;
1631 }
1632
1633 flag = true;
1634
1635 self.interpret_ast(try_body);
1636 },
1637
1638 NodeData::TryStatementPartFinally(try_body) => {
1639 self.interpret_ast(try_body);
1640 },
1641
1642 _ => panic!("Invalid AST node"),
1643 }
1644
1645 flag
1646 }
1647
1648 fn interpret_operation_node(&mut self, node: &Node) -> OptionDataObjectRef {
1649 let operation = match node.node_data() {
1650 NodeData::Operation(operation) |
1651 NodeData::Math(operation) |
1652 NodeData::Condition(operation) => operation,
1653
1654 _ => panic!("Invalid AST node"),
1655 };
1656
1657 let left_side_operand = if operation.operator().is_unary() &&
1658 operation.operator().lazy_evaluation() {
1659 None
1660 }else {
1661 self.interpret_node(None, operation.left_side_operand().unwrap())
1662 };
1663
1664 let mut middle_operand = if !operation.operator().is_ternary() ||
1665 operation.operator().lazy_evaluation() {
1666 None
1667 }else {
1668 self.interpret_node(None, operation.middle_operand().unwrap())
1669 };
1670
1671 let mut right_side_operand = if operation.operator().is_unary() ||
1672 operation.operator().lazy_evaluation() {
1673 None
1674 }else {
1675 self.interpret_node(None, operation.right_side_operand().unwrap())
1676 };
1677
1678 if left_side_operand.is_none() && matches!(operation.operator(),
1680 Operator::Non | Operator::MathNon | Operator::ConditionalNon) {
1681 return None;
1682 }
1683
1684 if matches!(operation.operator(), Operator::Slice | Operator::OptionalSlice) {
1686 if middle_operand.is_none() {
1687 middle_operand = Some(DataObjectRef::new(DataObject::new_void()));
1688 }
1689
1690 if right_side_operand.is_none() {
1691 right_side_operand = Some(DataObjectRef::new(DataObject::new_void()));
1692 }
1693 }
1694
1695 if (left_side_operand.is_none() && (!operation.operator().is_unary() || !operation.operator().lazy_evaluation())) ||
1696 (!operation.operator().lazy_evaluation() && ((!operation.operator().is_unary() && right_side_operand.is_none()) ||
1697 (operation.operator().is_ternary() && middle_operand.is_none()))) {
1698 return Some(self.set_errno_error_object(
1699 InterpretingError::InvalidAstNode,
1700 Some("Missing operand"),
1701 node.pos(),
1702 ));
1703 }
1704
1705 match operation.operator_type() {
1706 OperatorType::All => {
1707 let output = match operation.operator() {
1708 Operator::Comma => {
1709 return Some(self.set_errno_error_object(
1710 InterpretingError::InvalidAstNode,
1711 Some("The COMMA operator is parser-only (If you meant the text value of \",\", you must escape the COMMA operator: \"\\,\")"),
1712 node.pos(),
1713 ));
1714 },
1715
1716 Operator::OptionalGetItem => {
1717 operators::op_optional_get_item(
1718 self,
1719 left_side_operand.as_ref().unwrap(),
1720 right_side_operand.as_ref().unwrap(),
1721 node.pos(),
1722 )
1723 },
1724
1725 Operator::GetItem => {
1726 operators::op_get_item(
1727 self,
1728 left_side_operand.as_ref().unwrap(),
1729 right_side_operand.as_ref().unwrap(),
1730 node.pos(),
1731 )
1732 },
1733
1734 Operator::OptionalSlice => {
1735 operators::op_optional_slice(
1736 self,
1737 left_side_operand.as_ref().unwrap(),
1738 middle_operand.as_ref().unwrap(),
1739 right_side_operand.as_ref().unwrap(),
1740 node.pos(),
1741 )
1742 },
1743
1744 Operator::Slice => {
1745 operators::op_slice(
1746 self,
1747 left_side_operand.as_ref().unwrap(),
1748 middle_operand.as_ref().unwrap(),
1749 right_side_operand.as_ref().unwrap(),
1750 node.pos(),
1751 )
1752 },
1753
1754 Operator::MemberAccessPointer => {
1755 let left_side_operand = left_side_operand.as_ref().unwrap();
1756
1757 let Some(left_side_operand) = left_side_operand.var_pointer_value() else {
1758 return Some(self.set_errno_error_object(
1759 InterpretingError::InvalidArguments,
1760 Some(&format!(
1761 "The left side operand of the member access pointer operator (\"{}\") must be a pointer",
1762 operation.operator().symbol(),
1763 )),
1764 node.pos(),
1765 ));
1766 };
1767
1768 if !utils::is_member_access_allowed(&left_side_operand) {
1769 return Some(self.set_errno_error_object(
1770 InterpretingError::InvalidArguments,
1771 Some(&format!(
1772 "The left side operand of the member access pointer operator (\"{}\") must be a pointer pointing to a composite type",
1773 operation.operator().symbol(),
1774 )),
1775 node.pos(),
1776 ));
1777 }
1778
1779 return self.interpret_node(Some(left_side_operand), operation.right_side_operand().unwrap());
1780 },
1781
1782 Operator::MemberAccess => {
1783 let left_side_operand = left_side_operand.unwrap();
1784
1785 let is_super_keyword = {
1786 if let Some(text_value) = left_side_operand.text_value() {
1787 matches!(operation.left_side_operand().unwrap().node_data(), NodeData::TextValue(..)) &&
1788 &*text_value == "super"
1789 }else {
1790 false
1791 }
1792 };
1793
1794 if !is_super_keyword && !utils::is_member_access_allowed(&left_side_operand) {
1795 return Some(self.set_errno_error_object(
1796 InterpretingError::InvalidArguments,
1797 Some(&format!(
1798 "The left side operand of the member access operator (\"{}\") must be a composite type",
1799 operation.operator().symbol(),
1800 )),
1801 node.pos(),
1802 ));
1803 }
1804
1805 return self.interpret_node(Some(left_side_operand), operation.right_side_operand().unwrap());
1806 },
1807
1808 Operator::MemberAccessThis => {
1809 let composite_type = self.data_ref().var.get("&this").cloned();
1810
1811 if composite_type.as_ref().is_none_or(|composite_type|
1812 !matches!(composite_type.data_type(), DataType::STRUCT | DataType::OBJECT)) {
1813 return Some(self.set_errno_error_object(
1814 InterpretingError::InvalidArguments,
1815 Some(&format!(
1816 "\"&this\" is not present or invalid for the member access this operator (\"{}\")",
1817 operation.operator().symbol(),
1818 )),
1819 node.pos(),
1820 ));
1821 }
1822
1823 return self.interpret_node(composite_type, operation.left_side_operand().unwrap());
1824 },
1825
1826 Operator::OptionalMemberAccess => {
1827 let left_side_operand = left_side_operand.unwrap();
1828 if matches!(left_side_operand.data_type(), DataType::NULL | DataType::VOID) {
1829 return Some(DataObjectRef::new(DataObject::new_void()));
1830 }
1831
1832 if !utils::is_member_access_allowed(&left_side_operand) {
1833 return Some(self.set_errno_error_object(
1834 InterpretingError::InvalidArguments,
1835 Some(&format!(
1836 "The left side operand of the optional member access operator (\"{}\") must be a composite type",
1837 operation.operator().symbol(),
1838 )),
1839 node.pos(),
1840 ));
1841 }
1842
1843 return self.interpret_node(Some(left_side_operand), operation.right_side_operand().unwrap());
1844 },
1845
1846 _ => panic!("Invalid AST node"),
1847 };
1848
1849 if output.is_none() {
1850 let left_side_operand_data_type = {
1851 let left_side_operand = left_side_operand.as_ref().unwrap();
1852
1853 format!("{}", left_side_operand.data_type())
1854 };
1855
1856 let middle_operand_data_type = {
1857 if operation.operator().is_ternary() {
1858 let middle_operand = middle_operand.as_ref().unwrap();
1859
1860 format!(", {},", middle_operand.data_type())
1861 }else {
1862 String::new()
1863 }
1864 };
1865
1866 let right_side_operand_data_type = {
1867 if !operation.operator().is_unary() {
1868 let right_side_operand = right_side_operand.as_ref().unwrap();
1869
1870 format!(" and {}", right_side_operand.data_type())
1871 }else {
1872 String::new()
1873 }
1874 };
1875
1876 return Some(self.set_errno_error_object(
1877 InterpretingError::InvalidArguments,
1878 Some(&format!(
1879 "The \"{}\" operator is not defined for {}{}{}",
1880 operation.operator().symbol(),
1881 left_side_operand_data_type,
1882 middle_operand_data_type,
1883 right_side_operand_data_type,
1884 )),
1885 node.pos(),
1886 ));
1887 }
1888
1889 output
1890 },
1891
1892 OperatorType::General => {
1893 let output = match operation.operator() {
1894 Operator::Non => {
1896 let left_side_operand = left_side_operand.as_ref().unwrap();
1897
1898 Some(left_side_operand.clone())
1899 },
1900
1901 Operator::Len => {
1902 operators::op_len(
1903 self,
1904 left_side_operand.as_ref().unwrap(),
1905 node.pos(),
1906 )
1907 },
1908
1909 Operator::DeepCopy => {
1910 operators::op_deep_copy(
1911 self,
1912 left_side_operand.as_ref().unwrap(),
1913 node.pos(),
1914 )
1915 },
1916
1917 Operator::Concat => {
1919 operators::op_concat(
1920 self,
1921 left_side_operand.as_ref().unwrap(),
1922 right_side_operand.as_ref().unwrap(),
1923 node.pos(),
1924 )
1925 },
1926
1927 Operator::Spaceship => {
1928 operators::op_spaceship(
1929 self,
1930 left_side_operand.as_ref().unwrap(),
1931 right_side_operand.as_ref().unwrap(),
1932 node.pos(),
1933 )
1934 },
1935
1936 Operator::Elvis => {
1937 let left_side_operand = left_side_operand.unwrap();
1938 if conversions::to_bool(self, &left_side_operand, node.pos()) {
1939 return Some(left_side_operand);
1940 }
1941
1942 let right_side_operand = self.interpret_node(
1943 None, operation.right_side_operand().unwrap(),
1944 );
1945
1946 if right_side_operand.is_none() {
1947 return Some(self.set_errno_error_object(
1948 InterpretingError::InvalidAstNode,
1949 Some("Missing operand"),
1950 node.pos(),
1951 ));
1952 }
1953
1954 return right_side_operand;
1955 },
1956
1957 Operator::NullCoalescing => {
1958 let left_side_operand = left_side_operand.unwrap();
1959 if !matches!(left_side_operand.data_type(), DataType::NULL | DataType::VOID) {
1960 return Some(left_side_operand);
1961 }
1962
1963 let right_side_operand = self.interpret_node(
1964 None, operation.right_side_operand().unwrap(),
1965 );
1966
1967 if right_side_operand.is_none() {
1968 return Some(self.set_errno_error_object(
1969 InterpretingError::InvalidAstNode,
1970 Some("Missing operand"),
1971 node.pos(),
1972 ));
1973 }
1974
1975 return right_side_operand;
1976 },
1977
1978 Operator::InlineIf => {
1980 let left_side_operand = left_side_operand.unwrap();
1981
1982 let operand = if conversions::to_bool(self, &left_side_operand, node.pos()) {
1983 self.interpret_node(None, operation.middle_operand().unwrap())
1984 }else {
1985 self.interpret_node(None, operation.right_side_operand().unwrap())
1986 };
1987
1988 if operand.is_none() {
1989 return Some(self.set_errno_error_object(
1990 InterpretingError::InvalidAstNode,
1991 Some("Missing operand"),
1992 node.pos(),
1993 ));
1994 }
1995
1996 return operand;
1997 },
1998
1999 _ => panic!("Invalid AST node"),
2000 };
2001
2002 if output.is_none() {
2003 let left_side_operand_data_type = {
2004 let left_side_operand = left_side_operand.as_ref().unwrap();
2005
2006 format!("{}", left_side_operand.data_type())
2007 };
2008
2009 let middle_operand_data_type = {
2010 if operation.operator().is_ternary() {
2011 let middle_operand = middle_operand.as_ref().unwrap();
2012
2013 format!(", {},", middle_operand.data_type())
2014 }else {
2015 String::new()
2016 }
2017 };
2018
2019 let right_side_operand_data_type = {
2020 if !operation.operator().is_unary() {
2021 let right_side_operand = right_side_operand.as_ref().unwrap();
2022
2023 format!(" and {}", right_side_operand.data_type())
2024 }else {
2025 String::new()
2026 }
2027 };
2028
2029 return Some(self.set_errno_error_object(
2030 InterpretingError::InvalidArguments,
2031 Some(&format!(
2032 "The \"{}\" operator is not defined for {}{}{}",
2033 operation.operator().symbol(),
2034 left_side_operand_data_type,
2035 middle_operand_data_type,
2036 right_side_operand_data_type,
2037 )),
2038 node.pos(),
2039 ));
2040 }
2041
2042 output
2043 },
2044
2045 OperatorType::Math => {
2046 let output = match operation.operator() {
2047 Operator::MathNon => {
2049 let left_side_operand = left_side_operand.as_ref().unwrap();
2050
2051 Some(left_side_operand.clone())
2052 },
2053
2054 Operator::Pos => {
2055 operators::op_pos(
2056 self,
2057 left_side_operand.as_ref().unwrap(),
2058 node.pos(),
2059 )
2060 },
2061
2062 Operator::Inv => {
2063 operators::op_inv(
2064 self,
2065 left_side_operand.as_ref().unwrap(),
2066 node.pos(),
2067 )
2068 },
2069
2070 Operator::BitwiseNot => {
2071 operators::op_not(
2072 self,
2073 left_side_operand.as_ref().unwrap(),
2074 node.pos(),
2075 )
2076 },
2077
2078 Operator::Inc => {
2079 operators::op_inc(
2080 self,
2081 left_side_operand.as_ref().unwrap(),
2082 node.pos(),
2083 )
2084 },
2085
2086 Operator::Dec => {
2087 operators::op_dec(
2088 self,
2089 left_side_operand.as_ref().unwrap(),
2090 node.pos(),
2091 )
2092 },
2093
2094 Operator::Pow => {
2096 operators::op_pow(
2097 self,
2098 left_side_operand.as_ref().unwrap(),
2099 right_side_operand.as_ref().unwrap(),
2100 node.pos(),
2101 )
2102 },
2103
2104 Operator::Mul => {
2105 operators::op_mul(
2106 self,
2107 left_side_operand.as_ref().unwrap(),
2108 right_side_operand.as_ref().unwrap(),
2109 node.pos(),
2110 )
2111 },
2112
2113 Operator::Div => {
2114 operators::op_div(
2115 self,
2116 left_side_operand.as_ref().unwrap(),
2117 right_side_operand.as_ref().unwrap(),
2118 node.pos(),
2119 )
2120 },
2121
2122 Operator::TruncDiv => {
2123 operators::op_trunc_div(
2124 self,
2125 left_side_operand.as_ref().unwrap(),
2126 right_side_operand.as_ref().unwrap(),
2127 node.pos(),
2128 )
2129 },
2130
2131 Operator::FloorDiv => {
2132 operators::op_floor_div(
2133 self,
2134 left_side_operand.as_ref().unwrap(),
2135 right_side_operand.as_ref().unwrap(),
2136 node.pos(),
2137 )
2138 },
2139
2140 Operator::CeilDiv => {
2141 operators::op_ceil_div(
2142 self,
2143 left_side_operand.as_ref().unwrap(),
2144 right_side_operand.as_ref().unwrap(),
2145 node.pos(),
2146 )
2147 },
2148
2149 Operator::Mod => {
2150 operators::op_mod(
2151 self,
2152 left_side_operand.as_ref().unwrap(),
2153 right_side_operand.as_ref().unwrap(),
2154 node.pos(),
2155 )
2156 },
2157
2158 Operator::Add => {
2159 operators::op_add(
2160 self,
2161 left_side_operand.as_ref().unwrap(),
2162 right_side_operand.as_ref().unwrap(),
2163 node.pos(),
2164 )
2165 },
2166
2167 Operator::Sub => {
2168 operators::op_sub(
2169 self,
2170 left_side_operand.as_ref().unwrap(),
2171 right_side_operand.as_ref().unwrap(),
2172 node.pos(),
2173 )
2174 },
2175
2176 Operator::Lshift => {
2177 operators::op_lshift(
2178 self,
2179 left_side_operand.as_ref().unwrap(),
2180 right_side_operand.as_ref().unwrap(),
2181 node.pos(),
2182 )
2183 },
2184
2185 Operator::Rshift => {
2186 operators::op_rshift(
2187 self,
2188 left_side_operand.as_ref().unwrap(),
2189 right_side_operand.as_ref().unwrap(),
2190 node.pos(),
2191 )
2192 },
2193
2194 Operator::Rzshift => {
2195 operators::op_rzshift(
2196 self,
2197 left_side_operand.as_ref().unwrap(),
2198 right_side_operand.as_ref().unwrap(),
2199 node.pos(),
2200 )
2201 },
2202
2203 Operator::BitwiseAnd => {
2204 operators::op_and(
2205 self,
2206 left_side_operand.as_ref().unwrap(),
2207 right_side_operand.as_ref().unwrap(),
2208 node.pos(),
2209 )
2210 },
2211
2212 Operator::BitwiseXor => {
2213 operators::op_xor(
2214 self,
2215 left_side_operand.as_ref().unwrap(),
2216 right_side_operand.as_ref().unwrap(),
2217 node.pos(),
2218 )
2219 },
2220
2221 Operator::BitwiseOr => {
2222 operators::op_or(
2223 self,
2224 left_side_operand.as_ref().unwrap(),
2225 right_side_operand.as_ref().unwrap(),
2226 node.pos(),
2227 )
2228 },
2229
2230 _ => panic!("Invalid AST node"),
2231 };
2232
2233 if output.is_none() {
2234 let left_side_operand_data_type = {
2235 let left_side_operand = left_side_operand.as_ref().unwrap();
2236
2237 format!("{}", left_side_operand.data_type())
2238 };
2239
2240 let middle_operand_data_type = {
2241 if operation.operator().is_ternary() {
2242 let middle_operand = middle_operand.as_ref().unwrap();
2243
2244 format!(", {},", middle_operand.data_type())
2245 }else {
2246 String::new()
2247 }
2248 };
2249
2250 let right_side_operand_data_type = {
2251 if !operation.operator().is_unary() {
2252 let right_side_operand = right_side_operand.as_ref().unwrap();
2253
2254 format!(" and {}", right_side_operand.data_type())
2255 }else {
2256 String::new()
2257 }
2258 };
2259
2260 return Some(self.set_errno_error_object(
2261 InterpretingError::InvalidArguments,
2262 Some(&format!(
2263 "The \"{}\" operator is not defined for {}{}{}",
2264 operation.operator().symbol(),
2265 left_side_operand_data_type,
2266 middle_operand_data_type,
2267 right_side_operand_data_type,
2268 )),
2269 node.pos(),
2270 ));
2271 }
2272
2273 output
2274 },
2275
2276 OperatorType::Condition => {
2277 let condition_output = match operation.operator() {
2278 Operator::ConditionalNon | Operator::Not => {
2280 let condition_output = conversions::to_bool(
2281 self,
2282 left_side_operand.as_ref().unwrap(),
2283 node.pos(),
2284 );
2285
2286 condition_output ^ matches!(operation.operator(), Operator::Not)
2288 },
2289
2290 Operator::And => {
2292 let left_side_condition_output = conversions::to_bool(
2293 self,
2294 left_side_operand.as_ref().unwrap(),
2295 node.pos(),
2296 );
2297
2298 left_side_condition_output && {
2299 let right_side_operand = self.interpret_node(None, operation.right_side_operand().unwrap());
2300 let Some(right_side_operand) = right_side_operand else {
2301 return Some(self.set_errno_error_object(
2302 InterpretingError::InvalidAstNode,
2303 Some("Missing operand"),
2304 node.pos(),
2305 ));
2306 };
2307
2308 conversions::to_bool(
2309 self,
2310 &right_side_operand,
2311 node.pos(),
2312 )
2313 }
2314 },
2315
2316 Operator::Or => {
2317 let left_side_condition_output = conversions::to_bool(
2318 self,
2319 left_side_operand.as_ref().unwrap(),
2320 node.pos(),
2321 );
2322
2323 left_side_condition_output || {
2324 let right_side_operand = self.interpret_node(None, operation.right_side_operand().unwrap());
2325 let Some(right_side_operand) = right_side_operand else {
2326 return Some(self.set_errno_error_object(
2327 InterpretingError::InvalidAstNode,
2328 Some("Missing operand"),
2329 node.pos(),
2330 ));
2331 };
2332
2333 conversions::to_bool(
2334 self,
2335 &right_side_operand,
2336 node.pos(),
2337 )
2338 }
2339 },
2340
2341 Operator::InstanceOf => {
2343 let left_side_operand = left_side_operand.as_ref().unwrap();
2344 let right_side_operand = right_side_operand.as_ref().unwrap();
2345
2346 if let Some(type_value) = right_side_operand.type_value() {
2347 left_side_operand.data_type() == type_value
2348 }else if let Some(struct_definition) = right_side_operand.struct_value() {
2349 if !struct_definition.is_definition() {
2350 return Some(self.set_errno_error_object(
2351 InterpretingError::InvalidArguments,
2352 Some(&format!(
2353 "The second operand of the \"{}\" operator must be a struct definition",
2354 operation.operator().symbol(),
2355 )),
2356 node.pos(),
2357 ));
2358 }
2359
2360 if let Some(struct_value) = left_side_operand.struct_value() {
2361 !struct_value.is_definition() && ptr::eq(
2362 struct_value.base_definition().unwrap().deref(),
2363 struct_definition.deref(),
2364 )
2365 }else {
2366 false
2367 }
2368 }else if let Some(class_value) = right_side_operand.object_value() {
2369 if !class_value.borrow().is_class() {
2370 return Some(self.set_errno_error_object(
2371 InterpretingError::InvalidArguments,
2372 Some(&format!(
2373 "The second operand of the \"{}\" operator must be a class",
2374 operation.operator().symbol(),
2375 )),
2376 node.pos(),
2377 ));
2378 }
2379
2380 if let Some(object_value) = left_side_operand.object_value() {
2381 !object_value.borrow().is_class() && object_value.borrow().is_instance_of(class_value.borrow().deref())
2382 }else {
2383 false
2384 }
2385 }else {
2386 return Some(self.set_errno_error_object(
2387 InterpretingError::InvalidArguments,
2388 Some(&format!(
2389 "The second operand of the \"{}\" operator must be of type {}, {}, or {}",
2390 operation.operator().symbol(),
2391 DataType::TYPE,
2392 DataType::STRUCT,
2393 DataType::OBJECT,
2394 )),
2395 node.pos(),
2396 ));
2397 }
2398 },
2399
2400 Operator::Equals | Operator::NotEquals => {
2401 operators::is_equals(
2403 self,
2404 left_side_operand.as_ref().unwrap(),
2405 right_side_operand.as_ref().unwrap(),
2406 node.pos(),
2407 ) ^ matches!(operation.operator(), Operator::NotEquals)
2408 },
2409
2410 Operator::Matches | Operator::NotMatches => {
2411 let left_side_text = conversions::to_text(
2412 self,
2413 left_side_operand.as_ref().unwrap(),
2414 node.pos(),
2415 );
2416
2417 let right_side_text = conversions::to_text(
2418 self,
2419 right_side_operand.as_ref().unwrap(),
2420 node.pos(),
2421 );
2422
2423 let match_result = regex::matches(&left_side_text, &right_side_text);
2425 match match_result {
2426 Ok(is_match) => is_match ^ matches!(operation.operator(), Operator::NotMatches),
2427
2428 Err(error) => {
2429 return Some(self.set_errno_error_object(
2430 InterpretingError::InvalidRegexSyntax,
2431 Some(error.message()),
2432 node.pos(),
2433 ));
2434 },
2435 }
2436 },
2437
2438 Operator::StrictEquals | Operator::StrictNotEquals => {
2439 operators::is_strict_equals(
2441 self,
2442 left_side_operand.as_ref().unwrap(),
2443 right_side_operand.as_ref().unwrap(),
2444 node.pos(),
2445 ) ^ matches!(operation.operator(), Operator::StrictNotEquals)
2446 },
2447
2448 Operator::LessThan => {
2449 operators::is_less_than(
2450 self,
2451 left_side_operand.as_ref().unwrap(),
2452 right_side_operand.as_ref().unwrap(),
2453 node.pos(),
2454 )
2455 },
2456
2457 Operator::GreaterThan => {
2458 operators::is_greater_than(
2459 self,
2460 left_side_operand.as_ref().unwrap(),
2461 right_side_operand.as_ref().unwrap(),
2462 node.pos(),
2463 )
2464 },
2465
2466 Operator::LessThanOrEquals => {
2467 operators::is_less_than_or_equals(
2468 self,
2469 left_side_operand.as_ref().unwrap(),
2470 right_side_operand.as_ref().unwrap(),
2471 node.pos(),
2472 )
2473 },
2474
2475 Operator::GreaterThanOrEquals => {
2476 operators::is_greater_than_or_equals(
2477 self,
2478 left_side_operand.as_ref().unwrap(),
2479 right_side_operand.as_ref().unwrap(),
2480 node.pos(),
2481 )
2482 },
2483
2484 _ => panic!("Invalid AST node"),
2485 };
2486
2487 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
2488 data_object.set_bool(condition_output)
2489 }).unwrap()))
2490 },
2491 }
2492 }
2493
2494 fn interpret_return_node(&mut self, node: &Node) {
2495 let NodeData::Return = node.node_data() else {
2496 panic!("Invalid AST node");
2497 };
2498
2499 let returned_value_node = node.child_nodes().first();
2500 let returned_value = returned_value_node.and_then(|node| self.interpret_node(None, node));
2501
2502 self.execution_state.returned_or_thrown_value = returned_value;
2503 self.execution_state.return_or_throw_statement_pos = node.pos();
2504 self.execution_state.stop_execution_flag = true;
2505 }
2506
2507 fn interpret_throw_node(&mut self, node: &Node) {
2508 let NodeData::Throw = node.node_data() else {
2509 panic!("Invalid AST node");
2510 };
2511
2512 let thrown_node = &node.child_nodes()[0];
2513 let error_object = self.interpret_node(None, thrown_node);
2514
2515 let error_type;
2516 let error_message;
2517
2518 'skip_error: {
2519 if let Some(error_object) = &error_object &&
2520 let Some(error_value) = error_object.error_value() {
2521 let message_node = node.child_nodes().get(1);
2522 let message_object = message_node.
2523 and_then(|node| self.interpret_node(None, node));
2524
2525 error_type = error_value.err();
2526
2527 if let Some(message_object) = message_object {
2528 error_message = Some(conversions::to_text(self, &message_object, message_node.unwrap().pos()));
2529
2530 let error_message = error_message.as_deref();
2531 self.execution_state.returned_or_thrown_value = Some(DataObjectRef::new(DataObject::with_update(|data_object| {
2532 data_object.set_error(Gc::new(ErrorObject::new(error_value.err(), error_message)))
2533 }).unwrap()));
2534 }else {
2535 error_message = None;
2536
2537 self.execution_state.returned_or_thrown_value = Some(error_object.clone());
2538 }
2539
2540 break 'skip_error;
2541 }
2542
2543 error_type = InterpretingError::IncompatibleDataType;
2544 error_message = None;
2545
2546 self.execution_state.returned_or_thrown_value = Some(DataObjectRef::new(DataObject::with_update(|data_object| {
2547 data_object.set_error(Gc::new(ErrorObject::new(error_type, None)))
2548 }).unwrap()));
2549 }
2550 self.execution_state.is_thrown_value = error_type.error_code() > 0;
2551 self.execution_state.return_or_throw_statement_pos = node.pos();
2552 self.execution_state.stop_execution_flag = true;
2553
2554 if self.execution_state.is_thrown_value && self.scope_id > -1 {
2555 self.set_errno(error_type, error_message.as_deref(), self.execution_state.return_or_throw_statement_pos);
2556 }
2557
2558 if self.execution_state.is_thrown_value && self.execution_state.try_block_level > 0 &&
2559 (!self.execution_state.is_soft_try || self.execution_state.try_body_scope_id == self.scope_id) {
2560 self.execution_state.try_thrown_error = Some(error_type);
2561 self.execution_state.stop_execution_flag = true;
2562 }
2563 }
2564
2565 fn interpret_lang_data_and_execution_flags(
2566 &mut self,
2567 lang_data_execution_flag: &str,
2568 value: &DataObjectRef,
2569 pos: CodePosition,
2570 ) {
2571 match lang_data_execution_flag {
2572 "lang.version" => {
2574 let lang_ver = conversions::to_text(self, value, pos);
2575 let comp_ver = utils::compare_versions_str(Self::VERSION, &lang_ver);
2576 let Some(comp_ver) = comp_ver else {
2577 self.set_errno(
2578 InterpretingError::LangVerError,
2579 Some("lang.version has an invalid format"),
2580 pos,
2581 );
2582
2583 return;
2584 };
2585
2586 match comp_ver {
2587 Ordering::Greater => {
2588 self.set_errno(
2589 InterpretingError::LangVerWarning,
2590 Some("Lang file's version is older than this version! The Lang file could not be executed correctly"),
2591 pos,
2592 );
2593 },
2594
2595 Ordering::Less => {
2596 self.set_errno(
2597 InterpretingError::LangVerError,
2598 Some("Lang file's version is newer than this version! The Lang file will not be executed correctly!"),
2599 pos,
2600 );
2601 },
2602
2603 _ => {},
2604 }
2605 },
2606
2607 "lang.name" => {
2608 },
2610
2611 "lang.allowTermRedirect" => {
2613 let number = conversions::to_number(self, value, pos);
2614 let Some(number) = number else {
2615 self.set_errno(
2616 InterpretingError::InvalidArguments,
2617 Some("Invalid Data Type for the lang.allowTermRedirect flag!"),
2618 pos,
2619 );
2620
2621 return;
2622 };
2623
2624 self.execution_flags.allow_term_redirect = number.int_value() != 0;
2625 },
2626
2627 "lang.errorOutput" => {
2628 let number = conversions::to_number(self, value, pos);
2629 let Some(number) = number else {
2630 self.set_errno(
2631 InterpretingError::InvalidArguments,
2632 Some("Invalid Data Type for the lang.errorOutput flag!"),
2633 pos,
2634 );
2635
2636 return;
2637 };
2638
2639 self.execution_flags.error_output = ErrorOutputFlag::get_error_flag_for(number.int_value());
2640 },
2641
2642 "lang.test" => {
2643 let number = conversions::to_number(self, value, pos);
2644 let Some(number) = number else {
2645 self.set_errno(
2646 InterpretingError::InvalidArguments,
2647 Some("Invalid Data Type for the lang.test flag!"),
2648 pos,
2649 );
2650
2651 return;
2652 };
2653
2654 let lang_test_new_value = number.int_value() != 0;
2655
2656 if self.execution_flags.lang_test && !lang_test_new_value {
2657 self.set_errno(
2658 InterpretingError::InvalidArguments,
2659 Some("The lang.test flag can not be changed if it was once set to true!"),
2660 pos,
2661 );
2662
2663 return;
2664 }
2665
2666 self.execution_flags.lang_test = lang_test_new_value;
2667 },
2668
2669 "lang.rawVariableNames" => {
2670 let number = conversions::to_number(self, value, pos);
2671 let Some(number) = number else {
2672 self.set_errno(
2673 InterpretingError::InvalidArguments,
2674 Some("Invalid Data Type for the lang.rawVariableNames flag!"),
2675 pos,
2676 );
2677
2678 return;
2679 };
2680
2681 self.execution_flags.raw_variable_names = number.int_value() != 0;
2682 },
2683
2684 "lang.nativeStackTraces" => {
2685 let number = conversions::to_number(self, value, pos);
2686 let Some(number) = number else {
2687 self.set_errno(
2688 InterpretingError::InvalidArguments,
2689 Some("Invalid Data Type for the lang.nativeStackTraces flag!"),
2690 pos,
2691 );
2692
2693 return;
2694 };
2695
2696 self.execution_flags.native_stack_traces = number.int_value() != 0;
2697 },
2698
2699 _ => {
2700 self.set_errno(
2701 InterpretingError::InvalidExecFlagData,
2702 Some(&format!("\"{lang_data_execution_flag}\" is neither Lang data nor an execution flag")),
2703 pos,
2704 );
2705 }
2706 }
2707 }
2708
2709 fn interpret_assigment_node(&mut self, node: &Node) -> OptionDataObjectRef {
2710 let NodeData::Assignment = node.node_data() else {
2711 panic!("Invalid AST node");
2712 };
2713
2714 let lvalue_node = &node.child_nodes()[0];
2715 let rvalue_node = &node.child_nodes()[1];
2716
2717 let rvalue = self.interpret_node(None, rvalue_node);
2718 let rvalue = rvalue.unwrap_or_else(|| {
2719 DataObjectRef::new(DataObject::new())
2721 });
2722
2723 match lvalue_node.node_data() {
2724 NodeData::Operation(operation) |
2725 NodeData::Math(operation) |
2726 NodeData::Condition(operation) => {
2727 let mut operation_node = lvalue_node;
2729 let mut operation = operation;
2730
2731 while matches!(operation.operator(), Operator::Non | Operator::MathNon | Operator::ConditionalNon) {
2732 let left_side_operand = operation.left_side_operand().unwrap();
2733 match left_side_operand.node_data() {
2734 NodeData::Operation(left_side_operation) |
2735 NodeData::Math(left_side_operation) |
2736 NodeData::Condition(left_side_operation) => {
2737 operation_node = left_side_operand;
2738 operation = left_side_operation;
2739 },
2740
2741 _ => {},
2742 }
2743 }
2744
2745 let is_member_access_pointer_operator = matches!(operation.operator(), Operator::MemberAccessPointer);
2746 match operation.operator() {
2747 Operator::MemberAccessPointer |
2748 Operator::MemberAccess |
2749 Operator::MemberAccessThis => {
2750 let lvalue = self.interpret_operation_node(operation_node);
2751 let Some(lvalue) = lvalue else {
2752 return Some(self.set_errno_error_object(
2753 InterpretingError::InvalidAstNode,
2754 Some(&format!(
2755 "Invalid arguments for member access{}",
2756 if is_member_access_pointer_operator {
2757 " pointer"
2758 }else {
2759 ""
2760 }
2761 )),
2762 node.pos(),
2763 ));
2764 };
2765
2766 let mut lvalue = lvalue.borrow_mut();
2767 if lvalue.variable_name().is_none() {
2768 return Some(self.set_errno_error_object(
2769 InterpretingError::InvalidAssignment,
2770 Some("Anonymous values can not be changed"),
2771 node.pos(),
2772 ));
2773 }
2774
2775 if lvalue.is_final_data() || lvalue.is_lang_var() {
2776 return Some(self.set_errno_error_object(
2777 InterpretingError::FinalVarChange,
2778 None,
2779 node.pos(),
2780 ));
2781 }
2782
2783 let ret = lvalue.set_data(&rvalue.borrow());
2784 if ret.is_err() {
2785 return Some(self.set_errno_error_object(
2786 InterpretingError::IncompatibleDataType,
2787 Some("Incompatible type for rvalue in assignment"),
2788 node.pos(),
2789 ));
2790 }
2791
2792 return Some(rvalue);
2793 },
2794
2795 Operator::GetItem => {
2796 let composite_type_object = self.interpret_node(None, operation.left_side_operand().unwrap());
2797 let Some(composite_type_object) = composite_type_object else {
2798 return Some(self.set_errno_error_object(
2799 InterpretingError::InvalidAstNode,
2800 Some("Missing composite type operand for set item"),
2801 node.pos(),
2802 ));
2803 };
2804
2805 let index_object = self.interpret_node(None, operation.right_side_operand().unwrap());
2806 let Some(index_object) = index_object else {
2807 return Some(self.set_errno_error_object(
2808 InterpretingError::InvalidAstNode,
2809 Some("Missing index operand for set item"),
2810 node.pos(),
2811 ));
2812 };
2813
2814 let ret = operators::op_set_item(
2815 self,
2816 &composite_type_object,
2817 &index_object,
2818 &rvalue,
2819 operation_node.pos(),
2820 );
2821 if ret.is_none() {
2822 return Some(self.set_errno_error_object(
2823 InterpretingError::IncompatibleDataType,
2824 Some("Incompatible type for lvalue (composite type + index) or rvalue in assignment"),
2825 node.pos(),
2826 ));
2827 }
2828
2829 return Some(rvalue);
2830 },
2831
2832 _ => {},
2833 }
2834
2835 },
2837
2838 NodeData::UnprocessedVariableName(variable_name) => {
2839 let mut variable_name = variable_name.to_string();
2840
2841 let is_module_variable = variable_name.starts_with("[[");
2842 let module_name = if is_module_variable {
2843 let index_module_identifier_end = variable_name.find("]]::");
2844 let Some(index_module_identifier_end) = index_module_identifier_end else {
2845 return Some(self.set_errno_error_object(
2846 InterpretingError::InvalidAstNode,
2847 Some("Invalid variable name"),
2848 node.pos(),
2849 ));
2850 };
2851
2852 let module_name = variable_name[2..index_module_identifier_end].to_string();
2853 if !Self::is_alpha_numeric_with_underline(&module_name) {
2854 return Some(self.set_errno_error_object(
2855 InterpretingError::InvalidAstNode,
2856 Some("Invalid module name"),
2857 node.pos(),
2858 ));
2859 }
2860
2861 variable_name = variable_name[index_module_identifier_end + 4..].to_string();
2862
2863 Some(module_name)
2864 }else {
2865 None
2866 };
2867
2868 if Self::is_var_name_full_without_prefix(&variable_name) {
2869 let mut flags = [false, false];
2870 let lvalue = self.get_or_create_data_object_from_variable_name(
2871 None,
2872 module_name.as_deref(),
2873 &variable_name,
2874 false,
2875 true,
2876 true,
2877 &mut flags,
2878 node.pos(),
2879 );
2880
2881 if flags[0] {
2882 return lvalue;
2884 }
2885
2886 let lvalue = lvalue.unwrap();
2887
2888 let is_same_reference = ptr::eq(lvalue.deref(), rvalue.deref());
2889
2890 let mut lvalue = lvalue.borrow_mut();
2891
2892 let variable_name = lvalue.variable_name();
2893 let Some(variable_name) = variable_name else {
2894 drop(lvalue);
2895 return Some(self.set_errno_error_object(
2896 InterpretingError::InvalidAssignment,
2897 Some("Anonymous values can not be changed"),
2898 node.pos(),
2899 ));
2900 };
2901 let variable_name = Rc::from(variable_name);
2902
2903 if lvalue.is_final_data() || lvalue.is_lang_var() {
2904 if flags[1] {
2905 self.data_mut().var.remove(&variable_name);
2906 }
2907
2908 drop(lvalue);
2909 return Some(self.set_errno_error_object(
2910 InterpretingError::FinalVarChange,
2911 None,
2912 node.pos(),
2913 ));
2914 }
2915
2916 if !is_same_reference {
2918 let ret = lvalue.set_data(&rvalue.borrow());
2919 if ret.is_err() {
2920 if flags[1] {
2921 self.data_mut().var.remove(&variable_name);
2922 }
2923
2924 drop(lvalue);
2925 return Some(self.set_errno_error_object(
2926 InterpretingError::IncompatibleDataType,
2927 Some("Incompatible type for rvalue in assignment"),
2928 node.pos(),
2929 ));
2930 }
2931 }
2932
2933 drop(lvalue);
2934
2935 if let Some(func_name) = variable_name.strip_prefix("fp.")
2936 && self.funcs.iter().any(|(key, _)| *func_name == **key) {
2937 self.set_errno(
2938 InterpretingError::VarShadowingWarning,
2939 Some(&format!("\"{variable_name}\" shadows a predefined or linker function")),
2940 node.pos(),
2941 );
2942 }
2943
2944 return Some(rvalue);
2945 }
2946
2947 },
2949
2950 NodeData::ArgumentSeparator(..) => {
2951 return Some(self.set_errno_error_object(
2952 InterpretingError::InvalidAstNode,
2953 Some("Neither lvalue nor translationKey"),
2954 node.pos(),
2955 ));
2956 },
2957
2958 _ => {},
2959 };
2960
2961 let translation_key = self.interpret_node(None, lvalue_node);
2963 let Some(translation_key) = translation_key else {
2964 return Some(self.set_errno_error_object(
2965 InterpretingError::InvalidAstNode,
2966 Some("Invalid translationKey"),
2967 node.pos(),
2968 ));
2969 };
2970
2971 let translation_key = conversions::to_text(self, &translation_key, node.pos());
2972 if translation_key.starts_with("lang.") {
2973 self.interpret_lang_data_and_execution_flags(&translation_key, &rvalue, node.pos());
2974 }
2975
2976 let translation_value = conversions::to_text(self, &rvalue, node.pos());
2977
2978 self.data_mut().lang.insert(Rc::from(translation_key), Rc::from(translation_value));
2979
2980 Some(rvalue)
2981 }
2982
2983 #[expect(clippy::too_many_arguments)]
2990 fn get_or_create_data_object_from_variable_name(
2991 &mut self,
2992 composite_type: OptionDataObjectRef,
2993 module_name: Option<&str>,
2994 variable_name: &str,
2995 supports_pointer_referencing: bool,
2996 supports_pointer_dereferencing: bool,
2997 should_create_data_object: bool,
2998 flags: &mut [bool; 2],
2999 pos: CodePosition,
3000 ) -> OptionDataObjectRef {
3001 let ret = if let Some(composite_type) = &composite_type {
3002 match composite_type.data_type() {
3003 DataType::ERROR => {
3004 let error_value = composite_type.error_value().unwrap();
3005
3006 match variable_name {
3007 "$text" => Some(DataObjectRef::new(DataObject::with_update_final(|data_object| {
3008 data_object.
3009 set_text(error_value.err().error_text())?.
3010 set_variable_name(Some("$text"))?.
3011 set_type_constraint(Box::new(DataTypeConstraint::from_single_allowed_type(
3012 DataType::TEXT,
3013 )))
3014 }).unwrap())),
3015
3016 "$code" => Some(DataObjectRef::new(DataObject::with_update_final(|data_object| {
3017 data_object.
3018 set_int(error_value.err().error_code())?.
3019 set_variable_name(Some("$code"))?.
3020 set_type_constraint(Box::new(DataTypeConstraint::from_single_allowed_type(
3021 DataType::INT,
3022 )))
3023 }).unwrap())),
3024
3025 "$message" => Some(DataObjectRef::new(DataObject::with_update_final(|data_object| {
3026 if let Some(message) = error_value.message() {
3027 data_object.set_text(message)?;
3028 }
3029
3030 data_object.
3031 set_variable_name(Some("$message"))?.
3032 set_type_constraint(Box::new(DataTypeConstraint::from_allowed_types(&[
3033 DataType::NULL, DataType::TEXT,
3034 ])))
3035 }).unwrap())),
3036
3037 _ => None,
3038 }
3039 },
3040
3041 DataType::STRUCT => {
3042 let struct_value = composite_type.struct_value().unwrap();
3043
3044 let mut ret = None;
3045 for member_name in struct_value.member_names() {
3046 let member = struct_value.get_member(&member_name);
3047
3048 let member = match member {
3049 Ok(member) => member,
3050
3051 Err(e) => {
3052 flags[0] = true;
3053
3054 return Some(self.set_errno_error_object(
3055 InterpretingError::IncompatibleDataType,
3056 Some(e.message()),
3057 pos,
3058 ));
3059 },
3060 };
3061
3062 if *member_name == *variable_name {
3063 ret = Some(member);
3064 break;
3065 }
3066 }
3067
3068 ret
3069 },
3070
3071 DataType::OBJECT => {
3072 let object_value = composite_type.object_value().unwrap();
3073
3074 if variable_name.starts_with("mp.") || variable_name.starts_with("op:") || variable_name.starts_with("to:") {
3075 object_value.borrow().methods().iter().
3076 find(|(function_name, _)| ***function_name == *variable_name).
3077 map(|(function_name, functions)| {
3078 DataObjectRef::new(DataObject::with_update_final(|data_object| {
3079 data_object.
3080 set_function_pointer(Gc::new(
3081 functions.copy_with_function_name(function_name),
3082 ))?.
3083 set_variable_name(Some(function_name))
3084 }).unwrap())
3085 })
3086 }else {
3087 let mut ret = None;
3088
3089 for static_member in object_value.borrow().static_members() {
3090 let member_name = static_member.variable_name().unwrap();
3091
3092 if *member_name == *variable_name {
3093 ret = Some(static_member.clone());
3094 break;
3095 }
3096 }
3097
3098 if ret.is_none()
3099 && let Some(members) = object_value.borrow().members() {
3100 for member in members {
3102 let member_name = member.variable_name().unwrap();
3103
3104 if *member_name == *variable_name {
3105 ret = Some(member.clone());
3106 break;
3107 }
3108 }
3109 }
3110
3111 ret
3112 }
3113 },
3114
3115 _ => {
3116 flags[0] = true;
3117
3118 return Some(self.set_errno_error_object(
3119 InterpretingError::InvalidArguments,
3120 Some("Invalid composite type"),
3121 pos,
3122 ));
3123 },
3124 }
3125 }else if let Some(module_name) = module_name {
3126 let module = self.modules.get(module_name);
3127
3128 let Some(module) = module else {
3129 flags[0] = true;
3130
3131 return Some(self.set_errno_error_object(
3132 InterpretingError::ModuleLoadUnloadErr,
3133 Some(&format!("The module \"{module_name}\" is not loaded!")),
3134 pos,
3135 ));
3136 };
3137
3138 module.exported_variables().borrow().get(variable_name).cloned()
3139 }else {
3140 self.data_ref().var.get(variable_name).cloned()
3141 };
3142
3143 if let Some(ret) = ret {
3144 if !ret.is_accessible(self.current_call_stack_element.lang_class()) {
3145 flags[0] = true;
3146
3147 return Some(self.set_errno_error_object(
3148 InterpretingError::MemberNotAccessible,
3149 Some(&format!("For member \"{variable_name}\"")),
3150 pos,
3151 ));
3152 }
3153
3154 return Some(ret);
3155 }
3156
3157 if supports_pointer_dereferencing
3158 && let Some(index) = variable_name.find("*") {
3159 let referenced_variable_name = variable_name[..index].to_string() +
3160 &variable_name[index + 1..];
3161 let referenced_variable = self.get_or_create_data_object_from_variable_name(
3162 composite_type,
3163 module_name,
3164 &referenced_variable_name,
3165 supports_pointer_referencing,
3166 true,
3167 false,
3168 flags,
3169 pos,
3170 );
3171
3172 let Some(referenced_variable) = referenced_variable else {
3173 flags[0] = true;
3174
3175 return Some(self.set_errno_error_object(
3176 InterpretingError::InvalidPtr,
3177 None,
3178 pos,
3179 ));
3180 };
3181
3182 if let Some(var_pointer_value) = referenced_variable.var_pointer_value() {
3183 return Some(var_pointer_value);
3184 };
3185
3186 return Some(DataObjectRef::new(DataObject::new()));
3188 }
3189
3190 if supports_pointer_referencing && variable_name.contains("]")
3191 && let Some(index_opening_bracket) = variable_name.find("[") {
3192 let index_matching_bracket = utils::get_index_of_matching_bracket_str(
3193 variable_name,
3194 index_opening_bracket,
3195 usize::MAX, b'[', b']',
3196 );
3197
3198 let index_matching_bracket = index_matching_bracket.unwrap_or(0);
3200 if index_matching_bracket != variable_name.len() - 1 {
3201 flags[0] = true;
3202
3203 return Some(self.set_errno_error_object(
3204 InterpretingError::InvalidAstNode,
3205 Some("Non matching referencing brackets"),
3206 pos,
3207 ));
3208 }
3209
3210 let dereferenced_variable_name = variable_name[..index_opening_bracket].to_string() +
3211 &variable_name[index_opening_bracket + 1..index_matching_bracket];
3212 let dereferenced_variable = self.get_or_create_data_object_from_variable_name(
3213 composite_type,
3214 module_name,
3215 &dereferenced_variable_name,
3216 true,
3217 false,
3218 false,
3219 flags,
3220 pos,
3221 );
3222
3223 if let Some(dereferenced_variable) = dereferenced_variable {
3224 return Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3225 data_object.set_var_pointer(dereferenced_variable)
3226 }).unwrap()));
3227 };
3228
3229 return if should_create_data_object {
3230 flags[0] = true;
3231
3232 Some(self.set_errno_error_object(
3233 InterpretingError::InvalidPtr,
3234 Some("Pointer redirection is not supported"),
3235 pos,
3236 ))
3237 }else {
3238 None
3239 };
3240 }
3241
3242 if !should_create_data_object {
3243 return None;
3244 }
3245
3246 if composite_type.is_some() || module_name.is_some() ||
3248 Self::is_lang_var_or_lang_var_pointer_redirection_without_prefix(variable_name) {
3249 flags[0] = true;
3250
3251 return Some(self.set_errno_error_object(
3252 InterpretingError::FinalVarChange,
3253 if composite_type.is_some() {
3254 Some("Composite type members can not be created")
3255 }else if module_name.is_some() {
3256 Some("Module variables can not be created")
3257 }else {
3258 None
3259 },
3260 pos,
3261 ));
3262 }
3263
3264 flags[1] = true;
3265
3266 let data_object = DataObjectRef::new(DataObject::with_update(|data_object| {
3267 data_object.set_variable_name(Some(variable_name))
3268 }).unwrap());
3269
3270 self.data_mut().var.insert(Rc::from(variable_name), data_object.clone());
3271
3272 Some(data_object)
3273 }
3274 fn interpret_variable_name_node(&mut self, composite_type: OptionDataObjectRef, node: &Node) -> OptionDataObjectRef {
3278 let NodeData::VariableName {
3279 variable_name, ..
3280 } = node.node_data() else {
3281 panic!("Invalid AST node");
3282 };
3283
3284 let variable_name_orig = variable_name;
3285 let mut variable_name = variable_name_orig.to_string();
3286
3287 let is_module_variable = composite_type.is_none() && variable_name.starts_with("[[");
3288 let module_name = if is_module_variable {
3289 let index_module_identifier_end = variable_name.find("]]::");
3290 let Some(index_module_identifier_end) = index_module_identifier_end else {
3291 return Some(self.set_errno_error_object(
3292 InterpretingError::InvalidAstNode,
3293 Some("Invalid variable name"),
3294 node.pos(),
3295 ));
3296 };
3297
3298 let module_name = variable_name[2..index_module_identifier_end].to_string();
3299 if !Self::is_alpha_numeric_with_underline(&module_name) {
3300 return Some(self.set_errno_error_object(
3301 InterpretingError::InvalidAstNode,
3302 Some("Invalid module name"),
3303 node.pos(),
3304 ));
3305 }
3306
3307 variable_name = variable_name[index_module_identifier_end + 4..].to_string();
3308
3309 Some(module_name)
3310 }else {
3311 None
3312 };
3313
3314 if !Self::is_var_name_full_with_funcs_without_prefix(&variable_name) &&
3315 !Self::is_var_name_ptr_and_dereference_without_prefix(&variable_name) &&
3316 !Self::is_operator_method_name(&variable_name) &&
3317 !Self::is_conversion_method_name(&variable_name) {
3318 return Some(self.set_errno_error_object(
3319 InterpretingError::InvalidAstNode,
3320 Some("Invalid variable name"),
3321 node.pos(),
3322 ));
3323 }
3324
3325 if let Some(composite_type) = &composite_type
3326 && let Some(object_value) = composite_type.object_value()
3327 && (variable_name.starts_with("mp.") || variable_name.starts_with("op:") || variable_name.starts_with("to:")) &&
3328 !object_value.borrow().is_class() {
3329 return self.get_or_create_data_object_from_variable_name(
3330 Some(composite_type.clone()),
3331 module_name.as_deref(),
3332 &variable_name,
3333 false,
3334 false,
3335 false,
3336 &mut [false, false],
3337 node.pos(),
3338 );
3339 }
3340
3341 if variable_name.starts_with("$") || variable_name.starts_with("&") || variable_name.starts_with("fp.") {
3342 return self.get_or_create_data_object_from_variable_name(
3343 composite_type,
3344 module_name.as_deref(),
3345 &variable_name,
3346 variable_name.starts_with("$"),
3347 variable_name.starts_with("$"),
3348 true,
3349 &mut [false, false],
3350 node.pos(),
3351 );
3352 }
3353
3354 if composite_type.is_some() {
3355 return Some(self.set_errno_error_object(
3356 InterpretingError::InvalidAstNode,
3357 Some(&format!(
3358 "Invalid composite type member name: \"{variable_name}\""
3359 )),
3360 node.pos(),
3361 ));
3362 }
3363
3364 let is_linker_function;
3365 if !is_module_variable && variable_name.starts_with("func.") {
3366 is_linker_function = false;
3367
3368 variable_name = variable_name[5..].to_string();
3369 }else if !is_module_variable && variable_name.starts_with("fn.") {
3370 is_linker_function = false;
3371
3372 variable_name = variable_name[3..].to_string();
3373 }else if !is_module_variable && variable_name.starts_with("linker.") {
3374 is_linker_function = true;
3375
3376 variable_name = variable_name[7..].to_string();
3377 }else if !is_module_variable && variable_name.starts_with("ln.") {
3378 is_linker_function = true;
3379
3380 variable_name = variable_name[3..].to_string();
3381 }else {
3382 return Some(self.set_errno_error_object(
3383 InterpretingError::InvalidAstNode,
3384 Some("Invalid variable name"),
3385 node.pos(),
3386 ));
3387 }
3388
3389 let ret = self.funcs.iter().find(|(func_name, func)| {
3390 func.linker_function() == is_linker_function && *variable_name == ***func_name
3391 });
3392
3393 let Some(ret) = ret else {
3394 return Some(self.set_errno_error_object(
3395 InterpretingError::FunctionNotFound,
3396 Some(&format!("\"{variable_name}\" was not found")),
3397 node.pos(),
3398 ));
3399 };
3400
3401 let func = ret.1;
3402
3403 Some(DataObjectRef::new(DataObject::with_update_final(|data_object| {
3404 data_object.
3405 set_function_pointer(Gc::new(
3406 func.copy_with_function_name(variable_name_orig),
3407 ))?.
3408 set_variable_name(Some(variable_name_orig))
3409 }).unwrap()))
3410 }
3411
3412 fn interpret_escape_sequence_node(&mut self, node: &Node) -> OptionDataObjectRef {
3416 let NodeData::EscapeSequence(char) = node.node_data() else {
3417 panic!("Invalid AST node");
3418 };
3419
3420 match char {
3421 '0' => Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3422 data_object.set_char('\0')
3423 }).unwrap())),
3424 'n' => Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3425 data_object.set_char('\n')
3426 }).unwrap())),
3427 'r' => Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3428 data_object.set_char('\r')
3429 }).unwrap())),
3430 'f' => Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3431 data_object.set_char('\u{000C}')
3432 }).unwrap())),
3433 's' => Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3434 data_object.set_char(' ')
3435 }).unwrap())),
3436 'e' => Some(DataObjectRef::new(DataObject::new_text(""))),
3437 'E' => Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3438 data_object.set_char('\u{001B}')
3439 }).unwrap())),
3440 'b' => Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3441 data_object.set_char('\u{0008}')
3442 }).unwrap())),
3443 't' => Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3444 data_object.set_char('\t')
3445 }).unwrap())),
3446
3447 '$' | '&' | '#' | ',' | '.' | '(' | ')' | '[' | ']' | '{' | '}' | '=' | '<' | '>' |
3448 '+' | '-' | '/' | '*' | '%' | '|' | '~' | '^' | '?' | ':' | '@' | '\u{25b2}' |
3449 '\u{25bc}' | '\"' | '\\' => Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3450 data_object.set_char(*char)
3451 }).unwrap())),
3452
3453 '!' => None,
3454
3455 _ => {
3457 self.set_errno(InterpretingError::UndefEscapeSequence, Some(&format!("\"\\{char}\" was used")), node.pos());
3458
3459 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
3460 data_object.set_char(*char)
3461 }).unwrap()))
3462 },
3463 }
3464 }
3465
3466 fn interpret_unicode_escape_sequence_node(&mut self, node: &Node) -> DataObjectRef {
3467 let NodeData::UnicodeEscapeSequence(hex_code_point) = node.node_data() else {
3468 panic!("Invalid AST node");
3469 };
3470
3471 for c in hex_code_point.bytes() {
3472 if !c.is_ascii_alphanumeric() {
3473 return self.set_errno_error_object(
3474 InterpretingError::InvalidAstNode,
3475 Some(&format!(
3476 "Invalid unicode escape sequence: \"\\u{{{hex_code_point}}}\"",
3477 )),
3478 node.pos(),
3479 );
3480 }
3481 }
3482
3483 let code_point = u32::from_str_radix(&hex_code_point.to_ascii_uppercase(), 16);
3484 let char = code_point.ok().and_then(char::from_u32).unwrap_or('\u{FFFD}');
3485
3486 DataObjectRef::new(DataObject::with_update(|data_object| {
3487 data_object.set_char(char)
3488 }).unwrap())
3489 }
3490
3491 fn interpret_argument_separator_node(&mut self, node: &Node) -> DataObjectRef {
3492 let NodeData::ArgumentSeparator(original_text) = node.node_data() else {
3493 panic!("Invalid AST node");
3494 };
3495
3496 DataObjectRef::new(DataObject::with_update(|data_object| {
3497 data_object.set_argument_separator(original_text)
3498 }).unwrap())
3499 }
3500
3501 fn get_and_reset_return_value(&mut self) -> OptionDataObjectRef {
3502 let ret_tmp = self.execution_state.returned_or_thrown_value.take();
3503
3504 if self.execution_flags.lang_test && self.scope_id == self.lang_test_expected_return_value_scope_id {
3505 if let Some(lang_test_expected_throw_value) = self.lang_test_expected_throw_value.take() {
3506 let error = ret_tmp.as_ref().
3507 and_then(|ret_tmp| self.execution_state.is_thrown_value.then(|| {
3508 ret_tmp.error_value().map(|error_value| error_value.err())
3509 })).flatten();
3510
3511 self.lang_test_store.add_assert_result(AssertResult::new_throw_result(
3512 error.is_some_and(|error| error == lang_test_expected_throw_value),
3513 Some(&self.print_stack_trace(CodePosition::EMPTY)),
3514 self.lang_test_message_for_last_test_result.take().as_deref(),
3515 error,
3516 lang_test_expected_throw_value,
3517 ));
3518 }
3519
3520 if let Some(lang_test_expected_return_value) = self.lang_test_expected_return_value.take() {
3521 let assert_result = AssertResult::new_return_result(
3522 !self.execution_state.is_thrown_value && ret_tmp.as_ref().is_some_and(
3523 |ret_tmp| operators::is_strict_equals(
3524 self,
3525 &lang_test_expected_return_value,
3526 ret_tmp,
3527 CodePosition::EMPTY,
3528 ),
3529 ),
3530 Some(&self.print_stack_trace(CodePosition::EMPTY)),
3531 self.lang_test_message_for_last_test_result.take().as_deref(),
3532 ret_tmp.as_ref().map(|ret_tmp| {
3533 (ret_tmp, conversions::to_text(self, ret_tmp, CodePosition::EMPTY))
3534 }),
3535 lang_test_expected_return_value.borrow().deref(),
3536 &conversions::to_text(self, &lang_test_expected_return_value, CodePosition::EMPTY),
3537 );
3538
3539 self.lang_test_store.add_assert_result(assert_result);
3540 }
3541
3542 if self.lang_test_expected_no_return_value {
3543 let assert_result = AssertResult::new_no_return_result(
3544 ret_tmp.is_none(),
3545 Some(&self.print_stack_trace(CodePosition::EMPTY)),
3546 self.lang_test_message_for_last_test_result.take().as_deref(),
3547 ret_tmp.as_ref().map(|ret_tmp| {
3548 (ret_tmp, conversions::to_text(self, ret_tmp, CodePosition::EMPTY))
3549 }),
3550 );
3551
3552 self.lang_test_store.add_assert_result(assert_result);
3553
3554 self.lang_test_expected_no_return_value = false;
3555 }
3556
3557 self.lang_test_message_for_last_test_result = None;
3558 self.lang_test_expected_return_value_scope_id = 0;
3559 }
3560
3561 self.execution_state.is_thrown_value = false;
3562
3563 if self.execution_state.try_thrown_error.is_none() || self.execution_state.try_block_level == 0 ||
3564 (self.execution_state.is_soft_try && self.execution_state.try_body_scope_id != self.scope_id) {
3565 self.execution_state.stop_execution_flag = false;
3566 }
3567
3568 ret_tmp.map(|ret_tmp| {
3569 DataObjectRef::new(DataObject::with_update(|data_object| {
3570 data_object.set_data(&ret_tmp.borrow())
3571 }).unwrap())
3572 })
3573 }
3574 fn is_thrown_value(&self) -> bool {
3575 self.execution_state.is_thrown_value || (self.execution_state.try_thrown_error.is_some() &&
3576 self.execution_state.try_block_level > 0 && (!self.execution_state.is_soft_try ||
3577 self.execution_state.try_body_scope_id == self.scope_id))
3578 }
3579
3580 #[expect(clippy::too_many_arguments)]
3581 #[inline(always)]
3582 fn call_function_pointer_internal(
3583 &mut self,
3584 fp: &FunctionPointerObject,
3585 this_object: Option<&LangObjectRef>,
3586 function_name: &str,
3587 internal_function: &InternalFunction,
3588 argument_list: &[DataObjectRef],
3589 mut combined_argument_list: Vec<DataObjectRef>,
3590 parent_pos: CodePosition,
3591 ) -> OptionDataObjectRef {
3592 let function = internal_function.function();
3593 match function.function() {
3594 FunctionData::Normal(normal_function) => {
3595 let parameter_list = function.parameter_list();
3596 let argument_pos_list = normal_function.argument_pos_list();
3597 let arg_count = parameter_list.len();
3598
3599 if function.combinator_function_call_count().is_some() {
3600 let combined_argument_list_orig = combined_argument_list;
3601
3602 let combinator_function_provided_arguments = function.combinator_function_provided_arguments();
3603
3604 combined_argument_list = Vec::with_capacity(combined_argument_list_orig.len() + combinator_function_provided_arguments.len());
3605 combined_argument_list.append(&mut Vec::from(combinator_function_provided_arguments));
3606
3607 combined_argument_list_orig.iter().for_each(|argument| {
3608 combined_argument_list.push(DataObjectRef::new(DataObject::with_update(|data_object| {
3609 data_object.set_data(&argument.borrow())
3610 }).unwrap()));
3611 });
3612 }
3613
3614 let function_body = normal_function.function_body();
3615
3616 if function.var_args_parameter().is_none() {
3617 if function.combinator_function_call_count().is_none() && combined_argument_list.len() < arg_count {
3618 return Some(self.set_errno_error_object(
3619 InterpretingError::InvalidArgCount,
3620 Some(&format!("Not enough arguments ({arg_count} needed)")),
3621 parent_pos,
3622 ));
3623 }
3624
3625 if combined_argument_list.len() > arg_count {
3626 return Some(self.set_errno_error_object(
3627 InterpretingError::InvalidArgCount,
3628 Some(&format!("Too many arguments ({arg_count} needed)")),
3629 parent_pos,
3630 ));
3631 }
3632 }else {
3633 if function.combinator_function_call_count().is_none_or(|call_count| call_count > 0) && combined_argument_list.len() < arg_count - 1 {
3635 return Some(self.set_errno_error_object(
3636 InterpretingError::InvalidArgCount,
3637 Some(&format!("Not enough arguments (at least {} needed)", arg_count - 1)),
3638 parent_pos,
3639 ));
3640 }
3641 }
3642
3643 let mut combinator_function_call_ret = None;
3644 let ret = 'early_ret: {
3645 let caller_data = self.data_ref().var.clone();
3646
3647 self.enter_scope(None);
3648
3649 for (key, val) in caller_data {
3651 if val.is_static_data() {
3652 self.data_mut().var.insert(key, val);
3654 }else if !val.is_lang_var() {
3655 self.data_mut().var.insert(key, DataObjectRef::new(DataObject::with_update(|data_object| {
3657 data_object.set_data(&val.borrow())?.
3658 set_variable_name(val.borrow().variable_name())
3659 }).unwrap()));
3660 }
3661 }
3662
3663 if let Some(this_object) = this_object {
3665 let old = self.data_mut().var.insert(Rc::from("&this"), DataObjectRef::new(DataObject::with_update_final(|data_object| {
3666 data_object.set_object(this_object.clone())?.
3667 set_variable_name(Some("&this"))
3668 }).unwrap()));
3669 if old.is_some_and(|old| old.is_static_data()) {
3670 self.set_errno(
3671 InterpretingError::VarShadowingWarning,
3672 Some("This-object \"&this\" shadows a static variable"),
3673 function_body.get_pos(),
3674 );
3675 }
3676
3677 let old = self.data_mut().var.insert(Rc::from("&This"), DataObjectRef::new(DataObject::with_update_final(|data_object| {
3678 data_object.set_object(this_object.borrow().base_definition().unwrap())?.
3679 set_variable_name(Some("&This"))
3680 }).unwrap()));
3681 if old.is_some_and(|old| old.is_static_data()) {
3682 self.set_errno(
3683 InterpretingError::VarShadowingWarning,
3684 Some("This-class \"&This\" shadows a static variable"),
3685 function_body.get_pos(),
3686 );
3687 }
3688 }
3689
3690 let mut argument_index = 0;
3692 for i in 0..arg_count {
3693 if let Some(call_count) = function.combinator_function_call_count()
3694 && argument_index >= combined_argument_list.len() &&
3695 (function.var_args_parameter().is_none() || call_count == 0) {
3696 combinator_function_call_ret = Some(function.combinator_call(
3697 this_object.map(|this_object| (this_object.clone(), internal_function.super_level().unwrap())),
3698 combined_argument_list,
3699 ));
3700
3701 break;
3702 }
3703
3704 let parameter = ¶meter_list[i];
3705 let argument_pos = argument_pos_list[i];
3706
3707 match parameter.parameter_type() {
3708 ParameterType::VarArgs => {
3709 if function.combinator_function_call_count().is_some_and(|call_count| call_count == 0) {
3711 combinator_function_call_ret = Some(function.combinator_call(
3712 this_object.map(|this_object| (this_object.clone(), internal_function.super_level().unwrap())),
3713 combined_argument_list,
3714 ));
3715
3716 break;
3717 }
3718
3719 if parameter.parameter_name().starts_with("$") {
3720 if *parameter.type_constraint() != *data::CONSTRAINT_NORMAL {
3722 break 'early_ret Some(Some(self.set_errno_error_object(
3723 InterpretingError::InvalidAstNode,
3724 Some(&format!(
3725 "function parameter \"{}\": Text var args argument must not have a type constraint definition",
3726 parameter.parameter_name(),
3727 )),
3728 argument_pos,
3729 )));
3730 }
3731
3732 let mut argument_list_copy = VecDeque::from_iter(argument_list.iter().cloned());
3733
3734 for _ in 0..i {
3736 for _ in 0..argument_list_copy.len() {
3737 if argument_list_copy.pop_front().
3738 is_some_and(|val| val.
3739 data_type() == DataType::ARGUMENT_SEPARATOR) {
3740 break;
3741 }
3742 }
3743 }
3744
3745 for _ in 0..arg_count - i - 1 {
3747 for k in (0..argument_list_copy.len()).rev() {
3748 if argument_list_copy.remove(k).
3749 is_some_and(|val| val.
3750 data_type() == DataType::ARGUMENT_SEPARATOR) {
3751 break;
3752 }
3753 }
3754 }
3755
3756 let data_object = utils::combine_data_objects(
3757 argument_list_copy.make_contiguous(),
3758 self,
3759 CodePosition::EMPTY,
3760 );
3761
3762 let text = data_object.map(|arg| conversions::to_text(
3763 self,
3764 &arg,
3765 CodePosition::EMPTY,
3766 )).unwrap_or_default();
3767
3768 let new_data_object = DataObject::with_update(|data_object| {
3769 data_object.set_text(text)?.
3770 set_variable_name(Some(parameter.parameter_name()))
3771 });
3772 let new_data_object = match new_data_object {
3773 Ok(new_data_object) => new_data_object,
3774 Err(e) => {
3775 break 'early_ret Some(Some(self.set_errno_error_object(
3776 InterpretingError::InvalidAstNode,
3777 Some(&format!(
3778 "Invalid argument value for function parameter \"{}\" ({})",
3779 parameter.parameter_name(),
3780 e.message(),
3781 )),
3782 argument_pos,
3783 )));
3784 },
3785 };
3786
3787 let old = self.data_mut().var.insert(
3788 Rc::from(parameter.parameter_name()),
3789 DataObjectRef::new(new_data_object),
3790 );
3791 if old.is_some_and(|old| old.is_static_data()) {
3792 self.set_errno(
3793 InterpretingError::VarShadowingWarning,
3794 Some(&format!(
3795 "Parameter \"{}\" shadows a static variable",
3796 parameter.parameter_name(),
3797 )),
3798 function_body.get_pos(),
3799 );
3800 }
3801 }else {
3802 let var_args_argument_list = combined_argument_list[i..combined_argument_list.len() + i + 1 - arg_count].iter().
3804 map(|data_object| DataObjectRef::new(DataObject::with_update(|new_data_object|
3805 new_data_object.set_data(&data_object.borrow())
3806 ).unwrap())).collect::<Vec<_>>();
3807
3808 for (j, argument) in var_args_argument_list.iter().
3809 enumerate() {
3810 if !parameter.type_constraint().is_type_allowed(argument.data_type()) {
3811 break 'early_ret Some(Some(self.set_errno_error_object(
3812 InterpretingError::IncompatibleDataType,
3813 Some(&format!(
3814 "Invalid argument (Argument {}) value for var args function parameter \"{}\": Value must be one of [{}]",
3815 argument_index + j + 1,
3816 parameter.parameter_name(),
3817 parameter.type_constraint().allowed_types().iter().
3818 map(|data_type| data_type.to_string()).
3819 collect::<Vec<_>>().
3820 join(", "),
3821 )),
3822 argument_pos,
3823 )));
3824 }
3825 }
3826
3827 let new_data_object = DataObject::with_update(|data_object| {
3828 data_object.set_array(var_args_argument_list.into_boxed_slice())?.
3829 set_variable_name(Some(parameter.parameter_name()))
3830 });
3831 let new_data_object = match new_data_object {
3832 Ok(new_data_object) => new_data_object,
3833 Err(e) => {
3834 break 'early_ret Some(Some(self.set_errno_error_object(
3835 InterpretingError::InvalidAstNode,
3836 Some(&format!(
3837 "Invalid argument value for function parameter \"{}\" ({})",
3838 parameter.parameter_name(),
3839 e.message(),
3840 )),
3841 argument_pos,
3842 )));
3843 },
3844 };
3845
3846 let old = self.data_mut().var.insert(
3847 Rc::from(parameter.parameter_name()),
3848 DataObjectRef::new(new_data_object),
3849 );
3850 if old.is_some_and(|old| old.is_static_data()) {
3851 self.set_errno(
3852 InterpretingError::VarShadowingWarning,
3853 Some(&format!(
3854 "Parameter \"{}\" shadows a static variable",
3855 parameter.parameter_name(),
3856 )),
3857 function_body.get_pos(),
3858 );
3859 }
3860 }
3861
3862 argument_index = combined_argument_list.len() + i + 1 - arg_count;
3863 continue;
3864 },
3865
3866 ParameterType::CallByPointer => {
3867 let new_data_object = DataObject::with_update(|data_object| {
3868 data_object.set_var_pointer(combined_argument_list[argument_index].clone())?.
3869 set_variable_name(Some(parameter.parameter_name()))?.
3870 set_type_constraint(Box::new(parameter.type_constraint().clone()))
3871 });
3872 let new_data_object = match new_data_object {
3873 Ok(new_data_object) => new_data_object,
3874 Err(e) => {
3875 break 'early_ret Some(Some(self.set_errno_error_object(
3876 InterpretingError::InvalidAstNode,
3877 Some(&format!(
3878 "Invalid argument value for function parameter \"{}\" ({})",
3879 parameter.parameter_name(),
3880 e.message(),
3881 )),
3882 argument_pos,
3883 )));
3884 },
3885 };
3886
3887 let old = self.data_mut().var.insert(
3888 Rc::from(parameter.parameter_name()),
3889 DataObjectRef::new(new_data_object),
3890 );
3891 if old.is_some_and(|old| old.is_static_data()) {
3892 self.set_errno(
3893 InterpretingError::VarShadowingWarning,
3894 Some(&format!(
3895 "Parameter \"{}\" shadows a static variable",
3896 parameter.parameter_name(),
3897 )),
3898 function_body.get_pos(),
3899 );
3900 }
3901
3902 argument_index += 1;
3903 continue;
3904 },
3905
3906 _ => {},
3907 }
3908
3909 let mut value = combined_argument_list[argument_index].clone();
3910 match parameter.parameter_type() {
3911 ParameterType::Boolean => {
3912 value = DataObjectRef::new(DataObject::with_update(|data_object| {
3913 data_object.set_bool(conversions::to_bool(
3914 self,
3915 &value,
3916 argument_pos,
3917 ))
3918 }).unwrap());
3919 },
3920
3921 ParameterType::Number => {
3922 let number = conversions::to_number(
3923 self,
3924 &value,
3925 argument_pos,
3926 );
3927 let Some(number) = number else {
3928 break 'early_ret Some(Some(self.set_errno_error_object(
3929 InterpretingError::IncompatibleDataType,
3930 Some(&format!(
3931 "Invalid argument value for function parameter \"{}\" (Must be a number)",
3932 parameter.parameter_name(),
3933 )),
3934 argument_pos,
3935 )));
3936 };
3937
3938 value = DataObjectRef::new(DataObject::with_update(|data_object| {
3939 data_object.set_number(number)
3940 }).unwrap());
3941 },
3942
3943 ParameterType::Callable => {
3944 if !utils::is_callable(&value) {
3945 break 'early_ret Some(Some(self.set_errno_error_object(
3946 InterpretingError::IncompatibleDataType,
3947 Some(&format!(
3948 "Invalid argument value for function parameter \"{}\" (Must be callable)",
3949 parameter.parameter_name(),
3950 )),
3951 argument_pos,
3952 )));
3953 };
3954 },
3955
3956 _ => {},
3957 }
3958
3959 let new_data_object = DataObject::with_update(|data_object| {
3960 data_object.set_data(&value.borrow())?.
3961 set_variable_name(Some(parameter.parameter_name()))?.
3962 set_type_constraint(Box::new(parameter.type_constraint().clone()))
3963 });
3964 let new_data_object = match new_data_object {
3965 Ok(new_data_object) => new_data_object,
3966 Err(e) => {
3967 break 'early_ret Some(Some(self.set_errno_error_object(
3968 InterpretingError::InvalidAstNode,
3969 Some(&format!(
3970 "Invalid argument value for function parameter \"{}\" ({})",
3971 parameter.parameter_name(),
3972 e.message(),
3973 )),
3974 argument_pos,
3975 )));
3976 },
3977 };
3978
3979 let old = self.data_mut().var.insert(
3980 Rc::from(parameter.parameter_name()),
3981 DataObjectRef::new(new_data_object),
3982 );
3983 if old.is_some_and(|old| old.is_static_data()) {
3984 self.set_errno(
3985 InterpretingError::VarShadowingWarning,
3986 Some(&format!(
3987 "Parameter \"{}\" shadows a static variable",
3988 parameter.parameter_name(),
3989 )),
3990 function_body.get_pos(),
3991 );
3992 }
3993
3994 argument_index += 1;
3995 }
3996
3997 if combinator_function_call_ret.is_none() {
3998 self.interpret_ast(function_body);
4000 }
4001
4002 None
4003 };
4004 {
4006 let scope_data = self.data_ref().lang.clone();
4007
4008 self.exit_scope();
4009
4010 self.data_mut().lang.extend(scope_data);
4012 }
4013 if let Some(ret) = ret {
4015 return ret;
4016 }
4017
4018 if let Some(deprecation_info) = fp.deprecated() {
4019 let message = format!(
4020 "Use of deprecated function \"{}\". This function will no longer be supported in \"{}\"!{}",
4021 function_name,
4022 deprecation_info.remove_version().unwrap_or("the_future"),
4023 if let Some(deprecated_replacement_function) = deprecation_info.replacement_function() {
4024 format!("\nUse \"{deprecated_replacement_function}\" instead!")
4025 }else {
4026 String::new()
4027 }
4028 );
4029
4030 self.set_errno(InterpretingError::DeprecatedFuncCall, Some(&message), parent_pos);
4031 }
4032
4033 let (
4034 return_value_type_constraint,
4035 return_or_throw_statement_pos,
4036 ) = if combinator_function_call_ret.is_none() {
4037 (function.return_value_type_constraint(), self.execution_state.return_or_throw_statement_pos)
4038 }else {
4039 (None, CodePosition::EMPTY)
4040 };
4041
4042 let thrown_value = self.is_thrown_value();
4043 let ret_tmp = combinator_function_call_ret.
4044 unwrap_or_else(|| utils::none_to_lang_void(self.get_and_reset_return_value()));
4045
4046 if !thrown_value
4047 && let Some(return_value_type_constraint) = return_value_type_constraint {
4048 if !return_value_type_constraint.is_type_allowed(ret_tmp.data_type()) {
4050 return Some(self.set_errno_error_object(
4051 InterpretingError::IncompatibleDataType,
4052 Some(&format!(
4053 "Invalid return value type \"{}\"",
4054 ret_tmp.data_type(),
4055 )),
4056 return_or_throw_statement_pos,
4057 ));
4058 }
4059 }
4060
4061 Some(ret_tmp)
4062 },
4063
4064 FunctionData::Native(_) => {
4065 let ret = function.call_native_func(
4066 self,
4067 this_object.map(|this_object| (this_object.clone(), internal_function.super_level().unwrap())),
4068 Vec::from(argument_list),
4069 combined_argument_list,
4070 );
4071
4072 if let Some(deprecation_info) = fp.deprecated() {
4073 let message = format!(
4074 "Use of deprecated function \"{}\". This function will no longer be supported in \"{}\"!{}",
4075 function_name,
4076 deprecation_info.remove_version().unwrap_or("the_future"),
4077 if let Some(deprecated_replacement_function) = deprecation_info.replacement_function() {
4078 format!("\nUse \"{deprecated_replacement_function}\" instead!")
4079 }else {
4080 String::new()
4081 }
4082 );
4083
4084 self.set_errno(InterpretingError::DeprecatedFuncCall, Some(&message), parent_pos);
4085 }
4086
4087 if let Some(ret) = ret {
4089 if ret.is_copy_static_and_final_modifiers() {
4090 Some(ret)
4091 }else {
4092 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
4093 data_object.set_data(&ret.borrow())
4094 }).unwrap()))
4095 }
4096 }else {
4097 Some(DataObjectRef::new(DataObject::new_void()))
4098 }
4099 },
4100 }
4101 }
4102
4103 fn call_function_pointer(
4104 &mut self,
4105 fp: &FunctionPointerObject,
4106 function_name: Option<&str>,
4107 argument_list: &[DataObjectRef],
4108 parent_pos: CodePosition,
4109 ) -> OptionDataObjectRef {
4110 let this_object = fp.this_object();
4111 let mut original_super_level = None;
4112
4113 let combined_argument_list = utils::combine_arguments_without_argument_separators(
4114 argument_list, self, parent_pos,
4115 );
4116
4117 let internal_function = if fp.get_overloaded_function_count() == 1 {
4118 fp.get_function(0)
4119 }else {
4120 utils::get_most_restrictive_function(fp, &combined_argument_list)
4121 };
4122
4123 let Some(internal_function) = internal_function else {
4124 return Some(self.set_errno_error_object(
4125 InterpretingError::InvalidArguments,
4126 Some(&format!(
4127 "No matching function signature was found for the given arguments. \
4128 Available function signatures:\n {}{}",
4129 function_name.unwrap_or("null"),
4130 fp.functions().iter().
4131 map(|function| function.to_function_signature_string()).
4132 collect::<Vec<_>>().
4133 join(&("\n ".to_string() + function_name.unwrap_or("null"))),
4134 )),
4135 CodePosition::EMPTY,
4136 ));
4137 };
4138
4139 if !internal_function.is_accessible(self.current_call_stack_element().lang_class()) {
4140 return Some(self.set_errno_error_object(
4141 InterpretingError::MemberNotAccessible,
4142 Some(&format!("For member \"{}\"", function_name.unwrap_or("null"))),
4143 CodePosition::EMPTY,
4144 ));
4145 }
4146
4147 if let Some(this_object) = this_object {
4148 let mut this_object = this_object.borrow_mut();
4149
4150 if !this_object.is_class() {
4151 original_super_level = this_object.super_level();
4152 this_object.set_super_level(internal_function.super_level().unwrap()).unwrap();
4153 }
4154 }
4155
4156 let member_of_class = internal_function.member_of_class();
4157
4158 let function_lang_path = internal_function.lang_path();
4159 let function_lang_file = internal_function.lang_file();
4160
4161 let function_name = if let Some(function_name) = function_name &&
4162 fp.function_name().is_none() {
4163 function_name.to_string()
4164 }else {
4165 fp.to_string()
4166 };
4167
4168 let current_stack_element = self.current_call_stack_element();
4170
4171 let lang_class_name = if let Some(member_of_class) = member_of_class {
4172 if let Some(class_name) = member_of_class.borrow().class_name() {
4173 Some(class_name.to_string())
4174 }else {
4175 Some("<class>".to_string())
4176 }
4177 }else {
4178 None
4179 };
4180
4181 let new_stack_element = StackElement::new(
4182 if let Some(function_lang_path) = function_lang_path {
4183 function_lang_path
4184 }else {
4185 current_stack_element.lang_path()
4186 },
4187 if function_lang_path.is_none() && function_lang_file.is_none() {
4188 current_stack_element.lang_file()
4189 }else {
4190 function_lang_file
4191 },
4192 if let Some(member_of_class_value) = member_of_class &&
4193 !member_of_class_value.borrow().is_class() {
4194 Some(member_of_class_value.borrow().base_definition().unwrap())
4195 }else {
4196 member_of_class.cloned()
4197 },
4198 lang_class_name.as_deref(),
4199 Some(&function_name),
4200 current_stack_element.module.clone(),
4201 );
4202 self.push_stack_element(new_stack_element, parent_pos);
4203
4204 let ret = self.call_function_pointer_internal(
4205 fp,
4206 this_object,
4207 &function_name,
4208 internal_function,
4209 argument_list,
4210 combined_argument_list,
4211 parent_pos,
4212 );
4213
4214 if let Some(this_object) = this_object {
4215 let mut this_object = this_object.borrow_mut();
4216
4217 if !this_object.is_class() {
4218 this_object.set_super_level(original_super_level.unwrap()).unwrap();
4219 }
4220 }
4221
4222 self.pop_stack_element();
4224
4225 ret
4226 }
4227 fn interpret_function_pointer_arguments(&mut self, argument_list: &[Node]) -> Vec<DataObjectRef> {
4228 let mut argument_value_list = Vec::new();
4229 let mut previous_data_object = None;
4230 for argument in argument_list {
4231 if matches!(argument.node_data(), NodeData::FunctionCallPreviousNodeValue {..}) &&
4232 previous_data_object.is_some() {
4233 let ret = self.process_function_call_previous_node_value_node(
4234 argument,
4235 previous_data_object.clone(),
4236 );
4237
4238 if matches!(ret.node_data(), NodeData::FunctionCallPreviousNodeValue {..}) {
4239 argument_value_list.pop();
4241 argument_value_list.push(self.interpret_function_call_previous_node(&ret, previous_data_object.unwrap()));
4242 }else {
4243 argument_value_list.push(self.interpret_node(None, &ret).unwrap());
4244 }
4245
4246 previous_data_object = Some(argument_value_list[argument_value_list.len() - 1].clone());
4247
4248 continue;
4249 }
4250
4251 if let NodeData::UnprocessedVariableName(variable_name) = argument.node_data()
4253 && variable_name.contains("&") && variable_name.ends_with("...") {
4254 let mut variable_name = variable_name.to_string();
4255
4256 let is_module_variable = variable_name.starts_with("[[");
4257 let module_name = if is_module_variable {
4258 let index_module_identifier_end = variable_name.find("]]::");
4259 let Some(index_module_identifier_end) = index_module_identifier_end else {
4260 argument_value_list.push(self.set_errno_error_object(
4261 InterpretingError::InvalidAstNode,
4262 Some("Invalid variable name"),
4263 argument.pos(),
4264 ));
4265
4266 continue;
4267 };
4268
4269 let module_name = variable_name[2..index_module_identifier_end].to_string();
4270 if !Self::is_alpha_numeric_with_underline(&module_name) {
4271 argument_value_list.push(self.set_errno_error_object(
4272 InterpretingError::InvalidAstNode,
4273 Some("Invalid module name"),
4274 argument.pos(),
4275 ));
4276
4277 continue;
4278 }
4279
4280 variable_name = variable_name[index_module_identifier_end + 4..].to_string();
4281
4282 Some(module_name)
4283 }else {
4284 None
4285 };
4286
4287 if variable_name.starts_with("&") {
4288 let data_object = self.get_or_create_data_object_from_variable_name(
4289 None,
4290 module_name.as_deref(),
4291 &variable_name[..variable_name.len() - 3],
4292 false,
4293 false,
4294 false,
4295 &mut [false, false],
4296 argument.pos(),
4297 );
4298
4299 let Some(data_object) = data_object else {
4300 argument_value_list.push(self.set_errno_error_object(
4301 InterpretingError::InvalidArguments,
4302 Some("Unpacking of undefined variable"),
4303 argument.pos(),
4304 ));
4305
4306 continue;
4307 };
4308
4309 if let Some(array_value) = data_object.array_value() {
4310 let array_value = array_value.borrow();
4311 let array_value = array_value.deref().deref();
4312
4313 argument_value_list.append(&mut utils::separate_arguments_with_argument_separators(
4314 array_value,
4315 ));
4316 }else if let Some(list_value) = data_object.list_value() {
4317 let mut list_value = list_value.borrow().clone();
4318
4319 argument_value_list.append(&mut utils::separate_arguments_with_argument_separators(
4320 list_value.make_contiguous(),
4321 ));
4322 }else if let Some(struct_value) = data_object.struct_value() {
4323 if struct_value.is_definition() {
4324 let member_names = struct_value.member_names().iter().
4325 map(|member_name| DataObjectRef::new(DataObject::new_text(&**member_name))).
4326 collect::<Vec<_>>();
4327
4328 argument_value_list.append(&mut utils::separate_arguments_with_argument_separators(
4329 &member_names,
4330 ));
4331 }else {
4332 let members = struct_value.member_names().iter().
4333 map(|member_name| struct_value.get_member(member_name).unwrap()).
4334 collect::<Vec<_>>();
4335
4336 argument_value_list.append(&mut utils::separate_arguments_with_argument_separators(
4337 &members,
4338 ));
4339 }
4340 }else {
4341 argument_value_list.push(self.set_errno_error_object(
4342 InterpretingError::InvalidArguments,
4343 Some("Unpacking of unsupported composite type variable"),
4344 argument.pos(),
4345 ));
4346 }
4347
4348 continue;
4349 }
4350 }
4351
4352 let argument_value = self.interpret_node(None, argument);
4353 if let Some(argument_value) = &argument_value {
4354 argument_value_list.push(argument_value.clone());
4355 }
4356
4357 previous_data_object = argument_value;
4358 }
4359
4360 argument_value_list
4361 }
4362 fn interpret_function_call_node(&mut self, composite_type: OptionDataObjectRef, node: &Node) -> OptionDataObjectRef {
4366 let NodeData::FunctionCall(function_name) = node.node_data() else {
4367 panic!("Invalid AST node");
4368 };
4369 let original_function_name = function_name;
4370 let mut function_name = function_name.to_string();
4371
4372 if function_name.starts_with("mp.") {
4373 let Some(composite_type) = &composite_type else {
4374 return Some(self.set_errno_error_object(
4375 InterpretingError::InvalidAstNode,
4376 Some("Method call without object"),
4377 node.pos(),
4378 ));
4379 };
4380
4381 if let Some(object_value) = composite_type.object_value() {
4382 if object_value.borrow().is_class() {
4383 return Some(self.set_errno_error_object(
4384 InterpretingError::InvalidAstNode,
4385 Some("Method can not be called on classes"),
4386 node.pos(),
4387 ));
4388 }
4389 }else if let Some(text_value) = composite_type.text_value() {
4390 if &*text_value != "super" {
4391 return Some(self.set_errno_error_object(
4392 InterpretingError::InvalidAstNode,
4393 Some("Method call without object"),
4394 node.pos(),
4395 ));
4396 }
4397 }else {
4398 return Some(self.set_errno_error_object(
4399 InterpretingError::InvalidAstNode,
4400 Some("Method call without object"),
4401 node.pos(),
4402 ));
4403 }
4404 }
4405
4406 let is_module_variable = composite_type.is_none() && function_name.starts_with("[[");
4407 let (ret, ret_with_fp_prefix) = if is_module_variable {
4408 let index_module_identifier_end = function_name.find("]]::");
4409 let Some(index_module_identifier_end) = index_module_identifier_end else {
4410 return Some(self.set_errno_error_object(
4411 InterpretingError::InvalidAstNode,
4412 Some("Invalid variable name"),
4413 node.pos(),
4414 ));
4415 };
4416
4417 let module_name = function_name[2..index_module_identifier_end].to_string();
4418 if !Self::is_alpha_numeric_with_underline(&module_name) {
4419 return Some(self.set_errno_error_object(
4420 InterpretingError::InvalidAstNode,
4421 Some("Invalid module name"),
4422 node.pos(),
4423 ));
4424 }
4425
4426 function_name = function_name[index_module_identifier_end + 4..].to_string();
4427
4428 let module = self.modules.get(&*module_name);
4429
4430 let Some(module) = module else {
4431 return Some(self.set_errno_error_object(
4432 InterpretingError::ModuleLoadUnloadErr,
4433 Some(&format!("The module \"{module_name}\" is not loaded!")),
4434 node.pos(),
4435 ));
4436 };
4437
4438 let variables = module.exported_variables();
4439 (
4440 variables.borrow().get(&*function_name).cloned(),
4441 variables.borrow().get(&*("fp.".to_string() + &function_name)).cloned(),
4442 )
4443 }else {
4444 let variables = &self.data_ref().var;
4445 (
4446 variables.get(&*function_name).cloned(),
4447 variables.get(&*("fp.".to_string() + &function_name)).cloned(),
4448 )
4449 };
4450
4451 let fp = if let Some(composite_type) = composite_type {
4452 let object_value = composite_type.object_value();
4453
4454 if let Some(struct_value) = composite_type.struct_value() {
4455 if !function_name.starts_with("fp.") {
4456 function_name = "fp.".to_string() + &function_name;
4457 }
4458
4459 let member = struct_value.get_member(&function_name);
4460 let member = match member {
4461 Ok(member) => member,
4462 Err(e) => {
4463 return Some(self.set_errno_error_object(
4464 InterpretingError::IncompatibleDataType,
4465 Some(e.message()),
4466 node.pos(),
4467 ));
4468 },
4469 };
4470
4471 let Some(fp) = member.function_pointer_value() else {
4472 return Some(self.set_errno_error_object(
4473 InterpretingError::InvalidFuncPtr,
4474 Some(&format!("\"{original_function_name}\": Function pointer is invalid")),
4475 node.pos(),
4476 ));
4477 };
4478
4479 fp
4480 }else if let Some(text_value) = composite_type.text_value() {
4481 if &*text_value != "super" {
4482 return Some(self.set_errno_error_object(
4483 InterpretingError::InvalidArguments,
4484 Some("Invalid composite type"),
4485 node.pos(),
4486 ));
4487 }
4488
4489 let composite_type = self.data_ref().var.get("&this").cloned();
4490 let Some(composite_type) = composite_type else {
4491 return Some(self.set_errno_error_object(
4492 InterpretingError::InvalidArguments,
4493 Some("Super can only be used in methods if \"&this\" is present"),
4494 CodePosition::EMPTY,
4495 ));
4496 };
4497
4498 let object_value = {
4499 let Some(object_value) = composite_type.object_value() else {
4500 return Some(self.set_errno_error_object(
4501 InterpretingError::InvalidArguments,
4502 Some("Super can only be used in methods if \"&this\" is present"),
4503 CodePosition::EMPTY,
4504 ));
4505 };
4506
4507 object_value
4508 };
4509
4510 let argument_list = self.interpret_function_pointer_arguments(node.child_nodes());
4511
4512 if function_name == "construct" {
4513 return Some(self.call_super_constructor(&object_value, &argument_list, node.pos()));
4514 }
4515
4516 return self.call_super_method(&object_value, &function_name, &argument_list, node.pos());
4517 }else if let Some(object_value) = object_value {
4518 let argument_list = self.interpret_function_pointer_arguments(node.child_nodes());
4519
4520 if function_name == "construct" {
4521 return Some(self.call_constructor(&object_value, &argument_list, node.pos()));
4522 }
4523
4524 return self.call_method(&object_value, &function_name, &argument_list, node.pos());
4525 }else {
4526 return Some(self.set_errno_error_object(
4527 InterpretingError::InvalidArguments,
4528 Some("Invalid composite type"),
4529 node.pos(),
4530 ));
4531 }
4532 }else if !is_module_variable && Self::is_func_name(&function_name) {
4533 let is_linker_function;
4534 if !is_module_variable && function_name.starts_with("func.") {
4535 is_linker_function = false;
4536
4537 function_name = function_name[5..].to_string();
4538 }else if !is_module_variable && function_name.starts_with("fn.") {
4539 is_linker_function = false;
4540
4541 function_name = function_name[3..].to_string();
4542 }else if !is_module_variable && function_name.starts_with("linker.") {
4543 is_linker_function = true;
4544
4545 function_name = function_name[7..].to_string();
4546 }else if !is_module_variable && function_name.starts_with("ln.") {
4547 is_linker_function = true;
4548
4549 function_name = function_name[3..].to_string();
4550 }else {
4551 return Some(self.set_errno_error_object(
4552 InterpretingError::InvalidAstNode,
4553 Some("Invalid native, predefined, or linker function name"),
4554 node.pos(),
4555 ));
4556 }
4557
4558 let ret = self.funcs.iter().find(|(func_name, func)| {
4559 func.linker_function() == is_linker_function && function_name == ***func_name
4560 });
4561
4562 let Some(ret) = ret else {
4563 return Some(self.set_errno_error_object(
4564 InterpretingError::FunctionNotFound,
4565 Some(&format!(
4566 "\"{function_name}\": Native, predefined, or linker function was not found",
4567 )),
4568 node.pos(),
4569 ));
4570 };
4571
4572 let func = ret.1;
4573 Gc::new(func.copy_with_function_name(original_function_name))
4574 }else if Self::is_var_name_func_ptr_without_prefix(&function_name) {
4575 let Some(fp) = ret.and_then(|ret| ret.function_pointer_value()) else {
4576 return Some(self.set_errno_error_object(
4577 InterpretingError::InvalidFuncPtr,
4578 Some(&format!("\"{original_function_name}\": Function pointer is invalid")),
4579 node.pos(),
4580 ));
4581 };
4582
4583 fp
4584 }else {
4585 if let Some(ret) = ret_with_fp_prefix {
4589 let Some(fp) = ret.function_pointer_value() else {
4590 return Some(self.set_errno_error_object(
4591 InterpretingError::InvalidFuncPtr,
4592 Some(&format!("\"{original_function_name}\": Function pointer is invalid")),
4593 node.pos(),
4594 ));
4595 };
4596
4597 fp
4598 }else if !is_module_variable {
4599 let ret = self.funcs.iter().find(|(func_name, func)| {
4602 !func.linker_function() && function_name == ***func_name
4603 });
4604
4605 if let Some(ret) = ret {
4606 let func = ret.1;
4607 Gc::new(func.copy_with_function_name(&("func.".to_string() + &function_name)))
4608 }else {
4609 let ret = self.funcs.iter().find(|(func_name, func)| {
4611 func.linker_function() && function_name == ***func_name
4612 });
4613
4614 let Some(ret) = ret else {
4615 return Some(self.set_errno_error_object(
4616 InterpretingError::FunctionNotFound,
4617 Some(&format!(
4618 "\"{original_function_name}\": Normal, native, predefined, or linker function was not found",
4619 )),
4620 node.pos(),
4621 ));
4622 };
4623
4624 let func = ret.1;
4625 Gc::new(func.copy_with_function_name(&("linker.".to_string() + &function_name)))
4626 }
4627 }else {
4628 return Some(self.set_errno_error_object(
4629 InterpretingError::FunctionNotFound,
4630 Some(&format!(
4631 "\"{original_function_name}\": Normal, native, predefined, or linker function was not found",
4632 )),
4633 node.pos(),
4634 ));
4635 }
4636 };
4637
4638 let argument_list = self.interpret_function_pointer_arguments(node.child_nodes());
4639
4640 self.call_function_pointer(fp.deref(), Some(&function_name), &argument_list, node.pos())
4641 }
4642
4643 fn interpret_function_call_previous_node(&mut self, node: &Node, previous_value: DataObjectRef) -> DataObjectRef {
4644 let NodeData::FunctionCallPreviousNodeValue { .. } = node.node_data() else {
4645 panic!("Invalid AST node");
4646 };
4647
4648 let args = self.interpret_function_pointer_arguments(node.child_nodes());
4649
4650 let ret = operators::op_call(self, &previous_value, &args, node.pos());
4651 if let Some(ret) = ret {
4652 ret
4653 }else {
4654 self.set_errno_error_object(
4655 InterpretingError::InvalidAstNode,
4656 Some("Invalid data type"),
4657 node.pos(),
4658 )
4659 }
4660 }
4661
4662 fn interpret_function_definition_node(&mut self, node: &Node) -> OptionDataObjectRef {
4663 let NodeData::FunctionDefinition(function_definition) = node.node_data() else {
4664 panic!("Invalid AST node");
4665 };
4666
4667 let function_name_without_prefix;
4668 let function_pointer_data_object;
4669 let mut flags = [false, false];
4670 if let Some(function_name) = function_definition.function_name() {
4671 if function_name.starts_with("$") || function_name.starts_with("&") {
4672 function_name_without_prefix = Some(&function_name[1..]);
4673 }else {
4674 function_name_without_prefix = function_name.strip_prefix("fp.");
4675 }
4676
4677 function_pointer_data_object = self.get_or_create_data_object_from_variable_name(
4678 None,
4679 None,
4680 function_name,
4681 false,
4682 false,
4683 !function_definition.overloaded(),
4684 &mut flags,
4685 node.pos(),
4686 );
4687
4688 if flags[0] {
4689 return function_pointer_data_object;
4691 }
4692
4693 let Some(function_pointer_data_object) = &function_pointer_data_object else {
4694 return Some(self.set_errno_error_object(
4695 InterpretingError::InvalidAssignment,
4696 Some(&format!(
4697 "Can not overload variable \"{function_name}\" because the variable does not \
4698 exist or is not of type function pointer",
4699 )),
4700 node.pos(),
4701 ));
4702 };
4703 if function_definition.overloaded() &&
4704 function_pointer_data_object.data_type() != DataType::FUNCTION_POINTER {
4705 return Some(self.set_errno_error_object(
4706 InterpretingError::InvalidAssignment,
4707 Some(&format!(
4708 "Can not overload variable \"{function_name}\" because the variable does not \
4709 exist or is not of type function pointer",
4710 )),
4711 node.pos(),
4712 ));
4713 }
4714
4715 if !function_definition.overloaded() &&
4716 function_pointer_data_object.data_type() != DataType::NULL {
4717 return Some(self.set_errno_error_object(
4718 InterpretingError::InvalidAssignment,
4719 Some(&format!(
4720 "Can not set \"{function_name}\" to function because the variable already \
4721 exists (You should use \"function overload\" instead of \"function\" to overload a function)",
4722 )),
4723 node.pos(),
4724 ));
4725 }
4726
4727 let Some(variable_name) = function_pointer_data_object.variable_name() else {
4728 return Some(self.set_errno_error_object(
4729 InterpretingError::InvalidAssignment,
4730 Some("Anonymous values can not be changed"),
4731 node.pos(),
4732 ));
4733 };
4734
4735 if function_pointer_data_object.is_final_data() || function_pointer_data_object.is_lang_var() {
4736 if flags[1] {
4737 self.data_mut().var.remove(&*variable_name);
4738 }
4739
4740 return Some(self.set_errno_error_object(
4741 InterpretingError::FinalVarChange,
4742 None,
4743 node.pos(),
4744 ));
4745 }
4746 }else {
4747 function_pointer_data_object = None;
4748 function_name_without_prefix = None;
4749 }
4750
4751 let mut parameter_doc_comments = HashMap::new();
4752 let mut string_builder = String::new();
4753 if let Some(doc_comment) = function_definition.doc_comment() {
4754 for token in doc_comment.split("\n") {
4755 let token = token.trim();
4756
4757 if token.starts_with("@param") && token.chars().nth(6).
4758 is_some_and(|char| char.is_whitespace())
4759 && let Some(colon_index) = token.find(":") {
4760 let name = token[6..colon_index].trim();
4761 let comment = token[colon_index + 1..].trim();
4762 parameter_doc_comments.insert(name, comment);
4763
4764 continue;
4765 }
4766
4767 string_builder += token;
4768 string_builder += "\n";
4769 }
4770
4771 if !string_builder.is_empty() {
4773 string_builder.remove(string_builder.len() - 1);
4774 }
4775 }
4776
4777 let function_doc_comment = function_definition.doc_comment().map(|_| string_builder);
4778
4779 let mut parameters = Vec::with_capacity(node.child_nodes().len());
4780 let mut argument_pos_list = Vec::with_capacity(node.child_nodes().len());
4781
4782 for (index, child) in node.child_nodes().iter().
4783 enumerate() {
4784 let NodeData::VariableName {
4785 variable_name,
4786 type_constraint,
4787 } = child.node_data() else {
4788 return if matches!(child.node_data(), NodeData::ParsingError {..}) {
4789 self.interpret_node(None, child)
4790 }else {
4791 Some(self.set_errno_error_object(
4792 InterpretingError::InvalidAstNode,
4793 Some("Invalid AST node type for parameter"),
4794 node.pos(),
4795 ))
4796 };
4797 };
4798
4799 let parameter_type;
4800 let parameter_type_constraint;
4801 if let Some(type_constraint) = type_constraint {
4802 match &**type_constraint {
4803 "bool" => {
4804 parameter_type_constraint = None;
4805 parameter_type = ParameterType::Boolean;
4806 },
4807
4808 "number" => {
4809 parameter_type_constraint = None;
4810 parameter_type = ParameterType::Number;
4811 },
4812
4813 "callable" => {
4814 parameter_type_constraint = None;
4815 parameter_type = ParameterType::Callable;
4816 },
4817
4818 _ => {
4819 let mut error_out = DataObject::new_void();
4820 parameter_type_constraint = Some(self.interpret_type_constraint(
4821 type_constraint, &mut error_out, child.pos(),
4822 ));
4823
4824 if error_out.data_type() == DataType::ERROR {
4825 return Some(DataObjectRef::new(error_out));
4826 }
4827
4828 parameter_type = ParameterType::Normal;
4829 },
4830 }
4831 }else {
4832 parameter_type_constraint = None;
4833 parameter_type = ParameterType::Normal;
4834 }
4835
4836 if index == node.child_nodes().len() - 1 && !Self::is_lang_var_without_prefix(variable_name) &&
4837 Self::is_func_call_var_args(variable_name) {
4838 let variable_name = &variable_name[..variable_name.len() - 3];
4842
4843 parameters.push(ParameterMetadata::new(
4844 variable_name,
4845 parameter_doc_comments.remove(variable_name),
4846 Some(parameter_type_constraint.unwrap_or_else(|| data::CONSTRAINT_NORMAL.clone())),
4847 ParameterType::VarArgs,
4848 ));
4849 argument_pos_list.push(child.pos());
4850
4851 continue;
4852 }
4853
4854 if Self::is_func_call_call_by_ptr(variable_name) &&
4855 !Self::is_func_call_call_by_ptr_lang_var(variable_name) {
4856 let variable_name = "$".to_string() + &variable_name[2..variable_name.len() - 1];
4858
4859 parameters.push(ParameterMetadata::new(
4860 &variable_name,
4861 parameter_doc_comments.remove(&*variable_name),
4862 Some(parameter_type_constraint.unwrap_or_else(|| DataObject::get_type_constraint_for(Some(&variable_name)).clone())),
4863 ParameterType::CallByPointer,
4864 ));
4865 argument_pos_list.push(child.pos());
4866
4867 continue;
4868 }
4869
4870 if !Self::is_var_name_without_prefix(variable_name) || Self::is_lang_var_without_prefix(variable_name) {
4871 return Some(self.set_errno_error_object(
4872 InterpretingError::InvalidAstNode,
4873 Some(&format!("Invalid parameter: \"{variable_name}\"")),
4874 node.pos(),
4875 ));
4876 }
4877
4878 parameters.push(ParameterMetadata::new(
4879 variable_name,
4880 parameter_doc_comments.remove(&**variable_name),
4881 Some(parameter_type_constraint.unwrap_or_else(|| DataObject::get_type_constraint_for(Some(variable_name)).clone())),
4882 parameter_type,
4883 ));
4884 argument_pos_list.push(child.pos());
4885 }
4886
4887 let return_value_type_constraint = if let Some(return_value_type_constraint) = function_definition.return_value_type_constraint() {
4888 let mut error_out = DataObject::new_void();
4889 let return_value_type_constraint = self.interpret_type_constraint(
4890 return_value_type_constraint, &mut error_out, node.pos(),
4891 );
4892
4893 if error_out.data_type() == DataType::ERROR {
4894 return Some(DataObjectRef::new(error_out));
4895 }
4896
4897 return_value_type_constraint
4898 }else {
4899 data::CONSTRAINT_NORMAL.clone()
4900 };
4901
4902 if !parameter_doc_comments.is_empty() {
4903 self.set_errno(
4904 InterpretingError::InvalidDocComment,
4905 Some(&format!(
4906 "The following parameters defined in the doc comment do not exist: {}",
4907 parameter_doc_comments.into_keys().
4908 collect::<Vec<_>>().
4909 join(", "),
4910 )),
4911 node.pos(),
4912 );
4913 }
4914
4915 let function_metadata = FunctionMetadata::new(
4916 function_name_without_prefix,
4917 function_doc_comment.as_deref(),
4918 false,
4919 function_definition.combinator(),
4920 false,
4921 None,
4922 parameters,
4923 Some(return_value_type_constraint),
4924 );
4925
4926 let function = Function::new_normal(
4927 NormalFunction::new(
4928 argument_pos_list,
4929 function_definition.function_body().clone(),
4930 Some(&self.current_call_stack_element.lang_path),
4931 self.current_call_stack_element.lang_file.as_deref(),
4932 ),
4933 &function_metadata,
4934 );
4935
4936 let Some(function_pointer_data_object) = function_pointer_data_object else {
4937 return Some(DataObjectRef::new(DataObject::with_update(|data_object| {
4938 let mut fp = FunctionPointerObject::new(&function_metadata, function);
4939 if let Some(lang_class) = &self.current_call_stack_element.lang_class {
4940 fp = fp.copy_with_mapped_functions(|internal_functions| internal_functions.
4941 copy_with_class_member_attributes(lang_class.clone(), Visibility::Public));
4942 }
4943
4944 data_object.set_function_pointer(Gc::new(fp))
4945 }).unwrap()));
4946 };
4947
4948 let ret = if function_definition.overloaded() {
4949 let mut internal_function = InternalFunction::new(Gc::new(function));
4950 if let Some(lang_class) = &self.current_call_stack_element.lang_class {
4951 internal_function = internal_function.copy_with_class_member_attributes(lang_class.clone(), Visibility::Public);
4952 }
4953
4954 let fp = function_pointer_data_object.function_pointer_value().unwrap().
4955 copy_with_added_function(internal_function);
4956
4957 function_pointer_data_object.borrow_mut().set_function_pointer(Gc::new(fp)).map(|_| ())
4958 }else {
4959 let mut fp = FunctionPointerObject::new(&function_metadata, function);
4960 if let Some(lang_class) = &self.current_call_stack_element.lang_class {
4961 fp = fp.copy_with_mapped_functions(|internal_functions| internal_functions.
4962 copy_with_class_member_attributes(lang_class.clone(), Visibility::Public));
4963 }
4964
4965 function_pointer_data_object.borrow_mut().update(|data_object| {
4966 data_object.set_function_pointer(Gc::new(fp))?.
4967 set_type_constraint(Box::new(DataTypeConstraint::from_single_allowed_type(
4968 DataType::FUNCTION_POINTER,
4969 )))
4970 })
4971 };
4972 if ret.is_err() {
4973 if flags[1] {
4974 self.data_mut().var.remove(&*function_pointer_data_object.variable_name().unwrap());
4975 }
4976
4977 return Some(self.set_errno_error_object(
4978 InterpretingError::IncompatibleDataType,
4979 Some(&format!(
4980 "Incompatible type for function definition: \"{}\" was already defined and cannot be set to a function definition",
4981 function_pointer_data_object.variable_name().unwrap(),
4982 )),
4983 node.pos(),
4984 ));
4985 }
4986
4987 Some(function_pointer_data_object)
4988 }
4989
4990 fn interpret_array_node(&mut self, node: &Node) -> DataObjectRef {
4991 let NodeData::ArrayValue = node.node_data() else {
4992 panic!("Invalid AST node");
4993 };
4994
4995 let mut interpreted_nodes = Vec::new();
4996
4997 for element in node.child_nodes() {
4998 let argument_value = self.interpret_node(None, element);
4999 let Some(argument_value) = argument_value else {
5000 continue;
5001 };
5002
5003 interpreted_nodes.push(DataObjectRef::new(DataObject::with_update(|data_object| {
5004 data_object.set_data(&argument_value.borrow())
5005 }).unwrap()));
5006 }
5007
5008 let elements = utils::combine_arguments_without_argument_separators(
5009 &interpreted_nodes,
5010 self,
5011 node.pos(),
5012 );
5013 DataObjectRef::new(DataObject::with_update(|data_object| {
5014 data_object.set_array(elements.into_boxed_slice())
5015 }).unwrap())
5016 }
5017
5018 fn interpret_struct_definition_node(&mut self, node: &Node) -> OptionDataObjectRef {
5019 let NodeData::StructDefinition(struct_definition) = node.node_data() else {
5020 panic!("Invalid AST node");
5021 };
5022
5023 let struct_data_object;
5024 let mut flags = [false, false];
5025 if let Some(struct_name) = struct_definition.struct_name() {
5026 struct_data_object = self.get_or_create_data_object_from_variable_name(
5027 None,
5028 None,
5029 struct_name,
5030 false,
5031 false,
5032 true,
5033 &mut flags,
5034 node.pos(),
5035 );
5036 if flags[0] {
5037 return struct_data_object; }
5039
5040 let Some(struct_data_object) = &struct_data_object else {
5041 return Some(self.set_errno_error_object(
5042 InterpretingError::InvalidAssignment,
5043 Some("Anonymous values can not be changed"),
5044 node.pos(),
5045 ));
5046 };
5047
5048 let Some(variable_name) = struct_data_object.variable_name() else {
5049 return Some(self.set_errno_error_object(
5050 InterpretingError::InvalidAssignment,
5051 Some("Anonymous values can not be changed"),
5052 node.pos(),
5053 ));
5054 };
5055
5056 if struct_data_object.is_final_data() || struct_data_object.is_lang_var() {
5057 if flags[1] {
5058 self.data_mut().var.remove(&*variable_name);
5059 }
5060
5061 return Some(self.set_errno_error_object(
5062 InterpretingError::FinalVarChange,
5063 None,
5064 node.pos(),
5065 ));
5066 }
5067 }else {
5068 struct_data_object = None;
5069 }
5070
5071 let members = struct_definition.members();
5072
5073 for member in members {
5074 if !Self::is_var_name_without_prefix(member.name()) {
5075 return Some(self.set_errno_error_object(
5076 InterpretingError::InvalidAstNode,
5077 Some(&format!(
5078 "\"{}\" is no valid struct member name",
5079 member.name(),
5080 )),
5081 node.pos(),
5082 ));
5083 }
5084 }
5085
5086 let unique_member_count = members.iter().
5087 map(|member| member.name()).
5088 collect::<HashSet<_>>().
5089 len();
5090 if unique_member_count < members.len() {
5091 return Some(self.set_errno_error_object(
5092 InterpretingError::InvalidAstNode,
5093 Some("Struct member name may not be duplicated"),
5094 node.pos(),
5095 ));
5096 }
5097
5098 let mut interpreted_members = Vec::new();
5099 for member in members {
5100 let type_constraint = if let Some(type_constraint) = member.type_constraint() {
5101 let mut error_out = DataObject::new_void();
5102 let type_constraint = self.interpret_type_constraint(
5103 type_constraint, &mut error_out, node.pos(),
5104 );
5105
5106 if error_out.data_type() == DataType::ERROR {
5107 return Some(DataObjectRef::new(error_out));
5108 }
5109
5110 Some(type_constraint)
5111 }else {
5112 None
5113 };
5114
5115 interpreted_members.push((
5116 member.name(),
5117 type_constraint,
5118 ));
5119 }
5120
5121 let struct_object = Gc::new(StructObject::new_definition(
5122 &interpreted_members,
5123 ));
5124
5125 if let Some(data_object) = &struct_data_object {
5126 let ret = data_object.borrow_mut().update_final(|data_object| {
5127 data_object.set_struct(struct_object)?.
5128 set_type_constraint(Box::new(DataTypeConstraint::from_single_allowed_type(
5129 DataType::STRUCT,
5130 )))
5131 });
5132 if ret.is_err() {
5133 if flags[1] {
5134 self.data_mut().var.remove(&*data_object.variable_name().unwrap());
5135 }
5136
5137 return Some(self.set_errno_error_object(
5138 InterpretingError::IncompatibleDataType,
5139 Some(&format!(
5140 "Incompatible type for struct definition: \"{}\" was already defined and cannot be set to a struct definition",
5141 data_object.variable_name().unwrap(),
5142 )),
5143 node.pos(),
5144 ));
5145 }
5146
5147 struct_data_object
5148 }else {
5149 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
5150 data_object.set_struct(struct_object)
5151 }).unwrap()))
5152 }
5153 }
5154
5155 fn interpret_class_definition_node(&mut self, node: &Node) -> OptionDataObjectRef {
5156 let NodeData::ClassDefinition(class_definition) = node.node_data() else {
5157 panic!("Invalid AST node");
5158 };
5159
5160 let ret = 'early_ret: {
5161 let current_stack_element = self.current_call_stack_element();
5163 let new_stack_element = StackElement::new(
5164 ¤t_stack_element.lang_path,
5165 current_stack_element.lang_file.as_deref(),
5166 Some(LangObject::dummy_class_definition_class()),
5167 if let Some(class_name) = class_definition.class_name() {
5168 Some(class_name)
5169 }else {
5170 Some("<class>")
5171 },
5172 Some("<class-definition>"),
5173 current_stack_element.module.clone(),
5174 );
5175 self.push_stack_element(new_stack_element, node.pos());
5176
5177 let class_data_object;
5178 let mut flags = [false, false];
5179 if let Some(class_name) = class_definition.class_name() {
5180 class_data_object = self.get_or_create_data_object_from_variable_name(
5181 None,
5182 None,
5183 class_name,
5184 false,
5185 false,
5186 true,
5187 &mut flags,
5188 node.pos(),
5189 );
5190 if flags[0] {
5191 break 'early_ret class_data_object; }
5193
5194 let Some(class_data_object) = &class_data_object else {
5195 break 'early_ret Some(self.set_errno_error_object(
5196 InterpretingError::InvalidAssignment,
5197 Some("Anonymous values can not be changed"),
5198 node.pos(),
5199 ));
5200 };
5201
5202 let Some(variable_name) = class_data_object.variable_name() else {
5203 break 'early_ret Some(self.set_errno_error_object(
5204 InterpretingError::InvalidAssignment,
5205 Some("Anonymous values can not be changed"),
5206 node.pos(),
5207 ));
5208 };
5209
5210 if class_data_object.is_final_data() || class_data_object.is_lang_var() {
5211 if flags[1] {
5212 self.data_mut().var.remove(&*variable_name);
5213 }
5214
5215 break 'early_ret Some(self.set_errno_error_object(
5216 InterpretingError::FinalVarChange,
5217 None,
5218 node.pos(),
5219 ));
5220 }
5221 }else {
5222 class_data_object = None;
5223 }
5224
5225 let parent_class_list = self.interpret_function_pointer_arguments(
5226 class_definition.parent_classes(),
5227 );
5228 let parent_class_list = utils::combine_arguments_without_argument_separators(
5229 &parent_class_list, self, node.pos(),
5230 );
5231
5232 let mut parent_class_object_list = Vec::with_capacity(parent_class_list.len());
5233 for parent_class in parent_class_list {
5234 let Some(object_value) = parent_class.object_value() else {
5235 break 'early_ret Some(self.set_errno_error_object(
5236 InterpretingError::IncompatibleDataType,
5237 Some("Parent classes must be classes"),
5238 node.pos(),
5239 ));
5240 };
5241
5242 if !object_value.borrow().is_class() {
5243 break 'early_ret Some(self.set_errno_error_object(
5244 InterpretingError::IncompatibleDataType,
5245 Some("Parent classes must be classes"),
5246 node.pos(),
5247 ));
5248 }
5249
5250 parent_class_object_list.push(object_value);
5251 }
5252
5253 let mut interpreted_static_members = Vec::with_capacity(class_definition.static_members().len());
5254 for static_member in class_definition.static_members() {
5255 if !Self::is_var_name_without_prefix(static_member.name()) {
5256 break 'early_ret Some(self.set_errno_error_object(
5257 InterpretingError::InvalidAstNode,
5258 Some(&format!(
5259 "\"{}\" is no valid static member name",
5260 static_member.name(),
5261 )),
5262 node.pos(),
5263 ));
5264 }
5265
5266 let type_constraint = if let Some(type_constraint) = static_member.type_constraint() {
5267 let mut error_out = DataObject::new_void();
5268 let type_constraint = self.interpret_type_constraint(
5269 type_constraint, &mut error_out, node.pos(),
5270 );
5271
5272 if error_out.data_type() == DataType::ERROR {
5273 break 'early_ret Some(DataObjectRef::new(error_out));
5274 }
5275
5276 Some(type_constraint)
5277 }else {
5278 None
5279 };
5280
5281 let static_member_data_object = DataObject::with_update(|data_object| {
5282 let value = static_member.value().
5283 map(|value| self.interpret_node(None, value).
5284 unwrap_or_else(|| DataObjectRef::new(DataObject::new_void()))).
5285 unwrap_or_else(|| DataObjectRef::new(DataObject::new()));
5286
5287 data_object.set_data(&value.borrow())?;
5288 data_object.set_variable_name(Some(static_member.name()))?;
5289
5290 if let Some(type_constraint) = type_constraint {
5291 data_object.set_type_constraint(Box::new(type_constraint))?;
5292 }
5293
5294 if static_member.final_flag() {
5295 data_object.set_final_data(true);
5296 }
5297
5298 data_object.set_member_visibility(Some(Visibility::from(static_member.visibility())));
5299
5300 Ok(data_object)
5301 });
5302 let static_member_data_object = match static_member_data_object {
5303 Ok(data_object) => data_object,
5304 Err(e) => {
5305 break 'early_ret Some(self.set_errno_error_object(
5306 InterpretingError::InvalidAstNode,
5307 Some(e.message()),
5308 node.pos(),
5309 ));
5310 },
5311 };
5312
5313 interpreted_static_members.push(static_member_data_object);
5314 }
5315
5316 let unique_static_member_count = class_definition.static_members().iter().
5317 map(|member| member.name()).
5318 collect::<HashSet<_>>().
5319 len();
5320 if unique_static_member_count < class_definition.static_members().len() {
5321 break 'early_ret Some(self.set_errno_error_object(
5322 InterpretingError::InvalidAstNode,
5323 Some("Static member name may not be duplicated"),
5324 node.pos(),
5325 ));
5326 }
5327
5328 let mut interpreted_members = Vec::with_capacity(class_definition.members().len());
5329 for member in class_definition.members() {
5330 if !Self::is_var_name_without_prefix(member.name()) {
5331 break 'early_ret Some(self.set_errno_error_object(
5332 InterpretingError::InvalidAstNode,
5333 Some(&format!(
5334 "\"{}\" is no valid member name",
5335 member.name(),
5336 )),
5337 node.pos(),
5338 ));
5339 }
5340
5341 let type_constraint = if let Some(type_constraint) = member.type_constraint() {
5342 let mut error_out = DataObject::new_void();
5343 let type_constraint = self.interpret_type_constraint(
5344 type_constraint, &mut error_out, node.pos(),
5345 );
5346
5347 if error_out.data_type() == DataType::ERROR {
5348 break 'early_ret Some(DataObjectRef::new(error_out));
5349 }
5350
5351 Some(type_constraint)
5352 }else {
5353 None
5354 };
5355
5356 if member.value().is_some() {
5357 break 'early_ret Some(self.set_errno_error_object(
5358 InterpretingError::InvalidAstNode,
5359 Some("Member can not be initialized with value"),
5360 node.pos(),
5361 ));
5362 }
5363
5364 interpreted_members.push(MemberDefinition::new(
5365 member.name(),
5366 type_constraint.map(Box::new),
5367 member.final_flag(),
5368 Visibility::from(member.visibility()),
5369 LangObject::dummy_class_definition_class(),
5370 ));
5371 }
5372
5373 let unique_member_count = class_definition.members().iter().
5374 map(|member| member.name()).
5375 collect::<HashSet<_>>().
5376 len();
5377 if unique_member_count < class_definition.members().len() {
5378 break 'early_ret Some(self.set_errno_error_object(
5379 InterpretingError::InvalidAstNode,
5380 Some("Member name may not be duplicated"),
5381 node.pos(),
5382 ));
5383 }
5384
5385 let mut methods = HashMap::<Box<str>, FunctionPointerObject>::new();
5386 let mut method_override_flags = HashMap::<Box<str>, Vec<bool>>::new();
5387 let mut method_visibility = HashMap::<Box<str>, Vec<Visibility>>::new();
5388 for method in class_definition.methods() {
5389 if !Self::is_method_name(method.name()) && !Self::is_operator_method_name(method.name()) &&
5390 !Self::is_conversion_method_name(method.name()) {
5391 break 'early_ret Some(self.set_errno_error_object(
5392 InterpretingError::InvalidAstNode,
5393 Some(&format!(
5394 "\"{}\" is no valid method name",
5395 method.name(),
5396 )),
5397 node.pos(),
5398 ));
5399 }
5400
5401 let method_body = self.interpret_node(None, method.body());
5402 let Some(method_body) = method_body.
5403 and_then(|method_body| method_body.function_pointer_value()) else {
5404 break 'early_ret Some(self.set_errno_error_object(
5405 InterpretingError::IncompatibleDataType,
5406 Some(&format!(
5407 "Methods must be of type \"{}\"",
5408 DataType::FUNCTION_POINTER,
5409 )),
5410 node.pos(),
5411 ));
5412 };
5413
5414 let method_name: Box<str> = Box::from(method.name());
5415 let overloaded_function_count = method_body.get_overloaded_function_count();
5416
5417 let entry = methods.entry(method_name.clone());
5418 match entry {
5419 Entry::Occupied(mut entry) => {
5420 entry.insert(entry.get().copy_with_added_functions(&method_body));
5421 },
5422
5423 Entry::Vacant(entry) => {
5424 entry.insert(method_body.deref().clone());
5425 method_override_flags.insert(method_name.clone(), Vec::new());
5426 method_visibility.insert(method_name.clone(), Vec::new());
5427 },
5428 }
5429
5430 let method_override_flags = method_override_flags.get_mut(&method_name).unwrap();
5431 for _ in 0..overloaded_function_count {
5432 method_override_flags.push(method.override_flag());
5433 }
5434
5435 let method_visibility = method_visibility.get_mut(&method_name).unwrap();
5436 for _ in 0..overloaded_function_count {
5437 method_visibility.push(Visibility::from(method.visibility()));
5438 }
5439 }
5440
5441 let mut constructors: Option<FunctionPointerObject> = None;
5442 let mut constructor_visibility = Vec::new();
5443 for constructor in class_definition.constructors() {
5444 let constructor_body = self.interpret_node(None, constructor.body());
5445 let Some(constructor_body) = constructor_body.
5446 and_then(|constructor_body| constructor_body.function_pointer_value()) else {
5447 break 'early_ret Some(self.set_errno_error_object(
5448 InterpretingError::IncompatibleDataType,
5449 Some(&format!(
5450 "Constructors must be of type \"{}\"",
5451 DataType::FUNCTION_POINTER,
5452 )),
5453 node.pos(),
5454 ));
5455 };
5456
5457 let overloaded_function_count = constructor_body.get_overloaded_function_count();
5458
5459 if let Some(constructors) = &mut constructors {
5460 *constructors = constructors.copy_with_added_functions(&constructor_body);
5461 }else {
5462 constructors = Some(constructor_body.deref().clone());
5463 }
5464
5465 for _ in 0..overloaded_function_count {
5466 constructor_visibility.push(Visibility::from(constructor.visibility()));
5467 }
5468 }
5469
5470 let constructors = constructors.unwrap_or_else(|| {
5472 constructor_visibility.push(Visibility::Public);
5473
5474 let constructor = |_: &mut Interpreter, _: LangObjectRef| {};
5475 FunctionPointerObject::from(crate::lang_func!(
5476 constructor,
5477 crate::lang_func_metadata!(
5478 name="construct",
5479 return_type_constraint(
5480 allowed=["VOID"],
5481 ),
5482 ),
5483 ))
5484 });
5485
5486 let lang_object = LangObject::new_class(
5487 class_definition.class_name(),
5488 interpreted_static_members,
5489 interpreted_members,
5490 methods,
5491 method_override_flags,
5492 method_visibility,
5493 constructors,
5494 constructor_visibility,
5495 parent_class_object_list,
5496 );
5497 let lang_object = match lang_object {
5498 Ok(lang_object) => lang_object,
5499
5500 Err(e) => {
5501 break 'early_ret Some(self.set_errno_error_object(
5502 InterpretingError::InvalidAstNode,
5503 Some(e.message()),
5504 node.pos(),
5505 ));
5506 },
5507 };
5508
5509 break 'early_ret if let Some(data_object) = &class_data_object {
5511 let ret = data_object.borrow_mut().update_final(|data_object| {
5512 data_object.set_object(lang_object)?.
5513 set_type_constraint(Box::new(DataTypeConstraint::from_single_allowed_type(
5514 DataType::OBJECT,
5515 )))
5516 });
5517 if ret.is_err() {
5518 if flags[1] {
5519 self.data_mut().var.remove(&*data_object.variable_name().unwrap());
5520 }
5521
5522 break 'early_ret Some(self.set_errno_error_object(
5523 InterpretingError::IncompatibleDataType,
5524 Some(&format!(
5525 "Incompatible type for class definition: \"{}\" was already defined and cannot be set to a class definition",
5526 data_object.variable_name().unwrap(),
5527 )),
5528 node.pos(),
5529 ));
5530 }
5531
5532 class_data_object
5533 }else {
5534 Some(DataObjectRef::new(DataObject::with_update(|data_object| {
5535 data_object.set_object(lang_object)
5536 }).unwrap()))
5537 };
5538 };
5539 {
5541 self.pop_stack_element();
5543 }
5544 ret
5546 }
5547
5548 fn interpret_type_constraint(
5549 &mut self,
5550 mut type_constraint: &str,
5551 error_out: &mut DataObject,
5552 pos: CodePosition,
5553 ) -> DataTypeConstraint {
5554 if type_constraint.is_empty() {
5555 error_out.set_data(&self.set_errno_error_object(
5556 InterpretingError::InvalidAstNode,
5557 Some("Empty type constraint is not allowed"),
5558 pos,
5559 ).borrow()).unwrap();
5560
5561 return DataTypeConstraint::from_allowed_types(&[]);
5562 }
5563
5564 let nullable = type_constraint.as_bytes()[0] == b'?';
5565 let inverted = type_constraint.as_bytes()[0] == b'!';
5566 let mut type_values = Vec::new();
5567
5568 if nullable || inverted {
5569 type_constraint = &type_constraint[1..];
5570 }
5571
5572 loop {
5573 let pipe_index = type_constraint.find("|");
5574 let end_index = pipe_index.unwrap_or(type_constraint.len());
5575 let type_value = &type_constraint[..end_index];
5576
5577 if type_value.is_empty() || pipe_index.is_some_and(|pipe_index| pipe_index == type_constraint.len() - 1) {
5578 error_out.set_data(&self.set_errno_error_object(
5579 InterpretingError::InvalidAstNode,
5580 Some("Empty type constraint is not allowed"),
5581 pos,
5582 ).borrow()).unwrap();
5583
5584 return DataTypeConstraint::from_allowed_types(&[]);
5585 }
5586
5587 type_constraint = pipe_index.
5588 map(|pipe_index| &type_constraint[pipe_index + 1..]).
5589 unwrap_or("");
5590
5591 let data_type = DataType::from_string(type_value);
5592 if let Some(data_type) = data_type {
5593 type_values.push(data_type);
5594 }else {
5595 error_out.set_data(&self.set_errno_error_object(
5596 InterpretingError::InvalidAstNode,
5597 Some(&format!("Invalid type: \"{type_value}\"")),
5598 pos,
5599 ).borrow()).unwrap();
5600
5601 return DataTypeConstraint::from_allowed_types(&[]);
5602 }
5603
5604 if pipe_index.is_none() {
5605 break;
5606 }
5607 }
5608
5609 if nullable {
5610 type_values.push(DataType::NULL);
5611 }
5612
5613 if inverted {
5614 DataTypeConstraint::from_not_allowed_types(&type_values)
5615 }else {
5616 DataTypeConstraint::from_allowed_types(&type_values)
5617 }
5618 }
5619
5620 fn interpret_next_format_sequence(
5628 &mut self,
5629 format: &str,
5630 builder: &mut String,
5631 argument_list: &mut VecDeque<&DataObjectRef>,
5632 full_argument_list: &[DataObjectRef],
5633 ) -> Result<usize, FormatSequenceError> {
5634 const POSSIBLE_FORMATS: [char; 10] = ['b', 'c', 'd', 'f', 'n', 'o', 's', 't', 'x', '?'];
5635
5636 let min_end_index = POSSIBLE_FORMATS.into_iter().
5637 filter_map(|possible_format| format.find(possible_format)).
5638 min();
5639
5640 let Some(min_end_index) = min_end_index else {
5641 return Err(FormatSequenceError::InvalidFormatSequence(Box::from("Invalid format specifier")));
5642 };
5643
5644 let mut full_format = &format[..min_end_index + 1];
5645 let format_type = full_format.as_bytes()[full_format.len() - 1];
5646 let format_type_char = format_type as char;
5647
5648 let value_specified_index = if full_format.as_bytes()[0] == b'[' {
5650 let value_specified_index_end_index = full_format.find(']');
5651 let Some(value_specified_index_end_index) = value_specified_index_end_index else {
5652 return Err(FormatSequenceError::InvalidFormatSequence(Box::from("Missing closing bracket in value index")));
5653 };
5654
5655 let number = &full_format[1..value_specified_index_end_index];
5656 full_format = &full_format[value_specified_index_end_index + 1..];
5657
5658 for char in number.bytes() {
5659 if !char.is_ascii_digit() {
5660 return Err(FormatSequenceError::InvalidFormatSequence(Box::from("Invalid number in value index")));
5661 }
5662 }
5663 let number = usize::from_str(number).unwrap();
5664 if number >= full_argument_list.len() {
5665 return Err(FormatSequenceError::SpecifiedIndexOutOfBounds(Box::from("For value index")));
5666 }
5667
5668 Some(number)
5669 }else {
5670 None
5671 };
5672
5673 let force_sign = full_format.as_bytes()[0] == b'+';
5674 if force_sign {
5675 full_format = &full_format[1..];
5676 }
5677
5678 let sing_space = full_format.as_bytes()[0] == b' ';
5679 if sing_space {
5680 full_format = &full_format[1..];
5681 }
5682
5683 let left_justify = full_format.as_bytes()[0] == b'-';
5684 if left_justify {
5685 full_format = &full_format[1..];
5686 }
5687
5688 let mut leading_zeros = full_format.as_bytes()[0] == b'0';
5689 if leading_zeros {
5690 full_format = &full_format[1..];
5691 }
5692
5693 let size_in_argument = full_format.as_bytes()[0] == b'*';
5694 if size_in_argument {
5695 full_format = &full_format[1..];
5696 }
5697 let size_argument_index = if size_in_argument && full_format.as_bytes()[0] == b'[' {
5698 let value_specified_index_end_index = full_format.find(']');
5699 let Some(value_specified_index_end_index) = value_specified_index_end_index else {
5700 return Err(FormatSequenceError::InvalidFormatSequence(Box::from("Missing closing bracket in size argument index")));
5701 };
5702
5703 let number = &full_format[1..value_specified_index_end_index];
5704 full_format = &full_format[value_specified_index_end_index + 1..];
5705
5706 for char in number.bytes() {
5707 if !char.is_ascii_digit() {
5708 return Err(FormatSequenceError::InvalidFormatSequence(Box::from("Invalid number in value index")));
5709 }
5710 }
5711 let number = usize::from_str(number).unwrap();
5712 if number >= full_argument_list.len() {
5713 return Err(FormatSequenceError::SpecifiedIndexOutOfBounds(Box::from("For value index")));
5714 }
5715
5716 Some(number)
5717 }else {
5718 None
5719 };
5720
5721 let mut size = if full_format.as_bytes()[0].is_ascii_digit() {
5722 let mut i = 0;
5723 while i < full_format.len() && full_format.as_bytes()[i].is_ascii_digit() {
5724 i += 1;
5725 }
5726
5727 let number = &full_format[..i];
5728 full_format = &full_format[i..];
5729
5730 Some(usize::from_str(number).unwrap())
5731 }else {
5732 None
5733 };
5734
5735 let decimal_places = full_format.as_bytes()[0] == b'.';
5736 let decimal_places_in_argument;
5737 let decimal_places_count_index;
5738 let mut decimal_places_count;
5739 if decimal_places {
5740 full_format = &full_format[1..];
5741 decimal_places_in_argument = full_format.as_bytes()[0] == b'*';
5742 if decimal_places_in_argument {
5743 full_format = &full_format[1..];
5744 }
5745
5746 decimal_places_count_index = if decimal_places_in_argument && full_format.as_bytes()[0] == b'[' {
5747 let decimal_places_count_index_end_index = full_format.find(']');
5748 let Some(decimal_places_count_index_end_index) = decimal_places_count_index_end_index else {
5749 return Err(FormatSequenceError::InvalidFormatSequence(Box::from("Missing closing bracket in decimal places index")));
5750 };
5751
5752 let number = &full_format[1..decimal_places_count_index_end_index];
5753 full_format = &full_format[decimal_places_count_index_end_index + 1..];
5754
5755 for char in number.bytes() {
5756 if !char.is_ascii_digit() {
5757 return Err(FormatSequenceError::InvalidFormatSequence(Box::from("Invalid number in decimal places index")));
5758 }
5759 }
5760 let number = usize::from_str(number).unwrap();
5761 if number >= full_argument_list.len() {
5762 return Err(FormatSequenceError::SpecifiedIndexOutOfBounds(Box::from("For decimal places index")));
5763 }
5764
5765 Some(number)
5766 }else {
5767 None
5768 };
5769
5770 decimal_places_count = if full_format.as_bytes()[0].is_ascii_digit() {
5771 let mut i = 0;
5772 while i < full_format.len() && full_format.as_bytes()[i].is_ascii_digit() {
5773 i += 1;
5774 }
5775
5776 let number = &full_format[..i];
5777 full_format = &full_format[i..];
5778
5779 Some(usize::from_str(number).unwrap())
5780 }else {
5781 None
5782 };
5783 }else {
5784 decimal_places_in_argument = false;
5785 decimal_places_count_index = None;
5786 decimal_places_count = None;
5787 }
5788
5789 if full_format.as_bytes()[0] != format_type {
5790 return Err(FormatSequenceError::InvalidFormatSequence(Box::from("Invalid characters")));
5791 }
5792
5793 if (size_in_argument && size.is_some()) || (decimal_places_in_argument && decimal_places_count.is_some()) || (left_justify && leading_zeros) {
5794 return Err(FormatSequenceError::InvalidFormatSequence(Box::from("Invalid format argument combinations")));
5795 }
5796
5797 if left_justify && (!size_in_argument && size.is_none()) {
5798 return Err(FormatSequenceError::InvalidFormatSequence(Box::from("Missing size format argument for leftJustify")));
5799 }
5800
5801 if matches!(
5803 format_type,
5804 b'n'
5805 ) && (value_specified_index.is_some() || size_in_argument || size.is_some()) {
5806 return Err(FormatSequenceError::InvalidFormatSequence(Box::from(format!("Value index and size can not be used with %{format_type}"))));
5807 }
5808
5809 if matches!(
5810 format_type,
5811 b'n' |
5812 b'c' | b'?' |
5813 b's' | b't'
5814 ) && (force_sign || sing_space || leading_zeros) {
5815 return Err(FormatSequenceError::InvalidFormatSequence(Box::from(format!("Force sign, space sing, and leading zeros can not be used with %{format_type}"))));
5816 }
5817
5818 if matches!(
5819 format_type,
5820 b'n' |
5821 b'c' | b'?' |
5822 b'b' | b'd' | b'o' | b'x'
5824 ) && decimal_places {
5825 return Err(FormatSequenceError::InvalidFormatSequence(Box::from(format!("Decimal places can not be used with %{format_type}"))));
5826 }
5827
5828 if size_in_argument {
5830 if size_argument_index.is_none() && argument_list.is_empty() {
5831 return Err(FormatSequenceError::InvalidArgCount(Box::from("Size argument missing")));
5832 }
5833
5834 let data_object = if let Some(size_argument_index) = size_argument_index {
5835 full_argument_list.get(size_argument_index).unwrap()
5836 }else {
5837 argument_list.pop_front().unwrap()
5838 };
5839
5840 let number = conversions::to_number(self, data_object, CodePosition::EMPTY);
5841 let Some(number) = number else {
5842 return Err(FormatSequenceError::InvalidArguments(Box::from("Invalid number for size from arguments")));
5843 };
5844
5845 let number = number.int_value();
5846 if number < 0 {
5847 return Err(FormatSequenceError::InvalidArguments(Box::from("Size must be >= 0")));
5848 }
5849
5850 size = Some(number as usize);
5851 }
5852 if decimal_places_in_argument {
5853 if decimal_places_count_index.is_none() && argument_list.is_empty() {
5854 return Err(FormatSequenceError::InvalidArgCount(Box::from("Decimal places argument missing")));
5855 }
5856
5857 let data_object = if let Some(decimal_places_count_index) = decimal_places_count_index {
5858 full_argument_list.get(decimal_places_count_index).unwrap()
5859 }else {
5860 argument_list.pop_front().unwrap()
5861 };
5862
5863 let number = conversions::to_number(self, data_object, CodePosition::EMPTY);
5864 let Some(number) = number else {
5865 return Err(FormatSequenceError::InvalidArguments(Box::from("Invalid number for decimal places from arguments")));
5866 };
5867
5868 let number = number.int_value();
5869 if number < 0 {
5870 return Err(FormatSequenceError::InvalidArguments(Box::from("Decimal places must be >= 0")));
5871 }
5872
5873 decimal_places_count = Some(number as usize);
5874 }
5875
5876 let output = if format_type == b'n' {
5877 Some(utils::LINE_SEPARATOR.to_string())
5878 }else {
5879 if value_specified_index.is_none() && argument_list.is_empty() {
5880 return Err(FormatSequenceError::InvalidArgCount(Box::from("Argument missing")));
5881 }
5882
5883 let data_object = if let Some(value_specified_index) = value_specified_index {
5884 full_argument_list.get(value_specified_index).unwrap()
5885 }else {
5886 argument_list.pop_front().unwrap()
5887 };
5888
5889 match format_type {
5890 b'd' => {
5891 let number = conversions::to_number(self, data_object, CodePosition::EMPTY);
5892 let Some(number) = number else {
5893 return Err(FormatSequenceError::InvalidArguments(Box::from(format!("Argument can not be converted to number which is required for %{format_type_char}"))));
5894 };
5895
5896 let mut output = format!("{}", number.long_value());
5897 if force_sign && output.as_bytes()[0] != b'-' {
5898 output = "+".to_string() + &output;
5899 }
5900
5901 if sing_space && !matches!(output.as_bytes()[0], b'+'| b'-') {
5902 output = " ".to_string() + &output;
5903 }
5904
5905 Some(output)
5906 },
5907
5908 b'b' => {
5909 let number = conversions::to_number(self, data_object, CodePosition::EMPTY);
5910 let Some(number) = number else {
5911 return Err(FormatSequenceError::InvalidArguments(Box::from(format!("Argument can not be converted to number which is required for %{format_type_char}"))));
5912 };
5913
5914 let sign = if number.long_value().is_negative() { "-" } else { "" };
5915 let number_abs = number.long_value().unsigned_abs();
5916
5917 let mut output = format!("{sign}{:b}", number_abs);
5918 if force_sign && output.as_bytes()[0] != b'-' {
5919 output = "+".to_string() + &output;
5920 }
5921
5922 if sing_space && !matches!(output.as_bytes()[0], b'+'| b'-') {
5923 output = " ".to_string() + &output;
5924 }
5925
5926 Some(output)
5927 },
5928
5929 b'o' => {
5930 let number = conversions::to_number(self, data_object, CodePosition::EMPTY);
5931 let Some(number) = number else {
5932 return Err(FormatSequenceError::InvalidArguments(Box::from(format!("Argument can not be converted to number which is required for %{format_type_char}"))));
5933 };
5934
5935 let sign = if number.long_value().is_negative() { "-" } else { "" };
5936 let number_abs = number.long_value().unsigned_abs();
5937
5938 let mut output = format!("{sign}{:o}", number_abs);
5939 if force_sign && output.as_bytes()[0] != b'-' {
5940 output = "+".to_string() + &output;
5941 }
5942
5943 if sing_space && !matches!(output.as_bytes()[0], b'+'| b'-') {
5944 output = " ".to_string() + &output;
5945 }
5946
5947 Some(output)
5948 },
5949
5950 b'x' => {
5951 let number = conversions::to_number(self, data_object, CodePosition::EMPTY);
5952 let Some(number) = number else {
5953 return Err(FormatSequenceError::InvalidArguments(Box::from(format!("Argument can not be converted to number which is required for %{format_type_char}"))));
5954 };
5955
5956 let sign = if number.long_value().is_negative() { "-" } else { "" };
5957 let number_abs = number.long_value().unsigned_abs();
5958
5959 let mut output = format!("{sign}{:X}", number_abs);
5960 if force_sign && output.as_bytes()[0] != b'-' {
5961 output = "+".to_string() + &output;
5962 }
5963
5964 if sing_space && !matches!(output.as_bytes()[0], b'+'| b'-') {
5965 output = " ".to_string() + &output;
5966 }
5967
5968 Some(output)
5969 },
5970
5971 b'f' => {
5972 let number = conversions::to_number(self, data_object, CodePosition::EMPTY);
5973 let Some(number) = number else {
5974 return Err(FormatSequenceError::InvalidArguments(Box::from(format!("Argument can not be converted to number which is required for %{format_type_char}"))));
5975 };
5976
5977 let value = number.double_value();
5978 if value.is_nan() {
5979 let mut output = "NaN".to_string();
5980 leading_zeros = false;
5981
5982 if force_sign || sing_space {
5983 output = " ".to_string() + &output;
5984 }
5985
5986 Some(output)
5987 }else if value.is_infinite() {
5988 let mut output = (if value == f64::NEG_INFINITY { "-" } else { "" }).to_string() + "Infinity";
5989 leading_zeros = false;
5990
5991 if force_sign && output.as_bytes()[0] != b'-' {
5992 output = "+".to_string() + &output;
5993 }
5994
5995 if sing_space && !matches!(output.as_bytes()[0], b'+'| b'-') {
5996 output = " ".to_string() + &output;
5997 }
5998
5999 Some(output)
6000 }else {
6001 let mut output = if let Some(decimal_places_count) = decimal_places_count {
6002 if decimal_places_count == 0 {
6003 value.round().to_string()
6004 }else {
6005 format!("{:.*}", decimal_places_count, value)
6006 }
6007 }else {
6008 let ret = value.to_string();
6009 if ret.contains(".") {
6010 ret
6011 }else {
6012 format!("{ret}.0")
6013 }
6014 };
6015
6016 if force_sign && output.as_bytes()[0] != b'-' {
6017 output = "+".to_string() + &output;
6018 }
6019
6020 if sing_space && !matches!(output.as_bytes()[0], b'+'| b'-') {
6021 output = " ".to_string() + &output;
6022 }
6023
6024 Some(output)
6025 }
6026 },
6027
6028 b'c' => {
6029 let number = conversions::to_number(self, data_object, CodePosition::EMPTY);
6030 let Some(number) = number else {
6031 return Err(FormatSequenceError::InvalidArguments(Box::from(format!("Argument can not be converted to number which is required for %{format_type_char}"))));
6032 };
6033
6034 let code_point = number.int_value() as u32;
6035 let char = char::from_u32(code_point).unwrap_or('\u{FFFD}');
6036
6037 Some(char.to_string())
6038 },
6039
6040 b's' => {
6041 let mut output = conversions::to_text(self, data_object, CodePosition::EMPTY).to_string();
6042
6043 if let Some(decimal_places_count) = decimal_places_count {
6044 let ret = utils::format_translation_template_pluralization(
6045 &output,
6046 decimal_places_count as i32,
6047 );
6048 match ret {
6049 Ok(ret) => output = ret,
6050
6051 Err(e) => {
6052 return Err(FormatSequenceError::TranslationInvalidPluralizationTemplate(Box::from(e.message())));
6053 },
6054 }
6055 }
6056
6057 Some(output)
6058 },
6059
6060 b't' => {
6061 let translation_key = conversions::to_text(self, data_object, CodePosition::EMPTY).to_string();
6062 let translation_value = self.data_ref().lang.get(&*translation_key).cloned();
6063
6064 let Some(output) = translation_value else {
6065 return Err(FormatSequenceError::TranslationKeyNotFound(Box::from(format!("For translation key \"{translation_key}\""))));
6066 };
6067
6068 let mut output = output.to_string();
6069
6070 if let Some(decimal_places_count) = decimal_places_count {
6071 let ret = utils::format_translation_template_pluralization(
6072 &output,
6073 decimal_places_count as i32,
6074 );
6075 match ret {
6076 Ok(ret) => output = ret,
6077
6078 Err(e) => {
6079 return Err(FormatSequenceError::TranslationInvalidPluralizationTemplate(Box::from(e.message())));
6080 },
6081 }
6082 }
6083
6084 Some(output)
6085 },
6086
6087 b'?' => {
6088 let output = conversions::to_bool(
6089 self,
6090 data_object,
6091 CodePosition::EMPTY,
6092 );
6093 let output = if output { "true" } else { "false" };
6094
6095 Some(output.to_string())
6096 },
6097
6098 _ => None,
6099 }
6100 };
6101
6102 if let Some(mut output) = output {
6103 if let Some(size) = size {
6104 if left_justify {
6105 if output.len() < size {
6106 output = format!("{1:<0$}", size, output);
6107 }
6108 }else if leading_zeros {
6109 let sign_output = if matches!(output.as_bytes()[0], b'+'| b'-' | b' ') {
6110 let sign_output = output.as_bytes()[0];
6111 output = output[1..].to_string();
6112
6113 sign_output
6114 }else {
6115 0
6116 };
6117
6118 let padding_size = size - if sign_output == 0 { 0 } else { 1 };
6119 output = format!("{1:0>0$}", padding_size, output);
6120
6121 if sign_output != 0 {
6122 output = (sign_output as char).to_string() + &output;
6123 }
6124 }else if output.len() < size {
6125 output = format!("{1:>0$}", size, output);
6126 }
6127 }
6128
6129 *builder += &output;
6130 };
6131
6132 Ok(min_end_index + 1)
6133 }
6134 fn format_text(&mut self, format: &str, argument_list: &[DataObjectRef]) -> DataObjectRef {
6140 let mut builder = String::new();
6141
6142 let mut full_argument_list = Vec::with_capacity(argument_list.len() + 1);
6143 full_argument_list.push(DataObjectRef::new(DataObject::new_text(format)));
6144 full_argument_list.extend_from_slice(argument_list);
6145
6146 let mut argument_list = VecDeque::from_iter(argument_list);
6147
6148 let mut i = 0;
6149 while i < format.len() {
6150 let percent_index = format[i..].find("%").
6151 map(|percent_index| percent_index + i);
6152 if let Some(percent_index) = percent_index {
6153 builder += &format[i..percent_index];
6154
6155 i = percent_index + 1;
6156
6157 if i == format.len() {
6158 return self.set_errno_error_object_error_only(
6159 InterpretingError::InvalidFormat,
6160 );
6161 }
6162
6163 if format.as_bytes()[i] == b'%' {
6164 builder.push('%');
6165
6166 i += 1;
6167
6168 continue;
6169 }
6170
6171 let ret = self.interpret_next_format_sequence(
6172 &format[i..],
6173 &mut builder,
6174 &mut argument_list,
6175 &full_argument_list,
6176 );
6177 match ret {
6178 Ok(char_count_used) => i += char_count_used,
6179
6180 Err(e) => {
6181 let (interpreting_error, message) = match e {
6182 FormatSequenceError::InvalidFormatSequence(message) => (InterpretingError::InvalidFormat, message),
6183 FormatSequenceError::InvalidArguments(message) => (InterpretingError::InvalidArguments, message),
6184 FormatSequenceError::InvalidArgCount(message) => (InterpretingError::InvalidArgCount, message),
6185 FormatSequenceError::TranslationKeyNotFound(message) => (InterpretingError::TransKeyNotFound, message),
6186 FormatSequenceError::SpecifiedIndexOutOfBounds(message) => (InterpretingError::IndexOutOfBounds, message),
6187 FormatSequenceError::TranslationInvalidPluralizationTemplate(message) => (InterpretingError::InvalidTemplateSyntax, message),
6188 };
6189
6190 return self.set_errno_error_object(
6191 interpreting_error,
6192 Some(&message),
6193 CodePosition::EMPTY,
6194 );
6195 },
6196 }
6197 }else {
6198 builder += &format[i..];
6199 break;
6200 }
6201 }
6202
6203 DataObjectRef::new(DataObject::new_text(builder))
6204 }
6205
6206 pub fn call_constructor(
6207 &mut self,
6208 lang_object: &LangObjectRef,
6209 argument_list: &[DataObjectRef],
6210 pos: CodePosition,
6211 ) -> DataObjectRef {
6212 let is_class = lang_object.borrow().is_class();
6213
6214 if is_class {
6215 let created_object = LangObject::new_object(lang_object).unwrap();
6216
6217 let constructors = created_object.borrow().constructors();
6218
6219 let ret = self.call_function_pointer(
6220 &constructors,
6221 constructors.function_name(),
6222 argument_list,
6223 pos,
6224 ).unwrap_or_else(|| DataObjectRef::new(DataObject::new_void()));
6225
6226 if ret.data_type() != DataType::VOID {
6227 return self.set_errno_error_object(
6228 InterpretingError::InvalidAstNode,
6229 Some("Invalid constructor implementation: VOID must be returned"),
6230 pos,
6231 );
6232 }
6233
6234 let ret = created_object.borrow_mut().post_construct();
6235 if let Err(e) = ret {
6236 return self.set_errno_error_object(
6237 InterpretingError::IncompatibleDataType,
6238 Some(&format!(
6239 "Invalid constructor implementation (Some members have invalid types): {}",
6240 e.message(),
6241 )),
6242 pos,
6243 );
6244 };
6245
6246 DataObjectRef::new(DataObject::with_update(|data_object| {
6247 data_object.set_object(created_object)
6248 }).unwrap())
6249 }else {
6250 if lang_object.borrow().is_initialized().unwrap() {
6251 return self.set_errno_error_object(
6252 InterpretingError::InvalidArguments,
6253 Some("Object is already initialized"),
6254 pos,
6255 );
6256 }
6257
6258 let constructors = lang_object.borrow().constructors_for_current_super_level();
6260
6261 let ret = self.call_function_pointer(
6262 &constructors,
6263 constructors.function_name(),
6264 argument_list,
6265 pos,
6266 ).unwrap_or_else(|| DataObjectRef::new(DataObject::new_void()));
6267
6268 if ret.data_type() != DataType::VOID {
6269 return self.set_errno_error_object(
6270 InterpretingError::InvalidAstNode,
6271 Some("Invalid constructor implementation: VOID must be returned"),
6272 pos,
6273 );
6274 }
6275
6276 ret
6277 }
6278 }
6279
6280 pub fn call_method(
6281 &mut self,
6282 lang_object: &LangObjectRef,
6283 raw_method_name: &str,
6284 argument_list: &[DataObjectRef],
6285 pos: CodePosition,
6286 ) -> OptionDataObjectRef {
6287 if raw_method_name.starts_with("fn.") || raw_method_name.starts_with("func.") ||
6288 raw_method_name.starts_with("ln.") || raw_method_name.starts_with("linker.") {
6289 return Some(self.set_errno_error_object(
6290 InterpretingError::InvalidArguments,
6291 Some(&format!("The method \"{raw_method_name}\" is not part of this object")),
6292 pos,
6293 ));
6294 }
6295
6296 let method_name = if lang_object.borrow().is_class() || raw_method_name.starts_with("fp.") {
6297 None
6298 }else if raw_method_name.starts_with("mp.") || raw_method_name.starts_with("op:") ||
6299 raw_method_name.starts_with("to:") {
6300 Some(raw_method_name.to_string())
6301 }else {
6302 Some("mp.".to_string() + raw_method_name)
6303 };
6304
6305 let fp = {
6306 let lang_object = lang_object.borrow();
6307 let methods = method_name.and_then(|method_name| lang_object.methods().
6308 get(&*method_name).cloned());
6309
6310 if let Some(methods) = methods {
6311 methods
6312 }else {
6313 if raw_method_name.starts_with("mp.") {
6314 return Some(self.set_errno_error_object(
6315 InterpretingError::InvalidArguments,
6316 Some(&format!("The method \"{raw_method_name}\" is not part of this object")),
6317 pos,
6318 ));
6319 }
6320
6321 let raw_method_name = if !raw_method_name.starts_with("fp.") &&
6322 !raw_method_name.starts_with("op:") &&
6323 !raw_method_name.starts_with("to:") {
6324 "fp.".to_string() + raw_method_name
6325 }else {
6326 raw_method_name.to_string()
6327 };
6328
6329
6330 let member = lang_object.static_member(&raw_method_name);
6331 let member = match member {
6332 Ok(member) => member,
6333
6334 Err(e) => {
6335 if lang_object.is_class() {
6336 return Some(self.set_errno_error_object(
6337 InterpretingError::IncompatibleDataType,
6338 Some(e.message()),
6339 pos,
6340 ));
6341 }
6342
6343 let member = lang_object.member(&raw_method_name);
6344
6345 match member {
6346 Ok(member) => member,
6347
6348 Err(e) => {
6349 return Some(self.set_errno_error_object(
6350 InterpretingError::IncompatibleDataType,
6351 Some(e.message()),
6352 pos,
6353 ));
6354 },
6355 }
6356 },
6357 };
6358
6359 if !member.is_accessible(self.current_call_stack_element().lang_class()) {
6360 return Some(self.set_errno_error_object(
6361 InterpretingError::MemberNotAccessible,
6362 Some(&format!("For member \"{raw_method_name}\"")),
6363 CodePosition::EMPTY,
6364 ));
6365 }
6366
6367 let Some(fp) = member.function_pointer_value() else {
6368 return Some(self.set_errno_error_object(
6369 InterpretingError::InvalidFuncPtr,
6370 Some(&format!("\"{raw_method_name}\": Function pointer is invalid")),
6371 pos,
6372 ));
6373 };
6374
6375 fp
6376 }
6377 };
6378
6379 self.call_function_pointer(&fp, Some(raw_method_name), argument_list, pos)
6380 }
6381
6382 pub fn call_super_constructor(
6383 &mut self,
6384 lang_object: &LangObjectRef,
6385 argument_list: &[DataObjectRef],
6386 pos: CodePosition,
6387 ) -> DataObjectRef {
6388 if lang_object.borrow().is_class() {
6389 return self.set_errno_error_object(
6390 InterpretingError::InvalidArguments,
6391 Some("Super constructor can not be called on class"),
6392 pos,
6393 );
6394 }
6395
6396 if lang_object.borrow().is_initialized().unwrap() {
6397 return self.set_errno_error_object(
6398 InterpretingError::InvalidArguments,
6399 Some("Object is already initialized"),
6400 pos,
6401 );
6402 }
6403
6404 let super_constructors = lang_object.borrow().super_constructors();
6405
6406 let super_constructors = FunctionPointerObject::copy_with_this_object(
6408 &super_constructors,
6409 lang_object.clone(),
6410 ).unwrap().copy_with_mapped_functions(|internal_function| internal_function.
6411 copy_with_super_level(
6412 internal_function.super_level().unwrap_or_default() +
6413 lang_object.borrow().super_level().unwrap() + 1,
6414 ));
6415
6416 let ret = self.call_function_pointer(
6417 &super_constructors,
6418 super_constructors.function_name(),
6419 argument_list,
6420 pos,
6421 ).unwrap_or_else(|| DataObjectRef::new(DataObject::new_void()));
6422
6423 if ret.data_type() != DataType::VOID {
6424 return self.set_errno_error_object(
6425 InterpretingError::InvalidAstNode,
6426 Some("Invalid constructor implementation: VOID must be returned"),
6427 pos,
6428 );
6429 }
6430
6431 ret
6432 }
6433
6434 pub fn call_super_method(
6435 &mut self,
6436 lang_object: &LangObjectRef,
6437 raw_method_name: &str,
6438 argument_list: &[DataObjectRef],
6439 pos: CodePosition,
6440 ) -> OptionDataObjectRef {
6441 if raw_method_name.starts_with("fp.") || raw_method_name.starts_with("fn.") ||
6442 raw_method_name.starts_with("func.") || raw_method_name.starts_with("ln.") ||
6443 raw_method_name.starts_with("linker.") {
6444 return Some(self.set_errno_error_object(
6445 InterpretingError::InvalidArguments,
6446 Some(&format!("The method \"{raw_method_name}\" is not part of this object")),
6447 pos,
6448 ));
6449 }
6450
6451 let method_name = if raw_method_name.starts_with("mp.") || raw_method_name.starts_with("op:") ||
6452 raw_method_name.starts_with("to:") {
6453 raw_method_name.to_string()
6454 }else {
6455 "mp.".to_string() + raw_method_name
6456 };
6457
6458 let methods = lang_object.borrow().super_methods().get(&*method_name).cloned();
6459 let Some(methods) = methods else {
6460 return Some(self.set_errno_error_object(
6461 InterpretingError::InvalidArguments,
6462 Some(&format!("The method \"{raw_method_name}\" is not in any super class of this object")),
6463 pos,
6464 ));
6465 };
6466
6467 let fp = FunctionPointerObject::copy_with_this_object(
6469 &methods,
6470 lang_object.clone(),
6471 ).unwrap().copy_with_mapped_functions(|internal_function| internal_function.
6472 copy_with_super_level(
6473 internal_function.super_level().unwrap_or_default() +
6474 lang_object.borrow().super_level().unwrap() + 1,
6475 ));
6476
6477 self.call_function_pointer(&fp, Some(raw_method_name), argument_list, pos)
6478 }
6479
6480 fn is_alpha_numeric_with_underline(token: &str) -> bool {
6484 if token.is_empty() {
6485 return false;
6486 }
6487
6488 for c in token.bytes() {
6489 if !c.is_ascii_alphanumeric() && c != b'_' {
6490 return false;
6491 }
6492 }
6493
6494 true
6495 }
6496
6497 fn is_lang_var_without_prefix(token: &str) -> bool {
6501 if token.is_empty() {
6502 return false;
6503 }
6504
6505 let first_char = token.as_bytes()[0];
6506 (first_char == b'$' || first_char == b'&') && token[1..].starts_with("LANG_")
6507 }
6508
6509 fn is_lang_var_or_lang_var_pointer_redirection_without_prefix(token: &str) -> bool {
6513 if token.is_empty() {
6514 return false;
6515 }
6516
6517 let first_char = token.as_bytes()[0];
6518 (first_char == b'$' || first_char == b'&') && (token[1..].starts_with("LANG_") || token.contains("[LANG_"))
6519 }
6520
6521 fn is_func_call_var_args(token: &str) -> bool {
6525 if token.is_empty() {
6526 return false;
6527 }
6528
6529 let first_char = token.as_bytes()[0];
6530 if !((first_char == b'$' || first_char == b'&') && token.ends_with("...")) {
6531 return false;
6532 }
6533
6534 let mut i = 1;
6535 let mut has_var_name = false;
6536 while i < token.len() - 3 {
6537 let c = token.as_bytes()[i];
6538 if c.is_ascii_alphanumeric() || c == b'_' {
6539 has_var_name = true;
6540 }else {
6541 return false;
6542 }
6543
6544 i += 1;
6545 }
6546
6547 has_var_name
6548 }
6549
6550 fn is_func_call_call_by_ptr(token: &str) -> bool {
6554 if !(token.starts_with("$[") && token.ends_with("]")) {
6555 return false;
6556 }
6557
6558 let mut i = 2;
6559 let mut has_var_name = false;
6560 while i < token.len() - 1 {
6561 let c = token.as_bytes()[i];
6562 if c.is_ascii_alphanumeric() || c == b'_' {
6563 has_var_name = true;
6564 }else {
6565 return false;
6566 }
6567
6568 i += 1;
6569 }
6570
6571 has_var_name
6572 }
6573
6574 fn is_func_call_call_by_ptr_lang_var(token: &str) -> bool {
6578 token.starts_with("$[LANG_") && token.ends_with("]")
6579 }
6580
6581 fn is_var_name_without_prefix(token: &str) -> bool {
6585 if token.is_empty() {
6586 return false;
6587 }
6588
6589 let is_func_ptr = token.starts_with("fp.");
6590
6591 let first_char = token.as_bytes()[0];
6592 if !(is_func_ptr || first_char == b'$' || first_char == b'&') {
6593 return false;
6594 }
6595
6596 let mut i = if is_func_ptr { 3 } else { 1 };
6597 let mut has_var_name = false;
6598 while i < token.len() {
6599 let c = token.as_bytes()[i];
6600 if c.is_ascii_alphanumeric() || c == b'_' {
6601 has_var_name = true;
6602 }else {
6603 return false;
6604 }
6605
6606 i += 1;
6607 }
6608
6609 has_var_name
6610 }
6611
6612 fn is_method_name(token: &str) -> bool {
6616 if !token.starts_with("mp.") {
6617 return false;
6618 }
6619
6620 let mut i = 3;
6621
6622 let mut has_var_name = false;
6623 while i < token.len() {
6624 let c = token.as_bytes()[i];
6625 if c.is_ascii_alphanumeric() || c == b'_' {
6626 has_var_name = true;
6627 }else {
6628 return false;
6629 }
6630
6631 i += 1;
6632 }
6633
6634 has_var_name
6635 }
6636
6637 const OPERATOR_METHOD_NAMES: [&'static str; 55] = [
6638 "op:len",
6639 "op:deepCopy",
6640 "op:inc",
6641 "op:dec",
6642 "op:pos",
6643 "op:inv",
6644 "op:not",
6645 "op:abs",
6646 "op:iter",
6647 "op:hasNext",
6648 "op:next",
6649
6650 "op:concat", "op:r-concat",
6651 "op:add", "op:r-add",
6652 "op:sub", "op:r-sub",
6653 "op:mul", "op:r-mul",
6654 "op:pow", "op:r-pow",
6655 "op:div", "op:r-div",
6656 "op:truncDiv", "op:r-truncDiv",
6657 "op:floorDiv", "op:r-floorDiv",
6658 "op:ceilDiv", "op:r-ceilDiv",
6659 "op:mod", "op:r-mod",
6660 "op:and", "op:r-and",
6661 "op:or", "op:r-or",
6662 "op:xor", "op:r-xor",
6663 "op:lshift", "op:r-lshift",
6664 "op:rshift", "op:r-rshift",
6665 "op:rzshift", "op:r-rzshift",
6666 "op:isEquals", "op:r-isEquals",
6667 "op:isStrictEquals", "op:r-isStrictEquals",
6668 "op:isLessThan", "op:r-isLessThan",
6669 "op:isGreaterThan", "op:r-isGreaterThan",
6670
6671 "op:getItem",
6672 "op:setItem",
6673 "op:slice",
6674
6675 "op:call",
6676 ];
6677 fn is_operator_method_name(token: &str) -> bool {
6683 Self::OPERATOR_METHOD_NAMES.contains(&token)
6684 }
6685
6686 const CONVERSION_METHOD_NAMES: [&'static str; 11] = [
6687 "to:text",
6688 "to:char",
6689 "to:int",
6690 "to:long",
6691 "to:float",
6692 "to:double",
6693 "to:byteBuffer",
6694 "to:array",
6695 "to:list",
6696
6697 "to:bool",
6698 "to:number",
6699 ];
6700 fn is_conversion_method_name(token: &str) -> bool {
6704 Self::CONVERSION_METHOD_NAMES.contains(&token)
6705 }
6706
6707 fn is_var_name_full_without_prefix(token: &str) -> bool {
6711 if token.is_empty() {
6712 return false;
6713 }
6714
6715 let func_ptr = token.starts_with("fp.");
6716 let first_char = token.as_bytes()[0];
6717 let normal_var = first_char == b'$';
6718
6719 if !(func_ptr || normal_var || first_char == b'&') {
6720 return false;
6721 }
6722
6723 let mut i = if func_ptr { 3 } else { 1 };
6724
6725 if normal_var {
6726 while i < token.len() {
6727 if token.as_bytes()[i] != b'*' {
6728 break;
6729 }
6730
6731 i += 1;
6732 }
6733 }
6734
6735 let mut has_var_name = false;
6736 while i < token.len() {
6737 let c = token.as_bytes()[i];
6738 if c.is_ascii_alphanumeric() || c == b'_' {
6739 has_var_name = true;
6740 }else {
6741 return false;
6742 }
6743
6744 i += 1;
6745 }
6746
6747 has_var_name
6748 }
6749
6750 fn is_var_name_full_with_funcs_without_prefix(token: &str) -> bool {
6754 if token.is_empty() {
6755 return false;
6756 }
6757
6758 let is_func_ptr = token.starts_with("fp.");
6759 let is_method_ptr = token.starts_with("mp.");
6760 let is_func = token.starts_with("func.");
6761 let is_fn = token.starts_with("fn.");
6762 let is_linker = token.starts_with("linker.");
6763 let is_ln = token.starts_with("ln.");
6764
6765 let first_char = token.as_bytes()[0];
6766 let normal_var = first_char == b'$';
6767
6768 if !(is_func_ptr || is_method_ptr || is_func || is_fn || is_linker || is_ln || normal_var || first_char == b'&') {
6769 return false;
6770 }
6771
6772 let mut i = if is_func_ptr || is_method_ptr || is_fn || is_ln { 3 } else if is_func { 5 } else if is_linker { 7 } else { 1 };
6773
6774 if normal_var {
6775 while i < token.len() {
6776 if token.as_bytes()[i] != b'*' {
6777 break;
6778 }
6779
6780 i += 1;
6781 }
6782 }
6783
6784 let mut has_var_name = false;
6785 while i < token.len() {
6786 let c = token.as_bytes()[i];
6787 if c.is_ascii_alphanumeric() || c == b'_' {
6788 has_var_name = true;
6789 }else {
6790 return false;
6791 }
6792
6793 i += 1;
6794 }
6795
6796 has_var_name
6797 }
6798
6799 fn is_var_name_ptr_and_dereference_without_prefix(token: &str) -> bool {
6803 if token.is_empty() {
6804 return false;
6805 }
6806
6807 if token.as_bytes()[0] != b'$' {
6808 return false;
6809 }
6810
6811 let mut i = 1;
6812 while i < token.len() {
6813 if token.as_bytes()[i] != b'*' {
6814 break;
6815 }
6816
6817 i += 1;
6818 }
6819
6820 let mut has_no_bracket_opening = true;
6821 while i < token.len() {
6822 if token.as_bytes()[i] == b'[' {
6823 has_no_bracket_opening = false;
6824 }else {
6825 break;
6826 }
6827
6828 i += 1;
6829 }
6830
6831 if has_no_bracket_opening {
6832 return false;
6833 }
6834
6835 let mut has_no_var_name = true;
6836 while i < token.len() {
6837 let c = token.as_bytes()[i];
6838 if c.is_ascii_alphanumeric() || c == b'_' {
6839 has_no_var_name = false;
6840 }else {
6841 break;
6842 }
6843
6844 i += 1;
6845 }
6846
6847 if has_no_var_name {
6848 return false;
6849 }
6850
6851 let mut has_bracket_closing = false;
6852 while i < token.len() {
6853 if token.as_bytes()[i] == b']' {
6854 has_bracket_closing = true;
6855 }else {
6856 return false;
6857 }
6858
6859 i += 1;
6860 }
6861
6862 has_bracket_closing
6863 }
6864
6865 fn is_func_name(token: &str) -> bool {
6869 let is_func = token.starts_with("func.");
6870 let is_linker = token.starts_with("linker.");
6871
6872 if !(is_func || is_linker || token.starts_with("fn.") || token.starts_with("ln.")) {
6873 return false;
6874 }
6875
6876 let mut i = if is_func { 5 } else if is_linker { 7 } else { 3 };
6877
6878 let mut has_var_name = false;
6879 while i < token.len() {
6880 let c = token.as_bytes()[i];
6881 if c.is_ascii_alphanumeric() || c == b'_' {
6882 has_var_name = true;
6883 }else {
6884 return false;
6885 }
6886
6887 i += 1;
6888 }
6889
6890 has_var_name
6891 }
6892
6893 fn is_var_name_func_ptr_without_prefix(token: &str) -> bool {
6897 if !token.starts_with("fp.") {
6898 return false;
6899 }
6900
6901 let mut i = 3;
6902
6903 let mut has_var_name = false;
6904 while i < token.len() {
6905 let c = token.as_bytes()[i];
6906 if c.is_ascii_alphanumeric() || c == b'_' {
6907 has_var_name = true;
6908 }else {
6909 return false;
6910 }
6911
6912 i += 1;
6913 }
6914
6915 has_var_name
6916 }
6917
6918 fn scope_id(&self) -> isize {
6919 self.scope_id
6920 }
6921
6922 fn init_lang_standard(&mut self) {
6923 if !self.is_initializing_lang_standard_implementation {
6924 panic!("Initialization of lang standard implementation was already completed");
6925 }
6926
6927 {
6929 predefined_functions::add_predefined_functions(&mut self.funcs);
6930 predefined_functions::add_predefined_linker_functions(&mut self.funcs);
6931 }
6932
6933 self.push_stack_element(
6935 StackElement::new(
6936 "<standard>",
6937 Some("standard.lang"),
6938 None,
6939 None,
6940 None,
6941 None,
6942 ),
6943 CodePosition::EMPTY,
6944 );
6945 self.enter_scope(None);
6946
6947 let ret = self.init_lang_standard_lang_code();
6948 if let Err(e) = ret {
6949 panic!("Could not load lang standard implementation in lang code: {e}")
6950 }
6951
6952 self.pop_stack_element();
6954
6955 self.exit_scope();
6956
6957 self.reset_parser_positional_vars();
6958
6959 self.is_initializing_lang_standard_implementation = false;
6960 }
6961
6962 fn init_lang_standard_lang_code(&mut self) -> Result<(), NativeError> {
6963 let file = Self::RESOURCES_DIR.
6964 get_file("lang/standard.lang").
6965 ok_or_else(|| NativeError::new(
6966 "The \"standard.lang\" file was not complied into executable!", None,
6967 ))?;
6968
6969 lang_vars::add_essential_lang_vars(self, None);
6970
6971 let lang_standard_implementation = String::from_utf8_lossy(file.contents());
6972
6973 self.interpret_lines(lang_standard_implementation);
6975
6976 let data = self.data().clone();
6977 for (variable_name, variable) in &data.borrow().var {
6978 if let Some(function_name) = variable_name.strip_prefix("fp.") {
6979 if let Some(function_value) = variable.function_pointer_value() {
6980 self.funcs.insert(Box::from(function_name), Gc::new(function_value.
6981 copy_with_function_name(&("func.".to_string() + function_name))));
6982 }
6983 }else if matches!(variable.data_type(), DataType::STRUCT | DataType::OBJECT) {
6984 self.standard_types.insert(Box::from(&**variable_name), variable.clone());
6985 }
6986 }
6987
6988 Ok(())
6989 }
6990
6991 fn enter_scope(&mut self, lang_args: Option<Vec<Box<str>>>) {
6992 self.scope_id += 1;
6993
6994 self.data.push(Rc::new(RefCell::new(Data::new())));
6995
6996 if let Some(lang_args) = lang_args {
6997 let lang_args = lang_args.into_iter().
6998 map(|arg| DataObjectRef::new(DataObject::new_text(arg))).
6999 collect::<Box<[_]>>();
7000
7001 self.data_mut().var.insert(Rc::from("&LANG_ARGS"), DataObjectRef::new(DataObject::with_update(|data_object| {
7002 data_object.set_array(lang_args).
7003 unwrap().set_final_data(true).
7004 set_variable_name(Some("&LANG_ARGS"))
7005 }).unwrap()));
7006 }
7007
7008 self.reset_vars_and_func_ptrs();
7009
7010 if self.scope_id > 0 {
7011 for (k, v) in &self.data[self.scope_id as usize - 1].clone().borrow().lang {
7013 if !k.starts_with("lang.") {
7014 self.data_mut().lang.insert(k.clone(), v.clone());
7015 }
7016 }
7017 }
7018 }
7019 fn reset_vars_and_func_ptrs(&mut self) {
7020 let lang_args = self.data_ref().var.get("&LANG_ARGS").cloned();
7021 self.data_mut().var.clear();
7022
7023 if self.is_initializing_lang_standard_implementation {
7024 lang_vars::add_essential_lang_vars(self, lang_args);
7025 }else {
7026 lang_vars::add_lang_vars(self, lang_args);
7027 }
7028 }
7029 fn reset_vars(&mut self) {
7030 self.data_mut().var.retain(|k, v| v.is_lang_var() &&
7031 (k.starts_with("$") || k.starts_with("&")));
7032
7033 self.set_errno(InterpretingError::NoError, None, CodePosition::EMPTY); }
7036
7037 fn exit_scope(&mut self) {
7038 if !self.is_initializing_lang_standard_implementation && self.scope_id == 0 {
7039 self.set_errno(
7040 InterpretingError::SystemError,
7041 Some("Main scope can not be exited"),
7042 CodePosition::EMPTY,
7043 );
7044
7045 return;
7046 }
7047
7048 self.data.remove(self.scope_id as usize);
7049
7050 self.scope_id -= 1;
7051 }
7052
7053 fn set_errno(
7054 &mut self,
7055 error: InterpretingError,
7056 message: Option<&str>,
7057 pos: CodePosition,
7058 ) {
7059 self.set_errno_internal(error, message, pos, false);
7060 }
7061
7062 fn set_errno_internal(
7063 &mut self,
7064 error: InterpretingError,
7065 message: Option<&str>,
7066 pos: CodePosition,
7067 force_no_error_output: bool,
7068 ) {
7069 let current_errno = self.data_ref().var["$LANG_ERRNO"].int_value().unwrap();
7070 let new_errno = error.error_code();
7071
7072 if new_errno >= 0 || current_errno < 1 {
7073 self.data_mut().var.get_mut("$LANG_ERRNO").unwrap().borrow_mut().set_int(new_errno).unwrap();
7074 }
7075
7076 if !force_no_error_output && self.execution_flags.error_output.should_print(new_errno) {
7077 let message = message.unwrap_or_default();
7078
7079 let current_stack_element = self.current_call_stack_element();
7080 let lang_path = current_stack_element.lang_path();
7081 let lang_file = current_stack_element.lang_file().unwrap_or("<shell>");
7082
7083 let lang_path_with_file = lang_path.to_string() + if lang_path.ends_with("/") {
7084 ""
7085 }else {
7086 "/"
7087 } + lang_file;
7088 let lang_function_name = current_stack_element.lang_function_name();
7089
7090 let output = format!(
7091 "A{} {} occurred in \"{}:{}\" (FUNCTION: \"{}\", SCOPE_ID: \"{}\")!\n{}: {} ({}){}\nStack trace:\n{}",
7092 if new_errno < 0 { "" } else { "n" },
7093 if new_errno < 0 { "warning" } else { "error" },
7094 lang_path_with_file,
7095 if pos == CodePosition::EMPTY {
7096 "x".to_string()
7097 }else {
7098 pos.to_compact_string()
7099 },
7100 lang_function_name.unwrap_or("<main>"),
7101 self.scope_id,
7102 if new_errno < 0 { "Warning" } else { "Error" },
7103 error.error_text(),
7104 error.error_code(),
7105 if message.is_empty() {
7106 String::new()
7107 }else {
7108 "\nMessage: ".to_string() + message
7109 },
7110 self.print_stack_trace(pos),
7111 );
7112
7113 if let Some(term) = &mut self.term {
7114 term.log(
7115 if new_errno < 0 { Level::Warning } else { Level::Error },
7116 output,
7117 Self::LOG_TAG,
7118 );
7119 }else {
7120 self.platform_api.println_error(&output);
7121 }
7122 }
7123
7124 if new_errno > 0 {
7125 self.execution_state.is_thrown_value = true;
7126
7127 if self.execution_state.try_block_level > 0 && (!self.execution_state.is_soft_try ||
7128 self.execution_state.try_body_scope_id == self.scope_id) {
7129 self.execution_state.try_thrown_error = Some(error);
7130 self.execution_state.stop_execution_flag = true;
7131 }
7132 }
7133 }
7134
7135 #[must_use]
7136 fn set_errno_error_object_error_only(
7137 &mut self,
7138 error: InterpretingError,
7139 ) -> DataObjectRef {
7140 self.set_errno_error_object(error, None, CodePosition::EMPTY)
7141 }
7142
7143 #[must_use]
7144 fn set_errno_error_object(
7145 &mut self,
7146 error: InterpretingError,
7147 message: Option<&str>,
7148 pos: CodePosition,
7149 ) -> DataObjectRef {
7150 self.set_errno_error_object_internal(error, message, pos, false)
7151 }
7152
7153 #[must_use]
7154 fn set_errno_error_object_internal(
7155 &mut self,
7156 error: InterpretingError,
7157 message: Option<&str>,
7158 pos: CodePosition,
7159 force_no_error_output: bool,
7160 ) -> DataObjectRef {
7161 self.set_errno_internal(error, message, pos, force_no_error_output);
7162
7163 DataObjectRef::new(DataObject::with_update(|data_object| {
7164 data_object.set_error(Gc::new(ErrorObject::new(error, message)))
7165 }).unwrap())
7166 }
7167
7168 fn get_and_clear_errno_error_object(&mut self) -> InterpretingError {
7169 let errno = self.data_ref().var["$LANG_ERRNO"].int_value().unwrap();
7170
7171 self.set_errno(InterpretingError::NoError, None, CodePosition::EMPTY); InterpretingError::get_error_from_error_code(errno)
7174 }
7175}
7176
7177#[derive(Debug, Clone, Eq, PartialEq, Hash)]
7178enum FormatSequenceError {
7179 InvalidFormatSequence(Box<str>),
7180 InvalidArguments(Box<str>),
7181 InvalidArgCount(Box<str>),
7182 TranslationKeyNotFound(Box<str>),
7183 SpecifiedIndexOutOfBounds(Box<str>),
7184 TranslationInvalidPluralizationTemplate(Box<str>),
7185}
7186
7187#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
7188pub enum InterpretingError {
7189 NoError,
7190
7191 FinalVarChange,
7193 ToManyInnerLinks,
7194 NoLangFile,
7195 FileNotFound,
7196 InvalidFuncPtr,
7197 StackOverflow,
7198 NoTerminal,
7199 InvalidArgCount,
7200 InvalidLogLevel,
7201 InvalidArrPtr,
7202 NoHexNum,
7203 NoChar,
7204 NoNum,
7205 DivByZero,
7206 NegativeArrayLen,
7207 EmptyArray,
7208 LengthNan,
7209 IndexOutOfBounds,
7210 ArgCountNotArrLen,
7211 InvalidFuncPtrLoop,
7212 InvalidArguments,
7213 FunctionNotFound,
7214 Eof,
7215 SystemError,
7216 NegativeRepeatCount,
7217 TransKeyNotFound,
7218 FunctionNotSupported,
7219 BracketMismatch,
7220 ContFlowArgMissing,
7221 InvalidAstNode,
7222 InvalidPtr,
7223 IncompatibleDataType,
7224 LangArraysCopy,
7225 LangVerError,
7226 InvalidConPart,
7227 InvalidFormat,
7228 InvalidAssignment,
7229 NoBinNum,
7230 NoOctNum,
7231 NoBaseNNum,
7232 InvalidNumberBase,
7233 InvalidRegexSyntax,
7234 InvalidTemplateSyntax,
7235 InvalidModule,
7236 ModuleLoadUnloadErr,
7237 MemberNotAccessible,
7238
7239 DeprecatedFuncCall,
7241 NoTerminalWarning,
7242 LangVerWarning,
7243 InvalidExecFlagData,
7244 VarShadowingWarning,
7245 UndefEscapeSequence,
7246 InvalidDocComment,
7247}
7248
7249impl InterpretingError {
7250 pub(crate) const VALUES: [InterpretingError; 54] = [
7251 Self::NoError,
7252
7253 Self::FinalVarChange,
7255 Self::ToManyInnerLinks,
7256 Self::NoLangFile,
7257 Self::FileNotFound,
7258 Self::InvalidFuncPtr,
7259 Self::StackOverflow,
7260 Self::NoTerminal,
7261 Self::InvalidArgCount,
7262 Self::InvalidLogLevel,
7263 Self::InvalidArrPtr,
7264 Self::NoHexNum,
7265 Self::NoChar,
7266 Self::NoNum,
7267 Self::DivByZero,
7268 Self::NegativeArrayLen,
7269 Self::EmptyArray,
7270 Self::LengthNan,
7271 Self::IndexOutOfBounds,
7272 Self::ArgCountNotArrLen,
7273 Self::InvalidFuncPtrLoop,
7274 Self::InvalidArguments,
7275 Self::FunctionNotFound,
7276 Self::Eof,
7277 Self::SystemError,
7278 Self::NegativeRepeatCount,
7279 Self::TransKeyNotFound,
7280 Self::FunctionNotSupported,
7281 Self::BracketMismatch,
7282 Self::ContFlowArgMissing,
7283 Self::InvalidAstNode,
7284 Self::InvalidPtr,
7285 Self::IncompatibleDataType,
7286 Self::LangArraysCopy,
7287 Self::LangVerError,
7288 Self::InvalidConPart,
7289 Self::InvalidFormat,
7290 Self::InvalidAssignment,
7291 Self::NoBinNum,
7292 Self::NoOctNum,
7293 Self::NoBaseNNum,
7294 Self::InvalidNumberBase,
7295 Self::InvalidRegexSyntax,
7296 Self::InvalidTemplateSyntax,
7297 Self::InvalidModule,
7298 Self::ModuleLoadUnloadErr,
7299 Self::MemberNotAccessible,
7300
7301 Self::DeprecatedFuncCall,
7303 Self::NoTerminalWarning,
7304 Self::LangVerWarning,
7305 Self::InvalidExecFlagData,
7306 Self::VarShadowingWarning,
7307 Self::UndefEscapeSequence,
7308 Self::InvalidDocComment,
7309 ];
7310
7311 pub fn name(&self) -> &'static str {
7312 match self {
7313 Self::NoError => "NO_ERROR",
7314
7315 Self::FinalVarChange => "FINAL_VAR_CHANGE",
7317 Self::ToManyInnerLinks => "TO_MANY_INNER_LINKS",
7318 Self::NoLangFile => "NO_LANG_FILE",
7319 Self::FileNotFound => "FILE_NOT_FOUND",
7320 Self::InvalidFuncPtr => "INVALID_FUNC_PTR",
7321 Self::StackOverflow => "STACK_OVERFLOW",
7322 Self::NoTerminal => "NO_TERMINAL",
7323 Self::InvalidArgCount => "INVALID_ARG_COUNT",
7324 Self::InvalidLogLevel => "INVALID_LOG_LEVEL",
7325 Self::InvalidArrPtr => "INVALID_ARR_PTR",
7326 Self::NoHexNum => "NO_HEX_NUM",
7327 Self::NoChar => "NO_CHAR",
7328 Self::NoNum => "NO_NUM",
7329 Self::DivByZero => "DIV_BY_ZERO",
7330 Self::NegativeArrayLen => "NEGATIVE_ARRAY_LEN",
7331 Self::EmptyArray => "EMPTY_ARRAY",
7332 Self::LengthNan => "LENGTH_NAN",
7333 Self::IndexOutOfBounds => "INDEX_OUT_OF_BOUNDS",
7334 Self::ArgCountNotArrLen => "ARG_COUNT_NOT_ARR_LEN",
7335 Self::InvalidFuncPtrLoop => "INVALID_FUNC_PTR_LOOP",
7336 Self::InvalidArguments => "INVALID_ARGUMENTS",
7337 Self::FunctionNotFound => "FUNCTION_NOT_FOUND",
7338 Self::Eof => "EOF",
7339 Self::SystemError => "SYSTEM_ERROR",
7340 Self::NegativeRepeatCount => "NEGATIVE_REPEAT_COUNT",
7341 Self::TransKeyNotFound => "TRANS_KEY_NOT_FOUND",
7342 Self::FunctionNotSupported => "FUNCTION_NOT_SUPPORTED",
7343 Self::BracketMismatch => "BRACKET_MISMATCH",
7344 Self::ContFlowArgMissing => "CONT_FLOW_ARG_MISSING",
7345 Self::InvalidAstNode => "INVALID_AST_NODE",
7346 Self::InvalidPtr => "INVALID_PTR",
7347 Self::IncompatibleDataType => "INCOMPATIBLE_DATA_TYPE",
7348 Self::LangArraysCopy => "LANG_ARRAYS_COPY",
7349 Self::LangVerError => "LANG_VER_ERROR",
7350 Self::InvalidConPart => "INVALID_CON_PART",
7351 Self::InvalidFormat => "INVALID_FORMAT",
7352 Self::InvalidAssignment => "INVALID_ASSIGNMENT",
7353 Self::NoBinNum => "NO_BIN_NUM",
7354 Self::NoOctNum => "NO_OCT_NUM",
7355 Self::NoBaseNNum => "NO_BASE_N_NUM",
7356 Self::InvalidNumberBase => "INVALID_NUMBER_BASE",
7357 Self::InvalidRegexSyntax => "INVALID_REGEX_SYNTAX",
7358 Self::InvalidTemplateSyntax => "INVALID_TEMPLATE_SYNTAX",
7359 Self::InvalidModule => "INVALID_MODULE",
7360 Self::ModuleLoadUnloadErr => "MODULE_LOAD_UNLOAD_ERR",
7361 Self::MemberNotAccessible => "MEMBER_NOT_ACCESSIBLE",
7362
7363 Self::DeprecatedFuncCall => "DEPRECATED_FUNC_CALL",
7365 Self::NoTerminalWarning => "NO_TERMINAL_WARNING",
7366 Self::LangVerWarning => "LANG_VER_WARNING",
7367 Self::InvalidExecFlagData => "INVALID_EXEC_FLAG_DATA",
7368 Self::VarShadowingWarning => "VAR_SHADOWING_WARNING",
7369 Self::UndefEscapeSequence => "UNDEF_ESCAPE_SEQUENCE",
7370 Self::InvalidDocComment => "INVALID_DOC_COMMENT",
7371 }
7372 }
7373
7374 pub fn error_code(&self) -> i32 {
7375 match self {
7376 Self::NoError => 0,
7377
7378 Self::FinalVarChange => 1,
7380 Self::ToManyInnerLinks => 2,
7381 Self::NoLangFile => 3,
7382 Self::FileNotFound => 4,
7383 Self::InvalidFuncPtr => 5,
7384 Self::StackOverflow => 6,
7385 Self::NoTerminal => 7,
7386 Self::InvalidArgCount => 8,
7387 Self::InvalidLogLevel => 9,
7388 Self::InvalidArrPtr => 10,
7389 Self::NoHexNum => 11,
7390 Self::NoChar => 12,
7391 Self::NoNum => 13,
7392 Self::DivByZero => 14,
7393 Self::NegativeArrayLen => 15,
7394 Self::EmptyArray => 16,
7395 Self::LengthNan => 17,
7396 Self::IndexOutOfBounds => 18,
7397 Self::ArgCountNotArrLen => 19,
7398 Self::InvalidFuncPtrLoop => 20,
7399 Self::InvalidArguments => 21,
7400 Self::FunctionNotFound => 22,
7401 Self::Eof => 23,
7402 Self::SystemError => 24,
7403 Self::NegativeRepeatCount => 25,
7404 Self::TransKeyNotFound => 26,
7405 Self::FunctionNotSupported => 27,
7406 Self::BracketMismatch => 28,
7407 Self::ContFlowArgMissing => 29,
7408 Self::InvalidAstNode => 30,
7409 Self::InvalidPtr => 31,
7410 Self::IncompatibleDataType => 32,
7411 Self::LangArraysCopy => 33,
7412 Self::LangVerError => 34,
7413 Self::InvalidConPart => 35,
7414 Self::InvalidFormat => 36,
7415 Self::InvalidAssignment => 37,
7416 Self::NoBinNum => 38,
7417 Self::NoOctNum => 39,
7418 Self::NoBaseNNum => 40,
7419 Self::InvalidNumberBase => 41,
7420 Self::InvalidRegexSyntax => 42,
7421 Self::InvalidTemplateSyntax => 43,
7422 Self::InvalidModule => 44,
7423 Self::ModuleLoadUnloadErr => 45,
7424 Self::MemberNotAccessible => 46,
7425
7426 Self::DeprecatedFuncCall => -1,
7428 Self::NoTerminalWarning => -2,
7429 Self::LangVerWarning => -3,
7430 Self::InvalidExecFlagData => -4,
7431 Self::VarShadowingWarning => -5,
7432 Self::UndefEscapeSequence => -6,
7433 Self::InvalidDocComment => -7,
7434 }
7435 }
7436
7437 pub fn error_text(&self) -> &'static str {
7438 match self {
7439 Self::NoError => "No Error",
7440
7441 Self::FinalVarChange => "LANG or final vars must not be changed",
7443 Self::ToManyInnerLinks => "To many inner links",
7444 Self::NoLangFile => "No .lang-File",
7445 Self::FileNotFound => "File not found",
7446 Self::InvalidFuncPtr => "Function pointer is invalid",
7447 Self::StackOverflow => "Stack overflow",
7448 Self::NoTerminal => "No terminal available",
7449 Self::InvalidArgCount => "Invalid argument count",
7450 Self::InvalidLogLevel => "Invalid log level",
7451 Self::InvalidArrPtr => "Invalid array pointer",
7452 Self::NoHexNum => "No hexadecimal number",
7453 Self::NoChar => "No char",
7454 Self::NoNum => "No number",
7455 Self::DivByZero => "Dividing by 0",
7456 Self::NegativeArrayLen => "Negative array length",
7457 Self::EmptyArray => "Empty array",
7458 Self::LengthNan => "Length NAN",
7459 Self::IndexOutOfBounds => "Index out of bounds",
7460 Self::ArgCountNotArrLen => "Argument count is not array length",
7461 Self::InvalidFuncPtrLoop => "Invalid function pointer",
7462 Self::InvalidArguments => "Invalid arguments",
7463 Self::FunctionNotFound => "Function not found",
7464 Self::Eof => "End of file was reached early",
7465 Self::SystemError => "System Error",
7466 Self::NegativeRepeatCount => "Negative repeat count",
7467 Self::TransKeyNotFound => "Translation key does not exist",
7468 Self::FunctionNotSupported => "Function not supported",
7469 Self::BracketMismatch => "Bracket mismatch",
7470 Self::ContFlowArgMissing => "Control flow statement condition(s) or argument(s) is/are missing",
7471 Self::InvalidAstNode => "Invalid AST node or AST node order",
7472 Self::InvalidPtr => "Invalid pointer",
7473 Self::IncompatibleDataType => "Incompatible data type",
7474 Self::LangArraysCopy => "&LANG arrays can not be copied",
7475 Self::LangVerError => "Lang file's version is not compatible with this version",
7476 Self::InvalidConPart => "Invalid statement in control flow statement",
7477 Self::InvalidFormat => "Invalid format sequence",
7478 Self::InvalidAssignment => "Invalid assignment",
7479 Self::NoBinNum => "No binary number",
7480 Self::NoOctNum => "No octal number",
7481 Self::NoBaseNNum => "Number is not in base N",
7482 Self::InvalidNumberBase => "Invalid number base",
7483 Self::InvalidRegexSyntax => "Invalid RegEx syntax",
7484 Self::InvalidTemplateSyntax => "Invalid translation template syntax",
7485 Self::InvalidModule => "The Lang module is invalid",
7486 Self::ModuleLoadUnloadErr => "Error during load or unload of Lang module",
7487 Self::MemberNotAccessible => "The class/object member is not visible/accessible from the current scope",
7488
7489 Self::DeprecatedFuncCall => "A deprecated predefined function was called",
7491 Self::NoTerminalWarning => "No terminal available",
7492 Self::LangVerWarning => "Lang file's version is not compatible with this version",
7493 Self::InvalidExecFlagData => "Execution flag or Lang data is invalid",
7494 Self::VarShadowingWarning => "Variable name shadows an other variable",
7495 Self::UndefEscapeSequence => "An undefined escape sequence was used",
7496 Self::InvalidDocComment => "Dangling or invalid doc comment syntax",
7497 }
7498 }
7499
7500 pub fn get_error_from_error_code(error_code: i32) -> Self {
7501 match error_code {
7502 0 => Self::NoError,
7503
7504 1 => Self::FinalVarChange,
7506 2 => Self::ToManyInnerLinks,
7507 3 => Self::NoLangFile,
7508 4 => Self::FileNotFound,
7509 5 => Self::InvalidFuncPtr,
7510 6 => Self::StackOverflow,
7511 7 => Self::NoTerminal,
7512 8 => Self::InvalidArgCount,
7513 9 => Self::InvalidLogLevel,
7514 10 => Self::InvalidArrPtr,
7515 11 => Self::NoHexNum,
7516 12 => Self::NoChar,
7517 13 => Self::NoNum,
7518 14 => Self::DivByZero,
7519 15 => Self::NegativeArrayLen,
7520 16 => Self::EmptyArray,
7521 17 => Self::LengthNan,
7522 18 => Self::IndexOutOfBounds,
7523 19 => Self::ArgCountNotArrLen,
7524 20 => Self::InvalidFuncPtrLoop,
7525 21 => Self::InvalidArguments,
7526 22 => Self::FunctionNotFound,
7527 23 => Self::Eof,
7528 24 => Self::SystemError,
7529 25 => Self::NegativeRepeatCount,
7530 26 => Self::TransKeyNotFound,
7531 27 => Self::FunctionNotSupported,
7532 28 => Self::BracketMismatch,
7533 29 => Self::ContFlowArgMissing,
7534 30 => Self::InvalidAstNode,
7535 31 => Self::InvalidPtr,
7536 32 => Self::IncompatibleDataType,
7537 33 => Self::LangArraysCopy,
7538 34 => Self::LangVerError,
7539 35 => Self::InvalidConPart,
7540 36 => Self::InvalidFormat,
7541 37 => Self::InvalidAssignment,
7542 38 => Self::NoBinNum,
7543 39 => Self::NoOctNum,
7544 40 => Self::NoBaseNNum,
7545 41 => Self::InvalidNumberBase,
7546 42 => Self::InvalidRegexSyntax,
7547 43 => Self::InvalidTemplateSyntax,
7548 44 => Self::InvalidModule,
7549 45 => Self::ModuleLoadUnloadErr,
7550 46 => Self::MemberNotAccessible,
7551
7552 -1 => Self::DeprecatedFuncCall,
7554 -2 => Self::NoTerminalWarning,
7555 -3 => Self::LangVerWarning,
7556 -4 => Self::InvalidExecFlagData,
7557 -5 => Self::VarShadowingWarning,
7558 -6 => Self::UndefEscapeSequence,
7559 -7 => Self::InvalidDocComment,
7560
7561 _ => Self::NoError,
7562 }
7563 }
7564}
7565
7566#[derive(Debug)]
7567pub struct Data {
7568 lang: AHashMap<Rc<str>, Rc<str>>,
7569 var: AHashMap<Rc<str>, DataObjectRef>,
7570}
7571
7572impl Data {
7573 fn new() -> Self {
7574 Self {
7575 lang: AHashMap::new(),
7576 var: AHashMap::new(),
7577 }
7578 }
7579
7580 pub fn lang(&self) -> &AHashMap<Rc<str>, Rc<str>> {
7581 &self.lang
7582 }
7583
7584 pub fn var(&self) -> &AHashMap<Rc<str>, DataObjectRef> {
7585 &self.var
7586 }
7587}
7588
7589#[derive(Debug, Clone)]
7590pub struct StackElement {
7591 lang_path: Box<str>,
7592 lang_file: Option<Box<str>>,
7593 pos: CodePosition,
7594 lang_class: OptionLangObjectRef,
7595 lang_class_name: Option<Box<str>>,
7596 lang_function_name: Option<Box<str>>,
7597 module: Option<Rc<Module>>,
7598}
7599
7600impl StackElement {
7601 pub fn new(
7602 lang_path: &str,
7603 lang_file: Option<&str>,
7604 lang_class: OptionLangObjectRef,
7605 lang_class_name: Option<&str>,
7606 lang_function_name: Option<&str>,
7607 module: Option<Rc<Module>>,
7608 ) -> Self {
7609 Self {
7610 lang_path: Box::from(lang_path),
7611 lang_file: lang_file.map(Box::from),
7612 pos: CodePosition::EMPTY,
7613 lang_class,
7614 lang_class_name: lang_class_name.map(Box::from),
7615 lang_function_name: lang_function_name.map(Box::from),
7616 module,
7617 }
7618 }
7619
7620 #[must_use]
7621 pub fn copy_with_pos(&self, pos: CodePosition) -> Self {
7622 Self {
7623 lang_path: self.lang_path.clone(),
7624 lang_file: self.lang_file.clone(),
7625 pos,
7626 lang_class: self.lang_class.clone(),
7627 lang_class_name: self.lang_class_name.clone(),
7628 lang_function_name: self.lang_function_name.clone(),
7629 module: self.module.clone(),
7630 }
7631 }
7632
7633 pub fn lang_path(&self) -> &str {
7634 &self.lang_path
7635 }
7636
7637 pub fn lang_file(&self) -> Option<&str> {
7638 self.lang_file.as_deref()
7639 }
7640
7641 pub fn pos(&self) -> CodePosition {
7642 self.pos
7643 }
7644
7645 pub fn lang_class(&self) -> Option<&LangObjectRef> {
7646 self.lang_class.as_ref()
7647 }
7648
7649 pub fn lang_class_name(&self) -> Option<&str> {
7650 self.lang_class_name.as_deref()
7651 }
7652
7653 pub fn lang_function_name(&self) -> Option<&str> {
7654 self.lang_function_name.as_deref()
7655 }
7656
7657 pub fn module(&self) -> Option<Rc<Module>> {
7658 self.module.clone()
7659 }
7660}
7661
7662impl Display for StackElement {
7663 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
7664 let lang_path_with_file = format!(
7665 "{}{}{}",
7666 self.lang_path,
7667 if self.lang_path.ends_with("/") { "" } else { "/" },
7668 if let Some(lang_file) = &self.lang_file {
7669 lang_file
7670 }else {
7671 "<shell>"
7672 },
7673 );
7674
7675 write!(
7676 f, " at \"{}:{}\" in {} \"{}\"",
7677 lang_path_with_file,
7678 if self.pos == CodePosition::EMPTY { "x".to_string() } else { self.pos.to_compact_string() },
7679 if self.lang_class_name.is_some() {
7680 "method"
7681 }else {
7682 "function"
7683 },
7684 if let Some(lang_function_name) = &self.lang_function_name {
7685 if let Some(lang_class_name) = &self.lang_class_name {
7686 format!("{}::{}", lang_class_name, lang_function_name)
7687 }else {
7688 lang_function_name.to_string()
7689 }
7690 }else {
7691 "<main>".to_string()
7692 },
7693 )
7694 }
7695}
7696
7697#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash, Default)]
7698#[repr(u8)]
7699pub enum ErrorOutputFlag {
7700 Nothing,
7701 All,
7702 #[default]
7703 ErrorOnly,
7704}
7705
7706impl ErrorOutputFlag {
7707 pub fn get_error_flag_for(number: i32) -> Self {
7708 match number {
7709 0 => Self::Nothing,
7710 1.. => Self::All,
7711 ..=-1 => Self::ErrorOnly,
7712 }
7713 }
7714
7715 pub fn should_print(self, error_code: i32) -> bool {
7716 (error_code < 0 && self == Self::All) || (error_code > 0 && self != Self::Nothing)
7717 }
7718}
7719
7720#[derive(Debug)]
7721struct ExecutionFlags {
7722 allow_term_redirect: bool,
7726 error_output: ErrorOutputFlag,
7730 lang_test: bool,
7734 raw_variable_names: bool,
7738 native_stack_traces: bool,
7742}
7743
7744impl ExecutionFlags {
7745 pub fn new() -> Self {
7746 Self {
7747 allow_term_redirect: true,
7748 error_output: ErrorOutputFlag::ErrorOnly,
7749 lang_test: false,
7750 raw_variable_names: false,
7751 native_stack_traces: false,
7752 }
7753 }
7754}
7755
7756#[derive(Debug)]
7757struct ExecutionState {
7758 stop_execution_flag: bool,
7762 #[expect(dead_code)]
7763 force_stop_execution_flag: bool,
7764
7765 returned_or_thrown_value: OptionDataObjectRef,
7767 is_thrown_value: bool,
7768 return_or_throw_statement_pos: CodePosition,
7769
7770 break_continue_count: u32,
7775 is_continue_statement: bool,
7776
7777 try_block_level: u32,
7782 try_thrown_error: Option<InterpretingError>,
7783 is_soft_try: bool,
7784 try_body_scope_id: isize,
7785}
7786
7787impl ExecutionState {
7788 pub fn new() -> Self {
7789 Self {
7790 stop_execution_flag: false,
7791 force_stop_execution_flag: false,
7792
7793 returned_or_thrown_value: None,
7794 is_thrown_value: false,
7795 return_or_throw_statement_pos: CodePosition::EMPTY,
7796
7797 break_continue_count: 0,
7798 is_continue_statement: false,
7799
7800 try_block_level: 0,
7801 try_thrown_error: None,
7802 is_soft_try: false,
7803 try_body_scope_id: 0,
7804 }
7805 }
7806}