Skip to main content

rustc_errors/
emitter.rs

1//! The current rustc diagnostics emitter.
2//!
3//! An `Emitter` takes care of generating the output from a `Diag` struct.
4//!
5//! There are various `Emitter` implementations that generate different output formats such as
6//! JSON and human readable output.
7//!
8//! The output types are defined in `rustc_session::config::ErrorOutputType`.
9
10use std::borrow::Cow;
11use std::io::prelude::*;
12use std::io::{self, IsTerminal};
13use std::iter;
14use std::path::Path;
15
16use anstream::{AutoStream, ColorChoice};
17use anstyle::{AnsiColor, Effects};
18use rustc_data_structures::fx::FxIndexSet;
19use rustc_data_structures::sync::DynSend;
20use rustc_error_messages::DiagArgMap;
21use rustc_span::hygiene::{ExpnKind, MacroKind};
22use rustc_span::source_map::SourceMap;
23use rustc_span::{FileName, SourceFile, Span};
24use tracing::{debug, warn};
25
26use crate::formatting::format_diag_message;
27use crate::timings::TimingRecord;
28use crate::{
29    CodeSuggestion, DiagInner, DiagMessage, Level, MultiSpan, Style, Subdiag, Sublevel,
30    SuggestionStyle,
31};
32
33/// Describes the way the content of the `rendered` field of the json output is generated
34#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for HumanReadableErrorType {
}
#[automatically_derived]impl ::core::clone::Clone for HumanReadableErrorType {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<bool>;
        *self
    }
}Clone, #[automatically_derived]impl ::core::marker::Copy for HumanReadableErrorType {
}Copy, #[automatically_derived]impl ::core::fmt::Debug for HumanReadableErrorType {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "HumanReadableErrorType no_graphics short unicode",
            &self.no_graphics, &self.short, &&self.unicode)
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    HumanReadableErrorType {
}
#[automatically_derived]impl ::core::cmp::PartialEq for HumanReadableErrorType
    {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.no_graphics == other.no_graphics && self.short == other.short &&
            self.unicode == other.unicode
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for HumanReadableErrorType {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
    }
}Eq)]
35pub struct HumanReadableErrorType {
36    pub no_graphics: bool,
37    pub short: bool,
38    pub unicode: bool,
39}
40
41impl HumanReadableErrorType {
42    pub fn short(&self) -> bool {
43        self.short
44    }
45}
46
47pub enum TimingEvent {
48    Start,
49    End,
50}
51
52pub type DynEmitter = dyn Emitter + DynSend;
53
54/// Emitter trait for emitting errors and other structured information.
55pub trait Emitter {
56    /// Emit a structured diagnostic.
57    fn emit_diagnostic(&mut self, diag: DiagInner);
58
59    /// Emit a notification that an artifact has been output.
60    /// Currently only supported for the JSON format.
61    fn emit_artifact_notification(&mut self, _path: &Path, _artifact_type: &str) {}
62
63    /// Emit a timestamp with start/end of a timing section.
64    /// Currently only supported for the JSON format.
65    fn emit_timing_section(&mut self, _record: TimingRecord, _event: TimingEvent) {}
66
67    /// Emit a report about future breakage.
68    /// Currently only supported for the JSON format.
69    fn emit_future_breakage_report(&mut self, _diags: Vec<DiagInner>) {}
70
71    /// Emit list of unused externs.
72    /// Currently only supported for the JSON format.
73    fn emit_unused_externs(
74        &mut self,
75        _lint_level: rustc_lint_defs::Level,
76        _unused_externs: &[&str],
77    ) {
78    }
79
80    /// Checks if should show explanations about "rustc --explain"
81    fn should_show_explain(&self) -> bool {
82        true
83    }
84
85    /// Checks if we can use colors in the current output stream.
86    fn supports_color(&self) -> bool {
87        false
88    }
89
90    fn source_map(&self) -> Option<&SourceMap>;
91
92    /// Formats the substitutions of the primary_span
93    ///
94    /// There are a lot of conditions to this method, but in short:
95    ///
96    /// * If the current `DiagInner` has only one visible `CodeSuggestion`,
97    ///   we format the `help` suggestion depending on the content of the
98    ///   substitutions. In that case, we modify the span and clear the
99    ///   suggestions.
100    ///
101    /// * If the current `DiagInner` has multiple suggestions,
102    ///   we leave `primary_span` and the suggestions untouched.
103    fn primary_span_formatted(
104        &self,
105        primary_span: &mut MultiSpan,
106        suggestions: &mut Vec<CodeSuggestion>,
107        fluent_args: &DiagArgMap,
108    ) {
109        if let Some((sugg, rest)) = suggestions.split_first() {
110            let msg = format_diag_message(&sugg.msg, fluent_args);
111            if rest.is_empty()
112               // ^ if there is only one suggestion
113               // don't display multi-suggestions as labels
114               && let [substitution] = sugg.substitutions.as_slice()
115               // don't display multipart suggestions as labels
116               && let [part] = substitution.parts.as_slice()
117               // don't display long messages as labels
118               && msg.split_whitespace().count() < 10
119               // don't display multiline suggestions as labels
120               && !part.snippet.contains('\n')
121               && ![
122                    // when this style is set we want the suggestion to be a message, not inline
123                    SuggestionStyle::HideCodeAlways,
124                    // trivial suggestion for tooling's sake, never shown
125                    SuggestionStyle::CompletelyHidden,
126                    // subtle suggestion, never shown inline
127                    SuggestionStyle::ShowAlways,
128               ].contains(&sugg.style)
129            {
130                let snippet = part.snippet.trim();
131                let msg = if snippet.is_empty() || sugg.style.hide_inline() {
132                    // This substitution is only removal OR we explicitly don't want to show the
133                    // code inline (`hide_inline`). Therefore, we don't show the substitution.
134                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("help: {0}", msg))
    })format!("help: {msg}")
135                } else {
136                    // Show the default suggestion text with the substitution
137                    let confusion_type = self
138                        .source_map()
139                        .map(|sm| detect_confusion_type(sm, snippet, part.span))
140                        .unwrap_or(ConfusionType::None);
141                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("help: {0}{1}: `{2}`", msg,
                confusion_type.label_text(), snippet))
    })format!("help: {}{}: `{}`", msg, confusion_type.label_text(), snippet,)
142                };
143                primary_span.push_span_label(part.span, msg);
144
145                // We return only the modified primary_span
146                suggestions.clear();
147            } else {
148                // if there are multiple suggestions, print them all in full
149                // to be consistent. We could try to figure out if we can
150                // make one (or the first one) inline, but that would give
151                // undue importance to a semi-random suggestion
152            }
153        } else {
154            // do nothing
155        }
156    }
157
158    fn fix_multispans_in_extern_macros_and_render_macro_backtrace(
159        &self,
160        span: &mut MultiSpan,
161        children: &mut Vec<Subdiag>,
162        level: &Level,
163        backtrace: bool,
164    ) {
165        // Check for spans in macros, before `fix_multispans_in_extern_macros`
166        // has a chance to replace them.
167        let has_macro_spans: Vec<_> = iter::once(&*span)
168            .chain(children.iter().map(|child| &child.span))
169            .flat_map(|span| span.primary_spans())
170            .flat_map(|sp| sp.macro_backtrace().map(move |expn_data| (sp, expn_data)))
171            .filter_map(|(sp, expn_data)| {
172                match expn_data.kind {
173                    ExpnKind::Root => None,
174
175                    // Skip past non-macro entries, just in case there
176                    // are some which do actually involve macros.
177                    ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None,
178
179                    ExpnKind::Macro(macro_kind, name) => {
180                        let same_line = sp
181                            .overlaps(expn_data.def_site)
182                            .then(|| expn_data.def_site.with_hi(sp.lo()));
183                        Some((
184                            macro_kind,
185                            name,
186                            expn_data.diagnostic_opaque,
187                            expn_data.def_site,
188                            same_line,
189                        ))
190                    }
191                }
192            })
193            .collect();
194
195        if !backtrace {
196            self.fix_multispans_in_extern_macros(span, children);
197        }
198
199        self.render_multispans_macro_backtrace(span, children, backtrace);
200
201        if !backtrace
202            // Skip macros annotated with `#[diagnostic::opaque]`. Builtin macros are "opaque" too.
203            && let Some((macro_kind, name, _, sp, same_line_span)) = has_macro_spans.first()
204            && let Some((_, _, false, _, _)) = has_macro_spans.last()
205        {
206            // Mark the actual macro this originates from
207            let and_then = if let Some((macro_kind, last_name, _, _, _)) = has_macro_spans.last()
208                && last_name != name
209            {
210                let descr = macro_kind.descr();
211                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" which comes from the expansion of the {0} `{1}`",
                descr, last_name))
    })format!(" which comes from the expansion of the {descr} `{last_name}`")
212            } else {
213                "".to_string()
214            };
215
216            let descr = macro_kind.descr();
217            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this {0} originates in the {1} `{2}`{3}",
                level, descr, name, and_then))
    })format!("this {level} originates in the {descr} `{name}`{and_then}");
218
219            if let Some(source_map) = self.source_map() {
220                if source_map.is_imported(*sp) || same_line_span.is_none() {
221                    let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} (in Nightly builds, run with -Z macro-backtrace for more info)",
                msg))
    })format!(
222                        "{msg} (in Nightly builds, run with -Z macro-backtrace for more info)"
223                    );
224                    children.push(Subdiag {
225                        level: Sublevel::Note,
226                        messages: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(DiagMessage::from(msg), Style::NoStyle)]))vec![(DiagMessage::from(msg), Style::NoStyle)],
227                        span: MultiSpan::new(),
228                    });
229                } else if let Some(def) = same_line_span
230                    && source_map.is_multiline(*def)
231                    && !and_then.is_empty()
232                {
233                    // We only point at the macro definition when it is not on the same line as the
234                    // error produced and there are more levels of macro nesting.
235                    span.push_span_label(*sp, msg);
236                } else {
237                    // We point at the macro def line, but without an underline or message, we
238                    // leave it implied.
239                    span.push_span_context(sp.shrink_to_lo());
240                }
241            } else {
242                children.push(Subdiag {
243                    level: Sublevel::Note,
244                    messages: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(DiagMessage::from(msg), Style::NoStyle)]))vec![(DiagMessage::from(msg), Style::NoStyle)],
245                    span: MultiSpan::new(),
246                });
247            }
248        }
249    }
250
251    fn render_multispans_macro_backtrace(
252        &self,
253        span: &mut MultiSpan,
254        children: &mut Vec<Subdiag>,
255        backtrace: bool,
256    ) {
257        for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) {
258            self.render_multispan_macro_backtrace(span, backtrace);
259        }
260    }
261
262    fn render_multispan_macro_backtrace(&self, span: &mut MultiSpan, always_backtrace: bool) {
263        let mut new_labels = FxIndexSet::default();
264
265        for &sp in span.primary_spans() {
266            if sp.is_dummy() {
267                continue;
268            }
269
270            // FIXME(eddyb) use `retain` on `macro_backtrace` to remove all the
271            // entries we don't want to print, to make sure the indices being
272            // printed are contiguous (or omitted if there's only one entry).
273            let macro_backtrace: Vec<_> = sp.macro_backtrace().collect();
274            for (i, trace) in macro_backtrace.iter().rev().enumerate() {
275                if trace.def_site.is_dummy() {
276                    continue;
277                }
278
279                if always_backtrace {
280                    new_labels.insert((
281                        trace.def_site,
282                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in this expansion of `{0}`{1}",
                trace.kind.descr(),
                if macro_backtrace.len() > 1 {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" (#{0})", i + 1))
                        })
                } else { String::new() }))
    })format!(
283                            "in this expansion of `{}`{}",
284                            trace.kind.descr(),
285                            if macro_backtrace.len() > 1 {
286                                // if macro_backtrace.len() == 1 it'll be
287                                // pointed at by "in this macro invocation"
288                                format!(" (#{})", i + 1)
289                            } else {
290                                String::new()
291                            },
292                        ),
293                    ));
294                }
295
296                // Don't add a label on the call site if the diagnostic itself
297                // already points to (a part of) that call site, as the label
298                // is meant for showing the relevant invocation when the actual
299                // diagnostic is pointing to some part of macro definition.
300                //
301                // This also handles the case where an external span got replaced
302                // with the call site span by `fix_multispans_in_extern_macros`.
303                //
304                // NB: `-Zmacro-backtrace` overrides this, for uniformity, as the
305                // "in this expansion of" label above is always added in that mode,
306                // and it needs an "in this macro invocation" label to match that.
307                let redundant_span = trace.call_site.contains(sp);
308
309                if !redundant_span || always_backtrace {
310                    let msg: Cow<'static, _> = match trace.kind {
311                        ExpnKind::Macro(MacroKind::Attr, _) => {
312                            "this attribute macro expansion".into()
313                        }
314                        ExpnKind::Macro(MacroKind::Derive, _) => {
315                            "this derive macro expansion".into()
316                        }
317                        ExpnKind::Macro(MacroKind::Bang, _) => "this macro invocation".into(),
318                        ExpnKind::Root => "the crate root".into(),
319                        ExpnKind::AstPass(kind) => kind.descr().into(),
320                        ExpnKind::Desugaring(kind) => {
321                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this {0} desugaring",
                kind.descr()))
    })format!("this {} desugaring", kind.descr()).into()
322                        }
323                    };
324                    new_labels.insert((
325                        trace.call_site,
326                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("in {0}{1}", msg,
                if macro_backtrace.len() > 1 && always_backtrace {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(" (#{0})", i + 1))
                        })
                } else { String::new() }))
    })format!(
327                            "in {}{}",
328                            msg,
329                            if macro_backtrace.len() > 1 && always_backtrace {
330                                // only specify order when the macro
331                                // backtrace is multiple levels deep
332                                format!(" (#{})", i + 1)
333                            } else {
334                                String::new()
335                            },
336                        ),
337                    ));
338                }
339                if !always_backtrace {
340                    break;
341                }
342            }
343        }
344
345        for (label_span, label_text) in new_labels {
346            span.push_span_label(label_span, label_text);
347        }
348    }
349
350    // This does a small "fix" for multispans by looking to see if it can find any that
351    // point directly at external macros. Since these are often difficult to read,
352    // this will change the span to point at the use site.
353    fn fix_multispans_in_extern_macros(&self, span: &mut MultiSpan, children: &mut Vec<Subdiag>) {
354        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_errors/src/emitter.rs:354",
                        "rustc_errors::emitter", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_errors/src/emitter.rs"),
                        ::tracing_core::__macro_support::Option::Some(354u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_errors::emitter"),
                        ::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!("fix_multispans_in_extern_macros: before: span={0:?} children={1:?}",
                                                    span, children) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children);
355        self.fix_multispan_in_extern_macros(span);
356        for child in children.iter_mut() {
357            self.fix_multispan_in_extern_macros(&mut child.span);
358        }
359        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_errors/src/emitter.rs:359",
                        "rustc_errors::emitter", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_errors/src/emitter.rs"),
                        ::tracing_core::__macro_support::Option::Some(359u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_errors::emitter"),
                        ::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!("fix_multispans_in_extern_macros: after: span={0:?} children={1:?}",
                                                    span, children) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("fix_multispans_in_extern_macros: after: span={:?} children={:?}", span, children);
360    }
361
362    // This "fixes" MultiSpans that contain `Span`s pointing to locations inside of external macros.
363    // Since these locations are often difficult to read,
364    // we move these spans from the external macros to their corresponding use site.
365    fn fix_multispan_in_extern_macros(&self, span: &mut MultiSpan) {
366        let Some(source_map) = self.source_map() else { return };
367        let should_hide = |span| {
368            source_map.is_imported(span) || {
369                let expn = span.ctxt().outer_expn_data();
370                expn.diagnostic_opaque && #[allow(non_exhaustive_omitted_patterns)] match expn.kind {
    ExpnKind::Macro(MacroKind::Bang, _) => true,
    _ => false,
}matches!(expn.kind, ExpnKind::Macro(MacroKind::Bang, _))
371            }
372        };
373
374        // First, find all the spans in external macros and point instead at their use site.
375        let replacements: Vec<(Span, Span)> = span
376            .primary_spans()
377            .iter()
378            .copied()
379            .chain(span.span_labels().iter().map(|sp_label| sp_label.span))
380            .filter_map(|sp| {
381                if !sp.is_dummy() && should_hide(sp) {
382                    let mut span = sp;
383                    while let Some(callsite) = span.parent_callsite() {
384                        span = callsite;
385                        if !should_hide(span) {
386                            return Some((sp, span));
387                        }
388                    }
389                }
390                None
391            })
392            .collect();
393
394        // After we have them, make sure we replace these 'bad' def sites with their use sites.
395        for (from, to) in replacements {
396            span.replace(from, to);
397        }
398    }
399}
400
401/// An emitter that adds a note to each diagnostic.
402pub struct EmitterWithNote {
403    pub emitter: Box<dyn Emitter + DynSend>,
404    pub note: String,
405}
406
407impl Emitter for EmitterWithNote {
408    fn source_map(&self) -> Option<&SourceMap> {
409        None
410    }
411
412    fn emit_diagnostic(&mut self, mut diag: DiagInner) {
413        diag.sub(Sublevel::Note, self.note.clone(), MultiSpan::new());
414        self.emitter.emit_diagnostic(diag);
415    }
416}
417
418pub struct SilentEmitter;
419
420impl Emitter for SilentEmitter {
421    fn source_map(&self) -> Option<&SourceMap> {
422        None
423    }
424
425    fn emit_diagnostic(&mut self, _diag: DiagInner) {}
426}
427
428/// Maximum number of suggestions to be shown
429///
430/// Arbitrary, but taken from trait import suggestion limit
431pub const MAX_SUGGESTIONS: usize = 4;
432
433#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ColorConfig {
}
#[automatically_derived]impl ::core::clone::Clone for ColorConfig {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ColorConfig { }Copy, #[automatically_derived]impl ::core::fmt::Debug for ColorConfig {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ColorConfig::Auto => "Auto",
                ColorConfig::Always => "Always",
                ColorConfig::Never => "Never",
            })
    }
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ColorConfig {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ColorConfig {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ColorConfig { }Eq)]
434pub enum ColorConfig {
435    Auto,
436    Always,
437    Never,
438}
439
440impl ColorConfig {
441    pub fn to_color_choice(self) -> ColorChoice {
442        match self {
443            ColorConfig::Always => {
444                if io::stderr().is_terminal() {
445                    ColorChoice::Always
446                } else {
447                    ColorChoice::AlwaysAnsi
448                }
449            }
450            ColorConfig::Never => ColorChoice::Never,
451            ColorConfig::Auto if io::stderr().is_terminal() => ColorChoice::Auto,
452            ColorConfig::Auto => ColorChoice::Never,
453        }
454    }
455}
456
457#[derive(#[automatically_derived]impl ::core::fmt::Debug for OutputTheme {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                OutputTheme::Ascii => "Ascii",
                OutputTheme::Unicode => "Unicode",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for OutputTheme {
}
#[automatically_derived]impl ::core::clone::Clone for OutputTheme {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for OutputTheme { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    OutputTheme {
}
#[automatically_derived]impl ::core::cmp::PartialEq for OutputTheme {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for OutputTheme { }Eq)]
458pub enum OutputTheme {
459    Ascii,
460    Unicode,
461}
462
463// We replace some characters so the CLI output is always consistent and underlines aligned.
464// Keep the following list in sync with `rustc_span::char_width`.
465const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[
466    // In terminals without Unicode support the following will be garbled, but in *all* terminals
467    // the underlying codepoint will be as well. We could gate this replacement behind a "unicode
468    // support" gate.
469    ('\0', "␀"),
470    ('\u{0001}', "␁"),
471    ('\u{0002}', "␂"),
472    ('\u{0003}', "␃"),
473    ('\u{0004}', "␄"),
474    ('\u{0005}', "␅"),
475    ('\u{0006}', "␆"),
476    ('\u{0007}', "␇"),
477    ('\u{0008}', "␈"),
478    ('\t', "    "), // We do our own tab replacement
479    ('\u{000b}', "␋"),
480    ('\u{000c}', "␌"),
481    ('\u{000d}', "␍"),
482    ('\u{000e}', "␎"),
483    ('\u{000f}', "␏"),
484    ('\u{0010}', "␐"),
485    ('\u{0011}', "␑"),
486    ('\u{0012}', "␒"),
487    ('\u{0013}', "␓"),
488    ('\u{0014}', "␔"),
489    ('\u{0015}', "␕"),
490    ('\u{0016}', "␖"),
491    ('\u{0017}', "␗"),
492    ('\u{0018}', "␘"),
493    ('\u{0019}', "␙"),
494    ('\u{001a}', "␚"),
495    ('\u{001b}', "␛"),
496    ('\u{001c}', "␜"),
497    ('\u{001d}', "␝"),
498    ('\u{001e}', "␞"),
499    ('\u{001f}', "␟"),
500    ('\u{007f}', "␡"),
501    ('\u{200d}', ""), // Replace ZWJ for consistent terminal output of grapheme clusters.
502    ('\u{202a}', "�"), // The following unicode text flow control characters are inconsistently
503    ('\u{202b}', "�"), // supported across CLIs and can cause confusion due to the bytes on disk
504    ('\u{202c}', "�"), // not corresponding to the visible source code, so we replace them always.
505    ('\u{202d}', "�"),
506    ('\u{202e}', "�"),
507    ('\u{2066}', "�"),
508    ('\u{2067}', "�"),
509    ('\u{2068}', "�"),
510    ('\u{2069}', "�"),
511];
512
513pub(crate) fn normalize_whitespace(s: &str) -> String {
514    const {
515        let mut i = 1;
516        while i < OUTPUT_REPLACEMENTS.len() {
517            if !(OUTPUT_REPLACEMENTS[i - 1].0 < OUTPUT_REPLACEMENTS[i].0) {
    {
        ::core::panicking::panic_fmt(format_args!("The OUTPUT_REPLACEMENTS array must be sorted (for binary search to work) and must contain no duplicate entries"));
    }
};assert!(
518                OUTPUT_REPLACEMENTS[i - 1].0 < OUTPUT_REPLACEMENTS[i].0,
519                "The OUTPUT_REPLACEMENTS array must be sorted (for binary search to work) \
520                and must contain no duplicate entries"
521            );
522            i += 1;
523        }
524    }
525    // Scan the input string for a character in the ordered table above.
526    // If it's present, replace it with its alternative string (it can be more than 1 char!).
527    // Otherwise, retain the input char.
528    s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
529        match OUTPUT_REPLACEMENTS.binary_search_by_key(&c, |(k, _)| *k) {
530            Ok(i) => s.push_str(OUTPUT_REPLACEMENTS[i].1),
531            _ => s.push(c),
532        }
533        s
534    })
535}
536
537pub type Destination = AutoStream<Box<dyn Write + Send>>;
538
539struct Buffy {
540    buffer_writer: std::io::Stderr,
541    buffer: Vec<u8>,
542}
543
544impl Write for Buffy {
545    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
546        self.buffer.write(buf)
547    }
548
549    fn flush(&mut self) -> io::Result<()> {
550        self.buffer_writer.write_all(&self.buffer)?;
551        self.buffer.clear();
552        Ok(())
553    }
554}
555
556impl Drop for Buffy {
557    fn drop(&mut self) {
558        if !self.buffer.is_empty() {
559            self.flush().unwrap();
560            {
    ::core::panicking::panic_fmt(format_args!("buffers need to be flushed in order to print their contents"));
};panic!("buffers need to be flushed in order to print their contents");
561        }
562    }
563}
564
565pub fn stderr_destination(color: ColorConfig) -> Destination {
566    let buffer_writer = std::io::stderr();
567    // We need to resolve `ColorChoice::Auto` before `Box`ing since
568    // `ColorChoice::Auto` on `dyn Write` will always resolve to `Never`
569    let choice = get_stderr_color_choice(color, &buffer_writer);
570    // On Windows we'll be performing global synchronization on the entire
571    // system for emitting rustc errors, so there's no need to buffer
572    // anything.
573    //
574    // On non-Windows we rely on the atomicity of `write` to ensure errors
575    // don't get all jumbled up.
576    if falsecfg!(windows) {
577        AutoStream::new(Box::new(buffer_writer), choice)
578    } else {
579        let buffer = Vec::new();
580        AutoStream::new(Box::new(Buffy { buffer_writer, buffer }), choice)
581    }
582}
583
584pub fn get_stderr_color_choice(color: ColorConfig, stderr: &std::io::Stderr) -> ColorChoice {
585    let choice = color.to_color_choice();
586    if #[allow(non_exhaustive_omitted_patterns)] match choice {
    ColorChoice::Auto => true,
    _ => false,
}matches!(choice, ColorChoice::Auto) { AutoStream::choice(stderr) } else { choice }
587}
588
589impl Style {
590    pub(crate) fn anstyle(&self) -> anstyle::Style {
591        match self {
592            Style::NoStyle => anstyle::Style::new(),
593            Style::Highlight => AnsiColor::BrightCyan.on_default().effects(Effects::BOLD),
594        }
595    }
596}
597
598/// Whether the original and suggested code are the same.
599pub fn is_different(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
600    let found = match sm.span_to_snippet(sp) {
601        Ok(snippet) => snippet,
602        Err(e) => {
603            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_errors/src/emitter.rs:603",
                        "rustc_errors::emitter", ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_errors/src/emitter.rs"),
                        ::tracing_core::__macro_support::Option::Some(603u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_errors::emitter"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("error")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("error");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::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!("Invalid span {0:?}",
                                                    sp) as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&e)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};warn!(error = ?e, "Invalid span {:?}", sp);
604            return true;
605        }
606    };
607    found != suggested
608}
609
610/// Whether the original and suggested code are visually similar enough to warrant extra wording.
611pub fn detect_confusion_type(sm: &SourceMap, suggested: &str, sp: Span) -> ConfusionType {
612    let found = match sm.span_to_snippet(sp) {
613        Ok(snippet) => snippet,
614        Err(e) => {
615            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_errors/src/emitter.rs:615",
                        "rustc_errors::emitter", ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/137d1d49458b73b7b85d2c1599d8730886d65e47/compiler/rustc_errors/src/emitter.rs"),
                        ::tracing_core::__macro_support::Option::Some(615u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_errors::emitter"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("error")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("error");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::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!("Invalid span {0:?}",
                                                    sp) as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&e)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};warn!(error = ?e, "Invalid span {:?}", sp);
616            return ConfusionType::None;
617        }
618    };
619
620    let mut has_case_confusion = false;
621    let mut has_digit_letter_confusion = false;
622
623    if found.len() == suggested.len() {
624        let mut has_case_diff = false;
625        let mut has_digit_letter_confusable = false;
626        let mut has_other_diff = false;
627
628        // Letters whose lowercase version is very similar to the uppercase
629        // version.
630        let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
631
632        let digit_letter_confusables = [('0', 'O'), ('1', 'l'), ('5', 'S'), ('8', 'B'), ('9', 'g')];
633
634        for (f, s) in iter::zip(found.chars(), suggested.chars()) {
635            if f != s {
636                if f.eq_ignore_ascii_case(&s) {
637                    // Check for case differences (any character that differs only in case)
638                    if ascii_confusables.contains(&f) || ascii_confusables.contains(&s) {
639                        has_case_diff = true;
640                    } else {
641                        has_other_diff = true;
642                    }
643                } else if digit_letter_confusables.contains(&(f, s))
644                    || digit_letter_confusables.contains(&(s, f))
645                {
646                    // Check for digit-letter confusables (like 0 vs O, 1 vs l, etc.)
647                    has_digit_letter_confusable = true;
648                } else {
649                    has_other_diff = true;
650                }
651            }
652        }
653
654        // If we have case differences and no other differences
655        if has_case_diff && !has_other_diff && found != suggested {
656            has_case_confusion = true;
657        }
658        if has_digit_letter_confusable && !has_other_diff && found != suggested {
659            has_digit_letter_confusion = true;
660        }
661    }
662
663    match (has_case_confusion, has_digit_letter_confusion) {
664        (true, true) => ConfusionType::Both,
665        (true, false) => ConfusionType::Case,
666        (false, true) => ConfusionType::DigitLetter,
667        (false, false) => ConfusionType::None,
668    }
669}
670
671/// Represents the type of confusion detected between original and suggested code.
672#[derive(#[automatically_derived]impl ::core::fmt::Debug for ConfusionType {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ConfusionType::None => "None",
                ConfusionType::Case => "Case",
                ConfusionType::DigitLetter => "DigitLetter",
                ConfusionType::Both => "Both",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ConfusionType {
}
#[automatically_derived]impl ::core::clone::Clone for ConfusionType {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ConfusionType { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    ConfusionType {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ConfusionType {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ConfusionType { }Eq)]
673pub enum ConfusionType {
674    /// No confusion detected
675    None,
676    /// Only case differences (e.g., "hello" vs "Hello")
677    Case,
678    /// Only digit-letter confusion (e.g., "0" vs "O", "1" vs "l")
679    DigitLetter,
680    /// Both case and digit-letter confusion
681    Both,
682}
683
684impl ConfusionType {
685    /// Returns the appropriate label text for this confusion type.
686    pub fn label_text(&self) -> &'static str {
687        match self {
688            ConfusionType::None => "",
689            ConfusionType::Case => " (notice the capitalization)",
690            ConfusionType::DigitLetter => " (notice the digit/letter confusion)",
691            ConfusionType::Both => " (notice the capitalization and digit/letter confusion)",
692        }
693    }
694
695    /// Combines two confusion types. If either is `Both`, the result is `Both`.
696    /// If one is `Case` and the other is `DigitLetter`, the result is `Both`.
697    /// Otherwise, returns the non-`None` type, or `None` if both are `None`.
698    pub fn combine(self, other: ConfusionType) -> ConfusionType {
699        match (self, other) {
700            (ConfusionType::None, other) => other,
701            (this, ConfusionType::None) => this,
702            (ConfusionType::Both, _) | (_, ConfusionType::Both) => ConfusionType::Both,
703            (ConfusionType::Case, ConfusionType::DigitLetter)
704            | (ConfusionType::DigitLetter, ConfusionType::Case) => ConfusionType::Both,
705            (ConfusionType::Case, ConfusionType::Case) => ConfusionType::Case,
706            (ConfusionType::DigitLetter, ConfusionType::DigitLetter) => ConfusionType::DigitLetter,
707        }
708    }
709
710    /// Returns true if this confusion type represents any kind of confusion.
711    pub fn has_confusion(&self) -> bool {
712        *self != ConfusionType::None
713    }
714}
715
716pub(crate) fn should_show_source_code(
717    ignored_directories: &[String],
718    sm: &SourceMap,
719    file: &SourceFile,
720) -> bool {
721    if !sm.ensure_source_file_source_present(file) {
722        return false;
723    }
724
725    let FileName::Real(name) = &file.name else { return true };
726    name.local_path()
727        .map(|path| ignored_directories.iter().all(|dir| !path.starts_with(dir)))
728        .unwrap_or(true)
729}