1 // Copyright 2015 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.
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.
11 // Checking that `Vec<T>` cannot hide lifetimes within `T` when `T`
12 // implements `Drop` and might access methods of values that have
13 // since been deallocated.
15 // In this case, the values in question hold (non-zero) unique-ids
16 // that zero themselves out when dropped, and are wrapped in another
17 // type with a destructor that asserts that the ids it references are
18 // indeed non-zero (i.e., effectively checking that the id's are not
19 // dropped while there are still any outstanding references).
21 // However, the values in question are also formed into a
22 // cyclic-structure, ensuring that there is no way for all of the
23 // conditions above to be satisfied, meaning that if the dropck is
24 // sound, it should reject this code.
32 use std::sync::atomic::{AtomicUsize, Ordering};
34 static S_COUNT: AtomicUsize = AtomicUsize::new(0);
36 /// generates globally unique count (global across the current
38 pub fn next_count() -> usize {
39 S_COUNT.fetch_add(1, Ordering::SeqCst) + 1
46 /// Id represents a globally unique identifier (global across the
47 /// current process, that is). When dropped, it automatically
48 /// clears its `count` field, but leaves `orig_count` untouched,
49 /// so that if there are subsequent (erroneous) invocations of its
50 /// method (which is unsound), we can observe it by seeing that
51 /// the `count` is 0 while the `orig_count` is non-zero.
59 /// Creates an `Id` with a globally unique count.
61 let c = s::next_count();
62 println!("building Id {}", c);
63 Id { orig_count: c, count: c }
65 /// returns the `count` of self; should be non-zero if
66 /// everything is working.
67 pub fn count(&self) -> usize {
68 println!("Id::count on {} returns {}", self.orig_count, self.count);
75 println!("dropping Id {}", self.count);
82 fn count(&self) -> usize;
86 struct CheckId<T:HasId> {
90 #[allow(non_snake_case)]
91 fn CheckId<T:HasId>(t: T) -> CheckId<T> { CheckId{ v: t } }
93 impl<T:HasId> Drop for CheckId<T> {
95 assert!(self.v.count() > 0);
102 v: Vec<CheckId<Cell<Option<&'a C<'a>>>>>,
105 impl<'a> HasId for Cell<Option<&'a C<'a>>> {
106 fn count(&self) -> usize {
109 Some(c) => c.id.count(),
116 C { id: Id::new(), v: Vec::new() }
121 let (mut c1, mut c2);
125 c1.v.push(CheckId(Cell::new(None)));
126 c2.v.push(CheckId(Cell::new(None)));
127 c1.v[0].v.set(Some(&c2));
128 //~^ ERROR `c2` does not live long enough
129 c2.v[0].v.set(Some(&c1));
130 //~^ ERROR `c1` does not live long enough