]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/casts/char_lit_as_u8.rs
Rollup merge of #91834 - GuillaumeGomez:improve-gui-test-readability, r=jsha
[rust.git] / src / tools / clippy / clippy_lints / src / casts / char_lit_as_u8.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::snippet_with_applicability;
3 use if_chain::if_chain;
4 use rustc_ast::LitKind;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Expr, ExprKind};
7 use rustc_lint::LateContext;
8 use rustc_middle::ty::{self, UintTy};
9
10 use super::CHAR_LIT_AS_U8;
11
12 pub(super) fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
13     if_chain! {
14         if let ExprKind::Cast(e, _) = &expr.kind;
15         if let ExprKind::Lit(l) = &e.kind;
16         if let LitKind::Char(c) = l.node;
17         if ty::Uint(UintTy::U8) == *cx.typeck_results().expr_ty(expr).kind();
18         then {
19             let mut applicability = Applicability::MachineApplicable;
20             let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
21
22             span_lint_and_then(
23                 cx,
24                 CHAR_LIT_AS_U8,
25                 expr.span,
26                 "casting a character literal to `u8` truncates",
27                 |diag| {
28                     diag.note("`char` is four bytes wide, but `u8` is a single byte");
29
30                     if c.is_ascii() {
31                         diag.span_suggestion(
32                             expr.span,
33                             "use a byte literal instead",
34                             format!("b{}", snippet),
35                             applicability,
36                         );
37                     }
38             });
39         }
40     }
41 }