]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/neg_multiply.rs
Merge branch 'macro-use' into HEAD
[rust.git] / clippy_lints / src / neg_multiply.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use rustc::{declare_lint, lint_array};
4 use if_chain::if_chain;
5 use syntax::codemap::{Span, Spanned};
6
7 use crate::consts::{self, Constant};
8 use crate::utils::span_lint;
9
10 /// **What it does:** Checks for multiplication by -1 as a form of negation.
11 ///
12 /// **Why is this bad?** It's more readable to just negate.
13 ///
14 /// **Known problems:** This only catches integers (for now).
15 ///
16 /// **Example:**
17 /// ```rust
18 /// x * -1
19 /// ```
20 declare_clippy_lint! {
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
35 #[allow(match_same_arms)]
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NegMultiply {
37     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
38         if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, ref l, ref r) = e.node {
39             match (&l.node, &r.node) {
40                 (&ExprKind::Unary(..), &ExprKind::Unary(..)) => (),
41                 (&ExprKind::Unary(UnNeg, ref lit), _) => check_mul(cx, e.span, lit, r),
42                 (_, &ExprKind::Unary(UnNeg, ref lit)) => check_mul(cx, e.span, lit, l),
43                 _ => (),
44             }
45         }
46     }
47 }
48
49 fn check_mul(cx: &LateContext, span: Span, lit: &Expr, exp: &Expr) {
50     if_chain! {
51         if let ExprKind::Lit(ref l) = lit.node;
52         if let Constant::Int(val) = consts::lit_to_constant(&l.node, cx.tables.expr_ty(lit));
53         if val == 1;
54         if cx.tables.expr_ty(exp).is_integral();
55         then {
56             span_lint(cx,
57                       NEG_MULTIPLY,
58                       span,
59                       "Negation by multiplying with -1");
60         }
61     }
62 }