]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/transmute/transmute_int_to_char.rs
Auto merge of #95841 - ChrisDenton:pipe-server, r=m-ou-se
[rust.git] / src / tools / clippy / clippy_lints / src / transmute / transmute_int_to_char.rs
1 use super::TRANSMUTE_INT_TO_CHAR;
2 use clippy_utils::diagnostics::span_lint_and_then;
3 use clippy_utils::sugg;
4 use rustc_ast as ast;
5 use rustc_errors::Applicability;
6 use rustc_hir::Expr;
7 use rustc_lint::LateContext;
8 use rustc_middle::ty::{self, Ty};
9
10 /// Checks for `transmute_int_to_char` lint.
11 /// Returns `true` if it's triggered, otherwise returns `false`.
12 pub(super) fn check<'tcx>(
13     cx: &LateContext<'tcx>,
14     e: &'tcx Expr<'_>,
15     from_ty: Ty<'tcx>,
16     to_ty: Ty<'tcx>,
17     arg: &'tcx Expr<'_>,
18     const_context: bool,
19 ) -> bool {
20     match (&from_ty.kind(), &to_ty.kind()) {
21         (ty::Int(ty::IntTy::I32) | ty::Uint(ty::UintTy::U32), &ty::Char) if !const_context => {
22             span_lint_and_then(
23                 cx,
24                 TRANSMUTE_INT_TO_CHAR,
25                 e.span,
26                 &format!("transmute from a `{}` to a `char`", from_ty),
27                 |diag| {
28                     let arg = sugg::Sugg::hir(cx, arg, "..");
29                     let arg = if let ty::Int(_) = from_ty.kind() {
30                         arg.as_ty(ast::UintTy::U32.name_str())
31                     } else {
32                         arg
33                     };
34                     diag.span_suggestion(
35                         e.span,
36                         "consider using",
37                         format!("std::char::from_u32({}).unwrap()", arg),
38                         Applicability::Unspecified,
39                     );
40                 },
41             );
42             true
43         },
44         _ => false,
45     }
46 }