1 use if_chain::if_chain;
2 use rustc::declare_lint_pass;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc_session::declare_tool_lint;
6 use syntax::source_map::Span;
8 use crate::consts::{self, Constant};
9 use crate::utils::span_lint;
11 declare_clippy_lint! {
12 /// **What it does:** Checks for multiplication by -1 as a form of negation.
14 /// **Why is this bad?** It's more readable to just negate.
16 /// **Known problems:** This only catches integers (for now).
24 "multiplying integers with -1"
27 declare_lint_pass!(NegMultiply => [NEG_MULTIPLY]);
29 #[allow(clippy::match_same_arms)]
30 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NegMultiply {
31 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr) {
32 if let ExprKind::Binary(ref op, ref left, ref right) = e.kind {
33 if BinOpKind::Mul == op.node {
34 match (&left.kind, &right.kind) {
35 (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {},
36 (&ExprKind::Unary(UnNeg, ref lit), _) => check_mul(cx, e.span, lit, right),
37 (_, &ExprKind::Unary(UnNeg, ref lit)) => check_mul(cx, e.span, lit, left),
45 fn check_mul(cx: &LateContext<'_, '_>, span: Span, lit: &Expr, exp: &Expr) {
47 if let ExprKind::Lit(ref l) = lit.kind;
48 if let Constant::Int(1) = consts::lit_to_constant(&l.node, cx.tables.expr_ty_opt(lit));
49 if cx.tables.expr_ty(exp).is_integral();
51 span_lint(cx, NEG_MULTIPLY, span, "Negation by multiplying with -1");