Skip to main content

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 any field whose RENDERED display
210    /// equals `display` (the registry's rename applied; the raw name
211    /// when no entry exists). Field references carry the DISPLAY name
212    /// at emit time, so shadow checks must compare in display space —
213    /// a raw-named field can render exactly the name another class's
214    /// field displays.
215    fn declares_field_display(&self, internal: &str, display: &str) -> bool {
216        let _ = (internal, display);
217        false
218    }
219
220    /// True when `internal` declares a method named `name` (any descriptor).
221    fn declares_method_named(&self, internal: &str, name: &str) -> bool {
222        let _ = (internal, name);
223        false
224    }
225
226    /// True when `internal` is a framework-shadow stub class (the
227    /// front-end relocates its FILE identity; references render the raw
228    /// framework FQN — the platform class is what the bytecode means).
229    fn is_fw_shadow(&self, internal: &str) -> bool {
230        let _ = internal;
231        false
232    }
233
234    /// True when `internal` is an interface.
235    fn is_interface(&self, internal: &str) -> bool;
236
237    /// True when `internal` is sealed (its permitted subclasses are recorded).
238    fn is_sealed(&self, internal: &str) -> bool;
239
240    /// True when the container holds this class at all (naming probes use
241    /// it to test `Outer$1Local`-style candidates).
242    fn has_class(&self, internal: &str) -> bool;
243
244    /// Interfaces and superclass of `internal` (internal names, declaration
245    /// order). `None` when the class is unknown to the front-end.
246    fn class_bases(&self, internal: &str) -> Option<(Vec<String>, Option<String>)>;
247
248    /// True when `internal` is an inner class whose constructor forwards its
249    /// enclosing instance straight to `super` (javac 21+ drops `this$0` in
250    /// that case, but call sites still need the qualified-new form).
251    fn outer_param_via_super(&self, internal: &str) -> bool;
252
253    /// Decompile the nested method a lambda site refers to — a lambda body,
254    /// an anonymous-class method, or a local-class method — and run the
255    /// front-end's own idiom recovery on it.
256    ///
257    /// This is where machine-specific desugaring lives: the shared emitter
258    /// asks for a finished statement tree and prints it. The `LambdaExpr`
259    /// carries the call-site facts (impl owner/name/descriptor, the SAM's
260    /// parameter names, the capture expressions, and any front-end
261    /// annotations it attached, e.g. capture snapshots); `outer_vt` is the
262    /// enclosing method's variable table — the lexical scope the body will be
263    /// printed in.
264    fn nested_method(
265        &self,
266        l: &crate::ir::expr::LambdaExpr,
267        outer_vt: &crate::var::VarTable,
268    ) -> Option<MethodBody>;
269
270    /// Parameter types of the `<init>` of `internal` matching `skip + n`
271    /// descriptor args, with `skip` leading synthetic parameters removed.
272    /// Used to print `new` arguments with boolean/char constant adjustment.
273    fn ctor_param_types(
274        &self,
275        internal: &str,
276        skip: usize,
277        n: usize,
278        args: &[Expr],
279    ) -> Option<Vec<crate::types::JavaType>> {
280        let _ = (internal, skip, n, args);
281        None
282    }
283
284    /// Instantiated SAM return of a functional interface's method, resolved
285    /// against a cast's type arguments (`(Function<I,R>) lambda` needs
286    /// `(R) value` witnesses on the impl body's returns).
287    fn sam_ret_cast(&self, g: &crate::types::GenericType, sam_name: &str) -> Option<TypeRef> {
288        let _ = (g, sam_name);
289        None
290    }
291
292    /// True when `internal` declares class-level type parameters (so
293    /// `new internal<>(...)` should carry a diamond).
294    fn class_declares_generics(&self, internal: &str) -> bool {
295        !self.class_type_params(internal).is_empty()
296    }
297}
298
299/// A `Ctx` with no metadata: every query answers "unknown".
300///
301/// Useful for tests and for front-ends that have not implemented a query yet —
302/// the core degrades gracefully (no nesting assumptions, no generic casts).
303pub struct NullCtx {
304    pub class_name: String,
305    pub level: u16,
306}
307
308impl Default for NullCtx {
309    fn default() -> Self {
310        NullCtx {
311            class_name: String::new(),
312            level: 52,
313        }
314    }
315}
316
317impl Ctx for NullCtx {
318    fn class_name(&self) -> &str {
319        &self.class_name
320    }
321    fn source_level(&self) -> u16 {
322        self.level
323    }
324    fn find_outer(&self, _internal: &str) -> Option<String> {
325        None
326    }
327    fn family(&self, root: &str) -> Family {
328        Family {
329            root: root.to_string(),
330            ..Default::default()
331        }
332    }
333    fn nested_is_static(&self, _internal: &str) -> bool {
334        true
335    }
336    fn class_has_this0(&self, _internal: &str) -> bool {
337        false
338    }
339    fn is_subtype_of(&self, _sub: &crate::types::JavaType, _sup: &str) -> bool {
340        false
341    }
342    fn class_supers_args(
343        &self,
344        _internal: &str,
345        _args: &[crate::types::GenericType],
346    ) -> Vec<(String, Vec<crate::types::GenericType>)> {
347        Vec::new()
348    }
349    fn is_generic_call(&self, _e: &Expr) -> bool {
350        false
351    }
352    fn generic_call_formals(
353        &self,
354        _e: &Expr,
355    ) -> Option<(Vec<crate::types::GenericType>, Vec<String>)> {
356        None
357    }
358    fn polymorphic_ret_cast(
359        &self,
360        _cls: &str,
361        _name: &str,
362        _desc: &MethodDescriptor,
363    ) -> Option<crate::types::JavaType> {
364        None
365    }
366    fn ctor_formals_by_arity(
367        &self,
368        _internal: &str,
369        _arity: usize,
370    ) -> Option<Vec<crate::types::GenericType>> {
371        None
372    }
373    fn is_interface(&self, _internal: &str) -> bool {
374        false
375    }
376    fn is_sealed(&self, _internal: &str) -> bool {
377        false
378    }
379    fn has_class(&self, _internal: &str) -> bool {
380        false
381    }
382    fn class_bases(&self, _internal: &str) -> Option<(Vec<String>, Option<String>)> {
383        None
384    }
385    fn outer_param_via_super(&self, _internal: &str) -> bool {
386        false
387    }
388    fn nested_method(
389        &self,
390        _l: &crate::ir::expr::LambdaExpr,
391        _outer_vt: &crate::var::VarTable,
392    ) -> Option<MethodBody> {
393        None
394    }
395}
396
397/// Assemble a [`MethodBody`] (front-ends return these from `Ctx::nested_method`).
398pub fn ctx_method_body(
399    body: crate::ir::stmt::Stmt,
400    vt: crate::var::VarTable,
401    desc: MethodDescriptor,
402) -> MethodBody {
403    MethodBody { body, vt, desc }
404}