let unnecessary_cast work for trivial non_literal expressions

Signed-off-by: TennyZhuang <zty0826@gmail.com>
This commit is contained in:
TennyZhuang 2022-10-02 17:12:08 +08:00
parent ac12011315
commit 081f73954b
4 changed files with 37 additions and 2 deletions

View File

@ -31,8 +31,10 @@ pub(super) fn check<'tcx>(
}
}
let cast_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();
if let Some(lit) = get_numeric_literal(cast_expr) {
let literal_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();
let literal_str = cast_str;
if_chain! {
if let LitKind::Int(n, _) = lit.node;
@ -81,6 +83,17 @@ pub(super) fn check<'tcx>(
}
},
}
} else if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
span_lint_and_sugg(
cx,
UNNECESSARY_CAST,
expr.span,
&format!("casting to the same type is unnecessary (`{cast_from}` -> `{cast_to}`)"),
"try",
cast_str,
Applicability::MachineApplicable,
);
return true;
}
false

View File

@ -103,4 +103,12 @@ mod fixable {
#[allow(clippy::precedence)]
let _: f64 = -8.0_f64.exp(); // should suggest `-8.0_f64.exp()` here not to change code behavior
}
fn issue_9562_non_literal() {
fn foo() -> f32 {
0.
}
let _num = foo();
}
}

View File

@ -103,4 +103,12 @@ fn issue_9563() {
#[allow(clippy::precedence)]
let _: f64 = -(8.0 as f64).exp(); // should suggest `-8.0_f64.exp()` here not to change code behavior
}
fn issue_9562_non_literal() {
fn foo() -> f32 {
0.
}
let _num = foo() as f32;
}
}

View File

@ -174,5 +174,11 @@ error: casting float literal to `f64` is unnecessary
LL | let _: f64 = -(8.0 as f64).exp(); // should suggest `-8.0_f64.exp()` here not to change code behavior
| ^^^^^^^^^^^^ help: try: `8.0_f64`
error: aborting due to 29 previous errors
error: casting to the same type is unnecessary (`f32` -> `f32`)
--> $DIR/unnecessary_cast.rs:112:20
|
LL | let _num = foo() as f32;
| ^^^^^^^^^^^^ help: try: `foo()`
error: aborting due to 30 previous errors