rapx/analysis/core/
heap_analysis.rs

1pub mod default;
2
3use rustc_middle::ty::{Ty, TyKind};
4use rustc_span::def_id::DefId;
5
6use std::{
7    collections::{HashMap, HashSet},
8    env, fmt,
9};
10
11use crate::{rap_info, Analysis};
12
13#[repr(u8)]
14#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
15pub enum HeapInfo {
16    False = 0,
17    True = 1,
18    Unknown = 2,
19}
20
21impl Default for HeapInfo {
22    fn default() -> Self {
23        Self::Unknown
24    }
25}
26
27impl HeapInfo {
28    pub fn is_onheap(&self) -> bool {
29        match self {
30            HeapInfo::True => true,
31            _ => false,
32        }
33    }
34}
35
36impl fmt::Display for HeapInfo {
37    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
38        let name = match self {
39            HeapInfo::False => "0",
40            HeapInfo::True => "1",
41            HeapInfo::Unknown => "2",
42        };
43        write!(f, "{}", name)
44    }
45}
46
47/// This is the type for storing the heap analysis results.
48/// The result is represented as a hashmap, where the key is `DefId` and the value contains the
49/// information of whether the type contains data on heap.
50/// Since a type may have multiple fields, the value is represented as a vec, indicating the heap
51/// information of each field.
52/// Also, because it may contain type parameters or generic types,
53/// the heap information is a tuple containing the information of each type parameter.
54pub type HAResult = HashMap<DefId, Vec<(HeapInfo, Vec<bool>)>>;
55
56pub trait HeapAnalysis: Analysis {
57    fn get_all_items(&mut self) -> HAResult;
58    fn is_onheap<'tcx>(hares: HAResult, ty: Ty<'tcx>) -> Result<bool, &'static str> {
59        match ty.kind() {
60            TyKind::Adt(adtdef, ..) => {
61                let ans = hares.get(&adtdef.0 .0.did).unwrap();
62                if ans[0].0 == HeapInfo::True {
63                    return Ok(true);
64                }
65                Ok(false)
66            }
67            _ => Err("The input is not an ADT"),
68        }
69    }
70}