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