]> git.proxmox.com Git - rustc.git/blob - src/test/compile-fail/borrowck/borrowck-union-borrow.rs
New upstream version 1.13.0+dfsg1
[rustc.git] / src / test / compile-fail / borrowck / borrowck-union-borrow.rs
1 // Copyright 2016 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 // ignore-tidy-linelength
12
13 #![feature(untagged_unions)]
14
15 #[derive(Clone, Copy)]
16 union U {
17 a: u8,
18 b: u64,
19 }
20
21 fn main() {
22 unsafe {
23 let mut u = U { b: 0 };
24 // Imm borrow, same field
25 {
26 let ra = &u.a;
27 let ra2 = &u.a; // OK
28 }
29 {
30 let ra = &u.a;
31 let a = u.a; // OK
32 }
33 {
34 let ra = &u.a;
35 let rma = &mut u.a; //~ ERROR cannot borrow `u.a` as mutable because it is also borrowed as immutable
36 }
37 {
38 let ra = &u.a;
39 u.a = 1; //~ ERROR cannot assign to `u.a` because it is borrowed
40 }
41 // Imm borrow, other field
42 {
43 let ra = &u.a;
44 let rb = &u.b; // OK
45 }
46 {
47 let ra = &u.a;
48 let b = u.b; // OK
49 }
50 {
51 let ra = &u.a;
52 let rmb = &mut u.b; //~ ERROR cannot borrow `u` (via `u.b`) as mutable because `u` is also borrowed as immutable (via `u.a`)
53 }
54 {
55 let ra = &u.a;
56 u.b = 1; //~ ERROR cannot assign to `u.b` because it is borrowed
57 }
58 // Mut borrow, same field
59 {
60 let rma = &mut u.a;
61 let ra = &u.a; //~ ERROR cannot borrow `u.a` as immutable because it is also borrowed as mutable
62 }
63 {
64 let ra = &mut u.a;
65 let a = u.a; //~ ERROR cannot use `u.a` because it was mutably borrowed
66 }
67 {
68 let rma = &mut u.a;
69 let rma2 = &mut u.a; //~ ERROR cannot borrow `u.a` as mutable more than once at a time
70 }
71 {
72 let rma = &mut u.a;
73 u.a = 1; //~ ERROR cannot assign to `u.a` because it is borrowed
74 }
75 // Mut borrow, other field
76 {
77 let rma = &mut u.a;
78 let rb = &u.b; //~ ERROR cannot borrow `u` (via `u.b`) as immutable because `u` is also borrowed as mutable (via `u.a`)
79 }
80 {
81 let ra = &mut u.a;
82 let b = u.b; //~ ERROR cannot use `u.b` because it was mutably borrowed
83 }
84 {
85 let rma = &mut u.a;
86 let rmb2 = &mut u.b; //~ ERROR cannot borrow `u` (via `u.b`) as mutable more than once at a time
87 }
88 {
89 let rma = &mut u.a;
90 u.b = 1; //~ ERROR cannot assign to `u.b` because it is borrowed
91 }
92 }
93 }