Skip to main content

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