summaryrefslogtreecommitdiff
path: root/tests/src/borrow-check-negative.rs
blob: 697546ddfd6b8f7328c2ca33b1a290641ed5675f (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
78
79
80
81
82
83
84
85
86
87
88
89
90
//@ [!borrow-check] skip
//@ [borrow-check] known-failure
// Some negative tests for borrow checking

// This succeeds
fn choose<'a, T>(b: bool, x: &'a mut T, y: &'a mut T) -> &'a mut T {
    if b {
        x
    } else {
        y
    }
}

pub fn choose_test() {
    let mut x = 0;
    let mut y = 0;
    let z = choose(true, &mut x, &mut y);
    *z += 1;
    assert!(*z == 1);
    // drop(z)
    assert!(x == 1);
    assert!(y == 0);
    assert!(*z == 1); // z is not valid anymore
}

fn choose_wrong<'a, 'b, T>(b: bool, x: &'a mut T, y: &'b mut T) -> &'a mut T {
    if b {
        x
    } else {
        y // Expected lifetime 'a
    }
}

fn test_mut1(b: bool) {
    let mut x = 0;
    let mut y = 1;
    let z = if b { &mut x } else { &mut y };
    *z += 1;
    assert!(x >= 0);
    *z += 1; // z is not valid anymore
}

#[allow(unused_assignments)]
fn test_mut2(b: bool) {
    let mut x = 0;
    let mut y = 1;
    let z = if b { &x } else { &y };
    x += 1;
    assert!(*z == 0); // z is not valid anymore
}

fn test_move1<T>(x: T) -> T {
    let _ = x;
    return x; // x has been moved
}

pub fn refs_test1() {
    let mut x = 0;
    let mut px = &mut x;
    let ppx = &mut px;
    **ppx = 1;
    assert!(x == 1);
    assert!(**ppx == 1); // ppx has ended
}

pub fn refs_test2() {
    let mut x = 0;
    let mut y = 1;
    let mut px = &mut x;
    let py = &mut y;
    let ppx = &mut px;
    *ppx = py;
    **ppx = 2;
    assert!(*px == 2);
    assert!(x == 0);
    assert!(*py == 2);
    assert!(y == 2);
    assert!(**ppx == 2); // ppx has ended
}

pub fn test_box1() {
    use std::ops::Deref;
    use std::ops::DerefMut;
    let mut b: Box<i32> = Box::new(0);
    let x0 = b.deref_mut();
    *x0 = 1;
    let x1 = b.deref();
    assert!(*x1 == 1);
    assert!(*x0 == 1); // x0 has ended
}