Skip to main content

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