utils/parser/base.rs
1use crate::input::InputError;
2use crate::parser::combinator::{
3 Commit, Map, MapResult, Optional, Or, RepeatArrayVec, RepeatFold, RepeatN, RepeatVec,
4 WithConsumed, WithPrefix, WithSuffix,
5};
6use crate::parser::error::{ParseError, WithErrorMsg};
7use crate::parser::iterator::{ParserIterator, ParserMatchesIterator};
8use crate::parser::simple::{Constant, Eol};
9use crate::parser::then::{Then, Then2, Unimplemented};
10
11/// [`Result`] type returned by [`Parser::parse_ctx`].
12pub type ParserResult<'i, T> = Result<(T, &'i [u8]), ErrToken>;
13
14/// Trait implemented by all parsers.
15///
16/// Unlike [`Leaf`](super::Leaf) parsers, parsers implementing this trait may handle branching and
17/// error recovery, including backtracking and commit.
18///
19/// Every [`Leaf`](super::Leaf) parser is also a [`Parser`] via a blanket implementation.
20#[must_use]
21pub trait Parser<'i>: Sized {
22 /// Type of the value produced by [`parse`](Self::parse_ctx) when successful.
23 type Output;
24
25 /// Type of the chained parser returned by [`then`](Self::then).
26 ///
27 /// This is used to allow multiple [`then`](Self::then) calls to extend one tuple, instead of
28 /// nesting tuples inside each other.
29 type Then<T: Parser<'i>>: Then<'i, Self, T>;
30
31 /// Parse the provided bytes.
32 ///
33 /// Returns a tuple of the successfully parsed [`Output`](Self::Output) value and the
34 /// remaining bytes, or an [`ErrToken`] representing that an error was pushed into the provided
35 /// [`ParseState`].
36 fn parse_ctx(
37 &self,
38 input: &'i [u8],
39 state: &mut ParseState<'i>,
40 commit: &mut bool,
41 tail: bool,
42 ) -> ParserResult<'i, Self::Output>;
43
44 // Provided methods
45
46 /// Sequence another parser after this one.
47 ///
48 /// # Examples
49 /// ```
50 /// # use utils::parser::{self, ParseState, Parser};
51 /// assert!(matches!(
52 /// parser::i32()
53 /// .then(parser::i32())
54 /// .parse_complete("123-123"),
55 /// Ok((123, -123)),
56 /// ));
57 /// ```
58 #[inline]
59 fn then<T: Parser<'i>>(self, next: T) -> Self::Then<T> {
60 Then::then(self, next)
61 }
62
63 /// Attempt to parse using this parser, followed by the provided parser.
64 ///
65 /// The second parser will not be tried if the first parser commits.
66 ///
67 /// See also [`parser::one_of`](super::one_of()).
68 ///
69 /// # Examples
70 /// ```
71 /// # use utils::parser::{self, ParseError, Parser};
72 /// let parser = parser::u8()
73 /// .map(|x| u32::from(x) * 1001001)
74 /// .or(parser::u32());
75 /// assert!(matches!(
76 /// parser.parse_complete("123"),
77 /// Ok(123123123)
78 /// ));
79 /// assert!(matches!(
80 /// parser.parse_complete("1000"),
81 /// Ok(1000)
82 /// ));
83 /// ```
84 #[inline]
85 fn or<T: Parser<'i, Output = Self::Output>>(self, alternative: T) -> Or<Self, T> {
86 Or {
87 first: self,
88 second: alternative,
89 }
90 }
91
92 /// Prevent backtracking past this parser if it succeeds and consumes input.
93 ///
94 /// After committing, any later errors within the current alternative are treated as fatal,
95 /// preventing the current innermost alternative parser from trying other branches.
96 ///
97 /// This can be used to help ensure error messages are clear in cases where returning the
98 /// furthest error from another branch would be misleading.
99 /// It can also improve performance in error cases.
100 ///
101 /// If this parser is not inside an alternative, this has no effect.
102 ///
103 /// The following alternative parsers honor commit to prevent backtracking:
104 /// - [`Parser::optional`]
105 /// - [`Parser::or`]
106 /// - [`Parser::repeat_arrayvec`]
107 /// - [`Parser::repeat`]
108 /// - [`parser::one_of`](super::one_of())
109 /// - [`parser::parse_tree`](super::parse_tree)
110 #[inline]
111 fn commit(self) -> Commit<Self> {
112 Commit { parser: self }
113 }
114
115 /// Map the output of this parser using the supplied function.
116 ///
117 /// # Examples
118 /// ```
119 /// # use utils::parser::{self, Parser};
120 /// assert!(matches!(
121 /// parser::u32()
122 /// .map(|x| x * 2)
123 /// .parse_complete("123"),
124 /// Ok(246)
125 /// ));
126 /// ```
127 ///
128 /// Closure that returns a value borrowing from both its input and an outer variable:
129 /// ```
130 /// # use utils::parser::{self, Parser};
131 /// let my_string = String::from("123");
132 /// let my_vec = vec![4, 5, 6];
133 /// assert!(matches!(
134 /// parser::take_while(u8::is_ascii_digit)
135 /// .map(|x| (x, my_vec.as_slice()))
136 /// .parse_complete(&my_string),
137 /// Ok((&[b'1', b'2', b'3'], &[4, 5, 6]))
138 /// ));
139 /// ```
140 #[inline]
141 fn map<O, F: Fn(Self::Output) -> O>(self, f: F) -> Map<Self, F> {
142 Map {
143 parser: self,
144 map_fn: f,
145 }
146 }
147
148 /// Map the output of this parser using the supplied fallible function.
149 ///
150 /// Errors must be `&'static str`, which will be mapped to [`ParseError::Custom`].
151 ///
152 /// # Examples
153 /// ```
154 /// # use utils::parser::{self, ParseError, Parser};
155 /// let parser = parser::u8()
156 /// .map_res(|x| x.checked_mul(2).ok_or("input too large"));
157 /// assert!(matches!(
158 /// parser.parse_complete("123"),
159 /// Ok(246)
160 /// ));
161 /// assert_eq!(
162 /// parser.parse_complete("200").unwrap_err().into_source(),
163 /// ParseError::Custom("input too large"),
164 /// );
165 /// ```
166 ///
167 /// Closure that returns a value borrowing from both its input and an outer variable:
168 /// ```
169 /// # use utils::parser::{self, Parser};
170 /// let my_string = String::from("123");
171 /// let my_vec = vec![4, 5, 6];
172 /// assert!(matches!(
173 /// parser::take_while(u8::is_ascii_digit)
174 /// .map_res(|x| {
175 /// if x.len() < 10 {
176 /// Ok((x, my_vec.as_slice()))
177 /// } else {
178 /// Err("expected fewer than 10 digits")
179 /// }
180 /// })
181 /// .parse_complete(&my_string),
182 /// Ok((&[b'1', b'2', b'3'], &[4, 5, 6]))
183 /// ));
184 /// ```
185 #[inline]
186 fn map_res<O, F: Fn(Self::Output) -> Result<O, &'static str>>(
187 self,
188 f: F,
189 ) -> MapResult<Self, F> {
190 MapResult {
191 parser: self,
192 map_fn: f,
193 }
194 }
195
196 /// Wrap [`Output`](Self::Output) in [`Option`], returning [`None`] on error unless the parser
197 /// commits.
198 ///
199 /// # Examples
200 /// ```
201 /// # use utils::parser::{self, ParseError, Parser};
202 /// let parser = parser::u32()
203 /// .optional();
204 /// assert!(matches!(
205 /// parser.parse_first("123"),
206 /// Ok((Some(123), &[]))
207 /// ));
208 /// assert!(matches!(
209 /// parser.parse_first("abc"),
210 /// Ok((None, &[b'a', b'b', b'c']))
211 /// ));
212 /// ```
213 #[inline]
214 fn optional(self) -> Optional<Self> {
215 Optional { parser: self }
216 }
217
218 /// Repeat this parser `N` times, returning an [`array`].
219 ///
220 /// If the number of items is variable use [`repeat_arrayvec`](Self::repeat_arrayvec) or
221 /// [`repeat`](Self::repeat).
222 ///
223 /// # Examples
224 /// ```
225 /// # use utils::parser::{self, Parser};
226 /// assert!(matches!(
227 /// parser::u32()
228 /// .repeat_n(",") // N = 3 is inferred
229 /// .parse_complete("12,34,56"),
230 /// Ok([12, 34, 56])
231 /// ));
232 /// ```
233 #[inline]
234 fn repeat_n<const N: usize, S: Parser<'i>>(self, separator: S) -> RepeatN<N, Self, S>
235 where
236 Self::Output: Default,
237 {
238 RepeatN {
239 parser: self,
240 separator,
241 }
242 }
243
244 /// Repeat this parser while it matches, returning a [`ArrayVec`](crate::array::ArrayVec).
245 ///
246 /// This parser can parse up to `N` items. If more items match, it will return an error.
247 ///
248 /// Returns error if the item parser commits and fails, or if the separator commits and then
249 /// either it or the next item fails.
250 ///
251 /// See [`repeat`](Self::repeat) if the upper bound is large or not known, and
252 /// [`repeat_n`](Self::repeat_n) if the number of items is consistent.
253 ///
254 /// # Examples
255 /// ```
256 /// # use utils::array::ArrayVec;
257 /// # use utils::parser::{self, Parser};
258 /// let parser = parser::u32()
259 /// .repeat_arrayvec::<5, _>(",", 3);
260 /// assert_eq!(
261 /// parser.parse_first("12,34,56,78").unwrap(),
262 /// (ArrayVec::from_slice(&[12, 34, 56, 78]).unwrap(), &b""[..])
263 /// );
264 /// assert_eq!(
265 /// parser.parse_first("12,34,56,abc").unwrap(),
266 /// (ArrayVec::from_slice(&[12, 34, 56]).unwrap(), &b",abc"[..])
267 /// );
268 /// assert!(parser.parse_first("12,34").is_err());
269 /// ```
270 #[inline]
271 fn repeat_arrayvec<const N: usize, S: Parser<'i>>(
272 self,
273 separator: S,
274 min_elements: usize,
275 ) -> RepeatArrayVec<N, Self, S>
276 where
277 Self::Output: Copy + Default,
278 {
279 RepeatArrayVec {
280 parser: self,
281 separator,
282 min_elements,
283 }
284 }
285
286 /// Repeat this parser while it matches, folding every element into an accumulator.
287 ///
288 /// This is modeled after [`Iterator::fold`]. See also [`repeat`](Self::repeat).
289 ///
290 /// # Examples
291 /// ```
292 /// # use utils::parser::{self, Parser};
293 /// let parser = parser::u32().repeat_fold(",", 3, 0, |acc, x| acc + x);
294 /// assert_eq!(
295 /// parser.parse_first("12,34,56,78").unwrap(),
296 /// (12 + 34 + 56 + 78, &b""[..])
297 /// );
298 /// assert_eq!(
299 /// parser.parse_first("12,34,56,abc").unwrap(),
300 /// (12 + 34 + 56, &b",abc"[..])
301 /// );
302 /// assert!(parser.parse_first("12,34").is_err());
303 /// ```
304 #[inline]
305 fn repeat_fold<S: Parser<'i>, A: Clone, F: Fn(A, Self::Output) -> A>(
306 self,
307 separator: S,
308 min_elements: usize,
309 init: A,
310 f: F,
311 ) -> RepeatFold<Self, S, A, F> {
312 RepeatFold {
313 parser: self,
314 separator,
315 min_elements,
316 init,
317 f,
318 }
319 }
320
321 /// Repeat this parser while it matches, returning a [`Vec`].
322 ///
323 /// Returns error if the item parser commits and fails, or if the separator commits and then
324 /// either it or the next item fails.
325 ///
326 /// To avoid allocating, prefer [`repeat_n`](Self::repeat_n) if the number of items is
327 /// consistent and known in advance, or [`repeat_arrayvec`](Self::repeat_arrayvec) if the number
328 /// of items is variable but has a known upper bound.
329 ///
330 /// # Examples
331 /// ```
332 /// # use utils::parser::{self, Parser};
333 /// let parser = parser::u32()
334 /// .repeat(",", 3);
335 /// assert_eq!(parser.parse_first("12,34,56,78").unwrap(), (vec![12, 34, 56, 78], &b""[..]));
336 /// assert_eq!(parser.parse_first("12,34,56,abc").unwrap(), (vec![12, 34, 56], &b",abc"[..]));
337 /// assert!(parser.parse_first("12,34").is_err());
338 /// ```
339 #[inline]
340 fn repeat<S: Parser<'i>>(self, separator: S, min_elements: usize) -> RepeatVec<Self, S> {
341 RepeatVec {
342 parser: self,
343 separator,
344 min_elements,
345 }
346 }
347
348 /// Return the output of this parser as well as the bytes consumed.
349 ///
350 /// This can be used to map any errors that occur while processing the parsed input back to the
351 /// problematic item's position in the input.
352 ///
353 /// # Examples
354 /// ```
355 /// # use utils::parser::{self, Parser};
356 /// assert_eq!(
357 /// parser::u32().with_consumed().parse_first("012,345,678").unwrap(),
358 /// ((12, &b"012"[..]), &b",345,678"[..])
359 /// );
360 /// ```
361 #[inline]
362 fn with_consumed(self) -> WithConsumed<Self> {
363 WithConsumed { parser: self }
364 }
365
366 /// Parse a prefix (normally a string literal) before this parser.
367 ///
368 /// The result of the prefix parser is discarded.
369 ///
370 /// # Examples
371 /// ```
372 /// # use utils::parser::{self, Parser};
373 /// assert_eq!(
374 /// parser::u32()
375 /// .with_prefix("abc")
376 /// .parse_complete("abc123")
377 /// .unwrap(),
378 /// 123,
379 /// );
380 /// ```
381 #[inline]
382 fn with_prefix<T: Parser<'i>>(self, prefix: T) -> WithPrefix<Self, T> {
383 WithPrefix {
384 parser: self,
385 prefix,
386 }
387 }
388
389 /// Parse a suffix (normally a string literal) after this parser.
390 ///
391 /// The result of the suffix parser is discarded.
392 ///
393 /// # Examples
394 /// ```
395 /// # use utils::parser::{self, Parser};
396 /// assert_eq!(
397 /// parser::u32()
398 /// .with_suffix("abc")
399 /// .parse_complete("123abc")
400 /// .unwrap(),
401 /// 123,
402 /// );
403 /// ```
404 #[inline]
405 fn with_suffix<T: Parser<'i>>(self, suffix: T) -> WithSuffix<Self, T> {
406 WithSuffix {
407 parser: self,
408 suffix,
409 }
410 }
411
412 /// Parse a end of line (or end of string) after this parser.
413 ///
414 /// Equivalent to [`parser.with_suffix`](Parser::with_suffix)`(`[`parser::eol()`](super::eol)`)`.
415 ///
416 /// # Examples
417 /// ```
418 /// # use utils::parser::{self, Parser};
419 /// assert_eq!(
420 /// parser::u32()
421 /// .with_eol()
422 /// .parse_first("123\nabc")
423 /// .unwrap(),
424 /// (123, &b"abc"[..]),
425 /// );
426 /// ```
427 #[inline]
428 fn with_eol(self) -> WithSuffix<Self, Eol> {
429 WithSuffix {
430 parser: self,
431 suffix: Eol(),
432 }
433 }
434
435 /// Replace this parser's error message with the provided string.
436 ///
437 /// # Examples
438 /// ```
439 /// # use utils::parser::{self, ParseError, Parser};
440 /// let parser = parser::u8()
441 /// .error_msg("expected power level");
442 /// assert_eq!(
443 /// parser.parse_complete("123").unwrap(),
444 /// 123,
445 /// );
446 /// assert_eq!(
447 /// parser.parse_complete("abc").unwrap_err().into_source(),
448 /// ParseError::Custom("expected power level"),
449 /// );
450 /// ```
451 #[inline]
452 fn error_msg(self, message: &'static str) -> WithErrorMsg<Self> {
453 WithErrorMsg {
454 parser: self,
455 message,
456 }
457 }
458
459 /// Apply this parser once, returning the parsed value and the remaining input or error.
460 ///
461 /// This method should only be used to parse the first match and should not be called repeatedly
462 /// to parse the remainder of the input, as the reported error positions will be incorrect.
463 ///
464 /// # Examples
465 /// ```
466 /// # use utils::parser::{self, Parser};
467 /// assert_eq!(parser::u32().parse_first("1234").unwrap(), (1234, &b""[..]));
468 /// assert_eq!(parser::u32().parse_first("123abc").unwrap(), (123, &b"abc"[..]));
469 /// assert!(parser::u32().parse_first("abc123").is_err());
470 /// ```
471 #[inline]
472 fn parse_first(&self, input: &'i str) -> Result<(Self::Output, &'i [u8]), InputError> {
473 let mut state = ParseState::default();
474 self.parse_ctx(input.as_bytes(), &mut state, &mut false, false)
475 .map_err(|_| state.into_input_error(input))
476 }
477
478 /// Apply this parser once, checking the provided input is fully consumed.
479 ///
480 /// # Examples
481 /// ```
482 /// # use utils::parser::{self, Parser};
483 /// assert_eq!(parser::u32().parse_complete("1234").unwrap(), 1234);
484 /// assert!(parser::u32().parse_complete("1234abc").is_err());
485 /// ```
486 #[inline]
487 fn parse_complete(&self, input: &'i str) -> Result<Self::Output, InputError> {
488 let mut state = ParseState::default();
489 match self.parse_ctx(input.as_bytes(), &mut state, &mut false, true) {
490 Ok((v, [])) => return Ok(v),
491 Ok((_, remaining)) => {
492 // Ensure there is an error reported. This may not be the error returned below, as
493 // one may have already been reported further into the input.
494 let _ = state.error(ParseError::ExpectedEof(), remaining);
495 }
496 Err(_) => {}
497 }
498 Err(state.into_input_error(input))
499 }
500
501 /// Apply this parser repeatedly until the provided input is fully consumed.
502 ///
503 /// Equivalent to `parser.repeat(parser::noop(), 0).parse_complete(input)`.
504 ///
505 /// # Examples
506 /// ```
507 /// # use utils::parser::{self, Parser};
508 /// assert_eq!(
509 /// parser::u32()
510 /// .then(parser::u32().with_prefix("x"))
511 /// .with_suffix(",".or(parser::eof()))
512 /// .parse_all("1x2,3x4,1234x5678")
513 /// .unwrap(),
514 /// vec![
515 /// (1, 2),
516 /// (3, 4),
517 /// (1234, 5678),
518 /// ]
519 /// );
520 /// ```
521 #[inline]
522 fn parse_all(&self, input: &'i str) -> Result<Vec<Self::Output>, InputError> {
523 ParserRef(self)
524 .repeat(Constant(()), 1)
525 .parse_complete(input)
526 }
527
528 /// Similar to [`parse_all`](Self::parse_all) but expects a newline between each item.
529 ///
530 /// # Examples
531 /// ```
532 /// # use utils::parser::{self, Parser};
533 /// assert_eq!(
534 /// parser::u32()
535 /// .then(parser::u32().with_prefix("x"))
536 /// .parse_lines("1x2\n3x4\n1234x5678")
537 /// .unwrap(),
538 /// vec![
539 /// (1, 2),
540 /// (3, 4),
541 /// (1234, 5678),
542 /// ]
543 /// );
544 /// ```
545 #[inline]
546 fn parse_lines(&self, input: &'i str) -> Result<Vec<Self::Output>, InputError> {
547 ParserRef(self).repeat(Eol(), 1).parse_complete(input)
548 }
549
550 /// Create an iterator which applies this parser repeatedly until the provided input is fully
551 /// consumed.
552 ///
553 /// The returned iterator will lazily parse the provided input string, producing a sequence of
554 /// [`Result`] values. Once the end of input is reached, or an error is returned, the parser
555 /// will always return [`None`].
556 ///
557 /// # Examples
558 /// ```
559 /// # use utils::input::InputError;
560 /// # use utils::parser::{self, Parser};
561 /// let iterator = parser::u32()
562 /// .with_eol()
563 /// .parse_iterator("12\n34\n56\n78");
564 /// for item in iterator {
565 /// println!("{}", item?);
566 /// }
567 /// # Ok::<(), InputError>(())
568 /// ```
569 ///
570 /// ```
571 /// # use utils::parser::{self, Parser};
572 /// let mut iterator = parser::u32()
573 /// .with_eol()
574 /// .parse_iterator("12\n34\nnot a integer");
575 /// assert_eq!(iterator.next().unwrap().unwrap(), 12);
576 /// assert_eq!(iterator.next().unwrap().unwrap(), 34);
577 /// assert!(iterator.next().unwrap().is_err());
578 /// assert!(iterator.next().is_none());
579 /// ```
580 ///
581 /// ```
582 /// # use utils::input::InputError;
583 /// # use utils::parser::{self, Parser};
584 /// let filtered = parser::u32()
585 /// .with_eol()
586 /// .parse_iterator("11\n22\n33\n44\n55")
587 /// .filter(|r| r.is_err() || r.as_ref().is_ok_and(|v| v % 2 == 0))
588 /// .collect::<Result<Vec<u32>, InputError>>()?;
589 /// assert_eq!(filtered, vec![22, 44]);
590 /// # Ok::<(), InputError>(())
591 /// ```
592 #[inline]
593 fn parse_iterator(self, input: &str) -> ParserIterator<'_, Self> {
594 ParserIterator {
595 input,
596 remaining: input.as_bytes(),
597 parser: self,
598 }
599 }
600
601 /// Create an iterator which returns matches only and skips over errors.
602 ///
603 /// This is intended for cases that require extracting matches out of the input.
604 /// Otherwise, [`parse_iterator`](Self::parse_iterator) should be used with a parser that can
605 /// match the entire input structure.
606 ///
607 /// # Examples
608 /// ```
609 /// # use utils::parser::{self, Parser};
610 /// assert_eq!(
611 /// parser::u32()
612 /// .matches_iterator("abc123d456efg7hi8jk9lmnop")
613 /// .collect::<Vec<_>>(),
614 /// vec![123, 456, 7, 8, 9]
615 /// );
616 /// ```
617 #[inline]
618 fn matches_iterator(self, input: &str) -> ParserMatchesIterator<'_, Self> {
619 ParserMatchesIterator {
620 remaining: input.as_bytes(),
621 parser: self,
622 }
623 }
624}
625
626// Workaround to allow using methods which consume a parser in methods which take references.
627struct ParserRef<'a, P>(&'a P);
628impl<'i, P: Parser<'i>> Parser<'i> for ParserRef<'_, P> {
629 type Output = P::Output;
630 type Then<T: Parser<'i>> = Unimplemented;
631
632 #[inline]
633 fn parse_ctx(
634 &self,
635 input: &'i [u8],
636 state: &mut ParseState<'i>,
637 commit: &mut bool,
638 tail: bool,
639 ) -> ParserResult<'i, Self::Output> {
640 self.0.parse_ctx(input, state, commit, tail)
641 }
642}
643
644struct FromFn<F>(F);
645impl<'i, F: Fn(&'i [u8], &mut ParseState<'i>, &mut bool, bool) -> ParserResult<'i, O>, O> Parser<'i>
646 for FromFn<F>
647{
648 type Output = O;
649 type Then<T: Parser<'i>> = Then2<Self, T>;
650
651 #[inline]
652 fn parse_ctx(
653 &self,
654 input: &'i [u8],
655 state: &mut ParseState<'i>,
656 commit: &mut bool,
657 tail: bool,
658 ) -> ParserResult<'i, Self::Output> {
659 self.0(input, state, commit, tail)
660 }
661}
662
663/// [`Parser`] which delegates to the provided function/closure.
664///
665/// This wrapper exists to avoid conflicting implementations of the [`Parser`] trait, which would
666/// occur if both [`Leaf`](super::Leaf) and [`Parser`] were implemented for the [`Fn`] trait family.
667#[inline]
668pub fn from_parser_fn<'i, O>(
669 f: impl Fn(&'i [u8], &mut ParseState<'i>, &mut bool, bool) -> ParserResult<'i, O>,
670) -> impl Parser<'i, Output = O> {
671 FromFn(f)
672}
673
674/// Per-parse shared state.
675///
676/// Tracks the furthest encountered error, allowing combinators like [`Parser::optional`] to return
677/// [`Ok`] while still reporting the furthest seen error for better user-facing error messages.
678#[must_use]
679#[derive(Default)]
680pub struct ParseState<'i> {
681 pub(super) error: Option<(ParseError, &'i [u8])>,
682}
683
684impl<'i> ParseState<'i> {
685 /// Record an error.
686 ///
687 /// The error will be discarded if a further error is already stored.
688 ///
689 /// Returns an [`ErrToken`] which can be used to return [`Err`] from [`Parser::parse_ctx`].
690 #[inline]
691 pub fn error(&mut self, error: ParseError, remaining: &'i [u8]) -> ErrToken {
692 if self.error.is_none() || matches!(self.error, Some((_, r)) if r.len() > remaining.len()) {
693 self.error = Some((error, remaining));
694 }
695 ErrToken::new()
696 }
697
698 /// Build an [`InputError`] from the furthest error seen.
699 #[cold]
700 pub fn into_input_error(self, input: &str) -> InputError {
701 let (error, remaining) = self.error.expect("error not set");
702 InputError::new(input, remaining, error)
703 }
704}
705
706mod token {
707 use std::fmt::{Debug, Formatter};
708
709 // Must not be public
710 #[derive(PartialEq, Eq)]
711 struct Private;
712
713 /// ZST used to ensure that [`Parser`](super::Parser) implementations push errors to
714 /// [`ParseState`](super::ParseState).
715 ///
716 /// Parser implementation must acquire an `ErrToken` to return
717 /// [`ParserResult::Err`](super::ParserResult), which can only be done by calling
718 /// [`ParseState::error`](super::ParseState::error) or by propagating an `ErrToken` returned by
719 /// a child parser.
720 #[must_use]
721 #[derive(PartialEq, Eq)] // Must not implement Clone or Default
722 pub struct ErrToken(Private);
723
724 impl ErrToken {
725 pub(super) fn new() -> Self {
726 Self(Private)
727 }
728 }
729
730 impl Debug for ErrToken {
731 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
732 write!(f, "ErrToken")
733 }
734 }
735}
736pub use token::ErrToken;