]> git.lizzy.rs Git - rust.git/blob - src/test/ui/rfc-2091-track-caller/std-panic-locations.rs
Auto merge of #102164 - compiler-errors:rpitit-foreign, r=TaKO8Ki
[rust.git] / src / test / ui / rfc-2091-track-caller / std-panic-locations.rs
1 // run-pass
2 // needs-unwind
3 // revisions: default mir-opt
4 //[mir-opt] compile-flags: -Zmir-opt-level=4
5
6 #![allow(unconditional_panic)]
7
8 //! Test that panic locations for `#[track_caller]` functions in std have the correct
9 //! location reported.
10
11 use std::cell::RefCell;
12 use std::collections::{BTreeMap, HashMap, VecDeque};
13 use std::ops::{Index, IndexMut};
14 use std::panic::{AssertUnwindSafe, UnwindSafe};
15
16 fn main() {
17     // inspect the `PanicInfo` we receive to ensure the right file is the source
18     std::panic::set_hook(Box::new(|info| {
19         let actual = info.location().unwrap();
20         if actual.file() != file!() {
21             eprintln!("expected a location in the test file, found {:?}", actual);
22             panic!();
23         }
24     }));
25
26     fn assert_panicked(f: impl FnOnce() + UnwindSafe) {
27         std::panic::catch_unwind(f).unwrap_err();
28     }
29
30     let nope: Option<()> = None;
31     assert_panicked(|| nope.unwrap());
32     assert_panicked(|| nope.expect(""));
33
34     let oops: Result<(), ()> = Err(());
35     assert_panicked(|| oops.unwrap());
36     assert_panicked(|| oops.expect(""));
37
38     let fine: Result<(), ()> = Ok(());
39     assert_panicked(|| fine.unwrap_err());
40     assert_panicked(|| fine.expect_err(""));
41
42     let mut small = [0]; // the implementation backing str, vec, etc
43     assert_panicked(move || { small.index(1); });
44     assert_panicked(move || { small[1]; });
45     assert_panicked(move || { small.index_mut(1); });
46     assert_panicked(move || { small[1] += 1; });
47
48     let sorted: BTreeMap<bool, bool> = Default::default();
49     assert_panicked(|| { sorted.index(&false); });
50     assert_panicked(|| { sorted[&false]; });
51
52     let unsorted: HashMap<bool, bool> = Default::default();
53     assert_panicked(|| { unsorted.index(&false); });
54     assert_panicked(|| { unsorted[&false]; });
55
56     let weirdo: VecDeque<()> = Default::default();
57     assert_panicked(|| { weirdo.index(1); });
58     assert_panicked(|| { weirdo[1]; });
59
60     let refcell: RefCell<()> = Default::default();
61     let _conflicting = refcell.borrow_mut();
62     assert_panicked(AssertUnwindSafe(|| { refcell.borrow(); }));
63     assert_panicked(AssertUnwindSafe(|| { refcell.borrow_mut(); }));
64 }