rustc_errors/
annotate_snippet_emitter_writer.rs

1//! Emit diagnostics using the `annotate-snippets` library
2//!
3//! This is the equivalent of `./emitter.rs` but making use of the
4//! [`annotate-snippets`][annotate_snippets] library instead of building the output ourselves.
5//!
6//! [annotate_snippets]: https://docs.rs/crate/annotate-snippets/
7
8use std::borrow::Cow;
9use std::error::Report;
10use std::fmt::Debug;
11use std::io;
12use std::io::Write;
13use std::sync::Arc;
14
15use annotate_snippets::renderer::DEFAULT_TERM_WIDTH;
16use annotate_snippets::{AnnotationKind, Group, Origin, Padding, Patch, Renderer, Snippet};
17use anstream::ColorChoice;
18use derive_setters::Setters;
19use rustc_data_structures::sync::IntoDynSyncSend;
20use rustc_error_messages::{FluentArgs, SpanLabel};
21use rustc_lint_defs::pluralize;
22use rustc_span::source_map::SourceMap;
23use rustc_span::{BytePos, FileName, Pos, SourceFile, Span};
24use tracing::debug;
25
26use crate::emitter::{
27    ConfusionType, Destination, MAX_SUGGESTIONS, OutputTheme, detect_confusion_type, is_different,
28    normalize_whitespace, should_show_source_code,
29};
30use crate::registry::Registry;
31use crate::translation::{Translator, to_fluent_args};
32use crate::{
33    CodeSuggestion, DiagInner, DiagMessage, Emitter, ErrCode, Level, MultiSpan, Style, Subdiag,
34    SuggestionStyle, TerminalUrl,
35};
36
37/// Generates diagnostics using annotate-snippet
38#[derive(Setters)]
39pub struct AnnotateSnippetEmitter {
40    #[setters(skip)]
41    dst: IntoDynSyncSend<Destination>,
42    sm: Option<Arc<SourceMap>>,
43    #[setters(skip)]
44    translator: Translator,
45    short_message: bool,
46    ui_testing: bool,
47    ignored_directories_in_source_blocks: Vec<String>,
48    diagnostic_width: Option<usize>,
49
50    macro_backtrace: bool,
51    track_diagnostics: bool,
52    terminal_url: TerminalUrl,
53    theme: OutputTheme,
54}
55
56impl Debug for AnnotateSnippetEmitter {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("AnnotateSnippetEmitter")
59            .field("short_message", &self.short_message)
60            .field("ui_testing", &self.ui_testing)
61            .field(
62                "ignored_directories_in_source_blocks",
63                &self.ignored_directories_in_source_blocks,
64            )
65            .field("diagnostic_width", &self.diagnostic_width)
66            .field("macro_backtrace", &self.macro_backtrace)
67            .field("track_diagnostics", &self.track_diagnostics)
68            .field("terminal_url", &self.terminal_url)
69            .field("theme", &self.theme)
70            .finish()
71    }
72}
73
74impl Emitter for AnnotateSnippetEmitter {
75    /// The entry point for the diagnostics generation
76    fn emit_diagnostic(&mut self, mut diag: DiagInner, _registry: &Registry) {
77        let fluent_args = to_fluent_args(diag.args.iter());
78
79        if self.track_diagnostics && diag.span.has_primary_spans() && !diag.span.is_dummy() {
80            diag.children.insert(0, diag.emitted_at_sub_diag());
81        }
82
83        let mut suggestions = diag.suggestions.unwrap_tag();
84        self.primary_span_formatted(&mut diag.span, &mut suggestions, &fluent_args);
85
86        self.fix_multispans_in_extern_macros_and_render_macro_backtrace(
87            &mut diag.span,
88            &mut diag.children,
89            &diag.level,
90            self.macro_backtrace,
91        );
92
93        self.emit_messages_default(
94            &diag.level,
95            &diag.messages,
96            &fluent_args,
97            &diag.code,
98            &diag.span,
99            &diag.children,
100            suggestions,
101        );
102    }
103
104    fn source_map(&self) -> Option<&SourceMap> {
105        self.sm.as_deref()
106    }
107
108    fn should_show_explain(&self) -> bool {
109        !self.short_message
110    }
111
112    fn translator(&self) -> &Translator {
113        &self.translator
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 | Level::OnceNote => annotate_snippets::Level::NOTE,
129        Level::Help | Level::OnceHelp => annotate_snippets::Level::HELP,
130        Level::FailureNote => annotate_snippets::Level::NOTE.no_name(),
131        Level::Allow => panic!("Should not call with Allow"),
132        Level::Expect => panic!("Should not call with Expect"),
133    }
134}
135
136impl AnnotateSnippetEmitter {
137    pub fn new(dst: Destination, translator: Translator) -> Self {
138        Self {
139            dst: IntoDynSyncSend(dst),
140            sm: None,
141            translator,
142            short_message: false,
143            ui_testing: false,
144            ignored_directories_in_source_blocks: Vec::new(),
145            diagnostic_width: None,
146            macro_backtrace: false,
147            track_diagnostics: false,
148            terminal_url: TerminalUrl::No,
149            theme: OutputTheme::Ascii,
150        }
151    }
152
153    fn emit_messages_default(
154        &mut self,
155        level: &Level,
156        msgs: &[(DiagMessage, Style)],
157        args: &FluentArgs<'_>,
158        code: &Option<ErrCode>,
159        msp: &MultiSpan,
160        children: &[Subdiag],
161        suggestions: Vec<CodeSuggestion>,
162    ) {
163        let renderer = self.renderer();
164        let annotation_level = annotation_level_for_level(*level);
165
166        // If at least one portion of the message is styled, we need to
167        // "pre-style" the message
168        let mut title = if msgs.iter().any(|(_, style)| style != &crate::Style::NoStyle) {
169            annotation_level
170                .clone()
171                .secondary_title(Cow::Owned(self.pre_style_msgs(msgs, *level, args)))
172        } else {
173            annotation_level.clone().primary_title(self.translator.translate_messages(msgs, args))
174        };
175
176        if let Some(c) = code {
177            title = title.id(c.to_string());
178            if let TerminalUrl::Yes = self.terminal_url {
179                title = title.id_url(format!("https://doc.rust-lang.org/error_codes/{c}.html"));
180            }
181        }
182
183        let mut report = vec![];
184        let mut group = Group::with_title(title);
185
186        // If we don't have span information, emit and exit
187        let Some(sm) = self.sm.as_ref() else {
188            group = group.elements(children.iter().map(|c| {
189                let msg = self.translator.translate_messages(&c.messages, args).to_string();
190                let level = annotation_level_for_level(c.level);
191                level.message(msg)
192            }));
193
194            report.push(group);
195            if let Err(e) = emit_to_destination(
196                renderer.render(&report),
197                level,
198                &mut self.dst,
199                self.short_message,
200            ) {
201                panic!("failed to emit error: {e}");
202            }
203            return;
204        };
205
206        let mut file_ann = collect_annotations(args, msp, sm, &self.translator);
207
208        // Make sure our primary file comes first
209        let primary_span = msp.primary_span().unwrap_or_default();
210        if !primary_span.is_dummy() {
211            let primary_lo = sm.lookup_char_pos(primary_span.lo());
212            if let Ok(pos) = file_ann.binary_search_by(|(f, _)| f.name.cmp(&primary_lo.file.name)) {
213                file_ann.swap(0, pos);
214            }
215
216            for (file_idx, (file, annotations)) in file_ann.into_iter().enumerate() {
217                if should_show_source_code(&self.ignored_directories_in_source_blocks, sm, &file) {
218                    if let Some(snippet) = self.annotated_snippet(annotations, &file.name, sm) {
219                        group = group.element(snippet);
220                    }
221                // we can't annotate anything if the source is unavailable.
222                } else if !self.short_message {
223                    // We'll just print unannotated messages
224                    group = self.unannotated_messages(
225                        annotations,
226                        &file.name,
227                        sm,
228                        file_idx,
229                        &mut report,
230                        group,
231                        &annotation_level,
232                    );
233                    // If this is the last annotation for a file, and
234                    // this is the last file, and the first child is a
235                    // "secondary" message, we need to add padding
236                    // ╭▸ /rustc/FAKE_PREFIX/library/core/src/clone.rs:236:13
237                    // │
238                    // ├ note: the late bound lifetime parameter
239                    // │ (<- It adds *this*)
240                    // ╰ warning: this was previously accepted
241                    if let Some(c) = children.first()
242                        && (!c.span.has_primary_spans() && !c.span.has_span_labels())
243                    {
244                        group = group.element(Padding);
245                    }
246                }
247            }
248        }
249
250        for c in children {
251            let level = annotation_level_for_level(c.level);
252
253            // If at least one portion of the message is styled, we need to
254            // "pre-style" the message
255            let msg = if c.messages.iter().any(|(_, style)| style != &crate::Style::NoStyle) {
256                Cow::Owned(self.pre_style_msgs(&c.messages, c.level, args))
257            } else {
258                self.translator.translate_messages(&c.messages, args)
259            };
260
261            // This is a secondary message with no span info
262            if !c.span.has_primary_spans() && !c.span.has_span_labels() {
263                group = group.element(level.clone().message(msg));
264                continue;
265            }
266
267            report.push(std::mem::replace(
268                &mut group,
269                Group::with_title(level.clone().secondary_title(msg)),
270            ));
271
272            let mut file_ann = collect_annotations(args, &c.span, sm, &self.translator);
273            let primary_span = c.span.primary_span().unwrap_or_default();
274            if !primary_span.is_dummy() {
275                let primary_lo = sm.lookup_char_pos(primary_span.lo());
276                if let Ok(pos) =
277                    file_ann.binary_search_by(|(f, _)| f.name.cmp(&primary_lo.file.name))
278                {
279                    file_ann.swap(0, pos);
280                }
281            }
282
283            for (file_idx, (file, annotations)) in file_ann.into_iter().enumerate() {
284                if should_show_source_code(&self.ignored_directories_in_source_blocks, sm, &file) {
285                    if let Some(snippet) = self.annotated_snippet(annotations, &file.name, sm) {
286                        group = group.element(snippet);
287                    }
288                // we can't annotate anything if the source is unavailable.
289                } else if !self.short_message {
290                    // We'll just print unannotated messages
291                    group = self.unannotated_messages(
292                        annotations,
293                        &file.name,
294                        sm,
295                        file_idx,
296                        &mut report,
297                        group,
298                        &level,
299                    );
300                }
301            }
302        }
303
304        let suggestions_expected = suggestions
305            .iter()
306            .filter(|s| {
307                matches!(
308                    s.style,
309                    SuggestionStyle::HideCodeInline
310                        | SuggestionStyle::ShowCode
311                        | SuggestionStyle::ShowAlways
312                )
313            })
314            .count();
315        for suggestion in suggestions {
316            match suggestion.style {
317                SuggestionStyle::CompletelyHidden => {
318                    // do not display this suggestion, it is meant only for tools
319                }
320                SuggestionStyle::HideCodeAlways => {
321                    let msg = self
322                        .translator
323                        .translate_messages(&[(suggestion.msg.to_owned(), Style::HeaderMsg)], args);
324                    group = group.element(annotate_snippets::Level::HELP.message(msg));
325                }
326                SuggestionStyle::HideCodeInline
327                | SuggestionStyle::ShowCode
328                | SuggestionStyle::ShowAlways => {
329                    let substitutions = suggestion
330                        .substitutions
331                        .into_iter()
332                        .filter(|subst| {
333                            // Suggestions coming from macros can have malformed spans. This is a heavy
334                            // handed approach to avoid ICEs by ignoring the suggestion outright.
335                            let invalid =
336                                subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
337                            if invalid {
338                                debug!("suggestion contains an invalid span: {:?}", subst);
339                            }
340                            !invalid
341                        })
342                        .filter_map(|mut subst| {
343                            // Assumption: all spans are in the same file, and all spans
344                            // are disjoint. Sort in ascending order.
345                            subst.parts.sort_by_key(|part| part.span.lo());
346                            // Verify the assumption that all spans are disjoint
347                            debug_assert_eq!(
348                                subst.parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
349                                None,
350                                "all spans must be disjoint",
351                            );
352
353                            // Account for cases where we are suggesting the same code that's already
354                            // there. This shouldn't happen often, but in some cases for multipart
355                            // suggestions it's much easier to handle it here than in the origin.
356                            subst.parts.retain(|p| is_different(sm, &p.snippet, p.span));
357
358                            let item_span = subst.parts.first()?;
359                            let file = sm.lookup_source_file(item_span.span.lo());
360                            if should_show_source_code(
361                                &self.ignored_directories_in_source_blocks,
362                                sm,
363                                &file,
364                            ) {
365                                Some(subst)
366                            } else {
367                                None
368                            }
369                        })
370                        .collect::<Vec<_>>();
371
372                    if substitutions.is_empty() {
373                        continue;
374                    }
375                    let mut msg = self
376                        .translator
377                        .translate_message(&suggestion.msg, args)
378                        .map_err(Report::new)
379                        .unwrap()
380                        .to_string();
381
382                    let lo = substitutions
383                        .iter()
384                        .find_map(|sub| sub.parts.first().map(|p| p.span.lo()))
385                        .unwrap();
386                    let file = sm.lookup_source_file(lo);
387
388                    let filename =
389                        sm.filename_for_diagnostics(&file.name).to_string_lossy().to_string();
390
391                    let other_suggestions = substitutions.len().saturating_sub(MAX_SUGGESTIONS);
392
393                    let subs = substitutions
394                        .into_iter()
395                        .take(MAX_SUGGESTIONS)
396                        .filter_map(|sub| {
397                            let mut confusion_type = ConfusionType::None;
398                            for part in &sub.parts {
399                                let part_confusion =
400                                    detect_confusion_type(sm, &part.snippet, part.span);
401                                confusion_type = confusion_type.combine(part_confusion);
402                            }
403
404                            if !matches!(confusion_type, ConfusionType::None) {
405                                msg.push_str(confusion_type.label_text());
406                            }
407
408                            let mut parts = sub
409                                .parts
410                                .into_iter()
411                                .filter_map(|p| {
412                                    if is_different(sm, &p.snippet, p.span) {
413                                        Some((p.span, p.snippet))
414                                    } else {
415                                        None
416                                    }
417                                })
418                                .collect::<Vec<_>>();
419
420                            if parts.is_empty() {
421                                None
422                            } else {
423                                let spans = parts.iter().map(|(span, _)| *span).collect::<Vec<_>>();
424                                // The suggestion adds an entire line of code, ending on a newline, so we'll also
425                                // print the *following* line, to provide context of what we're advising people to
426                                // do. Otherwise you would only see contextless code that can be confused for
427                                // already existing code, despite the colors and UI elements.
428                                // We special case `#[derive(_)]\n` and other attribute suggestions, because those
429                                // are the ones where context is most useful.
430                                let fold = if let [(p, snippet)] = &mut parts[..]
431                                    && snippet.trim().starts_with("#[")
432                                    // This allows for spaces to come between the attribute and the newline
433                                    && snippet.trim().ends_with("]")
434                                    && snippet.ends_with('\n')
435                                    && p.hi() == p.lo()
436                                    && let Ok(b) = sm.span_to_prev_source(*p)
437                                    && let b = b.rsplit_once('\n').unwrap_or_else(|| ("", &b)).1
438                                    && b.trim().is_empty()
439                                {
440                                    // FIXME: This is a hack:
441                                    // The span for attribute suggestions often times points to the
442                                    // beginning of an item, disregarding leading whitespace. This
443                                    // causes the attribute to be properly indented, but leaves original
444                                    // item without indentation when rendered.
445                                    // This fixes that problem by adjusting the span to point to the start
446                                    // of the whitespace, and adds the whitespace to the replacement.
447                                    //
448                                    // Source: "    extern "custom" fn negate(a: i64) -> i64 {\n"
449                                    // Span: 4..4
450                                    // Replacement: "#[unsafe(naked)]\n"
451                                    //
452                                    // Before:
453                                    // help: convert this to an `#[unsafe(naked)]` function
454                                    //    |
455                                    // LL +     #[unsafe(naked)]
456                                    // LL | extern "custom" fn negate(a: i64) -> i64 {
457                                    //    |
458                                    //
459                                    // After
460                                    // help: convert this to an `#[unsafe(naked)]` function
461                                    //    |
462                                    // LL +     #[unsafe(naked)]
463                                    // LL |     extern "custom" fn negate(a: i64) -> i64 {
464                                    //    |
465                                    if !b.is_empty() && !snippet.ends_with(b) {
466                                        snippet.insert_str(0, b);
467                                        let offset = BytePos(b.len() as u32);
468                                        *p = p.with_lo(p.lo() - offset).shrink_to_lo();
469                                    }
470                                    false
471                                } else {
472                                    true
473                                };
474
475                                if let Some((bounding_span, source, line_offset)) =
476                                    shrink_file(spans.as_slice(), &file.name, sm)
477                                {
478                                    let adj_lo = bounding_span.lo().to_usize();
479                                    Some(
480                                        Snippet::source(source)
481                                            .line_start(line_offset)
482                                            .path(filename.clone())
483                                            .fold(fold)
484                                            .patches(parts.into_iter().map(
485                                                |(span, replacement)| {
486                                                    let lo =
487                                                        span.lo().to_usize().saturating_sub(adj_lo);
488                                                    let hi =
489                                                        span.hi().to_usize().saturating_sub(adj_lo);
490
491                                                    Patch::new(lo..hi, replacement)
492                                                },
493                                            )),
494                                    )
495                                } else {
496                                    None
497                                }
498                            }
499                        })
500                        .collect::<Vec<_>>();
501                    if !subs.is_empty() {
502                        report.push(std::mem::replace(
503                            &mut group,
504                            Group::with_title(annotate_snippets::Level::HELP.secondary_title(msg)),
505                        ));
506
507                        group = group.elements(subs);
508                        if other_suggestions > 0 {
509                            group = group.element(
510                                annotate_snippets::Level::NOTE.no_name().message(format!(
511                                    "and {} other candidate{}",
512                                    other_suggestions,
513                                    pluralize!(other_suggestions)
514                                )),
515                            );
516                        }
517                    }
518                }
519            }
520        }
521
522        // FIXME: This hack should be removed once annotate_snippets is the
523        // default emitter.
524        if suggestions_expected > 0 && report.is_empty() {
525            group = group.element(Padding);
526        }
527
528        if !group.is_empty() {
529            report.push(group);
530        }
531        if let Err(e) =
532            emit_to_destination(renderer.render(&report), level, &mut self.dst, self.short_message)
533        {
534            panic!("failed to emit error: {e}");
535        }
536    }
537
538    fn renderer(&self) -> Renderer {
539        let width = if let Some(width) = self.diagnostic_width {
540            width
541        } else if self.ui_testing || cfg!(miri) {
542            DEFAULT_TERM_WIDTH
543        } else {
544            termize::dimensions().map(|(w, _)| w).unwrap_or(DEFAULT_TERM_WIDTH)
545        };
546        let decor_style = match self.theme {
547            OutputTheme::Ascii => annotate_snippets::renderer::DecorStyle::Ascii,
548            OutputTheme::Unicode => annotate_snippets::renderer::DecorStyle::Unicode,
549        };
550
551        match self.dst.current_choice() {
552            ColorChoice::AlwaysAnsi | ColorChoice::Always | ColorChoice::Auto => Renderer::styled(),
553            ColorChoice::Never => Renderer::plain(),
554        }
555        .term_width(width)
556        .anonymized_line_numbers(self.ui_testing)
557        .decor_style(decor_style)
558        .short_message(self.short_message)
559    }
560
561    fn pre_style_msgs(
562        &self,
563        msgs: &[(DiagMessage, Style)],
564        level: Level,
565        args: &FluentArgs<'_>,
566    ) -> String {
567        msgs.iter()
568            .filter_map(|(m, style)| {
569                let text = self.translator.translate_message(m, args).map_err(Report::new).unwrap();
570                let style = style.anstyle(level);
571                if text.is_empty() { None } else { Some(format!("{style}{text}{style:#}")) }
572            })
573            .collect()
574    }
575
576    fn annotated_snippet<'a>(
577        &self,
578        annotations: Vec<Annotation>,
579        file_name: &FileName,
580        sm: &Arc<SourceMap>,
581    ) -> Option<Snippet<'a, annotate_snippets::Annotation<'a>>> {
582        let spans = annotations.iter().map(|a| a.span).collect::<Vec<_>>();
583        if let Some((bounding_span, source, offset_line)) = shrink_file(&spans, file_name, sm) {
584            let adj_lo = bounding_span.lo().to_usize();
585            let filename = sm.filename_for_diagnostics(file_name).to_string_lossy().to_string();
586            Some(Snippet::source(source).line_start(offset_line).path(filename).annotations(
587                annotations.into_iter().map(move |a| {
588                    let lo = a.span.lo().to_usize().saturating_sub(adj_lo);
589                    let hi = a.span.hi().to_usize().saturating_sub(adj_lo);
590                    let ann = a.kind.span(lo..hi);
591                    if let Some(label) = a.label { ann.label(label) } else { ann }
592                }),
593            ))
594        } else {
595            None
596        }
597    }
598
599    fn unannotated_messages<'a>(
600        &self,
601        annotations: Vec<Annotation>,
602        file_name: &FileName,
603        sm: &Arc<SourceMap>,
604        file_idx: usize,
605        report: &mut Vec<Group<'a>>,
606        mut group: Group<'a>,
607        level: &annotate_snippets::level::Level<'static>,
608    ) -> Group<'a> {
609        let filename = sm.filename_for_diagnostics(file_name).to_string_lossy().to_string();
610        let mut line_tracker = vec![];
611        for (i, a) in annotations.into_iter().enumerate() {
612            let lo = sm.lookup_char_pos(a.span.lo());
613            let hi = sm.lookup_char_pos(a.span.hi());
614            if i == 0 || (a.label.is_some()) {
615                // Render each new file after the first in its own Group
616                //    ╭▸ $DIR/deriving-meta-unknown-trait.rs:1:10
617                //    │
618                // LL │ #[derive(Eqr)]
619                //    │          ━━━
620                //    ╰╴ (<- It makes it so *this* will get printed)
621                //    ╭▸ $SRC_DIR/core/src/option.rs:594:0
622                //    ⸬  $SRC_DIR/core/src/option.rs:602:4
623                //    │
624                //    ╰ note: not covered
625                if i == 0 && file_idx != 0 {
626                    report.push(std::mem::replace(&mut group, Group::with_level(level.clone())));
627                }
628
629                if !line_tracker.contains(&lo.line) {
630                    line_tracker.push(lo.line);
631                    // ╭▸ $SRC_DIR/core/src/option.rs:594:0 (<- It adds *this*)
632                    // ⸬  $SRC_DIR/core/src/option.rs:602:4
633                    // │
634                    // ╰ note: not covered
635                    group = group.element(
636                        Origin::path(filename.clone())
637                            .line(sm.doctest_offset_line(file_name, lo.line))
638                            .char_column(lo.col_display),
639                    );
640                }
641
642                if hi.line > lo.line
643                    && a.label.as_ref().is_some_and(|l| !l.is_empty())
644                    && !line_tracker.contains(&hi.line)
645                {
646                    line_tracker.push(hi.line);
647                    // ╭▸ $SRC_DIR/core/src/option.rs:594:0
648                    // ⸬  $SRC_DIR/core/src/option.rs:602:4 (<- It adds *this*)
649                    // │
650                    // ╰ note: not covered
651                    group = group.element(
652                        Origin::path(filename.clone())
653                            .line(sm.doctest_offset_line(file_name, hi.line))
654                            .char_column(hi.col_display),
655                    );
656                }
657
658                if let Some(label) = a.label
659                    && !label.is_empty()
660                {
661                    // ╭▸ $SRC_DIR/core/src/option.rs:594:0
662                    // ⸬  $SRC_DIR/core/src/option.rs:602:4
663                    // │ (<- It adds *this*)
664                    // ╰ note: not covered (<- and *this*)
665                    group = group
666                        .element(Padding)
667                        .element(annotate_snippets::Level::NOTE.message(label));
668                }
669            }
670        }
671        group
672    }
673}
674
675fn emit_to_destination(
676    rendered: String,
677    lvl: &Level,
678    dst: &mut Destination,
679    short_message: bool,
680) -> io::Result<()> {
681    use crate::lock;
682    let _buffer_lock = lock::acquire_global_lock("rustc_errors");
683    writeln!(dst, "{rendered}")?;
684    if !short_message && !lvl.is_failure_note() {
685        writeln!(dst)?;
686    }
687    dst.flush()?;
688    Ok(())
689}
690
691#[derive(Debug)]
692struct Annotation {
693    kind: AnnotationKind,
694    span: Span,
695    label: Option<String>,
696}
697
698fn collect_annotations(
699    args: &FluentArgs<'_>,
700    msp: &MultiSpan,
701    sm: &Arc<SourceMap>,
702    translator: &Translator,
703) -> Vec<(Arc<SourceFile>, Vec<Annotation>)> {
704    let mut output: Vec<(Arc<SourceFile>, Vec<Annotation>)> = vec![];
705
706    for SpanLabel { span, is_primary, label } in msp.span_labels() {
707        // If we don't have a useful span, pick the primary span if that exists.
708        // Worst case we'll just print an error at the top of the main file.
709        let span = match (span.is_dummy(), msp.primary_span()) {
710            (_, None) | (false, _) => span,
711            (true, Some(span)) => span,
712        };
713        let file = sm.lookup_source_file(span.lo());
714
715        let kind = if is_primary { AnnotationKind::Primary } else { AnnotationKind::Context };
716
717        let label = label.as_ref().map(|m| {
718            normalize_whitespace(
719                &translator.translate_message(m, args).map_err(Report::new).unwrap(),
720            )
721        });
722
723        let ann = Annotation { kind, span, label };
724        if sm.is_valid_span(ann.span).is_ok() {
725            // Look through each of our files for the one we're adding to. We
726            // use each files `stable_id` to avoid issues with file name
727            // collisions when multiple versions of the same crate are present
728            // in the dependency graph
729            if let Some((_, annotations)) =
730                output.iter_mut().find(|(f, _)| f.stable_id == file.stable_id)
731            {
732                annotations.push(ann);
733            } else {
734                output.push((file, vec![ann]));
735            }
736        }
737    }
738    output
739}
740
741fn shrink_file(
742    spans: &[Span],
743    file_name: &FileName,
744    sm: &Arc<SourceMap>,
745) -> Option<(Span, String, usize)> {
746    let lo_byte = spans.iter().map(|s| s.lo()).min()?;
747    let lo_loc = sm.lookup_char_pos(lo_byte);
748    let lo = lo_loc.file.line_bounds(lo_loc.line.saturating_sub(1)).start;
749
750    let hi_byte = spans.iter().map(|s| s.hi()).max()?;
751    let hi_loc = sm.lookup_char_pos(hi_byte);
752    let hi = lo_loc.file.line_bounds(hi_loc.line.saturating_sub(1)).end;
753
754    let bounding_span = Span::with_root_ctxt(lo, hi);
755    let source = sm.span_to_snippet(bounding_span).unwrap_or_default();
756    let offset_line = sm.doctest_offset_line(file_name, lo_loc.line);
757
758    Some((bounding_span, source, offset_line))
759}