1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use rustc::hir;
use rustc::hir::intravisit;
use rustc::lint::*;
use rustc::ty::{TypeAndMut, TyRef};
use utils::{higher, in_external_macro, span_lint};
declare_lint! {
pub MUT_MUT,
Allow,
"usage of double-mut refs, e.g. `&mut &mut ...`"
}
#[derive(Copy,Clone)]
pub struct MutMut;
impl LintPass for MutMut {
fn get_lints(&self) -> LintArray {
lint_array!(MUT_MUT)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutMut {
fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx hir::Block) {
intravisit::walk_block(&mut MutVisitor { cx: cx }, block);
}
fn check_ty(&mut self, cx: &LateContext<'a, 'tcx>, ty: &'tcx hir::Ty) {
use rustc::hir::intravisit::Visitor;
MutVisitor { cx: cx }.visit_ty(ty);
}
}
pub struct MutVisitor<'a, 'tcx: 'a> {
cx: &'a LateContext<'a, 'tcx>,
}
impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> {
fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
if in_external_macro(self.cx, expr.span) {
return;
}
if let Some((_, arg, body)) = higher::for_loop(expr) {
intravisit::walk_expr(self, arg);
intravisit::walk_expr(self, body);
} else if let hir::ExprAddrOf(hir::MutMutable, ref e) = expr.node {
if let hir::ExprAddrOf(hir::MutMutable, _) = e.node {
span_lint(self.cx,
MUT_MUT,
expr.span,
"generally you want to avoid `&mut &mut _` if possible");
} else if let TyRef(_, TypeAndMut { mutbl: hir::MutMutable, .. }) = self.cx.tcx.tables().expr_ty(e).sty {
span_lint(self.cx,
MUT_MUT,
expr.span,
"this expression mutably borrows a mutable reference. Consider reborrowing");
}
}
}
fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
if let hir::TyRptr(_, hir::MutTy { ty: ref pty, mutbl: hir::MutMutable }) = ty.node {
if let hir::TyRptr(_, hir::MutTy { mutbl: hir::MutMutable, .. }) = pty.node {
span_lint(self.cx,
MUT_MUT,
ty.span,
"generally you want to avoid `&mut &mut _` if possible");
}
}
intravisit::walk_ty(self, ty);
}
fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
intravisit::NestedVisitorMap::All(&self.cx.tcx.map)
}
}