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

Disentangle Debug and Display for Ty. #115661

Merged
merged 1 commit into from
Sep 11, 2023
Merged
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: 5 additions & 1 deletion compiler/rustc_borrowck/src/nll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use rustc_middle::mir::{
Body, ClosureOutlivesSubject, ClosureRegionRequirements, LocalKind, Location, Promoted,
START_BLOCK,
};
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self, OpaqueHiddenType, TyCtxt};
use rustc_span::symbol::sym;
use std::env;
Expand Down Expand Up @@ -441,7 +442,10 @@ fn for_each_region_constraint<'tcx>(
let subject = match req.subject {
ClosureOutlivesSubject::Region(subject) => format!("{subject:?}"),
ClosureOutlivesSubject::Ty(ty) => {
format!("{:?}", ty.instantiate(tcx, |vid| ty::Region::new_var(tcx, vid)))
with_no_trimmed_paths!(format!(
"{}",
ty.instantiate(tcx, |vid| ty::Region::new_var(tcx, vid))
))
}
};
with_msg(format!("where {}: {:?}", subject, req.outlived_free_region,))?;
Expand Down
21 changes: 17 additions & 4 deletions compiler/rustc_borrowck/src/universal_regions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use rustc_hir::BodyOwnerKind;
use rustc_index::IndexVec;
use rustc_infer::infer::NllRegionVariableOrigin;
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self, InlineConstArgs, InlineConstArgsParts, RegionVid, Ty, TyCtxt};
use rustc_middle::ty::{GenericArgs, GenericArgsRef};
use rustc_span::symbol::{kw, sym};
Expand Down Expand Up @@ -332,10 +333,16 @@ impl<'tcx> UniversalRegions<'tcx> {
pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) {
match self.defining_ty {
DefiningTy::Closure(def_id, args) => {
let v = with_no_trimmed_paths!(
args[tcx.generics_of(def_id).parent_count..]
.iter()
.map(|arg| arg.to_string())
.collect::<Vec<_>>()
);
err.note(format!(
"defining type: {} with closure args {:#?}",
"defining type: {} with closure args [\n {},\n]",
nnethercote marked this conversation as resolved.
Show resolved Hide resolved
tcx.def_path_str_with_args(def_id, args),
&args[tcx.generics_of(def_id).parent_count..],
v.join(",\n "),
));

// FIXME: It'd be nice to print the late-bound regions
Expand All @@ -348,10 +355,16 @@ impl<'tcx> UniversalRegions<'tcx> {
});
}
DefiningTy::Generator(def_id, args, _) => {
let v = with_no_trimmed_paths!(
args[tcx.generics_of(def_id).parent_count..]
.iter()
.map(|arg| arg.to_string())
.collect::<Vec<_>>()
);
err.note(format!(
"defining type: {} with generator args {:#?}",
"defining type: {} with generator args [\n {},\n]",
tcx.def_path_str_with_args(def_id, args),
&args[tcx.generics_of(def_id).parent_count..],
v.join(",\n "),
));

// FIXME: As above, we'd like to print out the region
Expand Down
11 changes: 11 additions & 0 deletions compiler/rustc_middle/src/infer/canonical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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> {
Expand Down
20 changes: 12 additions & 8 deletions compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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:?}]")?;
Expand Down Expand Up @@ -2077,19 +2078,22 @@ 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)) => {
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) => 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))
Expand Down Expand Up @@ -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})"))
}
}
}
Expand Down
10 changes: 6 additions & 4 deletions compiler/rustc_middle/src/mir/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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() {
Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_middle/src/ty/generic_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand Down
7 changes: 5 additions & 2 deletions compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
nnethercote marked this conversation as resolved.
Show resolved Hide resolved
// [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);
}

Expand Down Expand Up @@ -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!(
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 @@ -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))
}
}

Expand Down
11 changes: 11 additions & 0 deletions compiler/rustc_middle/src/ty/typeck_results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
}
}
1 change: 1 addition & 0 deletions compiler/rustc_passes/src/abi_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ fn dump_abi_of_fn_item(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribut
tcx.sess.emit_err(AbiOf {
span: tcx.def_span(item_def_id),
fn_name,
// FIXME: using the `Debug` impl here isn't ideal.
fn_abi: format!("{:#?}", abi),
});
}
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_passes/src/layout_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,13 @@ 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,
)
);
// FIXME: using the `Debug` impl here isn't ideal.
let ty_layout = format!("{:#?}", *ty_layout);
tcx.sess.emit_err(LayoutOf { span, normalized_ty, ty_layout });
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1805,7 +1805,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
3 changes: 2 additions & 1 deletion compiler/rustc_ty_utils/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use rustc_middle::query::Providers;
use rustc_middle::ty::layout::{
IntegerExt, LayoutCx, LayoutError, LayoutOf, TyAndLayout, MAX_SIMD_LANES,
};
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{
self, AdtDef, EarlyBinder, GenericArgsRef, ReprOptions, Ty, TyCtxt, TypeVisitableExt,
};
Expand Down Expand Up @@ -937,7 +938,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 = with_no_trimmed_paths!(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,29 @@
/* generator_layout = GeneratorLayout {
field_tys: {
_0: GeneratorSavedTy {
ty: impl std::future::Future<Output = ()>,
ty: Alias(
Opaque,
AliasTy {
args: [
],
def_id: DefId(0:7 ~ async_await[ccf8]::a::{opaque#0}),
},
),
source_info: SourceInfo {
span: $DIR/async_await.rs:15:9: 15:14 (#8),
scope: scope[0],
},
ignore_for_traits: false,
},
_1: GeneratorSavedTy {
ty: impl std::future::Future<Output = ()>,
ty: Alias(
Opaque,
AliasTy {
args: [
],
def_id: DefId(0:7 ~ async_await[ccf8]::a::{opaque#0}),
},
),
source_info: SourceInfo {
span: $DIR/async_await.rs:16:9: 16:14 (#10),
scope: scope[0],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@
/* 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,11 @@
/* 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,11 @@
/* 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
@@ -1,8 +1,8 @@
// MIR for `main` after built

| User Type Annotations
| 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">}
| 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">}
| 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">}
| 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">}
|
fn main() -> () {
let mut _0: ();
Expand Down
Loading
Loading