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