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.
10 use rustc::lint::LateContext;
12 use rustc::hir::def::Def;
14 use rustc::middle::expr_use_visitor::*;
15 use rustc::middle::mem_categorization::cmt_;
16 use rustc::middle::mem_categorization::Categorization;
18 use rustc_data_structures::fx::FxHashSet;
19 use syntax::ast::NodeId;
20 use syntax::source_map::Span;
22 /// Returns a set of mutated local variable ids or None if mutations could not be determined.
23 pub fn mutated_variables<'a, 'tcx: 'a>(expr: &'tcx Expr, cx: &'a LateContext<'a, 'tcx>) -> Option<FxHashSet<NodeId>> {
24 let mut delegate = MutVarsDelegate {
25 used_mutably: FxHashSet::default(),
28 let def_id = def_id::DefId::local(expr.hir_id.owner);
29 let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
30 ExprUseVisitor::new(&mut delegate, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).walk_expr(expr);
35 Some(delegate.used_mutably)
38 pub fn is_potentially_mutated<'a, 'tcx: 'a>(
41 cx: &'a LateContext<'a, 'tcx>,
43 let id = match variable.def {
44 Def::Local(id) | Def::Upvar(id, ..) => id,
47 mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id))
50 struct MutVarsDelegate {
51 used_mutably: FxHashSet<NodeId>,
55 impl<'tcx> MutVarsDelegate {
56 #[allow(clippy::similar_names)]
57 fn update(&mut self, cat: &'tcx Categorization<'_>) {
59 Categorization::Local(id) => {
60 self.used_mutably.insert(id);
62 Categorization::Upvar(_) => {
63 //FIXME: This causes false negatives. We can't get the `NodeId` from
64 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
65 //`while`-body, not just the ones in the condition.
68 Categorization::Deref(ref cmt, _) | Categorization::Interior(ref cmt, _) => self.update(&cmt.cat),
74 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
75 fn consume(&mut self, _: NodeId, _: Span, _: &cmt_<'tcx>, _: ConsumeMode) {}
77 fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
79 fn consume_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: ConsumeMode) {}
81 fn borrow(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, _: ty::Region<'_>, bk: ty::BorrowKind, _: LoanCause) {
82 if let ty::BorrowKind::MutBorrow = bk {
87 fn mutate(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, _: MutateMode) {
91 fn decl_without_init(&mut self, _: NodeId, _: Span) {}