Change lint type to unique and add the suggestion.

This commit is contained in:
Victor Korkin 2018-05-29 22:56:38 +07:00
parent 01be53f929
commit f6e0388e08
3 changed files with 31 additions and 6 deletions

View file

@ -673,6 +673,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
types::UNIT_ARG,
types::UNIT_CMP,
types::UNNECESSARY_CAST,
types::FN_TO_NUMERIC_CAST,
unicode::ZERO_WIDTH_SPACE,
unsafe_removed_from_name::UNSAFE_REMOVED_FROM_NAME,
unused_io_amount::UNUSED_IO_AMOUNT,

View file

@ -679,6 +679,23 @@ declare_clippy_lint! {
"cast to the same type, e.g. `x as i32` where `x: i32`"
}
/// **What it does:** Checks for casts function pointer to the numeric type.
///
/// **Why is this bad?** Cast pointer not to usize truncate value.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust
/// fn test_fn() -> i16;
/// let _ = test_fn as i32
/// ```
declare_clippy_lint! {
pub FN_TO_NUMERIC_CAST,
correctness,
"cast function pointer to the numeric type"
}
/// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
/// more-strictly-aligned pointer
///
@ -891,7 +908,8 @@ impl LintPass for CastPass {
CAST_POSSIBLE_WRAP,
CAST_LOSSLESS,
UNNECESSARY_CAST,
CAST_PTR_ALIGNMENT
CAST_PTR_ALIGNMENT,
FN_TO_NUMERIC_CAST
)
}
}
@ -980,11 +998,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
ty::TyFnDef(..) |
ty::TyFnPtr(..) => {
if cast_to.is_numeric() && cast_to.sty != ty::TyUint(UintTy::Usize){
span_lint(
span_lint_and_sugg(
cx,
UNNECESSARY_CAST,
FN_TO_NUMERIC_CAST,
expr.span,
"casting Fn not to usize may truncate the value",
&format!("casting a Fn to {} may truncate the function address value.", cast_to),
"if you need address of function, use cast to `usize` instead:",
format!("{} as usize", &snippet(cx, ex.span, "x"))
);
}
}

View file

@ -1,10 +1,14 @@
error: casting Fn not to usize may truncate the value
error: casting a Fn to i32 may truncate the function address value.
--> $DIR/types_fn_to_int.rs:8:13
|
8 | let y = x as i32;
| ^^^^^^^^
|
= note: `-D unnecessary-cast` implied by `-D warnings`
= note: #[deny(fn_to_numeric_cast)] on by default
help: if you need address of function, use cast to `usize` instead:
|
8 | let y = x as usize;
| ^^^^^^^^^^
error: aborting due to previous error