Skip to content

Add support for ty::Instance path shortening in diagnostics #144914

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
4 changes: 1 addition & 3 deletions compiler/rustc_middle/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,6 @@ middle_strict_coherence_needs_negative_coherence =
to use `strict_coherence` on this trait, the `with_negative_coherence` feature must be enabled
.label = due to this attribute

middle_type_length_limit = reached the type-length limit while instantiating `{$shrunk}`
middle_type_length_limit = reached the type-length limit while instantiating `{$instance}`

middle_unsupported_union = we don't support unions yet: '{$ty_name}'

middle_written_to_path = the full type name has been written to '{$path}'
11 changes: 4 additions & 7 deletions compiler/rustc_middle/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::path::{Path, PathBuf};
use std::path::Path;
use std::{fmt, io};

use rustc_errors::codes::*;
use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage};
use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{Span, Symbol};

use crate::ty::Ty;
use crate::ty::{Instance, Ty};

#[derive(Diagnostic)]
#[diag(middle_drop_check_overflow, code = E0320)]
Expand Down Expand Up @@ -161,13 +161,10 @@ pub(crate) struct ErroneousConstant {
#[derive(Diagnostic)]
#[diag(middle_type_length_limit)]
#[help(middle_consider_type_length_limit)]
pub(crate) struct TypeLengthLimit {
pub(crate) struct TypeLengthLimit<'tcx> {
#[primary_span]
pub span: Span,
pub shrunk: String,
#[note(middle_written_to_path)]
pub was_written: bool,
pub path: PathBuf,
pub instance: Instance<'tcx>,
pub type_length: usize,
}

Expand Down
13 changes: 11 additions & 2 deletions compiler/rustc_middle/src/ty/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ use rustc_data_structures::fx::FxIndexMap;
use rustc_errors::{
Applicability, Diag, DiagArgValue, IntoDiagArg, into_diag_arg_using_display, listify, pluralize,
};
use rustc_hir::def::DefKind;
use rustc_hir::def::{DefKind, Namespace};
use rustc_hir::def_id::DefId;
use rustc_hir::{self as hir, AmbigArg, LangItem, PredicateOrigin, WherePredicateKind};
use rustc_span::{BytePos, Span};
use rustc_type_ir::TyKind::*;

use crate::ty::{
self, AliasTy, Const, ConstKind, FallibleTypeFolder, InferConst, InferTy, Opaque,
self, AliasTy, Const, ConstKind, FallibleTypeFolder, InferConst, InferTy, Instance, Opaque,
PolyTraitPredicate, Projection, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable,
TypeSuperVisitable, TypeVisitable, TypeVisitor,
};
Expand All @@ -28,6 +28,15 @@ impl IntoDiagArg for Ty<'_> {
}
}

impl IntoDiagArg for Instance<'_> {
fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
ty::tls::with(|tcx| {
let instance = tcx.short_string_namespace(self, path, Namespace::ValueNS);
rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(instance))
})
}
}

into_diag_arg_using_display! {
ty::Region<'_>,
}
Expand Down
38 changes: 27 additions & 11 deletions compiler/rustc_middle/src/ty/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,11 @@ impl<'tcx> Ty<'tcx> {
_ => {
let width = tcx.sess.diagnostic_width();
let length_limit = std::cmp::max(width / 4, 40);
format!("`{}`", tcx.string_with_limit(self, length_limit)).into()
format!(
"`{}`",
tcx.string_with_limit(self, length_limit, hir::def::Namespace::TypeNS)
)
.into()
}
}
}
Expand Down Expand Up @@ -213,12 +217,12 @@ impl<'tcx> Ty<'tcx> {
}

impl<'tcx> TyCtxt<'tcx> {
pub fn string_with_limit<T>(self, p: T, length_limit: usize) -> String
pub fn string_with_limit<T>(self, p: T, length_limit: usize, ns: hir::def::Namespace) -> String
where
T: Copy + for<'a, 'b> Lift<TyCtxt<'b>, Lifted: Print<'b, FmtPrinter<'a, 'b>>>,
{
let mut type_limit = 50;
let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |cx| {
let regular = FmtPrinter::print_string(self, ns, |cx| {
self.lift(p).expect("could not lift for printing").print(cx)
})
.expect("could not write to `String`");
Expand All @@ -229,11 +233,7 @@ impl<'tcx> TyCtxt<'tcx> {
loop {
// Look for the longest properly trimmed path that still fits in length_limit.
short = with_forced_trimmed_paths!({
let mut cx = FmtPrinter::new_with_limit(
self,
hir::def::Namespace::TypeNS,
rustc_session::Limit(type_limit),
);
let mut cx = FmtPrinter::new_with_limit(self, ns, rustc_session::Limit(type_limit));
self.lift(p)
.expect("could not lift for printing")
.print(&mut cx)
Expand All @@ -251,12 +251,28 @@ impl<'tcx> TyCtxt<'tcx> {
/// When calling this after a `Diag` is constructed, the preferred way of doing so is
/// `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that keeps
/// the existence of a "long type" anywhere in the diagnostic, so the note telling the user
/// where we wrote the file to is only printed once.
/// where we wrote the file to is only printed once. The path will use the type namespace.
pub fn short_string<T>(self, p: T, path: &mut Option<PathBuf>) -> String
where
T: Copy + Hash + for<'a, 'b> Lift<TyCtxt<'b>, Lifted: Print<'b, FmtPrinter<'a, 'b>>>,
{
let regular = FmtPrinter::print_string(self, hir::def::Namespace::TypeNS, |cx| {
self.short_string_namespace(p, path, hir::def::Namespace::TypeNS)
}

/// When calling this after a `Diag` is constructed, the preferred way of doing so is
/// `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that keeps
/// the existence of a "long type" anywhere in the diagnostic, so the note telling the user
/// where we wrote the file to is only printed once.
pub fn short_string_namespace<T>(
self,
p: T,
path: &mut Option<PathBuf>,
namespace: hir::def::Namespace,
) -> String
where
T: Copy + Hash + for<'a, 'b> Lift<TyCtxt<'b>, Lifted: Print<'b, FmtPrinter<'a, 'b>>>,
{
let regular = FmtPrinter::print_string(self, namespace, |cx| {
self.lift(p).expect("could not lift for printing").print(cx)
})
.expect("could not write to `String`");
Expand All @@ -270,7 +286,7 @@ impl<'tcx> TyCtxt<'tcx> {
if regular.len() <= width * 2 / 3 {
return regular;
}
let short = self.string_with_limit(p, length_limit);
let short = self.string_with_limit(p, length_limit, namespace);
if regular == short {
return regular;
}
Expand Down
74 changes: 9 additions & 65 deletions compiler/rustc_middle/src/ty/instance.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::assert_matches::assert_matches;
use std::fmt;
use std::path::PathBuf;

use rustc_data_structures::fx::FxHashMap;
use rustc_errors::ErrorGuaranteed;
Expand All @@ -17,7 +16,7 @@ use tracing::{debug, instrument};
use crate::error;
use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
use crate::ty::normalize_erasing_regions::NormalizationError;
use crate::ty::print::{FmtPrinter, Printer, shrunk_instance_name};
use crate::ty::print::{FmtPrinter, Print};
use crate::ty::{
self, EarlyBinder, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
TypeVisitable, TypeVisitableExt, TypeVisitor,
Expand Down Expand Up @@ -389,59 +388,15 @@ fn type_length<'tcx>(item: impl TypeVisitable<TyCtxt<'tcx>>) -> usize {
visitor.type_length
}

pub fn fmt_instance(
f: &mut fmt::Formatter<'_>,
instance: Instance<'_>,
type_length: Option<rustc_session::Limit>,
) -> fmt::Result {
ty::tls::with(|tcx| {
let args = tcx.lift(instance.args).expect("could not lift for printing");

let mut cx = if let Some(type_length) = type_length {
FmtPrinter::new_with_limit(tcx, Namespace::ValueNS, type_length)
} else {
FmtPrinter::new(tcx, Namespace::ValueNS)
};
cx.print_def_path(instance.def_id(), args)?;
let s = cx.into_buffer();
f.write_str(&s)
})?;

match instance.def {
InstanceKind::Item(_) => Ok(()),
InstanceKind::VTableShim(_) => write!(f, " - shim(vtable)"),
InstanceKind::ReifyShim(_, None) => write!(f, " - shim(reify)"),
InstanceKind::ReifyShim(_, Some(ReifyReason::FnPtr)) => write!(f, " - shim(reify-fnptr)"),
InstanceKind::ReifyShim(_, Some(ReifyReason::Vtable)) => write!(f, " - shim(reify-vtable)"),
InstanceKind::ThreadLocalShim(_) => write!(f, " - shim(tls)"),
InstanceKind::Intrinsic(_) => write!(f, " - intrinsic"),
InstanceKind::Virtual(_, num) => write!(f, " - virtual#{num}"),
InstanceKind::FnPtrShim(_, ty) => write!(f, " - shim({ty})"),
InstanceKind::ClosureOnceShim { .. } => write!(f, " - shim"),
InstanceKind::ConstructCoroutineInClosureShim { .. } => write!(f, " - shim"),
InstanceKind::DropGlue(_, None) => write!(f, " - shim(None)"),
InstanceKind::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({ty}))"),
InstanceKind::CloneShim(_, ty) => write!(f, " - shim({ty})"),
InstanceKind::FnPtrAddrShim(_, ty) => write!(f, " - shim({ty})"),
InstanceKind::FutureDropPollShim(_, proxy_ty, impl_ty) => {
write!(f, " - dropshim({proxy_ty}-{impl_ty})")
}
InstanceKind::AsyncDropGlue(_, ty) => write!(f, " - shim({ty})"),
InstanceKind::AsyncDropGlueCtorShim(_, ty) => write!(f, " - shim(Some({ty}))"),
}
}

pub struct ShortInstance<'tcx>(pub Instance<'tcx>, pub usize);

impl<'tcx> fmt::Display for ShortInstance<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_instance(f, self.0, Some(rustc_session::Limit(self.1)))
}
}

impl<'tcx> fmt::Display for Instance<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_instance(f, *self, None)
ty::tls::with(|tcx| {
let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS);
let instance = tcx.lift(*self).expect("could not lift for printing");
instance.print(&mut cx)?;
let s = cx.into_buffer();
f.write_str(&s)
})
}
}

Expand Down Expand Up @@ -610,23 +565,12 @@ impl<'tcx> Instance<'tcx> {
Ok(None) => {
let type_length = type_length(args);
if !tcx.type_length_limit().value_within_limit(type_length) {
let (shrunk, written_to_path) =
shrunk_instance_name(tcx, Instance::new_raw(def_id, args));
let mut path = PathBuf::new();
let was_written = if let Some(path2) = written_to_path {
path = path2;
true
} else {
false
};
tcx.dcx().emit_fatal(error::TypeLengthLimit {
// We don't use `def_span(def_id)` so that diagnostics point
// to the crate root during mono instead of to foreign items.
// This is arguably better.
span: span_or_local_def_span(),
shrunk,
was_written,
path,
instance: Instance::new_raw(def_id, args),
type_length,
});
} else {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub use self::context::{
TyCtxtFeed, tls,
};
pub use self::fold::*;
pub use self::instance::{Instance, InstanceKind, ReifyReason, ShortInstance, UnusedGenericParams};
pub use self::instance::{Instance, InstanceKind, ReifyReason, UnusedGenericParams};
pub use self::list::{List, ListWithCachedTypeInfo};
pub use self::opaque_types::OpaqueTypeKey;
pub use self::parameterized::ParameterizedOverTcx;
Expand Down
69 changes: 38 additions & 31 deletions compiler/rustc_middle/src/ty/print/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::path::PathBuf;

use hir::def::Namespace;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sso::SsoHashSet;
Expand All @@ -8,7 +6,7 @@ use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
use tracing::{debug, instrument, trace};

use crate::ty::{self, GenericArg, ShortInstance, Ty, TyCtxt};
use crate::ty::{self, GenericArg, Ty, TyCtxt};

// `pretty` is a separate module only for organization.
mod pretty;
Expand Down Expand Up @@ -323,6 +321,43 @@ impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for Ty<'tcx> {
}
}

impl<'tcx, P: Printer<'tcx> + std::fmt::Write> Print<'tcx, P> for ty::Instance<'tcx> {
fn print(&self, cx: &mut P) -> Result<(), PrintError> {
cx.print_def_path(self.def_id(), self.args)?;
match self.def {
ty::InstanceKind::Item(_) => {}
ty::InstanceKind::VTableShim(_) => cx.write_str(" - shim(vtable)")?,
ty::InstanceKind::ReifyShim(_, None) => cx.write_str(" - shim(reify)")?,
ty::InstanceKind::ReifyShim(_, Some(ty::ReifyReason::FnPtr)) => {
cx.write_str(" - shim(reify-fnptr)")?
}
ty::InstanceKind::ReifyShim(_, Some(ty::ReifyReason::Vtable)) => {
cx.write_str(" - shim(reify-vtable)")?
}
ty::InstanceKind::ThreadLocalShim(_) => cx.write_str(" - shim(tls)")?,
ty::InstanceKind::Intrinsic(_) => cx.write_str(" - intrinsic")?,
ty::InstanceKind::Virtual(_, num) => cx.write_str(&format!(" - virtual#{num}"))?,
ty::InstanceKind::FnPtrShim(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
ty::InstanceKind::ClosureOnceShim { .. } => cx.write_str(" - shim")?,
ty::InstanceKind::ConstructCoroutineInClosureShim { .. } => cx.write_str(" - shim")?,
ty::InstanceKind::DropGlue(_, None) => cx.write_str(" - shim(None)")?,
ty::InstanceKind::DropGlue(_, Some(ty)) => {
cx.write_str(&format!(" - shim(Some({ty}))"))?
}
ty::InstanceKind::CloneShim(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
ty::InstanceKind::FnPtrAddrShim(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
ty::InstanceKind::FutureDropPollShim(_, proxy_ty, impl_ty) => {
cx.write_str(&format!(" - dropshim({proxy_ty}-{impl_ty})"))?
}
ty::InstanceKind::AsyncDropGlue(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
ty::InstanceKind::AsyncDropGlueCtorShim(_, ty) => {
cx.write_str(&format!(" - shim(Some({ty}))"))?
}
};
Ok(())
}
}

impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> {
fn print(&self, cx: &mut P) -> Result<(), PrintError> {
cx.print_dyn_existential(self)
Expand Down Expand Up @@ -362,31 +397,3 @@ where
with_no_trimmed_paths!(Self::print(t, fmt))
}
}

/// Format instance name that is already known to be too long for rustc.
/// Show only the first 2 types if it is longer than 32 characters to avoid blasting
/// the user's terminal with thousands of lines of type-name.
///
/// If the type name is longer than before+after, it will be written to a file.
pub fn shrunk_instance_name<'tcx>(
tcx: TyCtxt<'tcx>,
instance: ty::Instance<'tcx>,
) -> (String, Option<PathBuf>) {
let s = instance.to_string();

// Only use the shrunk version if it's really shorter.
// This also avoids the case where before and after slices overlap.
if s.chars().nth(33).is_some() {
let shrunk = format!("{}", ShortInstance(instance, 4));
if shrunk == s {
return (s, None);
}

let path = tcx.output_filenames(()).temp_path_for_diagnostic("long-type.txt");
let written_to_path = std::fs::write(&path, s).ok().map(|_| path);

(shrunk, written_to_path)
} else {
(s, None)
}
}
9 changes: 5 additions & 4 deletions compiler/rustc_monomorphize/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ monomorphize_couldnt_dump_mono_stats =
unexpected error occurred while dumping monomorphization stats: {$error}

monomorphize_encountered_error_while_instantiating =
the above error was encountered while instantiating `{$formatted_item}`
the above error was encountered while instantiating `{$kind} {$instance}`

monomorphize_encountered_error_while_instantiating_global_asm =
the above error was encountered while instantiating `global_asm`

monomorphize_large_assignments =
moving {$size} bytes
Expand All @@ -52,12 +55,10 @@ monomorphize_no_optimized_mir =
.note = missing optimized MIR for this item (was the crate `{$crate_name}` compiled with `--emit=metadata`?)

monomorphize_recursion_limit =
reached the recursion limit while instantiating `{$shrunk}`
reached the recursion limit while instantiating `{$instance}`
.note = `{$def_path_str}` defined here

monomorphize_start_not_found = using `fn main` requires the standard library
.help = use `#![no_main]` to bypass the Rust generated entrypoint and declare a platform specific entrypoint yourself, usually with `#[no_mangle]`

monomorphize_symbol_already_defined = symbol `{$symbol}` is already defined

monomorphize_written_to_path = the full type name has been written to '{$path}'
Loading
Loading