]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/neg_multiply.rs
Merge pull request #3269 from rust-lang-nursery/relicense
[rust.git] / clippy_lints / src / neg_multiply.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use if_chain::if_chain;
15 use crate::syntax::source_map::{Span, Spanned};
16
17 use crate::consts::{self, Constant};
18 use crate::utils::span_lint;
19
20 /// **What it does:** Checks for multiplication by -1 as a form of negation.
21 ///
22 /// **Why is this bad?** It's more readable to just negate.
23 ///
24 /// **Known problems:** This only catches integers (for now).
25 ///
26 /// **Example:**
27 /// ```rust
28 /// x * -1
29 /// ```
30 declare_clippy_lint! {
31     pub NEG_MULTIPLY,
32     style,
33     "multiplying integers with -1"
34 }
35
36 #[derive(Copy, Clone)]
37 pub struct NegMultiply;
38
39 impl LintPass for NegMultiply {
40     fn get_lints(&self) -> LintArray {
41         lint_array!(NEG_MULTIPLY)
42     }
43 }
44
45 #[allow(clippy::match_same_arms)]
46 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NegMultiply {
47     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
48         if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, ref l, ref r) = e.node {
49             match (&l.node, &r.node) {
50                 (&ExprKind::Unary(..), &ExprKind::Unary(..)) => (),
51                 (&ExprKind::Unary(UnNeg, ref lit), _) => check_mul(cx, e.span, lit, r),
52                 (_, &ExprKind::Unary(UnNeg, ref lit)) => check_mul(cx, e.span, lit, l),
53                 _ => (),
54             }
55         }
56     }
57 }
58
59 fn check_mul(cx: &LateContext<'_, '_>, span: Span, lit: &Expr, exp: &Expr) {
60     if_chain! {
61         if let ExprKind::Lit(ref l) = lit.node;
62         if let Constant::Int(val) = consts::lit_to_constant(&l.node, cx.tables.expr_ty(lit));
63         if val == 1;
64         if cx.tables.expr_ty(exp).is_integral();
65         then {
66             span_lint(cx,
67                       NEG_MULTIPLY,
68                       span,
69                       "Negation by multiplying with -1");
70         }
71     }
72 }