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