Skip to content

Commit 4d4c366

Browse files
committed
add lint for transmute from &T to &mut T of a ADT arguement
1 parent 5e7ce90 commit 4d4c366

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

clippy_lints/src/transmute/mod.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
mod crosspointer_transmute;
22
mod eager_transmute;
33
mod missing_transmute_annotations;
4+
mod transmute_adt_arguement;
45
mod transmute_int_to_bool;
56
mod transmute_int_to_non_zero;
67
mod transmute_null_to_fn;
@@ -44,6 +45,22 @@ declare_clippy_lint! {
4445
correctness,
4546
"transmutes that are confusing at best, undefined behavior at worst and always useless"
4647
}
48+
declare_clippy_lint! {
49+
/// ### What it does
50+
/// Checks for transmutes between the same adt, where at least one of the type arguement goes from &T to &mut T.
51+
/// This is an a more complicated version of https://doc.rust-lang.org/rustc/lints/listing/deny-by-default.html#mutable-transmutes.
52+
/// ### Example
53+
///
54+
/// ```ignore
55+
/// unsafe {
56+
/// std::mem::transmute::<Option<&i32>, Option<&mut i32>>(&Some(5));
57+
/// }
58+
/// ```
59+
#[clippy::version = "1.92.0"]
60+
pub MUTABLE_ADT_ARGUEMENT_TRANSMUTE,
61+
correctness,
62+
"transmutes on the same adt where at least one of the type arguement goes from &T to &mut T"
63+
}
4764

4865
declare_clippy_lint! {
4966
/// ### What it does
@@ -516,6 +533,7 @@ impl<'tcx> LateLintPass<'tcx> for Transmute {
516533
}
517534

518535
let linted = wrong_transmute::check(cx, e, from_ty, to_ty)
536+
| transmute_adt_arguement::check(cx, e, from_ty, to_ty)
519537
| crosspointer_transmute::check(cx, e, from_ty, to_ty)
520538
| transmuting_null::check(cx, e, arg, to_ty)
521539
| transmute_null_to_fn::check(cx, e, arg, to_ty)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
use super::MUTABLE_ADT_ARGUEMENT_TRANSMUTE;
2+
use clippy_utils::diagnostics::span_lint;
3+
use rustc_hir::Expr;
4+
use rustc_lint::LateContext;
5+
use rustc_middle::ty::{self, GenericArgKind, Ty};
6+
7+
pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> bool {
8+
from_ty
9+
.walk()
10+
.zip(to_ty.walk())
11+
.filter_map(|(from_ty, to_ty)| {
12+
if let (GenericArgKind::Type(from_ty), GenericArgKind::Type(to_ty)) = (from_ty.kind(), to_ty.kind()) {
13+
Some((from_ty, to_ty))
14+
} else {
15+
None
16+
}
17+
})
18+
.filter(|(from_ty_inner, to_ty_inner)| {
19+
if let (ty::Ref(_, _, from_mut), ty::Ref(_, _, to_mut)) = (from_ty_inner.kind(), to_ty_inner.kind())
20+
&& from_mut < to_mut
21+
{
22+
span_lint(
23+
cx,
24+
MUTABLE_ADT_ARGUEMENT_TRANSMUTE,
25+
e.span,
26+
format!("transmute of type arguement {from_ty_inner} to {from_ty_inner}"),
27+
);
28+
true
29+
} else {
30+
false
31+
}
32+
})
33+
.count()
34+
> 0
35+
}

0 commit comments

Comments
 (0)