Skip to main content

rapx/check/opt/data_collection/initialization/
local_set.rs

1use annotate_snippets::Level;
2
3use crate::{analysis::dataflow::*, check::opt::OptCheck};
4use rustc_middle::{mir::Local, ty::TyCtxt};
5use rustc_span::Span;
6
7use crate::check::opt::check_utils::node_matches_any_call;
8use crate::check::opt::report::OptReport;
9
10crate::def_paths! {
11    hashset_new: "std::collections::HashSet::new",
12    hashset_with_capacity: "std::collections::HashSet::with_capacity",
13    hashmap_new: "std::collections::HashMap::new",
14    hashmap_with_capacity: "std::collections::HashMap::with_capacity",
15    btreeset_new: "std::collections::BTreeSet::new",
16    btreemap_new: "std::collections::BTreeMap::new",
17}
18
19pub struct LocalSetCheck {
20    record: Vec<Span>,
21}
22
23impl OptCheck for LocalSetCheck {
24    fn new() -> Self {
25        Self { record: Vec::new() }
26    }
27
28    fn check(&mut self, graph: &Graph, tcx: &TyCtxt) {
29        let def_paths = &DEFPATHS.get_or_init(|| DefPaths::new(tcx));
30        for (node_idx, node) in graph.nodes.iter_enumerated() {
31            if node_matches_any_call(node, |id| {
32                id == def_paths.hashset_new.last_def_id()
33                    || id == def_paths.hashmap_new.last_def_id()
34                    || id == def_paths.btreemap_new.last_def_id()
35                    || id == def_paths.btreeset_new.last_def_id()
36                    || id == def_paths.hashmap_with_capacity.last_def_id()
37                    || id == def_paths.hashset_with_capacity.last_def_id()
38            }) && !graph.is_connected(Local::from_usize(0), node_idx)
39            {
40                self.record.push(node.span);
41            }
42        }
43    }
44
45    fn report(&self, graph: &Graph) {
46        for span in self.record.iter() {
47            report_local_set(graph, *span);
48        }
49    }
50
51    fn cnt(&self) -> usize {
52        self.record.len()
53    }
54}
55
56fn report_local_set(graph: &Graph, span: Span) {
57    OptReport::from_graph(graph)
58        .file_name(span)
59        .title("Unnecessary data collection initialization detected")
60        .annotate(Level::Error, span, "Initialization happens here")
61        .footer("Move it into parameter list and use hash table to save allocation.")
62        .emit();
63}