]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/mut_mut.rs
split clippy into lints, plugin and cargo-clippy
[rust.git] / clippy_lints / src / mut_mut.rs
1 use rustc::lint::*;
2 use rustc::ty::{TypeAndMut, TyRef};
3 use rustc::hir::*;
4 use utils::{in_external_macro, span_lint};
5
6 /// **What it does:** This lint checks for instances of `mut mut` references.
7 ///
8 /// **Why is this bad?** Multiple `mut`s don't add anything meaningful to the source.
9 ///
10 /// **Known problems:** None
11 ///
12 /// **Example:** `let x = &mut &mut y;`
13 declare_lint! {
14     pub MUT_MUT,
15     Allow,
16     "usage of double-mut refs, e.g. `&mut &mut ...` (either copy'n'paste error, \
17      or shows a fundamental misunderstanding of references)"
18 }
19
20 #[derive(Copy,Clone)]
21 pub struct MutMut;
22
23 impl LintPass for MutMut {
24     fn get_lints(&self) -> LintArray {
25         lint_array!(MUT_MUT)
26     }
27 }
28
29 impl LateLintPass for MutMut {
30     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
31         if in_external_macro(cx, expr.span) {
32             return;
33         }
34
35         if let ExprAddrOf(MutMutable, ref e) = expr.node {
36             if let ExprAddrOf(MutMutable, _) = e.node {
37                 span_lint(cx,
38                           MUT_MUT,
39                           expr.span,
40                           "generally you want to avoid `&mut &mut _` if possible");
41             } else {
42                 if let TyRef(_, TypeAndMut { mutbl: MutMutable, .. }) = cx.tcx.expr_ty(e).sty {
43                     span_lint(cx,
44                               MUT_MUT,
45                               expr.span,
46                               "this expression mutably borrows a mutable reference. Consider reborrowing");
47                 }
48             }
49         }
50     }
51
52     fn check_ty(&mut self, cx: &LateContext, ty: &Ty) {
53         if let TyRptr(_, MutTy { ty: ref pty, mutbl: MutMutable }) = ty.node {
54             if let TyRptr(_, MutTy { mutbl: MutMutable, .. }) = pty.node {
55                 span_lint(cx, MUT_MUT, ty.span, "generally you want to avoid `&mut &mut _` if possible");
56             }
57         }
58     }
59 }