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

Debug-format fat pointers with their metadata for better insight #93544

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
40 changes: 38 additions & 2 deletions library/core/src/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::cell::{Cell, Ref, RefCell, RefMut, UnsafeCell};
use crate::char::EscapeDebugExtArgs;
use crate::marker::PhantomData;
use crate::mem;
use crate::ptr::{self, DynMetadata};
use crate::num::fmt as numfmt;
use crate::ops::Deref;
use crate::result;
Expand Down Expand Up @@ -2281,16 +2282,51 @@ impl<T: ?Sized> Pointer for &mut T {

// Implementation of Display/Debug for various core types

/// A local trait for pointer Debug impl so that we can have
/// min_specialization-compliant specializations for two types of fat ptrs.
trait PtrMetadataFmt {
fn fmt_ptr(&self, ptr: *const (), f: &mut Formatter<'_>) -> Result;
}

// Regular pointer / default impl
impl<T> PtrMetadataFmt for T {
Comment on lines +2291 to +2292
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should be able to improve this in one of two ways:

  • split the () case from the default:
    • () is "guaranteed simple" (but maybe specializing on the original pointee being Sized would be stronger)
    • the default would only be hit by custom DSTs (and unreachable today? could print some indication of metadata existing but not being understood, or just fit an unreachable!() in there)
  • add a new sealed trait, and a bound for it on Pointee::Metadata (just like it requires Copy, Eq, etc. today)
    • ("sealed" as in a pub trait in a private mod, not nameable outside core - for now, anyway)
    • the new trait could just be this PR's PtrMetadataFmt for now, even if we may want to change it in the future (see below)
    • no specialization should be needed, since Pointee would be claiming it's always implemented for valid metadata types
    • whenever we get custom DSTs, it would be a nice bonus to force the user to implement such a trait, effectively making them decide how raw pointers to their custom DST should be formatted
      • this is when we'd remove the "sealing"
      • maybe it should just be a fmt::Debug bound and not let the user see the data pointer or choose how it is printed?
      • but this part is really all a bikshed for the future

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know exactly what you mean, in fact, I've been meaning to propose in #81513 that Pointee::Metadata should maybe be its own trait (and yeah initially sealed by all means), which could enable attaching arbitrary things to it that might be needed in the future, be it debug printing or something else.

I initially did try the fmt::Debug bound approach but I think there was issues with it, altough I don't remember off the top of my head at the moment...

Copy link
Contributor Author

@vojtechkral vojtechkral Feb 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I initially did try the fmt::Debug bound approach but I think there was issues with it, altough I don't remember off the top of my head at the moment...

Right, because Debug on Pointee::Metadata gets me the ability to debug-print the metadata, but in this case I need to format the whole pointer+metadata combo somehow, ideally preserving the simple "just hex number" format for simple pointers...

Edit: But I could use a custom sealed trait, sure, I'll try that later and wil update...

#[inline]
default fn fmt_ptr(&self, ptr: *const (), f: &mut Formatter<'_>) -> Result {
Pointer::fmt(&ptr, f)
}
}

// Pointer + length
impl PtrMetadataFmt for usize {
#[inline]
fn fmt_ptr(&self, ptr: *const (), f: &mut Formatter<'_>) -> Result {
write!(f, "({:p}, {})", ptr, *self)
Copy link
Member

@eddyb eddyb Feb 8, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(bikeshedding) I wonder how silly something like *[_] { data: 0x..., len: 123 } would be. (and have meta instead of len in the general case, I guess?)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I understand, what's the *[_] part?

}
}

// Pointer + vtable
impl<Dyn: ?Sized> PtrMetadataFmt for DynMetadata<Dyn> {
#[inline]
fn fmt_ptr(&self, ptr: *const (), f: &mut Formatter<'_>) -> Result {
f.debug_tuple("")
.field(&ptr)
.field(self)
.finish()
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Debug for *const T {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
Pointer::fmt(self, f)
let meta = ptr::metadata(*self);
meta.fmt_ptr(*self as *const (), f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Debug for *mut T {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
Pointer::fmt(self, f)
let ptr: *const T = *self;
Debug::fmt(&ptr, f)
}
}

Expand Down
38 changes: 36 additions & 2 deletions library/core/tests/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ mod builders;
mod float;
mod num;

use core::any::Any;
use core::fmt;
use core::ptr;

#[test]
fn test_format_flags() {
// No residual flags left by pointer formatting
Expand All @@ -19,6 +23,36 @@ fn test_pointer_formats_data_pointer() {
assert_eq!(format!("{:p}", b), format!("{:p}", b.as_ptr()));
}

#[test]
fn test_pointer_formats_debug_thin() {
let thinptr = &42 as *const i32;
assert_eq!(format!("{:?}", thinptr as *const ()), format!("{:p}", thinptr));
}

#[test]
fn test_pointer_formats_debug_slice() {
let b: &[u8] = b"hello";
let s: &str = "hello";
let b_ptr = &*b as *const _;
let s_ptr = &*s as *const _;
assert_eq!(format!("{:?}", b_ptr), format!("({:?}, 5)", b.as_ptr()));
assert_eq!(format!("{:?}", s_ptr), format!("({:?}, 5)", s.as_ptr()));

// :p should format as a thin pointer / without metadata
assert_eq!(format!("{:p}", b_ptr), format!("{:p}", b.as_ptr()));
assert_eq!(format!("{:p}", s_ptr), format!("{:p}", s.as_ptr()));
}

#[test]
fn test_pointer_formats_debug_trait_object() {
let mut any: Box<dyn Any> = Box::new(42);
let dyn_ptr = &mut *any as *mut dyn Any;
assert_eq!(format!("{:?}", dyn_ptr), format!("({:?}, {:?})", dyn_ptr as *const (), ptr::metadata(dyn_ptr)));

// :p should format as a thin pointer / without metadata
assert_eq!(format!("{:p}", dyn_ptr), format!("{:p}", dyn_ptr as *const ()));
}

#[test]
fn test_estimated_capacity() {
assert_eq!(format_args!("").estimated_capacity(), 0);
Expand All @@ -33,8 +67,8 @@ fn test_estimated_capacity() {
fn pad_integral_resets() {
struct Bar;

impl core::fmt::Display for Bar {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
impl fmt::Display for Bar {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
"1".fmt(f)?;
f.pad_integral(true, "", "5")?;
"1".fmt(f)
Expand Down