2018-05-30 10:15:50 +02:00
|
|
|
use crate::consts::{constant_simple, Constant};
|
2017-09-30 20:14:00 +03:00
|
|
|
use rustc::hir::*;
|
2018-08-28 13:13:42 +02:00
|
|
|
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
|
2018-07-29 11:04:40 +02:00
|
|
|
use rustc::{declare_tool_lint, lint_array};
|
2018-08-19 19:06:53 -07:00
|
|
|
use syntax::source_map::Span;
|
2018-05-30 10:15:50 +02:00
|
|
|
use crate::utils::{in_macro, span_lint};
|
2017-09-30 20:14:00 +03:00
|
|
|
|
|
|
|
/// **What it does:** Checks for erasing operations, e.g. `x * 0`.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** The whole expression can be replaced by zero.
|
2017-10-15 10:32:47 +03:00
|
|
|
/// This is most likely not the intended outcome and should probably be
|
|
|
|
/// corrected
|
2017-09-30 20:14:00 +03:00
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
/// ```rust
|
|
|
|
/// 0 / x; 0 * x; x & 0
|
|
|
|
/// ```
|
2018-03-28 15:24:26 +02:00
|
|
|
declare_clippy_lint! {
|
2017-09-30 20:14:00 +03:00
|
|
|
pub ERASING_OP,
|
2018-03-28 15:24:26 +02:00
|
|
|
correctness,
|
2017-09-30 20:14:00 +03:00
|
|
|
"using erasing operations, e.g. `x * 0` or `y & 0`"
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Copy, Clone)]
|
|
|
|
pub struct ErasingOp;
|
|
|
|
|
|
|
|
impl LintPass for ErasingOp {
|
|
|
|
fn get_lints(&self) -> LintArray {
|
|
|
|
lint_array!(ERASING_OP)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ErasingOp {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
|
|
|
|
if in_macro(e.span) {
|
|
|
|
return;
|
|
|
|
}
|
2018-07-12 15:30:57 +08:00
|
|
|
if let ExprKind::Binary(ref cmp, ref left, ref right) = e.node {
|
2017-09-30 20:14:00 +03:00
|
|
|
match cmp.node {
|
2018-07-12 15:50:09 +08:00
|
|
|
BinOpKind::Mul | BinOpKind::BitAnd => {
|
2017-09-30 20:14:00 +03:00
|
|
|
check(cx, left, e.span);
|
|
|
|
check(cx, right, e.span);
|
|
|
|
},
|
2018-07-12 15:50:09 +08:00
|
|
|
BinOpKind::Div => check(cx, left, e.span),
|
2017-09-30 20:14:00 +03:00
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-23 13:01:12 +02:00
|
|
|
fn check(cx: &LateContext<'_, '_>, e: &Expr, span: Span) {
|
2018-05-13 13:16:31 +02:00
|
|
|
if let Some(Constant::Int(v)) = constant_simple(cx, cx.tables, e) {
|
2018-03-13 11:38:11 +01:00
|
|
|
if v == 0 {
|
2017-09-30 20:14:00 +03:00
|
|
|
span_lint(
|
|
|
|
cx,
|
|
|
|
ERASING_OP,
|
|
|
|
span,
|
2017-10-15 10:32:47 +03:00
|
|
|
"this operation will always return zero. This is likely not the intended outcome",
|
2017-09-30 20:14:00 +03:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|