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    /// assert!(parser.parse_first("12,34,56,78,90,0").is_err());
270    /// ```
271    #[inline]
272    fn repeat_arrayvec<const N: usize, S: Parser<'i>>(
273        self,
274        separator: S,
275        min_elements: usize,
276    ) -> RepeatArrayVec<N, Self, S>
277    where
278        Self::Output: Copy + Default,
279    {
280        RepeatArrayVec {
281            parser: self,
282            separator,
283            min_elements,
284        }
285    }
286
287    /// Repeat this parser while it matches, folding every element into an accumulator.
288    ///
289    /// This is modeled after [`Iterator::fold`]. See also [`repeat`](Self::repeat).
290    ///
291    /// # Examples
292    /// ```
293    /// # use utils::parser::{self, Parser};
294    /// let parser = parser::u32().repeat_fold(",", 3, 0, |acc, x| acc + x);
295    /// assert_eq!(
296    ///     parser.parse_first("12,34,56,78").unwrap(),
297    ///     (12 + 34 + 56 + 78, &b""[..])
298    /// );
299    /// assert_eq!(
300    ///     parser.parse_first("12,34,56,abc").unwrap(),
301    ///     (12 + 34 + 56, &b",abc"[..])
302    /// );
303    /// assert!(parser.parse_first("12,34").is_err());
304    /// ```
305    #[inline]
306    fn repeat_fold<S: Parser<'i>, A: Clone, F: Fn(A, Self::Output) -> A>(
307        self,
308        separator: S,
309        min_elements: usize,
310        init: A,
311        f: F,
312    ) -> RepeatFold<Self, S, A, F> {
313        RepeatFold {
314            parser: self,
315            separator,
316            min_elements,
317            init,
318            f,
319        }
320    }
321
322    /// Repeat this parser while it matches, returning a [`Vec`].
323    ///
324    /// Returns error if the item parser commits and fails, or if the separator commits and then
325    /// either it or the next item fails.
326    ///
327    /// To avoid allocating, prefer [`repeat_n`](Self::repeat_n) if the number of items is
328    /// consistent and known in advance, or [`repeat_arrayvec`](Self::repeat_arrayvec) if the number
329    /// of items is variable but has a known upper bound.
330    ///
331    /// # Examples
332    /// ```
333    /// # use utils::parser::{self, Parser};
334    /// let parser = parser::u32()
335    ///     .repeat(",", 3);
336    /// assert_eq!(parser.parse_first("12,34,56,78").unwrap(), (vec![12, 34, 56, 78], &b""[..]));
337    /// assert_eq!(parser.parse_first("12,34,56,abc").unwrap(), (vec![12, 34, 56], &b",abc"[..]));
338    /// assert!(parser.parse_first("12,34").is_err());
339    /// ```
340    #[inline]
341    fn repeat<S: Parser<'i>>(self, separator: S, min_elements: usize) -> RepeatVec<Self, S> {
342        RepeatVec {
343            parser: self,
344            separator,
345            min_elements,
346        }
347    }
348
349    /// Return the output of this parser as well as the bytes consumed.
350    ///
351    /// This can be used to map any errors that occur while processing the parsed input back to the
352    /// problematic item's position in the input.
353    ///
354    /// # Examples
355    /// ```
356    /// # use utils::parser::{self, Parser};
357    /// assert_eq!(
358    ///     parser::u32().with_consumed().parse_first("012,345,678").unwrap(),
359    ///     ((12, &b"012"[..]), &b",345,678"[..])
360    /// );
361    /// ```
362    #[inline]
363    fn with_consumed(self) -> WithConsumed<Self> {
364        WithConsumed { parser: self }
365    }
366
367    /// Parse a prefix (normally a string literal) before this parser.
368    ///
369    /// The result of the prefix parser is discarded.
370    ///
371    /// # Examples
372    /// ```
373    /// # use utils::parser::{self, Parser};
374    /// assert_eq!(
375    ///     parser::u32()
376    ///         .with_prefix("abc")
377    ///         .parse_complete("abc123")
378    ///         .unwrap(),
379    ///     123,
380    /// );
381    /// ```
382    #[inline]
383    fn with_prefix<T: Parser<'i>>(self, prefix: T) -> WithPrefix<Self, T> {
384        WithPrefix {
385            parser: self,
386            prefix,
387        }
388    }
389
390    /// Parse a suffix (normally a string literal) after this parser.
391    ///
392    /// The result of the suffix parser is discarded.
393    ///
394    /// # Examples
395    /// ```
396    /// # use utils::parser::{self, Parser};
397    /// assert_eq!(
398    ///     parser::u32()
399    ///         .with_suffix("abc")
400    ///         .parse_complete("123abc")
401    ///         .unwrap(),
402    ///     123,
403    /// );
404    /// ```
405    #[inline]
406    fn with_suffix<T: Parser<'i>>(self, suffix: T) -> WithSuffix<Self, T> {
407        WithSuffix {
408            parser: self,
409            suffix,
410        }
411    }
412
413    /// Parse a end of line (or end of string) after this parser.
414    ///
415    /// Equivalent to [`parser.with_suffix`](Parser::with_suffix)`(`[`parser::eol()`](super::eol)`)`.
416    ///
417    /// # Examples
418    /// ```
419    /// # use utils::parser::{self, Parser};
420    /// assert_eq!(
421    ///     parser::u32()
422    ///         .with_eol()
423    ///         .parse_first("123\nabc")
424    ///         .unwrap(),
425    ///     (123, &b"abc"[..]),
426    /// );
427    /// ```
428    #[inline]
429    fn with_eol(self) -> WithSuffix<Self, Eol> {
430        WithSuffix {
431            parser: self,
432            suffix: Eol(),
433        }
434    }
435
436    /// Replace this parser's error message with the provided string.
437    ///
438    /// # Examples
439    /// ```
440    /// # use utils::parser::{self, ParseError, Parser};
441    /// let parser = parser::u8()
442    ///     .error_msg("expected power level");
443    /// assert_eq!(
444    ///     parser.parse_complete("123").unwrap(),
445    ///     123,
446    /// );
447    /// assert_eq!(
448    ///     parser.parse_complete("abc").unwrap_err().into_source(),
449    ///     ParseError::Custom("expected power level"),
450    /// );
451    /// ```
452    #[inline]
453    fn error_msg(self, message: &'static str) -> WithErrorMsg<Self> {
454        WithErrorMsg {
455            parser: self,
456            message,
457        }
458    }
459
460    /// Apply this parser once, returning the parsed value and the remaining input or error.
461    ///
462    /// This method should only be used to parse the first match and should not be called repeatedly
463    /// to parse the remainder of the input, as the reported error positions will be incorrect.
464    ///
465    /// # Examples
466    /// ```
467    /// # use utils::parser::{self, Parser};
468    /// assert_eq!(parser::u32().parse_first("1234").unwrap(), (1234, &b""[..]));
469    /// assert_eq!(parser::u32().parse_first("123abc").unwrap(), (123, &b"abc"[..]));
470    /// assert!(parser::u32().parse_first("abc123").is_err());
471    /// ```
472    #[inline]
473    fn parse_first(&self, input: &'i str) -> Result<(Self::Output, &'i [u8]), InputError> {
474        let mut state = ParseState::default();
475        self.parse_ctx(input.as_bytes(), &mut state, &mut false, false)
476            .map_err(|_| state.into_input_error(input))
477    }
478
479    /// Apply this parser once, checking the provided input is fully consumed.
480    ///
481    /// # Examples
482    /// ```
483    /// # use utils::parser::{self, Parser};
484    /// assert_eq!(parser::u32().parse_complete("1234").unwrap(), 1234);
485    /// assert!(parser::u32().parse_complete("1234abc").is_err());
486    /// ```
487    #[inline]
488    fn parse_complete(&self, input: &'i str) -> Result<Self::Output, InputError> {
489        let mut state = ParseState::default();
490        match self.parse_ctx(input.as_bytes(), &mut state, &mut false, true) {
491            Ok((v, [])) => return Ok(v),
492            Ok((_, remaining)) => {
493                // Ensure there is an error reported. This may not be the error returned below, as
494                // one may have already been reported further into the input.
495                let _ = state.error(ParseError::ExpectedEof(), remaining);
496            }
497            Err(_) => {}
498        }
499        Err(state.into_input_error(input))
500    }
501
502    /// Apply this parser repeatedly until the provided input is fully consumed.
503    ///
504    /// Equivalent to `parser.repeat(parser::noop(), 0).parse_complete(input)`.
505    ///
506    /// # Examples
507    /// ```
508    /// # use utils::parser::{self, Parser};
509    /// assert_eq!(
510    ///     parser::u32()
511    ///         .then(parser::u32().with_prefix("x"))
512    ///         .with_suffix(",".or(parser::eof()))
513    ///         .parse_all("1x2,3x4,1234x5678")
514    ///         .unwrap(),
515    ///     vec![
516    ///         (1, 2),
517    ///         (3, 4),
518    ///         (1234, 5678),
519    ///     ]
520    /// );
521    /// ```
522    #[inline]
523    fn parse_all(&self, input: &'i str) -> Result<Vec<Self::Output>, InputError> {
524        ParserRef(self)
525            .repeat(Constant(()), 1)
526            .parse_complete(input)
527    }
528
529    /// Similar to [`parse_all`](Self::parse_all) but expects a newline between each item.
530    ///
531    /// # Examples
532    /// ```
533    /// # use utils::parser::{self, Parser};
534    /// assert_eq!(
535    ///     parser::u32()
536    ///         .then(parser::u32().with_prefix("x"))
537    ///         .parse_lines("1x2\n3x4\n1234x5678")
538    ///         .unwrap(),
539    ///     vec![
540    ///         (1, 2),
541    ///         (3, 4),
542    ///         (1234, 5678),
543    ///     ]
544    /// );
545    /// ```
546    #[inline]
547    fn parse_lines(&self, input: &'i str) -> Result<Vec<Self::Output>, InputError> {
548        ParserRef(self).repeat(Eol(), 1).parse_complete(input)
549    }
550
551    /// Create an iterator which applies this parser repeatedly until the provided input is fully
552    /// consumed.
553    ///
554    /// The returned iterator will lazily parse the provided input string, producing a sequence of
555    /// [`Result`] values. Once the end of input is reached, or an error is returned, the parser
556    /// will always return [`None`].
557    ///
558    /// # Examples
559    /// ```
560    /// # use utils::input::InputError;
561    /// # use utils::parser::{self, Parser};
562    /// let iterator = parser::u32()
563    ///     .with_eol()
564    ///     .parse_iterator("12\n34\n56\n78");
565    /// for item in iterator {
566    ///     println!("{}", item?);
567    /// }
568    /// # Ok::<(), InputError>(())
569    /// ```
570    ///
571    /// ```
572    /// # use utils::parser::{self, Parser};
573    /// let mut iterator = parser::u32()
574    ///     .with_eol()
575    ///     .parse_iterator("12\n34\nnot a integer");
576    /// assert_eq!(iterator.next().unwrap().unwrap(), 12);
577    /// assert_eq!(iterator.next().unwrap().unwrap(), 34);
578    /// assert!(iterator.next().unwrap().is_err());
579    /// assert!(iterator.next().is_none());
580    /// ```
581    ///
582    /// ```
583    /// # use utils::input::InputError;
584    /// # use utils::parser::{self, Parser};
585    /// let filtered = parser::u32()
586    ///     .with_eol()
587    ///     .parse_iterator("11\n22\n33\n44\n55")
588    ///     .filter(|r| r.is_err() || r.as_ref().is_ok_and(|v| v % 2 == 0))
589    ///     .collect::<Result<Vec<u32>, InputError>>()?;
590    /// assert_eq!(filtered, vec![22, 44]);
591    /// # Ok::<(), InputError>(())
592    /// ```
593    #[inline]
594    fn parse_iterator(self, input: &str) -> ParserIterator<'_, Self> {
595        ParserIterator {
596            input,
597            remaining: input.as_bytes(),
598            parser: self,
599        }
600    }
601
602    /// Create an iterator which returns matches only and skips over errors.
603    ///
604    /// This is intended for cases that require extracting matches out of the input.
605    /// Otherwise, [`parse_iterator`](Self::parse_iterator) should be used with a parser that can
606    /// match the entire input structure.
607    ///
608    /// # Examples
609    /// ```
610    /// # use utils::parser::{self, Parser};
611    /// assert_eq!(
612    ///     parser::u32()
613    ///         .matches_iterator("abc123d456efg7hi8jk9lmnop")
614    ///         .collect::<Vec<_>>(),
615    ///     vec![123, 456, 7, 8, 9]
616    /// );
617    /// ```
618    #[inline]
619    fn matches_iterator(self, input: &str) -> ParserMatchesIterator<'_, Self> {
620        ParserMatchesIterator {
621            remaining: input.as_bytes(),
622            parser: self,
623        }
624    }
625}
626
627// Workaround to allow using methods which consume a parser in methods which take references.
628struct ParserRef<'a, P>(&'a P);
629impl<'i, P: Parser<'i>> Parser<'i> for ParserRef<'_, P> {
630    type Output = P::Output;
631    type Then<T: Parser<'i>> = Unimplemented;
632
633    #[inline]
634    fn parse_ctx(
635        &self,
636        input: &'i [u8],
637        state: &mut ParseState<'i>,
638        commit: &mut bool,
639        tail: bool,
640    ) -> ParserResult<'i, Self::Output> {
641        self.0.parse_ctx(input, state, commit, tail)
642    }
643}
644
645#[derive(Copy, Clone)]
646pub struct FromFn<F>(F);
647impl<'i, F: Fn(&'i [u8], &mut ParseState<'i>, &mut bool, bool) -> ParserResult<'i, O>, O> Parser<'i>
648    for FromFn<F>
649{
650    type Output = O;
651    type Then<T: Parser<'i>> = Then2<Self, T>;
652
653    #[inline]
654    fn parse_ctx(
655        &self,
656        input: &'i [u8],
657        state: &mut ParseState<'i>,
658        commit: &mut bool,
659        tail: bool,
660    ) -> ParserResult<'i, Self::Output> {
661        self.0(input, state, commit, tail)
662    }
663}
664
665/// [`Parser`] which delegates to the provided function/closure.
666///
667/// This wrapper exists to avoid conflicting implementations of the [`Parser`] trait, which would
668/// occur if both [`Leaf`](super::Leaf) and [`Parser`] were implemented for the [`Fn`] trait family.
669#[inline]
670pub fn from_parser_fn<'i, O, F>(f: F) -> FromFn<F>
671where
672    F: Fn(&'i [u8], &mut ParseState<'i>, &mut bool, bool) -> ParserResult<'i, O>,
673{
674    FromFn(f)
675}
676
677/// Per-parse shared state.
678///
679/// Tracks the furthest encountered error, allowing combinators like [`Parser::optional`] to return
680/// [`Ok`] while still reporting the furthest seen error for better user-facing error messages.
681#[must_use]
682#[derive(Default)]
683pub struct ParseState<'i> {
684    pub(super) error: Option<(ParseError, &'i [u8])>,
685}
686
687impl<'i> ParseState<'i> {
688    /// Record an error.
689    ///
690    /// The error will be discarded if a further error is already stored.
691    ///
692    /// Returns an [`ErrToken`] which can be used to return [`Err`] from [`Parser::parse_ctx`].
693    #[inline]
694    pub fn error(&mut self, error: ParseError, remaining: &'i [u8]) -> ErrToken {
695        if self.error.is_none() || matches!(self.error, Some((_, r)) if r.len() > remaining.len()) {
696            self.error = Some((error, remaining));
697        }
698        ErrToken::new()
699    }
700
701    /// Build an [`InputError`] from the furthest error seen.
702    #[cold]
703    pub fn into_input_error(self, input: &str) -> InputError {
704        let (error, remaining) = self.error.expect("error not set");
705        InputError::new(input, remaining, error)
706    }
707}
708
709mod token {
710    use std::fmt::{Debug, Formatter};
711
712    // Must not be public
713    #[derive(PartialEq, Eq)]
714    struct Private;
715
716    /// ZST used to ensure that [`Parser`](super::Parser) implementations push errors to
717    /// [`ParseState`](super::ParseState).
718    ///
719    /// Parser implementation must acquire an `ErrToken` to return
720    /// [`ParserResult::Err`](super::ParserResult), which can only be done by calling
721    /// [`ParseState::error`](super::ParseState::error) or by propagating an `ErrToken` returned by
722    /// a child parser.
723    #[must_use]
724    #[derive(PartialEq, Eq)] // Must not implement Clone or Default
725    pub struct ErrToken(Private);
726
727    impl ErrToken {
728        pub(super) fn new() -> Self {
729            Self(Private)
730        }
731    }
732
733    impl Debug for ErrToken {
734        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
735            write!(f, "ErrToken")
736        }
737    }
738}
739pub use token::ErrToken;