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_lint_pass, declare_tool_lint};
9 /// **What it does:** Checks for instances of `mut mut` references.
11 /// **Why is this bad?** Multiple `mut`s don't add anything meaningful to the
12 /// source. This is either a copy'n'paste error, or it shows a fundamental
13 /// misunderstanding of references.
15 /// **Known problems:** None.
20 /// let x = &mut &mut y;
24 "usage of double-mut refs, e.g., `&mut &mut ...`"
27 declare_lint_pass!(MutMut => [MUT_MUT]);
29 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutMut {
30 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx hir::Block) {
31 intravisit::walk_block(&mut MutVisitor { cx }, block);
34 fn check_ty(&mut self, cx: &LateContext<'a, 'tcx>, ty: &'tcx hir::Ty) {
35 use rustc::hir::intravisit::Visitor;
37 MutVisitor { cx }.visit_ty(ty);
41 pub struct MutVisitor<'a, 'tcx> {
42 cx: &'a LateContext<'a, 'tcx>,
45 impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> {
46 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
47 if in_external_macro(self.cx.sess(), expr.span) {
51 if let Some((_, arg, body)) = higher::for_loop(expr) {
52 // A `for` loop lowers to:
54 // match ::std::iter::Iterator::next(&mut iter) {
57 // Let's ignore the generated code.
58 intravisit::walk_expr(self, arg);
59 intravisit::walk_expr(self, body);
60 } else if let hir::ExprKind::AddrOf(hir::MutMutable, ref e) = expr.kind {
61 if let hir::ExprKind::AddrOf(hir::MutMutable, _) = e.kind {
66 "generally you want to avoid `&mut &mut _` if possible",
68 } else if let ty::Ref(_, _, hir::MutMutable) = self.cx.tables.expr_ty(e).kind {
73 "this expression mutably borrows a mutable reference. Consider reborrowing",
79 fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
80 if let hir::TyKind::Rptr(
84 mutbl: hir::MutMutable,
88 if let hir::TyKind::Rptr(
91 mutbl: hir::MutMutable, ..
99 "generally you want to avoid `&mut &mut _` if possible",
104 intravisit::walk_ty(self, ty);
106 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
107 intravisit::NestedVisitorMap::None