1use 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
60pub 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#[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
143pub 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
190pub 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
247pub 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
292pub 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
343pub 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
413pub 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
531pub 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>
692where
693 Input: Stream,
694 P: Parser<Input>,
695{
696 NoPartial(p)
697}
698
699#[derive(Copy, Clone)]
700pub struct Ignore<P>(P);
701impl<Input, P> Parser<Input> for Ignore<P>
702where
703 Input: Stream,
704 P: Parser<Input>,
705{
706 type Output = ();
707 type PartialState = P::PartialState;
708
709 #[inline]
710 fn parse_lazy(
711 &mut self,
712 input: &mut Input,
713 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
714 self.0.parse_lazy(input).map(|_| ())
715 }
716
717 parse_mode!(Input);
718 #[inline]
719 fn parse_mode_impl<M>(
720 &mut self,
721 mode: M,
722 input: &mut Input,
723 state: &mut Self::PartialState,
724 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
725 where
726 M: ParseMode,
727 {
728 self.0.parse_mode(mode, input, state).map(|_| ())
729 }
730
731 forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
732}
733
734#[doc(hidden)]
735pub fn ignore<Input, P>(p: P) -> Ignore<P>
736where
737 Input: Stream,
738 P: Parser<Input>,
739{
740 Ignore(p)
741}
742
743#[cfg(feature = "alloc")]
744#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
745#[derive(Default)]
746pub struct AnyPartialState(Option<Box<dyn Any>>);
747
748#[cfg(feature = "alloc")]
749#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
750pub struct AnyPartialStateParser<P>(P);
751
752#[cfg(feature = "alloc")]
753impl<Input, P> Parser<Input> for AnyPartialStateParser<P>
754where
755 Input: Stream,
756 P: Parser<Input>,
757 P::PartialState: 'static,
758{
759 type Output = P::Output;
760 type PartialState = AnyPartialState;
761
762 #[inline]
763 fn parse_lazy(
764 &mut self,
765 input: &mut Input,
766 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
767 self.0.parse_lazy(input)
768 }
769
770 parse_mode!(Input);
771 #[inline]
772 fn parse_mode<M>(
773 &mut self,
774 mode: M,
775 input: &mut Input,
776 state: &mut Self::PartialState,
777 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
778 where
779 M: ParseMode,
780 {
781 let mut new_child_state;
782 let result = {
783 let child_state = if state.0.is_none() {
784 new_child_state = Some(Default::default());
785 new_child_state.as_mut().unwrap()
786 } else {
787 new_child_state = None;
788 state.0.as_mut().unwrap().downcast_mut().unwrap()
789 };
790
791 self.0.parse_mode(mode, input, child_state)
792 };
793
794 if let CommitErr(_) = result {
795 if state.0.is_none() {
796 state.0 = Some(Box::new(new_child_state.unwrap()));
798 }
799 }
800
801 result
802 }
803
804 forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
805}
806
807#[cfg(feature = "alloc")]
836#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
837pub fn any_partial_state<Input, P>(p: P) -> AnyPartialStateParser<P>
838where
839 Input: Stream,
840 P: Parser<Input>,
841 P::PartialState: 'static,
842{
843 AnyPartialStateParser(p)
844}
845
846#[cfg(feature = "alloc")]
847#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
848#[derive(Default)]
849pub struct AnySendPartialState(Option<Box<dyn Any + Send>>);
850
851#[cfg(feature = "alloc")]
852#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
853pub struct AnySendPartialStateParser<P>(P);
854
855#[cfg(feature = "alloc")]
856impl<Input, P> Parser<Input> for AnySendPartialStateParser<P>
857where
858 Input: Stream,
859 P: Parser<Input>,
860 P::PartialState: Send + 'static,
861{
862 type Output = P::Output;
863 type PartialState = AnySendPartialState;
864
865 #[inline]
866 fn parse_lazy(
867 &mut self,
868 input: &mut Input,
869 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
870 self.0.parse_lazy(input)
871 }
872
873 parse_mode!(Input);
874 #[inline]
875 fn parse_mode<M>(
876 &mut self,
877 mode: M,
878 input: &mut Input,
879 state: &mut Self::PartialState,
880 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
881 where
882 M: ParseMode,
883 {
884 let mut new_child_state;
885 let result = {
886 let child_state = if state.0.is_none() {
887 new_child_state = Some(Default::default());
888 new_child_state.as_mut().unwrap()
889 } else {
890 new_child_state = None;
891 state.0.as_mut().unwrap().downcast_mut().unwrap()
892 };
893
894 self.0.parse_mode(mode, input, child_state)
895 };
896
897 if let CommitErr(_) = result {
898 if state.0.is_none() {
899 state.0 = Some(Box::new(new_child_state.unwrap()));
901 }
902 }
903
904 result
905 }
906
907 forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
908}
909
910#[cfg(feature = "alloc")]
939#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
940pub fn any_send_partial_state<Input, P>(p: P) -> AnySendPartialStateParser<P>
941where
942 Input: Stream,
943 P: Parser<Input>,
944 P::PartialState: Send + 'static,
945{
946 AnySendPartialStateParser(p)
947}
948
949#[cfg(feature = "alloc")]
950#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
951#[derive(Default)]
952pub struct AnySendSyncPartialState(Option<Box<dyn Any + Send + Sync>>);
953
954#[cfg(feature = "alloc")]
955#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
956pub struct AnySendSyncPartialStateParser<P>(P);
957
958#[cfg(feature = "alloc")]
959impl<Input, P> Parser<Input> for AnySendSyncPartialStateParser<P>
960where
961 Input: Stream,
962 P: Parser<Input>,
963 P::PartialState: Send + Sync + 'static,
964{
965 type Output = P::Output;
966 type PartialState = AnySendSyncPartialState;
967
968 #[inline]
969 fn parse_lazy(
970 &mut self,
971 input: &mut Input,
972 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error> {
973 self.0.parse_lazy(input)
974 }
975
976 parse_mode!(Input);
977 #[inline]
978 fn parse_mode<M>(
979 &mut self,
980 mode: M,
981 input: &mut Input,
982 state: &mut Self::PartialState,
983 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
984 where
985 M: ParseMode,
986 {
987 let mut new_child_state;
988 let result = {
989 let child_state = if state.0.is_none() {
990 new_child_state = Some(Default::default());
991 new_child_state.as_mut().unwrap()
992 } else {
993 new_child_state = None;
994 state.0.as_mut().unwrap().downcast_mut().unwrap()
995 };
996
997 self.0.parse_mode(mode, input, child_state)
998 };
999
1000 if let CommitErr(_) = result {
1001 if state.0.is_none() {
1002 state.0 = Some(Box::new(new_child_state.unwrap()));
1004 }
1005 }
1006
1007 result
1008 }
1009
1010 forward_parser!(Input, add_error add_committed_expected_error parser_count, 0);
1011}
1012
1013#[cfg(feature = "alloc")]
1040#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
1041pub fn any_send_sync_partial_state<Input, P>(p: P) -> AnySendSyncPartialStateParser<P>
1042where
1043 Input: Stream,
1044 P: Parser<Input>,
1045 P::PartialState: Send + Sync + 'static,
1046{
1047 AnySendSyncPartialStateParser(p)
1048}
1049
1050#[derive(Copy, Clone)]
1051pub struct Lazy<P>(P);
1052impl<Input, O, P, R> Parser<Input> for Lazy<P>
1053where
1054 Input: Stream,
1055 P: FnMut() -> R,
1056 R: Parser<Input, Output = O>,
1057{
1058 type Output = O;
1059 type PartialState = R::PartialState;
1060
1061 fn parse_stream(&mut self, input: &mut Input) -> ParseResult<O, <Input as StreamOnce>::Error> {
1062 (self.0)().parse_stream(input)
1063 }
1064
1065 fn parse_lazy(&mut self, input: &mut Input) -> ParseResult<O, <Input as StreamOnce>::Error> {
1066 (self.0)().parse_lazy(input)
1067 }
1068
1069 parse_mode!(Input);
1070
1071 fn parse_committed_mode<M>(
1072 &mut self,
1073 mode: M,
1074 input: &mut Input,
1075 state: &mut Self::PartialState,
1076 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
1077 where
1078 M: ParseMode,
1079 {
1080 (self.0)().parse_mode(mode, input, state)
1081 }
1082
1083 fn parse_mode_impl<M>(
1084 &mut self,
1085 mode: M,
1086 input: &mut Input,
1087 state: &mut Self::PartialState,
1088 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
1089 where
1090 M: ParseMode,
1091 {
1092 (self.0)().parse_mode_impl(mode, input, state)
1093 }
1094
1095 fn add_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1096 (self.0)().add_error(errors);
1097 }
1098
1099 fn add_committed_expected_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1100 (self.0)().add_committed_expected_error(errors);
1101 }
1102}
1103
1104pub fn lazy<Input, P, R>(p: P) -> Lazy<P>
1113where
1114 Input: Stream,
1115 P: FnMut() -> R,
1116 R: Parser<Input>,
1117{
1118 Lazy(p)
1119}
1120
1121#[derive(Copy, Clone)]
1122pub struct Factory<P, R>(P, Option<R>);
1123
1124impl<P, R> Factory<P, R> {
1125 fn parser<Input>(&mut self, input: &mut Input) -> &mut R
1126 where
1127 P: FnMut(&mut Input) -> R,
1128 {
1129 if let Some(ref mut r) = self.1 {
1130 return r;
1131 }
1132 self.1 = Some((self.0)(input));
1133 self.1.as_mut().unwrap()
1134 }
1135}
1136
1137impl<Input, O, P, R> Parser<Input> for Factory<P, R>
1138where
1139 Input: Stream,
1140 P: FnMut(&mut Input) -> R,
1141 R: Parser<Input, Output = O>,
1142{
1143 type Output = O;
1144 type PartialState = R::PartialState;
1145
1146 parse_mode!(Input);
1147
1148 fn parse_mode_impl<M>(
1149 &mut self,
1150 mode: M,
1151 input: &mut Input,
1152 state: &mut Self::PartialState,
1153 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
1154 where
1155 M: ParseMode,
1156 {
1157 if mode.is_first() {
1160 self.1 = None;
1161 }
1162 self.parser(input).parse_mode_impl(mode, input, state)
1163 }
1164
1165 fn add_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1166 if let Some(parser) = &mut self.1 {
1167 parser.add_error(errors);
1168 }
1169 }
1170
1171 fn add_committed_expected_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1172 if let Some(parser) = &mut self.1 {
1173 parser.add_committed_expected_error(errors);
1174 }
1175 }
1176}
1177
1178pub fn factory<Input, P, R>(p: P) -> Factory<P, R>
1195where
1196 Input: Stream,
1197 P: FnMut(&mut Input) -> R,
1198 R: Parser<Input>,
1199{
1200 Factory(p, None)
1201}
1202
1203mod internal {
1204 pub trait Sealed {}
1205}
1206
1207use self::internal::Sealed;
1208
1209pub trait StrLike: Sealed {
1210 fn from_utf8(&self) -> Option<&str>;
1211}
1212
1213#[cfg(feature = "alloc")]
1214impl Sealed for String {}
1215#[cfg(feature = "alloc")]
1216impl StrLike for String {
1217 fn from_utf8(&self) -> Option<&str> {
1218 Some(self)
1219 }
1220}
1221
1222impl<'a> Sealed for &'a str {}
1223impl<'a> StrLike for &'a str {
1224 fn from_utf8(&self) -> Option<&str> {
1225 Some(*self)
1226 }
1227}
1228
1229impl Sealed for str {}
1230impl StrLike for str {
1231 fn from_utf8(&self) -> Option<&str> {
1232 Some(self)
1233 }
1234}
1235
1236#[cfg(feature = "alloc")]
1237impl Sealed for Vec<u8> {}
1238#[cfg(feature = "alloc")]
1239impl StrLike for Vec<u8> {
1240 fn from_utf8(&self) -> Option<&str> {
1241 (**self).from_utf8()
1242 }
1243}
1244
1245impl<'a> Sealed for &'a [u8] {}
1246impl<'a> StrLike for &'a [u8] {
1247 fn from_utf8(&self) -> Option<&str> {
1248 (**self).from_utf8()
1249 }
1250}
1251
1252impl Sealed for [u8] {}
1253impl StrLike for [u8] {
1254 fn from_utf8(&self) -> Option<&str> {
1255 str::from_utf8(self).ok()
1256 }
1257}
1258
1259parser! {
1260pub struct FromStr;
1261type PartialState = P::PartialState;
1262
1263pub fn from_str[Input, O, P](parser: P)(Input) -> O
1297where [
1298 P: Parser<Input>,
1299 P::Output: StrLike,
1300 O: str::FromStr,
1301 O::Err: fmt::Display,
1302]
1303{
1304 parser.and_then(|r| {
1305 r.from_utf8()
1306 .ok_or_else(|| StreamErrorFor::<Input>::expected_static_message("UTF-8"))
1307 .and_then(|s| s.parse().map_err(StreamErrorFor::<Input>::message_format))
1308 })
1309}
1310}
1311
1312#[derive(Copy, Clone)]
1313pub struct Opaque<F, Input, O, S>(F, PhantomData<fn(&mut Input, &mut S) -> O>);
1314impl<Input, F, O, S> Parser<Input> for Opaque<F, Input, O, S>
1315where
1316 Input: Stream,
1317 S: Default,
1318 F: FnMut(&mut dyn FnMut(&mut dyn Parser<Input, Output = O, PartialState = S>)),
1319{
1320 type Output = O;
1321 type PartialState = S;
1322
1323 fn parse_stream(&mut self, input: &mut Input) -> ParseResult<O, <Input as StreamOnce>::Error> {
1324 let mut x = None;
1325 (self.0)(&mut |parser| x = Some(parser.parse_stream(input)));
1326 x.expect("Parser")
1327 }
1328
1329 fn parse_lazy(&mut self, input: &mut Input) -> ParseResult<O, <Input as StreamOnce>::Error> {
1330 let mut x = None;
1331 (self.0)(&mut |parser| x = Some(parser.parse_lazy(input)));
1332 x.expect("Parser")
1333 }
1334
1335 parse_mode!(Input);
1336
1337 fn parse_mode_impl<M>(
1338 &mut self,
1339 mode: M,
1340 input: &mut Input,
1341 state: &mut Self::PartialState,
1342 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
1343 where
1344 M: ParseMode,
1345 {
1346 let mut x = None;
1347 (self.0)(&mut |parser| {
1348 x = Some(if mode.is_first() {
1349 parser.parse_first(input, state)
1350 } else {
1351 parser.parse_partial(input, state)
1352 })
1353 });
1354 x.expect("Parser")
1355 }
1356
1357 fn add_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1358 (self.0)(&mut |parser| parser.add_error(errors));
1359 }
1360
1361 fn add_committed_expected_error(&mut self, errors: &mut Tracked<<Input as StreamOnce>::Error>) {
1362 (self.0)(&mut |parser| parser.add_committed_expected_error(errors));
1363 }
1364}
1365
1366pub type FnOpaque<Input, O, S = ()> =
1369 Opaque<fn(&mut dyn FnMut(&mut dyn Parser<Input, Output = O, PartialState = S>)), Input, O, S>;
1370
1371pub fn opaque<Input, F, O, S>(f: F) -> Opaque<F, Input, O, S>
1423where
1424 Input: Stream,
1425 S: Default,
1426 F: FnMut(&mut dyn FnMut(&mut dyn Parser<Input, Output = O, PartialState = S>)),
1427{
1428 Opaque(f, PhantomData)
1429}
1430
1431#[macro_export]
1435macro_rules! opaque {
1436 ($e: expr) => {
1437 $crate::opaque!($e,)
1438 };
1439 ($e: expr,) => {
1440 $crate::parser::combinator::opaque(
1441 move |f: &mut dyn FnMut(&mut $crate::Parser<_, Output = _, PartialState = _>)| {
1442 f(&mut $e)
1443 },
1444 )
1445 };
1446}
1447
1448pub struct InputConverter<InputInner, P, C>
1449where
1450 InputInner: Stream,
1451{
1452 pub parser: P,
1453 pub converter: C,
1454 pub _marker: PhantomData<fn(InputInner)>,
1455}
1456impl<Input, InputInner, P, C> Parser<Input> for InputConverter<InputInner, P, C>
1457where
1458 Input: Stream,
1459 InputInner: Stream,
1460 P: Parser<InputInner>,
1461 for<'c> C: Converter<'c, Input, InputInner = InputInner>,
1462{
1463 type Output = P::Output;
1464 type PartialState = P::PartialState;
1465
1466 parse_mode!(Input);
1467
1468 fn parse_mode_impl<M>(
1469 &mut self,
1470 mode: M,
1471 input: &mut Input,
1472 state: &mut Self::PartialState,
1473 ) -> ParseResult<Self::Output, Input::Error>
1474 where
1475 M: ParseMode,
1476 {
1477 let mut input_inner = match self.converter.convert(input) {
1478 Ok(x) => x,
1479 Err(err) => return PeekErr(err.into()),
1480 };
1481 self.parser
1482 .parse_mode(mode, &mut input_inner, state)
1483 .map_err(|err| self.converter.convert_error(input, err))
1484 }
1485}
1486
1487pub trait Converter<'a, Input>
1488where
1489 Input: Stream,
1490{
1491 type InputInner: Stream + 'a;
1492 fn convert(&mut self, input: &'a mut Input) -> Result<Self::InputInner, Input::Error>;
1493 fn convert_error(
1494 &mut self,
1495 input: &'a mut Input,
1496 error: <Self::InputInner as StreamOnce>::Error,
1497 ) -> Input::Error;
1498}
1499
1500impl<'a, Input, InputInner> Converter<'a, Input>
1501 for (
1502 fn(&'a mut Input) -> Result<InputInner, Input::Error>,
1503 fn(&'a mut Input, InputInner::Error) -> Input::Error,
1504 )
1505where
1506 Input: Stream,
1507 InputInner: Stream + 'a,
1508{
1509 type InputInner = InputInner;
1510 fn convert(&mut self, input: &'a mut Input) -> Result<InputInner, Input::Error> {
1511 (self.0)(input)
1512 }
1513 fn convert_error(&mut self, input: &'a mut Input, error: InputInner::Error) -> Input::Error {
1514 (self.1)(input, error)
1515 }
1516}
1517
1518pub fn input_converter<Input, InputInner, P, C>(
1519 parser: P,
1520 converter: C,
1521) -> InputConverter<InputInner, P, C>
1522where
1523 Input: Stream,
1524 InputInner: Stream,
1525 P: Parser<InputInner>,
1526 for<'c> C: Converter<'c, Input, InputInner = InputInner>,
1527{
1528 InputConverter {
1529 parser,
1530 converter,
1531 _marker: PhantomData,
1532 }
1533}
1534
1535#[derive(Clone)]
1536pub struct Spanned<P>(P);
1537impl<Input, P, Q> Parser<Input> for Spanned<P>
1538where
1539 P: Parser<Input>,
1540 Input: Stream<Position = Span<Q>>,
1541 Q: Ord + Clone,
1542{
1543 type Output = P::Output;
1544 type PartialState = P::PartialState;
1545
1546 parse_mode!(Input);
1547 #[inline]
1548 fn parse_mode_impl<M>(
1549 &mut self,
1550 mode: M,
1551 input: &mut Input,
1552 state: &mut Self::PartialState,
1553 ) -> ParseResult<Self::Output, <Input as StreamOnce>::Error>
1554 where
1555 M: ParseMode,
1556 {
1557 let start = input.position().start;
1558 self.0.parse_mode(mode, input, state).map_err(|mut err| {
1559 let error_span = err.position();
1560 if error_span.start == error_span.end {
1563 let end = input.position().end;
1564 err.set_position(Span { start, end });
1565 }
1566 err
1567 })
1568 }
1569
1570 forward_parser!(Input, add_error, add_committed_expected_error, 0);
1571}
1572
1573pub fn spanned<Input, P>(p: P) -> Spanned<P>
1577where
1578 P: Parser<Input>,
1579 Input: Stream,
1580{
1581 Spanned(p)
1582}