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