]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/neg_multiply.rs
Auto merge of #8960 - Jarcho:iter_cloned, r=giraffate
[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 impl<'tcx> LateLintPass<'tcx> for NegMultiply {
38     fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
39         if let ExprKind::Binary(ref op, left, right) = e.kind {
40             if BinOpKind::Mul == op.node {
41                 match (&left.kind, &right.kind) {
42                     (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {},
43                     (&ExprKind::Unary(UnOp::Neg, lit), _) => check_mul(cx, e.span, lit, right),
44                     (_, &ExprKind::Unary(UnOp::Neg, lit)) => check_mul(cx, e.span, lit, left),
45                     _ => {},
46                 }
47             }
48         }
49     }
50 }
51
52 fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
53     if_chain! {
54         if let ExprKind::Lit(ref l) = lit.kind;
55         if consts::lit_to_mir_constant(&l.node, cx.typeck_results().expr_ty_opt(lit)) == Constant::Int(1);
56         if cx.typeck_results().expr_ty(exp).is_integral();
57
58         then {
59             let mut applicability = Applicability::MachineApplicable;
60             let suggestion = format!("-{}", snippet_with_applicability(cx, exp.span, "..", &mut applicability));
61             span_lint_and_sugg(
62                     cx,
63                     NEG_MULTIPLY,
64                     span,
65                     "this multiplication by -1 can be written more succinctly",
66                     "consider using",
67                     suggestion,
68                     applicability,
69                 );
70         }
71     }
72 }