Skip to content

Commit d72d47a

Browse files
committed
Add support for shortening Instance and use it
Replace ad-hoc type path shortening logic for recursive mono instantiation errors to use `tcx.short_string()` instead.
1 parent 1e79819 commit d72d47a

File tree

61 files changed

+191
-178
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

61 files changed

+191
-178
lines changed

compiler/rustc_middle/messages.ftl

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,6 @@ middle_strict_coherence_needs_negative_coherence =
122122
to use `strict_coherence` on this trait, the `with_negative_coherence` feature must be enabled
123123
.label = due to this attribute
124124
125-
middle_type_length_limit = reached the type-length limit while instantiating `{$shrunk}`
125+
middle_type_length_limit = reached the type-length limit while instantiating `{$instance}`
126126
127127
middle_unsupported_union = we don't support unions yet: '{$ty_name}'
128-
129-
middle_written_to_path = the full type name has been written to '{$path}'

compiler/rustc_middle/src/error.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
use std::path::{Path, PathBuf};
1+
use std::path::Path;
22
use std::{fmt, io};
33

44
use rustc_errors::codes::*;
55
use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage};
66
use rustc_macros::{Diagnostic, Subdiagnostic};
77
use rustc_span::{Span, Symbol};
88

9-
use crate::ty::Ty;
9+
use crate::ty::{Instance, Ty};
1010

1111
#[derive(Diagnostic)]
1212
#[diag(middle_drop_check_overflow, code = E0320)]
@@ -161,13 +161,10 @@ pub(crate) struct ErroneousConstant {
161161
#[derive(Diagnostic)]
162162
#[diag(middle_type_length_limit)]
163163
#[help(middle_consider_type_length_limit)]
164-
pub(crate) struct TypeLengthLimit {
164+
pub(crate) struct TypeLengthLimit<'tcx> {
165165
#[primary_span]
166166
pub span: Span,
167-
pub shrunk: String,
168-
#[note(middle_written_to_path)]
169-
pub was_written: bool,
170-
pub path: PathBuf,
167+
pub instance: Instance<'tcx>,
171168
pub type_length: usize,
172169
}
173170

compiler/rustc_middle/src/ty/diagnostics.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc_span::{BytePos, Span};
1414
use rustc_type_ir::TyKind::*;
1515

1616
use crate::ty::{
17-
self, AliasTy, Const, ConstKind, FallibleTypeFolder, InferConst, InferTy, Opaque,
17+
self, AliasTy, Const, ConstKind, FallibleTypeFolder, InferConst, InferTy, Instance, Opaque,
1818
PolyTraitPredicate, Projection, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable,
1919
TypeSuperVisitable, TypeVisitable, TypeVisitor,
2020
};
@@ -28,6 +28,15 @@ impl IntoDiagArg for Ty<'_> {
2828
}
2929
}
3030

31+
impl IntoDiagArg for Instance<'_> {
32+
fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
33+
ty::tls::with(|tcx| {
34+
let instance = tcx.short_string(self, path);
35+
rustc_errors::DiagArgValue::Str(std::borrow::Cow::Owned(instance))
36+
})
37+
}
38+
}
39+
3140
into_diag_arg_using_display! {
3241
ty::Region<'_>,
3342
}

compiler/rustc_middle/src/ty/instance.rs

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::assert_matches::assert_matches;
22
use std::fmt;
3-
use std::path::PathBuf;
43

54
use rustc_data_structures::fx::FxHashMap;
65
use rustc_errors::ErrorGuaranteed;
@@ -17,7 +16,7 @@ use tracing::{debug, instrument};
1716
use crate::error;
1817
use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
1918
use crate::ty::normalize_erasing_regions::NormalizationError;
20-
use crate::ty::print::{FmtPrinter, Printer, shrunk_instance_name};
19+
use crate::ty::print::{FmtPrinter, Printer};
2120
use crate::ty::{
2221
self, EarlyBinder, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
2322
TypeVisitable, TypeVisitableExt, TypeVisitor,
@@ -431,14 +430,6 @@ pub fn fmt_instance(
431430
}
432431
}
433432

434-
pub struct ShortInstance<'tcx>(pub Instance<'tcx>, pub usize);
435-
436-
impl<'tcx> fmt::Display for ShortInstance<'tcx> {
437-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
438-
fmt_instance(f, self.0, Some(rustc_session::Limit(self.1)))
439-
}
440-
}
441-
442433
impl<'tcx> fmt::Display for Instance<'tcx> {
443434
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444435
fmt_instance(f, *self, None)
@@ -610,23 +601,12 @@ impl<'tcx> Instance<'tcx> {
610601
Ok(None) => {
611602
let type_length = type_length(args);
612603
if !tcx.type_length_limit().value_within_limit(type_length) {
613-
let (shrunk, written_to_path) =
614-
shrunk_instance_name(tcx, Instance::new_raw(def_id, args));
615-
let mut path = PathBuf::new();
616-
let was_written = if let Some(path2) = written_to_path {
617-
path = path2;
618-
true
619-
} else {
620-
false
621-
};
622604
tcx.dcx().emit_fatal(error::TypeLengthLimit {
623605
// We don't use `def_span(def_id)` so that diagnostics point
624606
// to the crate root during mono instead of to foreign items.
625607
// This is arguably better.
626608
span: span_or_local_def_span(),
627-
shrunk,
628-
was_written,
629-
path,
609+
instance: Instance::new_raw(def_id, args),
630610
type_length,
631611
});
632612
} else {

compiler/rustc_middle/src/ty/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ pub use self::context::{
8282
TyCtxtFeed, tls,
8383
};
8484
pub use self::fold::*;
85-
pub use self::instance::{Instance, InstanceKind, ReifyReason, ShortInstance, UnusedGenericParams};
85+
pub use self::instance::{Instance, InstanceKind, ReifyReason, UnusedGenericParams};
8686
pub use self::list::{List, ListWithCachedTypeInfo};
8787
pub use self::opaque_types::OpaqueTypeKey;
8888
pub use self::parameterized::ParameterizedOverTcx;

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

Lines changed: 38 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
use std::path::PathBuf;
2-
31
use hir::def::Namespace;
42
use rustc_data_structures::fx::FxHashSet;
53
use rustc_data_structures::sso::SsoHashSet;
@@ -8,7 +6,7 @@ use rustc_hir::def_id::{CrateNum, DefId, LocalDefId};
86
use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData};
97
use tracing::{debug, instrument, trace};
108

11-
use crate::ty::{self, GenericArg, ShortInstance, Ty, TyCtxt};
9+
use crate::ty::{self, GenericArg, Ty, TyCtxt};
1210

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

324+
impl<'tcx, P: Printer<'tcx> + std::fmt::Write> Print<'tcx, P> for ty::Instance<'tcx> {
325+
fn print(&self, cx: &mut P) -> Result<(), PrintError> {
326+
cx.print_def_path(self.def_id(), self.args)?;
327+
match self.def {
328+
ty::InstanceKind::Item(_) => {}
329+
ty::InstanceKind::VTableShim(_) => cx.write_str(" - shim(vtable)")?,
330+
ty::InstanceKind::ReifyShim(_, None) => cx.write_str(" - shim(reify)")?,
331+
ty::InstanceKind::ReifyShim(_, Some(ty::ReifyReason::FnPtr)) => {
332+
cx.write_str(" - shim(reify-fnptr)")?
333+
}
334+
ty::InstanceKind::ReifyShim(_, Some(ty::ReifyReason::Vtable)) => {
335+
cx.write_str(" - shim(reify-vtable)")?
336+
}
337+
ty::InstanceKind::ThreadLocalShim(_) => cx.write_str(" - shim(tls)")?,
338+
ty::InstanceKind::Intrinsic(_) => cx.write_str(" - intrinsic")?,
339+
ty::InstanceKind::Virtual(_, num) => cx.write_str(&format!(" - virtual#{num}"))?,
340+
ty::InstanceKind::FnPtrShim(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
341+
ty::InstanceKind::ClosureOnceShim { .. } => cx.write_str(" - shim")?,
342+
ty::InstanceKind::ConstructCoroutineInClosureShim { .. } => cx.write_str(" - shim")?,
343+
ty::InstanceKind::DropGlue(_, None) => cx.write_str(" - shim(None)")?,
344+
ty::InstanceKind::DropGlue(_, Some(ty)) => {
345+
cx.write_str(&format!(" - shim(Some({ty}))"))?
346+
}
347+
ty::InstanceKind::CloneShim(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
348+
ty::InstanceKind::FnPtrAddrShim(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
349+
ty::InstanceKind::FutureDropPollShim(_, proxy_ty, impl_ty) => {
350+
cx.write_str(&format!(" - dropshim({proxy_ty}-{impl_ty})"))?
351+
}
352+
ty::InstanceKind::AsyncDropGlue(_, ty) => cx.write_str(&format!(" - shim({ty})"))?,
353+
ty::InstanceKind::AsyncDropGlueCtorShim(_, ty) => {
354+
cx.write_str(&format!(" - shim(Some({ty}))"))?
355+
}
356+
};
357+
Ok(())
358+
}
359+
}
360+
326361
impl<'tcx, P: Printer<'tcx>> Print<'tcx, P> for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> {
327362
fn print(&self, cx: &mut P) -> Result<(), PrintError> {
328363
cx.print_dyn_existential(self)
@@ -362,31 +397,3 @@ where
362397
with_no_trimmed_paths!(Self::print(t, fmt))
363398
}
364399
}
365-
366-
/// Format instance name that is already known to be too long for rustc.
367-
/// Show only the first 2 types if it is longer than 32 characters to avoid blasting
368-
/// the user's terminal with thousands of lines of type-name.
369-
///
370-
/// If the type name is longer than before+after, it will be written to a file.
371-
pub fn shrunk_instance_name<'tcx>(
372-
tcx: TyCtxt<'tcx>,
373-
instance: ty::Instance<'tcx>,
374-
) -> (String, Option<PathBuf>) {
375-
let s = instance.to_string();
376-
377-
// Only use the shrunk version if it's really shorter.
378-
// This also avoids the case where before and after slices overlap.
379-
if s.chars().nth(33).is_some() {
380-
let shrunk = format!("{}", ShortInstance(instance, 4));
381-
if shrunk == s {
382-
return (s, None);
383-
}
384-
385-
let path = tcx.output_filenames(()).temp_path_for_diagnostic("long-type.txt");
386-
let written_to_path = std::fs::write(&path, s).ok().map(|_| path);
387-
388-
(shrunk, written_to_path)
389-
} else {
390-
(s, None)
391-
}
392-
}

compiler/rustc_monomorphize/messages.ftl

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,10 @@ monomorphize_couldnt_dump_mono_stats =
4040
unexpected error occurred while dumping monomorphization stats: {$error}
4141
4242
monomorphize_encountered_error_while_instantiating =
43-
the above error was encountered while instantiating `{$formatted_item}`
43+
the above error was encountered while instantiating `{$kind} {$instance}`
44+
45+
monomorphize_encountered_error_while_instantiating_global_asm =
46+
the above error was encountered while instantiating `global_asm`
4447
4548
monomorphize_large_assignments =
4649
moving {$size} bytes
@@ -52,12 +55,10 @@ monomorphize_no_optimized_mir =
5255
.note = missing optimized MIR for this item (was the crate `{$crate_name}` compiled with `--emit=metadata`?)
5356
5457
monomorphize_recursion_limit =
55-
reached the recursion limit while instantiating `{$shrunk}`
58+
reached the recursion limit while instantiating `{$instance}`
5659
.note = `{$def_path_str}` defined here
5760
5861
monomorphize_start_not_found = using `fn main` requires the standard library
5962
.help = use `#![no_main]` to bypass the Rust generated entrypoint and declare a platform specific entrypoint yourself, usually with `#[no_mangle]`
6063
6164
monomorphize_symbol_already_defined = symbol `{$symbol}` is already defined
62-
63-
monomorphize_written_to_path = the full type name has been written to '{$path}'

compiler/rustc_monomorphize/src/collector.rs

Lines changed: 22 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,6 @@
206206
//! regardless of whether it is actually needed or not.
207207
208208
use std::cell::OnceCell;
209-
use std::path::PathBuf;
210209

211210
use rustc_attr_data_structures::InlineAttr;
212211
use rustc_data_structures::fx::FxIndexMap;
@@ -224,7 +223,6 @@ use rustc_middle::mir::{self, Location, MentionedItem, traversal};
224223
use rustc_middle::query::TyCtxtAt;
225224
use rustc_middle::ty::adjustment::{CustomCoerceUnsized, PointerCoercion};
226225
use rustc_middle::ty::layout::ValidityRequirement;
227-
use rustc_middle::ty::print::{shrunk_instance_name, with_no_trimmed_paths};
228226
use rustc_middle::ty::{
229227
self, GenericArgs, GenericParamDefKind, Instance, InstanceKind, Ty, TyCtxt, TypeFoldable,
230228
TypeVisitableExt, VtblEntry,
@@ -237,7 +235,10 @@ use rustc_span::source_map::{Spanned, dummy_spanned, respan};
237235
use rustc_span::{DUMMY_SP, Span};
238236
use tracing::{debug, instrument, trace};
239237

240-
use crate::errors::{self, EncounteredErrorWhileInstantiating, NoOptimizedMir, RecursionLimit};
238+
use crate::errors::{
239+
self, EncounteredErrorWhileInstantiating, EncounteredErrorWhileInstantiatingGlobalAsm,
240+
NoOptimizedMir, RecursionLimit,
241+
};
241242

242243
#[derive(PartialEq)]
243244
pub(crate) enum MonoItemCollectionStrategy {
@@ -525,11 +526,23 @@ fn collect_items_rec<'tcx>(
525526
&& starting_item.node.is_generic_fn()
526527
&& starting_item.node.is_user_defined()
527528
{
528-
let formatted_item = with_no_trimmed_paths!(starting_item.node.to_string());
529-
tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
530-
span: starting_item.span,
531-
formatted_item,
532-
});
529+
match starting_item.node {
530+
MonoItem::Fn(instance) => tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
531+
span: starting_item.span,
532+
kind: "fn",
533+
instance,
534+
}),
535+
MonoItem::Static(def_id) => tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
536+
span: starting_item.span,
537+
kind: "static",
538+
instance: Instance::new_raw(def_id, GenericArgs::empty()),
539+
}),
540+
MonoItem::GlobalAsm(_) => {
541+
tcx.dcx().emit_note(EncounteredErrorWhileInstantiatingGlobalAsm {
542+
span: starting_item.span,
543+
})
544+
}
545+
}
533546
}
534547
// Only updating `usage_map` for used items as otherwise we may be inserting the same item
535548
// multiple times (if it is first 'mentioned' and then later actually used), and the usage map
@@ -612,22 +625,7 @@ fn check_recursion_limit<'tcx>(
612625
if !recursion_limit.value_within_limit(adjusted_recursion_depth) {
613626
let def_span = tcx.def_span(def_id);
614627
let def_path_str = tcx.def_path_str(def_id);
615-
let (shrunk, written_to_path) = shrunk_instance_name(tcx, instance);
616-
let mut path = PathBuf::new();
617-
let was_written = if let Some(written_to_path) = written_to_path {
618-
path = written_to_path;
619-
true
620-
} else {
621-
false
622-
};
623-
tcx.dcx().emit_fatal(RecursionLimit {
624-
span,
625-
shrunk,
626-
def_span,
627-
def_path_str,
628-
was_written,
629-
path,
630-
});
628+
tcx.dcx().emit_fatal(RecursionLimit { span, instance, def_span, def_path_str });
631629
}
632630

633631
recursion_depths.insert(def_id, recursion_depth + 1);

compiler/rustc_monomorphize/src/errors.rs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,16 @@
1-
use std::path::PathBuf;
2-
31
use rustc_macros::{Diagnostic, LintDiagnostic};
4-
use rustc_middle::ty::Ty;
2+
use rustc_middle::ty::{Instance, Ty};
53
use rustc_span::{Span, Symbol};
64

75
#[derive(Diagnostic)]
86
#[diag(monomorphize_recursion_limit)]
9-
pub(crate) struct RecursionLimit {
7+
pub(crate) struct RecursionLimit<'tcx> {
108
#[primary_span]
119
pub span: Span,
12-
pub shrunk: String,
10+
pub instance: Instance<'tcx>,
1311
#[note]
1412
pub def_span: Span,
1513
pub def_path_str: String,
16-
#[note(monomorphize_written_to_path)]
17-
pub was_written: bool,
18-
pub path: PathBuf,
1914
}
2015

2116
#[derive(Diagnostic)]
@@ -53,10 +48,18 @@ pub(crate) struct CouldntDumpMonoStats {
5348

5449
#[derive(Diagnostic)]
5550
#[diag(monomorphize_encountered_error_while_instantiating)]
56-
pub(crate) struct EncounteredErrorWhileInstantiating {
51+
pub(crate) struct EncounteredErrorWhileInstantiating<'tcx> {
52+
#[primary_span]
53+
pub span: Span,
54+
pub kind: &'static str,
55+
pub instance: Instance<'tcx>,
56+
}
57+
58+
#[derive(Diagnostic)]
59+
#[diag(monomorphize_encountered_error_while_instantiating_global_asm)]
60+
pub(crate) struct EncounteredErrorWhileInstantiatingGlobalAsm {
5761
#[primary_span]
5862
pub span: Span,
59-
pub formatted_item: String,
6063
}
6164

6265
#[derive(Diagnostic)]

tests/ui/async-await/async-closures/post-mono-higher-ranked-hang-2.stderr

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
error: reached the recursion limit while instantiating `recur::<{async closure@$DIR/post-mono-higher-ranked-hang-2.rs:13:24: 13:32}>`
1+
error: reached the recursion limit while instantiating `recur<{async closure@$DIR/post-mono-higher-ranked-hang-2.rs:13:24: 13:32}>`
22
--> $DIR/post-mono-higher-ranked-hang-2.rs:13:17
33
|
44
LL | let _ = recur(&async || {

0 commit comments

Comments
 (0)