rust-clippy/clippy_lints/src/erasing_op.rs

75 lines
2.2 KiB
Rust
Raw Normal View History

2018-10-06 16:18:06 +00:00
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
2018-05-30 08:15:50 +00:00
use crate::consts::{constant_simple, Constant};
use crate::rustc::hir::*;
use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
use crate::rustc::{declare_tool_lint, lint_array};
use crate::syntax::source_map::Span;
2018-05-30 08:15:50 +00:00
use crate::utils::{in_macro, span_lint};
/// **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 07:32:47 +00:00
/// This is most likely not the intended outcome and should probably be
/// corrected
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// 0 / x; 0 * x; x & 0
/// ```
2018-03-28 13:24:26 +00:00
declare_clippy_lint! {
pub ERASING_OP,
2018-03-28 13:24:26 +00:00
correctness,
"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 07:30:57 +00:00
if let ExprKind::Binary(ref cmp, ref left, ref right) = e.node {
match cmp.node {
2018-07-12 07:50:09 +00:00
BinOpKind::Mul | BinOpKind::BitAnd => {
check(cx, left, e.span);
check(cx, right, e.span);
},
2018-07-12 07:50:09 +00:00
BinOpKind::Div => check(cx, left, e.span),
_ => (),
}
}
}
}
2018-07-23 11:01:12 +00:00
fn check(cx: &LateContext<'_, '_>, e: &Expr, span: Span) {
2018-05-13 11:16:31 +00:00
if let Some(Constant::Int(v)) = constant_simple(cx, cx.tables, e) {
2018-03-13 10:38:11 +00:00
if v == 0 {
span_lint(
cx,
ERASING_OP,
span,
2017-10-15 07:32:47 +00:00
"this operation will always return zero. This is likely not the intended outcome",
);
}
}
}