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;
9 use syntax::source_map::Span;
11 /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined.
12 pub fn mutated_variables<'a, 'tcx>(expr: &'tcx Expr, cx: &'a LateContext<'a, 'tcx>) -> Option<FxHashSet<HirId>> {
13 let mut delegate = MutVarsDelegate {
14 used_mutably: FxHashSet::default(),
17 let def_id = def_id::DefId::local(expr.hir_id.owner);
18 let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
33 Some(delegate.used_mutably)
36 pub fn is_potentially_mutated<'a, 'tcx>(variable: &'tcx Path, expr: &'tcx Expr, cx: &'a LateContext<'a, 'tcx>) -> bool {
37 if let Res::Local(id) = variable.res {
38 mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id))
44 struct MutVarsDelegate {
45 used_mutably: FxHashSet<HirId>,
49 impl<'tcx> MutVarsDelegate {
50 #[allow(clippy::similar_names)]
51 fn update(&mut self, cat: &'tcx Categorization<'_>) {
53 Categorization::Local(id) => {
54 self.used_mutably.insert(id);
56 Categorization::Upvar(_) => {
57 //FIXME: This causes false negatives. We can't get the `NodeId` from
58 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
59 //`while`-body, not just the ones in the condition.
62 Categorization::Deref(ref cmt, _) | Categorization::Interior(ref cmt, _) => self.update(&cmt.cat),
68 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
69 fn consume(&mut self, _: HirId, _: Span, _: &cmt_<'tcx>, _: ConsumeMode) {}
71 fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
73 fn consume_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: ConsumeMode) {}
75 fn borrow(&mut self, _: HirId, _: Span, cmt: &cmt_<'tcx>, _: ty::Region<'_>, bk: ty::BorrowKind, _: LoanCause) {
76 if let ty::BorrowKind::MutBorrow = bk {
81 fn mutate(&mut self, _: HirId, _: Span, cmt: &cmt_<'tcx>, _: MutateMode) {
85 fn decl_without_init(&mut self, _: HirId, _: Span) {}