Skip to content

Commit 880ff24

Browse files
committed
Auto merge of #8596 - Jaic1:unnecessary_cast, r=flip1995
Fix unnecessary_cast suggestion for type aliasses Fix #6923. The [`unnecessary_cast`] lint now will skip casting to non-primitive type. changelog: fix lint [`unnecessary_cast `]
2 parents 41f2ecc + ec851b8 commit 880ff24

File tree

4 files changed

+29
-1
lines changed

4 files changed

+29
-1
lines changed

clippy_lints/src/casts/unnecessary_cast.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ use clippy_utils::source::snippet_opt;
44
use if_chain::if_chain;
55
use rustc_ast::{LitFloatType, LitIntType, LitKind};
66
use rustc_errors::Applicability;
7-
use rustc_hir::{Expr, ExprKind, Lit, UnOp};
7+
use rustc_hir::def::Res;
8+
use rustc_hir::{Expr, ExprKind, Lit, QPath, TyKind, UnOp};
89
use rustc_lint::{LateContext, LintContext};
910
use rustc_middle::lint::in_external_macro;
1011
use rustc_middle::ty::{self, FloatTy, InferTy, Ty};
@@ -18,6 +19,17 @@ pub(super) fn check(
1819
cast_from: Ty<'_>,
1920
cast_to: Ty<'_>,
2021
) -> bool {
22+
// skip non-primitive type cast
23+
if_chain! {
24+
if let ExprKind::Cast(_, cast_to) = expr.kind;
25+
if let TyKind::Path(QPath::Resolved(_, path)) = &cast_to.kind;
26+
if let Res::PrimTy(_) = path.res;
27+
then {}
28+
else {
29+
return false
30+
}
31+
}
32+
2133
if let Some(lit) = get_numeric_literal(cast_expr) {
2234
let literal_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();
2335

tests/ui/unnecessary_cast.rs

+6
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,10 @@ fn main() {
3030

3131
// do not lint cast to cfg-dependant type
3232
1 as std::os::raw::c_char;
33+
34+
// do not lint cast to alias type
35+
1 as I32Alias;
36+
&1 as &I32Alias;
3337
}
38+
39+
type I32Alias = i32;

tests/ui/unnecessary_cast_fixable.fixed

+5
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,9 @@ fn main() {
4242

4343
let _ = -1_i32;
4444
let _ = -1.0_f32;
45+
46+
let _ = 1 as I32Alias;
47+
let _ = &1 as &I32Alias;
4548
}
49+
50+
type I32Alias = i32;

tests/ui/unnecessary_cast_fixable.rs

+5
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,9 @@ fn main() {
4242

4343
let _ = -1 as i32;
4444
let _ = -1.0 as f32;
45+
46+
let _ = 1 as I32Alias;
47+
let _ = &1 as &I32Alias;
4548
}
49+
50+
type I32Alias = i32;

0 commit comments

Comments
 (0)