]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/neg_multiply.rs
Rollup merge of #82739 - jyn514:separate-stage0-stage1, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / neg_multiply.rs
1 use clippy_utils::diagnostics::span_lint;
2 use if_chain::if_chain;
3 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
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 use crate::consts::{self, Constant};
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks for multiplication by -1 as a form of negation.
12     ///
13     /// **Why is this bad?** It's more readable to just negate.
14     ///
15     /// **Known problems:** This only catches integers (for now).
16     ///
17     /// **Example:**
18     /// ```ignore
19     /// x * -1
20     /// ```
21     pub NEG_MULTIPLY,
22     style,
23     "multiplying integers with `-1`"
24 }
25
26 declare_lint_pass!(NegMultiply => [NEG_MULTIPLY]);
27
28 #[allow(clippy::match_same_arms)]
29 impl<'tcx> LateLintPass<'tcx> for NegMultiply {
30     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
31         if let ExprKind::Binary(ref op, ref left, ref right) = e.kind {
32             if BinOpKind::Mul == op.node {
33                 match (&left.kind, &right.kind) {
34                     (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {},
35                     (&ExprKind::Unary(UnOp::Neg, ref lit), _) => check_mul(cx, e.span, lit, right),
36                     (_, &ExprKind::Unary(UnOp::Neg, ref lit)) => check_mul(cx, e.span, lit, left),
37                     _ => {},
38                 }
39             }
40         }
41     }
42 }
43
44 fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
45     if_chain! {
46         if let ExprKind::Lit(ref l) = lit.kind;
47         if let Constant::Int(1) = consts::lit_to_constant(&l.node, cx.typeck_results().expr_ty_opt(lit));
48         if cx.typeck_results().expr_ty(exp).is_integral();
49         then {
50             span_lint(cx, NEG_MULTIPLY, span, "negation by multiplying with `-1`");
51         }
52     }
53 }