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