Skip to content

Commit 7d1e416

Browse files
committed
Auto merge of #115661 - nnethercote:disentangle-Debug-Display, r=compiler-errors
Disentangle `Debug` and `Display` for `Ty`. The `Debug` impl for `Ty` just calls the `Display` impl for `Ty`. This is surprising and annoying. In particular, it means `Debug` doesn't show as much information as `Debug` for `TyKind` does. And `Debug` is used in some user-facing error messages, which seems bad. This commit changes the `Debug` impl for `Ty` to call the `Debug` impl for `TyKind`. It also does a number of follow-up changes to preserve existing output, many of which involve inserting `with_no_trimmed_paths!` calls. It also adds `Display` impls for `UserType` and `Canonical`. Some tests have changes to expected output: - Those that use the `rustc_abi(debug)` attribute. - Those that use the `rustc_layout(debug)` attribute. - Those that use the `EMIT_MIR` annotation. In each case the output is slightly uglier than before. This isn't ideal, but it's pretty weird (particularly for the attributes) that the output is using `Debug` in the first place. They're fairly obscure attributes (I hadn't heard of them) so I'm not worried by this. For `async-is-unwindsafe.stderr`, there is one line that now lacks a full path. This is a consistency improvement, because all the other mentions of `Context` in this test lack a path.
2 parents e39976f + 64ea8eb commit 7d1e416

27 files changed

+502
-77
lines changed

compiler/rustc_borrowck/src/nll.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use rustc_middle::mir::{
1010
Body, ClosureOutlivesSubject, ClosureRegionRequirements, LocalKind, Location, Promoted,
1111
START_BLOCK,
1212
};
13+
use rustc_middle::ty::print::with_no_trimmed_paths;
1314
use rustc_middle::ty::{self, OpaqueHiddenType, TyCtxt};
1415
use rustc_span::symbol::sym;
1516
use std::env;
@@ -441,7 +442,10 @@ fn for_each_region_constraint<'tcx>(
441442
let subject = match req.subject {
442443
ClosureOutlivesSubject::Region(subject) => format!("{subject:?}"),
443444
ClosureOutlivesSubject::Ty(ty) => {
444-
format!("{:?}", ty.instantiate(tcx, |vid| ty::Region::new_var(tcx, vid)))
445+
with_no_trimmed_paths!(format!(
446+
"{}",
447+
ty.instantiate(tcx, |vid| ty::Region::new_var(tcx, vid))
448+
))
445449
}
446450
};
447451
with_msg(format!("where {}: {:?}", subject, req.outlived_free_region,))?;

compiler/rustc_borrowck/src/universal_regions.rs

+17-4
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use rustc_hir::BodyOwnerKind;
2121
use rustc_index::IndexVec;
2222
use rustc_infer::infer::NllRegionVariableOrigin;
2323
use rustc_middle::ty::fold::TypeFoldable;
24+
use rustc_middle::ty::print::with_no_trimmed_paths;
2425
use rustc_middle::ty::{self, InlineConstArgs, InlineConstArgsParts, RegionVid, Ty, TyCtxt};
2526
use rustc_middle::ty::{GenericArgs, GenericArgsRef};
2627
use rustc_span::symbol::{kw, sym};
@@ -332,10 +333,16 @@ impl<'tcx> UniversalRegions<'tcx> {
332333
pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
333334
match self.defining_ty {
334335
DefiningTy::Closure(def_id, args) => {
336+
let v = with_no_trimmed_paths!(
337+
args[tcx.generics_of(def_id).parent_count..]
338+
.iter()
339+
.map(|arg| arg.to_string())
340+
.collect::<Vec<_>>()
341+
);
335342
err.note(format!(
336-
"defining type: {} with closure args {:#?}",
343+
"defining type: {} with closure args [\n {},\n]",
337344
tcx.def_path_str_with_args(def_id, args),
338-
&args[tcx.generics_of(def_id).parent_count..],
345+
v.join(",\n "),
339346
));
340347

341348
// FIXME: It'd be nice to print the late-bound regions
@@ -348,10 +355,16 @@ impl<'tcx> UniversalRegions<'tcx> {
348355
});
349356
}
350357
DefiningTy::Generator(def_id, args, _) => {
358+
let v = with_no_trimmed_paths!(
359+
args[tcx.generics_of(def_id).parent_count..]
360+
.iter()
361+
.map(|arg| arg.to_string())
362+
.collect::<Vec<_>>()
363+
);
351364
err.note(format!(
352-
"defining type: {} with generator args {:#?}",
365+
"defining type: {} with generator args [\n {},\n]",
353366
tcx.def_path_str_with_args(def_id, args),
354-
&args[tcx.generics_of(def_id).parent_count..],
367+
v.join(",\n "),
355368
));
356369

357370
// FIXME: As above, we'd like to print out the region

compiler/rustc_middle/src/infer/canonical.rs

+11
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ use crate::ty::GenericArg;
2727
use crate::ty::{self, BoundVar, List, Region, Ty, TyCtxt};
2828
use rustc_macros::HashStable;
2929
use smallvec::SmallVec;
30+
use std::fmt::Display;
3031
use std::ops::Index;
3132

3233
/// A "canonicalized" type `V` is one where all free inference
@@ -40,6 +41,16 @@ pub struct Canonical<'tcx, V> {
4041
pub variables: CanonicalVarInfos<'tcx>,
4142
}
4243

44+
impl<'tcx, V: Display> std::fmt::Display for Canonical<'tcx, V> {
45+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46+
write!(
47+
f,
48+
"Canonical {{ value: {}, max_universe: {:?}, variables: {:?} }}",
49+
self.value, self.max_universe, self.variables
50+
)
51+
}
52+
}
53+
4354
pub type CanonicalVarInfos<'tcx> = &'tcx List<CanonicalVarInfo<'tcx>>;
4455

4556
impl<'tcx> ty::TypeFoldable<TyCtxt<'tcx>> for CanonicalVarInfos<'tcx> {

compiler/rustc_middle/src/mir/mod.rs

+12-8
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use crate::mir::interpret::{
88
use crate::mir::visit::MirVisitable;
99
use crate::ty::codec::{TyDecoder, TyEncoder};
1010
use crate::ty::fold::{FallibleTypeFolder, TypeFoldable};
11+
use crate::ty::print::with_no_trimmed_paths;
1112
use crate::ty::print::{FmtPrinter, Printer};
1213
use crate::ty::visit::TypeVisitableExt;
1314
use crate::ty::{self, List, Ty, TyCtxt};
@@ -1794,7 +1795,7 @@ fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) ->
17941795
write!(fmt, ")")?;
17951796
}
17961797
ProjectionElem::Field(field, ty) => {
1797-
write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
1798+
with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
17981799
}
17991800
ProjectionElem::Index(ref index) => {
18001801
write!(fmt, "[{index:?}]")?;
@@ -2077,19 +2078,22 @@ impl<'tcx> Debug for Rvalue<'tcx> {
20772078
}
20782079
Len(ref a) => write!(fmt, "Len({a:?})"),
20792080
Cast(ref kind, ref place, ref ty) => {
2080-
write!(fmt, "{place:?} as {ty:?} ({kind:?})")
2081+
with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
20812082
}
20822083
BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"),
20832084
CheckedBinaryOp(ref op, box (ref a, ref b)) => {
20842085
write!(fmt, "Checked{op:?}({a:?}, {b:?})")
20852086
}
20862087
UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"),
20872088
Discriminant(ref place) => write!(fmt, "discriminant({place:?})"),
2088-
NullaryOp(ref op, ref t) => match op {
2089-
NullOp::SizeOf => write!(fmt, "SizeOf({t:?})"),
2090-
NullOp::AlignOf => write!(fmt, "AlignOf({t:?})"),
2091-
NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t:?}, {fields:?})"),
2092-
},
2089+
NullaryOp(ref op, ref t) => {
2090+
let t = with_no_trimmed_paths!(format!("{}", t));
2091+
match op {
2092+
NullOp::SizeOf => write!(fmt, "SizeOf({t})"),
2093+
NullOp::AlignOf => write!(fmt, "AlignOf({t})"),
2094+
NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t}, {fields:?})"),
2095+
}
2096+
}
20932097
ThreadLocalRef(did) => ty::tls::with(|tcx| {
20942098
let muta = tcx.static_mutability(did).unwrap().prefix_str();
20952099
write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
@@ -2225,7 +2229,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
22252229
}
22262230

22272231
ShallowInitBox(ref place, ref ty) => {
2228-
write!(fmt, "ShallowInitBox({place:?}, {ty:?})")
2232+
with_no_trimmed_paths!(write!(fmt, "ShallowInitBox({place:?}, {ty})"))
22292233
}
22302234
}
22312235
}

compiler/rustc_middle/src/mir/pretty.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -583,8 +583,10 @@ fn write_scope_tree(
583583

584584
let mut_str = local_decl.mutability.prefix_str();
585585

586-
let mut indented_decl =
587-
format!("{0:1$}let {2}{3:?}: {4:?}", INDENT, indent, mut_str, local, local_decl.ty);
586+
let mut indented_decl = ty::print::with_no_trimmed_paths!(format!(
587+
"{0:1$}let {2}{3:?}: {4}",
588+
INDENT, indent, mut_str, local, local_decl.ty
589+
));
588590
if let Some(user_ty) = &local_decl.user_ty {
589591
for user_ty in user_ty.projections() {
590592
write!(indented_decl, " as {user_ty:?}").unwrap();
@@ -1058,11 +1060,11 @@ fn write_user_type_annotations(
10581060
for (index, annotation) in body.user_type_annotations.iter_enumerated() {
10591061
writeln!(
10601062
w,
1061-
"| {:?}: user_ty: {:?}, span: {}, inferred_ty: {:?}",
1063+
"| {:?}: user_ty: {}, span: {}, inferred_ty: {}",
10621064
index.index(),
10631065
annotation.user_ty,
10641066
tcx.sess.source_map().span_to_embeddable_string(annotation.span),
1065-
annotation.inferred_ty,
1067+
with_no_trimmed_paths!(format!("{}", annotation.inferred_ty)),
10661068
)?;
10671069
}
10681070
if !body.user_type_annotations.is_empty() {

compiler/rustc_middle/src/ty/generic_args.rs

+5
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,11 @@ impl<'tcx> GenericArgs<'tcx> {
450450
pub fn host_effect_param(&'tcx self) -> Option<ty::Const<'tcx>> {
451451
self.consts().rfind(|x| matches!(x.kind(), ty::ConstKind::Param(p) if p.name == sym::host))
452452
}
453+
454+
pub fn print_as_list(&self) -> String {
455+
let v = self.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();
456+
format!("[{}]", v.join(", "))
457+
}
453458
}
454459

455460
impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for GenericArgsRef<'tcx> {

compiler/rustc_middle/src/ty/print/pretty.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -760,9 +760,12 @@ pub trait PrettyPrinter<'tcx>:
760760
// only affect certain debug messages (e.g. messages printed
761761
// from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
762762
// and should have no effect on any compiler output.
763+
// [Unless `-Zverbose` is used, e.g. in the output of
764+
// `tests/ui/nll/ty-outlives/impl-trait-captures.rs`, for
765+
// example.]
763766
if self.should_print_verbose() {
764767
// FIXME(eddyb) print this with `print_def_path`.
765-
p!(write("Opaque({:?}, {:?})", def_id, args));
768+
p!(write("Opaque({:?}, {})", def_id, args.print_as_list()));
766769
return Ok(self);
767770
}
768771

@@ -894,7 +897,7 @@ pub trait PrettyPrinter<'tcx>:
894897
p!(print_def_path(did, args));
895898
if !args.as_closure().is_valid() {
896899
p!(" closure_args=(unavailable)");
897-
p!(write(" args={:?}", args));
900+
p!(write(" args={}", args.print_as_list()));
898901
} else {
899902
p!(" closure_kind_ty=", print(args.as_closure().kind_ty()));
900903
p!(

compiler/rustc_middle/src/ty/structural_impls.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ impl<'tcx> ty::DebugWithInfcx<TyCtxt<'tcx>> for Ty<'tcx> {
154154
}
155155
impl<'tcx> fmt::Debug for Ty<'tcx> {
156156
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157-
with_no_trimmed_paths!(fmt::Display::fmt(self, f))
157+
with_no_trimmed_paths!(fmt::Debug::fmt(self.kind(), f))
158158
}
159159
}
160160

compiler/rustc_middle/src/ty/typeck_results.rs

+11
Original file line numberDiff line numberDiff line change
@@ -722,3 +722,14 @@ pub enum UserType<'tcx> {
722722
/// given substitutions applied.
723723
TypeOf(DefId, UserArgs<'tcx>),
724724
}
725+
726+
impl<'tcx> std::fmt::Display for UserType<'tcx> {
727+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
728+
match self {
729+
Self::Ty(arg0) => {
730+
ty::print::with_no_trimmed_paths!(write!(f, "Ty({})", arg0))
731+
}
732+
Self::TypeOf(arg0, arg1) => write!(f, "TypeOf({:?}, {:?})", arg0, arg1),
733+
}
734+
}
735+
}

compiler/rustc_passes/src/abi_test.rs

+1
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ fn dump_abi_of_fn_item(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribut
8989
tcx.sess.emit_err(AbiOf {
9090
span: tcx.def_span(item_def_id),
9191
fn_name,
92+
// FIXME: using the `Debug` impl here isn't ideal.
9293
fn_abi: format!("{:#?}", abi),
9394
});
9495
}

compiler/rustc_passes/src/layout_test.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -107,12 +107,13 @@ fn dump_layout_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribute) {
107107

108108
sym::debug => {
109109
let normalized_ty = format!(
110-
"{:?}",
110+
"{}",
111111
tcx.normalize_erasing_regions(
112112
param_env.with_reveal_all_normalized(tcx),
113113
ty,
114114
)
115115
);
116+
// FIXME: using the `Debug` impl here isn't ideal.
116117
let ty_layout = format!("{:#?}", *ty_layout);
117118
tcx.sess.emit_err(LayoutOf { span, normalized_ty, ty_layout });
118119
}

compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1805,7 +1805,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
18051805
);
18061806
} else {
18071807
err.note(format!(
1808-
"`{}` is implemented for `{:?}`, but not for `{:?}`",
1808+
"`{}` is implemented for `{}`, but not for `{}`",
18091809
trait_pred.print_modifiers_and_trait_path(),
18101810
suggested_ty,
18111811
trait_pred.skip_binder().self_ty(),

compiler/rustc_ty_utils/src/layout.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use rustc_middle::query::Providers;
77
use rustc_middle::ty::layout::{
88
IntegerExt, LayoutCx, LayoutError, LayoutOf, TyAndLayout, MAX_SIMD_LANES,
99
};
10+
use rustc_middle::ty::print::with_no_trimmed_paths;
1011
use rustc_middle::ty::{
1112
self, AdtDef, EarlyBinder, GenericArgsRef, ReprOptions, Ty, TyCtxt, TypeVisitableExt,
1213
};
@@ -937,7 +938,7 @@ fn record_layout_for_printing_outlined<'tcx>(
937938

938939
// (delay format until we actually need it)
939940
let record = |kind, packed, opt_discr_size, variants| {
940-
let type_desc = format!("{:?}", layout.ty);
941+
let type_desc = with_no_trimmed_paths!(format!("{}", layout.ty));
941942
cx.tcx.sess.code_stats.record_type_size(
942943
kind,
943944
type_desc,

tests/mir-opt/building/async_await.b-{closure#0}.generator_resume.0.mir

+16-2
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,29 @@
22
/* generator_layout = GeneratorLayout {
33
field_tys: {
44
_0: GeneratorSavedTy {
5-
ty: impl std::future::Future<Output = ()>,
5+
ty: Alias(
6+
Opaque,
7+
AliasTy {
8+
args: [
9+
],
10+
def_id: DefId(0:7 ~ async_await[ccf8]::a::{opaque#0}),
11+
},
12+
),
613
source_info: SourceInfo {
714
span: $DIR/async_await.rs:15:9: 15:14 (#8),
815
scope: scope[0],
916
},
1017
ignore_for_traits: false,
1118
},
1219
_1: GeneratorSavedTy {
13-
ty: impl std::future::Future<Output = ()>,
20+
ty: Alias(
21+
Opaque,
22+
AliasTy {
23+
args: [
24+
],
25+
def_id: DefId(0:7 ~ async_await[ccf8]::a::{opaque#0}),
26+
},
27+
),
1428
source_info: SourceInfo {
1529
span: $DIR/async_await.rs:16:9: 16:14 (#10),
1630
scope: scope[0],

tests/mir-opt/generator_drop_cleanup.main-{closure#0}.generator_drop.0.panic-abort.mir

+5-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
/* generator_layout = GeneratorLayout {
33
field_tys: {
44
_0: GeneratorSavedTy {
5-
ty: std::string::String,
5+
ty: Adt(
6+
std::string::String,
7+
[
8+
],
9+
),
610
source_info: SourceInfo {
711
span: $DIR/generator_drop_cleanup.rs:11:13: 11:15 (#0),
812
scope: scope[0],

tests/mir-opt/generator_drop_cleanup.main-{closure#0}.generator_drop.0.panic-unwind.mir

+5-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
/* generator_layout = GeneratorLayout {
33
field_tys: {
44
_0: GeneratorSavedTy {
5-
ty: std::string::String,
5+
ty: Adt(
6+
std::string::String,
7+
[
8+
],
9+
),
610
source_info: SourceInfo {
711
span: $DIR/generator_drop_cleanup.rs:11:13: 11:15 (#0),
812
scope: scope[0],

tests/mir-opt/generator_tiny.main-{closure#0}.generator_resume.0.mir

+5-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22
/* generator_layout = GeneratorLayout {
33
field_tys: {
44
_0: GeneratorSavedTy {
5-
ty: HasDrop,
5+
ty: Adt(
6+
HasDrop,
7+
[
8+
],
9+
),
610
source_info: SourceInfo {
711
span: $DIR/generator_tiny.rs:20:13: 20:15 (#0),
812
scope: scope[0],

tests/mir-opt/issue_99325.main.built.after.mir renamed to tests/mir-opt/issue_99325.main.built.after.32bit.mir

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
// MIR for `main` after built
22

33
| User Type Annotations
4-
| 0: user_ty: Canonical { value: TypeOf(DefId(0:3 ~ issue_99325[22bb]::function_with_bytes), UserArgs { args: [Const { ty: &'static [u8; 4], kind: Branch([Leaf(0x41), Leaf(0x41), Leaf(0x41), Leaf(0x41)]) }], user_self_ty: None }), max_universe: U0, variables: [] }, span: $DIR/issue_99325.rs:10:16: 10:46, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">}
5-
| 1: user_ty: Canonical { value: TypeOf(DefId(0:3 ~ issue_99325[22bb]::function_with_bytes), UserArgs { args: [Const { ty: &'static [u8; 4], kind: UnevaluatedConst { def: DefId(0:8 ~ issue_99325[22bb]::main::{constant#1}), args: [] } }], user_self_ty: None }), max_universe: U0, variables: [] }, span: $DIR/issue_99325.rs:11:16: 11:68, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">}
4+
| 0: user_ty: Canonical { value: TypeOf(DefId(0:3 ~ issue_99325[22bb]::function_with_bytes), UserArgs { args: [Const { ty: &ReStatic [u8; Const { ty: usize, kind: Leaf(0x00000004) }], kind: Branch([Leaf(0x41), Leaf(0x41), Leaf(0x41), Leaf(0x41)]) }], user_self_ty: None }), max_universe: U0, variables: [] }, span: $DIR/issue_99325.rs:12:16: 12:46, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">}
5+
| 1: user_ty: Canonical { value: TypeOf(DefId(0:3 ~ issue_99325[22bb]::function_with_bytes), UserArgs { args: [Const { ty: &ReStatic [u8; Const { ty: usize, kind: Leaf(0x00000004) }], kind: UnevaluatedConst { def: DefId(0:8 ~ issue_99325[22bb]::main::{constant#1}), args: [] } }], user_self_ty: None }), max_universe: U0, variables: [] }, span: $DIR/issue_99325.rs:13:16: 13:68, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">}
66
|
77
fn main() -> () {
88
let mut _0: ();

0 commit comments

Comments
 (0)