]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/usage.rs
Merge branch 'master' into fix-4727
[rust.git] / clippy_lints / src / utils / usage.rs
1 use rustc::hir::def::Res;
2 use rustc::hir::*;
3 use rustc::lint::LateContext;
4 use rustc::middle::expr_use_visitor::*;
5 use rustc::middle::mem_categorization::cmt_;
6 use rustc::middle::mem_categorization::Categorization;
7 use rustc::ty;
8 use rustc_data_structures::fx::FxHashSet;
9
10 /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined.
11 pub fn mutated_variables<'a, 'tcx>(expr: &'tcx Expr, cx: &'a LateContext<'a, 'tcx>) -> Option<FxHashSet<HirId>> {
12     let mut delegate = MutVarsDelegate {
13         used_mutably: FxHashSet::default(),
14         skip: false,
15     };
16     let def_id = def_id::DefId::local(expr.hir_id.owner);
17     let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
18     ExprUseVisitor::new(
19         &mut delegate,
20         cx.tcx,
21         def_id,
22         cx.param_env,
23         region_scope_tree,
24         cx.tables,
25     )
26     .walk_expr(expr);
27
28     if delegate.skip {
29         return None;
30     }
31     Some(delegate.used_mutably)
32 }
33
34 pub fn is_potentially_mutated<'a, 'tcx>(variable: &'tcx Path, expr: &'tcx Expr, cx: &'a LateContext<'a, 'tcx>) -> bool {
35     if let Res::Local(id) = variable.res {
36         mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id))
37     } else {
38         true
39     }
40 }
41
42 struct MutVarsDelegate {
43     used_mutably: FxHashSet<HirId>,
44     skip: bool,
45 }
46
47 impl<'tcx> MutVarsDelegate {
48     #[allow(clippy::similar_names)]
49     fn update(&mut self, cat: &'tcx Categorization<'_>) {
50         match *cat {
51             Categorization::Local(id) => {
52                 self.used_mutably.insert(id);
53             },
54             Categorization::Upvar(_) => {
55                 //FIXME: This causes false negatives. We can't get the `NodeId` from
56                 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
57                 //`while`-body, not just the ones in the condition.
58                 self.skip = true
59             },
60             Categorization::Deref(ref cmt, _) | Categorization::Interior(ref cmt, _) => self.update(&cmt.cat),
61             _ => {},
62         }
63     }
64 }
65
66 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
67     fn consume(&mut self, _: &cmt_<'tcx>, _: ConsumeMode) {}
68
69     fn borrow(&mut self, cmt: &cmt_<'tcx>, bk: ty::BorrowKind) {
70         if let ty::BorrowKind::MutBorrow = bk {
71             self.update(&cmt.cat)
72         }
73     }
74
75     fn mutate(&mut self, cmt: &cmt_<'tcx>) {
76         self.update(&cmt.cat)
77     }
78 }