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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use crate::{TokenIter, TokenStream, TokenTree};
use std::sync::Arc;
/// Result type for parsing.
pub type Result<T> = std::result::Result<T, Error>;
// To keep the Error passing simple and allocation free for the common cases we define these
// common cases plus adding the generic case as dyn boxed error.
/// Actual kind of an error.
#[derive(Clone)]
pub enum ErrorKind {
/// A no error state that can be upgraded by later errors.
NoError,
/// Parser failed.
UnexpectedToken,
/// `RangedRepeats` with invalid bound.
OutOfRange {
/// The min/max bound that failed
have: usize,
/// The MIN/MAX defined in the type
want: usize,
},
/// A repeating parser detected that the inner parser succeeded without consuming any tokens.
InfiniteLoop {
/// The type that succeeded without consuming tokens
parser_type: &'static str,
},
/// Something else failed which can be formatted as `String`.
Other {
/// explanation what failed
reason: String,
},
/// Any other error.
Dynamic(Arc<dyn std::error::Error>),
}
/// Error type for parsing.
#[must_use]
#[derive(Clone)]
pub struct Error {
/// Kind of the error.
pub kind: ErrorKind,
/// type name of what was expected
expected: &'static str,
/// refines type name for complex parsers
refined: Option<&'static str>,
at: Option<TokenTree>,
/// Cloned iterator positioned at the error
after: Option<TokenIter>,
// TokenIter position where it happened
// on disjunct parsers we use this to determine which error to keep
pos: usize,
}
impl Error {
/// Create a `ErrorKind::NoError` error.
#[allow(clippy::missing_errors_doc)]
pub const fn no_error() -> Self {
Error {
kind: ErrorKind::NoError,
expected: "<NoError>",
refined: None,
at: None,
after: None,
pos: 0,
}
}
/// Upgrade an error to one with greater pos value.
#[allow(clippy::missing_errors_doc)]
pub fn upgrade<T>(&mut self, r: Result<T>) -> Result<T> {
if let Err(other) = &r {
if matches!(self.kind, ErrorKind::NoError) || other.pos > self.pos {
*self = other.clone();
}
}
r
}
/// Set the position of the error.
///
/// Sometimes the position of the error is not known at the time of creation. This allows
/// to adjust it later.
pub fn set_pos(&mut self, pos: impl TokenCount) {
self.pos = pos.token_count();
}
/// Get the position of the error.
#[must_use]
pub const fn pos(&self) -> usize {
self.pos
}
/// Create a `Result<T>::Err(Error{ kind: ErrorKind::UnexpectedToken })` error at a token iter position.
/// Takes the failed token (if available) and a reference to the `TokenIter` past the error.
///
/// # Note on position tracking
/// The `pos` field is set to `after.counter()`, which represents the number of tokens
/// that were consumed up to and including the failed token (if any):
/// - If `at` is `Some(token)`: The token was consumed by `next()` which incremented the counter,
/// so `pos` reflects the position AFTER consuming the failed token.
/// - If `at` is `None`: The iterator was exhausted, so `pos` reflects how many tokens were
/// successfully consumed before running out.
// This semantic is crucial for `Either<>` to correctly identify which alternative parsed
// furthest into the token stream.
#[allow(clippy::missing_errors_doc)]
pub fn unexpected_token<T>(at: Option<TokenTree>, after: &TokenIter) -> Result<T> {
// Clone the iterator and collect remaining tokens into a new TokenStream
let pos = after.counter();
Err(Error {
kind: ErrorKind::UnexpectedToken,
expected: std::any::type_name::<T>(),
refined: None,
at,
after: Some(after.clone()),
pos,
})
}
/// Create a `Result<T>::Err(Error{ kind: ErrorKind::UnexpectedToken })` error without a token iter.
#[allow(clippy::missing_errors_doc)]
pub fn unexpected_end<T>() -> Result<T> {
Err(Error {
kind: ErrorKind::UnexpectedToken,
expected: std::any::type_name::<T>(),
refined: None,
at: None,
after: None,
pos: usize::MAX,
})
}
/// Create a `Result<T>::Err(Error{ kind: ErrorKind::OutOfRange })` error at a token iter position.
/// Takes the failed token (if available) and a reference to the `TokenIter` past the error.
#[allow(clippy::missing_errors_doc)]
pub fn out_of_range<const LIM: usize, T>(
have: usize,
at: Option<TokenTree>,
after: &TokenIter,
) -> Result<T> {
let pos = after.counter();
Err(Error {
kind: ErrorKind::OutOfRange { have, want: LIM },
expected: std::any::type_name::<T>(),
refined: None,
at,
after: Some(after.clone()),
pos,
})
}
/// Create a `Result<T>::Err(Error{ kind: ErrorKind::Other })` error. Takes the failed
/// token (if available), a reference to the `TokenIter` past the error and a `String`
/// describing the error.
#[allow(clippy::missing_errors_doc)]
pub fn other<T>(at: Option<TokenTree>, after: &TokenIter, reason: String) -> Result<T> {
let pos = after.counter();
Err(Error {
kind: ErrorKind::Other { reason },
expected: std::any::type_name::<T>(),
refined: None,
at,
after: Some(after.clone()),
pos,
})
}
/// Create a `Result<T>::Err(Error{ kind: ErrorKind::InfiniteLoop })` error. Used when a
/// repeating (conatianer) parser detects that the inner parser succeeded without
/// consuming any tokens, which would lead to an infinite loop.
#[allow(clippy::missing_errors_doc)]
pub fn infinite_loop<T>(at: Option<TokenTree>, after: &TokenIter) -> Result<T> {
let pos = after.counter();
Err(Error {
kind: ErrorKind::InfiniteLoop {
parser_type: std::any::type_name::<T>(),
},
expected: std::any::type_name::<T>(),
refined: None,
at,
after: Some(after.clone()),
pos,
})
}
/// Create a `Result<T>::Err(Error{ kind: ErrorKind::Dynamic })` error. Takes the failed
/// token (if available), a reference to the `TokenIter` past the error and a boxed error.
#[allow(clippy::missing_errors_doc)]
pub fn dynamic<T>(
at: Option<TokenTree>,
after: &TokenIter,
error: impl std::error::Error + Send + Sync + 'static,
) -> Result<T> {
let pos = after.counter();
Err(Error {
kind: ErrorKind::Dynamic(Arc::new(error)),
expected: std::any::type_name::<T>(),
refined: None,
at,
after: Some(after.clone()),
pos,
})
}
/// Returns the refined type name of the parser that failed.
#[must_use]
pub fn expected_type_name(&self) -> &'static str {
self.refined.unwrap_or(self.expected)
}
/// Returns the original/fundamental type name of the parser that failed.
#[must_use]
pub const fn expected_original_type_name(&self) -> &'static str {
self.expected
}
/// Returns a `Option<TokenTree>` where the error happend.
#[must_use]
pub fn failed_at(&self) -> Option<TokenTree> {
self.at.clone()
}
/// Returns a iterator to the tokens after the error
///
/// Creates a new `TokenIter` from the stored token stream position
#[must_use]
pub fn tokens_after(&self) -> TokenIter {
self.after
.clone()
.unwrap_or_else(|| TokenIter::new(TokenStream::new()))
}
}
impl std::error::Error for Error {}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &self.kind {
ErrorKind::NoError => {
write!(f, "NoError")
}
ErrorKind::UnexpectedToken => {
write!(
f,
"Unexpected token: expected {}, found {:?} at {:?}",
self.expected_type_name(),
OptionPP(&self.at),
OptionPP(&self.at.as_ref().map(|s| s.span().start()))
)
}
ErrorKind::OutOfRange { have, want } => {
write!(
f,
"RangedRepeats out of bounds: expected {want}, requested {have} at {:?}",
OptionPP(&self.at.as_ref().map(|s| s.span().start()))
)
}
ErrorKind::InfiniteLoop { parser_type } => {
write!(
f,
"Infinite loop detected: parser {} succeeded without consuming tokens at {:?}",
parser_type,
OptionPP(&self.at.as_ref().map(|s| s.span().start()))
)
}
ErrorKind::Other { reason } => {
write!(
f,
"Parser failed: expected {}, because {reason}, found {:?} at {:?}",
self.expected_type_name(),
OptionPP(&self.at),
OptionPP(&self.at.as_ref().map(|s| s.span().start()))
)
}
ErrorKind::Dynamic(err) => {
write!(
f,
"Parser failed: expected {}, because {err}, found {:?} at {:?}",
self.expected_type_name(),
OptionPP(&self.at),
OptionPP(&self.at.as_ref().map(|s| s.span().start()))
)
}
}
}
}
impl std::fmt::Display for Error {
#[cfg_attr(test, mutants::skip)]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match &self.kind {
ErrorKind::NoError => {
write!(f, "NoError")
}
ErrorKind::UnexpectedToken => {
write!(
f,
"Unexpected token: expected {}, found {:?} at {:?}",
self.expected_type_name(),
OptionPP(&self.at),
OptionPP(&self.at.as_ref().map(|s| s.span().start()))
)
}
ErrorKind::OutOfRange { have, want } => {
write!(
f,
"RangedRepeats out of bounds: expected {want}, requested {have} at {:?}",
OptionPP(&self.at.as_ref().map(|s| s.span().start()))
)
}
ErrorKind::InfiniteLoop { parser_type } => {
write!(
f,
"Infinite loop detected: parser {} succeeded without consuming tokens at {:?}",
parser_type,
OptionPP(&self.at.as_ref().map(|s| s.span().start()))
)
}
ErrorKind::Other { reason } => {
write!(
f,
"Parser failed: expected {}, because {reason}, found {:?} at {:?}",
self.expected_type_name(),
OptionPP(&self.at),
OptionPP(&self.at.as_ref().map(|s| s.span().start()))
)
}
ErrorKind::Dynamic(err) => {
write!(
f,
"Parser failed: expected {}, because {err}, found {:?} at {:?}",
self.expected_type_name(),
OptionPP(&self.at),
OptionPP(&self.at.as_ref().map(|s| s.span().start()))
)
}
}
}
}
/// Helper Trait for refining error type names. Every parser type in unsynn eventually tries
/// to parse one of the fundamental types. When parsing fails then that fundamental type name
/// is recorded as expected type name of the error. Often this is not desired, a user wants to
/// know the type of parser that actually failed. Since we don't want to keep a stack/vec of
/// errors for simplicity and performance reasons we provide a way to register refined type
/// names in errors. Note that this refinement should only be applied to leaves in the
/// AST. Refining errors on composed types will lead to unexpected results.
pub trait RefineErr {
/// Refines a errors type name to the type name of `T`.
#[must_use]
fn refine_err<T>(self) -> Self
where
Self: Sized;
}
impl<T> RefineErr for Result<T> {
fn refine_err<U>(mut self) -> Self
where
Self: Sized,
{
if let Err(ref mut err) = self {
err.refined = Some(std::any::type_name::<U>());
}
self
}
}
/// Pretty printer for Options, either prints `None` or `T` without the enclosing Some.
struct OptionPP<'a, T>(&'a Option<T>);
impl<T: std::fmt::Debug> std::fmt::Debug for OptionPP<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
Some(value) => write!(f, "{value:?}"),
None => write!(f, "None"),
}
}
}
impl<T: std::fmt::Display> std::fmt::Display for OptionPP<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
Some(value) => write!(f, "{value}"),
None => write!(f, "None"),
}
}
}
#[test]
fn test_optionpp() {
let none = format!("{}", OptionPP::<i32>(&None));
assert_eq!(none, "None");
let populated = format!("{}", OptionPP(&Some(42)));
assert_eq!(populated, "42");
let none = format!("{:?}", OptionPP::<i32>(&None));
assert_eq!(none, "None");
let populated = format!("{:?}", OptionPP(&Some(42)));
assert_eq!(populated, "42");
}
/// We track the position of the error by counting tokens. This trait is implemented for
/// references to shadow counted `TokenIter`, and `usize`. The later allows to pass in a
/// position directly or use `usize::MAX` in case no position data is available (which will
/// make this error the be the final one when upgrading).
pub trait TokenCount {
/// Get the position of the token iterator.
fn token_count(self) -> usize;
}
// Allows passing a usize directly.
impl TokenCount for usize {
#[inline]
fn token_count(self) -> usize {
self
}
}
impl TokenCount for &TokenIter {
#[inline]
fn token_count(self) -> usize {
self.counter()
}
}
impl TokenCount for &mut TokenIter {
#[inline]
fn token_count(self) -> usize {
self.counter()
}
}
// implementing for &&mut allows us to pass a &mut TokenIter by reference when it is still needed
// later. Otherwise it would need to be reborrow '&mut *iter' which is less ergonomic.
impl TokenCount for &&mut TokenIter {
#[inline]
fn token_count(self) -> usize {
self.counter()
}
}