rust/clippy_lints/src/utils/usage.rs

87 lines
2.7 KiB
Rust
Raw Normal View History

use rustc::hir::def::Res;
use rustc::hir::*;
2019-01-30 19:15:29 -06:00
use rustc::lint::LateContext;
use rustc::middle::expr_use_visitor::*;
use rustc::middle::mem_categorization::cmt_;
use rustc::middle::mem_categorization::Categorization;
use rustc::ty;
use rustc_data_structures::fx::FxHashSet;
use syntax::source_map::Span;
2019-01-30 19:15:29 -06:00
/// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined.
pub fn mutated_variables<'a, 'tcx>(expr: &'tcx Expr, cx: &'a LateContext<'a, 'tcx>) -> Option<FxHashSet<HirId>> {
let mut delegate = MutVarsDelegate {
used_mutably: FxHashSet::default(),
skip: false,
};
let def_id = def_id::DefId::local(expr.hir_id.owner);
let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
2019-06-02 11:58:11 -05:00
ExprUseVisitor::new(
&mut delegate,
cx.tcx,
def_id,
cx.param_env,
region_scope_tree,
cx.tables,
None,
)
.walk_expr(expr);
if delegate.skip {
return None;
}
Some(delegate.used_mutably)
}
pub fn is_potentially_mutated<'a, 'tcx>(variable: &'tcx Path, expr: &'tcx Expr, cx: &'a LateContext<'a, 'tcx>) -> bool {
if let Res::Local(id) = variable.res {
mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id))
} else {
2019-06-02 11:58:11 -05:00
return true;
}
}
struct MutVarsDelegate {
2019-03-01 06:26:06 -06:00
used_mutably: FxHashSet<HirId>,
skip: bool,
}
impl<'tcx> MutVarsDelegate {
#[allow(clippy::similar_names)]
2018-07-23 06:01:12 -05:00
fn update(&mut self, cat: &'tcx Categorization<'_>) {
match *cat {
Categorization::Local(id) => {
self.used_mutably.insert(id);
},
Categorization::Upvar(_) => {
//FIXME: This causes false negatives. We can't get the `NodeId` from
//`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
//`while`-body, not just the ones in the condition.
self.skip = true
},
Categorization::Deref(ref cmt, _) | Categorization::Interior(ref cmt, _) => self.update(&cmt.cat),
_ => {},
}
}
}
impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
2019-02-24 12:43:15 -06:00
fn consume(&mut self, _: HirId, _: Span, _: &cmt_<'tcx>, _: ConsumeMode) {}
fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
fn consume_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: ConsumeMode) {}
2019-02-24 12:43:15 -06:00
fn borrow(&mut self, _: HirId, _: Span, cmt: &cmt_<'tcx>, _: ty::Region<'_>, bk: ty::BorrowKind, _: LoanCause) {
if let ty::BorrowKind::MutBorrow = bk {
self.update(&cmt.cat)
}
}
2019-02-24 12:43:15 -06:00
fn mutate(&mut self, _: HirId, _: Span, cmt: &cmt_<'tcx>, _: MutateMode) {
self.update(&cmt.cat)
}
2019-03-01 06:26:06 -06:00
fn decl_without_init(&mut self, _: HirId, _: Span) {}
}