1 use crate::utils::{higher, span_lint};
3 use rustc_hir::intravisit;
4 use rustc_lint::{LateContext, LateLintPass, LintContext};
5 use rustc_middle::hir::map::Map;
6 use rustc_middle::lint::in_external_macro;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for instances of `mut mut` references.
13 /// **Why is this bad?** Multiple `mut`s don't add anything meaningful to the
14 /// source. This is either a copy'n'paste error, or it shows a fundamental
15 /// misunderstanding of references.
17 /// **Known problems:** None.
22 /// let x = &mut &mut y;
26 "usage of double-mut refs, e.g., `&mut &mut ...`"
29 declare_lint_pass!(MutMut => [MUT_MUT]);
31 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutMut {
32 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx hir::Block<'_>) {
33 intravisit::walk_block(&mut MutVisitor { cx }, block);
36 fn check_ty(&mut self, cx: &LateContext<'a, 'tcx>, ty: &'tcx hir::Ty<'_>) {
37 use rustc_hir::intravisit::Visitor;
39 MutVisitor { cx }.visit_ty(ty);
43 pub struct MutVisitor<'a, 'tcx> {
44 cx: &'a LateContext<'a, 'tcx>,
47 impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> {
50 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
51 if in_external_macro(self.cx.sess(), expr.span) {
55 if let Some((_, arg, body)) = higher::for_loop(expr) {
56 // A `for` loop lowers to:
58 // match ::std::iter::Iterator::next(&mut iter) {
61 // Let's ignore the generated code.
62 intravisit::walk_expr(self, arg);
63 intravisit::walk_expr(self, body);
64 } else if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, ref e) = expr.kind {
65 if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, _) = e.kind {
70 "generally you want to avoid `&mut &mut _` if possible",
72 } else if let ty::Ref(_, _, hir::Mutability::Mut) = self.cx.tables.expr_ty(e).kind {
77 "this expression mutably borrows a mutable reference. Consider reborrowing",
83 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
84 if let hir::TyKind::Rptr(
88 mutbl: hir::Mutability::Mut,
92 if let hir::TyKind::Rptr(
95 mutbl: hir::Mutability::Mut,
104 "generally you want to avoid `&mut &mut _` if possible",
109 intravisit::walk_ty(self, ty);
111 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
112 intravisit::NestedVisitorMap::None