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            let file_ann_len = file_ann.len();
217            for (file_idx, (file, annotations)) in file_ann.into_iter().enumerate() {
218                if should_show_source_code(&self.ignored_directories_in_source_blocks, sm, &file) {
219                    if let Some(snippet) = self.annotated_snippet(annotations, &file.name, sm) {
220                        group = group.element(snippet);
221                    }
222                // we can't annotate anything if the source is unavailable.
223                } else if !self.short_message {
224                    // We'll just print unannotated messages
225                    group = self.unannotated_messages(
226                        annotations,
227                        &file.name,
228                        sm,
229                        file_idx,
230                        &mut report,
231                        group,
232                        &annotation_level,
233                    );
234                    // If this is the last annotation for a file, and
235                    // this is the last file, and the first child is a
236                    // "secondary" message, we need to add padding
237                    // ╭▸ /rustc/FAKE_PREFIX/library/core/src/clone.rs:236:13
238                    // │
239                    // ├ note: the late bound lifetime parameter
240                    // │ (<- It adds *this*)
241                    // ╰ warning: this was previously accepted
242                    if let Some(c) = children.first()
243                        && (!c.span.has_primary_spans() && !c.span.has_span_labels())
244                        && file_idx == file_ann_len - 1
245                    {
246                        group = group.element(Padding);
247                    }
248                }
249            }
250        }
251
252        for c in children {
253            let level = annotation_level_for_level(c.level);
254
255            // If at least one portion of the message is styled, we need to
256            // "pre-style" the message
257            let msg = if c.messages.iter().any(|(_, style)| style != &crate::Style::NoStyle) {
258                Cow::Owned(self.pre_style_msgs(&c.messages, c.level, args))
259            } else {
260                self.translator.translate_messages(&c.messages, args)
261            };
262
263            // This is a secondary message with no span info
264            if !c.span.has_primary_spans() && !c.span.has_span_labels() {
265                group = group.element(level.clone().message(msg));
266                continue;
267            }
268
269            report.push(std::mem::replace(
270                &mut group,
271                Group::with_title(level.clone().secondary_title(msg)),
272            ));
273
274            let mut file_ann = collect_annotations(args, &c.span, sm, &self.translator);
275            let primary_span = c.span.primary_span().unwrap_or_default();
276            if !primary_span.is_dummy() {
277                let primary_lo = sm.lookup_char_pos(primary_span.lo());
278                if let Ok(pos) =
279                    file_ann.binary_search_by(|(f, _)| f.name.cmp(&primary_lo.file.name))
280                {
281                    file_ann.swap(0, pos);
282                }
283            }
284
285            for (file_idx, (file, annotations)) in file_ann.into_iter().enumerate() {
286                if should_show_source_code(&self.ignored_directories_in_source_blocks, sm, &file) {
287                    if let Some(snippet) = self.annotated_snippet(annotations, &file.name, sm) {
288                        group = group.element(snippet);
289                    }
290                // we can't annotate anything if the source is unavailable.
291                } else if !self.short_message {
292                    // We'll just print unannotated messages
293                    group = self.unannotated_messages(
294                        annotations,
295                        &file.name,
296                        sm,
297                        file_idx,
298                        &mut report,
299                        group,
300                        &level,
301                    );
302                }
303            }
304        }
305
306        for suggestion in suggestions {
307            match suggestion.style {
308                SuggestionStyle::CompletelyHidden => {
309                    // do not display this suggestion, it is meant only for tools
310                }
311                SuggestionStyle::HideCodeAlways => {
312                    let msg = self
313                        .translator
314                        .translate_messages(&[(suggestion.msg.to_owned(), Style::HeaderMsg)], args);
315                    group = group.element(annotate_snippets::Level::HELP.message(msg));
316                }
317                SuggestionStyle::HideCodeInline
318                | SuggestionStyle::ShowCode
319                | SuggestionStyle::ShowAlways => {
320                    let substitutions = suggestion
321                        .substitutions
322                        .into_iter()
323                        .filter(|subst| {
324                            // Suggestions coming from macros can have malformed spans. This is a heavy
325                            // handed approach to avoid ICEs by ignoring the suggestion outright.
326                            let invalid =
327                                subst.parts.iter().any(|item| sm.is_valid_span(item.span).is_err());
328                            if invalid {
329                                debug!("suggestion contains an invalid span: {:?}", subst);
330                            }
331                            !invalid
332                        })
333                        .filter_map(|mut subst| {
334                            // Assumption: all spans are in the same file, and all spans
335                            // are disjoint. Sort in ascending order.
336                            subst.parts.sort_by_key(|part| part.span.lo());
337                            // Verify the assumption that all spans are disjoint
338                            debug_assert_eq!(
339                                subst.parts.array_windows().find(|[a, b]| a.span.overlaps(b.span)),
340                                None,
341                                "all spans must be disjoint",
342                            );
343
344                            let lo = subst.parts.iter().map(|part| part.span.lo()).min()?;
345                            let lo_file = sm.lookup_source_file(lo);
346                            let hi = subst.parts.iter().map(|part| part.span.hi()).max()?;
347                            let hi_file = sm.lookup_source_file(hi);
348
349                            // The different spans might belong to different contexts, if so ignore suggestion.
350                            if lo_file.stable_id != hi_file.stable_id {
351                                return None;
352                            }
353
354                            // We can't splice anything if the source is unavailable.
355                            if !sm.ensure_source_file_source_present(&lo_file) {
356                                return None;
357                            }
358
359                            // Account for cases where we are suggesting the same code that's already
360                            // there. This shouldn't happen often, but in some cases for multipart
361                            // suggestions it's much easier to handle it here than in the origin.
362                            subst.parts.retain(|p| is_different(sm, &p.snippet, p.span));
363
364                            if subst.parts.is_empty() { None } else { Some(subst) }
365                        })
366                        .collect::<Vec<_>>();
367
368                    if substitutions.is_empty() {
369                        continue;
370                    }
371                    let mut msg = self
372                        .translator
373                        .translate_message(&suggestion.msg, args)
374                        .map_err(Report::new)
375                        .unwrap()
376                        .to_string();
377
378                    let lo = substitutions
379                        .iter()
380                        .find_map(|sub| sub.parts.first().map(|p| p.span.lo()))
381                        .unwrap();
382                    let file = sm.lookup_source_file(lo);
383
384                    let filename =
385                        sm.filename_for_diagnostics(&file.name).to_string_lossy().to_string();
386
387                    let other_suggestions = substitutions.len().saturating_sub(MAX_SUGGESTIONS);
388
389                    let subs = substitutions
390                        .into_iter()
391                        .take(MAX_SUGGESTIONS)
392                        .filter_map(|sub| {
393                            let mut confusion_type = ConfusionType::None;
394                            for part in &sub.parts {
395                                let part_confusion =
396                                    detect_confusion_type(sm, &part.snippet, part.span);
397                                confusion_type = confusion_type.combine(part_confusion);
398                            }
399
400                            if !matches!(confusion_type, ConfusionType::None) {
401                                msg.push_str(confusion_type.label_text());
402                            }
403
404                            let mut parts = sub
405                                .parts
406                                .into_iter()
407                                .filter_map(|p| {
408                                    if is_different(sm, &p.snippet, p.span) {
409                                        Some((p.span, p.snippet))
410                                    } else {
411                                        None
412                                    }
413                                })
414                                .collect::<Vec<_>>();
415
416                            if parts.is_empty() {
417                                None
418                            } else {
419                                let spans = parts.iter().map(|(span, _)| *span).collect::<Vec<_>>();
420                                // The suggestion adds an entire line of code, ending on a newline, so we'll also
421                                // print the *following* line, to provide context of what we're advising people to
422                                // do. Otherwise you would only see contextless code that can be confused for
423                                // already existing code, despite the colors and UI elements.
424                                // We special case `#[derive(_)]\n` and other attribute suggestions, because those
425                                // are the ones where context is most useful.
426                                let fold = if let [(p, snippet)] = &mut parts[..]
427                                    && snippet.trim().starts_with("#[")
428                                    // This allows for spaces to come between the attribute and the newline
429                                    && snippet.trim().ends_with("]")
430                                    && snippet.ends_with('\n')
431                                    && p.hi() == p.lo()
432                                    && let Ok(b) = sm.span_to_prev_source(*p)
433                                    && let b = b.rsplit_once('\n').unwrap_or_else(|| ("", &b)).1
434                                    && b.trim().is_empty()
435                                {
436                                    // FIXME: This is a hack:
437                                    // The span for attribute suggestions often times points to the
438                                    // beginning of an item, disregarding leading whitespace. This
439                                    // causes the attribute to be properly indented, but leaves original
440                                    // item without indentation when rendered.
441                                    // This fixes that problem by adjusting the span to point to the start
442                                    // of the whitespace, and adds the whitespace to the replacement.
443                                    //
444                                    // Source: "    extern "custom" fn negate(a: i64) -> i64 {\n"
445                                    // Span: 4..4
446                                    // Replacement: "#[unsafe(naked)]\n"
447                                    //
448                                    // Before:
449                                    // help: convert this to an `#[unsafe(naked)]` function
450                                    //    |
451                                    // LL +     #[unsafe(naked)]
452                                    // LL | extern "custom" fn negate(a: i64) -> i64 {
453                                    //    |
454                                    //
455                                    // After
456                                    // help: convert this to an `#[unsafe(naked)]` function
457                                    //    |
458                                    // LL +     #[unsafe(naked)]
459                                    // LL |     extern "custom" fn negate(a: i64) -> i64 {
460                                    //    |
461                                    if !b.is_empty() && !snippet.ends_with(b) {
462                                        snippet.insert_str(0, b);
463                                        let offset = BytePos(b.len() as u32);
464                                        *p = p.with_lo(p.lo() - offset).shrink_to_lo();
465                                    }
466                                    false
467                                } else {
468                                    true
469                                };
470
471                                if let Some((bounding_span, source, line_offset)) =
472                                    shrink_file(spans.as_slice(), &file.name, sm)
473                                {
474                                    let adj_lo = bounding_span.lo().to_usize();
475                                    Some(
476                                        Snippet::source(source)
477                                            .line_start(line_offset)
478                                            .path(filename.clone())
479                                            .fold(fold)
480                                            .patches(parts.into_iter().map(
481                                                |(span, replacement)| {
482                                                    let lo =
483                                                        span.lo().to_usize().saturating_sub(adj_lo);
484                                                    let hi =
485                                                        span.hi().to_usize().saturating_sub(adj_lo);
486
487                                                    Patch::new(lo..hi, replacement)
488                                                },
489                                            )),
490                                    )
491                                } else {
492                                    None
493                                }
494                            }
495                        })
496                        .collect::<Vec<_>>();
497                    if !subs.is_empty() {
498                        report.push(std::mem::replace(
499                            &mut group,
500                            Group::with_title(annotate_snippets::Level::HELP.secondary_title(msg)),
501                        ));
502
503                        group = group.elements(subs);
504                        if other_suggestions > 0 {
505                            group = group.element(
506                                annotate_snippets::Level::NOTE.no_name().message(format!(
507                                    "and {} other candidate{}",
508                                    other_suggestions,
509                                    pluralize!(other_suggestions)
510                                )),
511                            );
512                        }
513                    }
514                }
515            }
516        }
517
518        if !group.is_empty() {
519            report.push(group);
520        }
521        if let Err(e) =
522            emit_to_destination(renderer.render(&report), level, &mut self.dst, self.short_message)
523        {
524            panic!("failed to emit error: {e}");
525        }
526    }
527
528    fn renderer(&self) -> Renderer {
529        let width = if let Some(width) = self.diagnostic_width {
530            width
531        } else if self.ui_testing || cfg!(miri) {
532            DEFAULT_TERM_WIDTH
533        } else {
534            termize::dimensions().map(|(w, _)| w).unwrap_or(DEFAULT_TERM_WIDTH)
535        };
536        let decor_style = match self.theme {
537            OutputTheme::Ascii => annotate_snippets::renderer::DecorStyle::Ascii,
538            OutputTheme::Unicode => annotate_snippets::renderer::DecorStyle::Unicode,
539        };
540
541        match self.dst.current_choice() {
542            ColorChoice::AlwaysAnsi | ColorChoice::Always | ColorChoice::Auto => Renderer::styled(),
543            ColorChoice::Never => Renderer::plain(),
544        }
545        .term_width(width)
546        .anonymized_line_numbers(self.ui_testing)
547        .decor_style(decor_style)
548        .short_message(self.short_message)
549    }
550
551    fn pre_style_msgs(
552        &self,
553        msgs: &[(DiagMessage, Style)],
554        level: Level,
555        args: &FluentArgs<'_>,
556    ) -> String {
557        msgs.iter()
558            .filter_map(|(m, style)| {
559                let text = self.translator.translate_message(m, args).map_err(Report::new).unwrap();
560                let style = style.anstyle(level);
561                if text.is_empty() { None } else { Some(format!("{style}{text}{style:#}")) }
562            })
563            .collect()
564    }
565
566    fn annotated_snippet<'a>(
567        &self,
568        annotations: Vec<Annotation>,
569        file_name: &FileName,
570        sm: &Arc<SourceMap>,
571    ) -> Option<Snippet<'a, annotate_snippets::Annotation<'a>>> {
572        let spans = annotations.iter().map(|a| a.span).collect::<Vec<_>>();
573        if let Some((bounding_span, source, offset_line)) = shrink_file(&spans, file_name, sm) {
574            let adj_lo = bounding_span.lo().to_usize();
575            let filename = sm.filename_for_diagnostics(file_name).to_string_lossy().to_string();
576            Some(Snippet::source(source).line_start(offset_line).path(filename).annotations(
577                annotations.into_iter().map(move |a| {
578                    let lo = a.span.lo().to_usize().saturating_sub(adj_lo);
579                    let hi = a.span.hi().to_usize().saturating_sub(adj_lo);
580                    let ann = a.kind.span(lo..hi);
581                    if let Some(label) = a.label { ann.label(label) } else { ann }
582                }),
583            ))
584        } else {
585            None
586        }
587    }
588
589    fn unannotated_messages<'a>(
590        &self,
591        annotations: Vec<Annotation>,
592        file_name: &FileName,
593        sm: &Arc<SourceMap>,
594        file_idx: usize,
595        report: &mut Vec<Group<'a>>,
596        mut group: Group<'a>,
597        level: &annotate_snippets::level::Level<'static>,
598    ) -> Group<'a> {
599        let filename = sm.filename_for_diagnostics(file_name).to_string_lossy().to_string();
600        let mut line_tracker = vec![];
601        for (i, a) in annotations.into_iter().enumerate() {
602            let lo = sm.lookup_char_pos(a.span.lo());
603            let hi = sm.lookup_char_pos(a.span.hi());
604            if i == 0 || (a.label.is_some()) {
605                // Render each new file after the first in its own Group
606                //    ╭▸ $DIR/deriving-meta-unknown-trait.rs:1:10
607                //    │
608                // LL │ #[derive(Eqr)]
609                //    │          ━━━
610                //    ╰╴ (<- It makes it so *this* will get printed)
611                //    ╭▸ $SRC_DIR/core/src/option.rs:594:0
612                //    ⸬  $SRC_DIR/core/src/option.rs:602:4
613                //    │
614                //    ╰ note: not covered
615                if i == 0 && file_idx != 0 {
616                    report.push(std::mem::replace(&mut group, Group::with_level(level.clone())));
617                }
618
619                if !line_tracker.contains(&lo.line) && (i == 0 || hi.line <= lo.line) {
620                    line_tracker.push(lo.line);
621                    // ╭▸ $SRC_DIR/core/src/option.rs:594:0 (<- It adds *this*)
622                    // ⸬  $SRC_DIR/core/src/option.rs:602:4
623                    // │
624                    // ╰ note: not covered
625                    group = group.element(
626                        Origin::path(filename.clone())
627                            .line(sm.doctest_offset_line(file_name, lo.line))
628                            .char_column(lo.col_display),
629                    );
630                }
631
632                if hi.line > lo.line
633                    && a.label.as_ref().is_some_and(|l| !l.is_empty())
634                    && !line_tracker.contains(&hi.line)
635                {
636                    line_tracker.push(hi.line);
637                    // ╭▸ $SRC_DIR/core/src/option.rs:594:0
638                    // ⸬  $SRC_DIR/core/src/option.rs:602:4 (<- It adds *this*)
639                    // │
640                    // ╰ note: not covered
641                    group = group.element(
642                        Origin::path(filename.clone())
643                            .line(sm.doctest_offset_line(file_name, hi.line))
644                            .char_column(hi.col_display),
645                    );
646                }
647
648                if let Some(label) = a.label
649                    && !label.is_empty()
650                {
651                    // ╭▸ $SRC_DIR/core/src/option.rs:594:0
652                    // ⸬  $SRC_DIR/core/src/option.rs:602:4
653                    // │ (<- It adds *this*)
654                    // ╰ note: not covered (<- and *this*)
655                    group = group
656                        .element(Padding)
657                        .element(annotate_snippets::Level::NOTE.message(label));
658                }
659            }
660        }
661        group
662    }
663}
664
665fn emit_to_destination(
666    rendered: String,
667    lvl: &Level,
668    dst: &mut Destination,
669    short_message: bool,
670) -> io::Result<()> {
671    use crate::lock;
672    let _buffer_lock = lock::acquire_global_lock("rustc_errors");
673    writeln!(dst, "{rendered}")?;
674    if !short_message && !lvl.is_failure_note() {
675        writeln!(dst)?;
676    }
677    dst.flush()?;
678    Ok(())
679}
680
681#[derive(Debug)]
682struct Annotation {
683    kind: AnnotationKind,
684    span: Span,
685    label: Option<String>,
686}
687
688fn collect_annotations(
689    args: &FluentArgs<'_>,
690    msp: &MultiSpan,
691    sm: &Arc<SourceMap>,
692    translator: &Translator,
693) -> Vec<(Arc<SourceFile>, Vec<Annotation>)> {
694    let mut output: Vec<(Arc<SourceFile>, Vec<Annotation>)> = vec![];
695
696    for SpanLabel { span, is_primary, label } in msp.span_labels() {
697        // If we don't have a useful span, pick the primary span if that exists.
698        // Worst case we'll just print an error at the top of the main file.
699        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| {
708            normalize_whitespace(
709                &translator.translate_message(m, args).map_err(Report::new).unwrap(),
710            )
711        });
712
713        let ann = Annotation { kind, span, label };
714        if sm.is_valid_span(ann.span).is_ok() {
715            // Look through each of our files for the one we're adding to. We
716            // use each files `stable_id` to avoid issues with file name
717            // collisions when multiple versions of the same crate are present
718            // in the dependency graph
719            if let Some((_, annotations)) =
720                output.iter_mut().find(|(f, _)| f.stable_id == file.stable_id)
721            {
722                annotations.push(ann);
723            } else {
724                output.push((file, vec![ann]));
725            }
726        }
727    }
728
729    // Sort annotations within each file by line number
730    for (_, ann) in output.iter_mut() {
731        ann.sort_by_key(|a| {
732            let lo = sm.lookup_char_pos(a.span.lo());
733            lo.line
734        });
735    }
736    output
737}
738
739fn shrink_file(
740    spans: &[Span],
741    file_name: &FileName,
742    sm: &Arc<SourceMap>,
743) -> Option<(Span, String, usize)> {
744    let lo_byte = spans.iter().map(|s| s.lo()).min()?;
745    let lo_loc = sm.lookup_char_pos(lo_byte);
746
747    let hi_byte = spans.iter().map(|s| s.hi()).max()?;
748    let hi_loc = sm.lookup_char_pos(hi_byte);
749
750    if lo_loc.file.stable_id != hi_loc.file.stable_id {
751        // this may happen when spans cross file boundaries due to macro expansion.
752        return None;
753    }
754
755    let lo = lo_loc.file.line_bounds(lo_loc.line.saturating_sub(1)).start;
756    let hi = hi_loc.file.line_bounds(hi_loc.line.saturating_sub(1)).end;
757
758    let bounding_span = Span::with_root_ctxt(lo, hi);
759    let source = sm.span_to_snippet(bounding_span).ok()?;
760    let offset_line = sm.doctest_offset_line(file_name, lo_loc.line);
761
762    Some((bounding_span, source, offset_line))
763}