Skip to content

Commit edfdfc2

Browse files
authored
Rollup merge of rust-lang#47689 - davidtwco:issue-45157, r=nikomatsakis
Fix borrow checker unsoundness with unions Fixes rust-lang#45157. After discussion with @nikomatsakis on Gitter, this PR only adds a test since the original issue was resolved elsewhere. r? @nikomatsakis
2 parents 28a1e4f + e6376a1 commit edfdfc2

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

src/test/ui/issue-45157.rs

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![allow(unused)]
12+
#![feature(nll)]
13+
14+
#[derive(Clone, Copy, Default)]
15+
struct S {
16+
a: u8,
17+
b: u8,
18+
}
19+
#[derive(Clone, Copy, Default)]
20+
struct Z {
21+
c: u8,
22+
d: u8,
23+
}
24+
25+
union U {
26+
s: S,
27+
z: Z,
28+
}
29+
30+
fn main() {
31+
unsafe {
32+
let mut u = U { s: Default::default() };
33+
34+
let mref = &mut u.s.a;
35+
*mref = 22;
36+
37+
let nref = &u.z.c;
38+
//~^ ERROR cannot borrow `u.z.c` as immutable because it is also borrowed as mutable [E0502]
39+
println!("{} {}", mref, nref)
40+
//~^ ERROR cannot borrow `u.s.a` as mutable because it is also borrowed as immutable [E0502]
41+
}
42+
}
43+

src/test/ui/issue-45157.stderr

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error[E0502]: cannot borrow `u.z.c` as immutable because it is also borrowed as mutable
2+
--> $DIR/issue-45157.rs:37:20
3+
|
4+
34 | let mref = &mut u.s.a;
5+
| ---------- mutable borrow occurs here
6+
...
7+
37 | let nref = &u.z.c;
8+
| ^^^^^^ immutable borrow occurs here
9+
10+
error[E0502]: cannot borrow `u.s.a` as mutable because it is also borrowed as immutable
11+
--> $DIR/issue-45157.rs:39:27
12+
|
13+
37 | let nref = &u.z.c;
14+
| ------ immutable borrow occurs here
15+
38 | //~^ ERROR cannot borrow `u.z.c` as immutable because it is also borrowed as mutable [E0502]
16+
39 | println!("{} {}", mref, nref)
17+
| ^^^^ mutable borrow occurs here
18+
19+
error: aborting due to 2 previous errors
20+

0 commit comments

Comments
 (0)