Skip to content

Commit 49891df

Browse files
compiler-errorscuviper
authored andcommitted
Check params for unsafety in THIR
(cherry picked from commit 12f2bcd)
1 parent 85f29bd commit 49891df

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;
@@ -1066,6 +1073,13 @@ pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) {
10661073
warnings: &mut warnings,
10671074
suggest_unsafe_block: true,
10681075
};
1076+
// params in THIR may be unsafe, e.g. a union pattern.
1077+
for param in &thir.params {
1078+
if let Some(param_pat) = param.pat.as_deref() {
1079+
visitor.visit_pat(param_pat);
1080+
}
1081+
}
1082+
// Visit the body.
10691083
visitor.visit_expr(&thir[expr]);
10701084

10711085
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)