11use clippy_utils:: consts:: { self , Constant } ;
2- use clippy_utils:: diagnostics:: span_lint ;
2+ use clippy_utils:: diagnostics:: span_lint_and_sugg ;
33use if_chain:: if_chain;
4- use rustc_hir:: { BinOpKind , Expr , ExprKind , UnOp } ;
4+ use rustc_errors:: Applicability ;
5+ use rustc_hir:: { BinOpKind , Expr , ExprKind , QPath , UnOp } ;
56use rustc_lint:: { LateContext , LateLintPass } ;
67use rustc_session:: { declare_lint_pass, declare_tool_lint} ;
78use rustc_span:: source_map:: Span ;
@@ -18,7 +19,11 @@ declare_clippy_lint! {
1819 ///
1920 /// ### Example
2021 /// ```ignore
21- /// x * -1
22+ /// // Bad
23+ /// let a = x * -1;
24+ ///
25+ /// // Good
26+ /// let b = -x;
2227 /// ```
2328 #[ clippy:: version = "pre 1.29.0" ]
2429 pub NEG_MULTIPLY ,
@@ -49,8 +54,21 @@ fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
4954 if let ExprKind :: Lit ( ref l) = lit. kind;
5055 if consts:: lit_to_constant( & l. node, cx. typeck_results( ) . expr_ty_opt( lit) ) == Constant :: Int ( 1 ) ;
5156 if cx. typeck_results( ) . expr_ty( exp) . is_integral( ) ;
57+ if let ExprKind :: Path ( QPath :: Resolved ( _, var_path) ) = exp. kind;
58+
5259 then {
53- span_lint( cx, NEG_MULTIPLY , span, "negation by multiplying with `-1`" ) ;
60+ let var_name = var_path. segments[ 0 ] . ident. name. as_str( ) ;
61+ let suggestion = format!( "-{var}" , var=var_name) ;
62+ let applicability = Applicability :: MachineApplicable ;
63+ span_lint_and_sugg(
64+ cx,
65+ NEG_MULTIPLY ,
66+ span,
67+ "this `multiplication with -1` can be written more succinctly" ,
68+ "consider using" ,
69+ suggestion,
70+ applicability,
71+ ) ;
5472 }
5573 }
5674}
0 commit comments