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, Place, PlaceBase};
13 /// Returns a set of mutated local variable IDs, or `None` if mutations could not be determined.
14 pub fn mutated_variables<'a, 'tcx>(expr: &'tcx Expr<'_>, cx: &'a LateContext<'a, '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<'a, 'tcx>(
31 variable: &'tcx Path<'_>,
33 cx: &'a LateContext<'a, 'tcx>,
35 if let Res::Local(id) = variable.res {
36 mutated_variables(expr, cx).map_or(true, |mutated| mutated.contains(&id))
42 struct MutVarsDelegate {
43 used_mutably: FxHashSet<HirId>,
47 impl<'tcx> MutVarsDelegate {
48 #[allow(clippy::similar_names)]
49 fn update(&mut self, cat: &Place<'tcx>) {
51 PlaceBase::Local(id) => {
52 self.used_mutably.insert(id);
54 PlaceBase::Upvar(_) => {
55 //FIXME: This causes false negatives. We can't get the `NodeId` from
56 //`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
57 //`while`-body, not just the ones in the condition.
65 impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
66 fn consume(&mut self, _: &Place<'tcx>, _: ConsumeMode) {}
68 fn borrow(&mut self, cmt: &Place<'tcx>, bk: ty::BorrowKind) {
69 if let ty::BorrowKind::MutBorrow = bk {
74 fn mutate(&mut self, cmt: &Place<'tcx>) {
79 pub struct UsedVisitor {
80 pub var: Symbol, // var to look for
81 pub used: bool, // has the var been used otherwise?
84 impl<'tcx> Visitor<'tcx> for UsedVisitor {
87 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
88 if match_var(expr, self.var) {
91 walk_expr(self, expr);
95 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
96 NestedVisitorMap::None
100 pub fn is_unused<'tcx>(ident: &'tcx Ident, body: &'tcx Expr<'_>) -> bool {
101 let mut visitor = UsedVisitor {
105 walk_expr(&mut visitor, body);