Skip to content

Commit afb14d5

Browse files
committed
add suggestion for neg_multiply lint
1 parent 25e90ec commit afb14d5

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

clippy_lints/src/neg_multiply.rs

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use clippy_utils::consts::{self, Constant};
2-
use clippy_utils::diagnostics::span_lint;
2+
use clippy_utils::diagnostics::span_lint_and_sugg;
33
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};
56
use rustc_lint::{LateContext, LateLintPass};
67
use rustc_session::{declare_lint_pass, declare_tool_lint};
78
use 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
}

tests/ui/neg_multiply.stderr

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
error: negation by multiplying with `-1`
1+
error: this `multiplication with -1` can be written more succinctly
22
--> $DIR/neg_multiply.rs:27:5
33
|
44
LL | x * -1;
5-
| ^^^^^^
5+
| ^^^^^^ help: consider using: `-x`
66
|
77
= note: `-D clippy::neg-multiply` implied by `-D warnings`
88

9-
error: negation by multiplying with `-1`
9+
error: this `multiplication with -1` can be written more succinctly
1010
--> $DIR/neg_multiply.rs:29:5
1111
|
1212
LL | -1 * x;
13-
| ^^^^^^
13+
| ^^^^^^ help: consider using: `-x`
1414

1515
error: aborting due to 2 previous errors
1616

0 commit comments

Comments
 (0)