1pub mod function;
2pub mod object;
3
4use std::collections::{HashSet, VecDeque};
5use std::error::Error;
6use std::fmt::{Debug, Display, Formatter, Write as _};
7use std::ops::Deref;
8use std::rc::Rc;
9use std::sync::LazyLock;
10use gc::{Finalize, Gc, GcCell, Trace};
11use crate::interpreter::data::function::FunctionPointerObject;
12use crate::interpreter::data::object::LangObject;
13use crate::interpreter::InterpretingError;
14
15pub type OptionDataObjectRef = Option<DataObjectRef>;
16
17pub type LangObjectRef = Gc<GcCell<LangObject>>;
18pub type OptionLangObjectRef = Option<LangObjectRef>;
19
20pub type FunctionPointerObjectRef = Gc<FunctionPointerObject>;
21
22#[derive(Clone, Copy, Eq, PartialEq, Hash)]
23pub struct DataType(u8);
24
25impl DataType {
26 pub const TEXT: DataType = Self(0);
27 pub const CHAR: DataType = Self(1);
28 pub const INT: DataType = Self(2);
29 pub const LONG: DataType = Self(3);
30 pub const FLOAT: DataType = Self(4);
31 pub const DOUBLE: DataType = Self(5);
32 pub const BYTE_BUFFER: DataType = Self(6);
33 pub const ARRAY: DataType = Self(7);
34 pub const LIST: DataType = Self(8);
35 pub const VAR_POINTER: DataType = Self(9);
36 pub const FUNCTION_POINTER: DataType = Self(10);
37 pub const STRUCT: DataType = Self(11);
38 pub const OBJECT: DataType = Self(12);
39 pub const ERROR: DataType = Self(13);
40 pub const NULL: DataType = Self(14);
41 pub const VOID: DataType = Self(15);
42 pub const ARGUMENT_SEPARATOR: DataType = Self(16);
43 pub const TYPE: DataType = Self(17);
44
45 pub(crate) const VALUES: [DataType; 18] = [
46 Self::TEXT, Self::CHAR, Self::INT, Self::LONG, Self::FLOAT, Self::DOUBLE, Self::BYTE_BUFFER,
47 Self::ARRAY, Self::LIST, Self::VAR_POINTER, Self::FUNCTION_POINTER, Self::STRUCT, Self::OBJECT,
48 Self::ERROR, Self::NULL, Self::VOID, Self::ARGUMENT_SEPARATOR, Self::TYPE,
49 ];
50
51 pub fn from_string(str: &str) -> Option<Self> {
52 match str {
53 "TEXT" => Some(Self::TEXT),
54 "CHAR" => Some(Self::CHAR),
55 "INT" => Some(Self::INT),
56 "LONG" => Some(Self::LONG),
57 "FLOAT" => Some(Self::FLOAT),
58 "DOUBLE" => Some(Self::DOUBLE),
59 "BYTE_BUFFER" => Some(Self::BYTE_BUFFER),
60 "ARRAY" => Some(Self::ARRAY),
61 "LIST" => Some(Self::LIST),
62 "VAR_POINTER" => Some(Self::VAR_POINTER),
63 "FUNCTION_POINTER" => Some(Self::FUNCTION_POINTER),
64 "STRUCT" => Some(Self::STRUCT),
65 "OBJECT" => Some(Self::OBJECT),
66 "ERROR" => Some(Self::ERROR),
67 "NULL" => Some(Self::NULL),
68 "VOID" => Some(Self::VOID),
69 "ARGUMENT_SEPARATOR" => Some(Self::ARGUMENT_SEPARATOR),
70 "TYPE" => Some(Self::TYPE),
71
72 _ => None,
73 }
74 }
75
76 fn type_name(&self) -> &'static str {
77 match *self {
78 Self::TEXT => "TEXT",
79 Self::CHAR => "CHAR",
80 Self::INT => "INT",
81 Self::LONG => "LONG",
82 Self::FLOAT => "FLOAT",
83 Self::DOUBLE => "DOUBLE",
84 Self::BYTE_BUFFER => "BYTE_BUFFER",
85 Self::ARRAY => "ARRAY",
86 Self::LIST => "LIST",
87 Self::VAR_POINTER => "VAR_POINTER",
88 Self::FUNCTION_POINTER => "FUNCTION_POINTER",
89 Self::STRUCT => "STRUCT",
90 Self::OBJECT => "OBJECT",
91 Self::ERROR => "ERROR",
92 Self::NULL => "NULL",
93 Self::VOID => "VOID",
94 Self::ARGUMENT_SEPARATOR => "ARGUMENT_SEPARATOR",
95 Self::TYPE => "TYPE",
96
97 _ => "invalid"
98 }
99 }
100
101 pub const fn lang_type_id(&self) -> u8 {
102 self.0
103 }
104}
105
106impl Debug for DataType {
107 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
108 f.write_str(self.type_name())
109 }
110}
111
112impl Display for DataType {
113 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
114 f.write_str(self.type_name())
115 }
116}
117
118#[derive(Debug, Clone, Eq)]
119pub struct DataTypeConstraint {
120 types: HashSet<DataType>,
121 allowed: bool,
122}
123
124impl DataTypeConstraint {
125 pub fn from_allowed_types(allowed_types: &[DataType]) -> Self {
126 Self {
127 types: HashSet::from_iter(allowed_types.iter().copied()),
128 allowed: true,
129 }
130 }
131
132 pub fn from_not_allowed_types(not_allowed_types: &[DataType]) -> Self {
133 Self {
134 types: HashSet::from_iter(not_allowed_types.iter().copied()),
135 allowed: false,
136 }
137 }
138
139 pub fn from_single_allowed_type(allowed_type: DataType) -> Self {
140 Self {
141 types: HashSet::from([allowed_type]),
142 allowed: true,
143 }
144 }
145
146 pub fn is_type_allowed(&self, data_type: DataType) -> bool {
147 self.types.contains(&data_type) == self.allowed
148 }
149
150 pub fn allowed_types(&self) -> Vec<DataType> {
151 if self.allowed {
152 Vec::from_iter(self.types.iter().copied())
153 }else {
154 Vec::from_iter(
155 DataType::VALUES.iter().
156 filter(|data_type| !self.types.contains(data_type)).
157 copied(),
158 )
159 }
160 }
161
162 pub fn not_allowed_types(&self) -> Vec<DataType> {
163 if self.allowed {
164 Vec::from_iter(
165 DataType::VALUES.iter().
166 filter(|data_type| !self.types.contains(data_type)).
167 copied(),
168 )
169 }else {
170 Vec::from_iter(self.types.iter().copied())
171 }
172 }
173
174 pub fn to_type_constraint_syntax(&self) -> String {
175 let mut builder = String::new();
176 builder += "{";
177
178 let inverted = !self.allowed ^ self.types.is_empty();
180 if inverted {
181 builder += "!";
182 }
183
184 let mut types = if self.types.is_empty() {
185 HashSet::from(DataType::VALUES)
186 }else {
187 self.types.clone()
188 };
189
190 if !inverted && types.len() > 1 && types.contains(&DataType::NULL) {
191 types.remove(&DataType::NULL);
192
193 builder += "?";
194 }
195
196 for data_type in types {
197 let _ = write!(builder, "{data_type}|");
198 }
199
200 builder = builder[..builder.len() - 1].to_string();
201
202 builder += "}";
203 builder
204 }
205}
206
207impl PartialEq for DataTypeConstraint {
208 fn eq(&self, other: &Self) -> bool {
209 self.allowed_types() == other.allowed_types()
210 }
211}
212
213impl Display for DataTypeConstraint {
214 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
215 write!(
216 f,
217 "{}[{}]",
218 if self.allowed {
219 "= "
220 }else {
221 "! "
222 },
223 self.types.iter().
224 map(|ele| ele.to_string()).
225 collect::<Vec<_>>().
226 join(", "),
227 )
228 }
229}
230
231pub static CONSTRAINT_NORMAL: LazyLock<DataTypeConstraint, fn() -> DataTypeConstraint> =
232 LazyLock::new(|| DataTypeConstraint::from_not_allowed_types(&[]));
233
234pub static CONSTRAINT_COMPOSITE: LazyLock<DataTypeConstraint, fn() -> DataTypeConstraint> =
235 LazyLock::new(|| DataTypeConstraint::from_allowed_types(&[
236 DataType::ARRAY, DataType::LIST, DataType::STRUCT, DataType::OBJECT, DataType::NULL,
237 ]));
238
239pub static CONSTRAINT_FUNCTION_POINTER: LazyLock<DataTypeConstraint, fn() -> DataTypeConstraint> =
240 LazyLock::new(|| DataTypeConstraint::from_allowed_types(&[
241 DataType::FUNCTION_POINTER, DataType::NULL,
242 ]));
243
244#[repr(u8)]
245#[derive(Debug, Clone, Trace, Finalize)]
246pub enum DataValue {
247 Text(Rc<str>),
248 Char(char),
249 Int(i32),
250 Long(i64),
251 Float(f32),
252 Double(f64),
253 ByteBuffer(Gc<GcCell<Box<[u8]>>>),
254 Array(Gc<GcCell<Box<[DataObjectRef]>>>),
255 List(Gc<GcCell<VecDeque<DataObjectRef>>>),
256 VarPointer(DataObjectRef),
257 FunctionPointer(FunctionPointerObjectRef),
258 Struct(Gc<StructObject>),
259 Object(LangObjectRef),
260 Error(Gc<ErrorObject>),
261 Null,
262 Void,
263 ArgumentSeparator(Rc<str>),
264 Type(#[unsafe_ignore_trace] DataType),
266}
267
268impl DataValue {
269 pub const fn data_type(&self) -> DataType {
270 match self {
271 DataValue::Text(..) => DataType::TEXT,
272 DataValue::Char(..) => DataType::CHAR,
273 DataValue::Int(..) => DataType::INT,
274 DataValue::Long(..) => DataType::LONG,
275 DataValue::Float(..) => DataType::FLOAT,
276 DataValue::Double(..) => DataType::DOUBLE,
277 DataValue::ByteBuffer(..) => DataType::BYTE_BUFFER,
278 DataValue::Array(..) => DataType::ARRAY,
279 DataValue::List(..) => DataType::LIST,
280 DataValue::VarPointer(..) => DataType::VAR_POINTER,
281 DataValue::FunctionPointer(..) => DataType::FUNCTION_POINTER,
282 DataValue::Struct(..) => DataType::STRUCT,
283 DataValue::Object(..) => DataType::OBJECT,
284 DataValue::Error(..) => DataType::ERROR,
285 DataValue::Null => DataType::NULL,
286 DataValue::Void => DataType::VOID,
287 DataValue::ArgumentSeparator(..) => DataType::ARGUMENT_SEPARATOR,
288 DataValue::Type(..) => DataType::TYPE,
289 }
290 }
291
292 pub const fn is_of_type(&self, data_type: DataType) -> bool {
293 self.data_type().0 == data_type.0
294 }
295}
296
297#[derive(Debug, Trace, Finalize)]
298pub struct DataObject {
299 value: DataValue,
300
301 #[unsafe_ignore_trace]
303 type_constraint: Box<DataTypeConstraint>,
304
305 variable_name: Option<Box<str>>,
306 flags: u8,
307 member_of_class_id: i64,
308 #[unsafe_ignore_trace]
310 member_visibility: Option<Visibility>,
311}
312
313impl DataObject {
314 const FLAG_FINAL: u8 = 1;
315 const FLAG_STATIC: u8 = 2;
316 const FLAG_COPY_STATIC_AND_FINAL: u8 = 4;
317 const FLAG_LANG_VAR: u8 = 8;
318
319 pub fn get_type_constraint_for(variable_name: Option<&str>) -> &DataTypeConstraint {
320 if let Some(variable_name) = variable_name {
321 if variable_name.starts_with("&") {
322 &CONSTRAINT_COMPOSITE
323 }else if variable_name.starts_with("mp.") | variable_name.starts_with("fp.") |
324 variable_name.starts_with("func.") | variable_name.starts_with("fn.") |
325 variable_name.starts_with("linker.") | variable_name.starts_with("ln.") {
326 &CONSTRAINT_FUNCTION_POINTER
327 }else {
328 &CONSTRAINT_NORMAL
329 }
330 }else {
331 &CONSTRAINT_NORMAL
332 }
333 }
334
335 pub fn new() -> Self {
337 Self {
338 value: DataValue::Null,
339
340 type_constraint: Box::new(CONSTRAINT_NORMAL.clone()),
341
342 variable_name: None,
343 flags: 0,
344 member_of_class_id: -1,
345 member_visibility: None,
346 }
347 }
348
349 pub fn new_void() -> Self {
350 Self {
351 value: DataValue::Void,
352
353 type_constraint: Box::new(CONSTRAINT_NORMAL.clone()),
354
355 variable_name: None,
356 flags: 0,
357 member_of_class_id: -1,
358 member_visibility: None,
359 }
360 }
361
362 pub fn new_text(str: impl Into<Rc<str>>) -> Self {
363 Self {
364 value: DataValue::Text(str.into()),
365
366 type_constraint: Box::new(CONSTRAINT_NORMAL.clone()),
367
368 variable_name: None,
369 flags: 0,
370 member_of_class_id: -1,
371 member_visibility: None,
372 }
373 }
374
375 pub fn new_number(value: impl Into<Number>) -> Self {
376 Self {
377 value: match value.into() {
378 Number::Int(value) => DataValue::Int(value),
379 Number::Long(value) => DataValue::Long(value),
380 Number::Float(value) => DataValue::Float(value),
381 Number::Double(value) => DataValue::Double(value),
382 },
383
384 type_constraint: Box::new(CONSTRAINT_NORMAL.clone()),
385
386 variable_name: None,
387 flags: 0,
388 member_of_class_id: -1,
389 member_visibility: None,
390 }
391 }
392
393 pub fn new_optional_text(str: Option<impl Into<Rc<str>>>) -> Self {
394 if let Some(str) = str {
395 Self::new_text(str)
396 }else {
397 Self {
398 value: DataValue::Null,
399
400 type_constraint: Box::new(CONSTRAINT_NORMAL.clone()),
401
402 variable_name: None,
403 flags: 0,
404 member_of_class_id: -1,
405 member_visibility: None,
406 }
407 }
408 }
409
410 pub fn new_final_text(str: impl Into<Rc<str>>) -> Self {
411 Self {
412 value: DataValue::Text(str.into()),
413
414 type_constraint: Box::new(CONSTRAINT_NORMAL.clone()),
415
416 variable_name: None,
417 flags: Self::FLAG_FINAL,
418 member_of_class_id: -1,
419 member_visibility: None,
420 }
421 }
422
423 #[inline(always)]
425 pub fn with_update(func: impl FnOnce(&mut Self) -> Result<&mut DataObject, DataTypeConstraintError>) -> Result<DataObject, DataTypeConstraintError> {
426 let mut data_object = DataObject::new();
427
428 data_object.update(func)?;
429
430 Ok(data_object)
431 }
432
433 #[inline(always)]
435 pub fn with_update_final(func: impl FnOnce(&mut Self) -> Result<&mut DataObject, DataTypeConstraintError>) -> Result<DataObject, DataTypeConstraintError> {
436 let mut data_object = DataObject::new();
437
438 data_object.update(func)?;
439 data_object.set_final_data(true);
440
441 Ok(data_object)
442 }
443
444 #[inline(always)]
446 pub fn update(&mut self, func: impl FnOnce(&mut Self) -> Result<&mut DataObject, DataTypeConstraintError>) -> Result<(), DataTypeConstraintError> {
447 func(self)?;
448
449 Ok(())
450 }
451
452 #[inline(always)]
454 pub fn update_final(&mut self, func: impl FnOnce(&mut Self) -> Result<&mut DataObject, DataTypeConstraintError>) -> Result<(), DataTypeConstraintError> {
455 func(self)?;
456 self.set_final_data(true);
457
458 Ok(())
459 }
460
461 pub fn set_data(&mut self, data_object: &DataObject) -> Result<&mut Self, DataTypeConstraintError> {
467 self.check_type(data_object.value.data_type())?;
468
469 if let DataValue::FunctionPointer(function_pointer) = &data_object.value {
471 if let Some(variable_name) = &self.variable_name {
472 if self.variable_name().is_some() && function_pointer.function_name().is_none() {
473 self.value = DataValue::FunctionPointer(Gc::new(function_pointer.
474 copy_with_function_name(variable_name)));
475 }else {
476 self.value = data_object.value.clone();
477 }
478 }else {
479 self.value = data_object.value.clone();
480 }
481 }else {
482 self.value = data_object.value.clone();
483 }
484
485 if data_object.is_copy_static_and_final_modifiers() {
486 if data_object.is_final_data() {
487 self.flags |= Self::FLAG_FINAL;
488 }
489
490 if data_object.is_static_data() {
491 self.flags |= Self::FLAG_STATIC;
492 }
493 }
494
495 Ok(self)
496 }
497
498 pub(crate) fn data_value(&self) -> &DataValue {
499 &self.value
500 }
501
502 pub(crate) fn set_argument_separator(&mut self, value: &str) -> Result<&mut Self, DataTypeConstraintError> {
503 if self.is_final_data() {
504 return Ok(self);
505 }
506
507 self.check_type(DataType::ARGUMENT_SEPARATOR)?;
508 self.value = DataValue::ArgumentSeparator(value.into());
509
510 Ok(self)
511 }
512
513 pub fn set_text(&mut self, value: impl Into<Rc<str>>) -> Result<&mut Self, DataTypeConstraintError> {
514 if self.is_final_data() {
515 return Ok(self);
516 }
517
518 self.check_type(DataType::TEXT)?;
519 self.value = DataValue::Text(value.into());
520
521 Ok(self)
522 }
523
524 pub fn text_value(&self) -> Option<&str> {
525 match &self.value {
526 DataValue::Text(value) | DataValue::ArgumentSeparator(value) => Some(value.as_ref()),
527
528 _ => None,
529 }
530 }
531
532 pub fn set_byte_buffer(&mut self, value: Box<[u8]>) -> Result<&mut Self, DataTypeConstraintError> {
533 if self.is_final_data() {
534 return Ok(self);
535 }
536
537 self.check_type(DataType::BYTE_BUFFER)?;
538 self.value = DataValue::ByteBuffer(Gc::new(GcCell::new(value)));
539
540 Ok(self)
541 }
542
543 pub fn byte_buffer_value(&self) -> Option<Gc<GcCell<Box<[u8]>>>> {
544 match &self.value {
545 DataValue::ByteBuffer(value) => Some(value.clone()),
546
547 _ => None,
548 }
549 }
550
551 pub fn set_array(&mut self, value: Box<[DataObjectRef]>) -> Result<&mut Self, DataTypeConstraintError> {
552 if self.is_final_data() {
553 return Ok(self);
554 }
555
556 self.check_type(DataType::ARRAY)?;
557 self.value = DataValue::Array(Gc::new(GcCell::new(value)));
558
559 Ok(self)
560 }
561
562 pub fn array_value(&self) -> Option<Gc<GcCell<Box<[DataObjectRef]>>>> {
563 match &self.value {
564 DataValue::Array(value) => Some(value.clone()),
565
566 _ => None,
567 }
568 }
569
570 pub fn set_list(&mut self, value: VecDeque<DataObjectRef>) -> Result<&mut Self, DataTypeConstraintError> {
571 if self.is_final_data() {
572 return Ok(self);
573 }
574
575 self.check_type(DataType::LIST)?;
576 self.value = DataValue::List(Gc::new(GcCell::new(value)));
577
578 Ok(self)
579 }
580
581 pub fn list_value(&self) -> Option<Gc<GcCell<VecDeque<DataObjectRef>>>> {
582 match &self.value {
583 DataValue::List(value) => Some(value.clone()),
584
585 _ => None,
586 }
587 }
588
589 pub fn set_var_pointer(&mut self, value: DataObjectRef) -> Result<&mut Self, DataTypeConstraintError> {
590 if self.is_final_data() {
591 return Ok(self);
592 }
593
594 self.check_type(DataType::VAR_POINTER)?;
595 self.value = DataValue::VarPointer(value);
596
597 Ok(self)
598 }
599
600 pub fn var_pointer_value(&self) -> Option<DataObjectRef> {
601 match &self.value {
602 DataValue::VarPointer(value) => Some(value.clone()),
603
604 _ => None,
605 }
606 }
607
608 pub fn set_function_pointer(&mut self, value: FunctionPointerObjectRef) -> Result<&mut Self, DataTypeConstraintError> {
609 if self.is_final_data() {
610 return Ok(self);
611 }
612
613 self.check_type(DataType::FUNCTION_POINTER)?;
614
615 if let Some(variable_name) = &self.variable_name {
616 if self.variable_name().is_some() && value.function_name().is_none() {
617 self.value = DataValue::FunctionPointer(Gc::new(value.
618 copy_with_function_name(variable_name)));
619 }else {
620 self.value = DataValue::FunctionPointer(value);
621 }
622 }else {
623 self.value = DataValue::FunctionPointer(value);
624 }
625
626 Ok(self)
627 }
628
629 pub fn function_pointer_value(&self) -> Option<FunctionPointerObjectRef> {
630 match &self.value {
631 DataValue::FunctionPointer(value) => Some(value.clone()),
632
633 _ => None,
634 }
635 }
636
637 pub fn set_struct(&mut self, value: Gc<StructObject>) -> Result<&mut Self, DataTypeConstraintError> {
638 if self.is_final_data() {
639 return Ok(self);
640 }
641
642 self.check_type(DataType::STRUCT)?;
643 self.value = DataValue::Struct(value);
644
645 Ok(self)
646 }
647
648 pub fn struct_value(&self) -> Option<Gc<StructObject>> {
649 match &self.value {
650 DataValue::Struct(value) => Some(value.clone()),
651
652 _ => None,
653 }
654 }
655
656 pub fn set_object(&mut self, value: LangObjectRef) -> Result<&mut Self, DataTypeConstraintError> {
657 if self.is_final_data() {
658 return Ok(self);
659 }
660
661 self.check_type(DataType::OBJECT)?;
662 self.value = DataValue::Object(value);
663
664 Ok(self)
665 }
666
667 pub fn object_value(&self) -> Option<LangObjectRef> {
668 match &self.value {
669 DataValue::Object(value) => Some(value.clone()),
670
671 _ => None,
672 }
673 }
674
675 pub fn set_null(&mut self) -> Result<&mut Self, DataTypeConstraintError> {
676 if self.is_final_data() {
677 return Ok(self);
678 }
679
680 self.check_type(DataType::NULL)?;
681 self.value = DataValue::Null;
682
683 Ok(self)
684 }
685
686 pub fn set_void(&mut self) -> Result<&mut Self, DataTypeConstraintError> {
687 if self.is_final_data() {
688 return Ok(self);
689 }
690
691 self.check_type(DataType::VOID)?;
692 self.value = DataValue::Void;
693
694 Ok(self)
695 }
696
697 pub fn set_number(&mut self, value: Number) -> Result<&mut Self, DataTypeConstraintError> {
698 if self.is_final_data() {
699 return Ok(self);
700 }
701
702 match value {
703 Number::Int(value) => {
704 self.check_type(DataType::INT)?;
705 self.value = DataValue::Int(value);
706 },
707
708 Number::Long(value) => {
709 self.check_type(DataType::LONG)?;
710 self.value = DataValue::Long(value);
711 },
712
713 Number::Float(value) => {
714 self.check_type(DataType::FLOAT)?;
715 self.value = DataValue::Float(value);
716 },
717
718 Number::Double(value) => {
719 self.check_type(DataType::DOUBLE)?;
720 self.value = DataValue::Double(value);
721 },
722 }
723
724 Ok(self)
725 }
726
727 pub fn set_int(&mut self, value: i32) -> Result<&mut Self, DataTypeConstraintError> {
728 if self.is_final_data() {
729 return Ok(self);
730 }
731
732 self.check_type(DataType::INT)?;
733 self.value = DataValue::Int(value);
734
735 Ok(self)
736 }
737
738 pub fn int_value(&self) -> Option<i32> {
739 match self.value {
740 DataValue::Int(value) => Some(value),
741
742 _ => None,
743 }
744 }
745
746 pub fn set_bool(&mut self, value: bool) -> Result<&mut Self, DataTypeConstraintError> {
748 if self.is_final_data() {
749 return Ok(self);
750 }
751
752 self.check_type(DataType::INT)?;
753 self.value = DataValue::Int(value as i32);
754
755 Ok(self)
756 }
757
758 pub fn set_long(&mut self, value: i64) -> Result<&mut Self, DataTypeConstraintError> {
759 if self.is_final_data() {
760 return Ok(self);
761 }
762
763 self.check_type(DataType::LONG)?;
764 self.value = DataValue::Long(value);
765
766 Ok(self)
767 }
768
769 pub fn long_value(&self) -> Option<i64> {
770 match self.value {
771 DataValue::Long(value) => Some(value),
772
773 _ => None,
774 }
775 }
776
777 pub fn set_float(&mut self, value: f32) -> Result<&mut Self, DataTypeConstraintError> {
778 if self.is_final_data() {
779 return Ok(self);
780 }
781
782 self.check_type(DataType::FLOAT)?;
783 self.value = DataValue::Float(value);
784
785 Ok(self)
786 }
787
788 pub fn float_value(&self) -> Option<f32> {
789 match self.value {
790 DataValue::Float(value) => Some(value),
791
792 _ => None,
793 }
794 }
795
796 pub fn set_double(&mut self, value: f64) -> Result<&mut Self, DataTypeConstraintError> {
797 if self.is_final_data() {
798 return Ok(self);
799 }
800
801 self.check_type(DataType::DOUBLE)?;
802 self.value = DataValue::Double(value);
803
804 Ok(self)
805 }
806
807 pub fn double_value(&self) -> Option<f64> {
808 match self.value {
809 DataValue::Double(value) => Some(value),
810
811 _ => None,
812 }
813 }
814
815 pub fn set_char(&mut self, value: char) -> Result<&mut Self, DataTypeConstraintError> {
816 if self.is_final_data() {
817 return Ok(self);
818 }
819
820 self.check_type(DataType::CHAR)?;
821 self.value = DataValue::Char(value);
822
823 Ok(self)
824 }
825
826 pub fn char_value(&self) -> Option<char> {
827 match self.value {
828 DataValue::Char(value) => Some(value),
829
830 _ => None,
831 }
832 }
833
834 pub fn set_error(&mut self, value: Gc<ErrorObject>) -> Result<&mut Self, DataTypeConstraintError> {
835 if self.is_final_data() {
836 return Ok(self);
837 }
838
839 self.check_type(DataType::ERROR)?;
840 self.value = DataValue::Error(value);
841
842 Ok(self)
843 }
844
845 pub fn error_value(&self) -> Option<Gc<ErrorObject>> {
846 match &self.value {
847 DataValue::Error(value) => Some(value.clone()),
848
849 _ => None,
850 }
851 }
852
853 pub fn set_type(&mut self, value: DataType) -> Result<&mut Self, DataTypeConstraintError> {
854 if self.is_final_data() {
855 return Ok(self);
856 }
857
858 self.check_type(DataType::TYPE)?;
859 self.value = DataValue::Type(value);
860
861 Ok(self)
862 }
863
864 pub fn type_value(&self) -> Option<DataType> {
865 match self.value {
866 DataValue::Type(value) => Some(value),
867
868 _ => None,
869 }
870 }
871
872 pub fn number_value(&self) -> Option<Number> {
878 match self.value {
879 DataValue::Int(value) => Some(value.into()),
880 DataValue::Long(value) => Some(value.into()),
881 DataValue::Float(value) => Some(value.into()),
882 DataValue::Double(value) => Some(value.into()),
883
884 _ => None,
885 }
886 }
887
888 pub fn bool_value(&self) -> Option<bool> {
894 match self.value {
895 DataValue::Int(value) => Some(value != 0),
896
897 _ => None,
898 }
899 }
900
901 pub fn set_variable_name(&mut self, variable_name: Option<&str>) -> Result<&mut Self, DataTypeConstraintError> {
902 let new_type_requirement = Self::get_type_constraint_for(variable_name);
903 if !new_type_requirement.is_type_allowed(self.value.data_type()) {
904 return Err(DataTypeConstraintError::new());
905 }
906
907 self.type_constraint = Box::new(new_type_requirement.clone());
908 self.variable_name = variable_name.map(Box::from);
909
910 Ok(self)
911 }
912
913 pub fn variable_name(&self) -> Option<&str> {
914 self.variable_name.as_deref()
915 }
916
917 pub fn set_final_data(&mut self, final_data: bool) -> &mut Self {
918 self.flags = (self.flags | Self::FLAG_FINAL) ^ if final_data {
919 0
920 }else {
921 Self::FLAG_FINAL
922 };
923
924 self
925 }
926
927 pub fn is_final_data(&self) -> bool {
928 (self.flags & DataObject::FLAG_FINAL) != 0
929 }
930
931 pub fn set_static_data(&mut self, final_data: bool) -> &mut Self {
932 self.flags = (self.flags | Self::FLAG_STATIC) ^ if final_data {
933 0
934 }else {
935 Self::FLAG_STATIC
936 };
937
938 self
939 }
940
941 pub fn is_static_data(&self) -> bool {
942 (self.flags & DataObject::FLAG_STATIC) != 0
943 }
944
945 pub(crate) fn set_copy_static_and_final_modifiers(&mut self, copy_static_and_final_modifiers: bool) -> &mut Self {
946 self.flags = (self.flags | Self::FLAG_COPY_STATIC_AND_FINAL) ^ if copy_static_and_final_modifiers {
947 0
948 }else {
949 Self::FLAG_COPY_STATIC_AND_FINAL
950 };
951
952 self
953 }
954
955 pub fn is_copy_static_and_final_modifiers(&self) -> bool {
956 (self.flags & DataObject::FLAG_COPY_STATIC_AND_FINAL) != 0
957 }
958
959 pub(crate) fn set_lang_var(&mut self) -> &mut Self {
960 self.flags |= Self::FLAG_LANG_VAR;
961
962 self
963 }
964
965 pub fn is_lang_var(&self) -> bool {
966 (self.flags & DataObject::FLAG_LANG_VAR) != 0
967 }
968
969 pub fn data_type(&self) -> DataType {
970 self.value.data_type()
971 }
972
973 pub(crate) fn set_type_constraint(&mut self, type_constraint: Box<DataTypeConstraint>) -> Result<&mut Self, DataTypeConstraintError> {
974 for data_type in self.type_constraint.not_allowed_types() {
975 if type_constraint.is_type_allowed(data_type) {
976 return Err(DataTypeConstraintError::with_message("New type constraint must not allow types which were not allowed previously"));
977 }
978 }
979
980 if !type_constraint.is_type_allowed(self.value.data_type()) {
981 return Err(DataTypeConstraintError::new());
982 }
983
984 self.type_constraint = type_constraint;
985
986 Ok(self)
987 }
988
989 pub fn type_constraint(&self) -> &DataTypeConstraint {
990 &self.type_constraint
991 }
992
993 pub fn check_type(&self, data_type: DataType) -> Result<(), DataTypeConstraintError> {
994 if !self.type_constraint.is_type_allowed(data_type) {
995 return Err(DataTypeConstraintError::new());
996 }
997
998 Ok(())
999 }
1000
1001 pub(crate) fn set_member_visibility(&mut self, member_visibility: Option<Visibility>) -> &mut Self {
1002 self.member_visibility = member_visibility;
1003
1004 self
1005 }
1006
1007 pub fn member_visibility(&self) -> Option<Visibility> {
1008 self.member_visibility
1009 }
1010
1011 pub(crate) fn set_member_of_class(&mut self, member_of_class: OptionLangObjectRef) -> &mut Self {
1012 self.member_of_class_id = member_of_class.map(|lang_object| {
1013 lang_object.borrow().class_id
1014 }).unwrap_or(-1);
1015
1016 self
1017 }
1018
1019 pub fn member_of_class(&self) -> i64 {
1020 self.member_of_class_id
1021 }
1022
1023 pub fn is_accessible(&self, accessing_class: Option<&LangObjectRef>) -> bool {
1024 if self.member_of_class_id == -1 {
1025 return true;
1026 }
1027
1028 let Some(member_visibility) = self.member_visibility else {
1029 return true;
1030 };
1031
1032 if member_visibility == Visibility::Public {
1033 return true;
1034 }
1035
1036 let Some(accessing_class) = accessing_class else {
1037 return false;
1038 };
1039
1040 let accessing_class_id = accessing_class.borrow().class_id;
1041
1042 accessing_class_id == self.member_of_class_id || (
1043 member_visibility == Visibility::Protected && object::CLASS_ID_TO_SUPER_CLASS_IDS.lock().
1044 unwrap()[&accessing_class_id].contains(&self.member_of_class_id)
1045 )
1046 }
1047}
1048
1049impl Default for DataObject {
1050 fn default() -> Self {
1051 Self::new()
1052 }
1053}
1054
1055impl Display for DataObject {
1056 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1057 write!(f, "<DataObject>")
1058 }
1059}
1060
1061#[derive(Debug, Clone, Default, Trace, Finalize)]
1062pub struct DataObjectRef(Gc<GcCell<DataObject>>);
1063
1064impl DataObjectRef {
1065 pub fn new(data_object: DataObject) -> Self {
1066 Self(Gc::new(GcCell::new(data_object)))
1067 }
1068
1069 pub(crate) fn data_value(&self) -> DataValue {
1070 self.0.borrow().data_value().clone()
1071 }
1072
1073 pub fn text_value(&self) -> Option<Box<str>> {
1074 self.0.borrow().text_value().map(Box::from)
1075 }
1076
1077 pub fn byte_buffer_value(&self) -> Option<Gc<GcCell<Box<[u8]>>>> {
1078 self.0.borrow().byte_buffer_value()
1079 }
1080
1081 pub fn array_value(&self) -> Option<Gc<GcCell<Box<[DataObjectRef]>>>> {
1082 self.0.borrow().array_value()
1083 }
1084
1085 pub fn list_value(&self) -> Option<Gc<GcCell<VecDeque<DataObjectRef>>>> {
1086 self.0.borrow().list_value()
1087 }
1088
1089 pub fn var_pointer_value(&self) -> Option<DataObjectRef> {
1090 self.0.borrow().var_pointer_value()
1091 }
1092
1093 pub fn function_pointer_value(&self) -> Option<FunctionPointerObjectRef> {
1094 self.0.borrow().function_pointer_value()
1095 }
1096
1097 pub fn struct_value(&self) -> Option<Gc<StructObject>> {
1098 self.0.borrow().struct_value()
1099 }
1100
1101 pub fn object_value(&self) -> Option<LangObjectRef> {
1102 self.0.borrow().object_value()
1103 }
1104
1105 pub fn int_value(&self) -> Option<i32> {
1106 self.0.borrow().int_value()
1107 }
1108
1109 pub fn long_value(&self) -> Option<i64> {
1110 self.0.borrow().long_value()
1111 }
1112
1113 pub fn float_value(&self) -> Option<f32> {
1114 self.0.borrow().float_value()
1115 }
1116
1117 pub fn double_value(&self) -> Option<f64> {
1118 self.0.borrow().double_value()
1119 }
1120
1121 pub fn char_value(&self) -> Option<char> {
1122 self.0.borrow().char_value()
1123 }
1124
1125 pub fn error_value(&self) -> Option<Gc<ErrorObject>> {
1126 self.0.borrow().error_value()
1127 }
1128
1129 pub fn type_value(&self) -> Option<DataType> {
1130 self.0.borrow().type_value()
1131 }
1132
1133 pub fn number_value(&self) -> Option<Number> {
1135 self.0.borrow().number_value()
1136 }
1137
1138 pub fn bool_value(&self) -> Option<bool> {
1140 self.0.borrow().bool_value()
1141 }
1142
1143 pub fn variable_name(&self) -> Option<Box<str>> {
1144 self.0.borrow().variable_name().map(Box::from)
1145 }
1146
1147 pub fn is_final_data(&self) -> bool {
1148 self.0.borrow().is_final_data()
1149 }
1150
1151 pub fn is_static_data(&self) -> bool {
1152 self.0.borrow().is_static_data()
1153 }
1154
1155 pub fn is_copy_static_and_final_modifiers(&self) -> bool {
1156 self.0.borrow().is_copy_static_and_final_modifiers()
1157 }
1158
1159 pub fn is_lang_var(&self) -> bool {
1160 self.0.borrow().is_lang_var()
1161 }
1162
1163 pub fn data_type(&self) -> DataType {
1164 self.0.borrow().data_type()
1165 }
1166
1167 pub fn type_constraint(&self) -> DataTypeConstraint {
1169 self.0.borrow().type_constraint().clone()
1170 }
1171
1172 pub fn member_visibility(&self) -> Option<Visibility> {
1173 self.0.borrow().member_visibility()
1174 }
1175
1176 pub fn member_of_class(&self) -> i64 {
1177 self.0.borrow().member_of_class()
1178 }
1179
1180 pub fn is_accessible(&self, accessing_class: Option<&LangObjectRef>) -> bool {
1181 self.0.borrow().is_accessible(accessing_class)
1182 }
1183}
1184
1185impl Deref for DataObjectRef {
1186 type Target = GcCell<DataObject>;
1187
1188 fn deref(&self) -> &Self::Target {
1189 self.0.deref()
1190 }
1191}
1192
1193#[derive(Debug, Trace, Finalize)]
1194enum StructData {
1195 Definition(#[unsafe_ignore_trace] Vec<(Box<str>, Option<Box<DataTypeConstraint>>)>),
1197 Instance {
1198 members: Vec<(Box<str>, DataObjectRef)>,
1199 struct_base_definition: Gc<StructObject>,
1200 },
1201}
1202
1203#[derive(Debug, Trace, Finalize)]
1204pub struct StructObject {
1205 data: StructData,
1206}
1207
1208impl StructObject {
1209 pub fn new_definition(members: &[(&str, Option<DataTypeConstraint>)]) -> Self {
1210 let members = Vec::from_iter(members.iter().
1211 cloned().
1212 map(|(key, value)| (Box::from(key), value.
1213 map(Box::new))));
1214
1215 Self {
1216 data: StructData::Definition(members),
1217 }
1218 }
1219
1220 pub fn new_instance(
1221 struct_base_definition: Gc<StructObject>,
1222 values: &[DataObjectRef],
1223 ) -> Result<Self, DataTypeConstraintError> {
1224 let mut members = Vec::with_capacity(values.len());
1225
1226 {
1227 let StructData::Definition(struct_definition_members) = &struct_base_definition.data else {
1228 return Err(DataTypeConstraintError::with_message(
1229 "No instance can be created of another struct instance",
1230 ));
1231 };
1232
1233 if struct_definition_members.len() != values.len() {
1234 return Err(DataTypeConstraintError::with_message(
1235 "The count of members must be equals to the count of values",
1236 ));
1237 }
1238
1239 for (i, member_definition) in struct_definition_members.iter().
1240 enumerate() {
1241 let member_name = member_definition.0.clone();
1242
1243 let mut member = DataObject::new();
1244 member.set_variable_name(Some(&member_name))?;
1245
1246 member.set_data(&values[i].borrow())?;
1247
1248 if let Some(type_constraint) = member_definition.1.clone() {
1249 member.set_type_constraint(type_constraint)?;
1250 }
1251
1252 members.push((member_name, DataObjectRef::new(member)));
1253 }
1254 }
1255
1256 Ok(Self {
1257 data: StructData::Instance {
1258 members,
1259 struct_base_definition
1260 },
1261 })
1262 }
1263
1264 pub fn member_names(&self) -> Vec<Box<str>> {
1265 match &self.data {
1266 StructData::Definition(members) => {
1267 Vec::from_iter(members.iter().map(|(member_name, ..)| member_name.clone()))
1268 },
1269
1270 StructData::Instance { struct_base_definition, .. } => {
1271 struct_base_definition.member_names()
1272 },
1273 }
1274 }
1275
1276 pub fn type_constraints(&self) -> Vec<Option<Box<DataTypeConstraint>>> {
1277 match &self.data {
1278 StructData::Definition(members) => {
1279 Vec::from_iter(members.iter().map(|(.., type_constraint)| type_constraint.clone()))
1280 },
1281
1282 StructData::Instance { struct_base_definition, .. } => {
1283 struct_base_definition.type_constraints()
1284 },
1285 }
1286 }
1287
1288 pub fn base_definition(&self) -> Option<Gc<StructObject>> {
1289 match &self.data {
1290 StructData::Instance { struct_base_definition, .. } =>
1291 Some(struct_base_definition.clone()),
1292
1293 StructData::Definition(..) => None,
1294 }
1295 }
1296
1297 pub fn index_of(&self, member_name: &str) -> Option<usize> {
1298 match &self.data {
1299 StructData::Definition(members) => {
1300 for (i, (member, ..)) in members.iter().
1301 enumerate() {
1302 if **member == *member_name {
1303 return Some(i);
1304 }
1305 }
1306 },
1307
1308 StructData::Instance { struct_base_definition, .. } =>
1309 return struct_base_definition.index_of(member_name),
1310 }
1311
1312 None
1313 }
1314
1315 pub fn type_constraint(&self, member_name: &str) -> Result<Option<Box<DataTypeConstraint>>, DataTypeConstraintError> {
1316 let Some(index) = self.index_of(member_name) else {
1317 return Err(DataTypeConstraintError::with_message(
1318 format!("The member \"{member_name}\" is not part of this struct"),
1319 ));
1320 };
1321
1322 match &self.data {
1323 StructData::Definition(members) => Ok(members[index].1.clone()),
1324
1325 StructData::Instance { struct_base_definition, .. } =>
1326 struct_base_definition.type_constraint(member_name),
1327 }
1328 }
1329
1330 pub fn get_member(&self, member_name: &str) -> Result<DataObjectRef, DataTypeConstraintError> {
1331 let StructData::Instance { members, .. } = &self.data else {
1332 return Err(DataTypeConstraintError::with_message(
1333 "The struct definition is no struct instance and has no member values",
1334 ));
1335 };
1336
1337 let Some(index) = self.index_of(member_name) else {
1338 return Err(DataTypeConstraintError::with_message(
1339 format!("The member \"{member_name}\" is not part of this struct"),
1340 ));
1341 };
1342
1343 Ok(members[index].1.clone())
1344 }
1345
1346 pub fn set_member(&self, member_name: &str, value: &DataObject) -> Result<(), DataTypeConstraintError> {
1347 let StructData::Instance { members, .. } = &self.data else {
1348 return Err(DataTypeConstraintError::with_message(
1349 "The struct definition is no struct instance and has no member values",
1350 ));
1351 };
1352
1353 let Some(index) = self.index_of(member_name) else {
1354 return Err(DataTypeConstraintError::with_message(
1355 format!("The member \"{member_name}\" is not part of this struct"),
1356 ));
1357 };
1358
1359 members[index].1.borrow_mut().set_data(value)?;
1360
1361 Ok(())
1362 }
1363
1364 pub fn is_definition(&self) -> bool {
1365 matches!(self.data, StructData::Definition(..))
1366 }
1367}
1368
1369impl Display for StructObject {
1370 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1371 if self.is_definition() {
1372 write!(f, "<Struct[Definition]>")
1373 }else {
1374 write!(f, "<Struct[Instance]>")
1375 }
1376 }
1377}
1378
1379#[derive(Debug, Eq, Trace, Finalize)]
1380pub struct ErrorObject {
1381 #[unsafe_ignore_trace]
1383 err: InterpretingError,
1384 message: Option<Box<str>>,
1385}
1386
1387impl ErrorObject {
1388 pub fn new(err: InterpretingError, message: Option<&str>) -> Self {
1389 Self {
1390 err,
1391 message: message.map(Box::from),
1392 }
1393 }
1394
1395 pub fn err(&self) -> InterpretingError {
1396 self.err
1397 }
1398
1399 pub fn message(&self) -> Option<&str> {
1400 self.message.as_deref()
1401 }
1402}
1403
1404impl PartialEq for ErrorObject {
1405 fn eq(&self, other: &Self) -> bool {
1406 self.err == other.err
1407 }
1408}
1409
1410impl Display for ErrorObject {
1411 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1412 write!(f, "Error")
1413 }
1414}
1415
1416#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash)]
1417pub enum Visibility {
1418 Private,
1419 Protected,
1420 Public,
1421}
1422
1423impl Visibility {
1424 pub fn symbol(&self) -> &'static str {
1425 match self {
1426 Visibility::Private => "-",
1427 Visibility::Protected => "~",
1428 Visibility::Public => "+",
1429 }
1430 }
1431}
1432
1433impl From<crate::parser::ast::Visibility> for Visibility {
1434 fn from(value: crate::parser::ast::Visibility) -> Self {
1435 match value {
1436 crate::parser::ast::Visibility::Private => Visibility::Private,
1437 crate::parser::ast::Visibility::Protected => Visibility::Protected,
1438 crate::parser::ast::Visibility::Public => Visibility::Public,
1439 }
1440 }
1441}
1442
1443#[derive(Debug, Copy, Clone)]
1444pub enum Number {
1445 Int(i32),
1446 Long(i64),
1447 Float(f32),
1448 Double(f64),
1449}
1450
1451impl Number {
1452 pub fn int_value(self) -> i32 {
1453 match self {
1454 Self::Int(value) => value,
1455 Self::Long(value) => value as i32,
1456 Self::Float(value) => value as i32,
1457 Self::Double(value) => value as i32,
1458 }
1459 }
1460
1461 pub fn long_value(self) -> i64 {
1462 match self {
1463 Self::Int(value) => value as i64,
1464 Self::Long(value) => value,
1465 Self::Float(value) => value as i64,
1466 Self::Double(value) => value as i64,
1467 }
1468 }
1469
1470 pub fn float_value(self) -> f32 {
1471 match self {
1472 Self::Int(value) => value as f32,
1473 Self::Long(value) => value as f32,
1474 Self::Float(value) => value,
1475 Self::Double(value) => value as f32,
1476 }
1477 }
1478
1479 pub fn double_value(self) -> f64 {
1480 match self {
1481 Self::Int(value) => value as f64,
1482 Self::Long(value) => value as f64,
1483 Self::Float(value) => value as f64,
1484 Self::Double(value) => value,
1485 }
1486 }
1487}
1488
1489impl From<i32> for Number {
1490 fn from(value: i32) -> Self {
1491 Self::Int(value)
1492 }
1493}
1494
1495impl From<i64> for Number {
1496 fn from(value: i64) -> Self {
1497 Self::Long(value)
1498 }
1499}
1500
1501impl From<f32> for Number {
1502 fn from(value: f32) -> Self {
1503 Self::Float(value)
1504 }
1505}
1506
1507impl From<f64> for Number {
1508 fn from(value: f64) -> Self {
1509 Self::Double(value)
1510 }
1511}
1512
1513#[derive(Debug)]
1514pub struct DataTypeConstraintError {
1515 message: String
1516}
1517
1518impl DataTypeConstraintError {
1519 pub fn new() -> Self {
1520 Self {
1521 message: "The data type would violate a type constraint".to_string(),
1522 }
1523 }
1524
1525 pub fn with_message(message: impl Into<String>) -> Self {
1526 Self { message: message.into() }
1527 }
1528
1529 pub fn message(&self) -> &str {
1530 &self.message
1531 }
1532}
1533
1534impl Default for DataTypeConstraintError {
1535 fn default() -> Self {
1536 Self::new()
1537 }
1538}
1539
1540impl Display for DataTypeConstraintError {
1541 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1542 f.write_str(&self.message)
1543 }
1544}
1545
1546impl Error for DataTypeConstraintError {}