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