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