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

Introduce with_forced_trimmed_paths #105411

Merged
merged 2 commits into from
Dec 11, 2022
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
46 changes: 30 additions & 16 deletions compiler/rustc_middle/src/ty/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::traits::{ObligationCause, ObligationCauseCode};
use crate::ty::diagnostics::suggest_constraining_type_param;
use crate::ty::print::{FmtPrinter, Printer};
use crate::ty::print::{with_forced_trimmed_paths, FmtPrinter, Printer};
use crate::ty::{self, BoundRegionKind, Region, Ty, TyCtxt};
use hir::def::DefKind;
use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
Expand Down Expand Up @@ -162,17 +162,29 @@ impl<'tcx> fmt::Display for TypeError<'tcx> {
),
RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
ArgumentSorts(values, _) | Sorts(values) => ty::tls::with(|tcx| {
report_maybe_different(
f,
&values.expected.sort_string(tcx),
&values.found.sort_string(tcx),
)
let (mut expected, mut found) = with_forced_trimmed_paths!((
values.expected.sort_string(tcx),
values.found.sort_string(tcx),
));
if expected == found {
expected = values.expected.sort_string(tcx);
found = values.found.sort_string(tcx);
}
report_maybe_different(f, &expected, &found)
}),
Traits(values) => ty::tls::with(|tcx| {
let (mut expected, mut found) = with_forced_trimmed_paths!((
tcx.def_path_str(values.expected),
tcx.def_path_str(values.found),
));
if expected == found {
expected = tcx.def_path_str(values.expected);
found = tcx.def_path_str(values.found);
}
report_maybe_different(
f,
&format!("trait `{}`", tcx.def_path_str(values.expected)),
&format!("trait `{}`", tcx.def_path_str(values.found)),
&format!("trait `{expected}`"),
&format!("trait `{found}`"),
)
}),
IntMismatch(ref values) => {
Expand Down Expand Up @@ -999,14 +1011,16 @@ fn foo(&self) -> Self::T { String::new() }
let mut short;
loop {
// Look for the longest properly trimmed path that still fits in lenght_limit.
short = FmtPrinter::new_with_limit(
self,
hir::def::Namespace::TypeNS,
rustc_session::Limit(type_limit),
)
.pretty_print_type(ty)
.expect("could not write to `String`")
.into_buffer();
short = with_forced_trimmed_paths!(
FmtPrinter::new_with_limit(
self,
hir::def::Namespace::TypeNS,
rustc_session::Limit(type_limit),
)
.pretty_print_type(ty)
.expect("could not write to `String`")
.into_buffer()
);
if short.len() <= length_limit || type_limit == 0 {
break;
}
Expand Down
82 changes: 81 additions & 1 deletion compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use rustc_data_structures::sso::SsoHashSet;
use rustc_hir as hir;
use rustc_hir::def::{self, CtorKind, DefKind, Namespace};
use rustc_hir::def_id::{DefId, DefIdSet, CRATE_DEF_ID, LOCAL_CRATE};
use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
use rustc_hir::definitions::{DefKey, DefPathData, DefPathDataName, DisambiguatedDefPathData};
use rustc_hir::LangItem;
use rustc_session::config::TrimmedDefPaths;
use rustc_session::cstore::{ExternCrate, ExternCrateSource};
Expand Down Expand Up @@ -63,6 +63,7 @@ thread_local! {
static FORCE_IMPL_FILENAME_LINE: Cell<bool> = const { Cell::new(false) };
static SHOULD_PREFIX_WITH_CRATE: Cell<bool> = const { Cell::new(false) };
static NO_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
static FORCE_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) };
static NO_QUERIES: Cell<bool> = const { Cell::new(false) };
static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) };
}
Expand Down Expand Up @@ -116,6 +117,7 @@ define_helper!(
/// of various rustc types, for example `std::vec::Vec` would be trimmed to `Vec`,
/// if no other `Vec` is found.
fn with_no_trimmed_paths(NoTrimmedGuard, NO_TRIMMED_PATH);
fn with_forced_trimmed_paths(ForceTrimmedGuard, FORCE_TRIMMED_PATH);
/// Prevent selection of visible paths. `Display` impl of DefId will prefer
/// visible (public) reexports of types as paths.
fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH);
Expand Down Expand Up @@ -295,11 +297,89 @@ pub trait PrettyPrinter<'tcx>:
self.try_print_visible_def_path_recur(def_id, &mut callers)
}

// Given a `DefId`, produce a short name. For types and traits, it prints *only* its name,
// For associated items on traits it prints out the trait's name and the associated item's name.
// For enum variants, if they have an unique name, then we only print the name, otherwise we
// print the enum name and the variant name. Otherwise, we do not print anything and let the
// caller use the `print_def_path` fallback.
fn force_print_trimmed_def_path(
mut self,
def_id: DefId,
) -> Result<(Self::Path, bool), Self::Error> {
let key = self.tcx().def_key(def_id);
let visible_parent_map = self.tcx().visible_parent_map(());
let kind = self.tcx().def_kind(def_id);

let get_local_name = |this: &Self, name, def_id, key: DefKey| {
if let Some(visible_parent) = visible_parent_map.get(&def_id)
&& let actual_parent = this.tcx().opt_parent(def_id)
&& let DefPathData::TypeNs(_) = key.disambiguated_data.data
&& Some(*visible_parent) != actual_parent
{
this
.tcx()
.module_children(visible_parent)
.iter()
.filter(|child| child.res.opt_def_id() == Some(def_id))
.find(|child| child.vis.is_public() && child.ident.name != kw::Underscore)
.map(|child| child.ident.name)
.unwrap_or(name)
} else {
name
}
};
if let DefKind::Variant = kind
&& let Some(symbol) = self.tcx().trimmed_def_paths(()).get(&def_id)
{
// If `Assoc` is unique, we don't want to talk about `Trait::Assoc`.
self.write_str(get_local_name(&self, *symbol, def_id, key).as_str())?;
return Ok((self, true));
}
if let Some(symbol) = key.get_opt_name() {
if let DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy = kind
&& let Some(parent) = self.tcx().opt_parent(def_id)
&& let parent_key = self.tcx().def_key(parent)
&& let Some(symbol) = parent_key.get_opt_name()
{
// Trait
self.write_str(get_local_name(&self, symbol, parent, parent_key).as_str())?;
self.write_str("::")?;
} else if let DefKind::Variant = kind
&& let Some(parent) = self.tcx().opt_parent(def_id)
&& let parent_key = self.tcx().def_key(parent)
&& let Some(symbol) = parent_key.get_opt_name()
{
// Enum

// For associated items and variants, we want the "full" path, namely, include
// the parent type in the path. For example, `Iterator::Item`.
self.write_str(get_local_name(&self, symbol, parent, parent_key).as_str())?;
self.write_str("::")?;
} else if let DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Trait
| DefKind::TyAlias | DefKind::Fn | DefKind::Const | DefKind::Static(_) = kind
{
} else {
// If not covered above, like for example items out of `impl` blocks, fallback.
return Ok((self, false));
}
self.write_str(get_local_name(&self, symbol, def_id, key).as_str())?;
return Ok((self, true));
}
Ok((self, false))
}

/// Try to see if this path can be trimmed to a unique symbol name.
fn try_print_trimmed_def_path(
mut self,
def_id: DefId,
) -> Result<(Self::Path, bool), Self::Error> {
if FORCE_TRIMMED_PATH.with(|flag| flag.get()) {
let (s, trimmed) = self.force_print_trimmed_def_path(def_id)?;
if trimmed {
return Ok((s, true));
}
self = s;
}
if !self.tcx().sess.opts.unstable_opts.trim_diagnostic_paths
|| matches!(self.tcx().sess.opts.trimmed_def_paths, TrimmedDefPaths::Never)
|| NO_TRIMMED_PATH.with(|flag| flag.get())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use std::fmt;
use super::InferCtxtPrivExt;
use crate::infer::InferCtxtExt as _;
use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};

#[derive(Debug)]
pub enum GeneratorInteriorOrUpvar {
Expand Down Expand Up @@ -2412,6 +2412,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
ObligationCauseCode::BindingObligation(item_def_id, span)
| ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..) => {
let item_name = tcx.def_path_str(item_def_id);
let short_item_name = with_forced_trimmed_paths!(tcx.def_path_str(item_def_id));
let mut multispan = MultiSpan::from(span);
let sm = tcx.sess.source_map();
if let Some(ident) = tcx.opt_item_ident(item_def_id) {
Expand All @@ -2424,9 +2425,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
multispan.push_span_label(ident.span, "required by a bound in this");
}
}
let descr = format!("required by a bound in `{}`", item_name);
let descr = format!("required by a bound in `{item_name}`");
if span.is_visible(sm) {
let msg = format!("required by this bound in `{}`", item_name);
let msg = format!("required by this bound in `{short_item_name}`");
multispan.push_span_label(span, msg);
err.span_note(multispan, &descr);
} else {
Expand Down
6 changes: 3 additions & 3 deletions src/test/ui/closures/closure-return-type-must-be-sized.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ note: required by a bound in `a::bar`
--> $DIR/closure-return-type-must-be-sized.rs:14:19
|
LL | pub fn bar<F: FnOnce() -> R, R: ?Sized>() {}
| ^^^^^^^^^^^^^ required by this bound in `a::bar`
| ^^^^^^^^^^^^^ required by this bound in `bar`

error[E0277]: the size for values of type `dyn A` cannot be known at compilation time
--> $DIR/closure-return-type-must-be-sized.rs:56:5
Expand Down Expand Up @@ -51,7 +51,7 @@ note: required by a bound in `b::bar`
--> $DIR/closure-return-type-must-be-sized.rs:28:19
|
LL | pub fn bar<F: Fn() -> R, R: ?Sized>() {}
| ^^^^^^^^^ required by this bound in `b::bar`
| ^^^^^^^^^ required by this bound in `bar`

error[E0277]: the size for values of type `dyn A` cannot be known at compilation time
--> $DIR/closure-return-type-must-be-sized.rs:63:5
Expand Down Expand Up @@ -83,7 +83,7 @@ note: required by a bound in `c::bar`
--> $DIR/closure-return-type-must-be-sized.rs:42:19
|
LL | pub fn bar<F: FnMut() -> R, R: ?Sized>() {}
| ^^^^^^^^^^^^ required by this bound in `c::bar`
| ^^^^^^^^^^^^ required by this bound in `bar`

error[E0277]: the size for values of type `dyn A` cannot be known at compilation time
--> $DIR/closure-return-type-must-be-sized.rs:70:5
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ note: required by a bound in `use_trait_impl::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:14:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error[E0308]: mismatched types
--> $DIR/abstract-const-as-cast-3.rs:17:5
Expand All @@ -28,7 +28,7 @@ note: required by a bound in `use_trait_impl::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:14:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error: unconstrained generic constant
--> $DIR/abstract-const-as-cast-3.rs:20:19
Expand All @@ -46,7 +46,7 @@ note: required by a bound in `use_trait_impl::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:14:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error[E0308]: mismatched types
--> $DIR/abstract-const-as-cast-3.rs:20:5
Expand All @@ -60,7 +60,7 @@ note: required by a bound in `use_trait_impl::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:14:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error[E0308]: mismatched types
--> $DIR/abstract-const-as-cast-3.rs:23:5
Expand All @@ -74,7 +74,7 @@ note: required by a bound in `use_trait_impl::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:14:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error[E0308]: mismatched types
--> $DIR/abstract-const-as-cast-3.rs:25:5
Expand All @@ -88,7 +88,7 @@ note: required by a bound in `use_trait_impl::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:14:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error: unconstrained generic constant
--> $DIR/abstract-const-as-cast-3.rs:35:19
Expand All @@ -106,7 +106,7 @@ note: required by a bound in `use_trait_impl_2::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:32:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl_2::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error[E0308]: mismatched types
--> $DIR/abstract-const-as-cast-3.rs:35:5
Expand All @@ -120,7 +120,7 @@ note: required by a bound in `use_trait_impl_2::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:32:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl_2::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error: unconstrained generic constant
--> $DIR/abstract-const-as-cast-3.rs:38:19
Expand All @@ -138,7 +138,7 @@ note: required by a bound in `use_trait_impl_2::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:32:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl_2::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error[E0308]: mismatched types
--> $DIR/abstract-const-as-cast-3.rs:38:5
Expand All @@ -152,7 +152,7 @@ note: required by a bound in `use_trait_impl_2::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:32:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl_2::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error[E0308]: mismatched types
--> $DIR/abstract-const-as-cast-3.rs:41:5
Expand All @@ -166,7 +166,7 @@ note: required by a bound in `use_trait_impl_2::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:32:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl_2::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error[E0308]: mismatched types
--> $DIR/abstract-const-as-cast-3.rs:43:5
Expand All @@ -180,7 +180,7 @@ note: required by a bound in `use_trait_impl_2::assert_impl`
--> $DIR/abstract-const-as-cast-3.rs:32:23
|
LL | fn assert_impl<T: Trait>() {}
| ^^^^^ required by this bound in `use_trait_impl_2::assert_impl`
| ^^^^^ required by this bound in `assert_impl`

error: aborting due to 12 previous errors

Expand Down
17 changes: 14 additions & 3 deletions src/test/ui/diagnostic-width/long-E0308.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
// compile-flags: --diagnostic-width=60
// normalize-stderr-test: "long-type-\d+" -> "long-type-hash"

struct Atype<T, K>(T, K);
struct Btype<T, K>(T, K);
struct Ctype<T, K>(T, K);
mod a {
// Force the "short path for unique types" machinery to trip up
pub struct Atype;
pub struct Btype;
pub struct Ctype;
}

mod b {
pub struct Atype<T, K>(T, K);
pub struct Btype<T, K>(T, K);
pub struct Ctype<T, K>(T, K);
}

use b::*;

fn main() {
let x: Atype<
Expand Down
Loading