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