]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/erasing_op.rs
Auto merge of #3987 - phansch:rustfix_option_map_or_none, r=flip1995
[rust.git] / clippy_lints / src / erasing_op.rs
1 use rustc::hir::*;
2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_lint_pass, declare_tool_lint};
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     /// let x = 1;
21     /// 0 / x;
22     /// 0 * x;
23     /// x & 0;
24     /// ```
25     pub ERASING_OP,
26     correctness,
27     "using erasing operations, e.g., `x * 0` or `y & 0`"
28 }
29
30 declare_lint_pass!(ErasingOp => [ERASING_OP]);
31
32 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ErasingOp {
33     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
34         if in_macro(e.span) {
35             return;
36         }
37         if let ExprKind::Binary(ref cmp, ref left, ref right) = e.node {
38             match cmp.node {
39                 BinOpKind::Mul | BinOpKind::BitAnd => {
40                     check(cx, left, e.span);
41                     check(cx, right, e.span);
42                 },
43                 BinOpKind::Div => check(cx, left, e.span),
44                 _ => (),
45             }
46         }
47     }
48 }
49
50 fn check(cx: &LateContext<'_, '_>, e: &Expr, span: Span) {
51     if let Some(Constant::Int(v)) = constant_simple(cx, cx.tables, e) {
52         if v == 0 {
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     }
61 }