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