Skip to content

Commit 15b68c2

Browse files
committed
Extract the logic for if a snippet equals a type
1 parent dcfc6a2 commit 15b68c2

File tree

2 files changed

+18
-15
lines changed

2 files changed

+18
-15
lines changed

clippy_lints/src/casts/mod.rs

+8
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,14 @@ declare_clippy_lint! {
181181
/// ### Why is this bad?
182182
/// It's just unnecessary.
183183
///
184+
/// ### Known problems
185+
/// When the expression on the left is a function call, the lint considers the return type to be
186+
/// a type alias if it's aliased through a `use` statement
187+
/// (like `use std::io::Result as IoResult`). It will not lint such cases.
188+
///
189+
/// This check is also rather primitive. It will only work on primitive types without any
190+
/// intermediate references, raw pointers and trait objects may or may not work.
191+
///
184192
/// ### Example
185193
/// ```rust
186194
/// let _ = 2i32 as i32;

clippy_lints/src/casts/unnecessary_cast.rs

+10-15
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,6 @@ pub(super) fn check<'tcx>(
8585
}
8686
}
8787

88-
// skip cast of fn call that returns type alias
89-
if let ExprKind::Cast(inner, ..) = expr.kind && is_cast_from_ty_alias(cx, inner, cast_from) {
90-
return false;
91-
}
92-
9388
// skip cast to non-primitive type
9489
if_chain! {
9590
if let ExprKind::Cast(_, cast_to) = expr.kind;
@@ -101,6 +96,11 @@ pub(super) fn check<'tcx>(
10196
}
10297
}
10398

99+
// skip cast of fn call that returns type alias
100+
if let ExprKind::Cast(inner, ..) = expr.kind && is_cast_from_ty_alias(cx, inner, cast_from) {
101+
return false;
102+
}
103+
104104
if let Some(lit) = get_numeric_literal(cast_expr) {
105105
let literal_str = &cast_str;
106106

@@ -259,16 +259,7 @@ fn is_cast_from_ty_alias<'tcx>(cx: &LateContext<'tcx>, expr: impl Visitable<'tcx
259259
if !snippet
260260
.split("->")
261261
.skip(1)
262-
.map(|s| {
263-
s.trim() == cast_from.to_string()
264-
|| s.trim().contains(&format!("::{cast_from}"))
265-
|| s.split("where").any(|ty| {
266-
ty.trim() == cast_from.to_string()
267-
|| ty.trim() == cast_from.to_string()
268-
// Fully qualified path, or something silly like `::u32`
269-
|| s.trim().contains(&format!("::{cast_from}"))
270-
})
271-
})
262+
.map(|s| snippet_eq_ty(s, cast_from) || s.split("where").any(|ty| snippet_eq_ty(ty, cast_from)))
272263
.any(|a| a)
273264
{
274265
return ControlFlow::Break(());
@@ -295,3 +286,7 @@ fn is_cast_from_ty_alias<'tcx>(cx: &LateContext<'tcx>, expr: impl Visitable<'tcx
295286
})
296287
.is_some()
297288
}
289+
290+
fn snippet_eq_ty(snippet: &str, ty: Ty<'_>) -> bool {
291+
snippet.trim() == ty.to_string() || snippet.trim().contains(&format!("::{ty}"))
292+
}

0 commit comments

Comments
 (0)