solar_interface/
panic_hook.rs1use crate::diagnostics::{DiagCtxt, ExplicitBug, FatalAbort, flush_withheld};
4use std::panic::PanicHookInfo;
5
6const BUG_REPORT_URL: &str =
7 "https://github.com/paradigmxyz/solar/issues/new/?labels=C-bug%2C+I-ICE&template=ice.yml";
8
9pub fn install() {
11 if std::env::var_os("RUST_BACKTRACE").is_none() {
12 unsafe { std::env::set_var("RUST_BACKTRACE", "1") };
13 }
14
15 update_hook(|default_hook, info| {
16 if info.payload().is::<FatalAbort>() {
17 std::process::exit(1);
18 }
19
20 flush_withheld();
22
23 let _guard = std::io::stderr().lock();
25
26 default_hook(info);
27
28 eprintln!();
30
31 panic_hook(info);
32 });
33}
34
35fn panic_hook(info: &PanicHookInfo<'_>) {
36 let dcx = DiagCtxt::new_early();
37
38 if !info.payload().is::<ExplicitBug>() {
40 dcx.err("the compiler unexpectedly panicked; this is a bug.").emit();
41 }
42
43 dcx.note(format!("we would appreciate a bug report: {BUG_REPORT_URL}")).emit();
44}
45
46#[cfg(feature = "nightly")]
47use std::panic::update_hook;
48
49#[cfg(not(feature = "nightly"))]
51fn update_hook<F>(hook_fn: F)
52where
53 F: Fn(&(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static), &PanicHookInfo<'_>)
54 + Sync
55 + Send
56 + 'static,
57{
58 let default_hook = std::panic::take_hook();
59 std::panic::set_hook(Box::new(move |info| hook_fn(&default_hook, info)));
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65 use snapbox::{assert_data_eq, str};
66 use std::process::Command;
67
68 const TEST: &str = "panic_hook::tests::ice_prints_withheld_diagnostics_first";
69 const CHILD: &str = "SOLAR_PANIC_HOOK_TEST_CHILD";
70
71 #[test]
73 fn ice_prints_withheld_diagnostics_first() {
74 if std::env::var_os(CHILD).is_some() {
75 install();
76 let dcx = DiagCtxt::with_stderr_emitter(None).with_flags(|flags| {
77 flags.track_diagnostics = false;
78 });
79 let (_, _withheld) = dcx.defer(|| dcx.err("earlier error").emit());
81 panic!("boom");
82 }
83
84 let output = Command::new(std::env::current_exe().unwrap())
85 .args(["--exact", TEST, "--nocapture", "--test-threads=1"])
86 .env(CHILD, "1")
87 .output()
88 .unwrap();
89 assert!(!output.status.success());
90 assert_data_eq!(
91 String::from_utf8(output.stderr).unwrap(),
92 str![[r#"
93...
94error: earlier error
95
96...
97boom
98...
99error: the compiler unexpectedly panicked; this is a bug.
100...
101"#]]
102 );
103 }
104}