Skip to main content

rustc_errors/
diagnostic.rs

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