rapx/check/opt/data_collection/suboptimal/
slice_contains.rs1use annotate_snippets::{Level, Renderer, Snippet};
2
3use once_cell::sync::OnceCell;
4
5use crate::{
6 analysis::dataflow::Graph,
7 check::opt::OptCheck,
8 helpers::def_path::DefPath,
9 utils::log::{relative_pos_range, span_to_filename, span_to_line_number, span_to_source_code},
10};
11use rustc_hir::{Expr, ExprKind, intravisit};
12use rustc_middle::ty::{TyCtxt, TypeckResults};
13use rustc_span::Span;
14
15struct DefPaths {
16 slice_contains: DefPath,
17}
18
19static DEFPATHS: OnceCell<DefPaths> = OnceCell::new();
20
21impl DefPaths {
22 pub fn new(tcx: &TyCtxt<'_>) -> Self {
23 Self {
24 slice_contains: DefPath::new("slice::contains", tcx),
25 }
26 }
27}
28
29struct ContainsFinder<'tcx> {
30 typeck_results: &'tcx TypeckResults<'tcx>,
31 record: Vec<Span>,
32}
33
34impl<'tcx> intravisit::Visitor<'tcx> for ContainsFinder<'tcx> {
35 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
36 if let ExprKind::MethodCall(.., span) = ex.kind {
37 let def_id = self
38 .typeck_results
39 .type_dependent_def_id(ex.hir_id)
40 .unwrap();
41 let target_def_id = (&DEFPATHS.get().unwrap()).slice_contains.last_def_id();
42 if def_id == target_def_id {
43 self.record.push(span);
44 }
45 }
46 intravisit::walk_expr(self, ex);
47 }
48}
49
50pub struct SliceContainsCheck {
51 record: Vec<Span>,
52}
53
54impl OptCheck for SliceContainsCheck {
55 fn new() -> Self {
56 Self { record: Vec::new() }
57 }
58
59 fn check(&mut self, graph: &Graph, tcx: &TyCtxt) {
60 let _ = &DEFPATHS.get_or_init(|| DefPaths::new(tcx));
61 let def_id = graph.def_id;
62 let body = tcx.hir_body_owned_by(def_id.as_local().unwrap());
63 let typeck_results = tcx.typeck(def_id.as_local().unwrap());
64 let mut contains_finder = ContainsFinder {
65 typeck_results,
66 record: Vec::new(),
67 };
68 intravisit::walk_body(&mut contains_finder, body);
69 self.record = contains_finder.record;
70 }
71
72 fn report(&self, graph: &Graph) {
73 for contains_span in self.record.iter() {
74 report_slice_contains_bug(graph, *contains_span);
75 }
76 }
77
78 fn cnt(&self) -> usize {
79 self.record.len()
80 }
81}
82
83fn report_slice_contains_bug(graph: &Graph, contains_span: Span) {
84 let code_source = span_to_source_code(graph.span);
85 let filename = span_to_filename(graph.span);
86 let snippet = Snippet::source(&code_source)
87 .line_start(span_to_line_number(graph.span))
88 .origin(&filename)
89 .fold(true)
90 .annotation(
91 Level::Error
92 .span(relative_pos_range(graph.span, contains_span))
93 .label("Slice contains happens here."),
94 );
95 let message = Level::Warning
96 .title("Improper data collection detected")
97 .snippet(snippet)
98 .footer(Level::Help.title("Use Set instead of Slice."));
99 let renderer = Renderer::styled();
100 rap_warn!("{}", renderer.render(message));
101}