]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/neg_multiply.rs
Auto merge of #4551 - mikerite:fix-ice-reporting, r=llogiq
[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_lint_pass, declare_tool_lint};
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 declare_lint_pass!(NegMultiply => [NEG_MULTIPLY]);
27
28 #[allow(clippy::match_same_arms)]
29 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NegMultiply {
30     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
31         if let ExprKind::Binary(
32             Spanned {
33                 node: BinOpKind::Mul, ..
34             },
35             ref l,
36             ref r,
37         ) = e.node
38         {
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 }