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