1
1
use clippy_utils:: consts:: { self , Constant } ;
2
- use clippy_utils:: diagnostics:: span_lint ;
2
+ use clippy_utils:: diagnostics:: span_lint_and_sugg ;
3
3
use 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 } ;
5
6
use rustc_lint:: { LateContext , LateLintPass } ;
6
7
use rustc_session:: { declare_lint_pass, declare_tool_lint} ;
7
8
use rustc_span:: source_map:: Span ;
@@ -18,7 +19,11 @@ declare_clippy_lint! {
18
19
///
19
20
/// ### Example
20
21
/// ```ignore
21
- /// x * -1
22
+ /// // Bad
23
+ /// let a = x * -1;
24
+ ///
25
+ /// // Good
26
+ /// let b = -x;
22
27
/// ```
23
28
#[ clippy:: version = "pre 1.29.0" ]
24
29
pub NEG_MULTIPLY ,
@@ -49,8 +54,21 @@ fn check_mul(cx: &LateContext<'_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) {
49
54
if let ExprKind :: Lit ( ref l) = lit. kind;
50
55
if consts:: lit_to_constant( & l. node, cx. typeck_results( ) . expr_ty_opt( lit) ) == Constant :: Int ( 1 ) ;
51
56
if cx. typeck_results( ) . expr_ty( exp) . is_integral( ) ;
57
+ if let ExprKind :: Path ( QPath :: Resolved ( _, var_path) ) = exp. kind;
58
+
52
59
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
+ ) ;
54
72
}
55
73
}
56
74
}
0 commit comments