3 use rustc::{declare_lint, lint_array};
4 use if_chain::if_chain;
5 use syntax::codemap::{Span, Spanned};
7 use crate::consts::{self, Constant};
8 use crate::utils::span_lint;
10 /// **What it does:** Checks for multiplication by -1 as a form of negation.
12 /// **Why is this bad?** It's more readable to just negate.
14 /// **Known problems:** This only catches integers (for now).
20 declare_clippy_lint! {
23 "multiplying integers with -1"
26 #[derive(Copy, Clone)]
27 pub struct NegMultiply;
29 impl LintPass for NegMultiply {
30 fn get_lints(&self) -> LintArray {
31 lint_array!(NEG_MULTIPLY)
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),
49 fn check_mul(cx: &LateContext, span: Span, lit: &Expr, exp: &Expr) {
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));
54 if cx.tables.expr_ty(exp).is_integral();
59 "Negation by multiplying with -1");