3 use rustc::lint::{Context, LintPass, LintArray, Lint};
4 use rustc::middle::ty::{TypeVariants, TypeAndMut, TyRef};
5 use syntax::codemap::{BytePos, ExpnInfo, Span};
6 use utils::{in_macro, span_lint};
8 declare_lint!(pub MUT_MUT, Warn,
9 "Warn on usage of double-mut refs, e.g. '&mut &mut ...'");
14 impl LintPass for MutMut {
15 fn get_lints(&self) -> LintArray {
19 fn check_expr(&mut self, cx: &Context, expr: &Expr) {
20 cx.sess().codemap().with_expn_info(expr.span.expn_id,
21 |info| check_expr_expd(cx, expr, info))
24 fn check_ty(&mut self, cx: &Context, ty: &Ty) {
25 unwrap_mut(ty).and_then(unwrap_mut).map_or((), |_| span_lint(cx, MUT_MUT,
26 ty.span, "generally you want to avoid `&mut &mut _` if possible"))
30 fn check_expr_expd(cx: &Context, expr: &Expr, info: Option<&ExpnInfo>) {
31 if in_macro(cx, info) { return; }
33 fn unwrap_addr(expr : &Expr) -> Option<&Expr> {
35 ExprAddrOf(MutMutable, ref e) => Option::Some(e),
40 unwrap_addr(expr).map_or((), |e| {
41 unwrap_addr(e).map(|_| {
42 span_lint(cx, MUT_MUT, expr.span,
43 "generally you want to avoid `&mut &mut _` if possible")
44 }).unwrap_or_else(|| {
45 if let TyRef(_, TypeAndMut{ty: _, mutbl: MutMutable}) =
46 cx.tcx.expr_ty(e).sty {
47 span_lint(cx, MUT_MUT, expr.span,
48 "this expression mutably borrows a mutable reference. \
49 Consider reborrowing.")
55 fn unwrap_mut(ty : &Ty) -> Option<&Ty> {
57 TyPtr(MutTy{ ty: ref pty, mutbl: MutMutable }) => Option::Some(pty),
58 TyRptr(_, MutTy{ ty: ref pty, mutbl: MutMutable }) => Option::Some(pty),