1use std::fmt;
2use std::io::{self, Write};
3use std::ops::Range;
4use std::sync::Arc;
5
6use ariadne::{Cache, Color, Config, IndexType, Report, ReportKind, Source};
7use xur_span::{SourceFile, SourceMap, Span};
8
9use crate::{Diag, Level};
10
11type ReportSpan = (usize, Range<usize>);
13
14pub struct Emitter<'a> {
16 files: &'a [Arc<SourceFile>],
17 sources: Vec<Source<&'a str>>,
18 color: bool,
19}
20
21impl<'a> Emitter<'a> {
22 pub fn new(source_map: &'a SourceMap) -> Self {
23 let files = source_map.files();
24 Self {
25 files,
26 sources: files
27 .iter()
28 .map(|file| Source::from(file.src.as_str()))
29 .collect(),
30 color: false,
31 }
32 }
33
34 pub fn with_color(mut self, color: bool) -> Self {
35 self.color = color;
36 self
37 }
38
39 pub fn emit(&self, diag: &Diag, out: &mut impl Write) -> io::Result<()> {
40 let cache = Sources {
41 files: self.files,
42 sources: &self.sources,
43 };
44 self.report(diag).write(cache, out)
45 }
46
47 fn locate(&self, span: Span) -> ReportSpan {
48 let index = self
49 .files
50 .iter()
51 .position(|file| file.contains(span.start))
52 .expect("diagnostic span is in no source file");
53 let start = self.files[index].start;
54 (index, span.start - start..span.end - start)
55 }
56
57 fn report(&self, diag: &Diag) -> Report<'_, ReportSpan> {
58 let (kind, primary_color) = match diag.level {
59 Level::Error => (ReportKind::Error, Color::Red),
60 Level::Warning => (ReportKind::Warning, Color::Yellow),
61 };
62 let config = Config::default()
63 .with_index_type(IndexType::Byte)
64 .with_color(self.color);
65
66 let mut report = Report::build(kind, self.locate(diag.span))
67 .with_config(config)
68 .with_message(&diag.message);
69 for label in &diag.labels {
70 let color = if label.span == diag.span {
71 primary_color
72 } else {
73 Color::Blue
74 };
75 report.add_label(
76 ariadne::Label::new(self.locate(label.span))
77 .with_message(&label.message)
78 .with_color(color),
79 );
80 }
81 for note in &diag.notes {
82 report.add_note(note);
83 }
84 report.finish()
85 }
86}
87
88struct Sources<'a> {
90 files: &'a [Arc<SourceFile>],
91 sources: &'a [Source<&'a str>],
92}
93
94impl<'a> Cache<usize> for Sources<'a> {
95 type Storage = &'a str;
96
97 fn fetch(&mut self, id: &usize) -> Result<&Source<&'a str>, impl fmt::Debug> {
98 self.sources.get(*id).ok_or("unknown source file")
99 }
100
101 fn display<'b>(&self, id: &'b usize) -> Option<impl fmt::Display + 'b> {
102 Some(self.files[*id].name.clone())
103 }
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109
110 fn render(map: &SourceMap, diag: &Diag) -> String {
111 let mut out = Vec::new();
112 Emitter::new(map).emit(diag, &mut out).unwrap();
113 String::from_utf8(out).unwrap()
114 }
115
116 #[test]
117 fn renders_message_labels_and_notes() {
118 let mut map = SourceMap::new();
119 map.add_file("test.xur", "let x = $;");
120 let diag = Diag::error("unexpected character `$`", Span::new(8, 9))
121 .with_label(Span::new(8, 9), "not valid here")
122 .with_note("remove it");
123 let out = render(&map, &diag);
124 assert!(out.starts_with("Error: unexpected character `$`"), "{out}");
125 assert!(out.contains("test.xur:1:9"), "{out}");
126 assert!(out.contains("not valid here"), "{out}");
127 assert!(out.contains("Note: remove it"), "{out}");
128 }
129
130 #[test]
131 fn labels_can_point_into_other_files() {
132 let mut map = SourceMap::new();
133 let a = map.add_file("a.xur", "fn f() {}");
134 let b = map.add_file("b.xur", "fn f() {}");
135 let in_a = Span::new(a.start + 3, a.start + 4);
136 let in_b = Span::new(b.start + 3, b.start + 4);
137 let diag = Diag::error("the name `f` is defined multiple times", in_b)
138 .with_label(in_b, "redefined here")
139 .with_label(in_a, "previous definition here");
140 let out = render(&map, &diag);
141 assert!(out.contains("b.xur:1:4"), "{out}");
142 assert!(out.contains("a.xur:1:4"), "{out}");
143 }
144}