1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use crate::rustc::lint::LateContext;
13 use crate::rustc::hir::def::Def;
14 use crate::rustc::hir::*;
15 use crate::rustc::middle::expr_use_visitor::*;
16 use crate::rustc::middle::mem_categorization::cmt_;
17 use crate::rustc::middle::mem_categorization::Categorization;
19 use crate::rustc_data_structures::fx::FxHashSet;
20 use crate::syntax::ast::NodeId;
21 use crate::syntax::source_map::Span;
23 /// Returns a set of mutated local variable ids or None if mutations could not be determined.
24 pub fn mutated_variables<'a, 'tcx: 'a>(expr: &'tcx Expr, cx: &'a LateContext<'a, 'tcx>) -> Option<FxHashSet<NodeId>> {
25 let mut delegate = MutVarsDelegate {
26 used_mutably: FxHashSet::default(),
29 let def_id = def_id::DefId::local(expr.hir_id.owner);
30 let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
31 ExprUseVisitor::new(&mut delegate, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).walk_expr(expr);
36 Some(delegate.used_mutably)
39 pub fn is_potentially_mutated<'a, 'tcx: 'a>(
42 cx: &'a LateContext<'a, 'tcx>,
44 let id = match variable.def {
45 Def::Local(id) | Def::Upvar(id, ..) => id,
48 mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id))
51 struct MutVarsDelegate {
52 used_mutably: FxHashSet<NodeId>,
56 impl<'tcx> MutVarsDelegate {
57 #[allow(clippy::similar_names)]
58 fn update(&mut self, cat: &'tcx Categorization<'_>) {
60 Categorization::Local(id) => {
61 self.used_mutably.insert(id);
63 Categorization::Upvar(_) => {
64 //FIXME: This causes false negatives. We can't get the `NodeId` from
65 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
66 //`while`-body, not just the ones in the condition.
69 Categorization::Deref(ref cmt, _) | Categorization::Interior(ref cmt, _) => self.update(&cmt.cat),
75 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
76 fn consume(&mut self, _: NodeId, _: Span, _: &cmt_<'tcx>, _: ConsumeMode) {}
78 fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
80 fn consume_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: ConsumeMode) {}
82 fn borrow(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, _: ty::Region<'_>, bk: ty::BorrowKind, _: LoanCause) {
83 if let ty::BorrowKind::MutBorrow = bk {
88 fn mutate(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, _: MutateMode) {
92 fn decl_without_init(&mut self, _: NodeId, _: Span) {}