]> git.lizzy.rs Git - rust.git/blob - src/test/ui/span/dropck_vec_cycle_checked.rs
Rollup merge of #100953 - joshtriplett:write-docs, r=Mark-Simulacrum
[rust.git] / src / test / ui / span / dropck_vec_cycle_checked.rs
1 // Reject mixing cyclic structure and Drop when using Vec.
2 //
3 // (Compare against ui/span/dropck_arr_cycle_checked.rs)
4
5 use std::cell::Cell;
6 use id::Id;
7
8 mod s {
9     use std::sync::atomic::{AtomicUsize, Ordering};
10
11     static S_COUNT: AtomicUsize = AtomicUsize::new(0);
12
13     pub fn next_count() -> usize {
14         S_COUNT.fetch_add(1, Ordering::SeqCst) + 1
15     }
16 }
17
18 mod id {
19     use s;
20     #[derive(Debug)]
21     pub struct Id {
22         orig_count: usize,
23         count: usize,
24     }
25
26     impl Id {
27         pub fn new() -> Id {
28             let c = s::next_count();
29             println!("building Id {}", c);
30             Id { orig_count: c, count: c }
31         }
32         pub fn count(&self) -> usize {
33             println!("Id::count on {} returns {}", self.orig_count, self.count);
34             self.count
35         }
36     }
37
38     impl Drop for Id {
39         fn drop(&mut self) {
40             println!("dropping Id {}", self.count);
41             self.count = 0;
42         }
43     }
44 }
45
46 trait HasId {
47     fn count(&self) -> usize;
48 }
49
50 #[derive(Debug)]
51 struct CheckId<T:HasId> {
52     v: T
53 }
54
55 #[allow(non_snake_case)]
56 fn CheckId<T:HasId>(t: T) -> CheckId<T> { CheckId{ v: t } }
57
58 impl<T:HasId> Drop for CheckId<T> {
59     fn drop(&mut self) {
60         assert!(self.v.count() > 0);
61     }
62 }
63
64 #[derive(Debug)]
65 struct C<'a> {
66     id: Id,
67     v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>,
68 }
69
70 impl<'a> HasId for Cell<Option<&'a C<'a>>> {
71     fn count(&self) -> usize {
72         match self.get() {
73             None => 1,
74             Some(c) => c.id.count(),
75         }
76     }
77 }
78
79 impl<'a> C<'a> {
80     fn new() -> C<'a> {
81         C { id: Id::new(), v: Vec::new() }
82     }
83 }
84
85 fn f() {
86     let (mut c1, mut c2, mut c3);
87     c1 = C::new();
88     c2 = C::new();
89     c3 = C::new();
90
91     c1.v.push(CheckId(Cell::new(None)));
92     c1.v.push(CheckId(Cell::new(None)));
93     c2.v.push(CheckId(Cell::new(None)));
94     c2.v.push(CheckId(Cell::new(None)));
95     c3.v.push(CheckId(Cell::new(None)));
96     c3.v.push(CheckId(Cell::new(None)));
97
98     c1.v[0].v.set(Some(&c2));
99     //~^ ERROR `c2` does not live long enough
100     c1.v[1].v.set(Some(&c3));
101     //~^ ERROR `c3` does not live long enough
102     c2.v[0].v.set(Some(&c2));
103     c2.v[1].v.set(Some(&c3));
104     c3.v[0].v.set(Some(&c1));
105     //~^ ERROR `c1` does not live long enough
106     c3.v[1].v.set(Some(&c2));
107 }
108
109 fn main() {
110     f();
111 }