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
use miette::{Diagnostic, SourceCode, SourceSpan};
use std::sync::Arc;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(thiserror::Error, Diagnostic, Clone, Debug)]
pub enum Error {
#[error("{context}")]
IoError {
#[source]
error: Arc<std::io::Error>,
context: String,
},
#[error("parse error: {msg}")]
#[diagnostic()]
ParseError {
msg: String,
#[source_code]
src: Source,
#[label("{msg}")]
span: SourceSpan,
},
#[error("type error: {msg}")]
#[diagnostic()]
TypeError {
msg: String,
#[source_code]
src: Source,
#[label("{msg}")]
span: SourceSpan,
},
#[error("Found {} errors:\n\n{}",
self.unwrap_errors().len(),
DisplayErrors(self.unwrap_errors()))]
#[diagnostic()]
Errors(#[related] Vec<Error>),
}
impl Error {
pub fn from_io(error: std::io::Error, context: impl Into<String>) -> Self {
Error::IoError {
error: Arc::new(error),
context: context.into(),
}
}
}
impl From<Vec<Error>> for Error {
fn from(es: Vec<Error>) -> Self {
Error::Errors(es)
}
}
impl Error {
fn unwrap_errors(&self) -> &[Error] {
match self {
Error::Errors(e) => e,
_ => panic!("`isle::Error::unwrap_errors` on non-`isle::Error::Errors`"),
}
}
}
struct DisplayErrors<'a>(&'a [Error]);
impl std::fmt::Display for DisplayErrors<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for e in self.0 {
writeln!(f, "{}", e)?;
}
Ok(())
}
}
#[derive(Clone)]
pub struct Source {
name: Arc<str>,
text: Arc<str>,
}
impl std::fmt::Debug for Source {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Source")
.field("name", &self.name)
.field("source", &"<redacted>");
Ok(())
}
}
impl Source {
pub(crate) fn new(name: Arc<str>, text: Arc<str>) -> Self {
Self { name, text }
}
pub fn name(&self) -> &Arc<str> {
&self.name
}
pub fn text(&self) -> &Arc<str> {
&self.name
}
}
impl SourceCode for Source {
fn read_span<'a>(
&'a self,
span: &SourceSpan,
context_lines_before: usize,
context_lines_after: usize,
) -> std::result::Result<Box<dyn miette::SpanContents<'a> + 'a>, miette::MietteError> {
let contents = self
.text
.read_span(span, context_lines_before, context_lines_after)?;
Ok(Box::new(miette::MietteSpanContents::new_named(
self.name.to_string(),
contents.data(),
contents.span().clone(),
contents.line(),
contents.column(),
contents.line_count(),
)))
}
}