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