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 clippy_utils::sugg::has_enclosing_paren;
5 use if_chain::if_chain;
6 use rustc_ast::util::parser::PREC_PREFIX;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, Expr, ExprKind, UnOp};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::source_map::Span;
13 declare_clippy_lint! {
15 /// Checks for multiplication by -1 as a form of negation.
17 /// ### Why is this bad?
18 /// It's more readable to just negate.
20 /// ### Known problems
21 /// This only catches integers (for now).
32 #[clippy::version = "pre 1.29.0"]
35 "multiplying integers by `-1`"
38 declare_lint_pass!(NegMultiply => [NEG_MULTIPLY]);
40 impl<'tcx> LateLintPass<'tcx> for NegMultiply {
41 fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) {
42 if let ExprKind::Binary(ref op, left, right) = e.kind {
43 if BinOpKind::Mul == op.node {
44 match (&left.kind, &right.kind) {
45 (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {},
46 (&ExprKind::Unary(UnOp::Neg, lit), _) => check_mul(cx, e.span, lit, right),
47 (_, &ExprKind::Unary(UnOp::Neg, lit)) => check_mul(cx, e.span, lit, left),
55 fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
57 if let ExprKind::Lit(ref l) = lit.kind;
58 if consts::lit_to_mir_constant(&l.node, cx.typeck_results().expr_ty_opt(lit)) == Constant::Int(1);
59 if cx.typeck_results().expr_ty(exp).is_integral();
62 let mut applicability = Applicability::MachineApplicable;
63 let snip = snippet_with_applicability(cx, exp.span, "..", &mut applicability);
64 let suggestion = if exp.precedence().order() < PREC_PREFIX && !has_enclosing_paren(&snip) {
65 format!("-({})", snip)
73 "this multiplication by -1 can be written more succinctly",