Skip to content

Commit b245fbd

Browse files
committed
Auto merge of #4889 - krishna-veerareddy:issue-3993-float-to-int-transmute, r=llogiq
Add lint to detect transmutes from float to integer Add lint that detects transmutation from a float to an integer and suggests usage of `{f32, f64}.to_bits()` instead. Fixes #3993 changelog: Add lint `transmute_float_to_int`
2 parents 61b19a1 + 23c03e4 commit b245fbd

File tree

7 files changed

+131
-2
lines changed

7 files changed

+131
-2
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -1214,6 +1214,7 @@ Released 2018-09-13
12141214
[`too_many_lines`]: https://rust-lang.github.io/rust-clippy/master/index.html#too_many_lines
12151215
[`toplevel_ref_arg`]: https://rust-lang.github.io/rust-clippy/master/index.html#toplevel_ref_arg
12161216
[`transmute_bytes_to_str`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_bytes_to_str
1217+
[`transmute_float_to_int`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_float_to_int
12171218
[`transmute_int_to_bool`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_int_to_bool
12181219
[`transmute_int_to_char`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_int_to_char
12191220
[`transmute_int_to_float`]: https://rust-lang.github.io/rust-clippy/master/index.html#transmute_int_to_float

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
A collection of lints to catch common mistakes and improve your [Rust](https://github.com/rust-lang/rust) code.
88

9-
[There are 339 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
9+
[There are 340 lints included in this crate!](https://rust-lang.github.io/rust-clippy/master/index.html)
1010

1111
We have a bunch of lint categories to allow you to choose how much Clippy is supposed to ~~annoy~~ help you:
1212

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,7 @@ pub fn register_plugins(store: &mut lint::LintStore, sess: &Session, conf: &Conf
735735
&trait_bounds::TYPE_REPETITION_IN_BOUNDS,
736736
&transmute::CROSSPOINTER_TRANSMUTE,
737737
&transmute::TRANSMUTE_BYTES_TO_STR,
738+
&transmute::TRANSMUTE_FLOAT_TO_INT,
738739
&transmute::TRANSMUTE_INT_TO_BOOL,
739740
&transmute::TRANSMUTE_INT_TO_CHAR,
740741
&transmute::TRANSMUTE_INT_TO_FLOAT,
@@ -1586,6 +1587,7 @@ pub fn register_plugins(store: &mut lint::LintStore, sess: &Session, conf: &Conf
15861587
LintId::of(&mutex_atomic::MUTEX_INTEGER),
15871588
LintId::of(&needless_borrow::NEEDLESS_BORROW),
15881589
LintId::of(&path_buf_push_overwrite::PATH_BUF_PUSH_OVERWRITE),
1590+
LintId::of(&transmute::TRANSMUTE_FLOAT_TO_INT),
15891591
LintId::of(&use_self::USE_SELF),
15901592
]);
15911593
}

clippy_lints/src/transmute.rs

+67
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,28 @@ declare_clippy_lint! {
190190
"transmutes from an integer to a float"
191191
}
192192

193+
declare_clippy_lint! {
194+
/// **What it does:** Checks for transmutes from a float to an integer.
195+
///
196+
/// **Why is this bad?** Transmutes are dangerous and error-prone, whereas `to_bits` is intuitive
197+
/// and safe.
198+
///
199+
/// **Known problems:** None.
200+
///
201+
/// **Example:**
202+
/// ```rust
203+
/// unsafe {
204+
/// let _: u32 = std::mem::transmute(1f32);
205+
/// }
206+
///
207+
/// // should be:
208+
/// let _: u32 = 1f32.to_bits();
209+
/// ```
210+
pub TRANSMUTE_FLOAT_TO_INT,
211+
nursery,
212+
"transmutes from a float to an integer"
213+
}
214+
193215
declare_clippy_lint! {
194216
/// **What it does:** Checks for transmutes from a pointer to a pointer, or
195217
/// from a reference to a reference.
@@ -254,6 +276,7 @@ declare_lint_pass!(Transmute => [
254276
TRANSMUTE_BYTES_TO_STR,
255277
TRANSMUTE_INT_TO_BOOL,
256278
TRANSMUTE_INT_TO_FLOAT,
279+
TRANSMUTE_FLOAT_TO_INT,
257280
UNSOUND_COLLECTION_TRANSMUTE,
258281
]);
259282

@@ -520,6 +543,50 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute {
520543
);
521544
},
522545
),
546+
(&ty::Float(float_ty), &ty::Int(_)) | (&ty::Float(float_ty), &ty::Uint(_)) => span_lint_and_then(
547+
cx,
548+
TRANSMUTE_FLOAT_TO_INT,
549+
e.span,
550+
&format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
551+
|db| {
552+
let mut expr = &args[0];
553+
let mut arg = sugg::Sugg::hir(cx, expr, "..");
554+
555+
if let ExprKind::Unary(UnOp::UnNeg, inner_expr) = &expr.kind {
556+
expr = &inner_expr;
557+
}
558+
559+
if_chain! {
560+
// if the expression is a float literal and it is unsuffixed then
561+
// add a suffix so the suggestion is valid and unambiguous
562+
let op = format!("{}{}", arg, float_ty.name_str()).into();
563+
if let ExprKind::Lit(lit) = &expr.kind;
564+
if let ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) = lit.node;
565+
then {
566+
match arg {
567+
sugg::Sugg::MaybeParen(_) => arg = sugg::Sugg::MaybeParen(op),
568+
_ => arg = sugg::Sugg::NonParen(op)
569+
}
570+
}
571+
}
572+
573+
arg = sugg::Sugg::NonParen(format!("{}.to_bits()", arg.maybe_par()).into());
574+
575+
// cast the result of `to_bits` if `to_ty` is signed
576+
arg = if let ty::Int(int_ty) = to_ty.kind {
577+
arg.as_ty(int_ty.name_str().to_string())
578+
} else {
579+
arg
580+
};
581+
582+
db.span_suggestion(
583+
e.span,
584+
"consider using",
585+
arg.to_string(),
586+
Applicability::Unspecified,
587+
);
588+
},
589+
),
523590
(&ty::Adt(ref from_adt, ref from_substs), &ty::Adt(ref to_adt, ref to_substs)) => {
524591
if from_adt.did != to_adt.did ||
525592
!COLLECTIONS.iter().any(|path| match_def_path(cx, to_adt.did, path)) {

src/lintlist/mod.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ pub use lint::Lint;
66
pub use lint::LINT_LEVELS;
77

88
// begin lint list, do not remove this comment, it’s used in `update_lints`
9-
pub const ALL_LINTS: [Lint; 339] = [
9+
pub const ALL_LINTS: [Lint; 340] = [
1010
Lint {
1111
name: "absurd_extreme_comparisons",
1212
group: "correctness",
@@ -1953,6 +1953,13 @@ pub const ALL_LINTS: [Lint; 339] = [
19531953
deprecation: None,
19541954
module: "transmute",
19551955
},
1956+
Lint {
1957+
name: "transmute_float_to_int",
1958+
group: "nursery",
1959+
desc: "transmutes from a float to an integer",
1960+
deprecation: None,
1961+
module: "transmute",
1962+
},
19561963
Lint {
19571964
name: "transmute_int_to_bool",
19581965
group: "complexity",

tests/ui/transmute_float_to_int.rs

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#[warn(clippy::transmute_float_to_int)]
2+
3+
fn float_to_int() {
4+
let _: u32 = unsafe { std::mem::transmute(1f32) };
5+
let _: i32 = unsafe { std::mem::transmute(1f32) };
6+
let _: u64 = unsafe { std::mem::transmute(1f64) };
7+
let _: i64 = unsafe { std::mem::transmute(1f64) };
8+
let _: u64 = unsafe { std::mem::transmute(1.0) };
9+
let _: u64 = unsafe { std::mem::transmute(-1.0) };
10+
}
11+
12+
fn main() {}
+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
error: transmute from a `f32` to a `u32`
2+
--> $DIR/transmute_float_to_int.rs:4:27
3+
|
4+
LL | let _: u32 = unsafe { std::mem::transmute(1f32) };
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1f32.to_bits()`
6+
|
7+
= note: `-D clippy::transmute-float-to-int` implied by `-D warnings`
8+
9+
error: transmute from a `f32` to a `i32`
10+
--> $DIR/transmute_float_to_int.rs:5:27
11+
|
12+
LL | let _: i32 = unsafe { std::mem::transmute(1f32) };
13+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1f32.to_bits() as i32`
14+
15+
error: transmute from a `f64` to a `u64`
16+
--> $DIR/transmute_float_to_int.rs:6:27
17+
|
18+
LL | let _: u64 = unsafe { std::mem::transmute(1f64) };
19+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1f64.to_bits()`
20+
21+
error: transmute from a `f64` to a `i64`
22+
--> $DIR/transmute_float_to_int.rs:7:27
23+
|
24+
LL | let _: i64 = unsafe { std::mem::transmute(1f64) };
25+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1f64.to_bits() as i64`
26+
27+
error: transmute from a `f64` to a `u64`
28+
--> $DIR/transmute_float_to_int.rs:8:27
29+
|
30+
LL | let _: u64 = unsafe { std::mem::transmute(1.0) };
31+
| ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1.0f64.to_bits()`
32+
33+
error: transmute from a `f64` to a `u64`
34+
--> $DIR/transmute_float_to_int.rs:9:27
35+
|
36+
LL | let _: u64 = unsafe { std::mem::transmute(-1.0) };
37+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `(-1.0f64).to_bits()`
38+
39+
error: aborting due to 6 previous errors
40+

0 commit comments

Comments
 (0)