Skip to content

Commit f3dafe9

Browse files
committed
Add support for deferred casting for the invalid_reference_casting lint
1 parent 345d6b8 commit f3dafe9

File tree

6 files changed

+80
-32
lines changed

6 files changed

+80
-32
lines changed

compiler/rustc_lint/messages.ftl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,7 @@ lint_invalid_nan_comparisons_eq_ne = incorrect NaN comparison, NaN cannot be dir
319319
lint_invalid_nan_comparisons_lt_le_gt_ge = incorrect NaN comparison, NaN is not orderable
320320
321321
lint_invalid_reference_casting = casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell`
322+
.label = casting happend here
322323
323324
lint_lintpass_by_hand = implementing `LintPass` by hand
324325
.help = try using `declare_lint_pass!` or `impl_lint_pass!` instead

compiler/rustc_lint/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ late_lint_methods!(
218218
BoxPointers: BoxPointers,
219219
PathStatements: PathStatements,
220220
LetUnderscore: LetUnderscore,
221-
InvalidReferenceCasting: InvalidReferenceCasting,
221+
InvalidReferenceCasting: InvalidReferenceCasting::default(),
222222
// Depends on referenced function signatures in expressions
223223
UnusedResults: UnusedResults,
224224
NonUpperCaseGlobals: NonUpperCaseGlobals,

compiler/rustc_lint/src/lints.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -746,7 +746,10 @@ pub enum InvalidFromUtf8Diag {
746746
// reference_casting.rs
747747
#[derive(LintDiagnostic)]
748748
#[diag(lint_invalid_reference_casting)]
749-
pub struct InvalidReferenceCastingDiag;
749+
pub struct InvalidReferenceCastingDiag {
750+
#[label]
751+
pub orig_cast: Option<Span>,
752+
}
750753

751754
// hidden_unicode_codepoints.rs
752755
#[derive(LintDiagnostic)]
Lines changed: 62 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
use rustc_ast::Mutability;
2-
use rustc_hir::{Expr, ExprKind, MutTy, TyKind, UnOp};
3-
use rustc_middle::ty;
4-
use rustc_span::sym;
2+
use rustc_data_structures::fx::FxHashMap;
3+
use rustc_hir::{def::Res, Expr, ExprKind, HirId, Local, QPath, StmtKind, UnOp};
4+
use rustc_middle::ty::{self, TypeAndMut};
5+
use rustc_span::{sym, Span};
56

67
use crate::{lints::InvalidReferenceCastingDiag, LateContext, LateLintPass, LintContext};
78

@@ -33,42 +34,74 @@ declare_lint! {
3334
"casts of `&T` to `&mut T` without interior mutability"
3435
}
3536

36-
declare_lint_pass!(InvalidReferenceCasting => [INVALID_REFERENCE_CASTING]);
37+
#[derive(Default)]
38+
pub struct InvalidReferenceCasting {
39+
casted: FxHashMap<HirId, Span>,
40+
}
41+
42+
impl_lint_pass!(InvalidReferenceCasting => [INVALID_REFERENCE_CASTING]);
3743

3844
impl<'tcx> LateLintPass<'tcx> for InvalidReferenceCasting {
39-
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
40-
let ExprKind::Unary(UnOp::Deref, e) = &expr.kind else {
45+
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx rustc_hir::Stmt<'tcx>) {
46+
let StmtKind::Local(local) = stmt.kind else {
4147
return;
4248
};
43-
44-
let e = e.peel_blocks();
45-
let e = if let ExprKind::Cast(e, t) = e.kind
46-
&& let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind {
47-
e
48-
} else if let ExprKind::MethodCall(_, expr, [], _) = e.kind
49-
&& let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id)
50-
&& cx.tcx.is_diagnostic_item(sym::ptr_cast_mut, def_id) {
51-
expr
52-
} else {
49+
let Local { init: Some(init), els: None, .. } = local else {
5350
return;
5451
};
5552

56-
let e = e.peel_blocks();
57-
let e = if let ExprKind::Cast(e, t) = e.kind
58-
&& let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind {
59-
e
60-
} else if let ExprKind::Call(path, [arg]) = e.kind
61-
&& let ExprKind::Path(ref qpath) = path.kind
62-
&& let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
63-
&& cx.tcx.is_diagnostic_item(sym::ptr_from_ref, def_id) {
64-
arg
65-
} else {
53+
if is_cast_from_const_to_mut(cx, init) {
54+
self.casted.insert(local.pat.hir_id, init.span);
55+
}
56+
}
57+
58+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
59+
let ExprKind::Unary(UnOp::Deref, e) = &expr.kind else {
6660
return;
6761
};
6862

69-
let e = e.peel_blocks();
70-
if let ty::Ref(..) = cx.typeck_results().node_type(e.hir_id).kind() {
71-
cx.emit_spanned_lint(INVALID_REFERENCE_CASTING, expr.span, InvalidReferenceCastingDiag);
63+
if is_cast_from_const_to_mut(cx, e) {
64+
cx.emit_spanned_lint(INVALID_REFERENCE_CASTING, expr.span, InvalidReferenceCastingDiag { orig_cast: None });
65+
} else if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind
66+
&& let Res::Local(hir_id) = &path.res
67+
&& let Some(orig_cast) = self.casted.get(hir_id) {
68+
cx.emit_spanned_lint(INVALID_REFERENCE_CASTING, expr.span, InvalidReferenceCastingDiag { orig_cast: Some(*orig_cast) });
7269
}
7370
}
7471
}
72+
73+
fn is_cast_from_const_to_mut<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) -> bool {
74+
let e = e.peel_blocks();
75+
76+
// <expr> as *mut ...
77+
let e = if let ExprKind::Cast(e, t) = e.kind
78+
&& let ty::RawPtr(TypeAndMut { mutbl: Mutability::Mut, .. }) = cx.typeck_results().node_type(t.hir_id).kind() {
79+
e
80+
// <expr>.cast_mut()
81+
} else if let ExprKind::MethodCall(_, expr, [], _) = e.kind
82+
&& let Some(def_id) = cx.typeck_results().type_dependent_def_id(e.hir_id)
83+
&& cx.tcx.is_diagnostic_item(sym::ptr_cast_mut, def_id) {
84+
expr
85+
} else {
86+
return false;
87+
};
88+
89+
let e = e.peel_blocks();
90+
91+
// <expr> as *const ...
92+
let e = if let ExprKind::Cast(e, t) = e.kind
93+
&& let ty::RawPtr(TypeAndMut { mutbl: Mutability::Not, .. }) = cx.typeck_results().node_type(t.hir_id).kind() {
94+
e
95+
// ptr::from_ref(<expr>)
96+
} else if let ExprKind::Call(path, [arg]) = e.kind
97+
&& let ExprKind::Path(ref qpath) = path.kind
98+
&& let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
99+
&& cx.tcx.is_diagnostic_item(sym::ptr_from_ref, def_id) {
100+
arg
101+
} else {
102+
return false;
103+
};
104+
105+
let e = e.peel_blocks();
106+
matches!(cx.typeck_results().node_type(e.hir_id).kind(), ty::Ref(..))
107+
}

tests/ui/lint/reference_casting.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ fn main() {
3636
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
3737
*(std::ptr::from_ref({ num }) as *mut i32) += 1;
3838
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
39+
let value = num as *const i32 as *mut i32;
40+
*value = 1;
41+
//~^ ERROR casting `&T` to `&mut T` is undefined behavior
3942

4043
// Shouldn't be warned against
4144
println!("{}", *(num as *const _ as *const i16));

tests/ui/lint/reference_casting.stderr

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,5 +60,13 @@ error: casting `&T` to `&mut T` is undefined behavior, even if the reference is
6060
LL | *(std::ptr::from_ref({ num }) as *mut i32) += 1;
6161
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6262

63-
error: aborting due to 10 previous errors
63+
error: casting `&T` to `&mut T` is undefined behavior, even if the reference is unused, consider instead using an `UnsafeCell`
64+
--> $DIR/reference_casting.rs:40:9
65+
|
66+
LL | let value = num as *const i32 as *mut i32;
67+
| ----------------------------- casting happend here
68+
LL | *value = 1;
69+
| ^^^^^^
70+
71+
error: aborting due to 11 previous errors
6472

0 commit comments

Comments
 (0)