1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::higher;
4 use rustc_hir::intravisit;
5 use rustc_lint::{LateContext, LateLintPass, LintContext};
6 use rustc_middle::hir::map::Map;
7 use rustc_middle::lint::in_external_macro;
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 declare_clippy_lint! {
13 /// Checks for instances of `mut mut` references.
15 /// ### Why is this bad?
16 /// Multiple `mut`s don't add anything meaningful to the
17 /// source. This is either a copy'n'paste error, or it shows a fundamental
18 /// misunderstanding of references.
23 /// let x = &mut &mut y;
25 #[clippy::version = "pre 1.29.0"]
28 "usage of double-mut refs, e.g., `&mut &mut ...`"
31 declare_lint_pass!(MutMut => [MUT_MUT]);
33 impl<'tcx> LateLintPass<'tcx> for MutMut {
34 fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
35 intravisit::walk_block(&mut MutVisitor { cx }, block);
38 fn check_ty(&mut self, cx: &LateContext<'tcx>, ty: &'tcx hir::Ty<'_>) {
39 use rustc_hir::intravisit::Visitor;
41 MutVisitor { cx }.visit_ty(ty);
45 pub struct MutVisitor<'a, 'tcx> {
46 cx: &'a LateContext<'tcx>,
49 impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> {
52 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
53 if in_external_macro(self.cx.sess(), expr.span) {
57 if let Some(higher::ForLoop { arg, body, .. }) = higher::ForLoop::hir(expr) {
58 // A `for` loop lowers to:
60 // match ::std::iter::Iterator::next(&mut iter) {
63 // Let's ignore the generated code.
64 intravisit::walk_expr(self, arg);
65 intravisit::walk_expr(self, body);
66 } else if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e) = expr.kind {
67 if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, _) = e.kind {
72 "generally you want to avoid `&mut &mut _` if possible",
74 } else if let ty::Ref(_, _, hir::Mutability::Mut) = self.cx.typeck_results().expr_ty(e).kind() {
79 "this expression mutably borrows a mutable reference. Consider reborrowing",
85 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
86 if in_external_macro(self.cx.sess(), ty.span) {
90 if let hir::TyKind::Rptr(
94 mutbl: hir::Mutability::Mut,
98 if let hir::TyKind::Rptr(
101 mutbl: hir::Mutability::Mut,
110 "generally you want to avoid `&mut &mut _` if possible",
115 intravisit::walk_ty(self, ty);
117 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
118 intravisit::NestedVisitorMap::None