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]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for HumanReadableErrorType {
}Copy, #[automatically_derived]impl ::core::fmt::Debug for HumanReadableErrorType {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"HumanReadableErrorType no_graphics short unicode",
&self.no_graphics, &self.short, &&self.unicode)
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
HumanReadableErrorType {
}
#[automatically_derived]impl ::core::cmp::PartialEq for HumanReadableErrorType
{
#[inline]
fn eq(&self, other: &Self) -> bool {
self.no_graphics == other.no_graphics && self.short == other.short &&
self.unicode == other.unicode
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for HumanReadableErrorType {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq)]
35pub struct HumanReadableErrorType {
36 pub no_graphics: bool,
37 pub short: bool,
38 pub unicode: bool,
39}
40
41impl HumanReadableErrorType {
42 pub fn short(&self) -> bool {
43 self.short
44 }
45}
46
47pub enum TimingEvent {
48 Start,
49 End,
50}
51
52pub type DynEmitter = dyn Emitter + DynSend;
53
54pub trait Emitter {
56 fn emit_diagnostic(&mut self, diag: DiagInner);
58
59 fn emit_artifact_notification(&mut self, _path: &Path, _artifact_type: &str) {}
62
63 fn emit_timing_section(&mut self, _record: TimingRecord, _event: TimingEvent) {}
66
67 fn emit_future_breakage_report(&mut self, _diags: Vec<DiagInner>) {}
70
71 fn emit_unused_externs(
74 &mut self,
75 _lint_level: rustc_lint_defs::Level,
76 _unused_externs: &[&str],
77 ) {
78 }
79
80 fn should_show_explain(&self) -> bool {
82 true
83 }
84
85 fn supports_color(&self) -> bool {
87 false
88 }
89
90 fn source_map(&self) -> Option<&SourceMap>;
91
92 fn primary_span_formatted(
104 &self,
105 primary_span: &mut MultiSpan,
106 suggestions: &mut Vec<CodeSuggestion>,
107 fluent_args: &DiagArgMap,
108 ) {
109 if let Some((sugg, rest)) = suggestions.split_first() {
110 let msg = format_diag_message(&sugg.msg, fluent_args);
111 if rest.is_empty()
112 && let [substitution] = sugg.substitutions.as_slice()
115 && let [part] = substitution.parts.as_slice()
117 && msg.split_whitespace().count() < 10
119 && !part.snippet.contains('\n')
121 && ![
122 SuggestionStyle::HideCodeAlways,
124 SuggestionStyle::CompletelyHidden,
126 SuggestionStyle::ShowAlways,
128 ].contains(&sugg.style)
129 {
130 let snippet = part.snippet.trim();
131 let msg = if snippet.is_empty() || sugg.style.hide_inline() {
132 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("help: {0}", msg))
})format!("help: {msg}")
135 } else {
136 let confusion_type = self
138 .source_map()
139 .map(|sm| detect_confusion_type(sm, snippet, part.span))
140 .unwrap_or(ConfusionType::None);
141 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("help: {0}{1}: `{2}`", msg,
confusion_type.label_text(), snippet))
})format!("help: {}{}: `{}`", msg, confusion_type.label_text(), snippet,)
142 };
143 primary_span.push_span_label(part.span, msg);
144
145 suggestions.clear();
147 } else {
148 }
153 } else {
154 }
156 }
157
158 fn fix_multispans_in_extern_macros_and_render_macro_backtrace(
159 &self,
160 span: &mut MultiSpan,
161 children: &mut Vec<Subdiag>,
162 level: &Level,
163 backtrace: bool,
164 ) {
165 let has_macro_spans: Vec<_> = iter::once(&*span)
168 .chain(children.iter().map(|child| &child.span))
169 .flat_map(|span| span.primary_spans())
170 .flat_map(|sp| sp.macro_backtrace().map(move |expn_data| (sp, expn_data)))
171 .filter_map(|(sp, expn_data)| {
172 match expn_data.kind {
173 ExpnKind::Root => None,
174
175 ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None,
178
179 ExpnKind::Macro(macro_kind, name) => {
180 let same_line = sp
181 .overlaps(expn_data.def_site)
182 .then(|| expn_data.def_site.with_hi(sp.lo()));
183 Some((
184 macro_kind,
185 name,
186 expn_data.diagnostic_opaque,
187 expn_data.def_site,
188 same_line,
189 ))
190 }
191 }
192 })
193 .collect();
194
195 if !backtrace {
196 self.fix_multispans_in_extern_macros(span, children);
197 }
198
199 self.render_multispans_macro_backtrace(span, children, backtrace);
200
201 if !backtrace
202 && let Some((macro_kind, name, _, sp, same_line_span)) = has_macro_spans.first()
204 && let Some((_, _, false, _, _)) = has_macro_spans.last()
205 {
206 let and_then = if let Some((macro_kind, last_name, _, _, _)) = has_macro_spans.last()
208 && last_name != name
209 {
210 let descr = macro_kind.descr();
211 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" which comes from the expansion of the {0} `{1}`",
descr, last_name))
})format!(" which comes from the expansion of the {descr} `{last_name}`")
212 } else {
213 "".to_string()
214 };
215
216 let descr = macro_kind.descr();
217 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this {0} originates in the {1} `{2}`{3}",
level, descr, name, and_then))
})format!("this {level} originates in the {descr} `{name}`{and_then}");
218
219 if let Some(source_map) = self.source_map() {
220 if source_map.is_imported(*sp) || same_line_span.is_none() {
221 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} (in Nightly builds, run with -Z macro-backtrace for more info)",
msg))
})format!(
222 "{msg} (in Nightly builds, run with -Z macro-backtrace for more info)"
223 );
224 children.push(Subdiag {
225 level: Sublevel::Note,
226 messages: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(DiagMessage::from(msg), Style::NoStyle)]))vec![(DiagMessage::from(msg), Style::NoStyle)],
227 span: MultiSpan::new(),
228 });
229 } else if let Some(def) = same_line_span
230 && source_map.is_multiline(*def)
231 && !and_then.is_empty()
232 {
233 span.push_span_label(*sp, msg);
236 } else {
237 span.push_span_context(sp.shrink_to_lo());
240 }
241 } else {
242 children.push(Subdiag {
243 level: Sublevel::Note,
244 messages: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(DiagMessage::from(msg), Style::NoStyle)]))vec![(DiagMessage::from(msg), Style::NoStyle)],
245 span: MultiSpan::new(),
246 });
247 }
248 }
249 }
250
251 fn render_multispans_macro_backtrace(
252 &self,
253 span: &mut MultiSpan,
254 children: &mut Vec<Subdiag>,
255 backtrace: bool,
256 ) {
257 for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) {
258 self.render_multispan_macro_backtrace(span, backtrace);
259 }
260 }
261
262 fn render_multispan_macro_backtrace(&self, span: &mut MultiSpan, always_backtrace: bool) {
263 let mut new_labels = FxIndexSet::default();
264
265 for &sp in span.primary_spans() {
266 if sp.is_dummy() {
267 continue;
268 }
269
270 let macro_backtrace: Vec<_> = sp.macro_backtrace().collect();
274 for (i, trace) in macro_backtrace.iter().rev().enumerate() {
275 if trace.def_site.is_dummy() {
276 continue;
277 }
278
279 if always_backtrace {
280 new_labels.insert((
281 trace.def_site,
282 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in this expansion of `{0}`{1}",
trace.kind.descr(),
if macro_backtrace.len() > 1 {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" (#{0})", i + 1))
})
} else { String::new() }))
})format!(
283 "in this expansion of `{}`{}",
284 trace.kind.descr(),
285 if macro_backtrace.len() > 1 {
286 format!(" (#{})", i + 1)
289 } else {
290 String::new()
291 },
292 ),
293 ));
294 }
295
296 let redundant_span = trace.call_site.contains(sp);
308
309 if !redundant_span || always_backtrace {
310 let msg: Cow<'static, _> = match trace.kind {
311 ExpnKind::Macro(MacroKind::Attr, _) => {
312 "this attribute macro expansion".into()
313 }
314 ExpnKind::Macro(MacroKind::Derive, _) => {
315 "this derive macro expansion".into()
316 }
317 ExpnKind::Macro(MacroKind::Bang, _) => "this macro invocation".into(),
318 ExpnKind::Root => "the crate root".into(),
319 ExpnKind::AstPass(kind) => kind.descr().into(),
320 ExpnKind::Desugaring(kind) => {
321 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this {0} desugaring",
kind.descr()))
})format!("this {} desugaring", kind.descr()).into()
322 }
323 };
324 new_labels.insert((
325 trace.call_site,
326 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in {0}{1}", msg,
if macro_backtrace.len() > 1 && always_backtrace {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" (#{0})", i + 1))
})
} else { String::new() }))
})format!(
327 "in {}{}",
328 msg,
329 if macro_backtrace.len() > 1 && always_backtrace {
330 format!(" (#{})", i + 1)
333 } else {
334 String::new()
335 },
336 ),
337 ));
338 }
339 if !always_backtrace {
340 break;
341 }
342 }
343 }
344
345 for (label_span, label_text) in new_labels {
346 span.push_span_label(label_span, label_text);
347 }
348 }
349
350 fn fix_multispans_in_extern_macros(&self, span: &mut MultiSpan, children: &mut Vec<Subdiag>) {
354 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_errors/src/emitter.rs:354",
"rustc_errors::emitter", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_errors/src/emitter.rs"),
::tracing_core::__macro_support::Option::Some(354u32),
::tracing_core::__macro_support::Option::Some("rustc_errors::emitter"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("fix_multispans_in_extern_macros: before: span={0:?} children={1:?}",
span, children) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children);
355 self.fix_multispan_in_extern_macros(span);
356 for child in children.iter_mut() {
357 self.fix_multispan_in_extern_macros(&mut child.span);
358 }
359 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_errors/src/emitter.rs:359",
"rustc_errors::emitter", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_errors/src/emitter.rs"),
::tracing_core::__macro_support::Option::Some(359u32),
::tracing_core::__macro_support::Option::Some("rustc_errors::emitter"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("fix_multispans_in_extern_macros: after: span={0:?} children={1:?}",
span, children) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("fix_multispans_in_extern_macros: after: span={:?} children={:?}", span, children);
360 }
361
362 fn fix_multispan_in_extern_macros(&self, span: &mut MultiSpan) {
366 let Some(source_map) = self.source_map() else { return };
367 let should_hide = |span| {
368 source_map.is_imported(span) || {
369 let expn = span.ctxt().outer_expn_data();
370 expn.diagnostic_opaque && #[allow(non_exhaustive_omitted_patterns)] match expn.kind {
ExpnKind::Macro(MacroKind::Bang, _) => true,
_ => false,
}matches!(expn.kind, ExpnKind::Macro(MacroKind::Bang, _))
371 }
372 };
373
374 let replacements: Vec<(Span, Span)> = span
376 .primary_spans()
377 .iter()
378 .copied()
379 .chain(span.span_labels().iter().map(|sp_label| sp_label.span))
380 .filter_map(|sp| {
381 if !sp.is_dummy() && should_hide(sp) {
382 let mut span = sp;
383 while let Some(callsite) = span.parent_callsite() {
384 span = callsite;
385 if !should_hide(span) {
386 return Some((sp, span));
387 }
388 }
389 }
390 None
391 })
392 .collect();
393
394 for (from, to) in replacements {
396 span.replace(from, to);
397 }
398 }
399}
400
401pub struct EmitterWithNote {
403 pub emitter: Box<dyn Emitter + DynSend>,
404 pub note: String,
405}
406
407impl Emitter for EmitterWithNote {
408 fn source_map(&self) -> Option<&SourceMap> {
409 None
410 }
411
412 fn emit_diagnostic(&mut self, mut diag: DiagInner) {
413 diag.sub(Sublevel::Note, self.note.clone(), MultiSpan::new());
414 self.emitter.emit_diagnostic(diag);
415 }
416}
417
418pub struct SilentEmitter;
419
420impl Emitter for SilentEmitter {
421 fn source_map(&self) -> Option<&SourceMap> {
422 None
423 }
424
425 fn emit_diagnostic(&mut self, _diag: DiagInner) {}
426}
427
428pub const MAX_SUGGESTIONS: usize = 4;
432
433#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ColorConfig {
}
#[automatically_derived]impl ::core::clone::Clone for ColorConfig {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ColorConfig { }Copy, #[automatically_derived]impl ::core::fmt::Debug for ColorConfig {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ColorConfig::Auto => "Auto",
ColorConfig::Always => "Always",
ColorConfig::Never => "Never",
})
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ColorConfig {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ColorConfig {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ColorConfig { }Eq)]
434pub enum ColorConfig {
435 Auto,
436 Always,
437 Never,
438}
439
440impl ColorConfig {
441 pub fn to_color_choice(self) -> ColorChoice {
442 match self {
443 ColorConfig::Always => {
444 if io::stderr().is_terminal() {
445 ColorChoice::Always
446 } else {
447 ColorChoice::AlwaysAnsi
448 }
449 }
450 ColorConfig::Never => ColorChoice::Never,
451 ColorConfig::Auto if io::stderr().is_terminal() => ColorChoice::Auto,
452 ColorConfig::Auto => ColorChoice::Never,
453 }
454 }
455}
456
457#[derive(#[automatically_derived]impl ::core::fmt::Debug for OutputTheme {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
OutputTheme::Ascii => "Ascii",
OutputTheme::Unicode => "Unicode",
})
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for OutputTheme {
}
#[automatically_derived]impl ::core::clone::Clone for OutputTheme {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for OutputTheme { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
OutputTheme {
}
#[automatically_derived]impl ::core::cmp::PartialEq for OutputTheme {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for OutputTheme { }Eq)]
458pub enum OutputTheme {
459 Ascii,
460 Unicode,
461}
462
463const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[
466 ('\0', "␀"),
470 ('\u{0001}', "␁"),
471 ('\u{0002}', "␂"),
472 ('\u{0003}', "␃"),
473 ('\u{0004}', "␄"),
474 ('\u{0005}', "␅"),
475 ('\u{0006}', "␆"),
476 ('\u{0007}', "␇"),
477 ('\u{0008}', "␈"),
478 ('\t', " "), ('\u{000b}', "␋"),
480 ('\u{000c}', "␌"),
481 ('\u{000d}', "␍"),
482 ('\u{000e}', "␎"),
483 ('\u{000f}', "␏"),
484 ('\u{0010}', "␐"),
485 ('\u{0011}', "␑"),
486 ('\u{0012}', "␒"),
487 ('\u{0013}', "␓"),
488 ('\u{0014}', "␔"),
489 ('\u{0015}', "␕"),
490 ('\u{0016}', "␖"),
491 ('\u{0017}', "␗"),
492 ('\u{0018}', "␘"),
493 ('\u{0019}', "␙"),
494 ('\u{001a}', "␚"),
495 ('\u{001b}', "␛"),
496 ('\u{001c}', "␜"),
497 ('\u{001d}', "␝"),
498 ('\u{001e}', "␞"),
499 ('\u{001f}', "␟"),
500 ('\u{007f}', "␡"),
501 ('\u{200d}', ""), ('\u{202a}', "�"), ('\u{202b}', "�"), ('\u{202c}', "�"), ('\u{202d}', "�"),
506 ('\u{202e}', "�"),
507 ('\u{2066}', "�"),
508 ('\u{2067}', "�"),
509 ('\u{2068}', "�"),
510 ('\u{2069}', "�"),
511];
512
513pub(crate) fn normalize_whitespace(s: &str) -> String {
514 const {
515 let mut i = 1;
516 while i < OUTPUT_REPLACEMENTS.len() {
517 if !(OUTPUT_REPLACEMENTS[i - 1].0 < OUTPUT_REPLACEMENTS[i].0) {
{
::core::panicking::panic_fmt(format_args!("The OUTPUT_REPLACEMENTS array must be sorted (for binary search to work) and must contain no duplicate entries"));
}
};assert!(
518 OUTPUT_REPLACEMENTS[i - 1].0 < OUTPUT_REPLACEMENTS[i].0,
519 "The OUTPUT_REPLACEMENTS array must be sorted (for binary search to work) \
520 and must contain no duplicate entries"
521 );
522 i += 1;
523 }
524 }
525 s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
529 match OUTPUT_REPLACEMENTS.binary_search_by_key(&c, |(k, _)| *k) {
530 Ok(i) => s.push_str(OUTPUT_REPLACEMENTS[i].1),
531 _ => s.push(c),
532 }
533 s
534 })
535}
536
537pub type Destination = AutoStream<Box<dyn Write + Send>>;
538
539struct Buffy {
540 buffer_writer: std::io::Stderr,
541 buffer: Vec<u8>,
542}
543
544impl Write for Buffy {
545 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
546 self.buffer.write(buf)
547 }
548
549 fn flush(&mut self) -> io::Result<()> {
550 self.buffer_writer.write_all(&self.buffer)?;
551 self.buffer.clear();
552 Ok(())
553 }
554}
555
556impl Drop for Buffy {
557 fn drop(&mut self) {
558 if !self.buffer.is_empty() {
559 self.flush().unwrap();
560 {
::core::panicking::panic_fmt(format_args!("buffers need to be flushed in order to print their contents"));
};panic!("buffers need to be flushed in order to print their contents");
561 }
562 }
563}
564
565pub fn stderr_destination(color: ColorConfig) -> Destination {
566 let buffer_writer = std::io::stderr();
567 let choice = get_stderr_color_choice(color, &buffer_writer);
570 if falsecfg!(windows) {
577 AutoStream::new(Box::new(buffer_writer), choice)
578 } else {
579 let buffer = Vec::new();
580 AutoStream::new(Box::new(Buffy { buffer_writer, buffer }), choice)
581 }
582}
583
584pub fn get_stderr_color_choice(color: ColorConfig, stderr: &std::io::Stderr) -> ColorChoice {
585 let choice = color.to_color_choice();
586 if #[allow(non_exhaustive_omitted_patterns)] match choice {
ColorChoice::Auto => true,
_ => false,
}matches!(choice, ColorChoice::Auto) { AutoStream::choice(stderr) } else { choice }
587}
588
589impl Style {
590 pub(crate) fn anstyle(&self) -> anstyle::Style {
591 match self {
592 Style::NoStyle => anstyle::Style::new(),
593 Style::Highlight => AnsiColor::BrightCyan.on_default().effects(Effects::BOLD),
594 }
595 }
596}
597
598pub fn is_different(sm: &SourceMap, suggested: &str, sp: Span) -> bool {
600 let found = match sm.span_to_snippet(sp) {
601 Ok(snippet) => snippet,
602 Err(e) => {
603 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_errors/src/emitter.rs:603",
"rustc_errors::emitter", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_errors/src/emitter.rs"),
::tracing_core::__macro_support::Option::Some(603u32),
::tracing_core::__macro_support::Option::Some("rustc_errors::emitter"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("error")
}> =
::tracing::__macro_support::FieldName::new("error");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Invalid span {0:?}",
sp) as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&e)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};warn!(error = ?e, "Invalid span {:?}", sp);
604 return true;
605 }
606 };
607 found != suggested
608}
609
610pub fn detect_confusion_type(sm: &SourceMap, suggested: &str, sp: Span) -> ConfusionType {
612 let found = match sm.span_to_snippet(sp) {
613 Ok(snippet) => snippet,
614 Err(e) => {
615 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_errors/src/emitter.rs:615",
"rustc_errors::emitter", ::tracing::Level::WARN,
::tracing_core::__macro_support::Option::Some("/rustc-dev/59cbdee2e7b3ee50e44b460561c43c9e3023d9f0/compiler/rustc_errors/src/emitter.rs"),
::tracing_core::__macro_support::Option::Some(615u32),
::tracing_core::__macro_support::Option::Some("rustc_errors::emitter"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("error")
}> =
::tracing::__macro_support::FieldName::new("error");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::WARN <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Invalid span {0:?}",
sp) as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&e)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};warn!(error = ?e, "Invalid span {:?}", sp);
616 return ConfusionType::None;
617 }
618 };
619
620 let mut has_case_confusion = false;
621 let mut has_digit_letter_confusion = false;
622
623 if found.len() == suggested.len() {
624 let mut has_case_diff = false;
625 let mut has_digit_letter_confusable = false;
626 let mut has_other_diff = false;
627
628 let ascii_confusables = &['c', 'f', 'i', 'k', 'o', 's', 'u', 'v', 'w', 'x', 'y', 'z'];
631
632 let digit_letter_confusables = [('0', 'O'), ('1', 'l'), ('5', 'S'), ('8', 'B'), ('9', 'g')];
633
634 for (f, s) in iter::zip(found.chars(), suggested.chars()) {
635 if f != s {
636 if f.eq_ignore_ascii_case(&s) {
637 if ascii_confusables.contains(&f) || ascii_confusables.contains(&s) {
639 has_case_diff = true;
640 } else {
641 has_other_diff = true;
642 }
643 } else if digit_letter_confusables.contains(&(f, s))
644 || digit_letter_confusables.contains(&(s, f))
645 {
646 has_digit_letter_confusable = true;
648 } else {
649 has_other_diff = true;
650 }
651 }
652 }
653
654 if has_case_diff && !has_other_diff && found != suggested {
656 has_case_confusion = true;
657 }
658 if has_digit_letter_confusable && !has_other_diff && found != suggested {
659 has_digit_letter_confusion = true;
660 }
661 }
662
663 match (has_case_confusion, has_digit_letter_confusion) {
664 (true, true) => ConfusionType::Both,
665 (true, false) => ConfusionType::Case,
666 (false, true) => ConfusionType::DigitLetter,
667 (false, false) => ConfusionType::None,
668 }
669}
670
671#[derive(#[automatically_derived]impl ::core::fmt::Debug for ConfusionType {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ConfusionType::None => "None",
ConfusionType::Case => "Case",
ConfusionType::DigitLetter => "DigitLetter",
ConfusionType::Both => "Both",
})
}
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for ConfusionType {
}
#[automatically_derived]impl ::core::clone::Clone for ConfusionType {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ConfusionType { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
ConfusionType {
}
#[automatically_derived]impl ::core::cmp::PartialEq for ConfusionType {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for ConfusionType { }Eq)]
673pub enum ConfusionType {
674 None,
676 Case,
678 DigitLetter,
680 Both,
682}
683
684impl ConfusionType {
685 pub fn label_text(&self) -> &'static str {
687 match self {
688 ConfusionType::None => "",
689 ConfusionType::Case => " (notice the capitalization)",
690 ConfusionType::DigitLetter => " (notice the digit/letter confusion)",
691 ConfusionType::Both => " (notice the capitalization and digit/letter confusion)",
692 }
693 }
694
695 pub fn combine(self, other: ConfusionType) -> ConfusionType {
699 match (self, other) {
700 (ConfusionType::None, other) => other,
701 (this, ConfusionType::None) => this,
702 (ConfusionType::Both, _) | (_, ConfusionType::Both) => ConfusionType::Both,
703 (ConfusionType::Case, ConfusionType::DigitLetter)
704 | (ConfusionType::DigitLetter, ConfusionType::Case) => ConfusionType::Both,
705 (ConfusionType::Case, ConfusionType::Case) => ConfusionType::Case,
706 (ConfusionType::DigitLetter, ConfusionType::DigitLetter) => ConfusionType::DigitLetter,
707 }
708 }
709
710 pub fn has_confusion(&self) -> bool {
712 *self != ConfusionType::None
713 }
714}
715
716pub(crate) fn should_show_source_code(
717 ignored_directories: &[String],
718 sm: &SourceMap,
719 file: &SourceFile,
720) -> bool {
721 if !sm.ensure_source_file_source_present(file) {
722 return false;
723 }
724
725 let FileName::Real(name) = &file.name else { return true };
726 name.local_path()
727 .map(|path| ignored_directories.iter().all(|dir| !path.starts_with(dir)))
728 .unwrap_or(true)
729}