combine/parser/
combinator.rs

1//! Various combinators which do not fit anywhere else.
2
3use crate::{
4    error::{
5        Info, ParseError,
6        ParseResult::{self, *},
7        ResultExt, StreamError, Tracked,
8    },
9    lib::{fmt, marker::PhantomData, mem, str},
10    parser::ParseMode,
11    stream::{input_at_eof, span::Span, ResetStream, Stream, StreamErrorFor, StreamOnce},
12    Parser,
13};
14
15#[cfg(feature = "alloc")]
16use alloc::{boxed::Box, string::String, vec::Vec};
17
18#[cfg(feature = "alloc")]
19use crate::lib::any::Any;
20
21#[derive(Copy, Clone)]
22pub struct NotFollowedBy<P>(P);
23impl<Input, O, P> Parser<Input> for NotFollowedBy<P>
24where
25    Input: Stream,
26    P: Parser<Input, Output = O>,
27{
28    type Output = ();
29    type PartialState = P::PartialState;
30
31    parse_mode!(Input);
32    #[inline]
33    fn parse_mode_impl<M>(
34        &mut self,
35        mode: M,
36        input: &mut Input,
37        state: &mut Self::PartialState,
38    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
39    where
40        M: ParseMode,
41    {
42        let checkpoint = input.checkpoint();
43        let result = self.0.parse_mode(mode, input, state);
44        ctry!(input.reset(checkpoint).committed());
45        match result {
46            CommitOk(_) | PeekOk(_) => PeekErr(Input::Error::empty(input.position()).into()),
47            CommitErr(_) | PeekErr(_) => PeekOk(()),
48        }
49    }
50
51    #[inline]
52    fn add_error(&mut self, _errors: &mut Tracked<<Input as StreamOnce>::Error>) {}
53
54    fn add_committed_expected_error(&mut self, _error: &mut Tracked<<Input as StreamOnce>::Error>) {
55    }
56
57    forward_parser!(Input, parser_count, 0);
58}
59
60/// Succeeds only if `parser` fails.
61/// Never consumes any input.
62///
63/// ```
64/// # extern crate combine;
65/// # use combine::*;
66/// # use combine::parser::char::{alpha_num, string};
67/// # fn main() {
68/// let result = string("let")
69///     .skip(not_followed_by(alpha_num()))
70///     .parse("letx")
71///     .map(|x| x.0);
72/// assert!(result.is_err());
73///
74/// # }
75/// ```
76pub fn not_followed_by<Input, P>(parser: P) -> NotFollowedBy<P>
77where
78    Input: Stream,
79    P: Parser<Input>,
80    P::Output: Into<Info<<Input as StreamOnce>::Token, <Input as StreamOnce>::Range, &'static str>>,
81{
82    NotFollowedBy(parser)
83}
84
85/*
86 * TODO :: Rename `Try` to `Attempt`
87 * Because this is public, it's name cannot be changed without also making a breaking change.
88 */
89#[derive(Copy, Clone)]
90pub struct Try<P>(P);
91impl<Input, O, P> Parser<Input> for Try<P>
92where
93    Input: Stream,
94    P: Parser<Input, Output = O>,
95{
96    type Output = O;
97    type PartialState = P::PartialState;
98
99    #[inline]
100    fn parse_stream(&mut self, input: &mut Input) -> ParseResult<O, <Input as StreamOnce>::Error> {
101        self.parse_lazy(input)
102    }
103
104    parse_mode!(Input);
105    #[inline]
106    fn parse_committed_mode<M>(
107        &mut self,
108        mode: M,
109        input: &mut Input,
110        state: &mut Self::PartialState,
111    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
112    where
113        M: ParseMode,
114    {
115        self.parse_mode(mode, input, state)
116    }
117
118    #[inline]
119    fn parse_mode_impl<M>(
120        &mut self,
121        mode: M,
122        input: &mut Input,
123        state: &mut Self::PartialState,
124    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
125    where
126        M: ParseMode,
127    {
128        match self.0.parse_committed_mode(mode, input, state) {
129            v @ CommitOk(_) | v @ PeekOk(_) | v @ PeekErr(_) => v,
130            CommitErr(err) => {
131                if input.is_partial() && err.is_unexpected_end_of_input() {
132                    CommitErr(err)
133                } else {
134                    PeekErr(err.into())
135                }
136            }
137        }
138    }
139
140    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
141}
142
143/// `attempt(p)` behaves as `p` except it always acts as `p` peeked instead of committed on its
144/// parse.
145///
146/// ```
147/// # extern crate combine;
148/// # use combine::*;
149/// # use combine::parser::char::string;
150/// # fn main() {
151/// let mut p = attempt(string("let"))
152///     .or(string("lex"));
153/// let result = p.parse("lex").map(|x| x.0);
154/// assert_eq!(result, Ok("lex"));
155/// let result = p.parse("aet").map(|x| x.0);
156/// assert!(result.is_err());
157/// # }
158/// ```
159pub fn attempt<Input, P>(p: P) -> Try<P>
160where
161    Input: Stream,
162    P: Parser<Input>,
163{
164    Try(p)
165}
166
167#[derive(Copy, Clone)]
168pub struct LookAhead<P>(P);
169
170impl<Input, O, P> Parser<Input> for LookAhead<P>
171where
172    Input: Stream,
173    P: Parser<Input, Output = O>,
174{
175    type Output = O;
176    type PartialState = ();
177
178    #[inline]
179    fn parse_lazy(&mut self, input: &mut Input) -> ParseResult<O, <Input as StreamOnce>::Error> {
180        let before = input.checkpoint();
181        let result = self.0.parse_lazy(input);
182        ctry!(input.reset(before).committed());
183        let (o, _input) = ctry!(result);
184        PeekOk(o)
185    }
186
187    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
188}
189
190/// `look_ahead(p)` acts as `p` but doesn't consume input on success.
191///
192/// ```
193/// # extern crate combine;
194/// # use combine::*;
195/// # use combine::parser::char::string;
196/// # fn main() {
197/// let mut p = look_ahead(string("test"));
198///
199/// let result = p.parse("test str");
200/// assert_eq!(result, Ok(("test", "test str")));
201///
202/// let result = p.parse("aet");
203/// assert!(result.is_err());
204/// # }
205/// ```
206pub fn look_ahead<Input, P>(p: P) -> LookAhead<P>
207where
208    Input: Stream,
209    P: Parser<Input>,
210{
211    LookAhead(p)
212}
213
214#[derive(Copy, Clone)]
215pub struct Map<P, F>(P, F);
216impl<Input, A, B, P, F> Parser<Input> for Map<P, F>
217where
218    Input: Stream,
219    P: Parser<Input, Output = A>,
220    F: FnMut(A) -> B,
221{
222    type Output = B;
223    type PartialState = P::PartialState;
224
225    parse_mode!(Input);
226    #[inline]
227    fn parse_mode_impl<M>(
228        &mut self,
229        mode: M,
230        input: &mut Input,
231        state: &mut Self::PartialState,
232    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
233    where
234        M: ParseMode,
235    {
236        match self.0.parse_mode(mode, input, state) {
237            CommitOk(x) => CommitOk((self.1)(x)),
238            PeekOk(x) => PeekOk((self.1)(x)),
239            CommitErr(err) => CommitErr(err),
240            PeekErr(err) => PeekErr(err),
241        }
242    }
243
244    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
245}
246
247/// Equivalent to [`p.map(f)`].
248///
249/// [`p.map(f)`]: ../trait.Parser.html#method.map
250pub fn map<Input, P, F, B>(p: P, f: F) -> Map<P, F>
251where
252    Input: Stream,
253    P: Parser<Input>,
254    F: FnMut(P::Output) -> B,
255{
256    Map(p, f)
257}
258
259#[derive(Copy, Clone)]
260pub struct MapInput<P, F>(P, F);
261impl<Input, A, B, P, F> Parser<Input> for MapInput<P, F>
262where
263    Input: Stream,
264    P: Parser<Input, Output = A>,
265    F: FnMut(A, &mut Input) -> B,
266{
267    type Output = B;
268    type PartialState = P::PartialState;
269
270    parse_mode!(Input);
271    #[inline]
272    fn parse_mode_impl<M>(
273        &mut self,
274        mode: M,
275        input: &mut Input,
276        state: &mut Self::PartialState,
277    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
278    where
279        M: ParseMode,
280    {
281        match self.0.parse_mode(mode, input, state) {
282            CommitOk(x) => CommitOk((self.1)(x, input)),
283            PeekOk(x) => PeekOk((self.1)(x, input)),
284            CommitErr(err) => CommitErr(err),
285            PeekErr(err) => PeekErr(err),
286        }
287    }
288
289    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
290}
291
292/// Equivalent to [`p.map_input(f)`].
293///
294/// [`p.map_input(f)`]: ../trait.Parser.html#method.map_input
295pub fn map_input<Input, P, F, B>(p: P, f: F) -> MapInput<P, F>
296where
297    Input: Stream,
298    P: Parser<Input>,
299    F: FnMut(P::Output, &mut Input) -> B,
300{
301    MapInput(p, f)
302}
303
304#[derive(Copy, Clone)]
305pub struct FlatMap<P, F>(P, F);
306impl<Input, A, B, P, F> Parser<Input> for FlatMap<P, F>
307where
308    Input: Stream,
309    P: Parser<Input, Output = A>,
310    F: FnMut(A) -> Result<B, Input::Error>,
311{
312    type Output = B;
313    type PartialState = P::PartialState;
314
315    parse_mode!(Input);
316    #[inline]
317    fn parse_mode_impl<M>(
318        &mut self,
319        mode: M,
320        input: &mut Input,
321        state: &mut Self::PartialState,
322    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
323    where
324        M: ParseMode,
325    {
326        match self.0.parse_mode(mode, input, state) {
327            PeekOk(o) => match (self.1)(o) {
328                Ok(x) => PeekOk(x),
329                Err(err) => PeekErr(err.into()),
330            },
331            CommitOk(o) => match (self.1)(o) {
332                Ok(x) => CommitOk(x),
333                Err(err) => CommitErr(err),
334            },
335            PeekErr(err) => PeekErr(err),
336            CommitErr(err) => CommitErr(err),
337        }
338    }
339
340    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
341}
342
343/// Equivalent to [`p.flat_map(f)`].
344///
345/// [`p.flat_map(f)`]: ../trait.Parser.html#method.flat_map
346pub fn flat_map<Input, P, F, B>(p: P, f: F) -> FlatMap<P, F>
347where
348    Input: Stream,
349    P: Parser<Input>,
350    F: FnMut(P::Output) -> Result<B, <Input as StreamOnce>::Error>,
351{
352    FlatMap(p, f)
353}
354
355#[derive(Copy, Clone)]
356pub struct AndThen<P, F>(P, F);
357impl<Input, P, F, O, E> Parser<Input> for AndThen<P, F>
358where
359    Input: Stream,
360    P: Parser<Input>,
361    F: FnMut(P::Output) -> Result<O, E>,
362    E: Into<<Input::Error as ParseError<Input::Token, Input::Range, Input::Position>>::StreamError>,
363{
364    type Output = O;
365    type PartialState = P::PartialState;
366
367    parse_mode!(Input);
368    fn parse_mode_impl<M>(
369        &mut self,
370        mode: M,
371        input: &mut Input,
372        state: &mut Self::PartialState,
373    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
374    where
375        M: ParseMode,
376    {
377        let position = input.position();
378        let checkpoint = input.checkpoint();
379        match self.0.parse_mode(mode, input, state) {
380            PeekOk(o) => match (self.1)(o) {
381                Ok(o) => PeekOk(o),
382                Err(err) => {
383                    let err = <Input as StreamOnce>::Error::from_error(position, err.into());
384
385                    if input.is_partial() && input_at_eof(input) {
386                        ctry!(input.reset(checkpoint).committed());
387                        CommitErr(err)
388                    } else {
389                        PeekErr(err.into())
390                    }
391                }
392            },
393            CommitOk(o) => match (self.1)(o) {
394                Ok(o) => CommitOk(o),
395                Err(err) => {
396                    if input.is_partial() && input_at_eof(input) {
397                        ctry!(input.reset(checkpoint).committed());
398                    }
399                    CommitErr(<Input as StreamOnce>::Error::from_error(
400                        position,
401                        err.into(),
402                    ))
403                }
404            },
405            PeekErr(err) => PeekErr(err),
406            CommitErr(err) => CommitErr(err),
407        }
408    }
409
410    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
411}
412
413/// Equivalent to [`p.and_then(f)`].
414///
415/// [`p.and_then(f)`]: ../trait.Parser.html#method.and_then
416pub fn and_then<Input, P, F, O, E>(p: P, f: F) -> AndThen<P, F>
417where
418    P: Parser<Input>,
419    F: FnMut(P::Output) -> Result<O, E>,
420    Input: Stream,
421    E: Into<<Input::Error as ParseError<Input::Token, Input::Range, Input::Position>>::StreamError>,
422{
423    AndThen(p, f)
424}
425
426#[derive(Copy, Clone)]
427pub struct Recognize<F, P>(P, PhantomData<fn() -> F>);
428
429impl<F, P> Recognize<F, P> {
430    #[inline]
431    fn recognize_result<Input>(
432        elements: &mut F,
433        before: <Input as ResetStream>::Checkpoint,
434        input: &mut Input,
435        result: ParseResult<P::Output, <Input as StreamOnce>::Error>,
436    ) -> ParseResult<F, <Input as StreamOnce>::Error>
437    where
438        P: Parser<Input>,
439        Input: Stream,
440        F: Default + Extend<Input::Token>,
441    {
442        match result {
443            PeekOk(_) => {
444                let last_position = input.position();
445                ctry!(input.reset(before).committed());
446
447                while input.position() != last_position {
448                    match input.uncons() {
449                        Ok(elem) => elements.extend(Some(elem)),
450                        Err(err) => {
451                            return PeekErr(
452                                <Input as StreamOnce>::Error::from_error(input.position(), err)
453                                    .into(),
454                            );
455                        }
456                    }
457                }
458                PeekOk(mem::take(elements))
459            }
460            CommitOk(_) => {
461                let last_position = input.position();
462                ctry!(input.reset(before).committed());
463
464                while input.position() != last_position {
465                    match input.uncons() {
466                        Ok(elem) => elements.extend(Some(elem)),
467                        Err(err) => {
468                            return CommitErr(<Input as StreamOnce>::Error::from_error(
469                                input.position(),
470                                err,
471                            ));
472                        }
473                    }
474                }
475                CommitOk(mem::take(elements))
476            }
477            CommitErr(err) => {
478                let last_position = input.position();
479                ctry!(input.reset(before).committed());
480
481                while input.position() != last_position {
482                    match input.uncons() {
483                        Ok(elem) => elements.extend(Some(elem)),
484                        Err(err) => {
485                            return CommitErr(<Input as StreamOnce>::Error::from_error(
486                                input.position(),
487                                err,
488                            ));
489                        }
490                    }
491                }
492                CommitErr(err)
493            }
494            PeekErr(err) => PeekErr(err),
495        }
496    }
497}
498
499impl<Input, P, F> Parser<Input> for Recognize<F, P>
500where
501    Input: Stream,
502    P: Parser<Input>,
503    F: Default + Extend<<Input as StreamOnce>::Token>,
504{
505    type Output = F;
506    type PartialState = (F, P::PartialState);
507
508    parse_mode!(Input);
509    fn parse_mode_impl<M>(
510        &mut self,
511        mode: M,
512        input: &mut Input,
513        state: &mut Self::PartialState,
514    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
515    where
516        M: ParseMode,
517    {
518        let (ref mut elements, ref mut child_state) = *state;
519
520        let before = input.checkpoint();
521        let result = self.0.parse_mode(mode, input, child_state);
522        Self::recognize_result(elements, before, input, result)
523    }
524
525    #[inline]
526    fn add_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
527        self.0.add_error(errors)
528    }
529}
530
531/// Constructs a parser which returns the tokens parsed by `parser` accumulated in
532/// `F: Extend<Input::Token>` instead of `P::Output`.
533///
534/// ```
535/// use combine::Parser;
536/// use combine::parser::{repeat::skip_many1, token::token, combinator::recognize, char::digit};
537///
538/// let mut parser = recognize((skip_many1(digit()), token('.'), skip_many1(digit())));
539/// assert_eq!(parser.parse("123.45"), Ok(("123.45".to_string(), "")));
540/// assert_eq!(parser.parse("123.45"), Ok(("123.45".to_string(), "")));
541/// ```
542pub fn recognize<F, Input, P>(parser: P) -> Recognize<F, P>
543where
544    Input: Stream,
545    P: Parser<Input>,
546    F: Default + Extend<<Input as StreamOnce>::Token>,
547{
548    Recognize(parser, PhantomData)
549}
550
551pub enum Either<L, R> {
552    Left(L),
553    Right(R),
554}
555
556impl<Input, L, R> Parser<Input> for Either<L, R>
557where
558    Input: Stream,
559    L: Parser<Input>,
560    R: Parser<Input, Output = L::Output>,
561{
562    type Output = L::Output;
563    type PartialState = Option<Either<L::PartialState, R::PartialState>>;
564
565    #[inline]
566    fn parse_lazy(
567        &mut self,
568        input: &mut Input,
569    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
570        match *self {
571            Either::Left(ref mut x) => x.parse_lazy(input),
572            Either::Right(ref mut x) => x.parse_lazy(input),
573        }
574    }
575
576    parse_mode!(Input);
577    #[inline]
578    fn parse_mode_impl<M>(
579        &mut self,
580        mode: M,
581        input: &mut Input,
582        state: &mut Self::PartialState,
583    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
584    where
585        M: ParseMode,
586    {
587        match *self {
588            Either::Left(ref mut x) => {
589                match *state {
590                    None | Some(Either::Right(_)) => {
591                        *state = Some(Either::Left(L::PartialState::default()))
592                    }
593                    Some(Either::Left(_)) => (),
594                }
595                x.parse_mode(
596                    mode,
597                    input,
598                    match state {
599                        Some(Either::Left(state)) => state,
600                        _ => unreachable!(),
601                    },
602                )
603            }
604            Either::Right(ref mut x) => {
605                match *state {
606                    None | Some(Either::Left(_)) => {
607                        *state = Some(Either::Right(R::PartialState::default()))
608                    }
609                    Some(Either::Right(_)) => (),
610                }
611                x.parse_mode(
612                    mode,
613                    input,
614                    match state {
615                        Some(Either::Right(state)) => state,
616                        _ => unreachable!(),
617                    },
618                )
619            }
620        }
621    }
622
623    #[inline]
624    fn add_error(&mut self, error: &mut Tracked<<Input as StreamOnce>::Error>) {
625        match *self {
626            Either::Left(ref mut x) => x.add_error(error),
627            Either::Right(ref mut x) => x.add_error(error),
628        }
629    }
630}
631
632pub struct NoPartial<P>(P);
633
634impl<Input, P> Parser<Input> for NoPartial<P>
635where
636    Input: Stream,
637    P: Parser<Input>,
638{
639    type Output = <P as Parser<Input>>::Output;
640    type PartialState = ();
641
642    #[inline]
643    fn parse_lazy(
644        &mut self,
645        input: &mut Input,
646    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
647        self.0.parse_lazy(input)
648    }
649
650    parse_mode!(Input);
651    #[inline]
652    fn parse_mode_impl<M>(
653        &mut self,
654        _mode: M,
655        input: &mut Input,
656        _state: &mut Self::PartialState,
657    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
658    where
659        M: ParseMode,
660    {
661        self.0.parse_lazy(input)
662    }
663
664    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
665}
666
667pub fn no_partial<Input, P>(p: P) -> NoPartial<P>
668where
669    Input: Stream,
670    P: Parser<Input>,
671{
672    NoPartial(p)
673}
674
675#[derive(Copy, Clone)]
676pub struct Ignore<P>(P);
677impl<Input, P> Parser<Input> for Ignore<P>
678where
679    Input: Stream,
680    P: Parser<Input>,
681{
682    type Output = ();
683    type PartialState = P::PartialState;
684
685    #[inline]
686    fn parse_lazy(
687        &mut self,
688        input: &mut Input,
689    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
690        self.0.parse_lazy(input).map(|_| ())
691    }
692
693    parse_mode!(Input);
694    #[inline]
695    fn parse_mode_impl<M>(
696        &mut self,
697        mode: M,
698        input: &mut Input,
699        state: &mut Self::PartialState,
700    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
701    where
702        M: ParseMode,
703    {
704        self.0.parse_mode(mode, input, state).map(|_| ())
705    }
706
707    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
708}
709
710#[doc(hidden)]
711pub fn ignore<Input, P>(p: P) -> Ignore<P>
712where
713    Input: Stream,
714    P: Parser<Input>,
715{
716    Ignore(p)
717}
718
719#[cfg(feature = "alloc")]
720#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
721#[derive(Default)]
722pub struct AnyPartialState(Option<Box<dyn Any>>);
723
724#[cfg(feature = "alloc")]
725#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
726pub struct AnyPartialStateParser<P>(P);
727
728#[cfg(feature = "alloc")]
729impl<Input, P> Parser<Input> for AnyPartialStateParser<P>
730where
731    Input: Stream,
732    P: Parser<Input>,
733    P::PartialState: 'static,
734{
735    type Output = P::Output;
736    type PartialState = AnyPartialState;
737
738    #[inline]
739    fn parse_lazy(
740        &mut self,
741        input: &mut Input,
742    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
743        self.0.parse_lazy(input)
744    }
745
746    parse_mode!(Input);
747    #[inline]
748    fn parse_mode<M>(
749        &mut self,
750        mode: M,
751        input: &mut Input,
752        state: &mut Self::PartialState,
753    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
754    where
755        M: ParseMode,
756    {
757        let mut new_child_state;
758        let result = {
759            let child_state = if state.0.is_none() {
760                new_child_state = Some(Default::default());
761                new_child_state.as_mut().unwrap()
762            } else {
763                new_child_state = None;
764                state.0.as_mut().unwrap().downcast_mut().unwrap()
765            };
766
767            self.0.parse_mode(mode, input, child_state)
768        };
769
770        if let CommitErr(_) = result {
771            if state.0.is_none() {
772                // FIXME Make None unreachable for LLVM
773                state.0 = Some(Box::new(new_child_state.unwrap()));
774            }
775        }
776
777        result
778    }
779
780    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
781}
782
783/// Returns a parser where `P::PartialState` is boxed. Useful as a way to avoid writing the type
784/// since it can get very large after combining a few parsers.
785///
786/// ```
787/// # #[macro_use]
788/// # extern crate combine;
789/// # use combine::parser::combinator::{AnyPartialState, any_partial_state};
790/// # use combine::parser::char::letter;
791/// # use combine::*;
792///
793/// # fn main() {
794///
795/// parser! {
796///     type PartialState = AnyPartialState;
797///     fn example[Input]()(Input) -> (char, char)
798///     where [ Input: Stream<Token = char> ]
799///     {
800///         any_partial_state((letter(), letter()))
801///     }
802/// }
803///
804/// assert_eq!(
805///     example().easy_parse("ab"),
806///     Ok((('a', 'b'), ""))
807/// );
808///
809/// # }
810/// ```
811#[cfg(feature = "alloc")]
812#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
813pub fn any_partial_state<Input, P>(p: P) -> AnyPartialStateParser<P>
814where
815    Input: Stream,
816    P: Parser<Input>,
817    P::PartialState: 'static,
818{
819    AnyPartialStateParser(p)
820}
821
822#[cfg(feature = "alloc")]
823#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
824#[derive(Default)]
825pub struct AnySendPartialState(Option<Box<dyn Any + Send>>);
826
827#[cfg(feature = "alloc")]
828#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
829pub struct AnySendPartialStateParser<P>(P);
830
831#[cfg(feature = "alloc")]
832impl<Input, P> Parser<Input> for AnySendPartialStateParser<P>
833where
834    Input: Stream,
835    P: Parser<Input>,
836    P::PartialState: Send + 'static,
837{
838    type Output = P::Output;
839    type PartialState = AnySendPartialState;
840
841    #[inline]
842    fn parse_lazy(
843        &mut self,
844        input: &mut Input,
845    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
846        self.0.parse_lazy(input)
847    }
848
849    parse_mode!(Input);
850    #[inline]
851    fn parse_mode<M>(
852        &mut self,
853        mode: M,
854        input: &mut Input,
855        state: &mut Self::PartialState,
856    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
857    where
858        M: ParseMode,
859    {
860        let mut new_child_state;
861        let result = {
862            let child_state = if state.0.is_none() {
863                new_child_state = Some(Default::default());
864                new_child_state.as_mut().unwrap()
865            } else {
866                new_child_state = None;
867                state.0.as_mut().unwrap().downcast_mut().unwrap()
868            };
869
870            self.0.parse_mode(mode, input, child_state)
871        };
872
873        if let CommitErr(_) = result {
874            if state.0.is_none() {
875                // FIXME Make None unreachable for LLVM
876                state.0 = Some(Box::new(new_child_state.unwrap()));
877            }
878        }
879
880        result
881    }
882
883    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
884}
885
886/// Returns a parser where `P::PartialState` is boxed. Useful as a way to avoid writing the type
887/// since it can get very large after combining a few parsers.
888///
889/// ```
890/// # #[macro_use]
891/// # extern crate combine;
892/// # use combine::parser::combinator::{AnySendPartialState, any_send_partial_state};
893/// # use combine::parser::char::letter;
894/// # use combine::*;
895///
896/// # fn main() {
897///
898/// parser! {
899///     type PartialState = AnySendPartialState;
900///     fn example[Input]()(Input) -> (char, char)
901///     where [ Input: Stream<Token = char> ]
902///     {
903///         any_send_partial_state((letter(), letter()))
904///     }
905/// }
906///
907/// assert_eq!(
908///     example().easy_parse("ab"),
909///     Ok((('a', 'b'), ""))
910/// );
911///
912/// # }
913/// ```
914#[cfg(feature = "alloc")]
915#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
916pub fn any_send_partial_state<Input, P>(p: P) -> AnySendPartialStateParser<P>
917where
918    Input: Stream,
919    P: Parser<Input>,
920    P::PartialState: Send + 'static,
921{
922    AnySendPartialStateParser(p)
923}
924
925#[cfg(feature = "alloc")]
926#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
927#[derive(Default)]
928pub struct AnySendSyncPartialState(Option<Box<dyn Any + Send + Sync>>);
929
930#[cfg(feature = "alloc")]
931#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
932pub struct AnySendSyncPartialStateParser<P>(P);
933
934#[cfg(feature = "alloc")]
935impl<Input, P> Parser<Input> for AnySendSyncPartialStateParser<P>
936where
937    Input: Stream,
938    P: Parser<Input>,
939    P::PartialState: Send + Sync + 'static,
940{
941    type Output = P::Output;
942    type PartialState = AnySendSyncPartialState;
943
944    #[inline]
945    fn parse_lazy(
946        &mut self,
947        input: &mut Input,
948    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
949        self.0.parse_lazy(input)
950    }
951
952    parse_mode!(Input);
953    #[inline]
954    fn parse_mode<M>(
955        &mut self,
956        mode: M,
957        input: &mut Input,
958        state: &mut Self::PartialState,
959    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
960    where
961        M: ParseMode,
962    {
963        let mut new_child_state;
964        let result = {
965            let child_state = if state.0.is_none() {
966                new_child_state = Some(Default::default());
967                new_child_state.as_mut().unwrap()
968            } else {
969                new_child_state = None;
970                state.0.as_mut().unwrap().downcast_mut().unwrap()
971            };
972
973            self.0.parse_mode(mode, input, child_state)
974        };
975
976        if let CommitErr(_) = result {
977            if state.0.is_none() {
978                // FIXME Make None unreachable for LLVM
979                state.0 = Some(Box::new(new_child_state.unwrap()));
980            }
981        }
982
983        result
984    }
985
986    forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
987}
988
989/// Returns a parser where `P::PartialState` is boxed. Useful as a way to avoid writing the type
990/// since it can get very large after combining a few parsers.
991///
992/// ```
993/// # #[macro_use]
994/// # extern crate combine;
995/// # use combine::parser::combinator::{AnySendSyncPartialState, any_send_sync_partial_state};
996/// # use combine::parser::char::letter;
997/// # use combine::*;
998///
999/// # fn main() {
1000///
1001/// fn example<Input>() -> impl Parser<Input, Output = (char, char), PartialState = AnySendSyncPartialState>
1002/// where
1003///     Input: Stream<Token = char>,
1004/// {
1005///     any_send_sync_partial_state((letter(), letter()))
1006/// }
1007///
1008/// assert_eq!(
1009///     example().easy_parse("ab"),
1010///     Ok((('a', 'b'), ""))
1011/// );
1012///
1013/// # }
1014/// ```
1015#[cfg(feature = "alloc")]
1016#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1017pub fn any_send_sync_partial_state<Input, P>(p: P) -> AnySendSyncPartialStateParser<P>
1018where
1019    Input: Stream,
1020    P: Parser<Input>,
1021    P::PartialState: Send + Sync + 'static,
1022{
1023    AnySendSyncPartialStateParser(p)
1024}
1025
1026#[derive(Copy, Clone)]
1027pub struct Lazy<P>(P);
1028impl<Input, O, P, R> Parser<Input> for Lazy<P>
1029where
1030    Input: Stream,
1031    P: FnMut() -> R,
1032    R: Parser<Input, Output = O>,
1033{
1034    type Output = O;
1035    type PartialState = R::PartialState;
1036
1037    fn parse_stream(&mut self, input: &mut Input) -> ParseResult<O, <Input as StreamOnce>::Error> {
1038        (self.0)().parse_stream(input)
1039    }
1040
1041    fn parse_lazy(&mut self, input: &mut Input) -> ParseResult<O, <Input as StreamOnce>::Error> {
1042        (self.0)().parse_lazy(input)
1043    }
1044
1045    parse_mode!(Input);
1046
1047    fn parse_committed_mode<M>(
1048        &mut self,
1049        mode: M,
1050        input: &mut Input,
1051        state: &mut Self::PartialState,
1052    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
1053    where
1054        M: ParseMode,
1055    {
1056        (self.0)().parse_mode(mode, input, state)
1057    }
1058
1059    fn parse_mode_impl<M>(
1060        &mut self,
1061        mode: M,
1062        input: &mut Input,
1063        state: &mut Self::PartialState,
1064    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
1065    where
1066        M: ParseMode,
1067    {
1068        (self.0)().parse_mode_impl(mode, input, state)
1069    }
1070
1071    fn add_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1072        (self.0)().add_error(errors);
1073    }
1074
1075    fn add_committed_expected_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1076        (self.0)().add_committed_expected_error(errors);
1077    }
1078}
1079
1080/// Constructs the parser lazily on each `parse_*` call. Can be used to effectively reduce the
1081/// size of deeply nested parsers as only the function producing the parser is stored.
1082///
1083/// NOTE: Expects that the parser returned is always the same one, if that is not the case the
1084/// reported error may be wrong. If different parsers may be returned, use the [`factory`][] parser
1085/// instead.
1086///
1087/// [`factory`]: fn.factory.html
1088pub fn lazy<Input, P, R>(p: P) -> Lazy<P>
1089where
1090    Input: Stream,
1091    P: FnMut() -> R,
1092    R: Parser<Input>,
1093{
1094    Lazy(p)
1095}
1096
1097#[derive(Copy, Clone)]
1098pub struct Factory<P, R>(P, Option<R>);
1099
1100impl<P, R> Factory<P, R> {
1101    fn parser<Input>(&mut self, input: &mut Input) -> &mut R
1102    where
1103        P: FnMut(&mut Input) -> R,
1104    {
1105        if let Some(ref mut r) = self.1 {
1106            return r;
1107        }
1108        self.1 = Some((self.0)(input));
1109        self.1.as_mut().unwrap()
1110    }
1111}
1112
1113impl<Input, O, P, R> Parser<Input> for Factory<P, R>
1114where
1115    Input: Stream,
1116    P: FnMut(&mut Input) -> R,
1117    R: Parser<Input, Output = O>,
1118{
1119    type Output = O;
1120    type PartialState = R::PartialState;
1121
1122    parse_mode!(Input);
1123
1124    fn parse_mode_impl<M>(
1125        &mut self,
1126        mode: M,
1127        input: &mut Input,
1128        state: &mut Self::PartialState,
1129    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
1130    where
1131        M: ParseMode,
1132    {
1133        // Always ask for a new parser except if we are in a partial call being resumed as we want
1134        // to resume the same parser then
1135        if mode.is_first() {
1136            self.1 = None;
1137        }
1138        self.parser(input).parse_mode_impl(mode, input, state)
1139    }
1140
1141    fn add_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1142        if let Some(parser) = &mut self.1 {
1143            parser.add_error(errors);
1144        }
1145    }
1146
1147    fn add_committed_expected_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1148        if let Some(parser) = &mut self.1 {
1149            parser.add_committed_expected_error(errors);
1150        }
1151    }
1152}
1153
1154/// Constructs the parser lazily on each `parse_*` call. This is similar to [`lazy`][] but it
1155/// takes `Input` as an argument and allows different parsers to be returned on each call to
1156/// `p` while still reporting the correct errors.
1157///
1158/// [`lazy`]: fn.lazy.html
1159///
1160/// ```
1161/// # use combine::*;
1162/// # use combine::parser::char::{digit, letter};
1163/// # use combine::parser::combinator::{FnOpaque, opaque, factory};
1164///
1165/// let mut parsers: Vec<FnOpaque<_, _>> = vec![opaque(|f| f(&mut digit())), opaque(|f| f(&mut letter()))];
1166/// let mut iter = parsers.into_iter().cycle();
1167/// let mut parser = many(factory(move |_| iter.next().unwrap()));
1168/// assert_eq!(parser.parse("1a2b3cd"), Ok(("1a2b3c".to_string(), "d")));
1169/// ```
1170pub fn factory<Input, P, R>(p: P) -> Factory<P, R>
1171where
1172    Input: Stream,
1173    P: FnMut(&mut Input) -> R,
1174    R: Parser<Input>,
1175{
1176    Factory(p, None)
1177}
1178
1179mod internal {
1180    pub trait Sealed {}
1181}
1182
1183use self::internal::Sealed;
1184
1185pub trait StrLike: Sealed {
1186    fn from_utf8(&self) -> Option<&str>;
1187}
1188
1189#[cfg(feature = "alloc")]
1190impl Sealed for String {}
1191#[cfg(feature = "alloc")]
1192impl StrLike for String {
1193    fn from_utf8(&self) -> Option<&str> {
1194        Some(self)
1195    }
1196}
1197
1198impl<'a> Sealed for &'a str {}
1199impl<'a> StrLike for &'a str {
1200    fn from_utf8(&self) -> Option<&str> {
1201        Some(*self)
1202    }
1203}
1204
1205impl Sealed for str {}
1206impl StrLike for str {
1207    fn from_utf8(&self) -> Option<&str> {
1208        Some(self)
1209    }
1210}
1211
1212#[cfg(feature = "alloc")]
1213impl Sealed for Vec<u8> {}
1214#[cfg(feature = "alloc")]
1215impl StrLike for Vec<u8> {
1216    fn from_utf8(&self) -> Option<&str> {
1217        (**self).from_utf8()
1218    }
1219}
1220
1221impl<'a> Sealed for &'a [u8] {}
1222impl<'a> StrLike for &'a [u8] {
1223    fn from_utf8(&self) -> Option<&str> {
1224        (**self).from_utf8()
1225    }
1226}
1227
1228impl Sealed for [u8] {}
1229impl StrLike for [u8] {
1230    fn from_utf8(&self) -> Option<&str> {
1231        str::from_utf8(self).ok()
1232    }
1233}
1234
1235parser! {
1236pub struct FromStr;
1237type PartialState = P::PartialState;
1238
1239/// Takes a parser that outputs a string like value (`&str`, `String`, `&[u8]` or `Vec<u8>`) and parses it
1240/// using `std::str::FromStr`. Errors if the output of `parser` is not UTF-8 or if
1241/// `FromStr::from_str` returns an error.
1242///
1243/// ```
1244/// # extern crate combine;
1245/// # use combine::parser::range;
1246/// # use combine::parser::repeat::many1;
1247/// # use combine::parser::combinator::from_str;
1248/// # use combine::parser::char;
1249/// # use combine::parser::byte;
1250/// # use combine::*;
1251/// # fn main() {
1252/// let mut parser = from_str(many1::<String, _, _>(char::digit()));
1253/// let result = parser.parse("12345\r\n");
1254/// assert_eq!(result, Ok((12345i32, "\r\n")));
1255///
1256/// // Range parsers work as well
1257/// let mut parser = from_str(range::take_while1(|c: char| c.is_digit(10)));
1258/// let result = parser.parse("12345\r\n");
1259/// assert_eq!(result, Ok((12345i32, "\r\n")));
1260///
1261/// // As do parsers that work with bytes
1262/// let digits = || range::take_while1(|b: u8| b >= b'0' && b <= b'9');
1263/// let mut parser = from_str(range::recognize((
1264///     digits(),
1265///     byte::byte(b'.'),
1266///     digits(),
1267/// )));
1268/// let result = parser.parse(&b"123.45\r\n"[..]);
1269/// assert_eq!(result, Ok((123.45f64, &b"\r\n"[..])));
1270/// # }
1271/// ```
1272pub fn from_str[Input, O, P](parser: P)(Input) -> O
1273where [
1274    P: Parser<Input>,
1275    P::Output: StrLike,
1276    O: str::FromStr,
1277    O::Err: fmt::Display,
1278]
1279{
1280    parser.and_then(|r| {
1281        r.from_utf8()
1282            .ok_or_else(|| StreamErrorFor::<Input>::expected_static_message("UTF-8"))
1283            .and_then(|s| s.parse().map_err(StreamErrorFor::<Input>::message_format))
1284    })
1285}
1286}
1287
1288#[derive(Copy, Clone)]
1289pub struct Opaque<F, Input, O, S>(F, PhantomData<fn(&mut Input, &mut S) -> O>);
1290impl<Input, F, O, S> Parser<Input> for Opaque<F, Input, O, S>
1291where
1292    Input: Stream,
1293    S: Default,
1294    F: FnMut(&mut dyn FnMut(&mut dyn Parser<Input, Output = O, PartialState = S>)),
1295{
1296    type Output = O;
1297    type PartialState = S;
1298
1299    fn parse_stream(&mut self, input: &mut Input) -> ParseResult<O, <Input as StreamOnce>::Error> {
1300        let mut x = None;
1301        (self.0)(&mut |parser| x = Some(parser.parse_stream(input)));
1302        x.expect("Parser")
1303    }
1304
1305    fn parse_lazy(&mut self, input: &mut Input) -> ParseResult<O, <Input as StreamOnce>::Error> {
1306        let mut x = None;
1307        (self.0)(&mut |parser| x = Some(parser.parse_lazy(input)));
1308        x.expect("Parser")
1309    }
1310
1311    parse_mode!(Input);
1312
1313    fn parse_mode_impl<M>(
1314        &mut self,
1315        mode: M,
1316        input: &mut Input,
1317        state: &mut Self::PartialState,
1318    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
1319    where
1320        M: ParseMode,
1321    {
1322        let mut x = None;
1323        (self.0)(&mut |parser| {
1324            x = Some(if mode.is_first() {
1325                parser.parse_first(input, state)
1326            } else {
1327                parser.parse_partial(input, state)
1328            })
1329        });
1330        x.expect("Parser")
1331    }
1332
1333    fn add_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1334        (self.0)(&mut |parser| parser.add_error(errors));
1335    }
1336
1337    fn add_committed_expected_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1338        (self.0)(&mut |parser| parser.add_committed_expected_error(errors));
1339    }
1340}
1341
1342/// Alias over `Opaque` where the function can be a plain function pointer (does not need to
1343/// capture any values)
1344pub type FnOpaque<Input, O, S = ()> =
1345    Opaque<fn(&mut dyn FnMut(&mut dyn Parser<Input, Output = O, PartialState = S>)), Input, O, S>;
1346
1347/// Creates a parser from a function which takes a function that are given the actual parser.
1348/// Though convoluted this makes it possible to hide the concrete parser type without `Box` or
1349/// losing the full information about the parser as is the case of [`parser`][].
1350///
1351/// Since this hides the type this can also be useful for writing mutually recursive `impl Parser`
1352/// parsers to break the otherwise arbitrarily large type that rustc creates internally.
1353///
1354/// If you need a more general version (that does not need trait objects) try the [`parser!`][]
1355/// macro.
1356///
1357/// ```
1358/// # #[macro_use]
1359/// # extern crate combine;
1360/// # use combine::parser::combinator::{FnOpaque, no_partial};
1361/// # use combine::parser::char::{char, digit};
1362/// # use combine::*;
1363///
1364/// # fn main() {
1365///
1366/// #[derive(PartialEq, Debug)]
1367/// enum Expr {
1368///     Number(i64),
1369///     Pair(Box<Expr>, Box<Expr>),
1370/// }
1371///
1372/// fn expr<Input>() -> FnOpaque<Input, Expr>
1373/// where
1374///     Input: Stream<Token = char>,
1375/// {
1376///     opaque!(
1377///         // `no_partial` disables partial parsing and replaces the partial state with `()`,
1378///         // letting us avoid naming that type
1379///         no_partial(choice((
1380///             from_str(many1::<String, _, _>(digit()))
1381///                 .map(Expr::Number),
1382///             (char('('), expr(), char(','), expr(), char(')'))
1383///                 .map(|(_, l, _, r, _)| Expr::Pair(Box::new(l), Box::new(r)))
1384///         ))),
1385///     )
1386/// }
1387///
1388/// assert_eq!(
1389///     expr().easy_parse("123"),
1390///     Ok((Expr::Number(123), ""))
1391/// );
1392///
1393/// # }
1394/// ```
1395///
1396/// [`parser`]: ../function/fn.parser.html
1397/// [`parser!`]: ../../macro.parser.html
1398pub fn opaque<Input, F, O, S>(f: F) -> Opaque<F, Input, O, S>
1399where
1400    Input: Stream,
1401    S: Default,
1402    F: FnMut(&mut dyn FnMut(&mut dyn Parser<Input, Output = O, PartialState = S>)),
1403{
1404    Opaque(f, PhantomData)
1405}
1406
1407/// Convenience macro over [`opaque`][].
1408///
1409/// [`opaque`]: parser/combinator/fn.opaque.html
1410#[macro_export]
1411macro_rules! opaque {
1412    ($e: expr) => {
1413        $crate::opaque!($e,);
1414    };
1415    ($e: expr,) => {
1416        $crate::parser::combinator::opaque(
1417            move |f: &mut dyn FnMut(&mut $crate::Parser<_, Output = _, PartialState = _>)| {
1418                f(&mut $e)
1419            },
1420        )
1421    };
1422}
1423
1424pub struct InputConverter<InputInner, P, C>
1425where
1426    InputInner: Stream,
1427{
1428    pub parser: P,
1429    pub converter: C,
1430    pub _marker: PhantomData<fn(InputInner)>,
1431}
1432impl<Input, InputInner, P, C> Parser<Input> for InputConverter<InputInner, P, C>
1433where
1434    Input: Stream,
1435    InputInner: Stream,
1436    P: Parser<InputInner>,
1437    for<'c> C: Converter<'c, Input, InputInner = InputInner>,
1438{
1439    type Output = P::Output;
1440    type PartialState = P::PartialState;
1441
1442    parse_mode!(Input);
1443
1444    fn parse_mode_impl<M>(
1445        &mut self,
1446        mode: M,
1447        input: &mut Input,
1448        state: &mut Self::PartialState,
1449    ) -> ParseResult<Self::Output, Input::Error>
1450    where
1451        M: ParseMode,
1452    {
1453        let mut input_inner = match self.converter.convert(input) {
1454            Ok(x) => x,
1455            Err(err) => return PeekErr(err.into()),
1456        };
1457        self.parser
1458            .parse_mode(mode, &mut input_inner, state)
1459            .map_err(|err| self.converter.convert_error(input, err))
1460    }
1461}
1462
1463pub trait Converter<'a, Input>
1464where
1465    Input: Stream,
1466{
1467    type InputInner: Stream + 'a;
1468    fn convert(&mut self, input: &'a mut Input) -> Result<Self::InputInner, Input::Error>;
1469    fn convert_error(
1470        &mut self,
1471        input: &'a mut Input,
1472        error: <Self::InputInner as StreamOnce>::Error,
1473    ) -> Input::Error;
1474}
1475
1476impl<'a, Input, InputInner> Converter<'a, Input>
1477    for (
1478        fn(&'a mut Input) -> Result<InputInner, Input::Error>,
1479        fn(&'a mut Input, InputInner::Error) -> Input::Error,
1480    )
1481where
1482    Input: Stream,
1483    InputInner: Stream + 'a,
1484{
1485    type InputInner = InputInner;
1486    fn convert(&mut self, input: &'a mut Input) -> Result<InputInner, Input::Error> {
1487        (self.0)(input)
1488    }
1489    fn convert_error(&mut self, input: &'a mut Input, error: InputInner::Error) -> Input::Error {
1490        (self.1)(input, error)
1491    }
1492}
1493
1494pub fn input_converter<Input, InputInner, P, C>(
1495    parser: P,
1496    converter: C,
1497) -> InputConverter<InputInner, P, C>
1498where
1499    Input: Stream,
1500    InputInner: Stream,
1501    P: Parser<InputInner>,
1502    for<'c> C: Converter<'c, Input, InputInner = InputInner>,
1503{
1504    InputConverter {
1505        parser,
1506        converter,
1507        _marker: PhantomData,
1508    }
1509}
1510
1511#[derive(Clone)]
1512pub struct Spanned<P>(P);
1513impl<Input, P, Q> Parser<Input> for Spanned<P>
1514where
1515    P: Parser<Input>,
1516    Input: Stream<Position = Span<Q>>,
1517    Q: Ord + Clone,
1518{
1519    type Output = P::Output;
1520    type PartialState = P::PartialState;
1521
1522    parse_mode!(Input);
1523    #[inline]
1524    fn parse_mode_impl<M>(
1525        &mut self,
1526        mode: M,
1527        input: &mut Input,
1528        state: &mut Self::PartialState,
1529    ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
1530    where
1531        M: ParseMode,
1532    {
1533        let start = input.position().start;
1534        self.0.parse_mode(mode, input, state).map_err(|mut err| {
1535            let error_span = err.position();
1536            // If an inner `spanned` combinator has already attached its span that will be more
1537            // specific so only set a span if the current error has a position, not a span
1538            if error_span.start == error_span.end {
1539                let end = input.position().end;
1540                err.set_position(Span { start, end });
1541            }
1542            err
1543        })
1544    }
1545
1546    forward_parser!(Input, add_error, add_committed_expected_error, 0);
1547}
1548
1549/// Equivalent to [`p.spanned()`].
1550///
1551/// [`p.spanned()`]: ../trait.Parser.html#method.spanned
1552pub fn spanned<Input, P>(p: P) -> Spanned<P>
1553where
1554    P: Parser<Input>,
1555    Input: Stream,
1556{
1557    Spanned(p)
1558}