Skip to content

Commit

Permalink
Auto merge of rust-lang#8596 - Jaic1:unnecessary_cast, r=flip1995
Browse files Browse the repository at this point in the history
Fix unnecessary_cast suggestion for type aliasses

Fix rust-lang#6923. The [`unnecessary_cast`] lint now will skip casting to non-primitive type.

changelog: fix lint [`unnecessary_cast `]
  • Loading branch information
bors committed Apr 6, 2022
2 parents 41f2ecc + ec851b8 commit 880ff24
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
14 changes: 13 additions & 1 deletion clippy_lints/src/casts/unnecessary_cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use clippy_utils::source::snippet_opt;
use if_chain::if_chain;
use rustc_ast::{LitFloatType, LitIntType, LitKind};
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind, Lit, UnOp};
use rustc_hir::def::Res;
use rustc_hir::{Expr, ExprKind, Lit, QPath, TyKind, UnOp};
use rustc_lint::{LateContext, LintContext};
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::{self, FloatTy, InferTy, Ty};
Expand All @@ -18,6 +19,17 @@ pub(super) fn check(
cast_from: Ty<'_>,
cast_to: Ty<'_>,
) -> bool {
// skip non-primitive type cast
if_chain! {
if let ExprKind::Cast(_, cast_to) = expr.kind;
if let TyKind::Path(QPath::Resolved(_, path)) = &cast_to.kind;
if let Res::PrimTy(_) = path.res;
then {}
else {
return false
}
}

if let Some(lit) = get_numeric_literal(cast_expr) {
let literal_str = snippet_opt(cx, cast_expr.span).unwrap_or_default();

Expand Down
6 changes: 6 additions & 0 deletions tests/ui/unnecessary_cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,10 @@ fn main() {

// do not lint cast to cfg-dependant type
1 as std::os::raw::c_char;

// do not lint cast to alias type
1 as I32Alias;
&1 as &I32Alias;
}

type I32Alias = i32;
5 changes: 5 additions & 0 deletions tests/ui/unnecessary_cast_fixable.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,9 @@ fn main() {

let _ = -1_i32;
let _ = -1.0_f32;

let _ = 1 as I32Alias;
let _ = &1 as &I32Alias;
}

type I32Alias = i32;
5 changes: 5 additions & 0 deletions tests/ui/unnecessary_cast_fixable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,9 @@ fn main() {

let _ = -1 as i32;
let _ = -1.0 as f32;

let _ = 1 as I32Alias;
let _ = &1 as &I32Alias;
}

type I32Alias = i32;

0 comments on commit 880ff24

Please sign in to comment.