rapx/analysis/opt/data_collection/initialization/
vec_init.rs

1use annotate_snippets::{Level, Renderer, Snippet};
2
3use once_cell::sync::OnceCell;
4
5use rustc_hir::def_id::DefId;
6use rustc_middle::ty::TyCtxt;
7use rustc_span::Span;
8
9use crate::{
10    analysis::{
11        core::dataflow::{graph::*, *},
12        opt::OptCheck,
13        utils::def_path::DefPath,
14    },
15    utils::log::{relative_pos_range, span_to_filename, span_to_line_number, span_to_source_code},
16};
17
18struct DefPaths {
19    vec_from_elem: DefPath,
20}
21
22static DEFPATHS: OnceCell<DefPaths> = OnceCell::new();
23
24impl DefPaths {
25    pub fn new(tcx: &TyCtxt<'_>) -> Self {
26        Self {
27            vec_from_elem: DefPath::new("std::vec::from_elem", tcx),
28        }
29    }
30
31    fn has_id(&self, def_id: DefId) -> bool {
32        def_id == self.vec_from_elem.last_def_id()
33    }
34}
35
36pub struct VecInitCheck {
37    record: Vec<Span>,
38}
39
40impl OptCheck for VecInitCheck {
41    fn new() -> Self {
42        Self { record: Vec::new() }
43    }
44
45    fn check(&mut self, graph: &Graph, tcx: &TyCtxt) {
46        let def_paths = &DEFPATHS.get_or_init(|| DefPaths::new(tcx));
47        for node in graph.nodes.iter() {
48            for op in node.ops.iter() {
49                if let NodeOp::Call(def_id) = op {
50                    if def_paths.has_id(*def_id) {
51                        self.record.push(node.span);
52                    }
53                }
54            }
55        }
56    }
57
58    fn report(&self, graph: &Graph) {
59        for span in self.record.iter() {
60            report_vec_init(graph, *span);
61        }
62    }
63
64    fn cnt(&self) -> usize {
65        self.record.len()
66    }
67}
68
69fn report_vec_init(graph: &Graph, span: Span) {
70    let code_source = span_to_source_code(graph.span);
71    let filename = span_to_filename(span);
72    let snippet = Snippet::source(&code_source)
73        .line_start(span_to_line_number(graph.span))
74        .origin(&filename)
75        .fold(true)
76        .annotation(
77            Level::Error
78                .span(relative_pos_range(graph.span, span))
79                .label("Initialization happens here"),
80        );
81    let message = Level::Warning
82        .title("Unnecessary data collection initialization detected")
83        .snippet(snippet)
84        .footer(Level::Help.title("Use unsafe APIs to skip initialization."));
85    let renderer = Renderer::styled();
86    println!("{}", renderer.render(message));
87}