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).
25 "multiplying integers with `-1`"
28 declare_lint_pass!(NegMultiply => [NEG_MULTIPLY]);
30 #[allow(clippy::match_same_arms)]
31 impl<'tcx> LateLintPass<'tcx> for NegMultiply {
32 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
33 if let ExprKind::Binary(ref op, left, right) = e.kind {
34 if BinOpKind::Mul == op.node {
35 match (&left.kind, &right.kind) {
36 (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {},
37 (&ExprKind::Unary(UnOp::Neg, lit), _) => check_mul(cx, e.span, lit, right),
38 (_, &ExprKind::Unary(UnOp::Neg, lit)) => check_mul(cx, e.span, lit, left),
46 fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
48 if let ExprKind::Lit(ref l) = lit.kind;
49 if let Constant::Int(1) = consts::lit_to_constant(&l.node, cx.typeck_results().expr_ty_opt(lit));
50 if cx.typeck_results().expr_ty(exp).is_integral();
52 span_lint(cx, NEG_MULTIPLY, span, "negation by multiplying with `-1`");