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::formatting::format_diag_message;
27use crate::timings::TimingRecord;
28use crate::{
29 CodeSuggestion, DiagInner, DiagMessage, Level, MultiSpan, Style, Subdiag, Sublevel,
30 SuggestionStyle,
31};
32
33#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for HumanReadableErrorType { }
#[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::marker::StructuralPartialEq for HumanReadableErrorType { }
#[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)]
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
53pub trait Emitter {
55 fn emit_diagnostic(&mut self, diag: DiagInner);
57
58 fn emit_artifact_notification(&mut self, _path: &Path, _artifact_type: &str) {}
61
62 fn emit_timing_section(&mut self, _record: TimingRecord, _event: TimingEvent) {}
65
66 fn emit_future_breakage_report(&mut self, _diags: Vec<DiagInner>) {}
69
70 fn emit_unused_externs(
73 &mut self,
74 _lint_level: rustc_lint_defs::Level,
75 _unused_externs: &[&str],
76 ) {
77 }
78
79 fn should_show_explain(&self) -> bool {
81 true
82 }
83
84 fn supports_color(&self) -> bool {
86 false
87 }
88
89 fn source_map(&self) -> Option<&SourceMap>;
90
91 fn primary_span_formatted(
103 &self,
104 primary_span: &mut MultiSpan,
105 suggestions: &mut Vec<CodeSuggestion>,
106 fluent_args: &DiagArgMap,
107 ) {
108 if let Some((sugg, rest)) = suggestions.split_first() {
109 let msg = format_diag_message(&sugg.msg, fluent_args);
110 if rest.is_empty()
111 && let [substitution] = sugg.substitutions.as_slice()
114 && let [part] = substitution.parts.as_slice()
116 && msg.split_whitespace().count() < 10
118 && !part.snippet.contains('\n')
120 && ![
121 SuggestionStyle::HideCodeAlways,
123 SuggestionStyle::CompletelyHidden,
125 SuggestionStyle::ShowAlways,
127 ].contains(&sugg.style)
128 {
129 let snippet = part.snippet.trim();
130 let msg = if snippet.is_empty() || sugg.style.hide_inline() {
131 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("help: {0}", msg))
})format!("help: {msg}")
134 } else {
135 let confusion_type = self
137 .source_map()
138 .map(|sm| detect_confusion_type(sm, snippet, part.span))
139 .unwrap_or(ConfusionType::None);
140 ::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,)
141 };
142 primary_span.push_span_label(part.span, msg);
143
144 suggestions.clear();
146 } else {
147 }
152 } else {
153 }
155 }
156
157 fn fix_multispans_in_extern_macros_and_render_macro_backtrace(
158 &self,
159 span: &mut MultiSpan,
160 children: &mut Vec<Subdiag>,
161 level: &Level,
162 backtrace: bool,
163 ) {
164 let has_macro_spans: Vec<_> = iter::once(&*span)
167 .chain(children.iter().map(|child| &child.span))
168 .flat_map(|span| span.primary_spans())
169 .flat_map(|sp| sp.macro_backtrace())
170 .filter_map(|expn_data| {
171 match expn_data.kind {
172 ExpnKind::Root => None,
173
174 ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None,
177
178 ExpnKind::Macro(macro_kind, name) => {
179 Some((macro_kind, name, expn_data.diagnostic_opaque))
180 }
181 }
182 })
183 .collect();
184
185 if !backtrace {
186 self.fix_multispans_in_extern_macros(span, children);
187 }
188
189 self.render_multispans_macro_backtrace(span, children, backtrace);
190
191 if !backtrace {
192 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: Sublevel::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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_errors/src/emitter.rs:324",
"rustc_errors::emitter", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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};
__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);
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 /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_errors/src/emitter.rs:329",
"rustc_errors::emitter", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/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};
__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);
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 should_hide = |span| {
338 source_map.is_imported(span) || {
339 let expn = span.data().ctxt.outer_expn_data();
340 expn.diagnostic_opaque && #[allow(non_exhaustive_omitted_patterns)] match expn.kind {
ExpnKind::Macro(MacroKind::Bang, _) => true,
_ => false,
}matches!(expn.kind, ExpnKind::Macro(MacroKind::Bang, _))
341 }
342 };
343
344 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() && should_hide(sp) {
352 let mut span = sp;
353 while let Some(callsite) = span.parent_callsite() {
354 span = callsite;
355 if !should_hide(span) {
356 return Some((sp, span));
357 }
358 }
359 }
360 None
361 })
362 .collect();
363
364 for (from, to) in replacements {
366 span.replace(from, to);
367 }
368 }
369}
370
371pub 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(Sublevel::Note, self.note.clone(), MultiSpan::new());
384 self.emitter.emit_diagnostic(diag);
385 }
386}
387
388pub struct SilentEmitter;
389
390impl Emitter for SilentEmitter {
391 fn source_map(&self) -> Option<&SourceMap> {
392 None
393 }
394
395 fn emit_diagnostic(&mut self, _diag: DiagInner) {}
396}
397
398pub const MAX_SUGGESTIONS: usize = 4;
402
403#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ColorConfig { }
#[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::marker::StructuralPartialEq for ColorConfig { }
#[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 { }Eq)]
404pub enum ColorConfig {
405 Auto,
406 Always,
407 Never,
408}
409
410impl ColorConfig {
411 pub fn to_color_choice(self) -> ColorChoice {
412 match self {
413 ColorConfig::Always => {
414 if io::stderr().is_terminal() {
415 ColorChoice::Always
416 } else {
417 ColorChoice::AlwaysAnsi
418 }
419 }
420 ColorConfig::Never => ColorChoice::Never,
421 ColorConfig::Auto if io::stderr().is_terminal() => ColorChoice::Auto,
422 ColorConfig::Auto => ColorChoice::Never,
423 }
424 }
425}
426
427#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for OutputTheme { }
#[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::marker::StructuralPartialEq for OutputTheme { }
#[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 { }Eq)]
428pub enum OutputTheme {
429 Ascii,
430 Unicode,
431}
432
433const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[
436 ('\0', "␀"),
440 ('\u{0001}', "␁"),
441 ('\u{0002}', "␂"),
442 ('\u{0003}', "␃"),
443 ('\u{0004}', "␄"),
444 ('\u{0005}', "␅"),
445 ('\u{0006}', "␆"),
446 ('\u{0007}', "␇"),
447 ('\u{0008}', "␈"),
448 ('\t', " "), ('\u{000b}', "␋"),
450 ('\u{000c}', "␌"),
451 ('\u{000d}', "␍"),
452 ('\u{000e}', "␎"),
453 ('\u{000f}', "␏"),
454 ('\u{0010}', "␐"),
455 ('\u{0011}', "␑"),
456 ('\u{0012}', "␒"),
457 ('\u{0013}', "␓"),
458 ('\u{0014}', "␔"),
459 ('\u{0015}', "␕"),
460 ('\u{0016}', "␖"),
461 ('\u{0017}', "␗"),
462 ('\u{0018}', "␘"),
463 ('\u{0019}', "␙"),
464 ('\u{001a}', "␚"),
465 ('\u{001b}', "␛"),
466 ('\u{001c}', "␜"),
467 ('\u{001d}', "␝"),
468 ('\u{001e}', "␞"),
469 ('\u{001f}', "␟"),
470 ('\u{007f}', "␡"),
471 ('\u{200d}', ""), ('\u{202a}', "�"), ('\u{202b}', "�"), ('\u{202c}', "�"), ('\u{202d}', "�"),
476 ('\u{202e}', "�"),
477 ('\u{2066}', "�"),
478 ('\u{2067}', "�"),
479 ('\u{2068}', "�"),
480 ('\u{2069}', "�"),
481];
482
483pub(crate) fn normalize_whitespace(s: &str) -> String {
484 const {
485 let mut i = 1;
486 while i < OUTPUT_REPLACEMENTS.len() {
487 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!(
488 OUTPUT_REPLACEMENTS[i - 1].0 < OUTPUT_REPLACEMENTS[i].0,
489 "The OUTPUT_REPLACEMENTS array must be sorted (for binary search to work) \
490 and must contain no duplicate entries"
491 );
492 i += 1;
493 }
494 }
495 s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
499 match OUTPUT_REPLACEMENTS.binary_search_by_key(&c, |(k, _)| *k) {
500 Ok(i) => s.push_str(OUTPUT_REPLACEMENTS[i].1),
501 _ => s.push(c),
502 }
503 s
504 })
505}
506
507pub type Destination = AutoStream<Box<dyn Write + Send>>;
508
509struct Buffy {
510 buffer_writer: std::io::Stderr,
511 buffer: Vec<u8>,
512}
513
514impl Write for Buffy {
515 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
516 self.buffer.write(buf)
517 }
518
519 fn flush(&mut self) -> io::Result<()> {
520 self.buffer_writer.write_all(&self.buffer)?;
521 self.buffer.clear();
522 Ok(())
523 }
524}
525
526impl Drop for Buffy {
527 fn drop(&mut self) {
528 if !self.buffer.is_empty() {
529 self.flush().unwrap();
530 {
::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");
531 }
532 }
533}
534
535pub fn stderr_destination(color: ColorConfig) -> Destination {
536 let buffer_writer = std::io::stderr();
537 let choice = get_stderr_color_choice(color, &buffer_writer);
540 if falsecfg!(windows) {
547 AutoStream::new(Box::new(buffer_writer), choice)
548 } else {
549 let buffer = Vec::new();
550 AutoStream::new(Box::new(Buffy { buffer_writer, buffer }), choice)
551 }
552}
553
554pub fn get_stderr_color_choice(color: ColorConfig, stderr: &std::io::Stderr) -> ColorChoice {
555 let choice = color.to_color_choice();
556 if #[allow(non_exhaustive_omitted_patterns)] match choice {
ColorChoice::Auto => true,
_ => false,
}matches!(choice, ColorChoice::Auto) { AutoStream::choice(stderr) } else { choice }
557}
558
559impl Style {
560 pub(crate) fn anstyle(&self) -> anstyle::Style {
561 match self {
562 Style::NoStyle => anstyle::Style::new(),
563 Style::Highlight => AnsiColor::Magenta.on_default().effects(Effects::BOLD),
564 }
565 }
566}
567
568pub fn is_different(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
570 let found = match sm.span_to_snippet(sp) {
571 Ok(snippet) => snippet,
572 Err(e) => {
573 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_errors/src/emitter.rs:573",
"rustc_errors::emitter", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_errors/src/emitter.rs"),
::tracing_core::__macro_support::Option::Some(573u32),
::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);
574 return true;
575 }
576 };
577 found != suggested
578}
579
580pub fn detect_confusion_type(sm: &SourceMap, suggested: &str, sp: Span) -> ConfusionType {
582 let found = match sm.span_to_snippet(sp) {
583 Ok(snippet) => snippet,
584 Err(e) => {
585 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_errors/src/emitter.rs:585",
"rustc_errors::emitter", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_errors/src/emitter.rs"),
::tracing_core::__macro_support::Option::Some(585u32),
::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);
586 return ConfusionType::None;
587 }
588 };
589
590 let mut has_case_confusion = false;
591 let mut has_digit_letter_confusion = false;
592
593 if found.len() == suggested.len() {
594 let mut has_case_diff = false;
595 let mut has_digit_letter_confusable = false;
596 let mut has_other_diff = false;
597
598 let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
601
602 let digit_letter_confusables = [('0', 'O'), ('1', 'l'), ('5', 'S'), ('8', 'B'), ('9', 'g')];
603
604 for (f, s) in iter::zip(found.chars(), suggested.chars()) {
605 if f != s {
606 if f.eq_ignore_ascii_case(&s) {
607 if ascii_confusables.contains(&f) || ascii_confusables.contains(&s) {
609 has_case_diff = true;
610 } else {
611 has_other_diff = true;
612 }
613 } else if digit_letter_confusables.contains(&(f, s))
614 || digit_letter_confusables.contains(&(s, f))
615 {
616 has_digit_letter_confusable = true;
618 } else {
619 has_other_diff = true;
620 }
621 }
622 }
623
624 if has_case_diff && !has_other_diff && found != suggested {
626 has_case_confusion = true;
627 }
628 if has_digit_letter_confusable && !has_other_diff && found != suggested {
629 has_digit_letter_confusion = true;
630 }
631 }
632
633 match (has_case_confusion, has_digit_letter_confusion) {
634 (true, true) => ConfusionType::Both,
635 (true, false) => ConfusionType::Case,
636 (false, true) => ConfusionType::DigitLetter,
637 (false, false) => ConfusionType::None,
638 }
639}
640
641#[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]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ConfusionType { }
#[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::marker::StructuralPartialEq for ConfusionType { }
#[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 { }Eq)]
643pub enum ConfusionType {
644 None,
646 Case,
648 DigitLetter,
650 Both,
652}
653
654impl ConfusionType {
655 pub fn label_text(&self) -> &'static str {
657 match self {
658 ConfusionType::None => "",
659 ConfusionType::Case => " (notice the capitalization)",
660 ConfusionType::DigitLetter => " (notice the digit/letter confusion)",
661 ConfusionType::Both => " (notice the capitalization and digit/letter confusion)",
662 }
663 }
664
665 pub fn combine(self, other: ConfusionType) -> ConfusionType {
669 match (self, other) {
670 (ConfusionType::None, other) => other,
671 (this, ConfusionType::None) => this,
672 (ConfusionType::Both, _) | (_, ConfusionType::Both) => ConfusionType::Both,
673 (ConfusionType::Case, ConfusionType::DigitLetter)
674 | (ConfusionType::DigitLetter, ConfusionType::Case) => ConfusionType::Both,
675 (ConfusionType::Case, ConfusionType::Case) => ConfusionType::Case,
676 (ConfusionType::DigitLetter, ConfusionType::DigitLetter) => ConfusionType::DigitLetter,
677 }
678 }
679
680 pub fn has_confusion(&self) -> bool {
682 *self != ConfusionType::None
683 }
684}
685
686pub(crate) fn should_show_source_code(
687 ignored_directories: &[String],
688 sm: &SourceMap,
689 file: &SourceFile,
690) -> bool {
691 if !sm.ensure_source_file_source_present(file) {
692 return false;
693 }
694
695 let FileName::Real(name) = &file.name else { return true };
696 name.local_path()
697 .map(|path| ignored_directories.iter().all(|dir| !path.starts_with(dir)))
698 .unwrap_or(true)
699}