Skip to content

Commit 4c65221

Browse files
magurotunaflip1995
authored andcommitted
Move transmute_int_to_char to its own module
1 parent 6442d45 commit 4c65221

File tree

2 files changed

+52
-22
lines changed

2 files changed

+52
-22
lines changed

clippy_lints/src/transmute/mod.rs

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
mod crosspointer_transmute;
2+
mod transmute_int_to_char;
23
mod transmute_ptr_to_ref;
34
mod useless_transmute;
45
mod utils;
@@ -365,30 +366,12 @@ impl<'tcx> LateLintPass<'tcx> for Transmute {
365366
if triggered {
366367
return;
367368
}
369+
let triggered = transmute_int_to_char::check(cx, e, from_ty, to_ty, args);
370+
if triggered {
371+
return;
372+
}
368373

369374
match (&from_ty.kind(), &to_ty.kind()) {
370-
(ty::Int(ty::IntTy::I32) | ty::Uint(ty::UintTy::U32), &ty::Char) => {
371-
span_lint_and_then(
372-
cx,
373-
TRANSMUTE_INT_TO_CHAR,
374-
e.span,
375-
&format!("transmute from a `{}` to a `char`", from_ty),
376-
|diag| {
377-
let arg = sugg::Sugg::hir(cx, &args[0], "..");
378-
let arg = if let ty::Int(_) = from_ty.kind() {
379-
arg.as_ty(ast::UintTy::U32.name_str())
380-
} else {
381-
arg
382-
};
383-
diag.span_suggestion(
384-
e.span,
385-
"consider using",
386-
format!("std::char::from_u32({}).unwrap()", arg.to_string()),
387-
Applicability::Unspecified,
388-
);
389-
},
390-
)
391-
},
392375
(ty::Ref(_, ty_from, from_mutbl), ty::Ref(_, ty_to, to_mutbl)) => {
393376
if_chain! {
394377
if let (&ty::Slice(slice_ty), &ty::Str) = (&ty_from.kind(), &ty_to.kind());
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
use super::TRANSMUTE_INT_TO_CHAR;
2+
use crate::utils::{span_lint_and_then, sugg};
3+
use rustc_ast as ast;
4+
use rustc_errors::Applicability;
5+
use rustc_hir::Expr;
6+
use rustc_lint::LateContext;
7+
use rustc_middle::ty;
8+
use rustc_middle::ty::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+
args: &'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+
{
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, &args[0], "..");
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.to_string()),
38+
Applicability::Unspecified,
39+
);
40+
},
41+
)
42+
};
43+
true
44+
},
45+
_ => false,
46+
}
47+
}

0 commit comments

Comments
 (0)