1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
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};
17 use crate::consts::{self, Constant};
18 use crate::utils::span_lint;
20 /// **What it does:** Checks for multiplication by -1 as a form of negation.
22 /// **Why is this bad?** It's more readable to just negate.
24 /// **Known problems:** This only catches integers (for now).
30 declare_clippy_lint! {
33 "multiplying integers with -1"
36 #[derive(Copy, Clone)]
37 pub struct NegMultiply;
39 impl LintPass for NegMultiply {
40 fn get_lints(&self) -> LintArray {
41 lint_array!(NEG_MULTIPLY)
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),
59 fn check_mul(cx: &LateContext<'_, '_>, span: Span, lit: &Expr, exp: &Expr) {
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));
64 if cx.tables.expr_ty(exp).is_integral();
69 "Negation by multiplying with -1");