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