]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/erasing_op.rs
Rustup to rust-lang/rust#66936
[rust.git] / clippy_lints / src / erasing_op.rs
1 use rustc::declare_lint_pass;
2 use rustc::hir::*;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc_session::declare_tool_lint;
5 use syntax::source_map::Span;
6
7 use crate::consts::{constant_simple, Constant};
8 use crate::utils::span_lint;
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for erasing operations, e.g., `x * 0`.
12     ///
13     /// **Why is this bad?** The whole expression can be replaced by zero.
14     /// This is most likely not the intended outcome and should probably be
15     /// corrected
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     /// ```rust
21     /// let x = 1;
22     /// 0 / x;
23     /// 0 * x;
24     /// x & 0;
25     /// ```
26     pub ERASING_OP,
27     correctness,
28     "using erasing operations, e.g., `x * 0` or `y & 0`"
29 }
30
31 declare_lint_pass!(ErasingOp => [ERASING_OP]);
32
33 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ErasingOp {
34     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) {
35         if e.span.from_expansion() {
36             return;
37         }
38         if let ExprKind::Binary(ref cmp, ref left, ref right) = e.kind {
39             match cmp.node {
40                 BinOpKind::Mul | BinOpKind::BitAnd => {
41                     check(cx, left, e.span);
42                     check(cx, right, e.span);
43                 },
44                 BinOpKind::Div => check(cx, left, e.span),
45                 _ => (),
46             }
47         }
48     }
49 }
50
51 fn check(cx: &LateContext<'_, '_>, e: &Expr<'_>, span: Span) {
52     if let Some(Constant::Int(0)) = constant_simple(cx, cx.tables, e) {
53         span_lint(
54             cx,
55             ERASING_OP,
56             span,
57             "this operation will always return zero. This is likely not the intended outcome",
58         );
59     }
60 }