mirror of
https://github.com/torvalds/linux.git
synced 2026-11-07 06:17:02 +01:00
rust: pin-init: internal: improve diagnostics robustness against panicking
Currently, if proc macro panicked, the diagnostics clean up is not executed, and further invocation will cause the "DiagCtxt cannot be nested" error. While we should aim to have no panics inside proc macros, producing a sensible diagnostics message even when macro panicked is very useful for developing. Thus, catch proc macro panics and convert them to errors, and emit them together with all diagnostics accumulated so far. Ideally we would like panic location w/ line numbers being available as well; however this is not currently implementable without overriding the global panic hook. Reviewed-by: Benno Lossin <lossin@kernel.org> Link: https://patch.msgid.link/20260923140618.1978181-3-gary@kernel.org Signed-off-by: Gary Guo <gary@garyguo.net>
This commit is contained in:
parent
73c1f15790
commit
95593ed361
|
|
@ -4,7 +4,7 @@
|
|||
use std::fmt::Display;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use proc_macro2::TokenStream;
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::{quote, quote_spanned};
|
||||
use syn::{spanned::Spanned, Error};
|
||||
|
||||
|
|
@ -77,7 +77,27 @@ fn with(
|
|||
});
|
||||
});
|
||||
|
||||
let result = f(&mut DiagCtxt(PhantomData));
|
||||
let mut dcx = DiagCtxt(PhantomData);
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&mut dcx))) {
|
||||
Ok(result) => result,
|
||||
Err(payload) => {
|
||||
// Robustness against panicking in macros.
|
||||
//
|
||||
// Ensure that any error messages are still emitted when this happens.
|
||||
let message = if let Some(&s) = payload.downcast_ref::<&'static str>() {
|
||||
s
|
||||
} else if let Some(s) = payload.downcast_ref::<String>() {
|
||||
s.as_str()
|
||||
} else {
|
||||
"Box<dyn Any>"
|
||||
};
|
||||
|
||||
Err(dcx.error(
|
||||
Span::mixed_site(),
|
||||
format!("proc macro panicked: {message}"),
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
let data = DIAGNOSTICS.with_borrow_mut(|data| data.take().unwrap());
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user