]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/erasing_op.rs
Auto merge of #3700 - phansch:would_you_like_some_help_with_this_const_fn, r=oli-obk
[rust.git] / clippy_lints / src / erasing_op.rs
1 use crate::consts::{constant_simple, Constant};
2 use crate::utils::{in_macro, span_lint};
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use syntax::source_map::Span;
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;
19 /// 0 * x;
20 /// x & 0
21 /// ```
22 declare_clippy_lint! {
23     pub ERASING_OP,
24     correctness,
25     "using erasing operations, e.g. `x * 0` or `y & 0`"
26 }
27
28 #[derive(Copy, Clone)]
29 pub struct ErasingOp;
30
31 impl LintPass for ErasingOp {
32     fn get_lints(&self) -> LintArray {
33         lint_array!(ERASING_OP)
34     }
35
36     fn name(&self) -> &'static str {
37         "ErasingOp"
38     }
39 }
40
41 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ErasingOp {
42     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
43         if in_macro(e.span) {
44             return;
45         }
46         if let ExprKind::Binary(ref cmp, ref left, ref right) = e.node {
47             match cmp.node {
48                 BinOpKind::Mul | BinOpKind::BitAnd => {
49                     check(cx, left, e.span);
50                     check(cx, right, e.span);
51                 },
52                 BinOpKind::Div => check(cx, left, e.span),
53                 _ => (),
54             }
55         }
56     }
57 }
58
59 fn check(cx: &LateContext<'_, '_>, e: &Expr, span: Span) {
60     if let Some(Constant::Int(v)) = constant_simple(cx, cx.tables, e) {
61         if v == 0 {
62             span_lint(
63                 cx,
64                 ERASING_OP,
65                 span,
66                 "this operation will always return zero. This is likely not the intended outcome",
67             );
68         }
69     }
70 }