]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/erasing_op.rs
Fix lint registration
[rust.git] / clippy_lints / src / erasing_op.rs
1 use clippy_utils::consts::{constant_simple, Constant};
2 use clippy_utils::diagnostics::span_lint;
3 use clippy_utils::ty::same_type_and_consts;
4
5 use rustc_hir::{BinOpKind, Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty::TypeckResults;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9
10 declare_clippy_lint! {
11     /// ### What it does
12     /// Checks for erasing operations, e.g., `x * 0`.
13     ///
14     /// ### Why is this bad?
15     /// The whole expression can be replaced by zero.
16     /// This is most likely not the intended outcome and should probably be
17     /// corrected
18     ///
19     /// ### Example
20     /// ```rust
21     /// let x = 1;
22     /// 0 / x;
23     /// 0 * x;
24     /// x & 0;
25     /// ```
26     #[clippy::version = "pre 1.29.0"]
27     pub ERASING_OP,
28     correctness,
29     "using erasing operations, e.g., `x * 0` or `y & 0`"
30 }
31
32 declare_lint_pass!(ErasingOp => [ERASING_OP]);
33
34 impl<'tcx> LateLintPass<'tcx> for ErasingOp {
35     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
36         if e.span.from_expansion() {
37             return;
38         }
39         if let ExprKind::Binary(ref cmp, left, right) = e.kind {
40             let tck = cx.typeck_results();
41             match cmp.node {
42                 BinOpKind::Mul | BinOpKind::BitAnd => {
43                     check(cx, tck, left, right, e);
44                     check(cx, tck, right, left, e);
45                 },
46                 BinOpKind::Div => check(cx, tck, left, right, e),
47                 _ => (),
48             }
49         }
50     }
51 }
52
53 fn different_types(tck: &TypeckResults<'_>, input: &Expr<'_>, output: &Expr<'_>) -> bool {
54     let input_ty = tck.expr_ty(input).peel_refs();
55     let output_ty = tck.expr_ty(output).peel_refs();
56     !same_type_and_consts(input_ty, output_ty)
57 }
58
59 fn check<'tcx>(
60     cx: &LateContext<'tcx>,
61     tck: &TypeckResults<'tcx>,
62     op: &Expr<'tcx>,
63     other: &Expr<'tcx>,
64     parent: &Expr<'tcx>,
65 ) {
66     if constant_simple(cx, tck, op) == Some(Constant::Int(0)) {
67         if different_types(tck, other, parent) {
68             return;
69         }
70         span_lint(
71             cx,
72             ERASING_OP,
73             parent.span,
74             "this operation will always return zero. This is likely not the intended outcome",
75         );
76     }
77 }