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