rust/src/mut_mut.rs

76 lines
2.5 KiB
Rust
Raw Normal View History

use rustc::lint::*;
use rustc_front::hir::*;
use rustc::middle::ty::{TypeAndMut, TyRef};
2015-09-06 03:53:55 -05:00
use utils::{in_external_macro, span_lint};
2015-05-18 02:02:24 -05:00
/// **What it does:** This lint checks for instances of `mut mut` references. It is `Warn` by default.
///
/// **Why is this bad?** Multiple `mut`s don't add anything meaningful to the source.
///
/// **Known problems:** None
///
/// **Example:** `let x = &mut &mut y;`
declare_lint!(pub MUT_MUT, Allow,
"usage of double-mut refs, e.g. `&mut &mut ...` (either copy'n'paste error, \
or shows a fundamental misunderstanding of references)");
2015-05-18 02:02:24 -05:00
#[derive(Copy,Clone)]
pub struct MutMut;
impl LintPass for MutMut {
fn get_lints(&self) -> LintArray {
2015-05-18 02:02:24 -05:00
lint_array!(MUT_MUT)
}
}
impl LateLintPass for MutMut {
fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
2015-11-16 23:22:57 -06:00
check_expr_mut(cx, expr)
}
fn check_ty(&mut self, cx: &LateContext, ty: &Ty) {
2016-01-03 22:26:12 -06:00
unwrap_mut(ty).and_then(unwrap_mut).map_or((), |_| {
span_lint(cx, MUT_MUT, ty.span, "generally you want to avoid `&mut &mut _` if possible");
});
}
2015-05-18 02:02:24 -05:00
}
fn check_expr_mut(cx: &LateContext, expr: &Expr) {
2016-01-03 22:26:12 -06:00
if in_external_macro(cx, expr.span) {
return;
}
2015-11-16 23:22:57 -06:00
fn unwrap_addr(expr: &Expr) -> Option<&Expr> {
match expr.node {
2015-11-27 09:47:24 -06:00
ExprAddrOf(MutMutable, ref e) => Some(e),
2016-01-03 22:26:12 -06:00
_ => None,
}
}
unwrap_addr(expr).map_or((), |e| {
2016-01-03 22:26:12 -06:00
unwrap_addr(e).map_or_else(|| {
if let TyRef(_, TypeAndMut{mutbl: MutMutable, ..}) = cx.tcx.expr_ty(e).sty {
span_lint(cx,
MUT_MUT,
expr.span,
"this expression mutably borrows a mutable reference. Consider \
reborrowing");
}
},
|_| {
span_lint(cx,
MUT_MUT,
expr.span,
"generally you want to avoid `&mut &mut _` if possible");
})
})
}
2015-11-16 23:22:57 -06:00
fn unwrap_mut(ty: &Ty) -> Option<&Ty> {
match ty.node {
2015-11-27 09:47:24 -06:00
TyRptr(_, MutTy{ ty: ref pty, mutbl: MutMutable }) => Some(pty),
2016-01-03 22:26:12 -06:00
_ => None,
}
}