jdc_core/ctx.rs
1//! What the core needs to ask the front-end.
2//!
3//! Everything in this crate works on machine-neutral IR; the few questions
4//! that depend on the machine's *class metadata* — how nested classes are
5//! related, what a method's signature says, how a nested method body looks —
6//! go through [`Ctx`]. A front-end implements it once (JVM: over its class
7//! pool; DEX: over its class definitions) and every shared pass/emitter works.
8//!
9//! The trait is deliberately *semantic*, not a raw pool: the core never sees
10//! a constant pool, a `Signature` attribute, or an `InnerClasses` table.
11
12use std::collections::{HashMap, HashSet};
13
14use crate::ir::expr::Expr;
15use crate::ir::expr::TypeRef;
16use crate::ir::stmt::Stmt;
17use crate::types::{ClassAccessFlags, MethodDescriptor};
18
19/// How a nested class was classified.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum NestedKind {
22 /// Declared as a member of its outer class.
23 Member,
24 /// An anonymous class: inlined at its `new` site, never printed separately.
25 Anonymous,
26 /// A local class: declared at its use site inside a method.
27 Local,
28 /// A lambda implementation class: skipped entirely.
29 Lambda,
30}
31
32/// One nested class of a family.
33#[derive(Debug, Clone)]
34pub struct NestedClass {
35 /// Internal name (e.g. `p/Outer$Inner`).
36 pub name: String,
37 /// Source-visible simple name (`Inner`, or a synthesized name for locals).
38 pub simple: String,
39 pub kind: NestedKind,
40 pub access: ClassAccessFlags,
41 /// Source header rendered from the class's generic signature when the
42 /// container records one; `None` for front-ends without signature info
43 /// (DEX), in which case tracking falls back to the erased rendering.
44 pub sig_header: Option<String>,
45}
46
47/// The nested-class family of one top-level class.
48#[derive(Debug, Default, Clone)]
49pub struct Family {
50 pub root: String,
51 /// All nested classes (any depth) keyed by internal name.
52 pub nested: HashMap<String, NestedClass>,
53 /// Anonymous classes inlined at `new` sites.
54 pub anonymous: HashSet<String>,
55 /// Local classes declared at their use site.
56 pub locals: HashSet<String>,
57 /// Lambda implementation classes (skipped).
58 pub lambdas: HashSet<String>,
59}
60
61/// A decompiled nested method body (lambda body, anonymous-class method, ...).
62pub struct MethodBody {
63 /// Final statement tree.
64 pub body: Stmt,
65 pub vt: crate::var::VarTable,
66 pub desc: MethodDescriptor,
67}
68
69/// Front-end services used by the shared passes and the emitter.
70pub trait Ctx {
71 /// Internal name of the class currently being emitted
72 /// (e.g. `java/util/ArrayList`).
73 fn class_name(&self) -> &str;
74
75 /// Source level gate for version-dependent rendering: the JVM front-end
76 /// returns the class-file major version; a DEX front-end returns the
77 /// equivalent language level it decided to target. `52` means "Java 8
78 /// features available" (lambdas, diamond, ...).
79 fn source_level(&self) -> u16 {
80 52
81 }
82
83 /// Identity of the backing container (pool), for caches keyed on
84 /// pool-dependent pure queries (`Printer::shorten` memoization).
85 /// Default 0 is safe only for single-pool processes; multi-pool
86 /// front-ends (ddc/jcdc) override with the pool pointer so a second
87 /// pool never reads the first pool's cached shortenings.
88 fn pool_id(&self) -> u64 {
89 0
90 }
91
92 /// The class that `internal` is nested in, when the container records the
93 /// nesting (JVM `InnerClasses`/`NestHost`; DEX inner-class annotations).
94 /// `None` for a top-level class — including literal-`$` names that only
95 /// *look* nested.
96 fn find_outer(&self, internal: &str) -> Option<String>;
97
98 /// Nested-class family of `root`, as far as the container records it.
99 fn family(&self, root: &str) -> Family;
100
101 /// True when a nested class is static (`Outer$Inner` with ACC_STATIC), so
102 /// it is not constructed with an enclosing instance.
103 fn nested_is_static(&self, internal: &str) -> bool;
104
105 /// True when the class carries a synthetic `this$0` field (an inner class
106 /// with an enclosing instance parameter).
107 fn class_has_this0(&self, internal: &str) -> bool;
108
109 /// True when `sub` is assignable to `sup` (both internal names).
110 fn is_subtype_of(&self, sub: &crate::types::JavaType, sup: &str) -> bool;
111
112 /// Superclasses/interfaces of `internal` with the given type arguments
113 /// applied: `[(java/lang/Object, []), ...]`, most-derived first.
114 fn class_supers_args(
115 &self,
116 internal: &str,
117 args: &[crate::types::GenericType],
118 ) -> Vec<(String, Vec<crate::types::GenericType>)>;
119
120 /// True when the call carries inferred type arguments that the source
121 /// must spell out.
122 fn is_generic_call(&self, e: &Expr) -> bool;
123
124 /// Instantiated formal parameter types of a generic call plus the callee's
125 /// own method type variables (for witness casts). `None` when the call has
126 /// no inferred type arguments to spell out.
127 fn generic_call_formals(
128 &self,
129 e: &Expr,
130 ) -> Option<(Vec<crate::types::GenericType>, Vec<String>)>;
131
132 /// The instantiated return type of a call whose methodref owner redeclares
133 /// the method with a self-covariant return (Stream over BaseStream).
134 fn polymorphic_ret_cast(
135 &self,
136 cls: &str,
137 name: &str,
138 desc: &MethodDescriptor,
139 ) -> Option<crate::types::JavaType>;
140
141 /// Constructor parameter types of `internal` matching `arity`, for
142 /// rendering `new` arguments against the right overload.
143 fn ctor_formals_by_arity(
144 &self,
145 internal: &str,
146 arity: usize,
147 ) -> Option<Vec<crate::types::GenericType>>;
148
149 /// Local-class name recorded for a `$`-style synthetic marker, when the
150 /// container records one (`Outer$1Local` -> `Local`).
151 fn local_class_internal(&self, simple: &str) -> Option<String> {
152 let _ = simple;
153 None
154 }
155
156 /// Generic type parameters declared by `internal` (from its class
157 /// signature); empty when the container records none.
158 fn class_type_params(&self, internal: &str) -> Vec<crate::types::TypeParam> {
159 let _ = internal;
160 Vec::new()
161 }
162
163 /// Type variables of the *method* the call refers to (used to decide
164 /// whether a formal still carries the callee's own typevars).
165 fn generic_call_mt_typevars(&self, e: &Expr) -> Vec<String> {
166 let _ = e;
167 Vec::new()
168 }
169
170 /// Superclass of `internal` (internal name); `None` at `Object`/unknown.
171 fn super_name(&self, internal: &str) -> Option<String> {
172 let _ = internal;
173 None
174 }
175
176 /// Access flags of the field `internal.name`; `None` when absent.
177 fn field_flags(&self, internal: &str, name: &str) -> Option<crate::types::FieldAccessFlags> {
178 let _ = (internal, name);
179 None
180 }
181
182 /// Access flags of the method `internal.name(desc)`; `None` when absent.
183 fn method_flags(
184 &self,
185 internal: &str,
186 name: &str,
187 desc: &str,
188 ) -> Option<crate::types::MethodAccessFlags> {
189 let _ = (internal, name, desc);
190 None
191 }
192
193 /// True when `internal` declares any field named `name`.
194 fn declares_field(&self, internal: &str, name: &str) -> bool {
195 self.field_flags(internal, name).is_some()
196 }
197
198 /// True when `internal` declares a method named `name` (any descriptor).
199 fn declares_method_named(&self, internal: &str, name: &str) -> bool {
200 let _ = (internal, name);
201 false
202 }
203
204 /// True when `internal` is an interface.
205 fn is_interface(&self, internal: &str) -> bool;
206
207 /// True when `internal` is sealed (its permitted subclasses are recorded).
208 fn is_sealed(&self, internal: &str) -> bool;
209
210 /// True when the container holds this class at all (naming probes use
211 /// it to test `Outer$1Local`-style candidates).
212 fn has_class(&self, internal: &str) -> bool;
213
214 /// Interfaces and superclass of `internal` (internal names, declaration
215 /// order). `None` when the class is unknown to the front-end.
216 fn class_bases(&self, internal: &str) -> Option<(Vec<String>, Option<String>)>;
217
218 /// True when `internal` is an inner class whose constructor forwards its
219 /// enclosing instance straight to `super` (javac 21+ drops `this$0` in
220 /// that case, but call sites still need the qualified-new form).
221 fn outer_param_via_super(&self, internal: &str) -> bool;
222
223 /// Decompile the nested method a lambda site refers to — a lambda body,
224 /// an anonymous-class method, or a local-class method — and run the
225 /// front-end's own idiom recovery on it.
226 ///
227 /// This is where machine-specific desugaring lives: the shared emitter
228 /// asks for a finished statement tree and prints it. The `LambdaExpr`
229 /// carries the call-site facts (impl owner/name/descriptor, the SAM's
230 /// parameter names, the capture expressions, and any front-end
231 /// annotations it attached, e.g. capture snapshots); `outer_vt` is the
232 /// enclosing method's variable table — the lexical scope the body will be
233 /// printed in.
234 fn nested_method(
235 &self,
236 l: &crate::ir::expr::LambdaExpr,
237 outer_vt: &crate::var::VarTable,
238 ) -> Option<MethodBody>;
239
240 /// Parameter types of the `<init>` of `internal` matching `skip + n`
241 /// descriptor args, with `skip` leading synthetic parameters removed.
242 /// Used to print `new` arguments with boolean/char constant adjustment.
243 fn ctor_param_types(
244 &self,
245 internal: &str,
246 skip: usize,
247 n: usize,
248 args: &[Expr],
249 ) -> Option<Vec<crate::types::JavaType>> {
250 let _ = (internal, skip, n, args);
251 None
252 }
253
254 /// Instantiated SAM return of a functional interface's method, resolved
255 /// against a cast's type arguments (`(Function<I,R>) lambda` needs
256 /// `(R) value` witnesses on the impl body's returns).
257 fn sam_ret_cast(&self, g: &crate::types::GenericType, sam_name: &str) -> Option<TypeRef> {
258 let _ = (g, sam_name);
259 None
260 }
261
262 /// True when `internal` declares class-level type parameters (so
263 /// `new internal<>(...)` should carry a diamond).
264 fn class_declares_generics(&self, internal: &str) -> bool {
265 !self.class_type_params(internal).is_empty()
266 }
267}
268
269/// A `Ctx` with no metadata: every query answers "unknown".
270///
271/// Useful for tests and for front-ends that have not implemented a query yet —
272/// the core degrades gracefully (no nesting assumptions, no generic casts).
273pub struct NullCtx {
274 pub class_name: String,
275 pub level: u16,
276}
277
278impl Default for NullCtx {
279 fn default() -> Self {
280 NullCtx {
281 class_name: String::new(),
282 level: 52,
283 }
284 }
285}
286
287impl Ctx for NullCtx {
288 fn class_name(&self) -> &str {
289 &self.class_name
290 }
291 fn source_level(&self) -> u16 {
292 self.level
293 }
294 fn find_outer(&self, _internal: &str) -> Option<String> {
295 None
296 }
297 fn family(&self, root: &str) -> Family {
298 Family {
299 root: root.to_string(),
300 ..Default::default()
301 }
302 }
303 fn nested_is_static(&self, _internal: &str) -> bool {
304 true
305 }
306 fn class_has_this0(&self, _internal: &str) -> bool {
307 false
308 }
309 fn is_subtype_of(&self, _sub: &crate::types::JavaType, _sup: &str) -> bool {
310 false
311 }
312 fn class_supers_args(
313 &self,
314 _internal: &str,
315 _args: &[crate::types::GenericType],
316 ) -> Vec<(String, Vec<crate::types::GenericType>)> {
317 Vec::new()
318 }
319 fn is_generic_call(&self, _e: &Expr) -> bool {
320 false
321 }
322 fn generic_call_formals(
323 &self,
324 _e: &Expr,
325 ) -> Option<(Vec<crate::types::GenericType>, Vec<String>)> {
326 None
327 }
328 fn polymorphic_ret_cast(
329 &self,
330 _cls: &str,
331 _name: &str,
332 _desc: &MethodDescriptor,
333 ) -> Option<crate::types::JavaType> {
334 None
335 }
336 fn ctor_formals_by_arity(
337 &self,
338 _internal: &str,
339 _arity: usize,
340 ) -> Option<Vec<crate::types::GenericType>> {
341 None
342 }
343 fn is_interface(&self, _internal: &str) -> bool {
344 false
345 }
346 fn is_sealed(&self, _internal: &str) -> bool {
347 false
348 }
349 fn has_class(&self, _internal: &str) -> bool {
350 false
351 }
352 fn class_bases(&self, _internal: &str) -> Option<(Vec<String>, Option<String>)> {
353 None
354 }
355 fn outer_param_via_super(&self, _internal: &str) -> bool {
356 false
357 }
358 fn nested_method(
359 &self,
360 _l: &crate::ir::expr::LambdaExpr,
361 _outer_vt: &crate::var::VarTable,
362 ) -> Option<MethodBody> {
363 None
364 }
365}
366
367/// Assemble a [`MethodBody`] (front-ends return these from `Ctx::nested_method`).
368pub fn ctx_method_body(
369 body: crate::ir::stmt::Stmt,
370 vt: crate::var::VarTable,
371 desc: MethodDescriptor,
372) -> MethodBody {
373 MethodBody { body, vt, desc }
374}