Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split core's PanicInfo and std's PanicInfo #115974

Merged
merged 24 commits into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
e3e8153
Split core's PanicInfo and std's PanicInfo.
m-ou-se Sep 19, 2023
a519dc8
Document difference between core and std's PanicInfo.
m-ou-se Sep 26, 2023
16dfc6d
Add core::panic::PanicInfo::payload() for compatibility.
m-ou-se Sep 26, 2023
331b8a3
Fix doc link.
m-ou-se Sep 26, 2023
83dd214
Update doc comment about core::panicking.
m-ou-se Oct 2, 2023
0266bbf
Remove core::panic::PanicInfo::internal_constructor.
m-ou-se Oct 2, 2023
0642cb2
Remove std::panic::PanicInfo::internal_constructor+set_payload.
m-ou-se Oct 2, 2023
0087d89
Mark some PanicInfo methods as #[inline] for consistency.
m-ou-se Oct 2, 2023
4e356f3
Move downcasting panic payload to str to a function.
m-ou-se Oct 2, 2023
22f7399
Use unnamed lifetimes for [..]Payload impl blocks.
m-ou-se Oct 2, 2023
1642de3
Impl Display for PanicPayload to simplify things.
m-ou-se Oct 2, 2023
bab26b0
Reorder body of begin_panic for consistency.
m-ou-se Oct 2, 2023
6b2d7c4
Fix invalid markdown/html.
m-ou-se Oct 2, 2023
b6180a9
Formatting.
m-ou-se Jan 31, 2024
64e56db
Rename std::panic::PanicInfo to PanicHookInfo.
m-ou-se Jan 31, 2024
3854357
Fix deprecation version.
m-ou-se Jan 31, 2024
f5fe82f
Move deprecation of std::panic::PanicInfo to 1.80.0.
m-ou-se Jan 31, 2024
ce0bc8b
Downcast panic payload to String too in example.
m-ou-se May 16, 2024
32bfe70
Add note on panic payload type.
m-ou-se May 16, 2024
877a26f
Mention core's PanicInfo in error.md.
m-ou-se May 16, 2024
fb0990d
Fix display of panic message in recursive panic.
m-ou-se May 16, 2024
de07c1a
Add PanicHookInfo::payload_as_str().
m-ou-se May 16, 2024
a345c3d
Bump deprecation of std's PanicInfo alias to 1.82.0.
m-ou-se May 16, 2024
a6e23b1
Formatting.
m-ou-se Jun 11, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions compiler/rustc_driver_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ use std::ffi::OsString;
use std::fmt::Write as _;
use std::fs::{self, File};
use std::io::{self, IsTerminal, Read, Write};
use std::panic::{self, catch_unwind, PanicInfo};
use std::panic::{self, catch_unwind, PanicHookInfo};
use std::path::PathBuf;
use std::process::{self, Command, Stdio};
use std::str;
Expand Down Expand Up @@ -1366,11 +1366,10 @@ pub fn install_ice_hook(
let using_internal_features = Arc::new(std::sync::atomic::AtomicBool::default());
let using_internal_features_hook = using_internal_features.clone();
panic::update_hook(Box::new(
move |default_hook: &(dyn Fn(&PanicInfo<'_>) + Send + Sync + 'static),
info: &PanicInfo<'_>| {
move |default_hook: &(dyn Fn(&PanicHookInfo<'_>) + Send + Sync + 'static),
info: &PanicHookInfo<'_>| {
// Lock stderr to prevent interleaving of concurrent panics.
let _guard = io::stderr().lock();

// If the error was caused by a broken pipe then this is not a bug.
// Write the error and return immediately. See #98700.
#[cfg(windows)]
Expand Down Expand Up @@ -1431,7 +1430,7 @@ pub fn install_ice_hook(
/// When `install_ice_hook` is called, this function will be called as the panic
/// hook.
fn report_ice(
info: &panic::PanicInfo<'_>,
info: &panic::PanicHookInfo<'_>,
bug_report_url: &str,
extra_info: fn(&DiagCtxt),
using_internal_features: &AtomicBool,
Expand Down
5 changes: 3 additions & 2 deletions library/core/src/error.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ The following are the primary interfaces of the panic system and the
responsibilities they cover:

* [`panic!`] and [`panic_any`] (Constructing, Propagated automatically)
* [`PanicInfo`] (Reporting)
* [`set_hook`], [`take_hook`], and [`#[panic_handler]`][panic-handler] (Reporting)
* [`set_hook`], [`take_hook`], and [`PanicHookInfo`] (Reporting)
* [`#[panic_handler]`][panic-handler] and [`PanicInfo`] (Reporting in no_std)
* [`catch_unwind`] and [`resume_unwind`] (Discarding, Propagating)

The following are the primary interfaces of the error system and the
Expand Down Expand Up @@ -125,6 +125,7 @@ expect-as-precondition style error messages remember to focus on the word
should be available and executable by the current user".

[`panic_any`]: ../../std/panic/fn.panic_any.html
[`PanicHookInfo`]: ../../std/panic/struct.PanicHookInfo.html
[`PanicInfo`]: crate::panic::PanicInfo
[`catch_unwind`]: ../../std/panic/fn.catch_unwind.html
[`resume_unwind`]: ../../std/panic/fn.resume_unwind.html
Expand Down
7 changes: 6 additions & 1 deletion library/core/src/panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ pub macro unreachable_2021 {
/// use.
#[unstable(feature = "std_internals", issue = "none")]
#[doc(hidden)]
pub unsafe trait PanicPayload {
pub unsafe trait PanicPayload: crate::fmt::Display {
/// Take full ownership of the contents.
/// The return type is actually `Box<dyn Any + Send>`, but we cannot use `Box` in core.
///
Expand All @@ -157,4 +157,9 @@ pub unsafe trait PanicPayload {

/// Just borrow the contents.
fn get(&mut self) -> &(dyn Any + Send);

/// Try to borrow the contents as `&str`, if possible without doing any allocations.
fn as_str(&mut self) -> Option<&str> {
None
}
}
3 changes: 2 additions & 1 deletion library/core/src/panic/location.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ use crate::fmt;

/// A struct containing information about the location of a panic.
///
/// This structure is created by [`PanicInfo::location()`].
/// This structure is created by [`PanicHookInfo::location()`] and [`PanicInfo::location()`].
///
/// [`PanicInfo::location()`]: crate::panic::PanicInfo::location
/// [`PanicHookInfo::location()`]: ../../std/panic/struct.PanicHookInfo.html#method.location
///
/// # Examples
///
Expand Down
106 changes: 28 additions & 78 deletions library/core/src/panic/panic_info.rs
Original file line number Diff line number Diff line change
@@ -1,98 +1,40 @@
use crate::any::Any;
use crate::fmt;
use crate::panic::Location;

/// A struct providing information about a panic.
///
/// `PanicInfo` structure is passed to a panic hook set by the [`set_hook`]
/// function.
/// A `PanicInfo` structure is passed to the panic handler defined by `#[panic_handler]`.
///
/// [`set_hook`]: ../../std/panic/fn.set_hook.html
/// For the type used by the panic hook mechanism in `std`, see [`std::panic::PanicHookInfo`].
///
/// # Examples
///
/// ```should_panic
/// use std::panic;
///
/// panic::set_hook(Box::new(|panic_info| {
/// println!("panic occurred: {panic_info}");
/// }));
///
/// panic!("critical system failure");
/// ```
/// [`std::panic::PanicHookInfo`]: ../../std/panic/struct.PanicHookInfo.html
#[lang = "panic_info"]
#[stable(feature = "panic_hooks", since = "1.10.0")]
#[derive(Debug)]
pub struct PanicInfo<'a> {
payload: &'a (dyn Any + Send),
message: Option<&'a fmt::Arguments<'a>>,
message: fmt::Arguments<'a>,
location: &'a Location<'a>,
can_unwind: bool,
force_no_backtrace: bool,
}

impl<'a> PanicInfo<'a> {
#[unstable(
feature = "panic_internals",
reason = "internal details of the implementation of the `panic!` and related macros",
issue = "none"
)]
#[doc(hidden)]
#[inline]
pub fn internal_constructor(
message: Option<&'a fmt::Arguments<'a>>,
pub(crate) fn new(
message: fmt::Arguments<'a>,
location: &'a Location<'a>,
can_unwind: bool,
force_no_backtrace: bool,
) -> Self {
struct NoPayload;
PanicInfo { location, message, payload: &NoPayload, can_unwind, force_no_backtrace }
}

#[unstable(
feature = "panic_internals",
reason = "internal details of the implementation of the `panic!` and related macros",
issue = "none"
)]
#[doc(hidden)]
#[inline]
pub fn set_payload(&mut self, info: &'a (dyn Any + Send)) {
self.payload = info;
}

/// Returns the payload associated with the panic.
///
/// This will commonly, but not always, be a `&'static str` or [`String`].
///
/// [`String`]: ../../std/string/struct.String.html
///
/// # Examples
///
/// ```should_panic
/// use std::panic;
///
/// panic::set_hook(Box::new(|panic_info| {
/// if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
/// println!("panic occurred: {s:?}");
/// } else {
/// println!("panic occurred");
/// }
/// }));
///
/// panic!("Normal panic");
/// ```
#[must_use]
#[stable(feature = "panic_hooks", since = "1.10.0")]
pub fn payload(&self) -> &(dyn Any + Send) {
self.payload
PanicInfo { location, message, can_unwind, force_no_backtrace }
}

/// If the `panic!` macro from the `core` crate (not from `std`)
/// was used with a formatting string and some additional arguments,
/// returns that message ready to be used for example with [`fmt::write`]
#[must_use]
m-ou-se marked this conversation as resolved.
Show resolved Hide resolved
#[unstable(feature = "panic_info_message", issue = "66745")]
pub fn message(&self) -> Option<&fmt::Arguments<'_>> {
pub fn message(&self) -> fmt::Arguments<'_> {
self.message
}

Expand Down Expand Up @@ -128,6 +70,24 @@ impl<'a> PanicInfo<'a> {
Some(&self.location)
}

/// Returns the payload associated with the panic.
///
/// On `core::panic::PanicInfo`, this method never returns anything useful.
/// It only exists because of compatibility with [`std::panic::PanicHookInfo`],
m-ou-se marked this conversation as resolved.
Show resolved Hide resolved
/// which used to be the same type.
///
/// See [`std::panic::PanicHookInfo::payload`].
///
/// [`std::panic::PanicHookInfo`]: ../../std/panic/struct.PanicHookInfo.html
/// [`std::panic::PanicHookInfo::payload`]: ../../std/panic/struct.PanicHookInfo.html#method.payload
#[deprecated(since = "1.77.0", note = "this never returns anything useful")]
#[stable(feature = "panic_hooks", since = "1.10.0")]
m-ou-se marked this conversation as resolved.
Show resolved Hide resolved
#[allow(deprecated, deprecated_in_future)]
pub fn payload(&self) -> &(dyn crate::any::Any + Send) {
struct NoPayload;
&NoPayload
}

/// Returns whether the panic handler is allowed to unwind the stack from
/// the point where the panic occurred.
///
Expand Down Expand Up @@ -161,18 +121,8 @@ impl fmt::Display for PanicInfo<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("panicked at ")?;
self.location.fmt(formatter)?;
formatter.write_str(":")?;
if let Some(message) = self.message {
formatter.write_str("\n")?;
formatter.write_fmt(*message)?;
} else if let Some(payload) = self.payload.downcast_ref::<&'static str>() {
formatter.write_str("\n")?;
formatter.write_str(payload)?;
}
// NOTE: we cannot use downcast_ref::<String>() here
// since String is not available in core!
// The payload is a String when `std::panic!` is called with multiple arguments,
// but in that case the message is also available.
formatter.write_str(":\n")?;
formatter.write_fmt(self.message)?;
Ok(())
}
}
24 changes: 13 additions & 11 deletions library/core/src/panicking.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
//! Panic support for core
//!
//! The core library cannot define panicking, but it does *declare* panicking. This
//! means that the functions inside of core are allowed to panic, but to be
//! In core, panicking is always done with a message, resulting in a `core::panic::PanicInfo`
//! containing a `fmt::Arguments`. In std, however, panicking can be done with panic_any, which
//! throws a `Box<dyn Any>` containing any type of value. Because of this,
//! `std::panic::PanicHookInfo` is a different type, which contains a `&dyn Any` instead of a
//! `fmt::Arguments`. std's panic handler will convert the `fmt::Arguments` to a `&dyn Any`
//! containing either a `&'static str` or `String` containing the formatted message.
//!
//! The core library cannot define any panic handler, but it can invoke it.
//! This means that the functions inside of core are allowed to panic, but to be
//! useful an upstream crate must define panicking for core to use. The current
//! interface for panicking is:
//!
Expand All @@ -10,11 +17,6 @@
//! # { loop {} }
//! ```
//!
//! This definition allows for panicking with any general message, but it does not
//! allow for failing with a `Box<Any>` value. (`PanicInfo` just contains a `&(dyn Any + Send)`,
//! for which we fill in a dummy value in `PanicInfo::internal_constructor`.)
//! The reason for this is that core is not allowed to allocate.
//!
//! This module contains a few other panicking functions, but these are just the
//! necessary lang items for the compiler. All panics are funneled through this
//! one function. The actual symbol is declared through the `#[panic_handler]` attribute.
Expand Down Expand Up @@ -61,8 +63,8 @@ pub const fn panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
fn panic_impl(pi: &PanicInfo<'_>) -> !;
}

let pi = PanicInfo::internal_constructor(
Some(&fmt),
let pi = PanicInfo::new(
fmt,
Location::caller(),
/* can_unwind */ true,
/* force_no_backtrace */ false,
Expand Down Expand Up @@ -99,8 +101,8 @@ pub const fn panic_nounwind_fmt(fmt: fmt::Arguments<'_>, force_no_backtrace: boo
}

// PanicInfo with the `can_unwind` flag set to false forces an abort.
let pi = PanicInfo::internal_constructor(
Some(&fmt),
let pi = PanicInfo::new(
fmt,
Location::caller(),
/* can_unwind */ false,
force_no_backtrace,
Expand Down
Loading
Loading