Skip to content

Commit be40534

Browse files
Add primitive_method_to_numeric_cast lint
1 parent 7fdded3 commit be40534

File tree

4 files changed

+88
-0
lines changed

4 files changed

+88
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6068,6 +6068,7 @@ Released 2018-09-13
60686068
[`possible_missing_comma`]: https://rust-lang.github.io/rust-clippy/master/index.html#possible_missing_comma
60696069
[`precedence`]: https://rust-lang.github.io/rust-clippy/master/index.html#precedence
60706070
[`precedence_bits`]: https://rust-lang.github.io/rust-clippy/master/index.html#precedence_bits
6071+
[`primitive_method_to_numeric_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#primitive_method_to_numeric_cast
60716072
[`print_in_format_impl`]: https://rust-lang.github.io/rust-clippy/master/index.html#print_in_format_impl
60726073
[`print_literal`]: https://rust-lang.github.io/rust-clippy/master/index.html#print_literal
60736074
[`print_stderr`]: https://rust-lang.github.io/rust-clippy/master/index.html#print_stderr

clippy_lints/src/casts/mod.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ mod fn_to_numeric_cast;
1818
mod fn_to_numeric_cast_any;
1919
mod fn_to_numeric_cast_with_truncation;
2020
mod manual_dangling_ptr;
21+
mod primitive_method_to_numeric_cast;
2122
mod ptr_as_ptr;
2223
mod ptr_cast_constness;
2324
mod ref_as_ptr;
@@ -786,6 +787,32 @@ declare_clippy_lint! {
786787
"casting small constant literals to pointers to create dangling pointers"
787788
}
788789

790+
declare_clippy_lint! {
791+
/// ### What it does
792+
/// Checks for casts of a primitive method pointer to any integer type.
793+
///
794+
/// ### Why restrict this?
795+
/// Casting a function pointer to an integer can have surprising results and can occur
796+
/// accidentally if parentheses are omitted from a function call. If you aren't doing anything
797+
/// low-level with function pointers then you can opt out of casting functions to integers in
798+
/// order to avoid mistakes. Alternatively, you can use this lint to audit all uses of function
799+
/// pointer casts in your code.
800+
///
801+
/// ### Example
802+
/// ```no_run
803+
/// let _ = u16::max as usize;
804+
/// ```
805+
///
806+
/// Use instead:
807+
/// ```no_run
808+
/// let _ = u16::MAX as usize;
809+
/// ```
810+
#[clippy::version = "1.86.0"]
811+
pub PRIMITIVE_METHOD_TO_NUMERIC_CAST,
812+
suspicious,
813+
"casting a primitive method pointer to any integer type"
814+
}
815+
789816
pub struct Casts {
790817
msrv: Msrv,
791818
}
@@ -823,6 +850,7 @@ impl_lint_pass!(Casts => [
823850
REF_AS_PTR,
824851
AS_POINTER_UNDERSCORE,
825852
MANUAL_DANGLING_PTR,
853+
PRIMITIVE_METHOD_TO_NUMERIC_CAST,
826854
]);
827855

828856
impl<'tcx> LateLintPass<'tcx> for Casts {
@@ -847,6 +875,7 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
847875
ptr_cast_constness::check(cx, expr, cast_from_expr, cast_from, cast_to, self.msrv);
848876
as_ptr_cast_mut::check(cx, expr, cast_from_expr, cast_to);
849877
fn_to_numeric_cast_any::check(cx, expr, cast_from_expr, cast_from, cast_to);
878+
primitive_method_to_numeric_cast::check(cx, expr, cast_from_expr, cast_from, cast_to);
850879
fn_to_numeric_cast::check(cx, expr, cast_from_expr, cast_from, cast_to);
851880
fn_to_numeric_cast_with_truncation::check(cx, expr, cast_from_expr, cast_from, cast_to);
852881
zero_ptr::check(cx, expr, cast_from_expr, cast_to_hir);
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
use clippy_utils::diagnostics::span_lint_and_then;
2+
use clippy_utils::match_def_path;
3+
use clippy_utils::source::snippet_with_applicability;
4+
use rustc_errors::Applicability;
5+
use rustc_hir::Expr;
6+
use rustc_lint::LateContext;
7+
use rustc_middle::ty::{self, Ty};
8+
9+
use super::PRIMITIVE_METHOD_TO_NUMERIC_CAST;
10+
11+
fn get_primitive_ty_name(ty: Ty<'_>) -> Option<&'static str> {
12+
match ty.kind() {
13+
ty::Char => Some("char"),
14+
ty::Int(int) => Some(int.name_str()),
15+
ty::Uint(uint) => Some(uint.name_str()),
16+
ty::Float(float) => Some(float.name_str()),
17+
_ => None,
18+
}
19+
}
20+
21+
pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
22+
// We allow casts from any function type to any function type.
23+
match cast_to.kind() {
24+
ty::FnDef(..) | ty::FnPtr(..) => return,
25+
_ => { /* continue to checks */ },
26+
}
27+
28+
if let ty::FnDef(def_id, generics) = cast_from.kind()
29+
&& let Some(method_name) = cx.tcx.opt_item_name(*def_id)
30+
&& let method_name = method_name.as_str()
31+
&& (method_name == "min" || method_name == "max")
32+
// We get the type on which the `min`/`max` method of the `Ord` trait is implemented.
33+
&& let [ty] = generics.as_slice()
34+
&& let Some(ty) = ty.as_type()
35+
// We get its name in case it's a primitive with an associated MIN/MAX constant.
36+
&& let Some(ty_name) = get_primitive_ty_name(ty)
37+
&& match_def_path(cx, *def_id, &["core", "cmp", "Ord", method_name])
38+
{
39+
let mut applicability = Applicability::MaybeIncorrect;
40+
let from_snippet = snippet_with_applicability(cx, cast_expr.span, "..", &mut applicability);
41+
42+
span_lint_and_then(
43+
cx,
44+
PRIMITIVE_METHOD_TO_NUMERIC_CAST,
45+
expr.span,
46+
format!("casting function pointer `{from_snippet}` to `{cast_to}`"),
47+
|diag| {
48+
diag.span_suggestion_verbose(
49+
expr.span,
50+
"did you mean to use the associated constant?",
51+
format!("{ty_name}::{} as {cast_to}", method_name.to_ascii_uppercase()),
52+
applicability,
53+
);
54+
},
55+
);
56+
}
57+
}

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ pub static LINTS: &[&crate::LintInfo] = &[
6868
crate::casts::FN_TO_NUMERIC_CAST_ANY_INFO,
6969
crate::casts::FN_TO_NUMERIC_CAST_WITH_TRUNCATION_INFO,
7070
crate::casts::MANUAL_DANGLING_PTR_INFO,
71+
crate::casts::PRIMITIVE_METHOD_TO_NUMERIC_CAST_INFO,
7172
crate::casts::PTR_AS_PTR_INFO,
7273
crate::casts::PTR_CAST_CONSTNESS_INFO,
7374
crate::casts::REF_AS_PTR_INFO,

0 commit comments

Comments
 (0)