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