@@ -17,6 +17,7 @@ mod char_lit_as_u8;
17
17
mod fn_to_numeric_cast;
18
18
mod fn_to_numeric_cast_any;
19
19
mod fn_to_numeric_cast_with_truncation;
20
+ mod primitive_method_to_numeric_cast;
20
21
mod ptr_as_ptr;
21
22
mod ptr_cast_constness;
22
23
mod ref_as_ptr;
@@ -754,6 +755,32 @@ declare_clippy_lint! {
754
755
"detects `as *mut _` and `as *const _` conversion"
755
756
}
756
757
758
+ declare_clippy_lint ! {
759
+ /// ### What it does
760
+ /// Checks for casts of a primitive method pointer to any integer type.
761
+ ///
762
+ /// ### Why restrict this?
763
+ /// Casting a function pointer to an integer can have surprising results and can occur
764
+ /// accidentally if parentheses are omitted from a function call. If you aren't doing anything
765
+ /// low-level with function pointers then you can opt out of casting functions to integers in
766
+ /// order to avoid mistakes. Alternatively, you can use this lint to audit all uses of function
767
+ /// pointer casts in your code.
768
+ ///
769
+ /// ### Example
770
+ /// ```no_run
771
+ /// let _ = u16::max as usize;
772
+ /// ```
773
+ ///
774
+ /// Use instead:
775
+ /// ```no_run
776
+ /// let _ = u16::MAX as usize;
777
+ /// ```
778
+ #[ clippy:: version = "1.86.0" ]
779
+ pub PRIMITIVE_METHOD_TO_NUMERIC_CAST ,
780
+ suspicious,
781
+ "casting a primitive method pointer to any integer type"
782
+ }
783
+
757
784
pub struct Casts {
758
785
msrv : Msrv ,
759
786
}
@@ -792,6 +819,7 @@ impl_lint_pass!(Casts => [
792
819
ZERO_PTR ,
793
820
REF_AS_PTR ,
794
821
AS_POINTER_UNDERSCORE ,
822
+ PRIMITIVE_METHOD_TO_NUMERIC_CAST ,
795
823
] ) ;
796
824
797
825
impl < ' tcx > LateLintPass < ' tcx > for Casts {
@@ -816,6 +844,7 @@ impl<'tcx> LateLintPass<'tcx> for Casts {
816
844
ptr_cast_constness:: check ( cx, expr, cast_from_expr, cast_from, cast_to, & self . msrv ) ;
817
845
as_ptr_cast_mut:: check ( cx, expr, cast_from_expr, cast_to) ;
818
846
fn_to_numeric_cast_any:: check ( cx, expr, cast_from_expr, cast_from, cast_to) ;
847
+ primitive_method_to_numeric_cast:: check ( cx, expr, cast_from_expr, cast_from, cast_to) ;
819
848
fn_to_numeric_cast:: check ( cx, expr, cast_from_expr, cast_from, cast_to) ;
820
849
fn_to_numeric_cast_with_truncation:: check ( cx, expr, cast_from_expr, cast_from, cast_to) ;
821
850
zero_ptr:: check ( cx, expr, cast_from_expr, cast_to_hir) ;
0 commit comments