1 use rustc::hir::def::Res;
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;
8 use rustc_data_structures::fx::FxHashSet;
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(),
16 let def_id = def_id::DefId::local(expr.hir_id.owner);
17 let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
31 Some(delegate.used_mutably)
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))
42 struct MutVarsDelegate {
43 used_mutably: FxHashSet<HirId>,
47 impl<'tcx> MutVarsDelegate {
48 #[allow(clippy::similar_names)]
49 fn update(&mut self, cat: &'tcx Categorization<'_>) {
51 Categorization::Local(id) => {
52 self.used_mutably.insert(id);
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.
60 Categorization::Deref(ref cmt, _) | Categorization::Interior(ref cmt, _) => self.update(&cmt.cat),
66 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
67 fn consume(&mut self, _: &cmt_<'tcx>, _: ConsumeMode) {}
69 fn borrow(&mut self, cmt: &cmt_<'tcx>, bk: ty::BorrowKind) {
70 if let ty::BorrowKind::MutBorrow = bk {
75 fn mutate(&mut self, cmt: &cmt_<'tcx>) {