]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/transmute/transmute_int_to_char.rs
Merge commit '57b3c4b90f4346b3990c1be387c3b3ca7b78412c' into clippyup
[rust.git] / 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 ) -> bool {
19     match (&from_ty.kind(), &to_ty.kind()) {
20         (ty::Int(ty::IntTy::I32) | ty::Uint(ty::UintTy::U32), &ty::Char) => {
21             span_lint_and_then(
22                 cx,
23                 TRANSMUTE_INT_TO_CHAR,
24                 e.span,
25                 &format!("transmute from a `{}` to a `char`", from_ty),
26                 |diag| {
27                     let arg = sugg::Sugg::hir(cx, arg, "..");
28                     let arg = if let ty::Int(_) = from_ty.kind() {
29                         arg.as_ty(ast::UintTy::U32.name_str())
30                     } else {
31                         arg
32                     };
33                     diag.span_suggestion(
34                         e.span,
35                         "consider using",
36                         format!("std::char::from_u32({}).unwrap()", arg),
37                         Applicability::Unspecified,
38                     );
39                 },
40             );
41             true
42         },
43         _ => false,
44     }
45 }