]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/erasing_op.rs
Auto merge of #3519 - phansch:brave_newer_ui_tests, r=flip1995
[rust.git] / clippy_lints / src / erasing_op.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::consts::{constant_simple, Constant};
11 use crate::utils::{in_macro, span_lint};
12 use rustc::hir::*;
13 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use rustc::{declare_tool_lint, lint_array};
15 use syntax::source_map::Span;
16
17 /// **What it does:** Checks for erasing operations, e.g. `x * 0`.
18 ///
19 /// **Why is this bad?** The whole expression can be replaced by zero.
20 /// This is most likely not the intended outcome and should probably be
21 /// corrected
22 ///
23 /// **Known problems:** None.
24 ///
25 /// **Example:**
26 /// ```rust
27 /// 0 / x;
28 /// 0 * x;
29 /// x & 0
30 /// ```
31 declare_clippy_lint! {
32     pub ERASING_OP,
33     correctness,
34     "using erasing operations, e.g. `x * 0` or `y & 0`"
35 }
36
37 #[derive(Copy, Clone)]
38 pub struct ErasingOp;
39
40 impl LintPass for ErasingOp {
41     fn get_lints(&self) -> LintArray {
42         lint_array!(ERASING_OP)
43     }
44 }
45
46 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ErasingOp {
47     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
48         if in_macro(e.span) {
49             return;
50         }
51         if let ExprKind::Binary(ref cmp, ref left, ref right) = e.node {
52             match cmp.node {
53                 BinOpKind::Mul | BinOpKind::BitAnd => {
54                     check(cx, left, e.span);
55                     check(cx, right, e.span);
56                 },
57                 BinOpKind::Div => check(cx, left, e.span),
58                 _ => (),
59             }
60         }
61     }
62 }
63
64 fn check(cx: &LateContext<'_, '_>, e: &Expr, span: Span) {
65     if let Some(Constant::Int(v)) = constant_simple(cx, cx.tables, e) {
66         if v == 0 {
67             span_lint(
68                 cx,
69                 ERASING_OP,
70                 span,
71                 "this operation will always return zero. This is likely not the intended outcome",
72             );
73         }
74     }
75 }