1use 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::timings::TimingRecord;
27use crate::translation::format_diag_message;
28use crate::{
29 CodeSuggestion, DiagInner, DiagMessage, Level, MultiSpan, Style, Subdiag, SuggestionStyle,
30};
31
32#[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_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq)]
34pub struct HumanReadableErrorType {
35 pub short: bool,
36 pub unicode: bool,
37}
38
39impl HumanReadableErrorType {
40 pub fn short(&self) -> bool {
41 self.short
42 }
43}
44
45pub enum TimingEvent {
46 Start,
47 End,
48}
49
50pub type DynEmitter = dyn Emitter + DynSend;
51
52pub trait Emitter {
54 fn emit_diagnostic(&mut self, diag: DiagInner);
56
57 fn emit_artifact_notification(&mut self, _path: &Path, _artifact_type: &str) {}
60
61 fn emit_timing_section(&mut self, _record: TimingRecord, _event: TimingEvent) {}
64
65 fn emit_future_breakage_report(&mut self, _diags: Vec<DiagInner>) {}
68
69 fn emit_unused_externs(
72 &mut self,
73 _lint_level: rustc_lint_defs::Level,
74 _unused_externs: &[&str],
75 ) {
76 }
77
78 fn should_show_explain(&self) -> bool {
80 true
81 }
82
83 fn supports_color(&self) -> bool {
85 false
86 }
87
88 fn source_map(&self) -> Option<&SourceMap>;
89
90 fn primary_span_formatted(
102 &self,
103 primary_span: &mut MultiSpan,
104 suggestions: &mut Vec<CodeSuggestion>,
105 fluent_args: &DiagArgMap,
106 ) {
107 if let Some((sugg, rest)) = suggestions.split_first() {
108 let msg = format_diag_message(&sugg.msg, fluent_args);
109 if rest.is_empty()
110 && let [substitution] = sugg.substitutions.as_slice()
113 && let [part] = substitution.parts.as_slice()
115 && msg.split_whitespace().count() < 10
117 && !part.snippet.contains('\n')
119 && ![
120 SuggestionStyle::HideCodeAlways,
122 SuggestionStyle::CompletelyHidden,
124 SuggestionStyle::ShowAlways,
126 ].contains(&sugg.style)
127 {
128 let snippet = part.snippet.trim();
129 let msg = if snippet.is_empty() || sugg.style.hide_inline() {
130 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("help: {0}", msg))
})format!("help: {msg}")
133 } else {
134 let confusion_type = self
136 .source_map()
137 .map(|sm| detect_confusion_type(sm, snippet, part.span))
138 .unwrap_or(ConfusionType::None);
139 ::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,)
140 };
141 primary_span.push_span_label(part.span, msg);
142
143 suggestions.clear();
145 } else {
146 }
151 } else {
152 }
154 }
155
156 fn fix_multispans_in_extern_macros_and_render_macro_backtrace(
157 &self,
158 span: &mut MultiSpan,
159 children: &mut Vec<Subdiag>,
160 level: &Level,
161 backtrace: bool,
162 ) {
163 let has_macro_spans: Vec<_> = iter::once(&*span)
166 .chain(children.iter().map(|child| &child.span))
167 .flat_map(|span| span.primary_spans())
168 .flat_map(|sp| sp.macro_backtrace())
169 .filter_map(|expn_data| {
170 match expn_data.kind {
171 ExpnKind::Root => None,
172
173 ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None,
176
177 ExpnKind::Macro(macro_kind, name) => {
178 Some((macro_kind, name, expn_data.hide_backtrace))
179 }
180 }
181 })
182 .collect();
183
184 if !backtrace {
185 self.fix_multispans_in_extern_macros(span, children);
186 }
187
188 self.render_multispans_macro_backtrace(span, children, backtrace);
189
190 if !backtrace {
191 if let Some((macro_kind, name, _)) = has_macro_spans.first()
194 && let Some((_, _, false)) = has_macro_spans.last()
195 {
196 let and_then = if let Some((macro_kind, last_name, _)) = has_macro_spans.last()
198 && last_name != name
199 {
200 let descr = macro_kind.descr();
201 ::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}`")
202 } else {
203 "".to_string()
204 };
205
206 let descr = macro_kind.descr();
207 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!(
208 "this {level} originates in the {descr} `{name}`{and_then} \
209 (in Nightly builds, run with -Z macro-backtrace for more info)",
210 );
211
212 children.push(Subdiag {
213 level: Level::Note,
214 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)],
215 span: MultiSpan::new(),
216 });
217 }
218 }
219 }
220
221 fn render_multispans_macro_backtrace(
222 &self,
223 span: &mut MultiSpan,
224 children: &mut Vec<Subdiag>,
225 backtrace: bool,
226 ) {
227 for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) {
228 self.render_multispan_macro_backtrace(span, backtrace);
229 }
230 }
231
232 fn render_multispan_macro_backtrace(&self, span: &mut MultiSpan, always_backtrace: bool) {
233 let mut new_labels = FxIndexSet::default();
234
235 for &sp in span.primary_spans() {
236 if sp.is_dummy() {
237 continue;
238 }
239
240 let macro_backtrace: Vec<_> = sp.macro_backtrace().collect();
244 for (i, trace) in macro_backtrace.iter().rev().enumerate() {
245 if trace.def_site.is_dummy() {
246 continue;
247 }
248
249 if always_backtrace {
250 new_labels.insert((
251 trace.def_site,
252 ::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!(
253 "in this expansion of `{}`{}",
254 trace.kind.descr(),
255 if macro_backtrace.len() > 1 {
256 format!(" (#{})", i + 1)
259 } else {
260 String::new()
261 },
262 ),
263 ));
264 }
265
266 let redundant_span = trace.call_site.contains(sp);
278
279 if !redundant_span || always_backtrace {
280 let msg: Cow<'static, _> = match trace.kind {
281 ExpnKind::Macro(MacroKind::Attr, _) => {
282 "this attribute macro expansion".into()
283 }
284 ExpnKind::Macro(MacroKind::Derive, _) => {
285 "this derive macro expansion".into()
286 }
287 ExpnKind::Macro(MacroKind::Bang, _) => "this macro invocation".into(),
288 ExpnKind::Root => "the crate root".into(),
289 ExpnKind::AstPass(kind) => kind.descr().into(),
290 ExpnKind::Desugaring(kind) => {
291 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this {0} desugaring",
kind.descr()))
})format!("this {} desugaring", kind.descr()).into()
292 }
293 };
294 new_labels.insert((
295 trace.call_site,
296 ::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!(
297 "in {}{}",
298 msg,
299 if macro_backtrace.len() > 1 && always_backtrace {
300 format!(" (#{})", i + 1)
303 } else {
304 String::new()
305 },
306 ),
307 ));
308 }
309 if !always_backtrace {
310 break;
311 }
312 }
313 }
314
315 for (label_span, label_text) in new_labels {
316 span.push_span_label(label_span, label_text);
317 }
318 }
319
320 fn fix_multispans_in_extern_macros(&self, span: &mut MultiSpan, children: &mut Vec<Subdiag>) {
324 {
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:324",
"rustc_errors::emitter", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_errors/src/emitter.rs"),
::tracing_core::__macro_support::Option::Some(324u32),
::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);
325 self.fix_multispan_in_extern_macros(span);
326 for child in children.iter_mut() {
327 self.fix_multispan_in_extern_macros(&mut child.span);
328 }
329 {
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:329",
"rustc_errors::emitter", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_errors/src/emitter.rs"),
::tracing_core::__macro_support::Option::Some(329u32),
::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);
330 }
331
332 fn fix_multispan_in_extern_macros(&self, span: &mut MultiSpan) {
336 let Some(source_map) = self.source_map() else { return };
337 let replacements: Vec<(Span, Span)> = span
339 .primary_spans()
340 .iter()
341 .copied()
342 .chain(span.span_labels().iter().map(|sp_label| sp_label.span))
343 .filter_map(|sp| {
344 if !sp.is_dummy() && source_map.is_imported(sp) {
345 let mut span = sp;
346 while let Some(callsite) = span.parent_callsite() {
347 span = callsite;
348 if !source_map.is_imported(span) {
349 return Some((sp, span));
350 }
351 }
352 }
353 None
354 })
355 .collect();
356
357 for (from, to) in replacements {
359 span.replace(from, to);
360 }
361 }
362}
363
364pub struct EmitterWithNote {
366 pub emitter: Box<dyn Emitter + DynSend>,
367 pub note: String,
368}
369
370impl Emitter for EmitterWithNote {
371 fn source_map(&self) -> Option<&SourceMap> {
372 None
373 }
374
375 fn emit_diagnostic(&mut self, mut diag: DiagInner) {
376 diag.sub(Level::Note, self.note.clone(), MultiSpan::new());
377 self.emitter.emit_diagnostic(diag);
378 }
379}
380
381pub struct SilentEmitter;
382
383impl Emitter for SilentEmitter {
384 fn source_map(&self) -> Option<&SourceMap> {
385 None
386 }
387
388 fn emit_diagnostic(&mut self, _diag: DiagInner) {}
389}
390
391pub const MAX_SUGGESTIONS: usize = 4;
395
396#[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_fields_are_eq(&self) {}
}Eq)]
397pub enum ColorConfig {
398 Auto,
399 Always,
400 Never,
401}
402
403impl ColorConfig {
404 pub fn to_color_choice(self) -> ColorChoice {
405 match self {
406 ColorConfig::Always => {
407 if io::stderr().is_terminal() {
408 ColorChoice::Always
409 } else {
410 ColorChoice::AlwaysAnsi
411 }
412 }
413 ColorConfig::Never => ColorChoice::Never,
414 ColorConfig::Auto if io::stderr().is_terminal() => ColorChoice::Auto,
415 ColorConfig::Auto => ColorChoice::Never,
416 }
417 }
418}
419
420#[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_fields_are_eq(&self) {}
}Eq)]
421pub enum OutputTheme {
422 Ascii,
423 Unicode,
424}
425
426const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[
429 ('\0', "␀"),
433 ('\u{0001}', "␁"),
434 ('\u{0002}', "␂"),
435 ('\u{0003}', "␃"),
436 ('\u{0004}', "␄"),
437 ('\u{0005}', "␅"),
438 ('\u{0006}', "␆"),
439 ('\u{0007}', "␇"),
440 ('\u{0008}', "␈"),
441 ('\t', " "), ('\u{000b}', "␋"),
443 ('\u{000c}', "␌"),
444 ('\u{000d}', "␍"),
445 ('\u{000e}', "␎"),
446 ('\u{000f}', "␏"),
447 ('\u{0010}', "␐"),
448 ('\u{0011}', "␑"),
449 ('\u{0012}', "␒"),
450 ('\u{0013}', "␓"),
451 ('\u{0014}', "␔"),
452 ('\u{0015}', "␕"),
453 ('\u{0016}', "␖"),
454 ('\u{0017}', "␗"),
455 ('\u{0018}', "␘"),
456 ('\u{0019}', "␙"),
457 ('\u{001a}', "␚"),
458 ('\u{001b}', "␛"),
459 ('\u{001c}', "␜"),
460 ('\u{001d}', "␝"),
461 ('\u{001e}', "␞"),
462 ('\u{001f}', "␟"),
463 ('\u{007f}', "␡"),
464 ('\u{200d}', ""), ('\u{202a}', "�"), ('\u{202b}', "�"), ('\u{202c}', "�"), ('\u{202d}', "�"),
469 ('\u{202e}', "�"),
470 ('\u{2066}', "�"),
471 ('\u{2067}', "�"),
472 ('\u{2068}', "�"),
473 ('\u{2069}', "�"),
474];
475
476pub(crate) fn normalize_whitespace(s: &str) -> String {
477 const {
478 let mut i = 1;
479 while i < OUTPUT_REPLACEMENTS.len() {
480 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!(
481 OUTPUT_REPLACEMENTS[i - 1].0 < OUTPUT_REPLACEMENTS[i].0,
482 "The OUTPUT_REPLACEMENTS array must be sorted (for binary search to work) \
483 and must contain no duplicate entries"
484 );
485 i += 1;
486 }
487 }
488 s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
492 match OUTPUT_REPLACEMENTS.binary_search_by_key(&c, |(k, _)| *k) {
493 Ok(i) => s.push_str(OUTPUT_REPLACEMENTS[i].1),
494 _ => s.push(c),
495 }
496 s
497 })
498}
499
500pub type Destination = AutoStream<Box<dyn Write + Send>>;
501
502struct Buffy {
503 buffer_writer: std::io::Stderr,
504 buffer: Vec<u8>,
505}
506
507impl Write for Buffy {
508 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
509 self.buffer.write(buf)
510 }
511
512 fn flush(&mut self) -> io::Result<()> {
513 self.buffer_writer.write_all(&self.buffer)?;
514 self.buffer.clear();
515 Ok(())
516 }
517}
518
519impl Drop for Buffy {
520 fn drop(&mut self) {
521 if !self.buffer.is_empty() {
522 self.flush().unwrap();
523 {
::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");
524 }
525 }
526}
527
528pub fn stderr_destination(color: ColorConfig) -> Destination {
529 let buffer_writer = std::io::stderr();
530 let choice = get_stderr_color_choice(color, &buffer_writer);
533 if falsecfg!(windows) {
540 AutoStream::new(Box::new(buffer_writer), choice)
541 } else {
542 let buffer = Vec::new();
543 AutoStream::new(Box::new(Buffy { buffer_writer, buffer }), choice)
544 }
545}
546
547pub fn get_stderr_color_choice(color: ColorConfig, stderr: &std::io::Stderr) -> ColorChoice {
548 let choice = color.to_color_choice();
549 if #[allow(non_exhaustive_omitted_patterns)] match choice {
ColorChoice::Auto => true,
_ => false,
}matches!(choice, ColorChoice::Auto) { AutoStream::choice(stderr) } else { choice }
550}
551
552const BRIGHT_BLUE: anstyle::Style = if falsecfg!(windows) {
556 AnsiColor::BrightCyan.on_default()
557} else {
558 AnsiColor::BrightBlue.on_default()
559};
560
561impl Style {
562 pub(crate) fn anstyle(&self, lvl: Level) -> anstyle::Style {
563 match self {
564 Style::Addition => AnsiColor::BrightGreen.on_default(),
565 Style::Removal => AnsiColor::BrightRed.on_default(),
566 Style::LineAndColumn => anstyle::Style::new(),
567 Style::LineNumber => BRIGHT_BLUE.effects(Effects::BOLD),
568 Style::Quotation => anstyle::Style::new(),
569 Style::MainHeaderMsg => if falsecfg!(windows) {
570 AnsiColor::BrightWhite.on_default()
571 } else {
572 anstyle::Style::new()
573 }
574 .effects(Effects::BOLD),
575 Style::UnderlinePrimary | Style::LabelPrimary => lvl.color().effects(Effects::BOLD),
576 Style::UnderlineSecondary | Style::LabelSecondary => BRIGHT_BLUE.effects(Effects::BOLD),
577 Style::HeaderMsg | Style::NoStyle => anstyle::Style::new(),
578 Style::Level(lvl) => lvl.color().effects(Effects::BOLD),
579 Style::Highlight => AnsiColor::Magenta.on_default().effects(Effects::BOLD),
580 }
581 }
582}
583
584pub fn is_different(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
586 let found = match sm.span_to_snippet(sp) {
587 Ok(snippet) => snippet,
588 Err(e) => {
589 {
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:589",
"rustc_errors::emitter", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_errors/src/emitter.rs"),
::tracing_core::__macro_support::Option::Some(589u32),
::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);
590 return true;
591 }
592 };
593 found != suggested
594}
595
596pub fn detect_confusion_type(sm: &SourceMap, suggested: &str, sp: Span) -> ConfusionType {
598 let found = match sm.span_to_snippet(sp) {
599 Ok(snippet) => snippet,
600 Err(e) => {
601 {
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:601",
"rustc_errors::emitter", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("compiler/rustc_errors/src/emitter.rs"),
::tracing_core::__macro_support::Option::Some(601u32),
::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);
602 return ConfusionType::None;
603 }
604 };
605
606 let mut has_case_confusion = false;
607 let mut has_digit_letter_confusion = false;
608
609 if found.len() == suggested.len() {
610 let mut has_case_diff = false;
611 let mut has_digit_letter_confusable = false;
612 let mut has_other_diff = false;
613
614 let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
617
618 let digit_letter_confusables = [('0', 'O'), ('1', 'l'), ('5', 'S'), ('8', 'B'), ('9', 'g')];
619
620 for (f, s) in iter::zip(found.chars(), suggested.chars()) {
621 if f != s {
622 if f.eq_ignore_ascii_case(&s) {
623 if ascii_confusables.contains(&f) || ascii_confusables.contains(&s) {
625 has_case_diff = true;
626 } else {
627 has_other_diff = true;
628 }
629 } else if digit_letter_confusables.contains(&(f, s))
630 || digit_letter_confusables.contains(&(s, f))
631 {
632 has_digit_letter_confusable = true;
634 } else {
635 has_other_diff = true;
636 }
637 }
638 }
639
640 if has_case_diff && !has_other_diff && found != suggested {
642 has_case_confusion = true;
643 }
644 if has_digit_letter_confusable && !has_other_diff && found != suggested {
645 has_digit_letter_confusion = true;
646 }
647 }
648
649 match (has_case_confusion, has_digit_letter_confusion) {
650 (true, true) => ConfusionType::Both,
651 (true, false) => ConfusionType::Case,
652 (false, true) => ConfusionType::DigitLetter,
653 (false, false) => ConfusionType::None,
654 }
655}
656
657#[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_fields_are_eq(&self) {}
}Eq)]
659pub enum ConfusionType {
660 None,
662 Case,
664 DigitLetter,
666 Both,
668}
669
670impl ConfusionType {
671 pub fn label_text(&self) -> &'static str {
673 match self {
674 ConfusionType::None => "",
675 ConfusionType::Case => " (notice the capitalization)",
676 ConfusionType::DigitLetter => " (notice the digit/letter confusion)",
677 ConfusionType::Both => " (notice the capitalization and digit/letter confusion)",
678 }
679 }
680
681 pub fn combine(self, other: ConfusionType) -> ConfusionType {
685 match (self, other) {
686 (ConfusionType::None, other) => other,
687 (this, ConfusionType::None) => this,
688 (ConfusionType::Both, _) | (_, ConfusionType::Both) => ConfusionType::Both,
689 (ConfusionType::Case, ConfusionType::DigitLetter)
690 | (ConfusionType::DigitLetter, ConfusionType::Case) => ConfusionType::Both,
691 (ConfusionType::Case, ConfusionType::Case) => ConfusionType::Case,
692 (ConfusionType::DigitLetter, ConfusionType::DigitLetter) => ConfusionType::DigitLetter,
693 }
694 }
695
696 pub fn has_confusion(&self) -> bool {
698 *self != ConfusionType::None
699 }
700}
701
702pub(crate) fn should_show_source_code(
703 ignored_directories: &[String],
704 sm: &SourceMap,
705 file: &SourceFile,
706) -> bool {
707 if !sm.ensure_source_file_source_present(file) {
708 return false;
709 }
710
711 let FileName::Real(name) = &file.name else { return true };
712 name.local_path()
713 .map(|path| ignored_directories.iter().all(|dir| !path.starts_with(dir)))
714 .unwrap_or(true)
715}