]> git.lizzy.rs Git - rust.git/blob - src/test/ui/binding/fn-arg-incomplete-pattern-drop-order.rs
Auto merge of #99612 - yanchen4791:issue-95079-fix, r=compiler-errors
[rust.git] / src / test / ui / binding / fn-arg-incomplete-pattern-drop-order.rs
1 // run-pass
2 // needs-unwind
3 // Check that partially moved from function parameters are dropped after the
4 // named bindings that move from them.
5
6 // ignore-wasm32-bare compiled with panic=abort by default
7
8 use std::{panic, cell::RefCell};
9
10 struct LogDrop<'a>(i32, Context<'a>);
11
12 #[derive(Copy, Clone)]
13 struct Context<'a> {
14     panic_on: i32,
15     drops: &'a RefCell<Vec<i32>>,
16 }
17
18 impl<'a> Context<'a> {
19     fn record_drop(self, index: i32) {
20         self.drops.borrow_mut().push(index);
21         if index == self.panic_on {
22             panic!();
23         }
24     }
25 }
26
27 impl<'a> Drop for LogDrop<'a> {
28     fn drop(&mut self) {
29         self.1.record_drop(self.0);
30     }
31 }
32
33 fn bindings_in_params((_x, _): (LogDrop, LogDrop), (_, _y): (LogDrop, LogDrop)) {}
34 fn bindings_with_let(a: (LogDrop, LogDrop), b: (LogDrop, LogDrop)) {
35     // Drop order in foo is the same as the following bindings.
36     // _temp2 is declared after _x to avoid a difference between `_: T` and
37     // `x: T` in function parameters.
38     let _temp1 = a;
39     let (_x, _) = _temp1;
40
41     let _temp2 = b;
42     let (_, _y) = _temp2;
43 }
44
45 fn test_drop_order(panic_on: i32, fun: fn((LogDrop, LogDrop), (LogDrop, LogDrop))) {
46     let context = Context {
47         panic_on,
48         drops: &RefCell::new(Vec::new()),
49     };
50     let one = LogDrop(1, context);
51     let two = LogDrop(2, context);
52     let three = LogDrop(3, context);
53     let four = LogDrop(4, context);
54
55     let res = panic::catch_unwind(panic::AssertUnwindSafe(|| {
56         fun((three, four), (two, one));
57     }));
58     if panic_on == 0 {
59         assert!(res.is_ok(), "should not have panicked");
60     } else {
61         assert!(res.is_err(), "should have panicked");
62     }
63     assert_eq!(*context.drops.borrow(), [1, 2, 3, 4], "incorrect drop order");
64 }
65
66 fn main() {
67     (0..=4).for_each(|i| test_drop_order(i, bindings_in_params));
68     (0..=4).for_each(|i| test_drop_order(i, bindings_with_let));
69     (0..=4).for_each(|i| test_drop_order(i, |(_x, _), (_, _y)| {}));
70 }