2017-02-17 08:32:51 +00:00
|
|
|
use rustc::lint::*;
|
|
|
|
use rustc::hir::*;
|
2017-02-17 10:59:52 +00:00
|
|
|
use utils::{is_direct_expn_of, implements_trait, span_lint};
|
2017-02-17 08:32:51 +00:00
|
|
|
|
|
|
|
/// **What it does:** Checks for `assert!(x == y)` which can be written better
|
|
|
|
/// as `assert_eq!(x, y)` if `x` and `y` implement `Debug` trait.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** `assert_eq` provides better assertion failure reporting.
|
|
|
|
///
|
2017-02-17 10:59:52 +00:00
|
|
|
/// **Known problems:** Hopefully none.
|
2017-02-17 08:32:51 +00:00
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
/// ```rust
|
|
|
|
/// let (x, y) = (1, 2);
|
|
|
|
///
|
|
|
|
/// assert!(x == y); // assertion failed: x == y
|
|
|
|
/// assert_eq!(x, y); // assertion failed: `(left == right)` (left: `1`, right: `2`)
|
|
|
|
/// ```
|
|
|
|
declare_lint! {
|
|
|
|
pub SHOULD_ASSERT_EQ,
|
|
|
|
Warn,
|
|
|
|
"using `assert` macro for asserting equality"
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct ShouldAssertEq;
|
|
|
|
|
|
|
|
impl LintPass for ShouldAssertEq {
|
|
|
|
fn get_lints(&self) -> LintArray {
|
|
|
|
lint_array![SHOULD_ASSERT_EQ]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ShouldAssertEq {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
|
|
|
|
if_let_chain! {[
|
|
|
|
let ExprIf(ref cond, ..) = e.node,
|
|
|
|
let ExprUnary(UnOp::UnNot, ref cond) = cond.node,
|
|
|
|
let ExprBinary(ref binop, ref expr1, ref expr2) = cond.node,
|
|
|
|
], {
|
|
|
|
if is_direct_expn_of(cx, e.span, "assert").is_none() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if binop.node != BinOp_::BiEq {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-02-17 10:59:52 +00:00
|
|
|
let debug_trait = if let Some(t) = cx.tcx.lang_items.debug_trait() {
|
|
|
|
t
|
|
|
|
} else {
|
|
|
|
return;
|
|
|
|
};
|
2017-02-17 08:32:51 +00:00
|
|
|
|
|
|
|
let ty1 = cx.tables.expr_ty(expr1);
|
|
|
|
let ty2 = cx.tables.expr_ty(expr2);
|
2017-02-17 10:59:52 +00:00
|
|
|
|
|
|
|
let parent = cx.tcx.hir.get_parent(e.id);
|
|
|
|
|
|
|
|
if implements_trait(cx, ty1, debug_trait, &[], Some(parent)) &&
|
|
|
|
implements_trait(cx, ty2, debug_trait, &[], Some(parent)) {
|
2017-02-17 08:32:51 +00:00
|
|
|
span_lint(cx, SHOULD_ASSERT_EQ, e.span, "use `assert_eq` for better reporting");
|
|
|
|
}
|
|
|
|
}}
|
|
|
|
}
|
|
|
|
}
|