Skip to content

Commit c77fc06

Browse files
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.
1 parent 61b19a1 commit c77fc06

File tree

7 files changed

+136
-11
lines changed

7 files changed

+136
-11
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.rs

+10
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,16 @@ fn int_to_float() {
126126
let _: f32 = unsafe { std::mem::transmute(0_i32) };
127127
}
128128

129+
#[warn(clippy::transmute_float_to_int)]
130+
fn float_to_int() {
131+
let _: u32 = unsafe { std::mem::transmute(1f32) };
132+
let _: i32 = unsafe { std::mem::transmute(1f32) };
133+
let _: u64 = unsafe { std::mem::transmute(1f64) };
134+
let _: i64 = unsafe { std::mem::transmute(1f64) };
135+
let _: u64 = unsafe { std::mem::transmute(1.0) };
136+
let _: u64 = unsafe { std::mem::transmute(-1.0) };
137+
}
138+
129139
fn bytes_to_str(b: &[u8], mb: &mut [u8]) {
130140
let _: &str = unsafe { std::mem::transmute(b) };
131141
let _: &mut str = unsafe { std::mem::transmute(mb) };

tests/ui/transmute.stderr

+47-9
Original file line numberDiff line numberDiff line change
@@ -190,57 +190,95 @@ error: transmute from a `i32` to a `f32`
190190
LL | let _: f32 = unsafe { std::mem::transmute(0_i32) };
191191
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `f32::from_bits(0_i32 as u32)`
192192

193+
error: transmute from a `f32` to a `u32`
194+
--> $DIR/transmute.rs:131:27
195+
|
196+
LL | let _: u32 = unsafe { std::mem::transmute(1f32) };
197+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1f32.to_bits()`
198+
|
199+
= note: `-D clippy::transmute-float-to-int` implied by `-D warnings`
200+
201+
error: transmute from a `f32` to a `i32`
202+
--> $DIR/transmute.rs:132:27
203+
|
204+
LL | let _: i32 = unsafe { std::mem::transmute(1f32) };
205+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1f32.to_bits() as i32`
206+
207+
error: transmute from a `f64` to a `u64`
208+
--> $DIR/transmute.rs:133:27
209+
|
210+
LL | let _: u64 = unsafe { std::mem::transmute(1f64) };
211+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1f64.to_bits()`
212+
213+
error: transmute from a `f64` to a `i64`
214+
--> $DIR/transmute.rs:134:27
215+
|
216+
LL | let _: i64 = unsafe { std::mem::transmute(1f64) };
217+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1f64.to_bits() as i64`
218+
219+
error: transmute from a `f64` to a `u64`
220+
--> $DIR/transmute.rs:135:27
221+
|
222+
LL | let _: u64 = unsafe { std::mem::transmute(1.0) };
223+
| ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `1.0f64.to_bits()`
224+
225+
error: transmute from a `f64` to a `u64`
226+
--> $DIR/transmute.rs:136:27
227+
|
228+
LL | let _: u64 = unsafe { std::mem::transmute(-1.0) };
229+
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `(-1.0f64).to_bits()`
230+
193231
error: transmute from a `&[u8]` to a `&str`
194-
--> $DIR/transmute.rs:130:28
232+
--> $DIR/transmute.rs:140:28
195233
|
196234
LL | let _: &str = unsafe { std::mem::transmute(b) };
197235
| ^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::str::from_utf8(b).unwrap()`
198236
|
199237
= note: `-D clippy::transmute-bytes-to-str` implied by `-D warnings`
200238

201239
error: transmute from a `&mut [u8]` to a `&mut str`
202-
--> $DIR/transmute.rs:131:32
240+
--> $DIR/transmute.rs:141:32
203241
|
204242
LL | let _: &mut str = unsafe { std::mem::transmute(mb) };
205243
| ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using: `std::str::from_utf8_mut(mb).unwrap()`
206244

207245
error: transmute from a pointer to a pointer
208-
--> $DIR/transmute.rs:163:29
246+
--> $DIR/transmute.rs:173:29
209247
|
210248
LL | let _: *const f32 = std::mem::transmute(ptr);
211249
| ^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `ptr as *const f32`
212250
|
213251
= note: `-D clippy::transmute-ptr-to-ptr` implied by `-D warnings`
214252

215253
error: transmute from a pointer to a pointer
216-
--> $DIR/transmute.rs:164:27
254+
--> $DIR/transmute.rs:174:27
217255
|
218256
LL | let _: *mut f32 = std::mem::transmute(mut_ptr);
219257
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `mut_ptr as *mut f32`
220258

221259
error: transmute from a reference to a reference
222-
--> $DIR/transmute.rs:166:23
260+
--> $DIR/transmute.rs:176:23
223261
|
224262
LL | let _: &f32 = std::mem::transmute(&1u32);
225263
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(&1u32 as *const u32 as *const f32)`
226264

227265
error: transmute from a reference to a reference
228-
--> $DIR/transmute.rs:167:23
266+
--> $DIR/transmute.rs:177:23
229267
|
230268
LL | let _: &f64 = std::mem::transmute(&1f32);
231269
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(&1f32 as *const f32 as *const f64)`
232270

233271
error: transmute from a reference to a reference
234-
--> $DIR/transmute.rs:170:27
272+
--> $DIR/transmute.rs:180:27
235273
|
236274
LL | let _: &mut f32 = std::mem::transmute(&mut 1u32);
237275
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&mut *(&mut 1u32 as *mut u32 as *mut f32)`
238276

239277
error: transmute from a reference to a reference
240-
--> $DIR/transmute.rs:171:37
278+
--> $DIR/transmute.rs:181:37
241279
|
242280
LL | let _: &GenericParam<f32> = std::mem::transmute(&GenericParam { t: 1u32 });
243281
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `&*(&GenericParam { t: 1u32 } as *const GenericParam<u32> as *const GenericParam<f32>)`
244282

245-
error: aborting due to 38 previous errors
283+
error: aborting due to 44 previous errors
246284

0 commit comments

Comments
 (0)