#[derive(Debug, Clone, PartialEq)]
pub struct Program {
pub class_name: String,
pub main: Vec<Stmt>,
pub main_param: Option<String>,
pub methods: Vec<Method>,
pub classes: Vec<Class>,
pub uses_exceptions: bool,
pub uses_functional: bool,
}
pub const ENUM_NAME: &str = "#name";
pub const ENUM_ORDINAL: &str = "#ordinal";
pub fn enum_global(class: &str, constant: &str) -> String {
format!("#enum#{class}#{constant}")
}
pub fn static_global(class: &str, field: &str) -> String {
format!("#static#{class}#{field}")
}
pub fn hidden_field_key(class: &str, field: &str) -> String {
format!("#hide#{class}#{field}")
}
pub fn field_key_name(key: &str) -> &str {
match key.strip_prefix("#hide#") {
Some(rest) => rest.rsplit('#').next().unwrap_or(rest),
None => key,
}
}
pub const OUTER_THIS: &str = "this$0";
#[derive(Debug, Clone, PartialEq)]
pub struct Class {
pub type_params: Vec<String>,
pub super_targs: Vec<String>,
pub interface_targs: Vec<Vec<String>>,
pub is_sealed: bool,
pub is_abstract: bool,
pub permits: Vec<String>,
pub name: String,
pub binary: String,
pub superclass: Option<String>,
pub interfaces: Vec<String>,
pub is_interface: bool,
pub is_enum: bool,
pub is_record: bool,
pub enum_constants: Vec<EnumConstant>,
pub fields: Vec<FieldDecl>,
pub static_fields: Vec<FieldDecl>,
pub static_init: Vec<Stmt>,
pub inst_init: Vec<Stmt>,
pub ctors: Vec<Ctor>,
pub methods: Vec<Method>,
pub captures: Vec<Param>,
pub line: u32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EnumConstant {
pub name: String,
pub line: u32,
pub args: Vec<Expr>,
pub body_class: Option<String>,
}
pub fn enum_body_class(enum_name: &str, constant: &str) -> String {
format!("{enum_name}#{constant}")
}
#[derive(Debug, Clone, PartialEq)]
pub struct FieldDecl {
pub ty: String,
pub targs: Vec<String>,
pub super_slots: Vec<usize>,
pub wildcard: bool,
pub name: String,
pub is_final: bool,
pub init: Option<Expr>,
pub line: u32,
pub has_init: bool,
pub init_pos: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Ctor {
pub params: Vec<Param>,
pub body: Vec<Stmt>,
pub line: u32,
pub end_line: u32,
pub implicit: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Method {
pub name: String,
pub owner: String,
pub params: Vec<Param>,
pub ret: String,
pub ret_targs: Vec<String>,
pub ret_super_slots: Vec<usize>,
pub ret_wildcard: bool,
pub body: Vec<Stmt>,
pub is_abstract: bool,
pub access: Access,
pub line: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Access {
Public,
Protected,
Package,
Private,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Param {
pub ty: String,
pub targs: Vec<String>,
pub super_slots: Vec<usize>,
pub wildcard: bool,
pub name: String,
pub varargs: bool,
pub is_final: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Stmt {
pub line: u32,
pub kind: StmtKind,
}
impl Stmt {
pub fn new(line: u32, kind: StmtKind) -> Self {
Stmt { line, kind }
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum StmtKind {
Local {
ty: String,
targs: Vec<String>,
wildcard: bool,
super_slots: Vec<usize>,
name: String,
init: Option<Expr>,
is_final: bool,
},
Locals(Vec<Stmt>),
Assign {
name: String,
op: AssignOp,
value: Expr,
},
IndexAssign {
array: Expr,
index: Expr,
op: AssignOp,
value: Expr,
},
FieldAssign {
recv: Expr,
name: String,
op: AssignOp,
value: Expr,
},
Expr(Expr),
If {
cond: Expr,
then: Vec<Stmt>,
els: Vec<Stmt>,
},
While { cond: Expr, body: Vec<Stmt> },
DoWhile { body: Vec<Stmt>, cond: Expr },
For {
init: Vec<Stmt>,
cond: Option<Expr>,
update: Vec<Stmt>,
body: Vec<Stmt>,
},
ForEach {
ty: String,
targs: Vec<String>,
super_slots: Vec<usize>,
name: String,
is_final: bool,
iter: Expr,
body: Vec<Stmt>,
},
Switch {
disc: Expr,
groups: Vec<SwitchGroup>,
},
Labeled { label: String, body: Box<Stmt> },
Try {
body: Vec<Stmt>,
catches: Vec<CatchArm>,
finally_body: Vec<Stmt>,
},
Throw(Expr),
LocalClass(String),
Assert { cond: Expr, detail: Option<Expr> },
Yield(Expr),
Break(Option<String>),
Continue(Option<String>),
Return(Option<Expr>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct SwitchGroup {
pub labels: Vec<Expr>,
pub is_default: bool,
pub guard: Option<Expr>,
pub body: Vec<Stmt>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CatchArm {
pub types: Vec<String>,
pub name: String,
pub is_final: bool,
pub body: Vec<Stmt>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssignOp {
Assign,
Add,
Sub,
Mul,
Div,
Mod,
BitAnd,
BitOr,
BitXor,
Shl,
Shr,
Ushr,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
ClassLit(String),
Int(i64),
Long(i64),
Float(f64),
Float32(f64),
Str(String),
Char(char),
Bool(bool),
Var(String),
Unary {
op: UnOp,
rhs: Box<Expr>,
},
Binary {
op: BinOp,
lhs: Box<Expr>,
rhs: Box<Expr>,
},
Ternary {
cond: Box<Expr>,
then: Box<Expr>,
els: Box<Expr>,
},
Println {
newline: bool,
err: bool,
arg: Option<Box<Expr>>,
},
PostIncDec {
name: String,
inc: bool,
},
PreIncDec {
name: String,
inc: bool,
},
IncDec {
target: Box<Expr>,
inc: bool,
post: bool,
line: u32,
},
Assign {
target: Box<Expr>,
op: AssignOp,
value: Box<Expr>,
line: u32,
},
Cast {
ty: String,
targs: Vec<String>,
expr: Box<Expr>,
line: u32,
},
Call {
name: String,
args: Vec<Expr>,
line: u32,
},
MethodCall {
recv: Box<Expr>,
method: String,
args: Vec<Expr>,
line: u32,
},
NewArray {
elem_ty: String,
sizes: Vec<Expr>,
extra_dims: usize,
},
ArrayLit {
elems: Vec<Expr>,
elem_ty: Option<String>,
},
Index {
array: Box<Expr>,
index: Box<Expr>,
},
Field {
recv: Box<Expr>,
name: String,
},
NewObject {
class: String,
args: Vec<Expr>,
targs: Option<Vec<String>>,
outer: Option<Box<Expr>>,
line: u32,
},
This,
TypePattern {
class: String,
binding: Option<String>,
components: Vec<Expr>,
},
InstanceOf {
expr: Box<Expr>,
class: String,
binding: Option<String>,
components: Vec<Expr>,
},
Lambda {
params: Vec<String>,
finals: Vec<bool>,
body: LambdaBody,
line: u32,
},
MethodRef {
recv: Box<Expr>,
method: String,
line: u32,
},
SwitchExpr {
disc: Box<Expr>,
arms: Vec<SwitchArm>,
line: u32,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct SwitchArm {
pub labels: Vec<Expr>,
pub is_default: bool,
pub guard: Option<Expr>,
pub body: SwitchArmBody,
}
#[derive(Debug, Clone, PartialEq)]
pub enum SwitchArmBody {
Expr(Box<Expr>),
Block(Vec<Stmt>),
}
#[derive(Debug, Clone, PartialEq)]
pub enum LambdaBody {
Expr(Box<Expr>),
Block(Vec<Stmt>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
Neg,
Not,
BitNot,
Plus,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Mod,
Eq,
Ne,
Lt,
Gt,
Le,
Ge,
And,
Or,
BitAnd,
BitOr,
BitXor,
Shl,
Shr,
Ushr,
}
pub fn generic_parts(ty: &str) -> (String, Vec<String>) {
let Some(open) = ty.find('<') else {
return (ty.to_string(), Vec::new());
};
let close = ty.rfind('>').unwrap_or(ty.len() - 1);
let suffix = &ty[close + 1..];
let name = format!("{}{suffix}", &ty[..open]);
if !suffix.is_empty() {
return (name, Vec::new());
}
(name, split_top_level(&ty[open + 1..close]))
}
fn split_top_level(s: &str) -> Vec<String> {
let mut out = Vec::new();
let mut depth = 0i32;
let mut cur = String::new();
for ch in s.chars() {
match ch {
'<' => depth += 1,
'>' => depth -= 1,
',' if depth == 0 => {
out.push(std::mem::take(&mut cur));
continue;
}
_ => {}
}
cur.push(ch);
}
if !cur.is_empty() {
out.push(cur);
}
out
}
pub fn normalize_type_arg(raw: &str) -> String {
let s = raw.trim();
if let Some(rest) = s.strip_prefix('?') {
let rest = rest.trim_start();
return match rest.strip_prefix("extends") {
Some(bound) if bound.starts_with(char::is_whitespace) => {
normalize_type_arg(bound)
}
_ => "Object".to_string(),
};
}
let (head, tail) = match s.find(['<', '[']) {
Some(i) => s.split_at(i),
None => (s, ""),
};
let simple = head.rsplit('.').next().unwrap_or(head).trim();
let Some(inner) = tail.strip_prefix('<') else {
return format!("{simple}{}", tail.replace(' ', ""));
};
let mut depth = 1i32;
let mut end = inner.len();
for (i, ch) in inner.char_indices() {
match ch {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth == 0 {
end = i;
break;
}
}
_ => {}
}
}
let args: Vec<String> = split_top_level(&inner[..end])
.iter()
.map(|a| normalize_type_arg(a))
.collect();
let rest = inner.get(end + 1..).unwrap_or("").replace(' ', "");
format!("{simple}<{}>{rest}", args.join(","))
}