1use std::fmt::Debug;
9use std::io;
10use std::io::Write;
11use std::sync::Arc;
12
13use annotate_snippets::renderer::DEFAULT_TERM_WIDTH;
14use annotate_snippets::{AnnotationKind, Group, Origin, Padding, Patch, Renderer, Snippet};
15use anstream::ColorChoice;
16use derive_setters::Setters;
17use rustc_data_structures::sync::IntoDynSyncSend;
18use rustc_error_messages::{DiagArgMap, SpanLabel};
19use rustc_lint_defs::pluralize;
20use rustc_span::source_map::SourceMap;
21use rustc_span::{BytePos, FileName, Pos, SourceFile, Span};
22use tracing::debug;
23
24use crate::emitter::{
25 ConfusionType, Destination, MAX_SUGGESTIONS, OutputTheme, detect_confusion_type, is_different,
26 normalize_whitespace, should_show_source_code,
27};
28use crate::formatting::{format_diag_message, format_diag_messages};
29use crate::{
30 CodeSuggestion, DiagInner, DiagMessage, Emitter, ErrCode, Level, MultiSpan, Style, Subdiag,
31 Sublevel, SuggestionStyle, TerminalUrl,
32};
33
34#[derive(impl AnnotateSnippetEmitter {
#[must_use]
pub fn sm(mut self, value: Option<Arc<SourceMap>>) -> Self {
self.sm = value;
self
}
#[must_use]
pub fn short_message(mut self, value: bool) -> Self {
self.short_message = value;
self
}
#[must_use]
pub fn ui_testing(mut self, value: bool) -> Self {
self.ui_testing = value;
self
}
#[must_use]
pub fn ignored_directories_in_source_blocks(mut self, value: Vec<String>)
-> Self {
self.ignored_directories_in_source_blocks = value;
self
}
#[must_use]
pub fn diagnostic_width(mut self, value: Option<usize>) -> Self {
self.diagnostic_width = value;
self
}
#[must_use]
pub fn macro_backtrace(mut self, value: bool) -> Self {
self.macro_backtrace = value;
self
}
#[must_use]
pub fn track_diagnostics(mut self, value: bool) -> Self {
self.track_diagnostics = value;
self
}
#[must_use]
pub fn terminal_url(mut self, value: TerminalUrl) -> Self {
self.terminal_url = value;
self
}
#[must_use]
pub fn theme(mut self, value: OutputTheme) -> Self {
self.theme = value;
self
}
#[must_use]
pub fn no_graphics(mut self, value: bool) -> Self {
self.no_graphics = value;
self
}
}Setters)]
36pub struct AnnotateSnippetEmitter {
37 #[setters(skip)]
38 dst: IntoDynSyncSend<Destination>,
39 sm: Option<Arc<SourceMap>>,
40 short_message: bool,
41 ui_testing: bool,
42 ignored_directories_in_source_blocks: Vec<String>,
43 diagnostic_width: Option<usize>,
44 macro_backtrace: bool,
45 track_diagnostics: bool,
46 terminal_url: TerminalUrl,
47 theme: OutputTheme,
48 no_graphics: bool,
49}
50
51impl Debug for AnnotateSnippetEmitter {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 let AnnotateSnippetEmitter {
54 dst,
55 sm,
56 short_message,
57 ui_testing,
58 ignored_directories_in_source_blocks,
59 diagnostic_width,
60 macro_backtrace,
61 track_diagnostics,
62 terminal_url,
63 theme,
64 no_graphics,
65 } = self;
66
67 f.debug_struct("AnnotateSnippetEmitter")
68 .field("dst", &format_args!("<writer@{0:p}>", dst)format_args!("<writer@{dst:p}>"))
69 .field("sm", sm)
70 .field("short_message", short_message)
71 .field("ui_testing", ui_testing)
72 .field("ignored_directories_in_source_blocks", ignored_directories_in_source_blocks)
73 .field("diagnostic_width", diagnostic_width)
74 .field("macro_backtrace", macro_backtrace)
75 .field("track_diagnostics", track_diagnostics)
76 .field("terminal_url", terminal_url)
77 .field("theme", theme)
78 .field("no_graphics", no_graphics)
79 .finish()
80 }
81}
82
83impl Emitter for AnnotateSnippetEmitter {
84 fn emit_diagnostic(&mut self, mut diag: DiagInner) {
86 if self.track_diagnostics && diag.span.has_primary_spans() && !diag.span.is_dummy() {
87 diag.children.insert(0, diag.emitted_at_sub_diag());
88 }
89
90 let mut suggestions = diag.suggestions.unwrap_tag();
91 self.primary_span_formatted(&mut diag.span, &mut suggestions, &diag.args);
92
93 self.fix_multispans_in_extern_macros_and_render_macro_backtrace(
94 &mut diag.span,
95 &mut diag.children,
96 &diag.level,
97 self.macro_backtrace,
98 );
99
100 self.emit_messages_default(
101 &diag.level,
102 &diag.messages,
103 &diag.args,
104 &diag.code,
105 &diag.span,
106 &diag.children,
107 suggestions,
108 );
109 }
110
111 fn source_map(&self) -> Option<&SourceMap> {
112 self.sm.as_deref()
113 }
114
115 fn should_show_explain(&self) -> bool {
116 !self.short_message
117 }
118
119 fn supports_color(&self) -> bool {
120 false
121 }
122}
123
124fn annotation_level_for_level(level: Level) -> annotate_snippets::level::Level<'static> {
125 match level {
126 Level::Bug | Level::DelayedBug => {
127 annotate_snippets::Level::ERROR.with_name("error: internal compiler error")
128 }
129 Level::Fatal | Level::Error => annotate_snippets::level::ERROR,
130 Level::Warning(_) => annotate_snippets::Level::WARNING,
131 Level::Note => annotate_snippets::Level::NOTE,
132 Level::Help => annotate_snippets::Level::HELP,
133 Level::FailureNote => annotate_snippets::Level::NOTE.no_name(),
134 }
135}
136
137fn annotation_level_for_sublevel(level: Sublevel) -> annotate_snippets::level::Level<'static> {
138 match level {
139 Sublevel::Error => annotate_snippets::Level::ERROR,
140 Sublevel::Warning => annotate_snippets::Level::WARNING,
141 Sublevel::Note | Sublevel::OnceNote => annotate_snippets::Level::NOTE,
142 Sublevel::Help | Sublevel::OnceHelp => annotate_snippets::Level::HELP,
143 }
144}
145
146impl AnnotateSnippetEmitter {
147 pub fn new(dst: Destination) -> Self {
148 Self {
149 dst: IntoDynSyncSend(dst),
150 sm: None,
151 short_message: false,
152 ui_testing: false,
153 ignored_directories_in_source_blocks: Vec::new(),
154 diagnostic_width: None,
155 macro_backtrace: false,
156 track_diagnostics: false,
157 terminal_url: TerminalUrl::No,
158 theme: OutputTheme::Ascii,
159 no_graphics: false,
160 }
161 }
162
163 fn emit_messages_default(
164 &mut self,
165 level: &Level,
166 msgs: &[(DiagMessage, Style)],
167 args: &DiagArgMap,
168 code: &Option<ErrCode>,
169 msp: &MultiSpan,
170 children: &[Subdiag],
171 suggestions: Vec<CodeSuggestion>,
172 ) {
173 let renderer = self.renderer();
174 let annotation_level = annotation_level_for_level(*level);
175
176 let mut title = if msgs.iter().any(|(_, style)| style != &crate::Style::NoStyle) {
179 annotation_level.clone().secondary_title(self.pre_style_msgs(msgs, args))
180 } else {
181 annotation_level.clone().primary_title(format_diag_messages(msgs, args))
182 };
183
184 if let Some(c) = code {
185 title = title.id(c.to_string());
186 if let TerminalUrl::Yes = self.terminal_url {
187 title = title.id_url(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("https://doc.rust-lang.org/error_codes/{0}.html",
c))
})format!("https://doc.rust-lang.org/error_codes/{c}.html"));
188 }
189 }
190
191 let mut report = ::alloc::vec::Vec::new()vec![];
192 let mut group = Group::with_title(title);
193
194 let Some(sm) = self.sm.as_ref() else {
196 group = group.elements(children.iter().map(|c| {
197 let msg = format_diag_messages(&c.messages, args);
198 let level = annotation_level_for_sublevel(c.level);
199 level.message(msg)
200 }));
201
202 report.push(group);
203 if let Err(e) = emit_to_destination(
204 renderer.render(&report),
205 level,
206 &mut self.dst,
207 self.short_message,
208 ) {
209 {
::core::panicking::panic_fmt(format_args!("failed to emit error: {0}",
e));
};panic!("failed to emit error: {e}");
210 }
211 return;
212 };
213
214 let mut file_ann = collect_annotations(args, msp, sm);
215
216 let primary_span = msp.primary_span().unwrap_or_default();
218 if !primary_span.is_dummy() {
219 let primary_lo = sm.lookup_char_pos(primary_span.lo());
220 if let Ok(pos) = file_ann.binary_search_by(|(f, _)| f.name.cmp(&primary_lo.file.name)) {
221 file_ann.swap(0, pos);
222 }
223
224 let file_ann_len = file_ann.len();
225 for (file_idx, (file, annotations)) in file_ann.into_iter().enumerate() {
226 if should_show_source_code(&self.ignored_directories_in_source_blocks, sm, &file) {
227 if let Some(snippet) = self.annotated_snippet(annotations, &file.name, sm) {
228 group = group.element(snippet);
229 }
230 } else if !self.short_message {
232 group = self.unannotated_messages(
234 annotations,
235 &file.name,
236 sm,
237 file_idx,
238 &mut report,
239 group,
240 &annotation_level,
241 );
242 if let Some(c) = children.first()
251 && (!c.span.has_primary_spans() && !c.span.has_span_labels())
252 && file_idx == file_ann_len - 1
253 {
254 group = group.element(Padding);
255 }
256 }
257 }
258 }
259
260 for c in children {
261 let level = annotation_level_for_sublevel(c.level);
262
263 let msg = if c.messages.iter().any(|(_, style)| style != &crate::Style::NoStyle) {
266 self.pre_style_msgs(&c.messages, args)
267 } else {
268 format_diag_messages(&c.messages, args)
269 };
270
271 if !c.span.has_primary_spans() && !c.span.has_span_labels() {
273 group = group.element(level.clone().message(msg));
274 continue;
275 }
276
277 report.push(std::mem::replace(
278 &mut group,
279 Group::with_title(level.clone().secondary_title(msg)),
280 ));
281
282 let mut file_ann = collect_annotations(args, &c.span, sm);
283 let primary_span = c.span.primary_span().unwrap_or_default();
284 if !primary_span.is_dummy() {
285 let primary_lo = sm.lookup_char_pos(primary_span.lo());
286 if let Ok(pos) =
287 file_ann.binary_search_by(|(f, _)| f.name.cmp(&primary_lo.file.name))
288 {
289 file_ann.swap(0, pos);
290 }
291 }
292
293 for (file_idx, (file, annotations)) in file_ann.into_iter().enumerate() {
294 if should_show_source_code(&self.ignored_directories_in_source_blocks, sm, &file) {
295 if let Some(snippet) = self.annotated_snippet(annotations, &file.name, sm) {
296 group = group.element(snippet);
297 }
298 } else if !self.short_message {
300 group = self.unannotated_messages(
302 annotations,
303 &file.name,
304 sm,
305 file_idx,
306 &mut report,
307 group,
308 &level,
309 );
310 }
311 }
312 }
313
314 for suggestion in suggestions {
315 match suggestion.style {
316 SuggestionStyle::CompletelyHidden => {
317 }
319 SuggestionStyle::HideCodeAlways => {
320 let msg = format_diag_message(&suggestion.msg, args).into_owned();
321 group = group.element(annotate_snippets::Level::HELP.message(msg));
322 }
323 SuggestionStyle::HideCodeInline
324 | SuggestionStyle::ShowCode
325 | SuggestionStyle::ShowAlways => {
326 let substitutions = suggestion
327 .substitutions
328 .into_iter()
329 .filter(|subst| {
330 let invalid =
333 subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
334 if invalid {
335 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs:335",
"rustc_errors::annotate_snippet_emitter_writer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs"),
::tracing_core::__macro_support::Option::Some(335u32),
::tracing_core::__macro_support::Option::Some("rustc_errors::annotate_snippet_emitter_writer"),
::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!("suggestion contains an invalid span: {0:?}",
subst) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("suggestion contains an invalid span: {:?}", subst);
336 }
337 !invalid
338 })
339 .filter_map(|mut subst| {
340 subst.parts.sort_by_key(|part| part.span.lo());
343 if true {
{
match (&subst.parts.array_windows().find(|[a, b]|
a.span.overlaps(b.span)), &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("all spans must be disjoint")));
}
}
}
};
};debug_assert_eq!(
345 subst.parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
346 None,
347 "all spans must be disjoint",
348 );
349
350 let lo = subst.parts.iter().map(|part| part.span.lo()).min()?;
351 let lo_file = sm.lookup_source_file(lo);
352 let hi = subst.parts.iter().map(|part| part.span.hi()).max()?;
353 let hi_file = sm.lookup_source_file(hi);
354
355 if lo_file.stable_id != hi_file.stable_id {
357 return None;
358 }
359
360 if !sm.ensure_source_file_source_present(&lo_file) {
362 return None;
363 }
364
365 subst.parts.retain(|p| is_different(sm, &p.snippet, p.span));
369
370 if subst.parts.is_empty() { None } else { Some(subst) }
371 })
372 .collect::<Vec<_>>();
373
374 if substitutions.is_empty() {
375 continue;
376 }
377 let mut msg = format_diag_message(&suggestion.msg, args).to_string();
378
379 let lo = substitutions
380 .iter()
381 .find_map(|sub| sub.parts.first().map(|p| p.span.lo()))
382 .unwrap();
383 let file = sm.lookup_source_file(lo);
384
385 let filename =
386 sm.filename_for_diagnostics(&file.name).to_string_lossy().to_string();
387
388 let other_suggestions = substitutions.len().saturating_sub(MAX_SUGGESTIONS);
389
390 let subs = substitutions
391 .into_iter()
392 .take(MAX_SUGGESTIONS)
393 .filter_map(|sub| {
394 let mut confusion_type = ConfusionType::None;
395 for part in &sub.parts {
396 let part_confusion =
397 detect_confusion_type(sm, &part.snippet, part.span);
398 confusion_type = confusion_type.combine(part_confusion);
399 }
400
401 if !#[allow(non_exhaustive_omitted_patterns)] match confusion_type {
ConfusionType::None => true,
_ => false,
}matches!(confusion_type, ConfusionType::None) {
402 msg.push_str(confusion_type.label_text());
403 }
404
405 let mut parts = sub
406 .parts
407 .into_iter()
408 .filter_map(|p| {
409 if is_different(sm, &p.snippet, p.span) {
410 Some((p.span, p.snippet))
411 } else {
412 None
413 }
414 })
415 .collect::<Vec<_>>();
416
417 if parts.is_empty() {
418 None
419 } else {
420 let spans = parts.iter().map(|(span, _)| *span).collect::<Vec<_>>();
421 let fold = if let [(p, snippet)] = &mut parts[..]
428 && snippet.trim().starts_with("#[")
429 && snippet.trim().ends_with("]")
431 && snippet.ends_with('\n')
432 && p.hi() == p.lo()
433 && let Ok(b) = sm.span_to_prev_source(*p)
434 && let b = b.rsplit_once('\n').unwrap_or_else(|| ("", &b)).1
435 && b.trim().is_empty()
436 {
437 if !b.is_empty() && !snippet.ends_with(b) {
463 snippet.insert_str(0, b);
464 let offset = BytePos(b.len() as u32);
465 *p = p.with_lo(p.lo() - offset).shrink_to_lo();
466 }
467 false
468 } else {
469 true
470 };
471
472 if let Some((bounding_span, source, line_offset)) =
473 shrink_file(spans.as_slice(), &file.name, sm)
474 {
475 let adj_lo = bounding_span.lo().to_usize();
476 Some(
477 Snippet::source(source)
478 .line_start(line_offset)
479 .path(filename.clone())
480 .fold(fold)
481 .patches(parts.into_iter().map(
482 |(span, replacement)| {
483 let lo =
484 span.lo().to_usize().saturating_sub(adj_lo);
485 let hi =
486 span.hi().to_usize().saturating_sub(adj_lo);
487
488 Patch::new(lo..hi, replacement)
489 },
490 )),
491 )
492 } else {
493 None
494 }
495 }
496 })
497 .collect::<Vec<_>>();
498 if !subs.is_empty() {
499 report.push(std::mem::replace(
500 &mut group,
501 Group::with_title(annotate_snippets::Level::HELP.secondary_title(msg)),
502 ));
503
504 group = group.elements(subs);
505 if other_suggestions > 0 {
506 group = group.element(
507 annotate_snippets::Level::NOTE.no_name().message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("and {0} other candidate{1}",
other_suggestions,
if other_suggestions == 1 { "" } else { "s" }))
})format!(
508 "and {} other candidate{}",
509 other_suggestions,
510 pluralize!(other_suggestions)
511 )),
512 );
513 }
514 }
515 }
516 }
517 }
518
519 if !group.is_empty() {
520 report.push(group);
521 }
522 if let Err(e) =
523 emit_to_destination(renderer.render(&report), level, &mut self.dst, self.short_message)
524 {
525 {
::core::panicking::panic_fmt(format_args!("failed to emit error: {0}",
e));
};panic!("failed to emit error: {e}");
526 }
527 }
528
529 fn renderer(&self) -> Renderer {
530 let width = if let Some(width) = self.diagnostic_width {
531 width
532 } else if self.ui_testing || falsecfg!(miri) {
533 DEFAULT_TERM_WIDTH
534 } else {
535 termize::dimensions().map(|(w, _)| w).unwrap_or(DEFAULT_TERM_WIDTH)
536 };
537 let decor_style = match self.theme {
538 OutputTheme::Ascii => annotate_snippets::renderer::DecorStyle::Ascii,
539 OutputTheme::Unicode => annotate_snippets::renderer::DecorStyle::Unicode,
540 };
541
542 match self.dst.current_choice() {
543 ColorChoice::AlwaysAnsi | ColorChoice::Always | ColorChoice::Auto => Renderer::styled(),
544 ColorChoice::Never => Renderer::plain(),
545 }
546 .term_width(width)
547 .anonymized_snippet_line_numbers(self.ui_testing)
548 .decor_style(decor_style)
549 .short_message(self.short_message)
550 .no_graphics(self.no_graphics)
551 }
552
553 fn pre_style_msgs(&self, msgs: &[(DiagMessage, Style)], args: &DiagArgMap) -> String {
554 msgs.iter()
555 .filter_map(|(m, style)| {
556 let text = format_diag_message(m, args);
557 let style = style.anstyle();
558 if text.is_empty() { None } else { Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}{0:#}", style, text))
})format!("{style}{text}{style:#}")) }
559 })
560 .collect()
561 }
562
563 fn annotated_snippet<'a>(
564 &self,
565 annotations: Vec<Annotation>,
566 file_name: &FileName,
567 sm: &Arc<SourceMap>,
568 ) -> Option<Snippet<'a, annotate_snippets::Annotation<'a>>> {
569 let spans = annotations.iter().map(|a| a.span).collect::<Vec<_>>();
570 if let Some((bounding_span, source, offset_line)) = shrink_file(&spans, file_name, sm) {
571 let adj_lo = bounding_span.lo().to_usize();
572 let filename = sm.filename_for_diagnostics(file_name).to_string_lossy().to_string();
573 Some(Snippet::source(source).line_start(offset_line).path(filename).annotations(
574 annotations.into_iter().map(move |a| {
575 let lo = a.span.lo().to_usize().saturating_sub(adj_lo);
576 let hi = a.span.hi().to_usize().saturating_sub(adj_lo);
577 let ann = a.kind.span(lo..hi);
578 if let Some(label) = a.label { ann.label(label) } else { ann }
579 }),
580 ))
581 } else {
582 None
583 }
584 }
585
586 fn unannotated_messages<'a>(
587 &self,
588 annotations: Vec<Annotation>,
589 file_name: &FileName,
590 sm: &Arc<SourceMap>,
591 file_idx: usize,
592 report: &mut Vec<Group<'a>>,
593 mut group: Group<'a>,
594 level: &annotate_snippets::level::Level<'static>,
595 ) -> Group<'a> {
596 let filename = sm.filename_for_diagnostics(file_name).to_string_lossy().to_string();
597 let mut line_tracker = ::alloc::vec::Vec::new()vec![];
598 for (i, a) in annotations
599 .into_iter()
600 .filter(|a| !#[allow(non_exhaustive_omitted_patterns)] match a.kind {
AnnotationKind::Visible => true,
_ => false,
}matches!(a.kind, AnnotationKind::Visible))
601 .enumerate()
602 {
603 let lo = sm.lookup_char_pos(a.span.lo());
604 let hi = sm.lookup_char_pos(a.span.hi());
605 if i == 0 || (a.label.is_some()) {
606 if i == 0 && file_idx != 0 {
617 report.push(std::mem::replace(&mut group, Group::with_level(level.clone())));
618 }
619
620 if !line_tracker.contains(&lo.line) && (i == 0 || hi.line <= lo.line) {
621 line_tracker.push(lo.line);
622 group = group.element(
627 Origin::path(filename.clone())
628 .line(sm.doctest_offset_line(file_name, lo.line))
629 .char_column(lo.col_display),
630 );
631 }
632
633 if hi.line > lo.line
634 && a.label.as_ref().is_some_and(|l| !l.is_empty())
635 && !line_tracker.contains(&hi.line)
636 {
637 line_tracker.push(hi.line);
638 group = group.element(
643 Origin::path(filename.clone())
644 .line(sm.doctest_offset_line(file_name, hi.line))
645 .char_column(hi.col_display),
646 );
647 }
648
649 if let Some(label) = a.label
650 && !label.is_empty()
651 {
652 group = group
657 .element(Padding)
658 .element(annotate_snippets::Level::NOTE.message(label));
659 }
660 }
661 }
662 group
663 }
664}
665
666fn emit_to_destination(
667 rendered: String,
668 lvl: &Level,
669 dst: &mut Destination,
670 short_message: bool,
671) -> io::Result<()> {
672 use crate::lock;
673 let _buffer_lock = lock::acquire_global_lock("rustc_errors");
674 dst.write_fmt(format_args!("{0}\n", rendered))writeln!(dst, "{rendered}")?;
675 if !short_message && !lvl.is_failure_note() {
676 dst.write_fmt(format_args!("\n"))writeln!(dst)?;
677 }
678 dst.flush()?;
679 Ok(())
680}
681
682#[derive(#[automatically_derived]impl ::core::fmt::Debug for Annotation {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"Annotation kind span label", &self.kind, &self.span,
&&self.label)
}
}Debug)]
683struct Annotation {
684 kind: AnnotationKind,
685 span: Span,
686 label: Option<String>,
687}
688
689fn collect_annotations(
690 args: &DiagArgMap,
691 msp: &MultiSpan,
692 sm: &Arc<SourceMap>,
693) -> Vec<(Arc<SourceFile>, Vec<Annotation>)> {
694 let mut output: Vec<(Arc<SourceFile>, Vec<Annotation>)> = ::alloc::vec::Vec::new()vec![];
695
696 for SpanLabel { span, is_primary, label } in msp.span_labels() {
697 let span = match (span.is_dummy(), msp.primary_span()) {
700 (_, None) | (false, _) => span,
701 (true, Some(span)) => span,
702 };
703 let file = sm.lookup_source_file(span.lo());
704
705 let kind = if is_primary { AnnotationKind::Primary } else { AnnotationKind::Context };
706
707 let label = label.as_ref().map(|m| normalize_whitespace(&format_diag_message(m, args)));
708
709 let ann = Annotation { kind, span, label };
710 if sm.is_valid_span(ann.span).is_ok() {
711 if let Some((_, annotations)) =
716 output.iter_mut().find(|(f, _)| f.stable_id == file.stable_id)
717 {
718 annotations.push(ann);
719 } else {
720 output.push((file, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ann]))vec![ann]));
721 }
722 }
723 }
724
725 for span in msp.span_context() {
726 let file = sm.lookup_source_file(span.lo());
727 let ann = Annotation { kind: AnnotationKind::Visible, span: *span, label: None };
728 if let Some((_, annotations)) =
729 output.iter_mut().find(|(f, _)| f.stable_id == file.stable_id)
730 {
731 annotations.push(ann);
732 } else {
733 output.push((file, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ann]))vec![ann]));
734 }
735 }
736
737 for (_, ann) in output.iter_mut() {
739 ann.sort_by_key(|a| {
740 let lo = sm.lookup_char_pos(a.span.lo());
741 lo.line
742 });
743 }
744 output
745}
746
747fn shrink_file(
748 spans: &[Span],
749 file_name: &FileName,
750 sm: &Arc<SourceMap>,
751) -> Option<(Span, String, usize)> {
752 let lo_byte = spans.iter().map(|s| s.lo()).min()?;
753 let lo_loc = sm.lookup_char_pos(lo_byte);
754
755 let hi_byte = spans.iter().map(|s| s.hi()).max()?;
756 let hi_loc = sm.lookup_char_pos(hi_byte);
757
758 if lo_loc.file.stable_id != hi_loc.file.stable_id {
759 return None;
761 }
762
763 let lo = lo_loc.file.line_bounds(lo_loc.line.saturating_sub(1)).start;
764 let hi = hi_loc.file.line_bounds(hi_loc.line.saturating_sub(1)).end;
765
766 let bounding_span = Span::with_root_ctxt(lo, hi);
767 let source = sm.span_to_snippet(bounding_span).ok()?;
768 let offset_line = sm.doctest_offset_line(file_name, lo_loc.line);
769
770 Some((bounding_span, source, offset_line))
771}