2 use rustc::hir::intravisit;
4 use rustc::ty::{TypeAndMut, TyRef};
5 use utils::{higher, in_external_macro, span_lint};
7 /// **What it does:** Checks for instances of `mut mut` references.
9 /// **Why is this bad?** Multiple `mut`s don't add anything meaningful to the
10 /// source. This is either a copy'n'paste error, or it shows a fundamental
11 /// misunderstanding of references.
13 /// **Known problems:** None.
17 /// let x = &mut &mut y;
22 "usage of double-mut refs, e.g. `&mut &mut ...`"
28 impl LintPass for MutMut {
29 fn get_lints(&self) -> LintArray {
34 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutMut {
35 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx hir::Block) {
36 intravisit::walk_block(&mut MutVisitor { cx: cx }, block);
39 fn check_ty(&mut self, cx: &LateContext<'a, 'tcx>, ty: &'tcx hir::Ty) {
40 use rustc::hir::intravisit::Visitor;
42 MutVisitor { cx: cx }.visit_ty(ty);
46 pub struct MutVisitor<'a, 'tcx: 'a> {
47 cx: &'a LateContext<'a, 'tcx>,
50 impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> {
51 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
52 if in_external_macro(self.cx, expr.span) {
56 if let Some((_, arg, body)) = higher::for_loop(expr) {
57 // A `for` loop lowers to:
59 // match ::std::iter::Iterator::next(&mut iter) {
62 // Let's ignore the generated code.
63 intravisit::walk_expr(self, arg);
64 intravisit::walk_expr(self, body);
65 } else if let hir::ExprAddrOf(hir::MutMutable, ref e) = expr.node {
66 if let hir::ExprAddrOf(hir::MutMutable, _) = e.node {
70 "generally you want to avoid `&mut &mut _` if possible");
71 } else if let TyRef(_, TypeAndMut { mutbl: hir::MutMutable, .. }) = self.cx.tables.expr_ty(e).sty {
75 "this expression mutably borrows a mutable reference. Consider reborrowing");
80 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
81 if let hir::TyRptr(_, hir::MutTy { ty: ref pty, mutbl: hir::MutMutable }) = ty.node {
82 if let hir::TyRptr(_, hir::MutTy { mutbl: hir::MutMutable, .. }) = pty.node {
86 "generally you want to avoid `&mut &mut _` if possible");
91 intravisit::walk_ty(self, ty);
93 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
94 intravisit::NestedVisitorMap::All(&self.cx.tcx.hir)