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