Skip to main content

annotate_snippets/renderer/
graphics.rs

1// Most of this file is adapted from https://github.com/rust-lang/rust/blob/160905b6253f42967ed4aef4b98002944c7df24c/compiler/rustc_errors/src/emitter.rs
2
3use alloc::borrow::Cow;
4use alloc::collections::BTreeMap;
5use alloc::string::{String, ToString};
6use alloc::{format, vec, vec::Vec};
7use core::cmp::{Ordering, Reverse, max, min};
8use core::fmt;
9
10use anstyle::Style;
11
12use super::DecorStyle;
13use super::Renderer;
14use super::margin::Margin;
15use super::preprocess::{DisplaySuggestion, Preprocessed, PreprocessedElement, PreprocessedGroup};
16use super::stylesheet::Stylesheet;
17use crate::level::{Level, LevelInner};
18use crate::renderer::source_map::{
19    AnnotatedLineInfo, LineInfo, Loc, PatchKind, SourceMap, SplicedLines, SubstitutionHighlight,
20};
21use crate::renderer::styled_buffer::StyledBuffer;
22use crate::snippet::Id;
23use crate::{
24    Annotation, AnnotationKind, Element, Group, Message, Origin, Patch, Report, Snippet, Title,
25};
26
27pub(crate) const ANONYMIZED_LINE_NUM: &str = "LL";
28
29pub(crate) fn render(renderer: &Renderer, groups: Report<'_>) -> String {
30    if renderer.short_message {
31        render_short_message(renderer, groups).unwrap()
32    } else {
33        render_full_message(renderer, groups)
34    }
35}
36
37pub(crate) fn render_full_message(renderer: &Renderer, groups: Report<'_>) -> String {
38    let Preprocessed {
39        max_line_num,
40        report_primary_path,
41        groups,
42    } = Preprocessed::preprocess(groups);
43    let max_line_num_len = if renderer.anonymized_snippet_line_numbers {
44        ANONYMIZED_LINE_NUM.len()
45    } else {
46        num_decimal_digits(max_line_num)
47    };
48    let mut out_string = String::new();
49    let group_len = groups.len();
50    for (
51        g,
52        PreprocessedGroup {
53            group,
54            elements,
55            primary_path,
56            max_depth,
57        },
58    ) in groups.into_iter().enumerate()
59    {
60        let mut buffer = StyledBuffer::new();
61        let level = group.primary_level.clone();
62        let mut message_iter = elements.into_iter().enumerate().peekable();
63        if let Some(title) = &group.title {
64            let peek = message_iter.peek().map(|(_, s)| s);
65            let title_style = if title.allows_styling {
66                TitleStyle::Secondary
67            } else {
68                TitleStyle::Primary
69            };
70            let buffer_msg_line_offset = buffer.num_lines();
71            render_title(
72                renderer,
73                &mut buffer,
74                title,
75                max_line_num_len,
76                title_style,
77                matches!(peek, Some(PreprocessedElement::Message(_))),
78                buffer_msg_line_offset,
79            );
80            let buffer_msg_line_offset = buffer.num_lines();
81
82            if matches!(peek, Some(PreprocessedElement::Message(_))) {
83                draw_col_separator_no_space(
84                    renderer,
85                    &mut buffer,
86                    buffer_msg_line_offset,
87                    max_line_num_len + 1,
88                );
89            }
90            if peek.is_none() && title_style == TitleStyle::Primary && g == 0 && group_len > 1 {
91                draw_col_separator_end(
92                    renderer,
93                    &mut buffer,
94                    buffer_msg_line_offset,
95                    max_line_num_len + 1,
96                );
97            }
98        }
99        let mut seen_primary = false;
100        let mut last_suggestion_path = None;
101        while let Some((i, section)) = message_iter.next() {
102            let peek = message_iter.peek().map(|(_, s)| s);
103            let is_first = i == 0;
104            match section {
105                PreprocessedElement::Message(title) => {
106                    let title_style = TitleStyle::Message;
107                    let buffer_msg_line_offset = buffer.num_lines();
108                    render_title(
109                        renderer,
110                        &mut buffer,
111                        title,
112                        max_line_num_len,
113                        title_style,
114                        peek.is_some(),
115                        buffer_msg_line_offset,
116                    );
117                }
118                PreprocessedElement::Cause((cause, source_map, annotated_lines)) => {
119                    let is_primary = primary_path == cause.path.as_ref() && !seen_primary;
120                    seen_primary |= is_primary;
121                    render_snippet_annotations(
122                        renderer,
123                        &mut buffer,
124                        max_line_num_len,
125                        cause,
126                        is_primary,
127                        &source_map,
128                        &annotated_lines,
129                        max_depth,
130                        peek.is_some() || (g == 0 && group_len > 1),
131                        is_first,
132                    );
133
134                    if g == 0 {
135                        let current_line = buffer.num_lines();
136                        match peek {
137                            Some(PreprocessedElement::Message(_)) => {
138                                draw_col_separator_no_space(
139                                    renderer,
140                                    &mut buffer,
141                                    current_line,
142                                    max_line_num_len + 1,
143                                );
144                            }
145                            None if group_len > 1 => draw_col_separator_end(
146                                renderer,
147                                &mut buffer,
148                                current_line,
149                                max_line_num_len + 1,
150                            ),
151                            _ => {}
152                        }
153                    }
154                }
155                PreprocessedElement::Suggestion((
156                    suggestion,
157                    source_map,
158                    spliced_lines,
159                    display_suggestion,
160                )) => {
161                    let matches_previous_suggestion =
162                        last_suggestion_path == Some(suggestion.path.as_ref());
163                    emit_suggestion_default(
164                        renderer,
165                        &mut buffer,
166                        suggestion,
167                        spliced_lines,
168                        display_suggestion,
169                        max_line_num_len,
170                        &source_map,
171                        primary_path.or(report_primary_path),
172                        matches_previous_suggestion,
173                        is_first,
174                        //matches!(peek, Some(Element::Message(_) | Element::Padding(_))),
175                        peek.is_some(),
176                    );
177
178                    if matches!(peek, Some(PreprocessedElement::Suggestion(_))) {
179                        last_suggestion_path = Some(suggestion.path.as_ref());
180                    } else {
181                        last_suggestion_path = None;
182                    }
183                }
184
185                PreprocessedElement::Origin(origin) => {
186                    let buffer_msg_line_offset = buffer.num_lines();
187                    let is_primary = primary_path == origin.path.as_ref() && !seen_primary;
188                    seen_primary |= is_primary;
189                    render_origin(
190                        renderer,
191                        &mut buffer,
192                        max_line_num_len,
193                        origin,
194                        is_primary,
195                        is_first,
196                        peek.is_none(),
197                        buffer_msg_line_offset,
198                    );
199                    let current_line = buffer.num_lines();
200                    if g == 0 && peek.is_none() && group_len > 1 {
201                        draw_col_separator_end(
202                            renderer,
203                            &mut buffer,
204                            current_line,
205                            max_line_num_len + 1,
206                        );
207                    }
208                }
209                PreprocessedElement::Padding(_) => {
210                    let current_line = buffer.num_lines();
211                    if peek.is_none() {
212                        draw_col_separator_end(
213                            renderer,
214                            &mut buffer,
215                            current_line,
216                            max_line_num_len + 1,
217                        );
218                    } else {
219                        draw_col_separator_no_space(
220                            renderer,
221                            &mut buffer,
222                            current_line,
223                            max_line_num_len + 1,
224                        );
225                    }
226                }
227            }
228        }
229        buffer
230            .render(&level, &renderer.stylesheet, &mut out_string)
231            .unwrap();
232        if g != group_len - 1 {
233            out_string.push('\n');
234        }
235    }
236    out_string
237}
238
239fn render_short_message(renderer: &Renderer, groups: &[Group<'_>]) -> Result<String, fmt::Error> {
240    let mut buffer = StyledBuffer::new();
241    let mut labels = None;
242    let group = groups.first().expect("Expected at least one group");
243
244    let Some(title) = &group.title else {
245        panic!("Expected a Title");
246    };
247
248    if let Some(Element::Cause(cause)) = group
249        .elements
250        .iter()
251        .find(|e| matches!(e, Element::Cause(_)))
252    {
253        let labels_inner = cause
254            .markers
255            .iter()
256            .filter_map(|ann| match &ann.label {
257                Some(msg) if ann.kind.is_primary() => {
258                    if !msg.trim().is_empty() {
259                        Some(msg.to_string())
260                    } else {
261                        None
262                    }
263                }
264                _ => None,
265            })
266            .collect::<Vec<_>>()
267            .join(", ");
268        if !labels_inner.is_empty() {
269            labels = Some(labels_inner);
270        }
271
272        if let Some(mut origin) = cause.to_origin() {
273            let source_map = SourceMap::new(&cause.source, cause.line_start);
274            let (_depth, annotated_lines) =
275                source_map.annotated_lines(cause.markers.clone(), cause.fold);
276
277            if let Some(primary_line) = annotated_lines
278                .iter()
279                .find(|l| l.annotations.iter().any(LineAnnotation::is_primary))
280                .or(annotated_lines.iter().find(|l| !l.annotations.is_empty()))
281            {
282                origin.line = Some(primary_line.line_index);
283                if let Some(first_annotation) = primary_line
284                    .annotations
285                    .iter()
286                    .min_by_key(|a| (Reverse(a.is_primary()), a.start.char))
287                {
288                    origin.char_column = Some(first_annotation.start.char + 1);
289                }
290            }
291
292            let str = format_origin(&origin, renderer.anonymized_origin_line_numbers);
293            buffer.append(0, &str, ElementStyle::LineAndColumn);
294            buffer.append(0, ": ", ElementStyle::LineAndColumn);
295        }
296    }
297
298    render_title(
299        renderer,
300        &mut buffer,
301        title,
302        0, // No line numbers in short messages
303        TitleStyle::Primary,
304        false,
305        0,
306    );
307
308    if let Some(labels) = labels {
309        buffer.append(0, &format!(": {labels}"), ElementStyle::NoStyle);
310    }
311
312    let mut out_string = String::new();
313    buffer.render(&title.level, &renderer.stylesheet, &mut out_string)?;
314
315    Ok(out_string)
316}
317
318#[allow(clippy::too_many_arguments, reason = "All arguments are necessary")]
319fn render_title(
320    renderer: &Renderer,
321    buffer: &mut StyledBuffer,
322    title: &dyn MessageOrTitle,
323    max_line_num_len: usize,
324    title_style: TitleStyle,
325    is_cont: bool,
326    buffer_msg_line_offset: usize,
327) {
328    let (label_style, title_element_style) = match title_style {
329        TitleStyle::Primary => (
330            ElementStyle::Level(title.level().level),
331            if renderer.short_message {
332                ElementStyle::NoStyle
333            } else {
334                ElementStyle::MainHeaderMsg
335            },
336        ),
337        TitleStyle::Secondary => (
338            ElementStyle::Level(title.level().level),
339            ElementStyle::HeaderMsg,
340        ),
341        TitleStyle::Message => {
342            for _ in 0..max_line_num_len {
343                buffer.append(buffer_msg_line_offset, " ", ElementStyle::NoStyle);
344            }
345
346            draw_note_separator(
347                renderer,
348                buffer,
349                buffer_msg_line_offset,
350                max_line_num_len + 1,
351                is_cont,
352            );
353            (ElementStyle::MainHeaderMsg, ElementStyle::NoStyle)
354        }
355    };
356
357    let mut label_width = 0;
358    let level_is_visible = title.level().name != Some(None);
359    if level_is_visible || title.id().is_some() {
360        if level_is_visible {
361            buffer.append(buffer_msg_line_offset, title.level().as_str(), label_style);
362            label_width += str_width(title.level().as_str());
363        }
364
365        if let Some(Id { id: Some(id), url }) = &title.id() {
366            let url = url
367                .as_deref()
368                .filter(|_| renderer.hyperlink)
369                .map(Hyperlink::with_url)
370                .unwrap_or_default();
371
372            if level_is_visible {
373                buffer.append(buffer_msg_line_offset, "[", label_style);
374                label_width += 1;
375            }
376
377            buffer.append(buffer_msg_line_offset, &format!("{url}"), label_style);
378            buffer.append(buffer_msg_line_offset, id, label_style);
379            buffer.append(buffer_msg_line_offset, &format!("{url:#}"), label_style);
380            label_width += str_width(id);
381
382            if level_is_visible {
383                buffer.append(buffer_msg_line_offset, "]", label_style);
384                label_width += 1;
385            }
386        }
387
388        if let Some(footnote_marker) = title.footnote_marker() {
389            buffer.append(buffer_msg_line_offset, footnote_marker, label_style);
390            label_width += str_width(footnote_marker);
391        }
392
393        buffer.append(buffer_msg_line_offset, ": ", title_element_style);
394        label_width += 2;
395    }
396
397    let padding = " ".repeat(if title_style == TitleStyle::Message {
398        // The extra 3 ` ` is padding that's always needed to align to the
399        // label i.e. `note: `:
400        //
401        //   error: message
402        //     --> file.rs:13:20
403        //      |
404        //   13 |     <CODE>
405        //      |      ^^^^
406        //      |
407        //      = note: multiline
408        //              message
409        //   ++^^^------
410        //    |  |     |
411        //    |  |     |
412        //    |  |     width of label
413        //    |  magic `3`
414        //    `max_line_num_len`
415        max_line_num_len + 3 + label_width
416    } else {
417        label_width
418    });
419
420    let (title_str, style) = if title.allows_styling() {
421        (Cow::Borrowed(title.text()), ElementStyle::NoStyle)
422    } else {
423        (normalize_whitespace(title.text()), title_element_style)
424    };
425    for (i, text) in title_str.split('\n').enumerate() {
426        if i != 0 {
427            buffer.append(buffer_msg_line_offset + i, &padding, ElementStyle::NoStyle);
428            if title_style == TitleStyle::Message
429                && is_cont
430                && matches!(renderer.decor_style, DecorStyle::Unicode)
431            {
432                // There's another note after this one, associated to the subwindow above.
433                // We write additional vertical lines to join them:
434                //   ╭▸ test.rs:3:3
435                //   │
436                // 3 │   code
437                //   │   ━━━━
438                //   │
439                //   ├ note: foo
440                //   │       bar
441                //   ╰ note: foo
442                //           bar
443                draw_col_separator_no_space(
444                    renderer,
445                    buffer,
446                    buffer_msg_line_offset + i,
447                    max_line_num_len + 1,
448                );
449            }
450        }
451        buffer.append(buffer_msg_line_offset + i, text, style);
452    }
453}
454
455#[allow(clippy::too_many_arguments, reason = "All arguments are necessary")]
456fn render_origin(
457    renderer: &Renderer,
458    buffer: &mut StyledBuffer,
459    max_line_num_len: usize,
460    origin: &Origin<'_>,
461    is_primary: bool,
462    is_first: bool,
463    alone: bool,
464    buffer_msg_line_offset: usize,
465) {
466    if !renderer.short_message {
467        for _ in 0..max_line_num_len {
468            buffer.append(buffer_msg_line_offset, " ", ElementStyle::NoStyle);
469        }
470
471        if is_primary {
472            buffer.append(
473                buffer_msg_line_offset,
474                renderer.decor_style.file_start(is_first, alone),
475                ElementStyle::LineNumber,
476            );
477        } else {
478            // if !origin.standalone {
479            //     // Add spacing line, as shown:
480            //     //   --> $DIR/file:54:15
481            //     //    |
482            //     // LL |         code
483            //     //    |         ^^^^
484            //     //    | (<- It prints *this* line)
485            //     //   ::: $DIR/other_file.rs:15:5
486            //     //    |
487            //     // LL |     code
488            //     //    |     ----
489            //     draw_col_separator_no_space(renderer,
490            //         buffer,
491            //         buffer_msg_line_offset,
492            //         max_line_num_len + 1,
493            //     );
494            //
495            //     buffer_msg_line_offset += 1;
496            // }
497            // Then, the secondary file indicator
498            buffer.append(
499                buffer_msg_line_offset,
500                renderer.decor_style.secondary_file_start(),
501                ElementStyle::LineNumber,
502            );
503        }
504    }
505
506    let str = format_origin(origin, renderer.anonymized_origin_line_numbers);
507    buffer.append(buffer_msg_line_offset, &str, ElementStyle::LineAndColumn);
508}
509
510fn format_origin(origin: &Origin<'_>, anonymized_origin_line_numbers: bool) -> String {
511    use core::fmt::Write as _;
512
513    let mut buffer = String::new();
514    if let Some(path) = &origin.path {
515        write!(&mut buffer, "{path}").unwrap();
516    }
517    if let Some(section) = &origin.section {
518        if !buffer.is_empty() {
519            write!(&mut buffer, ":").unwrap();
520        }
521        write!(&mut buffer, "{section}").unwrap();
522    }
523    if let Some(line) = origin.line {
524        if anonymized_origin_line_numbers {
525            let line = ANONYMIZED_LINE_NUM;
526            write!(&mut buffer, ":{line}").unwrap();
527        } else {
528            write!(&mut buffer, ":{line}").unwrap();
529        }
530        if let Some(col) = origin.char_column {
531            write!(&mut buffer, ":{col}").unwrap();
532        }
533    }
534    buffer
535}
536
537#[allow(clippy::too_many_arguments, reason = "All arguments are necessary")]
538fn render_snippet_annotations(
539    renderer: &Renderer,
540    buffer: &mut StyledBuffer,
541    max_line_num_len: usize,
542    snippet: &Snippet<'_, Annotation<'_>>,
543    is_primary: bool,
544    sm: &SourceMap<'_>,
545    annotated_lines: &[AnnotatedLineInfo<'_>],
546    multiline_depth: usize,
547    is_cont: bool,
548    is_first: bool,
549) {
550    if let Some(mut origin) = snippet.to_origin() {
551        // print out the span location and spacer before we print the annotated source
552        // to do this, we need to know if this span will be primary
553        //let is_primary = primary_path == Some(&origin.path);
554
555        if is_primary {
556            if let Some(primary_line) = annotated_lines
557                .iter()
558                .find(|l| l.annotations.iter().any(LineAnnotation::is_primary))
559                .or(annotated_lines.iter().find(|l| !l.annotations.is_empty()))
560            {
561                origin.line = Some(primary_line.line_index);
562                if let Some(first_annotation) = primary_line
563                    .annotations
564                    .iter()
565                    .min_by_key(|a| (Reverse(a.is_primary()), a.start.char))
566                {
567                    origin.char_column = Some(first_annotation.start.char + 1);
568                }
569            }
570        } else {
571            let buffer_msg_line_offset = buffer.num_lines();
572            // Add spacing line, as shown:
573            //   --> $DIR/file:54:15
574            //    |
575            // LL |         code
576            //    |         ^^^^
577            //    | (<- It prints *this* line)
578            //   ::: $DIR/other_file.rs:15:5
579            //    |
580            // LL |     code
581            //    |     ----
582            draw_col_separator_no_space(
583                renderer,
584                buffer,
585                buffer_msg_line_offset,
586                max_line_num_len + 1,
587            );
588            if let Some(first_line) = annotated_lines
589                .iter()
590                .find(|l| !l.annotations.is_empty())
591                .or(annotated_lines.first())
592            {
593                origin.line = Some(first_line.line_index);
594                if let Some(first_annotation) = first_line.annotations.first() {
595                    origin.char_column = Some(first_annotation.start.char + 1);
596                }
597            }
598        }
599        let buffer_msg_line_offset = buffer.num_lines();
600        render_origin(
601            renderer,
602            buffer,
603            max_line_num_len,
604            &origin,
605            is_primary,
606            is_first,
607            false,
608            buffer_msg_line_offset,
609        );
610        // Put in the spacer between the location and annotated source
611        draw_col_separator_no_space(
612            renderer,
613            buffer,
614            buffer_msg_line_offset + 1,
615            max_line_num_len + 1,
616        );
617    } else {
618        let buffer_msg_line_offset = buffer.num_lines();
619        if is_primary {
620            if renderer.decor_style == DecorStyle::Unicode {
621                buffer.puts(
622                    buffer_msg_line_offset,
623                    max_line_num_len,
624                    renderer.decor_style.file_start(is_first, false),
625                    ElementStyle::LineNumber,
626                );
627            } else {
628                draw_col_separator_no_space(
629                    renderer,
630                    buffer,
631                    buffer_msg_line_offset,
632                    max_line_num_len + 1,
633                );
634            }
635        } else {
636            // Add spacing line, as shown:
637            //   --> $DIR/file:54:15
638            //    |
639            // LL |         code
640            //    |         ^^^^
641            //    | (<- It prints *this* line)
642            //   ::: $DIR/other_file.rs:15:5
643            //    |
644            // LL |     code
645            //    |     ----
646            draw_col_separator_no_space(
647                renderer,
648                buffer,
649                buffer_msg_line_offset,
650                max_line_num_len + 1,
651            );
652
653            buffer.puts(
654                buffer_msg_line_offset + 1,
655                max_line_num_len,
656                renderer.decor_style.secondary_file_start(),
657                ElementStyle::LineNumber,
658            );
659        }
660    }
661
662    // Contains the vertical lines' positions for active multiline annotations
663    let mut multilines = Vec::new();
664
665    // Get the left-side margin to remove it
666    let mut whitespace_margin = usize::MAX;
667    for line_info in annotated_lines {
668        let leading_whitespace = line_info
669            .line
670            .chars()
671            .take_while(|c| c.is_whitespace())
672            .map(|c| {
673                match c {
674                    // Tabs are displayed as 4 spaces
675                    '\t' => 4,
676                    _ => 1,
677                }
678            })
679            .sum();
680        if line_info.line.chars().any(|c| !c.is_whitespace()) {
681            whitespace_margin = min(whitespace_margin, leading_whitespace);
682        }
683    }
684    if whitespace_margin == usize::MAX {
685        whitespace_margin = 0;
686    }
687
688    // Left-most column any visible span points at.
689    let mut span_left_margin = usize::MAX;
690    for line_info in annotated_lines {
691        for ann in &line_info.annotations {
692            // The spans from `LineAnnotationType::MultilineLine` are always
693            // zero, which leads to incorrect calculation of the left margin,
694            // so we skip them here.
695            if matches!(ann.annotation_type, LineAnnotationType::MultilineLine(_)) {
696                continue;
697            }
698            span_left_margin = min(span_left_margin, ann.start.display);
699            span_left_margin = min(span_left_margin, ann.end.display);
700        }
701    }
702    if span_left_margin == usize::MAX {
703        span_left_margin = 0;
704    }
705
706    // Right-most column any visible span points at.
707    let mut span_right_margin = 0;
708    let mut label_right_margin = 0;
709    let mut max_line_len = 0;
710    for line_info in annotated_lines {
711        max_line_len = max(max_line_len, str_width(line_info.line));
712        for ann in &line_info.annotations {
713            span_right_margin = max(span_right_margin, ann.start.display);
714            span_right_margin = max(span_right_margin, ann.end.display);
715            // FIXME: account for labels not in the same line
716            let label_right = ann.label.as_ref().map_or(0, |l| str_width(l) + 1);
717            label_right_margin = max(label_right_margin, ann.end.display + label_right);
718        }
719    }
720    let width_offset = 3 + max_line_num_len;
721    let code_offset = if multiline_depth == 0 {
722        width_offset
723    } else {
724        width_offset + multiline_depth + 1
725    };
726
727    let column_width = renderer.term_width.saturating_sub(code_offset);
728
729    let margin = Margin::new(
730        whitespace_margin,
731        span_left_margin,
732        span_right_margin,
733        label_right_margin,
734        column_width,
735        max_line_len,
736    );
737
738    // Next, output the annotate source for this file
739    for annotated_line_idx in 0..annotated_lines.len() {
740        let previous_buffer_line = buffer.num_lines();
741
742        let depths = render_source_line(
743            renderer,
744            &annotated_lines[annotated_line_idx],
745            buffer,
746            width_offset,
747            code_offset,
748            max_line_num_len,
749            margin,
750            !is_cont && annotated_line_idx + 1 == annotated_lines.len(),
751            snippet.line_numbering,
752        );
753
754        let mut to_add = BTreeMap::new();
755
756        for (depth, style) in depths {
757            if let Some(index) = multilines.iter().position(|(d, _)| d == &depth) {
758                multilines.swap_remove(index);
759            } else {
760                to_add.insert(depth, style);
761            }
762        }
763
764        // Set the multiline annotation vertical lines to the left of
765        // the code in this line.
766        for (depth, style) in &multilines {
767            for line in previous_buffer_line..buffer.num_lines() {
768                draw_multiline_line(renderer, buffer, line, width_offset, *depth, *style, false);
769            }
770        }
771        // check to see if we need to print out or elide lines that come between
772        // this annotated line and the next one.
773        if annotated_line_idx < (annotated_lines.len() - 1) {
774            let line_idx_delta = annotated_lines[annotated_line_idx + 1].line_index
775                - annotated_lines[annotated_line_idx].line_index;
776            match line_idx_delta.cmp(&2) {
777                Ordering::Greater => {
778                    let last_buffer_line_num = buffer.num_lines();
779
780                    draw_line_separator(renderer, buffer, last_buffer_line_num, width_offset);
781
782                    // Set the multiline annotation vertical lines on `...` bridging line.
783                    for (depth, style) in &multilines {
784                        draw_multiline_line(
785                            renderer,
786                            buffer,
787                            last_buffer_line_num,
788                            width_offset,
789                            *depth,
790                            *style,
791                            true,
792                        );
793                    }
794                    if let Some(line) = annotated_lines.get(annotated_line_idx) {
795                        for ann in &line.annotations {
796                            if let LineAnnotationType::MultilineStart(pos) = ann.annotation_type {
797                                // In the case where we have elided the entire start of the
798                                // multispan because those lines were empty, we still need
799                                // to draw the `|`s across the `...`.
800                                draw_multiline_line(
801                                    renderer,
802                                    buffer,
803                                    last_buffer_line_num,
804                                    width_offset,
805                                    pos,
806                                    if ann.is_primary() {
807                                        ElementStyle::UnderlinePrimary
808                                    } else {
809                                        ElementStyle::UnderlineSecondary
810                                    },
811                                    true,
812                                );
813                            }
814                        }
815                    }
816                }
817
818                Ordering::Equal => {
819                    let unannotated_line = sm
820                        .get_line(annotated_lines[annotated_line_idx].line_index + 1)
821                        .unwrap_or("");
822
823                    let last_buffer_line_num = buffer.num_lines();
824
825                    draw_line(
826                        renderer,
827                        buffer,
828                        &normalize_whitespace(unannotated_line),
829                        annotated_lines[annotated_line_idx + 1].line_index - 1,
830                        last_buffer_line_num,
831                        width_offset,
832                        code_offset,
833                        max_line_num_len,
834                        margin,
835                        snippet.line_numbering,
836                    );
837
838                    for (depth, style) in &multilines {
839                        draw_multiline_line(
840                            renderer,
841                            buffer,
842                            last_buffer_line_num,
843                            width_offset,
844                            *depth,
845                            *style,
846                            false,
847                        );
848                    }
849                    if let Some(line) = annotated_lines.get(annotated_line_idx) {
850                        for ann in &line.annotations {
851                            if let LineAnnotationType::MultilineStart(pos) = ann.annotation_type {
852                                draw_multiline_line(
853                                    renderer,
854                                    buffer,
855                                    last_buffer_line_num,
856                                    width_offset,
857                                    pos,
858                                    if ann.is_primary() {
859                                        ElementStyle::UnderlinePrimary
860                                    } else {
861                                        ElementStyle::UnderlineSecondary
862                                    },
863                                    false,
864                                );
865                            }
866                        }
867                    }
868                }
869                Ordering::Less => {}
870            }
871        }
872
873        multilines.extend(to_add);
874    }
875}
876
877#[allow(clippy::too_many_arguments, reason = "All arguments are necessary")]
878fn render_source_line(
879    renderer: &Renderer,
880    line_info: &AnnotatedLineInfo<'_>,
881    buffer: &mut StyledBuffer,
882    width_offset: usize,
883    code_offset: usize,
884    max_line_num_len: usize,
885    margin: Margin,
886    close_window: bool,
887    line_numbering: bool,
888) -> Vec<(usize, ElementStyle)> {
889    // Draw:
890    //
891    //   LL | ... code ...
892    //      |     ^^-^ span label
893    //      |       |
894    //      |       secondary span label
895    //
896    //   ^^ ^ ^^^ ^^^^ ^^^ we don't care about code too far to the right of a span, we trim it
897    //   |  | |   |
898    //   |  | |   actual code found in your source code and the spans we use to mark it
899    //   |  | when there's too much wasted space to the left, trim it
900    //   |  vertical divider between the column number and the code
901    //   column number
902
903    let source_string = normalize_whitespace(line_info.line);
904
905    let line_offset = buffer.num_lines();
906
907    let left = draw_line(
908        renderer,
909        buffer,
910        &source_string,
911        line_info.line_index,
912        line_offset,
913        width_offset,
914        code_offset,
915        max_line_num_len,
916        margin,
917        line_numbering,
918    );
919
920    // If there are no annotations, we are done
921    if line_info.annotations.is_empty() {
922        // `close_window` normally gets handled later, but we are early
923        // returning, so it needs to be handled here
924        if close_window {
925            draw_col_separator_end(renderer, buffer, line_offset + 1, width_offset - 2);
926        }
927        return vec![];
928    }
929
930    // Special case when there's only one annotation involved, it is the start of a multiline
931    // span and there's no text at the beginning of the code line. Instead of doing the whole
932    // graph:
933    //
934    // 2 |   fn foo() {
935    //   |  _^
936    // 3 | |
937    // 4 | | }
938    //   | |_^ test
939    //
940    // we simplify the output to:
941    //
942    // 2 | / fn foo() {
943    // 3 | |
944    // 4 | | }
945    //   | |_^ test
946    let mut buffer_ops = vec![];
947    let mut annotations = vec![];
948    let mut short_start = true;
949    for ann in &line_info.annotations {
950        if let LineAnnotationType::MultilineStart(depth) = ann.annotation_type {
951            if source_string
952                .chars()
953                .take(ann.start.display)
954                .all(char::is_whitespace)
955            {
956                let uline = renderer.decor_style.underline(ann.is_primary());
957                let chr = uline.multiline_whole_line;
958                annotations.push((depth, uline.style));
959                buffer_ops.push((line_offset, width_offset + depth - 1, chr, uline.style));
960            } else {
961                short_start = false;
962                break;
963            }
964        } else if let LineAnnotationType::MultilineLine(_) = ann.annotation_type {
965        } else {
966            short_start = false;
967            break;
968        }
969    }
970    if short_start {
971        for (y, x, c, s) in buffer_ops {
972            buffer.putc(y, x, c, s);
973        }
974        return annotations;
975    }
976
977    // We want to display like this:
978    //
979    //      vec.push(vec.pop().unwrap());
980    //      ---      ^^^               - previous borrow ends here
981    //      |        |
982    //      |        error occurs here
983    //      previous borrow of `vec` occurs here
984    //
985    // But there are some weird edge cases to be aware of:
986    //
987    //      vec.push(vec.pop().unwrap());
988    //      --------                    - previous borrow ends here
989    //      ||
990    //      |this makes no sense
991    //      previous borrow of `vec` occurs here
992    //
993    // For this reason, we group the lines into "highlight lines"
994    // and "annotations lines", where the highlight lines have the `^`.
995
996    // Sort the annotations by (start, end col)
997    // The labels are reversed, sort and then reversed again.
998    // Consider a list of annotations (A1, A2, C1, C2, B1, B2) where
999    // the letter signifies the span. Here we are only sorting by the
1000    // span and hence, the order of the elements with the same span will
1001    // not change. On reversing the ordering (|a, b| but b.cmp(a)), you get
1002    // (C1, C2, B1, B2, A1, A2). All the elements with the same span are
1003    // still ordered first to last, but all the elements with different
1004    // spans are ordered by their spans in last to first order. Last to
1005    // first order is important, because the jiggly lines and | are on
1006    // the left, so the rightmost span needs to be rendered first,
1007    // otherwise the lines would end up needing to go over a message.
1008
1009    let mut annotations = line_info.annotations.clone();
1010    annotations.sort_by_key(|a| Reverse((a.start.display, a.start.char)));
1011
1012    // First, figure out where each label will be positioned.
1013    //
1014    // In the case where you have the following annotations:
1015    //
1016    //      vec.push(vec.pop().unwrap());
1017    //      --------                    - previous borrow ends here [C]
1018    //      ||
1019    //      |this makes no sense [B]
1020    //      previous borrow of `vec` occurs here [A]
1021    //
1022    // `annotations_position` will hold [(2, A), (1, B), (0, C)].
1023    //
1024    // We try, when possible, to stick the rightmost annotation at the end
1025    // of the highlight line:
1026    //
1027    //      vec.push(vec.pop().unwrap());
1028    //      ---      ---               - previous borrow ends here
1029    //
1030    // But sometimes that's not possible because one of the other
1031    // annotations overlaps it. For example, from the test
1032    // `span_overlap_label`, we have the following annotations
1033    // (written on distinct lines for clarity):
1034    //
1035    //      fn foo(x: u32) {
1036    //      --------------
1037    //             -
1038    //
1039    // In this case, we can't stick the rightmost-most label on
1040    // the highlight line, or we would get:
1041    //
1042    //      fn foo(x: u32) {
1043    //      -------- x_span
1044    //      |
1045    //      fn_span
1046    //
1047    // which is totally weird. Instead we want:
1048    //
1049    //      fn foo(x: u32) {
1050    //      --------------
1051    //      |      |
1052    //      |      x_span
1053    //      fn_span
1054    //
1055    // which is...less weird, at least. In fact, in general, if
1056    // the rightmost span overlaps with any other span, we should
1057    // use the "hang below" version, so we can at least make it
1058    // clear where the span *starts*. There's an exception for this
1059    // logic, when the labels do not have a message:
1060    //
1061    //      fn foo(x: u32) {
1062    //      --------------
1063    //             |
1064    //             x_span
1065    //
1066    // instead of:
1067    //
1068    //      fn foo(x: u32) {
1069    //      --------------
1070    //      |      |
1071    //      |      x_span
1072    //      <EMPTY LINE>
1073    //
1074    let mut overlap = vec![false; annotations.len()];
1075    let mut annotations_position = vec![];
1076    let mut line_len: usize = 0;
1077    let mut p = 0;
1078    for (i, annotation) in annotations.iter().enumerate() {
1079        for (j, next) in annotations.iter().enumerate() {
1080            if overlaps(next, annotation, 0) && j > 1 {
1081                overlap[i] = true;
1082                overlap[j] = true;
1083            }
1084            if overlaps(next, annotation, 0)  // This label overlaps with another one and both
1085                    && annotation.has_label()     // take space (they have text and are not
1086                    && j > i                      // multiline lines).
1087                    && p == 0
1088            // We're currently on the first line, move the label one line down
1089            {
1090                // If we're overlapping with an un-labelled annotation with the same span
1091                // we can just merge them in the output
1092                if next.start.display == annotation.start.display
1093                    && next.start.char == annotation.start.char
1094                    && next.end.display == annotation.end.display
1095                    && next.end.char == annotation.end.char
1096                    && !next.has_label()
1097                {
1098                    continue;
1099                }
1100
1101                // This annotation needs a new line in the output.
1102                p += 1;
1103                break;
1104            }
1105        }
1106        annotations_position.push((p, annotation));
1107        for (j, next) in annotations.iter().enumerate() {
1108            if j > i {
1109                let l = next.label.as_ref().map_or(0, |label| label.len() + 2);
1110                if (overlaps(next, annotation, l) // Do not allow two labels to be in the same
1111                        // line if they overlap including padding, to
1112                        // avoid situations like:
1113                        //
1114                        //      fn foo(x: u32) {
1115                        //      -------^------
1116                        //      |      |
1117                        //      fn_spanx_span
1118                        //
1119                        && annotation.has_label()    // Both labels must have some text, otherwise
1120                        && next.has_label())         // they are not overlapping.
1121                        // Do not add a new line if this annotation
1122                        // or the next are vertical line placeholders.
1123                        || (annotation.takes_space() // If either this or the next annotation is
1124                        && next.has_label())     // multiline start/end, move it to a new line
1125                        || (annotation.has_label()   // so as not to overlap the horizontal lines.
1126                        && next.takes_space())
1127                        || (annotation.takes_space() && next.takes_space())
1128                        || (overlaps(next, annotation, l)
1129                        && (next.end.display, next.end.char) <= (annotation.end.display, annotation.end.char)
1130                        && next.has_label()
1131                        && p == 0)
1132                // Avoid #42595.
1133                {
1134                    // This annotation needs a new line in the output.
1135                    p += 1;
1136                    break;
1137                }
1138            }
1139        }
1140        line_len = max(line_len, p);
1141    }
1142
1143    if line_len != 0 {
1144        line_len += 1;
1145    }
1146
1147    // If there are no annotations or the only annotations on this line are
1148    // MultilineLine, then there's only code being shown, stop processing.
1149    if line_info.annotations.iter().all(LineAnnotation::is_line) {
1150        return vec![];
1151    }
1152
1153    if annotations_position
1154        .iter()
1155        .all(|(_, ann)| matches!(ann.annotation_type, LineAnnotationType::MultilineStart(_)))
1156        && let Some(max_pos) = annotations_position.iter().map(|(pos, _)| *pos).max()
1157    {
1158        // Special case the following, so that we minimize overlapping multiline spans.
1159        //
1160        // 3 │       X0 Y0 Z0
1161        //   │ ┏━━━━━┛  │  │     < We are writing these lines
1162        //   │ ┃┌───────┘  │     < by reverting the "depth" of
1163        //   │ ┃│┌─────────┘     < their multiline spans.
1164        // 4 │ ┃││   X1 Y1 Z1
1165        // 5 │ ┃││   X2 Y2 Z2
1166        //   │ ┃│└────╿──│──┘ `Z` label
1167        //   │ ┃└─────│──┤
1168        //   │ ┗━━━━━━┥  `Y` is a good letter too
1169        //   ╰╴       `X` is a good letter
1170        for (pos, _) in &mut annotations_position {
1171            *pos = max_pos - *pos;
1172        }
1173        // We know then that we don't need an additional line for the span label, saving us
1174        // one line of vertical space.
1175        line_len = line_len.saturating_sub(1);
1176    }
1177
1178    // Write the column separator.
1179    //
1180    // After this we will have:
1181    //
1182    // 2 |   fn foo() {
1183    //   |
1184    //   |
1185    //   |
1186    // 3 |
1187    // 4 |   }
1188    //   |
1189    for pos in 0..=line_len {
1190        draw_col_separator_no_space(renderer, buffer, line_offset + pos + 1, width_offset - 2);
1191    }
1192    if close_window {
1193        draw_col_separator_end(
1194            renderer,
1195            buffer,
1196            line_offset + line_len + 1,
1197            width_offset - 2,
1198        );
1199    }
1200    // Write the horizontal lines for multiline annotations
1201    // (only the first and last lines need this).
1202    //
1203    // After this we will have:
1204    //
1205    // 2 |   fn foo() {
1206    //   |  __________
1207    //   |
1208    //   |
1209    // 3 |
1210    // 4 |   }
1211    //   |  _
1212    for &(pos, annotation) in &annotations_position {
1213        let underline = renderer.decor_style.underline(annotation.is_primary());
1214        let pos = pos + 1;
1215        match annotation.annotation_type {
1216            LineAnnotationType::MultilineStart(depth) | LineAnnotationType::MultilineEnd(depth) => {
1217                draw_range(
1218                    buffer,
1219                    underline.multiline_horizontal,
1220                    line_offset + pos,
1221                    width_offset + depth,
1222                    (code_offset + annotation.start.display).saturating_sub(left),
1223                    underline.style,
1224                );
1225            }
1226            _ if annotation.highlight_source => {
1227                buffer.set_style_range(
1228                    line_offset,
1229                    (code_offset + annotation.start.char).saturating_sub(left),
1230                    (code_offset + annotation.end.char).saturating_sub(left),
1231                    underline.style,
1232                    annotation.is_primary(),
1233                );
1234            }
1235            _ => {}
1236        }
1237    }
1238
1239    // Write the vertical lines for labels that are on a different line as the underline.
1240    //
1241    // After this we will have:
1242    //
1243    // 2 |   fn foo() {
1244    //   |  __________
1245    //   | |    |
1246    //   | |
1247    // 3 | |
1248    // 4 | | }
1249    //   | |_
1250    for &(pos, annotation) in &annotations_position {
1251        let underline = renderer.decor_style.underline(annotation.is_primary());
1252        let pos = pos + 1;
1253
1254        if pos > 1 && (annotation.has_label() || annotation.takes_space()) {
1255            for p in line_offset + 1..=line_offset + pos {
1256                buffer.putc(
1257                    p,
1258                    (code_offset + annotation.start.display).saturating_sub(left),
1259                    match annotation.annotation_type {
1260                        LineAnnotationType::MultilineLine(_) => underline.multiline_vertical,
1261                        _ => underline.vertical_text_line,
1262                    },
1263                    underline.style,
1264                );
1265            }
1266            if let LineAnnotationType::MultilineStart(_) = annotation.annotation_type {
1267                buffer.putc(
1268                    line_offset + pos,
1269                    (code_offset + annotation.start.display).saturating_sub(left),
1270                    underline.bottom_right,
1271                    underline.style,
1272                );
1273            }
1274            if matches!(
1275                annotation.annotation_type,
1276                LineAnnotationType::MultilineEnd(_)
1277            ) && annotation.has_label()
1278            {
1279                buffer.putc(
1280                    line_offset + pos,
1281                    (code_offset + annotation.start.display).saturating_sub(left),
1282                    underline.multiline_bottom_right_with_text,
1283                    underline.style,
1284                );
1285            }
1286        }
1287        match annotation.annotation_type {
1288            LineAnnotationType::MultilineStart(depth) => {
1289                buffer.putc(
1290                    line_offset + pos,
1291                    width_offset + depth - 1,
1292                    underline.top_left,
1293                    underline.style,
1294                );
1295                for p in line_offset + pos + 1..line_offset + line_len + 2 {
1296                    buffer.putc(
1297                        p,
1298                        width_offset + depth - 1,
1299                        underline.multiline_vertical,
1300                        underline.style,
1301                    );
1302                }
1303            }
1304            LineAnnotationType::MultilineEnd(depth) => {
1305                for p in line_offset..line_offset + pos {
1306                    buffer.putc(
1307                        p,
1308                        width_offset + depth - 1,
1309                        underline.multiline_vertical,
1310                        underline.style,
1311                    );
1312                }
1313                buffer.putc(
1314                    line_offset + pos,
1315                    width_offset + depth - 1,
1316                    underline.bottom_left,
1317                    underline.style,
1318                );
1319            }
1320            _ => (),
1321        }
1322    }
1323
1324    // Write the labels on the annotations that actually have a label.
1325    //
1326    // After this we will have:
1327    //
1328    // 2 |   fn foo() {
1329    //   |  __________
1330    //   |      |
1331    //   |      something about `foo`
1332    // 3 |
1333    // 4 |   }
1334    //   |  _  test
1335    for &(pos, annotation) in &annotations_position {
1336        let style = if annotation.is_primary() {
1337            ElementStyle::LabelPrimary
1338        } else {
1339            ElementStyle::LabelSecondary
1340        };
1341        let (pos, col) = if pos == 0 {
1342            if annotation.end.display == 0 {
1343                (pos + 1, (annotation.end.display + 2).saturating_sub(left))
1344            } else {
1345                (pos + 1, (annotation.end.display + 1).saturating_sub(left))
1346            }
1347        } else {
1348            (pos + 2, annotation.start.display.saturating_sub(left))
1349        };
1350        if let Some(label) = &annotation.label {
1351            buffer.puts(line_offset + pos, code_offset + col, label, style);
1352        }
1353    }
1354
1355    // Sort from biggest span to smallest span so that smaller spans are
1356    // represented in the output:
1357    //
1358    // x | fn foo()
1359    //   | ^^^---^^
1360    //   | |  |
1361    //   | |  something about `foo`
1362    //   | something about `fn foo()`
1363    annotations_position.sort_by_key(|(_, ann)| {
1364        // Decreasing order. When annotations share the same length, prefer `Primary`.
1365        (Reverse(ann.len()), ann.is_primary())
1366    });
1367
1368    // Write the underlines.
1369    //
1370    // After this we will have:
1371    //
1372    // 2 |   fn foo() {
1373    //   |  ____-_____^
1374    //   |      |
1375    //   |      something about `foo`
1376    // 3 |
1377    // 4 |   }
1378    //   |  _^  test
1379    for &(pos, annotation) in &annotations_position {
1380        let uline = renderer.decor_style.underline(annotation.is_primary());
1381        for p in annotation.start.display..annotation.end.display {
1382            // The default span label underline.
1383            buffer.putc(
1384                line_offset + 1,
1385                (code_offset + p).saturating_sub(left),
1386                uline.underline,
1387                uline.style,
1388            );
1389        }
1390
1391        if pos == 0
1392            && matches!(
1393                annotation.annotation_type,
1394                LineAnnotationType::MultilineStart(_) | LineAnnotationType::MultilineEnd(_)
1395            )
1396        {
1397            // The beginning of a multiline span with its leftward moving line on the same line.
1398            buffer.putc(
1399                line_offset + 1,
1400                (code_offset + annotation.start.display).saturating_sub(left),
1401                match annotation.annotation_type {
1402                    LineAnnotationType::MultilineStart(_) => uline.top_right_flat,
1403                    LineAnnotationType::MultilineEnd(_) => uline.multiline_end_same_line,
1404                    _ => panic!("unexpected annotation type: {annotation:?}"),
1405                },
1406                uline.style,
1407            );
1408        } else if pos != 0
1409            && matches!(
1410                annotation.annotation_type,
1411                LineAnnotationType::MultilineStart(_) | LineAnnotationType::MultilineEnd(_)
1412            )
1413        {
1414            // The beginning of a multiline span with its leftward moving line on another line,
1415            // so we start going down first.
1416            buffer.putc(
1417                line_offset + 1,
1418                (code_offset + annotation.start.display).saturating_sub(left),
1419                match annotation.annotation_type {
1420                    LineAnnotationType::MultilineStart(_) => uline.multiline_start_down,
1421                    LineAnnotationType::MultilineEnd(_) => uline.multiline_end_up,
1422                    _ => panic!("unexpected annotation type: {annotation:?}"),
1423                },
1424                uline.style,
1425            );
1426        } else if pos != 0 && annotation.has_label() {
1427            // The beginning of a span label with an actual label, we'll point down.
1428            buffer.putc(
1429                line_offset + 1,
1430                (code_offset + annotation.start.display).saturating_sub(left),
1431                uline.label_start,
1432                uline.style,
1433            );
1434        }
1435    }
1436
1437    // We look for individual *long* spans, and we trim the *middle*, so that we render
1438    // LL | ...= [0, 0, 0, ..., 0, 0];
1439    //    |      ^^^^^^^^^^...^^^^^^^ expected `&[u8]`, found `[{integer}; 1680]`
1440    for (i, (_pos, annotation)) in annotations_position.iter().enumerate() {
1441        // Skip cases where multiple spans overlap eachother.
1442        if overlap[i] {
1443            continue;
1444        };
1445        let LineAnnotationType::Singleline = annotation.annotation_type else {
1446            continue;
1447        };
1448        let width = annotation.end.display - annotation.start.display;
1449
1450        static MIN_PAD: usize = 5;
1451        let margin_width = str_width(renderer.decor_style.margin());
1452        if width > margin.term_width * 2 && width > (MIN_PAD * 2 + margin_width) {
1453            // If the terminal is *too* small, we keep at least a tiny bit of the span for
1454            // display.
1455            let pad = max(margin.term_width / 3, MIN_PAD);
1456            // Code line
1457            buffer.replace(
1458                line_offset,
1459                code_offset + (annotation.start.display + pad).saturating_sub(left),
1460                code_offset + (annotation.end.display - pad).saturating_sub(left),
1461                renderer.decor_style.margin(),
1462            );
1463            // Underline line
1464            buffer.replace(
1465                line_offset + 1,
1466                code_offset + (annotation.start.display + pad).saturating_sub(left),
1467                code_offset + (annotation.end.display - pad).saturating_sub(left),
1468                renderer.decor_style.margin(),
1469            );
1470        }
1471    }
1472    annotations_position
1473        .iter()
1474        .filter_map(|&(_, annotation)| match annotation.annotation_type {
1475            LineAnnotationType::MultilineStart(p) | LineAnnotationType::MultilineEnd(p) => {
1476                let style = if annotation.is_primary() {
1477                    ElementStyle::LabelPrimary
1478                } else {
1479                    ElementStyle::LabelSecondary
1480                };
1481                Some((p, style))
1482            }
1483            _ => None,
1484        })
1485        .collect::<Vec<_>>()
1486}
1487
1488#[allow(clippy::too_many_arguments, reason = "All arguments are necessary")]
1489fn emit_suggestion_default(
1490    renderer: &Renderer,
1491    buffer: &mut StyledBuffer,
1492    suggestion: &Snippet<'_, Patch<'_>>,
1493    spliced_lines: SplicedLines<'_>,
1494    show_code_change: DisplaySuggestion,
1495    max_line_num_len: usize,
1496    sm: &SourceMap<'_>,
1497    primary_path: Option<&Cow<'_, str>>,
1498    matches_previous_suggestion: bool,
1499    is_first: bool,
1500    is_cont: bool,
1501) {
1502    let buffer_offset = buffer.num_lines();
1503    let mut row_num = buffer_offset + usize::from(!matches_previous_suggestion);
1504    let is_multiline = spliced_lines.complete.lines().count() > 1;
1505
1506    if suggestion.path.as_ref() != primary_path
1507        && let Some(mut origin) = suggestion.to_origin()
1508        && !matches_previous_suggestion
1509    {
1510        let (loc, _) = sm.span_to_locations(spliced_lines.patches[0].span());
1511        // --> file.rs:line:col
1512        //  |
1513        for _ in 0..max_line_num_len {
1514            buffer.append(row_num - 1, " ", ElementStyle::NoStyle);
1515        }
1516        let arrow = renderer.decor_style.file_start(is_first, false);
1517        buffer.append(row_num - 1, arrow, ElementStyle::LineNumber);
1518        origin.line = Some(loc.line);
1519        origin.char_column = Some(loc.char + 1);
1520        let message = format_origin(&origin, renderer.anonymized_origin_line_numbers);
1521        buffer.append(row_num - 1, &message, ElementStyle::LineAndColumn);
1522
1523        draw_col_separator_no_space(renderer, buffer, row_num, max_line_num_len + 1);
1524        row_num += 1;
1525    } else if matches_previous_suggestion {
1526        buffer.puts(
1527            row_num - 1,
1528            max_line_num_len + 1,
1529            renderer.decor_style.multi_suggestion_separator(),
1530            ElementStyle::LineNumber,
1531        );
1532    } else {
1533        draw_col_separator_start(renderer, buffer, row_num - 1, max_line_num_len + 1);
1534    }
1535
1536    if let DisplaySuggestion::Diff = show_code_change {
1537        row_num += 1;
1538    }
1539
1540    let lo = spliced_lines
1541        .patches
1542        .iter()
1543        .map(|p| p.span().start)
1544        .min()
1545        .unwrap();
1546    let hi = spliced_lines
1547        .patches
1548        .iter()
1549        .map(|p| p.span().end)
1550        .max()
1551        .unwrap();
1552
1553    let file_lines = sm.span_to_lines(lo..hi);
1554    let (line_start, line_end) = if suggestion.fold {
1555        // We use the original span to get original line_start
1556        sm.span_to_locations(spliced_lines.patches[0].original_span())
1557    } else {
1558        sm.span_to_locations(0..sm.source.len())
1559    };
1560    let mut lines = spliced_lines.complete.lines();
1561    if lines.clone().next().is_none() {
1562        // Account for a suggestion to completely remove a line(s) with whitespace (#94192).
1563        for line in line_start.line..=line_end.line {
1564            buffer.puts(
1565                row_num - 1 + line - line_start.line,
1566                0,
1567                &maybe_anonymized(renderer, line, max_line_num_len, suggestion.line_numbering),
1568                ElementStyle::LineNumber,
1569            );
1570            buffer.puts(
1571                row_num - 1 + line - line_start.line,
1572                max_line_num_len + 1,
1573                "- ",
1574                ElementStyle::Removal,
1575            );
1576            buffer.puts(
1577                row_num - 1 + line - line_start.line,
1578                max_line_num_len + 3,
1579                &normalize_whitespace(sm.get_line(line).unwrap()),
1580                ElementStyle::Removal,
1581            );
1582        }
1583        row_num += line_end.line - line_start.line;
1584    }
1585    let mut unhighlighted_lines = Vec::new();
1586    for (line_pos, (line, highlight_parts)) in
1587        lines.by_ref().zip(spliced_lines.highlights).enumerate()
1588    {
1589        // Remember lines that are not highlighted to hide them if needed
1590        if highlight_parts.is_empty() && suggestion.fold {
1591            unhighlighted_lines.push((line_pos, line));
1592            continue;
1593        }
1594
1595        match unhighlighted_lines.len() {
1596            0 => (),
1597            // Since we show first line, "..." line and last line,
1598            // There is no reason to hide if there are 3 or less lines
1599            // (because then we just replace a line with ... which is
1600            // not helpful)
1601            n if n <= 3 => unhighlighted_lines.drain(..).for_each(|(p, l)| {
1602                draw_code_line(
1603                    renderer,
1604                    buffer,
1605                    &mut row_num,
1606                    &[],
1607                    &[],
1608                    p + line_start.line,
1609                    l,
1610                    show_code_change,
1611                    max_line_num_len,
1612                    &file_lines,
1613                    is_multiline,
1614                    suggestion.line_numbering,
1615                );
1616            }),
1617            // Print first unhighlighted line, "..." and last unhighlighted line, like so:
1618            //
1619            // LL | this line was highlighted
1620            // LL | this line is just for context
1621            // ...
1622            // LL | this line is just for context
1623            // LL | this line was highlighted
1624            _ => {
1625                let last_line = unhighlighted_lines.pop();
1626                let first_line = unhighlighted_lines.drain(..).next();
1627
1628                if let Some((p, l)) = first_line {
1629                    draw_code_line(
1630                        renderer,
1631                        buffer,
1632                        &mut row_num,
1633                        &[],
1634                        &[],
1635                        p + line_start.line,
1636                        l,
1637                        show_code_change,
1638                        max_line_num_len,
1639                        &file_lines,
1640                        is_multiline,
1641                        suggestion.line_numbering,
1642                    );
1643                }
1644
1645                let placeholder = renderer.decor_style.margin();
1646                let padding = str_width(placeholder);
1647                buffer.puts(
1648                    row_num,
1649                    max_line_num_len.saturating_sub(padding),
1650                    placeholder,
1651                    ElementStyle::LineNumber,
1652                );
1653                row_num += 1;
1654
1655                if let Some((p, l)) = last_line {
1656                    draw_code_line(
1657                        renderer,
1658                        buffer,
1659                        &mut row_num,
1660                        &[],
1661                        &[],
1662                        p + line_start.line,
1663                        l,
1664                        show_code_change,
1665                        max_line_num_len,
1666                        &file_lines,
1667                        is_multiline,
1668                        suggestion.line_numbering,
1669                    );
1670                }
1671            }
1672        }
1673        draw_code_line(
1674            renderer,
1675            buffer,
1676            &mut row_num,
1677            &highlight_parts,
1678            &spliced_lines.replaced_highlights,
1679            line_pos + line_start.line,
1680            line,
1681            show_code_change,
1682            max_line_num_len,
1683            &file_lines,
1684            is_multiline,
1685            suggestion.line_numbering,
1686        );
1687    }
1688
1689    // This offset and the ones below need to be signed to account for replacement code
1690    // that is shorter than the original code.
1691    let mut offsets: Vec<(usize, isize)> = Vec::new();
1692    // Only show an underline in the suggestions if the suggestion is not the
1693    // entirety of the code being shown and the displayed code is not multiline.
1694    if let DisplaySuggestion::Diff | DisplaySuggestion::Underline | DisplaySuggestion::Add =
1695        show_code_change
1696    {
1697        for part in spliced_lines.patches {
1698            let (span_start, span_end) = sm.span_to_locations(part.span());
1699            let span_start_pos = span_start.display;
1700            let span_end_pos = span_end.display;
1701
1702            // If this addition is _only_ whitespace, then don't trim it,
1703            // or else we're just not rendering anything.
1704            let is_whitespace_addition = part.replacement().trim().is_empty();
1705
1706            // Do not underline the leading...
1707            let start = if is_whitespace_addition {
1708                0
1709            } else {
1710                part.replacement()
1711                    .len()
1712                    .saturating_sub(part.replacement().trim_start().len())
1713            };
1714            // ...or trailing spaces. Account for substitutions containing unicode
1715            // characters.
1716            let sub_len: usize = str_width(if is_whitespace_addition {
1717                part.replacement()
1718            } else {
1719                part.replacement().trim()
1720            });
1721
1722            let offset: isize = offsets
1723                .iter()
1724                .filter_map(|(start, v)| {
1725                    if span_start_pos < *start {
1726                        None
1727                    } else {
1728                        Some(v)
1729                    }
1730                })
1731                .sum();
1732            let underline_start = (span_start_pos + start).cast_signed() + offset;
1733            let underline_end = (span_start_pos + start + sub_len).cast_signed() + offset;
1734            assert!(underline_start >= 0 && underline_end >= 0);
1735            let padding: usize = max_line_num_len + 3;
1736            for p in underline_start..underline_end {
1737                if matches!(show_code_change, DisplaySuggestion::Underline) {
1738                    // If this is a replacement, underline with `~`, if this is an addition
1739                    // underline with `+`.
1740                    buffer.putc(
1741                        row_num,
1742                        (padding.cast_signed() + p).cast_unsigned(),
1743                        if matches!(part.kind(), Some(PatchKind::Insertion)) {
1744                            '+'
1745                        } else {
1746                            renderer.decor_style.diff()
1747                        },
1748                        ElementStyle::Addition,
1749                    );
1750                }
1751            }
1752
1753            // length of the code after substitution
1754            let full_sub_len = str_width(part.replacement()).cast_signed();
1755
1756            // length of the code to be substituted
1757            let snippet_len = span_end_pos.cast_signed() - span_start_pos.cast_signed();
1758            // For multiple substitutions, use the position *after* the previous
1759            // substitutions have happened, only when further substitutions are
1760            // located strictly after.
1761            offsets.push((span_end_pos, full_sub_len - snippet_len));
1762        }
1763        row_num += 1;
1764    }
1765
1766    // if we elided some lines, add an ellipsis
1767    if lines.next().is_some() {
1768        let placeholder = renderer.decor_style.margin();
1769        let padding = str_width(placeholder);
1770        buffer.puts(
1771            row_num,
1772            max_line_num_len.saturating_sub(padding),
1773            placeholder,
1774            ElementStyle::LineNumber,
1775        );
1776    } else {
1777        let row = match show_code_change {
1778            DisplaySuggestion::Diff | DisplaySuggestion::Add | DisplaySuggestion::Underline => {
1779                row_num - 1
1780            }
1781            DisplaySuggestion::None => row_num,
1782        };
1783        if is_cont {
1784            draw_col_separator_no_space(renderer, buffer, row, max_line_num_len + 1);
1785        } else {
1786            draw_col_separator_end(renderer, buffer, row, max_line_num_len + 1);
1787        }
1788    }
1789}
1790
1791#[allow(clippy::too_many_arguments, reason = "All arguments are necessary")]
1792fn draw_code_line(
1793    renderer: &Renderer,
1794    buffer: &mut StyledBuffer,
1795    row_num: &mut usize,
1796    highlight_parts: &[SubstitutionHighlight],
1797    replaced_parts: &[Vec<SubstitutionHighlight>],
1798    line_num: usize,
1799    line_to_add: &str,
1800    show_code_change: DisplaySuggestion,
1801    max_line_num_len: usize,
1802    file_lines: &[&LineInfo<'_>],
1803    is_multiline: bool,
1804    line_numbering: bool,
1805) {
1806    if let DisplaySuggestion::Diff = show_code_change {
1807        // We need to print more than one line if the span we need to remove is multiline.
1808        // For more info: https://github.com/rust-lang/rust/issues/92741
1809        let lines_to_remove = file_lines.iter().take(file_lines.len() - 1);
1810        for (index, (line_to_remove, parts)) in lines_to_remove.zip(replaced_parts).enumerate() {
1811            buffer.puts(
1812                *row_num - 1,
1813                0,
1814                &maybe_anonymized(renderer, line_num + index, max_line_num_len, line_numbering),
1815                ElementStyle::LineNumber,
1816            );
1817            buffer.puts(
1818                *row_num - 1,
1819                max_line_num_len + 1,
1820                "- ",
1821                ElementStyle::Removal,
1822            );
1823            let line = normalize_whitespace(line_to_remove.line);
1824            buffer.puts(
1825                *row_num - 1,
1826                max_line_num_len + 3,
1827                &line,
1828                ElementStyle::NoStyle,
1829            );
1830            style_substitution_highlights(
1831                parts,
1832                ElementStyle::Removal,
1833                *row_num - 1,
1834                line_to_remove.line,
1835                max_line_num_len,
1836                buffer,
1837            );
1838            *row_num += 1;
1839        }
1840        // If the last line is exactly equal to the line we need to add, we can skip both of
1841        // them. This allows us to avoid output like the following:
1842        // 2 - &
1843        // 2 + if true { true } else { false }
1844        // 3 - if true { true } else { false }
1845        // If those lines aren't equal, we print their diff
1846        let last_line = &file_lines.last().unwrap();
1847        if last_line.line == line_to_add {
1848            *row_num -= 2;
1849            // The last original line collapses into the previous drawn row, so
1850            // fold its replaced-code highlights onto that row too.
1851            style_substitution_highlights(
1852                replaced_parts.last().unwrap(),
1853                ElementStyle::Removal,
1854                *row_num,
1855                last_line.line,
1856                max_line_num_len,
1857                buffer,
1858            );
1859        } else {
1860            buffer.puts(
1861                *row_num - 1,
1862                0,
1863                &maybe_anonymized(
1864                    renderer,
1865                    line_num + file_lines.len() - 1,
1866                    max_line_num_len,
1867                    line_numbering,
1868                ),
1869                ElementStyle::LineNumber,
1870            );
1871            buffer.puts(
1872                *row_num - 1,
1873                max_line_num_len + 1,
1874                "- ",
1875                ElementStyle::Removal,
1876            );
1877            buffer.puts(
1878                *row_num - 1,
1879                max_line_num_len + 3,
1880                &normalize_whitespace(last_line.line),
1881                ElementStyle::NoStyle,
1882            );
1883            style_substitution_highlights(
1884                replaced_parts.last().unwrap(),
1885                ElementStyle::Removal,
1886                *row_num - 1,
1887                last_line.line,
1888                max_line_num_len,
1889                buffer,
1890            );
1891
1892            if line_to_add.trim().is_empty() {
1893                *row_num -= 1;
1894            } else {
1895                // Check if after the removal, the line is left with only whitespace. If so, we
1896                // will not show an "addition" line, as removing the whole line is what the user
1897                // would really want.
1898                // For example, for the following:
1899                //   |
1900                // 2 -     .await
1901                // 2 +     (note the left over whitespace)
1902                //   |
1903                // We really want
1904                //   |
1905                // 2 -     .await
1906                //   |
1907                // *row_num -= 1;
1908                buffer.puts(
1909                    *row_num,
1910                    0,
1911                    &maybe_anonymized(renderer, line_num, max_line_num_len, line_numbering),
1912                    ElementStyle::LineNumber,
1913                );
1914                buffer.puts(*row_num, max_line_num_len + 1, "+ ", ElementStyle::Addition);
1915                buffer.append(
1916                    *row_num,
1917                    &normalize_whitespace(line_to_add),
1918                    ElementStyle::NoStyle,
1919                );
1920            }
1921        }
1922    } else if is_multiline {
1923        buffer.puts(
1924            *row_num,
1925            0,
1926            &maybe_anonymized(renderer, line_num, max_line_num_len, line_numbering),
1927            ElementStyle::LineNumber,
1928        );
1929        match &highlight_parts {
1930            [SubstitutionHighlight { start: 0, end }] if *end == line_to_add.len() => {
1931                buffer.puts(*row_num, max_line_num_len + 1, "+ ", ElementStyle::Addition);
1932            }
1933            [] | [SubstitutionHighlight { start: 0, end: 0 }] => {
1934                // FIXME: needed? Doesn't get exercised in any test.
1935                draw_col_separator_no_space(renderer, buffer, *row_num, max_line_num_len + 1);
1936            }
1937            _ => {
1938                let diff = renderer.decor_style.diff();
1939                buffer.puts(
1940                    *row_num,
1941                    max_line_num_len + 1,
1942                    &format!("{diff} "),
1943                    ElementStyle::Addition,
1944                );
1945            }
1946        }
1947        //   LL | line_to_add
1948        //   ++^^^
1949        //    |  |
1950        //    |  magic `3`
1951        //    `max_line_num_len`
1952        buffer.puts(
1953            *row_num,
1954            max_line_num_len + 3,
1955            &normalize_whitespace(line_to_add),
1956            ElementStyle::NoStyle,
1957        );
1958    } else if let DisplaySuggestion::Add = show_code_change {
1959        buffer.puts(
1960            *row_num,
1961            0,
1962            &maybe_anonymized(renderer, line_num, max_line_num_len, line_numbering),
1963            ElementStyle::LineNumber,
1964        );
1965        buffer.puts(*row_num, max_line_num_len + 1, "+ ", ElementStyle::Addition);
1966        buffer.append(
1967            *row_num,
1968            &normalize_whitespace(line_to_add),
1969            ElementStyle::NoStyle,
1970        );
1971    } else {
1972        buffer.puts(
1973            *row_num,
1974            0,
1975            &maybe_anonymized(renderer, line_num, max_line_num_len, line_numbering),
1976            ElementStyle::LineNumber,
1977        );
1978        draw_col_separator(renderer, buffer, *row_num, max_line_num_len + 1);
1979        buffer.append(
1980            *row_num,
1981            &normalize_whitespace(line_to_add),
1982            ElementStyle::NoStyle,
1983        );
1984    }
1985
1986    style_substitution_highlights(
1987        highlight_parts,
1988        ElementStyle::Addition,
1989        *row_num,
1990        line_to_add,
1991        max_line_num_len,
1992        buffer,
1993    );
1994
1995    *row_num += 1;
1996}
1997
1998fn style_substitution_highlights(
1999    highlight_parts: &[SubstitutionHighlight],
2000    style: ElementStyle,
2001    row_num: usize,
2002    unnormalized_line: &str,
2003    max_line_num_len: usize,
2004    buffer: &mut StyledBuffer,
2005) {
2006    for &SubstitutionHighlight { start, end } in highlight_parts {
2007        // This is a no-op for empty ranges
2008        if start != end {
2009            // We calculate the extra width from tabs for both the start and end
2010            // of the span, as tabs could be present in the middle of the span
2011            let extra_width_start: usize = extra_width_from_tabs(unnormalized_line, start);
2012            let extra_width_end: usize = extra_width_from_tabs(unnormalized_line, end);
2013            buffer.set_style_range(
2014                row_num,
2015                max_line_num_len + 3 + start + extra_width_start,
2016                max_line_num_len + 3 + end + extra_width_end,
2017                style,
2018                true,
2019            );
2020        }
2021    }
2022}
2023
2024#[allow(clippy::too_many_arguments, reason = "All arguments are necessary")]
2025fn draw_line(
2026    renderer: &Renderer,
2027    buffer: &mut StyledBuffer,
2028    source_string: &str,
2029    line_index: usize,
2030    line_offset: usize,
2031    width_offset: usize,
2032    code_offset: usize,
2033    max_line_num_len: usize,
2034    margin: Margin,
2035    line_numbering: bool,
2036) -> usize {
2037    // Tabs are assumed to have been replaced by spaces in calling code.
2038    debug_assert!(!source_string.contains('\t'));
2039    let line_len = str_width(source_string);
2040    // Create the source line we will highlight.
2041    let mut left = margin.left(line_len);
2042    let right = margin.right(line_len);
2043
2044    let mut taken = 0;
2045    let mut skipped = 0;
2046    let code: String = source_string
2047        .chars()
2048        .skip_while(|ch| {
2049            let w = char_width(*ch);
2050            // If `skipped` is less than `left`, always skip the next `ch`,
2051            // even if `ch` is a multi-width char that would make `skipped`
2052            // exceed `left`. This ensures that we do not exceed term width on
2053            // source lines.
2054            if skipped < left {
2055                skipped += w;
2056                true
2057            } else {
2058                false
2059            }
2060        })
2061        .take_while(|ch| {
2062            // Make sure that the trimming on the right will fall within the terminal width.
2063            taken += char_width(*ch);
2064            taken <= (right - left)
2065        })
2066        .collect();
2067    // If we skipped more than `left`, adjust `left` to account for it.
2068    if skipped > left {
2069        left += skipped - left;
2070    }
2071    let placeholder = renderer.decor_style.margin();
2072    let padding = str_width(placeholder);
2073    let (width_taken, bytes_taken) = if margin.was_cut_left() {
2074        // We have stripped some code/whitespace from the beginning, make it clear.
2075        let mut bytes_taken = 0;
2076        let mut width_taken = 0;
2077        for ch in code.chars() {
2078            width_taken += char_width(ch);
2079            bytes_taken += ch.len_utf8();
2080
2081            if width_taken >= padding {
2082                break;
2083            }
2084        }
2085
2086        buffer.puts(
2087            line_offset,
2088            code_offset,
2089            placeholder,
2090            ElementStyle::LineNumber,
2091        );
2092        (width_taken, bytes_taken)
2093    } else {
2094        (0, 0)
2095    };
2096
2097    buffer.puts(
2098        line_offset,
2099        code_offset + width_taken,
2100        &code[bytes_taken..],
2101        ElementStyle::Quotation,
2102    );
2103
2104    if line_len > right {
2105        // We have stripped some code/whitespace from the beginning, make it clear.
2106        let mut char_taken = 0;
2107        let mut width_taken_inner = 0;
2108        for ch in code.chars().rev() {
2109            width_taken_inner += char_width(ch);
2110            char_taken += 1;
2111
2112            if width_taken_inner >= padding {
2113                break;
2114            }
2115        }
2116
2117        buffer.puts(
2118            line_offset,
2119            code_offset + width_taken + code[bytes_taken..].chars().count() - char_taken,
2120            placeholder,
2121            ElementStyle::LineNumber,
2122        );
2123    }
2124
2125    buffer.puts(
2126        line_offset,
2127        0,
2128        &maybe_anonymized(renderer, line_index, max_line_num_len, line_numbering),
2129        ElementStyle::LineNumber,
2130    );
2131
2132    draw_col_separator_no_space(renderer, buffer, line_offset, width_offset - 2);
2133
2134    left
2135}
2136
2137fn draw_range(
2138    buffer: &mut StyledBuffer,
2139    symbol: char,
2140    line: usize,
2141    col_from: usize,
2142    col_to: usize,
2143    style: ElementStyle,
2144) {
2145    for col in col_from..col_to {
2146        buffer.putc(line, col, symbol, style);
2147    }
2148}
2149
2150fn draw_multiline_line(
2151    renderer: &Renderer,
2152    buffer: &mut StyledBuffer,
2153    line: usize,
2154    offset: usize,
2155    depth: usize,
2156    style: ElementStyle,
2157    elided: bool,
2158) {
2159    let chr = match (style, renderer.decor_style) {
2160        (ElementStyle::UnderlinePrimary | ElementStyle::LabelPrimary, DecorStyle::Ascii) => '|',
2161        (_, DecorStyle::Ascii) => '|',
2162        (ElementStyle::UnderlinePrimary | ElementStyle::LabelPrimary, DecorStyle::Unicode) => {
2163            if elided {
2164                '┇'
2165            } else {
2166                '┃'
2167            }
2168        }
2169        (_, DecorStyle::Unicode) => {
2170            if elided {
2171                '┆'
2172            } else {
2173                '│'
2174            }
2175        }
2176    };
2177    buffer.putc(line, offset + depth - 1, chr, style);
2178}
2179
2180fn draw_col_separator(renderer: &Renderer, buffer: &mut StyledBuffer, line: usize, col: usize) {
2181    let chr = renderer.decor_style.col_separator();
2182    buffer.puts(line, col, &format!("{chr} "), ElementStyle::LineNumber);
2183}
2184
2185fn draw_col_separator_no_space(
2186    renderer: &Renderer,
2187    buffer: &mut StyledBuffer,
2188    line: usize,
2189    col: usize,
2190) {
2191    let chr = renderer.decor_style.col_separator();
2192    draw_col_separator_no_space_with_style(buffer, chr, line, col, ElementStyle::LineNumber);
2193}
2194
2195fn draw_col_separator_start(
2196    renderer: &Renderer,
2197    buffer: &mut StyledBuffer,
2198    line: usize,
2199    col: usize,
2200) {
2201    match renderer.decor_style {
2202        DecorStyle::Ascii => {
2203            draw_col_separator_no_space_with_style(
2204                buffer,
2205                '|',
2206                line,
2207                col,
2208                ElementStyle::LineNumber,
2209            );
2210        }
2211        DecorStyle::Unicode => {
2212            draw_col_separator_no_space_with_style(
2213                buffer,
2214                '╭',
2215                line,
2216                col,
2217                ElementStyle::LineNumber,
2218            );
2219            draw_col_separator_no_space_with_style(
2220                buffer,
2221                '╴',
2222                line,
2223                col + 1,
2224                ElementStyle::LineNumber,
2225            );
2226        }
2227    }
2228}
2229
2230fn draw_col_separator_end(renderer: &Renderer, buffer: &mut StyledBuffer, line: usize, col: usize) {
2231    match renderer.decor_style {
2232        DecorStyle::Ascii => {
2233            draw_col_separator_no_space_with_style(
2234                buffer,
2235                '|',
2236                line,
2237                col,
2238                ElementStyle::LineNumber,
2239            );
2240        }
2241        DecorStyle::Unicode => {
2242            draw_col_separator_no_space_with_style(
2243                buffer,
2244                '╰',
2245                line,
2246                col,
2247                ElementStyle::LineNumber,
2248            );
2249            draw_col_separator_no_space_with_style(
2250                buffer,
2251                '╴',
2252                line,
2253                col + 1,
2254                ElementStyle::LineNumber,
2255            );
2256        }
2257    }
2258}
2259
2260fn draw_col_separator_no_space_with_style(
2261    buffer: &mut StyledBuffer,
2262    chr: char,
2263    line: usize,
2264    col: usize,
2265    style: ElementStyle,
2266) {
2267    buffer.putc(line, col, chr, style);
2268}
2269
2270fn maybe_anonymized(
2271    renderer: &Renderer,
2272    line_num: usize,
2273    max_line_num_len: usize,
2274    line_numbering: bool,
2275) -> String {
2276    format!(
2277        "{:>max_line_num_len$}",
2278        if !line_numbering {
2279            Cow::Borrowed("")
2280        } else if renderer.anonymized_snippet_line_numbers {
2281            Cow::Borrowed(ANONYMIZED_LINE_NUM)
2282        } else {
2283            Cow::Owned(line_num.to_string())
2284        }
2285    )
2286}
2287
2288fn draw_note_separator(
2289    renderer: &Renderer,
2290    buffer: &mut StyledBuffer,
2291    line: usize,
2292    col: usize,
2293    is_cont: bool,
2294) {
2295    let chr = renderer.decor_style.note_separator(is_cont);
2296    buffer.puts(line, col, chr, ElementStyle::LineNumber);
2297}
2298
2299fn draw_line_separator(renderer: &Renderer, buffer: &mut StyledBuffer, line: usize, col: usize) {
2300    let (column, dots) = match renderer.decor_style {
2301        DecorStyle::Ascii => (0, "..."),
2302        DecorStyle::Unicode => (col - 2, "┆"),
2303    };
2304    buffer.puts(line, column, dots, ElementStyle::LineNumber);
2305}
2306
2307pub(crate) trait MessageOrTitle {
2308    fn level(&self) -> &Level<'_>;
2309    fn id(&self) -> Option<&Id<'_>>;
2310    fn footnote_marker(&self) -> Option<&str>;
2311    fn text(&self) -> &str;
2312    fn allows_styling(&self) -> bool;
2313}
2314
2315impl MessageOrTitle for Title<'_> {
2316    fn level(&self) -> &Level<'_> {
2317        &self.level
2318    }
2319    fn id(&self) -> Option<&Id<'_>> {
2320        self.id.as_ref()
2321    }
2322    fn footnote_marker(&self) -> Option<&str> {
2323        self.footnote_marker.as_deref()
2324    }
2325    fn text(&self) -> &str {
2326        self.text.as_ref()
2327    }
2328    fn allows_styling(&self) -> bool {
2329        self.allows_styling
2330    }
2331}
2332
2333impl MessageOrTitle for Message<'_> {
2334    fn level(&self) -> &Level<'_> {
2335        &self.level
2336    }
2337    fn id(&self) -> Option<&Id<'_>> {
2338        None
2339    }
2340    fn footnote_marker(&self) -> Option<&str> {
2341        None
2342    }
2343    fn text(&self) -> &str {
2344        self.text.as_ref()
2345    }
2346    fn allows_styling(&self) -> bool {
2347        true
2348    }
2349}
2350
2351/// Count extra display columns from tabs in the first `n` chars of `s`.
2352/// Each tab is displayed as 4 spaces, so the extra width per tab is 3.
2353fn extra_width_from_tabs(s: &str, n: usize) -> usize {
2354    s.chars().take(n).filter(|&ch| ch == '\t').count() * 3
2355}
2356
2357// instead of taking the String length or dividing by 10 while > 0, we multiply a limit by 10 until
2358// we're higher. If the loop isn't exited by the `return`, the last multiplication will wrap, which
2359// is OK, because while we cannot fit a higher power of 10 in a usize, the loop will end anyway.
2360// This is also why we need the max number of decimal digits within a `usize`.
2361fn num_decimal_digits(num: Option<usize>) -> usize {
2362    #[cfg(target_pointer_width = "64")]
2363    const MAX_DIGITS: usize = 20;
2364
2365    #[cfg(target_pointer_width = "32")]
2366    const MAX_DIGITS: usize = 10;
2367
2368    #[cfg(target_pointer_width = "16")]
2369    const MAX_DIGITS: usize = 5;
2370
2371    let Some(num) = num else {
2372        return 0;
2373    };
2374
2375    let mut lim = 10;
2376    for num_digits in 1..MAX_DIGITS {
2377        if num < lim {
2378            return num_digits;
2379        }
2380        lim = lim.wrapping_mul(10);
2381    }
2382    MAX_DIGITS
2383}
2384
2385pub(crate) fn str_width(s: &str) -> usize {
2386    s.chars().map(char_width).sum()
2387}
2388
2389pub(crate) fn char_width(ch: char) -> usize {
2390    // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is. For now,
2391    // just accept that sometimes the code line will be longer than desired.
2392    match ch {
2393        '\t' => 4,
2394        // Keep the following list in sync with `rustc_errors::emitter::OUTPUT_REPLACEMENTS`. These
2395        // are control points that we replace before printing with a visible codepoint for the sake
2396        // of being able to point at them with underlines.
2397        '\u{0000}' | '\u{0001}' | '\u{0002}' | '\u{0003}' | '\u{0004}' | '\u{0005}'
2398        | '\u{0006}' | '\u{0007}' | '\u{0008}' | '\u{000B}' | '\u{000C}' | '\u{000D}'
2399        | '\u{000E}' | '\u{000F}' | '\u{0010}' | '\u{0011}' | '\u{0012}' | '\u{0013}'
2400        | '\u{0014}' | '\u{0015}' | '\u{0016}' | '\u{0017}' | '\u{0018}' | '\u{0019}'
2401        | '\u{001A}' | '\u{001B}' | '\u{001C}' | '\u{001D}' | '\u{001E}' | '\u{001F}'
2402        | '\u{007F}' | '\u{202A}' | '\u{202B}' | '\u{202D}' | '\u{202E}' | '\u{2066}'
2403        | '\u{2067}' | '\u{2068}' | '\u{202C}' | '\u{2069}' => 1,
2404        _ => unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1),
2405    }
2406}
2407
2408pub(crate) fn num_overlap(
2409    a_start: usize,
2410    a_end: usize,
2411    b_start: usize,
2412    b_end: usize,
2413    inclusive: bool,
2414) -> bool {
2415    let extra = usize::from(inclusive);
2416    (b_start..b_end + extra).contains(&a_start) || (a_start..a_end + extra).contains(&b_start)
2417}
2418
2419fn overlaps(a1: &LineAnnotation<'_>, a2: &LineAnnotation<'_>, padding: usize) -> bool {
2420    num_overlap(
2421        a1.start.display,
2422        a1.end.display + padding,
2423        a2.start.display,
2424        a2.end.display,
2425        false,
2426    )
2427}
2428
2429#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
2430pub(crate) enum LineAnnotationType {
2431    /// Annotation under a single line of code
2432    Singleline,
2433
2434    // The Multiline type above is replaced with the following three in order
2435    // to reuse the current label drawing code.
2436    //
2437    // Each of these corresponds to one part of the following diagram:
2438    //
2439    //     x |   foo(1 + bar(x,
2440    //       |  _________^              < MultilineStart
2441    //     x | |             y),        < MultilineLine
2442    //       | |______________^ label   < MultilineEnd
2443    //     x |       z);
2444    /// Annotation marking the first character of a fully shown multiline span
2445    MultilineStart(usize),
2446    /// Annotation marking the last character of a fully shown multiline span
2447    MultilineEnd(usize),
2448    /// Line at the left enclosing the lines of a fully shown multiline span
2449    // Just a placeholder for the drawing algorithm, to know that it shouldn't skip the first 4
2450    // and last 2 lines of code. The actual line is drawn in `emit_message_default` and not in
2451    // `draw_multiline_line`.
2452    MultilineLine(usize),
2453}
2454
2455#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
2456pub(crate) struct LineAnnotation<'a> {
2457    /// Start column.
2458    /// Note that it is important that this field goes
2459    /// first, so that when we sort, we sort orderings by start
2460    /// column.
2461    pub start: Loc,
2462
2463    /// End column within the line (exclusive)
2464    pub end: Loc,
2465
2466    /// level
2467    pub kind: AnnotationKind,
2468
2469    /// Optional label to display adjacent to the annotation.
2470    pub label: Option<Cow<'a, str>>,
2471
2472    /// Is this a single line, multiline or multiline span minimized down to a
2473    /// smaller span.
2474    pub annotation_type: LineAnnotationType,
2475
2476    /// Whether the source code should be highlighted
2477    pub highlight_source: bool,
2478}
2479
2480impl LineAnnotation<'_> {
2481    pub(crate) fn is_primary(&self) -> bool {
2482        self.kind == AnnotationKind::Primary
2483    }
2484
2485    /// Whether this annotation is a vertical line placeholder.
2486    pub(crate) fn is_line(&self) -> bool {
2487        matches!(self.annotation_type, LineAnnotationType::MultilineLine(_))
2488    }
2489
2490    /// Length of this annotation as displayed in the stderr output
2491    pub(crate) fn len(&self) -> usize {
2492        // Account for usize underflows
2493        self.end.display.abs_diff(self.start.display)
2494    }
2495
2496    pub(crate) fn has_label(&self) -> bool {
2497        if let Some(label) = &self.label {
2498            // Consider labels with no text as effectively not being there
2499            // to avoid weird output with unnecessary vertical lines, like:
2500            //
2501            //     X | fn foo(x: u32) {
2502            //       | -------^------
2503            //       | |      |
2504            //       | |
2505            //       |
2506            //
2507            // Note that this would be the complete output users would see.
2508            !label.is_empty()
2509        } else {
2510            false
2511        }
2512    }
2513
2514    pub(crate) fn takes_space(&self) -> bool {
2515        // Multiline annotations always have to keep vertical space.
2516        matches!(
2517            self.annotation_type,
2518            LineAnnotationType::MultilineStart(_) | LineAnnotationType::MultilineEnd(_)
2519        )
2520    }
2521}
2522
2523// We replace some characters so the CLI output is always consistent and underlines aligned.
2524// Keep the following list in sync with `rustc_span::char_width`.
2525const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[
2526    // In terminals without Unicode support the following will be garbled, but in *all* terminals
2527    // the underlying codepoint will be as well. We could gate this replacement behind a "unicode
2528    // support" gate.
2529    ('\0', "␀"),
2530    ('\u{0001}', "␁"),
2531    ('\u{0002}', "␂"),
2532    ('\u{0003}', "␃"),
2533    ('\u{0004}', "␄"),
2534    ('\u{0005}', "␅"),
2535    ('\u{0006}', "␆"),
2536    ('\u{0007}', "␇"),
2537    ('\u{0008}', "␈"),
2538    ('\t', "    "), // We do our own tab replacement
2539    ('\u{000b}', "␋"),
2540    ('\u{000c}', "␌"),
2541    ('\u{000d}', "␍"),
2542    ('\u{000e}', "␎"),
2543    ('\u{000f}', "␏"),
2544    ('\u{0010}', "␐"),
2545    ('\u{0011}', "␑"),
2546    ('\u{0012}', "␒"),
2547    ('\u{0013}', "␓"),
2548    ('\u{0014}', "␔"),
2549    ('\u{0015}', "␕"),
2550    ('\u{0016}', "␖"),
2551    ('\u{0017}', "␗"),
2552    ('\u{0018}', "␘"),
2553    ('\u{0019}', "␙"),
2554    ('\u{001a}', "␚"),
2555    ('\u{001b}', "␛"),
2556    ('\u{001c}', "␜"),
2557    ('\u{001d}', "␝"),
2558    ('\u{001e}', "␞"),
2559    ('\u{001f}', "␟"),
2560    ('\u{007f}', "␡"),
2561    ('\u{200d}', ""), // Replace ZWJ for consistent terminal output of grapheme clusters.
2562    ('\u{202a}', "�"), // The following unicode text flow control characters are inconsistently
2563    ('\u{202b}', "�"), // supported across CLIs and can cause confusion due to the bytes on disk
2564    ('\u{202c}', "�"), // not corresponding to the visible source code, so we replace them always.
2565    ('\u{202d}', "�"),
2566    ('\u{202e}', "�"),
2567    ('\u{2066}', "�"),
2568    ('\u{2067}', "�"),
2569    ('\u{2068}', "�"),
2570    ('\u{2069}', "�"),
2571];
2572
2573pub(crate) fn normalize_whitespace(s: &str) -> Cow<'_, str> {
2574    if !s
2575        .chars()
2576        .any(|user| OUTPUT_REPLACEMENTS.iter().any(|(bad, _)| user == *bad))
2577    {
2578        return Cow::Borrowed(s);
2579    }
2580
2581    // Scan the input string for a character in the ordered table above.
2582    // If it's present, replace it with its alternative string (it can be more than 1 char!).
2583    // Otherwise, retain the input char.
2584    let normalized = s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
2585        match OUTPUT_REPLACEMENTS.binary_search_by_key(&c, |(k, _)| *k) {
2586            Ok(i) => s.push_str(OUTPUT_REPLACEMENTS[i].1),
2587            _ => s.push(c),
2588        }
2589        s
2590    });
2591    Cow::Owned(normalized)
2592}
2593
2594#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)]
2595pub(crate) enum ElementStyle {
2596    MainHeaderMsg,
2597    HeaderMsg,
2598    LineAndColumn,
2599    LineNumber,
2600    Quotation,
2601    UnderlinePrimary,
2602    UnderlineSecondary,
2603    LabelPrimary,
2604    LabelSecondary,
2605    NoStyle,
2606    Level(LevelInner),
2607    Addition,
2608    Removal,
2609}
2610
2611impl ElementStyle {
2612    pub(crate) fn color_spec(&self, level: &Level<'_>, stylesheet: &Stylesheet) -> Style {
2613        match self {
2614            Self::Addition => stylesheet.addition,
2615            Self::Removal => stylesheet.removal,
2616            Self::LineAndColumn => stylesheet.none,
2617            Self::LineNumber => stylesheet.line_num,
2618            Self::Quotation => stylesheet.none,
2619            Self::MainHeaderMsg => stylesheet.emphasis,
2620            Self::UnderlinePrimary | Self::LabelPrimary => level.style(stylesheet),
2621            Self::UnderlineSecondary | Self::LabelSecondary => stylesheet.context,
2622            Self::HeaderMsg | Self::NoStyle => stylesheet.none,
2623            Self::Level(lvl) => lvl.style(stylesheet),
2624        }
2625    }
2626}
2627
2628#[derive(Debug, Clone, Copy)]
2629pub(crate) struct UnderlineParts {
2630    pub(crate) style: ElementStyle,
2631    pub(crate) underline: char,
2632    pub(crate) label_start: char,
2633    pub(crate) vertical_text_line: char,
2634    pub(crate) multiline_vertical: char,
2635    pub(crate) multiline_horizontal: char,
2636    pub(crate) multiline_whole_line: char,
2637    pub(crate) multiline_start_down: char,
2638    pub(crate) bottom_right: char,
2639    pub(crate) top_left: char,
2640    pub(crate) top_right_flat: char,
2641    pub(crate) bottom_left: char,
2642    pub(crate) multiline_end_up: char,
2643    pub(crate) multiline_end_same_line: char,
2644    pub(crate) multiline_bottom_right_with_text: char,
2645}
2646
2647#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2648pub(crate) enum TitleStyle {
2649    Primary,
2650    Secondary,
2651    Message,
2652}
2653
2654pub(crate) struct Hyperlink<D: fmt::Display> {
2655    url: Option<D>,
2656}
2657
2658impl<D: fmt::Display> Hyperlink<D> {
2659    pub(crate) fn with_url(url: D) -> Self {
2660        Self { url: Some(url) }
2661    }
2662}
2663
2664impl<D: fmt::Display> Default for Hyperlink<D> {
2665    fn default() -> Self {
2666        Self { url: None }
2667    }
2668}
2669
2670impl<D: fmt::Display> fmt::Display for Hyperlink<D> {
2671    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2672        let Some(url) = self.url.as_ref() else {
2673            return Ok(());
2674        };
2675        if f.alternate() {
2676            write!(f, "\x1B]8;;\x1B\\")
2677        } else {
2678            write!(f, "\x1B]8;;{url}\x1B\\")
2679        }
2680    }
2681}
2682
2683#[cfg(test)]
2684mod test {
2685    use super::OUTPUT_REPLACEMENTS;
2686    use snapbox::IntoData;
2687
2688    fn format_replacements(replacements: Vec<(char, &str)>) -> String {
2689        replacements
2690            .into_iter()
2691            .map(|r| format!("    {r:?}"))
2692            .collect::<Vec<_>>()
2693            .join("\n")
2694    }
2695
2696    #[test]
2697    /// The [`OUTPUT_REPLACEMENTS`] array must be sorted (for binary search to
2698    /// work) and must contain no duplicate entries
2699    fn ensure_output_replacements_is_sorted() {
2700        let mut expected = OUTPUT_REPLACEMENTS.to_owned();
2701        expected.sort_by_key(|r| r.0);
2702        expected.dedup_by_key(|r| r.0);
2703        let expected = format_replacements(expected);
2704        let actual = format_replacements(OUTPUT_REPLACEMENTS.to_owned());
2705        snapbox::assert_data_eq!(actual, expected.into_data().raw());
2706    }
2707}