1 use crate::utils::{higher, span_lint};
3 use rustc::hir::intravisit;
4 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
6 use rustc::{declare_tool_lint, lint_array};
8 /// **What it does:** Checks for instances of `mut mut` references.
10 /// **Why is this bad?** Multiple `mut`s don't add anything meaningful to the
11 /// source. This is either a copy'n'paste error, or it shows a fundamental
12 /// misunderstanding of references.
14 /// **Known problems:** None.
18 /// let x = &mut &mut y;
20 declare_clippy_lint! {
23 "usage of double-mut refs, e.g. `&mut &mut ...`"
26 #[derive(Copy, Clone)]
29 impl LintPass for MutMut {
30 fn get_lints(&self) -> LintArray {
35 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutMut {
36 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx hir::Block) {
37 intravisit::walk_block(&mut MutVisitor { cx }, block);
40 fn check_ty(&mut self, cx: &LateContext<'a, 'tcx>, ty: &'tcx hir::Ty) {
41 use rustc::hir::intravisit::Visitor;
43 MutVisitor { cx }.visit_ty(ty);
47 pub struct MutVisitor<'a, 'tcx: 'a> {
48 cx: &'a LateContext<'a, 'tcx>,
51 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((_, arg, body)) = higher::for_loop(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::MutMutable, ref e) = expr.node {
67 if let hir::ExprKind::AddrOf(hir::MutMutable, _) = e.node {
72 "generally you want to avoid `&mut &mut _` if possible",
74 } else if let ty::Ref(_, _, hir::MutMutable) = self.cx.tables.expr_ty(e).sty {
79 "this expression mutably borrows a mutable reference. Consider reborrowing",
85 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
86 if let hir::TyKind::Rptr(
90 mutbl: hir::MutMutable,
94 if let hir::TyKind::Rptr(
97 mutbl: hir::MutMutable, ..
105 "generally you want to avoid `&mut &mut _` if possible",
110 intravisit::walk_ty(self, ty);
112 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
113 intravisit::NestedVisitorMap::None