Skip to main content

ferro_jtype/
result.rs

1use crate::{
2    ClassName, Diagnostic, DynamicCallKind, GenericSignature, InferredType, MethodDescriptor,
3    ReturnType, TypeDescriptor,
4};
5
6/// Type-inference results for one Java class file.
7///
8/// Diagnostics describe recoverable conditions observed while processing the
9/// class. Inspect them when consuming inference from malformed, unsupported,
10/// or intentionally obfuscated bytecode.
11#[derive(Debug, Clone)]
12pub struct ClassInference {
13    class_name: ClassName,
14    generic_signature: Option<GenericSignature>,
15    methods: Vec<MethodInference>,
16    diagnostics: Vec<Diagnostic>,
17}
18
19impl ClassInference {
20    pub(crate) fn new(
21        class_name: ClassName,
22        generic_signature: Option<GenericSignature>,
23        methods: Vec<MethodInference>,
24        diagnostics: Vec<Diagnostic>,
25    ) -> Self {
26        Self {
27            class_name,
28            generic_signature,
29            methods,
30            diagnostics,
31        }
32    }
33
34    /// Returns the JVM internal name of the analyzed class.
35    #[must_use]
36    pub const fn class_name(&self) -> &ClassName {
37        &self.class_name
38    }
39
40    /// Returns the class's generic `Signature` attribute, when present.
41    #[must_use]
42    pub const fn generic_signature(&self) -> Option<&GenericSignature> {
43        self.generic_signature.as_ref()
44    }
45
46    /// Returns one inference result for each method in the class file.
47    #[must_use]
48    pub fn methods(&self) -> &[MethodInference] {
49        &self.methods
50    }
51
52    /// Returns diagnostics emitted while analyzing the class.
53    #[must_use]
54    pub fn diagnostics(&self) -> &[Diagnostic] {
55        &self.diagnostics
56    }
57
58    /// Returns whether every method reached a fixed point within configured limits.
59    ///
60    /// This does not hide instruction-level diagnostics; inspect
61    /// [`Self::diagnostics`] for unsupported or malformed bytecode details.
62    #[must_use]
63    pub fn analysis_complete(&self) -> bool {
64        self.methods.iter().all(MethodInference::analysis_complete)
65    }
66
67    pub(crate) fn mark_batch_analysis_incomplete(&mut self) {
68        for method in &mut self.methods {
69            method.mark_analysis_incomplete();
70        }
71        self.diagnostics.push(Diagnostic::new(
72            crate::DiagnosticSeverity::Error,
73            crate::DiagnosticKind::AnalysisLimitReached,
74            crate::DiagnosticLocation::class_level(),
75            "batch method-summary work-item budget was reached",
76        ));
77    }
78}
79
80/// Type-inference results for a caller-supplied batch of class files.
81///
82/// Entries retain the input order. Each JVM internal class name may occur only
83/// once in a batch.
84#[derive(Debug, Clone)]
85pub struct ClassInferences {
86    classes: Vec<ClassInference>,
87}
88
89impl ClassInferences {
90    pub(crate) const fn new(classes: Vec<ClassInference>) -> Self {
91        Self { classes }
92    }
93
94    /// Returns inference results in the same order as the input class files.
95    #[must_use]
96    pub fn classes(&self) -> &[ClassInference] {
97        &self.classes
98    }
99
100    /// Returns the result for one JVM internal class name.
101    #[must_use]
102    pub fn get(&self, class_name: &ClassName) -> Option<&ClassInference> {
103        self.classes
104            .iter()
105            .find(|inference| inference.class_name() == class_name)
106    }
107
108    /// Returns the number of analyzed class files.
109    #[must_use]
110    pub const fn len(&self) -> usize {
111        self.classes.len()
112    }
113
114    /// Returns whether the batch contains no class files.
115    #[must_use]
116    pub const fn is_empty(&self) -> bool {
117        self.classes.is_empty()
118    }
119
120    /// Returns whether analysis completed for every class in the batch.
121    #[must_use]
122    pub fn analysis_complete(&self) -> bool {
123        self.classes.iter().all(ClassInference::analysis_complete)
124    }
125}
126
127/// Type-inference results for one method.
128///
129/// Parameter and return types come from the method descriptor. Local-variable
130/// and instruction states are inferred from the method's bytecode.
131#[derive(Debug, Clone)]
132pub struct MethodInference {
133    name: String,
134    descriptor: MethodDescriptor,
135    generic_signature: Option<GenericSignature>,
136    analysis_complete: bool,
137    parameter_types: Vec<InferredType>,
138    return_type: ReturnType,
139    inferred_return_type: Option<InferredType>,
140    returned_parameter_index: Option<usize>,
141    local_types: Vec<InferredType>,
142    instructions: Vec<InstructionInference>,
143}
144
145pub(crate) struct MethodHeader {
146    pub(crate) descriptor: MethodDescriptor,
147    pub(crate) generic_signature: Option<GenericSignature>,
148    pub(crate) analysis_complete: bool,
149    pub(crate) parameter_types: Vec<InferredType>,
150    pub(crate) return_type: ReturnType,
151    pub(crate) inferred_return_type: Option<InferredType>,
152    pub(crate) returned_parameter_index: Option<usize>,
153}
154
155impl MethodInference {
156    pub(crate) fn new(
157        name: String,
158        header: MethodHeader,
159        local_types: Vec<InferredType>,
160        instructions: Vec<InstructionInference>,
161    ) -> Self {
162        Self {
163            name,
164            descriptor: header.descriptor,
165            generic_signature: header.generic_signature,
166            analysis_complete: header.analysis_complete,
167            parameter_types: header.parameter_types,
168            return_type: header.return_type,
169            inferred_return_type: header.inferred_return_type,
170            returned_parameter_index: header.returned_parameter_index,
171            local_types,
172            instructions,
173        }
174    }
175
176    /// Returns the method name as stored in the class file.
177    #[must_use]
178    pub fn name(&self) -> &str {
179        &self.name
180    }
181
182    /// Returns the parsed JVM method descriptor.
183    #[must_use]
184    pub const fn descriptor(&self) -> &MethodDescriptor {
185        &self.descriptor
186    }
187
188    /// Returns the method's generic `Signature` attribute, when present.
189    #[must_use]
190    pub const fn generic_signature(&self) -> Option<&GenericSignature> {
191        self.generic_signature.as_ref()
192    }
193
194    /// Returns whether analysis reached a fixed point within configured limits.
195    #[must_use]
196    pub const fn analysis_complete(&self) -> bool {
197        self.analysis_complete
198    }
199
200    /// Returns the descriptor-derived parameter types in declaration order.
201    #[must_use]
202    pub fn parameter_types(&self) -> &[InferredType] {
203        &self.parameter_types
204    }
205
206    /// Returns the descriptor-derived method return type.
207    #[must_use]
208    pub const fn return_type(&self) -> &ReturnType {
209        &self.return_type
210    }
211
212    /// Returns the inferred value type observed at reachable value-return instructions.
213    ///
214    /// This is more precise than [`Self::return_type`] when a method declares a
215    /// broad reference type but consistently returns a narrower one. `None`
216    /// means the method is void, did not reach a value return, or did not reach
217    /// a complete, descriptor-compatible fixed point.
218    #[must_use]
219    pub const fn inferred_return_type(&self) -> Option<&InferredType> {
220        self.inferred_return_type.as_ref()
221    }
222
223    /// Returns the parameter index returned unchanged by every reachable value return.
224    ///
225    /// This enables direct-call inference to use an argument's actual type. The
226    /// index is in declaration order and excludes an instance method's implicit
227    /// `this` receiver. `None` means no single parameter source was proven.
228    #[must_use]
229    pub const fn returned_parameter_index(&self) -> Option<usize> {
230        self.returned_parameter_index
231    }
232
233    pub(crate) fn mark_analysis_incomplete(&mut self) {
234        self.analysis_complete = false;
235        self.inferred_return_type = None;
236        self.returned_parameter_index = None;
237    }
238
239    /// Returns inferred local-variable types indexed by JVM local slot.
240    ///
241    /// Aggregates the types observed across the method, including separate
242    /// lifetimes of a reused slot. Distinct reference candidates are retained
243    /// rather than collapsed to a hierarchy-derived common supertype here.
244    #[must_use]
245    pub fn local_types(&self) -> &[InferredType] {
246        &self.local_types
247    }
248
249    /// Returns type states for modeled bytecode instructions.
250    #[must_use]
251    pub fn instructions(&self) -> &[InstructionInference] {
252        &self.instructions
253    }
254}
255
256/// Inferred abstract state at one bytecode instruction.
257///
258/// The local-variable and operand-stack slices describe the state immediately
259/// before and immediately after the instruction at [`Self::bytecode_offset`].
260#[derive(Debug, Clone)]
261pub struct InstructionInference {
262    bytecode_offset: u16,
263    dynamic_call_kind: Option<DynamicCallKind>,
264    operand_expectations: Vec<OperandExpectation>,
265    local_types: std::sync::Arc<[InferredType]>,
266    stack_before: Vec<InferredType>,
267    stack_after: Vec<InferredType>,
268}
269
270impl InstructionInference {
271    pub(crate) fn new(
272        bytecode_offset: u16,
273        dynamic_call_kind: Option<DynamicCallKind>,
274        operand_expectations: Vec<OperandExpectation>,
275        local_types: std::sync::Arc<[InferredType]>,
276        stack_before: Vec<InferredType>,
277        stack_after: Vec<InferredType>,
278    ) -> Self {
279        Self {
280            bytecode_offset,
281            dynamic_call_kind,
282            operand_expectations,
283            local_types,
284            stack_before,
285            stack_after,
286        }
287    }
288
289    /// Returns this instruction's offset within its method's `Code` attribute.
290    #[must_use]
291    pub const fn bytecode_offset(&self) -> u16 {
292        self.bytecode_offset
293    }
294
295    /// Returns recognized bootstrap metadata for an `invokedynamic` instruction.
296    #[must_use]
297    pub const fn dynamic_call_kind(&self) -> Option<DynamicCallKind> {
298        self.dynamic_call_kind
299    }
300
301    /// Returns verifier-derived requirements for operands consumed by this instruction.
302    ///
303    /// Each expectation names an index into [`Self::stack_before`]. The index
304    /// uses that slice's bottom-to-top order. Member calls, `invokedynamic`,
305    /// field stores, and value returns report constraints when their descriptors
306    /// and a complete operand stack are available. This does not execute a
307    /// bootstrap method or alter the observed inferred types.
308    #[must_use]
309    pub fn operand_expectations(&self) -> &[OperandExpectation] {
310        &self.operand_expectations
311    }
312
313    /// Returns local-variable types immediately before this instruction.
314    ///
315    /// Values from different or unproven origins retain reference alternatives
316    /// at joins. A reference hierarchy may refine joins of the same proven value.
317    #[must_use]
318    pub fn local_types(&self) -> &[InferredType] {
319        &self.local_types
320    }
321
322    /// Returns operand-stack types immediately before this instruction.
323    #[must_use]
324    pub fn stack_before(&self) -> &[InferredType] {
325        &self.stack_before
326    }
327
328    /// Returns operand-stack types immediately after this instruction.
329    #[must_use]
330    pub fn stack_after(&self) -> &[InferredType] {
331        &self.stack_after
332    }
333}
334
335/// A verifier-derived type requirement for one operand-stack value.
336///
337/// The index identifies a value in [`InstructionInference::stack_before`].
338/// It is not an assertion that the observed value has one exact allocation
339/// class: receiver requirements are assignability constraints.
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub struct OperandExpectation {
342    stack_index: usize,
343    constraint: OperandConstraint,
344}
345
346impl OperandExpectation {
347    pub(crate) const fn new(stack_index: usize, constraint: OperandConstraint) -> Self {
348        Self {
349            stack_index,
350            constraint,
351        }
352    }
353
354    /// Returns the zero-based index in [`InstructionInference::stack_before`].
355    #[must_use]
356    pub const fn stack_index(&self) -> usize {
357        self.stack_index
358    }
359
360    /// Returns the JVM requirement imposed on the value at [`Self::stack_index`].
361    #[must_use]
362    pub const fn constraint(&self) -> &OperandConstraint {
363        &self.constraint
364    }
365}
366
367/// The JVM type condition required for an instruction operand.
368#[derive(Debug, Clone, PartialEq, Eq)]
369pub enum OperandConstraint {
370    /// The operand must have the category described by this JVM descriptor.
371    Descriptor(TypeDescriptor),
372    /// The operand is an instance receiver assignable to this member owner.
373    ReceiverAssignableTo(ClassName),
374}