1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
use std::borrow::Borrow;
use std::io;
use std::ops::Range;

use super::draw::{self, StreamAwareFmt, StreamType};
use super::{Cache, CharSet, Label, LabelAttach, Report, ReportKind, Show, Span, Write};

// A WARNING, FOR ALL YE WHO VENTURE IN HERE
//
// - This code is complex and has a lot of implicit invariants
// - Yes, it has some bugs
// - Yes, it needs rewriting
// - No, you are not expected to understand it. I will probably not understand it either in a month, but that will only
//   give me a reason to rewrite it

enum LabelKind {
    Inline,
    Multiline,
}

struct LabelInfo<'a, S> {
    kind: LabelKind,
    label: &'a Label<S>,
}

struct SourceGroup<'a, S: Span> {
    src_id: &'a S::SourceId,
    span: Range<usize>,
    labels: Vec<LabelInfo<'a, S>>,
}

impl<S: Span> Report<'_, S> {
    fn get_source_groups(&self, cache: &mut impl Cache<S::SourceId>) -> Vec<SourceGroup<S>> {
        let mut groups = Vec::new();
        for label in self.labels.iter() {
            let src_display = cache.display(label.span.source());
            let src = match cache.fetch(label.span.source()) {
                Ok(src) => src,
                Err(e) => {
                    eprintln!("Unable to fetch source '{}': {:?}", Show(src_display), e);
                    continue;
                }
            };

            let start_line = src.get_offset_line(label.span.start()).map(|(_, l, _)| l);
            let end_line = src
                .get_offset_line(label.span.end().saturating_sub(1).max(label.span.start()))
                .map(|(_, l, _)| l);

            let label_info = LabelInfo {
                kind: if start_line == end_line {
                    LabelKind::Inline
                } else {
                    LabelKind::Multiline
                },
                label,
            };

            if let Some(group) = groups
                .iter_mut()
                .find(|g: &&mut SourceGroup<S>| g.src_id == label.span.source())
            {
                group.span.start = group.span.start.min(label.span.start());
                group.span.end = group.span.end.max(label.span.end());
                group.labels.push(label_info);
            } else {
                groups.push(SourceGroup {
                    src_id: label.span.source(),
                    span: label.span.start()..label.span.end(),
                    labels: vec![label_info],
                });
            }
        }
        groups
    }

    /// Write this diagnostic to an implementor of [`Write`].
    ///
    /// If using the `concolor` feature, this method assumes that the output is ultimately going to be printed to
    /// `stderr`.  If you are printing to `stdout`, use the [`write_for_stdout`](Self::write_for_stdout) method instead.
    ///
    /// If you wish to write to `stderr` or `stdout`, you can do so via [`Report::eprint`] or [`Report::print`] respectively.
    pub fn write<C: Cache<S::SourceId>, W: Write>(&self, cache: C, w: W) -> io::Result<()> {
        self.write_for_stream(cache, w, StreamType::Stderr)
    }

    /// Write this diagnostic to an implementor of [`Write`], assuming that the output is ultimately going to be printed
    /// to `stdout`.
    pub fn write_for_stdout<C: Cache<S::SourceId>, W: Write>(
        &self,
        cache: C,
        w: W,
    ) -> io::Result<()> {
        self.write_for_stream(cache, w, StreamType::Stdout)
    }

    /// Write this diagnostic to an implementor of [`Write`], assuming that the output is ultimately going to be printed
    /// to the given output stream (`stdout` or `stderr`).
    fn write_for_stream<C: Cache<S::SourceId>, W: Write>(
        &self,
        mut cache: C,
        mut w: W,
        s: StreamType,
    ) -> io::Result<()> {
        let draw = match self.config.char_set {
            CharSet::Unicode => draw::Characters::unicode(),
            CharSet::Ascii => draw::Characters::ascii(),
        };

        // --- Header ---

        let code = self.code.as_ref().map(|c| format!("[{}] ", c));
        let id = format!("{}{}:", Show(code), self.kind);
        let kind_color = match self.kind {
            ReportKind::Error => self.config.error_color(),
            ReportKind::Warning => self.config.warning_color(),
            ReportKind::Advice => self.config.advice_color(),
            ReportKind::Custom(_, color) => Some(color),
        };
        writeln!(w, "{} {}", id.fg(kind_color, s), Show(self.msg.as_ref()))?;

        let groups = self.get_source_groups(&mut cache);

        // Line number maximum width
        let line_no_width = groups
            .iter()
            .filter_map(|SourceGroup { span, src_id, .. }| {
                let src_name = cache
                    .display(src_id)
                    .map(|d| d.to_string())
                    .unwrap_or_else(|| "<unknown>".to_string());

                let src = match cache.fetch(src_id) {
                    Ok(src) => src,
                    Err(e) => {
                        eprintln!("Unable to fetch source {}: {:?}", src_name, e);
                        return None;
                    }
                };

                let line_range = src.get_line_range(span);
                Some(
                    (1..)
                        .map(|x| 10u32.pow(x))
                        .take_while(|x| line_range.end as u32 / x != 0)
                        .count()
                        + 1,
                )
            })
            .max()
            .unwrap_or(0);

        // --- Source sections ---
        let groups_len = groups.len();
        for (
            group_idx,
            SourceGroup {
                src_id,
                span,
                labels,
            },
        ) in groups.into_iter().enumerate()
        {
            let src_name = cache
                .display(src_id)
                .map(|d| d.to_string())
                .unwrap_or_else(|| "<unknown>".to_string());

            let src = match cache.fetch(src_id) {
                Ok(src) => src,
                Err(e) => {
                    eprintln!("Unable to fetch source {}: {:?}", src_name, e);
                    continue;
                }
            };

            let line_range = src.get_line_range(&span);

            // File name & reference
            let location = if src_id == self.location.0.borrow() {
                self.location.1
            } else {
                labels[0].label.span.start()
            };
            let (line_no, col_no) = src
                .get_offset_line(location)
                .map(|(_, idx, col)| (format!("{}", idx + 1), format!("{}", col + 1)))
                .unwrap_or_else(|| ('?'.to_string(), '?'.to_string()));
            let line_ref = format!(":{}:{}", line_no, col_no);
            writeln!(
                w,
                "{}{}{}{}{}{}{}",
                Show((' ', line_no_width + 2)),
                if group_idx == 0 {
                    draw.ltop
                } else {
                    draw.lcross
                }
                .fg(self.config.margin_color(), s),
                draw.hbar.fg(self.config.margin_color(), s),
                draw.lbox.fg(self.config.margin_color(), s),
                src_name,
                line_ref,
                draw.rbox.fg(self.config.margin_color(), s),
            )?;

            if !self.config.compact {
                writeln!(
                    w,
                    "{}{}",
                    Show((' ', line_no_width + 2)),
                    draw.vbar.fg(self.config.margin_color(), s)
                )?;
            }

            struct LineLabel<'a, S> {
                col: usize,
                label: &'a Label<S>,
                multi: bool,
                draw_msg: bool,
            }

            // Generate a list of multi-line labels
            let mut multi_labels = Vec::new();
            let mut multi_labels_with_message = Vec::new();
            for label_info in &labels {
                if matches!(label_info.kind, LabelKind::Multiline) {
                    multi_labels.push(&label_info.label);
                    if label_info.label.msg.is_some() {
                        multi_labels_with_message.push(&label_info.label);
                    }
                }
            }

            // Sort multiline labels by length
            multi_labels.sort_by_key(|m| -(m.span.len() as isize));
            multi_labels_with_message.sort_by_key(|m| -(m.span.len() as isize));

            let write_margin = |w: &mut W,
                                idx: usize,
                                is_line: bool,
                                is_ellipsis: bool,
                                draw_labels: bool,
                                report_row: Option<(usize, bool)>,
                                line_labels: &[LineLabel<S>],
                                margin_label: &Option<LineLabel<S>>|
             -> std::io::Result<()> {
                let line_no_margin = if is_line && !is_ellipsis {
                    let line_no = format!("{}", idx + 1);
                    format!(
                        "{}{} {}",
                        Show((' ', line_no_width - line_no.chars().count())),
                        line_no,
                        draw.vbar,
                    )
                    .fg(self.config.margin_color(), s)
                } else {
                    format!(
                        "{}{}",
                        Show((' ', line_no_width + 1)),
                        if is_ellipsis {
                            draw.vbar_gap
                        } else {
                            draw.vbar
                        }
                    )
                    .fg(self.config.skipped_margin_color(), s)
                };

                write!(
                    w,
                    " {}{}",
                    line_no_margin,
                    Show(Some(' ').filter(|_| !self.config.compact)),
                )?;

                // Multi-line margins
                if draw_labels {
                    for col in 0..multi_labels_with_message.len() + (multi_labels_with_message.len() > 0) as usize {
                        let mut corner = None;
                        let mut hbar = None;
                        let mut vbar: Option<&&Label<S>> = None;
                        let mut margin_ptr = None;

                        let multi_label = multi_labels_with_message.get(col);
                        let line_span = src.line(idx).unwrap().span();

                        for (i, label) in multi_labels_with_message[0..(col + 1).min(multi_labels_with_message.len())]
                            .iter()
                            .enumerate()
                        {
                            let margin = margin_label
                                .as_ref()
                                .filter(|m| **label as *const _ == m.label as *const _);

                            if label.span.start() <= line_span.end
                                && label.span.end() > line_span.start
                            {
                                let is_parent = i != col;
                                let is_start = line_span.contains(&label.span.start());
                                let is_end = line_span.contains(&label.last_offset());

                                if let Some(margin) = margin.filter(|_| is_line) {
                                    margin_ptr = Some((margin, is_start));
                                } else if !is_start && (!is_end || is_line) {
                                    vbar = vbar.or(Some(*label).filter(|_| !is_parent));
                                } else if let Some((report_row, is_arrow)) = report_row {
                                    let label_row = line_labels
                                        .iter()
                                        .enumerate()
                                        .find(|(_, l)| **label as *const _ == l.label as *const _)
                                        .map_or(0, |(r, _)| r);
                                    if report_row == label_row {
                                        if let Some(margin) = margin {
                                            vbar = Some(&margin.label).filter(|_| col == i);
                                            if is_start {
                                                continue;
                                            }
                                        }

                                        if is_arrow {
                                            hbar = Some(**label);
                                            if !is_parent {
                                                corner = Some((label, is_start));
                                            }
                                        } else if !is_start {
                                            vbar = vbar.or(Some(*label).filter(|_| !is_parent));
                                        }
                                    } else {
                                        vbar = vbar.or(Some(*label).filter(|_| {
                                            !is_parent && (is_start ^ (report_row < label_row))
                                        }));
                                    }
                                }
                            }
                        }

                        if let (Some((margin, _is_start)), true) = (margin_ptr, is_line) {
                            let is_col = multi_label
                                .map_or(false, |ml| **ml as *const _ == margin.label as *const _);
                            let is_limit = col + 1 == multi_labels_with_message.len();
                            if !is_col && !is_limit {
                                hbar = hbar.or(Some(margin.label));
                            }
                        }

                        hbar = hbar.filter(|l| {
                            margin_label
                                .as_ref()
                                .map_or(true, |margin| margin.label as *const _ != *l as *const _)
                                || !is_line
                        });

                        let (a, b) = if let Some((label, is_start)) = corner {
                            (
                                if is_start { draw.ltop } else { draw.lbot }.fg(label.color, s),
                                draw.hbar.fg(label.color, s),
                            )
                        } else if let Some(label) =
                            hbar.filter(|_| vbar.is_some() && !self.config.cross_gap)
                        {
                            (draw.xbar.fg(label.color, s), draw.hbar.fg(label.color, s))
                        } else if let Some(label) = hbar {
                            (draw.hbar.fg(label.color, s), draw.hbar.fg(label.color, s))
                        } else if let Some(label) = vbar {
                            (
                                if is_ellipsis {
                                    draw.vbar_gap
                                } else {
                                    draw.vbar
                                }
                                .fg(label.color, s),
                                ' '.fg(None, s),
                            )
                        } else if let (Some((margin, is_start)), true) = (margin_ptr, is_line) {
                            let is_col = multi_label
                                .map_or(false, |ml| **ml as *const _ == margin.label as *const _);
                            let is_limit = col == multi_labels_with_message.len();
                            (
                                if is_limit {
                                    draw.rarrow
                                } else if is_col {
                                    if is_start {
                                        draw.ltop
                                    } else {
                                        draw.lcross
                                    }
                                } else {
                                    draw.hbar
                                }
                                .fg(margin.label.color, s),
                                if !is_limit { draw.hbar } else { ' ' }.fg(margin.label.color, s),
                            )
                        } else {
                            (' '.fg(None, s), ' '.fg(None, s))
                        };
                        write!(w, "{}", a)?;
                        if !self.config.compact {
                            write!(w, "{}", b)?;
                        }
                    }
                }

                Ok(())
            };

            let mut is_ellipsis = false;
            for idx in line_range {
                let line = if let Some(line) = src.line(idx) {
                    line
                } else {
                    continue;
                };

                let margin_label = multi_labels_with_message
                    .iter()
                    .enumerate()
                    .filter_map(|(_i, label)| {
                        let is_start = line.span().contains(&label.span.start());
                        let is_end = line.span().contains(&label.last_offset());
                        if is_start {
                            // TODO: Check to see whether multi is the first on the start line or first on the end line
                            Some(LineLabel {
                                col: label.span.start() - line.offset(),
                                label: **label,
                                multi: true,
                                draw_msg: false, // Multi-line spans don;t have their messages drawn at the start
                            })
                        } else if is_end {
                            Some(LineLabel {
                                col: label.last_offset() - line.offset(),
                                label: **label,
                                multi: true,
                                draw_msg: true, // Multi-line spans have their messages drawn at the end
                            })
                        } else {
                            None
                        }
                    })
                    .min_by_key(|ll| (ll.col, !ll.label.span.start()));

                // Generate a list of labels for this line, along with their label columns
                let mut line_labels = multi_labels_with_message
                    .iter()
                    .enumerate()
                    .filter_map(|(_i, label)| {
                        let is_start = line.span().contains(&label.span.start());
                        let is_end = line.span().contains(&label.last_offset());
                        if is_start
                            && margin_label
                                .as_ref()
                                .map_or(true, |m| **label as *const _ != m.label as *const _)
                        {
                            // TODO: Check to see whether multi is the first on the start line or first on the end line
                            Some(LineLabel {
                                col: label.span.start() - line.offset(),
                                label: **label,
                                multi: true,
                                draw_msg: false, // Multi-line spans don;t have their messages drawn at the start
                            })
                        } else if is_end {
                            Some(LineLabel {
                                col: label.last_offset() - line.offset(),
                                label: **label,
                                multi: true,
                                draw_msg: true, // Multi-line spans have their messages drawn at the end
                            })
                        } else {
                            None
                        }
                    })
                    .collect::<Vec<_>>();

                for label_info in labels.iter().filter(|l| {
                    l.label.span.start() >= line.span().start
                        && l.label.span.end() <= line.span().end
                }) {
                    if matches!(label_info.kind, LabelKind::Inline) {
                        line_labels.push(LineLabel {
                            col: match &self.config.label_attach {
                                LabelAttach::Start => label_info.label.span.start(),
                                LabelAttach::Middle => {
                                    (label_info.label.span.start() + label_info.label.span.end())
                                        / 2
                                }
                                LabelAttach::End => label_info.label.last_offset(),
                            }
                            .max(label_info.label.span.start())
                                - line.offset(),
                            label: label_info.label,
                            multi: false,
                            draw_msg: true,
                        });
                    }
                }

                // Skip this line if we don't have labels for it
                if line_labels.len() == 0 && margin_label.is_none() {
                    let within_label = multi_labels
                        .iter()
                        .any(|label| label.span.contains(line.span().start()));
                    if !is_ellipsis && within_label {
                        is_ellipsis = true;
                    } else {
                        if !self.config.compact && !is_ellipsis {
                            write_margin(&mut w, idx, false, is_ellipsis, false, None, &[], &None)?;
                            write!(w, "\n")?;
                        }
                        is_ellipsis = true;
                        continue;
                    }
                } else {
                    is_ellipsis = false;
                }

                // Sort the labels by their columns
                line_labels.sort_by_key(|ll| (ll.label.order, ll.col, !ll.label.span.start()));

                // Determine label bounds so we know where to put error messages
                let arrow_end_space = if self.config.compact { 1 } else { 2 };
                let arrow_len = line_labels.iter().fold(0, |l, ll| {
                    if ll.multi {
                        line.len()
                    } else {
                        l.max(ll.label.span.end().saturating_sub(line.offset()))
                    }
                }) + arrow_end_space;

                // Should we draw a vertical bar as part of a label arrow on this line?
                let get_vbar = |col, row| {
                    line_labels
                        .iter()
                        // Only labels with notes get an arrow
                        .enumerate()
                        .filter(|(_, ll)| {
                            ll.label.msg.is_some()
                                && margin_label
                                    .as_ref()
                                    .map_or(true, |m| ll.label as *const _ != m.label as *const _)
                        })
                        .find(|(j, ll)| {
                            ll.col == col && ((row <= *j && !ll.multi) || (row <= *j && ll.multi))
                        })
                        .map(|(_, ll)| ll)
                };

                let get_highlight = |col| {
                    margin_label
                        .iter()
                        .map(|ll| ll.label)
                        .chain(multi_labels.iter().map(|l| **l))
                        .chain(line_labels.iter().map(|l| l.label))
                        .filter(|l| l.span.contains(line.offset() + col))
                        // Prioritise displaying smaller spans
                        .min_by_key(|l| (-l.priority, l.span.len()))
                };

                let get_underline = |col| {
                    line_labels
                        .iter()
                        .filter(|ll| {
                            self.config.underlines
                        // Underlines only occur for inline spans (highlighting can occur for all spans)
                        && !ll.multi
                        && ll.label.span.contains(line.offset() + col)
                        })
                        // Prioritise displaying smaller spans
                        .min_by_key(|ll| (-ll.label.priority, ll.label.span.len()))
                };

                // Margin
                write_margin(
                    &mut w,
                    idx,
                    true,
                    is_ellipsis,
                    true,
                    None,
                    &line_labels,
                    &margin_label,
                )?;

                // Line
                if !is_ellipsis {
                    for (col, c) in src.get_line_text(line).unwrap().chars().enumerate() {
                        let color = if let Some(highlight) = get_highlight(col) {
                            highlight.color
                        } else {
                            self.config.unimportant_color()
                        };
                        let (c, width) = self.config.char_width(c, col);
                        if c.is_whitespace() {
                            for _ in 0..width {
                                write!(w, "{}", c.fg(color, s))?;
                            }
                        } else {
                            write!(w, "{}", c.fg(color, s))?;
                        };
                    }
                }
                write!(w, "\n")?;

                // Arrows
                for row in 0..line_labels.len() {
                    let line_label = &line_labels[row];
                    //No message to draw thus no arrow to draw
                    if line_label.label.msg.is_none() {
                        continue
                    }
                    if !self.config.compact {
                        // Margin alternate
                        write_margin(
                            &mut w,
                            idx,
                            false,
                            is_ellipsis,
                            true,
                            Some((row, false)),
                            &line_labels,
                            &margin_label,
                        )?;
                        // Lines alternate
                        let mut chars = src.get_line_text(line).unwrap().chars();
                        for col in 0..arrow_len {
                            let width =
                                chars.next().map_or(1, |c| self.config.char_width(c, col).1);

                            let vbar = get_vbar(col, row);
                            let underline = get_underline(col).filter(|_| row == 0);
                            let [c, tail] = if let Some(vbar_ll) = vbar {
                                let [c, tail] = if underline.is_some() {
                                    // TODO: Is this good?
                                    if vbar_ll.label.span.len() <= 1 || true {
                                        [draw.underbar, draw.underline]
                                    } else if line.offset() + col == vbar_ll.label.span.start() {
                                        [draw.ltop, draw.underbar]
                                    } else if line.offset() + col == vbar_ll.label.last_offset() {
                                        [draw.rtop, draw.underbar]
                                    } else {
                                        [draw.underbar, draw.underline]
                                    }
                                } else if vbar_ll.multi && row == 0 && self.config.multiline_arrows
                                {
                                    [draw.uarrow, ' ']
                                } else {
                                    [draw.vbar, ' ']
                                };
                                [
                                    c.fg(vbar_ll.label.color, s),
                                    tail.fg(vbar_ll.label.color, s),
                                ]
                            } else if let Some(underline_ll) = underline {
                                [draw.underline.fg(underline_ll.label.color, s); 2]
                            } else {
                                [' '.fg(None, s); 2]
                            };

                            for i in 0..width {
                                write!(w, "{}", if i == 0 { c } else { tail })?;
                            }
                        }
                        write!(w, "\n")?;
                    }

                    // Margin
                    write_margin(
                        &mut w,
                        idx,
                        false,
                        is_ellipsis,
                        true,
                        Some((row, true)),
                        &line_labels,
                        &margin_label,
                    )?;
                    // Lines
                    let mut chars = src.get_line_text(line).unwrap().chars();
                    for col in 0..arrow_len {
                        let width = chars.next().map_or(1, |c| self.config.char_width(c, col).1);

                        let is_hbar = (((col > line_label.col) ^ line_label.multi)
                            || (line_label.label.msg.is_some()
                                && line_label.draw_msg
                                && col > line_label.col))
                            && line_label.label.msg.is_some();
                        let [c, tail] = if col == line_label.col
                            && line_label.label.msg.is_some()
                            && margin_label.as_ref().map_or(true, |m| {
                                line_label.label as *const _ != m.label as *const _
                            }) {
                            [
                                if line_label.multi {
                                    if line_label.draw_msg {
                                        draw.mbot
                                    } else {
                                        draw.rbot
                                    }
                                } else {
                                    draw.lbot
                                }
                                .fg(line_label.label.color, s),
                                draw.hbar.fg(line_label.label.color, s),
                            ]
                        } else if let Some(vbar_ll) = get_vbar(col, row)
                            .filter(|_| (col != line_label.col || line_label.label.msg.is_some()))
                        {
                            if !self.config.cross_gap && is_hbar {
                                [
                                    draw.xbar.fg(line_label.label.color, s),
                                    ' '.fg(line_label.label.color, s),
                                ]
                            } else if is_hbar {
                                [draw.hbar.fg(line_label.label.color, s); 2]
                            } else {
                                [
                                    if vbar_ll.multi && row == 0 && self.config.compact {
                                        draw.uarrow
                                    } else {
                                        draw.vbar
                                    }
                                    .fg(vbar_ll.label.color, s),
                                    ' '.fg(line_label.label.color, s),
                                ]
                            }
                        } else if is_hbar {
                            [draw.hbar.fg(line_label.label.color, s); 2]
                        } else {
                            [' '.fg(None, s); 2]
                        };

                        if width > 0 {
                            write!(w, "{}", c)?;
                        }
                        for _ in 1..width {
                            write!(w, "{}", tail)?;
                        }
                    }
                    if line_label.draw_msg {
                        write!(w, " {}", Show(line_label.label.msg.as_ref()))?;
                    }
                    write!(w, "\n")?;
                }
            }

            let is_final_group = group_idx + 1 == groups_len;

            // Help
            if let (Some(note), true) = (&self.help, is_final_group) {
                if !self.config.compact {
                    write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
                    write!(w, "\n")?;
                }
                write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
                write!(w, "{}: {}\n", "Help".fg(self.config.note_color(), s), note)?;
            }

            // Note
            if let (Some(note), true) = (&self.note, is_final_group) {
                if !self.config.compact {
                    write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
                    write!(w, "\n")?;
                }
                write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
                write!(w, "{}: {}\n", "Note".fg(self.config.note_color(), s), note)?;
            }

            // Tail of report
            if !self.config.compact {
                if is_final_group {
                    let final_margin =
                        format!("{}{}", Show((draw.hbar, line_no_width + 2)), draw.rbot);
                    writeln!(w, "{}", final_margin.fg(self.config.margin_color(), s))?;
                } else {
                    writeln!(
                        w,
                        "{}{}",
                        Show((' ', line_no_width + 2)),
                        draw.vbar.fg(self.config.margin_color(), s)
                    )?;
                }
            }
        }
        Ok(())
    }
}

impl<S: Span> Label<S> {
    fn last_offset(&self) -> usize {
        self.span.end().saturating_sub(1).max(self.span.start())
    }
}

#[cfg(test)]
mod tests {
    //! These tests use [insta](https://insta.rs/). If you do `cargo install cargo-insta` you can
    //! automatically update the snapshots with `cargo insta review` or `cargo insta accept`.
    //!
    //! When adding new tests you can leave the string in the `assert_snapshot!` macro call empty:
    //!
    //!     assert_snapshot!(msg, @"");
    //!
    //! and insta will fill it in.

    use std::ops::Range;

    use insta::assert_snapshot;

    use crate::{Cache, CharSet, Config, Label, Report, ReportKind, Source, Span};

    impl<S: Span> Report<'_, S> {
        fn write_to_string<C: Cache<S::SourceId>>(&self, cache: C) -> String {
            let mut vec = Vec::new();
            self.write(cache, &mut vec).unwrap();
            String::from_utf8(vec).unwrap()
        }
    }

    fn no_color_and_ascii() -> Config {
        Config::default()
            .with_color(false)
            // Using Ascii so that the inline snapshots display correctly
            // even with fonts where characters like '┬' take up more space.
            .with_char_set(CharSet::Ascii)
    }

    #[test]
    fn one_message() {
        let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
            .with_config(no_color_and_ascii())
            .with_message("can't compare apples with oranges")
            .finish()
            .write_to_string(Source::from(""));
        assert_snapshot!(msg, @r###"
        Error: can't compare apples with oranges
        "###)
    }

    #[test]
    fn two_labels_without_messages() {
        let source = "apple == orange;";
        let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
            .with_config(no_color_and_ascii())
            .with_message("can't compare apples with oranges")
            .with_label(Label::new(0..5))
            .with_label(Label::new(9..15))
            .finish()
            .write_to_string(Source::from(source));
        // TODO: it would be nice if these spans still showed up (like codespan-reporting does)
        assert_snapshot!(msg, @r###"
        Error: can't compare apples with oranges
           ,-[<unknown>:1:1]
           |
         1 | apple == orange;
        ---'
        "###);
    }

    #[test]
    fn two_labels_with_messages() {
        let source = "apple == orange;";
        let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
            .with_config(no_color_and_ascii())
            .with_message("can't compare apples with oranges")
            .with_label(Label::new(0..5).with_message("This is an apple"))
            .with_label(Label::new(9..15).with_message("This is an orange"))
            .finish()
            .write_to_string(Source::from(source));
        // TODO: it would be nice if these lines didn't cross
        assert_snapshot!(msg, @r###"
        Error: can't compare apples with oranges
           ,-[<unknown>:1:1]
           |
         1 | apple == orange;
           | ^^|^^    ^^^|^^  
           |   `-------------- This is an apple
           |             |    
           |             `---- This is an orange
        ---'
        "###);
    }

    #[test]
    fn label_at_end_of_long_line() {
        let source = format!("{}orange", "apple == ".repeat(100));
        let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
            .with_config(no_color_and_ascii())
            .with_message("can't compare apples with oranges")
            .with_label(
                Label::new(source.len() - 5..source.len()).with_message("This is an orange"),
            )
            .finish()
            .write_to_string(Source::from(source));
        // TODO: it would be nice if the start of long lines would be omitted (like rustc does)
        assert_snapshot!(msg, @r###"
        Error: can't compare apples with oranges
           ,-[<unknown>:1:1]
           |
         1 | apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == apple == orange
           |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      ^^|^^  
           |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        `---- This is an orange
        ---'
        "###);
    }

    #[test]
    fn multiline_label() {
        let source = "apple\n==\norange";
        let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
            .with_config(no_color_and_ascii())
            .with_label(Label::new(0..source.len()).with_message("illegal comparison"))
            .finish()
            .write_to_string(Source::from(source));
        // TODO: it would be nice if the 2nd line wasn't omitted
        assert_snapshot!(msg, @r###"
        Error: 
           ,-[<unknown>:1:1]
           |
         1 | ,-> apple
           : :   
         3 | |-> orange
           | |           
           | `----------- illegal comparison
        ---'
        "###);
    }

    #[test]
    fn partially_overlapping_labels() {
        let source = "https://example.com/";
        let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
            .with_config(no_color_and_ascii())
            .with_label(Label::new(0..source.len()).with_message("URL"))
            .with_label(Label::new(0..source.find(':').unwrap()).with_message("scheme"))
            .finish()
            .write_to_string(Source::from(source));
        // TODO: it would be nice if you could tell where the spans start and end.
        assert_snapshot!(msg, @r###"
        Error: 
           ,-[<unknown>:1:1]
           |
         1 | https://example.com/
           | ^^|^^^^^^^|^^^^^^^^^  
           |   `------------------- scheme
           |           |           
           |           `----------- URL
        ---'
        "###);
    }

    #[test]
    fn multiple_labels_same_span() {
        let source = "apple == orange;";
        let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
            .with_config(no_color_and_ascii())
            .with_message("can't compare apples with oranges")
            .with_label(Label::new(0..5).with_message("This is an apple"))
            .with_label(Label::new(0..5).with_message("Have I mentioned that this is an apple?"))
            .with_label(Label::new(0..5).with_message("No really, have I mentioned that?"))
            .with_label(Label::new(9..15).with_message("This is an orange"))
            .with_label(Label::new(9..15).with_message("Have I mentioned that this is an orange?"))
            .with_label(Label::new(9..15).with_message("No really, have I mentioned that?"))
            .finish()
            .write_to_string(Source::from(source));
        assert_snapshot!(msg, @r###"
        Error: can't compare apples with oranges
           ,-[<unknown>:1:1]
           |
         1 | apple == orange;
           | ^^|^^    ^^^|^^  
           |   `-------------- This is an apple
           |   |         |    
           |   `-------------- Have I mentioned that this is an apple?
           |   |         |    
           |   `-------------- No really, have I mentioned that?
           |             |    
           |             `---- This is an orange
           |             |    
           |             `---- Have I mentioned that this is an orange?
           |             |    
           |             `---- No really, have I mentioned that?
        ---'
        "###)
    }

    #[test]
    fn note() {
        let source = "apple == orange;";
        let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
            .with_config(no_color_and_ascii())
            .with_message("can't compare apples with oranges")
            .with_label(Label::new(0..5).with_message("This is an apple"))
            .with_label(Label::new(9..15).with_message("This is an orange"))
            .with_note("stop trying ... this is a fruitless endeavor")
            .finish()
            .write_to_string(Source::from(source));
        assert_snapshot!(msg, @r###"
        Error: can't compare apples with oranges
           ,-[<unknown>:1:1]
           |
         1 | apple == orange;
           | ^^|^^    ^^^|^^  
           |   `-------------- This is an apple
           |             |    
           |             `---- This is an orange
           | 
           | Note: stop trying ... this is a fruitless endeavor
        ---'
        "###)
    }

    #[test]
    fn help() {
        let source = "apple == orange;";
        let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
            .with_config(no_color_and_ascii())
            .with_message("can't compare apples with oranges")
            .with_label(Label::new(0..5).with_message("This is an apple"))
            .with_label(Label::new(9..15).with_message("This is an orange"))
            .with_help("have you tried peeling the orange?")
            .finish()
            .write_to_string(Source::from(source));
        assert_snapshot!(msg, @r###"
        Error: can't compare apples with oranges
           ,-[<unknown>:1:1]
           |
         1 | apple == orange;
           | ^^|^^    ^^^|^^  
           |   `-------------- This is an apple
           |             |    
           |             `---- This is an orange
           | 
           | Help: have you tried peeling the orange?
        ---'
        "###)
    }

    #[test]
    fn help_and_note() {
        let source = "apple == orange;";
        let msg = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
            .with_config(no_color_and_ascii())
            .with_message("can't compare apples with oranges")
            .with_label(Label::new(0..5).with_message("This is an apple"))
            .with_label(Label::new(9..15).with_message("This is an orange"))
            .with_help("have you tried peeling the orange?")
            .with_note("stop trying ... this is a fruitless endeavor")
            .finish()
            .write_to_string(Source::from(source));
        assert_snapshot!(msg, @r###"
        Error: can't compare apples with oranges
           ,-[<unknown>:1:1]
           |
         1 | apple == orange;
           | ^^|^^    ^^^|^^  
           |   `-------------- This is an apple
           |             |    
           |             `---- This is an orange
           | 
           | Help: have you tried peeling the orange?
           | 
           | Note: stop trying ... this is a fruitless endeavor
        ---'
        "###)
    }
}