Skip to main content

jdc_core/
emit.rs

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