1 use clippy_utils::consts::{self, Constant};
2 use clippy_utils::diagnostics::span_lint;
3 use if_chain::if_chain;
4 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7 use rustc_span::source_map::Span;
11 /// Checks for multiplication by -1 as a form of negation.
13 /// ### Why is this bad?
14 /// It's more readable to just negate.
16 /// ### Known problems
17 /// This only catches integers (for now).
23 #[clippy::version = "pre 1.29.0"]
26 "multiplying integers with `-1`"
29 declare_lint_pass!(NegMultiply => [NEG_MULTIPLY]);
31 #[allow(clippy::match_same_arms)]
32 impl<'tcx> LateLintPass<'tcx> for NegMultiply {
33 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
34 if let ExprKind::Binary(ref op, left, right) = e.kind {
35 if BinOpKind::Mul == op.node {
36 match (&left.kind, &right.kind) {
37 (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {},
38 (&ExprKind::Unary(UnOp::Neg, lit), _) => check_mul(cx, e.span, lit, right),
39 (_, &ExprKind::Unary(UnOp::Neg, lit)) => check_mul(cx, e.span, lit, left),
47 fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
49 if let ExprKind::Lit(ref l) = lit.kind;
50 if consts::lit_to_constant(&l.node, cx.typeck_results().expr_ty_opt(lit)) == Constant::Int(1);
51 if cx.typeck_results().expr_ty(exp).is_integral();
53 span_lint(cx, NEG_MULTIPLY, span, "negation by multiplying with `-1`");