rapx/check/opt/data_collection/reallocation/
unreserved_vec.rs1use crate::{
2 analysis::dataflow::*,
3 check::opt::OptCheck,
4};
5use rustc_hir::intravisit;
6use rustc_middle::mir::Local;
7use rustc_middle::ty::TyCtxt;
8
9use annotate_snippets::Level;
10use rustc_span::Span;
11
12use crate::check::opt::report::OptReport;
13use crate::check::opt::check_utils::node_matches_call;
14
15use super::super::super::loop_visitors::LoopFinder;
16use super::super::super::LEVEL;
17
18crate::def_paths! {
19 vec_new: "std::vec::Vec::new",
20 vec_push: "std::vec::Vec::push",
21 vec_with_capacity: "std::vec::Vec::with_capacity",
22 vec_reserve: "std::vec::Vec::reserve",
23}
24
25
26pub struct UnreservedVecCheck {
27 record: Vec<Span>,
28}
29
30fn find_upside_reservation(graph: &Graph, node_idx: Local) -> Option<Local> {
31 let def_paths = &DEFPATHS.get().unwrap();
32 graph.find_first_node(
33 node_idx,
34 Direction::Upside,
35 &mut |graph: &Graph, idx: Local| {
36 let node = &graph.nodes[idx];
37 for op in node.ops.iter() {
38 if let NodeOp::Call(def_id) = op {
39 if *def_id == def_paths.vec_with_capacity.last_def_id()
40 || *def_id == def_paths.vec_reserve.last_def_id()
41 {
42 return true;
43 }
44 }
45 }
46 false
47 },
48 &mut Graph::equivalent_edge_validator,
49 )
50}
51
52impl OptCheck for UnreservedVecCheck {
53 fn new() -> Self {
54 Self { record: Vec::new() }
55 }
56
57 fn check(&mut self, graph: &Graph, tcx: &TyCtxt) {
58 let def_paths = &DEFPATHS.get_or_init(|| DefPaths::new(tcx));
59 let level = LEVEL.lock().unwrap();
60 if *level == 2 {
61 for (node_idx, node) in graph.nodes.iter_enumerated() {
62 if node_matches_call(node, &[def_paths.vec_new.last_def_id()]) {
63 self.record.push(node.span);
64 }
65 if node_matches_call(node, &[def_paths.vec_push.last_def_id()]) {
66 if let None = find_upside_reservation(graph, node_idx) {
67 self.record.push(node.span);
68 }
69 }
70 }
71 }
72
73 let def_id = graph.def_id;
74 let body = tcx.hir_body_owned_by(def_id.as_local().unwrap());
75 let typeck_results = tcx.typeck(def_id.as_local().unwrap());
76 let target_def_id = def_paths.vec_push.last_def_id();
77 let mut loop_finder = LoopFinder::new(typeck_results, target_def_id);
78 intravisit::walk_body(&mut loop_finder, body);
79 for (_, push_record) in loop_finder.into_record() {
80 for push_span in push_record {
81 if let Some((node_idx, _)) = graph.query_node_by_span(push_span, false) {
82 if let None = find_upside_reservation(graph, node_idx) {
83 self.record.push(push_span);
84 }
85 }
86 }
87 }
88 }
89
90 fn report(&self, graph: &Graph) {
91 for span in self.record.iter() {
92 report_unreserved_vec_bug(graph, *span);
93 }
94 }
95
96 fn cnt(&self) -> usize {
97 self.record.len()
98 }
99}
100
101fn report_unreserved_vec_bug(graph: &Graph, span: Span) {
102 OptReport::from_graph(graph)
103 .file_name(span)
104 .title("Improper data collection detected")
105 .annotate(Level::Error, span, "Space unreserved.")
106 .footer("Reserve enough space.")
107 .emit();
108}