-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherror.rs
60 lines (53 loc) · 1.52 KB
/
error.rs
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
use std::{fmt, sync::Arc, sync::RwLock};
use swc_common::errors::{Diagnostic, DiagnosticBuilder, Emitter};
use swc_common::{Loc, Span};
/// A buffer for collecting errors from the AST parser.
#[derive(Debug, Clone)]
pub struct ErrorBuffer {
specifier: String,
diagnostics: Arc<RwLock<Vec<Diagnostic>>>,
}
impl ErrorBuffer {
pub fn new(specifier: &str) -> Self {
Self {
specifier: specifier.into(),
diagnostics: Arc::new(RwLock::new(Vec::new())),
}
}
}
impl Emitter for ErrorBuffer {
fn emit(&mut self, diagnostic_builder: &DiagnosticBuilder) {
self.diagnostics.write().unwrap().push((**diagnostic_builder).clone());
}
}
/// A buffer for collecting diagnostic messages from the AST parser.
#[derive(Debug)]
pub struct DiagnosticBuffer(Vec<String>);
impl fmt::Display for DiagnosticBuffer {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.pad(&self.0.join(","))
}
}
impl DiagnosticBuffer {
pub fn from_error_buffer<F>(error_buffer: ErrorBuffer, get_loc: F) -> Self
where
F: Fn(Span) -> Loc,
{
let diagnostics = error_buffer.diagnostics.read().unwrap().clone();
let diagnostics = diagnostics
.iter()
.map(|d| {
let mut message = d.message();
if let Some(span) = d.span.primary_span() {
let loc = get_loc(span);
message = format!(
"{} at {}:{}:{}",
message, error_buffer.specifier, loc.line, loc.col_display
);
}
message
})
.collect();
Self(diagnostics)
}
}