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.contains(&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 {
1073 cls,
1074 args,
1075 ty,
1076 arg_tys,
1077 ..
1078 } => {
1079 // The dex invoke-direct descriptor's formals, when the
1080 // node carries them at full arity: GROUND TRUTH for the
1081 // typed-arg rendering. The arity-based ctx lookup picks
1082 // `ctors_by_arity(..).first()` — a class with two
1083 // same-arity ctors (netease EnterLive: `(long,boolean)`
1084 // beside `(List,int)`) got the WRONG overload's formals
1085 // and the boolean formal rendered the int const arg as
1086 // `false` ("找不到合适的构造器" ×1,053-family).
1087 let pinned: Option<&[crate::types::JavaType]> =
1088 if !arg_tys.is_empty() && arg_tys.len() == args.len() {
1089 Some(arg_tys.as_slice())
1090 } else {
1091 None
1092 };
1093 let no_diamond = self.suppress_diamond;
1094 self.suppress_diamond = false;
1095 // Explicit type arguments pinned by the AST passes
1096 // (diamond_explicit_args_from_call_args): print them
1097 // instead of the diamond.
1098 let explicit = match ty {
1099 TypeRef::G(crate::types::GenericType::Class(cs))
1100 if cs.parts.last().map(|p| !p.args.is_empty()).unwrap_or(false)
1101 && crate::typeutil::classsig_internal(cs).as_str() == cls.as_ref() =>
1102 {
1103 let rendered: Vec<String> = cs
1104 .parts
1105 .last()
1106 .unwrap()
1107 .args
1108 .iter()
1109 .map(|a| self.generic_name(a))
1110 .collect();
1111 Some(format!("<{}>", rendered.join(", ")))
1112 }
1113 _ => None,
1114 };
1115 // A wildcard-typed ctor argument dooms diamond inference
1116 // (the inference variable gets an equality constraint from
1117 // the capture and a different bound from the context —
1118 // "cannot infer type arguments for Entry<>", jdk11
1119 // Hashtable `tab[i] = new Entry<>(hash, key, value, e)`
1120 // with e: Entry<?,?>; the source declared e as Entry<K,V>
1121 // via an unchecked cast that leaves no bytecode trace).
1122 // The raw form is always applicable (unchecked).
1123 let args_wildcard = args.iter().any(|a| {
1124 matches!(a.type_ref(), TypeRef::G(ref g)
1125 if crate::typeutil::g_has_wildcard(g))
1126 });
1127 let diamond: std::borrow::Cow<str> = match &explicit {
1128 Some(x) => x.as_str().into(),
1129 // Pre-Java-8 conditional branches are not poly
1130 // expressions: the diamond cannot see the assignment
1131 // target through the `?:` and infers <Object,Object>
1132 // (jdk7 HashSet.readObject map-ternary 不兼容的类型).
1133 // Raw is unchecked but always compilable.
1134 None if no_diamond
1135 || args_wildcard
1136 || (self.in_cond && self.ctx.source_level() < 52) =>
1137 {
1138 "".into()
1139 }
1140 None => self.diamond_for(cls).into(),
1141 };
1142 let diamond = diamond.as_ref();
1143 if let Some(local) = cls.strip_prefix('\u{2}') {
1144 out.push_str("new ");
1145 out.push_str(local);
1146 out.push_str(diamond);
1147 out.push('(');
1148 // Local records/classes keep bytecode-arity ctors:
1149 // typed rendering turns an int constant into the
1150 // char/boolean literal the ctor expects (jdk17
1151 // MessageFormat `new Qchar(39, quoted)`).
1152 // Nested local-class method printing runs under a
1153 // TAKEN LOCAL_CLASS_INTERNALS registry — resolve a
1154 // self-construction (`new BitSetSpliterator(..)` inside
1155 // BitSetSpliterator.trySplit) through the printer's
1156 // own class when the registry misses. Local-class
1157 // ctors capture the enclosing instance as a leading
1158 // param that the printed new-site omits; the this$0
1159 // fallback in ctor_param_types lines the formals up
1160 // (jdk11 BitSet$1BitSetSpliterator(BitSet,int,int,int,
1161 // boolean) — the boolean formal rendered its arg `0`).
1162 let internal = self.ctx.local_class_internal(local).or_else(|| {
1163 let tail = self.ctx.class_name().rsplit('$').next().unwrap_or("");
1164 let simple = tail.trim_start_matches(|c: char| c.is_ascii_digit());
1165 if !simple.is_empty() && simple == local {
1166 return Some(self.ctx.class_name().to_string());
1167 }
1168 // Probe the nested-name space of the printing
1169 // context (javac numbers method-local classes
1170 // `$1Name`): the new-site needs the real class to
1171 // resolve its ctor formals.
1172 let base = format!("{}${}", self.ctx.class_name(), local);
1173 if self.ctx.has_class(&base) {
1174 return Some(base);
1175 }
1176 for d in 0..10 {
1177 let cand = format!("{}${}{}", self.ctx.class_name(), d, local);
1178 if self.ctx.has_class(&cand) {
1179 return Some(cand);
1180 }
1181 }
1182 None
1183 });
1184 match internal
1185 .as_deref()
1186 .and_then(|i| self.ctor_param_types(i, 0, args.len(), args))
1187 {
1188 Some(pt) => self.args_typed(args, &pt, out),
1189 None => self.args(args, out),
1190 }
1191 out.push(')');
1192 } else if self.is_member_inner(cls)
1193 && !args.is_empty()
1194 && !matches!(args[0], Expr::This)
1195 && !is_this_expr(&args[0])
1196 // A constant (null/0) as the first argument is a real
1197 // parameter value, not the synthetic outer instance —
1198 // `0.new a()` / `null.new a()` are not valid Java.
1199 && !matches!(args[0], Expr::Const(_))
1200 // Anonymous classes (digit tails) are emitted as
1201 // separate top-level-ish classes — a qualified
1202 // `this.new 1(...)` is not valid Java; the flat
1203 // `new Outer$1(...)` form is. Test the RAW tail:
1204 // inner_simple already sanitizes a leading digit to
1205 // `_`, which silently bypassed this guard and emitted
1206 // `this.new _1(..)` against a flat top-level
1207 // declaration (weibo HorseRaceDetector$4 family).
1208 && !cls
1209 .rsplit('$')
1210 .next()
1211 .map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
1212 .unwrap_or(false)
1213 {
1214 // `outerExpr.new Inner(rest...)` — the first ctor arg
1215 // is the synthetic outer instance when the class has a
1216 // this$0 field, or when the ctor forwards it straight
1217 // to super (no field of its own; is_member_inner
1218 // detected it). Either way the qualified-new form
1219 // supplies the outer implicitly, so skip args[0].
1220 self.expr(&args[0], 15, out);
1221 out.push_str(".new ");
1222 out.push_str(&inner_simple(cls));
1223 out.push_str(diamond);
1224 out.push('(');
1225 if let Some(pt) = pinned {
1226 self.args_typed(&args[1..], &pt[1..], out);
1227 } else {
1228 match self.ctor_param_types(cls, 1, args.len() - 1, &args[1..]) {
1229 Some(pt) => self.args_typed(&args[1..], &pt, out),
1230 None => self.args(&args[1..], out),
1231 }
1232 }
1233 out.push(')');
1234 } else {
1235 out.push_str("new ");
1236 let digit_tail = cls
1237 .rsplit('$')
1238 .next()
1239 .map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
1240 .unwrap_or(false);
1241 // A digit-tail class (anonymous `Outer$1`, d8 lambda)
1242 // is rendered as a SEPARATE top-level file declaring
1243 // `class Outer$1` with the outer instance as an
1244 // ordinary ctor parameter — the ctor signature keeps
1245 // that parameter (the inner-ctor strip excludes
1246 // digit tails for exactly this shape). The member
1247 // form `this.new _1(..)` would look for a member of
1248 // the enclosing class that does not exist there —
1249 // the flat `new Outer$1(outer, ..)` with ALL args is
1250 // the shape that matches the declaration.
1251 let member_this = self.is_member_inner(cls)
1252 && !digit_tail
1253 && !args.is_empty()
1254 && matches!(args[0], Expr::This);
1255 let shown = if member_this {
1256 // `new Inner()` from inside the outer class
1257 inner_simple(cls)
1258 } else if digit_tail {
1259 // Digit-suffixed class at a `new` site: a d8/R8-
1260 // desugared lambda (`...$lambda$N$$inlined$log$1`,
1261 // `Outer$$ExternalSyntheticLambda0`) or an anonymous
1262 // class (`Outer$1`). Both are concrete, pool-rendered
1263 // classes, so print the real binary name — NOT the
1264 // abstract SAM interface `shorten` falls back to
1265 // (which yields an invalid `new Iface(..)`: "a是抽象
1266 // 的; 无法实例化", the biggest abstract-instantiation
1267 // family on Kotlin corpora, v6.a/l/p = Function0/1/2).
1268 // Type positions keep `shorten` (interface), so the
1269 // declaration stays phi-compatible across branches
1270 // that mint different lambdas: `Iface v = new C(..)`.
1271 self.shorten_concrete(cls)
1272 } else {
1273 self.shorten(cls)
1274 };
1275 out.push_str(&shown);
1276 out.push_str(diamond);
1277 out.push('(');
1278 if member_this {
1279 if let Some(pt) = pinned {
1280 self.args_typed(&args[1..], &pt[1..], out);
1281 } else {
1282 match self.ctor_param_types(cls, 1, args.len() - 1, &args[1..]) {
1283 Some(pt) => self.args_typed(&args[1..], &pt, out),
1284 None => self.args(&args[1..], out),
1285 }
1286 }
1287 } else {
1288 // Pinned generic instantiation: prime lambda args
1289 // from the ctor's instantiated Signature formals.
1290 let sam_rets: Vec<Option<TypeRef>> = match ty {
1291 TypeRef::G(crate::types::GenericType::Class(cs))
1292 if explicit.is_some()
1293 && crate::typeutil::classsig_internal(cs).as_str() == cls.as_ref() =>
1294 {
1295 let pinned = cs.parts.last().map(|p| p.args.clone());
1296 let formals = self.ctx.ctor_formals_by_arity(cls, args.len());
1297 // The raw ctor formals carry the class's
1298 // own typevars — substitute the pinned
1299 // instantiation before reading the SAM
1300 // return (an unsubstituted R printed `(R)`
1301 // — 找不到符号).
1302 let class_params = self.ctx.class_type_params(cls);
1303 args.iter()
1304 .enumerate()
1305 .map(|(i, a)| {
1306 if !matches!(a, Expr::Lambda(_)) {
1307 return None;
1308 }
1309 let f = formals.as_ref()?.get(i)?;
1310 let pinned = pinned.as_ref()?;
1311 if pinned.len() != class_params.len() {
1312 return None;
1313 }
1314 let inst = crate::typeutil::subst_typevars(
1315 f,
1316 &class_params,
1317 pinned,
1318 );
1319 let Expr::Lambda(l) = a else { return None };
1320 self.sam_ret_cast(&inst, &l.sam_name)
1321 })
1322 .collect()
1323 }
1324 _ => Vec::new(),
1325 };
1326 if let Some(pt) = pinned {
1327 self.args_typed_sam(args, pt, &sam_rets, out);
1328 } else {
1329 match self.ctor_param_types(cls, 0, args.len(), args) {
1330 Some(pt) => self.args_typed_sam(args, &pt, &sam_rets, out),
1331 None => self.args(args, out),
1332 }
1333 }
1334 }
1335 out.push(')');
1336 }
1337 }
1338 Expr::NewArray {
1339 elem,
1340 dims,
1341 trailing_dims,
1342 init,
1343 } => {
1344 out.push_str("new ");
1345 out.push_str(&self.type_name(elem));
1346 match init {
1347 Some(vals) => {
1348 for _ in 0..=*trailing_dims {
1349 out.push_str("[]");
1350 }
1351 out.push_str(" {");
1352 // boolean[]/char[] initializers hold int constants
1353 // in bytecode (iconst + bastore/castore): render
1354 // them as true/false and char literals (jdk11
1355 // PKCS9Attribute `new boolean[] {0, 0, 1, ..}` x18).
1356 let elem_bool = elem.erased() == crate::types::JavaType::Boolean;
1357 let elem_char = elem.erased() == crate::types::JavaType::Char;
1358 for (i, v) in vals.iter().enumerate() {
1359 if i > 0 {
1360 out.push_str(", ");
1361 }
1362 if elem_bool {
1363 self.expr_bool(v, out);
1364 } else if elem_char {
1365 self.expr_char(v, out);
1366 } else {
1367 self.expr(v, 1, out);
1368 }
1369 }
1370 out.push('}');
1371 }
1372 None => {
1373 for d in dims {
1374 out.push('[');
1375 self.expr(d, 1, out);
1376 out.push(']');
1377 }
1378 for _ in 0..*trailing_dims {
1379 out.push_str("[]");
1380 }
1381 }
1382 }
1383 }
1384 Expr::NewMultiArray { ty, dims } => {
1385 // Strip the dims.len() leading array levels from the type.
1386 let mut base = ty.erased();
1387 for _ in 0..dims.len() {
1388 match base {
1389 crate::types::JavaType::Array(inner) => base = *inner,
1390 _ => break,
1391 }
1392 }
1393 out.push_str("new ");
1394 out.push_str(&self.type_name(&TypeRef::J(base)));
1395 for d in dims {
1396 out.push('[');
1397 self.expr(d, 1, out);
1398 out.push(']');
1399 }
1400 }
1401 Expr::Field {
1402 owner,
1403 cls,
1404 name,
1405 is_static,
1406 ..
1407 } => {
1408 // javac reserves `$assertionsDisabled`; the declaration and
1409 // all references are emitted under a private alias.
1410 let name: &str = if name.as_ref() == "$assertionsDisabled" {
1411 crate::analysis::ASSERT_FIELD
1412 } else {
1413 name
1414 };
1415 if name == crate::analysis::ASSERT_FIELD {
1416 // Assert guards print bare: the field is declared on
1417 // the enclosing emitted class or inlined body; the
1418 // bytecode owner is often a synthetic holder class
1419 // (`ConstantGroup$1`) whose shorten() fallback is
1420 // `Object` — a qualified read can never resolve.
1421 out.push_str(&java_ident(name));
1422 } else if name == "length" && cls.is_empty() {
1423 if let Some(o) = owner {
1424 if let Expr::Const(_) = o.as_ref() {
1425 // Receiver tracking lost: `0.length` is not
1426 // parseable — cast-null array form.
1427 out.push_str("((java.lang.Object[]) null)");
1428 } else {
1429 self.expr(o, 15, out);
1430 }
1431 }
1432 out.push_str(".length");
1433 } else if let Some(o) = owner {
1434 if let Expr::Const(cv) = o.as_ref() {
1435 if matches!(
1436 cv,
1437 crate::ir::expr::ConstVal::Str(_)
1438 | crate::ir::expr::ConstVal::ClassLit(_)
1439 ) {
1440 // Literal receivers keep their value (see the
1441 // Method arm): `Foo.class.name`, not
1442 // `((Class) null).name`.
1443 self.expr(o, 15, out);
1444 out.push('.');
1445 } else {
1446 // Receiver tracking lost (a null placeholder leaked
1447 // through): `0.b` is not parseable — the same
1448 // cast-null form the Method arm uses.
1449 out.push_str("((");
1450 out.push_str(&self.shorten(cls));
1451 out.push_str(") null).");
1452 }
1453 out.push_str(&java_ident(name));
1454 } else if matches!(o.as_ref(), Expr::Raw(t) if t == "\u{3}") {
1455 // Outer anonymous class member: unqualified lexical
1456 // resolution (an anon outer has no nameable this).
1457 out.push_str(&java_ident(name));
1458 } else if self.private_super_field(cls, name, o.as_ref()) {
1459 // A private field of a SUPERCLASS is not inherited
1460 // into the subclass's member scope: `this.algorithm`
1461 // inside Delegate (extends MessageDigest, algorithm
1462 // private) is "private access" even though the
1463 // source comment says it all — jdk11
1464 // MessageDigest.Delegate.clone casts
1465 // `((MessageDigest)this).algorithm`.
1466 out.push_str("((");
1467 out.push_str(&self.shorten(cls));
1468 out.push_str(") ");
1469 if matches!(o.as_ref(), Expr::This) {
1470 out.push_str("this");
1471 } else {
1472 self.expr(o, 14, out);
1473 }
1474 out.push_str(").");
1475 out.push_str(&java_ident(name));
1476 } else if match o.type_ref().erased() {
1477 crate::types::JavaType::Object(ref n) => {
1478 n.as_ref() != cls.as_ref()
1479 && !matches!(o.as_ref(), Expr::Raw(_) | Expr::RawT(..) | Expr::This)
1480 && (n.as_ref() == "java/lang/Object"
1481 || self.ctx.is_subtype_of(
1482 &crate::types::JavaType::Object(
1483 std::sync::Arc::from(cls.as_ref()),
1484 ),
1485 n,
1486 ))
1487 }
1488 _ => false,
1489 } {
1490 // The receiver's static type is a strict SUPERTYPE
1491 // of the declaring class: either widened to Object
1492 // (when-materialization residue) or a register
1493 // reuse the vt kept at the supertype (`v9.label`
1494 // with v9: ContinuationImpl, label on the suspend
1495 // frame subclass — weibo coroutine cluster ×1.3k).
1496 // The downcast is what the bytecode's field
1497 // resolution did; same honest cast as the Method
1498 // arm. Concrete name: a `$<digits>` declaring
1499 // class loses its pushed-down members under the
1500 // anon fallback.
1501 out.push_str("((");
1502 out.push_str(&self.shorten_concrete(cls));
1503 out.push_str(") ");
1504 self.expr(o, 14, out);
1505 out.push_str(").");
1506 out.push_str(&java_ident(name));
1507 } else {
1508 self.expr(o, 15, out);
1509 out.push('.');
1510 out.push_str(&java_ident(name));
1511 }
1512 } else if *is_static {
1513 // A same-class static read prints bare — unless a local
1514 // of this method shadows the field name: javac resolves
1515 // the bare name as the LOCAL (jdk17 Socket.setImpl's
1516 // `SocketImplFactory factory = factory;` self-reference
1517 // — 可能尚未初始化变量factory x2 sites). Qualify with the
1518 // class name to reach the field.
1519 let shadowed_by_local = cls.as_ref() == self.ctx.class_name()
1520 && self.vt.vars.iter().any(|v| v.name == name);
1521 // ENCLOSING-class static fields read from a nested
1522 // class print bare too (lexical scope) — and MUST when
1523 // the class name itself is shadowed by a member of the
1524 // same name: jdk26 HPKE$Impl reads the outer
1525 // `byte[] HPKE`/PSK_ID_HASH/SECRET/EXP/KEY constants;
1526 // `HPKE.PSK_ID_HASH` resolves the qualifier as the
1527 // byte[] FIELD (variables obscure type names in
1528 // expression names) — 找不到符号 变量 PSK_ID_HASH x6.
1529 let enclosing_static = cls.as_ref() != self.ctx.class_name()
1530 && self.renders_nested_in(cls)
1531 && !self.vt.vars.iter().any(|v| v.name == name)
1532 && {
1533 let mut cur = self.ctx.class_name().to_string();
1534 let mut shadow = false;
1535 while cur.as_str() != cls.as_ref() {
1536 // Inherited fields shadow too (superclass
1537 // chain — see the method-side twin).
1538 let mut sup = Some(cur.clone());
1539 while let Some(c) = sup.take() {
1540 {
1541 // Display-space: the reference's
1542 // name is the registry DISPLAY
1543 // (the lift applied it), so the
1544 // shadow comparison must be too —
1545 // the nested class's raw `a`
1546 // displaying `a17` shadows the
1547 // outer field that displays a17
1548 // (lark ch6/b$a: `a17.length` bound
1549 // to the List instead of the
1550 // outer array).
1551 if self.ctx.declares_field_display(&c, name) {
1552 shadow = true;
1553 break;
1554 }
1555 sup = self.ctx.super_name(&c);
1556 }
1557 }
1558 if shadow {
1559 break;
1560 }
1561 match cur.rfind('$') {
1562 Some(i) => cur.truncate(i),
1563 None => break,
1564 }
1565 }
1566 !shadow
1567 };
1568 if !enclosing_static && (cls.as_ref() != self.ctx.class_name() || shadowed_by_local) {
1569 // The owner must name a DECLARABLE class: the
1570 // anonymous→interface/Object fallback (right for
1571 // phi-compatible type positions) leaves the field
1572 // unresolvable — `Object.$SwitchMap$java$math$
1573 // RoundingMode` (485 weibo / 308 lark / 217
1574 // weixin cannot-finds; the synthetic holder
1575 // `LongMath$1` IS rendered as a flat file with
1576 // the field, 0 own errors). Fall back to the
1577 // concrete `$N` name — `$` and digits are legal
1578 // Java identifier characters, and the holder
1579 // always sits in the referring class's package.
1580 // The qualifier of a STATIC member is always the
1581 // CONCRETE name: anon/lambda classes emit as flat
1582 // `$`-named top-level files, while shorten()'s
1583 // anon fallback renders the SAM interface — which
1584 // does not declare the member. `Function0.INSTANCE`
1585 // (1.7k weibo lines) is the sget of
1586 // ActivityResultRegistry$generateRandomNumber$1
1587 // .INSTANCE; the same trap took $SwitchMap holders
1588 // to `Object.` before (the narrow rendered=="Object"
1589 // check this replaces).
1590 out.push_str(&self.shorten_concrete(cls));
1591 out.push('.');
1592 }
1593 out.push_str(&java_ident(name));
1594 } else if self.private_super_field(cls, name, &Expr::This) {
1595 out.push_str("((");
1596 out.push_str(&self.shorten(cls));
1597 out.push_str(") this).");
1598 out.push_str(&java_ident(name));
1599 } else {
1600 out.push_str("this.");
1601 out.push_str(&java_ident(name));
1602 }
1603 }
1604 Expr::Method {
1605 owner,
1606 cls,
1607 name,
1608 desc,
1609 args,
1610 is_static,
1611 is_special,
1612 is_super,
1613 type_args,
1614 ..
1615 } => {
1616 // Signature-polymorphic calls need the descriptor return cast
1617 // in source form (see classdec::polymorphic_ret_cast) — except
1618 // at the root of an expression statement, where the bare call
1619 // is the only legal form. Consume the flag so a poly call
1620 // NESTED in the args still gets its cast.
1621 let bare_stmt_root = self.suppress_poly_cast;
1622 self.suppress_poly_cast = false;
1623 if !bare_stmt_root {
1624 if let Some(t) = self.ctx.polymorphic_ret_cast(cls, name, desc) {
1625 out.push('(');
1626 out.push_str(&self.type_name(&crate::ir::expr::TypeRef::J(t)));
1627 out.push_str(") ");
1628 }
1629 }
1630 if name.as_ref() == "<init>" && *is_special {
1631 // The ctor fold normally turns `new X; <init>` into a
1632 // New expr at the LIFT. When the new-instance view was
1633 // lost (crossed a merge / got materialized), the call
1634 // arrives here with a NON-this receiver: rendering a
1635 // this/super delegation produced `this.super(...)`,
1636 // which is not valid Java. The allocation did happen —
1637 // print the construction call.
1638 let lost_alloc = owner
1639 .as_deref()
1640 .is_some_and(|o| !is_this_expr(o) && !matches!(o, Expr::This));
1641 if lost_alloc {
1642 // A member-inner construction call carries the
1643 // synthetic outer as args[0] and the emitted
1644 // ctor signature drops it (the inner-ctor
1645 // normalization) — supply it implicitly with the
1646 // qualified-new form, mirroring the New-expr
1647 // branches. Digit-tail classes keep the flat
1648 // full-args form (their ctor declares the
1649 // outer parameter).
1650 let digit_tail = cls
1651 .rsplit('$')
1652 .next()
1653 .map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
1654 .unwrap_or(false);
1655 if self.is_member_inner(cls)
1656 && !digit_tail
1657 && !args.is_empty()
1658 && !matches!(args[0], Expr::Const(_))
1659 {
1660 if matches!(args[0], Expr::This) || is_this_expr(&args[0]) {
1661 out.push_str("this.new ");
1662 } else {
1663 self.expr(&args[0], 15, out);
1664 out.push_str(".new ");
1665 }
1666 out.push_str(&inner_simple(cls));
1667 out.push('(');
1668 match self.ctor_param_types(cls, 1, args.len() - 1, &args[1..]) {
1669 Some(pt) => self.args_typed(&args[1..], &pt, out),
1670 None => self.args(&args[1..], out),
1671 }
1672 out.push(')');
1673 return;
1674 }
1675 out.push_str("new ");
1676 out.push_str(&self.shorten(cls));
1677 out.push('(');
1678 self.args(args, out);
1679 out.push(')');
1680 return;
1681 }
1682 // super(...) / this(...)
1683 let is_super_form = *is_super || cls.as_ref() != self.ctx.class_name();
1684 // Qualified super for a STATIC class extending an
1685 // INNER superclass: javac synthesizes the enclosing
1686 // instance as the ctor's first param, and the source
1687 // form is `outer.super(rest)` (jdk11/17/26
1688 // BoundMethodHandle.SpeciesData extends
1689 // ClassSpecializer<..>.SpeciesData — plain
1690 // super(outer, key) is "需要包含..的封闭实例" x3 trees).
1691 let qualified_outer = if is_super_form
1692 && !args.is_empty()
1693 && cls.contains('$')
1694 && !self.ctx.class_has_this0(self.ctx.class_name())
1695 {
1696 let enclosing = cls.rsplit_once('$').map(|(o, _)| o.to_string());
1697 match enclosing {
1698 Some(enc)
1699 if self.ctx.class_has_this0(cls)
1700 && self
1701 .ctx
1702 .is_subtype_of(&args[0].type_ref().erased(), &enc) =>
1703 {
1704 Some(enc)
1705 }
1706 _ => None,
1707 }
1708 } else {
1709 None
1710 };
1711 // The enclosing instance passed explicitly is `this`
1712 // itself (qualified_outer found the enclosing, but the
1713 // argument IS this class's own outer): the source form
1714 // is plain `super(rest...)` — the implicit outer —
1715 // because `this.super(...)` is not valid Java (weibo
1716 // HorseRaceDetector, reqable androidx.fragment.app.d).
1717 let this_outer =
1718 is_super_form && !args.is_empty() && is_this_expr(&args[0]);
1719 let skip_outer_arg = qualified_outer.is_some() || this_outer;
1720 if qualified_outer.is_some() && !this_outer {
1721 self.expr(&args[0], 15, out);
1722 out.push_str(".super(");
1723 } else if is_super_form {
1724 out.push_str("super(");
1725 } else {
1726 out.push_str("this(");
1727 }
1728 // Typed rendering: boolean/char params must not receive
1729 // raw 0/1 int constants (`this(refKind, false)`). The
1730 // methodref's descriptor `desc.args` is the EXACT invoked
1731 // ctor signature, so prefer it over `ctor_param_types`
1732 // (which matches by arg count and picks the wrong
1733 // overload when a class has several ctors of equal arity,
1734 // e.g. jdk26 Thread(ThreadGroup,Runnable,String,long,
1735 // boolean) vs (...,long,Thread[])).
1736 let _ = is_super_form;
1737 // Upcast restoration only for SELF delegation: this(..)
1738 // overload resolution binds the arg's static type (a
1739 // JarEntry arg would recurse into JarEntry(JarEntry)
1740 // instead of the descriptor's JarEntry(ZipEntry)).
1741 // super(..) resolution is unambiguous through the
1742 // generic formals — casting there broke FindOps
1743 // `super(parent, spliterator)` (K := FindTask<..>
1744 // accepts the arg fine; the raw erasure cast does not).
1745 if skip_outer_arg {
1746 if desc.args.len() == args.len() && !desc.args.is_empty() {
1747 self.args_typed(&args[1..], &desc.args[1..], out);
1748 } else {
1749 self.args(&args[1..], out);
1750 }
1751 } else if desc.args.len() == args.len() {
1752 if is_super_form {
1753 self.args_typed(args, &desc.args, out);
1754 } else {
1755 self.args_delegation(args, &desc.args, out);
1756 }
1757 } else if !is_super_form {
1758 // desc is the EXACT invoked ctor signature and the
1759 // args are outer-stripped: args_delegation aligns
1760 // by tail (jdk11 ZipFileInflaterInputStream —
1761 // ctor_param_types' arity match would pick the
1762 // wrong same-arity overload and cast against
1763 // shifted formals, (ZipFile) zfin x3).
1764 self.args_delegation(args, &desc.args, out);
1765 } else {
1766 match self.ctor_param_types(cls, 0, args.len(), args) {
1767 Some(pt) if pt.len() == args.len() => self.args_typed(args, &pt, out),
1768 _ => self.args(args, out),
1769 }
1770 }
1771 out.push(')');
1772 } else {
1773 if *is_super {
1774 // invokespecial on `this` targeting another class:
1775 // a superclass method call. Interface targets are
1776 // qualified `Iface.super.m()` (JDK8 default-method
1777 // invocations from implementors) — but only a
1778 // DIRECT superinterface may carry the qualifier
1779 // (JLS 15.11.2). A default reached through a
1780 // SUBINTERFACE (weixin jsapi/f0 implements e0
1781 // extends l; `l.super.m()` = "不是封闭类: l" ×67)
1782 // qualifies with the direct interface inheriting
1783 // it; one reached only through the superclass
1784 // chain falls back to plain `super.` (the super
1785 // inherits the default as its own member).
1786 let itf = self.ctx.is_interface(cls);
1787 if itf {
1788 let mut qual: Option<String> = None;
1789 if let Some((ifs, _)) =
1790 self.ctx.class_bases(self.ctx.class_name())
1791 {
1792 if ifs.iter().any(|i| i.as_str() == cls.as_ref()) {
1793 qual = Some(cls.to_string());
1794 } else {
1795 qual = ifs.into_iter().find(|i| {
1796 self.ctx.is_subtype_of(
1797 &crate::types::JavaType::Object(
1798 i.as_str().into(),
1799 ),
1800 cls,
1801 )
1802 });
1803 }
1804 }
1805 if let Some(q) = qual {
1806 out.push_str(&self.shorten(&q));
1807 out.push('.');
1808 }
1809 }
1810 out.push_str("super.");
1811 } else if let Some(o) = owner {
1812 if let Expr::Const(cv) = o.as_ref() {
1813 if matches!(
1814 cv,
1815 crate::ir::expr::ConstVal::Str(_)
1816 | crate::ir::expr::ConstVal::ClassLit(_)
1817 ) {
1818 // A literal receiver is valid, faithful
1819 // Java (`"http".equalsIgnoreCase(x)`,
1820 // `Foo.class.getName()`). Rendering it as
1821 // cast-null silently DROPPED the constant
1822 // — 73.5k sites across the 4 corpora
1823 // (`((String) null).m()`), invisible to
1824 // javac (it compiles) and an NPE at run
1825 // time. Only valueless placeholders take
1826 // the cast-null path below.
1827 self.expr(o, 15, out);
1828 out.push('.');
1829 } else {
1830 // Receiver tracking lost: a null placeholder
1831 // (const/4 0) leaked through as the receiver —
1832 // `0.close()` is not parseable. Cast-null keeps
1833 // the statement compilable and honestly marks
1834 // the value as unknown on this path.
1835 out.push_str("((");
1836 out.push_str(&self.shorten(cls));
1837 out.push_str(") null).");
1838 }
1839 } else if let Expr::Lambda(l) = o.as_ref() {
1840 // A lambda RECEIVER needs the source's SAM cast
1841 // (`((BooleanSupplier) () -> ..).getAsBoolean()`
1842 // — a bare lambda cannot own a call: 此处不应为
1843 // lambda 表达式, jdk26 Proxy assert).
1844 if !l.sam_cls.is_empty() {
1845 out.push_str("((");
1846 out.push_str(&self.shorten(&l.sam_cls));
1847 out.push_str(") ");
1848 self.expr(o, 14, out);
1849 out.push_str(").");
1850 } else {
1851 self.expr(o, 15, out);
1852 out.push('.');
1853 }
1854 } else if matches!(o.as_ref(), Expr::Raw(t) if t == "\u{3}") {
1855 // Outer anonymous member call: unqualified
1856 // lexical resolution.
1857 } else if self.needs_owner_cast(cls, name, desc, o) {
1858 // Private / cross-package members are NOT
1859 // inherited by the receiver's static type:
1860 // the source cast to the declaring class
1861 // (`((ZipFile) jar).getManifestNum()`) leaves
1862 // no bytecode trace when the receiver is
1863 // already a subtype.
1864 out.push_str("((");
1865 out.push_str(&self.shorten_concrete(cls));
1866 out.push_str(") ");
1867 self.expr(o, 14, out);
1868 out.push_str(").");
1869 } else {
1870 self.expr(o, 15, out);
1871 out.push('.');
1872 }
1873 } else if *is_static && (cls.as_ref() != self.ctx.class_name() || !type_args.is_empty())
1874 {
1875 // A static member of an ENCLOSING class resolves
1876 // through lexical scope unqualified — and the
1877 // qualified form is a TRAP when a field/local is
1878 // named after the class: expression-name
1879 // resolution prefers variables, so jdk26
1880 // HPKE$Impl's `private static final byte[] HPKE`
1881 // hijacked `HPKE.usePSK(psk)` into a member
1882 // lookup on the array (找不到符号 方法
1883 // usePSK(SecretKey) 位置: 类型为byte[]的变量
1884 // HPKE). Keep the qualifier when an own or
1885 // intermediate class declares a same-named
1886 // method (real member shadowing) or when type
1887 // witnesses need an explicit receiver.
1888 // renders_nested_in: flat-rendered (digit-tail)
1889 // nested classes have NO lexical scope.
1890 let enclosing_static = type_args.is_empty()
1891 && self.renders_nested_in(cls)
1892 && {
1893 let mut cur = self.ctx.class_name().to_string();
1894 let mut shadow = false;
1895 while cur.as_str() != cls.as_ref() {
1896 // Inherited members shadow too: the
1897 // lexical member scope of a class
1898 // includes its whole superclass chain
1899 // (jdk26 GaloisCounterMode$GCMDecrypt
1900 // extends GCMEngine, whose own
1901 // implGCMCrypt(ByteBuffer,..) hijacks
1902 // the bare 9-arg call to the OUTER
1903 // static — 无法将方法应用到给定类型).
1904 let mut sup = Some(cur.clone());
1905 while let Some(c) = sup.take() {
1906 {
1907 if self.ctx.declares_method_named(&c, name) {
1908 shadow = true;
1909 break;
1910 }
1911 sup = self.ctx.super_name(&c);
1912 }
1913 }
1914 if shadow {
1915 break;
1916 }
1917 match cur.rfind('$') {
1918 Some(i) => cur.truncate(i),
1919 None => break,
1920 }
1921 }
1922 !shadow
1923 };
1924 if !enclosing_static {
1925 // Concrete name: same anon-class trap as the
1926 // static FIELD qualifier (the SAM interface
1927 // does not declare the synthetic static).
1928 out.push_str(&self.shorten_concrete(cls));
1929 out.push('.');
1930 }
1931 } else if !type_args.is_empty() {
1932 // Type witnesses require an explicit receiver.
1933 out.push_str("this.");
1934 }
1935 if !type_args.is_empty() {
1936 out.push('<');
1937 out.push_str(&type_args.join(", "));
1938 out.push('>');
1939 }
1940 // A BARE `yield(...)` invocation trips Java 13's
1941 // restricted identifier (Kotlin suspend funs name
1942 // their continuation entry `yield`; news_article
1943 // ships CoroutineExtKt$yield). Qualified calls are
1944 // fine — when no receiver was printed, add one.
1945 if name.as_ref() == "yield" && !out.ends_with('.') && !out.ends_with('>') {
1946 out.push_str(&self.shorten(cls));
1947 out.push('.');
1948 }
1949 out.push_str(&java_ident(name));
1950 out.push('(');
1951 // Lambda args of a GENERIC call: prime each one's
1952 // body-return cast from the instantiated formal's SAM
1953 // return (jdk17 AbstractPipeline.opEvaluateParallelLazy:
1954 // `i -> (E_OUT[]) new Object[i]` — the erasure-equal
1955 // cast leaves no bytecode trace and without it the
1956 // IntFunction<E_OUT[]> formal starves: Object[]无法
1957 // 转换为E_OUT[]).
1958 let sam_rets: Vec<Option<TypeRef>> = {
1959 let mut v: Vec<Option<TypeRef>> =
1960 std::iter::repeat_with(|| None).take(args.len()).collect();
1961 if self.ctx.is_generic_call(e) {
1962 if let Some((formals, mtvars)) = self.ctx.generic_call_formals(e) {
1963 if formals.len() == args.len() {
1964 for (i, (a, f)) in args.iter().zip(formals.iter()).enumerate() {
1965 // A raw-SAM-cast wrapper still
1966 // exposes the lambda (the overload
1967 // disambiguation cast; the primed
1968 // body return types the lambda
1969 // precisely).
1970 let a_inner = match a {
1971 Expr::Cast { e: ce, .. } => ce.as_ref(),
1972 other => other,
1973 };
1974 if let Expr::Lambda(l) = a_inner {
1975 // A formal still carrying the
1976 // callee's own method typevars
1977 // is not denotable at this
1978 // call site.
1979 if crate::typeutil::g_mentions_any(f, &mtvars) {
1980 continue;
1981 }
1982 v[i] = self.sam_ret_cast(f, &l.sam_name);
1983 }
1984 }
1985 }
1986 }
1987 }
1988 v
1989 };
1990 if sam_rets.iter().any(|x| x.is_some()) {
1991 self.args_typed_sam(args, &desc.args, &sam_rets, out);
1992 } else {
1993 self.args_typed(args, &desc.args, out);
1994 }
1995 out.push(')');
1996 }
1997 }
1998 Expr::ArrayIndex { array, index } => {
1999 self.expr(array, 15, out);
2000 out.push('[');
2001 // Array indexes are int by definition: a long-typed index
2002 // local (slot-sharing/merge typed the foreach lowering's
2003 // counter long — jdk26 Files.copy `options[i]`,
2004 // 从long转换到int可能会有损失) needs the narrowing cast.
2005 let idx_ty = match &**index {
2006 Expr::Local { var, .. } => self.vt.var(*var).ty.erased(),
2007 other => other.type_ref().erased(),
2008 };
2009 if matches!(idx_ty, crate::types::JavaType::Long) {
2010 out.push_str("(int) ");
2011 }
2012 self.expr(index, 1, out);
2013 out.push(']');
2014 }
2015 Expr::Cast { ty, e } => {
2016 // `(T) (Serializable) lambda` is invalid Java: the source
2017 // form of a serializable-lambda cast is the intersection
2018 // `(T & Serializable) lambda`.
2019 if let Expr::Cast {
2020 ty: inner_ty,
2021 e: inner_e,
2022 } = &**e
2023 {
2024 let is_serializable = |t: &crate::ir::expr::TypeRef| {
2025 t.erased() == crate::types::JavaType::Object("java/io/Serializable".into())
2026 };
2027 if matches!(&**inner_e, Expr::Lambda(_)) && is_serializable(inner_ty) {
2028 out.push('(');
2029 out.push_str(&self.type_name(ty));
2030 out.push_str(" & ");
2031 out.push_str(&self.type_name(inner_ty));
2032 out.push_str(") ");
2033 self.expr(inner_e, 14, out);
2034 return;
2035 }
2036 }
2037 // CLASS-argument generic casts only: a TYPEVAR cast is
2038 // load-bearing (`(T) new SimpleEntry<>(..)` — jdk11
2039 // IdentityHashMap.toArray: the diamond infers from the
2040 // ctor args and the unchecked (T) makes the T[] store
2041 // legal; dropping it left the diamond to infer from the
2042 // array target T — 无法推断SimpleEntry<>的类型参数).
2043 if let (TypeRef::G(crate::types::GenericType::Class(_)), Expr::New { cls, .. }) =
2044 (ty, &**e)
2045 {
2046 if !self.diamond_for(cls).is_empty() {
2047 // Synthetic generics-only cast around a diamond new:
2048 // DROP the cast and keep the diamond. A generic-typed
2049 // cast is always jcdc's own witness (a real checkcast
2050 // carries only erasure), and every cast form loses
2051 // here: with the diamond the cast starves inference
2052 // (`(PendingFuture<Void,A>) new PendingFuture<>(..)`
2053 // infers Object bounds and fails the cast), and the
2054 // bare/raw form makes the whole creation raw so
2055 // method-ref/lambda arguments stop type-checking
2056 // (jdk17 Collectors `(Collector<T,?,C>) new
2057 // CollectorImpl(.., Collection::add, ..)`). Cast-free
2058 // `return new CollectorImpl<>(..)` / `x = new
2059 // PendingFuture<>(..)` target-types the diamond —
2060 // the source shape.
2061 self.expr(e, outer_prec, out);
2062 return;
2063 }
2064 }
2065 out.push('(');
2066 // A cast to a pool `$<digits>` class (desugared lambda /
2067 // coroutine frame) must keep the CONCRETE name: the
2068 // anon-fallback would print the SAM interface/super and
2069 // drop exactly the members the cast exists to reach
2070 // (weibo `(($reportWhenComplete$1) continuation).label`
2071 // rendered `(ContinuationImpl) …` — label lives on the
2072 // frame class only, R8 pushed it down; 找不到符号 ×420).
2073 match ty {
2074 TypeRef::J(crate::types::JavaType::Object(n))
2075 if self.ctx.has_class(n)
2076 && n.rsplit('$')
2077 .next()
2078 .is_some_and(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit())) =>
2079 {
2080 out.push_str(&self.shorten_concrete(n));
2081 }
2082 _ => out.push_str(&self.type_name(ty)),
2083 }
2084 out.push_str(") ");
2085 // Inconvertible direct casts from mis-joined stack-merge
2086 // vars (jdk26 AnnotationReader: `(SupertypeTarget)
2087 // var3_341` with var3 typed Iterator — sealed targets
2088 // reject the cross-cast): relay through Object, which is
2089 // always legal and semantically identical (the runtime
2090 // value IS the target type).
2091 if self.needs_object_relay(ty, e) {
2092 out.push_str("(Object) ");
2093 }
2094 if matches!(&**e, Expr::New { .. }) {
2095 self.suppress_diamond = true;
2096 }
2097 if let (TypeRef::G(g), Expr::Lambda(l)) = (ty, &**e) {
2098 self.lambda_sam_ret = self.sam_ret_cast(g, &l.sam_name);
2099 }
2100 self.expr(e, 14, out);
2101 self.suppress_diamond = false;
2102 self.lambda_sam_ret = None;
2103 }
2104 Expr::InstanceOf { e, ty } => {
2105 // `error2 instanceof CodecException` with error2: Error
2106 // is "不兼容的类型" — instanceof demands castability
2107 // exactly like a cast, so it takes the same Object
2108 // relay (semantics unchanged: instanceof is a runtime
2109 // type test).
2110 if self.needs_object_relay(ty, e) {
2111 out.push_str("((Object) ");
2112 self.expr(e, 14, out);
2113 out.push(')');
2114 } else {
2115 self.expr(e, 10, out);
2116 }
2117 out.push_str(" instanceof ");
2118 out.push_str(&self.type_name(ty));
2119 }
2120 Expr::Un { op, e } => {
2121 out.push_str(match op {
2122 UnOp::Neg => "-",
2123 UnOp::Not => "!",
2124 UnOp::BitNot => "~",
2125 });
2126 self.expr(e, 14, out);
2127 }
2128 Expr::Bin { op, l, r, .. } => {
2129 // Boolean context special cases: `b == 0` → `!b`. A
2130 // Local's embedded type can be stale (booleanize retypes
2131 // the VarTable), and a boolified bitwise bin over
2132 // bool-ish operands is boolean too (jdk26
2133 // LinkedTransferQueue `(spin & !upc) == 0` — the frozen-Int
2134 // And with an int-form ternary side printed
2135 // `spin & (!upc ? 1 : 0)`: boolean & int).
2136 let lt = match &**l {
2137 Expr::Local { var, .. } => self.vt.var(*var).ty.erased(),
2138 other => other.type_ref().erased(),
2139 };
2140 let l_bool = lt == JavaType::Boolean;
2141 let l_boolish = l_bool || self.bool_ish_vt(l);
2142 if matches!(op, BinOp::Eq | BinOp::Ne | BinOp::RefEq | BinOp::RefNe) && l_boolish {
2143 if let Expr::Const(ConstVal::Int(n)) = &**r {
2144 let polarity = matches!(op, BinOp::Eq | BinOp::RefEq);
2145 let want_true = (*n != 0) == polarity;
2146 if !want_true {
2147 out.push('!');
2148 }
2149 if l_bool {
2150 self.expr(l, 14, out);
2151 } else {
2152 // Composite boolean (a bitwise bin): parenthesize
2153 // so a leading `!` binds the whole value.
2154 out.push('(');
2155 self.expr_bool(l, out);
2156 out.push(')');
2157 }
2158 if parens {
2159 out.push(')');
2160 }
2161 return;
2162 }
2163 }
2164 // Mixed boolean/int equality on non-constants (stack-merge
2165 // vars of an assert desugaring: jdk26 VirtualThread
2166 // `stack38 == stack39` with stack38 boolean, stack39 int
2167 // 0/1 — "boolean和int不可比较"): normalize the int side
2168 // through `!= 0`.
2169 {
2170 let rt = r.type_ref().erased();
2171 if matches!(op, BinOp::Eq | BinOp::Ne)
2172 && ((lt == crate::types::JavaType::Boolean
2173 && rt == crate::types::JavaType::Int)
2174 || (lt == crate::types::JavaType::Int
2175 && rt == crate::types::JavaType::Boolean))
2176 {
2177 for (i, side) in [l, r].iter().enumerate() {
2178 if i > 0 {
2179 out.push(' ');
2180 out.push_str(op.symbol());
2181 out.push(' ');
2182 }
2183 if side.type_ref().erased() == crate::types::JavaType::Boolean {
2184 self.expr_bool(side, out);
2185 } else {
2186 out.push('(');
2187 self.expr(side, 1, out);
2188 out.push_str(" != 0)");
2189 }
2190 }
2191 if parens {
2192 out.push(')');
2193 }
2194 return;
2195 }
2196 }
2197 let p = op.precedence();
2198 self.expr(l, p, out);
2199 out.push(' ');
2200 out.push_str(op.symbol());
2201 out.push(' ');
2202 self.expr(r, p + 1, out);
2203 }
2204 Expr::Cond { c, t, f } => {
2205 self.expr(c, 3, out);
2206 out.push_str(" ? ");
2207 let prev = std::mem::replace(&mut self.in_cond, true);
2208 self.expr(t, 2, out);
2209 out.push_str(" : ");
2210 self.expr(f, 2, out);
2211 self.in_cond = prev;
2212 }
2213 Expr::Assign { target, op, value } => {
2214 // The local's VarTable type is authoritative: booleanize
2215 // flips vt types after the embedded Local tys were frozen
2216 // (Security `boolean var4_122 = 1` printed the int form —
2217 // "int无法转换为boolean").
2218 let tgt_er = match &**target {
2219 Expr::Local { var, .. } => self.vt.var(*var).ty.erased(),
2220 other => other.type_ref().erased(),
2221 };
2222 self.expr(target, 1, out);
2223 out.push(' ');
2224 out.push_str(op.symbol());
2225 out.push(' ');
2226 if matches!(op, crate::ir::expr::AssignOp::Plain) {
2227 // Narrow-target assignments render int constants in the
2228 // target's form (jdk11/17/26 xml Parser: `mESt = ch !=
2229 // 116 ? 512 : 60` against `private char mESt` —
2230 // "从int转换到char可能会有损失").
2231 match tgt_er {
2232 crate::types::JavaType::Boolean => self.expr_bool(value, out),
2233 crate::types::JavaType::Char => self.expr_char(value, out),
2234 crate::types::JavaType::Byte => {
2235 self.expr_narrow(value, &crate::types::JavaType::Byte, out)
2236 }
2237 crate::types::JavaType::Short => {
2238 self.expr_narrow(value, &crate::types::JavaType::Short, out)
2239 }
2240 _ => self.expr(value, 1, out),
2241 }
2242 } else {
2243 self.expr(value, 1, out);
2244 }
2245 }
2246 Expr::PreIncDec { e, delta, .. } => {
2247 out.push_str(if *delta > 0 { "++" } else { "--" });
2248 self.expr(e, 14, out);
2249 }
2250 Expr::PostIncDec { e, delta, .. } => {
2251 self.expr(e, 14, out);
2252 out.push_str(if *delta > 0 { "++" } else { "--" });
2253 }
2254 Expr::Lambda(l) => self.lambda(l, out),
2255 Expr::AnonNew {
2256 base, args, body, ..
2257 } => {
2258 out.push_str("new ");
2259 let base_s = self.type_name(base);
2260 out.push_str(&base_s);
2261 out.push('(');
2262 // Render the ctor args through the base class's matching
2263 // <init> descriptor: an int 0/1 at a boolean parameter
2264 // must print as false/true (jdk11 Console's anonymous
2265 // PrintWriter subclass — `new PrintWriter(out, 1)` finds
2266 // no ctor). Pick the arity-matching ctor whose param
2267 // erasures best fit the actual arg types.
2268 let base_internal = match base {
2269 TypeRef::J(crate::types::JavaType::Object(n)) => Some(n.clone()),
2270 TypeRef::G(crate::types::GenericType::Class(cs)) => {
2271 Some(crate::typeutil::classsig_internal(cs).into())
2272 }
2273 _ => None,
2274 };
2275 // Overload choice for the ctor args (int 0/1 at a boolean
2276 // formal must print false/true) reads the base class's own
2277 // `<init>` set: front-end metadata.
2278 let ctor_params = base_internal
2279 .and_then(|bi| self.ctx.ctor_param_types(&bi, 0, args.len(), args));
2280 match ctor_params {
2281 Some(pt) => self.args_typed(args, &pt, out),
2282 None => self.args(args, out),
2283 }
2284 out.push_str(") {\n");
2285 for line in body.lines() {
2286 for _ in 0..self.indent + 1 {
2287 out.push_str(" ");
2288 }
2289 out.push_str(line.trim_start_matches(' '));
2290 out.push('\n');
2291 }
2292 for _ in 0..self.indent {
2293 out.push_str(" ");
2294 }
2295 out.push('}');
2296 }
2297 Expr::StringConcat(parts) => {
2298 let mut first = true;
2299 // Java semantics: the concatenation must start with a
2300 // String. NOT for an empty parts list: the trailing
2301 // is_empty guard below already prints `""` — both firing
2302 // printed four quotes.
2303 let needs_prefix =
2304 !parts.is_empty() && !matches!(parts.first(), Some(ConcatPart::Const(_)));
2305 if needs_prefix {
2306 out.push_str("\"\"");
2307 first = false;
2308 }
2309 for p in parts {
2310 // Right-hand operands of `+` need parens at equal
2311 // precedence to keep arithmetic grouping (`"t" + (x+1)`).
2312 let is_first = first;
2313 if !first {
2314 out.push_str(" + ");
2315 }
2316 first = false;
2317 match p {
2318 ConcatPart::Const(s) => {
2319 out.push('"');
2320 out.push_str(&escape_string(s));
2321 out.push('"');
2322 }
2323 ConcatPart::Str(e) => self.expr(e, if is_first { 12 } else { 13 }, out),
2324 }
2325 }
2326 if parts.is_empty() {
2327 out.push_str("\"\"");
2328 }
2329 }
2330 Expr::Invokedynamic {
2331 name,
2332 args,
2333 bsm_text,
2334 ..
2335 } => {
2336 if name.starts_with('\u{0}') {
2337 out.push_str("/*bad-cmp*/0");
2338 } else {
2339 out.push_str("/* invokedynamic ");
2340 out.push_str(name);
2341 out.push(' ');
2342 out.push_str(bsm_text);
2343 out.push_str(" */ (");
2344 self.args(args, out);
2345 out.push(')');
2346 }
2347 }
2348 }
2349 if parens {
2350 out.push(')');
2351 }
2352 }
2353
2354 fn args(&mut self, args: &[Expr], out: &mut String) {
2355 for (i, a) in args.iter().enumerate() {
2356 if i > 0 {
2357 out.push_str(", ");
2358 }
2359 self.expr(a, 1, out);
2360 }
2361 }
2362
2363 /// Print call args applying boolean-parameter constant adjustment.
2364 /// Delegation (this(..)/super(..)) args: typed rendering PLUS the
2365 /// elided-upcast restoration when the arg's static type differs from
2366 /// the descriptor formal — overload resolution binds the arg's type,
2367 /// not the descriptor (jdk17 JarEntry copy ctor: `this(je)` resolves
2368 /// recursively to JarEntry(JarEntry); the source `this((ZipEntry) je)`
2369 /// upcast is elided from bytecode because je <: ZipEntry is provable).
2370 fn args_delegation(
2371 &mut self,
2372 args: &[Expr],
2373 param_types: &[crate::types::JavaType],
2374 out: &mut String,
2375 ) {
2376 // Inner-class ctor descriptors carry the synthetic outer param
2377 // while the expression args are outer-stripped: align the formals
2378 // with the TRAIL of the args, like apply_ctor_param_casts (jdk11
2379 // ZipFileInflaterInputStream this(zfin, res, res.getInflater(),
2380 // size) was cast against the shifted descriptor formals —
2381 // (ZipFile) zfin, (ZipFileInputStream) res... x3 inconvertible).
2382 let off = param_types.len().saturating_sub(args.len());
2383 for (i, a) in args.iter().enumerate() {
2384 if i > 0 {
2385 out.push_str(", ");
2386 }
2387 match param_types.get(off + i) {
2388 Some(pt @ crate::types::JavaType::Object(_)) => {
2389 let have = a.type_ref().erased();
2390 // Generically-typed args (typevars/parameterized) are
2391 // already source-typed: casting them to the descriptor
2392 // erasure breaks convertibility to typevar formals
2393 // (jdk17 StreamSpliterators SliceSpliterator.OfPrimitive
2394 // this((Spliterator.OfPrimitive) s, ..) against a
2395 // T_SPLITR formal — OfPrimitive无法转换为T_SPLITR).
2396 if &have != pt
2397 && !matches!(a.type_ref(), TypeRef::G(_))
2398 && !matches!(
2399 a,
2400 Expr::Cast { .. }
2401 | Expr::Const(_)
2402 | Expr::Lambda(_)
2403 | Expr::New { .. }
2404 | Expr::AnonNew { .. }
2405 )
2406 {
2407 out.push('(');
2408 out.push_str(&self.type_name(&TypeRef::J(pt.clone())));
2409 out.push_str(") ");
2410 self.expr(a, 14, out);
2411 continue;
2412 }
2413 self.expr(a, 1, out);
2414 }
2415 Some(crate::types::JavaType::Boolean) => self.expr_bool(a, out),
2416 Some(crate::types::JavaType::Char) => self.expr_char(a, out),
2417 Some(pt @ (crate::types::JavaType::Byte | crate::types::JavaType::Short)) => {
2418 self.expr_narrow_arg(a, pt, out)
2419 }
2420 _ => self.expr(a, 1, out),
2421 }
2422 }
2423 }
2424
2425 fn args_typed(
2426 &mut self,
2427 args: &[Expr],
2428 param_types: &[crate::types::JavaType],
2429 out: &mut String,
2430 ) {
2431 self.args_typed_sam(args, param_types, &[], out)
2432 }
2433
2434 /// args_typed with per-argument SAM-return priming: a lambda actual at
2435 /// a parameterized-SAM formal of a pinned generic ctor gets its body
2436 /// return cast from the formal's instantiated SAM return (jdk11/17/26
2437 /// Collectors.toUnmodifiable*'s finisher `list -> (List<T>)
2438 /// List.of(list.toArray())` — the erased instantiatedMethodType says
2439 /// only List, so the generic cast is recoverable solely from the
2440 /// diamond's resolved formal).
2441 fn args_typed_sam(
2442 &mut self,
2443 args: &[Expr],
2444 param_types: &[crate::types::JavaType],
2445 sam_rets: &[Option<TypeRef>],
2446 out: &mut String,
2447 ) {
2448 for (i, a) in args.iter().enumerate() {
2449 if i > 0 {
2450 out.push_str(", ");
2451 }
2452 match param_types.get(i) {
2453 Some(crate::types::JavaType::Boolean) => self.expr_bool(a, out),
2454 // Char/narrow params: expr_char/expr_narrow render both
2455 // constants AND conditional branches in the target form
2456 // (jdk17 BasicAuthentication `super(!isProxy ? 115 : 112,
2457 // ..)` — the char param needs `!isProxy ? 's' : 'p'`;
2458 // a plain int ternary is "条件表达式中的类型错误").
2459 Some(crate::types::JavaType::Char) => self.expr_char(a, out),
2460 // Byte/short parameters: an int literal argument needs an
2461 // explicit cast (invocation conversion never narrows, even
2462 // for in-range constants) — and so do the branches of an
2463 // int conditional (jdk CompressedResourceHeader
2464 // `buffer.put(isTerminal ? (byte) 1 : (byte) 0)` — the
2465 // byte casts fold away in bytecode; a bare int ternary is
2466 // "对于put(int), 找不到合适的方法" x3 trees).
2467 Some(crate::types::JavaType::Byte) | Some(crate::types::JavaType::Short) => {
2468 self.expr_narrow_arg(a, ¶m_types[i].clone(), out);
2469 }
2470 _ => {
2471 let lam_under_cast = matches!(a, Expr::Lambda(_))
2472 || matches!(a, Expr::Cast { e: ce, .. } if matches!(&**ce, Expr::Lambda(_)));
2473 match sam_rets.get(i).and_then(|x| x.as_ref()) {
2474 Some(t) if lam_under_cast => {
2475 let prev = self.lambda_sam_ret.replace(t.clone());
2476 self.expr(a, 1, out);
2477 self.lambda_sam_ret = prev;
2478 }
2479 _ => self.expr(a, 1, out),
2480 }
2481 }
2482 }
2483 }
2484 }
2485
2486 fn const_val(&self, c: &ConstVal, out: &mut String) {
2487 match c {
2488 ConstVal::Int(i) => out.push_str(&i.to_string()),
2489 ConstVal::Long(l) => {
2490 if *l == i64::MIN {
2491 out.push_str("-9223372036854775808L");
2492 } else {
2493 out.push_str(&format!("{}L", l));
2494 }
2495 }
2496 ConstVal::Float(f) => out.push_str(&format_float(*f as f64, true)),
2497 ConstVal::Double(d) => out.push_str(&format_float(*d, false)),
2498 ConstVal::Str(s) => {
2499 out.push('"');
2500 out.push_str(&escape_string(s));
2501 out.push('"');
2502 }
2503 ConstVal::Null => out.push_str("null"),
2504 ConstVal::ClassLit(t) => {
2505 out.push_str(&self.type_name(t));
2506 out.push_str(".class");
2507 }
2508 }
2509 }
2510
2511 fn lambda(&mut self, l: &crate::ir::expr::LambdaExpr, out: &mut String) {
2512 // A `lambda$...` implementation method in the current class is a
2513 // compiler-generated lambda body, never a real method reference —
2514 // emit the body inline even when classified as a reference (the
2515 // method itself is hidden from the output).
2516 let synthetic_self_lambda =
2517 l.impl_name.starts_with("lambda$") && l.impl_owner == self.ctx.class_name();
2518 match l.kind {
2519 LambdaKind::MethodRef if !synthetic_self_lambda => {
2520 // Determine receiver form.
2521 if l.impl_name == "<init>" {
2522 out.push_str(&self.shorten(&l.impl_owner));
2523 out.push_str("::new");
2524 return;
2525 }
2526 if let Some(recv) = &l.ref_receiver {
2527 out.push_str(&self.shorten(recv));
2528 out.push_str("::");
2529 out.push_str(&l.impl_name);
2530 } else if !l.captures.is_empty() {
2531 // bound receiver: first capture is the instance
2532 // A method-ref/lambda receiver needs its functional
2533 // type spelled out: `A::new::get` parses as a
2534 // QUALIFIED reference and is rejected — the source form
2535 // is `((Supplier<A>) A::new)::get`.
2536 let cap = &l.captures[0];
2537 let func_ty = match cap {
2538 Expr::Lambda(l2) => Some(l2.sam_cls.clone()),
2539 Expr::Cast { ty, e } if matches!(**e, Expr::Lambda(_)) => {
2540 Some(ty.erased().to_descriptor())
2541 }
2542 _ => None,
2543 };
2544 if let Some(f) = func_ty {
2545 out.push_str("((");
2546 out.push_str(&self.shorten(&f));
2547 out.push_str(") ");
2548 self.expr(cap, 1, out);
2549 out.push(')');
2550 } else {
2551 self.expr(cap, 15, out);
2552 }
2553 out.push_str("::");
2554 out.push_str(&l.impl_name);
2555 } else {
2556 out.push_str(&self.shorten(&l.impl_owner));
2557 out.push_str("::");
2558 out.push_str(&l.impl_name);
2559 }
2560 }
2561 _ => {
2562 if self.lambda_depth >= 8 {
2563 out.push_str("/*nested-lambda*/null");
2564 return;
2565 }
2566 // The nested-body preparation — decompiling the impl
2567 // method and running the front-end's idiom recovery
2568 // (anonymous inlining, capture snapshots, enum switches,
2569 // witness casts, outer-this substitution, label pruning,
2570 // ...) — belongs to the front-end: that is where
2571 // machine-specific desugaring lives. Ask it for a finished
2572 // statement tree and print that.
2573 // The nested-body preparation — decompiling the impl method
2574 // and running the front-end's idiom recovery (anonymous
2575 // inlining, capture snapshots, enum switches, witness casts,
2576 // outer-this substitution, label pruning, ...) — belongs to
2577 // the front-end: that is where machine-specific desugaring
2578 // lives. Ask it for a finished statement tree and print that.
2579 let nested = self.ctx.nested_method(l, self.vt);
2580 // params: prefer the impl method's own parameter names so the
2581 // printed parameter list matches the body's references
2582 // (instance lambda impls carry only the SAM params).
2583 let mut pnames = l.param_names.clone();
2584 if let Some(MethodBody { vt, .. }) = &nested {
2585 let mut vt_params: Vec<String> = vt
2586 .vars
2587 .iter()
2588 .filter(|v| v.is_param && v.name != "this")
2589 .map(|v| v.name.clone())
2590 .collect();
2591 if vt_params.len() == pnames.len() {
2592 pnames = vt_params;
2593 } else if vt_params.len() > pnames.len() {
2594 // The impl method's signature is (captures..., SAM
2595 // params...): take the TRAILING SAM slice so the
2596 // printed parameter list matches the body's variable
2597 // references (ConcurrentMap.replaceAll printed
2598 // `(x0, x1) -> { .. replace(k, v, ..) }` — undefined
2599 // symbols; the captured `function` occupied the first
2600 // impl slot, breaking the exact-length alignment).
2601 let n = pnames.len();
2602 pnames = vt_params.split_off(vt_params.len() - n);
2603 }
2604 }
2605 let single = pnames.len() == 1;
2606 if !single {
2607 out.push('(');
2608 }
2609 for (i, n) in pnames.iter().enumerate() {
2610 if i > 0 {
2611 out.push_str(", ");
2612 }
2613 out.push_str(n);
2614 }
2615 if !single {
2616 out.push(')');
2617 }
2618 out.push_str(" -> ");
2619 let sam_wrap = self.lambda_sam_ret.take();
2620 match nested {
2621 Some(MethodBody {
2622 mut body, mut vt, ..
2623 }) => {
2624 // Single-return body → expression lambda.
2625 let mut single_expr = match &body {
2626 Stmt::Return(Some(e)) => Some(e.clone()),
2627 Stmt::Block(v) if v.len() == 1 => match &v[0] {
2628 Stmt::Return(Some(e)) => Some(e.clone()),
2629 _ => None,
2630 },
2631 _ => None,
2632 };
2633 // Witness the instantiated SAM return on the body's
2634 // returns: the impl method is erased, so `i -> i`
2635 // under `(Function<I,R>)` fails inference without
2636 // `(R) i`.
2637 fn sam_ok(t: &TypeRef, e: &Expr) -> bool {
2638 !matches!(e, Expr::Cast { .. } | Expr::Const(_)) && e.type_ref() != *t
2639 }
2640 fn wrap_returns(s: &mut Stmt, t: &TypeRef) {
2641 match s {
2642 Stmt::Return(Some(e)) => {
2643 if sam_ok(t, e) {
2644 let v = std::mem::replace(e, Expr::This);
2645 *e = Expr::Cast {
2646 ty: t.clone(),
2647 e: Box::new(v),
2648 };
2649 }
2650 }
2651 Stmt::Block(v) => v.iter_mut().for_each(|x| wrap_returns(x, t)),
2652 Stmt::If {
2653 then_stmt,
2654 else_stmt,
2655 ..
2656 } => {
2657 wrap_returns(then_stmt, t);
2658 if let Some(x) = else_stmt {
2659 wrap_returns(x, t);
2660 }
2661 }
2662 Stmt::While { body, .. }
2663 | Stmt::DoWhile { body, .. }
2664 | Stmt::ForEach { body, .. }
2665 | Stmt::Labeled { body, .. }
2666 | Stmt::Synchronized { body, .. } => wrap_returns(body, t),
2667 Stmt::For { init, body, .. } => {
2668 init.iter_mut().for_each(|i| wrap_returns(i, t));
2669 wrap_returns(body, t);
2670 }
2671 Stmt::Switch { cases, default, .. } => {
2672 for c in cases.iter_mut() {
2673 for st in c.body.iter_mut() {
2674 wrap_returns(st, t);
2675 }
2676 }
2677 if let Some(d) = default {
2678 wrap_returns(d, t);
2679 }
2680 }
2681 Stmt::Try {
2682 body,
2683 catches,
2684 finally,
2685 } => {
2686 wrap_returns(body, t);
2687 for c in catches.iter_mut() {
2688 wrap_returns(&mut c.body, t);
2689 }
2690 if let Some(f) = finally {
2691 wrap_returns(f, t);
2692 }
2693 }
2694 _ => {}
2695 }
2696 }
2697 if let Some(t) = &sam_wrap {
2698 if let Some(e) = &mut single_expr {
2699 if sam_ok(t, e) {
2700 let v = std::mem::replace(e, Expr::This);
2701 *e = Expr::Cast {
2702 ty: t.clone(),
2703 e: Box::new(v),
2704 };
2705 } else if let TypeRef::G(_) = t {
2706 // The body already carries the erasure
2707 // checkcast: retype it to the generic
2708 // SAM return (jdk26
2709 // CopyOnWriteArrayList.toArray `i ->
2710 // (T[]) new Object[i]` printed
2711 // `(Object[])` — Object[]无法转换为T[]
2712 // against IntFunction<T[]>).
2713 if let Expr::Cast { ty: ct, e: ce } = e {
2714 if ct.erased() == t.erased()
2715 && !matches!(&**ce, Expr::Cast { .. })
2716 {
2717 *ct = t.clone();
2718 }
2719 }
2720 }
2721 } else {
2722 wrap_returns(&mut body, t);
2723 }
2724 } else if let Some(inst) = &l.inst_sam_desc {
2725 if crate::dbg_flag!("JCDC_DBG_LAMRET") {
2726 eprintln!(
2727 "LAMRET impl={}.{} inst_ret={:?} single={}",
2728 l.impl_owner,
2729 l.impl_name,
2730 inst.ret,
2731 single_expr.is_some()
2732 );
2733 }
2734 // The invokedynamic's instantiatedMethodType
2735 // records the lambda's inferred return at the
2736 // call site; a source upcast can be elided from
2737 // the bytecode when provable (jdk17
2738 // JrtFileSystem.iteratorOf: `(Path)` around
2739 // path.resolve(..) inside map(child -> ...) —
2740 // JrtPath <: Path needs no checkcast, but
2741 // without the cast map infers Stream<JrtPath>
2742 // and .iterator() fails the Iterator<Path>
2743 // return). Restore it when the expression body
2744 // is typed a strict subtype of the recorded
2745 // return.
2746 fn upcast_ok(
2747 e: &Expr,
2748 target: &crate::types::JavaType,
2749 ctx: &dyn crate::ctx::Ctx,
2750 ) -> bool {
2751 let crate::types::JavaType::Object(t) = target else {
2752 return false;
2753 };
2754 // A parameterized (generic) value whose
2755 // erasure IS the target reaches it unchecked
2756 // (jdk17 CompletionStage exceptionallyCompose:
2757 // the cond branch fn.apply(ex) types as the
2758 // capture ? extends CompletionStage<T>; the
2759 // erased impl return CompletionStage needs no
2760 // cast, and printing one breaks the outer
2761 // chain's inference).
2762 if let TypeRef::G(crate::types::GenericType::Class(cs)) =
2763 e.type_ref()
2764 {
2765 if crate::typeutil::classsig_internal(&cs).as_str() == t.as_ref() {
2766 return true;
2767 }
2768 }
2769 let crate::types::JavaType::Object(e0) = e.type_ref().erased()
2770 else {
2771 return false;
2772 };
2773 if &e0 == t {
2774 return false;
2775 }
2776 let mut queue = vec![e0];
2777 let mut seen = std::collections::HashSet::new();
2778 while let Some(cur) = queue.pop() {
2779 if !seen.insert(cur.clone()) {
2780 continue;
2781 }
2782 if !ctx.has_class(&cur) {
2783 continue;
2784 }
2785 for (sup, _) in ctx.class_supers_args(&cur, &[]) {
2786 if sup.as_str() == t.as_ref() {
2787 return true;
2788 }
2789 queue.push(sup.into());
2790 }
2791 }
2792 false
2793 }
2794 let want = TypeRef::J(inst.ret.clone());
2795 // The sam_wrap prime (declared local / pinned
2796 // ctor formal / generic-call formal) carries the
2797 // GENERIC SAM return the erased
2798 // instantiatedMethodType lost: upgrade an
2799 // existing erasure-equal cast on the body (jdk26
2800 // CopyOnWriteArrayList.toArray's `i -> (T[]) new
2801 // Object[i]` printed `(Object[])` — the real
2802 // checkcast erases T[] and Object[] alike;
2803 // Object[]无法转换为T[] against
2804 // IntFunction<T[]>).
2805 let g_want: Option<TypeRef> = sam_wrap.as_ref().and_then(|t| {
2806 if let TypeRef::G(g) = t {
2807 if TypeRef::G(g.clone()).erased() == inst.ret {
2808 return Some(t.clone());
2809 }
2810 }
2811 None
2812 });
2813 if let Some(e) = &mut single_expr {
2814 if crate::dbg_flag!("JCDC_DBG_LAMRET") {
2815 eprintln!(
2816 "LAMRET2 inst_ret={:?} expr_ty={:?} sam_ok={} upcast_ok={} g_want={:?}",
2817 inst.ret,
2818 e.type_ref(),
2819 sam_ok(&want, e),
2820 upcast_ok(e, &inst.ret, self.ctx),
2821 g_want
2822 );
2823 }
2824 let mut upgraded = false;
2825 if let Some(gw) = &g_want {
2826 if let Expr::Cast { ty, e: ce } = e {
2827 if ty.erased() == inst.ret
2828 && !matches!(&**ce, Expr::Cast { .. })
2829 {
2830 *ty = gw.clone();
2831 upgraded = true;
2832 }
2833 }
2834 }
2835 if !upgraded
2836 && sam_ok(&want, e)
2837 && upcast_ok(e, &inst.ret, self.ctx)
2838 {
2839 let v = std::mem::replace(e, Expr::This);
2840 *e = Expr::Cast {
2841 ty: want,
2842 e: Box::new(v),
2843 };
2844 }
2845 }
2846 }
2847 // A nested lambda body shares the ENCLOSING
2848 // lambda's scope rules: its own locals must not
2849 // redeclare names visible there (jdk26
2850 // MethodHandleProxies.createTemplate — the clb
2851 // lambda's foreach-desugared `i$`/`mi` collided
2852 // with the nested cob lambda's own `i$`/`mi`,
2853 // 已在方法中定义了变量 x2). Rename the inner
2854 // impl's non-param locals on collision; the
2855 // method-level twin is handled by
2856 // disambiguate_lambda_locals.
2857 {
2858 let mut outer_names: std::collections::HashSet<&str> =
2859 self.vt.vars.iter().map(|v| v.name.as_str()).collect();
2860 outer_names.extend(self.outer_names.iter().map(|n| n.as_str()));
2861 let mut used: std::collections::HashSet<String> =
2862 vt.vars.iter().map(|v| v.name.clone()).collect();
2863 for v in vt.vars.iter_mut() {
2864 if v.is_param || !outer_names.contains(v.name.as_str()) {
2865 continue;
2866 }
2867 let base = v.name.clone();
2868 let mut k = 1;
2869 loop {
2870 let cand = format!("{}${}", base, k);
2871 if !used.contains(&cand) && !outer_names.contains(cand.as_str())
2872 {
2873 used.insert(cand.clone());
2874 v.name = cand;
2875 break;
2876 }
2877 k += 1;
2878 }
2879 }
2880 }
2881 let mut sub = Printer {
2882 ctx: self.ctx,
2883 vt: &vt,
2884 out: String::new(),
2885 line_buf: String::new(),
2886 indent: self.indent,
2887 lambda_depth: self.lambda_depth + 1,
2888 ignored_seq: self.ignored_seq,
2889 outer_names: {
2890 let mut n = self.outer_names.clone();
2891 n.extend(self.vt.vars.iter().map(|v| v.name.clone()));
2892 n
2893 },
2894 // The SAM's return type governs the impl
2895 // body's renders: boolean SAMs must print
2896 // `return true;` not the JVM-int `return 1;`
2897 // (jdk26 Gatherers.fold's ofGreedy lambda).
2898 ret_bool: l.sam_desc.ret == crate::types::JavaType::Boolean,
2899 ret_char: l.sam_desc.ret == crate::types::JavaType::Char,
2900 ret_byte: l.sam_desc.ret == crate::types::JavaType::Byte,
2901 ret_short: l.sam_desc.ret == crate::types::JavaType::Short,
2902 suppress_poly_cast: false,
2903 suppress_diamond: false,
2904 // A lambda body is a fresh expression context:
2905 // the enclosing conditional's pre-8 non-poly
2906 // rule does not propagate into it (the lambda
2907 // is a standalone method body).
2908 in_cond: false,
2909 lambda_sam_ret: None,
2910 ret_sam: None,
2911 twin_cache: self.twin_cache.clone(),
2912 };
2913 if let Some(e) = single_expr {
2914 if l.sam_desc.ret == crate::types::JavaType::Boolean {
2915 sub.expr_bool(&e, out);
2916 } else {
2917 sub.expr(&e, 1, out);
2918 }
2919 } else {
2920 out.push_str("{\n");
2921 sub.indent += 1;
2922 sub.stmt(&body);
2923 let text = sub.out;
2924 out.push_str(&text);
2925 for _ in 0..self.indent {
2926 out.push_str(" ");
2927 }
2928 out.push('}');
2929 }
2930 }
2931 None => {
2932 out.push_str("/* lambda body in ");
2933 out.push_str(&l.impl_owner);
2934 out.push('.');
2935 out.push_str(&l.impl_name);
2936 out.push_str(" */ {}");
2937 }
2938 }
2939 }
2940 }
2941 }
2942
2943 // ---------------- names & types ----------------
2944
2945 /// True if `cls` is a member inner class (declares this$0) per the pool.
2946 /// Parameter types of the `<init>` matching `skip + n` descriptor args,
2947 /// returning the tail after `skip` leading synthetic params. Used to
2948 /// print `new` arguments with boolean/char constant adjustment.
2949 fn ctor_param_types(
2950 &self,
2951 cls: &str,
2952 skip: usize,
2953 n: usize,
2954 args: &[Expr],
2955 ) -> Option<Vec<crate::types::JavaType>> {
2956 // Overload/parameter recovery from the class's own `<init>` set is
2957 // container metadata: the front-end answers it.
2958 self.ctx.ctor_param_types(cls, skip, n, args)
2959 }
2960
2961 fn is_member_inner(&self, cls: &str) -> bool {
2962 // Front-end metadata question: synthetic outer field, or an enclosing
2963 // instance forwarded to super?
2964 if self.ctx.class_has_this0(cls) {
2965 return true;
2966 }
2967 if !cls.contains('$') || self.ctx.nested_is_static(cls) {
2968 return false;
2969 }
2970 self.ctx.outer_param_via_super(cls)
2971 }
2972
2973 /// Is `cls` lexically enclosing the CURRENT class in the RENDERED
2974 /// layout? Digit-tail classes (anonymous/d8-lambda shapes) and
2975 /// `-`-tail classes (Kotlin `X$-CC` facades — `-` is not a Java
2976 /// identifier start, so the class renders as a flat mangled
2977 /// top-level file, mirroring ddc-dec's clean_member_tail) are
2978 /// emitted as separate flat top-level files — the nested lexical
2979 /// scope they would provide does not exist there, so members of an
2980 /// outer class must be QUALIFIED from them (weibo
2981 /// CronetUrlRequest$3: bare `_$$Nest$misDoneLocked(..)` calls of
2982 /// the outer's statics were unresolvable).
2983 fn renders_nested_in(&self, cls: &str) -> bool {
2984 let cur = self.ctx.class_name();
2985 if !cur.starts_with(&format!("{}$", cls)) {
2986 return false;
2987 }
2988 let mut c = cur.to_string();
2989 while c.as_str() != cls {
2990 let tail = c.rsplit('$').next().unwrap_or(&c);
2991 if tail.is_empty()
2992 || tail.chars().next().is_some_and(|ch| ch.is_ascii_digit())
2993 || tail.starts_with('-')
2994 {
2995 return false; // flat-rendered boundary: no lexical scope
2996 }
2997 match c.rfind('$') {
2998 Some(i) => c.truncate(i),
2999 None => return false,
3000 }
3001 }
3002 true
3003 }
3004
3005 /// Instantiated SAM return for a cast to a generic functional
3006 /// interface (`(Function<I,R>) lambda`): resolves the interface's SAM
3007 /// method Signature return against the cast's type arguments. Only
3008 /// meaningful when the result still contains a type variable — the
3009 /// erased impl body then needs `(R) value` witnesses on its returns
3010 /// (javac: "return type I cannot be converted to R" for `i -> i`).
3011 fn sam_ret_cast(&self, g: &crate::types::GenericType, sam_name: &str) -> Option<TypeRef> {
3012 // Resolving a functional interface's SAM return against a cast's type
3013 // arguments reads the interface's method signatures: front-end
3014 // metadata.
3015 self.ctx.sam_ret_cast(g, sam_name)
3016 }
3017
3018 /// `<>` when `new cls(...)` should carry a diamond: the class is
3019 /// generic (class-level Signature with type params) and THIS file is
3020 /// Java 7+. A bare generic new compiles under old-style inference
3021 /// (standalone, not target-typed), which collapses to Object when
3022 /// implicitly-typed lambda args are involved — jdk11 Collectors.
3023 /// summingInt's `new CollectorImpl<>(() -> new int[1], (a, t) -> ...)`
3024 /// fails as bare `new CollectorImpl(...)` ("array required, but found
3025 /// Object", 72 errors in the concurrent-family closure). Bytecode
3026 /// cannot distinguish diamond from bare, so always prefer the diamond
3027 /// for generic classes.
3028 fn diamond_for(&self, cls: &str) -> &'static str {
3029 if self.ctx.source_level() < 51 {
3030 return "";
3031 }
3032 if self.ctx.class_declares_generics(cls) {
3033 "<>"
3034 } else {
3035 ""
3036 }
3037 }
3038
3039 /// Shorten an internal class name for emission: java.lang.* and same
3040 /// package use simple names; others fully qualified dotted.
3041 /// True when `cls.name` is a PRIVATE instance field and the owner
3042 /// expression's compile-time type is a strict subclass of cls: the
3043 /// field is not in the subclass's member scope, so the source must
3044 /// cast the owner to the declaring class
3045 /// (`((MessageDigest)this).algorithm` — jdk11 Delegate.clone x3,
3046 /// Signature.clone).
3047 fn private_super_field(&self, cls: &str, name: &str, o: &Expr) -> bool {
3048 if matches!(o, Expr::Raw(_) | Expr::RawT(..)) {
3049 return false;
3050 }
3051 let owner_ct = if matches!(o, Expr::This) {
3052 self.ctx.class_name().into()
3053 } else {
3054 match o.type_ref().erased() {
3055 crate::types::JavaType::Object(n) => n,
3056 _ => return false,
3057 }
3058 };
3059 if owner_ct.as_ref() == cls {
3060 return false;
3061 }
3062 let Some(flags) = self.ctx.field_flags(cls, name) else {
3063 return false;
3064 };
3065 if flags.contains(crate::types::FieldAccessFlags::STATIC)
3066 || !flags.contains(crate::types::FieldAccessFlags::PRIVATE)
3067 {
3068 return false;
3069 }
3070 // cls must be a strict superclass of the owner's compile-time type.
3071 let mut cur = owner_ct;
3072 for _ in 0..64 {
3073 let Some(sup) = self.ctx.super_name(&cur) else {
3074 return false;
3075 };
3076 if sup == cls {
3077 return true;
3078 }
3079 cur = sup.into();
3080 }
3081 false
3082 }
3083
3084 fn needs_owner_cast(
3085 &self,
3086 cls: &str,
3087 name: &str,
3088 desc: &crate::types::MethodDescriptor,
3089 o: &Expr,
3090 ) -> bool {
3091 // Raw-rendered owners (qualified `HashMap.this`, substituted
3092 // capture text) carry no trustworthy static type — and casting
3093 // them to a RAW class erases the whole generic member chain
3094 // (`((HashMap) HashMap.this).<T>keysToArray(..)` made the call
3095 // raw: "Object[]无法转换为T[]").
3096 if matches!(o, Expr::Raw(_) | Expr::RawT(..) | Expr::This) {
3097 return false;
3098 }
3099 let crate::types::JavaType::Object(on) = o.type_ref().erased() else {
3100 return false;
3101 };
3102 if on.as_ref() == cls {
3103 return false;
3104 }
3105 // A receiver widened to Object (Kotlin `when` materialization
3106 // residue — every branch's value lowered into one slot) cannot
3107 // resolve ANY member: cast to the invoke's resolved class. The
3108 // bytecode guarantees the runtime type (invokevirtual dispatch
3109 // on exactly this object), so the cast is always honest.
3110 if on.as_ref() == "java/lang/Object" && cls != "java/lang/Object" {
3111 return true;
3112 }
3113 let want = format!(
3114 "({}){}",
3115 desc.args
3116 .iter()
3117 .map(|t| t.to_descriptor())
3118 .collect::<String>(),
3119 desc.ret.to_descriptor()
3120 );
3121 // The receiver's static type is a strict SUPERTYPE of the
3122 // resolved class (register reuse left the vt at the supertype):
3123 // the member lives on `cls`, and the downcast is exactly what
3124 // the bytecode's resolution performed. ONLY when the owner type
3125 // cannot resolve the member itself: an interface-typed owner
3126 // whose IMPL the dex named resolves fine through the
3127 // interface, and casting to the impl sprinkles obscured/flat
3128 // impl names into expression position (weixin +3.3k
3129 // cannot-find when this fired unguarded).
3130 if self.ctx.is_subtype_of(
3131 &crate::types::JavaType::Object(std::sync::Arc::from(cls)),
3132 on.as_ref(),
3133 ) && self.ctx.method_flags(on.as_ref(), name, &want).is_none()
3134 {
3135 return true;
3136 }
3137 let Some(acc) = self.ctx.method_flags(cls, name, &want) else {
3138 return false;
3139 };
3140 use crate::types::MethodAccessFlags as M;
3141 if acc.contains(M::PRIVATE) {
3142 return true;
3143 }
3144 if !acc.contains(M::PUBLIC) && !acc.contains(M::PROTECTED) {
3145 fn pkg(n: &str) -> &str {
3146 n.rsplit_once('/').map(|(p, _)| p).unwrap_or("")
3147 }
3148 return pkg(&on) != pkg(cls);
3149 }
3150 false
3151 }
3152
3153 fn needs_object_relay(&self, ty: &TypeRef, e: &Expr) -> bool {
3154 if matches!(e, Expr::Cast { .. } | Expr::Const(_)) {
3155 return false;
3156 }
3157 let (crate::types::JavaType::Object(from), crate::types::JavaType::Object(to)) =
3158 (e.type_ref().erased(), ty.erased())
3159 else {
3160 return false;
3161 };
3162 if from == to || from.as_ref() == "java/lang/Object" || to.as_ref() == "java/lang/Object" {
3163 return false;
3164 }
3165 // A KNOWN interface on either side keeps the direct form legal
3166 // (casts/instanceof against an interface compile regardless of
3167 // the operand's class).
3168 let known_itf = |n: &str| self.ctx.has_class(n) && self.ctx.is_interface(n);
3169 if known_itf(&from) || known_itf(&to) {
3170 if self.ctx.has_class(&from) && self.ctx.has_class(&to) {
3171 if self.ctx.is_subtype_of(&e.type_ref().erased(), &to)
3172 || self.ctx.is_subtype_of(&ty.erased(), &from)
3173 {
3174 return false;
3175 }
3176 return self.ctx.is_sealed(&from) || self.ctx.is_sealed(&to);
3177 }
3178 return false;
3179 }
3180 if self.ctx.has_class(&from) && self.ctx.has_class(&to) {
3181 if self.ctx.is_subtype_of(&e.type_ref().erased(), &to)
3182 || self.ctx.is_subtype_of(&ty.erased(), &from)
3183 {
3184 return false;
3185 }
3186 let both_classes = !self.ctx.is_interface(&from) && !self.ctx.is_interface(&to);
3187 return both_classes || self.ctx.is_sealed(&from) || self.ctx.is_sealed(&to);
3188 }
3189 // Off-pool (framework) side: the hierarchy is unknowable here.
3190 // A direct cast fails exactly when both sides are classes and
3191 // unrelated — treat unknowns as classes (java/lang/Throwable,
3192 // Error, android.media.MediaCodec$CodecException all are) and
3193 // relay through Object; the relay never changes cast semantics
3194 // (`(T) e` vs `(T)(Object) e` — same runtime check), it only
3195 // widens compile legality (weixin EncoderWriter
3196 // `(CodecException) error2` with error2: Error, ry0/d4
3197 // `(k) th3x` with th3x: Throwable — 不兼容的类型 ×250+).
3198 true
3199 }
3200
3201 pub fn shorten(&self, internal: &str) -> String {
3202 // NOTE: deliberately NOT memoized across Printers — shorten_inner
3203 // consults per-Printer state (the emitting class's package via
3204 // ctx.class_name, its fields, and this method's vt.vars for the
3205 // shadowed-simple-name check), so the result is not a pure
3206 // function of (pool, internal).
3207 // Class-file names may contain characters Java cannot parse
3208 // (R8 desugared `Collection$-EL`) — EVERY return path runs the
3209 // deterministic sanitizer (early returns bypassed it).
3210 sanitize_source_name(&self.shorten_inner(internal, true))
3211 }
3212
3213 /// Like `shorten` but WITHOUT the anonymous-class → interface/super
3214 /// fallback: used at `new <cls>` sites so a d8/R8-desugared lambda
3215 /// class (which ends in `$<digits>` like an anonymous class) prints as
3216 /// its concrete, instantiable binary name instead of its abstract SAM
3217 /// interface. Type positions keep using `shorten` (interface), so the
3218 /// declaration and the constructor disagree in the correct direction:
3219 /// `Function0 v = new Outer$..$log$1(..)`.
3220 pub fn shorten_concrete(&self, internal: &str) -> String {
3221 // Field-obscured package first segments (JLS 6.4.2): the
3222 // qualified render is captured by the field, but the simple
3223 // resolves through the file's import (JLS 7.5.1 legally
3224 // shadows same-package siblings — the blocked set proved this
3225 // file uses none of them). Static-member qualifiers printed
3226 // qualified through the capture (lark pq/e: field `e2` ate
3227 // `e2.c.b(..)` — "变量 c" ×47); digit-tail names never reach
3228 // here (obscured_render_pub rejects un-importable simples).
3229 if let Some(simple) = self.ctx.obscured_simple(internal) {
3230 return sanitize_source_name(&simple);
3231 }
3232 sanitize_source_name(&self.shorten_inner(internal, false))
3233 }
3234
3235 /// Nesting-aware display chain: a `$` boundary dots ONLY when the
3236 /// prefix has a resolvable outer (a true member); when the prefix
3237 /// is itself an emission-unit top-level (R8 deleted the outer —
3238 /// weixin matrix `JiffiesMonitorFeature` gone, `$JiffiesSnapshot`
3239 /// survives as a flat file), its `$` stays and the member tail dots
3240 /// onto it: `...JiffiesMonitorFeature$JiffiesSnapshot.ThreadJiffiesEntry`.
3241 /// Blind `$`→`.` rendered a chain through the missing type
3242 /// ("是在不可访问的类或接口中定义的").
3243 fn nested_display(&self, internal: &str) -> String {
3244 if let Some(o) = self.ctx.find_outer(internal) {
3245 // The nesting boundary must be a literal `$` — a pool prefix
3246 // followed by another char (`c$1` inside `c$1-IA`) is not an
3247 // outer of this name.
3248 if internal.len() > o.len() + 1
3249 && internal.starts_with(&o)
3250 && internal.as_bytes()[o.len()] == b'$'
3251 {
3252 let tail = &internal[o.len() + 1..];
3253 if !tail.is_empty() && !tail.starts_with('$') && !tail.contains('/') {
3254 // The tail may span several member levels
3255 // (`a17$a18`): below a RESOLVED outer they are all
3256 // inline members of the family file — dot them.
3257 return format!(
3258 "{}.{}",
3259 self.nested_display(&o),
3260 tail.replace('$', ".")
3261 );
3262 }
3263 }
3264 }
3265 // Base: a POOL class with no resolvable outer is a flat `$`-named
3266 // emission unit — keep the `$` (its file name carries it). An
3267 // off-pool name is a framework member class (android.jar's
3268 // `LinearLayout$LayoutParams`) — dot it like the old blind
3269 // replace; the jar declares it as a member.
3270 if self.ctx.has_class(internal) {
3271 internal.replace('/', ".")
3272 } else {
3273 internal.replace(['/', '$'], ".")
3274 }
3275 }
3276
3277 /// Walk the MEMBER-TYPE scope of the emitting class: every lexical
3278 /// `$`-outer level, and at each level its superclass chain and direct
3279 /// interfaces — JLS 8.1.6: member types are INHERITED into scope, so
3280 /// a superclass's nested `a` captures the bare simple name `a` exactly
3281 /// like an own nestee (weixin pk4.d extends k0: same-package class ref
3282 /// `a.d` bound to inherited k0$a — "找不到符号 变量 d, 位置: 类 a").
3283 /// `f` is called with each in-scope class's internal name; the walk
3284 /// stops early when `f` returns true.
3285 fn scope_member_walk<F: FnMut(&str) -> bool>(&self, f: &mut F) -> bool {
3286 let mut cur: &str = self.ctx.class_name();
3287 loop {
3288 let mut stack: Vec<String> = vec![cur.to_string()];
3289 let mut seen: crate::FxHashSet<String> = crate::FxHashSet::default();
3290 while let Some(c) = stack.pop() {
3291 if !seen.insert(c.clone()) {
3292 continue;
3293 }
3294 if f(&c) {
3295 return true;
3296 }
3297 if let Some((ifaces, sup)) = self.ctx.class_bases(&c) {
3298 for i in ifaces {
3299 stack.push(i);
3300 }
3301 if let Some(s) = sup {
3302 if s != "java/lang/Object" {
3303 stack.push(s);
3304 }
3305 }
3306 }
3307 }
3308 match cur.rfind('$') {
3309 Some(i) => cur = &cur[..i],
3310 None => break,
3311 }
3312 }
3313 false
3314 }
3315
3316 fn shorten_inner(&self, internal: &str, anon_fallback: bool) -> String {
3317 if internal.is_empty() {
3318 return String::new();
3319 }
3320
3321 // An import-resolved obscured reference renders its simple name
3322 // (the qualified form binds to an in-scope class — JLS 6.4.2).
3323 if let Some(simple) = self.ctx.obscured_simple(internal) {
3324 return simple;
3325 }
3326 // Case-collision renames (`X/Cua` → `X/Cua_2`): the registry is
3327 // empty for ordinary corpora — one relaxed atomic load.
3328 let orig_internal = internal;
3329 // Framework-shadow stub: the reference means the PLATFORM class —
3330 // the raw FQN (only the stub's own file identity relocated).
3331 let cow = if self.ctx.is_fw_shadow(internal) {
3332 std::borrow::Cow::Borrowed(internal)
3333 } else {
3334 crate::rename::apply_class_rename(internal)
3335 };
3336 let internal: &str = &cow;
3337 // Literal-$ top-level class (in pool, no InnerClasses nesting
3338 // evidence): the $ is part of the SOURCE name (jextract-generated
3339 // errno_h$shared) — never dot it into a nested qualifier. Same rule
3340 // whenever dotting could not parse: `DolTest2$$dollah$$` has empty
3341 // segments, and `$` is a legal identifier character while `A..b` is
3342 // not.
3343 let dot_safe = |simple: &str| -> bool {
3344 // A LEADING `$` (`$Gson$Types`) is part of the source name —
3345 // dotting it yields `.Gson.Types` with a leading dot.
3346 simple.split('$').all(|seg| {
3347 !seg.is_empty()
3348 && seg
3349 .chars()
3350 .next()
3351 .map(|c| c.is_ascii_alphabetic() || c == '_')
3352 .unwrap_or(false)
3353 })
3354 };
3355 let simple_here = internal.rsplit('/').next().unwrap_or(internal).to_string();
3356 // Identifier-unsafe characters ANYWHERE in the name (Kotlin's
3357 // `-IA`/`-EL` hyphen markers: `org/a/c/c$1-IA`; R8 unicode
3358 // obfuscation: the Thai/Yi/Syriac classes of bin.mt.plus,
3359 // ejfkdev/ddc#4) are not source identifiers and can never be
3360 // nested members or local classes — they emit as FLAT sanitized
3361 // files, so references must render the same sanitized full name
3362 // (`_u<hex>` escapes on BOTH sides). The local-class digit-strip
3363 // path mangled them (`1-IA` → `-IA` → `_IA`, weibo ×157), and a
3364 // raw-unicode ref never resolves against the escaped decl.
3365 if !internal
3366 .chars()
3367 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$' || c == '/')
3368 {
3369 let dotted = sanitize_source_name(&internal.replace('/', "."));
3370 // NESTED member whose tail is structurally clean (starts an
3371 // identifier) but carries unsafe characters (weibo's Kotlin
3372 // `header/a$a-IA` → member `class a_u2dIA` INSIDE a.java):
3373 // the reference must dot the `$` boundary like the decl side
3374 // does — the flat `header.a$a_u2dIA` resolves to nothing
3375 // (找不到符号 类 ×~500: b2/a$a_u2dIA/b$a_u2dIA families).
3376 // Digit-start tails (`j$1-IA`) are flat emission-unit files
3377 // KEEPING the `$`, and non-pool names (framework
3378 // `Collection$-EL`) have no decl at all — both stay flat.
3379 if !simple_here.contains("$$ExternalSynthetic") {
3380 if let Some(i) = internal.rfind('$') {
3381 let tail = &internal[i + 1..];
3382 let outer = &internal[..i];
3383 let tail_clean = tail.chars().next().is_some_and(|c| {
3384 (c.is_ascii_alphabetic() || c == '_') && !c.is_ascii_digit()
3385 });
3386 let outer_safe = outer
3387 .chars()
3388 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$' || c == '/');
3389 // has_class on BOTH forms: when an outer rename rule
3390 // moved the family (obscuring a → a2), `internal` is
3391 // the DISPLAY chain and the pool key is the original
3392 // (weibo page/discover a$a-IA displayed under a2).
3393 if tail_clean
3394 && outer_safe
3395 && (self.ctx.has_class(internal)
3396 || self.ctx.has_class(orig_internal))
3397 {
3398 return format!(
3399 "{}.{}",
3400 sanitize_source_name(&outer.replace('/', ".")),
3401 sanitize_source_name(tail)
3402 );
3403 }
3404 }
3405 }
3406 return dotted;
3407 }
3408 // d8's synthetic outline/lambda/backport classes
3409 // (`X$$ExternalSyntheticLambda0`, `…ApiModelOutline0`,
3410 // `…BackportWithForwarding0`) are TOP-LEVEL synthetics emitted as
3411 // flat files with their full `$` name. The local-class digit-strip
3412 // path below mangles them to the bare innermost segment
3413 // (`ExternalSyntheticBackportWithForwarding0`) when the outer chain
3414 // has a digit segment (`PreviewView$1$$…`), which resolves to
3415 // nothing cross-package ("找不到符号 变量 ExternalSynthetic…", weibo
3416 // ×467). Render the full dotted name, like the hyphen case.
3417 if simple_here.contains("$$ExternalSynthetic") {
3418 return sanitize_source_name(&internal.replace('/', "."));
3419 }
3420 let keep_dollar_pool = internal.contains('$')
3421 && self.ctx.has_class(internal)
3422 && self.ctx.find_outer(internal).is_none();
3423 // R8 desugared-library names carry `$` inside the PACKAGE path
3424 // (`j$/util/Collection$-EL`): a `$` followed by `/` is never a
3425 // nesting boundary — dotting it produced `j..util`.
3426 let dollar_in_pkg = internal.contains("$/");
3427 let keep_dollar = keep_dollar_pool
3428 || dollar_in_pkg
3429 || (internal.contains('$') && !dot_safe(&simple_here));
3430 // Anonymous class types (all-digit last segment) have no source
3431 // name: print the base interface/superclass instead. Skipped for
3432 // `new <cls>` sites (anon_fallback=false): a d8/R8-desugared
3433 // LAMBDA class also ends in `$<digits>` (`...$lambda$N$$inlined
3434 // $log$1`, `Outer$$ExternalSyntheticLambda0`) but IS a concrete,
3435 // pool-rendered class — printing its SAM interface there yields an
3436 // invalid `new Iface(..)` ("a是抽象的; 无法实例化", the biggest
3437 // abstract-instantiation family on Kotlin corpora: v6.a/l/p =
3438 // Function0/1/2). The var/phi TYPE positions keep the interface
3439 // (shorten with fallback), so `Iface v = new ConcreteLambda(..)`
3440 // stays phi-compatible across branches that mint different lambdas.
3441 if anon_fallback {
3442 if let Some(last) = internal.rsplit('$').next() {
3443 if !last.is_empty() && last.chars().all(|c| c.is_ascii_digit()) {
3444 if let Some((ifaces, sup)) = self.ctx.class_bases(internal) {
3445 if let Some(n) = ifaces.first() {
3446 return self.shorten(n);
3447 }
3448 if let Some(sup) = sup {
3449 if sup != "java/lang/Object" {
3450 return self.shorten(&sup);
3451 }
3452 }
3453 return "Object".to_string();
3454 }
3455 }
3456 }
3457 }
3458 // Local classes are emitted with their simple source name.
3459 if let Some(last) = internal.rsplit('$').next() {
3460 if !keep_dollar_pool
3461 && !last.is_empty()
3462 && !last.chars().all(|c| c.is_ascii_digit())
3463 && internal.contains('$')
3464 {
3465 // Nested-class names print as Outer.Inner, except local
3466 // classes whose outer chain includes digits (e.g. Foo$1Bar).
3467 let mut segs = internal.split('$');
3468 if let Some(first) = segs.next() {
3469 let rest: Vec<&str> = segs.collect();
3470 if rest
3471 .iter()
3472 .any(|r| r.starts_with(|c: char| c.is_ascii_digit()))
3473 {
3474 // Local/synthetic class (digit-led segment): javac
3475 // encodes a method-local class as `Outer$1Name`; its
3476 // source name is the digit prefix stripped, declared
3477 // `class Name` at its use site and referenced only
3478 // within that scope. Printing the binary name leaves
3479 // an unresolvable symbol (ClassSpecializer$Factory$1Var).
3480 if let Some(last) = internal.rsplit('$').next() {
3481 let stripped = last.trim_start_matches(|c: char| c.is_ascii_digit());
3482 if !stripped.is_empty()
3483 && !stripped.chars().next().unwrap().is_ascii_digit()
3484 {
3485 return stripped.to_string();
3486 }
3487 }
3488 return internal.replace('/', ".");
3489 }
3490 let _ = first;
3491 let _ = last;
3492 }
3493 }
3494 }
3495 let dotted = internal.replace('/', ".");
3496 // A simple type name shadowed by an in-scope VARIABLE (a field of
3497 // this class or a method local) cannot qualify a static access:
3498 // javac resolves the leading name as the variable first
3499 // (无法取消引用int — jdk26 VerificationType declares
3500 // `private static final int Integer` and the source spells
3501 // java.lang.Integer.toHexString in full). Keep the fully-qualified
3502 // form whenever the leading segment collides.
3503 let shadowed = |first: &str| {
3504 self.ctx.declares_field(self.ctx.class_name(), first)
3505 || self.vt.vars.iter().any(|v| v.name == first)
3506 };
3507 if internal.starts_with("java/lang/") && !internal[10..].contains('/') {
3508 let simple = if keep_dollar {
3509 internal[10..].to_string()
3510 } else {
3511 internal[10..].replace('$', ".")
3512 };
3513 let first = simple.split('.').next().unwrap_or(simple.as_str());
3514 if !shadowed(first) {
3515 return simple;
3516 }
3517 return dotted.replace('$', ".");
3518 }
3519 if pkg_of(internal) == pkg_of(self.ctx.class_name()) {
3520 let simple = if keep_dollar {
3521 internal.rsplit('/').next().unwrap_or(internal).to_string()
3522 } else {
3523 let d = self.nested_display(internal);
3524 let pkg_dotted = pkg_of(internal).replace('/', ".");
3525 d.strip_prefix(&pkg_dotted)
3526 .and_then(|r| r.strip_prefix('.'))
3527 .map(str::to_string)
3528 .unwrap_or(d)
3529 };
3530 let first = simple.split('.').next().unwrap_or(simple.as_str());
3531 // Member-type shadow: the emitting class's OWN nested type
3532 // with the same simple name captures the bare render
3533 // (member types outrank same-package types in class scope) —
3534 // weibo PhoneInfoUtils: `b2.b(ctx,..)` for sibling class
3535 // com/weibo/ssosdk/b2 bound to nested PhoneInfoUtils$b2
3536 // (找不到符号 方法 b). The reference to the twin itself (or
3537 // its own nestees) keeps the simple form. FQN fallback is
3538 // unambiguous — no field/variable can shadow a dotted
3539 // package chain past its first segment.
3540 // Member-type twin shadow: a nested type of ANY enclosing
3541 // level whose display simple name equals `first` captures
3542 // the bare render (member types outrank same-package types
3543 // in class scope — weixin d2's `((w1) h0)` bound to nested
3544 // d2$$w1, not sibling viewitems/w1: 1,045 h0→w1 lines).
3545 // Walk the `$`-chain of the emitting class (the ctx may be a
3546 // nested `d2$$c`, whose lexical scope still sees d2's
3547 // members); R8 orphans use `$$`, normalization displays use
3548 // `$`, and rename displays live only in the registry's
3549 // reverse index — check all four shapes per level.
3550 let twin_exists = {
3551 // The borrow temp must die before the else arm's
3552 // borrow_mut (if-let scrutinee temps live across the
3553 // whole statement — RefCell double-borrow panic).
3554 let cached = self.twin_cache.borrow().get(first).copied();
3555 if let Some(v) = cached {
3556 v
3557 } else {
3558 // Own nestees AND inherited member types (the scope
3559 // walk) capture the bare simple name alike.
3560 let v = self.scope_member_walk(&mut |c| {
3561 let t1 = format!("{c}${first}");
3562 let t2 = format!("{c}$${first}");
3563 self.ctx.has_class(&t1)
3564 || self.ctx.has_class(&t2)
3565 || crate::rename::is_renamed_display(&t1)
3566 || crate::rename::is_renamed_display(&t2)
3567 });
3568 self.twin_cache
3569 .borrow_mut()
3570 .insert(first.to_string(), v);
3571 v
3572 }
3573 };
3574 // is_twin_ref only matters when a twin exists (otherwise
3575 // `!twin_exists` already grants the simple form) — keep it
3576 // off the hot path.
3577 let is_twin_ref = twin_exists
3578 && self.scope_member_walk(&mut |c| {
3579 let t1 = format!("{c}${first}");
3580 let t2 = format!("{c}$${first}");
3581 internal == t1
3582 || internal == t2
3583 || internal.starts_with(&format!("{t1}$"))
3584 || internal.starts_with(&format!("{t2}$"))
3585 });
3586 if !shadowed(first) && (is_twin_ref || !twin_exists) {
3587 return simple;
3588 }
3589 }
3590 if keep_dollar {
3591 dotted
3592 } else {
3593 self.nested_display(internal)
3594 }
3595 }
3596
3597 pub fn type_name(&self, ty: &TypeRef) -> String {
3598 match ty {
3599 TypeRef::J(t) => self.java_type_name(t),
3600 TypeRef::G(g) => {
3601 // Render generic signature with shortened class names.
3602 self.generic_name(g)
3603 }
3604 }
3605 }
3606
3607 /// Declared-type name for a local: normally `type_name` (which lets a
3608 /// `$<digits>` class fall back to its SAM interface for phi-friendly
3609 /// readability), but a var in `force_concrete_vars` keeps its concrete
3610 /// binary name so concrete-member accesses (`v.L$0`, the Kotlin
3611 /// coroutine capture fields) resolve — interfaces have no instance
3612 /// fields.
3613 fn local_decl_ty(&self, var: u32, ty: &TypeRef) -> String {
3614 if self.vt.force_concrete_vars.contains(&var) {
3615 if let TypeRef::J(JavaType::Object(cls)) = ty {
3616 return sanitize_source_name(&self.shorten_concrete(cls));
3617 }
3618 }
3619 self.type_name(ty)
3620 }
3621
3622 fn java_type_name(&self, t: &JavaType) -> String {
3623 // An import-resolved obscured class renders its simple name in
3624 // every type position (signatures, casts, type refs).
3625 if let JavaType::Object(c) = t {
3626 if let Some(simple) = self.ctx.obscured_simple(c) {
3627 // The simple is a RAW `$`/path tail — digit-leading and
3628 // other illegal source forms must pass the sanitizer
3629 // like every other name path (WhatsApp `11o_2 v21;`
3630 // local-decl types, 需要';' ×16,926).
3631 return sanitize_source_name(&simple);
3632 }
3633 }
3634 match t {
3635 JavaType::Object(n) => self.shorten(n),
3636 JavaType::Array(inner) => format!("{}[]", self.java_type_name(inner)),
3637 other => other.to_java(false),
3638 }
3639 }
3640
3641 fn generic_name(&self, g: &crate::types::GenericType) -> String {
3642 use crate::types::{GenericType, WildcardBound};
3643 match g {
3644 GenericType::Primitive(c) => prim_name(*c).to_string(),
3645 GenericType::Class(cs) => {
3646 // The signature parser splits a literal-$ top-level name
3647 // (jextract-generated errno_h$shared) into nested-looking
3648 // parts [errno_h, shared]; rejoin and, when the pool
3649 // proves the class is NOT nested, render the binary name
3650 // through shorten (same-package simple form keeps the $).
3651 if cs.parts.len() > 1 && cs.parts.iter().skip(1).all(|p| p.args.is_empty()) {
3652 let joined = cs
3653 .parts
3654 .iter()
3655 .map(|p| p.name.as_str())
3656 .collect::<Vec<_>>()
3657 .join("$");
3658 let full = if cs.package.is_empty() {
3659 joined
3660 } else {
3661 format!("{}/{}", cs.package, joined)
3662 };
3663 let literal = self.ctx.has_class(&full) && self.ctx.find_outer(&full).is_none();
3664 if literal {
3665 return self.shorten(&full);
3666 }
3667 }
3668 let mut s = String::new();
3669 if !cs.package.is_empty() {
3670 let full = format!(
3671 "{}/{}",
3672 cs.package,
3673 cs.parts.first().map(|p| p.name.as_str()).unwrap_or("")
3674 );
3675 s.push_str(&self.shorten(&full));
3676 } else {
3677 s.push_str(&cs.parts.first().map(|p| p.name.clone()).unwrap_or_default());
3678 }
3679 if let Some(first) = cs.parts.first() {
3680 if !first.args.is_empty() {
3681 s.push('<');
3682 for (i, a) in first.args.iter().enumerate() {
3683 if i > 0 {
3684 s.push_str(", ");
3685 }
3686 s.push_str(&self.generic_name(a));
3687 }
3688 s.push('>');
3689 }
3690 }
3691 for p in cs.parts.iter().skip(1) {
3692 let digit_led = p
3693 .name
3694 .chars()
3695 .next()
3696 .map(|c| c.is_ascii_digit())
3697 .unwrap_or(false);
3698 let stripped = p.name.trim_start_matches(|c: char| c.is_ascii_digit());
3699 if digit_led && !stripped.is_empty() && p.args.is_empty() {
3700 // javac's local-class encoding `Outer$1Name`: the
3701 // source name is the prefix-stripped simple name,
3702 // referenced WITHOUT qualification (there is no
3703 // legal `DocLint.1Pair` — `> or ',' expected`).
3704 s = stripped.to_string();
3705 continue;
3706 }
3707 s.push('.');
3708 s.push_str(&p.name);
3709 if !p.args.is_empty() {
3710 s.push('<');
3711 for (i, a) in p.args.iter().enumerate() {
3712 if i > 0 {
3713 s.push_str(", ");
3714 }
3715 s.push_str(&self.generic_name(a));
3716 }
3717 s.push('>');
3718 }
3719 }
3720 s
3721 }
3722 GenericType::Array(inner) => format!("{}[]", self.generic_name(inner)),
3723 GenericType::TypeVar(n) => n.clone(),
3724 GenericType::Wildcard(w) => match w {
3725 WildcardBound::Any => "?".to_string(),
3726 WildcardBound::Extends(t) => format!("? extends {}", self.generic_name(t)),
3727 WildcardBound::Super(t) => format!("? super {}", self.generic_name(t)),
3728 },
3729 }
3730 }
3731}
3732
3733fn inner_simple(cls: &str) -> String {
3734 // Apply the class-rename registry FIRST: a renamed nested class must
3735 // print its display tail at `outer.new Inner(..)` sites too — this
3736 // free function was the one emit-side path bypassing the registry
3737 // (round-55: declarations carried the rename while `this.new b()`
3738 // printed the raw tail → cannot-find).
3739 // Framework-shadow stub: keep the raw framework name (refs mean the
3740 // platform class; only the file identity relocated).
3741 let shadowed = crate::rename::fw_shadow_contains(cls);
3742 let cow = if shadowed {
3743 std::borrow::Cow::Borrowed(cls)
3744 } else {
3745 crate::rename::apply_class_rename(cls)
3746 };
3747 let cls: &str = &cow;
3748 let last = cls.rsplit('/').next().unwrap_or(cls);
3749 // R8 leaves class names ending in `$` (rimet's `ThreadMsg$$$`):
3750 // the last `$`-segment is EMPTY — fall back to the whole simple
3751 // name instead of printing `receiver.new (args)`.
3752 let seg = last.rsplit('$').next().unwrap_or(last);
3753 let last = if seg.is_empty() { last } else { seg };
3754 // Obfuscators name classes after keywords (`v10.new do("")`): the
3755 // qualified-new form prints this simple name raw.
3756 let name = last.to_string();
3757 if is_java_keyword(name.as_str())
3758 || is_restricted_type_name(name.as_str())
3759 || name.chars().next().is_some_and(|c| c.is_ascii_digit())
3760 {
3761 format!("_{name}")
3762 } else if name
3763 .chars()
3764 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
3765 {
3766 name
3767 } else {
3768 // Non-ASCII single chars (Alipay names a field `支`) map to a
3769 // lone `_` — itself reserved since Java 9. Escape it.
3770 let mapped: String = name
3771 .chars()
3772 .map(|c| {
3773 if c.is_ascii_alphanumeric() || c == '_' || c == '$' {
3774 c
3775 } else {
3776 '_'
3777 }
3778 })
3779 .collect();
3780 if mapped == "_" {
3781 "__".to_string()
3782 } else {
3783 mapped
3784 }
3785 }
3786}
3787
3788fn push_char_lit(out: &mut String, n: i32) {
3789 let c = (n as u16) as u32;
3790 match char::from_u32(c) {
3791 Some('\'') => out.push_str("'\\''"),
3792 Some('\\') => out.push_str("'\\\\'"),
3793 Some('\n') => out.push_str("'\\n'"),
3794 Some('\r') => out.push_str("'\\r'"),
3795 Some('\t') => out.push_str("'\\t'"),
3796 Some(ch) if ch.is_control() => out.push_str(&format!("'\\u{:04x}'", c)),
3797 Some(ch) => {
3798 out.push('\'');
3799 out.push(ch);
3800 out.push('\'');
3801 }
3802 None => out.push_str(&format!("'\\u{:04x}'", c)),
3803 }
3804}
3805
3806fn const_bool(e: &Expr) -> Option<bool> {
3807 match e {
3808 Expr::Const(ConstVal::Int(n)) => Some(*n != 0),
3809 _ => None,
3810 }
3811}
3812
3813fn pkg_of(n: &str) -> &str {
3814 n.rfind('/').map(|i| &n[..i]).unwrap_or("")
3815}
3816
3817fn prim_name(c: char) -> &'static str {
3818 match c {
3819 'V' => "void",
3820 'Z' => "boolean",
3821 'B' => "byte",
3822 'C' => "char",
3823 'S' => "short",
3824 'I' => "int",
3825 'F' => "float",
3826 'J' => "long",
3827 'D' => "double",
3828 _ => "?",
3829 }
3830}
3831
3832/// Kotlin emits method names like `invokeSuspend$lambda-0` — `-` and any
3833/// other non-identifier character is not legal Java. Deterministic
3834/// mapping; ddc's classdec applies the identical rule at declarations.
3835pub fn java_ident(name: &str) -> std::borrow::Cow<'_, str> {
3836 let clean = name
3837 .chars()
3838 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
3839 let keyword = is_java_keyword(name);
3840 // A simple name may not START with a digit either (nova names fields
3841 // `1x`/`2x`/`3x`): ddc's declaration side has the same branch.
3842 let digit_start = name.chars().next().is_some_and(|c| c.is_ascii_digit());
3843 if clean && !keyword && !digit_start {
3844 // The overwhelmingly common case: borrow, zero allocation (this
3845 // runs per rendered IDENTIFIER).
3846 std::borrow::Cow::Borrowed(name)
3847 } else if keyword || digit_start {
3848 std::borrow::Cow::Owned(format!("_{name}"))
3849 } else {
3850 // Non-ASCII single chars (Alipay names a field `支`) map to a
3851 // lone `_` — itself reserved since Java 9. Escape it.
3852 let mapped: String = name
3853 .chars()
3854 .map(|c| {
3855 if c.is_ascii_alphanumeric() || c == '_' || c == '$' {
3856 c
3857 } else {
3858 '_'
3859 }
3860 })
3861 .collect();
3862 if mapped == "_" {
3863 std::borrow::Cow::Owned("__".to_string())
3864 } else {
3865 std::borrow::Cow::Owned(mapped)
3866 }
3867 }
3868}
3869
3870/// Java reserved words (plus the null/true/false literals, and `_` — a
3871/// reserved IDENTIFIER since Java 9: Alipay's instant-run patch system
3872/// names fields `_`, and `javac` rejects it with "underscores are not
3873/// allowed here"): Kotlin emits methods and fields named `default`
3874/// (Companion.default()) — no Java program can name them, so both ddc's
3875/// declarations and these call sites map them to `_<name>` identically
3876/// (which turns `_` into `__`). NOTE: these are MEMBER-level escapes —
3877/// locals/fields/params MAY legally carry the restricted contextual
3878/// type names below (rt.jar has `var` locals), so those live in their
3879/// own predicate.
3880pub fn is_java_keyword(name: &str) -> bool {
3881 matches!(
3882 name,
3883 "abstract" | "assert" | "boolean" | "break" | "byte" | "case" | "catch" | "char"
3884 | "class" | "const" | "continue" | "default" | "do" | "double" | "else" | "enum"
3885 | "extends" | "final" | "finally" | "float" | "for" | "goto" | "if" | "implements"
3886 | "import" | "instanceof" | "int" | "interface" | "long" | "native" | "new"
3887 | "package" | "private" | "protected" | "public" | "return" | "short" | "static"
3888 | "strictfp" | "super" | "switch" | "synchronized" | "this" | "throw" | "throws"
3889 | "transient" | "try" | "void" | "volatile" | "while" | "true" | "false" | "null"
3890 | "_"
3891 )
3892}
3893
3894/// Restricted CONTEXTUAL type names — javac rejects them in TYPE
3895/// declarations and type references (`'var' 是受限类型名称`), but they
3896/// stay legal as member/local names (rt.jar compiles `var` locals).
3897/// Consulted ONLY where a CLASS name renders: type declarations,
3898/// segment sanitizers, the qualified-new simple name.
3899pub fn is_restricted_type_name(name: &str) -> bool {
3900 matches!(
3901 name,
3902 "var" | "yield" | "record" | "sealed" | "permits"
3903 )
3904}
3905
3906/// `this` in its Raw encoding (prints as `this`; see the Raw arm).
3907fn is_this_expr(e: &Expr) -> bool {
3908 matches!(e, Expr::This) || matches!(e, Expr::Raw(t) if t == "\u{3}" || t == "this")
3909}
3910
3911/// Class-file names may contain characters Java source identifiers
3912/// cannot (R8 desugared `Collection$-EL`); deterministic -→_ mapping,
3913/// matching ddc's declaration-site java_ident.
3914/// Legal Java expression-statement forms (JLS 14.8): assignment, method
3915/// invocation, inc/dec, class instance creation.
3916fn is_statement_expr(e: &Expr) -> bool {
3917 matches!(
3918 e,
3919 Expr::Assign { .. }
3920 | Expr::Method { .. }
3921 | Expr::New { .. }
3922 | Expr::PreIncDec { .. }
3923 | Expr::PostIncDec { .. }
3924 )
3925}
3926
3927pub fn sanitize_source_name(name: &str) -> String {
3928 // Obfuscators emit classes named `if`/`do`, PACKAGES named `do`
3929 // (weixin `package do;`) and `..badge.new..` paths (qq), WhatsApp
3930 // nests digit-start simple names (`X/0Xx`), Kotlin mints hyphenated
3931 // synthetic markers (`c$1-IA`, `Collection$-EL`) and R8 hardening
3932 // even names classes in Thai/Yi/Syriac code points (bin.mt.plus —
3933 // ejfkdev/ddc#4). EVERY identifier-unsafe character escapes to
3934 // `_u<hex>` per code point, then identifier-position repairs apply.
3935 // Byte-for-byte the mapping the DECLARATION side uses (ddc
3936 // `classdec::sanitize_fq_seg`): declaration, file name and every
3937 // reference must agree, and the escape must be INJECTIVE — the old
3938 // fold-everything-to-`_` mapping collapsed 22,636 distinct classes
3939 // onto 3 file names.
3940 let segs: Vec<&str> = name.split('.').collect();
3941 let clean = name
3942 .chars()
3943 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$' || c == '.')
3944 && segs.iter().all(|seg| {
3945 let first = seg.chars().next().unwrap_or('a');
3946 !is_java_keyword(seg)
3947 && !is_restricted_type_name(seg)
3948 && !first.is_ascii_digit()
3949 && *seg != "_"
3950 });
3951 if clean {
3952 return name.to_string();
3953 }
3954 segs.iter()
3955 .copied()
3956 .map(sanitize_ident_seg)
3957 .collect::<Vec<_>>()
3958 .join(".")
3959}
3960
3961/// One identifier segment: escape every ident-unsafe character as
3962/// `_u<hex>`, then repair identifier positions (keyword / restricted
3963/// type name / digit start gain a leading `_`; the lone `_` reserved
3964/// since Java 9 becomes `__`). Mirrors ddc `sanitize_fq_seg` exactly.
3965fn sanitize_ident_seg(seg: &str) -> String {
3966 let plain = seg
3967 .chars()
3968 .all(|c| c.is_ascii() && (c.is_ascii_alphanumeric() || c == '_' || c == '$'));
3969 let mut out = if plain {
3970 seg.to_string()
3971 } else {
3972 use std::fmt::Write as _;
3973 let mut s = String::with_capacity(seg.len() + 8);
3974 for c in seg.chars() {
3975 if c.is_ascii() && (c.is_ascii_alphanumeric() || c == '_' || c == '$') {
3976 s.push(c);
3977 } else {
3978 s.push_str("_u");
3979 let _ = write!(s, "{:x}", c as u32);
3980 }
3981 }
3982 s
3983 };
3984 if is_java_keyword(&out)
3985 || is_restricted_type_name(&out)
3986 || out.chars().next().is_some_and(|c| c.is_ascii_digit())
3987 {
3988 out.insert(0, '_');
3989 }
3990 if out == "_" {
3991 out = "__".to_string();
3992 }
3993 out
3994}
3995
3996pub fn escape_string(s: &str) -> String {
3997 let mut out = String::with_capacity(s.len());
3998 for c in s.chars() {
3999 match c {
4000 '"' => out.push_str("\\\""),
4001 '\\' => out.push_str("\\\\"),
4002 '\n' => out.push_str("\\n"),
4003 '\r' => out.push_str("\\r"),
4004 '\t' => out.push_str("\\t"),
4005 '\u{0}' => out.push_str("\\0"),
4006 '\u{8}' => out.push_str("\\b"),
4007 '\u{C}' => out.push_str("\\f"),
4008 c if (c as u32) < 0x20 || (c as u32) == 0x7F => {
4009 out.push_str(&format!("\\u{:04x}", c as u32));
4010 }
4011 c => out.push(c),
4012 }
4013 }
4014 out
4015}
4016
4017pub fn escape_char(c: char) -> String {
4018 match c {
4019 '\'' => "\\'".to_string(),
4020 '\\' => "\\\\".to_string(),
4021 '\n' => "\\n".to_string(),
4022 '\r' => "\\r".to_string(),
4023 '\t' => "\\t".to_string(),
4024 '\0' => "\\0".to_string(),
4025 c if (c as u32) < 0x20 || (c as u32) == 0x7F => format!("\\u{:04x}", c as u32),
4026 c => c.to_string(),
4027 }
4028}
4029
4030pub fn format_float(v: f64, is_float: bool) -> String {
4031 let suffix = if is_float { "f" } else { "" };
4032 // Arithmetic literals, not `Double.NaN`/`POSITIVE_INFINITY` field refs:
4033 // inside java.lang.Double/Float themselves a field reference would be
4034 // a self-reference initializing the very field being printed.
4035 if v.is_nan() {
4036 return if is_float {
4037 "(0.0f / 0.0f)".into()
4038 } else {
4039 "(0.0 / 0.0)".into()
4040 };
4041 }
4042 if v.is_infinite() {
4043 let one = if is_float { "1.0f" } else { "1.0" };
4044 let zero = if is_float { "0.0f" } else { "0.0" };
4045 return if v < 0.0 {
4046 format!("(-{} / {})", one, zero)
4047 } else {
4048 format!("({} / {})", one, zero)
4049 };
4050 }
4051 let mut s = format!("{}", v);
4052 if !s.contains('.') && !s.contains('e') && !s.contains('E') {
4053 s.push_str(".0");
4054 }
4055 // Java doesn't accept exponent forms like "1e-7"? It does: 1e-7 is a valid
4056 // double literal. But "inf"/"nan" handled above.
4057 format!("{}{}", s, suffix)
4058}
4059
4060// ---------------------------------------------------------------------------
4061// Unreachable-code truncation (final statement tree)
4062// ---------------------------------------------------------------------------
4063
4064/// Drop statements that follow a `while (true)` which cannot complete
4065/// normally (no `break` in its body binds to it): javac rejects them as
4066/// 无法访问的语句, and the structurers only emitted them as shared-tail
4067/// copies whose real arrivals all render INSIDE the loop arms (jdk17/26
4068/// Pattern.clazz's for(;;){switch}: case-93's `return prev/negate` tail
4069/// landed after the never-completing loop). Runs on the FINAL tree (after
4070/// switch restoration and goto resolution) so the break inventory is
4071/// exactly what gets emitted; every unknown shape stays conservative
4072/// (assumes the loop can complete).
4073fn tree_has_dead_end(s: &Stmt) -> bool {
4074 match s {
4075 Stmt::Block(v) => {
4076 for (i, x) in v.iter().enumerate() {
4077 if i > 0 && dead_end_infinite_while(&v[i - 1]) {
4078 return true;
4079 }
4080 if tree_has_dead_end(x) {
4081 return true;
4082 }
4083 }
4084 false
4085 }
4086 Stmt::If {
4087 then_stmt,
4088 else_stmt,
4089 ..
4090 } => tree_has_dead_end(then_stmt) || else_stmt.as_deref().is_some_and(tree_has_dead_end),
4091 Stmt::While { body, .. } | Stmt::DoWhile { body, .. } => tree_has_dead_end(body),
4092 Stmt::For { init, body, .. } => {
4093 init.iter().any(tree_has_dead_end) || tree_has_dead_end(body)
4094 }
4095 Stmt::ForEach { body, .. } => tree_has_dead_end(body),
4096 Stmt::Switch { cases, default, .. } => {
4097 cases.iter().any(|c| c.body.iter().any(tree_has_dead_end))
4098 || default.as_deref().is_some_and(tree_has_dead_end)
4099 }
4100 Stmt::Try {
4101 body,
4102 catches,
4103 finally,
4104 } => {
4105 tree_has_dead_end(body)
4106 || catches.iter().any(|c| tree_has_dead_end(&c.body))
4107 || finally.as_deref().is_some_and(tree_has_dead_end)
4108 }
4109 Stmt::TryWithResources {
4110 resources,
4111 body,
4112 catches,
4113 finally,
4114 ..
4115 } => {
4116 resources.iter().any(tree_has_dead_end)
4117 || tree_has_dead_end(body)
4118 || catches.iter().any(|c| tree_has_dead_end(&c.body))
4119 || finally.as_deref().is_some_and(tree_has_dead_end)
4120 }
4121 Stmt::Synchronized { body, .. } | Stmt::Labeled { body, .. } => tree_has_dead_end(body),
4122 _ => false,
4123 }
4124}
4125
4126fn truncate_dead_ends(s: &Stmt) -> Stmt {
4127 match s {
4128 Stmt::Block(v) => {
4129 let mut out: Vec<Stmt> = Vec::with_capacity(v.len());
4130 for x in v {
4131 if !out.is_empty() && dead_end_infinite_while(out.last().unwrap()) {
4132 if crate::dbg_flag!("JCDC_DBG_GOTO") {
4133 eprintln!(
4134 "DEADEND truncate {} unreachable stmt(s)",
4135 v.len() - out.len()
4136 );
4137 }
4138 break;
4139 }
4140 out.push(truncate_dead_ends(x));
4141 }
4142 Stmt::Block(out)
4143 }
4144 Stmt::If {
4145 cond,
4146 then_stmt,
4147 else_stmt,
4148 } => Stmt::If {
4149 cond: cond.clone(),
4150 then_stmt: Box::new(truncate_dead_ends(then_stmt)),
4151 else_stmt: else_stmt.as_deref().map(truncate_dead_ends).map(Box::new),
4152 },
4153 Stmt::While { cond, body } => Stmt::While {
4154 cond: cond.clone(),
4155 body: Box::new(truncate_dead_ends(body)),
4156 },
4157 Stmt::DoWhile { body, cond } => Stmt::DoWhile {
4158 body: Box::new(truncate_dead_ends(body)),
4159 cond: cond.clone(),
4160 },
4161 Stmt::For {
4162 init,
4163 cond,
4164 update,
4165 body,
4166 } => Stmt::For {
4167 init: init.iter().map(truncate_dead_ends).collect(),
4168 cond: cond.clone(),
4169 update: update.clone(),
4170 body: Box::new(truncate_dead_ends(body)),
4171 },
4172 Stmt::ForEach {
4173 var,
4174 iterable,
4175 is_array,
4176 body,
4177 } => Stmt::ForEach {
4178 var: *var,
4179 iterable: iterable.clone(),
4180 is_array: *is_array,
4181 body: Box::new(truncate_dead_ends(body)),
4182 },
4183 Stmt::Switch {
4184 selector,
4185 cases,
4186 default,
4187 on_string,
4188 } => Stmt::Switch {
4189 selector: selector.clone(),
4190 cases: cases
4191 .iter()
4192 .map(|c| CaseGroup {
4193 labels: c.labels.clone(),
4194 string_labels: c.string_labels.clone(),
4195 enum_labels: c.enum_labels.clone(),
4196 raw_labels: c.raw_labels.clone(),
4197 guard: c.guard.clone(),
4198 body: c.body.iter().map(truncate_dead_ends).collect(),
4199 })
4200 .collect(),
4201 default: default.as_deref().map(truncate_dead_ends).map(Box::new),
4202 on_string: *on_string,
4203 },
4204 Stmt::Try {
4205 body,
4206 catches,
4207 finally,
4208 } => Stmt::Try {
4209 body: Box::new(truncate_dead_ends(body)),
4210 catches: catches
4211 .iter()
4212 .map(|c| Catch {
4213 exc: c.exc.clone(),
4214 var: c.var,
4215 var_name: c.var_name.clone(),
4216 body: Box::new(truncate_dead_ends(&c.body)),
4217 })
4218 .collect(),
4219 finally: finally.as_deref().map(truncate_dead_ends).map(Box::new),
4220 },
4221 Stmt::TryWithResources {
4222 resources,
4223 body,
4224 catches,
4225 finally,
4226 } => Stmt::TryWithResources {
4227 resources: resources.iter().map(truncate_dead_ends).collect(),
4228 body: Box::new(truncate_dead_ends(body)),
4229 catches: catches
4230 .iter()
4231 .map(|c| Catch {
4232 exc: c.exc.clone(),
4233 var: c.var,
4234 var_name: c.var_name.clone(),
4235 body: Box::new(truncate_dead_ends(&c.body)),
4236 })
4237 .collect(),
4238 finally: finally.as_deref().map(truncate_dead_ends).map(Box::new),
4239 },
4240 Stmt::Synchronized { lock, body } => Stmt::Synchronized {
4241 lock: lock.clone(),
4242 body: Box::new(truncate_dead_ends(body)),
4243 },
4244 Stmt::Labeled { label, body } => Stmt::Labeled {
4245 label: label.clone(),
4246 body: Box::new(truncate_dead_ends(body)),
4247 },
4248 other => other.clone(),
4249 }
4250}
4251
4252/// True when `s` is a `while (true)` (labeled or not) whose body holds
4253/// no `break` binding to it — it can never complete normally.
4254pub(crate) fn dead_end_infinite_while(s: &Stmt) -> bool {
4255 let (label, body, cond) = match s {
4256 Stmt::While { cond, body } => (None, body.as_ref(), cond),
4257 Stmt::Labeled { label, body } => match &**body {
4258 Stmt::While { cond, body } => (Some(label.as_str()), body.as_ref(), cond),
4259 _ => return false,
4260 },
4261 _ => return false,
4262 };
4263 if !matches!(cond, Expr::Const(ConstVal::Int(1))) {
4264 return false;
4265 }
4266 // JLS 14.14: `while (true)` completes normally iff its body holds a
4267 // reachable break that exits IT: an unlabeled break not captured by
4268 // an inner breakable construct, or `break L` where L is THIS loop's
4269 // own label. A labeled break to any OTHER label — inner (Pattern
4270 // .clazz's `break L4`) or OUTER (jdk11/26 ThreadPoolExecutor
4271 // .addWorker's `break retry` inside the inner for(;;)) — completes
4272 // the while ABRUPTLY: javac's flow model marks the statements after
4273 // such a loop unreachable (the w26 `continue;` after the inner
4274 // while(true) was a latent 无法访问的语句 masked by alphabetically
4275 // earlier census errors).
4276 !has_break_exiting(body, label, 0)
4277}
4278
4279fn has_break_exiting(s: &Stmt, lbl: Option<&str>, depth: usize) -> bool {
4280 match s {
4281 Stmt::Break(None) => depth == 0,
4282 // Only this loop's OWN label completes it; any other labeled
4283 // break exits abruptly (JLS 14.14/14.17).
4284 Stmt::Break(Some(l)) => Some(l.as_str()) == lbl,
4285 Stmt::Continue(_) | Stmt::Return(_) | Stmt::Throw(_) => false,
4286 Stmt::Goto(_) => true,
4287 Stmt::Block(v) => v.iter().any(|x| has_break_exiting(x, lbl, depth)),
4288 Stmt::If {
4289 then_stmt,
4290 else_stmt,
4291 ..
4292 } => {
4293 has_break_exiting(then_stmt, lbl, depth)
4294 || else_stmt
4295 .as_deref()
4296 .map(|e| has_break_exiting(e, lbl, depth))
4297 .unwrap_or(false)
4298 }
4299 Stmt::While { body, .. }
4300 | Stmt::DoWhile { body, .. }
4301 | Stmt::For { body, .. }
4302 | Stmt::ForEach { body, .. } => has_break_exiting(body, lbl, depth + 1),
4303 Stmt::Switch { cases, default, .. } => {
4304 cases
4305 .iter()
4306 .any(|c| c.body.iter().any(|x| has_break_exiting(x, lbl, depth + 1)))
4307 || default
4308 .as_deref()
4309 .map(|d| has_break_exiting(d, lbl, depth + 1))
4310 .unwrap_or(false)
4311 }
4312 Stmt::Try {
4313 body,
4314 catches,
4315 finally,
4316 }
4317 | Stmt::TryWithResources {
4318 body,
4319 catches,
4320 finally,
4321 ..
4322 } => {
4323 has_break_exiting(body, lbl, depth)
4324 || catches
4325 .iter()
4326 .any(|c| has_break_exiting(&c.body, lbl, depth))
4327 || finally
4328 .as_deref()
4329 .map(|f| has_break_exiting(f, lbl, depth))
4330 .unwrap_or(false)
4331 }
4332 Stmt::Synchronized { body, .. } => has_break_exiting(body, lbl, depth),
4333 Stmt::Labeled { body, .. } => has_break_exiting(body, lbl, depth),
4334 // Plain leaf statements never contain a break.
4335 Stmt::ExprStmt(_)
4336 | Stmt::LocalDef { .. }
4337 | Stmt::Assert { .. }
4338 | Stmt::TernaryValue { .. }
4339 | Stmt::MonitorEnter(_)
4340 | Stmt::MonitorExit(_)
4341 | Stmt::Comment(_) => false,
4342 // Opaque shapes (raw labels, inline class decls, anything new):
4343 // keep truncation off when an escape cannot be ruled out.
4344 _ => true,
4345 }
4346}