By making it ignore the parent field of spans within the diagnostic.
This is done with a new `DedupHashEncoder` type that uses the existing
`Encoder`/`SpanEncoder` traits to traverse the fields within `DiagInner`
and `Subdiag`.
Fixes#162901.
- Introduce `Subdiag::dedup_hash`, which mirrors
`DiagInner::dedup_hash` and is necessary for the subsequent commits.
- Change the name and structure of `not_yet_emitted` to be clearer.
- Change `retain_mut` to `retain`; mutability isn't required.
Remove `PartialOrd`/`Ord` impls for `Span`/`SpanData`
Because they are inconsistent with the `PartialEq`/`Eq` impls, and span ordering is inherently dubious. Details in individual commits.
r? @oli-obk
`Span` and `SpanData` encode four fields: `lo`/`hi`, `ctxt`, and
`parent`. `ctxt` and `parent` have unorderable types.
Both types ignore `ctxt` and `parent` for `PartialOrd`/`Ord`. But their
`PartialEq`/`Eq` impls do *not* ignore those fields. This eq/ord
inconsistency is a bug. It was introduced in #123165.
The idea of ordering spans in general is dubious, because of `ctxt` and
`parent`. But the idea of ordering spans just with `lo`/`hi` is fine.
Therefore, this commit does the following.
- Removes the `PartialOrd`/`Ord` impls for `Span`/`SpanData`
- Adds a `Span::lo_hi` method which can be used in lots of places where
span locations are involved in sorting. E.g.
`xs.sort_by_key(|span| span.lo_hi())`
- Adds `OrdSpan`, a newtype around `Span` that impls
`PartialEq`/`Eq`/`PartialOrd`/`Ord` using `lo_hi`. This is for storing
spans in ordered types like `BTreeMap<OrdSpan, T>`.
Note also that some `sort`+`dedup` combinations might not remove all
duplicates with the old eq/ord inconsistency. These now all do the right
thing, which could affect some error messages, though in practice
nothing in the test suite is affected.
Because they're all just special cases of warnings. This requires
introducing a new `Option<EmissionOverride>` field to `Warning` that
describes the special case behaviour; the `DiagInner::lint_id` field
also gets merged in.
Specific nice things about this:
- Removes some unreachable match arms for `Allow`/`Expect`.
- Removes the hacky upgrading of `Allow`/`Expect` to `Warning` in
`emit_future_breakage_report`.
- The types now have structure that used to be maintained by comments
and assertions. E.g. it's now impossible to not have a `lint_id` for
an `expect` lint. (I always found the `DiagInner::lint_id` field
confusing; it's clearer now.)
- There's a nice comment on `EmissionOverride` summarizing all the
different cases.
- A little less code overall.
There is one match arm handling some `ForceWarning` cases and another
arm handling the remaining `ForceWarning` case and also `Expect`. They
can be rearranged into one arm handling `ForceWarning` and one arm
handling `Expect`.
Also fix some comments:
- `ForceWarning` no longer has a field.
- Clarify the `LintExpectationId` location.
- The one about deduplication was inverted.
Currently it's used in a really hacky way: a diagnostic with an empty
message and some suggestions is stashed. Later on it might be retrieved
and its suggestions extracted. It uses `Level::Allow` so that it isn't
printed by `emit_stashed_diagnostics` at shutdown if it hasn't been
retrieved.
This isn't a normal stashed diagnostic, more just a case of "save some
information that might be useful for diagnostics later". We can record
the information more simply and directly.
This commit adds `paths_matching_assoc_types` fields to `Resolver` and
`ResolverGlobalCtxt`. These store the spans of the paths of interest.
The new subdiagnostic `AssocTypeWithSameName` is used to construct the
relevant suggestions when they are needed. Much nicer. The old approach
removed the stashed diagnostic and the new approach doesn't remove the
set entry, so a single span could conceivably match more than once,
presumably a good thing, though this doesn't show up in the test suite.
Remove `DiagInner::sort_span`
It's a field that can be used for sorting diagnostics. By default it is set to the primary span. It's only used for `BorrowckDiagnosticsBuffer`.
This commit removes it and adds a `sort_span` to each diagnostic recorded in `BorrowckDiagnosticsBuffer`. This avoids various other pieces of code having to deal with it.
r? @lqd
It's no longer ever used for stashing, so the code looking for it is
dead.
It became dead in PR 141610 when `generic_arg_infer` was stabilized and
`[T; _]` became valid.
It's a field that can be used for sorting diagnostics. By default it is
set to the primary span. It's only used for `BorrowckDiagnosticsBuffer`.
This commit removes it and adds a `sort_span` to each diagnostic
recorded in `BorrowckDiagnosticsBuffer`. This avoids various other
pieces of code having to deal with it.
`DiagInner` impls `PartialEq` and `Hash`, as you'd expect for storing it
in a hash table. But there's a couple of strange things.
- We only store the hash value of the `DiagInner` to do deduplication,
not the `DiagInner` itself, which means the `PartialEq` impl is
unused.
- The `Hash` impl only considers some of the fields. Some of the ignored
fields are clearly deliberate (there are comments) but for some it is
unclear if it is deliberate.
This commit:
- Removes the unused `PartialEq` impl.
- Inlines and removes `keys` now that it's not needed for `PartialEq`.
- Uses struct deconstruction to ensure no fields can be accidentally
ignored. I have preserved existing behaviour by assuming that all the
ignored fields are supposed to be ignored.
- Renames `hash` as an inherent method `dedup_hash` to indicate that
it's not a typical hash function, and simplifies it to just return
`Hash128` instead of being generic.
- Replaces the unnecessary `collect` on `args` with `as_slice`.
- Improves the comment on `emitted_diagnostics`.
It encodes the `emit` behaviour, one of:
- `BugAbort`: Abort as a bug.
- `FatalAbort`: Abort as a fatal error.
- `ErrorGuaranteed`: Return an `ErrorGuaranteed` (the default).
- `()`: return `()`.
This is useful but `Diag` is very widely used and it's arguably not
useful enough to be worth the generic parameter. This commit removes it.
Benefits:
- Many fewer generic parameters, including many functions where the
genericity is entirely uninteresting. This includes every
`Diagnostic::into_diag` and `Subdiagnostic::add_to_diag`. Removes the
need for the comment about `<G>` on `trait Diagnostic`.
- No `PhantomData` in `Diag`.
- Makes bootstrapping a bit faster.
The downside is there is no longer a single `emit` method.
- Getting a `!` return type requires calling `emit_bug` or `emit_fatal`.
This only affects a few call sites.
- Getting an `ErrorGuaranteed` return type requires calling `emit_err`.
This affects a lot of call sites. (It arguably makes call sites more
self-documenting.)
- Using the wrong `emit_*` on a diagnostic causes a runtime abort, which
previously couldn't occur. Seems unlikely, but it's not impossible.
- Note: If no particular return type is needed, `emit` can be used for
any diagnostic. (Bug/fatal diagnostics will still trigger abort.)
Adjust `bug!`/`span_bug!` emission
PR rust-lang/rust#161873 moved these macros from `rustc_middle` to `rustc_span`. In doing so it made some undesirable changes.
- The internal `emit_producing_nothing` became public.
- The macros now have different behaviour to function-based ICEs like `dcx.bug(..)` or `dcx.struct_bug(..).emit()`.
This commit reverts those changes. This brings back `Box<dyn Any>` output in a few tests because the panic payload is `ExplicitBug` (which std doesn't know about) rather than `String`. That might be worth fixing again in the future, but if so, it should be done in a way that works with all aborts, not just those done via the macros.
r? @mejrs
Currently it uses `eprintln!` for the "query stack during panic" header
and "end of query stack" footer and
`struct_failure_note(..).with_span(..).emit()` for the stack frames. The
difference is curious.
Looking more closely:
- failure notes lack a leading label (e.g. no "note: ");
- although the failure note is given a span, the span never renders
because the `AnnotateSnippetEmitter` used for the query stack has an
empty source map field;
- the JSON emitter is never involved here.
Therefore, the only difference between using `struct_failure_note` and
`eprintln!` is that the former prints in bold. But boldness for frames
isn't important; indeed, normal backtrace frames don't use bold.
So the commit changes query stack frame printing to use `eprintln!`,
removes some now unnecessary `dcx` arguments, and also removes
`struct_failure_note`. That leaves "For more information about an error,
try `rustc --explain {}`" as the only use of `FailureNote`.
PR #161873 moved these macros from `rustc_middle` to `rustc_span`. In
doing so it made some undesirable changes.
- The internal `emit_producing_nothing` became public.
- It gave the macros different behaviour to function-based ICEs like
`dcx.bug(..)` or `dcx.struct_bug(..).emit()`.
- `ExplicitBug` is not used, so `report_ice` prints an extraneous,
unintended "the compiler unexpectedly panicked" message.
- It broke the interaction between `span_bug!` and
`-Ztrack-diagnostics`.
This commit adjusts things to avoid the undesirable changes. It required
moving `ExplicitBug` to `rustc_span`. Setting `diag.emitted_at` fixed
the `-Ztrack-diagnostics` problem, seen in the change from `callback.rs`
to `validate.rs` in `track7.stderr`.
`Box<dyn Any>` output now occurs again in a few tests because the panic
payload is `ExplicitBug` (which std doesn't know about) rather than
`String`. That might be worth addressing in the future but it would
require a different/additional mechanism and is beyond the scope of this
PR.
Remove one remaining use of `Level::Help`
Unfortunately we can't yet get rid of `Level::Help` entirely because of `proc_macro::Help`. Details in individual commits.
r? @estebank
`annotate-snippets-rs` supports pointing at `Span`s without an underline. Start using that feature in `rustc`. We currently use secondary span labels with no text to point at context that should appear in the diagnostic, but that are merely context.
It's a trait that is used to give `Diag::emit` different return types
depending on the `G` in `Diag<'_, G>`. It works, but it's overkill.
There are only four different `G` types in practice (`BugAbort`,
`FatalAbort`, `ErrorGuaranteed`, and `()`) and having inherent `emit`
methods for each of those four concrete `Diag<'_, G>` types is good
enough.
This commit makes that change. This removes `EmissionGuarantee`
trait bounds from many places, which is nice.
Currently `Level` is used for both diagnostics and subdiagnostics. But
both diagnostics and subdiagnostics only use some of the levels. This
commit introduces `Sublevel` to tighten up the representation and
prevent impossible combinations.
These are dead since the old emitter was removed in Jan 2026
(3ccabc6a8d).
Also removed: `BRIGHT_BLUE`, `Level::color`, and a couple of `level`
fn parameters.
Some cleanups around fatal errors and delayed bugs
With the aim of making it easier to move some compiler passes to different locations. And in particular to allow moving them across `has_errors_or_delayed_bugs` calls. This is a prerequisite for a local change that improves the effectiveness of cargo build pipelining.
Fixes https://github.com/rust-lang/rust/issues/152204
A fatal error that doesn't actually abort is indistinguishable from a
regular error. And the only places where emit_almost_fatal is called,
the produced FatalError is ignored.
We have `DiagCtxt`, `DiagCtxtInner`, and `DiagCtxtHandle`. They're all
necessary, but the method placement is inconsistent. This commit
establishes a clearer rule: methods should *not* go on `DiagCtxt`
whenever possible.
Benefits:
- Simpler rule for deciding where to put a method.
- `impl Deref for DiagCtxtHandle` can be removed, including its
non-standard double-reference `&&'a DiagCtxt` return value.
This makes it impossible to accidentally discard a taint target by
calling `handle` on a `DiagCtxtHandle`.
- Catches some places where we were calling `dcx.handle()` when `dcx`
was already a handle.
The reason `rustc_ast_ir` and `rustc_pattern_analysis` have nested
`cfg_attr`s is so that they don't mention `cfg(bootstrap)` when nightly
or rustc cargo feature turned on. If you don't do it like that, they stop
compiling on stable (or rather, they emit unexpected cfg warnings...).
Introduce a mechanism to textually trim highlighted strings, so that we can print out "expected/found" note with shorter output while still keeping the highlighted inner parts.
```
error[E0308]: mismatched types
--> $DIR/long-type-E0308.rs:30:5
|
LL | ) -> <
| ______-
LL | | <
LL | | <T::Wrapper<T> as FooBar>::Assoc as FooBar
LL | | >::Assoc as FooBar
LL | | >::Wrapper<<T::Assoc as FooBar>::Assoc>
| |_______________________________________- expected `<_ as FooBar>::Wrapper<_>` because of return type
...
LL | value...oc())
| ^^^^^...^^^^^ expected `really_really_really_long_module::FooBar::Wrapper`, found `really_really_really_long_module::FooBar::Assoc`
|
= note: expected associated type `<<<<_ as FooBar>::Wrapper<_> as...pper<_>`
found associated type `<<<<_ as FooBar>::Assoc as Fo...pper<_>`
= note: an associated type was expected, but a different one was found
= note: the full name for the type has been written to '$TEST_BUILD_DIR/long-type-E0308.long-type-$LONG_TYPE_HASH.txt'
= note: consider using `--verbose` to print the full type name to the console
```
Fix post-monomorphization error note race in the parallel frontend
Fixesrust-lang/rust#154260. Part of https://github.com/rust-lang/rust/issues/154314.
`collect_items_rec` decides whether to attach the note "the above error was encountered while instantiating `fn ...`" by snapshotting the error count before processing a mono item and comparing it afterwards. The mono item graph is walked in parallel (the `par_for_each_in` in `collect_crate_mono_items`), so the global error count can be bumped by an error emitted while collecting a different item on another thread between the two reads. That makes an unrelated item get blamed, which showed up as a spurious note when using parallel frontend:
```
note: the above error was encountered while instantiating `fn std::rt::lang_start::<()>`
```
This PR records the thread that emits each error alongside its `ErrorGuaranteed` in `err_guars`, `lint_err_guars`, and the stashed-diagnostics map, and add `err_count_on_current_thread`, which counts only the errors whose recorded thread is the calling thread. The collector uses it for the snapshot and comparison, so the delta is not affected by errors emitted on other threads. In serial compilation it is equivalent to a delta of `err_count`.