1 use clippy_utils::consts::{self, Constant};
2 use clippy_utils::diagnostics::span_lint_and_sugg;
3 use clippy_utils::source::snippet_with_applicability;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::Span;
11 declare_clippy_lint! {
13 /// Checks for multiplication by -1 as a form of negation.
15 /// ### Why is this bad?
16 /// It's more readable to just negate.
18 /// ### Known problems
19 /// This only catches integers (for now).
29 #[clippy::version = "pre 1.29.0"]
32 "multiplying integers by `-1`"
35 declare_lint_pass!(NegMultiply => [NEG_MULTIPLY]);
37 #[allow(clippy::match_same_arms)]
38 impl<'tcx> LateLintPass<'tcx> for NegMultiply {
39 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
40 if let ExprKind::Binary(ref op, left, right) = e.kind {
41 if BinOpKind::Mul == op.node {
42 match (&left.kind, &right.kind) {
43 (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {},
44 (&ExprKind::Unary(UnOp::Neg, lit), _) => check_mul(cx, e.span, lit, right),
45 (_, &ExprKind::Unary(UnOp::Neg, lit)) => check_mul(cx, e.span, lit, left),
53 fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
55 if let ExprKind::Lit(ref l) = lit.kind;
56 if consts::lit_to_constant(&l.node, cx.typeck_results().expr_ty_opt(lit)) == Constant::Int(1);
57 if cx.typeck_results().expr_ty(exp).is_integral();
60 let mut applicability = Applicability::MachineApplicable;
61 let suggestion = format!("-{}", snippet_with_applicability(cx, exp.span, "..", &mut applicability));
66 "this multiplication by -1 can be written more succinctly",