1 use if_chain::if_chain;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
4 use rustc::{declare_tool_lint, lint_array};
5 use syntax::source_map::{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)
34 fn name(&self) -> &'static str {
39 #[allow(clippy::match_same_arms)]
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NegMultiply {
41 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
42 if let ExprKind::Binary(
44 node: BinOpKind::Mul, ..
50 match (&l.node, &r.node) {
51 (&ExprKind::Unary(..), &ExprKind::Unary(..)) => (),
52 (&ExprKind::Unary(UnNeg, ref lit), _) => check_mul(cx, e.span, lit, r),
53 (_, &ExprKind::Unary(UnNeg, ref lit)) => check_mul(cx, e.span, lit, l),
60 fn check_mul(cx: &LateContext<'_, '_>, span: Span, lit: &Expr, exp: &Expr) {
62 if let ExprKind::Lit(ref l) = lit.node;
63 if let Constant::Int(val) = consts::lit_to_constant(&l.node, cx.tables.expr_ty(lit));
65 if cx.tables.expr_ty(exp).is_integral();
70 "Negation by multiplying with -1");