2015-05-18 07:02:24 +00:00
|
|
|
use syntax::ptr::P;
|
|
|
|
use syntax::ast::*;
|
2015-05-18 08:41:15 +00:00
|
|
|
use rustc::lint::{Context, LintPass, LintArray, Lint};
|
2015-06-15 11:27:24 +00:00
|
|
|
use rustc::middle::ty::{expr_ty, TypeVariants, mt, TyRef};
|
2015-05-26 11:52:40 +00:00
|
|
|
use syntax::codemap::{BytePos, ExpnInfo, MacroFormat, Span};
|
2015-06-01 20:30:34 +00:00
|
|
|
use utils::in_macro;
|
2015-05-18 07:02:24 +00:00
|
|
|
|
|
|
|
declare_lint!(pub MUT_MUT, Warn,
|
|
|
|
"Warn on 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)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_expr(&mut self, cx: &Context, expr: &Expr) {
|
2015-05-25 05:22:41 +00:00
|
|
|
cx.sess().codemap().with_expn_info(expr.span.expn_id,
|
|
|
|
|info| check_expr_expd(cx, expr, info))
|
2015-05-18 07:02:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn check_ty(&mut self, cx: &Context, ty: &Ty) {
|
2015-05-22 22:49:13 +00:00
|
|
|
unwrap_mut(ty).and_then(unwrap_mut).map_or((), |_| cx.span_lint(MUT_MUT,
|
|
|
|
ty.span, "Generally you want to avoid &mut &mut _ if possible."))
|
2015-05-18 07:02:24 +00:00
|
|
|
}
|
|
|
|
}
|
2015-05-18 08:41:15 +00:00
|
|
|
|
2015-05-25 05:22:41 +00:00
|
|
|
fn check_expr_expd(cx: &Context, expr: &Expr, info: Option<&ExpnInfo>) {
|
2015-05-26 11:52:40 +00:00
|
|
|
if in_macro(cx, info) { return; }
|
2015-05-25 05:22:41 +00:00
|
|
|
|
|
|
|
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(|_| {
|
|
|
|
cx.span_lint(MUT_MUT, expr.span,
|
|
|
|
"Generally you want to avoid &mut &mut _ if possible.")
|
|
|
|
}).unwrap_or_else(|| {
|
2015-06-15 11:27:24 +00:00
|
|
|
if let TyRef(_, mt{ty: _, mutbl: MutMutable}) =
|
2015-05-25 05:22:41 +00:00
|
|
|
expr_ty(cx.tcx, e).sty {
|
|
|
|
cx.span_lint(MUT_MUT, expr.span,
|
|
|
|
"This expression mutably borrows a mutable reference. \
|
|
|
|
Consider reborrowing")
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2015-05-18 08:41:15 +00:00
|
|
|
fn unwrap_mut(ty : &Ty) -> Option<&Ty> {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|