2020-09-29 18:08:27 +00:00
|
|
|
//! A micro-crate to enhance panic messages with context info.
|
|
|
|
//!
|
2021-06-14 04:57:10 +00:00
|
|
|
//! FIXME: upstream to <https://github.com/kriomant/panic-context> ?
|
2020-09-29 18:08:27 +00:00
|
|
|
|
|
|
|
use std::{cell::RefCell, panic, sync::Once};
|
|
|
|
|
2020-10-23 13:18:33 +00:00
|
|
|
pub fn enter(context: String) -> PanicContext {
|
2020-09-29 18:08:27 +00:00
|
|
|
static ONCE: Once = Once::new();
|
|
|
|
ONCE.call_once(PanicContext::init);
|
|
|
|
|
|
|
|
with_ctx(|ctx| ctx.push(context));
|
|
|
|
PanicContext { _priv: () }
|
|
|
|
}
|
|
|
|
|
|
|
|
#[must_use]
|
2020-10-23 13:18:33 +00:00
|
|
|
pub struct PanicContext {
|
2020-09-29 18:08:27 +00:00
|
|
|
_priv: (),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PanicContext {
|
2024-02-01 15:16:38 +00:00
|
|
|
#[allow(clippy::print_stderr)]
|
2020-09-29 18:08:27 +00:00
|
|
|
fn init() {
|
|
|
|
let default_hook = panic::take_hook();
|
2024-07-20 19:51:58 +00:00
|
|
|
#[allow(deprecated)]
|
2020-09-29 18:08:27 +00:00
|
|
|
let hook = move |panic_info: &panic::PanicInfo<'_>| {
|
|
|
|
with_ctx(|ctx| {
|
|
|
|
if !ctx.is_empty() {
|
|
|
|
eprintln!("Panic context:");
|
|
|
|
for frame in ctx.iter() {
|
2022-12-23 18:42:58 +00:00
|
|
|
eprintln!("> {frame}\n");
|
2020-09-29 18:08:27 +00:00
|
|
|
}
|
|
|
|
}
|
2021-10-03 12:39:43 +00:00
|
|
|
default_hook(panic_info);
|
|
|
|
});
|
2020-09-29 18:08:27 +00:00
|
|
|
};
|
2021-10-03 12:39:43 +00:00
|
|
|
panic::set_hook(Box::new(hook));
|
2020-09-29 18:08:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for PanicContext {
|
|
|
|
fn drop(&mut self) {
|
2021-10-03 12:39:43 +00:00
|
|
|
with_ctx(|ctx| assert!(ctx.pop().is_some()));
|
2020-09-29 18:08:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn with_ctx(f: impl FnOnce(&mut Vec<String>)) {
|
|
|
|
thread_local! {
|
2024-02-01 15:16:38 +00:00
|
|
|
static CTX: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
|
2020-09-29 18:08:27 +00:00
|
|
|
}
|
2022-12-23 07:51:52 +00:00
|
|
|
CTX.with(|ctx| f(&mut ctx.borrow_mut()));
|
2020-09-29 18:08:27 +00:00
|
|
|
}
|