summaryrefslogtreecommitdiffstats
path: root/tests/ui/drop/issue-21486.rs
blob: 46d6ccd56bdc2493c9976767543de37d20705f8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// run-pass
#![allow(unreachable_code)]
// Issue #21486: Make sure that all structures are dropped, even when
// created via FRU and control-flow breaks in the middle of
// construction.

use std::sync::atomic::{Ordering, AtomicUsize};

#[derive(Debug)]
struct Noisy(u8);
impl Drop for Noisy {
    fn drop(&mut self) {
        // println!("splat #{}", self.0);
        event(self.0);
    }
}

#[allow(dead_code)]
#[derive(Debug)]
struct Foo { n0: Noisy, n1: Noisy }
impl Foo {
    fn vals(&self) -> (u8, u8) { (self.n0.0, self.n1.0) }
}

fn leak_1_ret() -> Foo {
    let _old_foo = Foo { n0: Noisy(1), n1: Noisy(2) };
    Foo { n0: { return Foo { n0: Noisy(3), n1: Noisy(4) } },
          .._old_foo
    };
}

fn leak_2_ret() -> Foo {
    let _old_foo = Foo { n0: Noisy(1), n1: Noisy(2) };
    Foo { n1: { return Foo { n0: Noisy(3), n1: Noisy(4) } },
          .._old_foo
    };
}

// In this case, the control flow break happens *before* we construct
// `Foo(Noisy(1),Noisy(2))`, so there should be no record of it in the
// event log.
fn leak_3_ret() -> Foo {
    let _old_foo = || Foo { n0: Noisy(1), n1: Noisy(2) };
    Foo { n1: { return Foo { n0: Noisy(3), n1: Noisy(4) } },
          .._old_foo()
    };
}

pub fn main() {
    reset_log();
    assert_eq!(leak_1_ret().vals(), (3,4));
    assert_eq!(0x01_02_03_04, event_log());

    reset_log();
    assert_eq!(leak_2_ret().vals(), (3,4));
    assert_eq!(0x01_02_03_04, event_log());

    reset_log();
    assert_eq!(leak_3_ret().vals(), (3,4));
    assert_eq!(0x03_04, event_log());
}

static LOG: AtomicUsize = AtomicUsize::new(0);

fn reset_log() {
    LOG.store(0, Ordering::SeqCst);
}

fn event_log() -> usize {
    LOG.load(Ordering::SeqCst)
}

fn event(tag: u8) {
    let old_log = LOG.load(Ordering::SeqCst);
    let new_log = (old_log << 8) + tag as usize;
    LOG.store(new_log, Ordering::SeqCst);
}