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