Debian Codegraph @

debian/rust-vendor/ariadne/src/write.rs

raw
1 use std::io;
2 use std::ops::Range;
3
4 use crate::{IndexType, LabelDisplay};
5
6 use super::draw::{self, StreamAwareFmt, StreamType};
7 use super::{Cache, CharSet, LabelAttach, Report, ReportKind, Show, Span, Write};
8
9 // A WARNING, FOR ALL YE WHO VENTURE IN HERE
10 //
11 // - This code is complex and has a lot of implicit invariants
12 // - Yes, it has some bugs
13 // - Yes, it needs rewriting
14 // - No, you are not expected to understand it. I will probably not understand it either in a month, but that will only
15 // give me a reason to rewrite it
16
17 enum LabelKind {
18 Inline,
19 Multiline,
20 }
21
22 struct LabelInfo<'a> {
23 kind: LabelKind,
24 char_span: Range<usize>,
25 display_info: &'a LabelDisplay,
26 line: usize,
27 }
28
29 impl<'a> LabelInfo<'a> {
30 fn last_offset(&self) -> usize {
31 self.char_span
32 .end
33 .saturating_sub(1)
34 .max(self.char_span.start)
35 }
36 }
37
38 struct SourceGroup<'a, S: Span> {
39 src_id: &'a S::SourceId,
40 char_span: Range<usize>,
41 labels: Vec<LabelInfo<'a>>,
42 }
43
44 impl<S: Span> Report<'_, S> {
45 fn get_source_groups(&self, cache: &mut impl Cache<S::SourceId>) -> Vec<SourceGroup<S>> {
46 let mut labels = Vec::new();
47 for label in self.labels.iter() {
48 let label_source = label.span.source();
49
50 let src_display = cache.display(label_source);
51 let src = match cache.fetch(label_source) {
52 Ok(src) => src,
53 Err(e) => {
54 eprintln!("Unable to fetch source '{}': {:?}", Show(src_display), e);
55 continue;
56 }
57 };
58
59 let given_label_span = label.span.start()..label.span.end();
60
61 let (label_char_span, start_line, end_line) = match self.config.index_type {
62 IndexType::Char => {
63 let Some(start_line) = src.get_offset_line(given_label_span.start) else {
64 continue;
65 };
66 let end_line = if given_label_span.start >= given_label_span.end {
67 start_line.1
68 } else {
69 let Some(end_line) = src.get_offset_line(given_label_span.end - 1) else {
70 continue;
71 };
72 end_line.1
73 };
74 (given_label_span, start_line.1, end_line)
75 }
76 IndexType::Byte => {
77 let Some((start_line_obj, start_line, start_byte_col)) =
78 src.get_byte_line(given_label_span.start)
79 else {
80 continue;
81 };
82 let line_text = src.get_line_text(start_line_obj).unwrap();
83
84 let num_chars_before_start = line_text[..start_byte_col.min(line_text.len())]
85 .chars()
86 .count();
87 let start_char_offset = start_line_obj.offset() + num_chars_before_start;
88
89 if given_label_span.start >= given_label_span.end {
90 (start_char_offset..start_char_offset, start_line, start_line)
91 } else {
92 // We can subtract 1 from end, because get_byte_line doesn't actually index into the text.
93 let end_pos = given_label_span.end - 1;
94 let Some((end_line_obj, end_line, end_byte_col)) =
95 src.get_byte_line(end_pos)
96 else {
97 continue;
98 };
99 let end_line_text = src.get_line_text(end_line_obj).unwrap();
100 // Have to add 1 back now, so we don't cut a char in two.
101 let num_chars_before_end =
102 end_line_text[..end_byte_col + 1].chars().count();
103 let end_char_offset = end_line_obj.offset() + num_chars_before_end;
104
105 (start_char_offset..end_char_offset, start_line, end_line)
106 }
107 }
108 };
109
110 let label_info = LabelInfo {
111 kind: if start_line == end_line {
112 LabelKind::Inline
113 } else {
114 LabelKind::Multiline
115 },
116 char_span: label_char_span,
117 display_info: &label.display_info,
118 line: end_line,
119 };
120
121 labels.push((label_info, label_source));
122 }
123 labels.sort_by_key(|(l, _)| l.display_info.order);
124 let mut groups = Vec::<SourceGroup<_>>::new();
125 for (label, src_id) in labels {
126 match groups.last_mut() {
127 Some(group)
128 if group.src_id == src_id
129 && group
130 .labels
131 .last()
132 .map_or(true, |last| last.line <= label.line) =>
133 {
134 group.char_span.start = group.char_span.start.min(label.char_span.start);
135 group.char_span.end = group.char_span.end.max(label.char_span.end);
136 group.labels.push(label);
137 }
138 _ => {
139 groups.push(SourceGroup {
140 src_id: src_id,
141 char_span: label.char_span.clone(),
142 labels: vec![label],
143 });
144 }
145 }
146 }
147 groups
148 }
149
150 /// Write this diagnostic to an implementor of [`Write`].
151 ///
152 /// If using the `concolor` feature, this method assumes that the output is ultimately going to be printed to
153 /// `stderr`. If you are printing to `stdout`, use the [`write_for_stdout`](Self::write_for_stdout) method instead.
154 ///
155 /// If you wish to write to `stderr` or `stdout`, you can do so via [`Report::eprint`] or [`Report::print`] respectively.
156 pub fn write<C: Cache<S::SourceId>, W: Write>(&self, cache: C, w: W) -> io::Result<()> {
157 self.write_for_stream(cache, w, StreamType::Stderr)
158 }
159
160 /// Write this diagnostic to an implementor of [`Write`], assuming that the output is ultimately going to be printed
161 /// to `stdout`.
162 pub fn write_for_stdout<C: Cache<S::SourceId>, W: Write>(
163 &self,
164 cache: C,
165 w: W,
166 ) -> io::Result<()> {
167 self.write_for_stream(cache, w, StreamType::Stdout)
168 }
169
170 /// Write this diagnostic to an implementor of [`Write`], assuming that the output is ultimately going to be printed
171 /// to the given output stream (`stdout` or `stderr`).
172 fn write_for_stream<C: Cache<S::SourceId>, W: Write>(
173 &self,
174 mut cache: C,
175 mut w: W,
176 s: StreamType,
177 ) -> io::Result<()> {
178 let draw = match self.config.char_set {
179 CharSet::Unicode => draw::Characters::unicode(),
180 CharSet::Ascii => draw::Characters::ascii(),
181 };
182
183 // --- Header ---
184
185 let code = self.code.as_ref().map(|c| format!("[{}] ", c));
186 let id = format!("{}{}:", Show(code), self.kind);
187 let kind_color = match self.kind {
188 ReportKind::Error => self.config.error_color(),
189 ReportKind::Warning => self.config.warning_color(),
190 ReportKind::Advice => self.config.advice_color(),
191 ReportKind::Custom(_, color) => Some(color),
192 };
193 writeln!(w, "{} {}", id.fg(kind_color, s), Show(self.msg.as_ref()))?;
194
195 let groups = self.get_source_groups(&mut cache);
196
197 // Line number maximum width
198 let line_no_width = groups
199 .iter()
200 .filter_map(
201 |SourceGroup {
202 char_span, src_id, ..
203 }| {
204 let src_name = cache
205 .display(src_id)
206 .map(|d| d.to_string())
207 .unwrap_or_else(|| "<unknown>".to_string());
208
209 let src = match cache.fetch(src_id) {
210 Ok(src) => src,
211 Err(e) => {
212 eprintln!("Unable to fetch source {}: {:?}", src_name, e);
213 return None;
214 }
215 };
216
217 let line_range = src.get_line_range(char_span);
218 Some(
219 (1..)
220 .map(|x| 10u32.pow(x))
221 .take_while(|x| line_range.end as u32 / x != 0)
222 .count()
223 + 1,
224 )
225 },
226 )
227 .max()
228 .unwrap_or(0);
229
230 // --- Source sections ---
231 let groups_len = groups.len();
232 for (
233 group_idx,
234 SourceGroup {
235 src_id,
236 char_span,
237 labels,
238 },
239 ) in groups.into_iter().enumerate()
240 {
241 let src_name = cache
242 .display(src_id)
243 .map(|d| d.to_string())
244 .unwrap_or_else(|| "<unknown>".to_string());
245
246 let src = match cache.fetch(src_id) {
247 Ok(src) => src,
248 Err(e) => {
249 eprintln!("Unable to fetch source {}: {:?}", src_name, e);
250 continue;
251 }
252 };
253
254 let line_range = src.get_line_range(&char_span);
255
256 // File name & reference
257 let location = if src_id == self.span.source() {
258 self.span.start()
259 } else {
260 labels[0].char_span.start
261 };
262 let line_and_col = match self.config.index_type {
263 IndexType::Char => src.get_offset_line(location),
264 IndexType::Byte => src.get_byte_line(location).map(|(line_obj, idx, col)| {
265 let line_text = src.get_line_text(line_obj).unwrap();
266
267 let col = line_text[..col.min(line_text.len())].chars().count();
268
269 (line_obj, idx, col)
270 }),
271 };
272 let (line_no, col_no) = line_and_col
273 .map(|(_, idx, col)| {
274 (
275 format!("{}", idx + 1 + src.display_line_offset()),
276 format!("{}", col + 1),
277 )
278 })
279 .unwrap_or_else(|| ('?'.to_string(), '?'.to_string()));
280 let line_ref = format!("{}:{}:{}", src_name, line_no, col_no);
281 writeln!(
282 w,
283 "{}{}{}{} {} {}",
284 Show((' ', line_no_width + 2)),
285 if group_idx == 0 {
286 draw.ltop
287 } else {
288 draw.lcross
289 }
290 .fg(self.config.margin_color(), s),
291 draw.hbar.fg(self.config.margin_color(), s),
292 draw.lbox.fg(self.config.margin_color(), s),
293 line_ref,
294 draw.rbox.fg(self.config.margin_color(), s),
295 )?;
296
297 if !self.config.compact {
298 writeln!(
299 w,
300 "{}{}",
301 Show((' ', line_no_width + 2)),
302 draw.vbar.fg(self.config.margin_color(), s)
303 )?;
304 }
305
306 struct LineLabel<'a> {
307 col: usize,
308 label: &'a LabelInfo<'a>,
309 multi: bool,
310 draw_msg: bool,
311 }
312
313 // Generate a list of multi-line labels
314 let mut multi_labels = Vec::new();
315 let mut multi_labels_with_message = Vec::new();
316 for label_info in &labels {
317 if matches!(label_info.kind, LabelKind::Multiline) {
318 multi_labels.push(label_info);
319 if label_info.display_info.msg.is_some() {
320 multi_labels_with_message.push(label_info);
321 }
322 }
323 }
324
325 // Sort multiline labels by length
326 multi_labels.sort_by_key(|m| -(Span::len(&m.char_span) as isize));
327 multi_labels_with_message.sort_by_key(|m| -(Span::len(&m.char_span) as isize));
328
329 let write_margin = |w: &mut W,
330 idx: usize,
331 is_line: bool,
332 is_ellipsis: bool,
333 draw_labels: bool,
334 report_row: Option<(usize, bool)>,
335 line_labels: &[LineLabel],
336 margin_label: &Option<LineLabel>|
337 -> std::io::Result<()> {
338 let line_no_margin = if is_line && !is_ellipsis {
339 let line_no = format!("{}", idx + 1);
340 format!(
341 "{}{} {}",
342 Show((' ', line_no_width - line_no.chars().count())),
343 line_no,
344 draw.vbar,
345 )
346 .fg(self.config.margin_color(), s)
347 } else {
348 format!(
349 "{}{}",
350 Show((' ', line_no_width + 1)),
351 if is_ellipsis {
352 draw.vbar_gap
353 } else {
354 draw.vbar
355 }
356 )
357 .fg(self.config.skipped_margin_color(), s)
358 };
359
360 write!(
361 w,
362 " {}{}",
363 line_no_margin,
364 Show(Some(' ').filter(|_| !self.config.compact)),
365 )?;
366
367 // Multi-line margins
368 if draw_labels {
369 for col in 0..multi_labels_with_message.len()
370 + (!multi_labels_with_message.is_empty()) as usize
371 {
372 let mut corner = None;
373 let mut hbar: Option<&LabelInfo> = None;
374 let mut vbar: Option<&LabelInfo> = None;
375 let mut margin_ptr = None;
376
377 let multi_label = multi_labels_with_message.get(col);
378 let line_span = src.line(idx).unwrap().span();
379
380 for (i, label) in multi_labels_with_message
381 [0..(col + 1).min(multi_labels_with_message.len())]
382 .iter()
383 .enumerate()
384 {
385 let margin = margin_label
386 .as_ref()
387 .filter(|m| std::ptr::eq(*label, m.label));
388
389 if label.char_span.start <= line_span.end
390 && label.char_span.end > line_span.start
391 {
392 let is_parent = i != col;
393 let is_start = line_span.contains(&label.char_span.start);
394 let is_end = line_span.contains(&label.last_offset());
395
396 if let Some(margin) = margin.filter(|_| is_line) {
397 margin_ptr = Some((margin, is_start));
398 } else if !is_start && (!is_end || is_line) {
399 vbar = vbar.or(Some(*label).filter(|_| !is_parent));
400 } else if let Some((report_row, is_arrow)) = report_row {
401 let label_row = line_labels
402 .iter()
403 .enumerate()
404 .find(|(_, l)| std::ptr::eq(*label, l.label))
405 .map_or(0, |(r, _)| r);
406 if report_row == label_row {
407 if let Some(margin) = margin {
408 vbar = Some(margin.label).filter(|_| col == i);
409 if is_start {
410 continue;
411 }
412 }
413
414 if is_arrow {
415 hbar = Some(*label);
416 if !is_parent {
417 corner = Some((label, is_start));
418 }
419 } else if !is_start {
420 vbar = vbar.or(Some(*label).filter(|_| !is_parent));
421 }
422 } else {
423 vbar = vbar.or(Some(*label).filter(|_| {
424 !is_parent && (is_start ^ (report_row < label_row))
425 }));
426 }
427 }
428 }
429 }
430
431 if let (Some((margin, _is_start)), true) = (margin_ptr, is_line) {
432 let is_col =
433 multi_label.map_or(false, |ml| std::ptr::eq(*ml, margin.label));
434 let is_limit = col + 1 == multi_labels_with_message.len();
435 if !is_col && !is_limit {
436 hbar = hbar.or(Some(margin.label));
437 }
438 }
439
440 hbar = hbar.filter(|l| {
441 margin_label
442 .as_ref()
443 .map_or(true, |margin| !std::ptr::eq(margin.label, *l))
444 || !is_line
445 });
446
447 let (a, b) = if let Some((label, is_start)) = corner {
448 (
449 if is_start { draw.ltop } else { draw.lbot }
450 .fg(label.display_info.color, s),
451 draw.hbar.fg(label.display_info.color, s),
452 )
453 } else if let Some(label) =
454 hbar.filter(|_| vbar.is_some() && !self.config.cross_gap)
455 {
456 (
457 draw.xbar.fg(label.display_info.color, s),
458 draw.hbar.fg(label.display_info.color, s),
459 )
460 } else if let Some(label) = hbar {
461 (
462 draw.hbar.fg(label.display_info.color, s),
463 draw.hbar.fg(label.display_info.color, s),
464 )
465 } else if let Some(label) = vbar {
466 (
467 if is_ellipsis {
468 draw.vbar_gap
469 } else {
470 draw.vbar
471 }
472 .fg(label.display_info.color, s),
473 ' '.fg(None, s),
474 )
475 } else if let (Some((margin, is_start)), true) = (margin_ptr, is_line) {
476 let is_col =
477 multi_label.map_or(false, |ml| std::ptr::eq(*ml, margin.label));
478 let is_limit = col == multi_labels_with_message.len();
479 (
480 if is_limit {
481 draw.rarrow
482 } else if is_col {
483 if is_start {
484 draw.ltop
485 } else {
486 draw.lcross
487 }
488 } else {
489 draw.hbar
490 }
491 .fg(margin.label.display_info.color, s),
492 if !is_limit { draw.hbar } else { ' ' }
493 .fg(margin.label.display_info.color, s),
494 )
495 } else {
496 (' '.fg(None, s), ' '.fg(None, s))
497 };
498 write!(w, "{}", a)?;
499 if !self.config.compact {
500 write!(w, "{}", b)?;
501 }
502 }
503 }
504
505 Ok(())
506 };
507
508 let mut is_ellipsis = false;
509 for idx in line_range {
510 let line = if let Some(line) = src.line(idx) {
511 line
512 } else {
513 continue;
514 };
515
516 let margin_label = multi_labels_with_message
517 .iter()
518 .enumerate()
519 .filter_map(|(_i, label)| {
520 let is_start = line.span().contains(&label.char_span.start);
521 let is_end = line.span().contains(&label.last_offset());
522 if is_start {
523 // TODO: Check to see whether multi is the first on the start line or first on the end line
524 Some(LineLabel {
525 col: label.char_span.start - line.offset(),
526 label,
527 multi: true,
528 draw_msg: false, // Multi-line spans don;t have their messages drawn at the start
529 })
530 } else if is_end {
531 Some(LineLabel {
532 col: label.last_offset() - line.offset(),
533 label,
534 multi: true,
535 draw_msg: true, // Multi-line spans have their messages drawn at the end
536 })
537 } else {
538 None
539 }
540 })
541 .min_by_key(|ll| (ll.col, !ll.label.char_span.start));
542
543 // Generate a list of labels for this line, along with their label columns
544 let mut line_labels = multi_labels_with_message
545 .iter()
546 .enumerate()
547 .filter_map(|(_i, label)| {
548 let is_start = line.span().contains(&label.char_span.start);
549 let is_end = line.span().contains(&label.last_offset());
550 if is_start
551 && margin_label
552 .as_ref()
553 .map_or(true, |m| !std::ptr::eq(*label, m.label))
554 {
555 // TODO: Check to see whether multi is the first on the start line or first on the end line
556 Some(LineLabel {
557 col: label.char_span.start - line.offset(),
558 label,
559 multi: true,
560 draw_msg: false, // Multi-line spans don;t have their messages drawn at the start
561 })
562 } else if is_end {
563 Some(LineLabel {
564 col: label.last_offset() - line.offset(),
565 label,
566 multi: true,
567 draw_msg: true, // Multi-line spans have their messages drawn at the end
568 })
569 } else {
570 None
571 }
572 })
573 .collect::<Vec<_>>();
574
575 for label_info in labels.iter().filter(|l| {
576 l.char_span.start >= line.span().start && l.char_span.end <= line.span().end
577 }) {
578 if matches!(label_info.kind, LabelKind::Inline) {
579 line_labels.push(LineLabel {
580 col: match &self.config.label_attach {
581 LabelAttach::Start => label_info.char_span.start,
582 LabelAttach::Middle => {
583 (label_info.char_span.start + label_info.char_span.end) / 2
584 }
585 LabelAttach::End => label_info.last_offset(),
586 }
587 .max(label_info.char_span.start)
588 - line.offset(),
589 label: label_info,
590 multi: false,
591 draw_msg: true,
592 });
593 }
594 }
595
596 // Skip this line if we don't have labels for it
597 if line_labels.is_empty() && margin_label.is_none() {
598 let within_label = multi_labels
599 .iter()
600 .any(|label| label.char_span.contains(&line.span().start()));
601 if !is_ellipsis && within_label {
602 is_ellipsis = true;
603 } else {
604 if !self.config.compact && !is_ellipsis {
605 write_margin(&mut w, idx, false, is_ellipsis, false, None, &[], &None)?;
606 writeln!(w)?;
607 }
608 is_ellipsis = true;
609 continue;
610 }
611 } else {
612 is_ellipsis = false;
613 }
614
615 // Sort the labels by their columns
616 line_labels.sort_by_key(|ll| {
617 (
618 ll.label.display_info.order,
619 ll.col,
620 !ll.label.char_span.start,
621 )
622 });
623
624 // Determine label bounds so we know where to put error messages
625 let arrow_end_space = if self.config.compact { 1 } else { 2 };
626 let arrow_len = line_labels.iter().fold(0, |l, ll| {
627 if ll.multi {
628 line.len()
629 } else {
630 l.max(ll.label.char_span.end().saturating_sub(line.offset()))
631 }
632 }) + arrow_end_space;
633
634 // Should we draw a vertical bar as part of a label arrow on this line?
635 let get_vbar = |col, row| {
636 line_labels
637 .iter()
638 // Only labels with notes get an arrow
639 .enumerate()
640 .filter(|(_, ll)| {
641 ll.label.display_info.msg.is_some()
642 && margin_label
643 .as_ref()
644 .map_or(true, |m| !std::ptr::eq(ll.label, m.label))
645 })
646 .find(|(j, ll)| ll.col == col && row <= *j)
647 .map(|(_, ll)| ll)
648 };
649
650 let get_highlight = |col| {
651 margin_label
652 .iter()
653 .map(|ll| &ll.label)
654 .chain(multi_labels.iter())
655 .chain(line_labels.iter().map(|l| &l.label))
656 .filter(|l| l.char_span.contains(&(line.offset() + col)))
657 // Prioritise displaying smaller spans
658 .min_by_key(|l| {
659 (
660 -l.display_info.priority,
661 ExactSizeIterator::len(&l.char_span),
662 )
663 })
664 };
665
666 let get_underline = |col| {
667 line_labels
668 .iter()
669 .filter(|ll| {
670 self.config.underlines
671 // Underlines only occur for inline spans (highlighting can occur for all spans)
672 && !ll.multi
673 && ll.label.char_span.contains(&(line.offset() + col))
674 })
675 // Prioritise displaying smaller spans
676 .min_by_key(|ll| {
677 (
678 -ll.label.display_info.priority,
679 ExactSizeIterator::len(&ll.label.char_span),
680 )
681 })
682 };
683
684 // Margin
685 write_margin(
686 &mut w,
687 idx,
688 true,
689 is_ellipsis,
690 true,
691 None,
692 &line_labels,
693 &margin_label,
694 )?;
695
696 // Line
697 if !is_ellipsis {
698 for (col, c) in src
699 .get_line_text(line)
700 .unwrap()
701 .trim_end()
702 .chars()
703 .enumerate()
704 {
705 let color = if let Some(highlight) = get_highlight(col) {
706 highlight.display_info.color
707 } else {
708 self.config.unimportant_color()
709 };
710 let (c, width) = self.config.char_width(c, col);
711 if c.is_whitespace() {
712 for _ in 0..width {
713 write!(w, "{}", c.fg(color, s))?;
714 }
715 } else {
716 write!(w, "{}", c.fg(color, s))?;
717 };
718 }
719 }
720 writeln!(w)?;
721
722 // Arrows
723 for row in 0..line_labels.len() {
724 let line_label = &line_labels[row];
725 //No message to draw thus no arrow to draw
726 if line_label.label.display_info.msg.is_none() {
727 continue;
728 }
729 if !self.config.compact {
730 // Margin alternate
731 write_margin(
732 &mut w,
733 idx,
734 false,
735 is_ellipsis,
736 true,
737 Some((row, false)),
738 &line_labels,
739 &margin_label,
740 )?;
741 // Lines alternate
742 let mut chars = src.get_line_text(line).unwrap().trim_end().chars();
743 for col in 0..arrow_len {
744 let width =
745 chars.next().map_or(1, |c| self.config.char_width(c, col).1);
746
747 let vbar = get_vbar(col, row);
748 let underline = get_underline(col).filter(|_| row == 0);
749 let [c, tail] = if let Some(vbar_ll) = vbar {
750 let [c, tail] = if underline.is_some() {
751 // TODO: Is this good?
752 // The `true` is used here because it's temporarily disabling a
753 // feature that might be reenabled later.
754 #[allow(clippy::overly_complex_bool_expr)]
755 if ExactSizeIterator::len(&vbar_ll.label.char_span) <= 1 || true
756 {
757 [draw.underbar, draw.underline]
758 } else if line.offset() + col == vbar_ll.label.char_span.start {
759 [draw.ltop, draw.underbar]
760 } else if line.offset() + col == vbar_ll.label.last_offset() {
761 [draw.rtop, draw.underbar]
762 } else {
763 [draw.underbar, draw.underline]
764 }
765 } else if vbar_ll.multi && row == 0 && self.config.multiline_arrows
766 {
767 [draw.uarrow, ' ']
768 } else {
769 [draw.vbar, ' ']
770 };
771 [
772 c.fg(vbar_ll.label.display_info.color, s),
773 tail.fg(vbar_ll.label.display_info.color, s),
774 ]
775 } else if let Some(underline_ll) = underline {
776 [draw.underline.fg(underline_ll.label.display_info.color, s); 2]
777 } else {
778 [' '.fg(None, s); 2]
779 };
780
781 for i in 0..width {
782 write!(w, "{}", if i == 0 { c } else { tail })?;
783 }
784 }
785 writeln!(w)?;
786 }
787
788 // Margin
789 write_margin(
790 &mut w,
791 idx,
792 false,
793 is_ellipsis,
794 true,
795 Some((row, true)),
796 &line_labels,
797 &margin_label,
798 )?;
799 // Lines
800 let mut chars = src.get_line_text(line).unwrap().trim_end().chars();
801 for col in 0..arrow_len {
802 let width = chars.next().map_or(1, |c| self.config.char_width(c, col).1);
803
804 let is_hbar = (((col > line_label.col) ^ line_label.multi)
805 || (line_label.label.display_info.msg.is_some()
806 && line_label.draw_msg
807 && col > line_label.col))
808 && line_label.label.display_info.msg.is_some();
809 let [c, tail] = if col == line_label.col
810 && line_label.label.display_info.msg.is_some()
811 && margin_label
812 .as_ref()
813 .map_or(true, |m| !std::ptr::eq(line_label.label, m.label))
814 {
815 [
816 if line_label.multi {
817 if line_label.draw_msg {
818 draw.mbot
819 } else {
820 draw.rbot
821 }
822 } else {
823 draw.lbot
824 }
825 .fg(line_label.label.display_info.color, s),
826 draw.hbar.fg(line_label.label.display_info.color, s),
827 ]
828 } else if let Some(vbar_ll) = get_vbar(col, row).filter(|_| {
829 col != line_label.col || line_label.label.display_info.msg.is_some()
830 }) {
831 if !self.config.cross_gap && is_hbar {
832 [
833 draw.xbar.fg(line_label.label.display_info.color, s),
834 ' '.fg(line_label.label.display_info.color, s),
835 ]
836 } else if is_hbar {
837 [draw.hbar.fg(line_label.label.display_info.color, s); 2]
838 } else {
839 [
840 if vbar_ll.multi && row == 0 && self.config.compact {
841 draw.uarrow
842 } else {
843 draw.vbar
844 }
845 .fg(vbar_ll.label.display_info.color, s),
846 ' '.fg(line_label.label.display_info.color, s),
847 ]
848 }
849 } else if is_hbar {
850 [draw.hbar.fg(line_label.label.display_info.color, s); 2]
851 } else {
852 [' '.fg(None, s); 2]
853 };
854
855 if width > 0 {
856 write!(w, "{}", c)?;
857 }
858 for _ in 1..width {
859 write!(w, "{}", tail)?;
860 }
861 }
862 if line_label.draw_msg {
863 write!(w, " {}", Show(line_label.label.display_info.msg.as_ref()))?;
864 }
865 writeln!(w)?;
866 }
867 }
868
869 let is_final_group = group_idx + 1 == groups_len;
870
871 // Help
872 if is_final_group {
873 for (i, help) in self.help.iter().enumerate() {
874 if !self.config.compact {
875 write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
876 writeln!(w)?;
877 }
878 let help_prefix = format!("{} {}", "Help", i + 1);
879 let help_prefix_len = if self.help.len() > 1 {
880 help_prefix.len()
881 } else {
882 4
883 };
884 let mut lines = help.lines();
885 if let Some(line) = lines.next() {
886 write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
887 if self.help.len() > 1 {
888 writeln!(
889 w,
890 "{}: {}",
891 help_prefix.fg(self.config.note_color(), s),
892 line
893 )?;
894 } else {
895 writeln!(w, "{}: {}", "Help".fg(self.config.note_color(), s), line)?;
896 }
897 }
898 for line in lines {
899 write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
900 writeln!(w, "{:>pad$}{}", "", line, pad = help_prefix_len + 2)?;
901 }
902 }
903 }
904
905 // Note
906 if is_final_group {
907 for (i, note) in self.notes.iter().enumerate() {
908 if !self.config.compact {
909 write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
910 writeln!(w)?;
911 }
912 let note_prefix = format!("{} {}", "Note", i + 1);
913 let note_prefix_len = if self.notes.len() > 1 {
914 note_prefix.len()
915 } else {
916 4
917 };
918 let mut lines = note.lines();
919 if let Some(line) = lines.next() {
920 write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
921 if self.notes.len() > 1 {
922 writeln!(
923 w,
924 "{}: {}",
925 note_prefix.fg(self.config.note_color(), s),
926 line
927 )?;
928 } else {
929 writeln!(w, "{}: {}", "Note".fg(self.config.note_color(), s), line)?;
930 }
931 }
932 for line in lines {
933 write_margin(&mut w, 0, false, false, true, Some((0, false)), &[], &None)?;
934 writeln!(w, "{:>pad$}{}", "", line, pad = note_prefix_len + 2)?;
935 }
936 }
937 }
938
939 // Tail of report
940 if !self.config.compact {
941 if is_final_group {
942 let final_margin =
943 format!("{}{}", Show((draw.hbar, line_no_width + 2)), draw.rbot);
944 writeln!(w, "{}", final_margin.fg(self.config.margin_color(), s))?;
945 } else {
946 writeln!(
947 w,
948 "{}{}",
949 Show((' ', line_no_width + 2)),
950 draw.vbar.fg(self.config.margin_color(), s)
951 )?;
952 }
953 }
954 }
955 Ok(())
956 }
957 }
958
959 #[cfg(test)]
960 mod tests {
961 //! These tests use [insta](https://insta.rs/). If you do `cargo install cargo-insta` you can
962 //! automatically update the snapshots with `cargo insta review` or `cargo insta accept`.
963 //!
964 //! When adding new tests you can leave the string in the `assert_snapshot!` macro call empty:
965 //!
966 //! assert_snapshot!(msg, @"");
967 //!
968 //! and insta will fill it in.
969
970 use insta::assert_snapshot;
971
972 use crate::{Cache, CharSet, Config, IndexType, Label, Report, ReportKind, Source, Span};
973
974 impl<S: Span> Report<'_, S> {
975 fn write_to_string<C: Cache<S::SourceId>>(&self, cache: C) -> String {
976 let mut vec = Vec::new();
977 self.write(cache, &mut vec).unwrap();
978 String::from_utf8(vec).unwrap()
979 }
980 }
981
982 fn no_color_and_ascii() -> Config {
983 Config::default()
984 .with_color(false)
985 // Using Ascii so that the inline snapshots display correctly
986 // even with fonts where characters like '┬' take up more space.
987 .with_char_set(CharSet::Ascii)
988 }
989
990 fn remove_trailing(s: String) -> String {
991 s.lines().flat_map(|l| [l.trim_end(), "\n"]).collect()
992 }
993
994 #[test]
995 fn one_message() {
996 let msg = remove_trailing(
997 Report::build(ReportKind::Error, 0..0)
998 .with_config(no_color_and_ascii())
999 .with_message("can't compare apples with oranges")
1000 .finish()
1001 .write_to_string(Source::from("")),
1002 );
1003 assert_snapshot!(msg, @r###"
1004 Error: can't compare apples with oranges
1005 "###)
1006 }
1007
1008 #[test]
1009 fn two_labels_without_messages() {
1010 let source = "apple == orange;";
1011 let msg = remove_trailing(
1012 Report::build(ReportKind::Error, 0..0)
1013 .with_config(no_color_and_ascii())
1014 .with_message("can't compare apples with oranges")
1015 .with_label(Label::new(0..5))
1016 .with_label(Label::new(9..15))
1017 .finish()
1018 .write_to_string(Source::from(source)),
1019 );
1020 // TODO: it would be nice if these spans still showed up (like codespan-reporting does)
1021 assert_snapshot!(msg, @r###"
1022 Error: can't compare apples with oranges
1023 ,-[ <unknown>:1:1 ]
1024 |
1025 1 | apple == orange;
1026 ---'
1027 "###);
1028 }
1029
1030 #[test]
1031 fn two_labels_with_messages() {
1032 let source = "apple == orange;";
1033 let msg = remove_trailing(
1034 Report::build(ReportKind::Error, 0..0)
1035 .with_config(no_color_and_ascii())
1036 .with_message("can't compare apples with oranges")
1037 .with_label(Label::new(0..5).with_message("This is an apple"))
1038 .with_label(Label::new(9..15).with_message("This is an orange"))
1039 .finish()
1040 .write_to_string(Source::from(source)),
1041 );
1042 // TODO: it would be nice if these lines didn't cross
1043 assert_snapshot!(msg, @r###"
1044 Error: can't compare apples with oranges
1045 ,-[ <unknown>:1:1 ]
1046 |
1047 1 | apple == orange;
1048 | ^^|^^ ^^^|^^
1049 | `-------------- This is an apple
1050 | |
1051 | `---- This is an orange
1052 ---'
1053 "###);
1054 }
1055
1056 #[test]
1057 fn multi_byte_chars() {
1058 let source = "äpplë == örängë;";
1059 let msg = remove_trailing(
1060 Report::build(ReportKind::Error, 0..0)
1061 .with_config(no_color_and_ascii().with_index_type(IndexType::Char))
1062 .with_message("can't compare äpplës with örängës")
1063 .with_label(Label::new(0..5).with_message("This is an äpplë"))
1064 .with_label(Label::new(9..15).with_message("This is an örängë"))
1065 .finish()
1066 .write_to_string(Source::from(source)),
1067 );
1068 // TODO: it would be nice if these lines didn't cross
1069 assert_snapshot!(msg, @r###"
1070 Error: can't compare äpplës with örängës
1071 ,-[ <unknown>:1:1 ]
1072 |
1073 1 | äpplë == örängë;
1074 | ^^|^^ ^^^|^^
1075 | `-------------- This is an äpplë
1076 | |
1077 | `---- This is an örängë
1078 ---'
1079 "###);
1080 }
1081
1082 #[test]
1083 fn byte_label() {
1084 let source = "äpplë == örängë;";
1085 let msg = remove_trailing(
1086 Report::build(ReportKind::Error, 0..0)
1087 .with_config(no_color_and_ascii().with_index_type(IndexType::Byte))
1088 .with_message("can't compare äpplës with örängës")
1089 .with_label(Label::new(0..7).with_message("This is an äpplë"))
1090 .with_label(Label::new(11..20).with_message("This is an örängë"))
1091 .finish()
1092 .write_to_string(Source::from(source)),
1093 );
1094 // TODO: it would be nice if these lines didn't cross
1095 assert_snapshot!(msg, @r###"
1096 Error: can't compare äpplës with örängës
1097 ,-[ <unknown>:1:1 ]
1098 |
1099 1 | äpplë == örängë;
1100 | ^^|^^ ^^^|^^
1101 | `-------------- This is an äpplë
1102 | |
1103 | `---- This is an örängë
1104 ---'
1105 "###);
1106 }
1107
1108 #[test]
1109 fn byte_column() {
1110 let source = "äpplë == örängë;";
1111 let msg = remove_trailing(
1112 Report::build(ReportKind::Error, 11..11)
1113 .with_config(no_color_and_ascii().with_index_type(IndexType::Byte))
1114 .with_message("can't compare äpplës with örängës")
1115 .with_label(Label::new(0..7).with_message("This is an äpplë"))
1116 .with_label(Label::new(11..20).with_message("This is an örängë"))
1117 .finish()
1118 .write_to_string(Source::from(source)),
1119 );
1120 // TODO: it would be nice if these lines didn't cross
1121 assert_snapshot!(msg, @r###"
1122 Error: can't compare äpplës with örängës
1123 ,-[ <unknown>:1:10 ]
1124 |
1125 1 | äpplë == örängë;
1126 | ^^|^^ ^^^|^^
1127 | `-------------- This is an äpplë
1128 | |
1129 | `---- This is an örängë
1130 ---'
1131 "###);
1132 }
1133
1134 #[test]
1135 fn label_at_end_of_long_line() {
1136 let source = format!("{}orange", "apple == ".repeat(100));
1137 let msg = remove_trailing(
1138 Report::build(ReportKind::Error, 0..0)
1139 .with_config(no_color_and_ascii())
1140 .with_message("can't compare apples with oranges")
1141 .with_label(
1142 Label::new(source.len() - 5..source.len()).with_message("This is an orange"),
1143 )
1144 .finish()
1145 .write_to_string(Source::from(source)),
1146 );
1147 // TODO: it would be nice if the start of long lines would be omitted (like rustc does)
1148 assert_snapshot!(msg, @r###"
1149 Error: can't compare apples with oranges
1150 ,-[ <unknown>:1:1 ]
1151 |
1152 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
1153 | ^^|^^
1154 | `---- This is an orange
1155 ---'
1156 "###);
1157 }
1158
1159 #[test]
1160 fn label_of_width_zero_at_end_of_line() {
1161 let source = "apple ==\n";
1162 let msg = remove_trailing(
1163 Report::build(ReportKind::Error, 0..0)
1164 .with_config(no_color_and_ascii().with_index_type(IndexType::Byte))
1165 .with_message("unexpected end of file")
1166 .with_label(Label::new(9..9).with_message("Unexpected end of file"))
1167 .finish()
1168 .write_to_string(Source::from(source)),
1169 );
1170
1171 assert_snapshot!(msg, @r###"
1172 Error: unexpected end of file
1173 ,-[ <unknown>:1:1 ]
1174 |
1175 1 | apple ==
1176 | |
1177 | `- Unexpected end of file
1178 ---'
1179 "###);
1180 }
1181
1182 #[test]
1183 fn empty_input() {
1184 let source = "";
1185 let msg = remove_trailing(
1186 Report::build(ReportKind::Error, 0..0)
1187 .with_config(no_color_and_ascii())
1188 .with_message("unexpected end of file")
1189 .with_label(Label::new(0..0).with_message("No more fruit!"))
1190 .finish()
1191 .write_to_string(Source::from(source)),
1192 );
1193
1194 assert_snapshot!(msg, @r###"
1195 Error: unexpected end of file
1196 ,-[ <unknown>:1:1 ]
1197 |
1198 1 |
1199 | |
1200 | `- No more fruit!
1201 ---'
1202 "###);
1203 }
1204
1205 #[test]
1206 fn empty_input_help() {
1207 let source = "";
1208 let msg = remove_trailing(
1209 Report::build(ReportKind::Error, 0..0)
1210 .with_config(no_color_and_ascii())
1211 .with_message("unexpected end of file")
1212 .with_label(Label::new(0..0).with_message("No more fruit!"))
1213 .with_help("have you tried going to the farmer's market?")
1214 .finish()
1215 .write_to_string(Source::from(source)),
1216 );
1217
1218 assert_snapshot!(msg, @r###"
1219 Error: unexpected end of file
1220 ,-[ <unknown>:1:1 ]
1221 |
1222 1 |
1223 | |
1224 | `- No more fruit!
1225 |
1226 | Help: have you tried going to the farmer's market?
1227 ---'
1228 "###);
1229 }
1230
1231 #[test]
1232 fn empty_input_note() {
1233 let source = "";
1234 let msg = remove_trailing(
1235 Report::build(ReportKind::Error, 0..0)
1236 .with_config(no_color_and_ascii())
1237 .with_message("unexpected end of file")
1238 .with_label(Label::new(0..0).with_message("No more fruit!"))
1239 .with_note("eat your greens!")
1240 .finish()
1241 .write_to_string(Source::from(source)),
1242 );
1243
1244 assert_snapshot!(msg, @r###"
1245 Error: unexpected end of file
1246 ,-[ <unknown>:1:1 ]
1247 |
1248 1 |
1249 | |
1250 | `- No more fruit!
1251 |
1252 | Note: eat your greens!
1253 ---'
1254 "###);
1255 }
1256
1257 #[test]
1258 fn empty_input_help_note() {
1259 let source = "";
1260 let msg = remove_trailing(
1261 Report::build(ReportKind::Error, 0..0)
1262 .with_config(no_color_and_ascii())
1263 .with_message("unexpected end of file")
1264 .with_label(Label::new(0..0).with_message("No more fruit!"))
1265 .with_note("eat your greens!")
1266 .with_help("have you tried going to the farmer's market?")
1267 .finish()
1268 .write_to_string(Source::from(source)),
1269 );
1270
1271 assert_snapshot!(msg, @r###"
1272 Error: unexpected end of file
1273 ,-[ <unknown>:1:1 ]
1274 |
1275 1 |
1276 | |
1277 | `- No more fruit!
1278 |
1279 | Help: have you tried going to the farmer's market?
1280 |
1281 | Note: eat your greens!
1282 ---'
1283 "###);
1284 }
1285
1286 #[test]
1287 fn byte_spans_never_crash() {
1288 let source = "apple\np\n\nempty\n";
1289
1290 for i in 0..=source.len() {
1291 for j in i..=source.len() {
1292 let _ = remove_trailing(
1293 Report::build(ReportKind::Error, 0..0)
1294 .with_config(no_color_and_ascii().with_index_type(IndexType::Byte))
1295 .with_message("Label")
1296 .with_label(Label::new(i..j).with_message("Label"))
1297 .finish()
1298 .write_to_string(Source::from(source)),
1299 );
1300 }
1301 }
1302 }
1303
1304 #[test]
1305 fn multiline_label() {
1306 let source = "apple\n==\norange";
1307 let msg = remove_trailing(
1308 Report::build(ReportKind::Error, 0..0)
1309 .with_config(no_color_and_ascii())
1310 .with_label(Label::new(0..source.len()).with_message("illegal comparison"))
1311 .finish()
1312 .write_to_string(Source::from(source)),
1313 );
1314 // TODO: it would be nice if the 2nd line wasn't omitted
1315 assert_snapshot!(msg, @r###"
1316 Error:
1317 ,-[ <unknown>:1:1 ]
1318 |
1319 1 | ,-> apple
1320 : :
1321 3 | |-> orange
1322 | |
1323 | `----------- illegal comparison
1324 ---'
1325 "###);
1326 }
1327
1328 #[test]
1329 fn partially_overlapping_labels() {
1330 let source = "https://example.com/";
1331 let msg = remove_trailing(
1332 Report::build(ReportKind::Error, 0..0)
1333 .with_config(no_color_and_ascii())
1334 .with_label(Label::new(0..source.len()).with_message("URL"))
1335 .with_label(Label::new(0..source.find(':').unwrap()).with_message("scheme"))
1336 .finish()
1337 .write_to_string(Source::from(source)),
1338 );
1339 // TODO: it would be nice if you could tell where the spans start and end.
1340 assert_snapshot!(msg, @r###"
1341 Error:
1342 ,-[ <unknown>:1:1 ]
1343 |
1344 1 | https://example.com/
1345 | ^^|^^^^^^^|^^^^^^^^^
1346 | `------------------- scheme
1347 | |
1348 | `----------- URL
1349 ---'
1350 "###);
1351 }
1352
1353 #[test]
1354 fn multiple_labels_same_span() {
1355 let source = "apple == orange;";
1356 let msg = remove_trailing(
1357 Report::build(ReportKind::Error, 0..0)
1358 .with_config(no_color_and_ascii())
1359 .with_message("can't compare apples with oranges")
1360 .with_label(Label::new(0..5).with_message("This is an apple"))
1361 .with_label(
1362 Label::new(0..5).with_message("Have I mentioned that this is an apple?"),
1363 )
1364 .with_label(Label::new(0..5).with_message("No really, have I mentioned that?"))
1365 .with_label(Label::new(9..15).with_message("This is an orange"))
1366 .with_label(
1367 Label::new(9..15).with_message("Have I mentioned that this is an orange?"),
1368 )
1369 .with_label(Label::new(9..15).with_message("No really, have I mentioned that?"))
1370 .finish()
1371 .write_to_string(Source::from(source)),
1372 );
1373 assert_snapshot!(msg, @r###"
1374 Error: can't compare apples with oranges
1375 ,-[ <unknown>:1:1 ]
1376 |
1377 1 | apple == orange;
1378 | ^^|^^ ^^^|^^
1379 | `-------------- This is an apple
1380 | | |
1381 | `-------------- Have I mentioned that this is an apple?
1382 | | |
1383 | `-------------- No really, have I mentioned that?
1384 | |
1385 | `---- This is an orange
1386 | |
1387 | `---- Have I mentioned that this is an orange?
1388 | |
1389 | `---- No really, have I mentioned that?
1390 ---'
1391 "###)
1392 }
1393
1394 #[test]
1395 fn note() {
1396 let source = "apple == orange;";
1397 let msg = remove_trailing(
1398 Report::build(ReportKind::Error, 0..0)
1399 .with_config(no_color_and_ascii())
1400 .with_message("can't compare apples with oranges")
1401 .with_label(Label::new(0..5).with_message("This is an apple"))
1402 .with_label(Label::new(9..15).with_message("This is an orange"))
1403 .with_note("stop trying ... this is a fruitless endeavor")
1404 .finish()
1405 .write_to_string(Source::from(source)),
1406 );
1407 assert_snapshot!(msg, @r###"
1408 Error: can't compare apples with oranges
1409 ,-[ <unknown>:1:1 ]
1410 |
1411 1 | apple == orange;
1412 | ^^|^^ ^^^|^^
1413 | `-------------- This is an apple
1414 | |
1415 | `---- This is an orange
1416 |
1417 | Note: stop trying ... this is a fruitless endeavor
1418 ---'
1419 "###)
1420 }
1421
1422 #[test]
1423 fn help() {
1424 let source = "apple == orange;";
1425 let msg = remove_trailing(
1426 Report::build(ReportKind::Error, 0..0)
1427 .with_config(no_color_and_ascii())
1428 .with_message("can't compare apples with oranges")
1429 .with_label(Label::new(0..5).with_message("This is an apple"))
1430 .with_label(Label::new(9..15).with_message("This is an orange"))
1431 .with_help("have you tried peeling the orange?")
1432 .finish()
1433 .write_to_string(Source::from(source)),
1434 );
1435 assert_snapshot!(msg, @r###"
1436 Error: can't compare apples with oranges
1437 ,-[ <unknown>:1:1 ]
1438 |
1439 1 | apple == orange;
1440 | ^^|^^ ^^^|^^
1441 | `-------------- This is an apple
1442 | |
1443 | `---- This is an orange
1444 |
1445 | Help: have you tried peeling the orange?
1446 ---'
1447 "###)
1448 }
1449
1450 #[test]
1451 fn help_and_note() {
1452 let source = "apple == orange;";
1453 let msg = remove_trailing(
1454 Report::build(ReportKind::Error, 0..0)
1455 .with_config(no_color_and_ascii())
1456 .with_message("can't compare apples with oranges")
1457 .with_label(Label::new(0..5).with_message("This is an apple"))
1458 .with_label(Label::new(9..15).with_message("This is an orange"))
1459 .with_help("have you tried peeling the orange?")
1460 .with_note("stop trying ... this is a fruitless endeavor")
1461 .finish()
1462 .write_to_string(Source::from(source)),
1463 );
1464 assert_snapshot!(msg, @r###"
1465 Error: can't compare apples with oranges
1466 ,-[ <unknown>:1:1 ]
1467 |
1468 1 | apple == orange;
1469 | ^^|^^ ^^^|^^
1470 | `-------------- This is an apple
1471 | |
1472 | `---- This is an orange
1473 |
1474 | Help: have you tried peeling the orange?
1475 |
1476 | Note: stop trying ... this is a fruitless endeavor
1477 ---'
1478 "###)
1479 }
1480
1481 #[test]
1482 fn single_note_single_line() {
1483 let source = "apple == orange;";
1484 let msg = remove_trailing(
1485 Report::build(ReportKind::Error, 0..0)
1486 .with_config(no_color_and_ascii())
1487 .with_message("can't compare apples with oranges")
1488 .with_label(Label::new(0..15).with_message("This is a strange comparison"))
1489 .with_note("No need to try, they can't be compared.")
1490 .finish()
1491 .write_to_string(Source::from(source)),
1492 );
1493 assert_snapshot!(msg, @r###"
1494 Error: can't compare apples with oranges
1495 ,-[ <unknown>:1:1 ]
1496 |
1497 1 | apple == orange;
1498 | ^^^^^^^|^^^^^^^
1499 | `--------- This is a strange comparison
1500 |
1501 | Note: No need to try, they can't be compared.
1502 ---'
1503 "###)
1504 }
1505
1506 #[test]
1507 fn multi_notes_single_lines() {
1508 let source = "apple == orange;";
1509 let msg = remove_trailing(
1510 Report::build(ReportKind::Error, 0..0)
1511 .with_config(no_color_and_ascii())
1512 .with_message("can't compare apples with oranges")
1513 .with_label(Label::new(0..15).with_message("This is a strange comparison"))
1514 .with_note("No need to try, they can't be compared.")
1515 .with_note("Yeah, really, please stop.")
1516 .finish()
1517 .write_to_string(Source::from(source)),
1518 );
1519 assert_snapshot!(msg, @r###"
1520 Error: can't compare apples with oranges
1521 ,-[ <unknown>:1:1 ]
1522 |
1523 1 | apple == orange;
1524 | ^^^^^^^|^^^^^^^
1525 | `--------- This is a strange comparison
1526 |
1527 | Note 1: No need to try, they can't be compared.
1528 |
1529 | Note 2: Yeah, really, please stop.
1530 ---'
1531 "###)
1532 }
1533
1534 #[test]
1535 fn multi_notes_multi_lines() {
1536 let source = "apple == orange;";
1537 let msg = remove_trailing(
1538 Report::build(ReportKind::Error, 0..0)
1539 .with_config(no_color_and_ascii())
1540 .with_message("can't compare apples with oranges")
1541 .with_label(Label::new(0..15).with_message("This is a strange comparison"))
1542 .with_note("No need to try, they can't be compared.")
1543 .with_note("Yeah, really, please stop.\nIt has no resemblance.")
1544 .finish()
1545 .write_to_string(Source::from(source)),
1546 );
1547 assert_snapshot!(msg, @r###"
1548 Error: can't compare apples with oranges
1549 ,-[ <unknown>:1:1 ]
1550 |
1551 1 | apple == orange;
1552 | ^^^^^^^|^^^^^^^
1553 | `--------- This is a strange comparison
1554 |
1555 | Note 1: No need to try, they can't be compared.
1556 |
1557 | Note 2: Yeah, really, please stop.
1558 | It has no resemblance.
1559 ---'
1560 "###)
1561 }
1562
1563 #[test]
1564 fn multi_helps_multi_lines() {
1565 let source = "apple == orange;";
1566 let msg = remove_trailing(
1567 Report::build(ReportKind::Error, 0..0)
1568 .with_config(no_color_and_ascii())
1569 .with_message("can't compare apples with oranges")
1570 .with_label(Label::new(0..15).with_message("This is a strange comparison"))
1571 .with_help("No need to try, they can't be compared.")
1572 .with_help("Yeah, really, please stop.\nIt has no resemblance.")
1573 .finish()
1574 .write_to_string(Source::from(source)),
1575 );
1576 assert_snapshot!(msg, @r###"
1577 Error: can't compare apples with oranges
1578 ,-[ <unknown>:1:1 ]
1579 |
1580 1 | apple == orange;
1581 | ^^^^^^^|^^^^^^^
1582 | `--------- This is a strange comparison
1583 |
1584 | Help 1: No need to try, they can't be compared.
1585 |
1586 | Help 2: Yeah, really, please stop.
1587 | It has no resemblance.
1588 ---'
1589 "###)
1590 }
1591
1592 #[test]
1593 fn ordered_labels() {
1594 let msg = remove_trailing(
1595 Report::build(ReportKind::Error, ("", 0..0))
1596 .with_config(no_color_and_ascii())
1597 .with_label(Label::new(("b", 13..18)).with_order(1).with_message("1"))
1598 .with_label(Label::new(("a", 0..6)).with_order(2).with_message("2"))
1599 .with_label(Label::new(("a", 7..12)).with_order(3).with_message("3"))
1600 .with_label(Label::new(("b", 0..6)).with_order(4).with_message("4"))
1601 .with_label(Label::new(("b", 7..12)).with_order(5).with_message("5"))
1602 .finish()
1603 .write_to_string(crate::sources([
1604 ("a", "second\nthird"),
1605 ("b", "fourth\nfifth\nfirst"),
1606 ])),
1607 );
1608 assert_snapshot!(msg, @r###"
1609 Error:
1610 ,-[ b:3:1 ]
1611 |
1612 3 | first
1613 | ^^|^^
1614 | `---- 1
1615 |
1616 |-[ a:1:1 ]
1617 |
1618 1 | second
1619 | ^^^|^^
1620 | `---- 2
1621 2 | third
1622 | ^^|^^
1623 | `---- 3
1624 |
1625 |-[ b:1:1 ]
1626 |
1627 1 | fourth
1628 | ^^^|^^
1629 | `---- 4
1630 2 | fifth
1631 | ^^|^^
1632 | `---- 5
1633 ---'
1634 "###)
1635 }
1636 }