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