Skip to content

Commit 12f2bcd

Browse files
Check params for unsafety in THIR
1 parent 7fc70f8 commit 12f2bcd

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed

Diff for: compiler/rustc_mir_build/src/check_unsafety.rs

+14
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,13 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
218218
warnings: self.warnings,
219219
suggest_unsafe_block: self.suggest_unsafe_block,
220220
};
221+
// params in THIR may be unsafe, e.g. a union pattern.
222+
for param in &inner_thir.params {
223+
if let Some(param_pat) = param.pat.as_deref() {
224+
inner_visitor.visit_pat(param_pat);
225+
}
226+
}
227+
// Visit the body.
221228
inner_visitor.visit_expr(&inner_thir[expr]);
222229
// Unsafe blocks can be used in the inner body, make sure to take it into account
223230
self.safety_context = inner_visitor.safety_context;
@@ -1032,6 +1039,13 @@ pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) {
10321039
warnings: &mut warnings,
10331040
suggest_unsafe_block: true,
10341041
};
1042+
// params in THIR may be unsafe, e.g. a union pattern.
1043+
for param in &thir.params {
1044+
if let Some(param_pat) = param.pat.as_deref() {
1045+
visitor.visit_pat(param_pat);
1046+
}
1047+
}
1048+
// Visit the body.
10351049
visitor.visit_expr(&thir[expr]);
10361050

10371051
warnings.sort_by_key(|w| w.block_span);

Diff for: tests/ui/unsafe/union-pat-in-param.rs

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
union U {
2+
a: &'static i32,
3+
b: usize,
4+
}
5+
6+
fn fun(U { a }: U) {
7+
//~^ ERROR access to union field is unsafe
8+
dbg!(*a);
9+
}
10+
11+
fn main() {
12+
fun(U { b: 0 });
13+
14+
let closure = |U { a }| {
15+
//~^ ERROR access to union field is unsafe
16+
dbg!(*a);
17+
};
18+
closure(U { b: 0 });
19+
}

Diff for: tests/ui/unsafe/union-pat-in-param.stderr

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
error[E0133]: access to union field is unsafe and requires unsafe function or block
2+
--> $DIR/union-pat-in-param.rs:6:12
3+
|
4+
LL | fn fun(U { a }: U) {
5+
| ^ access to union field
6+
|
7+
= note: the field may not be properly initialized: using uninitialized data will cause undefined behavior
8+
9+
error[E0133]: access to union field is unsafe and requires unsafe function or block
10+
--> $DIR/union-pat-in-param.rs:14:24
11+
|
12+
LL | let closure = |U { a }| {
13+
| ^ access to union field
14+
|
15+
= note: the field may not be properly initialized: using uninitialized data will cause undefined behavior
16+
17+
error: aborting due to 2 previous errors
18+
19+
For more information about this error, try `rustc --explain E0133`.

0 commit comments

Comments
 (0)