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