]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/neg_multiply.rs
Rollup merge of #90102 - nbdd0121:box3, r=jonas-schievink
[rust.git] / clippy_lints / src / neg_multiply.rs
1 use clippy_utils::consts::{self, Constant};
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use clippy_utils::source::snippet_with_applicability;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::Span;
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Checks for multiplication by -1 as a form of negation.
14     ///
15     /// ### Why is this bad?
16     /// It's more readable to just negate.
17     ///
18     /// ### Known problems
19     /// This only catches integers (for now).
20     ///
21     /// ### Example
22     /// ```ignore
23     /// // Bad
24     /// let a = x * -1;
25     ///
26     /// // Good
27     /// let b = -x;
28     /// ```
29     #[clippy::version = "pre 1.29.0"]
30     pub NEG_MULTIPLY,
31     style,
32     "multiplying integers by `-1`"
33 }
34
35 declare_lint_pass!(NegMultiply => [NEG_MULTIPLY]);
36
37 #[allow(clippy::match_same_arms)]
38 impl<'tcx> LateLintPass<'tcx> for NegMultiply {
39     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
40         if let ExprKind::Binary(ref op, left, right) = e.kind {
41             if BinOpKind::Mul == op.node {
42                 match (&left.kind, &right.kind) {
43                     (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {},
44                     (&ExprKind::Unary(UnOp::Neg, lit), _) => check_mul(cx, e.span, lit, right),
45                     (_, &ExprKind::Unary(UnOp::Neg, lit)) => check_mul(cx, e.span, lit, left),
46                     _ => {},
47                 }
48             }
49         }
50     }
51 }
52
53 fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
54     if_chain! {
55         if let ExprKind::Lit(ref l) = lit.kind;
56         if consts::lit_to_constant(&l.node, cx.typeck_results().expr_ty_opt(lit)) == Constant::Int(1);
57         if cx.typeck_results().expr_ty(exp).is_integral();
58
59         then {
60             let mut applicability = Applicability::MachineApplicable;
61             let suggestion = format!("-{}", snippet_with_applicability(cx, exp.span, "..", &mut applicability));
62             span_lint_and_sugg(
63                     cx,
64                     NEG_MULTIPLY,
65                     span,
66                     "this multiplication by -1 can be written more succinctly",
67                     "consider using",
68                     suggestion,
69                     applicability,
70                 );
71         }
72     }
73 }