Skip to main content

rapx/check/opt/checking/bounds_checking/
bounds_loop_push.rs

1use once_cell::sync::OnceCell;
2
3use rustc_hir::intravisit;
4use rustc_middle::ty::TyCtxt;
5use rustc_span::Span;
6
7use crate::analysis::dataflow::Graph;
8use crate::helpers::def_path::DefPath;
9use crate::utils::span::{span_to_first_line, span_to_trimmed_span};
10
11use annotate_snippets::Level;
12
13use crate::check::opt::report::OptReport;
14
15use super::super::super::LEVEL;
16use super::super::super::NO_STD;
17use super::super::super::loop_visitors::LoopFinder;
18static DEFPATHS: OnceCell<DefPaths> = OnceCell::new();
19
20struct DefPaths {
21    vec_push: DefPath,
22}
23
24impl DefPaths {
25    pub fn new(tcx: &TyCtxt<'_>) -> Self {
26        let no_std = NO_STD.lock().unwrap();
27        if *no_std {
28            Self {
29                vec_push: DefPath::new("alloc::vec::Vec::push", tcx),
30            }
31        } else {
32            Self {
33                vec_push: DefPath::new("std::vec::Vec::push", tcx),
34            }
35        }
36    }
37}
38
39use crate::check::opt::OptCheck;
40
41pub struct BoundsLoopPushCheck {
42    pub record: Vec<(Span, Vec<Span>)>,
43}
44
45impl OptCheck for BoundsLoopPushCheck {
46    fn new() -> Self {
47        Self { record: Vec::new() }
48    }
49
50    fn check(&mut self, graph: &Graph, tcx: &TyCtxt) {
51        let def_paths = &DEFPATHS.get_or_init(|| DefPaths::new(tcx));
52        let level = LEVEL.lock().unwrap();
53        if *level == 2 {
54            let def_id = graph.def_id;
55            let body = tcx.hir_body_owned_by(def_id.as_local().unwrap());
56            let typeck_results = tcx.typeck(def_id.as_local().unwrap());
57            let target_def_id = def_paths.vec_push.last_def_id();
58            let mut loop_finder = LoopFinder::new(typeck_results, target_def_id);
59            intravisit::walk_body(&mut loop_finder, body);
60            self.record = loop_finder.into_record();
61        }
62    }
63
64    fn report(&self, _: &Graph) {
65        for (loop_span, push_record) in self.record.iter() {
66            report_loop_push_bug(*loop_span, push_record);
67        }
68    }
69
70    fn cnt(&self) -> usize {
71        self.record.iter().map(|(_, spans)| spans.len()).sum()
72    }
73}
74
75fn report_loop_push_bug(loop_span: Span, push_record: &Vec<Span>) {
76    let trimmed = span_to_trimmed_span(span_to_first_line(loop_span));
77    let mut report = OptReport::new(loop_span, loop_span)
78        .title("Unnecessary bounds checkings detected")
79        .annotate(Level::Info, trimmed, "A loop operation.");
80    for push_span in push_record {
81        report = report.annotate(Level::Error, *push_span, "Push happens here.");
82    }
83    report.emit();
84}