forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiagnostics.rs
More file actions
71 lines (63 loc) · 2.29 KB
/
Copy pathdiagnostics.rs
File metadata and controls
71 lines (63 loc) · 2.29 KB
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
use crate::files::{FileStore, SourceFileId};
use crate::Span;
pub use codespan_reporting::diagnostic::{
Diagnostic as CsDiagnostic, Label as CsLabel, LabelStyle, Severity,
};
use codespan_reporting::term;
use term::termcolor::{BufferWriter, ColorChoice};
pub type Diagnostic = CsDiagnostic<SourceFileId>;
pub struct Label {
pub style: LabelStyle,
pub span: Span,
pub message: String,
}
impl Label {
/// Create a primary label with the given message. This will underline the
/// given span with carets (`^^^^`).
pub fn primary<S: Into<String>>(span: Span, message: S) -> Self {
Label {
style: LabelStyle::Primary,
span,
message: message.into(),
}
}
/// Create a secondary label with the given message. This will underline the
/// given span with hyphens (`----`).
pub fn secondary<S: Into<String>>(span: Span, message: S) -> Self {
Label {
style: LabelStyle::Secondary,
span,
message: message.into(),
}
}
/// Convert into a [`codespan_reporting::Diagnostic::Label`]
pub fn into_cs_label(self, file_id: SourceFileId) -> CsLabel<SourceFileId> {
CsLabel {
style: self.style,
file_id,
range: self.span.into(),
message: self.message,
}
}
}
/// Print the given diagnostics to stderr.
pub fn print_diagnostics(diagnostics: &[Diagnostic], files: &FileStore) {
let writer = BufferWriter::stderr(ColorChoice::Auto);
let mut buffer = writer.buffer();
let config = term::Config::default();
for diag in diagnostics {
term::emit(&mut buffer, &config, files, &diag).unwrap();
}
// If we use `writer` here, the output won't be captured by rust's test system.
eprintln!("{}", std::str::from_utf8(buffer.as_slice()).unwrap());
}
/// Format the given diagnostics as a string.
pub fn diagnostics_string(diagnostics: &[Diagnostic], files: &FileStore) -> String {
let writer = BufferWriter::stderr(ColorChoice::Never);
let mut buffer = writer.buffer();
let config = term::Config::default();
for diag in diagnostics {
term::emit(&mut buffer, &config, files, &diag).expect("failed to emit diagnostic");
}
std::str::from_utf8(buffer.as_slice()).unwrap().to_string()
}