jdc_core/emit.rs
1//! Java source emission from the statement/expression tree.
2
3use crate::types::JavaType;
4
5use crate::ctx::MethodBody;
6use crate::ir::expr::{BinOp, ConcatPart, ConstVal, Expr, LambdaKind, TypeRef, UnOp};
7use crate::ir::stmt::{CaseGroup, Catch, Stmt};
8use crate::var::VarTable;
9
10pub struct Printer<'a> {
11 /// Front-end services: naming, nesting, type queries, nested bodies.
12 pub ctx: &'a dyn crate::ctx::Ctx,
13 pub vt: &'a VarTable,
14 out: String,
15 indent: usize,
16 /// Depth guard for recursive lambda printing.
17 lambda_depth: usize,
18 /// Names visible in enclosing lambda/method scopes BEYOND self.vt,
19 /// accumulated down the lambda print chain: a nested lambda's locals
20 /// must not redeclare ANY of them (jdk26 PackageSnippets
21 /// .fooToBarUnrolled: the depth-2 codeBuilder lambda's foreach `i$`
22 /// collided with the METHOD-level `i$` — the depth-1 rename only
23 /// consulted depth-1's vt, 已在方法中定义了变量 i$).
24 outer_names: Vec<String>,
25 /// Sequence for unbound catch parameters (`ignored`, `ignored2`, …):
26 /// two catch scopes can NEST (a try inside a catch body) and javac
27 /// rejects duplicate names across overlapping scopes ("已在方法
28 /// invokeSuspend(Object)中定义了变量 ignored", weixin hl5/m ×56).
29 ignored_seq: u32,
30 /// True when the enclosing method returns boolean.
31 /// Reused per-statement line buffer (millions of statements: the
32 /// fresh-String-per-line pattern re-allocated and re-grew each time).
33 line_buf: String,
34 pub ret_bool: bool,
35 /// True while rendering the ROOT of an expression statement: a
36 /// signature-polymorphic call there must stay bare (`NEXT.compareAndSet
37 /// (b, n, p);`) — `(boolean) call();` is not a legal statement.
38 suppress_poly_cast: bool,
39 /// True while rendering the direct child of a cast expression: a cast
40 /// gives the diamond NO target type, so ` (T) new X<>(args)` infers
41 /// Object bounds and then fails the cast — while the bare/raw form
42 /// `(T) new X(args)` compiles (unchecked).
43 suppress_diamond: bool,
44 /// True while rendering a conditional expression's branches. Pre-Java-8
45 /// (major < 52) conditionals are NOT poly expressions: a diamond branch
46 /// (`c ? new HashMap<>(..) : new LinkedHashMap<>(..)`) infers each side
47 /// standalone to <Object,Object> and fails the assignment target (jdk7
48 /// HashSet.readObject 不兼容的类型 — the golden source carried explicit
49 /// <E,Object> args). Diamond branches print RAW there instead:
50 /// unchecked but always compilable.
51 in_cond: bool,
52 /// Instantiated SAM return type while rendering the Lambda directly
53 /// inside a cast to a generic functional interface: the lambda body's
54 /// returns may need `(R) value` witnesses (jdk17 Collectors
55 /// `(Function<I,R>) i -> i`).
56 lambda_sam_ret: Option<TypeRef>,
57 /// The method's generic signature return (functional-interface or
58 /// array form): a lambda in RETURN position has no cast node to hang
59 /// the SAM witness on, so the Return arm derives it from this.
60 ret_sam: Option<TypeRef>,
61 /// True when the enclosing method returns char: int constants in the
62 /// returned expression render as char literals (bytecode chars are
63 /// ints; `return cond ? 63 : 105;` in a char method is a lossy
64 /// conversion — source was `? '?' : 'i'`, jdk XML Parser x23).
65 pub ret_char: bool,
66 /// Narrowing-return markers: int-valued expressions in the return
67 /// need `(byte)`/`(short)` casts (jdk11 MemberName:
68 /// `byte normalVirtual = cond ? 5 : 9;`).
69 pub ret_byte: bool,
70 pub ret_short: bool,
71 /// Memoized twin-exists probe for the same-package member-shadow
72 /// check, keyed by first segment (class_name is constant per ctx;
73 /// shared with sub-printers). The chain-walk does up to 4 registry
74 /// lookups per level — per-call that cost ~30% on weixin; per
75 /// distinct segment it is amortized to nothing.
76 twin_cache: std::rc::Rc<
77 std::cell::RefCell<std::collections::HashMap<String, bool>>,
78 >,
79}
80
81impl<'a> Printer<'a> {
82 pub fn new(ctx: &'a dyn crate::ctx::Ctx, vt: &'a VarTable) -> Self {
83 Printer {
84 ctx,
85 vt,
86 out: String::new(),
87 indent: 0,
88 lambda_depth: 0,
89 outer_names: Vec::new(),
90 ignored_seq: 0,
91 line_buf: String::new(),
92 ret_bool: false,
93 suppress_poly_cast: false,
94 suppress_diamond: false,
95 in_cond: false,
96 lambda_sam_ret: None,
97 ret_sam: None,
98 ret_char: false,
99 ret_byte: false,
100 ret_short: false,
101 twin_cache: std::rc::Rc::new(std::cell::RefCell::new(
102 std::collections::HashMap::new(),
103 )),
104 }
105 }
106
107 pub fn with_ret_bool(mut self, b: bool) -> Self {
108 self.ret_bool = b;
109 self
110 }
111
112 pub fn with_ret_sam(mut self, t: Option<TypeRef>) -> Self {
113 self.ret_sam = t;
114 self
115 }
116 pub fn with_ret_char(mut self, b: bool) -> Self {
117 self.ret_char = b;
118 self
119 }
120
121 pub fn with_ret_narrow(mut self, byte: bool, short: bool) -> Self {
122 self.ret_byte = byte;
123 self.ret_short = short;
124 self
125 }
126
127 /// Printer rendering into a caller-provided buffer: the method text
128 /// (signature, braces) and the printed body land in ONE string —
129 /// ddc used to render the body separately and copy it line-by-line
130 /// into the class buffer (a full extra pass over every method).
131 pub fn with_output(mut self, out: String) -> Self {
132 self.out = out;
133 self
134 }
135
136 /// Printer starting at a fixed indentation level (method bodies at 1).
137 pub fn with_indent(mut self, indent: usize) -> Self {
138 self.indent = indent;
139 self
140 }
141
142 pub fn into_string(mut self, body: &Stmt) -> String {
143 // The old unconditional truncate_dead_ends rebuilt (deep-cloned)
144 // the whole statement tree per method — a top profile cost. The
145 // truncation case is rare: probe read-only first.
146 if tree_has_dead_end(body) {
147 let truncated = truncate_dead_ends(body);
148 self.stmt(&truncated);
149 } else {
150 self.stmt(body);
151 }
152 self.out
153 }
154
155 /// Print an expression that appears in a boolean context; int 0/1
156 /// constants become true/false.
157 fn bool_ish_expr(x: &Expr) -> bool {
158 match x {
159 Expr::Const(ConstVal::Int(n)) => *n == 0 || *n == 1,
160 Expr::Cond { t, f, .. } => {
161 matches!(&**t, Expr::Const(ConstVal::Int(0 | 1)))
162 && matches!(&**f, Expr::Const(ConstVal::Int(0 | 1)))
163 }
164 Expr::Un {
165 op: crate::ir::expr::UnOp::Not,
166 ..
167 }
168 | Expr::InstanceOf { .. } => true,
169 Expr::Bin { op, .. } => matches!(
170 op,
171 crate::ir::expr::BinOp::Eq
172 | crate::ir::expr::BinOp::Ne
173 | crate::ir::expr::BinOp::Lt
174 | crate::ir::expr::BinOp::Ge
175 | crate::ir::expr::BinOp::Gt
176 | crate::ir::expr::BinOp::Le
177 | crate::ir::expr::BinOp::RefEq
178 | crate::ir::expr::BinOp::RefNe
179 | crate::ir::expr::BinOp::LogAnd
180 | crate::ir::expr::BinOp::LogOr
181 ),
182 other => other.type_ref().erased() == crate::types::JavaType::Boolean,
183 }
184 }
185
186 /// bool_ish_expr with VarTable resolution: booleanize retypes the vt
187 /// while embedded Local tys stay frozen, and a bitwise bin over
188 /// bool-ish sides is itself boolean (jdk26 LinkedTransferQueue
189 /// `(spin & !upc) == 0`).
190 fn bool_ish_vt(&self, x: &Expr) -> bool {
191 match x {
192 Expr::Local { var, .. } => {
193 matches!(
194 self.vt.var(*var).ty.erased(),
195 crate::types::JavaType::Boolean
196 )
197 }
198 Expr::Bin {
199 op: crate::ir::expr::BinOp::And | crate::ir::expr::BinOp::Or | crate::ir::expr::BinOp::Xor,
200 l,
201 r,
202 ..
203 } => self.bool_ish_vt(l) && self.bool_ish_vt(r),
204 _ => Self::bool_ish_expr(x),
205 }
206 }
207
208 pub fn expr_bool(&mut self, e: &Expr, out: &mut String) {
209 match e {
210 Expr::Const(ConstVal::Int(n)) => {
211 out.push_str(if *n != 0 { "true" } else { "false" });
212 }
213 // Bitwise ops over boolean-ish operands print as their
214 // logical form: javac computes `a != b` over booleans as
215 // IXOR of 0/1 ints (jdk17 DecimalFormat isNegative:
216 // `(c1 ? 1 : 0) ^ (c2 ? 1 : 0)` against a boolean local —
217 // "int无法转换为boolean").
218 Expr::Bin { op: bop, l, r, .. }
219 if matches!(
220 bop,
221 crate::ir::expr::BinOp::Xor
222 | crate::ir::expr::BinOp::And
223 | crate::ir::expr::BinOp::Or
224 ) && self.bool_ish_vt(l)
225 && self.bool_ish_vt(r) =>
226 {
227 let sym = match bop {
228 crate::ir::expr::BinOp::Xor => "^",
229 crate::ir::expr::BinOp::And => "&",
230 _ => "|",
231 };
232 // Parenthesize composite sides: expr_bool renders `||`/
233 // `&&` conditions bare and ^ binds LOOSER than && but
234 // TIGHTER than || (a || b && c ^ d would regroup).
235 for (i, side) in [l.as_ref(), r.as_ref()].iter().enumerate() {
236 if i > 0 {
237 out.push(' ');
238 out.push_str(sym);
239 out.push(' ');
240 }
241 let needs = matches!(
242 side,
243 Expr::Bin { .. } | Expr::Cond { .. } | Expr::Assign { .. }
244 );
245 if needs {
246 out.push('(');
247 }
248 self.expr_bool(side, out);
249 if needs {
250 out.push(')');
251 }
252 }
253 }
254 Expr::Cond { c, t, f } => {
255 // `x ? true : false` → x ; `x ? false : true` → !x
256 let tb = const_bool(t);
257 let fb = const_bool(f);
258 match (tb, fb) {
259 (Some(true), Some(false)) => self.expr_bool(c, out),
260 (Some(false), Some(true)) => {
261 // !(!x) collapses to x
262 if let Expr::Un {
263 op: crate::ir::expr::UnOp::Not,
264 e: inner,
265 } = &**c
266 {
267 self.expr_bool(inner, out);
268 } else {
269 out.push('!');
270 // expr_bool renders composite conditions bare:
271 // `!` + `ssign != 45` would regroup as
272 // `(!ssign) != 45` (jdk26 FloatingDecimal
273 // "一元运算符 '!' 的操作数类型int错误").
274 let needs = matches!(
275 &**c,
276 Expr::Bin { .. } | Expr::Cond { .. } | Expr::Assign { .. }
277 );
278 if needs {
279 out.push('(');
280 }
281 self.expr_bool(c, out);
282 if needs {
283 out.push(')');
284 }
285 }
286 }
287 _ => {
288 self.expr(c, 3, out);
289 out.push_str(" ? ");
290 self.expr_bool(t, out);
291 out.push_str(" : ");
292 self.expr_bool(f, out);
293 }
294 }
295 }
296 _ => self.expr(e, 1, out),
297 }
298 }
299
300 // ---------------- statements ----------------
301
302
303 /// Unique name for an unbound catch parameter; bound ones take
304 /// their recorded/var-table name. Uniqueness covers the printer's
305 /// own sequence, the var table and every enclosing-scope name the
306 /// lambda chain accumulated (a lambda body may not redeclare a
307 /// name visible outside it).
308 fn catch_var_name(&mut self, c: &crate::ir::stmt::Catch) -> String {
309 if c.var != u32::MAX {
310 return c
311 .var_name
312 .clone()
313 .unwrap_or_else(|| self.vt.var(c.var).name.clone());
314 }
315 loop {
316 self.ignored_seq += 1;
317 let name = if self.ignored_seq == 1 {
318 "ignored".to_string()
319 } else {
320 format!("ignored{}", self.ignored_seq)
321 };
322 let clash = self.vt.vars.iter().any(|v| v.name == name)
323 || self.outer_names.iter().any(|n| *n == name);
324 if !clash {
325 return name;
326 }
327 }
328 }
329 fn line(&mut self, s: &str) {
330 self.push_indent();
331 self.out.push_str(s);
332 self.out.push('\n');
333 }
334
335 /// Indentation as one contiguous push (the per-level push_str loop
336 /// ran per printed line).
337 fn push_indent(&mut self) {
338 const UNIT: &str = " "; // 32 spaces
339 let mut n = self.indent * 4;
340 while n >= 32 {
341 self.out.push_str(UNIT);
342 n -= 32;
343 }
344 if n > 0 {
345 self.out.push_str(&UNIT[..n]);
346 }
347 }
348
349 /// Render an int-typed expression in a byte/short target: constants
350 /// and ternary branches get the narrowing cast (javac's conditional
351 /// expression only narrows when the target type is known — a return
352 /// or local-decl of byte/short with int constants needs explicit
353 /// casts: `byte normalVirtual = !if() ? (byte) 5 : (byte) 9;`).
354 pub fn expr_narrow(&mut self, e: &Expr, ty: &crate::types::JavaType, out: &mut String) {
355 self.expr_narrow_f(e, ty, false, out)
356 }
357
358 /// `force_consts`: the enclosing conditional's condition is not a
359 /// compile-time constant, so the whole expression is not a constant
360 /// expression and javac's assignment-context narrowing does NOT apply
361 /// to in-range int constants either (byte getDirectionality: `return
362 /// (ch & 0xFFFE) == 0xFFFE ? -1 : 0` — 从int转换到byte可能会有损失;
363 /// the source branches are byte static finals the bytecode inlined).
364 fn expr_narrow_f(
365 &mut self,
366 e: &Expr,
367 ty: &crate::types::JavaType,
368 force_consts: bool,
369 out: &mut String,
370 ) {
371 match e {
372 Expr::Const(ConstVal::Int(n)) => {
373 let (lo, hi) = match ty {
374 crate::types::JavaType::Byte => (-128i64, 127i64),
375 crate::types::JavaType::Short => (-32768i64, 32767i64),
376 _ => (i32::MIN as i64, i32::MAX as i64),
377 };
378 if force_consts || (*n as i64) < lo || (*n as i64) > hi {
379 out.push('(');
380 out.push_str(&self.type_name(&TypeRef::J(ty.clone())));
381 out.push_str(") ");
382 }
383 out.push_str(&n.to_string());
384 }
385 Expr::Cond { c, t, f } => {
386 let force = force_consts || !matches!(&**c, Expr::Const(_));
387 self.expr(c, 3, out);
388 out.push_str(" ? ");
389 let prev = std::mem::replace(&mut self.in_cond, true);
390 self.expr_narrow_f(t, ty, force, out);
391 out.push_str(" : ");
392 self.expr_narrow_f(f, ty, force, out);
393 self.in_cond = prev;
394 }
395 // An int-typed local (typically a branch-merge stack temp)
396 // under a byte/short target needs the explicit narrowing cast
397 // (jdk17 InvokerBytecodeGenerator `return stack61;` —
398 // 从int转换到byte可能会有损失; the merged branches carried
399 // byte values the evidence widened to int).
400 Expr::Local { var, .. } => {
401 if matches!(
402 (self.vt.var(*var).ty.erased(), ty),
403 (crate::types::JavaType::Int, crate::types::JavaType::Byte)
404 | (crate::types::JavaType::Int, crate::types::JavaType::Short)
405 ) {
406 out.push('(');
407 out.push_str(&self.type_name(&TypeRef::J(ty.clone())));
408 out.push_str(") ");
409 }
410 self.expr(e, 1, out);
411 }
412 _ => self.expr(e, 1, out),
413 }
414 }
415
416 /// Call-argument variant of expr_narrow: invocation conversion never
417 /// narrows, so in-range int constants keep the explicit cast too, and
418 /// int conditionals get it per branch.
419 fn expr_narrow_arg(&mut self, e: &Expr, ty: &crate::types::JavaType, out: &mut String) {
420 match e {
421 Expr::Const(ConstVal::Int(n)) => {
422 out.push('(');
423 out.push_str(&self.type_name(&TypeRef::J(ty.clone())));
424 out.push_str(") ");
425 out.push_str(&n.to_string());
426 }
427 Expr::Cond { c, t, f } => {
428 self.expr(c, 3, out);
429 out.push_str(" ? ");
430 let prev = std::mem::replace(&mut self.in_cond, true);
431 self.expr_narrow_arg(t, ty, out);
432 out.push_str(" : ");
433 self.expr_narrow_arg(f, ty, out);
434 self.in_cond = prev;
435 }
436 _ => self.expr(e, 1, out),
437 }
438 }
439
440 /// Render an expression in a char-typed target: int constants become
441 /// char literals, ternary branches recurse (the lossy-conversion fix
442 /// for `char name2type(..) { return c ? 63 : 105; }`).
443 pub fn expr_char(&mut self, e: &Expr, out: &mut String) {
444 match e {
445 Expr::Const(ConstVal::Int(n)) => push_char_lit(out, *n),
446 Expr::Cond { c, t, f } => {
447 self.expr(c, 3, out);
448 out.push_str(" ? ");
449 let prev = std::mem::replace(&mut self.in_cond, true);
450 self.expr_char(t, out);
451 out.push_str(" : ");
452 self.expr_char(f, out);
453 self.in_cond = prev;
454 }
455 _ => self.expr(e, 1, out),
456 }
457 }
458
459 fn stmt(&mut self, s: &Stmt) {
460 match s {
461 Stmt::Block(v) => {
462 for x in v {
463 self.stmt(x);
464 }
465 }
466 Stmt::ExprStmt(e) => {
467 if !is_statement_expr(e) {
468 // Only assignments/calls/inc-dec/new are legal
469 // expression statements; a leftover pure concat
470 // (`"" + 48;`) renders as a comment instead.
471 let mut text = String::new();
472 self.expr(e, 0, &mut text);
473 self.line(&format!("/* {text}; */"));
474 return;
475 }
476 let mut line = std::mem::take(&mut self.line_buf);
477 line.clear();
478 if matches!(e, Expr::Method { .. }) {
479 self.suppress_poly_cast = true;
480 }
481 self.expr(e, 0, &mut line);
482 self.suppress_poly_cast = false;
483 line.push(';');
484 self.line(&line);
485 self.line_buf = line;
486 }
487 Stmt::LocalDef {
488 var,
489 init,
490 is_final,
491 force_type,
492 } => {
493 let _ = force_type;
494 let info = self.vt.var(*var);
495 let mut line = std::mem::take(&mut self.line_buf);
496 line.clear();
497 if *is_final {
498 line.push_str("final ");
499 }
500 line.push_str(&self.local_decl_ty(*var, &info.ty));
501 line.push(' ');
502 line.push_str(&java_ident(&info.name));
503 if let Some(e) = init {
504 line.push_str(" = ");
505 // A lambda initializing a generically-typed SAM local:
506 // the declared type is the only record of the
507 // instantiated SAM return (the indy's
508 // instantiatedMethodType is erased — IntFunction<T[]>
509 // records (I)[Object), so prime the lambda-body cast
510 // from it (jdk11 ForEachOps: `IntFunction<T[]>
511 // generator = size -> (T[]) new Object[size]` —
512 // without the cast "lambda 表达式中的返回类型错误").
513 if let (TypeRef::G(g @ crate::types::GenericType::Class(_)), Expr::Lambda(l)) =
514 (&info.ty, e)
515 {
516 if self.lambda_sam_ret.is_none() {
517 self.lambda_sam_ret = self.sam_ret_cast(g, &l.sam_name);
518 }
519 }
520 // Assigning a concrete type to a type-variable local
521 // needs the (erased-away) cast back in source form.
522 let need_cast =
523 matches!(&info.ty, TypeRef::G(crate::types::GenericType::TypeVar(_)))
524 && e.type_ref() != info.ty;
525 if need_cast {
526 line.push('(');
527 line.push_str(&self.type_name(&info.ty));
528 line.push_str(") ");
529 self.expr(e, 14, &mut line);
530 } else if info.ty.erased() == crate::types::JavaType::Boolean {
531 self.expr_bool(e, &mut line);
532 } else if info.ty.erased() == crate::types::JavaType::Char {
533 self.expr_char(e, &mut line);
534 } else if info.ty.erased() == crate::types::JavaType::Byte
535 || info.ty.erased() == crate::types::JavaType::Short
536 {
537 let t = info.ty.erased();
538 self.expr_narrow(e, &t, &mut line);
539 } else {
540 self.expr(e, 1, &mut line);
541 }
542 }
543 line.push(';');
544 self.line(&line);
545 self.line_buf = line;
546 }
547 Stmt::Return(Some(e)) => {
548 let mut line = String::from("return ");
549 if self.ret_bool {
550 self.expr_bool(e, &mut line);
551 } else if self.ret_char {
552 self.expr_char(e, &mut line);
553 } else if self.ret_byte {
554 self.expr_narrow(e, &crate::types::JavaType::Byte, &mut line);
555 } else if self.ret_short {
556 self.expr_narrow(e, &crate::types::JavaType::Short, &mut line);
557 } else {
558 // Lambda in return position of a generic method: the
559 // SAM return witnesses the erased body value
560 // (castingIdentity `return i -> (R) i`, toArray
561 // `() -> (T[]) new Object[]{..}` — jdk17 Collectors).
562 if let (Some(TypeRef::G(g)), Expr::Lambda(l)) = (&self.ret_sam, e) {
563 self.lambda_sam_ret = match g {
564 crate::types::GenericType::Class(_) => {
565 self.sam_ret_cast(g, &l.sam_name)
566 }
567 crate::types::GenericType::Array(_) => Some(TypeRef::G(g.clone())),
568 _ => None,
569 };
570 }
571 self.expr(e, 1, &mut line);
572 self.lambda_sam_ret = None;
573 }
574 line.push(';');
575 self.line(&line);
576 }
577 Stmt::Return(None) => self.line("return;"),
578 Stmt::Throw(e) => {
579 let mut line = String::from("throw ");
580 self.expr(e, 1, &mut line);
581 line.push(';');
582 self.line(&line);
583 }
584 Stmt::If {
585 cond,
586 then_stmt,
587 else_stmt,
588 } => {
589 self.print_if(cond, then_stmt, else_stmt.as_deref(), "");
590 }
591 Stmt::While { cond, body } => {
592 let mut head = String::from("while (");
593 if matches!(cond, Expr::Const(ConstVal::Int(1))) {
594 head.push_str("true");
595 } else {
596 self.expr_bool(cond, &mut head);
597 }
598 head.push(')');
599 self.block_stmt(&head, body);
600 }
601 Stmt::DoWhile { body, cond } => {
602 self.line("do {");
603 self.indent += 1;
604 self.stmt(body);
605 self.indent -= 1;
606 let mut tail = String::from("} while (");
607 self.expr_bool(cond, &mut tail);
608 tail.push_str(");");
609 self.line(&tail);
610 }
611 Stmt::For {
612 init,
613 cond,
614 update,
615 body,
616 } => {
617 let mut head = String::from("for (");
618 for (i, s) in init.iter().enumerate() {
619 if i > 0 {
620 head.push_str(", ");
621 }
622 self.stmt_inline(s, &mut head);
623 }
624 head.push_str("; ");
625 if let Some(c) = cond {
626 self.expr_bool(c, &mut head);
627 }
628 head.push_str("; ");
629 for (i, u) in update.iter().enumerate() {
630 if i > 0 {
631 head.push_str(", ");
632 }
633 self.expr(u, 1, &mut head);
634 }
635 head.push(')');
636 self.block_stmt(&head, body);
637 }
638 Stmt::ForEach {
639 var,
640 iterable,
641 is_array,
642 body,
643 } => {
644 let _ = is_array;
645 let info = self.vt.var(*var);
646 let mut head = String::from("for (");
647 head.push_str(&self.type_name(&info.ty));
648 head.push(' ');
649 head.push_str(&java_ident(&info.name));
650 head.push_str(" : ");
651 self.expr(iterable, 1, &mut head);
652 head.push(')');
653 self.block_stmt(&head, body);
654 }
655 Stmt::Switch {
656 selector,
657 cases,
658 default,
659 on_string,
660 } => {
661 let _ = on_string;
662 let mut head = String::from("switch (");
663 self.expr(selector, 1, &mut head);
664 head.push(')');
665 self.line(&format!("{} {{", head));
666 self.indent += 1;
667 for c in cases {
668 // MULTIPLE pattern labels in one arm cannot share a
669 // colon body: neither stacked (`case P1 x:` `case P2
670 // y:` — 贯穿到模式非法) nor comma-joined (`case P1 x,
671 // P2 y:` — javac still demands a break between pattern
672 // labels) compile. Duplicate the body per label — the
673 // source's arrow-form multi-pattern arm
674 // (`case A _, B _ -> r;`, jdk26 ParserVerifier
675 // valueSize) in colon form.
676 if c.raw_labels.len() > 1
677 && c.labels.is_empty()
678 && c.string_labels.is_empty()
679 && c.enum_labels.is_empty()
680 {
681 for l in &c.raw_labels {
682 match &c.guard {
683 Some(g) => {
684 let mut gtxt = String::new();
685 self.expr(g, 1, &mut gtxt);
686 self.line(&format!("case {} when {}:", l, gtxt));
687 }
688 None => self.line(&format!("case {}:", l)),
689 }
690 self.line("{");
691 self.indent += 1;
692 for st in &c.body {
693 self.stmt(st);
694 }
695 self.indent -= 1;
696 self.line("}");
697 }
698 continue;
699 }
700 for l in &c.enum_labels {
701 self.line(&format!("case {}:", l));
702 }
703 if let Some(g) = &c.guard {
704 // Folded pattern guard: the desugared restart shape
705 // (`if (guard) body else { state=N; continue; }`)
706 // restored to `case T v when guard:` (jdk26
707 // DecimalFormat — duplicate type-pattern labels are
708 // "此 case 标签由前一个 case 标签支配" without it).
709 let mut gtxt = String::new();
710 self.expr(g, 1, &mut gtxt);
711 let joined = c
712 .raw_labels
713 .iter()
714 .map(|l| format!("{} when {}", l, gtxt))
715 .collect::<Vec<_>>()
716 .join(", ");
717 self.line(&format!("case {}:", joined));
718 } else if !c.raw_labels.is_empty() {
719 // Pattern labels of one arm MUST be comma-joined:
720 // stacked `case P1 x:` / `case P2 y:` lines are a
721 // fall-through between patterns ("从模式贯穿非法",
722 // jdk26 ParserVerifier `case OfConstant _,
723 // OfClass _ -> 2`).
724 self.line(&format!("case {}:", c.raw_labels.join(", ")));
725 }
726 for l in &c.labels {
727 self.line(&format!("case {}:", l));
728 }
729 for l in &c.string_labels {
730 self.line(&format!("case \"{}\":", escape_string(l)));
731 }
732 // Braces give each case its own scope: pattern-switch
733 // restorations reuse binding names across cases.
734 self.line("{");
735 self.indent += 1;
736 for st in &c.body {
737 self.stmt(st);
738 }
739 self.indent -= 1;
740 self.line("}");
741 }
742 if let Some(d) = default {
743 self.line("default:");
744 self.indent += 1;
745 self.stmt(d);
746 self.indent -= 1;
747 }
748 self.indent -= 1;
749 self.line("}");
750 }
751 Stmt::Try {
752 body,
753 catches,
754 finally,
755 } => {
756 self.line("try {");
757 self.indent += 1;
758 self.stmt(body);
759 self.indent -= 1;
760 for c in catches {
761 let exc_name = if c.exc.is_empty() {
762 "Throwable".to_string()
763 } else {
764 c.exc
765 .iter()
766 .map(|e| self.shorten(e))
767 .collect::<Vec<_>>()
768 .join(" | ")
769 };
770 let var_name = self.catch_var_name(c);
771 self.line(&format!("}} catch ({} {}) {{", exc_name, var_name));
772 self.indent += 1;
773 self.stmt(&c.body);
774 self.indent -= 1;
775 }
776 if let Some(f) = finally {
777 self.line("} finally {");
778 self.indent += 1;
779 self.stmt(f);
780 self.indent -= 1;
781 }
782 // A try with no catches and no finally is not valid Java
783 // (the structurer can emit a bare degenerate try); an
784 // empty finally keeps the statement compilable.
785 if catches.is_empty() && finally.is_none() {
786 self.line("} finally {");
787 }
788 self.line("}");
789 }
790 Stmt::TryWithResources {
791 resources,
792 body,
793 catches,
794 finally,
795 } => {
796 let mut res: Vec<String> = Vec::new();
797 for r in resources {
798 if let Stmt::LocalDef { var, init, .. } = r {
799 let info = self.vt.var(*var);
800 let mut t = String::new();
801 t.push_str(&self.type_name(&info.ty));
802 t.push(' ');
803 t.push_str(&java_ident(&info.name));
804 if let Some(e) = init {
805 t.push_str(" = ");
806 self.expr(e, 1, &mut t);
807 }
808 res.push(t);
809 } else {
810 // The resource is not a declaration: a reused
811 // variable was rewritten to a plain assignment by
812 // dedupe_declarations, and `try (x = expr)` is not
813 // Java. Print it as the statement it is, BEFORE the
814 // try (resource init runs before the body anyway) —
815 // emitting nothing turned the header into the
816 // illegal `try () {`.
817 self.stmt(r);
818 }
819 }
820 if res.is_empty() && catches.is_empty() && finally.is_none() {
821 // Vestigial try-with-resources: the resource was
822 // hoisted into a plain assignment above and its close
823 // is a sibling statement, so nothing is left to head
824 // the statement — a bare `try {` does not compile
825 // ("'try' without 'catch', 'finally' or resource
826 // declarations"). A handler-less try IS a block.
827 self.line("{");
828 } else if res.is_empty() {
829 self.line("try {");
830 } else {
831 self.line(&format!("try ({}) {{", res.join("; ")));
832 }
833 self.indent += 1;
834 self.stmt(body);
835 self.indent -= 1;
836 for c in catches {
837 let exc_name = if c.exc.is_empty() {
838 "Throwable".to_string()
839 } else {
840 c.exc
841 .iter()
842 .map(|e| self.shorten(e))
843 .collect::<Vec<_>>()
844 .join(" | ")
845 };
846 let var_name = self.catch_var_name(c);
847 self.line(&format!("}} catch ({} {}) {{", exc_name, var_name));
848 self.indent += 1;
849 self.stmt(&c.body);
850 self.indent -= 1;
851 }
852 if let Some(f) = finally {
853 self.line("} finally {");
854 self.indent += 1;
855 self.stmt(f);
856 self.indent -= 1;
857 }
858 self.line("}");
859 }
860 Stmt::Assert { cond, msg } => {
861 let mut line = String::from("assert ");
862 // The assert-condition is boolean-typed: the synthesized
863 // `assert false` carries Const Int(0) — plain expr would
864 // print `assert 0` (int无法转换为boolean, jdk17 URI).
865 self.expr_bool(cond, &mut line);
866 if let Some(m) = msg {
867 line.push_str(" : ");
868 self.expr(m, 1, &mut line);
869 }
870 line.push(';');
871 self.line(&line);
872 }
873 Stmt::Synchronized { lock, body } => {
874 let mut head = String::from("synchronized (");
875 self.expr(lock, 1, &mut head);
876 head.push(')');
877 self.block_stmt(&head, body);
878 }
879 Stmt::TernaryValue { e } => {
880 let mut line = String::from("/* ternary */ ");
881 self.expr(e, 1, &mut line);
882 line.push(';');
883 self.line(&line);
884 }
885 Stmt::MonitorEnter(e) => {
886 // The lock expression goes INSIDE the comment: a bare
887 // local/field is not a valid expression statement
888 // (`/* monitorenter */ a;` failed javac).
889 let mut line = String::from("/* monitorenter ");
890 self.expr(e, 1, &mut line);
891 line.push_str(" */");
892 self.line(&line);
893 }
894 Stmt::MonitorExit(e) => {
895 let mut line = String::from("/* monitorexit ");
896 self.expr(e, 1, &mut line);
897 line.push_str(" */");
898 self.line(&line);
899 }
900 Stmt::ClassDecl { header, body, .. } => {
901 let kw = if header.starts_with("record ")
902 || header.starts_with("interface ")
903 || header.starts_with("enum ")
904 {
905 String::new()
906 } else {
907 "class ".to_string()
908 };
909 self.line(&format!("{}{} {{", kw, header));
910 for line in body.lines() {
911 if line.trim().is_empty() {
912 self.out.push('\n');
913 } else {
914 for _ in 0..self.indent + 1 {
915 self.out.push_str(" ");
916 }
917 self.out.push_str(line.trim_start());
918 self.out.push('\n');
919 }
920 }
921 self.line("}");
922 }
923 Stmt::Labeled { label, body } => {
924 // label prefix on the following statement's line
925 let save = self.out.len();
926 self.stmt(body);
927 // prepend "label: " before the first line just emitted
928 let indent_str = " ".repeat(self.indent);
929 let emitted = self.out[save..].to_string();
930 self.out.truncate(save);
931 if let Some(rest) = emitted.strip_prefix(&indent_str) {
932 self.out.push_str(&indent_str);
933 self.out.push_str(label);
934 self.out.push_str(": ");
935 self.out.push_str(rest);
936 } else {
937 self.out.push_str(&emitted);
938 }
939 }
940 Stmt::Break(lbl) => match lbl {
941 Some(l) => self.line(&format!("break {};", l)),
942 None => self.line("break;"),
943 },
944 Stmt::Continue(lbl) => match lbl {
945 Some(l) => self.line(&format!("continue {};", l)),
946 None => self.line("continue;"),
947 },
948 Stmt::Label(id) => {
949 // Emitted by breaking the following statement; standalone
950 // labels are invalid before non-statements, so use a marker.
951 self.line(&format!("L{}: ;", id));
952 }
953 Stmt::Goto(id) => self.line(&format!("break L{};", id)),
954 Stmt::Comment(c) => self.line(&format!("// {}", c)),
955 }
956 }
957
958 /// `head {` + body + `}`.
959 fn block_stmt(&mut self, head: &str, body: &Stmt) {
960 self.line(&format!("{} {{", head));
961 self.indent += 1;
962 self.stmt(body);
963 self.indent -= 1;
964 self.line("}");
965 }
966
967 /// Print an if statement; `opener` is "" for the first if and
968 /// "} else " when continuing an else-if chain on the closing line.
969 fn print_if(&mut self, cond: &Expr, then_stmt: &Stmt, else_stmt: Option<&Stmt>, opener: &str) {
970 let mut head = String::from(opener);
971 head.push_str("if (");
972 self.expr_bool(cond, &mut head);
973 head.push_str(") {");
974 self.line(&head);
975 self.indent += 1;
976 self.stmt(then_stmt);
977 self.indent -= 1;
978 match else_stmt {
979 Some(Stmt::If {
980 cond: c2,
981 then_stmt: t2,
982 else_stmt: e2,
983 }) => {
984 self.print_if(c2, t2, e2.as_deref(), "} else ");
985 }
986 Some(other) => {
987 self.line("} else {");
988 self.indent += 1;
989 self.stmt(other);
990 self.indent -= 1;
991 self.line("}");
992 }
993 None => self.line("}"),
994 }
995 }
996
997 fn stmt_inline(&self, s: &Stmt, out: &mut String) {
998 match s {
999 Stmt::ExprStmt(e) => {
1000 let mut p = self.sub();
1001 if matches!(e, Expr::Method { .. }) {
1002 p.suppress_poly_cast = true;
1003 }
1004 p.expr(e, 1, out);
1005 }
1006 Stmt::LocalDef { var, init, .. } => {
1007 let info = self.vt.var(*var);
1008 out.push_str(&self.local_decl_ty(*var, &info.ty));
1009 out.push(' ');
1010 out.push_str(&java_ident(&info.name));
1011 if let Some(e) = init {
1012 out.push_str(" = ");
1013 let mut p = self.sub();
1014 p.expr(e, 1, out);
1015 }
1016 }
1017 other => {
1018 let mut p = self.sub();
1019 p.stmt(other);
1020 out.push_str(p.out.trim_end());
1021 }
1022 }
1023 }
1024
1025 fn sub(&self) -> Printer<'a> {
1026 Printer {
1027 ctx: self.ctx,
1028 vt: self.vt,
1029 out: String::new(),
1030 line_buf: String::new(),
1031 indent: 0,
1032 lambda_depth: self.lambda_depth,
1033 ignored_seq: self.ignored_seq,
1034 outer_names: self.outer_names.clone(),
1035 ret_bool: self.ret_bool,
1036 ret_char: self.ret_char,
1037 ret_byte: self.ret_byte,
1038 ret_short: self.ret_short,
1039 suppress_poly_cast: self.suppress_poly_cast,
1040 suppress_diamond: self.suppress_diamond,
1041 in_cond: self.in_cond,
1042 lambda_sam_ret: self.lambda_sam_ret.clone(),
1043 ret_sam: self.ret_sam.clone(),
1044 twin_cache: self.twin_cache.clone(),
1045 }
1046 }
1047
1048 // ---------------- expressions ----------------
1049
1050 pub fn expr(&mut self, e: &Expr, outer_prec: u8, out: &mut String) {
1051 let parens = e.needs_parens(outer_prec, false);
1052 if parens {
1053 out.push('(');
1054 }
1055 match e {
1056 Expr::Const(c) => self.const_val(c, out),
1057 Expr::Raw(t) if t == "\u{3}" => out.push_str("this"),
1058 Expr::Raw(t) => out.push_str(t),
1059 Expr::RawT(t, _) => out.push_str(t),
1060 Expr::Local { var, .. } => {
1061 let info = self.vt.var(*var);
1062 // The receiver var carries the dex debug name "this" —
1063 // reads render as the keyword (legal in expression
1064 // position, and it is never declared).
1065 if info.name == "this" {
1066 out.push_str("this");
1067 } else {
1068 out.push_str(&java_ident(&info.name));
1069 }
1070 }
1071 Expr::This => out.push_str("this"),
1072 Expr::New { cls, args, ty, .. } => {
1073 let no_diamond = self.suppress_diamond;
1074 self.suppress_diamond = false;
1075 // Explicit type arguments pinned by the AST passes
1076 // (diamond_explicit_args_from_call_args): print them
1077 // instead of the diamond.
1078 let explicit = match ty {
1079 TypeRef::G(crate::types::GenericType::Class(cs))
1080 if cs.parts.last().map(|p| !p.args.is_empty()).unwrap_or(false)
1081 && crate::typeutil::classsig_internal(cs).as_str() == cls.as_ref() =>
1082 {
1083 let rendered: Vec<String> = cs
1084 .parts
1085 .last()
1086 .unwrap()
1087 .args
1088 .iter()
1089 .map(|a| self.generic_name(a))
1090 .collect();
1091 Some(format!("<{}>", rendered.join(", ")))
1092 }
1093 _ => None,
1094 };
1095 // A wildcard-typed ctor argument dooms diamond inference
1096 // (the inference variable gets an equality constraint from
1097 // the capture and a different bound from the context —
1098 // "cannot infer type arguments for Entry<>", jdk11
1099 // Hashtable `tab[i] = new Entry<>(hash, key, value, e)`
1100 // with e: Entry<?,?>; the source declared e as Entry<K,V>
1101 // via an unchecked cast that leaves no bytecode trace).
1102 // The raw form is always applicable (unchecked).
1103 let args_wildcard = args.iter().any(|a| {
1104 matches!(a.type_ref(), TypeRef::G(ref g)
1105 if crate::typeutil::g_has_wildcard(g))
1106 });
1107 let diamond: std::borrow::Cow<str> = match &explicit {
1108 Some(x) => x.as_str().into(),
1109 // Pre-Java-8 conditional branches are not poly
1110 // expressions: the diamond cannot see the assignment
1111 // target through the `?:` and infers <Object,Object>
1112 // (jdk7 HashSet.readObject map-ternary 不兼容的类型).
1113 // Raw is unchecked but always compilable.
1114 None if no_diamond
1115 || args_wildcard
1116 || (self.in_cond && self.ctx.source_level() < 52) =>
1117 {
1118 "".into()
1119 }
1120 None => self.diamond_for(cls).into(),
1121 };
1122 let diamond = diamond.as_ref();
1123 if let Some(local) = cls.strip_prefix('\u{2}') {
1124 out.push_str("new ");
1125 out.push_str(local);
1126 out.push_str(diamond);
1127 out.push('(');
1128 // Local records/classes keep bytecode-arity ctors:
1129 // typed rendering turns an int constant into the
1130 // char/boolean literal the ctor expects (jdk17
1131 // MessageFormat `new Qchar(39, quoted)`).
1132 // Nested local-class method printing runs under a
1133 // TAKEN LOCAL_CLASS_INTERNALS registry — resolve a
1134 // self-construction (`new BitSetSpliterator(..)` inside
1135 // BitSetSpliterator.trySplit) through the printer's
1136 // own class when the registry misses. Local-class
1137 // ctors capture the enclosing instance as a leading
1138 // param that the printed new-site omits; the this$0
1139 // fallback in ctor_param_types lines the formals up
1140 // (jdk11 BitSet$1BitSetSpliterator(BitSet,int,int,int,
1141 // boolean) — the boolean formal rendered its arg `0`).
1142 let internal = self.ctx.local_class_internal(local).or_else(|| {
1143 let tail = self.ctx.class_name().rsplit('$').next().unwrap_or("");
1144 let simple = tail.trim_start_matches(|c: char| c.is_ascii_digit());
1145 if !simple.is_empty() && simple == local {
1146 return Some(self.ctx.class_name().to_string());
1147 }
1148 // Probe the nested-name space of the printing
1149 // context (javac numbers method-local classes
1150 // `$1Name`): the new-site needs the real class to
1151 // resolve its ctor formals.
1152 let base = format!("{}${}", self.ctx.class_name(), local);
1153 if self.ctx.has_class(&base) {
1154 return Some(base);
1155 }
1156 for d in 0..10 {
1157 let cand = format!("{}${}{}", self.ctx.class_name(), d, local);
1158 if self.ctx.has_class(&cand) {
1159 return Some(cand);
1160 }
1161 }
1162 None
1163 });
1164 match internal
1165 .as_deref()
1166 .and_then(|i| self.ctor_param_types(i, 0, args.len(), args))
1167 {
1168 Some(pt) => self.args_typed(args, &pt, out),
1169 None => self.args(args, out),
1170 }
1171 out.push(')');
1172 } else if self.is_member_inner(cls)
1173 && !args.is_empty()
1174 && !matches!(args[0], Expr::This)
1175 && !is_this_expr(&args[0])
1176 // A constant (null/0) as the first argument is a real
1177 // parameter value, not the synthetic outer instance —
1178 // `0.new a()` / `null.new a()` are not valid Java.
1179 && !matches!(args[0], Expr::Const(_))
1180 // Anonymous classes (digit tails) are emitted as
1181 // separate top-level-ish classes — a qualified
1182 // `this.new 1(...)` is not valid Java; the flat
1183 // `new Outer$1(...)` form is. Test the RAW tail:
1184 // inner_simple already sanitizes a leading digit to
1185 // `_`, which silently bypassed this guard and emitted
1186 // `this.new _1(..)` against a flat top-level
1187 // declaration (weibo HorseRaceDetector$4 family).
1188 && !cls
1189 .rsplit('$')
1190 .next()
1191 .map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
1192 .unwrap_or(false)
1193 {
1194 // `outerExpr.new Inner(rest...)` — the first ctor arg
1195 // is the synthetic outer instance when the class has a
1196 // this$0 field, or when the ctor forwards it straight
1197 // to super (no field of its own; is_member_inner
1198 // detected it). Either way the qualified-new form
1199 // supplies the outer implicitly, so skip args[0].
1200 self.expr(&args[0], 15, out);
1201 out.push_str(".new ");
1202 out.push_str(&inner_simple(cls));
1203 out.push_str(diamond);
1204 out.push('(');
1205 match self.ctor_param_types(cls, 1, args.len() - 1, &args[1..]) {
1206 Some(pt) => self.args_typed(&args[1..], &pt, out),
1207 None => self.args(&args[1..], out),
1208 }
1209 out.push(')');
1210 } else {
1211 out.push_str("new ");
1212 let digit_tail = cls
1213 .rsplit('$')
1214 .next()
1215 .map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
1216 .unwrap_or(false);
1217 // A digit-tail class (anonymous `Outer$1`, d8 lambda)
1218 // is rendered as a SEPARATE top-level file declaring
1219 // `class Outer$1` with the outer instance as an
1220 // ordinary ctor parameter — the ctor signature keeps
1221 // that parameter (the inner-ctor strip excludes
1222 // digit tails for exactly this shape). The member
1223 // form `this.new _1(..)` would look for a member of
1224 // the enclosing class that does not exist there —
1225 // the flat `new Outer$1(outer, ..)` with ALL args is
1226 // the shape that matches the declaration.
1227 let member_this = self.is_member_inner(cls)
1228 && !digit_tail
1229 && !args.is_empty()
1230 && matches!(args[0], Expr::This);
1231 let shown = if member_this {
1232 // `new Inner()` from inside the outer class
1233 inner_simple(cls)
1234 } else if digit_tail {
1235 // Digit-suffixed class at a `new` site: a d8/R8-
1236 // desugared lambda (`...$lambda$N$$inlined$log$1`,
1237 // `Outer$$ExternalSyntheticLambda0`) or an anonymous
1238 // class (`Outer$1`). Both are concrete, pool-rendered
1239 // classes, so print the real binary name — NOT the
1240 // abstract SAM interface `shorten` falls back to
1241 // (which yields an invalid `new Iface(..)`: "a是抽象
1242 // 的; 无法实例化", the biggest abstract-instantiation
1243 // family on Kotlin corpora, v6.a/l/p = Function0/1/2).
1244 // Type positions keep `shorten` (interface), so the
1245 // declaration stays phi-compatible across branches
1246 // that mint different lambdas: `Iface v = new C(..)`.
1247 self.shorten_concrete(cls)
1248 } else {
1249 self.shorten(cls)
1250 };
1251 out.push_str(&shown);
1252 out.push_str(diamond);
1253 out.push('(');
1254 if member_this {
1255 match self.ctor_param_types(cls, 1, args.len() - 1, &args[1..]) {
1256 Some(pt) => self.args_typed(&args[1..], &pt, out),
1257 None => self.args(&args[1..], out),
1258 }
1259 } else {
1260 // Pinned generic instantiation: prime lambda args
1261 // from the ctor's instantiated Signature formals.
1262 let sam_rets: Vec<Option<TypeRef>> = match ty {
1263 TypeRef::G(crate::types::GenericType::Class(cs))
1264 if explicit.is_some()
1265 && crate::typeutil::classsig_internal(cs).as_str() == cls.as_ref() =>
1266 {
1267 let pinned = cs.parts.last().map(|p| p.args.clone());
1268 let formals = self.ctx.ctor_formals_by_arity(cls, args.len());
1269 // The raw ctor formals carry the class's
1270 // own typevars — substitute the pinned
1271 // instantiation before reading the SAM
1272 // return (an unsubstituted R printed `(R)`
1273 // — 找不到符号).
1274 let class_params = self.ctx.class_type_params(cls);
1275 args.iter()
1276 .enumerate()
1277 .map(|(i, a)| {
1278 if !matches!(a, Expr::Lambda(_)) {
1279 return None;
1280 }
1281 let f = formals.as_ref()?.get(i)?;
1282 let pinned = pinned.as_ref()?;
1283 if pinned.len() != class_params.len() {
1284 return None;
1285 }
1286 let inst = crate::typeutil::subst_typevars(
1287 f,
1288 &class_params,
1289 pinned,
1290 );
1291 let Expr::Lambda(l) = a else { return None };
1292 self.sam_ret_cast(&inst, &l.sam_name)
1293 })
1294 .collect()
1295 }
1296 _ => Vec::new(),
1297 };
1298 match self.ctor_param_types(cls, 0, args.len(), args) {
1299 Some(pt) => self.args_typed_sam(args, &pt, &sam_rets, out),
1300 None => self.args(args, out),
1301 }
1302 }
1303 out.push(')');
1304 }
1305 }
1306 Expr::NewArray {
1307 elem,
1308 dims,
1309 trailing_dims,
1310 init,
1311 } => {
1312 out.push_str("new ");
1313 out.push_str(&self.type_name(elem));
1314 match init {
1315 Some(vals) => {
1316 for _ in 0..=*trailing_dims {
1317 out.push_str("[]");
1318 }
1319 out.push_str(" {");
1320 // boolean[]/char[] initializers hold int constants
1321 // in bytecode (iconst + bastore/castore): render
1322 // them as true/false and char literals (jdk11
1323 // PKCS9Attribute `new boolean[] {0, 0, 1, ..}` x18).
1324 let elem_bool = elem.erased() == crate::types::JavaType::Boolean;
1325 let elem_char = elem.erased() == crate::types::JavaType::Char;
1326 for (i, v) in vals.iter().enumerate() {
1327 if i > 0 {
1328 out.push_str(", ");
1329 }
1330 if elem_bool {
1331 self.expr_bool(v, out);
1332 } else if elem_char {
1333 self.expr_char(v, out);
1334 } else {
1335 self.expr(v, 1, out);
1336 }
1337 }
1338 out.push('}');
1339 }
1340 None => {
1341 for d in dims {
1342 out.push('[');
1343 self.expr(d, 1, out);
1344 out.push(']');
1345 }
1346 for _ in 0..*trailing_dims {
1347 out.push_str("[]");
1348 }
1349 }
1350 }
1351 }
1352 Expr::NewMultiArray { ty, dims } => {
1353 // Strip the dims.len() leading array levels from the type.
1354 let mut base = ty.erased();
1355 for _ in 0..dims.len() {
1356 match base {
1357 crate::types::JavaType::Array(inner) => base = *inner,
1358 _ => break,
1359 }
1360 }
1361 out.push_str("new ");
1362 out.push_str(&self.type_name(&TypeRef::J(base)));
1363 for d in dims {
1364 out.push('[');
1365 self.expr(d, 1, out);
1366 out.push(']');
1367 }
1368 }
1369 Expr::Field {
1370 owner,
1371 cls,
1372 name,
1373 is_static,
1374 ..
1375 } => {
1376 // javac reserves `$assertionsDisabled`; the declaration and
1377 // all references are emitted under a private alias.
1378 let name: &str = if name.as_ref() == "$assertionsDisabled" {
1379 crate::analysis::ASSERT_FIELD
1380 } else {
1381 name
1382 };
1383 if name == crate::analysis::ASSERT_FIELD {
1384 // Assert guards print bare: the field is declared on
1385 // the enclosing emitted class or inlined body; the
1386 // bytecode owner is often a synthetic holder class
1387 // (`ConstantGroup$1`) whose shorten() fallback is
1388 // `Object` — a qualified read can never resolve.
1389 out.push_str(&java_ident(name));
1390 } else if name == "length" && cls.is_empty() {
1391 if let Some(o) = owner {
1392 if let Expr::Const(_) = o.as_ref() {
1393 // Receiver tracking lost: `0.length` is not
1394 // parseable — cast-null array form.
1395 out.push_str("((java.lang.Object[]) null)");
1396 } else {
1397 self.expr(o, 15, out);
1398 }
1399 }
1400 out.push_str(".length");
1401 } else if let Some(o) = owner {
1402 if let Expr::Const(cv) = o.as_ref() {
1403 if matches!(
1404 cv,
1405 crate::ir::expr::ConstVal::Str(_)
1406 | crate::ir::expr::ConstVal::ClassLit(_)
1407 ) {
1408 // Literal receivers keep their value (see the
1409 // Method arm): `Foo.class.name`, not
1410 // `((Class) null).name`.
1411 self.expr(o, 15, out);
1412 out.push('.');
1413 } else {
1414 // Receiver tracking lost (a null placeholder leaked
1415 // through): `0.b` is not parseable — the same
1416 // cast-null form the Method arm uses.
1417 out.push_str("((");
1418 out.push_str(&self.shorten(cls));
1419 out.push_str(") null).");
1420 }
1421 out.push_str(&java_ident(name));
1422 } else if matches!(o.as_ref(), Expr::Raw(t) if t == "\u{3}") {
1423 // Outer anonymous class member: unqualified lexical
1424 // resolution (an anon outer has no nameable this).
1425 out.push_str(&java_ident(name));
1426 } else if self.private_super_field(cls, name, o.as_ref()) {
1427 // A private field of a SUPERCLASS is not inherited
1428 // into the subclass's member scope: `this.algorithm`
1429 // inside Delegate (extends MessageDigest, algorithm
1430 // private) is "private access" even though the
1431 // source comment says it all — jdk11
1432 // MessageDigest.Delegate.clone casts
1433 // `((MessageDigest)this).algorithm`.
1434 out.push_str("((");
1435 out.push_str(&self.shorten(cls));
1436 out.push_str(") ");
1437 if matches!(o.as_ref(), Expr::This) {
1438 out.push_str("this");
1439 } else {
1440 self.expr(o, 14, out);
1441 }
1442 out.push_str(").");
1443 out.push_str(&java_ident(name));
1444 } else if match o.type_ref().erased() {
1445 crate::types::JavaType::Object(ref n) => {
1446 n.as_ref() != cls.as_ref()
1447 && !matches!(o.as_ref(), Expr::Raw(_) | Expr::RawT(..) | Expr::This)
1448 && (n.as_ref() == "java/lang/Object"
1449 || self.ctx.is_subtype_of(
1450 &crate::types::JavaType::Object(
1451 std::sync::Arc::from(cls.as_ref()),
1452 ),
1453 n,
1454 ))
1455 }
1456 _ => false,
1457 } {
1458 // The receiver's static type is a strict SUPERTYPE
1459 // of the declaring class: either widened to Object
1460 // (when-materialization residue) or a register
1461 // reuse the vt kept at the supertype (`v9.label`
1462 // with v9: ContinuationImpl, label on the suspend
1463 // frame subclass — weibo coroutine cluster ×1.3k).
1464 // The downcast is what the bytecode's field
1465 // resolution did; same honest cast as the Method
1466 // arm. Concrete name: a `$<digits>` declaring
1467 // class loses its pushed-down members under the
1468 // anon fallback.
1469 out.push_str("((");
1470 out.push_str(&self.shorten_concrete(cls));
1471 out.push_str(") ");
1472 self.expr(o, 14, out);
1473 out.push_str(").");
1474 out.push_str(&java_ident(name));
1475 } else {
1476 self.expr(o, 15, out);
1477 out.push('.');
1478 out.push_str(&java_ident(name));
1479 }
1480 } else if *is_static {
1481 // A same-class static read prints bare — unless a local
1482 // of this method shadows the field name: javac resolves
1483 // the bare name as the LOCAL (jdk17 Socket.setImpl's
1484 // `SocketImplFactory factory = factory;` self-reference
1485 // — 可能尚未初始化变量factory x2 sites). Qualify with the
1486 // class name to reach the field.
1487 let shadowed_by_local = cls.as_ref() == self.ctx.class_name()
1488 && self.vt.vars.iter().any(|v| v.name == name);
1489 // ENCLOSING-class static fields read from a nested
1490 // class print bare too (lexical scope) — and MUST when
1491 // the class name itself is shadowed by a member of the
1492 // same name: jdk26 HPKE$Impl reads the outer
1493 // `byte[] HPKE`/PSK_ID_HASH/SECRET/EXP/KEY constants;
1494 // `HPKE.PSK_ID_HASH` resolves the qualifier as the
1495 // byte[] FIELD (variables obscure type names in
1496 // expression names) — 找不到符号 变量 PSK_ID_HASH x6.
1497 let enclosing_static = cls.as_ref() != self.ctx.class_name()
1498 && self.renders_nested_in(cls)
1499 && !self.vt.vars.iter().any(|v| v.name == name)
1500 && {
1501 let mut cur = self.ctx.class_name().to_string();
1502 let mut shadow = false;
1503 while cur.as_str() != cls.as_ref() {
1504 // Inherited fields shadow too (superclass
1505 // chain — see the method-side twin).
1506 let mut sup = Some(cur.clone());
1507 while let Some(c) = sup.take() {
1508 {
1509 if self.ctx.declares_field(&c, name) {
1510 shadow = true;
1511 break;
1512 }
1513 sup = self.ctx.super_name(&c);
1514 }
1515 }
1516 if shadow {
1517 break;
1518 }
1519 match cur.rfind('$') {
1520 Some(i) => cur.truncate(i),
1521 None => break,
1522 }
1523 }
1524 !shadow
1525 };
1526 if !enclosing_static && (cls.as_ref() != self.ctx.class_name() || shadowed_by_local) {
1527 // The owner must name a DECLARABLE class: the
1528 // anonymous→interface/Object fallback (right for
1529 // phi-compatible type positions) leaves the field
1530 // unresolvable — `Object.$SwitchMap$java$math$
1531 // RoundingMode` (485 weibo / 308 lark / 217
1532 // weixin cannot-finds; the synthetic holder
1533 // `LongMath$1` IS rendered as a flat file with
1534 // the field, 0 own errors). Fall back to the
1535 // concrete `$N` name — `$` and digits are legal
1536 // Java identifier characters, and the holder
1537 // always sits in the referring class's package.
1538 // The qualifier of a STATIC member is always the
1539 // CONCRETE name: anon/lambda classes emit as flat
1540 // `$`-named top-level files, while shorten()'s
1541 // anon fallback renders the SAM interface — which
1542 // does not declare the member. `Function0.INSTANCE`
1543 // (1.7k weibo lines) is the sget of
1544 // ActivityResultRegistry$generateRandomNumber$1
1545 // .INSTANCE; the same trap took $SwitchMap holders
1546 // to `Object.` before (the narrow rendered=="Object"
1547 // check this replaces).
1548 out.push_str(&self.shorten_concrete(cls));
1549 out.push('.');
1550 }
1551 out.push_str(&java_ident(name));
1552 } else if self.private_super_field(cls, name, &Expr::This) {
1553 out.push_str("((");
1554 out.push_str(&self.shorten(cls));
1555 out.push_str(") this).");
1556 out.push_str(&java_ident(name));
1557 } else {
1558 out.push_str("this.");
1559 out.push_str(&java_ident(name));
1560 }
1561 }
1562 Expr::Method {
1563 owner,
1564 cls,
1565 name,
1566 desc,
1567 args,
1568 is_static,
1569 is_special,
1570 is_super,
1571 type_args,
1572 ..
1573 } => {
1574 // Signature-polymorphic calls need the descriptor return cast
1575 // in source form (see classdec::polymorphic_ret_cast) — except
1576 // at the root of an expression statement, where the bare call
1577 // is the only legal form. Consume the flag so a poly call
1578 // NESTED in the args still gets its cast.
1579 let bare_stmt_root = self.suppress_poly_cast;
1580 self.suppress_poly_cast = false;
1581 if !bare_stmt_root {
1582 if let Some(t) = self.ctx.polymorphic_ret_cast(cls, name, desc) {
1583 out.push('(');
1584 out.push_str(&self.type_name(&crate::ir::expr::TypeRef::J(t)));
1585 out.push_str(") ");
1586 }
1587 }
1588 if name.as_ref() == "<init>" && *is_special {
1589 // The ctor fold normally turns `new X; <init>` into a
1590 // New expr at the LIFT. When the new-instance view was
1591 // lost (crossed a merge / got materialized), the call
1592 // arrives here with a NON-this receiver: rendering a
1593 // this/super delegation produced `this.super(...)`,
1594 // which is not valid Java. The allocation did happen —
1595 // print the construction call.
1596 let lost_alloc = owner
1597 .as_deref()
1598 .is_some_and(|o| !is_this_expr(o) && !matches!(o, Expr::This));
1599 if lost_alloc {
1600 // A member-inner construction call carries the
1601 // synthetic outer as args[0] and the emitted
1602 // ctor signature drops it (the inner-ctor
1603 // normalization) — supply it implicitly with the
1604 // qualified-new form, mirroring the New-expr
1605 // branches. Digit-tail classes keep the flat
1606 // full-args form (their ctor declares the
1607 // outer parameter).
1608 let digit_tail = cls
1609 .rsplit('$')
1610 .next()
1611 .map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
1612 .unwrap_or(false);
1613 if self.is_member_inner(cls)
1614 && !digit_tail
1615 && !args.is_empty()
1616 && !matches!(args[0], Expr::Const(_))
1617 {
1618 if matches!(args[0], Expr::This) || is_this_expr(&args[0]) {
1619 out.push_str("this.new ");
1620 } else {
1621 self.expr(&args[0], 15, out);
1622 out.push_str(".new ");
1623 }
1624 out.push_str(&inner_simple(cls));
1625 out.push('(');
1626 match self.ctor_param_types(cls, 1, args.len() - 1, &args[1..]) {
1627 Some(pt) => self.args_typed(&args[1..], &pt, out),
1628 None => self.args(&args[1..], out),
1629 }
1630 out.push(')');
1631 return;
1632 }
1633 out.push_str("new ");
1634 out.push_str(&self.shorten(cls));
1635 out.push('(');
1636 self.args(args, out);
1637 out.push(')');
1638 return;
1639 }
1640 // super(...) / this(...)
1641 let is_super_form = *is_super || cls.as_ref() != self.ctx.class_name();
1642 // Qualified super for a STATIC class extending an
1643 // INNER superclass: javac synthesizes the enclosing
1644 // instance as the ctor's first param, and the source
1645 // form is `outer.super(rest)` (jdk11/17/26
1646 // BoundMethodHandle.SpeciesData extends
1647 // ClassSpecializer<..>.SpeciesData — plain
1648 // super(outer, key) is "需要包含..的封闭实例" x3 trees).
1649 let qualified_outer = if is_super_form
1650 && !args.is_empty()
1651 && cls.contains('$')
1652 && !self.ctx.class_has_this0(self.ctx.class_name())
1653 {
1654 let enclosing = cls.rsplit_once('$').map(|(o, _)| o.to_string());
1655 match enclosing {
1656 Some(enc)
1657 if self.ctx.class_has_this0(cls)
1658 && self
1659 .ctx
1660 .is_subtype_of(&args[0].type_ref().erased(), &enc) =>
1661 {
1662 Some(enc)
1663 }
1664 _ => None,
1665 }
1666 } else {
1667 None
1668 };
1669 // The enclosing instance passed explicitly is `this`
1670 // itself (qualified_outer found the enclosing, but the
1671 // argument IS this class's own outer): the source form
1672 // is plain `super(rest...)` — the implicit outer —
1673 // because `this.super(...)` is not valid Java (weibo
1674 // HorseRaceDetector, reqable androidx.fragment.app.d).
1675 let this_outer =
1676 is_super_form && !args.is_empty() && is_this_expr(&args[0]);
1677 let skip_outer_arg = qualified_outer.is_some() || this_outer;
1678 if qualified_outer.is_some() && !this_outer {
1679 self.expr(&args[0], 15, out);
1680 out.push_str(".super(");
1681 } else if is_super_form {
1682 out.push_str("super(");
1683 } else {
1684 out.push_str("this(");
1685 }
1686 // Typed rendering: boolean/char params must not receive
1687 // raw 0/1 int constants (`this(refKind, false)`). The
1688 // methodref's descriptor `desc.args` is the EXACT invoked
1689 // ctor signature, so prefer it over `ctor_param_types`
1690 // (which matches by arg count and picks the wrong
1691 // overload when a class has several ctors of equal arity,
1692 // e.g. jdk26 Thread(ThreadGroup,Runnable,String,long,
1693 // boolean) vs (...,long,Thread[])).
1694 let _ = is_super_form;
1695 // Upcast restoration only for SELF delegation: this(..)
1696 // overload resolution binds the arg's static type (a
1697 // JarEntry arg would recurse into JarEntry(JarEntry)
1698 // instead of the descriptor's JarEntry(ZipEntry)).
1699 // super(..) resolution is unambiguous through the
1700 // generic formals — casting there broke FindOps
1701 // `super(parent, spliterator)` (K := FindTask<..>
1702 // accepts the arg fine; the raw erasure cast does not).
1703 if skip_outer_arg {
1704 if desc.args.len() == args.len() && !desc.args.is_empty() {
1705 self.args_typed(&args[1..], &desc.args[1..], out);
1706 } else {
1707 self.args(&args[1..], out);
1708 }
1709 } else if desc.args.len() == args.len() {
1710 if is_super_form {
1711 self.args_typed(args, &desc.args, out);
1712 } else {
1713 self.args_delegation(args, &desc.args, out);
1714 }
1715 } else if !is_super_form {
1716 // desc is the EXACT invoked ctor signature and the
1717 // args are outer-stripped: args_delegation aligns
1718 // by tail (jdk11 ZipFileInflaterInputStream —
1719 // ctor_param_types' arity match would pick the
1720 // wrong same-arity overload and cast against
1721 // shifted formals, (ZipFile) zfin x3).
1722 self.args_delegation(args, &desc.args, out);
1723 } else {
1724 match self.ctor_param_types(cls, 0, args.len(), args) {
1725 Some(pt) if pt.len() == args.len() => self.args_typed(args, &pt, out),
1726 _ => self.args(args, out),
1727 }
1728 }
1729 out.push(')');
1730 } else {
1731 if *is_super {
1732 // invokespecial on `this` targeting another class:
1733 // a superclass method call. Interface targets are
1734 // qualified `Iface.super.m()` (JDK8 default-method
1735 // invocations from implementors) — but only a
1736 // DIRECT superinterface may carry the qualifier
1737 // (JLS 15.11.2). A default reached through a
1738 // SUBINTERFACE (weixin jsapi/f0 implements e0
1739 // extends l; `l.super.m()` = "不是封闭类: l" ×67)
1740 // qualifies with the direct interface inheriting
1741 // it; one reached only through the superclass
1742 // chain falls back to plain `super.` (the super
1743 // inherits the default as its own member).
1744 let itf = self.ctx.is_interface(cls);
1745 if itf {
1746 let mut qual: Option<String> = None;
1747 if let Some((ifs, _)) =
1748 self.ctx.class_bases(self.ctx.class_name())
1749 {
1750 if ifs.iter().any(|i| i.as_str() == cls.as_ref()) {
1751 qual = Some(cls.to_string());
1752 } else {
1753 qual = ifs.into_iter().find(|i| {
1754 self.ctx.is_subtype_of(
1755 &crate::types::JavaType::Object(
1756 i.as_str().into(),
1757 ),
1758 cls,
1759 )
1760 });
1761 }
1762 }
1763 if let Some(q) = qual {
1764 out.push_str(&self.shorten(&q));
1765 out.push('.');
1766 }
1767 }
1768 out.push_str("super.");
1769 } else if let Some(o) = owner {
1770 if let Expr::Const(cv) = o.as_ref() {
1771 if matches!(
1772 cv,
1773 crate::ir::expr::ConstVal::Str(_)
1774 | crate::ir::expr::ConstVal::ClassLit(_)
1775 ) {
1776 // A literal receiver is valid, faithful
1777 // Java (`"http".equalsIgnoreCase(x)`,
1778 // `Foo.class.getName()`). Rendering it as
1779 // cast-null silently DROPPED the constant
1780 // — 73.5k sites across the 4 corpora
1781 // (`((String) null).m()`), invisible to
1782 // javac (it compiles) and an NPE at run
1783 // time. Only valueless placeholders take
1784 // the cast-null path below.
1785 self.expr(o, 15, out);
1786 out.push('.');
1787 } else {
1788 // Receiver tracking lost: a null placeholder
1789 // (const/4 0) leaked through as the receiver —
1790 // `0.close()` is not parseable. Cast-null keeps
1791 // the statement compilable and honestly marks
1792 // the value as unknown on this path.
1793 out.push_str("((");
1794 out.push_str(&self.shorten(cls));
1795 out.push_str(") null).");
1796 }
1797 } else if let Expr::Lambda(l) = o.as_ref() {
1798 // A lambda RECEIVER needs the source's SAM cast
1799 // (`((BooleanSupplier) () -> ..).getAsBoolean()`
1800 // — a bare lambda cannot own a call: 此处不应为
1801 // lambda 表达式, jdk26 Proxy assert).
1802 if !l.sam_cls.is_empty() {
1803 out.push_str("((");
1804 out.push_str(&self.shorten(&l.sam_cls));
1805 out.push_str(") ");
1806 self.expr(o, 14, out);
1807 out.push_str(").");
1808 } else {
1809 self.expr(o, 15, out);
1810 out.push('.');
1811 }
1812 } else if matches!(o.as_ref(), Expr::Raw(t) if t == "\u{3}") {
1813 // Outer anonymous member call: unqualified
1814 // lexical resolution.
1815 } else if self.needs_owner_cast(cls, name, desc, o) {
1816 // Private / cross-package members are NOT
1817 // inherited by the receiver's static type:
1818 // the source cast to the declaring class
1819 // (`((ZipFile) jar).getManifestNum()`) leaves
1820 // no bytecode trace when the receiver is
1821 // already a subtype.
1822 out.push_str("((");
1823 out.push_str(&self.shorten_concrete(cls));
1824 out.push_str(") ");
1825 self.expr(o, 14, out);
1826 out.push_str(").");
1827 } else {
1828 self.expr(o, 15, out);
1829 out.push('.');
1830 }
1831 } else if *is_static && (cls.as_ref() != self.ctx.class_name() || !type_args.is_empty())
1832 {
1833 // A static member of an ENCLOSING class resolves
1834 // through lexical scope unqualified — and the
1835 // qualified form is a TRAP when a field/local is
1836 // named after the class: expression-name
1837 // resolution prefers variables, so jdk26
1838 // HPKE$Impl's `private static final byte[] HPKE`
1839 // hijacked `HPKE.usePSK(psk)` into a member
1840 // lookup on the array (找不到符号 方法
1841 // usePSK(SecretKey) 位置: 类型为byte[]的变量
1842 // HPKE). Keep the qualifier when an own or
1843 // intermediate class declares a same-named
1844 // method (real member shadowing) or when type
1845 // witnesses need an explicit receiver.
1846 // renders_nested_in: flat-rendered (digit-tail)
1847 // nested classes have NO lexical scope.
1848 let enclosing_static = type_args.is_empty()
1849 && self.renders_nested_in(cls)
1850 && {
1851 let mut cur = self.ctx.class_name().to_string();
1852 let mut shadow = false;
1853 while cur.as_str() != cls.as_ref() {
1854 // Inherited members shadow too: the
1855 // lexical member scope of a class
1856 // includes its whole superclass chain
1857 // (jdk26 GaloisCounterMode$GCMDecrypt
1858 // extends GCMEngine, whose own
1859 // implGCMCrypt(ByteBuffer,..) hijacks
1860 // the bare 9-arg call to the OUTER
1861 // static — 无法将方法应用到给定类型).
1862 let mut sup = Some(cur.clone());
1863 while let Some(c) = sup.take() {
1864 {
1865 if self.ctx.declares_method_named(&c, name) {
1866 shadow = true;
1867 break;
1868 }
1869 sup = self.ctx.super_name(&c);
1870 }
1871 }
1872 if shadow {
1873 break;
1874 }
1875 match cur.rfind('$') {
1876 Some(i) => cur.truncate(i),
1877 None => break,
1878 }
1879 }
1880 !shadow
1881 };
1882 if !enclosing_static {
1883 // Concrete name: same anon-class trap as the
1884 // static FIELD qualifier (the SAM interface
1885 // does not declare the synthetic static).
1886 out.push_str(&self.shorten_concrete(cls));
1887 out.push('.');
1888 }
1889 } else if !type_args.is_empty() {
1890 // Type witnesses require an explicit receiver.
1891 out.push_str("this.");
1892 }
1893 if !type_args.is_empty() {
1894 out.push('<');
1895 out.push_str(&type_args.join(", "));
1896 out.push('>');
1897 }
1898 // A BARE `yield(...)` invocation trips Java 13's
1899 // restricted identifier (Kotlin suspend funs name
1900 // their continuation entry `yield`; news_article
1901 // ships CoroutineExtKt$yield). Qualified calls are
1902 // fine — when no receiver was printed, add one.
1903 if name.as_ref() == "yield" && !out.ends_with('.') && !out.ends_with('>') {
1904 out.push_str(&self.shorten(cls));
1905 out.push('.');
1906 }
1907 out.push_str(&java_ident(name));
1908 out.push('(');
1909 // Lambda args of a GENERIC call: prime each one's
1910 // body-return cast from the instantiated formal's SAM
1911 // return (jdk17 AbstractPipeline.opEvaluateParallelLazy:
1912 // `i -> (E_OUT[]) new Object[i]` — the erasure-equal
1913 // cast leaves no bytecode trace and without it the
1914 // IntFunction<E_OUT[]> formal starves: Object[]无法
1915 // 转换为E_OUT[]).
1916 let sam_rets: Vec<Option<TypeRef>> = {
1917 let mut v: Vec<Option<TypeRef>> =
1918 std::iter::repeat_with(|| None).take(args.len()).collect();
1919 if self.ctx.is_generic_call(e) {
1920 if let Some((formals, mtvars)) = self.ctx.generic_call_formals(e) {
1921 if formals.len() == args.len() {
1922 for (i, (a, f)) in args.iter().zip(formals.iter()).enumerate() {
1923 // A raw-SAM-cast wrapper still
1924 // exposes the lambda (the overload
1925 // disambiguation cast; the primed
1926 // body return types the lambda
1927 // precisely).
1928 let a_inner = match a {
1929 Expr::Cast { e: ce, .. } => ce.as_ref(),
1930 other => other,
1931 };
1932 if let Expr::Lambda(l) = a_inner {
1933 // A formal still carrying the
1934 // callee's own method typevars
1935 // is not denotable at this
1936 // call site.
1937 if crate::typeutil::g_mentions_any(f, &mtvars) {
1938 continue;
1939 }
1940 v[i] = self.sam_ret_cast(f, &l.sam_name);
1941 }
1942 }
1943 }
1944 }
1945 }
1946 v
1947 };
1948 if sam_rets.iter().any(|x| x.is_some()) {
1949 self.args_typed_sam(args, &desc.args, &sam_rets, out);
1950 } else {
1951 self.args_typed(args, &desc.args, out);
1952 }
1953 out.push(')');
1954 }
1955 }
1956 Expr::ArrayIndex { array, index } => {
1957 self.expr(array, 15, out);
1958 out.push('[');
1959 // Array indexes are int by definition: a long-typed index
1960 // local (slot-sharing/merge typed the foreach lowering's
1961 // counter long — jdk26 Files.copy `options[i]`,
1962 // 从long转换到int可能会有损失) needs the narrowing cast.
1963 let idx_ty = match &**index {
1964 Expr::Local { var, .. } => self.vt.var(*var).ty.erased(),
1965 other => other.type_ref().erased(),
1966 };
1967 if matches!(idx_ty, crate::types::JavaType::Long) {
1968 out.push_str("(int) ");
1969 }
1970 self.expr(index, 1, out);
1971 out.push(']');
1972 }
1973 Expr::Cast { ty, e } => {
1974 // `(T) (Serializable) lambda` is invalid Java: the source
1975 // form of a serializable-lambda cast is the intersection
1976 // `(T & Serializable) lambda`.
1977 if let Expr::Cast {
1978 ty: inner_ty,
1979 e: inner_e,
1980 } = &**e
1981 {
1982 let is_serializable = |t: &crate::ir::expr::TypeRef| {
1983 t.erased() == crate::types::JavaType::Object("java/io/Serializable".into())
1984 };
1985 if matches!(&**inner_e, Expr::Lambda(_)) && is_serializable(inner_ty) {
1986 out.push('(');
1987 out.push_str(&self.type_name(ty));
1988 out.push_str(" & ");
1989 out.push_str(&self.type_name(inner_ty));
1990 out.push_str(") ");
1991 self.expr(inner_e, 14, out);
1992 return;
1993 }
1994 }
1995 // CLASS-argument generic casts only: a TYPEVAR cast is
1996 // load-bearing (`(T) new SimpleEntry<>(..)` — jdk11
1997 // IdentityHashMap.toArray: the diamond infers from the
1998 // ctor args and the unchecked (T) makes the T[] store
1999 // legal; dropping it left the diamond to infer from the
2000 // array target T — 无法推断SimpleEntry<>的类型参数).
2001 if let (TypeRef::G(crate::types::GenericType::Class(_)), Expr::New { cls, .. }) =
2002 (ty, &**e)
2003 {
2004 if !self.diamond_for(cls).is_empty() {
2005 // Synthetic generics-only cast around a diamond new:
2006 // DROP the cast and keep the diamond. A generic-typed
2007 // cast is always jcdc's own witness (a real checkcast
2008 // carries only erasure), and every cast form loses
2009 // here: with the diamond the cast starves inference
2010 // (`(PendingFuture<Void,A>) new PendingFuture<>(..)`
2011 // infers Object bounds and fails the cast), and the
2012 // bare/raw form makes the whole creation raw so
2013 // method-ref/lambda arguments stop type-checking
2014 // (jdk17 Collectors `(Collector<T,?,C>) new
2015 // CollectorImpl(.., Collection::add, ..)`). Cast-free
2016 // `return new CollectorImpl<>(..)` / `x = new
2017 // PendingFuture<>(..)` target-types the diamond —
2018 // the source shape.
2019 self.expr(e, outer_prec, out);
2020 return;
2021 }
2022 }
2023 out.push('(');
2024 // A cast to a pool `$<digits>` class (desugared lambda /
2025 // coroutine frame) must keep the CONCRETE name: the
2026 // anon-fallback would print the SAM interface/super and
2027 // drop exactly the members the cast exists to reach
2028 // (weibo `(($reportWhenComplete$1) continuation).label`
2029 // rendered `(ContinuationImpl) …` — label lives on the
2030 // frame class only, R8 pushed it down; 找不到符号 ×420).
2031 match ty {
2032 TypeRef::J(crate::types::JavaType::Object(n))
2033 if self.ctx.has_class(n)
2034 && n.rsplit('$')
2035 .next()
2036 .is_some_and(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit())) =>
2037 {
2038 out.push_str(&self.shorten_concrete(n));
2039 }
2040 _ => out.push_str(&self.type_name(ty)),
2041 }
2042 out.push_str(") ");
2043 // Inconvertible direct casts from mis-joined stack-merge
2044 // vars (jdk26 AnnotationReader: `(SupertypeTarget)
2045 // var3_341` with var3 typed Iterator — sealed targets
2046 // reject the cross-cast): relay through Object, which is
2047 // always legal and semantically identical (the runtime
2048 // value IS the target type).
2049 if self.needs_object_relay(ty, e) {
2050 out.push_str("(Object) ");
2051 }
2052 if matches!(&**e, Expr::New { .. }) {
2053 self.suppress_diamond = true;
2054 }
2055 if let (TypeRef::G(g), Expr::Lambda(l)) = (ty, &**e) {
2056 self.lambda_sam_ret = self.sam_ret_cast(g, &l.sam_name);
2057 }
2058 self.expr(e, 14, out);
2059 self.suppress_diamond = false;
2060 self.lambda_sam_ret = None;
2061 }
2062 Expr::InstanceOf { e, ty } => {
2063 // `error2 instanceof CodecException` with error2: Error
2064 // is "不兼容的类型" — instanceof demands castability
2065 // exactly like a cast, so it takes the same Object
2066 // relay (semantics unchanged: instanceof is a runtime
2067 // type test).
2068 if self.needs_object_relay(ty, e) {
2069 out.push_str("((Object) ");
2070 self.expr(e, 14, out);
2071 out.push(')');
2072 } else {
2073 self.expr(e, 10, out);
2074 }
2075 out.push_str(" instanceof ");
2076 out.push_str(&self.type_name(ty));
2077 }
2078 Expr::Un { op, e } => {
2079 out.push_str(match op {
2080 UnOp::Neg => "-",
2081 UnOp::Not => "!",
2082 UnOp::BitNot => "~",
2083 });
2084 self.expr(e, 14, out);
2085 }
2086 Expr::Bin { op, l, r, .. } => {
2087 // Boolean context special cases: `b == 0` → `!b`. A
2088 // Local's embedded type can be stale (booleanize retypes
2089 // the VarTable), and a boolified bitwise bin over
2090 // bool-ish operands is boolean too (jdk26
2091 // LinkedTransferQueue `(spin & !upc) == 0` — the frozen-Int
2092 // And with an int-form ternary side printed
2093 // `spin & (!upc ? 1 : 0)`: boolean & int).
2094 let lt = match &**l {
2095 Expr::Local { var, .. } => self.vt.var(*var).ty.erased(),
2096 other => other.type_ref().erased(),
2097 };
2098 let l_bool = lt == JavaType::Boolean;
2099 let l_boolish = l_bool || self.bool_ish_vt(l);
2100 if matches!(op, BinOp::Eq | BinOp::Ne | BinOp::RefEq | BinOp::RefNe) && l_boolish {
2101 if let Expr::Const(ConstVal::Int(n)) = &**r {
2102 let polarity = matches!(op, BinOp::Eq | BinOp::RefEq);
2103 let want_true = (*n != 0) == polarity;
2104 if !want_true {
2105 out.push('!');
2106 }
2107 if l_bool {
2108 self.expr(l, 14, out);
2109 } else {
2110 // Composite boolean (a bitwise bin): parenthesize
2111 // so a leading `!` binds the whole value.
2112 out.push('(');
2113 self.expr_bool(l, out);
2114 out.push(')');
2115 }
2116 if parens {
2117 out.push(')');
2118 }
2119 return;
2120 }
2121 }
2122 // Mixed boolean/int equality on non-constants (stack-merge
2123 // vars of an assert desugaring: jdk26 VirtualThread
2124 // `stack38 == stack39` with stack38 boolean, stack39 int
2125 // 0/1 — "boolean和int不可比较"): normalize the int side
2126 // through `!= 0`.
2127 {
2128 let rt = r.type_ref().erased();
2129 if matches!(op, BinOp::Eq | BinOp::Ne)
2130 && ((lt == crate::types::JavaType::Boolean
2131 && rt == crate::types::JavaType::Int)
2132 || (lt == crate::types::JavaType::Int
2133 && rt == crate::types::JavaType::Boolean))
2134 {
2135 for (i, side) in [l, r].iter().enumerate() {
2136 if i > 0 {
2137 out.push(' ');
2138 out.push_str(op.symbol());
2139 out.push(' ');
2140 }
2141 if side.type_ref().erased() == crate::types::JavaType::Boolean {
2142 self.expr_bool(side, out);
2143 } else {
2144 out.push('(');
2145 self.expr(side, 1, out);
2146 out.push_str(" != 0)");
2147 }
2148 }
2149 if parens {
2150 out.push(')');
2151 }
2152 return;
2153 }
2154 }
2155 let p = op.precedence();
2156 self.expr(l, p, out);
2157 out.push(' ');
2158 out.push_str(op.symbol());
2159 out.push(' ');
2160 self.expr(r, p + 1, out);
2161 }
2162 Expr::Cond { c, t, f } => {
2163 self.expr(c, 3, out);
2164 out.push_str(" ? ");
2165 let prev = std::mem::replace(&mut self.in_cond, true);
2166 self.expr(t, 2, out);
2167 out.push_str(" : ");
2168 self.expr(f, 2, out);
2169 self.in_cond = prev;
2170 }
2171 Expr::Assign { target, op, value } => {
2172 // The local's VarTable type is authoritative: booleanize
2173 // flips vt types after the embedded Local tys were frozen
2174 // (Security `boolean var4_122 = 1` printed the int form —
2175 // "int无法转换为boolean").
2176 let tgt_er = match &**target {
2177 Expr::Local { var, .. } => self.vt.var(*var).ty.erased(),
2178 other => other.type_ref().erased(),
2179 };
2180 self.expr(target, 1, out);
2181 out.push(' ');
2182 out.push_str(op.symbol());
2183 out.push(' ');
2184 if matches!(op, crate::ir::expr::AssignOp::Plain) {
2185 // Narrow-target assignments render int constants in the
2186 // target's form (jdk11/17/26 xml Parser: `mESt = ch !=
2187 // 116 ? 512 : 60` against `private char mESt` —
2188 // "从int转换到char可能会有损失").
2189 match tgt_er {
2190 crate::types::JavaType::Boolean => self.expr_bool(value, out),
2191 crate::types::JavaType::Char => self.expr_char(value, out),
2192 crate::types::JavaType::Byte => {
2193 self.expr_narrow(value, &crate::types::JavaType::Byte, out)
2194 }
2195 crate::types::JavaType::Short => {
2196 self.expr_narrow(value, &crate::types::JavaType::Short, out)
2197 }
2198 _ => self.expr(value, 1, out),
2199 }
2200 } else {
2201 self.expr(value, 1, out);
2202 }
2203 }
2204 Expr::PreIncDec { e, delta, .. } => {
2205 out.push_str(if *delta > 0 { "++" } else { "--" });
2206 self.expr(e, 14, out);
2207 }
2208 Expr::PostIncDec { e, delta, .. } => {
2209 self.expr(e, 14, out);
2210 out.push_str(if *delta > 0 { "++" } else { "--" });
2211 }
2212 Expr::Lambda(l) => self.lambda(l, out),
2213 Expr::AnonNew {
2214 base, args, body, ..
2215 } => {
2216 out.push_str("new ");
2217 let base_s = self.type_name(base);
2218 out.push_str(&base_s);
2219 out.push('(');
2220 // Render the ctor args through the base class's matching
2221 // <init> descriptor: an int 0/1 at a boolean parameter
2222 // must print as false/true (jdk11 Console's anonymous
2223 // PrintWriter subclass — `new PrintWriter(out, 1)` finds
2224 // no ctor). Pick the arity-matching ctor whose param
2225 // erasures best fit the actual arg types.
2226 let base_internal = match base {
2227 TypeRef::J(crate::types::JavaType::Object(n)) => Some(n.clone()),
2228 TypeRef::G(crate::types::GenericType::Class(cs)) => {
2229 Some(crate::typeutil::classsig_internal(cs).into())
2230 }
2231 _ => None,
2232 };
2233 // Overload choice for the ctor args (int 0/1 at a boolean
2234 // formal must print false/true) reads the base class's own
2235 // `<init>` set: front-end metadata.
2236 let ctor_params = base_internal
2237 .and_then(|bi| self.ctx.ctor_param_types(&bi, 0, args.len(), args));
2238 match ctor_params {
2239 Some(pt) => self.args_typed(args, &pt, out),
2240 None => self.args(args, out),
2241 }
2242 out.push_str(") {\n");
2243 for line in body.lines() {
2244 for _ in 0..self.indent + 1 {
2245 out.push_str(" ");
2246 }
2247 out.push_str(line.trim_start_matches(' '));
2248 out.push('\n');
2249 }
2250 for _ in 0..self.indent {
2251 out.push_str(" ");
2252 }
2253 out.push('}');
2254 }
2255 Expr::StringConcat(parts) => {
2256 let mut first = true;
2257 // Java semantics: the concatenation must start with a
2258 // String. NOT for an empty parts list: the trailing
2259 // is_empty guard below already prints `""` — both firing
2260 // printed four quotes.
2261 let needs_prefix =
2262 !parts.is_empty() && !matches!(parts.first(), Some(ConcatPart::Const(_)));
2263 if needs_prefix {
2264 out.push_str("\"\"");
2265 first = false;
2266 }
2267 for p in parts {
2268 // Right-hand operands of `+` need parens at equal
2269 // precedence to keep arithmetic grouping (`"t" + (x+1)`).
2270 let is_first = first;
2271 if !first {
2272 out.push_str(" + ");
2273 }
2274 first = false;
2275 match p {
2276 ConcatPart::Const(s) => {
2277 out.push('"');
2278 out.push_str(&escape_string(s));
2279 out.push('"');
2280 }
2281 ConcatPart::Str(e) => self.expr(e, if is_first { 12 } else { 13 }, out),
2282 }
2283 }
2284 if parts.is_empty() {
2285 out.push_str("\"\"");
2286 }
2287 }
2288 Expr::Invokedynamic {
2289 name,
2290 args,
2291 bsm_text,
2292 ..
2293 } => {
2294 if name.starts_with('\u{0}') {
2295 out.push_str("/*bad-cmp*/0");
2296 } else {
2297 out.push_str("/* invokedynamic ");
2298 out.push_str(name);
2299 out.push(' ');
2300 out.push_str(bsm_text);
2301 out.push_str(" */ (");
2302 self.args(args, out);
2303 out.push(')');
2304 }
2305 }
2306 }
2307 if parens {
2308 out.push(')');
2309 }
2310 }
2311
2312 fn args(&mut self, args: &[Expr], out: &mut String) {
2313 for (i, a) in args.iter().enumerate() {
2314 if i > 0 {
2315 out.push_str(", ");
2316 }
2317 self.expr(a, 1, out);
2318 }
2319 }
2320
2321 /// Print call args applying boolean-parameter constant adjustment.
2322 /// Delegation (this(..)/super(..)) args: typed rendering PLUS the
2323 /// elided-upcast restoration when the arg's static type differs from
2324 /// the descriptor formal — overload resolution binds the arg's type,
2325 /// not the descriptor (jdk17 JarEntry copy ctor: `this(je)` resolves
2326 /// recursively to JarEntry(JarEntry); the source `this((ZipEntry) je)`
2327 /// upcast is elided from bytecode because je <: ZipEntry is provable).
2328 fn args_delegation(
2329 &mut self,
2330 args: &[Expr],
2331 param_types: &[crate::types::JavaType],
2332 out: &mut String,
2333 ) {
2334 // Inner-class ctor descriptors carry the synthetic outer param
2335 // while the expression args are outer-stripped: align the formals
2336 // with the TRAIL of the args, like apply_ctor_param_casts (jdk11
2337 // ZipFileInflaterInputStream this(zfin, res, res.getInflater(),
2338 // size) was cast against the shifted descriptor formals —
2339 // (ZipFile) zfin, (ZipFileInputStream) res... x3 inconvertible).
2340 let off = param_types.len().saturating_sub(args.len());
2341 for (i, a) in args.iter().enumerate() {
2342 if i > 0 {
2343 out.push_str(", ");
2344 }
2345 match param_types.get(off + i) {
2346 Some(pt @ crate::types::JavaType::Object(_)) => {
2347 let have = a.type_ref().erased();
2348 // Generically-typed args (typevars/parameterized) are
2349 // already source-typed: casting them to the descriptor
2350 // erasure breaks convertibility to typevar formals
2351 // (jdk17 StreamSpliterators SliceSpliterator.OfPrimitive
2352 // this((Spliterator.OfPrimitive) s, ..) against a
2353 // T_SPLITR formal — OfPrimitive无法转换为T_SPLITR).
2354 if &have != pt
2355 && !matches!(a.type_ref(), TypeRef::G(_))
2356 && !matches!(
2357 a,
2358 Expr::Cast { .. }
2359 | Expr::Const(_)
2360 | Expr::Lambda(_)
2361 | Expr::New { .. }
2362 | Expr::AnonNew { .. }
2363 )
2364 {
2365 out.push('(');
2366 out.push_str(&self.type_name(&TypeRef::J(pt.clone())));
2367 out.push_str(") ");
2368 self.expr(a, 14, out);
2369 continue;
2370 }
2371 self.expr(a, 1, out);
2372 }
2373 Some(crate::types::JavaType::Boolean) => self.expr_bool(a, out),
2374 Some(crate::types::JavaType::Char) => self.expr_char(a, out),
2375 Some(pt @ (crate::types::JavaType::Byte | crate::types::JavaType::Short)) => {
2376 self.expr_narrow_arg(a, pt, out)
2377 }
2378 _ => self.expr(a, 1, out),
2379 }
2380 }
2381 }
2382
2383 fn args_typed(
2384 &mut self,
2385 args: &[Expr],
2386 param_types: &[crate::types::JavaType],
2387 out: &mut String,
2388 ) {
2389 self.args_typed_sam(args, param_types, &[], out)
2390 }
2391
2392 /// args_typed with per-argument SAM-return priming: a lambda actual at
2393 /// a parameterized-SAM formal of a pinned generic ctor gets its body
2394 /// return cast from the formal's instantiated SAM return (jdk11/17/26
2395 /// Collectors.toUnmodifiable*'s finisher `list -> (List<T>)
2396 /// List.of(list.toArray())` — the erased instantiatedMethodType says
2397 /// only List, so the generic cast is recoverable solely from the
2398 /// diamond's resolved formal).
2399 fn args_typed_sam(
2400 &mut self,
2401 args: &[Expr],
2402 param_types: &[crate::types::JavaType],
2403 sam_rets: &[Option<TypeRef>],
2404 out: &mut String,
2405 ) {
2406 for (i, a) in args.iter().enumerate() {
2407 if i > 0 {
2408 out.push_str(", ");
2409 }
2410 match param_types.get(i) {
2411 Some(crate::types::JavaType::Boolean) => self.expr_bool(a, out),
2412 // Char/narrow params: expr_char/expr_narrow render both
2413 // constants AND conditional branches in the target form
2414 // (jdk17 BasicAuthentication `super(!isProxy ? 115 : 112,
2415 // ..)` — the char param needs `!isProxy ? 's' : 'p'`;
2416 // a plain int ternary is "条件表达式中的类型错误").
2417 Some(crate::types::JavaType::Char) => self.expr_char(a, out),
2418 // Byte/short parameters: an int literal argument needs an
2419 // explicit cast (invocation conversion never narrows, even
2420 // for in-range constants) — and so do the branches of an
2421 // int conditional (jdk CompressedResourceHeader
2422 // `buffer.put(isTerminal ? (byte) 1 : (byte) 0)` — the
2423 // byte casts fold away in bytecode; a bare int ternary is
2424 // "对于put(int), 找不到合适的方法" x3 trees).
2425 Some(crate::types::JavaType::Byte) | Some(crate::types::JavaType::Short) => {
2426 self.expr_narrow_arg(a, ¶m_types[i].clone(), out);
2427 }
2428 _ => {
2429 let lam_under_cast = matches!(a, Expr::Lambda(_))
2430 || matches!(a, Expr::Cast { e: ce, .. } if matches!(&**ce, Expr::Lambda(_)));
2431 match sam_rets.get(i).and_then(|x| x.as_ref()) {
2432 Some(t) if lam_under_cast => {
2433 let prev = self.lambda_sam_ret.replace(t.clone());
2434 self.expr(a, 1, out);
2435 self.lambda_sam_ret = prev;
2436 }
2437 _ => self.expr(a, 1, out),
2438 }
2439 }
2440 }
2441 }
2442 }
2443
2444 fn const_val(&self, c: &ConstVal, out: &mut String) {
2445 match c {
2446 ConstVal::Int(i) => out.push_str(&i.to_string()),
2447 ConstVal::Long(l) => {
2448 if *l == i64::MIN {
2449 out.push_str("-9223372036854775808L");
2450 } else {
2451 out.push_str(&format!("{}L", l));
2452 }
2453 }
2454 ConstVal::Float(f) => out.push_str(&format_float(*f as f64, true)),
2455 ConstVal::Double(d) => out.push_str(&format_float(*d, false)),
2456 ConstVal::Str(s) => {
2457 out.push('"');
2458 out.push_str(&escape_string(s));
2459 out.push('"');
2460 }
2461 ConstVal::Null => out.push_str("null"),
2462 ConstVal::ClassLit(t) => {
2463 out.push_str(&self.type_name(t));
2464 out.push_str(".class");
2465 }
2466 }
2467 }
2468
2469 fn lambda(&mut self, l: &crate::ir::expr::LambdaExpr, out: &mut String) {
2470 // A `lambda$...` implementation method in the current class is a
2471 // compiler-generated lambda body, never a real method reference —
2472 // emit the body inline even when classified as a reference (the
2473 // method itself is hidden from the output).
2474 let synthetic_self_lambda =
2475 l.impl_name.starts_with("lambda$") && l.impl_owner == self.ctx.class_name();
2476 match l.kind {
2477 LambdaKind::MethodRef if !synthetic_self_lambda => {
2478 // Determine receiver form.
2479 if l.impl_name == "<init>" {
2480 out.push_str(&self.shorten(&l.impl_owner));
2481 out.push_str("::new");
2482 return;
2483 }
2484 if let Some(recv) = &l.ref_receiver {
2485 out.push_str(&self.shorten(recv));
2486 out.push_str("::");
2487 out.push_str(&l.impl_name);
2488 } else if !l.captures.is_empty() {
2489 // bound receiver: first capture is the instance
2490 // A method-ref/lambda receiver needs its functional
2491 // type spelled out: `A::new::get` parses as a
2492 // QUALIFIED reference and is rejected — the source form
2493 // is `((Supplier<A>) A::new)::get`.
2494 let cap = &l.captures[0];
2495 let func_ty = match cap {
2496 Expr::Lambda(l2) => Some(l2.sam_cls.clone()),
2497 Expr::Cast { ty, e } if matches!(**e, Expr::Lambda(_)) => {
2498 Some(ty.erased().to_descriptor())
2499 }
2500 _ => None,
2501 };
2502 if let Some(f) = func_ty {
2503 out.push_str("((");
2504 out.push_str(&self.shorten(&f));
2505 out.push_str(") ");
2506 self.expr(cap, 1, out);
2507 out.push(')');
2508 } else {
2509 self.expr(cap, 15, out);
2510 }
2511 out.push_str("::");
2512 out.push_str(&l.impl_name);
2513 } else {
2514 out.push_str(&self.shorten(&l.impl_owner));
2515 out.push_str("::");
2516 out.push_str(&l.impl_name);
2517 }
2518 }
2519 _ => {
2520 if self.lambda_depth >= 8 {
2521 out.push_str("/*nested-lambda*/null");
2522 return;
2523 }
2524 // The nested-body preparation — decompiling the impl
2525 // method and running the front-end's idiom recovery
2526 // (anonymous inlining, capture snapshots, enum switches,
2527 // witness casts, outer-this substitution, label pruning,
2528 // ...) — belongs to the front-end: that is where
2529 // machine-specific desugaring lives. Ask it for a finished
2530 // statement tree and print that.
2531 // The nested-body preparation — decompiling the impl method
2532 // and running the front-end's idiom recovery (anonymous
2533 // inlining, capture snapshots, enum switches, witness casts,
2534 // outer-this substitution, label pruning, ...) — belongs to
2535 // the front-end: that is where machine-specific desugaring
2536 // lives. Ask it for a finished statement tree and print that.
2537 let nested = self.ctx.nested_method(l, self.vt);
2538 // params: prefer the impl method's own parameter names so the
2539 // printed parameter list matches the body's references
2540 // (instance lambda impls carry only the SAM params).
2541 let mut pnames = l.param_names.clone();
2542 if let Some(MethodBody { vt, .. }) = &nested {
2543 let mut vt_params: Vec<String> = vt
2544 .vars
2545 .iter()
2546 .filter(|v| v.is_param && v.name != "this")
2547 .map(|v| v.name.clone())
2548 .collect();
2549 if vt_params.len() == pnames.len() {
2550 pnames = vt_params;
2551 } else if vt_params.len() > pnames.len() {
2552 // The impl method's signature is (captures..., SAM
2553 // params...): take the TRAILING SAM slice so the
2554 // printed parameter list matches the body's variable
2555 // references (ConcurrentMap.replaceAll printed
2556 // `(x0, x1) -> { .. replace(k, v, ..) }` — undefined
2557 // symbols; the captured `function` occupied the first
2558 // impl slot, breaking the exact-length alignment).
2559 let n = pnames.len();
2560 pnames = vt_params.split_off(vt_params.len() - n);
2561 }
2562 }
2563 let single = pnames.len() == 1;
2564 if !single {
2565 out.push('(');
2566 }
2567 for (i, n) in pnames.iter().enumerate() {
2568 if i > 0 {
2569 out.push_str(", ");
2570 }
2571 out.push_str(n);
2572 }
2573 if !single {
2574 out.push(')');
2575 }
2576 out.push_str(" -> ");
2577 let sam_wrap = self.lambda_sam_ret.take();
2578 match nested {
2579 Some(MethodBody {
2580 mut body, mut vt, ..
2581 }) => {
2582 // Single-return body → expression lambda.
2583 let mut single_expr = match &body {
2584 Stmt::Return(Some(e)) => Some(e.clone()),
2585 Stmt::Block(v) if v.len() == 1 => match &v[0] {
2586 Stmt::Return(Some(e)) => Some(e.clone()),
2587 _ => None,
2588 },
2589 _ => None,
2590 };
2591 // Witness the instantiated SAM return on the body's
2592 // returns: the impl method is erased, so `i -> i`
2593 // under `(Function<I,R>)` fails inference without
2594 // `(R) i`.
2595 fn sam_ok(t: &TypeRef, e: &Expr) -> bool {
2596 !matches!(e, Expr::Cast { .. } | Expr::Const(_)) && e.type_ref() != *t
2597 }
2598 fn wrap_returns(s: &mut Stmt, t: &TypeRef) {
2599 match s {
2600 Stmt::Return(Some(e)) => {
2601 if sam_ok(t, e) {
2602 let v = std::mem::replace(e, Expr::This);
2603 *e = Expr::Cast {
2604 ty: t.clone(),
2605 e: Box::new(v),
2606 };
2607 }
2608 }
2609 Stmt::Block(v) => v.iter_mut().for_each(|x| wrap_returns(x, t)),
2610 Stmt::If {
2611 then_stmt,
2612 else_stmt,
2613 ..
2614 } => {
2615 wrap_returns(then_stmt, t);
2616 if let Some(x) = else_stmt {
2617 wrap_returns(x, t);
2618 }
2619 }
2620 Stmt::While { body, .. }
2621 | Stmt::DoWhile { body, .. }
2622 | Stmt::ForEach { body, .. }
2623 | Stmt::Labeled { body, .. }
2624 | Stmt::Synchronized { body, .. } => wrap_returns(body, t),
2625 Stmt::For { init, body, .. } => {
2626 init.iter_mut().for_each(|i| wrap_returns(i, t));
2627 wrap_returns(body, t);
2628 }
2629 Stmt::Switch { cases, default, .. } => {
2630 for c in cases.iter_mut() {
2631 for st in c.body.iter_mut() {
2632 wrap_returns(st, t);
2633 }
2634 }
2635 if let Some(d) = default {
2636 wrap_returns(d, t);
2637 }
2638 }
2639 Stmt::Try {
2640 body,
2641 catches,
2642 finally,
2643 } => {
2644 wrap_returns(body, t);
2645 for c in catches.iter_mut() {
2646 wrap_returns(&mut c.body, t);
2647 }
2648 if let Some(f) = finally {
2649 wrap_returns(f, t);
2650 }
2651 }
2652 _ => {}
2653 }
2654 }
2655 if let Some(t) = &sam_wrap {
2656 if let Some(e) = &mut single_expr {
2657 if sam_ok(t, e) {
2658 let v = std::mem::replace(e, Expr::This);
2659 *e = Expr::Cast {
2660 ty: t.clone(),
2661 e: Box::new(v),
2662 };
2663 } else if let TypeRef::G(_) = t {
2664 // The body already carries the erasure
2665 // checkcast: retype it to the generic
2666 // SAM return (jdk26
2667 // CopyOnWriteArrayList.toArray `i ->
2668 // (T[]) new Object[i]` printed
2669 // `(Object[])` — Object[]无法转换为T[]
2670 // against IntFunction<T[]>).
2671 if let Expr::Cast { ty: ct, e: ce } = e {
2672 if ct.erased() == t.erased()
2673 && !matches!(&**ce, Expr::Cast { .. })
2674 {
2675 *ct = t.clone();
2676 }
2677 }
2678 }
2679 } else {
2680 wrap_returns(&mut body, t);
2681 }
2682 } else if let Some(inst) = &l.inst_sam_desc {
2683 if crate::dbg_flag!("JCDC_DBG_LAMRET") {
2684 eprintln!(
2685 "LAMRET impl={}.{} inst_ret={:?} single={}",
2686 l.impl_owner,
2687 l.impl_name,
2688 inst.ret,
2689 single_expr.is_some()
2690 );
2691 }
2692 // The invokedynamic's instantiatedMethodType
2693 // records the lambda's inferred return at the
2694 // call site; a source upcast can be elided from
2695 // the bytecode when provable (jdk17
2696 // JrtFileSystem.iteratorOf: `(Path)` around
2697 // path.resolve(..) inside map(child -> ...) —
2698 // JrtPath <: Path needs no checkcast, but
2699 // without the cast map infers Stream<JrtPath>
2700 // and .iterator() fails the Iterator<Path>
2701 // return). Restore it when the expression body
2702 // is typed a strict subtype of the recorded
2703 // return.
2704 fn upcast_ok(
2705 e: &Expr,
2706 target: &crate::types::JavaType,
2707 ctx: &dyn crate::ctx::Ctx,
2708 ) -> bool {
2709 let crate::types::JavaType::Object(t) = target else {
2710 return false;
2711 };
2712 // A parameterized (generic) value whose
2713 // erasure IS the target reaches it unchecked
2714 // (jdk17 CompletionStage exceptionallyCompose:
2715 // the cond branch fn.apply(ex) types as the
2716 // capture ? extends CompletionStage<T>; the
2717 // erased impl return CompletionStage needs no
2718 // cast, and printing one breaks the outer
2719 // chain's inference).
2720 if let TypeRef::G(crate::types::GenericType::Class(cs)) =
2721 e.type_ref()
2722 {
2723 if crate::typeutil::classsig_internal(&cs).as_str() == t.as_ref() {
2724 return true;
2725 }
2726 }
2727 let crate::types::JavaType::Object(e0) = e.type_ref().erased()
2728 else {
2729 return false;
2730 };
2731 if &e0 == t {
2732 return false;
2733 }
2734 let mut queue = vec![e0];
2735 let mut seen = std::collections::HashSet::new();
2736 while let Some(cur) = queue.pop() {
2737 if !seen.insert(cur.clone()) {
2738 continue;
2739 }
2740 if !ctx.has_class(&cur) {
2741 continue;
2742 }
2743 for (sup, _) in ctx.class_supers_args(&cur, &[]) {
2744 if sup.as_str() == t.as_ref() {
2745 return true;
2746 }
2747 queue.push(sup.into());
2748 }
2749 }
2750 false
2751 }
2752 let want = TypeRef::J(inst.ret.clone());
2753 // The sam_wrap prime (declared local / pinned
2754 // ctor formal / generic-call formal) carries the
2755 // GENERIC SAM return the erased
2756 // instantiatedMethodType lost: upgrade an
2757 // existing erasure-equal cast on the body (jdk26
2758 // CopyOnWriteArrayList.toArray's `i -> (T[]) new
2759 // Object[i]` printed `(Object[])` — the real
2760 // checkcast erases T[] and Object[] alike;
2761 // Object[]无法转换为T[] against
2762 // IntFunction<T[]>).
2763 let g_want: Option<TypeRef> = sam_wrap.as_ref().and_then(|t| {
2764 if let TypeRef::G(g) = t {
2765 if TypeRef::G(g.clone()).erased() == inst.ret {
2766 return Some(t.clone());
2767 }
2768 }
2769 None
2770 });
2771 if let Some(e) = &mut single_expr {
2772 if crate::dbg_flag!("JCDC_DBG_LAMRET") {
2773 eprintln!(
2774 "LAMRET2 inst_ret={:?} expr_ty={:?} sam_ok={} upcast_ok={} g_want={:?}",
2775 inst.ret,
2776 e.type_ref(),
2777 sam_ok(&want, e),
2778 upcast_ok(e, &inst.ret, self.ctx),
2779 g_want
2780 );
2781 }
2782 let mut upgraded = false;
2783 if let Some(gw) = &g_want {
2784 if let Expr::Cast { ty, e: ce } = e {
2785 if ty.erased() == inst.ret
2786 && !matches!(&**ce, Expr::Cast { .. })
2787 {
2788 *ty = gw.clone();
2789 upgraded = true;
2790 }
2791 }
2792 }
2793 if !upgraded
2794 && sam_ok(&want, e)
2795 && upcast_ok(e, &inst.ret, self.ctx)
2796 {
2797 let v = std::mem::replace(e, Expr::This);
2798 *e = Expr::Cast {
2799 ty: want,
2800 e: Box::new(v),
2801 };
2802 }
2803 }
2804 }
2805 // A nested lambda body shares the ENCLOSING
2806 // lambda's scope rules: its own locals must not
2807 // redeclare names visible there (jdk26
2808 // MethodHandleProxies.createTemplate — the clb
2809 // lambda's foreach-desugared `i$`/`mi` collided
2810 // with the nested cob lambda's own `i$`/`mi`,
2811 // 已在方法中定义了变量 x2). Rename the inner
2812 // impl's non-param locals on collision; the
2813 // method-level twin is handled by
2814 // disambiguate_lambda_locals.
2815 {
2816 let mut outer_names: std::collections::HashSet<&str> =
2817 self.vt.vars.iter().map(|v| v.name.as_str()).collect();
2818 outer_names.extend(self.outer_names.iter().map(|n| n.as_str()));
2819 let mut used: std::collections::HashSet<String> =
2820 vt.vars.iter().map(|v| v.name.clone()).collect();
2821 for v in vt.vars.iter_mut() {
2822 if v.is_param || !outer_names.contains(v.name.as_str()) {
2823 continue;
2824 }
2825 let base = v.name.clone();
2826 let mut k = 1;
2827 loop {
2828 let cand = format!("{}${}", base, k);
2829 if !used.contains(&cand) && !outer_names.contains(cand.as_str())
2830 {
2831 used.insert(cand.clone());
2832 v.name = cand;
2833 break;
2834 }
2835 k += 1;
2836 }
2837 }
2838 }
2839 let mut sub = Printer {
2840 ctx: self.ctx,
2841 vt: &vt,
2842 out: String::new(),
2843 line_buf: String::new(),
2844 indent: self.indent,
2845 lambda_depth: self.lambda_depth + 1,
2846 ignored_seq: self.ignored_seq,
2847 outer_names: {
2848 let mut n = self.outer_names.clone();
2849 n.extend(self.vt.vars.iter().map(|v| v.name.clone()));
2850 n
2851 },
2852 // The SAM's return type governs the impl
2853 // body's renders: boolean SAMs must print
2854 // `return true;` not the JVM-int `return 1;`
2855 // (jdk26 Gatherers.fold's ofGreedy lambda).
2856 ret_bool: l.sam_desc.ret == crate::types::JavaType::Boolean,
2857 ret_char: l.sam_desc.ret == crate::types::JavaType::Char,
2858 ret_byte: l.sam_desc.ret == crate::types::JavaType::Byte,
2859 ret_short: l.sam_desc.ret == crate::types::JavaType::Short,
2860 suppress_poly_cast: false,
2861 suppress_diamond: false,
2862 // A lambda body is a fresh expression context:
2863 // the enclosing conditional's pre-8 non-poly
2864 // rule does not propagate into it (the lambda
2865 // is a standalone method body).
2866 in_cond: false,
2867 lambda_sam_ret: None,
2868 ret_sam: None,
2869 twin_cache: self.twin_cache.clone(),
2870 };
2871 if let Some(e) = single_expr {
2872 if l.sam_desc.ret == crate::types::JavaType::Boolean {
2873 sub.expr_bool(&e, out);
2874 } else {
2875 sub.expr(&e, 1, out);
2876 }
2877 } else {
2878 out.push_str("{\n");
2879 sub.indent += 1;
2880 sub.stmt(&body);
2881 let text = sub.out;
2882 out.push_str(&text);
2883 for _ in 0..self.indent {
2884 out.push_str(" ");
2885 }
2886 out.push('}');
2887 }
2888 }
2889 None => {
2890 out.push_str("/* lambda body in ");
2891 out.push_str(&l.impl_owner);
2892 out.push('.');
2893 out.push_str(&l.impl_name);
2894 out.push_str(" */ {}");
2895 }
2896 }
2897 }
2898 }
2899 }
2900
2901 // ---------------- names & types ----------------
2902
2903 /// True if `cls` is a member inner class (declares this$0) per the pool.
2904 /// Parameter types of the `<init>` matching `skip + n` descriptor args,
2905 /// returning the tail after `skip` leading synthetic params. Used to
2906 /// print `new` arguments with boolean/char constant adjustment.
2907 fn ctor_param_types(
2908 &self,
2909 cls: &str,
2910 skip: usize,
2911 n: usize,
2912 args: &[Expr],
2913 ) -> Option<Vec<crate::types::JavaType>> {
2914 // Overload/parameter recovery from the class's own `<init>` set is
2915 // container metadata: the front-end answers it.
2916 self.ctx.ctor_param_types(cls, skip, n, args)
2917 }
2918
2919 fn is_member_inner(&self, cls: &str) -> bool {
2920 // Front-end metadata question: synthetic outer field, or an enclosing
2921 // instance forwarded to super?
2922 if self.ctx.class_has_this0(cls) {
2923 return true;
2924 }
2925 if !cls.contains('$') || self.ctx.nested_is_static(cls) {
2926 return false;
2927 }
2928 self.ctx.outer_param_via_super(cls)
2929 }
2930
2931 /// Is `cls` lexically enclosing the CURRENT class in the RENDERED
2932 /// layout? Digit-tail classes (anonymous/d8-lambda shapes) are
2933 /// emitted as separate flat top-level files — the nested lexical
2934 /// scope they would provide does not exist there, so members of an
2935 /// outer class must be QUALIFIED from them (weibo
2936 /// CronetUrlRequest$3: bare `_$$Nest$misDoneLocked(..)` calls of
2937 /// the outer's statics were unresolvable).
2938 fn renders_nested_in(&self, cls: &str) -> bool {
2939 let cur = self.ctx.class_name();
2940 if !cur.starts_with(&format!("{}$", cls)) {
2941 return false;
2942 }
2943 let mut c = cur.to_string();
2944 while c.as_str() != cls {
2945 let tail = c.rsplit('$').next().unwrap_or(&c);
2946 if tail.is_empty()
2947 || tail.chars().next().is_some_and(|ch| ch.is_ascii_digit())
2948 {
2949 return false; // flat-rendered boundary: no lexical scope
2950 }
2951 match c.rfind('$') {
2952 Some(i) => c.truncate(i),
2953 None => return false,
2954 }
2955 }
2956 true
2957 }
2958
2959 /// Instantiated SAM return for a cast to a generic functional
2960 /// interface (`(Function<I,R>) lambda`): resolves the interface's SAM
2961 /// method Signature return against the cast's type arguments. Only
2962 /// meaningful when the result still contains a type variable — the
2963 /// erased impl body then needs `(R) value` witnesses on its returns
2964 /// (javac: "return type I cannot be converted to R" for `i -> i`).
2965 fn sam_ret_cast(&self, g: &crate::types::GenericType, sam_name: &str) -> Option<TypeRef> {
2966 // Resolving a functional interface's SAM return against a cast's type
2967 // arguments reads the interface's method signatures: front-end
2968 // metadata.
2969 self.ctx.sam_ret_cast(g, sam_name)
2970 }
2971
2972 /// `<>` when `new cls(...)` should carry a diamond: the class is
2973 /// generic (class-level Signature with type params) and THIS file is
2974 /// Java 7+. A bare generic new compiles under old-style inference
2975 /// (standalone, not target-typed), which collapses to Object when
2976 /// implicitly-typed lambda args are involved — jdk11 Collectors.
2977 /// summingInt's `new CollectorImpl<>(() -> new int[1], (a, t) -> ...)`
2978 /// fails as bare `new CollectorImpl(...)` ("array required, but found
2979 /// Object", 72 errors in the concurrent-family closure). Bytecode
2980 /// cannot distinguish diamond from bare, so always prefer the diamond
2981 /// for generic classes.
2982 fn diamond_for(&self, cls: &str) -> &'static str {
2983 if self.ctx.source_level() < 51 {
2984 return "";
2985 }
2986 if self.ctx.class_declares_generics(cls) {
2987 "<>"
2988 } else {
2989 ""
2990 }
2991 }
2992
2993 /// Shorten an internal class name for emission: java.lang.* and same
2994 /// package use simple names; others fully qualified dotted.
2995 /// True when `cls.name` is a PRIVATE instance field and the owner
2996 /// expression's compile-time type is a strict subclass of cls: the
2997 /// field is not in the subclass's member scope, so the source must
2998 /// cast the owner to the declaring class
2999 /// (`((MessageDigest)this).algorithm` — jdk11 Delegate.clone x3,
3000 /// Signature.clone).
3001 fn private_super_field(&self, cls: &str, name: &str, o: &Expr) -> bool {
3002 if matches!(o, Expr::Raw(_) | Expr::RawT(..)) {
3003 return false;
3004 }
3005 let owner_ct = if matches!(o, Expr::This) {
3006 self.ctx.class_name().into()
3007 } else {
3008 match o.type_ref().erased() {
3009 crate::types::JavaType::Object(n) => n,
3010 _ => return false,
3011 }
3012 };
3013 if owner_ct.as_ref() == cls {
3014 return false;
3015 }
3016 let Some(flags) = self.ctx.field_flags(cls, name) else {
3017 return false;
3018 };
3019 if flags.contains(crate::types::FieldAccessFlags::STATIC)
3020 || !flags.contains(crate::types::FieldAccessFlags::PRIVATE)
3021 {
3022 return false;
3023 }
3024 // cls must be a strict superclass of the owner's compile-time type.
3025 let mut cur = owner_ct;
3026 for _ in 0..64 {
3027 let Some(sup) = self.ctx.super_name(&cur) else {
3028 return false;
3029 };
3030 if sup == cls {
3031 return true;
3032 }
3033 cur = sup.into();
3034 }
3035 false
3036 }
3037
3038 fn needs_owner_cast(
3039 &self,
3040 cls: &str,
3041 name: &str,
3042 desc: &crate::types::MethodDescriptor,
3043 o: &Expr,
3044 ) -> bool {
3045 // Raw-rendered owners (qualified `HashMap.this`, substituted
3046 // capture text) carry no trustworthy static type — and casting
3047 // them to a RAW class erases the whole generic member chain
3048 // (`((HashMap) HashMap.this).<T>keysToArray(..)` made the call
3049 // raw: "Object[]无法转换为T[]").
3050 if matches!(o, Expr::Raw(_) | Expr::RawT(..) | Expr::This) {
3051 return false;
3052 }
3053 let crate::types::JavaType::Object(on) = o.type_ref().erased() else {
3054 return false;
3055 };
3056 if on.as_ref() == cls {
3057 return false;
3058 }
3059 // A receiver widened to Object (Kotlin `when` materialization
3060 // residue — every branch's value lowered into one slot) cannot
3061 // resolve ANY member: cast to the invoke's resolved class. The
3062 // bytecode guarantees the runtime type (invokevirtual dispatch
3063 // on exactly this object), so the cast is always honest.
3064 if on.as_ref() == "java/lang/Object" && cls != "java/lang/Object" {
3065 return true;
3066 }
3067 let want = format!(
3068 "({}){}",
3069 desc.args
3070 .iter()
3071 .map(|t| t.to_descriptor())
3072 .collect::<String>(),
3073 desc.ret.to_descriptor()
3074 );
3075 // The receiver's static type is a strict SUPERTYPE of the
3076 // resolved class (register reuse left the vt at the supertype):
3077 // the member lives on `cls`, and the downcast is exactly what
3078 // the bytecode's resolution performed. ONLY when the owner type
3079 // cannot resolve the member itself: an interface-typed owner
3080 // whose IMPL the dex named resolves fine through the
3081 // interface, and casting to the impl sprinkles obscured/flat
3082 // impl names into expression position (weixin +3.3k
3083 // cannot-find when this fired unguarded).
3084 if self.ctx.is_subtype_of(
3085 &crate::types::JavaType::Object(std::sync::Arc::from(cls)),
3086 on.as_ref(),
3087 ) && self.ctx.method_flags(on.as_ref(), name, &want).is_none()
3088 {
3089 return true;
3090 }
3091 let Some(acc) = self.ctx.method_flags(cls, name, &want) else {
3092 return false;
3093 };
3094 use crate::types::MethodAccessFlags as M;
3095 if acc.contains(M::PRIVATE) {
3096 return true;
3097 }
3098 if !acc.contains(M::PUBLIC) && !acc.contains(M::PROTECTED) {
3099 fn pkg(n: &str) -> &str {
3100 n.rsplit_once('/').map(|(p, _)| p).unwrap_or("")
3101 }
3102 return pkg(&on) != pkg(cls);
3103 }
3104 false
3105 }
3106
3107 fn needs_object_relay(&self, ty: &TypeRef, e: &Expr) -> bool {
3108 if matches!(e, Expr::Cast { .. } | Expr::Const(_)) {
3109 return false;
3110 }
3111 let (crate::types::JavaType::Object(from), crate::types::JavaType::Object(to)) =
3112 (e.type_ref().erased(), ty.erased())
3113 else {
3114 return false;
3115 };
3116 if from == to || from.as_ref() == "java/lang/Object" || to.as_ref() == "java/lang/Object" {
3117 return false;
3118 }
3119 // A KNOWN interface on either side keeps the direct form legal
3120 // (casts/instanceof against an interface compile regardless of
3121 // the operand's class).
3122 let known_itf = |n: &str| self.ctx.has_class(n) && self.ctx.is_interface(n);
3123 if known_itf(&from) || known_itf(&to) {
3124 if self.ctx.has_class(&from) && self.ctx.has_class(&to) {
3125 if self.ctx.is_subtype_of(&e.type_ref().erased(), &to)
3126 || self.ctx.is_subtype_of(&ty.erased(), &from)
3127 {
3128 return false;
3129 }
3130 return self.ctx.is_sealed(&from) || self.ctx.is_sealed(&to);
3131 }
3132 return false;
3133 }
3134 if self.ctx.has_class(&from) && self.ctx.has_class(&to) {
3135 if self.ctx.is_subtype_of(&e.type_ref().erased(), &to)
3136 || self.ctx.is_subtype_of(&ty.erased(), &from)
3137 {
3138 return false;
3139 }
3140 let both_classes = !self.ctx.is_interface(&from) && !self.ctx.is_interface(&to);
3141 return both_classes || self.ctx.is_sealed(&from) || self.ctx.is_sealed(&to);
3142 }
3143 // Off-pool (framework) side: the hierarchy is unknowable here.
3144 // A direct cast fails exactly when both sides are classes and
3145 // unrelated — treat unknowns as classes (java/lang/Throwable,
3146 // Error, android.media.MediaCodec$CodecException all are) and
3147 // relay through Object; the relay never changes cast semantics
3148 // (`(T) e` vs `(T)(Object) e` — same runtime check), it only
3149 // widens compile legality (weixin EncoderWriter
3150 // `(CodecException) error2` with error2: Error, ry0/d4
3151 // `(k) th3x` with th3x: Throwable — 不兼容的类型 ×250+).
3152 true
3153 }
3154
3155 pub fn shorten(&self, internal: &str) -> String {
3156 // NOTE: deliberately NOT memoized across Printers — shorten_inner
3157 // consults per-Printer state (the emitting class's package via
3158 // ctx.class_name, its fields, and this method's vt.vars for the
3159 // shadowed-simple-name check), so the result is not a pure
3160 // function of (pool, internal).
3161 // Class-file names may contain characters Java cannot parse
3162 // (R8 desugared `Collection$-EL`) — EVERY return path runs the
3163 // deterministic sanitizer (early returns bypassed it).
3164 sanitize_source_name(&self.shorten_inner(internal, true))
3165 }
3166
3167 /// Like `shorten` but WITHOUT the anonymous-class → interface/super
3168 /// fallback: used at `new <cls>` sites so a d8/R8-desugared lambda
3169 /// class (which ends in `$<digits>` like an anonymous class) prints as
3170 /// its concrete, instantiable binary name instead of its abstract SAM
3171 /// interface. Type positions keep using `shorten` (interface), so the
3172 /// declaration and the constructor disagree in the correct direction:
3173 /// `Function0 v = new Outer$..$log$1(..)`.
3174 pub fn shorten_concrete(&self, internal: &str) -> String {
3175 sanitize_source_name(&self.shorten_inner(internal, false))
3176 }
3177
3178 /// Nesting-aware display chain: a `$` boundary dots ONLY when the
3179 /// prefix has a resolvable outer (a true member); when the prefix
3180 /// is itself an emission-unit top-level (R8 deleted the outer —
3181 /// weixin matrix `JiffiesMonitorFeature` gone, `$JiffiesSnapshot`
3182 /// survives as a flat file), its `$` stays and the member tail dots
3183 /// onto it: `...JiffiesMonitorFeature$JiffiesSnapshot.ThreadJiffiesEntry`.
3184 /// Blind `$`→`.` rendered a chain through the missing type
3185 /// ("是在不可访问的类或接口中定义的").
3186 fn nested_display(&self, internal: &str) -> String {
3187 if let Some(o) = self.ctx.find_outer(internal) {
3188 // The nesting boundary must be a literal `$` — a pool prefix
3189 // followed by another char (`c$1` inside `c$1-IA`) is not an
3190 // outer of this name.
3191 if internal.len() > o.len() + 1
3192 && internal.starts_with(&o)
3193 && internal.as_bytes()[o.len()] == b'$'
3194 {
3195 let tail = &internal[o.len() + 1..];
3196 if !tail.is_empty() && !tail.starts_with('$') && !tail.contains('/') {
3197 // The tail may span several member levels
3198 // (`a17$a18`): below a RESOLVED outer they are all
3199 // inline members of the family file — dot them.
3200 return format!(
3201 "{}.{}",
3202 self.nested_display(&o),
3203 tail.replace('$', ".")
3204 );
3205 }
3206 }
3207 }
3208 // Base: a POOL class with no resolvable outer is a flat `$`-named
3209 // emission unit — keep the `$` (its file name carries it). An
3210 // off-pool name is a framework member class (android.jar's
3211 // `LinearLayout$LayoutParams`) — dot it like the old blind
3212 // replace; the jar declares it as a member.
3213 if self.ctx.has_class(internal) {
3214 internal.replace('/', ".")
3215 } else {
3216 internal.replace(['/', '$'], ".")
3217 }
3218 }
3219
3220 /// Walk the MEMBER-TYPE scope of the emitting class: every lexical
3221 /// `$`-outer level, and at each level its superclass chain and direct
3222 /// interfaces — JLS 8.1.6: member types are INHERITED into scope, so
3223 /// a superclass's nested `a` captures the bare simple name `a` exactly
3224 /// like an own nestee (weixin pk4.d extends k0: same-package class ref
3225 /// `a.d` bound to inherited k0$a — "找不到符号 变量 d, 位置: 类 a").
3226 /// `f` is called with each in-scope class's internal name; the walk
3227 /// stops early when `f` returns true.
3228 fn scope_member_walk<F: FnMut(&str) -> bool>(&self, f: &mut F) -> bool {
3229 let mut cur: &str = self.ctx.class_name();
3230 loop {
3231 let mut stack: Vec<String> = vec![cur.to_string()];
3232 let mut seen: crate::FxHashSet<String> = crate::FxHashSet::default();
3233 while let Some(c) = stack.pop() {
3234 if !seen.insert(c.clone()) {
3235 continue;
3236 }
3237 if f(&c) {
3238 return true;
3239 }
3240 if let Some((ifaces, sup)) = self.ctx.class_bases(&c) {
3241 for i in ifaces {
3242 stack.push(i);
3243 }
3244 if let Some(s) = sup {
3245 if s != "java/lang/Object" {
3246 stack.push(s);
3247 }
3248 }
3249 }
3250 }
3251 match cur.rfind('$') {
3252 Some(i) => cur = &cur[..i],
3253 None => break,
3254 }
3255 }
3256 false
3257 }
3258
3259 fn shorten_inner(&self, internal: &str, anon_fallback: bool) -> String {
3260 if internal.is_empty() {
3261 return String::new();
3262 }
3263 // An import-resolved obscured reference renders its simple name
3264 // (the qualified form binds to an in-scope class — JLS 6.4.2).
3265 if let Some(simple) = self.ctx.obscured_simple(internal) {
3266 return simple;
3267 }
3268 // Case-collision renames (`X/Cua` → `X/Cua_2`): the registry is
3269 // empty for ordinary corpora — one relaxed atomic load.
3270 let cow = crate::rename::apply_class_rename(internal);
3271 let internal: &str = &cow;
3272 // Literal-$ top-level class (in pool, no InnerClasses nesting
3273 // evidence): the $ is part of the SOURCE name (jextract-generated
3274 // errno_h$shared) — never dot it into a nested qualifier. Same rule
3275 // whenever dotting could not parse: `DolTest2$$dollah$$` has empty
3276 // segments, and `$` is a legal identifier character while `A..b` is
3277 // not.
3278 let dot_safe = |simple: &str| -> bool {
3279 // A LEADING `$` (`$Gson$Types`) is part of the source name —
3280 // dotting it yields `.Gson.Types` with a leading dot.
3281 simple.split('$').all(|seg| {
3282 !seg.is_empty()
3283 && seg
3284 .chars()
3285 .next()
3286 .map(|c| c.is_ascii_alphabetic() || c == '_')
3287 .unwrap_or(false)
3288 })
3289 };
3290 let simple_here = internal.rsplit('/').next().unwrap_or(internal).to_string();
3291 // Identifier-unsafe characters ANYWHERE in the name (Kotlin's
3292 // `-IA`/`-EL` hyphen markers: `org/a/c/c$1-IA`; R8 unicode
3293 // obfuscation: the Thai/Yi/Syriac classes of bin.mt.plus,
3294 // ejfkdev/ddc#4) are not source identifiers and can never be
3295 // nested members or local classes — they emit as FLAT sanitized
3296 // files, so references must render the same sanitized full name
3297 // (`_u<hex>` escapes on BOTH sides). The local-class digit-strip
3298 // path mangled them (`1-IA` → `-IA` → `_IA`, weibo ×157), and a
3299 // raw-unicode ref never resolves against the escaped decl.
3300 if !internal
3301 .chars()
3302 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$' || c == '/')
3303 {
3304 return sanitize_source_name(&internal.replace('/', "."));
3305 }
3306 // d8's synthetic outline/lambda/backport classes
3307 // (`X$$ExternalSyntheticLambda0`, `…ApiModelOutline0`,
3308 // `…BackportWithForwarding0`) are TOP-LEVEL synthetics emitted as
3309 // flat files with their full `$` name. The local-class digit-strip
3310 // path below mangles them to the bare innermost segment
3311 // (`ExternalSyntheticBackportWithForwarding0`) when the outer chain
3312 // has a digit segment (`PreviewView$1$$…`), which resolves to
3313 // nothing cross-package ("找不到符号 变量 ExternalSynthetic…", weibo
3314 // ×467). Render the full dotted name, like the hyphen case.
3315 if simple_here.contains("$$ExternalSynthetic") {
3316 return sanitize_source_name(&internal.replace('/', "."));
3317 }
3318 let keep_dollar_pool = internal.contains('$')
3319 && self.ctx.has_class(internal)
3320 && self.ctx.find_outer(internal).is_none();
3321 // R8 desugared-library names carry `$` inside the PACKAGE path
3322 // (`j$/util/Collection$-EL`): a `$` followed by `/` is never a
3323 // nesting boundary — dotting it produced `j..util`.
3324 let dollar_in_pkg = internal.contains("$/");
3325 let keep_dollar = keep_dollar_pool
3326 || dollar_in_pkg
3327 || (internal.contains('$') && !dot_safe(&simple_here));
3328 // Anonymous class types (all-digit last segment) have no source
3329 // name: print the base interface/superclass instead. Skipped for
3330 // `new <cls>` sites (anon_fallback=false): a d8/R8-desugared
3331 // LAMBDA class also ends in `$<digits>` (`...$lambda$N$$inlined
3332 // $log$1`, `Outer$$ExternalSyntheticLambda0`) but IS a concrete,
3333 // pool-rendered class — printing its SAM interface there yields an
3334 // invalid `new Iface(..)` ("a是抽象的; 无法实例化", the biggest
3335 // abstract-instantiation family on Kotlin corpora: v6.a/l/p =
3336 // Function0/1/2). The var/phi TYPE positions keep the interface
3337 // (shorten with fallback), so `Iface v = new ConcreteLambda(..)`
3338 // stays phi-compatible across branches that mint different lambdas.
3339 if anon_fallback {
3340 if let Some(last) = internal.rsplit('$').next() {
3341 if !last.is_empty() && last.chars().all(|c| c.is_ascii_digit()) {
3342 if let Some((ifaces, sup)) = self.ctx.class_bases(internal) {
3343 if let Some(n) = ifaces.first() {
3344 return self.shorten(n);
3345 }
3346 if let Some(sup) = sup {
3347 if sup != "java/lang/Object" {
3348 return self.shorten(&sup);
3349 }
3350 }
3351 return "Object".to_string();
3352 }
3353 }
3354 }
3355 }
3356 // Local classes are emitted with their simple source name.
3357 if let Some(last) = internal.rsplit('$').next() {
3358 if !keep_dollar_pool
3359 && !last.is_empty()
3360 && !last.chars().all(|c| c.is_ascii_digit())
3361 && internal.contains('$')
3362 {
3363 // Nested-class names print as Outer.Inner, except local
3364 // classes whose outer chain includes digits (e.g. Foo$1Bar).
3365 let mut segs = internal.split('$');
3366 if let Some(first) = segs.next() {
3367 let rest: Vec<&str> = segs.collect();
3368 if rest
3369 .iter()
3370 .any(|r| r.starts_with(|c: char| c.is_ascii_digit()))
3371 {
3372 // Local/synthetic class (digit-led segment): javac
3373 // encodes a method-local class as `Outer$1Name`; its
3374 // source name is the digit prefix stripped, declared
3375 // `class Name` at its use site and referenced only
3376 // within that scope. Printing the binary name leaves
3377 // an unresolvable symbol (ClassSpecializer$Factory$1Var).
3378 if let Some(last) = internal.rsplit('$').next() {
3379 let stripped = last.trim_start_matches(|c: char| c.is_ascii_digit());
3380 if !stripped.is_empty()
3381 && !stripped.chars().next().unwrap().is_ascii_digit()
3382 {
3383 return stripped.to_string();
3384 }
3385 }
3386 return internal.replace('/', ".");
3387 }
3388 let _ = first;
3389 let _ = last;
3390 }
3391 }
3392 }
3393 let dotted = internal.replace('/', ".");
3394 // A simple type name shadowed by an in-scope VARIABLE (a field of
3395 // this class or a method local) cannot qualify a static access:
3396 // javac resolves the leading name as the variable first
3397 // (无法取消引用int — jdk26 VerificationType declares
3398 // `private static final int Integer` and the source spells
3399 // java.lang.Integer.toHexString in full). Keep the fully-qualified
3400 // form whenever the leading segment collides.
3401 let shadowed = |first: &str| {
3402 self.ctx.declares_field(self.ctx.class_name(), first)
3403 || self.vt.vars.iter().any(|v| v.name == first)
3404 };
3405 if internal.starts_with("java/lang/") && !internal[10..].contains('/') {
3406 let simple = if keep_dollar {
3407 internal[10..].to_string()
3408 } else {
3409 internal[10..].replace('$', ".")
3410 };
3411 let first = simple.split('.').next().unwrap_or(simple.as_str());
3412 if !shadowed(first) {
3413 return simple;
3414 }
3415 return dotted.replace('$', ".");
3416 }
3417 if pkg_of(internal) == pkg_of(self.ctx.class_name()) {
3418 let simple = if keep_dollar {
3419 internal.rsplit('/').next().unwrap_or(internal).to_string()
3420 } else {
3421 let d = self.nested_display(internal);
3422 let pkg_dotted = pkg_of(internal).replace('/', ".");
3423 d.strip_prefix(&pkg_dotted)
3424 .and_then(|r| r.strip_prefix('.'))
3425 .map(str::to_string)
3426 .unwrap_or(d)
3427 };
3428 let first = simple.split('.').next().unwrap_or(simple.as_str());
3429 // Member-type shadow: the emitting class's OWN nested type
3430 // with the same simple name captures the bare render
3431 // (member types outrank same-package types in class scope) —
3432 // weibo PhoneInfoUtils: `b2.b(ctx,..)` for sibling class
3433 // com/weibo/ssosdk/b2 bound to nested PhoneInfoUtils$b2
3434 // (找不到符号 方法 b). The reference to the twin itself (or
3435 // its own nestees) keeps the simple form. FQN fallback is
3436 // unambiguous — no field/variable can shadow a dotted
3437 // package chain past its first segment.
3438 // Member-type twin shadow: a nested type of ANY enclosing
3439 // level whose display simple name equals `first` captures
3440 // the bare render (member types outrank same-package types
3441 // in class scope — weixin d2's `((w1) h0)` bound to nested
3442 // d2$$w1, not sibling viewitems/w1: 1,045 h0→w1 lines).
3443 // Walk the `$`-chain of the emitting class (the ctx may be a
3444 // nested `d2$$c`, whose lexical scope still sees d2's
3445 // members); R8 orphans use `$$`, normalization displays use
3446 // `$`, and rename displays live only in the registry's
3447 // reverse index — check all four shapes per level.
3448 let twin_exists = {
3449 // The borrow temp must die before the else arm's
3450 // borrow_mut (if-let scrutinee temps live across the
3451 // whole statement — RefCell double-borrow panic).
3452 let cached = self.twin_cache.borrow().get(first).copied();
3453 if let Some(v) = cached {
3454 v
3455 } else {
3456 // Own nestees AND inherited member types (the scope
3457 // walk) capture the bare simple name alike.
3458 let v = self.scope_member_walk(&mut |c| {
3459 let t1 = format!("{c}${first}");
3460 let t2 = format!("{c}$${first}");
3461 self.ctx.has_class(&t1)
3462 || self.ctx.has_class(&t2)
3463 || crate::rename::is_renamed_display(&t1)
3464 || crate::rename::is_renamed_display(&t2)
3465 });
3466 self.twin_cache
3467 .borrow_mut()
3468 .insert(first.to_string(), v);
3469 v
3470 }
3471 };
3472 // is_twin_ref only matters when a twin exists (otherwise
3473 // `!twin_exists` already grants the simple form) — keep it
3474 // off the hot path.
3475 let is_twin_ref = twin_exists
3476 && self.scope_member_walk(&mut |c| {
3477 let t1 = format!("{c}${first}");
3478 let t2 = format!("{c}$${first}");
3479 internal == t1
3480 || internal == t2
3481 || internal.starts_with(&format!("{t1}$"))
3482 || internal.starts_with(&format!("{t2}$"))
3483 });
3484 if !shadowed(first) && (is_twin_ref || !twin_exists) {
3485 return simple;
3486 }
3487 }
3488 if keep_dollar {
3489 dotted
3490 } else {
3491 self.nested_display(internal)
3492 }
3493 }
3494
3495 pub fn type_name(&self, ty: &TypeRef) -> String {
3496 match ty {
3497 TypeRef::J(t) => self.java_type_name(t),
3498 TypeRef::G(g) => {
3499 // Render generic signature with shortened class names.
3500 self.generic_name(g)
3501 }
3502 }
3503 }
3504
3505 /// Declared-type name for a local: normally `type_name` (which lets a
3506 /// `$<digits>` class fall back to its SAM interface for phi-friendly
3507 /// readability), but a var in `force_concrete_vars` keeps its concrete
3508 /// binary name so concrete-member accesses (`v.L$0`, the Kotlin
3509 /// coroutine capture fields) resolve — interfaces have no instance
3510 /// fields.
3511 fn local_decl_ty(&self, var: u32, ty: &TypeRef) -> String {
3512 if self.vt.force_concrete_vars.contains(&var) {
3513 if let TypeRef::J(JavaType::Object(cls)) = ty {
3514 return sanitize_source_name(&self.shorten_concrete(cls));
3515 }
3516 }
3517 self.type_name(ty)
3518 }
3519
3520 fn java_type_name(&self, t: &JavaType) -> String {
3521 // An import-resolved obscured class renders its simple name in
3522 // every type position (signatures, casts, type refs).
3523 if let JavaType::Object(c) = t {
3524 if let Some(simple) = self.ctx.obscured_simple(c) {
3525 return simple;
3526 }
3527 }
3528 match t {
3529 JavaType::Object(n) => self.shorten(n),
3530 JavaType::Array(inner) => format!("{}[]", self.java_type_name(inner)),
3531 other => other.to_java(false),
3532 }
3533 }
3534
3535 fn generic_name(&self, g: &crate::types::GenericType) -> String {
3536 use crate::types::{GenericType, WildcardBound};
3537 match g {
3538 GenericType::Primitive(c) => prim_name(*c).to_string(),
3539 GenericType::Class(cs) => {
3540 // The signature parser splits a literal-$ top-level name
3541 // (jextract-generated errno_h$shared) into nested-looking
3542 // parts [errno_h, shared]; rejoin and, when the pool
3543 // proves the class is NOT nested, render the binary name
3544 // through shorten (same-package simple form keeps the $).
3545 if cs.parts.len() > 1 && cs.parts.iter().skip(1).all(|p| p.args.is_empty()) {
3546 let joined = cs
3547 .parts
3548 .iter()
3549 .map(|p| p.name.as_str())
3550 .collect::<Vec<_>>()
3551 .join("$");
3552 let full = if cs.package.is_empty() {
3553 joined
3554 } else {
3555 format!("{}/{}", cs.package, joined)
3556 };
3557 let literal = self.ctx.has_class(&full) && self.ctx.find_outer(&full).is_none();
3558 if literal {
3559 return self.shorten(&full);
3560 }
3561 }
3562 let mut s = String::new();
3563 if !cs.package.is_empty() {
3564 let full = format!(
3565 "{}/{}",
3566 cs.package,
3567 cs.parts.first().map(|p| p.name.as_str()).unwrap_or("")
3568 );
3569 s.push_str(&self.shorten(&full));
3570 } else {
3571 s.push_str(&cs.parts.first().map(|p| p.name.clone()).unwrap_or_default());
3572 }
3573 if let Some(first) = cs.parts.first() {
3574 if !first.args.is_empty() {
3575 s.push('<');
3576 for (i, a) in first.args.iter().enumerate() {
3577 if i > 0 {
3578 s.push_str(", ");
3579 }
3580 s.push_str(&self.generic_name(a));
3581 }
3582 s.push('>');
3583 }
3584 }
3585 for p in cs.parts.iter().skip(1) {
3586 let digit_led = p
3587 .name
3588 .chars()
3589 .next()
3590 .map(|c| c.is_ascii_digit())
3591 .unwrap_or(false);
3592 let stripped = p.name.trim_start_matches(|c: char| c.is_ascii_digit());
3593 if digit_led && !stripped.is_empty() && p.args.is_empty() {
3594 // javac's local-class encoding `Outer$1Name`: the
3595 // source name is the prefix-stripped simple name,
3596 // referenced WITHOUT qualification (there is no
3597 // legal `DocLint.1Pair` — `> or ',' expected`).
3598 s = stripped.to_string();
3599 continue;
3600 }
3601 s.push('.');
3602 s.push_str(&p.name);
3603 if !p.args.is_empty() {
3604 s.push('<');
3605 for (i, a) in p.args.iter().enumerate() {
3606 if i > 0 {
3607 s.push_str(", ");
3608 }
3609 s.push_str(&self.generic_name(a));
3610 }
3611 s.push('>');
3612 }
3613 }
3614 s
3615 }
3616 GenericType::Array(inner) => format!("{}[]", self.generic_name(inner)),
3617 GenericType::TypeVar(n) => n.clone(),
3618 GenericType::Wildcard(w) => match w {
3619 WildcardBound::Any => "?".to_string(),
3620 WildcardBound::Extends(t) => format!("? extends {}", self.generic_name(t)),
3621 WildcardBound::Super(t) => format!("? super {}", self.generic_name(t)),
3622 },
3623 }
3624 }
3625}
3626
3627fn inner_simple(cls: &str) -> String {
3628 // Apply the class-rename registry FIRST: a renamed nested class must
3629 // print its display tail at `outer.new Inner(..)` sites too — this
3630 // free function was the one emit-side path bypassing the registry
3631 // (round-55: declarations carried the rename while `this.new b()`
3632 // printed the raw tail → cannot-find).
3633 let cow = crate::rename::apply_class_rename(cls);
3634 let cls: &str = &cow;
3635 let last = cls.rsplit('/').next().unwrap_or(cls);
3636 // R8 leaves class names ending in `$` (rimet's `ThreadMsg$$$`):
3637 // the last `$`-segment is EMPTY — fall back to the whole simple
3638 // name instead of printing `receiver.new (args)`.
3639 let seg = last.rsplit('$').next().unwrap_or(last);
3640 let last = if seg.is_empty() { last } else { seg };
3641 // Obfuscators name classes after keywords (`v10.new do("")`): the
3642 // qualified-new form prints this simple name raw.
3643 let name = last.to_string();
3644 if is_java_keyword(name.as_str())
3645 || is_restricted_type_name(name.as_str())
3646 || name.chars().next().is_some_and(|c| c.is_ascii_digit())
3647 {
3648 format!("_{name}")
3649 } else if name
3650 .chars()
3651 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
3652 {
3653 name
3654 } else {
3655 // Non-ASCII single chars (Alipay names a field `支`) map to a
3656 // lone `_` — itself reserved since Java 9. Escape it.
3657 let mapped: String = name
3658 .chars()
3659 .map(|c| {
3660 if c.is_ascii_alphanumeric() || c == '_' || c == '$' {
3661 c
3662 } else {
3663 '_'
3664 }
3665 })
3666 .collect();
3667 if mapped == "_" {
3668 "__".to_string()
3669 } else {
3670 mapped
3671 }
3672 }
3673}
3674
3675fn push_char_lit(out: &mut String, n: i32) {
3676 let c = (n as u16) as u32;
3677 match char::from_u32(c) {
3678 Some('\'') => out.push_str("'\\''"),
3679 Some('\\') => out.push_str("'\\\\'"),
3680 Some('\n') => out.push_str("'\\n'"),
3681 Some('\r') => out.push_str("'\\r'"),
3682 Some('\t') => out.push_str("'\\t'"),
3683 Some(ch) if ch.is_control() => out.push_str(&format!("'\\u{:04x}'", c)),
3684 Some(ch) => {
3685 out.push('\'');
3686 out.push(ch);
3687 out.push('\'');
3688 }
3689 None => out.push_str(&format!("'\\u{:04x}'", c)),
3690 }
3691}
3692
3693fn const_bool(e: &Expr) -> Option<bool> {
3694 match e {
3695 Expr::Const(ConstVal::Int(n)) => Some(*n != 0),
3696 _ => None,
3697 }
3698}
3699
3700fn pkg_of(n: &str) -> &str {
3701 n.rfind('/').map(|i| &n[..i]).unwrap_or("")
3702}
3703
3704fn prim_name(c: char) -> &'static str {
3705 match c {
3706 'V' => "void",
3707 'Z' => "boolean",
3708 'B' => "byte",
3709 'C' => "char",
3710 'S' => "short",
3711 'I' => "int",
3712 'F' => "float",
3713 'J' => "long",
3714 'D' => "double",
3715 _ => "?",
3716 }
3717}
3718
3719/// Kotlin emits method names like `invokeSuspend$lambda-0` — `-` and any
3720/// other non-identifier character is not legal Java. Deterministic
3721/// mapping; ddc's classdec applies the identical rule at declarations.
3722pub fn java_ident(name: &str) -> std::borrow::Cow<'_, str> {
3723 let clean = name
3724 .chars()
3725 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
3726 let keyword = is_java_keyword(name);
3727 // A simple name may not START with a digit either (nova names fields
3728 // `1x`/`2x`/`3x`): ddc's declaration side has the same branch.
3729 let digit_start = name.chars().next().is_some_and(|c| c.is_ascii_digit());
3730 if clean && !keyword && !digit_start {
3731 // The overwhelmingly common case: borrow, zero allocation (this
3732 // runs per rendered IDENTIFIER).
3733 std::borrow::Cow::Borrowed(name)
3734 } else if keyword || digit_start {
3735 std::borrow::Cow::Owned(format!("_{name}"))
3736 } else {
3737 // Non-ASCII single chars (Alipay names a field `支`) map to a
3738 // lone `_` — itself reserved since Java 9. Escape it.
3739 let mapped: String = name
3740 .chars()
3741 .map(|c| {
3742 if c.is_ascii_alphanumeric() || c == '_' || c == '$' {
3743 c
3744 } else {
3745 '_'
3746 }
3747 })
3748 .collect();
3749 if mapped == "_" {
3750 std::borrow::Cow::Owned("__".to_string())
3751 } else {
3752 std::borrow::Cow::Owned(mapped)
3753 }
3754 }
3755}
3756
3757/// Java reserved words (plus the null/true/false literals, and `_` — a
3758/// reserved IDENTIFIER since Java 9: Alipay's instant-run patch system
3759/// names fields `_`, and `javac` rejects it with "underscores are not
3760/// allowed here"): Kotlin emits methods and fields named `default`
3761/// (Companion.default()) — no Java program can name them, so both ddc's
3762/// declarations and these call sites map them to `_<name>` identically
3763/// (which turns `_` into `__`). NOTE: these are MEMBER-level escapes —
3764/// locals/fields/params MAY legally carry the restricted contextual
3765/// type names below (rt.jar has `var` locals), so those live in their
3766/// own predicate.
3767pub fn is_java_keyword(name: &str) -> bool {
3768 matches!(
3769 name,
3770 "abstract" | "assert" | "boolean" | "break" | "byte" | "case" | "catch" | "char"
3771 | "class" | "const" | "continue" | "default" | "do" | "double" | "else" | "enum"
3772 | "extends" | "final" | "finally" | "float" | "for" | "goto" | "if" | "implements"
3773 | "import" | "instanceof" | "int" | "interface" | "long" | "native" | "new"
3774 | "package" | "private" | "protected" | "public" | "return" | "short" | "static"
3775 | "strictfp" | "super" | "switch" | "synchronized" | "this" | "throw" | "throws"
3776 | "transient" | "try" | "void" | "volatile" | "while" | "true" | "false" | "null"
3777 | "_"
3778 )
3779}
3780
3781/// Restricted CONTEXTUAL type names — javac rejects them in TYPE
3782/// declarations and type references (`'var' 是受限类型名称`), but they
3783/// stay legal as member/local names (rt.jar compiles `var` locals).
3784/// Consulted ONLY where a CLASS name renders: type declarations,
3785/// segment sanitizers, the qualified-new simple name.
3786pub fn is_restricted_type_name(name: &str) -> bool {
3787 matches!(
3788 name,
3789 "var" | "yield" | "record" | "sealed" | "permits"
3790 )
3791}
3792
3793/// `this` in its Raw encoding (prints as `this`; see the Raw arm).
3794fn is_this_expr(e: &Expr) -> bool {
3795 matches!(e, Expr::This) || matches!(e, Expr::Raw(t) if t == "\u{3}" || t == "this")
3796}
3797
3798/// Class-file names may contain characters Java source identifiers
3799/// cannot (R8 desugared `Collection$-EL`); deterministic -→_ mapping,
3800/// matching ddc's declaration-site java_ident.
3801/// Legal Java expression-statement forms (JLS 14.8): assignment, method
3802/// invocation, inc/dec, class instance creation.
3803fn is_statement_expr(e: &Expr) -> bool {
3804 matches!(
3805 e,
3806 Expr::Assign { .. }
3807 | Expr::Method { .. }
3808 | Expr::New { .. }
3809 | Expr::PreIncDec { .. }
3810 | Expr::PostIncDec { .. }
3811 )
3812}
3813
3814pub fn sanitize_source_name(name: &str) -> String {
3815 // Obfuscators emit classes named `if`/`do`, PACKAGES named `do`
3816 // (weixin `package do;`) and `..badge.new..` paths (qq), WhatsApp
3817 // nests digit-start simple names (`X/0Xx`), Kotlin mints hyphenated
3818 // synthetic markers (`c$1-IA`, `Collection$-EL`) and R8 hardening
3819 // even names classes in Thai/Yi/Syriac code points (bin.mt.plus —
3820 // ejfkdev/ddc#4). EVERY identifier-unsafe character escapes to
3821 // `_u<hex>` per code point, then identifier-position repairs apply.
3822 // Byte-for-byte the mapping the DECLARATION side uses (ddc
3823 // `classdec::sanitize_fq_seg`): declaration, file name and every
3824 // reference must agree, and the escape must be INJECTIVE — the old
3825 // fold-everything-to-`_` mapping collapsed 22,636 distinct classes
3826 // onto 3 file names.
3827 let segs: Vec<&str> = name.split('.').collect();
3828 let clean = name
3829 .chars()
3830 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$' || c == '.')
3831 && segs.iter().all(|seg| {
3832 let first = seg.chars().next().unwrap_or('a');
3833 !is_java_keyword(seg)
3834 && !is_restricted_type_name(seg)
3835 && !first.is_ascii_digit()
3836 && *seg != "_"
3837 });
3838 if clean {
3839 return name.to_string();
3840 }
3841 segs.iter()
3842 .copied()
3843 .map(sanitize_ident_seg)
3844 .collect::<Vec<_>>()
3845 .join(".")
3846}
3847
3848/// One identifier segment: escape every ident-unsafe character as
3849/// `_u<hex>`, then repair identifier positions (keyword / restricted
3850/// type name / digit start gain a leading `_`; the lone `_` reserved
3851/// since Java 9 becomes `__`). Mirrors ddc `sanitize_fq_seg` exactly.
3852fn sanitize_ident_seg(seg: &str) -> String {
3853 let plain = seg
3854 .chars()
3855 .all(|c| c.is_ascii() && (c.is_ascii_alphanumeric() || c == '_' || c == '$'));
3856 let mut out = if plain {
3857 seg.to_string()
3858 } else {
3859 use std::fmt::Write as _;
3860 let mut s = String::with_capacity(seg.len() + 8);
3861 for c in seg.chars() {
3862 if c.is_ascii() && (c.is_ascii_alphanumeric() || c == '_' || c == '$') {
3863 s.push(c);
3864 } else {
3865 s.push_str("_u");
3866 let _ = write!(s, "{:x}", c as u32);
3867 }
3868 }
3869 s
3870 };
3871 if is_java_keyword(&out)
3872 || is_restricted_type_name(&out)
3873 || out.chars().next().is_some_and(|c| c.is_ascii_digit())
3874 {
3875 out.insert(0, '_');
3876 }
3877 if out == "_" {
3878 out = "__".to_string();
3879 }
3880 out
3881}
3882
3883pub fn escape_string(s: &str) -> String {
3884 let mut out = String::with_capacity(s.len());
3885 for c in s.chars() {
3886 match c {
3887 '"' => out.push_str("\\\""),
3888 '\\' => out.push_str("\\\\"),
3889 '\n' => out.push_str("\\n"),
3890 '\r' => out.push_str("\\r"),
3891 '\t' => out.push_str("\\t"),
3892 '\u{0}' => out.push_str("\\0"),
3893 '\u{8}' => out.push_str("\\b"),
3894 '\u{C}' => out.push_str("\\f"),
3895 c if (c as u32) < 0x20 || (c as u32) == 0x7F => {
3896 out.push_str(&format!("\\u{:04x}", c as u32));
3897 }
3898 c => out.push(c),
3899 }
3900 }
3901 out
3902}
3903
3904pub fn escape_char(c: char) -> String {
3905 match c {
3906 '\'' => "\\'".to_string(),
3907 '\\' => "\\\\".to_string(),
3908 '\n' => "\\n".to_string(),
3909 '\r' => "\\r".to_string(),
3910 '\t' => "\\t".to_string(),
3911 '\0' => "\\0".to_string(),
3912 c if (c as u32) < 0x20 || (c as u32) == 0x7F => format!("\\u{:04x}", c as u32),
3913 c => c.to_string(),
3914 }
3915}
3916
3917pub fn format_float(v: f64, is_float: bool) -> String {
3918 let suffix = if is_float { "f" } else { "" };
3919 // Arithmetic literals, not `Double.NaN`/`POSITIVE_INFINITY` field refs:
3920 // inside java.lang.Double/Float themselves a field reference would be
3921 // a self-reference initializing the very field being printed.
3922 if v.is_nan() {
3923 return if is_float {
3924 "(0.0f / 0.0f)".into()
3925 } else {
3926 "(0.0 / 0.0)".into()
3927 };
3928 }
3929 if v.is_infinite() {
3930 let one = if is_float { "1.0f" } else { "1.0" };
3931 let zero = if is_float { "0.0f" } else { "0.0" };
3932 return if v < 0.0 {
3933 format!("(-{} / {})", one, zero)
3934 } else {
3935 format!("({} / {})", one, zero)
3936 };
3937 }
3938 let mut s = format!("{}", v);
3939 if !s.contains('.') && !s.contains('e') && !s.contains('E') {
3940 s.push_str(".0");
3941 }
3942 // Java doesn't accept exponent forms like "1e-7"? It does: 1e-7 is a valid
3943 // double literal. But "inf"/"nan" handled above.
3944 format!("{}{}", s, suffix)
3945}
3946
3947// ---------------------------------------------------------------------------
3948// Unreachable-code truncation (final statement tree)
3949// ---------------------------------------------------------------------------
3950
3951/// Drop statements that follow a `while (true)` which cannot complete
3952/// normally (no `break` in its body binds to it): javac rejects them as
3953/// 无法访问的语句, and the structurers only emitted them as shared-tail
3954/// copies whose real arrivals all render INSIDE the loop arms (jdk17/26
3955/// Pattern.clazz's for(;;){switch}: case-93's `return prev/negate` tail
3956/// landed after the never-completing loop). Runs on the FINAL tree (after
3957/// switch restoration and goto resolution) so the break inventory is
3958/// exactly what gets emitted; every unknown shape stays conservative
3959/// (assumes the loop can complete).
3960fn tree_has_dead_end(s: &Stmt) -> bool {
3961 match s {
3962 Stmt::Block(v) => {
3963 for (i, x) in v.iter().enumerate() {
3964 if i > 0 && dead_end_infinite_while(&v[i - 1]) {
3965 return true;
3966 }
3967 if tree_has_dead_end(x) {
3968 return true;
3969 }
3970 }
3971 false
3972 }
3973 Stmt::If {
3974 then_stmt,
3975 else_stmt,
3976 ..
3977 } => tree_has_dead_end(then_stmt) || else_stmt.as_deref().is_some_and(tree_has_dead_end),
3978 Stmt::While { body, .. } | Stmt::DoWhile { body, .. } => tree_has_dead_end(body),
3979 Stmt::For { init, body, .. } => {
3980 init.iter().any(tree_has_dead_end) || tree_has_dead_end(body)
3981 }
3982 Stmt::ForEach { body, .. } => tree_has_dead_end(body),
3983 Stmt::Switch { cases, default, .. } => {
3984 cases.iter().any(|c| c.body.iter().any(tree_has_dead_end))
3985 || default.as_deref().is_some_and(tree_has_dead_end)
3986 }
3987 Stmt::Try {
3988 body,
3989 catches,
3990 finally,
3991 } => {
3992 tree_has_dead_end(body)
3993 || catches.iter().any(|c| tree_has_dead_end(&c.body))
3994 || finally.as_deref().is_some_and(tree_has_dead_end)
3995 }
3996 Stmt::TryWithResources {
3997 resources,
3998 body,
3999 catches,
4000 finally,
4001 ..
4002 } => {
4003 resources.iter().any(tree_has_dead_end)
4004 || tree_has_dead_end(body)
4005 || catches.iter().any(|c| tree_has_dead_end(&c.body))
4006 || finally.as_deref().is_some_and(tree_has_dead_end)
4007 }
4008 Stmt::Synchronized { body, .. } | Stmt::Labeled { body, .. } => tree_has_dead_end(body),
4009 _ => false,
4010 }
4011}
4012
4013fn truncate_dead_ends(s: &Stmt) -> Stmt {
4014 match s {
4015 Stmt::Block(v) => {
4016 let mut out: Vec<Stmt> = Vec::with_capacity(v.len());
4017 for x in v {
4018 if !out.is_empty() && dead_end_infinite_while(out.last().unwrap()) {
4019 if crate::dbg_flag!("JCDC_DBG_GOTO") {
4020 eprintln!(
4021 "DEADEND truncate {} unreachable stmt(s)",
4022 v.len() - out.len()
4023 );
4024 }
4025 break;
4026 }
4027 out.push(truncate_dead_ends(x));
4028 }
4029 Stmt::Block(out)
4030 }
4031 Stmt::If {
4032 cond,
4033 then_stmt,
4034 else_stmt,
4035 } => Stmt::If {
4036 cond: cond.clone(),
4037 then_stmt: Box::new(truncate_dead_ends(then_stmt)),
4038 else_stmt: else_stmt.as_deref().map(truncate_dead_ends).map(Box::new),
4039 },
4040 Stmt::While { cond, body } => Stmt::While {
4041 cond: cond.clone(),
4042 body: Box::new(truncate_dead_ends(body)),
4043 },
4044 Stmt::DoWhile { body, cond } => Stmt::DoWhile {
4045 body: Box::new(truncate_dead_ends(body)),
4046 cond: cond.clone(),
4047 },
4048 Stmt::For {
4049 init,
4050 cond,
4051 update,
4052 body,
4053 } => Stmt::For {
4054 init: init.iter().map(truncate_dead_ends).collect(),
4055 cond: cond.clone(),
4056 update: update.clone(),
4057 body: Box::new(truncate_dead_ends(body)),
4058 },
4059 Stmt::ForEach {
4060 var,
4061 iterable,
4062 is_array,
4063 body,
4064 } => Stmt::ForEach {
4065 var: *var,
4066 iterable: iterable.clone(),
4067 is_array: *is_array,
4068 body: Box::new(truncate_dead_ends(body)),
4069 },
4070 Stmt::Switch {
4071 selector,
4072 cases,
4073 default,
4074 on_string,
4075 } => Stmt::Switch {
4076 selector: selector.clone(),
4077 cases: cases
4078 .iter()
4079 .map(|c| CaseGroup {
4080 labels: c.labels.clone(),
4081 string_labels: c.string_labels.clone(),
4082 enum_labels: c.enum_labels.clone(),
4083 raw_labels: c.raw_labels.clone(),
4084 guard: c.guard.clone(),
4085 body: c.body.iter().map(truncate_dead_ends).collect(),
4086 })
4087 .collect(),
4088 default: default.as_deref().map(truncate_dead_ends).map(Box::new),
4089 on_string: *on_string,
4090 },
4091 Stmt::Try {
4092 body,
4093 catches,
4094 finally,
4095 } => Stmt::Try {
4096 body: Box::new(truncate_dead_ends(body)),
4097 catches: catches
4098 .iter()
4099 .map(|c| Catch {
4100 exc: c.exc.clone(),
4101 var: c.var,
4102 var_name: c.var_name.clone(),
4103 body: Box::new(truncate_dead_ends(&c.body)),
4104 })
4105 .collect(),
4106 finally: finally.as_deref().map(truncate_dead_ends).map(Box::new),
4107 },
4108 Stmt::TryWithResources {
4109 resources,
4110 body,
4111 catches,
4112 finally,
4113 } => Stmt::TryWithResources {
4114 resources: resources.iter().map(truncate_dead_ends).collect(),
4115 body: Box::new(truncate_dead_ends(body)),
4116 catches: catches
4117 .iter()
4118 .map(|c| Catch {
4119 exc: c.exc.clone(),
4120 var: c.var,
4121 var_name: c.var_name.clone(),
4122 body: Box::new(truncate_dead_ends(&c.body)),
4123 })
4124 .collect(),
4125 finally: finally.as_deref().map(truncate_dead_ends).map(Box::new),
4126 },
4127 Stmt::Synchronized { lock, body } => Stmt::Synchronized {
4128 lock: lock.clone(),
4129 body: Box::new(truncate_dead_ends(body)),
4130 },
4131 Stmt::Labeled { label, body } => Stmt::Labeled {
4132 label: label.clone(),
4133 body: Box::new(truncate_dead_ends(body)),
4134 },
4135 other => other.clone(),
4136 }
4137}
4138
4139/// True when `s` is a `while (true)` (labeled or not) whose body holds
4140/// no `break` binding to it — it can never complete normally.
4141pub(crate) fn dead_end_infinite_while(s: &Stmt) -> bool {
4142 let (label, body, cond) = match s {
4143 Stmt::While { cond, body } => (None, body.as_ref(), cond),
4144 Stmt::Labeled { label, body } => match &**body {
4145 Stmt::While { cond, body } => (Some(label.as_str()), body.as_ref(), cond),
4146 _ => return false,
4147 },
4148 _ => return false,
4149 };
4150 if !matches!(cond, Expr::Const(ConstVal::Int(1))) {
4151 return false;
4152 }
4153 // JLS 14.14: `while (true)` completes normally iff its body holds a
4154 // reachable break that exits IT: an unlabeled break not captured by
4155 // an inner breakable construct, or `break L` where L is THIS loop's
4156 // own label. A labeled break to any OTHER label — inner (Pattern
4157 // .clazz's `break L4`) or OUTER (jdk11/26 ThreadPoolExecutor
4158 // .addWorker's `break retry` inside the inner for(;;)) — completes
4159 // the while ABRUPTLY: javac's flow model marks the statements after
4160 // such a loop unreachable (the w26 `continue;` after the inner
4161 // while(true) was a latent 无法访问的语句 masked by alphabetically
4162 // earlier census errors).
4163 !has_break_exiting(body, label, 0)
4164}
4165
4166fn has_break_exiting(s: &Stmt, lbl: Option<&str>, depth: usize) -> bool {
4167 match s {
4168 Stmt::Break(None) => depth == 0,
4169 // Only this loop's OWN label completes it; any other labeled
4170 // break exits abruptly (JLS 14.14/14.17).
4171 Stmt::Break(Some(l)) => Some(l.as_str()) == lbl,
4172 Stmt::Continue(_) | Stmt::Return(_) | Stmt::Throw(_) => false,
4173 Stmt::Goto(_) => true,
4174 Stmt::Block(v) => v.iter().any(|x| has_break_exiting(x, lbl, depth)),
4175 Stmt::If {
4176 then_stmt,
4177 else_stmt,
4178 ..
4179 } => {
4180 has_break_exiting(then_stmt, lbl, depth)
4181 || else_stmt
4182 .as_deref()
4183 .map(|e| has_break_exiting(e, lbl, depth))
4184 .unwrap_or(false)
4185 }
4186 Stmt::While { body, .. }
4187 | Stmt::DoWhile { body, .. }
4188 | Stmt::For { body, .. }
4189 | Stmt::ForEach { body, .. } => has_break_exiting(body, lbl, depth + 1),
4190 Stmt::Switch { cases, default, .. } => {
4191 cases
4192 .iter()
4193 .any(|c| c.body.iter().any(|x| has_break_exiting(x, lbl, depth + 1)))
4194 || default
4195 .as_deref()
4196 .map(|d| has_break_exiting(d, lbl, depth + 1))
4197 .unwrap_or(false)
4198 }
4199 Stmt::Try {
4200 body,
4201 catches,
4202 finally,
4203 }
4204 | Stmt::TryWithResources {
4205 body,
4206 catches,
4207 finally,
4208 ..
4209 } => {
4210 has_break_exiting(body, lbl, depth)
4211 || catches
4212 .iter()
4213 .any(|c| has_break_exiting(&c.body, lbl, depth))
4214 || finally
4215 .as_deref()
4216 .map(|f| has_break_exiting(f, lbl, depth))
4217 .unwrap_or(false)
4218 }
4219 Stmt::Synchronized { body, .. } => has_break_exiting(body, lbl, depth),
4220 Stmt::Labeled { body, .. } => has_break_exiting(body, lbl, depth),
4221 // Plain leaf statements never contain a break.
4222 Stmt::ExprStmt(_)
4223 | Stmt::LocalDef { .. }
4224 | Stmt::Assert { .. }
4225 | Stmt::TernaryValue { .. }
4226 | Stmt::MonitorEnter(_)
4227 | Stmt::MonitorExit(_)
4228 | Stmt::Comment(_) => false,
4229 // Opaque shapes (raw labels, inline class decls, anything new):
4230 // keep truncation off when an escape cannot be ruled out.
4231 _ => true,
4232 }
4233}