Skip to main content

rustc_errors/
lib.rs

1//! Diagnostics creation and emission for `rustc`.
2//!
3//! This module contains the code for creating and emitting diagnostics.
4
5// tidy-alphabetical-start
6#![feature(default_field_values)]
7#![feature(macro_metavar_expr_concat)]
8#![feature(negative_impls)]
9#![feature(register_tool)]
10#![register_tool(lint)]
11// tidy-alphabetical-end
12
13extern crate self as rustc_errors;
14
15use std::backtrace::{Backtrace, BacktraceStatus};
16use std::borrow::Cow;
17use std::cell::Cell;
18use std::ffi::OsStr;
19use std::hash::Hash;
20use std::io::Write;
21use std::num::NonZero;
22use std::ops::DerefMut;
23use std::path::{Path, PathBuf};
24use std::thread::ThreadId;
25use std::{assert_matches, fmt, mem, panic};
26
27use Level::*;
28// Used by external projects such as `rust-gpu`.
29// See https://github.com/rust-lang/rust/pull/115393.
30pub use anstream::{AutoStream, ColorChoice};
31pub use anstyle::{
32    Ansi256Color, AnsiColor, Color, EffectIter, Effects, Reset, RgbColor, Style as Anstyle,
33};
34pub use codes::*;
35pub use decorate_diag::{BufferedEarlyLint, DecorateDiagCompat, LintBuffer};
36pub use diagnostic::{
37    Diag, DiagDecorator, DiagInner, DiagLocation, DiagStyledString, Diagnostic, StringPart,
38    Subdiag, Subdiagnostic,
39};
40pub use diagnostic_impls::{
41    DiagSymbolList, ElidedLifetimeInPathSubdiag, ExpectedLifetimeParameter,
42    IndicateAnonymousLifetime, SingleLabelManySpans,
43};
44pub use emitter::ColorConfig;
45use emitter::{DynEmitter, Emitter};
46use rustc_ast::attr::version::RustcVersion;
47use rustc_data_structures::AtomicRef;
48use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
49use rustc_data_structures::sync::{DynSend, Lock};
50pub use rustc_error_messages::{
51    DiagArg, DiagArgFromDisplay, DiagArgMap, DiagArgName, DiagArgValue, DiagMessage, IntoDiagArg,
52    LanguageIdentifier, MultiSpan, SpanLabel, fluent_bundle, into_diag_arg_using_display,
53};
54use rustc_hashes::Hash128;
55use rustc_lint_defs::LintExpectationId;
56pub use rustc_lint_defs::{Applicability, listify, pluralize};
57pub use rustc_macros::msg;
58use rustc_macros::{Decodable, Encodable};
59pub use rustc_span::ErrorGuaranteed;
60pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker, catch_fatal_errors};
61pub use rustc_span::macros::ExplicitBug;
62use rustc_span::source_map::SourceMap;
63use rustc_span::{DUMMY_SP, Span};
64use tracing::debug;
65
66use crate::emitter::TimingEvent;
67use crate::formatting::DiagMessageAddArg;
68pub use crate::formatting::format_diag_message;
69use crate::timings::TimingRecord;
70
71pub mod annotate_snippet_emitter_writer;
72pub mod codes;
73mod decorate_diag;
74mod dedup_hash;
75mod diagnostic;
76mod diagnostic_impls;
77pub mod emitter;
78pub mod formatting;
79pub mod json;
80mod lock;
81pub mod markdown;
82pub mod timings;
83
84pub type PResult<'a, T> = Result<T, Diag<'a>>;
85
86// `PResult` is used a lot. Make sure it doesn't unintentionally get bigger.
87#[cfg(target_pointer_width = "64")]
88const _: [(); 24] = [(); ::std::mem::size_of::<PResult<'_, ()>>()];rustc_data_structures::static_assert_size!(PResult<'_, ()>, 24);
89#[cfg(target_pointer_width = "64")]
90const _: [(); 24] = [(); ::std::mem::size_of::<PResult<'_, bool>>()];rustc_data_structures::static_assert_size!(PResult<'_, bool>, 24);
91
92#[derive(#[automatically_derived]impl ::core::fmt::Debug for SuggestionStyle {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "HideCodeInline HideCodeAlways CompletelyHidden ShowCode ShowAlways",
            match self {
                SuggestionStyle::HideCodeInline => 0usize,
                SuggestionStyle::HideCodeAlways => 15usize,
                SuggestionStyle::CompletelyHidden => 30usize,
                SuggestionStyle::ShowCode => 47usize,
                SuggestionStyle::ShowAlways => 56usize,
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    SuggestionStyle {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SuggestionStyle {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for SuggestionStyle { }Eq, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SuggestionStyle {
}
#[automatically_derived]impl ::core::clone::Clone for SuggestionStyle {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for SuggestionStyle { }Copy, #[automatically_derived]impl ::core::hash::Hash for SuggestionStyle {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for SuggestionStyle {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        SuggestionStyle::HideCodeInline => { 0usize }
                        SuggestionStyle::HideCodeAlways => { 1usize }
                        SuggestionStyle::CompletelyHidden => { 2usize }
                        SuggestionStyle::ShowCode => { 3usize }
                        SuggestionStyle::ShowAlways => { 4usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for SuggestionStyle {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { SuggestionStyle::HideCodeInline }
                    1usize => { SuggestionStyle::HideCodeAlways }
                    2usize => { SuggestionStyle::CompletelyHidden }
                    3usize => { SuggestionStyle::ShowCode }
                    4usize => { SuggestionStyle::ShowAlways }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `SuggestionStyle`, expected 0..5, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
93pub enum SuggestionStyle {
94    /// Hide the suggested code when displaying this suggestion inline.
95    HideCodeInline,
96    /// Always hide the suggested code but display the message.
97    HideCodeAlways,
98    /// Do not display this suggestion in the cli output, it is only meant for tools.
99    CompletelyHidden,
100    /// Always show the suggested code.
101    /// This will *not* show the code if the suggestion is inline *and* the suggested code is
102    /// empty.
103    ShowCode,
104    /// Always show the suggested code independently.
105    ShowAlways,
106}
107
108impl SuggestionStyle {
109    fn hide_inline(&self) -> bool {
110        !#[allow(non_exhaustive_omitted_patterns)] match *self {
    SuggestionStyle::ShowCode => true,
    _ => false,
}matches!(*self, SuggestionStyle::ShowCode)
111    }
112}
113
114/// Represents the help messages seen on a diagnostic.
115#[derive(#[automatically_derived]impl ::core::clone::Clone for Suggestions {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Enabled(__self_0) =>
                Suggestions::Enabled(::core::clone::Clone::clone(__self_0)),
            Self::Sealed(__self_0) =>
                Suggestions::Sealed(::core::clone::Clone::clone(__self_0)),
            Self::Disabled => Suggestions::Disabled,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Suggestions {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Enabled(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Enabled", &__self_0),
            Self::Sealed(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Sealed", &__self_0),
            Self::Disabled =>
                ::core::fmt::Formatter::write_str(f, "Disabled"),
        }
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    Suggestions {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Suggestions {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Enabled(__self_0), Self::Enabled(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Sealed(__self_0), Self::Sealed(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for Suggestions {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state);
        match self {
            Self::Enabled(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            Self::Sealed(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Suggestions {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        Suggestions::Enabled(ref __binding_0) => { 0usize }
                        Suggestions::Sealed(ref __binding_0) => { 1usize }
                        Suggestions::Disabled => { 2usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    Suggestions::Enabled(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    Suggestions::Sealed(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    Suggestions::Disabled => {}
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for Suggestions {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        Suggestions::Enabled(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        Suggestions::Sealed(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    2usize => { Suggestions::Disabled }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Suggestions`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
116pub enum Suggestions {
117    /// Indicates that new suggestions can be added or removed from this diagnostic.
118    ///
119    /// `DiagInner`'s new_* methods initialize the `suggestions` field with
120    /// this variant. Also, this is the default variant for `Suggestions`.
121    Enabled(Vec<CodeSuggestion>),
122    /// Indicates that suggestions cannot be added or removed from this diagnostic.
123    ///
124    /// Gets toggled when `.seal_suggestions()` is called on the `DiagInner`.
125    Sealed(Box<[CodeSuggestion]>),
126    /// Indicates that no suggestion is available for this diagnostic.
127    ///
128    /// Gets toggled when `.disable_suggestions()` is called on the `DiagInner`.
129    Disabled,
130}
131
132impl Suggestions {
133    /// Returns the underlying list of suggestions.
134    pub fn unwrap_tag(self) -> Vec<CodeSuggestion> {
135        match self {
136            Suggestions::Enabled(suggestions) => suggestions,
137            Suggestions::Sealed(suggestions) => suggestions.into_vec(),
138            Suggestions::Disabled => Vec::new(),
139        }
140    }
141
142    pub fn len(&self) -> usize {
143        match self {
144            Suggestions::Enabled(suggestions) => suggestions.len(),
145            Suggestions::Sealed(suggestions) => suggestions.len(),
146            Suggestions::Disabled => 0,
147        }
148    }
149}
150
151impl Default for Suggestions {
152    fn default() -> Self {
153        Self::Enabled(::alloc::vec::Vec::new()vec![])
154    }
155}
156
157#[derive(#[automatically_derived]impl ::core::clone::Clone for CodeSuggestion {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        CodeSuggestion {
            substitutions: ::core::clone::Clone::clone(&self.substitutions),
            msg: ::core::clone::Clone::clone(&self.msg),
            style: ::core::clone::Clone::clone(&self.style),
            applicability: ::core::clone::Clone::clone(&self.applicability),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for CodeSuggestion {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "CodeSuggestion substitutions msg style applicability",
            &self.substitutions, &self.msg, &self.style, &&self.applicability)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    CodeSuggestion {
}
#[automatically_derived]impl ::core::cmp::PartialEq for CodeSuggestion {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.substitutions == other.substitutions && self.msg == other.msg &&
                self.style == other.style &&
            self.applicability == other.applicability
    }
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for CodeSuggestion {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.substitutions, state);
        ::core::hash::Hash::hash(&self.msg, state);
        ::core::hash::Hash::hash(&self.style, state);
        ::core::hash::Hash::hash(&self.applicability, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for CodeSuggestion {
            fn encode(&self, __encoder: &mut __E) {
                let CodeSuggestion {
                        substitutions: ref __binding_0,
                        msg: ref __binding_1,
                        style: ref __binding_2,
                        applicability: ref __binding_3 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_3,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for CodeSuggestion {
            fn decode(__decoder: &mut __D) -> Self {
                CodeSuggestion {
                    substitutions: ::rustc_serialize::Decodable::decode(__decoder),
                    msg: ::rustc_serialize::Decodable::decode(__decoder),
                    style: ::rustc_serialize::Decodable::decode(__decoder),
                    applicability: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
158pub struct CodeSuggestion {
159    /// Each substitute can have multiple variants due to multiple
160    /// applicable suggestions
161    ///
162    /// `foo.bar` might be replaced with `a.b` or `x.y` by replacing
163    /// `foo` and `bar` on their own:
164    ///
165    /// ```ignore (illustrative)
166    /// vec![
167    ///     Substitution { parts: vec![(0..3, "a"), (4..7, "b")] },
168    ///     Substitution { parts: vec![(0..3, "x"), (4..7, "y")] },
169    /// ]
170    /// ```
171    ///
172    /// or by replacing the entire span:
173    ///
174    /// ```ignore (illustrative)
175    /// vec![
176    ///     Substitution { parts: vec![(0..7, "a.b")] },
177    ///     Substitution { parts: vec![(0..7, "x.y")] },
178    /// ]
179    /// ```
180    pub substitutions: Vec<Substitution>,
181    pub msg: DiagMessage,
182    /// Visual representation of this suggestion.
183    pub style: SuggestionStyle,
184    /// Whether or not the suggestion is approximate
185    ///
186    /// Sometimes we may show suggestions with placeholders,
187    /// which are useful for users but not useful for
188    /// tools like rustfix
189    pub applicability: Applicability,
190}
191
192#[derive(#[automatically_derived]impl ::core::clone::Clone for Substitution {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        Substitution { parts: ::core::clone::Clone::clone(&self.parts) }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Substitution {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "Substitution parts", &&self.parts)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    Substitution {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Substitution {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.parts == other.parts }
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for Substitution {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.parts, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Substitution {
            fn encode(&self, __encoder: &mut __E) {
                let Substitution { parts: ref __binding_0 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for Substitution {
            fn decode(__decoder: &mut __D) -> Self {
                Substitution {
                    parts: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
193/// See the docs on `CodeSuggestion::substitutions`
194pub struct Substitution {
195    pub parts: Vec<SubstitutionPart>,
196}
197
198#[derive(#[automatically_derived]impl ::core::clone::Clone for SubstitutionPart {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        SubstitutionPart {
            span: ::core::clone::Clone::clone(&self.span),
            snippet: ::core::clone::Clone::clone(&self.snippet),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for SubstitutionPart {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "SubstitutionPart span snippet", &self.span, &&self.snippet)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    SubstitutionPart {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SubstitutionPart {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.span == other.span && self.snippet == other.snippet
    }
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for SubstitutionPart {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.span, state);
        ::core::hash::Hash::hash(&self.snippet, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for SubstitutionPart {
            fn encode(&self, __encoder: &mut __E) {
                let SubstitutionPart {
                        span: ref __binding_0, snippet: ref __binding_1 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for SubstitutionPart {
            fn decode(__decoder: &mut __D) -> Self {
                SubstitutionPart {
                    span: ::rustc_serialize::Decodable::decode(__decoder),
                    snippet: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
199pub struct SubstitutionPart {
200    pub span: Span,
201    pub snippet: String,
202}
203
204/// Signifies that the compiler died due to a delayed bug rather than a failed
205/// assertion, etc.
206pub struct DelayedBugPanic;
207
208/// A `DiagCtxt` deals with errors and other compiler output.
209/// Certain errors (fatal, bug, unimpl) may cause immediate exit,
210/// others log errors for later reporting.
211///
212/// Note: methods should be implemented not on this type but on `DiagCtxtHandle` or
213/// `DiagCtxtInner`, whenever possible.
214pub struct DiagCtxt {
215    inner: Lock<DiagCtxtInner>,
216}
217
218#[derive(#[automatically_derived]impl<'a> ::core::marker::Copy for DiagCtxtHandle<'a> {
}Copy, #[automatically_derived]#[doc(hidden)]unsafe impl<'a>
    ::core::clone::TrivialClone for DiagCtxtHandle<'a> {
}
#[automatically_derived]impl<'a> ::core::clone::Clone for DiagCtxtHandle<'a> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<&'a DiagCtxt>;
        let _:
                ::core::clone::AssertParamIsClone<Option<&'a Cell<Option<ErrorGuaranteed>>>>;
        *self
    }
}Clone)]
219pub struct DiagCtxtHandle<'a> {
220    dcx: &'a DiagCtxt,
221    /// Some contexts create `DiagCtxtHandle` with this field set, and thus all
222    /// errors emitted with it will automatically taint when emitting errors.
223    tainted_with_errors: Option<&'a Cell<Option<ErrorGuaranteed>>>,
224}
225
226/// This inner struct exists to keep it all behind a single lock;
227/// this is done to prevent possible deadlocks in a multi-threaded compiler,
228/// as well as inconsistent state observation.
229///
230/// Note: methods should be implemented not on this type but on `DiagCtxtHandle` whenever possible.
231/// Methods on this type should only be used e.g. when the lock is already held.
232struct DiagCtxtInner {
233    flags: DiagCtxtFlags,
234
235    /// The error guarantees from all emitted errors, each paired with the
236    /// thread that emitted it. The length gives the error count.
237    err_guars: Vec<(ErrorGuaranteed, ThreadId)>,
238    /// The error guarantee from all emitted lint errors, each paired with the
239    /// thread that emitted it. The length gives the lint error count.
240    lint_err_guars: Vec<(ErrorGuaranteed, ThreadId)>,
241    /// The delayed bugs and their error guarantees.
242    delayed_bugs: Vec<(DelayedDiagInner, ErrorGuaranteed)>,
243
244    /// The error count shown to the user at the end.
245    deduplicated_err_count: usize,
246    /// The warning count shown to the user at the end.
247    deduplicated_warn_count: usize,
248
249    emitter: Box<DynEmitter>,
250
251    /// Must we produce a diagnostic to justify the use of the expensive
252    /// `trimmed_def_paths` function? Backtrace is the location of the call.
253    must_produce_diag: Option<Backtrace>,
254
255    /// Has this diagnostic context printed any diagnostics? (I.e. has
256    /// `self.emitter.emit_diagnostic()` been called?
257    has_printed: bool,
258
259    /// This flag indicates that an expected diagnostic was emitted and suppressed.
260    /// This is used for the `must_produce_diag` check.
261    suppressed_expected_diag: bool,
262
263    /// This set contains the code of all emitted diagnostics to avoid
264    /// emitting the same diagnostic with extended help (`--teach`) twice, which
265    /// would be unnecessary repetition.
266    taught_diagnostics: FxHashSet<ErrCode>,
267
268    /// Used to suggest rustc --explain `<error code>`
269    emitted_diagnostic_codes: FxIndexSet<ErrCode>,
270
271    /// This set contains a hash of every diagnostic that has been emitted by
272    /// this `DiagCtxt`. These hashes are used to avoid emitting the same error
273    /// twice. (Because we don't store the diagnostics themselves, two
274    /// different diagnostics with the same hash value will be considered
275    /// equivalent. Such collisions should be vanishingly rare...)
276    emitted_diagnostics: FxHashSet<Hash128>,
277
278    /// We only want to emit `recursion_depth_exceeding_limit` once per
279    /// crate. Otherwise crates like `calimero-store` emit more than
280    /// a thousand warnings.
281    ///
282    /// We only check this in `TRACK_DIAGNOSTIC` meaning that the diagnostics
283    /// still get tracked by the query system, even if they don't get emitted
284    /// to users.
285    emitted_recursion_depth_exceeding_limit: bool,
286
287    /// Stashed diagnostics emitted in one stage of the compiler that may be
288    /// stolen and emitted/cancelled by other stages (e.g. to improve them and
289    /// add more information). All stashed diagnostics must be emitted with
290    /// `emit_stashed_diagnostics` by the time the `DiagCtxtInner` is dropped,
291    /// otherwise an assertion failure will occur.
292    stashed_diagnostics:
293        FxIndexMap<StashKey, FxIndexMap<Span, (DiagInner, Option<ErrorGuaranteed>, ThreadId)>>,
294
295    future_breakage_diagnostics: Vec<DiagInner>,
296
297    /// Any `expect` lint will carry the [`LintExpectationId`] of the expectation that can be
298    /// marked as fulfilled. This field is a collection of all [`LintExpectationId`]s
299    /// that have been marked as fulfilled this way.
300    ///
301    /// Emitting expectations after having stolen this field can happen. In particular, an
302    /// `#[expect(warnings)]` can easily make the `UNFULFILLED_LINT_EXPECTATIONS` lint expect
303    /// itself. To avoid needless complexity in this corner case, we tolerate failing to track
304    /// those expectations.
305    ///
306    /// [RFC-2383]: https://rust-lang.github.io/rfcs/2383-lint-reasons.html
307    fulfilled_expectations: FxIndexSet<LintExpectationId>,
308
309    /// The file where the ICE information is stored. This allows delayed_span_bug backtraces to be
310    /// stored along side the main panic backtrace.
311    ice_file: Option<PathBuf>,
312
313    /// Controlled by `-Z hint-msrv`; this allows avoiding emitting lints which would raise MSRV.
314    msrv: Option<RustcVersion>,
315}
316
317/// A key denoting where from a diagnostic was stashed.
318#[derive(#[automatically_derived]impl ::core::marker::Copy for StashKey { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for StashKey {
}
#[automatically_derived]impl ::core::clone::Clone for StashKey {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for StashKey
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for StashKey {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for StashKey { }Eq, #[automatically_derived]impl ::core::hash::Hash for StashKey {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, #[automatically_derived]impl ::core::fmt::Debug for StashKey {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "ItemNoType EarlySyntaxWarning CallIntoMethod LifetimeIsChar MaybeFruTypo CallAssocMethod UndeterminedMacroResolution ExprInPat GenericInFieldExpr ReturnTypeNotation ParenAroundGuardedPatInMatchArm",
            match self {
                StashKey::ItemNoType => 0usize,
                StashKey::EarlySyntaxWarning => 11usize,
                StashKey::CallIntoMethod => 30usize,
                StashKey::LifetimeIsChar => 45usize,
                StashKey::MaybeFruTypo => 60usize,
                StashKey::CallAssocMethod => 73usize,
                StashKey::UndeterminedMacroResolution => 89usize,
                StashKey::ExprInPat => 117usize,
                StashKey::GenericInFieldExpr => 127usize,
                StashKey::ReturnTypeNotation => 146usize,
                StashKey::ParenAroundGuardedPatInMatchArm => 165usize,
            })
    }
}Debug)]
319pub enum StashKey {
320    ItemNoType,
321    EarlySyntaxWarning,
322    CallIntoMethod,
323    /// When an invalid lifetime e.g. `'2` should be reinterpreted
324    /// as a char literal in the parser
325    LifetimeIsChar,
326    /// Maybe there was a typo where a comma was forgotten before
327    /// FRU syntax
328    MaybeFruTypo,
329    CallAssocMethod,
330    UndeterminedMacroResolution,
331    /// Used by `Parser::maybe_recover_trailing_expr`
332    ExprInPat,
333    /// If in the parser we detect a field expr with turbofish generic params it's possible that
334    /// it's a method call without parens. If later on in `hir_typeck` we find out that this is
335    /// the case we suppress this message and we give a better suggestion.
336    GenericInFieldExpr,
337    ReturnTypeNotation,
338    ParenAroundGuardedPatInMatchArm,
339}
340
341fn default_track_diagnostic<R>(diag: DiagInner, f: &mut dyn FnMut(DiagInner) -> R) -> R {
342    (*f)(diag)
343}
344
345/// Diagnostics emitted by `DiagCtxtInner::emit_diagnostic` are passed through this function. Used
346/// for tracking by incremental, to replay diagnostics as necessary.
347pub static TRACK_DIAGNOSTIC: AtomicRef<
348    fn(DiagInner, &mut dyn FnMut(DiagInner) -> Option<ErrorGuaranteed>) -> Option<ErrorGuaranteed>,
349> = AtomicRef::new(&(default_track_diagnostic as _));
350
351#[derive(#[automatically_derived]impl ::core::marker::Copy for DiagCtxtFlags { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for DiagCtxtFlags {
}
#[automatically_derived]impl ::core::clone::Clone for DiagCtxtFlags {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        let _: ::core::clone::AssertParamIsClone<Option<NonZero<usize>>>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::default::Default for DiagCtxtFlags {
    #[inline]
    fn default() -> Self {
        DiagCtxtFlags {
            can_emit_warnings: ::core::default::Default::default(),
            treat_err_as_bug: ::core::default::Default::default(),
            eagerly_emit_delayed_bugs: ::core::default::Default::default(),
            macro_backtrace: ::core::default::Default::default(),
            deduplicate_diagnostics: ::core::default::Default::default(),
            track_diagnostics: ::core::default::Default::default(),
        }
    }
}Default)]
352pub struct DiagCtxtFlags {
353    /// If false, warning-level lints are suppressed.
354    /// (rustc: see `--allow warnings` and `--cap-lints`)
355    pub can_emit_warnings: bool,
356    /// If Some, the Nth error-level diagnostic is upgraded to bug-level.
357    /// (rustc: see `-Z treat-err-as-bug`)
358    pub treat_err_as_bug: Option<NonZero<usize>>,
359    /// Eagerly emit delayed bugs as errors, so that the compiler debugger may
360    /// see all of the errors being emitted at once.
361    pub eagerly_emit_delayed_bugs: bool,
362    /// Show macro backtraces.
363    /// (rustc: see `-Z macro-backtrace`)
364    pub macro_backtrace: bool,
365    /// If true, identical diagnostics are reported only once.
366    pub deduplicate_diagnostics: bool,
367    /// Track where errors are created. Enabled with `-Ztrack-diagnostics`.
368    pub track_diagnostics: bool,
369}
370
371impl Drop for DiagCtxtInner {
372    fn drop(&mut self) {
373        // For tools using `interface::run_compiler` (e.g. rustc, rustdoc)
374        // stashed diagnostics will have already been emitted. But for others
375        // that don't use `interface::run_compiler` (e.g. rustfmt, some clippy
376        // lints) this fallback is necessary.
377        //
378        // Important: it is sound to produce an `ErrorGuaranteed` when stashing
379        // errors because they are guaranteed to be emitted here or earlier.
380        self.emit_stashed_diagnostics();
381
382        // Important: it is sound to produce an `ErrorGuaranteed` when emitting
383        // delayed bugs because they are guaranteed to be emitted here if
384        // necessary.
385        self.flush_delayed();
386
387        // Sanity check: did we use some of the expensive `trimmed_def_paths` functions
388        // unexpectedly, that is, without producing diagnostics? If so, for debugging purposes, we
389        // suggest where this happened and how to avoid it.
390        if !self.has_printed && !self.suppressed_expected_diag && !std::thread::panicking() {
391            if let Some(backtrace) = &self.must_produce_diag {
392                let suggestion = match backtrace.status() {
393                    BacktraceStatus::Disabled => String::from(
394                        "Backtraces are currently disabled: set `RUST_BACKTRACE=1` and re-run \
395                        to see where it happened.",
396                    ),
397                    BacktraceStatus::Captured => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("This happened in the following `must_produce_diag` call\'s backtrace:\n{0}",
                backtrace))
    })format!(
398                        "This happened in the following `must_produce_diag` call's backtrace:\n\
399                        {backtrace}",
400                    ),
401                    _ => String::from("(impossible to capture backtrace where this happened)"),
402                };
403                {
    ::core::panicking::panic_fmt(format_args!("`trimmed_def_paths` called, diagnostics were expected but none were emitted. Use `with_no_trimmed_paths` for debugging. {0}",
            suggestion));
};panic!(
404                    "`trimmed_def_paths` called, diagnostics were expected but none were emitted. \
405                    Use `with_no_trimmed_paths` for debugging. {suggestion}"
406                );
407            }
408        }
409    }
410}
411
412impl DiagCtxt {
413    pub fn disable_warnings(mut self) -> Self {
414        self.inner.get_mut().flags.can_emit_warnings = false;
415        self
416    }
417
418    pub fn with_flags(mut self, flags: DiagCtxtFlags) -> Self {
419        self.inner.get_mut().flags = flags;
420        self
421    }
422
423    pub fn with_ice_file(mut self, ice_file: PathBuf) -> Self {
424        self.inner.get_mut().ice_file = Some(ice_file);
425        self
426    }
427
428    pub fn with_msrv(mut self, msrv: RustcVersion) -> Self {
429        self.inner.get_mut().msrv = Some(msrv);
430        self
431    }
432
433    pub fn new(emitter: Box<DynEmitter>) -> Self {
434        Self { inner: Lock::new(DiagCtxtInner::new(emitter)) }
435    }
436
437    pub fn handle<'a>(&'a self) -> DiagCtxtHandle<'a> {
438        DiagCtxtHandle { dcx: self, tainted_with_errors: None }
439    }
440}
441
442impl<'a> DiagCtxtHandle<'a> {
443    pub fn make_silent(&self) {
444        let mut inner = self.dcx.inner.borrow_mut();
445        inner.emitter = Box::new(emitter::SilentEmitter {});
446    }
447
448    pub fn set_emitter(&self, emitter: Box<dyn Emitter + DynSend>) {
449        self.dcx.inner.borrow_mut().emitter = emitter;
450    }
451
452    // This is here to not allow mutation of flags; as of this writing it's used in
453    // `emit_lint_base` and in tests in `rustc_interface`.
454    pub fn can_emit_warnings(&self) -> bool {
455        self.dcx.inner.borrow().flags.can_emit_warnings
456    }
457
458    /// Resets the diagnostic error count as well as the cached emitted diagnostics.
459    ///
460    /// NOTE: *do not* call this function from rustc. It is only meant to be called from external
461    /// tools that want to reuse a `Parser` cleaning the previously emitted diagnostics as well as
462    /// the overall count of emitted error diagnostics.
463    pub fn reset_err_count(&self) {
464        // Use destructuring so that if a field gets added to `DiagCtxtInner`, it's impossible to
465        // fail to update this method as well.
466        let mut inner = self.dcx.inner.borrow_mut();
467        let DiagCtxtInner {
468            flags: _,
469            err_guars,
470            lint_err_guars,
471            delayed_bugs,
472            deduplicated_err_count,
473            deduplicated_warn_count,
474            emitter: _,
475            must_produce_diag,
476            has_printed,
477            suppressed_expected_diag,
478            taught_diagnostics,
479            emitted_diagnostic_codes,
480            emitted_diagnostics,
481            emitted_recursion_depth_exceeding_limit,
482            stashed_diagnostics,
483            future_breakage_diagnostics,
484            fulfilled_expectations,
485            ice_file: _,
486            msrv: _,
487        } = inner.deref_mut();
488
489        // For the `Vec`s and `HashMap`s, we overwrite with an empty container to free the
490        // underlying memory (which `clear` would not do).
491        *err_guars = Default::default();
492        *lint_err_guars = Default::default();
493        *delayed_bugs = Default::default();
494        *deduplicated_err_count = 0;
495        *deduplicated_warn_count = 0;
496        *must_produce_diag = None;
497        *has_printed = false;
498        *suppressed_expected_diag = false;
499        *taught_diagnostics = Default::default();
500        *emitted_diagnostic_codes = Default::default();
501        *emitted_diagnostics = Default::default();
502        *emitted_recursion_depth_exceeding_limit = false;
503        *stashed_diagnostics = Default::default();
504        *future_breakage_diagnostics = Default::default();
505        *fulfilled_expectations = Default::default();
506    }
507
508    /// Link this to a taintable context so that emitting errors will automatically set
509    /// the `Option<ErrorGuaranteed>` instead of having to do that manually at every error
510    /// emission site.
511    pub fn into_taintable(
512        self,
513        tainted_with_errors: &'a Cell<Option<ErrorGuaranteed>>,
514    ) -> DiagCtxtHandle<'a> {
515        DiagCtxtHandle { dcx: self.dcx, tainted_with_errors: Some(tainted_with_errors) }
516    }
517
518    /// Stashes a diagnostic for possible later improvement in a different,
519    /// later stage of the compiler. Possible actions depend on the diagnostic
520    /// level:
521    /// - Level::Bug, Level:Fatal: not allowed, will trigger a panic.
522    /// - Level::Error: immediately counted as an error that has occurred, because it
523    ///   is guaranteed to be emitted eventually. Can be later accessed with the
524    ///   provided `span` and `key` through
525    ///   [`DiagCtxtHandle::try_steal_modify_and_emit_err`] or
526    ///   [`DiagCtxtHandle::try_steal_replace_and_emit_err`]. These do not allow
527    ///   cancellation or downgrading of the error. Returns
528    ///   `Some(ErrorGuaranteed)`.
529    /// - Level::DelayedBug: this does happen occasionally with errors that are
530    ///   downgraded to delayed bugs. It is not stashed, but immediately
531    ///   emitted as a delayed bug. This is because stashing it would cause it
532    ///   to be counted by `err_count` which we don't want. It doesn't matter
533    ///   that we cannot steal and improve it later, because it's not a
534    ///   user-facing error. Returns `Some(ErrorGuaranteed)` as is normal for
535    ///   delayed bugs.
536    /// - Level::Warning and lower (i.e. !is_error()): can be accessed with the
537    ///   provided `span` and `key` through [`DiagCtxtHandle::steal_non_err()`]. This
538    ///   allows cancelling and downgrading of the diagnostic. Returns `None`.
539    pub fn stash_diagnostic(
540        &self,
541        span: Span,
542        key: StashKey,
543        diag: DiagInner,
544    ) -> Option<ErrorGuaranteed> {
545        let guar = match diag.level {
546            Bug | Fatal => {
547                self.span_bug(
548                    span,
549                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid level in `stash_diagnostic`: {0:?}",
                diag.level))
    })format!("invalid level in `stash_diagnostic`: {:?}", diag.level),
550                );
551            }
552            // We delay a bug here so that `-Ztreat-err-as-bug -Zeagerly-emit-delayed-bugs`
553            // can be used to create a backtrace at the stashing site instead of whenever the
554            // diagnostic context is dropped and thus delayed bugs are emitted.
555            Error => Some(self.span_delayed_bug(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("stashing {0:?}", key))
    })format!("stashing {key:?}"))),
556            DelayedBug => {
557                return self.dcx.inner.borrow_mut().emit_diagnostic(diag, self.tainted_with_errors);
558            }
559            Warning(_) | Note | Help | FailureNote => None,
560        };
561
562        // FIXME(Centril, #69537): Consider reintroducing panic on overwriting a stashed diagnostic
563        // if/when we have a more robust macro-friendly replacement for `(span, key)` as a key.
564        // See the PR for a discussion.
565        self.dcx
566            .inner
567            .borrow_mut()
568            .stashed_diagnostics
569            .entry(key)
570            .or_default()
571            .insert(span.with_parent(None), (diag, guar, std::thread::current().id()));
572
573        guar
574    }
575
576    /// Steal a previously stashed non-error diagnostic with the given `Span`
577    /// and [`StashKey`] as the key. Panics if the found diagnostic is an
578    /// error.
579    pub fn steal_non_err(self, span: Span, key: StashKey) -> Option<Diag<'a>> {
580        // FIXME(#120456) - is `swap_remove` correct?
581        let (diag, guar, _) =
582            self.dcx.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
583                |stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
584            )?;
585        if !!diag.is_error() {
    ::core::panicking::panic("assertion failed: !diag.is_error()")
};assert!(!diag.is_error());
586        if !guar.is_none() {
    ::core::panicking::panic("assertion failed: guar.is_none()")
};assert!(guar.is_none());
587        Some(Diag::new_diagnostic(self, diag))
588    }
589
590    /// Steals a previously stashed error with the given `Span` and
591    /// [`StashKey`] as the key, modifies it, and emits it. Returns `None` if
592    /// no matching diagnostic is found. Panics if the found diagnostic's level
593    /// isn't `Level::Error`.
594    pub fn try_steal_modify_and_emit_err<F>(
595        self,
596        span: Span,
597        key: StashKey,
598        mut modify_err: F,
599    ) -> Option<ErrorGuaranteed>
600    where
601        F: FnMut(&mut Diag<'_>),
602    {
603        // FIXME(#120456) - is `swap_remove` correct?
604        let err = self.dcx.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
605            |stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
606        );
607        err.map(|(err, guar, _)| {
608            {
    match (&err.level, &Error) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(err.level, Error);
609            if !guar.is_some() {
    ::core::panicking::panic("assertion failed: guar.is_some()")
};assert!(guar.is_some());
610            let mut err = Diag::new_diagnostic(self, err);
611            modify_err(&mut err);
612            {
    match (&err.level, &Error) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(err.level, Error);
613            err.emit_err()
614        })
615    }
616
617    /// Steals a previously stashed error with the given `Span` and
618    /// [`StashKey`] as the key, cancels it if found, and emits `new_err`.
619    /// Panics if the found diagnostic's level isn't `Level::Error`.
620    pub fn try_steal_replace_and_emit_err(
621        self,
622        span: Span,
623        key: StashKey,
624        new_err: Diag<'_>,
625    ) -> ErrorGuaranteed {
626        // FIXME(#120456) - is `swap_remove` correct?
627        let old_err = self.dcx.inner.borrow_mut().stashed_diagnostics.get_mut(&key).and_then(
628            |stashed_diagnostics| stashed_diagnostics.swap_remove(&span.with_parent(None)),
629        );
630        match old_err {
631            Some((old_err, guar, _)) => {
632                {
    match (&old_err.level, &Error) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(old_err.level, Error);
633                if !guar.is_some() {
    ::core::panicking::panic("assertion failed: guar.is_some()")
};assert!(guar.is_some());
634                // Because `old_err` has already been counted, it can only be
635                // safely cancelled because the `new_err` supplants it.
636                Diag::new_diagnostic(self, old_err).cancel();
637            }
638            None => {}
639        };
640        new_err.emit_err()
641    }
642
643    pub fn has_stashed_diagnostic(&self, span: Span, key: StashKey) -> bool {
644        let inner = self.dcx.inner.borrow();
645        if let Some(stashed_diagnostics) = inner.stashed_diagnostics.get(&key)
646            && !stashed_diagnostics.is_empty()
647        {
648            stashed_diagnostics.contains_key(&span.with_parent(None))
649        } else {
650            false
651        }
652    }
653
654    /// Emit all stashed diagnostics.
655    pub fn emit_stashed_diagnostics(&self) -> Option<ErrorGuaranteed> {
656        self.dcx.inner.borrow_mut().emit_stashed_diagnostics()
657    }
658
659    /// This excludes delayed bugs.
660    #[inline]
661    pub fn err_count(&self) -> usize {
662        let inner = self.dcx.inner.borrow();
663        inner.err_guars.len()
664            + inner.lint_err_guars.len()
665            + inner
666                .stashed_diagnostics
667                .values()
668                .map(|a| a.values().filter(|(_, guar, _)| guar.is_some()).count())
669                .sum::<usize>()
670    }
671
672    /// The number of errors that have been emitted on the *current thread*.
673    ///
674    /// Like [`DiagCtxtHandle::err_count`], but only counts errors whose recorded
675    /// emitting thread is the calling thread.
676    pub fn err_count_on_current_thread(&self) -> usize {
677        let inner = self.dcx.inner.borrow();
678        let current = std::thread::current().id();
679        inner.err_guars.iter().filter(|(_, thread)| *thread == current).count()
680            + inner.lint_err_guars.iter().filter(|(_, thread)| *thread == current).count()
681            + inner
682                .stashed_diagnostics
683                .values()
684                .map(|a| {
685                    a.values()
686                        .filter(|(_, guar, thread)| guar.is_some() && *thread == current)
687                        .count()
688                })
689                .sum::<usize>()
690    }
691
692    /// This excludes lint errors and delayed bugs. Unless absolutely
693    /// necessary, prefer `has_errors` to this method.
694    pub fn has_errors_excluding_lint_errors(&self) -> Option<ErrorGuaranteed> {
695        self.dcx.inner.borrow().has_errors_excluding_lint_errors()
696    }
697
698    /// This excludes delayed bugs.
699    pub fn has_errors(&self) -> Option<ErrorGuaranteed> {
700        self.dcx.inner.borrow().has_errors()
701    }
702
703    /// This excludes nothing. Unless absolutely necessary, prefer `has_errors`
704    /// to this method.
705    pub fn has_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
706        self.dcx.inner.borrow().has_errors_or_delayed_bugs()
707    }
708
709    pub fn print_error_count(&self) {
710        let mut inner = self.dcx.inner.borrow_mut();
711
712        // Any stashed diagnostics should have been handled by
713        // `emit_stashed_diagnostics` by now.
714        if !inner.stashed_diagnostics.is_empty() {
    ::core::panicking::panic("assertion failed: inner.stashed_diagnostics.is_empty()")
};assert!(inner.stashed_diagnostics.is_empty());
715
716        if inner.treat_err_as_bug() {
717            return;
718        }
719
720        let warnings = match inner.deduplicated_warn_count {
721            0 => Cow::from(""),
722            1 => Cow::from("1 warning emitted"),
723            count => Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} warnings emitted", count))
    })format!("{count} warnings emitted")),
724        };
725        let errors = match inner.deduplicated_err_count {
726            0 => Cow::from(""),
727            1 => Cow::from("aborting due to 1 previous error"),
728            count => Cow::from(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("aborting due to {0} previous errors",
                count))
    })format!("aborting due to {count} previous errors")),
729        };
730
731        match (errors.len(), warnings.len()) {
732            (0, 0) => return,
733            (0, _) => {
734                // Force emission so this message always prints.
735                let diag = DiagInner::new(
736                    Warning(Some(EmissionOverride::Forced { lint_id: None })),
737                    DiagMessage::Str(warnings),
738                );
739                inner.emit_diagnostic(diag, None);
740            }
741            (_, 0) => {
742                inner.emit_diagnostic(DiagInner::new(Error, errors), self.tainted_with_errors);
743            }
744            (_, _) => {
745                inner.emit_diagnostic(
746                    DiagInner::new(Error, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}; {1}", errors, warnings))
    })format!("{errors}; {warnings}")),
747                    self.tainted_with_errors,
748                );
749            }
750        }
751
752        let can_show_explain = inner.emitter.should_show_explain();
753        let are_there_diagnostics = !inner.emitted_diagnostic_codes.is_empty();
754        if can_show_explain && are_there_diagnostics {
755            let mut error_codes = inner
756                .emitted_diagnostic_codes
757                .iter()
758                .filter_map(|&code| {
759                    if crate::codes::try_find_description(code).is_ok() {
760                        Some(code.to_string())
761                    } else {
762                        None
763                    }
764                })
765                .collect::<Vec<_>>();
766            if !error_codes.is_empty() {
767                error_codes.sort();
768                if error_codes.len() > 1 {
769                    let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
770                    let msg1 = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Some errors have detailed explanations: {0}{1}",
                error_codes[..limit].join(", "),
                if error_codes.len() > 9 { "..." } else { "." }))
    })format!(
771                        "Some errors have detailed explanations: {}{}",
772                        error_codes[..limit].join(", "),
773                        if error_codes.len() > 9 { "..." } else { "." }
774                    );
775                    let msg2 = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("For more information about an error, try `rustc --explain {0}`.",
                &error_codes[0]))
    })format!(
776                        "For more information about an error, try `rustc --explain {}`.",
777                        &error_codes[0]
778                    );
779                    inner.emit_diagnostic(DiagInner::new(FailureNote, msg1), None);
780                    inner.emit_diagnostic(DiagInner::new(FailureNote, msg2), None);
781                } else {
782                    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("For more information about this error, try `rustc --explain {0}`.",
                &error_codes[0]))
    })format!(
783                        "For more information about this error, try `rustc --explain {}`.",
784                        &error_codes[0]
785                    );
786                    inner.emit_diagnostic(DiagInner::new(FailureNote, msg), None);
787                }
788            }
789        }
790    }
791
792    /// This excludes delayed bugs. Used for early aborts after errors occurred
793    /// -- e.g. because continuing in the face of errors is likely to lead to
794    /// bad results, such as spurious/uninteresting additional errors -- when
795    /// returning an error `Result` is difficult.
796    pub fn abort_if_errors(&self) {
797        if let Some(guar) = self.has_errors() {
798            guar.raise_fatal();
799        }
800    }
801
802    /// `true` if we haven't taught a diagnostic with this code already.
803    /// The caller must then teach the user about such a diagnostic.
804    ///
805    /// Used to suppress emitting the same error multiple times with extended explanation when
806    /// calling `-Zteach`.
807    pub fn must_teach(&self, code: ErrCode) -> bool {
808        self.dcx.inner.borrow_mut().taught_diagnostics.insert(code)
809    }
810
811    pub fn emit_diagnostic(&self, diagnostic: DiagInner) -> Option<ErrorGuaranteed> {
812        self.dcx.inner.borrow_mut().emit_diagnostic(diagnostic, self.tainted_with_errors)
813    }
814
815    pub fn emit_artifact_notification(&self, path: &Path, artifact_type: &str) {
816        self.dcx.inner.borrow_mut().emitter.emit_artifact_notification(path, artifact_type);
817    }
818
819    pub fn emit_timing_section_start(&self, record: TimingRecord) {
820        self.dcx.inner.borrow_mut().emitter.emit_timing_section(record, TimingEvent::Start);
821    }
822
823    pub fn emit_timing_section_end(&self, record: TimingRecord) {
824        self.dcx.inner.borrow_mut().emitter.emit_timing_section(record, TimingEvent::End);
825    }
826
827    pub fn emit_future_breakage_report(&self) {
828        let inner = &mut *self.dcx.inner.borrow_mut();
829        let diags = mem::take(&mut inner.future_breakage_diagnostics);
830        if !diags.is_empty() {
831            inner.emitter.emit_future_breakage_report(diags);
832        }
833    }
834
835    pub fn emit_unused_externs(
836        &self,
837        lint_level: rustc_lint_defs::Level,
838        loud: bool,
839        unused_externs: &[&str],
840    ) {
841        let mut inner = self.dcx.inner.borrow_mut();
842
843        // This "error" is an odd duck.
844        // - It's only produce with JSON output.
845        // - It's not emitted the usual way, via `emit_diagnostic`.
846        // - The `$message_type` field is "unused_externs" rather than the usual
847        //   "diagnostic".
848        //
849        // We count it as a lint error because it has a lint level. The value
850        // of `loud` (which comes from "unused-externs" or
851        // "unused-externs-silent"), also affects whether it's treated like a
852        // hard error or not.
853        if loud && lint_level.is_error() {
854            // This `unchecked_error_guaranteed` is valid. It is where the
855            // `ErrorGuaranteed` for unused_extern errors originates.
856            #[allow(deprecated)]
857            let guar = ErrorGuaranteed::unchecked_error_guaranteed();
858            inner.lint_err_guars.push((guar, std::thread::current().id()));
859            inner.panic_if_treat_err_as_bug();
860        }
861
862        inner.emitter.emit_unused_externs(lint_level, unused_externs)
863    }
864
865    /// We need to make sure that submitted expectation ids are correctly fulfilled, suppressed,
866    /// and stored between compilation sessions. To avoid doing these steps manually, we create a
867    /// dummy diagnostic and emit it as usual, which will be suppressed and stored like a normal
868    /// expected lint diagnostic.
869    #[track_caller]
870    pub fn fulfill_expectation(self, expectation: impl Into<LintExpectationId>) {
871        let emission_override = Some(EmissionOverride::Expected { lint_id: expectation.into() });
872        let msg = "this is a dummy diagnostic, to submit and store an expectation";
873        Diag::new(self, Warning(emission_override), msg).emit()
874    }
875
876    /// This methods steals all [`LintExpectationId`]s that are stored inside
877    /// [`DiagCtxtInner`] and indicate that the linked expectation has been fulfilled.
878    #[must_use]
879    pub fn steal_fulfilled_expectation_ids(&self) -> FxIndexSet<LintExpectationId> {
880        mem::take(&mut self.dcx.inner.borrow_mut().fulfilled_expectations)
881    }
882
883    /// Trigger an ICE if there are any delayed bugs and no hard errors.
884    ///
885    /// This will panic if there are any stashed diagnostics. You can call
886    /// `emit_stashed_diagnostics` to emit those before calling `flush_delayed`.
887    pub fn flush_delayed(&self) {
888        self.dcx.inner.borrow_mut().flush_delayed();
889    }
890
891    /// Used when trimmed_def_paths is called and we must produce a diagnostic
892    /// to justify its cost.
893    #[track_caller]
894    pub fn set_must_produce_diag(&self) {
895        if !self.dcx.inner.borrow().must_produce_diag.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("should only need to collect a backtrace once"));
    }
};assert!(
896            self.dcx.inner.borrow().must_produce_diag.is_none(),
897            "should only need to collect a backtrace once"
898        );
899        self.dcx.inner.borrow_mut().must_produce_diag = Some(Backtrace::capture());
900    }
901}
902
903// This `impl` block contains only the public diagnostic creation/emission API.
904//
905// Functions beginning with `struct_`/`create_` create a diagnostic. Other
906// functions create and emit a diagnostic all in one go.
907impl<'a> DiagCtxtHandle<'a> {
908    #[track_caller]
909    pub fn struct_bug(self, msg: impl Into<Cow<'static, str>>) -> Diag<'a> {
910        Diag::new(self, Bug, msg.into())
911    }
912
913    #[track_caller]
914    pub fn bug(self, msg: impl Into<Cow<'static, str>>) -> ! {
915        self.struct_bug(msg).emit_bug()
916    }
917
918    #[track_caller]
919    pub fn struct_span_bug(
920        self,
921        span: impl Into<MultiSpan>,
922        msg: impl Into<Cow<'static, str>>,
923    ) -> Diag<'a> {
924        self.struct_bug(msg).with_span(span)
925    }
926
927    #[track_caller]
928    pub fn span_bug(self, span: impl Into<MultiSpan>, msg: impl Into<Cow<'static, str>>) -> ! {
929        self.struct_span_bug(span, msg.into()).emit_bug()
930    }
931
932    #[track_caller]
933    pub fn create_bug(self, bug: impl Diagnostic<'a>) -> Diag<'a> {
934        bug.into_diag(self, Bug)
935    }
936
937    #[track_caller]
938    pub fn emit_bug(self, bug: impl Diagnostic<'a>) -> ! {
939        self.create_bug(bug).emit_bug()
940    }
941
942    #[track_caller]
943    pub fn struct_fatal(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
944        Diag::new(self, Fatal, msg)
945    }
946
947    #[track_caller]
948    pub fn fatal(self, msg: impl Into<DiagMessage>) -> ! {
949        self.struct_fatal(msg).emit_fatal()
950    }
951
952    #[track_caller]
953    pub fn struct_span_fatal(
954        self,
955        span: impl Into<MultiSpan>,
956        msg: impl Into<DiagMessage>,
957    ) -> Diag<'a> {
958        self.struct_fatal(msg).with_span(span)
959    }
960
961    #[track_caller]
962    pub fn span_fatal(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) -> ! {
963        self.struct_span_fatal(span, msg).emit_fatal()
964    }
965
966    #[track_caller]
967    pub fn create_fatal(self, fatal: impl Diagnostic<'a>) -> Diag<'a> {
968        fatal.into_diag(self, Fatal)
969    }
970
971    #[track_caller]
972    pub fn emit_fatal(self, fatal: impl Diagnostic<'a>) -> ! {
973        self.create_fatal(fatal).emit_fatal()
974    }
975
976    #[track_caller]
977    pub fn struct_err(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
978        Diag::new(self, Error, msg)
979    }
980
981    #[track_caller]
982    pub fn err(self, msg: impl Into<DiagMessage>) -> ErrorGuaranteed {
983        self.struct_err(msg).emit_err()
984    }
985
986    #[track_caller]
987    pub fn struct_span_err(
988        self,
989        span: impl Into<MultiSpan>,
990        msg: impl Into<DiagMessage>,
991    ) -> Diag<'a> {
992        self.struct_err(msg).with_span(span)
993    }
994
995    #[track_caller]
996    pub fn span_err(
997        self,
998        span: impl Into<MultiSpan>,
999        msg: impl Into<DiagMessage>,
1000    ) -> ErrorGuaranteed {
1001        self.struct_span_err(span, msg).emit_err()
1002    }
1003
1004    #[track_caller]
1005    pub fn create_err(self, err: impl Diagnostic<'a>) -> Diag<'a> {
1006        err.into_diag(self, Error)
1007    }
1008
1009    #[track_caller]
1010    pub fn emit_err(self, err: impl Diagnostic<'a>) -> ErrorGuaranteed {
1011        self.create_err(err).emit_err()
1012    }
1013
1014    /// Ensures that an error is printed. See [`Level::DelayedBug`].
1015    #[track_caller]
1016    pub fn delayed_bug(self, msg: impl Into<Cow<'static, str>>) -> ErrorGuaranteed {
1017        Diag::new(self, DelayedBug, msg.into()).emit_err()
1018    }
1019
1020    /// Ensures that an error is printed. See [`Level::DelayedBug`].
1021    ///
1022    /// Note: this function used to be called `delay_span_bug`. It was renamed
1023    /// to match similar functions like `span_err`, `span_warn`, etc.
1024    #[track_caller]
1025    pub fn span_delayed_bug(
1026        self,
1027        sp: impl Into<MultiSpan>,
1028        msg: impl Into<Cow<'static, str>>,
1029    ) -> ErrorGuaranteed {
1030        Diag::new(self, DelayedBug, msg.into()).with_span(sp).emit_err()
1031    }
1032
1033    #[track_caller]
1034    pub fn struct_warn(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
1035        Diag::new(self, Warning(None), msg)
1036    }
1037
1038    #[track_caller]
1039    pub fn warn(self, msg: impl Into<DiagMessage>) {
1040        self.struct_warn(msg).emit()
1041    }
1042
1043    #[track_caller]
1044    pub fn struct_span_warn(
1045        self,
1046        span: impl Into<MultiSpan>,
1047        msg: impl Into<DiagMessage>,
1048    ) -> Diag<'a> {
1049        self.struct_warn(msg).with_span(span)
1050    }
1051
1052    #[track_caller]
1053    pub fn span_warn(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
1054        self.struct_span_warn(span, msg).emit()
1055    }
1056
1057    #[track_caller]
1058    pub fn create_warn(self, warning: impl Diagnostic<'a>) -> Diag<'a> {
1059        warning.into_diag(self, Warning(None))
1060    }
1061
1062    #[track_caller]
1063    pub fn emit_warn(self, warning: impl Diagnostic<'a>) {
1064        self.create_warn(warning).emit()
1065    }
1066
1067    #[track_caller]
1068    pub fn struct_note(self, msg: impl Into<DiagMessage>) -> Diag<'a> {
1069        Diag::new(self, Note, msg)
1070    }
1071
1072    #[track_caller]
1073    pub fn note(&self, msg: impl Into<DiagMessage>) {
1074        self.struct_note(msg).emit()
1075    }
1076
1077    #[track_caller]
1078    pub fn struct_span_note(
1079        self,
1080        span: impl Into<MultiSpan>,
1081        msg: impl Into<DiagMessage>,
1082    ) -> Diag<'a> {
1083        self.struct_note(msg).with_span(span)
1084    }
1085
1086    #[track_caller]
1087    pub fn span_note(self, span: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
1088        self.struct_span_note(span, msg).emit()
1089    }
1090
1091    #[track_caller]
1092    pub fn create_note(self, note: impl Diagnostic<'a>) -> Diag<'a> {
1093        note.into_diag(self, Note)
1094    }
1095
1096    #[track_caller]
1097    pub fn emit_note(self, note: impl Diagnostic<'a>) {
1098        self.create_note(note).emit()
1099    }
1100}
1101
1102impl DiagCtxtInner {
1103    fn new(emitter: Box<DynEmitter>) -> Self {
1104        Self {
1105            flags: DiagCtxtFlags { can_emit_warnings: true, ..Default::default() },
1106            err_guars: Vec::new(),
1107            lint_err_guars: Vec::new(),
1108            delayed_bugs: Vec::new(),
1109            deduplicated_err_count: 0,
1110            deduplicated_warn_count: 0,
1111            emitter,
1112            must_produce_diag: None,
1113            has_printed: false,
1114            suppressed_expected_diag: false,
1115            taught_diagnostics: Default::default(),
1116            emitted_diagnostic_codes: Default::default(),
1117            emitted_diagnostics: Default::default(),
1118            emitted_recursion_depth_exceeding_limit: false,
1119            stashed_diagnostics: Default::default(),
1120            future_breakage_diagnostics: Vec::new(),
1121            fulfilled_expectations: Default::default(),
1122            ice_file: None,
1123            msrv: None,
1124        }
1125    }
1126
1127    /// Emit all stashed diagnostics.
1128    fn emit_stashed_diagnostics(&mut self) -> Option<ErrorGuaranteed> {
1129        let mut guar = None;
1130        let has_errors = !self.err_guars.is_empty();
1131        for (_, stashed_diagnostics) in mem::take(&mut self.stashed_diagnostics).into_iter() {
1132            for (_, (diag, _guar, _thread)) in stashed_diagnostics {
1133                // When there are errors, skip flushing of stashed unforced warnings, to avoid
1134                // warning overload. (They would have been stolen already if they were important.)
1135                if has_errors
1136                    && let Warning(emission_override) = diag.level
1137                    && !#[allow(non_exhaustive_omitted_patterns)] match emission_override {
    Some(EmissionOverride::Forced { .. }) => true,
    _ => false,
}matches!(emission_override, Some(EmissionOverride::Forced { .. }))
1138                {
1139                    continue;
1140                }
1141                guar = guar.or(self.emit_diagnostic(diag, None));
1142            }
1143        }
1144        guar
1145    }
1146
1147    // Return value is only `Some` if the level is `Error` or `DelayedBug`.
1148    fn emit_diagnostic(
1149        &mut self,
1150        mut diagnostic: DiagInner,
1151        taint: Option<&Cell<Option<ErrorGuaranteed>>>,
1152    ) -> Option<ErrorGuaranteed> {
1153        if diagnostic.has_future_breakage() {
1154            // About the `allow`/`expect` lint sub-cases of `Warning`: future breakages aren't
1155            // emitted for them, but they still need to be handled below so they'll trigger the
1156            // `must_produce_diag` check.
1157            {
    match diagnostic.level {
        Error | Warning(_) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "Error | Warning(_)", ::core::option::Option::None);
        }
    }
};assert_matches!(diagnostic.level, Error | Warning(_));
1158            self.future_breakage_diagnostics.push(diagnostic.clone());
1159        }
1160
1161        // We call TRACK_DIAGNOSTIC with an empty closure for the cases that
1162        // return early *and* have some kind of side-effect, except where
1163        // noted.
1164        match diagnostic.level {
1165            Bug => {}
1166            Fatal | Error => {
1167                if self.treat_next_err_as_bug() {
1168                    // `Fatal` and `Error` can be promoted to `Bug`.
1169                    diagnostic.level = Bug;
1170                }
1171            }
1172            DelayedBug => {
1173                // Note that because we check these conditions first,
1174                // `-Zeagerly-emit-delayed-bugs` and `-Ztreat-err-as-bug`
1175                // continue to work even after we've issued an error and
1176                // stopped recording new delayed bugs.
1177                if self.flags.eagerly_emit_delayed_bugs {
1178                    // `DelayedBug` can be promoted to `Error` or `Bug`.
1179                    if self.treat_next_err_as_bug() {
1180                        diagnostic.level = Bug;
1181                    } else {
1182                        diagnostic.level = Error;
1183                    }
1184                } else {
1185                    // If we have already emitted at least one error, we don't need
1186                    // to record the delayed bug, because it'll never be used.
1187                    return if let Some(guar) = self.has_errors() {
1188                        Some(guar)
1189                    } else {
1190                        // No `TRACK_DIAGNOSTIC` call is needed, because the
1191                        // incremental session is deleted if there is a delayed
1192                        // bug. This also saves us from cloning the diagnostic.
1193                        let backtrace = std::backtrace::Backtrace::capture();
1194                        // This `unchecked_error_guaranteed` is valid. It is where the
1195                        // `ErrorGuaranteed` for delayed bugs originates. See
1196                        // `DiagCtxtInner::drop`.
1197                        #[allow(deprecated)]
1198                        let guar = ErrorGuaranteed::unchecked_error_guaranteed();
1199                        self.delayed_bugs
1200                            .push((DelayedDiagInner::with_backtrace(diagnostic, backtrace), guar));
1201                        Some(guar)
1202                    };
1203                }
1204            }
1205            Warning(emission_override) => {
1206                match emission_override {
1207                    None => {
1208                        if !self.flags.can_emit_warnings {
1209                            // We are not emitting warnings.
1210                            if diagnostic.has_future_breakage() {
1211                                // The side-effect is at the top of this method.
1212                                TRACK_DIAGNOSTIC(diagnostic, &mut |_| None);
1213                            }
1214                            return None;
1215                        }
1216                    }
1217                    Some(EmissionOverride::Forced { lint_id: None }) => {}
1218                    Some(EmissionOverride::Forced { lint_id: Some(lint_id) }) => {
1219                        self.fulfilled_expectations.insert(lint_id);
1220                    }
1221                    Some(EmissionOverride::Allowed) => {
1222                        if !diagnostic.has_future_breakage() {
    ::core::panicking::panic("assertion failed: diagnostic.has_future_breakage()")
};assert!(diagnostic.has_future_breakage());
1223                        TRACK_DIAGNOSTIC(diagnostic, &mut |_| None);
1224                        self.suppressed_expected_diag = true;
1225                        return None;
1226                    }
1227                    Some(EmissionOverride::Expected { lint_id }) => {
1228                        self.fulfilled_expectations.insert(lint_id);
1229                        TRACK_DIAGNOSTIC(diagnostic, &mut |_| None);
1230                        self.suppressed_expected_diag = true;
1231                        return None;
1232                    }
1233                }
1234            }
1235            Note | Help | FailureNote => {}
1236        }
1237
1238        if let (Some(msrv), Some(diag_msrv)) = (self.msrv, diagnostic.rust_version())
1239            && diag_msrv > msrv
1240        {
1241            return None;
1242        }
1243
1244        TRACK_DIAGNOSTIC(diagnostic, &mut |mut diagnostic| {
1245            if let Some(code) = diagnostic.code {
1246                self.emitted_diagnostic_codes.insert(code);
1247            }
1248
1249            let already_emitted = !self.emitted_diagnostics.insert(diagnostic.dedup_hash());
1250
1251            let is_error = diagnostic.is_error();
1252            let is_lint = diagnostic.is_lint.is_some();
1253            // We only emit the first occurrence of `recursion_depth_exceeding_limit`.
1254            let silence_recursion_depth_exceeded_limit =
1255                diagnostic.is_lint.as_ref().is_some_and(|lint| {
1256                    lint.name.eq_ignore_ascii_case(
1257                        rustc_lint_defs::builtin::RECURSION_DEPTH_EXCEEDING_LIMIT.name,
1258                    ) && mem::replace(&mut self.emitted_recursion_depth_exceeding_limit, true)
1259                });
1260
1261            // Only emit the diagnostic if deduplication is disabled or we
1262            // haven't already emitted an equivalent diagnostic.
1263            if !silence_recursion_depth_exceeded_limit
1264                && !(self.flags.deduplicate_diagnostics && already_emitted)
1265            {
1266                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs:1266",
                        "rustc_errors", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1266u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("diagnostic")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("diagnostic");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diagnostic)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?diagnostic);
1267                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs:1267",
                        "rustc_errors", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1267u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("self.emitted_diagnostics")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("self.emitted_diagnostics");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.emitted_diagnostics)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?self.emitted_diagnostics);
1268
1269                let show_sub = |sub: &Subdiag| {
1270                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs:1270",
                        "rustc_errors", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_errors/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1270u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_errors"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("sub")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("sub");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sub)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?sub);
1271                    match sub.level {
1272                        Sublevel::Error | Sublevel::Warning | Sublevel::Note | Sublevel::Help => {
1273                            true
1274                        }
1275                        Sublevel::OnceNote | Sublevel::OnceHelp => {
1276                            self.emitted_diagnostics.insert(sub.dedup_hash())
1277                        }
1278                    }
1279                };
1280                diagnostic.children.retain(show_sub);
1281                if already_emitted {
1282                    let msg = "duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`";
1283                    diagnostic.sub(Sublevel::Note, msg, MultiSpan::new());
1284                }
1285
1286                if is_error {
1287                    self.deduplicated_err_count += 1;
1288                } else if #[allow(non_exhaustive_omitted_patterns)] match diagnostic.level {
    Warning(_) => true,
    _ => false,
}matches!(diagnostic.level, Warning(_)) {
1289                    self.deduplicated_warn_count += 1;
1290                }
1291                self.has_printed = true;
1292
1293                self.emitter.emit_diagnostic(diagnostic);
1294            }
1295
1296            if is_error {
1297                // If we have any delayed bugs recorded, we can discard them
1298                // because they won't be used. (This should only occur if there
1299                // have been no errors previously emitted, because we don't add
1300                // new delayed bugs once the first error is emitted.)
1301                if !self.delayed_bugs.is_empty() {
1302                    {
    match (&(self.lint_err_guars.len() + self.err_guars.len()), &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(self.lint_err_guars.len() + self.err_guars.len(), 0);
1303                    self.delayed_bugs.clear();
1304                    self.delayed_bugs.shrink_to_fit();
1305                }
1306
1307                // This `unchecked_error_guaranteed` is valid. It is where the
1308                // `ErrorGuaranteed` for errors and lint errors originates.
1309                #[allow(deprecated)]
1310                let guar = ErrorGuaranteed::unchecked_error_guaranteed();
1311                let thread = std::thread::current().id();
1312                if is_lint {
1313                    self.lint_err_guars.push((guar, thread));
1314                } else {
1315                    if let Some(taint) = taint {
1316                        taint.set(Some(guar));
1317                    }
1318                    self.err_guars.push((guar, thread));
1319                }
1320                self.panic_if_treat_err_as_bug();
1321                Some(guar)
1322            } else {
1323                None
1324            }
1325        })
1326    }
1327
1328    fn treat_err_as_bug(&self) -> bool {
1329        self.flags
1330            .treat_err_as_bug
1331            .is_some_and(|c| self.err_guars.len() + self.lint_err_guars.len() >= c.get())
1332    }
1333
1334    // Use this one before incrementing `err_count`.
1335    fn treat_next_err_as_bug(&self) -> bool {
1336        self.flags
1337            .treat_err_as_bug
1338            .is_some_and(|c| self.err_guars.len() + self.lint_err_guars.len() + 1 >= c.get())
1339    }
1340
1341    fn has_errors_excluding_lint_errors(&self) -> Option<ErrorGuaranteed> {
1342        self.err_guars.get(0).map(|(guar, _)| *guar).or_else(|| {
1343            if let Some((_diag, guar, _)) = self
1344                .stashed_diagnostics
1345                .values()
1346                .flat_map(|stashed_diagnostics| stashed_diagnostics.values())
1347                .find(|(diag, guar, _)| guar.is_some() && diag.is_lint.is_none())
1348            {
1349                *guar
1350            } else {
1351                None
1352            }
1353        })
1354    }
1355
1356    fn has_errors(&self) -> Option<ErrorGuaranteed> {
1357        self.err_guars
1358            .get(0)
1359            .map(|(guar, _)| *guar)
1360            .or_else(|| self.lint_err_guars.get(0).map(|(guar, _)| *guar))
1361            .or_else(|| {
1362                self.stashed_diagnostics.values().find_map(|stashed_diagnostics| {
1363                    stashed_diagnostics.values().find_map(|(_, guar, _)| *guar)
1364                })
1365            })
1366    }
1367
1368    fn has_errors_or_delayed_bugs(&self) -> Option<ErrorGuaranteed> {
1369        self.has_errors().or_else(|| self.delayed_bugs.get(0).map(|(_, guar)| guar).copied())
1370    }
1371
1372    fn flush_delayed(&mut self) {
1373        // Stashed diagnostics must be emitted before delayed bugs are flushed.
1374        // Otherwise, we might ICE prematurely when errors would have
1375        // eventually happened.
1376        if !self.stashed_diagnostics.is_empty() {
    ::core::panicking::panic("assertion failed: self.stashed_diagnostics.is_empty()")
};assert!(self.stashed_diagnostics.is_empty());
1377
1378        if !self.err_guars.is_empty() {
1379            // If an error happened already. We shouldn't expose delayed bugs.
1380            return;
1381        }
1382
1383        if self.delayed_bugs.is_empty() {
1384            // Nothing to do.
1385            return;
1386        }
1387
1388        let bugs: Vec<_> = mem::take(&mut self.delayed_bugs).into_iter().map(|(b, _)| b).collect();
1389
1390        let backtrace = std::env::var_os("RUST_BACKTRACE").as_deref() != Some(OsStr::new("0"));
1391        let decorate = backtrace || self.ice_file.is_none();
1392        let mut out = self
1393            .ice_file
1394            .as_ref()
1395            .and_then(|file| std::fs::File::options().create(true).append(true).open(file).ok());
1396
1397        // Put the overall explanation before the `DelayedBug`s, to frame them
1398        // better (e.g. separate warnings from them). Also, use notes, which
1399        // don't count as errors, to avoid possibly triggering
1400        // `-Ztreat-err-as-bug`, which we don't want.
1401        let note1 = "no errors encountered even though delayed bugs were created";
1402        let note2 = "those delayed bugs will now be shown as internal compiler errors";
1403        self.emit_diagnostic(DiagInner::new(Note, note1), None);
1404        self.emit_diagnostic(DiagInner::new(Note, note2), None);
1405
1406        for bug in bugs {
1407            if let Some(out) = &mut out {
1408                _ = out.write_fmt(format_args!("delayed bug: {0}\n{1}\n",
        bug.inner.messages.iter().filter_map(|(msg, _)|
                    msg.as_str()).collect::<String>(), &bug.note))write!(
1409                    out,
1410                    "delayed bug: {}\n{}\n",
1411                    bug.inner
1412                        .messages
1413                        .iter()
1414                        .filter_map(|(msg, _)| msg.as_str())
1415                        .collect::<String>(),
1416                    &bug.note
1417                );
1418            }
1419
1420            let mut bug = if decorate { bug.decorate() } else { bug.inner };
1421
1422            // "Undelay" the delayed bugs into plain bugs.
1423            if bug.level != DelayedBug {
1424                // NOTE(eddyb) not panicking here because we're already producing
1425                // an ICE, and the more information the merrier.
1426                //
1427                // We are at the `DiagInner`/`DiagCtxtInner` level rather than
1428                // the usual `Diag`/`DiagCtxt` level, so we must augment `bug`
1429                // in a lower-level fashion.
1430                let msg = rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`flushed_delayed` got diagnostic with level {$level}, instead of the expected `DelayedBug`"))msg!(
1431                    "`flushed_delayed` got diagnostic with level {$level}, instead of the expected `DelayedBug`"
1432                ).arg("level", bug.level).format();
1433                bug.sub(Sublevel::Note, msg, bug.span.primary_span().unwrap().into());
1434            }
1435            bug.level = Bug;
1436
1437            self.emit_diagnostic(bug, None);
1438        }
1439
1440        // Panic with `DelayedBugPanic` to avoid "unexpected panic" messages.
1441        panic::panic_any(DelayedBugPanic);
1442    }
1443
1444    fn panic_if_treat_err_as_bug(&self) {
1445        if self.treat_err_as_bug() {
1446            let n = self.flags.treat_err_as_bug.map(|c| c.get()).unwrap();
1447            {
    match (&n, &(self.err_guars.len() + self.lint_err_guars.len())) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(n, self.err_guars.len() + self.lint_err_guars.len());
1448            if n == 1 {
1449                {
    ::core::panicking::panic_fmt(format_args!("aborting due to `-Z treat-err-as-bug=1`"));
};panic!("aborting due to `-Z treat-err-as-bug=1`");
1450            } else {
1451                {
    ::core::panicking::panic_fmt(format_args!("aborting after {0} errors due to `-Z treat-err-as-bug={0}`",
            n));
};panic!("aborting after {n} errors due to `-Z treat-err-as-bug={n}`");
1452            }
1453        }
1454    }
1455}
1456
1457struct DelayedDiagInner {
1458    inner: DiagInner,
1459    note: Backtrace,
1460}
1461
1462impl DelayedDiagInner {
1463    fn with_backtrace(diagnostic: DiagInner, backtrace: Backtrace) -> Self {
1464        DelayedDiagInner { inner: diagnostic, note: backtrace }
1465    }
1466
1467    fn decorate(self) -> DiagInner {
1468        // We are at the `DiagInner`/`DiagCtxtInner` level rather than the
1469        // usual `Diag`/`DiagCtxt` level, so we must construct `diag` in a
1470        // lower-level fashion.
1471        let mut diag = self.inner;
1472        let msg = match self.note.status() {
1473            BacktraceStatus::Captured => rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("delayed at {$emitted_at}\n                {$note}"))msg!(
1474                "delayed at {$emitted_at}
1475                {$note}"
1476            ),
1477            // Avoid the needless newline when no backtrace has been captured,
1478            // the display impl should just be a single line.
1479            _ => rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("delayed at {$emitted_at} - {$note}"))msg!("delayed at {$emitted_at} - {$note}"),
1480        }
1481        .arg("emitted_at", diag.emitted_at.clone())
1482        .arg("note", self.note)
1483        .format();
1484        diag.sub(Sublevel::Note, msg, diag.span.primary_span().unwrap_or(DUMMY_SP).into());
1485        diag
1486    }
1487}
1488
1489/// Special emission behaviours on warning diagnostics. Combines with `DiagInner::is_lint` in the
1490/// following ways.
1491///
1492/// | case                              | is_lint | `Option<EmissionOverride>` field in `Warning`
1493/// | ----                              | ------- | ---------------------------------------------
1494/// | ordinary non-lint diagnostic      | None    | None
1495/// | warning-count summary             | None    | Some(Forced { lint_id: None })
1496/// | N/A                               | None    | Some(Forced { lint_id: Some(lint_id) })
1497/// | dummy expectation fulfillment     | None    | Some(Expected { lint_id })
1498/// | N/A                               | None    | Some(Allowed)
1499/// | ordinary `warn` lint              | Some    | None
1500/// | `warn` lint at `force-warn`       | Some    | Some(Forced { lint_id: None })
1501/// | `expect` lint at `force-warn`     | Some    | Some(Forced { lint_id: Some(lint_id) })
1502/// | `expect` lint                     | Some    | Some(Expected { lint_id })
1503/// | `allow` lint with future breakage | Some    | Some(Allowed)
1504///
1505#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for EmissionOverride {
}
#[automatically_derived]impl ::core::clone::Clone for EmissionOverride {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Option<LintExpectationId>>;
        let _: ::core::clone::AssertParamIsClone<LintExpectationId>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for EmissionOverride { }Copy, #[automatically_derived]impl ::core::fmt::Debug for EmissionOverride {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Forced { lint_id: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Forced lint_id", &__self_0),
            Self::Allowed => ::core::fmt::Formatter::write_str(f, "Allowed"),
            Self::Expected { lint_id: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Expected lint_id", &__self_0),
        }
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    EmissionOverride {
}
#[automatically_derived]impl ::core::cmp::PartialEq for EmissionOverride {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Forced { lint_id: __self_0 }, Self::Forced {
                    lint_id: __arg1_0 }) => __self_0 == __arg1_0,
                (Self::Expected { lint_id: __self_0 }, Self::Expected {
                    lint_id: __arg1_0 }) => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for EmissionOverride {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<LintExpectationId>>;
        let _: ::core::cmp::AssertParamIsEq<LintExpectationId>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for EmissionOverride {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state);
        match self {
            Self::Forced { lint_id: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
            Self::Expected { lint_id: __self_0 } =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for EmissionOverride {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        EmissionOverride::Forced { lint_id: ref __binding_0 } => {
                            0usize
                        }
                        EmissionOverride::Allowed => { 1usize }
                        EmissionOverride::Expected { lint_id: ref __binding_0 } => {
                            2usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    EmissionOverride::Forced { lint_id: ref __binding_0 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    EmissionOverride::Allowed => {}
                    EmissionOverride::Expected { lint_id: ref __binding_0 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for EmissionOverride {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        EmissionOverride::Forced {
                            lint_id: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    1usize => { EmissionOverride::Allowed }
                    2usize => {
                        EmissionOverride::Expected {
                            lint_id: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `EmissionOverride`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
1506pub enum EmissionOverride {
1507    /// Cases where emission is forced.
1508    Forced { lint_id: Option<LintExpectationId> },
1509
1510    /// Used for `allow` lints with future breakage. (Allow lints without future breakage are
1511    /// ignored and therefore never need an `EmissionOverride` value.)
1512    Allowed,
1513
1514    /// Used for `expect` lints.
1515    Expected { lint_id: LintExpectationId },
1516}
1517
1518/// | Level        | is_error | usable emit fns  | Top-level | Used in lints?
1519/// | -----        | -------- | ---------------  | --------- | --------------
1520/// | Bug          | yes      | emit, emit_bug   | yes       | -
1521/// | Fatal        | yes      | emit, emit_fatal | yes       | -
1522/// | Error        | yes      | emit, emit_err   | yes       | yes
1523/// | DelayedBug   | yes      | emit, emit_err   | yes       | -
1524/// | Warning      | -        | emit             | yes       | yes
1525/// | Note         | -        | emit             | rare      | -
1526/// | Help         | -        | emit             | don't use | -
1527/// | FailureNote  | -        | emit             | rare      | -
1528///
1529#[derive(#[automatically_derived]impl ::core::marker::Copy for Level { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Level { }
#[automatically_derived]impl ::core::cmp::PartialEq for Level {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Warning(__self_0), Self::Warning(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Level {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<EmissionOverride>>;
    }
}Eq, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Level {
}
#[automatically_derived]impl ::core::clone::Clone for Level {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Option<EmissionOverride>>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::hash::Hash for Level {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state);
        match self {
            Self::Warning(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            _ => {}
        }
    }
}Hash, #[automatically_derived]impl ::core::fmt::Debug for Level {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Bug => ::core::fmt::Formatter::write_str(f, "Bug"),
            Self::Fatal => ::core::fmt::Formatter::write_str(f, "Fatal"),
            Self::Error => ::core::fmt::Formatter::write_str(f, "Error"),
            Self::DelayedBug =>
                ::core::fmt::Formatter::write_str(f, "DelayedBug"),
            Self::Warning(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Warning", &__self_0),
            Self::Note => ::core::fmt::Formatter::write_str(f, "Note"),
            Self::Help => ::core::fmt::Formatter::write_str(f, "Help"),
            Self::FailureNote =>
                ::core::fmt::Formatter::write_str(f, "FailureNote"),
        }
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Level {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        Level::Bug => { 0usize }
                        Level::Fatal => { 1usize }
                        Level::Error => { 2usize }
                        Level::DelayedBug => { 3usize }
                        Level::Warning(ref __binding_0) => { 4usize }
                        Level::Note => { 5usize }
                        Level::Help => { 6usize }
                        Level::FailureNote => { 7usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    Level::Bug => {}
                    Level::Fatal => {}
                    Level::Error => {}
                    Level::DelayedBug => {}
                    Level::Warning(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    Level::Note => {}
                    Level::Help => {}
                    Level::FailureNote => {}
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for Level {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { Level::Bug }
                    1usize => { Level::Fatal }
                    2usize => { Level::Error }
                    3usize => { Level::DelayedBug }
                    4usize => {
                        Level::Warning(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    5usize => { Level::Note }
                    6usize => { Level::Help }
                    7usize => { Level::FailureNote }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Level`, expected 0..8, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
1530pub enum Level {
1531    /// For bugs in the compiler. Manifests as an ICE (internal compiler error) panic.
1532    Bug,
1533
1534    /// An error that causes an immediate abort. Used for things like configuration errors,
1535    /// internal overflows, some file operation errors.
1536    Fatal,
1537
1538    /// An error in the code being compiled, which prevents compilation from finishing. This is the
1539    /// most common case.
1540    Error,
1541
1542    /// This is a strange one: lets you register an error without emitting it. If compilation ends
1543    /// without any other errors occurring, this will be emitted as a bug. Otherwise, it will be
1544    /// silently dropped. I.e. "expect other errors are emitted" semantics. Useful on code paths
1545    /// that should only be reached when compiling erroneous code.
1546    DelayedBug,
1547
1548    /// A warning about the code being compiled. Does not prevent compilation from finishing.
1549    /// Might not be emitted, depending on the value of `EmissionOverride` and `can_emit_warnings`.
1550    Warning(Option<EmissionOverride>),
1551
1552    /// A rarely-used level for output that isn't an error or a warning.
1553    Note,
1554
1555    /// A message suggesting how to fix something.
1556    ///
1557    /// FIXME(nnethercote) Do not use this! Currently only exists to support `proc_macro::Help`,
1558    /// part of the unstable `proc_macro_diagnostic` feature (see #54140). Should be removed
1559    /// because help messages are fine as subdiagnostics but are silly as top-level diagnostics.
1560    Help,
1561
1562    /// Similar to `Note`, but even rarer. Lacks the a trailing blank line that all other
1563    /// diagnostics have. Also, when printed for human consumption it doesn't have a `note:` label.
1564    FailureNote,
1565}
1566
1567impl fmt::Display for Level {
1568    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1569        self.to_str().fmt(f)
1570    }
1571}
1572
1573impl Level {
1574    pub fn to_str(self) -> &'static str {
1575        match self {
1576            Bug | DelayedBug => "error: internal compiler error",
1577            Fatal | Error => "error",
1578            Warning(_) => "warning",
1579            Note => "note",
1580            Help => "help",
1581            FailureNote => "failure-note",
1582        }
1583    }
1584
1585    pub fn is_failure_note(self) -> bool {
1586        #[allow(non_exhaustive_omitted_patterns)] match self {
    FailureNote => true,
    _ => false,
}matches!(self, FailureNote)
1587    }
1588}
1589
1590impl IntoDiagArg for Level {
1591    fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> DiagArgValue {
1592        DiagArgValue::Str(Cow::from(self.to_string()))
1593    }
1594}
1595
1596/// The level for a subdiagnostic.
1597#[derive(#[automatically_derived]impl ::core::marker::Copy for Sublevel { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Sublevel
    {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Sublevel {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Sublevel { }Eq, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Sublevel {
}
#[automatically_derived]impl ::core::clone::Clone for Sublevel {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::hash::Hash for Sublevel {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, #[automatically_derived]impl ::core::fmt::Debug for Sublevel {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "Error Warning Note OnceNote Help OnceHelp",
            match self {
                Sublevel::Error => 0usize,
                Sublevel::Warning => 6usize,
                Sublevel::Note => 14usize,
                Sublevel::OnceNote => 19usize,
                Sublevel::Help => 28usize,
                Sublevel::OnceHelp => 33usize,
            })
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Sublevel {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        Sublevel::Error => { 0usize }
                        Sublevel::Warning => { 1usize }
                        Sublevel::Note => { 2usize }
                        Sublevel::OnceNote => { 3usize }
                        Sublevel::Help => { 4usize }
                        Sublevel::OnceHelp => { 5usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for Sublevel {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { Sublevel::Error }
                    1usize => { Sublevel::Warning }
                    2usize => { Sublevel::Note }
                    3usize => { Sublevel::OnceNote }
                    4usize => { Sublevel::Help }
                    5usize => { Sublevel::OnceHelp }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Sublevel`, expected 0..6, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
1598pub enum Sublevel {
1599    /// See `Level::Error`.
1600    ///
1601    /// The compiler never uses this level in a subdiagnostic, but it can be produced by proc
1602    /// macros. See tests/ui/proc-macro/sub-error-diag.rs for details.
1603    Error,
1604
1605    /// See `Level::Warning`.
1606    Warning,
1607
1608    /// A message giving additional context.
1609    Note,
1610
1611    /// A note that is only emitted once.
1612    OnceNote,
1613
1614    /// A message suggesting how to fix something.
1615    Help,
1616
1617    /// A help that is only emitted once.
1618    OnceHelp,
1619}
1620
1621impl Sublevel {
1622    pub fn to_str(self) -> &'static str {
1623        match self {
1624            Sublevel::Error => "error",
1625            Sublevel::Warning => "warning",
1626            Sublevel::Note | Sublevel::OnceNote => "note",
1627            Sublevel::Help | Sublevel::OnceHelp => "help",
1628        }
1629    }
1630}
1631
1632#[derive(#[automatically_derived]impl ::core::marker::Copy for Style { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Style {
}
#[automatically_derived]impl ::core::clone::Clone for Style {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Style {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Style::NoStyle => "NoStyle",
                Style::Highlight => "Highlight",
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Style { }
#[automatically_derived]impl ::core::cmp::PartialEq for Style {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Style { }Eq, #[automatically_derived]impl ::core::hash::Hash for Style {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Style {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        Style::NoStyle => { 0usize }
                        Style::Highlight => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for Style {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { Style::NoStyle }
                    1usize => { Style::Highlight }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Style`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
1633pub enum Style {
1634    NoStyle,
1635    Highlight,
1636}
1637
1638// FIXME(eddyb) this doesn't belong here AFAICT, should be moved to callsite.
1639pub fn elided_lifetime_in_path_suggestion(
1640    source_map: &SourceMap,
1641    n: usize,
1642    path_span: Span,
1643    incl_angl_brckt: bool,
1644    insertion_span: Span,
1645) -> ElidedLifetimeInPathSubdiag {
1646    let expected = ExpectedLifetimeParameter { span: path_span, count: n };
1647    // Do not try to suggest anything if generated by a proc-macro.
1648    let indicate = source_map.is_span_accessible(insertion_span).then(|| {
1649        let anon_lts = ::alloc::vec::from_elem_global("'_", n)vec!["'_"; n].join(", ");
1650        let suggestion =
1651            if incl_angl_brckt { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("<{0}>", anon_lts))
    })format!("<{anon_lts}>") } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}, ", anon_lts))
    })format!("{anon_lts}, ") };
1652
1653        IndicateAnonymousLifetime { span: insertion_span.shrink_to_hi(), count: n, suggestion }
1654    });
1655
1656    ElidedLifetimeInPathSubdiag { expected, indicate }
1657}
1658
1659/// Grammatical tool for displaying messages to end users in a nice form.
1660///
1661/// Returns "an" if the given string starts with a vowel, and "a" otherwise.
1662pub fn a_or_an(s: &str) -> &'static str {
1663    let mut chars = s.chars();
1664    let Some(mut first_alpha_char) = chars.next() else {
1665        return "a";
1666    };
1667    if first_alpha_char == '`' {
1668        let Some(next) = chars.next() else {
1669            return "a";
1670        };
1671        first_alpha_char = next;
1672    }
1673    if ["a", "e", "i", "o", "u", "&"].contains(&&first_alpha_char.to_lowercase().to_string()[..]) {
1674        "an"
1675    } else {
1676        "a"
1677    }
1678}
1679
1680#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for TerminalUrl {
}
#[automatically_derived]impl ::core::clone::Clone for TerminalUrl {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for TerminalUrl { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    TerminalUrl {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TerminalUrl {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for TerminalUrl {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state)
    }
}Hash, #[automatically_derived]impl ::core::fmt::Debug for TerminalUrl {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                TerminalUrl::No => "No",
                TerminalUrl::Yes => "Yes",
                TerminalUrl::Auto => "Auto",
            })
    }
}Debug)]
1681pub enum TerminalUrl {
1682    No,
1683    Yes,
1684    Auto,
1685}