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.
10 use if_chain::if_chain;
12 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use rustc::{declare_tool_lint, lint_array};
14 use syntax::source_map::{Span, Spanned};
16 use crate::consts::{self, Constant};
17 use crate::utils::span_lint;
19 /// **What it does:** Checks for multiplication by -1 as a form of negation.
21 /// **Why is this bad?** It's more readable to just negate.
23 /// **Known problems:** This only catches integers (for now).
29 declare_clippy_lint! {
32 "multiplying integers with -1"
35 #[derive(Copy, Clone)]
36 pub struct NegMultiply;
38 impl LintPass for NegMultiply {
39 fn get_lints(&self) -> LintArray {
40 lint_array!(NEG_MULTIPLY)
44 #[allow(clippy::match_same_arms)]
45 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NegMultiply {
46 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
47 if let ExprKind::Binary(
49 node: BinOpKind::Mul, ..
55 match (&l.node, &r.node) {
56 (&ExprKind::Unary(..), &ExprKind::Unary(..)) => (),
57 (&ExprKind::Unary(UnNeg, ref lit), _) => check_mul(cx, e.span, lit, r),
58 (_, &ExprKind::Unary(UnNeg, ref lit)) => check_mul(cx, e.span, lit, l),
65 fn check_mul(cx: &LateContext<'_, '_>, span: Span, lit: &Expr, exp: &Expr) {
67 if let ExprKind::Lit(ref l) = lit.node;
68 if let Constant::Int(val) = consts::lit_to_constant(&l.node, cx.tables.expr_ty(lit));
70 if cx.tables.expr_ty(exp).is_integral();
75 "Negation by multiplying with -1");