rust-analyzer/crates/stdx/src/panic_context.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

52 lines
1.3 KiB
Rust
Raw Normal View History

//! A micro-crate to enhance panic messages with context info.
//!
//! FIXME: upstream to <https://github.com/kriomant/panic-context> ?
use std::{cell::RefCell, panic, sync::Once};
2020-10-23 13:18:33 +00:00
pub fn enter(context: String) -> PanicContext {
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 {
_priv: (),
}
impl PanicContext {
#[allow(clippy::print_stderr)]
fn init() {
let default_hook = panic::take_hook();
#[allow(deprecated)]
let hook = move |panic_info: &panic::PanicInfo<'_>| {
with_ctx(|ctx| {
if !ctx.is_empty() {
eprintln!("Panic context:");
for frame in ctx.iter() {
eprintln!("> {frame}\n");
}
}
default_hook(panic_info);
});
};
panic::set_hook(Box::new(hook));
}
}
impl Drop for PanicContext {
fn drop(&mut self) {
with_ctx(|ctx| assert!(ctx.pop().is_some()));
}
}
fn with_ctx(f: impl FnOnce(&mut Vec<String>)) {
thread_local! {
static CTX: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
CTX.with(|ctx| f(&mut ctx.borrow_mut()));
}