]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute/transmute_int_to_float.rs
Auto merge of #6791 - TaKO8Ki:iter-count, r=matthiaskrgr
[rust.git] / clippy_lints / src / transmute / transmute_int_to_float.rs
1 use super::TRANSMUTE_INT_TO_FLOAT;
2 use crate::utils::{span_lint_and_then, sugg};
3 use rustc_errors::Applicability;
4 use rustc_hir::Expr;
5 use rustc_lint::LateContext;
6 use rustc_middle::ty::{self, Ty};
7
8 /// Checks for `transmute_int_to_float` lint.
9 /// Returns `true` if it's triggered, otherwise returns `false`.
10 pub(super) fn check<'tcx>(
11     cx: &LateContext<'tcx>,
12     e: &'tcx Expr<'_>,
13     from_ty: Ty<'tcx>,
14     to_ty: Ty<'tcx>,
15     args: &'tcx [Expr<'_>],
16     const_context: bool,
17 ) -> bool {
18     match (&from_ty.kind(), &to_ty.kind()) {
19         (ty::Int(_) | ty::Uint(_), ty::Float(_)) if !const_context => {
20             span_lint_and_then(
21                 cx,
22                 TRANSMUTE_INT_TO_FLOAT,
23                 e.span,
24                 &format!("transmute from a `{}` to a `{}`", from_ty, to_ty),
25                 |diag| {
26                     let arg = sugg::Sugg::hir(cx, &args[0], "..");
27                     let arg = if let ty::Int(int_ty) = from_ty.kind() {
28                         arg.as_ty(format!(
29                             "u{}",
30                             int_ty.bit_width().map_or_else(|| "size".to_string(), |v| v.to_string())
31                         ))
32                     } else {
33                         arg
34                     };
35                     diag.span_suggestion(
36                         e.span,
37                         "consider using",
38                         format!("{}::from_bits({})", to_ty, arg.to_string()),
39                         Applicability::Unspecified,
40                     );
41                 },
42             );
43             true
44         },
45         _ => false,
46     }
47 }