Skip to main content

rustc_errors/
diagnostic.rs

1use std::borrow::Cow;
2use std::fmt::{self, Debug};
3use std::hash::{Hash, Hasher};
4use std::marker::PhantomData;
5use std::ops::{Deref, DerefMut};
6use std::panic;
7use std::path::PathBuf;
8use std::thread::panicking;
9
10use rustc_data_structures::fx::FxIndexMap;
11use rustc_error_messages::{DiagArgName, DiagArgValue, IntoDiagArg};
12use rustc_lint_defs::{Applicability, LintExpectationId};
13use rustc_macros::{Decodable, Encodable};
14use rustc_span::source_map::Spanned;
15use rustc_span::{DUMMY_SP, Span, Symbol};
16use tracing::debug;
17
18use crate::{
19    CodeSuggestion, DiagCtxtHandle, DiagMessage, ErrCode, ErrorGuaranteed, ExplicitBug, Level,
20    MultiSpan, StashKey, Style, Substitution, SubstitutionPart, SuggestionStyle, Suggestions,
21};
22
23pub type DiagArgMap = FxIndexMap<DiagArgName, DiagArgValue>;
24
25/// Trait for types that `Diag::emit` can return as a "guarantee" (or "proof")
26/// token that the emission happened.
27pub trait EmissionGuarantee: Sized {
28    /// This exists so that bugs and fatal errors can both result in `!` (an
29    /// abort) when emitted, but have different aborting behaviour.
30    type EmitResult = Self;
31
32    /// Implementation of `Diag::emit`, fully controlled by each `impl` of
33    /// `EmissionGuarantee`, to make it impossible to create a value of
34    /// `Self::EmitResult` without actually performing the emission.
35    #[track_caller]
36    fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult;
37}
38
39impl EmissionGuarantee for ErrorGuaranteed {
40    fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
41        diag.emit_producing_error_guaranteed()
42    }
43}
44
45impl EmissionGuarantee for () {
46    fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
47        diag.emit_producing_nothing();
48    }
49}
50
51/// Marker type which enables implementation of `create_bug` and `emit_bug` functions for
52/// bug diagnostics.
53#[derive(#[automatically_derived]
impl ::core::marker::Copy for BugAbort { }Copy, #[automatically_derived]
impl ::core::clone::Clone for BugAbort {
    #[inline]
    fn clone(&self) -> BugAbort { *self }
}Clone)]
54pub struct BugAbort;
55
56impl EmissionGuarantee for BugAbort {
57    type EmitResult = !;
58
59    fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
60        diag.emit_producing_nothing();
61        panic::panic_any(ExplicitBug);
62    }
63}
64
65/// Marker type which enables implementation of `create_fatal` and `emit_fatal` functions for
66/// fatal diagnostics.
67#[derive(#[automatically_derived]
impl ::core::marker::Copy for FatalAbort { }Copy, #[automatically_derived]
impl ::core::clone::Clone for FatalAbort {
    #[inline]
    fn clone(&self) -> FatalAbort { *self }
}Clone)]
68pub struct FatalAbort;
69
70impl EmissionGuarantee for FatalAbort {
71    type EmitResult = !;
72
73    fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
74        diag.emit_producing_nothing();
75        crate::FatalError.raise()
76    }
77}
78
79impl EmissionGuarantee for rustc_span::fatal_error::FatalError {
80    fn emit_producing_guarantee(diag: Diag<'_, Self>) -> Self::EmitResult {
81        diag.emit_producing_nothing();
82        rustc_span::fatal_error::FatalError
83    }
84}
85
86/// Trait implemented by error types. This is rarely implemented manually. Instead, use
87/// `#[derive(Diagnostic)]` -- see [rustc_macros::Diagnostic].
88///
89/// When implemented manually, it should be generic over the emission
90/// guarantee, i.e.:
91/// ```ignore (fragment)
92/// impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for Foo { ... }
93/// ```
94/// rather than being specific:
95/// ```ignore (fragment)
96/// impl<'a> Diagnostic<'a> for Bar { ... }  // the default type param is `ErrorGuaranteed`
97/// impl<'a> Diagnostic<'a, ()> for Baz { ... }
98/// ```
99/// There are two reasons for this.
100/// - A diagnostic like `Foo` *could* be emitted at any level -- `level` is
101///   passed in to `into_diag` from outside. Even if in practice it is
102///   always emitted at a single level, we let the diagnostic creation/emission
103///   site determine the level (by using `create_err`, `emit_warn`, etc.)
104///   rather than the `Diagnostic` impl.
105/// - Derived impls are always generic, and it's good for the hand-written
106///   impls to be consistent with them.
107#[rustc_diagnostic_item = "Diagnostic"]
108pub trait Diagnostic<'a, G: EmissionGuarantee = ErrorGuaranteed> {
109    /// Write out as a diagnostic out of `DiagCtxt`.
110    #[must_use]
111    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G>;
112}
113
114impl<'a, T, G> Diagnostic<'a, G> for Spanned<T>
115where
116    T: Diagnostic<'a, G>,
117    G: EmissionGuarantee,
118{
119    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
120        self.node.into_diag(dcx, level).with_span(self.span)
121    }
122}
123
124/// Trait implemented by error types. This should not be implemented manually. Instead, use
125/// `#[derive(Subdiagnostic)]` -- see [rustc_macros::Subdiagnostic].
126#[rustc_diagnostic_item = "Subdiagnostic"]
127pub trait Subdiagnostic
128where
129    Self: Sized,
130{
131    /// Add a subdiagnostic to an existing diagnostic.
132    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>);
133}
134
135/// Trait implemented by lint types. This should not be implemented manually. Instead, use
136/// `#[derive(LintDiagnostic)]` -- see [rustc_macros::LintDiagnostic].
137#[rustc_diagnostic_item = "LintDiagnostic"]
138pub trait LintDiagnostic<'a, G: EmissionGuarantee> {
139    /// Decorate a lint with the information from this type.
140    fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, G>);
141}
142
143pub trait LintDiagnosticBox<'a, G: EmissionGuarantee> {
144    fn decorate_lint_box<'b>(self: Box<Self>, diag: &'b mut Diag<'a, G>);
145}
146
147impl<'a, G: EmissionGuarantee, D: LintDiagnostic<'a, G>> LintDiagnosticBox<'a, G> for D {
148    fn decorate_lint_box<'b>(self: Box<Self>, diag: &'b mut Diag<'a, G>) {
149        self.decorate_lint(diag);
150    }
151}
152
153#[derive(#[automatically_derived]
impl ::core::clone::Clone for DiagLocation {
    #[inline]
    fn clone(&self) -> DiagLocation {
        DiagLocation {
            file: ::core::clone::Clone::clone(&self.file),
            line: ::core::clone::Clone::clone(&self.line),
            col: ::core::clone::Clone::clone(&self.col),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for DiagLocation {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "DiagLocation",
            "file", &self.file, "line", &self.line, "col", &&self.col)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DiagLocation {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    DiagLocation {
                        file: ref __binding_0,
                        line: ref __binding_1,
                        col: ref __binding_2 } => {
                        ::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 DiagLocation {
            fn decode(__decoder: &mut __D) -> Self {
                DiagLocation {
                    file: ::rustc_serialize::Decodable::decode(__decoder),
                    line: ::rustc_serialize::Decodable::decode(__decoder),
                    col: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
154pub(crate) struct DiagLocation {
155    file: Cow<'static, str>,
156    line: u32,
157    col: u32,
158}
159
160impl DiagLocation {
161    #[track_caller]
162    fn caller() -> Self {
163        let loc = panic::Location::caller();
164        DiagLocation { file: loc.file().into(), line: loc.line(), col: loc.column() }
165    }
166}
167
168impl fmt::Display for DiagLocation {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        f.write_fmt(format_args!("{0}:{1}:{2}", self.file, self.line, self.col))write!(f, "{}:{}:{}", self.file, self.line, self.col)
171    }
172}
173
174#[derive(#[automatically_derived]
impl ::core::clone::Clone for IsLint {
    #[inline]
    fn clone(&self) -> IsLint {
        IsLint {
            name: ::core::clone::Clone::clone(&self.name),
            has_future_breakage: ::core::clone::Clone::clone(&self.has_future_breakage),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for IsLint {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "IsLint",
            "name", &self.name, "has_future_breakage",
            &&self.has_future_breakage)
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for IsLint {
    #[inline]
    fn eq(&self, other: &IsLint) -> bool {
        self.has_future_breakage == other.has_future_breakage &&
            self.name == other.name
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for IsLint {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<String>;
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for IsLint {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.name, state);
        ::core::hash::Hash::hash(&self.has_future_breakage, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for IsLint {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    IsLint {
                        name: ref __binding_0, has_future_breakage: ref __binding_1
                        } => {
                        ::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 IsLint {
            fn decode(__decoder: &mut __D) -> Self {
                IsLint {
                    name: ::rustc_serialize::Decodable::decode(__decoder),
                    has_future_breakage: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
175pub struct IsLint {
176    /// The lint name.
177    pub(crate) name: String,
178    /// Indicates whether this lint should show up in cargo's future breakage report.
179    has_future_breakage: bool,
180}
181
182#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DiagStyledString {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f,
            "DiagStyledString", &&self.0)
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for DiagStyledString {
    #[inline]
    fn eq(&self, other: &DiagStyledString) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DiagStyledString {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Vec<StringPart>>;
    }
}Eq)]
183pub struct DiagStyledString(pub Vec<StringPart>);
184
185impl DiagStyledString {
186    pub fn new() -> DiagStyledString {
187        DiagStyledString(::alloc::vec::Vec::new()vec![])
188    }
189    pub fn push_normal<S: Into<String>>(&mut self, t: S) {
190        self.0.push(StringPart::normal(t));
191    }
192    pub fn push_highlighted<S: Into<String>>(&mut self, t: S) {
193        self.0.push(StringPart::highlighted(t));
194    }
195    pub fn push<S: Into<String>>(&mut self, t: S, highlight: bool) {
196        if highlight {
197            self.push_highlighted(t);
198        } else {
199            self.push_normal(t);
200        }
201    }
202    pub fn normal<S: Into<String>>(t: S) -> DiagStyledString {
203        DiagStyledString(<[_]>::into_vec(::alloc::boxed::box_new([StringPart::normal(t)]))vec![StringPart::normal(t)])
204    }
205
206    pub fn highlighted<S: Into<String>>(t: S) -> DiagStyledString {
207        DiagStyledString(<[_]>::into_vec(::alloc::boxed::box_new([StringPart::highlighted(t)]))vec![StringPart::highlighted(t)])
208    }
209
210    pub fn content(&self) -> String {
211        self.0.iter().map(|x| x.content.as_str()).collect::<String>()
212    }
213}
214
215#[derive(#[automatically_derived]
impl ::core::fmt::Debug for StringPart {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "StringPart",
            "content", &self.content, "style", &&self.style)
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for StringPart {
    #[inline]
    fn eq(&self, other: &StringPart) -> bool {
        self.content == other.content && self.style == other.style
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for StringPart {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<String>;
        let _: ::core::cmp::AssertParamIsEq<Style>;
    }
}Eq)]
216pub struct StringPart {
217    content: String,
218    style: Style,
219}
220
221impl StringPart {
222    pub fn normal<S: Into<String>>(content: S) -> StringPart {
223        StringPart { content: content.into(), style: Style::NoStyle }
224    }
225
226    pub fn highlighted<S: Into<String>>(content: S) -> StringPart {
227        StringPart { content: content.into(), style: Style::Highlight }
228    }
229}
230
231/// The main part of a diagnostic. Note that `Diag`, which wraps this type, is
232/// used for most operations, and should be used instead whenever possible.
233/// This type should only be used when `Diag`'s lifetime causes difficulties,
234/// e.g. when storing diagnostics within `DiagCtxt`.
235#[must_use]
236#[derive(#[automatically_derived]
impl ::core::clone::Clone for DiagInner {
    #[inline]
    fn clone(&self) -> DiagInner {
        DiagInner {
            level: ::core::clone::Clone::clone(&self.level),
            messages: ::core::clone::Clone::clone(&self.messages),
            code: ::core::clone::Clone::clone(&self.code),
            lint_id: ::core::clone::Clone::clone(&self.lint_id),
            span: ::core::clone::Clone::clone(&self.span),
            children: ::core::clone::Clone::clone(&self.children),
            suggestions: ::core::clone::Clone::clone(&self.suggestions),
            args: ::core::clone::Clone::clone(&self.args),
            reserved_args: ::core::clone::Clone::clone(&self.reserved_args),
            sort_span: ::core::clone::Clone::clone(&self.sort_span),
            is_lint: ::core::clone::Clone::clone(&self.is_lint),
            long_ty_path: ::core::clone::Clone::clone(&self.long_ty_path),
            emitted_at: ::core::clone::Clone::clone(&self.emitted_at),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for DiagInner {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["level", "messages", "code", "lint_id", "span", "children",
                        "suggestions", "args", "reserved_args", "sort_span",
                        "is_lint", "long_ty_path", "emitted_at"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.level, &self.messages, &self.code, &self.lint_id,
                        &self.span, &self.children, &self.suggestions, &self.args,
                        &self.reserved_args, &self.sort_span, &self.is_lint,
                        &self.long_ty_path, &&self.emitted_at];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "DiagInner",
            names, values)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for DiagInner {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    DiagInner {
                        level: ref __binding_0,
                        messages: ref __binding_1,
                        code: ref __binding_2,
                        lint_id: ref __binding_3,
                        span: ref __binding_4,
                        children: ref __binding_5,
                        suggestions: ref __binding_6,
                        args: ref __binding_7,
                        reserved_args: ref __binding_8,
                        sort_span: ref __binding_9,
                        is_lint: ref __binding_10,
                        long_ty_path: ref __binding_11,
                        emitted_at: ref __binding_12 } => {
                        ::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);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_4,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_5,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_6,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_7,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_8,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_9,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_10,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_11,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_12,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for DiagInner {
            fn decode(__decoder: &mut __D) -> Self {
                DiagInner {
                    level: ::rustc_serialize::Decodable::decode(__decoder),
                    messages: ::rustc_serialize::Decodable::decode(__decoder),
                    code: ::rustc_serialize::Decodable::decode(__decoder),
                    lint_id: ::rustc_serialize::Decodable::decode(__decoder),
                    span: ::rustc_serialize::Decodable::decode(__decoder),
                    children: ::rustc_serialize::Decodable::decode(__decoder),
                    suggestions: ::rustc_serialize::Decodable::decode(__decoder),
                    args: ::rustc_serialize::Decodable::decode(__decoder),
                    reserved_args: ::rustc_serialize::Decodable::decode(__decoder),
                    sort_span: ::rustc_serialize::Decodable::decode(__decoder),
                    is_lint: ::rustc_serialize::Decodable::decode(__decoder),
                    long_ty_path: ::rustc_serialize::Decodable::decode(__decoder),
                    emitted_at: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
237pub struct DiagInner {
238    // NOTE(eddyb) this is private to disallow arbitrary after-the-fact changes,
239    // outside of what methods in this crate themselves allow.
240    pub(crate) level: Level,
241
242    pub messages: Vec<(DiagMessage, Style)>,
243    pub code: Option<ErrCode>,
244    pub lint_id: Option<LintExpectationId>,
245    pub span: MultiSpan,
246    pub children: Vec<Subdiag>,
247    pub suggestions: Suggestions,
248    pub args: DiagArgMap,
249
250    // This is used to store args and restore them after a subdiagnostic is rendered.
251    pub reserved_args: DiagArgMap,
252
253    /// This is not used for highlighting or rendering any error message. Rather, it can be used
254    /// as a sort key to sort a buffer of diagnostics. By default, it is the primary span of
255    /// `span` if there is one. Otherwise, it is `DUMMY_SP`.
256    pub sort_span: Span,
257
258    pub is_lint: Option<IsLint>,
259
260    pub long_ty_path: Option<PathBuf>,
261    /// With `-Ztrack_diagnostics` enabled,
262    /// we print where in rustc this error was emitted.
263    pub(crate) emitted_at: DiagLocation,
264}
265
266impl DiagInner {
267    #[track_caller]
268    pub fn new<M: Into<DiagMessage>>(level: Level, message: M) -> Self {
269        DiagInner::new_with_messages(level, <[_]>::into_vec(::alloc::boxed::box_new([(message.into(), Style::NoStyle)]))vec![(message.into(), Style::NoStyle)])
270    }
271
272    #[track_caller]
273    pub fn new_with_messages(level: Level, messages: Vec<(DiagMessage, Style)>) -> Self {
274        DiagInner {
275            level,
276            lint_id: None,
277            messages,
278            code: None,
279            span: MultiSpan::new(),
280            children: ::alloc::vec::Vec::new()vec![],
281            suggestions: Suggestions::Enabled(::alloc::vec::Vec::new()vec![]),
282            args: Default::default(),
283            reserved_args: Default::default(),
284            sort_span: DUMMY_SP,
285            is_lint: None,
286            long_ty_path: None,
287            emitted_at: DiagLocation::caller(),
288        }
289    }
290
291    #[inline(always)]
292    pub fn level(&self) -> Level {
293        self.level
294    }
295
296    pub fn is_error(&self) -> bool {
297        match self.level {
298            Level::Bug | Level::Fatal | Level::Error | Level::DelayedBug => true,
299
300            Level::ForceWarning
301            | Level::Warning
302            | Level::Note
303            | Level::OnceNote
304            | Level::Help
305            | Level::OnceHelp
306            | Level::FailureNote
307            | Level::Allow
308            | Level::Expect => false,
309        }
310    }
311
312    /// Indicates whether this diagnostic should show up in cargo's future breakage report.
313    pub(crate) fn has_future_breakage(&self) -> bool {
314        #[allow(non_exhaustive_omitted_patterns)] match self.is_lint {
    Some(IsLint { has_future_breakage: true, .. }) => true,
    _ => false,
}matches!(self.is_lint, Some(IsLint { has_future_breakage: true, .. }))
315    }
316
317    pub(crate) fn is_force_warn(&self) -> bool {
318        match self.level {
319            Level::ForceWarning => {
320                if !self.is_lint.is_some() {
    ::core::panicking::panic("assertion failed: self.is_lint.is_some()")
};assert!(self.is_lint.is_some());
321                true
322            }
323            _ => false,
324        }
325    }
326
327    pub(crate) fn sub(&mut self, level: Level, message: impl Into<DiagMessage>, span: MultiSpan) {
328        let sub = Subdiag { level, messages: <[_]>::into_vec(::alloc::boxed::box_new([(message.into(), Style::NoStyle)]))vec![(message.into(), Style::NoStyle)], span };
329        self.children.push(sub);
330    }
331
332    pub(crate) fn arg(&mut self, name: impl Into<DiagArgName>, arg: impl IntoDiagArg) {
333        let name = name.into();
334        let value = arg.into_diag_arg(&mut self.long_ty_path);
335        // This assertion is to avoid subdiagnostics overwriting an existing diagnostic arg.
336        if true {
    if !(!self.args.contains_key(&name) ||
                self.args.get(&name) == Some(&value)) {
        {
            ::core::panicking::panic_fmt(format_args!("arg {0} already exists",
                    name));
        }
    };
};debug_assert!(
337            !self.args.contains_key(&name) || self.args.get(&name) == Some(&value),
338            "arg {} already exists",
339            name
340        );
341        self.args.insert(name, value);
342    }
343
344    pub fn remove_arg(&mut self, name: &str) {
345        self.args.swap_remove(name);
346    }
347
348    pub fn store_args(&mut self) {
349        self.reserved_args = self.args.clone();
350    }
351
352    pub fn restore_args(&mut self) {
353        self.args = std::mem::take(&mut self.reserved_args);
354    }
355
356    pub fn emitted_at_sub_diag(&self) -> Subdiag {
357        let track = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-Ztrack-diagnostics: created at {0}",
                self.emitted_at))
    })format!("-Ztrack-diagnostics: created at {}", self.emitted_at);
358        Subdiag {
359            level: crate::Level::Note,
360            messages: <[_]>::into_vec(::alloc::boxed::box_new([(DiagMessage::Str(Cow::Owned(track)),
                    Style::NoStyle)]))vec![(DiagMessage::Str(Cow::Owned(track)), Style::NoStyle)],
361            span: MultiSpan::new(),
362        }
363    }
364
365    /// Fields used for Hash, and PartialEq trait.
366    fn keys(
367        &self,
368    ) -> (
369        &Level,
370        &[(DiagMessage, Style)],
371        &Option<ErrCode>,
372        &MultiSpan,
373        &[Subdiag],
374        &Suggestions,
375        Vec<(&DiagArgName, &DiagArgValue)>,
376        &Option<IsLint>,
377    ) {
378        (
379            &self.level,
380            &self.messages,
381            &self.code,
382            &self.span,
383            &self.children,
384            &self.suggestions,
385            self.args.iter().collect(),
386            // omit self.sort_span
387            &self.is_lint,
388            // omit self.emitted_at
389        )
390    }
391}
392
393impl Hash for DiagInner {
394    fn hash<H>(&self, state: &mut H)
395    where
396        H: Hasher,
397    {
398        self.keys().hash(state);
399    }
400}
401
402impl PartialEq for DiagInner {
403    fn eq(&self, other: &Self) -> bool {
404        self.keys() == other.keys()
405    }
406}
407
408/// A "sub"-diagnostic attached to a parent diagnostic.
409/// For example, a note attached to an error.
410#[derive(#[automatically_derived]
impl ::core::clone::Clone for Subdiag {
    #[inline]
    fn clone(&self) -> Subdiag {
        Subdiag {
            level: ::core::clone::Clone::clone(&self.level),
            messages: ::core::clone::Clone::clone(&self.messages),
            span: ::core::clone::Clone::clone(&self.span),
        }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Subdiag {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "Subdiag",
            "level", &self.level, "messages", &self.messages, "span",
            &&self.span)
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Subdiag {
    #[inline]
    fn eq(&self, other: &Subdiag) -> bool {
        self.level == other.level && self.messages == other.messages &&
            self.span == other.span
    }
}PartialEq, #[automatically_derived]
impl ::core::hash::Hash for Subdiag {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.level, state);
        ::core::hash::Hash::hash(&self.messages, state);
        ::core::hash::Hash::hash(&self.span, state)
    }
}Hash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Subdiag {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    Subdiag {
                        level: ref __binding_0,
                        messages: ref __binding_1,
                        span: ref __binding_2 } => {
                        ::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 Subdiag {
            fn decode(__decoder: &mut __D) -> Self {
                Subdiag {
                    level: ::rustc_serialize::Decodable::decode(__decoder),
                    messages: ::rustc_serialize::Decodable::decode(__decoder),
                    span: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
411pub struct Subdiag {
412    pub level: Level,
413    pub messages: Vec<(DiagMessage, Style)>,
414    pub span: MultiSpan,
415}
416
417/// Used for emitting structured error messages and other diagnostic information.
418/// Wraps a `DiagInner`, adding some useful things.
419/// - The `dcx` field, allowing it to (a) emit itself, and (b) do a drop check
420///   that it has been emitted or cancelled.
421/// - The `EmissionGuarantee`, which determines the type returned from `emit`.
422///
423/// Each constructed `Diag` must be consumed by a function such as `emit`,
424/// `cancel`, `delay_as_bug`, or `into_diag`. A panic occurs if a `Diag`
425/// is dropped without being consumed by one of these functions.
426///
427/// If there is some state in a downstream crate you would like to access in
428/// the methods of `Diag` here, consider extending `DiagCtxtFlags`.
429#[must_use]
430pub struct Diag<'a, G: EmissionGuarantee = ErrorGuaranteed> {
431    pub dcx: DiagCtxtHandle<'a>,
432
433    /// Why the `Option`? It is always `Some` until the `Diag` is consumed via
434    /// `emit`, `cancel`, etc. At that point it is consumed and replaced with
435    /// `None`. Then `drop` checks that it is `None`; if not, it panics because
436    /// a diagnostic was built but not used.
437    ///
438    /// Why the Box? `DiagInner` is a large type, and `Diag` is often used as a
439    /// return value, especially within the frequently-used `PResult` type. In
440    /// theory, return value optimization (RVO) should avoid unnecessary
441    /// copying. In practice, it does not (at the time of writing).
442    diag: Option<Box<DiagInner>>,
443
444    _marker: PhantomData<G>,
445}
446
447// Cloning a `Diag` is a recipe for a diagnostic being emitted twice, which
448// would be bad.
449impl<G> !Clone for Diag<'_, G> {}
450
451const _: [(); 3 * size_of::<usize>()] =
    [(); ::std::mem::size_of::<Diag<'_, ()>>()];rustc_data_structures::static_assert_size!(Diag<'_, ()>, 3 * size_of::<usize>());
452
453impl<G: EmissionGuarantee> Deref for Diag<'_, G> {
454    type Target = DiagInner;
455
456    fn deref(&self) -> &DiagInner {
457        self.diag.as_ref().unwrap()
458    }
459}
460
461impl<G: EmissionGuarantee> DerefMut for Diag<'_, G> {
462    fn deref_mut(&mut self) -> &mut DiagInner {
463        self.diag.as_mut().unwrap()
464    }
465}
466
467impl<G: EmissionGuarantee> Debug for Diag<'_, G> {
468    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469        self.diag.fmt(f)
470    }
471}
472
473/// `Diag` impls many `&mut self -> &mut Self` methods. Each one modifies an
474/// existing diagnostic, either in a standalone fashion, e.g.
475/// `err.code(code);`, or in a chained fashion to make multiple modifications,
476/// e.g. `err.code(code).span(span);`.
477///
478/// This macro creates an equivalent `self -> Self` method, with a `with_`
479/// prefix. This can be used in a chained fashion when making a new diagnostic,
480/// e.g. `let err = struct_err(msg).with_code(code);`, or emitting a new
481/// diagnostic, e.g. `struct_err(msg).with_code(code).emit();`.
482///
483/// Although the latter method can be used to modify an existing diagnostic,
484/// e.g. `err = err.with_code(code);`, this should be avoided because the former
485/// method gives shorter code, e.g. `err.code(code);`.
486///
487/// Note: the `with_` methods are added only when needed. If you want to use
488/// one and it's not defined, feel free to add it.
489///
490/// Note: any doc comments must be within the `with_fn!` call.
491macro_rules! with_fn {
492    {
493        $with_f:ident,
494        $(#[$attrs:meta])*
495        pub fn $f:ident(&mut $self:ident, $($name:ident: $ty:ty),* $(,)?) -> &mut Self {
496            $($body:tt)*
497        }
498    } => {
499        // The original function.
500        $(#[$attrs])*
501        #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
502        pub fn $f(&mut $self, $($name: $ty),*) -> &mut Self {
503            $($body)*
504        }
505
506        // The `with_*` variant.
507        $(#[$attrs])*
508        #[doc = concat!("See [`Diag::", stringify!($f), "()`].")]
509        pub fn $with_f(mut $self, $($name: $ty),*) -> Self {
510            $self.$f($($name),*);
511            $self
512        }
513    };
514}
515
516impl<'a, G: EmissionGuarantee> Diag<'a, G> {
517    #[track_caller]
518    pub fn new(dcx: DiagCtxtHandle<'a>, level: Level, message: impl Into<DiagMessage>) -> Self {
519        Self::new_diagnostic(dcx, DiagInner::new(level, message))
520    }
521
522    /// Allow moving diagnostics between different error tainting contexts
523    pub fn with_dcx(mut self, dcx: DiagCtxtHandle<'_>) -> Diag<'_, G> {
524        Diag { dcx, diag: self.diag.take(), _marker: PhantomData }
525    }
526
527    /// Creates a new `Diag` with an already constructed diagnostic.
528    #[track_caller]
529    pub(crate) fn new_diagnostic(dcx: DiagCtxtHandle<'a>, diag: DiagInner) -> Self {
530        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_errors/src/diagnostic.rs:530",
                        "rustc_errors::diagnostic", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_errors/src/diagnostic.rs"),
                        ::tracing_core::__macro_support::Option::Some(530u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_errors::diagnostic"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("Created new diagnostic")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("Created new diagnostic");
531        Self { dcx, diag: Some(Box::new(diag)), _marker: PhantomData }
532    }
533
534    /// Delay emission of this diagnostic as a bug.
535    ///
536    /// This can be useful in contexts where an error indicates a bug but
537    /// typically this only happens when other compilation errors have already
538    /// happened. In those cases this can be used to defer emission of this
539    /// diagnostic as a bug in the compiler only if no other errors have been
540    /// emitted.
541    ///
542    /// In the meantime, though, callsites are required to deal with the "bug"
543    /// locally in whichever way makes the most sense.
544    #[track_caller]
545    pub fn downgrade_to_delayed_bug(&mut self) {
546        if !#[allow(non_exhaustive_omitted_patterns)] match self.level {
            Level::Error | Level::DelayedBug => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("downgrade_to_delayed_bug: cannot downgrade {0:?} to DelayedBug: not an error",
                self.level));
    }
};assert!(
547            matches!(self.level, Level::Error | Level::DelayedBug),
548            "downgrade_to_delayed_bug: cannot downgrade {:?} to DelayedBug: not an error",
549            self.level
550        );
551        self.level = Level::DelayedBug;
552    }
553
554    /// Make emitting this diagnostic fatal
555    ///
556    /// Changes the level of this diagnostic to Fatal, and importantly also changes the emission guarantee.
557    /// This is sound for errors that would otherwise be printed, but now simply exit the process instead.
558    /// This function still gives an emission guarantee, the guarantee is now just that it exits fatally.
559    /// For delayed bugs this is different, since those are buffered. If we upgrade one to fatal, another
560    /// might now be ignored.
561    #[track_caller]
562    pub fn upgrade_to_fatal(mut self) -> Diag<'a, FatalAbort> {
563        if !#[allow(non_exhaustive_omitted_patterns)] match self.level {
            Level::Error => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("upgrade_to_fatal: cannot upgrade {0:?} to Fatal: not an error",
                self.level));
    }
};assert!(
564            matches!(self.level, Level::Error),
565            "upgrade_to_fatal: cannot upgrade {:?} to Fatal: not an error",
566            self.level
567        );
568        self.level = Level::Fatal;
569
570        // Take is okay since we immediately rewrap it in another diagnostic.
571        // i.e. we do emit it despite defusing the original diagnostic's drop bomb.
572        let diag = self.diag.take();
573        Diag { dcx: self.dcx, diag, _marker: PhantomData }
574    }
575
576    "See [`Diag::span_label()`]."
&mut Self
self
span
label
&mut Self
"See [`Diag::span_label()`]."
mut self
span
label
Self
self.span_label(span, label);
self;with_fn! { with_span_label,
577    /// Appends a labeled span to the diagnostic.
578    ///
579    /// Labels are used to convey additional context for the diagnostic's primary span. They will
580    /// be shown together with the original diagnostic's span, *not* with spans added by
581    /// `span_note`, `span_help`, etc. Therefore, if the primary span is not displayable (because
582    /// the span is `DUMMY_SP` or the source code isn't found), labels will not be displayed
583    /// either.
584    ///
585    /// Implementation-wise, the label span is pushed onto the [`MultiSpan`] that was created when
586    /// the diagnostic was constructed. However, the label span is *not* considered a
587    /// ["primary span"][`MultiSpan`]; only the `Span` supplied when creating the diagnostic is
588    /// primary.
589    pub fn span_label(&mut self, span: Span, label: impl Into<DiagMessage>) -> &mut Self {
590        self.span.push_span_label(span, label.into());
591        self
592    } }
593
594    "See [`Diag::span_labels()`]."
&mut Self
self
spans
label
&mut Self
"See [`Diag::span_labels()`]."
mut self
spans
label
Self
self.span_labels(spans, label);
self;with_fn! { with_span_labels,
595    /// Labels all the given spans with the provided label.
596    /// See [`Self::span_label()`] for more information.
597    pub fn span_labels(&mut self, spans: impl IntoIterator<Item = Span>, label: &str) -> &mut Self {
598        for span in spans {
599            self.span_label(span, label.to_string());
600        }
601        self
602    } }
603
604    pub fn replace_span_with(&mut self, after: Span, keep_label: bool) -> &mut Self {
605        let before = self.span.clone();
606        self.span(after);
607        for span_label in before.span_labels() {
608            if let Some(label) = span_label.label {
609                if span_label.is_primary && keep_label {
610                    self.span.push_span_label(after, label);
611                } else {
612                    self.span.push_span_label(span_label.span, label);
613                }
614            }
615        }
616        self
617    }
618
619    pub fn note_expected_found(
620        &mut self,
621        expected_label: &str,
622        expected: DiagStyledString,
623        found_label: &str,
624        found: DiagStyledString,
625    ) -> &mut Self {
626        self.note_expected_found_extra(
627            expected_label,
628            expected,
629            found_label,
630            found,
631            DiagStyledString::normal(""),
632            DiagStyledString::normal(""),
633        )
634    }
635
636    pub fn note_expected_found_extra(
637        &mut self,
638        expected_label: &str,
639        expected: DiagStyledString,
640        found_label: &str,
641        found: DiagStyledString,
642        expected_extra: DiagStyledString,
643        found_extra: DiagStyledString,
644    ) -> &mut Self {
645        let expected_label = expected_label.to_string();
646        let expected_label = if expected_label.is_empty() {
647            "expected".to_string()
648        } else {
649            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected {0}", expected_label))
    })format!("expected {expected_label}")
650        };
651        let found_label = found_label.to_string();
652        let found_label = if found_label.is_empty() {
653            "found".to_string()
654        } else {
655            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("found {0}", found_label))
    })format!("found {found_label}")
656        };
657        let (found_padding, expected_padding) = if expected_label.len() > found_label.len() {
658            (expected_label.len() - found_label.len(), 0)
659        } else {
660            (0, found_label.len() - expected_label.len())
661        };
662        let mut msg = <[_]>::into_vec(::alloc::boxed::box_new([StringPart::normal(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("{0}{1} `",
                                    " ".repeat(expected_padding), expected_label))
                        }))]))vec![StringPart::normal(format!(
663            "{}{} `",
664            " ".repeat(expected_padding),
665            expected_label
666        ))];
667        msg.extend(expected.0);
668        msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("`")) })format!("`")));
669        msg.extend(expected_extra.0);
670        msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("\n")) })format!("\n")));
671        msg.push(StringPart::normal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1} `",
                " ".repeat(found_padding), found_label))
    })format!("{}{} `", " ".repeat(found_padding), found_label)));
672        msg.extend(found.0);
673        msg.push(StringPart::normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("`")) })format!("`")));
674        msg.extend(found_extra.0);
675
676        // For now, just attach these as notes.
677        self.highlighted_note(msg);
678        self
679    }
680
681    pub fn note_trait_signature(&mut self, name: Symbol, signature: String) -> &mut Self {
682        self.highlighted_note(<[_]>::into_vec(::alloc::boxed::box_new([StringPart::normal(::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("`{0}` from trait: `",
                                    name))
                        })), StringPart::highlighted(signature),
                StringPart::normal("`")]))vec![
683            StringPart::normal(format!("`{name}` from trait: `")),
684            StringPart::highlighted(signature),
685            StringPart::normal("`"),
686        ]);
687        self
688    }
689
690    "See [`Diag::note()`]."
&mut Self
self
msg
&mut Self
"See [`Diag::note()`]."
mut self
msg
Self
self.note(msg);
self;with_fn! { with_note,
691    /// Add a note attached to this diagnostic.
692    pub fn note(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
693        self.sub(Level::Note, msg, MultiSpan::new());
694        self
695    } }
696
697    pub fn highlighted_note(&mut self, msg: Vec<StringPart>) -> &mut Self {
698        self.sub_with_highlights(Level::Note, msg, MultiSpan::new());
699        self
700    }
701
702    pub fn highlighted_span_note(
703        &mut self,
704        span: impl Into<MultiSpan>,
705        msg: Vec<StringPart>,
706    ) -> &mut Self {
707        self.sub_with_highlights(Level::Note, msg, span.into());
708        self
709    }
710
711    /// This is like [`Diag::note()`], but it's only printed once.
712    pub fn note_once(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
713        self.sub(Level::OnceNote, msg, MultiSpan::new());
714        self
715    }
716
717    "See [`Diag::span_note()`]."
&mut Self
self
sp
msg
&mut Self
"See [`Diag::span_note()`]."
mut self
sp
msg
Self
self.span_note(sp, msg);
self;with_fn! { with_span_note,
718    /// Prints the span with a note above it.
719    /// This is like [`Diag::note()`], but it gets its own span.
720    pub fn span_note(
721        &mut self,
722        sp: impl Into<MultiSpan>,
723        msg: impl Into<DiagMessage>,
724    ) -> &mut Self {
725        self.sub(Level::Note, msg, sp.into());
726        self
727    } }
728
729    /// Prints the span with a note above it.
730    /// This is like [`Diag::note_once()`], but it gets its own span.
731    pub fn span_note_once<S: Into<MultiSpan>>(
732        &mut self,
733        sp: S,
734        msg: impl Into<DiagMessage>,
735    ) -> &mut Self {
736        self.sub(Level::OnceNote, msg, sp.into());
737        self
738    }
739
740    "See [`Diag::warn()`]."
&mut Self
self
msg
&mut Self
"See [`Diag::warn()`]."
mut self
msg
Self
self.warn(msg);
self;with_fn! { with_warn,
741    /// Add a warning attached to this diagnostic.
742    pub fn warn(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
743        self.sub(Level::Warning, msg, MultiSpan::new());
744        self
745    } }
746
747    /// Prints the span with a warning above it.
748    /// This is like [`Diag::warn()`], but it gets its own span.
749    pub fn span_warn<S: Into<MultiSpan>>(
750        &mut self,
751        sp: S,
752        msg: impl Into<DiagMessage>,
753    ) -> &mut Self {
754        self.sub(Level::Warning, msg, sp.into());
755        self
756    }
757
758    "See [`Diag::help()`]."
&mut Self
self
msg
&mut Self
"See [`Diag::help()`]."
mut self
msg
Self
self.help(msg);
self;with_fn! { with_help,
759    /// Add a help message attached to this diagnostic.
760    pub fn help(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
761        self.sub(Level::Help, msg, MultiSpan::new());
762        self
763    } }
764
765    /// This is like [`Diag::help()`], but it's only printed once.
766    pub fn help_once(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
767        self.sub(Level::OnceHelp, msg, MultiSpan::new());
768        self
769    }
770
771    /// Add a help message attached to this diagnostic with a customizable highlighted message.
772    pub fn highlighted_help(&mut self, msg: Vec<StringPart>) -> &mut Self {
773        self.sub_with_highlights(Level::Help, msg, MultiSpan::new());
774        self
775    }
776
777    /// Add a help message attached to this diagnostic with a customizable highlighted message.
778    pub fn highlighted_span_help(
779        &mut self,
780        span: impl Into<MultiSpan>,
781        msg: Vec<StringPart>,
782    ) -> &mut Self {
783        self.sub_with_highlights(Level::Help, msg, span.into());
784        self
785    }
786
787    "See [`Diag::span_help()`]."
&mut Self
self
sp
msg
&mut Self
"See [`Diag::span_help()`]."
mut self
sp
msg
Self
self.span_help(sp, msg);
self;with_fn! { with_span_help,
788    /// Prints the span with some help above it.
789    /// This is like [`Diag::help()`], but it gets its own span.
790    pub fn span_help(
791        &mut self,
792        sp: impl Into<MultiSpan>,
793        msg: impl Into<DiagMessage>,
794    ) -> &mut Self {
795        self.sub(Level::Help, msg, sp.into());
796        self
797    } }
798
799    /// Disallow attaching suggestions to this diagnostic.
800    /// Any suggestions attached e.g. with the `span_suggestion_*` methods
801    /// (before and after the call to `disable_suggestions`) will be ignored.
802    pub fn disable_suggestions(&mut self) -> &mut Self {
803        self.suggestions = Suggestions::Disabled;
804        self
805    }
806
807    /// Prevent new suggestions from being added to this diagnostic.
808    ///
809    /// Suggestions added before the call to `.seal_suggestions()` will be preserved
810    /// and new suggestions will be ignored.
811    pub fn seal_suggestions(&mut self) -> &mut Self {
812        if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
813            let suggestions_slice = std::mem::take(suggestions).into_boxed_slice();
814            self.suggestions = Suggestions::Sealed(suggestions_slice);
815        }
816        self
817    }
818
819    /// Helper for pushing to `self.suggestions`.
820    ///
821    /// A new suggestion is added if suggestions are enabled for this diagnostic.
822    /// Otherwise, they are ignored.
823    fn push_suggestion(&mut self, suggestion: CodeSuggestion) {
824        for subst in &suggestion.substitutions {
825            for part in &subst.parts {
826                let span = part.span;
827                let call_site = span.ctxt().outer_expn_data().call_site;
828                if span.in_derive_expansion() && span.overlaps_or_adjacent(call_site) {
829                    // Ignore if spans is from derive macro.
830                    return;
831                }
832            }
833        }
834
835        if let Suggestions::Enabled(suggestions) = &mut self.suggestions {
836            suggestions.push(suggestion);
837        }
838    }
839
840    "See [`Diag::multipart_suggestion()`]."
&mut Self
self
msg
suggestion
applicability
&mut Self
"See [`Diag::multipart_suggestion()`]."
mut self
msg
suggestion
applicability
Self
self.multipart_suggestion(msg, suggestion, applicability);
self;with_fn! { with_multipart_suggestion,
841    /// Show a suggestion that has multiple parts to it.
842    /// In other words, multiple changes need to be applied as part of this suggestion.
843    pub fn multipart_suggestion(
844        &mut self,
845        msg: impl Into<DiagMessage>,
846        suggestion: Vec<(Span, String)>,
847        applicability: Applicability,
848    ) -> &mut Self {
849        self.multipart_suggestion_with_style(
850            msg,
851            suggestion,
852            applicability,
853            SuggestionStyle::ShowCode,
854        )
855    } }
856
857    /// Show a suggestion that has multiple parts to it, always as its own subdiagnostic.
858    /// In other words, multiple changes need to be applied as part of this suggestion.
859    pub fn multipart_suggestion_verbose(
860        &mut self,
861        msg: impl Into<DiagMessage>,
862        suggestion: Vec<(Span, String)>,
863        applicability: Applicability,
864    ) -> &mut Self {
865        self.multipart_suggestion_with_style(
866            msg,
867            suggestion,
868            applicability,
869            SuggestionStyle::ShowAlways,
870        )
871    }
872
873    /// [`Diag::multipart_suggestion()`] but you can set the [`SuggestionStyle`].
874    pub fn multipart_suggestion_with_style(
875        &mut self,
876        msg: impl Into<DiagMessage>,
877        mut suggestion: Vec<(Span, String)>,
878        applicability: Applicability,
879        style: SuggestionStyle,
880    ) -> &mut Self {
881        let mut seen = crate::FxHashSet::default();
882        suggestion.retain(|(span, msg)| seen.insert((span.lo(), span.hi(), msg.clone())));
883
884        let parts = suggestion
885            .into_iter()
886            .map(|(span, snippet)| SubstitutionPart { snippet, span })
887            .collect::<Vec<_>>();
888
889        if !!parts.is_empty() {
    ::core::panicking::panic("assertion failed: !parts.is_empty()")
};assert!(!parts.is_empty());
890        if true {
    match (&parts.iter().find(|part|
                        part.span.is_empty() && part.snippet.is_empty()), &None) {
        (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::Some(format_args!("Span must not be empty and have no suggestion")));
            }
        }
    };
};debug_assert_eq!(
891            parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
892            None,
893            "Span must not be empty and have no suggestion",
894        );
895        if true {
    match (&parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
            &None) {
        (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::Some(format_args!("suggestion must not have overlapping parts")));
            }
        }
    };
};debug_assert_eq!(
896            parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
897            None,
898            "suggestion must not have overlapping parts",
899        );
900
901        self.push_suggestion(CodeSuggestion {
902            substitutions: <[_]>::into_vec(::alloc::boxed::box_new([Substitution { parts }]))vec![Substitution { parts }],
903            msg: msg.into(),
904            style,
905            applicability,
906        });
907        self
908    }
909
910    /// Prints out a message with for a multipart suggestion without showing the suggested code.
911    ///
912    /// This is intended to be used for suggestions that are obvious in what the changes need to
913    /// be from the message, showing the span label inline would be visually unpleasant
914    /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
915    /// improve understandability.
916    pub fn tool_only_multipart_suggestion(
917        &mut self,
918        msg: impl Into<DiagMessage>,
919        suggestion: Vec<(Span, String)>,
920        applicability: Applicability,
921    ) -> &mut Self {
922        self.multipart_suggestion_with_style(
923            msg,
924            suggestion,
925            applicability,
926            SuggestionStyle::CompletelyHidden,
927        )
928    }
929
930    "See [`Diag::span_suggestion()`]."
&mut Self
self
sp
msg
suggestion
applicability
&mut Self
"See [`Diag::span_suggestion()`]."
mut self
sp
msg
suggestion
applicability
Self
self.span_suggestion(sp, msg, suggestion, applicability);
self;with_fn! { with_span_suggestion,
931    /// Prints out a message with a suggested edit of the code.
932    ///
933    /// In case of short messages and a simple suggestion, rustc displays it as a label:
934    ///
935    /// ```text
936    /// try adding parentheses: `(tup.0).1`
937    /// ```
938    ///
939    /// The message
940    ///
941    /// * should not end in any punctuation (a `:` is added automatically)
942    /// * should not be a question (avoid language like "did you mean")
943    /// * should not contain any phrases like "the following", "as shown", etc.
944    /// * may look like "to do xyz, use" or "to do xyz, use abc"
945    /// * may contain a name of a function, variable, or type, but not whole expressions
946    ///
947    /// See [`CodeSuggestion`] for more information.
948    pub fn span_suggestion(
949        &mut self,
950        sp: Span,
951        msg: impl Into<DiagMessage>,
952        suggestion: impl ToString,
953        applicability: Applicability,
954    ) -> &mut Self {
955        self.span_suggestion_with_style(
956            sp,
957            msg,
958            suggestion,
959            applicability,
960            SuggestionStyle::ShowCode,
961        );
962        self
963    } }
964
965    /// [`Diag::span_suggestion()`] but you can set the [`SuggestionStyle`].
966    pub fn span_suggestion_with_style(
967        &mut self,
968        sp: Span,
969        msg: impl Into<DiagMessage>,
970        suggestion: impl ToString,
971        applicability: Applicability,
972        style: SuggestionStyle,
973    ) -> &mut Self {
974        if true {
    if !!(sp.is_empty() && suggestion.to_string().is_empty()) {
        {
            ::core::panicking::panic_fmt(format_args!("Span must not be empty and have no suggestion"));
        }
    };
};debug_assert!(
975            !(sp.is_empty() && suggestion.to_string().is_empty()),
976            "Span must not be empty and have no suggestion"
977        );
978        self.push_suggestion(CodeSuggestion {
979            substitutions: <[_]>::into_vec(::alloc::boxed::box_new([Substitution {
                    parts: <[_]>::into_vec(::alloc::boxed::box_new([SubstitutionPart {
                                        snippet: suggestion.to_string(),
                                        span: sp,
                                    }])),
                }]))vec![Substitution {
980                parts: vec![SubstitutionPart { snippet: suggestion.to_string(), span: sp }],
981            }],
982            msg: msg.into(),
983            style,
984            applicability,
985        });
986        self
987    }
988
989    "See [`Diag::span_suggestion_verbose()`]."
&mut Self
self
sp
msg
suggestion
applicability
&mut Self
"See [`Diag::span_suggestion_verbose()`]."
mut self
sp
msg
suggestion
applicability
Self
self.span_suggestion_verbose(sp, msg, suggestion, applicability);
self;with_fn! { with_span_suggestion_verbose,
990    /// Always show the suggested change.
991    pub fn span_suggestion_verbose(
992        &mut self,
993        sp: Span,
994        msg: impl Into<DiagMessage>,
995        suggestion: impl ToString,
996        applicability: Applicability,
997    ) -> &mut Self {
998        self.span_suggestion_with_style(
999            sp,
1000            msg,
1001            suggestion,
1002            applicability,
1003            SuggestionStyle::ShowAlways,
1004        );
1005        self
1006    } }
1007
1008    "See [`Diag::span_suggestions()`]."
&mut Self
self
sp
msg
suggestions
applicability
&mut Self
"See [`Diag::span_suggestions()`]."
mut self
sp
msg
suggestions
applicability
Self
self.span_suggestions(sp, msg, suggestions, applicability);
self;with_fn! { with_span_suggestions,
1009    /// Prints out a message with multiple suggested edits of the code.
1010    /// See also [`Diag::span_suggestion()`].
1011    pub fn span_suggestions(
1012        &mut self,
1013        sp: Span,
1014        msg: impl Into<DiagMessage>,
1015        suggestions: impl IntoIterator<Item = String>,
1016        applicability: Applicability,
1017    ) -> &mut Self {
1018        self.span_suggestions_with_style(
1019            sp,
1020            msg,
1021            suggestions,
1022            applicability,
1023            SuggestionStyle::ShowCode,
1024        )
1025    } }
1026
1027    pub fn span_suggestions_with_style(
1028        &mut self,
1029        sp: Span,
1030        msg: impl Into<DiagMessage>,
1031        suggestions: impl IntoIterator<Item = String>,
1032        applicability: Applicability,
1033        style: SuggestionStyle,
1034    ) -> &mut Self {
1035        let substitutions = suggestions
1036            .into_iter()
1037            .map(|snippet| {
1038                if true {
    if !!(sp.is_empty() && snippet.is_empty()) {
        {
            ::core::panicking::panic_fmt(format_args!("Span `{0:?}` must not be empty and have no suggestion",
                    sp));
        }
    };
};debug_assert!(
1039                    !(sp.is_empty() && snippet.is_empty()),
1040                    "Span `{sp:?}` must not be empty and have no suggestion"
1041                );
1042                Substitution { parts: <[_]>::into_vec(::alloc::boxed::box_new([SubstitutionPart {
                    snippet,
                    span: sp,
                }]))vec![SubstitutionPart { snippet, span: sp }] }
1043            })
1044            .collect();
1045        self.push_suggestion(CodeSuggestion {
1046            substitutions,
1047            msg: msg.into(),
1048            style,
1049            applicability,
1050        });
1051        self
1052    }
1053
1054    /// Prints out a message with multiple suggested edits of the code, where each edit consists of
1055    /// multiple parts.
1056    /// See also [`Diag::multipart_suggestion()`].
1057    pub fn multipart_suggestions(
1058        &mut self,
1059        msg: impl Into<DiagMessage>,
1060        suggestions: impl IntoIterator<Item = Vec<(Span, String)>>,
1061        applicability: Applicability,
1062    ) -> &mut Self {
1063        let substitutions = suggestions
1064            .into_iter()
1065            .map(|sugg| {
1066                let mut parts = sugg
1067                    .into_iter()
1068                    .map(|(span, snippet)| SubstitutionPart { snippet, span })
1069                    .collect::<Vec<_>>();
1070
1071                parts.sort_unstable_by_key(|part| part.span);
1072
1073                if !!parts.is_empty() {
    ::core::panicking::panic("assertion failed: !parts.is_empty()")
};assert!(!parts.is_empty());
1074                if true {
    match (&parts.iter().find(|part|
                        part.span.is_empty() && part.snippet.is_empty()), &None) {
        (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::Some(format_args!("Span must not be empty and have no suggestion")));
            }
        }
    };
};debug_assert_eq!(
1075                    parts.iter().find(|part| part.span.is_empty() && part.snippet.is_empty()),
1076                    None,
1077                    "Span must not be empty and have no suggestion",
1078                );
1079                if true {
    match (&parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
            &None) {
        (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::Some(format_args!("suggestion must not have overlapping parts")));
            }
        }
    };
};debug_assert_eq!(
1080                    parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
1081                    None,
1082                    "suggestion must not have overlapping parts",
1083                );
1084
1085                Substitution { parts }
1086            })
1087            .collect();
1088
1089        self.push_suggestion(CodeSuggestion {
1090            substitutions,
1091            msg: msg.into(),
1092            style: SuggestionStyle::ShowAlways,
1093            applicability,
1094        });
1095        self
1096    }
1097
1098    "See [`Diag::span_suggestion_short()`]."
&mut Self
self
sp
msg
suggestion
applicability
&mut Self
"See [`Diag::span_suggestion_short()`]."
mut self
sp
msg
suggestion
applicability
Self
self.span_suggestion_short(sp, msg, suggestion, applicability);
self;with_fn! { with_span_suggestion_short,
1099    /// Prints out a message with a suggested edit of the code. If the suggestion is presented
1100    /// inline, it will only show the message and not the suggestion.
1101    ///
1102    /// See [`CodeSuggestion`] for more information.
1103    pub fn span_suggestion_short(
1104        &mut self,
1105        sp: Span,
1106        msg: impl Into<DiagMessage>,
1107        suggestion: impl ToString,
1108        applicability: Applicability,
1109    ) -> &mut Self {
1110        self.span_suggestion_with_style(
1111            sp,
1112            msg,
1113            suggestion,
1114            applicability,
1115            SuggestionStyle::HideCodeInline,
1116        );
1117        self
1118    } }
1119
1120    /// Prints out a message for a suggestion without showing the suggested code.
1121    ///
1122    /// This is intended to be used for suggestions that are obvious in what the changes need to
1123    /// be from the message, showing the span label inline would be visually unpleasant
1124    /// (marginally overlapping spans or multiline spans) and showing the snippet window wouldn't
1125    /// improve understandability.
1126    pub fn span_suggestion_hidden(
1127        &mut self,
1128        sp: Span,
1129        msg: impl Into<DiagMessage>,
1130        suggestion: impl ToString,
1131        applicability: Applicability,
1132    ) -> &mut Self {
1133        self.span_suggestion_with_style(
1134            sp,
1135            msg,
1136            suggestion,
1137            applicability,
1138            SuggestionStyle::HideCodeAlways,
1139        );
1140        self
1141    }
1142
1143    "See [`Diag::tool_only_span_suggestion()`]."
&mut Self
self
sp
msg
suggestion
applicability
&mut Self
"See [`Diag::tool_only_span_suggestion()`]."
mut self
sp
msg
suggestion
applicability
Self
self.tool_only_span_suggestion(sp, msg, suggestion, applicability);
self;with_fn! { with_tool_only_span_suggestion,
1144    /// Adds a suggestion to the JSON output that will not be shown in the CLI.
1145    ///
1146    /// This is intended to be used for suggestions that are *very* obvious in what the changes
1147    /// need to be from the message, but we still want other tools to be able to apply them.
1148    pub fn tool_only_span_suggestion(
1149        &mut self,
1150        sp: Span,
1151        msg: impl Into<DiagMessage>,
1152        suggestion: impl ToString,
1153        applicability: Applicability,
1154    ) -> &mut Self {
1155        self.span_suggestion_with_style(
1156            sp,
1157            msg,
1158            suggestion,
1159            applicability,
1160            SuggestionStyle::CompletelyHidden,
1161        );
1162        self
1163    } }
1164
1165    /// Add a subdiagnostic from a type that implements `Subdiagnostic` (see
1166    /// [rustc_macros::Subdiagnostic]). Performs eager translation of any translatable messages
1167    /// used in the subdiagnostic, so suitable for use with repeated messages (i.e. re-use of
1168    /// interpolated variables).
1169    pub fn subdiagnostic(&mut self, subdiagnostic: impl Subdiagnostic) -> &mut Self {
1170        subdiagnostic.add_to_diag(self);
1171        self
1172    }
1173
1174    /// Fluent variables are not namespaced from each other, so when
1175    /// `Diagnostic`s and `Subdiagnostic`s use the same variable name,
1176    /// one value will clobber the other. Eagerly translating the
1177    /// diagnostic uses the variables defined right then, before the
1178    /// clobbering occurs.
1179    pub fn eagerly_translate(&self, msg: impl Into<DiagMessage>) -> DiagMessage {
1180        let args = self.args.iter();
1181        self.dcx.eagerly_translate(msg.into(), args)
1182    }
1183
1184    "See [`Diag::span()`]."
&mut Self
self
sp
&mut Self
"See [`Diag::span()`]."
mut self
sp
Self
self.span(sp);
self;with_fn! { with_span,
1185    /// Add a span.
1186    pub fn span(&mut self, sp: impl Into<MultiSpan>) -> &mut Self {
1187        self.span = sp.into();
1188        if let Some(span) = self.span.primary_span() {
1189            self.sort_span = span;
1190        }
1191        self
1192    } }
1193
1194    pub fn is_lint(&mut self, name: String, has_future_breakage: bool) -> &mut Self {
1195        self.is_lint = Some(IsLint { name, has_future_breakage });
1196        self
1197    }
1198
1199    "See [`Diag::code()`]."
&mut Self
self
code
&mut Self
"See [`Diag::code()`]."
mut self
code
Self
self.code(code);
self;with_fn! { with_code,
1200    /// Add an error code.
1201    pub fn code(&mut self, code: ErrCode) -> &mut Self {
1202        self.code = Some(code);
1203        self
1204    } }
1205
1206    "See [`Diag::lint_id()`]."
&mut Self
self
id
&mut Self
"See [`Diag::lint_id()`]."
mut self
id
Self
self.lint_id(id);
self;with_fn! { with_lint_id,
1207    /// Add an argument.
1208    pub fn lint_id(
1209        &mut self,
1210        id: LintExpectationId,
1211    ) -> &mut Self {
1212        self.lint_id = Some(id);
1213        self
1214    } }
1215
1216    "See [`Diag::primary_message()`]."
&mut Self
self
msg
&mut Self
"See [`Diag::primary_message()`]."
mut self
msg
Self
self.primary_message(msg);
self;with_fn! { with_primary_message,
1217    /// Add a primary message.
1218    pub fn primary_message(&mut self, msg: impl Into<DiagMessage>) -> &mut Self {
1219        self.messages[0] = (msg.into(), Style::NoStyle);
1220        self
1221    } }
1222
1223    "See [`Diag::arg()`]."
&mut Self
self
name
arg
&mut Self
"See [`Diag::arg()`]."
mut self
name
arg
Self
self.arg(name, arg);
self;with_fn! { with_arg,
1224    /// Add an argument.
1225    pub fn arg(
1226        &mut self,
1227        name: impl Into<DiagArgName>,
1228        arg: impl IntoDiagArg,
1229    ) -> &mut Self {
1230        self.deref_mut().arg(name, arg);
1231        self
1232    } }
1233
1234    /// Convenience function for internal use, clients should use one of the
1235    /// public methods above.
1236    ///
1237    /// Used by `proc_macro_server` for implementing `server::Diagnostic`.
1238    pub fn sub(&mut self, level: Level, message: impl Into<DiagMessage>, span: MultiSpan) {
1239        self.deref_mut().sub(level, message, span);
1240    }
1241
1242    /// Convenience function for internal use, clients should use one of the
1243    /// public methods above.
1244    fn sub_with_highlights(&mut self, level: Level, messages: Vec<StringPart>, span: MultiSpan) {
1245        let messages = messages.into_iter().map(|m| (m.content.into(), m.style)).collect();
1246        let sub = Subdiag { level, messages, span };
1247        self.children.push(sub);
1248    }
1249
1250    /// Takes the diagnostic. For use by methods that consume the Diag: `emit`,
1251    /// `cancel`, etc. Afterwards, `drop` is the only code that will be run on
1252    /// `self`.
1253    fn take_diag(&mut self) -> DiagInner {
1254        if let Some(path) = &self.long_ty_path {
1255            self.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the full name for the type has been written to \'{0}\'",
                path.display()))
    })format!(
1256                "the full name for the type has been written to '{}'",
1257                path.display()
1258            ));
1259            self.note("consider using `--verbose` to print the full type name to the console");
1260        }
1261        *self.diag.take().unwrap()
1262    }
1263
1264    /// This method allows us to access the path of the file where "long types" are written to.
1265    ///
1266    /// When calling `Diag::emit`, as part of that we will check if a `long_ty_path` has been set,
1267    /// and if it has been then we add a note mentioning the file where the "long types" were
1268    /// written to.
1269    ///
1270    /// When calling `tcx.short_string()` after a `Diag` is constructed, the preferred way of doing
1271    /// so is `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that
1272    /// keeps the existence of a "long type" anywhere in the diagnostic, so the note telling the
1273    /// user where we wrote the file to is only printed once at most, *and* it makes it much harder
1274    /// to forget to set it.
1275    ///
1276    /// If the diagnostic hasn't been created before a "short ty string" is created, then you should
1277    /// ensure that this method is called to set it `*diag.long_ty_path() = path`.
1278    ///
1279    /// As a rule of thumb, if you see or add at least one `tcx.short_string()` call anywhere, in a
1280    /// scope, `diag.long_ty_path()` should be called once somewhere close by.
1281    pub fn long_ty_path(&mut self) -> &mut Option<PathBuf> {
1282        &mut self.long_ty_path
1283    }
1284
1285    pub fn with_long_ty_path(mut self, long_ty_path: Option<PathBuf>) -> Self {
1286        self.long_ty_path = long_ty_path;
1287        self
1288    }
1289
1290    /// Most `emit_producing_guarantee` functions use this as a starting point.
1291    fn emit_producing_nothing(mut self) {
1292        let diag = self.take_diag();
1293        self.dcx.emit_diagnostic(diag);
1294    }
1295
1296    /// `ErrorGuaranteed::emit_producing_guarantee` uses this.
1297    fn emit_producing_error_guaranteed(mut self) -> ErrorGuaranteed {
1298        let diag = self.take_diag();
1299
1300        // The only error levels that produce `ErrorGuaranteed` are
1301        // `Error` and `DelayedBug`. But `DelayedBug` should never occur here
1302        // because delayed bugs have their level changed to `Bug` when they are
1303        // actually printed, so they produce an ICE.
1304        //
1305        // (Also, even though `level` isn't `pub`, the whole `DiagInner` could
1306        // be overwritten with a new one thanks to `DerefMut`. So this assert
1307        // protects against that, too.)
1308        if !#[allow(non_exhaustive_omitted_patterns)] match diag.level {
            Level::Error | Level::DelayedBug => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("invalid diagnostic level ({0:?})",
                diag.level));
    }
};assert!(
1309            matches!(diag.level, Level::Error | Level::DelayedBug),
1310            "invalid diagnostic level ({:?})",
1311            diag.level,
1312        );
1313
1314        let guar = self.dcx.emit_diagnostic(diag);
1315        guar.unwrap()
1316    }
1317
1318    /// Emit and consume the diagnostic.
1319    #[track_caller]
1320    pub fn emit(self) -> G::EmitResult {
1321        G::emit_producing_guarantee(self)
1322    }
1323
1324    /// Emit the diagnostic unless `delay` is true,
1325    /// in which case the emission will be delayed as a bug.
1326    ///
1327    /// See `emit` and `delay_as_bug` for details.
1328    #[track_caller]
1329    pub fn emit_unless_delay(mut self, delay: bool) -> G::EmitResult {
1330        if delay {
1331            self.downgrade_to_delayed_bug();
1332        }
1333        self.emit()
1334    }
1335
1336    /// Cancel and consume the diagnostic. (A diagnostic must either be emitted or
1337    /// cancelled or it will panic when dropped).
1338    pub fn cancel(mut self) {
1339        self.diag = None;
1340        drop(self);
1341    }
1342
1343    /// See `DiagCtxt::stash_diagnostic` for details.
1344    pub fn stash(mut self, span: Span, key: StashKey) -> Option<ErrorGuaranteed> {
1345        let diag = self.take_diag();
1346        self.dcx.stash_diagnostic(span, key, diag)
1347    }
1348
1349    /// Delay emission of this diagnostic as a bug.
1350    ///
1351    /// This can be useful in contexts where an error indicates a bug but
1352    /// typically this only happens when other compilation errors have already
1353    /// happened. In those cases this can be used to defer emission of this
1354    /// diagnostic as a bug in the compiler only if no other errors have been
1355    /// emitted.
1356    ///
1357    /// In the meantime, though, callsites are required to deal with the "bug"
1358    /// locally in whichever way makes the most sense.
1359    #[track_caller]
1360    pub fn delay_as_bug(mut self) -> G::EmitResult {
1361        self.downgrade_to_delayed_bug();
1362        self.emit()
1363    }
1364
1365    pub fn remove_arg(&mut self, name: &str) {
1366        if let Some(diag) = self.diag.as_mut() {
1367            diag.remove_arg(name);
1368        }
1369    }
1370}
1371
1372/// Destructor bomb: every `Diag` must be consumed (emitted, cancelled, etc.)
1373/// or we emit a bug.
1374impl<G: EmissionGuarantee> Drop for Diag<'_, G> {
1375    fn drop(&mut self) {
1376        match self.diag.take() {
1377            Some(diag) if !panicking() => {
1378                self.dcx.emit_diagnostic(DiagInner::new(
1379                    Level::Bug,
1380                    DiagMessage::from("the following error was constructed but not emitted"),
1381                ));
1382                self.dcx.emit_diagnostic(*diag);
1383                {
    ::core::panicking::panic_fmt(format_args!("error was constructed but not emitted"));
};panic!("error was constructed but not emitted");
1384            }
1385            _ => {}
1386        }
1387    }
1388}
1389
1390#[macro_export]
1391macro_rules! struct_span_code_err {
1392    ($dcx:expr, $span:expr, $code:expr, $($message:tt)*) => ({
1393        $dcx.struct_span_err($span, format!($($message)*)).with_code($code)
1394    })
1395}