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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use crate::lexer::{SpannedToken, Token};
use crate::num::ParseIntError;
use crate::string::UnescapeError;
use logos::Span;
use source_span::{
fmt::{Formatter, Style},
DefaultMetrics, Position, SourceBuffer, Span as SourceSpan,
};
use std::error::Error;
use std::fmt::{self, Debug, Display};
use std::num::ParseFloatError;
use std::str::ParseBoolError;
use thiserror::Error;
#[derive(Error, Debug, Clone)]
pub enum ParseError {
#[error(transparent)]
UnexpectedToken(#[from] UnexpectedTokenError),
#[error(transparent)]
InvalidPrimitive(#[from] PrimitiveError),
#[error(transparent)]
UnexpectedArrayKey(ArrayKeyError),
#[error(transparent)]
TrailingCharacters(#[from] TrailingError),
#[error("{0}")]
Serde(String),
}
impl serde::de::Error for ParseError {
fn custom<T>(msg: T) -> Self
where
T: Display,
{
ParseError::Serde(msg.to_string())
}
}
#[derive(Debug, Clone)]
pub struct UnexpectedTokenError {
src: String,
snip: Span,
err_span: Span,
pub expected: TokenList,
pub found: Option<Token>,
}
impl Display for UnexpectedTokenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let err = match &self.found {
Some(Token::Error) => {
format!("No valid token found, expected one of {}", self.expected)
}
Some(token) => format!(
"Unexpected token, found {} expected one of {}",
token, self.expected
),
None => format!(
"Unexpected token, found None expected one of {}",
self.expected
),
};
fmt_spanned(f, err, self.err_span.clone(), &self.src)
}
}
impl UnexpectedTokenError {
pub fn new(
expected: &[Token],
found: Option<Token>,
src: String,
snip: Span,
err_span: Span,
) -> Self {
UnexpectedTokenError {
src,
snip,
err_span,
expected: expected.into(),
found,
}
}
}
#[derive(Clone)]
pub struct TokenList(Vec<Token>);
impl Debug for TokenList {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl From<&[Token]> for TokenList {
fn from(list: &[Token]) -> Self {
TokenList(list.into())
}
}
impl Display for TokenList {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0.len() {
0 => {}
1 => write!(f, "{}", self.0[0])?,
_ => {
let mut tokens = self.0[0..self.0.len() - 1].iter();
write!(f, "{}", tokens.next().unwrap())?;
for token in tokens {
write!(f, ", {}", token)?;
}
if self.0.len() > 1 {
write!(f, " or {}", self.0.last().unwrap())?;
}
}
}
Ok(())
}
}
impl Error for UnexpectedTokenError {}
#[derive(Debug, Clone)]
pub struct PrimitiveError {
src: String,
snip: Span,
err_span: Span,
pub kind: PrimitiveErrorKind,
}
#[derive(Error, Debug, Clone)]
pub enum PrimitiveErrorKind {
#[error("Invalid boolean literal: {0}")]
InvalidBoolLiteral(#[from] ParseBoolError),
#[error("Invalid integer literal: {0}")]
InvalidIntLiteral(#[from] ParseIntError),
#[error("Invalid float literal: {0}")]
InvalidFloatLiteral(#[from] ParseFloatError),
#[error("Invalid string literal")]
InvalidStringLiteral,
}
impl Display for PrimitiveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let err = format!("{}", self.kind);
fmt_spanned(f, err, self.err_span.clone(), &self.src)
}
}
impl Error for PrimitiveError {}
impl PrimitiveErrorKind {
pub fn desc(&self) -> &str {
match self {
PrimitiveErrorKind::InvalidBoolLiteral(_) => "Not a boolean",
PrimitiveErrorKind::InvalidIntLiteral(err) => err.desc(),
PrimitiveErrorKind::InvalidFloatLiteral(_) => "Not a valid float",
PrimitiveErrorKind::InvalidStringLiteral => "Not a string literal",
}
}
}
impl From<UnescapeError> for PrimitiveErrorKind {
fn from(_: UnescapeError) -> Self {
PrimitiveErrorKind::InvalidStringLiteral
}
}
#[derive(Debug, Clone)]
pub struct ArrayKeyError {
src: String,
snip: Span,
err_span: Span,
kind: ArrayKeyErrorKind,
}
#[derive(Debug, Clone)]
pub enum ArrayKeyErrorKind {
IntegerExpected,
NonConsecutive,
}
impl Display for ArrayKeyErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
ArrayKeyErrorKind::IntegerExpected => "Expected integer key",
ArrayKeyErrorKind::NonConsecutive => "Expected consecutive integer key",
}
)
}
}
impl Display for ArrayKeyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let err = format!("{}", self.kind);
fmt_spanned(f, err, self.err_span.clone(), &self.src)
}
}
impl Error for ArrayKeyError {}
impl ArrayKeyError {
pub fn new(kind: ArrayKeyErrorKind, source: &str, err_span: Span) -> Self {
ArrayKeyError {
src: source.into(),
snip: (0..source.len()),
err_span,
kind,
}
}
}
#[derive(Debug, Clone)]
pub struct TrailingError {
src: String,
snip: Span,
err_span: Span,
}
impl TrailingError {
pub fn new(source: &str, err_span: Span) -> Self {
TrailingError {
src: source.into(),
snip: (0..source.len()),
err_span,
}
}
}
impl Display for TrailingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt_spanned(
f,
format!("end of parsed value"),
self.err_span.clone(),
&self.src,
)
}
}
impl Error for TrailingError {}
pub trait ExpectToken<'source> {
fn expect_token(
self,
expected: &[Token],
source: &str,
) -> Result<SpannedToken<'source>, ParseError>;
}
impl<'source> ExpectToken<'source> for Option<SpannedToken<'source>> {
fn expect_token(
self,
expected: &[Token],
source: &str,
) -> Result<SpannedToken<'source>, ParseError> {
self.ok_or_else(|| {
UnexpectedTokenError::new(
expected,
None,
source.into(),
0..source.len(),
source.len()..source.len(),
)
.into()
})
.and_then(|token| token.expect_token(expected, source))
}
}
impl<'a, 'source> ExpectToken<'source> for Option<&'a SpannedToken<'source>> {
fn expect_token(
self,
expected: &[Token],
source: &str,
) -> Result<SpannedToken<'source>, ParseError> {
self.ok_or_else(|| {
UnexpectedTokenError::new(
expected,
None,
source.into(),
0..source.len(),
source.len()..source.len(),
)
.into()
})
.and_then(|token| token.clone().expect_token(expected, source))
}
}
impl<'source> ExpectToken<'source> for SpannedToken<'source> {
fn expect_token(
self,
expected: &[Token],
source: &str,
) -> Result<SpannedToken<'source>, ParseError> {
if expected.iter().any(|expect| self.token.eq(expect)) {
Ok(self)
} else {
Err(UnexpectedTokenError::new(
expected,
Some(self.token),
source.into(),
0..source.len(),
self.span,
)
.into())
}
}
}
pub trait ResultExt<T> {
fn with_span(self, span: Span, source: &str) -> Result<T, ParseError>;
}
impl<T, E: Into<PrimitiveErrorKind>> ResultExt<T> for Result<T, E> {
fn with_span(self, span: Span, source: &str) -> Result<T, ParseError> {
self.map_err(|error| {
PrimitiveError {
src: source.into(),
snip: (0..source.len()),
err_span: span,
kind: error.into(),
}
.into()
})
}
}
fn get_position(text: &str, index: usize) -> Position {
let mut pos = Position::default();
for char in text.chars().take(index) {
pos = pos.next(char, &METRICS);
}
pos
}
const METRICS: DefaultMetrics = DefaultMetrics::with_tab_stop(4);
fn fmt_spanned(f: &mut fmt::Formatter<'_>, err: String, span: Span, source: &str) -> fmt::Result {
let start = get_position(source, span.start);
let end = get_position(source, span.end);
let span = SourceSpan::new(start, end, end.next_line());
let mut fmt = Formatter::new();
let buffer = SourceBuffer::new(
source.chars().map(|char| Result::<char, ()>::Ok(char)),
Position::default(),
METRICS,
);
fmt.add(span, Some(format!("{}", err)), Style::Error);
let formatted = fmt
.render(
buffer.iter(),
SourceSpan::new(
Position::default(),
Position::new(usize::max_value() - 1, usize::max_value()),
Position::end(),
),
&METRICS,
)
.unwrap();
write!(f, "{}", formatted)
}