1 use crate::utils::match_var;
2 use rustc_data_structures::fx::FxHashSet;
3 use rustc_hir::def::Res;
4 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
5 use rustc_hir::{Expr, HirId, Path};
6 use rustc_infer::infer::TyCtxtInferExt;
7 use rustc_lint::LateContext;
8 use rustc_middle::hir::map::Map;
10 use rustc_span::symbol::{Ident, Symbol};
11 use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
13 /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined.
14 pub fn mutated_variables<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> Option<FxHashSet<HirId>> {
15 let mut delegate = MutVarsDelegate {
16 used_mutably: FxHashSet::default(),
19 let def_id = expr.hir_id.owner.to_def_id();
20 cx.tcx.infer_ctxt().enter(|infcx| {
21 ExprUseVisitor::new(&mut delegate, &infcx, def_id.expect_local(), cx.param_env, cx.tables()).walk_expr(expr);
27 Some(delegate.used_mutably)
30 pub fn is_potentially_mutated<'tcx>(variable: &'tcx Path<'_>, expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) -> bool {
31 if let Res::Local(id) = variable.res {
32 mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id))
38 struct MutVarsDelegate {
39 used_mutably: FxHashSet<HirId>,
43 impl<'tcx> MutVarsDelegate {
44 #[allow(clippy::similar_names)]
45 fn update(&mut self, cat: &PlaceWithHirId<'tcx>) {
46 match cat.place.base {
47 PlaceBase::Local(id) => {
48 self.used_mutably.insert(id);
50 PlaceBase::Upvar(_) => {
51 //FIXME: This causes false negatives. We can't get the `NodeId` from
52 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
53 //`while`-body, not just the ones in the condition.
61 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
62 fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: ConsumeMode) {}
64 fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, bk: ty::BorrowKind) {
65 if let ty::BorrowKind::MutBorrow = bk {
70 fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>) {
75 pub struct UsedVisitor {
76 pub var: Symbol, // var to look for
77 pub used: bool, // has the var been used otherwise?
80 impl<'tcx> Visitor<'tcx> for UsedVisitor {
83 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
84 if match_var(expr, self.var) {
87 walk_expr(self, expr);
91 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
92 NestedVisitorMap::None
96 pub fn is_unused<'tcx>(ident: &'tcx Ident, body: &'tcx Expr<'_>) -> bool {
97 let mut visitor = UsedVisitor {
101 walk_expr(&mut visitor, body);