Skip to content

Commit 081f739

Browse files
committed
let unnecessary_cast work for trivial non_literal expressions
Signed-off-by: TennyZhuang <[email protected]>
1 parent ac12011 commit 081f739

File tree

4 files changed

+37
-2
lines changed

4 files changed

+37
-2
lines changed

clippy_lints/src/casts/unnecessary_cast.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,10 @@ pub(super) fn check<'tcx>(
3131
}
3232
}
3333

34+
let cast_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();
35+
3436
if let Some(lit) = get_numeric_literal(cast_expr) {
35-
let literal_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();
37+
let literal_str = cast_str;
3638

3739
if_chain! {
3840
if let LitKind::Int(n, _) = lit.node;
@@ -81,6 +83,17 @@ pub(super) fn check<'tcx>(
8183
}
8284
},
8385
}
86+
} else if cast_from.kind() == cast_to.kind() && !in_external_macro(cx.sess(), expr.span) {
87+
span_lint_and_sugg(
88+
cx,
89+
UNNECESSARY_CAST,
90+
expr.span,
91+
&format!("casting to the same type is unnecessary (`{cast_from}` -> `{cast_to}`)"),
92+
"try",
93+
cast_str,
94+
Applicability::MachineApplicable,
95+
);
96+
return true;
8497
}
8598

8699
false

tests/ui/unnecessary_cast.fixed

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,4 +103,12 @@ mod fixable {
103103
#[allow(clippy::precedence)]
104104
let _: f64 = -8.0_f64.exp(); // should suggest `-8.0_f64.exp()` here not to change code behavior
105105
}
106+
107+
fn issue_9562_non_literal() {
108+
fn foo() -> f32 {
109+
0.
110+
}
111+
112+
let _num = foo();
113+
}
106114
}

tests/ui/unnecessary_cast.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,4 +103,12 @@ mod fixable {
103103
#[allow(clippy::precedence)]
104104
let _: f64 = -(8.0 as f64).exp(); // should suggest `-8.0_f64.exp()` here not to change code behavior
105105
}
106+
107+
fn issue_9562_non_literal() {
108+
fn foo() -> f32 {
109+
0.
110+
}
111+
112+
let _num = foo() as f32;
113+
}
106114
}

tests/ui/unnecessary_cast.stderr

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,5 +174,11 @@ error: casting float literal to `f64` is unnecessary
174174
LL | let _: f64 = -(8.0 as f64).exp(); // should suggest `-8.0_f64.exp()` here not to change code behavior
175175
| ^^^^^^^^^^^^ help: try: `8.0_f64`
176176

177-
error: aborting due to 29 previous errors
177+
error: casting to the same type is unnecessary (`f32` -> `f32`)
178+
--> $DIR/unnecessary_cast.rs:112:20
179+
|
180+
LL | let _num = foo() as f32;
181+
| ^^^^^^^^^^^^ help: try: `foo()`
182+
183+
error: aborting due to 30 previous errors
178184

0 commit comments

Comments
 (0)