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 /// The front-end's render-time import map: when a referenced
84 /// internal name is OBSCURED in the current compilation unit (its
85 /// qualified form's first segment binds to an in-scope class name
86 /// — JLS 6.4.2), the front-end emits a single-type import for it
87 /// and the render must use the SIMPLE name. Returns the simple
88 /// name when so; `None` renders normally. Default None (no import
89 /// machinery).
90 fn obscured_simple(&self, _internal: &str) -> Option<String> {
91 None
92 }
93
94 /// Identity of the backing container (pool), for caches keyed on
95 /// pool-dependent pure queries (`Printer::shorten` memoization).
96 /// Default 0 is safe only for single-pool processes; multi-pool
97 /// front-ends (ddc/jcdc) override with the pool pointer so a second
98 /// pool never reads the first pool's cached shortenings.
99 fn pool_id(&self) -> u64 {
100 0
101 }
102
103 /// The class that `internal` is nested in, when the container records the
104 /// nesting (JVM `InnerClasses`/`NestHost`; DEX inner-class annotations).
105 /// `None` for a top-level class — including literal-`$` names that only
106 /// *look* nested.
107 fn find_outer(&self, internal: &str) -> Option<String>;
108
109 /// Nested-class family of `root`, as far as the container records it.
110 fn family(&self, root: &str) -> Family;
111
112 /// True when a nested class is static (`Outer$Inner` with ACC_STATIC), so
113 /// it is not constructed with an enclosing instance.
114 fn nested_is_static(&self, internal: &str) -> bool;
115
116 /// True when the class carries a synthetic `this$0` field (an inner class
117 /// with an enclosing instance parameter).
118 fn class_has_this0(&self, internal: &str) -> bool;
119
120 /// True when `sub` is assignable to `sup` (both internal names).
121 fn is_subtype_of(&self, sub: &crate::types::JavaType, sup: &str) -> bool;
122
123 /// Superclasses/interfaces of `internal` with the given type arguments
124 /// applied: `[(java/lang/Object, []), ...]`, most-derived first.
125 fn class_supers_args(
126 &self,
127 internal: &str,
128 args: &[crate::types::GenericType],
129 ) -> Vec<(String, Vec<crate::types::GenericType>)>;
130
131 /// True when the call carries inferred type arguments that the source
132 /// must spell out.
133 fn is_generic_call(&self, e: &Expr) -> bool;
134
135 /// Instantiated formal parameter types of a generic call plus the callee's
136 /// own method type variables (for witness casts). `None` when the call has
137 /// no inferred type arguments to spell out.
138 fn generic_call_formals(
139 &self,
140 e: &Expr,
141 ) -> Option<(Vec<crate::types::GenericType>, Vec<String>)>;
142
143 /// The instantiated return type of a call whose methodref owner redeclares
144 /// the method with a self-covariant return (Stream over BaseStream).
145 fn polymorphic_ret_cast(
146 &self,
147 cls: &str,
148 name: &str,
149 desc: &MethodDescriptor,
150 ) -> Option<crate::types::JavaType>;
151
152 /// Constructor parameter types of `internal` matching `arity`, for
153 /// rendering `new` arguments against the right overload.
154 fn ctor_formals_by_arity(
155 &self,
156 internal: &str,
157 arity: usize,
158 ) -> Option<Vec<crate::types::GenericType>>;
159
160 /// Local-class name recorded for a `$`-style synthetic marker, when the
161 /// container records one (`Outer$1Local` -> `Local`).
162 fn local_class_internal(&self, simple: &str) -> Option<String> {
163 let _ = simple;
164 None
165 }
166
167 /// Generic type parameters declared by `internal` (from its class
168 /// signature); empty when the container records none.
169 fn class_type_params(&self, internal: &str) -> Vec<crate::types::TypeParam> {
170 let _ = internal;
171 Vec::new()
172 }
173
174 /// Type variables of the *method* the call refers to (used to decide
175 /// whether a formal still carries the callee's own typevars).
176 fn generic_call_mt_typevars(&self, e: &Expr) -> Vec<String> {
177 let _ = e;
178 Vec::new()
179 }
180
181 /// Superclass of `internal` (internal name); `None` at `Object`/unknown.
182 fn super_name(&self, internal: &str) -> Option<String> {
183 let _ = internal;
184 None
185 }
186
187 /// Access flags of the field `internal.name`; `None` when absent.
188 fn field_flags(&self, internal: &str, name: &str) -> Option<crate::types::FieldAccessFlags> {
189 let _ = (internal, name);
190 None
191 }
192
193 /// Access flags of the method `internal.name(desc)`; `None` when absent.
194 fn method_flags(
195 &self,
196 internal: &str,
197 name: &str,
198 desc: &str,
199 ) -> Option<crate::types::MethodAccessFlags> {
200 let _ = (internal, name, desc);
201 None
202 }
203
204 /// True when `internal` declares any field named `name`.
205 fn declares_field(&self, internal: &str, name: &str) -> bool {
206 self.field_flags(internal, name).is_some()
207 }
208
209 /// True when `internal` declares a method named `name` (any descriptor).
210 fn declares_method_named(&self, internal: &str, name: &str) -> bool {
211 let _ = (internal, name);
212 false
213 }
214
215 /// True when `internal` is an interface.
216 fn is_interface(&self, internal: &str) -> bool;
217
218 /// True when `internal` is sealed (its permitted subclasses are recorded).
219 fn is_sealed(&self, internal: &str) -> bool;
220
221 /// True when the container holds this class at all (naming probes use
222 /// it to test `Outer$1Local`-style candidates).
223 fn has_class(&self, internal: &str) -> bool;
224
225 /// Interfaces and superclass of `internal` (internal names, declaration
226 /// order). `None` when the class is unknown to the front-end.
227 fn class_bases(&self, internal: &str) -> Option<(Vec<String>, Option<String>)>;
228
229 /// True when `internal` is an inner class whose constructor forwards its
230 /// enclosing instance straight to `super` (javac 21+ drops `this$0` in
231 /// that case, but call sites still need the qualified-new form).
232 fn outer_param_via_super(&self, internal: &str) -> bool;
233
234 /// Decompile the nested method a lambda site refers to — a lambda body,
235 /// an anonymous-class method, or a local-class method — and run the
236 /// front-end's own idiom recovery on it.
237 ///
238 /// This is where machine-specific desugaring lives: the shared emitter
239 /// asks for a finished statement tree and prints it. The `LambdaExpr`
240 /// carries the call-site facts (impl owner/name/descriptor, the SAM's
241 /// parameter names, the capture expressions, and any front-end
242 /// annotations it attached, e.g. capture snapshots); `outer_vt` is the
243 /// enclosing method's variable table — the lexical scope the body will be
244 /// printed in.
245 fn nested_method(
246 &self,
247 l: &crate::ir::expr::LambdaExpr,
248 outer_vt: &crate::var::VarTable,
249 ) -> Option<MethodBody>;
250
251 /// Parameter types of the `<init>` of `internal` matching `skip + n`
252 /// descriptor args, with `skip` leading synthetic parameters removed.
253 /// Used to print `new` arguments with boolean/char constant adjustment.
254 fn ctor_param_types(
255 &self,
256 internal: &str,
257 skip: usize,
258 n: usize,
259 args: &[Expr],
260 ) -> Option<Vec<crate::types::JavaType>> {
261 let _ = (internal, skip, n, args);
262 None
263 }
264
265 /// Instantiated SAM return of a functional interface's method, resolved
266 /// against a cast's type arguments (`(Function<I,R>) lambda` needs
267 /// `(R) value` witnesses on the impl body's returns).
268 fn sam_ret_cast(&self, g: &crate::types::GenericType, sam_name: &str) -> Option<TypeRef> {
269 let _ = (g, sam_name);
270 None
271 }
272
273 /// True when `internal` declares class-level type parameters (so
274 /// `new internal<>(...)` should carry a diamond).
275 fn class_declares_generics(&self, internal: &str) -> bool {
276 !self.class_type_params(internal).is_empty()
277 }
278}
279
280/// A `Ctx` with no metadata: every query answers "unknown".
281///
282/// Useful for tests and for front-ends that have not implemented a query yet —
283/// the core degrades gracefully (no nesting assumptions, no generic casts).
284pub struct NullCtx {
285 pub class_name: String,
286 pub level: u16,
287}
288
289impl Default for NullCtx {
290 fn default() -> Self {
291 NullCtx {
292 class_name: String::new(),
293 level: 52,
294 }
295 }
296}
297
298impl Ctx for NullCtx {
299 fn class_name(&self) -> &str {
300 &self.class_name
301 }
302 fn source_level(&self) -> u16 {
303 self.level
304 }
305 fn find_outer(&self, _internal: &str) -> Option<String> {
306 None
307 }
308 fn family(&self, root: &str) -> Family {
309 Family {
310 root: root.to_string(),
311 ..Default::default()
312 }
313 }
314 fn nested_is_static(&self, _internal: &str) -> bool {
315 true
316 }
317 fn class_has_this0(&self, _internal: &str) -> bool {
318 false
319 }
320 fn is_subtype_of(&self, _sub: &crate::types::JavaType, _sup: &str) -> bool {
321 false
322 }
323 fn class_supers_args(
324 &self,
325 _internal: &str,
326 _args: &[crate::types::GenericType],
327 ) -> Vec<(String, Vec<crate::types::GenericType>)> {
328 Vec::new()
329 }
330 fn is_generic_call(&self, _e: &Expr) -> bool {
331 false
332 }
333 fn generic_call_formals(
334 &self,
335 _e: &Expr,
336 ) -> Option<(Vec<crate::types::GenericType>, Vec<String>)> {
337 None
338 }
339 fn polymorphic_ret_cast(
340 &self,
341 _cls: &str,
342 _name: &str,
343 _desc: &MethodDescriptor,
344 ) -> Option<crate::types::JavaType> {
345 None
346 }
347 fn ctor_formals_by_arity(
348 &self,
349 _internal: &str,
350 _arity: usize,
351 ) -> Option<Vec<crate::types::GenericType>> {
352 None
353 }
354 fn is_interface(&self, _internal: &str) -> bool {
355 false
356 }
357 fn is_sealed(&self, _internal: &str) -> bool {
358 false
359 }
360 fn has_class(&self, _internal: &str) -> bool {
361 false
362 }
363 fn class_bases(&self, _internal: &str) -> Option<(Vec<String>, Option<String>)> {
364 None
365 }
366 fn outer_param_via_super(&self, _internal: &str) -> bool {
367 false
368 }
369 fn nested_method(
370 &self,
371 _l: &crate::ir::expr::LambdaExpr,
372 _outer_vt: &crate::var::VarTable,
373 ) -> Option<MethodBody> {
374 None
375 }
376}
377
378/// Assemble a [`MethodBody`] (front-ends return these from `Ctx::nested_method`).
379pub fn ctx_method_body(
380 body: crate::ir::stmt::Stmt,
381 vt: crate::var::VarTable,
382 desc: MethodDescriptor,
383) -> MethodBody {
384 MethodBody { body, vt, desc }
385}