]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/neg_multiply.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / neg_multiply.rs
1 use if_chain::if_chain;
2 use rustc::hir::*;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_tool_lint, lint_array};
5 use syntax::source_map::{Span, Spanned};
6
7 use crate::consts::{self, Constant};
8 use crate::utils::span_lint;
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 #[derive(Copy, Clone)]
27 pub struct NegMultiply;
28
29 impl LintPass for NegMultiply {
30     fn get_lints(&self) -> LintArray {
31         lint_array!(NEG_MULTIPLY)
32     }
33
34     fn name(&self) -> &'static str {
35         "NegMultiply"
36     }
37 }
38
39 #[allow(clippy::match_same_arms)]
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NegMultiply {
41     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
42         if let ExprKind::Binary(
43             Spanned {
44                 node: BinOpKind::Mul, ..
45             },
46             ref l,
47             ref r,
48         ) = e.node
49         {
50             match (&l.node, &r.node) {
51                 (&ExprKind::Unary(..), &ExprKind::Unary(..)) => (),
52                 (&ExprKind::Unary(UnNeg, ref lit), _) => check_mul(cx, e.span, lit, r),
53                 (_, &ExprKind::Unary(UnNeg, ref lit)) => check_mul(cx, e.span, lit, l),
54                 _ => (),
55             }
56         }
57     }
58 }
59
60 fn check_mul(cx: &LateContext<'_, '_>, span: Span, lit: &Expr, exp: &Expr) {
61     if_chain! {
62         if let ExprKind::Lit(ref l) = lit.node;
63         if let Constant::Int(val) = consts::lit_to_constant(&l.node, cx.tables.expr_ty(lit));
64         if val == 1;
65         if cx.tables.expr_ty(exp).is_integral();
66         then {
67             span_lint(cx,
68                       NEG_MULTIPLY,
69                       span,
70                       "Negation by multiplying with -1");
71         }
72     }
73 }