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