Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 458f6d1

Browse files
committed
Move fn_to_numeric_cast to its own module
1 parent 0dce992 commit 458f6d1

File tree

2 files changed

+40
-10
lines changed

2 files changed

+40
-10
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
use rustc_errors::Applicability;
2+
use rustc_hir::Expr;
3+
use rustc_lint::LateContext;
4+
use rustc_middle::ty::{self, Ty, UintTy};
5+
6+
use crate::utils::{snippet_with_applicability, span_lint_and_sugg};
7+
8+
use super::{utils, FN_TO_NUMERIC_CAST};
9+
10+
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
11+
// We only want to check casts to `ty::Uint` or `ty::Int`
12+
match cast_to.kind() {
13+
ty::Uint(_) | ty::Int(..) => { /* continue on */ },
14+
_ => return,
15+
}
16+
17+
match cast_from.kind() {
18+
ty::FnDef(..) | ty::FnPtr(_) => {
19+
let mut applicability = Applicability::MaybeIncorrect;
20+
let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
21+
let to_nbits = utils::int_ty_to_nbits(cast_to, cx.tcx);
22+
23+
if (to_nbits >= cx.tcx.data_layout.pointer_size.bits()) && (*cast_to.kind() != ty::Uint(UintTy::Usize)) {
24+
span_lint_and_sugg(
25+
cx,
26+
FN_TO_NUMERIC_CAST,
27+
expr.span,
28+
&format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
29+
"try",
30+
format!("{} as usize", from_snippet),
31+
applicability,
32+
);
33+
}
34+
},
35+
_ => {},
36+
}
37+
}

clippy_lints/src/casts/mod.rs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ mod cast_possible_truncation;
33
mod cast_possible_wrap;
44
mod cast_precision_loss;
55
mod cast_sign_loss;
6+
mod fn_to_numeric_cast;
67
mod unnecessary_cast;
78
mod utils;
89

@@ -301,6 +302,8 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
301302
if unnecessary_cast::check(cx, expr, cast_expr, cast_from, cast_to) {
302303
return;
303304
}
305+
306+
fn_to_numeric_cast::check(cx, expr, cast_expr, cast_from, cast_to);
304307
lint_fn_to_numeric_cast(cx, expr, cast_expr, cast_from, cast_to);
305308
lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
306309
if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
@@ -386,16 +389,6 @@ fn lint_fn_to_numeric_cast(
386389
format!("{} as usize", from_snippet),
387390
applicability,
388391
);
389-
} else if *cast_to.kind() != ty::Uint(UintTy::Usize) {
390-
span_lint_and_sugg(
391-
cx,
392-
FN_TO_NUMERIC_CAST,
393-
expr.span,
394-
&format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
395-
"try",
396-
format!("{} as usize", from_snippet),
397-
applicability,
398-
);
399392
}
400393
},
401394
_ => {},

0 commit comments

Comments
 (0)