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