]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/erasing_op.rs
Rollup merge of #91313 - petrochenkov:cratexp, r=Aaron1011
[rust.git] / src / tools / clippy / clippy_lints / src / erasing_op.rs
1 use clippy_utils::consts::{constant_simple, Constant};
2 use clippy_utils::diagnostics::span_lint;
3 use rustc_hir::{BinOpKind, Expr, ExprKind};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6 use rustc_span::source_map::Span;
7
8 declare_clippy_lint! {
9     /// ### What it does
10     /// Checks for erasing operations, e.g., `x * 0`.
11     ///
12     /// ### Why is this bad?
13     /// The whole expression can be replaced by zero.
14     /// This is most likely not the intended outcome and should probably be
15     /// corrected
16     ///
17     /// ### Example
18     /// ```rust
19     /// let x = 1;
20     /// 0 / x;
21     /// 0 * x;
22     /// x & 0;
23     /// ```
24     pub ERASING_OP,
25     correctness,
26     "using erasing operations, e.g., `x * 0` or `y & 0`"
27 }
28
29 declare_lint_pass!(ErasingOp => [ERASING_OP]);
30
31 impl<'tcx> LateLintPass<'tcx> for ErasingOp {
32     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
33         if e.span.from_expansion() {
34             return;
35         }
36         if let ExprKind::Binary(ref cmp, left, right) = e.kind {
37             match cmp.node {
38                 BinOpKind::Mul | BinOpKind::BitAnd => {
39                     check(cx, left, e.span);
40                     check(cx, right, e.span);
41                 },
42                 BinOpKind::Div => check(cx, left, e.span),
43                 _ => (),
44             }
45         }
46     }
47 }
48
49 fn check(cx: &LateContext<'_>, e: &Expr<'_>, span: Span) {
50     if constant_simple(cx, cx.typeck_results(), e) == Some(Constant::Int(0)) {
51         span_lint(
52             cx,
53             ERASING_OP,
54             span,
55             "this operation will always return zero. This is likely not the intended outcome",
56         );
57     }
58 }