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

make ty::Ty: Debug not call the Display impl #107084

Closed
wants to merge 8 commits into from
Closed
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
6 changes: 3 additions & 3 deletions compiler/rustc_const_eval/src/interpret/validity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -772,9 +772,9 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
// MyNewtype and then the scalar in there).
match op.layout.abi {
Abi::Uninhabited => {
throw_validation_failure!(self.path,
{ "a value of uninhabited type {:?}", op.layout.ty }
);
ty::print::with_no_trimmed_paths!(throw_validation_failure!(self.path,
{ "a value of uninhabited type {}", op.layout.ty }
));
}
Abi::Scalar(scalar_layout) => {
if !scalar_layout.is_uninit_valid() {
Expand Down
7 changes: 3 additions & 4 deletions compiler/rustc_middle/src/mir/graphviz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use rustc_graphviz as dot;
use rustc_hir::def_id::DefId;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, TyCtxt};
use std::fmt::Debug;
use std::io::{self, Write};

use super::generic_graph::mir_fn_to_generic_graph;
Expand Down Expand Up @@ -122,13 +121,13 @@ fn write_graph_label<'tcx, W: std::fmt::Write>(
w,
r#"debug {} =&gt; {};<br align="left"/>"#,
var_debug_info.name,
escape(&var_debug_info.value),
dot::escape_html(&format!("{:?}", &var_debug_info.value)),
)?;
}

Ok(())
}

fn escape<T: Debug>(t: &T) -> String {
dot::escape_html(&format!("{:?}", t))
fn escape<T: Display>(t: &T) -> String {
dot::escape_html(&format!("{}", t))
}
16 changes: 11 additions & 5 deletions compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1061,7 +1061,7 @@ impl<'tcx> Debug for VarDebugInfoContents<'tcx> {
VarDebugInfoContents::Const(c) => write!(fmt, "{}", c),
VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p),
VarDebugInfoContents::Composite { ty, fragments } => {
write!(fmt, "{:?}{{ ", ty)?;
ty::print::with_no_trimmed_paths!(write!(fmt, "{}{{ ", ty))?;
for f in fragments.iter() {
write!(fmt, "{:?}, ", f)?;
}
Expand Down Expand Up @@ -1722,7 +1722,8 @@ impl Debug for Place<'_> {
write!(fmt, ")")?;
}
ProjectionElem::Field(field, ty) => {
write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
let ty = ty::print::with_no_trimmed_paths!(format!("{ty}"));
write!(fmt, ".{:?}: {})", field.index(), ty)?;
}
ProjectionElem::Index(ref index) => {
write!(fmt, "[{:?}]", index)?;
Expand Down Expand Up @@ -2009,15 +2010,19 @@ impl<'tcx> Debug for Rvalue<'tcx> {
}
Len(ref a) => write!(fmt, "Len({:?})", a),
Cast(ref kind, ref place, ref ty) => {
write!(fmt, "{:?} as {:?} ({:?})", place, ty, kind)
let ty = ty::print::with_no_trimmed_paths!(format!("{ty}"));
compiler-errors marked this conversation as resolved.
Show resolved Hide resolved
write!(fmt, "{:?} as {} ({:?})", place, ty, kind)
}
BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{:?}({:?}, {:?})", op, a, b),
CheckedBinaryOp(ref op, box (ref a, ref b)) => {
write!(fmt, "Checked{:?}({:?}, {:?})", op, a, b)
}
UnaryOp(ref op, ref a) => write!(fmt, "{:?}({:?})", op, a),
Discriminant(ref place) => write!(fmt, "discriminant({:?})", place),
NullaryOp(ref op, ref t) => write!(fmt, "{:?}({:?})", op, t),
NullaryOp(ref op, ref t) => {
let t = ty::print::with_no_trimmed_paths!(format!("{t}"));
write!(fmt, "{:?}({})", op, t)
}
ThreadLocalRef(did) => ty::tls::with(|tcx| {
let muta = tcx.static_mutability(did).unwrap().prefix_str();
write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
Expand Down Expand Up @@ -2144,7 +2149,8 @@ impl<'tcx> Debug for Rvalue<'tcx> {
}

ShallowInitBox(ref place, ref ty) => {
write!(fmt, "ShallowInitBox({:?}, {:?})", place, ty)
let ty = ty::print::with_no_trimmed_paths!(format!("{ty}"));
write!(fmt, "ShallowInitBox({:?}, {})", place, ty)
}
}
}
Expand Down
14 changes: 10 additions & 4 deletions compiler/rustc_middle/src/mir/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -582,8 +582,14 @@ fn write_scope_tree(

let mut_str = if local_decl.mutability == Mutability::Mut { "mut " } else { "" };

let mut indented_decl =
format!("{0:1$}let {2}{3:?}: {4:?}", INDENT, indent, mut_str, local, local_decl.ty);
let mut indented_decl = format!(
"{0:1$}let {2}{3:?}: {4}",
INDENT,
indent,
mut_str,
local,
ty::print::with_no_trimmed_paths!(format!("{}", local_decl.ty))
);
if let Some(user_ty) = &local_decl.user_ty {
for user_ty in user_ty.projections() {
write!(indented_decl, " as {:?}", user_ty).unwrap();
Expand Down Expand Up @@ -1049,11 +1055,11 @@ fn write_user_type_annotations(
for (index, annotation) in body.user_type_annotations.iter_enumerated() {
writeln!(
w,
"| {:?}: user_ty: {:?}, span: {}, inferred_ty: {:?}",
"| {:?}: user_ty: {:?}, span: {}, inferred_ty: {}",
index.index(),
annotation.user_ty,
tcx.sess.source_map().span_to_embeddable_string(annotation.span),
annotation.inferred_ty,
ty::print::with_no_trimmed_paths!(format!("{}", annotation.inferred_ty)),
)?;
}
if !body.user_type_annotations.is_empty() {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/structural_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ impl<'tcx> fmt::Debug for ty::TraitRef<'tcx> {

impl<'tcx> fmt::Debug for Ty<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
with_no_trimmed_paths!(fmt::Display::fmt(self, f))
with_no_trimmed_paths!(fmt::Debug::fmt(self.kind(), f))
}
}

Expand Down
13 changes: 12 additions & 1 deletion compiler/rustc_middle/src/ty/typeck_results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -703,7 +703,7 @@ impl<'tcx> CanonicalUserType<'tcx> {
/// A user-given type annotation attached to a constant. These arise
/// from constants that are named via paths, like `Foo::<A>::new` and
/// so forth.
#[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)]
#[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable)]
#[derive(Eq, Hash, HashStable, TypeFoldable, TypeVisitable, Lift)]
pub enum UserType<'tcx> {
Ty(Ty<'tcx>),
Expand All @@ -712,3 +712,14 @@ pub enum UserType<'tcx> {
/// given substitutions applied.
TypeOf(DefId, UserSubsts<'tcx>),
}

impl<'tcx> std::fmt::Debug for UserType<'tcx> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Ty(arg0) => {
ty::print::with_no_trimmed_paths!(f.write_fmt(format_args!("Ty({})", arg0)))
}
Self::TypeOf(arg0, arg1) => f.debug_tuple("TypeOf").field(arg0).field(arg1).finish(),
}
}
}
16 changes: 9 additions & 7 deletions compiler/rustc_passes/src/layout_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,15 @@ fn dump_layout_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribute) {
}

sym::debug => {
let normalized_ty = format!(
"{:?}",
tcx.normalize_erasing_regions(
param_env.with_reveal_all_normalized(tcx),
ty,
)
);
let normalized_ty =
rustc_middle::ty::print::with_no_trimmed_paths!(format!(
"{}",
tcx.normalize_erasing_regions(
param_env.with_reveal_all_normalized(tcx),
ty,
)
));

let ty_layout = format!("{:#?}", *ty_layout);
tcx.sess.emit_err(LayoutOf {
span: tcx.def_span(item_def_id.to_def_id()),
Expand Down
23 changes: 21 additions & 2 deletions compiler/rustc_target/src/abi/call/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -458,12 +458,18 @@ impl<'a, Ty> TyAndLayout<'a, Ty> {

/// Information about how to pass an argument to,
/// or return a value from, a function, under some ABI.
#[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
#[derive(PartialEq, Eq, Hash, HashStable_Generic)]
pub struct ArgAbi<'a, Ty> {
pub layout: TyAndLayout<'a, Ty>,
pub mode: PassMode,
}

impl<'a, Ty: fmt::Debug + fmt::Display> fmt::Debug for ArgAbi<'a, Ty> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ArgAbi").field("layout", &self.layout).field("mode", &self.mode).finish()
}
Copy link
Member

@RalfJung RalfJung Jan 27, 2023

Choose a reason for hiding this comment

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

Why does this become necessary?

EDIT: Oh I see, it's the new trait bounds on the TyAndLayout debug impl. That's unfortunate... but still, this seems like the best option then.

}

impl<'a, Ty> ArgAbi<'a, Ty> {
pub fn new(
cx: &impl HasDataLayout,
Expand Down Expand Up @@ -605,7 +611,7 @@ pub enum Conv {
///
/// I will do my best to describe this structure, but these
/// comments are reverse-engineered and may be inaccurate. -NDM
#[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)]
#[derive(PartialEq, Eq, Hash, HashStable_Generic)]
pub struct FnAbi<'a, Ty> {
/// The LLVM types of each argument.
pub args: Box<[ArgAbi<'a, Ty>]>,
Expand All @@ -626,6 +632,19 @@ pub struct FnAbi<'a, Ty> {
pub can_unwind: bool,
}

impl<'a, Ty: fmt::Debug + fmt::Display> fmt::Debug for FnAbi<'a, Ty> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FnAbi")
.field("args", &self.args)
.field("ret", &self.ret)
.field("c_variadic", &self.c_variadic)
.field("fixed_count", &self.fixed_count)
.field("conv", &self.conv)
.field("can_unwind", &self.can_unwind)
.finish()
}
}

/// Error produced by attempting to adjust a `FnAbi`, for a "foreign" ABI.
#[derive(Copy, Clone, Debug, HashStable_Generic)]
pub enum AdjustForForeignAbiError {
Expand Down
11 changes: 10 additions & 1 deletion compiler/rustc_target/src/abi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,21 @@ impl<'a> Layout<'a> {
/// to that obtained from `layout_of(ty)`, as we need to produce
/// layouts for which Rust types do not exist, such as enum variants
/// or synthetic fields of enums (i.e., discriminants) and fat pointers.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable_Generic)]
#[derive(Copy, Clone, PartialEq, Eq, Hash, HashStable_Generic)]
pub struct TyAndLayout<'a, Ty> {
pub ty: Ty,
pub layout: Layout<'a>,
}

impl<'a, Ty: fmt::Debug + fmt::Display> fmt::Debug for TyAndLayout<'a, Ty> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TyAndLayout")
.field("ty", &format_args!("{}", &self.ty))
.field("layout", &self.layout)
.finish()
}
}

impl<'a, Ty> Deref for TyAndLayout<'a, Ty> {
type Target = &'a LayoutS<VariantIdx>;
fn deref(&self) -> &&'a LayoutS<VariantIdx> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1652,7 +1652,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
);
} else {
err.note(&format!(
"`{}` is implemented for `{:?}`, but not for `{:?}`",
"`{}` is implemented for `{}`, but not for `{}`",
trait_pred.print_modifiers_and_trait_path(),
suggested_ty,
trait_pred.skip_binder().self_ty(),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_ty_utils/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -826,7 +826,7 @@ fn record_layout_for_printing_outlined<'tcx>(

// (delay format until we actually need it)
let record = |kind, packed, opt_discr_size, variants| {
let type_desc = format!("{:?}", layout.ty);
let type_desc = format!("{}", layout.ty);
cx.tcx.sess.code_stats.record_type_size(
kind,
type_desc,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,27 @@
/* generator_layout = GeneratorLayout {
field_tys: {
_0: GeneratorSavedTy {
ty: impl std::future::Future<Output = ()>,
ty: Alias(
Opaque,
AliasTy {
substs: [],
def_id: DefId(0:7 ~ async_await[672b]::a::{opaque#0}),
},
),
source_info: SourceInfo {
span: $DIR/async_await.rs:15:8: 15:14 (#9),
scope: scope[0],
},
ignore_for_traits: false,
},
_1: GeneratorSavedTy {
ty: impl std::future::Future<Output = ()>,
ty: Alias(
Opaque,
AliasTy {
substs: [],
def_id: DefId(0:7 ~ async_await[672b]::a::{opaque#0}),
},
),
source_info: SourceInfo {
span: $DIR/async_await.rs:16:8: 16:14 (#12),
scope: scope[0],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
/* generator_layout = GeneratorLayout {
field_tys: {
_0: GeneratorSavedTy {
ty: std::string::String,
ty: Adt(
std::string::String,
[],
),
source_info: SourceInfo {
span: $DIR/generator_drop_cleanup.rs:11:13: 11:15 (#0),
scope: scope[0],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
/* generator_layout = GeneratorLayout {
field_tys: {
_0: GeneratorSavedTy {
ty: HasDrop,
ty: Adt(
HasDrop,
[],
),
source_info: SourceInfo {
span: $DIR/generator_tiny.rs:20:13: 20:15 (#0),
scope: scope[0],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
- bb2: {
+ // + span: $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
+ // + user_ty: UserType(0)
+ // + literal: Const { ty: alloc::raw_vec::RawVec<u32>, val: Unevaluated(alloc::raw_vec::RawVec::<T>::NEW, [u32], None) }
+ // + literal: Const { ty: alloc::raw_vec::RawVec<u32>, val: Unevaluated(alloc::raw_vec::RawVec::<T>::NEW, [Uint(U32)], None) }
+ Deinit(_9); // scope 3 at $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
+ (_9.0: alloc::raw_vec::RawVec<u32>) = move _10; // scope 3 at $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
+ (_9.1: usize) = const 0_usize; // scope 3 at $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// MIR for `main` after built

| User Type Annotations
| 0: user_ty: Canonical { max_universe: U0, variables: [], value: TypeOf(DefId(0:3 ~ issue_99325[8f58]::function_with_bytes), UserSubsts { substs: [Const { ty: &'static [u8; 4], kind: Value(Branch([Leaf(0x41), Leaf(0x41), Leaf(0x41), Leaf(0x41)])) }], user_self_ty: None }) }, span: $DIR/issue_99325.rs:10:16: 10:46, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">}
| 1: user_ty: Canonical { max_universe: U0, variables: [], value: TypeOf(DefId(0:3 ~ issue_99325[8f58]::function_with_bytes), UserSubsts { substs: [Const { ty: &'static [u8; 4], kind: Unevaluated(UnevaluatedConst { def: WithOptConstParam { did: DefId(0:8 ~ issue_99325[8f58]::main::{constant#1}), const_param_did: Some(DefId(0:4 ~ issue_99325[8f58]::function_with_bytes::BYTES)) }, substs: [] }) }], user_self_ty: None }) }, span: $DIR/issue_99325.rs:11:16: 11:68, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">}
| 0: user_ty: Canonical { max_universe: U0, variables: [], value: TypeOf(DefId(0:3 ~ issue_99325[8f58]::function_with_bytes), UserSubsts { substs: [Const { ty: Ref(ReStatic, Array(Uint(U8), Const { ty: Uint(Usize), kind: Value(Leaf(0x00000004)) }), Not), kind: Value(Branch([Leaf(0x41), Leaf(0x41), Leaf(0x41), Leaf(0x41)])) }], user_self_ty: None }) }, span: $DIR/issue_99325.rs:11:16: 11:46, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">}
| 1: user_ty: Canonical { max_universe: U0, variables: [], value: TypeOf(DefId(0:3 ~ issue_99325[8f58]::function_with_bytes), UserSubsts { substs: [Const { ty: Ref(ReStatic, Array(Uint(U8), Const { ty: Uint(Usize), kind: Value(Leaf(0x00000004)) }), Not), kind: Unevaluated(UnevaluatedConst { def: WithOptConstParam { did: DefId(0:8 ~ issue_99325[8f58]::main::{constant#1}), const_param_did: Some(DefId(0:4 ~ issue_99325[8f58]::function_with_bytes::BYTES)) }, substs: [] }) }], user_self_ty: None }) }, span: $DIR/issue_99325.rs:12:16: 12:68, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">}
|
fn main() -> () {
let mut _0: (); // return place in scope 0 at $DIR/issue_99325.rs:+0:15: +0:15
Expand Down Expand Up @@ -71,7 +71,7 @@ fn main() -> () {
StorageLive(_4); // scope 0 at $DIR/issue_99325.rs:+1:16: +1:48
_4 = function_with_bytes::<&*b"AAAA">() -> [return: bb1, unwind: bb19]; // scope 0 at $DIR/issue_99325.rs:+1:16: +1:48
// mir::Constant
// + span: $DIR/issue_99325.rs:10:16: 10:46
// + span: $DIR/issue_99325.rs:11:16: 11:46
// + user_ty: UserType(0)
// + literal: Const { ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">}, val: Value(<ZST>) }
}
Expand Down Expand Up @@ -179,7 +179,7 @@ fn main() -> () {
StorageLive(_26); // scope 0 at $DIR/issue_99325.rs:+2:16: +2:70
_26 = function_with_bytes::<&*b"AAAA">() -> [return: bb10, unwind: bb19]; // scope 0 at $DIR/issue_99325.rs:+2:16: +2:70
// mir::Constant
// + span: $DIR/issue_99325.rs:11:16: 11:68
// + span: $DIR/issue_99325.rs:12:16: 12:68
// + user_ty: UserType(1)
// + literal: Const { ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">}, val: Value(<ZST>) }
}
Expand All @@ -190,7 +190,7 @@ fn main() -> () {
StorageLive(_28); // scope 0 at $DIR/issue_99325.rs:+2:72: +2:79
_28 = const b"AAAA"; // scope 0 at $DIR/issue_99325.rs:+2:72: +2:79
// mir::Constant
// + span: $DIR/issue_99325.rs:11:72: 11:79
// + span: $DIR/issue_99325.rs:12:72: 12:79
// + literal: Const { ty: &[u8; 4], val: Value(Scalar(alloc4)) }
_27 = &_28; // scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL
_24 = (move _25, move _27); // scope 0 at $SRC_DIR/core/src/macros/mod.rs:LL:COL
Expand Down
Loading