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