1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Expression tree for decompiled code.
use crate::types::{GenericType, JavaType, MethodDescriptor};
/// A type reference that may carry generics from a Signature attribute.
#[derive(Debug, Clone, PartialEq)]
pub enum TypeRef {
/// Plain descriptor type.
J(JavaType),
/// Generic signature type.
G(GenericType),
}
impl TypeRef {
pub fn to_java(&self) -> String {
match self {
TypeRef::J(t) => t.to_java(true),
TypeRef::G(g) => g.to_java(),
}
}
/// Underlying erased Java type (for generics: erased class/primitive).
pub fn erased(&self) -> JavaType {
match self {
TypeRef::J(t) => t.clone(),
TypeRef::G(g) => generic_to_erased(g),
}
}
pub fn slot_size(&self) -> usize {
self.erased().slot_size()
}
pub fn is_wide(&self) -> bool {
self.erased().is_wide()
}
/// The internal class name if this is a plain object reference.
pub fn internal_name(&self) -> Option<&str> {
match self {
TypeRef::J(JavaType::Object(n)) => Some(n),
TypeRef::G(GenericType::Class(cs)) if cs.parts.iter().all(|p| p.args.is_empty()) => {
None
} // owned string; caller uses erased
_ => None,
}
}
}
pub fn generic_to_erased(g: &GenericType) -> JavaType {
match g {
GenericType::Primitive(c) => match c {
'V' => JavaType::Void,
'Z' => JavaType::Boolean,
'B' => JavaType::Byte,
'C' => JavaType::Char,
'S' => JavaType::Short,
'I' => JavaType::Int,
'F' => JavaType::Float,
'J' => JavaType::Long,
'D' => JavaType::Double,
_ => JavaType::Void,
},
GenericType::Class(cs) => JavaType::Object(cs.internal_name()),
GenericType::Array(inner) => JavaType::Array(Box::new(generic_to_erased(inner))),
GenericType::TypeVar(_) => JavaType::Object("java/lang/Object".into()),
GenericType::Wildcard(_) => JavaType::Object("java/lang/Object".into()),
}
}
impl From<JavaType> for TypeRef {
fn from(t: JavaType) -> Self {
TypeRef::J(t)
}
}
/// A constant value with its source-level type.
#[derive(Debug, Clone, PartialEq)]
pub enum ConstVal {
Int(i32),
Long(i64),
Float(f32),
Double(f64),
Str(String),
/// `null` literal.
Null,
/// Unloaded class constant resolved to a class literal or `X.class`.
ClassLit(TypeRef),
}
impl ConstVal {
pub fn type_ref(&self) -> TypeRef {
match self {
ConstVal::Int(_) => JavaType::Int.into(),
ConstVal::Long(_) => JavaType::Long.into(),
ConstVal::Float(_) => JavaType::Float.into(),
ConstVal::Double(_) => JavaType::Double.into(),
ConstVal::Str(_) => JavaType::Object("java/lang/String".into()).into(),
ConstVal::Null => JavaType::Object("java/lang/Object".into()).into(),
ConstVal::ClassLit(_) => JavaType::Object("java/lang/Class".into()).into(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
Neg, // -x
Not, // !x
BitNot, // ~x
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Rem,
Shl,
Shr,
Ushr,
And,
Or,
Xor,
Eq,
Ne,
Lt,
Ge,
Gt,
Le,
/// Reference equality on objects (==).
RefEq,
RefNe,
/// Logical && and || (from short-circuit structuring).
LogAnd,
LogOr,
/// String concatenation `+`.
StrCat,
}
impl BinOp {
/// Java operator precedence (higher binds tighter).
pub fn precedence(&self) -> u8 {
match self {
BinOp::Mul | BinOp::Div | BinOp::Rem => 13,
BinOp::Add | BinOp::Sub | BinOp::StrCat => 12,
BinOp::Shl | BinOp::Shr | BinOp::Ushr => 11,
BinOp::Lt | BinOp::Ge | BinOp::Gt | BinOp::Le => 10,
BinOp::Eq | BinOp::Ne | BinOp::RefEq | BinOp::RefNe => 9,
BinOp::And => 8,
BinOp::Xor => 7,
BinOp::Or => 6,
BinOp::LogAnd => 4,
BinOp::LogOr => 3,
}
}
pub fn symbol(&self) -> &'static str {
match self {
BinOp::Add | BinOp::StrCat => "+",
BinOp::Sub => "-",
BinOp::Mul => "*",
BinOp::Div => "/",
BinOp::Rem => "%",
BinOp::Shl => "<<",
BinOp::Shr => ">>",
BinOp::Ushr => ">>>",
BinOp::And => "&",
BinOp::Or => "|",
BinOp::Xor => "^",
BinOp::Eq | BinOp::RefEq => "==",
BinOp::Ne | BinOp::RefNe => "!=",
BinOp::Lt => "<",
BinOp::Ge => ">=",
BinOp::Gt => ">",
BinOp::Le => "<=",
BinOp::LogAnd => "&&",
BinOp::LogOr => "||",
}
}
/// The reversed comparison operator (for condition inversion).
pub fn invert(self) -> Option<BinOp> {
Some(match self {
BinOp::Eq | BinOp::RefEq => BinOp::Ne,
BinOp::Ne | BinOp::RefNe => BinOp::Eq,
BinOp::Lt => BinOp::Ge,
BinOp::Ge => BinOp::Lt,
BinOp::Gt => BinOp::Le,
BinOp::Le => BinOp::Gt,
// LogAnd/LogOr have NO operand-preserving inversion: negating
// them is De Morgan (negate both operands AND swap the op) —
// convert.rs negate() handles that recursively; an op-only swap
// here silently changed the condition's meaning (Arrays.equals'
// folded `a == null || a2 == null` inverted to `a == null &&
// a2 == null`, NPE-ing the a2==null path).
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssignOp {
Plain,
Add,
Sub,
Mul,
Div,
Rem,
Shl,
Shr,
Ushr,
And,
Or,
Xor,
}
impl AssignOp {
pub fn symbol(&self) -> &'static str {
match self {
AssignOp::Plain => "=",
AssignOp::Add => "+=",
AssignOp::Sub => "-=",
AssignOp::Mul => "*=",
AssignOp::Div => "/=",
AssignOp::Rem => "%=",
AssignOp::Shl => "<<=",
AssignOp::Shr => ">>=",
AssignOp::Ushr => ">>>=",
AssignOp::And => "&=",
AssignOp::Or => "|=",
AssignOp::Xor => "^=",
}
}
}
/// Lambda kind inferred from invokedynamic + LambdaMetafactory.
#[derive(Debug, Clone, PartialEq)]
pub enum LambdaKind {
/// `args -> body` referencing an implementation method.
Lambda,
/// `Cls::name` static/instance reference.
MethodRef,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LambdaExpr {
pub kind: LambdaKind,
/// Functional interface method name/desc for casting ambiguity if needed.
pub sam_name: String,
pub sam_desc: MethodDescriptor,
/// LambdaMetafactory instantiatedMethodType (bootstrap arg 2): the
/// SAM descriptor as javac INSTANTIATED it at this site — for
/// `.<ConstantDesc>map(Utf8Entry::stringValue)` it is
/// `(LUtf8Entry;)LConstantDesc;` against the erased samMethodType
/// `(LObject;)LObject;`. The only bytecode record of explicit type
/// arguments on a lambda/method-ref call.
pub inst_sam_desc: Option<MethodDescriptor>,
/// Implementation method (for Lambda kind: the body is emitted from it,
/// or referenced by name when it belongs to another class).
pub impl_owner: String,
pub impl_name: String,
pub impl_desc: MethodDescriptor,
pub impl_is_static: bool,
/// Captured arguments (evaluated at indy call site), in impl-arg order
/// after the SAM parameters.
pub captures: Vec<Expr>,
/// SAM parameter names (synthesized if absent).
pub param_names: Vec<String>,
/// The SAM interface's internal name (the indy descriptor's return):
/// a lambda used as a call RECEIVER must print with the source's SAM
/// cast (`((BooleanSupplier) () -> ..).getAsBoolean()` — a bare lambda
/// cannot be an owner: 此处不应为 lambda 表达式, jdk26 Proxy).
pub sam_cls: String,
/// Method-ref receiver class name, for `X::y` form.
pub ref_receiver: Option<String>,
/// Snapshot renames for captured outer locals that are NOT
/// effectively final (the decompiler hoists+reassigns them):
/// (outer var id, impl-method param var id, snapshot name). The
/// method pass declares `final T name = outer;` before the lambda's
/// statement and the printer renames the impl param accordingly.
pub capture_snaps: Vec<(u32, u32, String)>,
}
/// Resolved static bootstrap-method argument.
#[derive(Debug, Clone, PartialEq)]
pub enum BsmArg {
Str(String),
Cls(String),
/// Integer-valued constant label (Java 21+ typeSwitch constant
/// patterns: `case 1:`, char constants arrive as their code point).
Int(i32),
Other,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ConcatPart {
Str(Expr),
/// Recipe constant segment.
Const(String),
}
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
Const(ConstVal),
/// Local variable by VarId, with its declared type (needed for
/// category-1 vs category-2 stack operations like dup2/pop2).
Local {
var: u32,
ty: TypeRef,
},
This,
/// `new T(args)` (constructor call folded with New when possible).
New {
cls: String,
ty: TypeRef,
args: Vec<Expr>,
/// true if this is a raw `new` whose `<init>` hasn't been folded yet.
raw: bool,
},
/// Array creation: `new int[n]`, `new int[]{...}`, `new int[a][b][]`.
NewArray {
elem: TypeRef,
/// dimension sizes for the created dimensions
dims: Vec<Expr>,
/// trailing empty dimensions count (e.g. `new int[3][]` -> dims=[3], trailing=1)
trailing_dims: u8,
/// initializer for `new T[]{...}` form
init: Option<Vec<Expr>>,
},
/// Multi-dimensional array creation `multianewarray`.
NewMultiArray {
ty: TypeRef,
dims: Vec<Expr>,
},
Field {
/// None = `this` (instance field of current class) or static import-style.
owner: Option<Box<Expr>>,
/// Declaring class internal name.
cls: String,
name: String,
ty: TypeRef,
is_static: bool,
},
Method {
owner: Option<Box<Expr>>,
cls: String,
name: String,
desc: MethodDescriptor,
args: Vec<Expr>,
is_static: bool,
is_interface: bool,
/// invokespecial (super call / constructor / private).
is_special: bool,
/// `super.m(...)` form.
is_super: bool,
/// invokedynamic without recognized pattern.
is_dynamic: bool,
/// Explicit type arguments (`Cls.<E>m(...)`) restored for generic
/// calls in throw position, where inference would pick the bound.
type_args: Vec<String>,
},
ArrayIndex {
array: Box<Expr>,
index: Box<Expr>,
},
Cast {
ty: TypeRef,
e: Box<Expr>,
},
InstanceOf {
e: Box<Expr>,
ty: TypeRef,
},
Un {
op: UnOp,
e: Box<Expr>,
},
Bin {
op: BinOp,
l: Box<Expr>,
r: Box<Expr>,
/// Type context for `+` disambiguation (string vs numeric).
ty: Option<TypeRef>,
},
Cond {
c: Box<Expr>,
t: Box<Expr>,
f: Box<Expr>,
},
Assign {
target: Box<Expr>,
op: AssignOp,
value: Box<Expr>,
},
/// `++x` / `--x` (delta = +1 / -1)
PreIncDec {
e: Box<Expr>,
delta: i64,
wide: bool,
},
/// `x++` / `x--`
PostIncDec {
e: Box<Expr>,
delta: i64,
wide: bool,
},
Lambda(Box<LambdaExpr>),
/// String concatenation via StringConcatFactory recipe.
StringConcat(Vec<ConcatPart>),
/// Pre-rendered source fragment (used for captured expressions that are
/// substituted across method contexts).
Raw(String),
/// Pre-rendered capture text WITH the captured local's declared type:
/// comparisons inside local-class bodies need the operand's generic
/// type to drive witnesses (erased val$ field types cannot).
RawT(String, TypeRef),
/// Unrecognized invokedynamic fallback.
Invokedynamic {
name: String,
desc: MethodDescriptor,
args: Vec<Expr>,
bsm_text: String,
/// Resolved static bootstrap arguments (for SwitchBootstraps
/// typeSwitch restoration).
bsm_static_args: Vec<BsmArg>,
},
/// `new Anon(args) { ...class body... }` — anonymous class instantiation.
AnonNew {
/// The anonymous class itself.
cls: String,
/// Interface being implemented, or superclass (Object suppressed).
base: TypeRef,
args: Vec<Expr>,
/// Decompiled class body lines (already indented relative).
body: String,
},
}
impl Expr {
/// Best-effort static type of this expression.
pub fn type_ref(&self) -> TypeRef {
match self {
Expr::Const(c) => c.type_ref(),
Expr::Local { ty, .. } => ty.clone(),
Expr::This => JavaType::Object("java/lang/Object".into()).into(),
Expr::New { ty, .. } => ty.clone(),
// dims carries the lengths; `trailing_dims` counts EXTRA []
// levels beyond the element type (`new byte[][]{a,b,c}` =
// elem Byte + the init dimension + 1 trailing). type_ref
// dropped the trailing levels (ML_DSA_Impls.implGenerate-
// KeyPair: the byte[][] literal evidenced byte[] for the
// return-temp slot — byte[][]无法转换为byte[] x2 classes).
Expr::NewArray {
elem,
trailing_dims,
..
} => {
let mut t = elem.erased();
for _ in 0..=(*trailing_dims as usize) {
t = JavaType::Array(Box::new(t));
}
t.into()
}
Expr::NewMultiArray { ty, .. } => ty.clone(),
Expr::Field { ty, .. } => ty.clone(),
Expr::Method { desc, .. } => desc.ret.clone().into(),
Expr::ArrayIndex { array, .. } => match &**array {
other => match other.type_ref().erased() {
JavaType::Array(inner) => (*inner).clone().into(),
t => t.into(),
},
},
Expr::Cast { ty, .. } => ty.clone(),
Expr::InstanceOf { .. } => JavaType::Boolean.into(),
Expr::Un { op: UnOp::Not, .. } => JavaType::Boolean.into(),
Expr::Un { e, .. } => e.type_ref(),
Expr::Bin { op, ty, l, .. } => match op {
// Comparisons and short-circuit logicals are boolean
// regardless of operand types — the stored `ty` (when
// present it mirrors the operands) misled the bool->int
// assignment rewrite (`int mode = e != null;` stayed
// unrewrapped: jdk11 SynchronousQueue).
BinOp::Eq
| BinOp::Ne
| BinOp::Lt
| BinOp::Ge
| BinOp::Gt
| BinOp::Le
| BinOp::RefEq
| BinOp::RefNe
| BinOp::LogAnd
| BinOp::LogOr => JavaType::Boolean.into(),
_ => ty.clone().unwrap_or_else(|| l.type_ref()),
},
Expr::Cond { t, f, .. } => {
// Divergent reference branches join to their LUB; without
// hierarchy access that is plain Object (jdk17
// CodePointTrie: `c ? new Small32(..) : new Fast32(..)`
// typed the merge var Small32 and the sibling branch
// became "条件表达式中的类型错误").
let tt = t.type_ref();
let ft = f.type_ref();
match (&tt, &ft) {
(TypeRef::J(JavaType::Object(a)), TypeRef::J(JavaType::Object(b)))
if a != b =>
{
JavaType::Object("java/lang/Object".into()).into()
}
_ => tt,
}
}
Expr::Assign { value, .. } => value.type_ref(),
Expr::PreIncDec { e, .. } | Expr::PostIncDec { e, .. } => e.type_ref(),
Expr::Lambda(_) => JavaType::Object("java/lang/Object".into()).into(),
Expr::Raw(_) => JavaType::Object("java/lang/Object".into()).into(),
Expr::RawT(_, ty) => ty.clone(),
Expr::AnonNew { cls, .. } => JavaType::Object(cls.clone()).into(),
Expr::StringConcat(_) => JavaType::Object("java/lang/String".into()).into(),
Expr::Invokedynamic { desc, .. } => desc.ret.clone().into(),
}
}
/// True if emitting this expression as a statement component needs parens
/// at the given outer precedence context.
pub fn needs_parens(&self, outer_prec: u8, is_right: bool) -> bool {
match self {
Expr::Bin { op, .. } => {
let p = op.precedence();
p < outer_prec || (is_right && p == outer_prec)
}
// String concat is an additive-level expression: as a method
// receiver or cast operand it MUST parenthesize, or a call
// textually binds to the last operand (jdk11
// SSLSessionContextImpl.getKey: `(hostname + ":" + port)
// .toLowerCase(..)` rendered as .. + port.toLowerCase(..) —
// 无法取消引用int; SSLTrafficKeyDerivation's ("tls13 "+label)
// .getBytes lost to byte[] — String无法转换为byte[]).
Expr::StringConcat(_) => {
let p = BinOp::Add.precedence();
p < outer_prec || (is_right && p == outer_prec)
}
Expr::InstanceOf { .. } => outer_prec > 10,
Expr::Cond { .. } => outer_prec > 2,
Expr::Assign { .. } | Expr::PreIncDec { .. } | Expr::PostIncDec { .. } => {
outer_prec > 1
}
Expr::Un { .. } => outer_prec > 14,
Expr::Cast { .. } => outer_prec > 13,
// `new int[1][0]` as an indexing base or receiver must
// parenthesize: the emitted `new int[1][0][0]` re-parses as a
// THREE-dim creation, not an index into a two-dim one — and as
// an assignment target it is not a variable at all
// (CFR prints `(new int[1][0])[0] = new int[]{a};`).
Expr::NewArray { .. } | Expr::NewMultiArray { .. } => outer_prec >= 15,
_ => false,
}
}
}