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