From cf8f3796578b5423d9465ff0d1e8327668753cca Mon Sep 17 00:00:00 2001 From: Victor Korkin Date: Mon, 28 May 2018 23:31:55 +0700 Subject: [PATCH] Add lint on cast Fn to numerical. --- clippy_lints/src/types.rs | 16 ++++++++++++++++ tests/ui/types_fn_to_int.rs | 10 ++++++++++ tests/ui/types_fn_to_int.stderr | 10 ++++++++++ 3 files changed, 36 insertions(+) create mode 100644 tests/ui/types_fn_to_int.rs create mode 100644 tests/ui/types_fn_to_int.stderr diff --git a/clippy_lints/src/types.rs b/clippy_lints/src/types.rs index 168086d574a..f5cbcfb6b00 100644 --- a/clippy_lints/src/types.rs +++ b/clippy_lints/src/types.rs @@ -975,6 +975,22 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass { }, } } + + match &cast_from.sty { + ty::TyFnDef(..) | + ty::TyFnPtr(..) => { + if cast_to.is_numeric() && cast_to.sty != ty::TyUint(UintTy::Usize){ + span_lint( + cx, + UNNECESSARY_CAST, + expr.span, + "casting Fn not to usize may truncate the value", + ); + } + } + _ => () + } + if_chain!{ if let ty::TyRawPtr(from_ptr_ty) = &cast_from.sty; if let ty::TyRawPtr(to_ptr_ty) = &cast_to.sty; diff --git a/tests/ui/types_fn_to_int.rs b/tests/ui/types_fn_to_int.rs new file mode 100644 index 00000000000..250307e54b7 --- /dev/null +++ b/tests/ui/types_fn_to_int.rs @@ -0,0 +1,10 @@ +#![feature(tool_attributes)] +enum Foo { + A(usize), + B +} + +fn main() { + let x = Foo::A; + let y = x as i32; +} diff --git a/tests/ui/types_fn_to_int.stderr b/tests/ui/types_fn_to_int.stderr new file mode 100644 index 00000000000..dffcf008302 --- /dev/null +++ b/tests/ui/types_fn_to_int.stderr @@ -0,0 +1,10 @@ +error: casting Fn not to usize may truncate the value + --> $DIR/types_fn_to_int.rs:9:13 + | +9 | let y = x as i32; + | ^^^^^^^^ + | + = note: `-D unnecessary-cast` implied by `-D warnings` + +error: aborting due to previous error +