]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_lints/src/casts/char_lit_as_u8.rs
Merge tag 'debian/1.52.1+dfsg1-1_exp2' into proxmox/buster
[rustc.git] / src / tools / clippy / clippy_lints / src / casts / char_lit_as_u8.rs
CommitLineData
f20569fa
XL
1use rustc_ast::LitKind;
2use rustc_errors::Applicability;
3use rustc_hir::{Expr, ExprKind};
4use rustc_lint::LateContext;
5use rustc_middle::ty::{self, UintTy};
6
7use if_chain::if_chain;
8
9use crate::utils::{snippet_with_applicability, span_lint_and_then};
10
11use super::CHAR_LIT_AS_U8;
12
13pub(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}