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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
use std::{
fmt::{Display, Formatter},
};
use std::io::stderr;
use crate::location::Location;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ErrorContext {
pub start_end: Option<(Location, Location)>,
pub file_name: Option<String>,
pub file_content: Option<String>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Error {
pub kind: ErrorKind,
pub context: Option<Box<ErrorContext>>,
}
impl Error {
pub fn context_loc(self, start: Location, end: Location) -> Self {
let mut context = self.context.unwrap_or_default();
context.start_end.get_or_insert((start, end));
Error {
kind: self.kind,
context: Some(context),
}
}
pub fn context_file_name(self, file_name: String) -> Self {
let mut context = self.context.unwrap_or_default();
context.file_name.get_or_insert(file_name);
Error {
kind: self.kind,
context: Some(context),
}
}
pub fn context_file_content(self, file_content: String) -> Self {
let mut context = self.context.unwrap_or_default();
context.file_content.get_or_insert(file_content);
Error {
kind: self.kind,
context: Some(context),
}
}
pub fn start(&self) -> Option<Location> {
self.context
.as_ref()
.and_then(|c| c.start_end)
.map(|se| se.0)
}
pub fn end(&self) -> Option<Location> {
self.context
.as_ref()
.and_then(|c| c.start_end)
.map(|se| se.1)
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error {
kind: ErrorKind::IoError(e.to_string()),
context: None,
}
}
}
#[cfg(feature = "serde")]
impl serde::de::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: Display,
{
Error {
kind: ErrorKind::Custom(msg.to_string()),
context: None,
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.context.as_ref() {
Some(context) => match (
context.start_end.as_ref(),
context.file_name.as_ref(),
context.file_content.as_ref(),
) {
(Some((start, _)), _, _) => {
write!(f, "error at {}: {}", start, self.kind)
}
(_, _, _) => {
write!(f, "error: {}", self.kind)
}
},
None => write!(f, "error: {}", self.kind),
}
}
}
impl std::error::Error for Error {}
pub fn print_error(e: &Error) -> std::io::Result<()> {
use std::io::Write;
let f = stderr();
let mut f = f.lock();
match e.context.as_ref() {
Some(context) => match (
context.start_end.as_ref(),
context.file_name.as_ref(),
context.file_content.as_ref(),
) {
(Some((start, end)), file_name, Some(file_content)) => {
let max_line_col_width = start.line.max(end.line).to_string().len();
let col_ws_rep = " ".repeat(max_line_col_width);
writeln!(f, "error: {}", e.kind)?;
writeln!(
f,
"{}--> {}:{}:{}",
col_ws_rep,
file_name.map(AsRef::as_ref).unwrap_or("string"),
start.line,
start.column
)?;
writeln!(f, "{} |", col_ws_rep)?;
let mut lines = file_content.lines().skip(start.line as usize - 1);
let start_line_string = start.line.to_string();
let start_line_padding = " ".repeat(max_line_col_width - start_line_string.len());
if start.line == end.line {
writeln!(
f,
"{}{} | {}",
start_line_padding,
start.line,
lines.next().unwrap_or_default()
)?;
writeln!(
f,
"{} | {}{}",
col_ws_rep,
" ".repeat(start.column as usize - 1),
"^".repeat((end.column - start.column) as usize)
)?;
} else {
writeln!(
f,
"{}{} | {}",
start_line_padding,
start.line,
lines.next().unwrap_or_default()
)?;
writeln!(
f,
"{} | {}^",
col_ws_rep,
"_".repeat((start.column - 1) as usize),
)?;
for line_number in start.line + 1..=end.line {
let line_nr_string = line_number.to_string();
let line_padding = " ".repeat(max_line_col_width - line_nr_string.len());
writeln!(
f,
"{}{} | | {}",
line_padding,
line_nr_string,
lines.next().unwrap_or_default()
)?;
}
writeln!(
f,
"{} | |{}^",
col_ws_rep,
"_".repeat((end.column - 1) as usize)
)?;
}
writeln!(f, "{} |", col_ws_rep)
}
(_, Some(file_name), _) => writeln!(f, "file \"{}\": {}", file_name, e),
_ => writeln!(f, "{}", e),
},
_ => writeln!(f, "{}", e),
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
ExpectedBool,
ExpectedString,
ExpectedStrGotEscapes,
ExpectedList,
ParseError(String),
IoError(String),
Custom(String),
}
impl Display for ErrorKind {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ErrorKind::ExpectedBool => write!(f, "expected bool"),
ErrorKind::ExpectedStrGotEscapes => {
write!(f, "expected zero-copy string which doesn't support escapes")
}
ErrorKind::ExpectedString => write!(f, "expected string"),
ErrorKind::ExpectedList => write!(f, "expected list"),
ErrorKind::ParseError(e) => write!(f, "parsing error: {}", e),
ErrorKind::IoError(e) => write!(f, "io error: {}", e),
ErrorKind::Custom(s) => write!(f, "{}", s),
}
}
}