]> git.lizzy.rs Git - rust.git/blob - src/test/ui/span/issue-25199.rs
Rollup merge of #87922 - Manishearth:c-enum-target-spec, r=nagisa,eddyb
[rust.git] / src / test / ui / span / issue-25199.rs
1 // Regression test for Issue 25199: Check that one cannot hide a
2 // destructor's access to borrowed data behind a boxed trait object.
3 //
4 // Prior to fixing Issue 25199, this example was able to be compiled
5 // with rustc, and thus when you ran it, you would see the `Drop` impl
6 // for `Test` accessing state that had already been dropping (which is
7 // marked explicitly here with checking code within the `Drop` impl
8 // for `VecHolder`, but in the general case could just do unsound
9 // things like accessing memory that has been freed).
10 //
11 // Note that I would have liked to encode my go-to example of cyclic
12 // structure that accesses its neighbors in drop (and thus is
13 // fundamentally unsound) via this trick, but the closest I was able
14 // to come was dropck_trait_cycle_checked.rs, which is not quite as
15 // "good" as this regression test because the encoding of that example
16 // was forced to attach a lifetime to the trait definition itself
17 // (`trait Obj<'a>`) while *this* example is solely
18
19 use std::cell::RefCell;
20
21 trait Obj { }
22
23 struct VecHolder {
24     v: Vec<(bool, &'static str)>,
25 }
26
27 impl Drop for VecHolder {
28     fn drop(&mut self) {
29         println!("Dropping Vec");
30         self.v[30].0 = false;
31         self.v[30].1 = "invalid access: VecHolder dropped already";
32     }
33 }
34
35 struct Container<'a> {
36     v: VecHolder,
37     d: RefCell<Vec<Box<dyn Obj+'a>>>,
38 }
39
40 impl<'a> Container<'a> {
41     fn new() -> Container<'a> {
42         Container {
43             d: RefCell::new(Vec::new()),
44             v: VecHolder {
45                 v: vec![(true, "valid"); 100]
46             }
47         }
48     }
49
50     fn store<T: Obj+'a>(&'a self, val: T) {
51         self.d.borrow_mut().push(Box::new(val));
52     }
53 }
54
55 struct Test<'a> {
56     test: &'a Container<'a>,
57 }
58
59 impl<'a> Obj for Test<'a> { }
60 impl<'a> Drop for Test<'a> {
61     fn drop(&mut self) {
62         for e in &self.test.v.v {
63             assert!(e.0, e.1);
64         }
65     }
66 }
67
68 fn main() {
69     let container = Container::new();
70     let test = Test{test: &container};
71     //~^ ERROR `container` does not live long enough
72     println!("container.v[30]: {:?}", container.v.v[30]);
73     container.store(test);
74 }