1use bitflags::bitflags;
2use ownable::traits::IntoOwned;
3use std::borrow::Cow;
4use std::ops::Deref;
5use std::sync::{Arc, Mutex, MutexGuard};
6
7pub trait GetIdent {
8 fn ident(&self) -> &str;
9}
10
11#[allow(clippy::mutable_key_type)]
12#[derive(Debug, Clone)]
13pub struct ObjectCell<T: GetIdent>(Arc<String>, Arc<Mutex<T>>);
14
15impl<T: GetIdent> ObjectCell<T> {
16 pub fn borrow(&self) -> MutexGuard<'_, T> {
17 self.1.lock().unwrap()
18 }
19
20 pub fn borrow_mut(&self) -> MutexGuard<'_, T> {
21 self.1.lock().unwrap()
22 }
23}
24
25impl<T: GetIdent> GetIdent for ObjectCell<T> {
26 fn ident(&self) -> &str {
27 self.0.as_str()
28 }
29}
30
31impl<T: GetIdent> From<T> for ObjectCell<T> {
32 fn from(value: T) -> Self {
33 Self(
34 Arc::new(value.ident().to_string()),
35 Arc::new(Mutex::new(value)),
36 )
37 }
38}
39
40impl<T: GetIdent> From<Arc<Mutex<T>>> for ObjectCell<T> {
41 fn from(value: Arc<Mutex<T>>) -> Self {
42 let ident = Arc::new(value.lock().unwrap().ident().to_string());
43 Self(ident, value)
44 }
45}
46
47impl<T: GetIdent> Deref for ObjectCell<T> {
48 type Target = Mutex<T>;
49
50 fn deref(&self) -> &Self::Target {
51 self.1.deref()
52 }
53}
54
55impl<T: GetIdent> std::hash::Hash for ObjectCell<T> {
56 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
57 std::ptr::hash(Arc::as_ptr(&self.1), state);
58 }
59}
60
61impl<T: GetIdent> std::cmp::PartialEq for ObjectCell<T> {
62 fn eq(&self, other: &Self) -> bool {
63 Arc::as_ptr(&self.1) == Arc::as_ptr(&other.1)
64 }
65}
66
67impl<T: GetIdent> std::cmp::Eq for ObjectCell<T> {}
68
69bitflags! {
70 #[derive(Debug, Clone, PartialEq)]
71 pub struct Modifiers: u16 {
72 const PUBLIC = 1 << 0;
73 const PROTECTED = 1 << 1;
74 const PRIVATE = 1 << 2;
75
76 const STATIC = 1 << 3;
77 const FINAL = 1 << 4;
78 const SEALED = 1 << 5;
79 const NON_SEALED = 1 << 6;
80 const ABSTRACT = 1 << 7;
81
82 const NATIVE = 1 << 8;
83 const SYNCHRONIZED = 1 << 9;
84 const TRANSIENT = 1 << 10;
85 const VOLATILE = 1 << 11;
86 const STRICTFP = 1 << 12;
87
88 const DEFAULT = 1 << 13;
89 }
90}
91
92impl IntoOwned for Modifiers {
93 type Owned = Modifiers;
94
95 fn into_owned(self) -> Self::Owned {
96 self
97 }
98}
99
100#[derive(Clone, PartialEq)]
101pub enum TypeName {
102 Void,
103 Boolean,
104 Byte,
105 Char,
106 Short,
107 Integer,
108 Long,
109 Float,
110 Double,
111 Ident(String),
112 ResolvedGeneric(String),
113 ResolvedClass(ClassCell),
114 ResolvedInterface(InterfaceCell),
115}
116
117impl std::fmt::Debug for TypeName {
118 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119 match self {
120 Self::Void => write!(f, "Void"),
121 Self::Boolean => write!(f, "Boolean"),
122 Self::Byte => write!(f, "Byte"),
123 Self::Char => write!(f, "Char"),
124 Self::Short => write!(f, "Short"),
125 Self::Integer => write!(f, "Integer"),
126 Self::Long => write!(f, "Long"),
127 Self::Float => write!(f, "Float"),
128 Self::Double => write!(f, "Double"),
129 Self::Ident(arg0) => f.debug_tuple("Ident").field(arg0).finish(),
130 Self::ResolvedGeneric(arg0) => f.debug_tuple("ResolvedGeneric").field(arg0).finish(),
131 Self::ResolvedClass(arg0) => f
132 .debug_tuple("ResolvedIdent")
133 .field(&arg0.lock().unwrap().ident)
134 .finish(),
135 Self::ResolvedInterface(arg0) => f
136 .debug_tuple("ResolvedInterface")
137 .field(&arg0.lock().unwrap().ident)
138 .finish(),
139 }
140 }
141}
142
143impl std::fmt::Display for TypeName {
144 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145 match self {
146 TypeName::Void => write!(f, "void"),
147 TypeName::Boolean => write!(f, "boolean"),
148 TypeName::Byte => write!(f, "byte"),
149 TypeName::Char => write!(f, "char"),
150 TypeName::Short => write!(f, "short"),
151 TypeName::Integer => write!(f, "int"),
152 TypeName::Long => write!(f, "long"),
153 TypeName::Float => write!(f, "float"),
154 TypeName::Double => write!(f, "double"),
155 TypeName::Ident(ident) => write!(f, "{}", ident),
156 TypeName::ResolvedGeneric(ident) => write!(f, "{}", ident),
157 TypeName::ResolvedClass(class_cell) => write!(f, "{}", class_cell.ident()),
158 TypeName::ResolvedInterface(interface_cell) => write!(f, "{}", interface_cell.ident()),
159 }
160 }
161}
162
163impl TypeName {
164 pub fn resolved_class(&self) -> Option<&ClassCell> {
165 if let Self::ResolvedClass(class_cell) = self {
166 Some(class_cell)
167 } else {
168 None
169 }
170 }
171}
172
173#[derive(Debug, Clone, PartialEq)]
174pub enum WildcardBoundary {
175 None,
176 Extends(QualifiedType),
177 Super(QualifiedType),
178}
179
180impl std::fmt::Display for WildcardBoundary {
181 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182 match self {
183 WildcardBoundary::None => write!(f, "?"),
184 WildcardBoundary::Extends(items) => write!(
185 f,
186 "? extends {}",
187 items
188 .iter()
189 .map(|part| part.to_string())
190 .collect::<Vec<_>>()
191 .join(".")
192 ),
193 WildcardBoundary::Super(items) => write!(
194 f,
195 "? super {}",
196 items
197 .iter()
198 .map(|part| part.to_string())
199 .collect::<Vec<_>>()
200 .join(".")
201 ),
202 }
203 }
204}
205
206#[derive(Debug, Clone, PartialEq)]
207pub enum TypeGeneric {
208 Type(QualifiedType),
209 Wildcard(WildcardBoundary),
210}
211
212impl std::fmt::Display for TypeGeneric {
213 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214 match self {
215 TypeGeneric::Type(items) => write!(
216 f,
217 "{}",
218 items
219 .iter()
220 .map(|part| part.to_string())
221 .collect::<Vec<_>>()
222 .join(".")
223 ),
224 TypeGeneric::Wildcard(wildcard_boundary) => wildcard_boundary.fmt(f),
225 }
226 }
227}
228
229#[derive(Debug, Clone, PartialEq)]
230pub struct Type {
231 pub name: TypeName,
232 pub generics: Box<[TypeGeneric]>,
233 pub array_depth: usize,
234}
235
236impl std::fmt::Display for Type {
237 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
238 if self.generics.is_empty() {
239 write!(f, "{}{}", self.name, "[]".repeat(self.array_depth))
240 } else {
241 write!(
242 f,
243 "{}<{}>{}",
244 self.name,
245 self.generics
246 .iter()
247 .map(|part| part.to_string())
248 .collect::<Vec<_>>()
249 .join(", "),
250 "[]".repeat(self.array_depth)
251 )
252 }
253 }
254}
255
256pub type QualifiedType = Box<[Type]>;
257
258#[derive(Debug, Clone, PartialEq)]
259pub struct Variable {
260 pub modifiers: Modifiers,
261 pub r#type: QualifiedType,
262 pub ident: String,
263 }
265
266impl Variable {
267 pub fn new_array(
268 modifiers: Modifiers,
269 r#type: QualifiedType,
270 idents: Box<[(Cow<'_, str>, usize)]>,
271 ) -> Box<[Self]> {
272 idents
273 .into_iter()
274 .map(|(ident, array_depth)| Self {
275 modifiers: modifiers.clone(),
276 r#type: {
277 let mut clone = r#type.clone();
278 clone.last_mut().unwrap().array_depth += array_depth;
279 clone
280 },
281 ident: ident.to_string(),
282 })
283 .collect()
284 }
285}
286
287#[derive(Debug, Clone, PartialEq)]
288pub struct GenericDefinition {
289 pub ident: String,
290 pub extends: Box<[QualifiedType]>,
291}
292
293impl std::fmt::Display for GenericDefinition {
294 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295 if self.extends.is_empty() {
296 write!(f, "{}", self.ident)
297 } else {
298 write!(
299 f,
300 "{} extends {}",
301 self.ident,
302 self.extends
303 .iter()
304 .map(|extend| extend
305 .iter()
306 .map(|part| part.to_string())
307 .collect::<Vec<_>>()
308 .join("."))
309 .collect::<Vec<_>>()
310 .join(".")
311 )
312 }
313 }
314}
315
316#[derive(Debug, Clone, PartialEq)]
317pub struct FunctionArgument {
318 pub modifiers: Modifiers,
319 pub r#type: QualifiedType,
320 pub ident: String,
321 pub vararg: bool,
322}
323
324#[derive(Debug, Clone, PartialEq)]
325pub struct Function {
326 pub modifiers: Modifiers,
327 pub generics: Box<[GenericDefinition]>,
328 pub return_type: QualifiedType,
329 pub ident: String,
330 pub arguments: Box<[FunctionArgument]>,
331 }
333
334#[derive(Debug, Clone)]
335pub(super) enum ClassEntry {
336 Variables(Box<[Variable]>),
337 Function(Function),
338 Class(Class),
339 Enum(Enum),
340 Interface(Interface),
341 Skip,
342}
343
344#[derive(Debug, Clone)]
345pub struct Class {
346 pub modifiers: Modifiers,
347 pub ident: String,
348 pub generics: Box<[GenericDefinition]>,
349
350 pub extends: Option<QualifiedType>,
351 pub implements: Box<[QualifiedType]>,
352 pub permits: Box<[QualifiedType]>,
353
354 pub variables: Box<[Variable]>,
355 pub functions: Box<[Function]>,
356
357 pub classes: Box<[ClassCell]>,
358 pub enums: Box<[EnumCell]>,
359 pub interfaces: Box<[InterfaceCell]>,
360}
361
362impl GetIdent for Class {
363 fn ident(&self) -> &str {
364 self.ident.as_str()
365 }
366}
367
368pub type ClassCell = ObjectCell<Class>;
369
370impl
377 From<(
378 Modifiers,
379 Cow<'_, str>,
380 Option<Box<[GenericDefinition]>>,
381 Option<Box<[FunctionArgument]>>,
382 Option<Box<[QualifiedType]>>,
383 Option<Box<[ClassEntry]>>,
384 )> for Class
385{
386 fn from(
387 value: (
388 Modifiers,
389 Cow<'_, str>,
390 Option<Box<[GenericDefinition]>>,
391 Option<Box<[FunctionArgument]>>,
392 Option<Box<[QualifiedType]>>,
393 Option<Box<[ClassEntry]>>,
394 ),
395 ) -> Self {
396 let (mut modifiers, ident, generics, args, implements, entries) = value;
397
398 modifiers.insert(Modifiers::FINAL);
399
400 let mut variables = Vec::new();
401 let mut functions = Vec::new();
402 let mut classes = Vec::new();
403 let mut enums = Vec::new();
404 let mut interfaces = Vec::new();
405
406 if let Some(entries) = entries {
407 for entry in entries {
408 match entry {
409 ClassEntry::Variables(v) => variables.append(&mut v.into_vec()),
410 ClassEntry::Function(f) => functions.push(f),
411 ClassEntry::Class(c) => classes.push(c),
412 ClassEntry::Enum(e) => enums.push(e),
413 ClassEntry::Interface(i) => interfaces.push(i),
414 ClassEntry::Skip => {}
415 }
416 }
417 }
418
419 functions.push(Function {
420 modifiers: Modifiers::PUBLIC | Modifiers::STATIC,
421 generics: Box::new([]),
422 return_type: QualifiedType::from([Type {
423 name: TypeName::Ident(ident.to_string()),
424 generics: generics
425 .clone()
426 .unwrap_or_else(|| Box::new([]))
427 .into_iter()
428 .map(|x| {
429 TypeGeneric::Type(QualifiedType::from([Type {
430 name: TypeName::Ident(x.ident),
431 generics: Box::new([]),
432 array_depth: 0,
433 }]))
434 })
435 .collect::<Box<[_]>>(),
436 array_depth: 0,
437 }]),
438 ident: "__ctor".to_string(),
439 arguments: args.clone().unwrap_or_else(|| Box::new([])),
440 });
441
442 if let Some(args) = args {
443 for mut arg in args {
444 arg.modifiers.insert(Modifiers::PRIVATE | Modifiers::FINAL);
445
446 if arg.vararg {
447 arg.r#type.last_mut().unwrap().array_depth += 1;
448 }
449
450 functions.push(Function {
451 modifiers: Modifiers::PUBLIC,
452 generics: Box::new([]),
453 return_type: arg.r#type.clone(),
454 ident: arg.ident.clone(),
455 arguments: Box::new([]),
456 });
457
458 variables.push(Variable {
459 modifiers: arg.modifiers,
460 r#type: arg.r#type,
461 ident: arg.ident,
462 });
463 }
464 }
465
466 Self {
467 modifiers,
468 ident: ident.to_string(),
469 generics: generics.unwrap_or(Box::new([])),
470 extends: Some(Box::new([
471 Type {
472 name: TypeName::Ident("java".to_string()),
473 generics: Box::new([]),
474 array_depth: 0,
475 },
476 Type {
477 name: TypeName::Ident("lang".to_string()),
478 generics: Box::new([]),
479 array_depth: 0,
480 },
481 Type {
482 name: TypeName::Ident("Record".to_string()),
483 generics: Box::new([]),
484 array_depth: 0,
485 },
486 ])),
487 implements: implements.unwrap_or(Box::from([])),
488 permits: Box::from([]),
489 variables: variables.into_boxed_slice(),
490 functions: functions.into_boxed_slice(),
491 classes: classes.into_iter().map(ClassCell::from).collect(),
492 enums: enums.into_iter().map(EnumCell::from).collect(),
493 interfaces: interfaces.into_iter().map(InterfaceCell::from).collect(),
494 }
495 }
496}
497
498impl
499 From<(
500 Modifiers,
501 Cow<'_, str>,
502 Option<Box<[GenericDefinition]>>,
503 Option<QualifiedType>,
504 Option<Box<[QualifiedType]>>,
505 Option<Box<[QualifiedType]>>,
506 Option<Box<[ClassEntry]>>,
507 )> for Class
508{
509 fn from(
510 value: (
511 Modifiers,
512 Cow<'_, str>,
513 Option<Box<[GenericDefinition]>>,
514 Option<QualifiedType>,
515 Option<Box<[QualifiedType]>>,
516 Option<Box<[QualifiedType]>>,
517 Option<Box<[ClassEntry]>>,
518 ),
519 ) -> Self {
520 let (modifiers, ident, generics, extends, implements, permits, entries) = value;
521
522 let mut variables = Vec::new();
523 let mut functions = Vec::new();
524 let mut classes = Vec::new();
525 let mut enums = Vec::new();
526 let mut interfaces = Vec::new();
527
528 if let Some(entries) = entries {
529 for entry in entries {
530 match entry {
531 ClassEntry::Variables(v) => variables.append(&mut v.into_vec()),
532 ClassEntry::Function(f) => functions.push(f),
533 ClassEntry::Class(c) => classes.push(c),
534 ClassEntry::Enum(e) => enums.push(e),
535 ClassEntry::Interface(i) => interfaces.push(i),
536 ClassEntry::Skip => {}
537 }
538 }
539 }
540
541 Self {
542 modifiers,
543 ident: ident.to_string(),
544 generics: generics.unwrap_or(Box::new([])),
545 extends,
546 implements: implements.unwrap_or(Box::from([])),
547 permits: permits.unwrap_or(Box::from([])),
548 variables: variables.into_boxed_slice(),
549 functions: functions.into_boxed_slice(),
550 classes: classes.into_iter().map(ClassCell::from).collect(),
551 enums: enums.into_iter().map(EnumCell::from).collect(),
552 interfaces: interfaces.into_iter().map(InterfaceCell::from).collect(),
553 }
554 }
555}
556
557#[derive(Debug, Clone)]
558pub(super) enum EnumEntry {
559 Variables(Box<[Variable]>),
560 Function(Function),
561 Class(Class),
562 Enum(Enum),
563 Interface(Interface),
564 Skip,
565}
566
567#[derive(Debug, Clone)]
568pub struct Enum {
569 pub modifiers: Modifiers,
570 pub ident: String,
571 pub generics: Box<[GenericDefinition]>,
572
573 pub implements: Box<[QualifiedType]>,
574
575 pub variables: Box<[Variable]>,
576 pub functions: Box<[Function]>,
577
578 pub classes: Box<[ClassCell]>,
579 pub enums: Box<[EnumCell]>,
580 pub interfaces: Box<[InterfaceCell]>,
581}
582
583impl GetIdent for Enum {
584 fn ident(&self) -> &str {
585 self.ident.as_str()
586 }
587}
588
589pub type EnumCell = ObjectCell<Enum>;
590
591impl
598 From<(
599 Modifiers,
600 Cow<'_, str>,
601 Option<Box<[GenericDefinition]>>,
602 Option<Box<[QualifiedType]>>,
603 Option<Box<[EnumEntry]>>,
604 )> for Enum
605{
606 fn from(
607 value: (
608 Modifiers,
609 Cow<'_, str>,
610 Option<Box<[GenericDefinition]>>,
611 Option<Box<[QualifiedType]>>,
612 Option<Box<[EnumEntry]>>,
613 ),
614 ) -> Self {
615 let (modifiers, ident, generics, implements, entries) = value;
616
617 let mut variables = Vec::new();
618 let mut functions = Vec::new();
619 let mut classes = Vec::new();
620 let mut enums = Vec::new();
621 let mut interfaces = Vec::new();
622
623 if let Some(entries) = entries {
624 for entry in entries {
625 match entry {
626 EnumEntry::Variables(v) => variables.append(&mut v.into_vec()),
627 EnumEntry::Function(f) => functions.push(f),
628 EnumEntry::Class(c) => classes.push(c),
629 EnumEntry::Enum(e) => enums.push(e),
630 EnumEntry::Interface(i) => interfaces.push(i),
631 EnumEntry::Skip => {}
632 }
633 }
634 }
635
636 Self {
637 modifiers,
638 ident: ident.to_string(),
639 generics: generics.unwrap_or(Box::new([])),
640 implements: implements.unwrap_or(Box::from([])),
641 classes: classes.into_iter().map(ClassCell::from).collect(),
642 enums: enums.into_iter().map(EnumCell::from).collect(),
643 interfaces: interfaces.into_iter().map(InterfaceCell::from).collect(),
644 variables: variables.into_boxed_slice(),
645 functions: functions.into_boxed_slice(),
646 }
647 }
648}
649
650#[derive(Debug, Clone)]
651pub(super) enum InterfaceEntry {
652 Variables(Box<[Variable]>),
653 Function(Function),
654 Class(Class),
655 Enum(Enum),
656 Interface(Interface),
657 Skip,
658}
659
660#[derive(Debug, Clone, PartialEq)]
661pub struct Interface {
662 pub modifiers: Modifiers,
663 pub ident: String,
664 pub generics: Box<[GenericDefinition]>,
665
666 pub extends: Box<[QualifiedType]>,
667 pub permits: Box<[QualifiedType]>,
668
669 pub variables: Box<[Variable]>,
670 pub functions: Box<[Function]>,
671
672 pub classes: Box<[ClassCell]>,
673 pub enums: Box<[EnumCell]>,
674 pub interfaces: Box<[InterfaceCell]>,
675}
676
677impl GetIdent for Interface {
678 fn ident(&self) -> &str {
679 self.ident.as_str()
680 }
681}
682
683pub type InterfaceCell = ObjectCell<Interface>;
684
685impl
686 From<(
687 Modifiers,
688 Cow<'_, str>,
689 Option<Box<[GenericDefinition]>>,
690 Option<Box<[QualifiedType]>>,
691 Option<Box<[QualifiedType]>>,
692 Option<Box<[InterfaceEntry]>>,
693 )> for Interface
694{
695 fn from(
696 value: (
697 Modifiers,
698 Cow<'_, str>,
699 Option<Box<[GenericDefinition]>>,
700 Option<Box<[QualifiedType]>>,
701 Option<Box<[QualifiedType]>>,
702 Option<Box<[InterfaceEntry]>>,
703 ),
704 ) -> Self {
705 let (modifiers, ident, generics, extends, permits, entries) = value;
706
707 let mut variables = Vec::new();
708 let mut functions = Vec::new();
709 let mut classes = Vec::new();
710 let mut enums = Vec::new();
711 let mut interfaces = Vec::new();
712
713 if let Some(entries) = entries {
714 for entry in entries {
715 match entry {
716 InterfaceEntry::Variables(v) => variables.extend_from_slice(&v),
717 InterfaceEntry::Function(f) => functions.push(f),
718 InterfaceEntry::Class(c) => classes.push(c),
719 InterfaceEntry::Enum(e) => enums.push(e),
720 InterfaceEntry::Interface(i) => interfaces.push(i),
721 InterfaceEntry::Skip => {}
722 }
723 }
724 }
725
726 Self {
727 modifiers,
728 ident: ident.to_string(),
729 extends: extends.unwrap_or(Box::new([])),
730 permits: permits.unwrap_or(Box::new([])),
731 variables: variables.into_boxed_slice(),
732 generics: generics.unwrap_or(Box::new([])),
733 functions: functions.into_boxed_slice(),
734 classes: classes.into_iter().map(ClassCell::from).collect(),
735 enums: enums.into_iter().map(EnumCell::from).collect(),
736 interfaces: interfaces.into_iter().map(InterfaceCell::from).collect(),
737 }
738 }
739}
740
741#[derive(Debug, Clone)]
742pub(super) enum RootEntry {
743 Class(Class),
744 Enum(Enum),
745 Interface(Interface),
746}
747
748#[derive(Debug, Clone, PartialEq)]
749pub struct Root {
750 pub package: String,
751 pub imports: Box<[String]>,
752 pub classes: Box<[ClassCell]>,
753 pub enums: Box<[EnumCell]>,
754 pub interfaces: Box<[InterfaceCell]>,
755}
756
757impl From<(Cow<'_, str>, Vec<Cow<'_, str>>, Option<Box<[RootEntry]>>)> for Root {
758 fn from(value: (Cow<'_, str>, Vec<Cow<'_, str>>, Option<Box<[RootEntry]>>)) -> Self {
759 let (package, mut imports, entries) = value;
760
761 let mut classes = Vec::new();
762 let mut enums = Vec::new();
763 let mut interfaces = Vec::new();
764
765 if let Some(entries) = entries {
766 for entry in entries {
767 match entry {
768 RootEntry::Class(c) => classes.push(c),
769 RootEntry::Enum(e) => enums.push(e),
770 RootEntry::Interface(i) => interfaces.push(i),
771 }
772 }
773 }
774
775 imports.push(Cow::from("java.lang.*"));
776
777 Self {
778 package: package.to_string(),
779 imports: imports.into_iter().map(String::from).collect(),
780 classes: classes.into_iter().map(ClassCell::from).collect(),
781 enums: enums.into_iter().map(EnumCell::from).collect(),
782 interfaces: interfaces.into_iter().map(InterfaceCell::from).collect(),
783 }
784 }
785}
786
787impl std::hash::Hash for Root {
788 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
789 std::ptr::hash(self, state);
790 }
791}