2015-05-18 02:02:24 -05:00
|
|
|
use syntax::ptr::P;
|
|
|
|
use syntax::ast::*;
|
2015-05-18 03:41:15 -05:00
|
|
|
use rustc::lint::{Context, LintPass, LintArray, Lint};
|
2015-07-16 01:53:02 -05:00
|
|
|
use rustc::middle::ty::{TypeVariants, TypeAndMut, TyRef};
|
2015-06-18 17:29:13 -05:00
|
|
|
use syntax::codemap::{BytePos, ExpnInfo, Span};
|
2015-07-26 09:53:11 -05:00
|
|
|
use utils::{in_macro, span_lint};
|
2015-05-18 02:02:24 -05:00
|
|
|
|
|
|
|
declare_lint!(pub MUT_MUT, Warn,
|
2015-08-13 03:32:35 -05:00
|
|
|
"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 {
|
2015-08-11 13:22:20 -05:00
|
|
|
fn get_lints(&self) -> LintArray {
|
2015-05-18 02:02:24 -05:00
|
|
|
lint_array!(MUT_MUT)
|
2015-08-11 13:22:20 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn check_expr(&mut self, cx: &Context, expr: &Expr) {
|
|
|
|
cx.sess().codemap().with_expn_info(expr.span.expn_id,
|
|
|
|
|info| check_expr_expd(cx, expr, info))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_ty(&mut self, cx: &Context, ty: &Ty) {
|
|
|
|
unwrap_mut(ty).and_then(unwrap_mut).map_or((), |_| span_lint(cx, MUT_MUT,
|
2015-08-12 03:46:49 -05:00
|
|
|
ty.span, "generally you want to avoid `&mut &mut _` if possible"))
|
2015-08-11 13:22:20 -05:00
|
|
|
}
|
2015-05-18 02:02:24 -05:00
|
|
|
}
|
2015-05-18 03:41:15 -05:00
|
|
|
|
2015-05-25 00:22:41 -05:00
|
|
|
fn check_expr_expd(cx: &Context, expr: &Expr, info: Option<&ExpnInfo>) {
|
2015-08-11 13:22:20 -05:00
|
|
|
if in_macro(cx, info) { return; }
|
|
|
|
|
|
|
|
fn unwrap_addr(expr : &Expr) -> Option<&Expr> {
|
|
|
|
match expr.node {
|
|
|
|
ExprAddrOf(MutMutable, ref e) => Option::Some(e),
|
|
|
|
_ => Option::None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
unwrap_addr(expr).map_or((), |e| {
|
|
|
|
unwrap_addr(e).map(|_| {
|
|
|
|
span_lint(cx, MUT_MUT, expr.span,
|
2015-08-12 03:46:49 -05:00
|
|
|
"generally you want to avoid `&mut &mut _` if possible")
|
2015-08-11 13:22:20 -05:00
|
|
|
}).unwrap_or_else(|| {
|
|
|
|
if let TyRef(_, TypeAndMut{ty: _, mutbl: MutMutable}) =
|
|
|
|
cx.tcx.expr_ty(e).sty {
|
|
|
|
span_lint(cx, MUT_MUT, expr.span,
|
2015-08-12 03:46:49 -05:00
|
|
|
"this expression mutably borrows a mutable reference. \
|
2015-08-13 01:15:42 -05:00
|
|
|
Consider reborrowing")
|
2015-08-11 13:22:20 -05:00
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
2015-05-25 00:22:41 -05:00
|
|
|
}
|
|
|
|
|
2015-05-18 03:41:15 -05:00
|
|
|
fn unwrap_mut(ty : &Ty) -> Option<&Ty> {
|
2015-08-11 13:22:20 -05:00
|
|
|
match ty.node {
|
|
|
|
TyPtr(MutTy{ ty: ref pty, mutbl: MutMutable }) => Option::Some(pty),
|
|
|
|
TyRptr(_, MutTy{ ty: ref pty, mutbl: MutMutable }) => Option::Some(pty),
|
|
|
|
_ => Option::None
|
|
|
|
}
|
2015-05-18 03:41:15 -05:00
|
|
|
}
|