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