]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/neg_multiply.rs
Rollup merge of #85534 - csmoe:demagnle-assert, r=michaelwoerister
[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     pub NEG_MULTIPLY,
24     style,
25     "multiplying integers with `-1`"
26 }
27
28 declare_lint_pass!(NegMultiply => [NEG_MULTIPLY]);
29
30 #[allow(clippy::match_same_arms)]
31 impl<'tcx> LateLintPass<'tcx> for NegMultiply {
32     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
33         if let ExprKind::Binary(ref op, left, right) = e.kind {
34             if BinOpKind::Mul == op.node {
35                 match (&left.kind, &right.kind) {
36                     (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {},
37                     (&ExprKind::Unary(UnOp::Neg, lit), _) => check_mul(cx, e.span, lit, right),
38                     (_, &ExprKind::Unary(UnOp::Neg, lit)) => check_mul(cx, e.span, lit, left),
39                     _ => {},
40                 }
41             }
42         }
43     }
44 }
45
46 fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
47     if_chain! {
48         if let ExprKind::Lit(ref l) = lit.kind;
49         if let Constant::Int(1) = consts::lit_to_constant(&l.node, cx.typeck_results().expr_ty_opt(lit));
50         if cx.typeck_results().expr_ty(exp).is_integral();
51         then {
52             span_lint(cx, NEG_MULTIPLY, span, "negation by multiplying with `-1`");
53         }
54     }
55 }