Auto merge of #10971 - Centri3:unnecessary_cast_fully_qual_fix, r=dswij
Check for fully qualified paths in `unnecessary_cast` Noticed this doesn't pick up `::std::primitive::u32` or the sort, now it does changelog: none
This commit is contained in:
commit
fbe292e563
5 changed files with 104 additions and 48 deletions
|
|
@ -181,6 +181,14 @@ declare_clippy_lint! {
|
|||
/// ### Why is this bad?
|
||||
/// It's just unnecessary.
|
||||
///
|
||||
/// ### Known problems
|
||||
/// When the expression on the left is a function call, the lint considers the return type to be
|
||||
/// a type alias if it's aliased through a `use` statement
|
||||
/// (like `use std::io::Result as IoResult`). It will not lint such cases.
|
||||
///
|
||||
/// This check is also rather primitive. It will only work on primitive types without any
|
||||
/// intermediate references, raw pointers and trait objects may or may not work.
|
||||
///
|
||||
/// ### Example
|
||||
/// ```rust
|
||||
/// let _ = 2i32 as i32;
|
||||
|
|
|
|||
|
|
@ -85,11 +85,6 @@ pub(super) fn check<'tcx>(
|
|||
}
|
||||
}
|
||||
|
||||
// skip cast of fn call that returns type alias
|
||||
if let ExprKind::Cast(inner, ..) = expr.kind && is_cast_from_ty_alias(cx, inner, cast_from) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// skip cast to non-primitive type
|
||||
if_chain! {
|
||||
if let ExprKind::Cast(_, cast_to) = expr.kind;
|
||||
|
|
@ -101,6 +96,11 @@ pub(super) fn check<'tcx>(
|
|||
}
|
||||
}
|
||||
|
||||
// skip cast of fn call that returns type alias
|
||||
if let ExprKind::Cast(inner, ..) = expr.kind && is_cast_from_ty_alias(cx, inner, cast_from) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if let Some(lit) = get_numeric_literal(cast_expr) {
|
||||
let literal_str = &cast_str;
|
||||
|
||||
|
|
@ -254,14 +254,12 @@ fn is_cast_from_ty_alias<'tcx>(cx: &LateContext<'tcx>, expr: impl Visitable<'tcx
|
|||
// function's declaration snippet is exactly equal to the `Ty`. That way, we can
|
||||
// see whether it's a type alias.
|
||||
//
|
||||
// Will this work for more complex types? Probably not!
|
||||
// FIXME: This won't work if the type is given an alias through `use`, should we
|
||||
// consider this a type alias as well?
|
||||
if !snippet
|
||||
.split("->")
|
||||
.skip(1)
|
||||
.map(|s| {
|
||||
s.trim() == cast_from.to_string()
|
||||
|| s.split("where").any(|ty| ty.trim() == cast_from.to_string())
|
||||
})
|
||||
.map(|s| snippet_eq_ty(s, cast_from) || s.split("where").any(|ty| snippet_eq_ty(ty, cast_from)))
|
||||
.any(|a| a)
|
||||
{
|
||||
return ControlFlow::Break(());
|
||||
|
|
@ -288,3 +286,7 @@ fn is_cast_from_ty_alias<'tcx>(cx: &LateContext<'tcx>, expr: impl Visitable<'tcx
|
|||
})
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn snippet_eq_ty(snippet: &str, ty: Ty<'_>) -> bool {
|
||||
snippet.trim() == ty.to_string() || snippet.trim().contains(&format!("::{ty}"))
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue