Skip to main content

ClassInferences

Struct ClassInferences 

Source
pub struct ClassInferences { /* private fields */ }
Expand description

Type-inference results for a caller-supplied batch of class files.

Entries retain the input order. Each JVM internal class name may occur only once in a batch.

Implementations§

Source§

impl ClassInferences

Source

pub fn classes(&self) -> &[ClassInference]

Returns inference results in the same order as the input class files.

Examples found in repository?
examples/support/comparison.rs (line 15)
5pub fn report(label: &str, result: &ClassInferences) {
6    let mut methods = 0;
7    let mut instructions = 0;
8    let mut diagnostics = 0;
9    let mut unknown = 0;
10    let mut conflict = 0;
11    let mut bottom = 0;
12    let mut alternatives = 0;
13    let mut integral_all = 0;
14    let mut expectations = 0;
15    for class in result.classes() {
16        diagnostics += class.diagnostics().len();
17        for method in class.methods() {
18            methods += 1;
19            for instruction in method.instructions() {
20                instructions += 1;
21                expectations += instruction.operand_expectations().len();
22                for value in instruction
23                    .stack_before()
24                    .iter()
25                    .chain(instruction.stack_after())
26                {
27                    unknown += usize::from(contains(
28                        value,
29                        &InferredType::Reference(ReferenceType::Unknown),
30                    ));
31                    conflict += usize::from(contains(value, &InferredType::Conflict));
32                    bottom += usize::from(contains(value, &InferredType::Bottom));
33                    alternatives += usize::from(matches!(value, InferredType::Alternatives(_)));
34                    integral_all +=
35                        usize::from(value.integral_types() == Some(IntegralTypeSet::ALL));
36                }
37            }
38        }
39    }
40    println!(
41        "{label}: classes={}, methods={methods}, instructions={instructions}, complete={}, diagnostics={diagnostics}, stack unknown={unknown}, conflict={conflict}, bottom={bottom}, alternatives={alternatives}",
42        result.len(),
43        result.analysis_complete()
44    );
45    println!(
46        "  operand constraints={expectations}, stack values with all integral candidates={integral_all}"
47    );
48}
49
50fn contains(value: &InferredType, needle: &InferredType) -> bool {
51    value == needle
52        || matches!(value, InferredType::Alternatives(values) if values.iter().any(|value| contains(value, needle)))
53}
54
55pub fn compare(left: &ClassInferences, right: &ClassInferences) {
56    let mut changed = 0;
57    let mut stacks = 0;
58    let mut locals = 0;
59    let mut coverage = 0;
60    let mut returns = 0;
61    let mut method_locals = 0;
62    let mut constraints = 0;
63    assert_eq!(
64        left.len(),
65        right.len(),
66        "the same inputs must retain class metadata"
67    );
68    for (class, other) in left.classes().iter().zip(right.classes()) {
69        assert_eq!(class.class_name(), other.class_name());
70        assert_eq!(class.methods().len(), other.methods().len());
71        for (method, other) in class.methods().iter().zip(other.methods()) {
72            assert_eq!(method.name(), other.name());
73            assert_eq!(method.descriptor(), other.descriptor());
74            returns += usize::from(method.inferred_return_type() != other.inferred_return_type());
75            method_locals += usize::from(method.local_types() != other.local_types());
76            let before = method
77                .instructions()
78                .iter()
79                .map(|i| (i.bytecode_offset(), i))
80                .collect::<BTreeMap<_, _>>();
81            let after = other
82                .instructions()
83                .iter()
84                .map(|i| (i.bytecode_offset(), i))
85                .collect::<BTreeMap<_, _>>();
86            let offsets = before
87                .keys()
88                .chain(after.keys())
89                .copied()
90                .collect::<BTreeSet<_>>();
91            let mut method_changes = 0;
92            for offset in offsets {
93                let (Some(instruction), Some(other)) = (before.get(&offset), after.get(&offset))
94                else {
95                    coverage += 1;
96                    continue;
97                };
98                let local_changed = instruction.local_types() != other.local_types();
99                let stack_changed = instruction.stack_before() != other.stack_before()
100                    || instruction.stack_after() != other.stack_after();
101                locals += usize::from(local_changed);
102                stacks += usize::from(stack_changed);
103                constraints +=
104                    usize::from(instruction.operand_expectations() != other.operand_expectations());
105                if local_changed || stack_changed {
106                    changed += 1;
107                    method_changes += 1;
108                }
109            }
110            if method_changes != 0 {
111                println!(
112                    "  {}.{} {:?}: {method_changes} instruction states differ",
113                    class.class_name(),
114                    method.name(),
115                    method.descriptor()
116                );
117            }
118        }
119    }
120    println!(
121        "Differences: instructions={changed}, stacks={stacks}, locals={locals}, reachability={coverage}, returns={returns}, method-local summaries={method_locals}, operand constraints={constraints}"
122    );
123    println!(
124        "Bottom in unused locals and category-two companion slots is not a missing type. Reference alternatives are retained evidence, not Unknown. Completion is not proof of recovered source types."
125    );
126}
Source

pub fn get(&self, class_name: &ClassName) -> Option<&ClassInference>

Returns the result for one JVM internal class name.

Source

pub const fn len(&self) -> usize

Returns the number of analyzed class files.

Examples found in repository?
examples/support/comparison.rs (line 42)
5pub fn report(label: &str, result: &ClassInferences) {
6    let mut methods = 0;
7    let mut instructions = 0;
8    let mut diagnostics = 0;
9    let mut unknown = 0;
10    let mut conflict = 0;
11    let mut bottom = 0;
12    let mut alternatives = 0;
13    let mut integral_all = 0;
14    let mut expectations = 0;
15    for class in result.classes() {
16        diagnostics += class.diagnostics().len();
17        for method in class.methods() {
18            methods += 1;
19            for instruction in method.instructions() {
20                instructions += 1;
21                expectations += instruction.operand_expectations().len();
22                for value in instruction
23                    .stack_before()
24                    .iter()
25                    .chain(instruction.stack_after())
26                {
27                    unknown += usize::from(contains(
28                        value,
29                        &InferredType::Reference(ReferenceType::Unknown),
30                    ));
31                    conflict += usize::from(contains(value, &InferredType::Conflict));
32                    bottom += usize::from(contains(value, &InferredType::Bottom));
33                    alternatives += usize::from(matches!(value, InferredType::Alternatives(_)));
34                    integral_all +=
35                        usize::from(value.integral_types() == Some(IntegralTypeSet::ALL));
36                }
37            }
38        }
39    }
40    println!(
41        "{label}: classes={}, methods={methods}, instructions={instructions}, complete={}, diagnostics={diagnostics}, stack unknown={unknown}, conflict={conflict}, bottom={bottom}, alternatives={alternatives}",
42        result.len(),
43        result.analysis_complete()
44    );
45    println!(
46        "  operand constraints={expectations}, stack values with all integral candidates={integral_all}"
47    );
48}
49
50fn contains(value: &InferredType, needle: &InferredType) -> bool {
51    value == needle
52        || matches!(value, InferredType::Alternatives(values) if values.iter().any(|value| contains(value, needle)))
53}
54
55pub fn compare(left: &ClassInferences, right: &ClassInferences) {
56    let mut changed = 0;
57    let mut stacks = 0;
58    let mut locals = 0;
59    let mut coverage = 0;
60    let mut returns = 0;
61    let mut method_locals = 0;
62    let mut constraints = 0;
63    assert_eq!(
64        left.len(),
65        right.len(),
66        "the same inputs must retain class metadata"
67    );
68    for (class, other) in left.classes().iter().zip(right.classes()) {
69        assert_eq!(class.class_name(), other.class_name());
70        assert_eq!(class.methods().len(), other.methods().len());
71        for (method, other) in class.methods().iter().zip(other.methods()) {
72            assert_eq!(method.name(), other.name());
73            assert_eq!(method.descriptor(), other.descriptor());
74            returns += usize::from(method.inferred_return_type() != other.inferred_return_type());
75            method_locals += usize::from(method.local_types() != other.local_types());
76            let before = method
77                .instructions()
78                .iter()
79                .map(|i| (i.bytecode_offset(), i))
80                .collect::<BTreeMap<_, _>>();
81            let after = other
82                .instructions()
83                .iter()
84                .map(|i| (i.bytecode_offset(), i))
85                .collect::<BTreeMap<_, _>>();
86            let offsets = before
87                .keys()
88                .chain(after.keys())
89                .copied()
90                .collect::<BTreeSet<_>>();
91            let mut method_changes = 0;
92            for offset in offsets {
93                let (Some(instruction), Some(other)) = (before.get(&offset), after.get(&offset))
94                else {
95                    coverage += 1;
96                    continue;
97                };
98                let local_changed = instruction.local_types() != other.local_types();
99                let stack_changed = instruction.stack_before() != other.stack_before()
100                    || instruction.stack_after() != other.stack_after();
101                locals += usize::from(local_changed);
102                stacks += usize::from(stack_changed);
103                constraints +=
104                    usize::from(instruction.operand_expectations() != other.operand_expectations());
105                if local_changed || stack_changed {
106                    changed += 1;
107                    method_changes += 1;
108                }
109            }
110            if method_changes != 0 {
111                println!(
112                    "  {}.{} {:?}: {method_changes} instruction states differ",
113                    class.class_name(),
114                    method.name(),
115                    method.descriptor()
116                );
117            }
118        }
119    }
120    println!(
121        "Differences: instructions={changed}, stacks={stacks}, locals={locals}, reachability={coverage}, returns={returns}, method-local summaries={method_locals}, operand constraints={constraints}"
122    );
123    println!(
124        "Bottom in unused locals and category-two companion slots is not a missing type. Reference alternatives are retained evidence, not Unknown. Completion is not proof of recovered source types."
125    );
126}
Source

pub const fn is_empty(&self) -> bool

Returns whether the batch contains no class files.

Source

pub fn analysis_complete(&self) -> bool

Returns whether analysis completed for every class in the batch.

Examples found in repository?
examples/support/comparison.rs (line 43)
5pub fn report(label: &str, result: &ClassInferences) {
6    let mut methods = 0;
7    let mut instructions = 0;
8    let mut diagnostics = 0;
9    let mut unknown = 0;
10    let mut conflict = 0;
11    let mut bottom = 0;
12    let mut alternatives = 0;
13    let mut integral_all = 0;
14    let mut expectations = 0;
15    for class in result.classes() {
16        diagnostics += class.diagnostics().len();
17        for method in class.methods() {
18            methods += 1;
19            for instruction in method.instructions() {
20                instructions += 1;
21                expectations += instruction.operand_expectations().len();
22                for value in instruction
23                    .stack_before()
24                    .iter()
25                    .chain(instruction.stack_after())
26                {
27                    unknown += usize::from(contains(
28                        value,
29                        &InferredType::Reference(ReferenceType::Unknown),
30                    ));
31                    conflict += usize::from(contains(value, &InferredType::Conflict));
32                    bottom += usize::from(contains(value, &InferredType::Bottom));
33                    alternatives += usize::from(matches!(value, InferredType::Alternatives(_)));
34                    integral_all +=
35                        usize::from(value.integral_types() == Some(IntegralTypeSet::ALL));
36                }
37            }
38        }
39    }
40    println!(
41        "{label}: classes={}, methods={methods}, instructions={instructions}, complete={}, diagnostics={diagnostics}, stack unknown={unknown}, conflict={conflict}, bottom={bottom}, alternatives={alternatives}",
42        result.len(),
43        result.analysis_complete()
44    );
45    println!(
46        "  operand constraints={expectations}, stack values with all integral candidates={integral_all}"
47    );
48}
More examples
Hide additional examples
examples/infer_jrt.rs (line 48)
8fn main() -> Result<(), Box<dyn Error>> {
9    let arguments = env::args_os().skip(1).collect::<Vec<_>>();
10    if arguments.len() != 2 {
11        return Err("usage: cargo run --example infer_jrt -- <class-or-jar> <jdk-java-executable> (JDK 11+)".into());
12    }
13    let classes = read_classes(Path::new(&arguments[0]))?;
14    let mut input_hierarchy = ClassHierarchy::new();
15    for bytes in &classes {
16        input_hierarchy.insert_class(bytes)?;
17    }
18    let without_config =
19        InferenceConfig::default().with_shared_type_hierarchy(Arc::new(input_hierarchy));
20    let without_jrt = Inferer::new(without_config)?.infer_classes(&classes)?;
21    eprintln!("Reading jrt:/ from the selected JDK; target classes are never executed.");
22    let export = Command::new(&arguments[1])
23        .arg(concat!(
24            env!("CARGO_MANIFEST_DIR"),
25            "/examples/support/ExportJrt.java"
26        ))
27        .output()?;
28    if !export.status.success() {
29        return Err(format!(
30            "jrt export failed: {}",
31            String::from_utf8_lossy(&export.stderr)
32        )
33        .into());
34    }
35    let mut hierarchy = ClassHierarchy::new();
36    let reference_count = hierarchy.insert_jar(&export.stdout)?;
37    drop(export);
38    for bytes in &classes {
39        hierarchy.insert_class(bytes)?;
40    }
41    let config = InferenceConfig::default().with_shared_type_hierarchy(Arc::new(hierarchy));
42    let with_jrt = Inferer::new(config)?.infer_classes(&classes)?;
43    println!("JDK reference classes: {reference_count}");
44    println!("Both modes index the input class headers; only the second adds jrt.");
45    comparison::report("without jrt", &without_jrt);
46    comparison::report("with jrt", &with_jrt);
47    comparison::compare(&without_jrt, &with_jrt);
48    if !without_jrt.analysis_complete() || !with_jrt.analysis_complete() {
49        return Err("analysis did not reach a fixed point".into());
50    }
51    Ok(())
52}

Trait Implementations§

Source§

impl Clone for ClassInferences

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ClassInferences

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.