rust/clippy_lints/src/erasing_op.rs

61 lines
1.7 KiB
Rust
Raw Normal View History

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