1
Fork 0

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 `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 attribute) 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.
This commit is contained in:
Nicholas Nethercote 2023-09-07 15:14:40 +10:00
parent c0583a0221
commit 64ea8eb1a9
27 changed files with 502 additions and 77 deletions

View file

@ -27,6 +27,7 @@ use crate::ty::GenericArg;
use crate::ty::{self, BoundVar, List, Region, Ty, TyCtxt};
use rustc_macros::HashStable;
use smallvec::SmallVec;
use std::fmt::Display;
use std::ops::Index;
/// A "canonicalized" type `V` is one where all free inference
@ -40,6 +41,16 @@ pub struct Canonical<'tcx, V> {
pub variables: CanonicalVarInfos<'tcx>,
}
impl<'tcx, V: Display> std::fmt::Display for Canonical<'tcx, V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Canonical {{ value: {}, max_universe: {:?}, variables: {:?} }}",
self.value, self.max_universe, self.variables
)
}
}
pub type CanonicalVarInfos<'tcx> = &'tcx List<CanonicalVarInfo<'tcx>>;
impl<'tcx> ty::TypeFoldable<TyCtxt<'tcx>> for CanonicalVarInfos<'tcx> {

View file

@ -8,6 +8,7 @@ use crate::mir::interpret::{
use crate::mir::visit::MirVisitable;
use crate::ty::codec::{TyDecoder, TyEncoder};
use crate::ty::fold::{FallibleTypeFolder, TypeFoldable};
use crate::ty::print::with_no_trimmed_paths;
use crate::ty::print::{FmtPrinter, Printer};
use crate::ty::visit::TypeVisitableExt;
use crate::ty::{self, List, Ty, TyCtxt};
@ -1794,7 +1795,7 @@ fn post_fmt_projection(projection: &[PlaceElem<'_>], fmt: &mut Formatter<'_>) ->
write!(fmt, ")")?;
}
ProjectionElem::Field(field, ty) => {
write!(fmt, ".{:?}: {:?})", field.index(), ty)?;
with_no_trimmed_paths!(write!(fmt, ".{:?}: {})", field.index(), ty)?);
}
ProjectionElem::Index(ref index) => {
write!(fmt, "[{index:?}]")?;
@ -2077,7 +2078,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
}
Len(ref a) => write!(fmt, "Len({a:?})"),
Cast(ref kind, ref place, ref ty) => {
write!(fmt, "{place:?} as {ty:?} ({kind:?})")
with_no_trimmed_paths!(write!(fmt, "{place:?} as {ty} ({kind:?})"))
}
BinaryOp(ref op, box (ref a, ref b)) => write!(fmt, "{op:?}({a:?}, {b:?})"),
CheckedBinaryOp(ref op, box (ref a, ref b)) => {
@ -2085,11 +2086,14 @@ impl<'tcx> Debug for Rvalue<'tcx> {
}
UnaryOp(ref op, ref a) => write!(fmt, "{op:?}({a:?})"),
Discriminant(ref place) => write!(fmt, "discriminant({place:?})"),
NullaryOp(ref op, ref t) => match op {
NullOp::SizeOf => write!(fmt, "SizeOf({t:?})"),
NullOp::AlignOf => write!(fmt, "AlignOf({t:?})"),
NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t:?}, {fields:?})"),
},
NullaryOp(ref op, ref t) => {
let t = with_no_trimmed_paths!(format!("{}", t));
match op {
NullOp::SizeOf => write!(fmt, "SizeOf({t})"),
NullOp::AlignOf => write!(fmt, "AlignOf({t})"),
NullOp::OffsetOf(fields) => write!(fmt, "OffsetOf({t}, {fields:?})"),
}
}
ThreadLocalRef(did) => ty::tls::with(|tcx| {
let muta = tcx.static_mutability(did).unwrap().prefix_str();
write!(fmt, "&/*tls*/ {}{}", muta, tcx.def_path_str(did))
@ -2225,7 +2229,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
}
ShallowInitBox(ref place, ref ty) => {
write!(fmt, "ShallowInitBox({place:?}, {ty:?})")
with_no_trimmed_paths!(write!(fmt, "ShallowInitBox({place:?}, {ty})"))
}
}
}

View file

@ -583,8 +583,10 @@ fn write_scope_tree(
let mut_str = local_decl.mutability.prefix_str();
let mut indented_decl =
format!("{0:1$}let {2}{3:?}: {4:?}", INDENT, indent, mut_str, local, local_decl.ty);
let mut indented_decl = ty::print::with_no_trimmed_paths!(format!(
"{0:1$}let {2}{3:?}: {4}",
INDENT, indent, mut_str, local, 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();
@ -1058,11 +1060,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,
with_no_trimmed_paths!(format!("{}", annotation.inferred_ty)),
)?;
}
if !body.user_type_annotations.is_empty() {

View file

@ -450,6 +450,11 @@ impl<'tcx> GenericArgs<'tcx> {
pub fn host_effect_param(&'tcx self) -> Option<ty::Const<'tcx>> {
self.consts().rfind(|x| matches!(x.kind(), ty::ConstKind::Param(p) if p.name == sym::host))
}
pub fn print_as_list(&self) -> String {
let v = self.iter().map(|arg| arg.to_string()).collect::<Vec<_>>();
format!("[{}]", v.join(", "))
}
}
impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for GenericArgsRef<'tcx> {

View file

@ -760,9 +760,12 @@ pub trait PrettyPrinter<'tcx>:
// only affect certain debug messages (e.g. messages printed
// from `rustc_middle::ty` during the computation of `tcx.predicates_of`),
// and should have no effect on any compiler output.
// [Unless `-Zverbose` is used, e.g. in the output of
// `tests/ui/nll/ty-outlives/impl-trait-captures.rs`, for
// example.]
if self.should_print_verbose() {
// FIXME(eddyb) print this with `print_def_path`.
p!(write("Opaque({:?}, {:?})", def_id, args));
p!(write("Opaque({:?}, {})", def_id, args.print_as_list()));
return Ok(self);
}
@ -894,7 +897,7 @@ pub trait PrettyPrinter<'tcx>:
p!(print_def_path(did, args));
if !args.as_closure().is_valid() {
p!(" closure_args=(unavailable)");
p!(write(" args={:?}", args));
p!(write(" args={}", args.print_as_list()));
} else {
p!(" closure_kind_ty=", print(args.as_closure().kind_ty()));
p!(

View file

@ -154,7 +154,7 @@ impl<'tcx> ty::DebugWithInfcx<TyCtxt<'tcx>> for Ty<'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))
}
}

View file

@ -722,3 +722,14 @@ pub enum UserType<'tcx> {
/// given substitutions applied.
TypeOf(DefId, UserArgs<'tcx>),
}
impl<'tcx> std::fmt::Display 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!(write!(f, "Ty({})", arg0))
}
Self::TypeOf(arg0, arg1) => write!(f, "TypeOf({:?}, {:?})", arg0, arg1),
}
}
}