1 //! general purpose combinators
2
3 #![allow(unused_imports)]
4
5 #[cfg(feature = "alloc")]
6 use crate::lib::std::boxed::Box;
7
8 #[cfg(feature = "std")]
9 use crate::lib::std::fmt::Debug;
10 use crate::internal::*;
11 use crate::error::ParseError;
12 use crate::traits::{AsChar, InputIter, InputLength, InputTakeAtPosition, ParseTo};
13 use crate::lib::std::ops::{Range, RangeFrom, RangeTo};
14 use crate::lib::std::borrow::Borrow;
15 use crate::traits::{Compare, CompareResult, Offset, Slice};
16 use crate::error::ErrorKind;
17 use crate::lib::std::mem::transmute;
18
19 #[macro_use]
20 mod macros;
21
22 /// Return the remaining input
23 ///
24 /// ```rust
25 /// # use nom::error::ErrorKind;
26 /// use nom::combinator::rest;
27 /// assert_eq!(rest::<_,(_, ErrorKind)>("abc"), Ok(("", "abc")));
28 /// assert_eq!(rest::<_,(_, ErrorKind)>(""), Ok(("", "")));
29 /// ```
30 #[inline]
rest<T, E: ParseError<T>>(input: T) -> IResult<T, T, E> where T: Slice<Range<usize>> + Slice<RangeFrom<usize>> + Slice<RangeTo<usize>>, T: InputLength,31 pub fn rest<T, E: ParseError<T>>(input: T) -> IResult<T, T, E>
32 where
33 T: Slice<Range<usize>> + Slice<RangeFrom<usize>> + Slice<RangeTo<usize>>,
34 T: InputLength,
35 {
36 Ok((input.slice(input.input_len()..), input))
37 }
38
39 /// Return the length of the remaining input
40 ///
41 /// ```rust
42 /// # use nom::error::ErrorKind;
43 /// use nom::combinator::rest_len;
44 /// assert_eq!(rest_len::<_,(_, ErrorKind)>("abc"), Ok(("abc", 3)));
45 /// assert_eq!(rest_len::<_,(_, ErrorKind)>(""), Ok(("", 0)));
46 /// ```
47 #[inline]
rest_len<T, E: ParseError<T>>(input: T) -> IResult<T, usize, E> where T: Slice<Range<usize>> + Slice<RangeFrom<usize>> + Slice<RangeTo<usize>>, T: InputLength,48 pub fn rest_len<T, E: ParseError<T>>(input: T) -> IResult<T, usize, E>
49 where
50 T: Slice<Range<usize>> + Slice<RangeFrom<usize>> + Slice<RangeTo<usize>>,
51 T: InputLength,
52 {
53 let len = input.input_len();
54 Ok((input, len))
55 }
56
57 /// maps a function on the result of a parser
58 ///
59 /// ```rust
60 /// # #[macro_use] extern crate nom;
61 /// # use nom::{Err,error::ErrorKind, IResult};
62 /// use nom::character::complete::digit1;
63 /// use nom::combinator::map;
64 /// # fn main() {
65 ///
66 /// let parse = map(digit1, |s: &str| s.len());
67 ///
68 /// // the parser will count how many characters were returned by digit1
69 /// assert_eq!(parse("123456"), Ok(("", 6)));
70 ///
71 /// // this will fail if digit1 fails
72 /// assert_eq!(parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
73 /// # }
74 /// ```
map<I, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(O1) -> O2,75 pub fn map<I, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E>
76 where
77 F: Fn(I) -> IResult<I, O1, E>,
78 G: Fn(O1) -> O2,
79 {
80 move |input: I| {
81 let (input, o1) = first(input)?;
82 Ok((input, second(o1)))
83 }
84 }
85
86 #[doc(hidden)]
mapc<I, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(O1) -> O2,87 pub fn mapc<I, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O2, E>
88 where
89 F: Fn(I) -> IResult<I, O1, E>,
90 G: Fn(O1) -> O2,
91 {
92 map(first, second)(input)
93 }
94
95 /// applies a function returning a Result over the result of a parser
96 ///
97 /// ```rust
98 /// # #[macro_use] extern crate nom;
99 /// # use nom::{Err,error::ErrorKind, IResult};
100 /// use nom::character::complete::digit1;
101 /// use nom::combinator::map_res;
102 /// # fn main() {
103 ///
104 /// let parse = map_res(digit1, |s: &str| s.parse::<u8>());
105 ///
106 /// // the parser will convert the result of digit1 to a number
107 /// assert_eq!(parse("123"), Ok(("", 123)));
108 ///
109 /// // this will fail if digit1 fails
110 /// assert_eq!(parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
111 ///
112 /// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
113 /// assert_eq!(parse("123456"), Err(Err::Error(("123456", ErrorKind::MapRes))));
114 /// # }
115 /// ```
map_res<I: Clone, O1, O2, E: ParseError<I>, E2, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(O1) -> Result<O2, E2>,116 pub fn map_res<I: Clone, O1, O2, E: ParseError<I>, E2, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E>
117 where
118 F: Fn(I) -> IResult<I, O1, E>,
119 G: Fn(O1) -> Result<O2, E2>,
120 {
121 move |input: I| {
122 let i = input.clone();
123 let (input, o1) = first(input)?;
124 match second(o1) {
125 Ok(o2) => Ok((input, o2)),
126 Err(_) => Err(Err::Error(E::from_error_kind(i, ErrorKind::MapRes))),
127 }
128 }
129 }
130
131 #[doc(hidden)]
map_resc<I: Clone, O1, O2, E: ParseError<I>, E2, F, G>(input: I, first: F, second: G) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(O1) -> Result<O2, E2>,132 pub fn map_resc<I: Clone, O1, O2, E: ParseError<I>, E2, F, G>(input: I, first: F, second: G) -> IResult<I, O2, E>
133 where
134 F: Fn(I) -> IResult<I, O1, E>,
135 G: Fn(O1) -> Result<O2, E2>,
136 {
137 map_res(first, second)(input)
138 }
139
140 /// applies a function returning an Option over the result of a parser
141 ///
142 /// ```rust
143 /// # #[macro_use] extern crate nom;
144 /// # use nom::{Err,error::ErrorKind, IResult};
145 /// use nom::character::complete::digit1;
146 /// use nom::combinator::map_opt;
147 /// # fn main() {
148 ///
149 /// let parse = map_opt(digit1, |s: &str| s.parse::<u8>().ok());
150 ///
151 /// // the parser will convert the result of digit1 to a number
152 /// assert_eq!(parse("123"), Ok(("", 123)));
153 ///
154 /// // this will fail if digit1 fails
155 /// assert_eq!(parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
156 ///
157 /// // this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
158 /// assert_eq!(parse("123456"), Err(Err::Error(("123456", ErrorKind::MapOpt))));
159 /// # }
160 /// ```
map_opt<I: Clone, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(O1) -> Option<O2>,161 pub fn map_opt<I: Clone, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E>
162 where
163 F: Fn(I) -> IResult<I, O1, E>,
164 G: Fn(O1) -> Option<O2>,
165 {
166 move |input: I| {
167 let i = input.clone();
168 let (input, o1) = first(input)?;
169 match second(o1) {
170 Some(o2) => Ok((input, o2)),
171 None => Err(Err::Error(E::from_error_kind(i, ErrorKind::MapOpt))),
172 }
173 }
174 }
175
176 #[doc(hidden)]
map_optc<I: Clone, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(O1) -> Option<O2>,177 pub fn map_optc<I: Clone, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O2, E>
178 where
179 F: Fn(I) -> IResult<I, O1, E>,
180 G: Fn(O1) -> Option<O2>,
181 {
182 map_opt(first, second)(input)
183 }
184
185 /// applies a parser over the result of another one
186 ///
187 /// ```rust
188 /// # #[macro_use] extern crate nom;
189 /// # use nom::{Err,error::ErrorKind, IResult};
190 /// use nom::character::complete::digit1;
191 /// use nom::bytes::complete::take;
192 /// use nom::combinator::map_parser;
193 /// # fn main() {
194 ///
195 /// let parse = map_parser(take(5u8), digit1);
196 ///
197 /// assert_eq!(parse("12345"), Ok(("", "12345")));
198 /// assert_eq!(parse("123ab"), Ok(("", "123")));
199 /// assert_eq!(parse("123"), Err(Err::Error(("123", ErrorKind::Eof))));
200 /// # }
201 /// ```
map_parser<I: Clone, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(O1) -> IResult<O1, O2, E>, O1: InputLength,202 pub fn map_parser<I: Clone, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E>
203 where
204 F: Fn(I) -> IResult<I, O1, E>,
205 G: Fn(O1) -> IResult<O1, O2, E>,
206 O1: InputLength,
207 {
208 move |input: I| {
209 let (input, o1) = first(input)?;
210 let (_, o2) = second(o1)?;
211 Ok((input, o2))
212 }
213 }
214
215 #[doc(hidden)]
map_parserc<I: Clone, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(O1) -> IResult<O1, O2, E>, O1: InputLength,216 pub fn map_parserc<I: Clone, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O2, E>
217 where
218 F: Fn(I) -> IResult<I, O1, E>,
219 G: Fn(O1) -> IResult<O1, O2, E>,
220 O1: InputLength,
221 {
222 map_parser(first, second)(input)
223 }
224
225 /// creates a new parser from the output of the first parser, then apply that parser over the rest of the input
226 ///
227 /// ```rust
228 /// # #[macro_use] extern crate nom;
229 /// # use nom::{Err,error::ErrorKind, IResult};
230 /// use nom::bytes::complete::take;
231 /// use nom::number::complete::be_u8;
232 /// use nom::combinator::flat_map;
233 /// # fn main() {
234 ///
235 /// let parse = flat_map(be_u8, take);
236 ///
237 /// assert_eq!(parse(&[2, 0, 1, 2][..]), Ok((&[2][..], &[0, 1][..])));
238 /// assert_eq!(parse(&[4, 0, 1, 2][..]), Err(Err::Error((&[0, 1, 2][..], ErrorKind::Eof))));
239 /// # }
240 /// ```
flat_map<I, O1, O2, E: ParseError<I>, F, G, H>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(O1) -> H, H: Fn(I) -> IResult<I, O2, E>241 pub fn flat_map<I, O1, O2, E: ParseError<I>, F, G, H>(first: F, second: G) -> impl Fn(I) -> IResult<I, O2, E>
242 where
243 F: Fn(I) -> IResult<I, O1, E>,
244 G: Fn(O1) -> H,
245 H: Fn(I) -> IResult<I, O2, E>
246 {
247 move |input: I| {
248 let (input, o1) = first(input)?;
249 second(o1)(input)
250 }
251 }
252
253 /// optional parser: will return None if not successful
254 ///
255 /// ```rust
256 /// # #[macro_use] extern crate nom;
257 /// # use nom::{Err,error::ErrorKind, IResult};
258 /// use nom::combinator::opt;
259 /// use nom::character::complete::alpha1;
260 /// # fn main() {
261 ///
262 /// fn parser(i: &str) -> IResult<&str, Option<&str>> {
263 /// opt(alpha1)(i)
264 /// }
265 ///
266 /// assert_eq!(parser("abcd;"), Ok((";", Some("abcd"))));
267 /// assert_eq!(parser("123;"), Ok(("123;", None)));
268 /// # }
269 /// ```
opt<I:Clone, O, E: ParseError<I>, F>(f: F) -> impl Fn(I) -> IResult<I, Option<O>, E> where F: Fn(I) -> IResult<I, O, E>,270 pub fn opt<I:Clone, O, E: ParseError<I>, F>(f: F) -> impl Fn(I) -> IResult<I, Option<O>, E>
271 where
272 F: Fn(I) -> IResult<I, O, E>,
273 {
274 move |input: I| {
275 let i = input.clone();
276 match f(input) {
277 Ok((i, o)) => Ok((i, Some(o))),
278 Err(Err::Error(_)) => Ok((i, None)),
279 Err(e) => Err(e),
280 }
281 }
282 }
283
284 #[doc(hidden)]
optc<I:Clone, O, E: ParseError<I>, F>(input: I, f: F) -> IResult<I, Option<O>, E> where F: Fn(I) -> IResult<I, O, E>,285 pub fn optc<I:Clone, O, E: ParseError<I>, F>(input: I, f: F) -> IResult<I, Option<O>, E>
286 where
287 F: Fn(I) -> IResult<I, O, E>,
288 {
289 opt(f)(input)
290 }
291
292 /// calls the parser if the condition is met
293 ///
294 /// ```rust
295 /// # #[macro_use] extern crate nom;
296 /// # use nom::{Err,error::ErrorKind, IResult};
297 /// use nom::combinator::cond;
298 /// use nom::character::complete::alpha1;
299 /// # fn main() {
300 ///
301 /// fn parser(b: bool, i: &str) -> IResult<&str, Option<&str>> {
302 /// cond(b, alpha1)(i)
303 /// }
304 ///
305 /// assert_eq!(parser(true, "abcd;"), Ok((";", Some("abcd"))));
306 /// assert_eq!(parser(false, "abcd;"), Ok(("abcd;", None)));
307 /// assert_eq!(parser(true, "123;"), Err(Err::Error(("123;", ErrorKind::Alpha))));
308 /// assert_eq!(parser(false, "123;"), Ok(("123;", None)));
309 /// # }
310 /// ```
cond<I:Clone, O, E: ParseError<I>, F>(b: bool, f: F) -> impl Fn(I) -> IResult<I, Option<O>, E> where F: Fn(I) -> IResult<I, O, E>,311 pub fn cond<I:Clone, O, E: ParseError<I>, F>(b: bool, f: F) -> impl Fn(I) -> IResult<I, Option<O>, E>
312 where
313 F: Fn(I) -> IResult<I, O, E>,
314 {
315 move |input: I| {
316 if b {
317 match f(input) {
318 Ok((i, o)) => Ok((i, Some(o))),
319 Err(e) => Err(e),
320 }
321 } else {
322 Ok((input, None))
323 }
324 }
325 }
326
327 #[doc(hidden)]
condc<I:Clone, O, E: ParseError<I>, F>(input: I, b: bool, f: F) -> IResult<I, Option<O>, E> where F: Fn(I) -> IResult<I, O, E>,328 pub fn condc<I:Clone, O, E: ParseError<I>, F>(input: I, b: bool, f: F) -> IResult<I, Option<O>, E>
329 where
330 F: Fn(I) -> IResult<I, O, E>,
331 {
332 cond(b, f)(input)
333 }
334
335 /// tries to apply its parser without consuming the input
336 ///
337 /// ```rust
338 /// # #[macro_use] extern crate nom;
339 /// # use nom::{Err,error::ErrorKind, IResult};
340 /// use nom::combinator::peek;
341 /// use nom::character::complete::alpha1;
342 /// # fn main() {
343 ///
344 /// let parser = peek(alpha1);
345 ///
346 /// assert_eq!(parser("abcd;"), Ok(("abcd;", "abcd")));
347 /// assert_eq!(parser("123;"), Err(Err::Error(("123;", ErrorKind::Alpha))));
348 /// # }
349 /// ```
peek<I:Clone, O, E: ParseError<I>, F>(f: F) -> impl Fn(I) -> IResult<I, O, E> where F: Fn(I) -> IResult<I, O, E>,350 pub fn peek<I:Clone, O, E: ParseError<I>, F>(f: F) -> impl Fn(I) -> IResult<I, O, E>
351 where
352 F: Fn(I) -> IResult<I, O, E>,
353 {
354 move |input: I| {
355 let i = input.clone();
356 match f(input) {
357 Ok((_, o)) => Ok((i, o)),
358 Err(e) => Err(e),
359 }
360 }
361 }
362
363 #[doc(hidden)]
peekc<I:Clone, O, E: ParseError<I>, F>(input: I, f: F) -> IResult<I, O, E> where F: Fn(I) -> IResult<I, O, E>,364 pub fn peekc<I:Clone, O, E: ParseError<I>, F>(input: I, f: F) -> IResult<I, O, E>
365 where
366 F: Fn(I) -> IResult<I, O, E>,
367 {
368 peek(f)(input)
369 }
370
371 /// transforms Incomplete into Error
372 ///
373 /// ```rust
374 /// # #[macro_use] extern crate nom;
375 /// # use nom::{Err,error::ErrorKind, IResult};
376 /// use nom::bytes::streaming::take;
377 /// use nom::combinator::complete;
378 /// # fn main() {
379 ///
380 /// let parser = complete(take(5u8));
381 ///
382 /// assert_eq!(parser("abcdefg"), Ok(("fg", "abcde")));
383 /// assert_eq!(parser("abcd"), Err(Err::Error(("abcd", ErrorKind::Complete))));
384 /// # }
385 /// ```
complete<I: Clone, O, E: ParseError<I>, F>(f: F) -> impl Fn(I) -> IResult<I, O, E> where F: Fn(I) -> IResult<I, O, E>,386 pub fn complete<I: Clone, O, E: ParseError<I>, F>(f: F) -> impl Fn(I) -> IResult<I, O, E>
387 where
388 F: Fn(I) -> IResult<I, O, E>,
389 {
390 move |input: I| {
391 let i = input.clone();
392 match f(input) {
393 Err(Err::Incomplete(_)) => {
394 Err(Err::Error(E::from_error_kind(i, ErrorKind::Complete)))
395 },
396 rest => rest
397 }
398 }
399 }
400
401 #[doc(hidden)]
completec<I: Clone, O, E: ParseError<I>, F>(input: I, f: F) -> IResult<I, O, E> where F: Fn(I) -> IResult<I, O, E>,402 pub fn completec<I: Clone, O, E: ParseError<I>, F>(input: I, f: F) -> IResult<I, O, E>
403 where
404 F: Fn(I) -> IResult<I, O, E>,
405 {
406 complete(f)(input)
407 }
408
409 /// succeeds if all the input has been consumed by its child parser
410 ///
411 /// ```rust
412 /// # #[macro_use] extern crate nom;
413 /// # use nom::{Err,error::ErrorKind, IResult};
414 /// use nom::combinator::all_consuming;
415 /// use nom::character::complete::alpha1;
416 /// # fn main() {
417 ///
418 /// let parser = all_consuming(alpha1);
419 ///
420 /// assert_eq!(parser("abcd"), Ok(("", "abcd")));
421 /// assert_eq!(parser("abcd;"),Err(Err::Error((";", ErrorKind::Eof))));
422 /// assert_eq!(parser("123abcd;"),Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
423 /// # }
424 /// ```
all_consuming<I, O, E: ParseError<I>, F>(f: F) -> impl Fn(I) -> IResult<I, O, E> where I: InputLength, F: Fn(I) -> IResult<I, O, E>,425 pub fn all_consuming<I, O, E: ParseError<I>, F>(f: F) -> impl Fn(I) -> IResult<I, O, E>
426 where
427 I: InputLength,
428 F: Fn(I) -> IResult<I, O, E>,
429 {
430 move |input: I| {
431 let (input, res) = f(input)?;
432 if input.input_len() == 0 {
433 Ok((input, res))
434 } else {
435 Err(Err::Error(E::from_error_kind(input, ErrorKind::Eof)))
436 }
437 }
438 }
439
440 /// returns the result of the child parser if it satisfies a verification function
441 ///
442 /// the verification function takes as argument a reference to the output of the
443 /// parser
444 ///
445 /// ```rust
446 /// # #[macro_use] extern crate nom;
447 /// # use nom::{Err,error::ErrorKind, IResult};
448 /// use nom::combinator::verify;
449 /// use nom::character::complete::alpha1;
450 /// # fn main() {
451 ///
452 /// let parser = verify(alpha1, |s: &str| s.len() == 4);
453 ///
454 /// assert_eq!(parser("abcd"), Ok(("", "abcd")));
455 /// assert_eq!(parser("abcde"), Err(Err::Error(("abcde", ErrorKind::Verify))));
456 /// assert_eq!(parser("123abcd;"),Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
457 /// # }
458 /// ```
verify<I: Clone, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O1, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(&O2) -> bool, O1: Borrow<O2>, O2: ?Sized,459 pub fn verify<I: Clone, O1, O2, E: ParseError<I>, F, G>(first: F, second: G) -> impl Fn(I) -> IResult<I, O1, E>
460 where
461 F: Fn(I) -> IResult<I, O1, E>,
462 G: Fn(&O2) -> bool,
463 O1: Borrow<O2>,
464 O2: ?Sized,
465 {
466 move |input: I| {
467 let i = input.clone();
468 let (input, o) = first(input)?;
469
470 if second(o.borrow()) {
471 Ok((input, o))
472 } else {
473 Err(Err::Error(E::from_error_kind(i, ErrorKind::Verify)))
474 }
475 }
476 }
477
478 #[doc(hidden)]
verifyc<I: Clone, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O1, E> where F: Fn(I) -> IResult<I, O1, E>, G: Fn(&O2) -> bool, O1: Borrow<O2>, O2: ?Sized,479 pub fn verifyc<I: Clone, O1, O2, E: ParseError<I>, F, G>(input: I, first: F, second: G) -> IResult<I, O1, E>
480 where
481 F: Fn(I) -> IResult<I, O1, E>,
482 G: Fn(&O2) -> bool,
483 O1: Borrow<O2>,
484 O2: ?Sized,
485 {
486 verify(first, second)(input)
487 }
488
489 /// returns the provided value if the child parser succeeds
490 ///
491 /// ```rust
492 /// # #[macro_use] extern crate nom;
493 /// # use nom::{Err,error::ErrorKind, IResult};
494 /// use nom::combinator::value;
495 /// use nom::character::complete::alpha1;
496 /// # fn main() {
497 ///
498 /// let parser = value(1234, alpha1);
499 ///
500 /// assert_eq!(parser("abcd"), Ok(("", 1234)));
501 /// assert_eq!(parser("123abcd;"), Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
502 /// # }
503 /// ```
value<I, O1: Clone, O2, E: ParseError<I>, F>(val: O1, parser: F) -> impl Fn(I) -> IResult<I, O1, E> where F: Fn(I) -> IResult<I, O2, E>,504 pub fn value<I, O1: Clone, O2, E: ParseError<I>, F>(val: O1, parser: F) -> impl Fn(I) -> IResult<I, O1, E>
505 where
506 F: Fn(I) -> IResult<I, O2, E>,
507 {
508 move |input: I| {
509 parser(input).map(|(i, _)| (i, val.clone()))
510 }
511 }
512
513 #[doc(hidden)]
valuec<I, O1: Clone, O2, E: ParseError<I>, F>(input: I, val: O1, parser: F) -> IResult<I, O1, E> where F: Fn(I) -> IResult<I, O2, E>,514 pub fn valuec<I, O1: Clone, O2, E: ParseError<I>, F>(input: I, val: O1, parser: F) -> IResult<I, O1, E>
515 where
516 F: Fn(I) -> IResult<I, O2, E>,
517 {
518 value(val, parser)(input)
519 }
520
521 /// succeeds if the child parser returns an error
522 ///
523 /// ```rust
524 /// # #[macro_use] extern crate nom;
525 /// # use nom::{Err,error::ErrorKind, IResult};
526 /// use nom::combinator::not;
527 /// use nom::character::complete::alpha1;
528 /// # fn main() {
529 ///
530 /// let parser = not(alpha1);
531 ///
532 /// assert_eq!(parser("123"), Ok(("123", ())));
533 /// assert_eq!(parser("abcd"), Err(Err::Error(("abcd", ErrorKind::Not))));
534 /// # }
535 /// ```
not<I: Clone, O, E: ParseError<I>, F>(parser: F) -> impl Fn(I) -> IResult<I, (), E> where F: Fn(I) -> IResult<I, O, E>,536 pub fn not<I: Clone, O, E: ParseError<I>, F>(parser: F) -> impl Fn(I) -> IResult<I, (), E>
537 where
538 F: Fn(I) -> IResult<I, O, E>,
539 {
540 move |input: I| {
541 let i = input.clone();
542 match parser(input) {
543 Ok(_) => Err(Err::Error(E::from_error_kind(i, ErrorKind::Not))),
544 Err(Err::Error(_)) => Ok((i, ())),
545 Err(e) => Err(e),
546 }
547 }
548 }
549
550 #[doc(hidden)]
notc<I: Clone, O, E: ParseError<I>, F>(input: I, parser: F) -> IResult<I, (), E> where F: Fn(I) -> IResult<I, O, E>,551 pub fn notc<I: Clone, O, E: ParseError<I>, F>(input: I, parser: F) -> IResult<I, (), E>
552 where
553 F: Fn(I) -> IResult<I, O, E>,
554 {
555 not(parser)(input)
556 }
557
558 /// if the child parser was successful, return the consumed input as produced value
559 ///
560 /// ```rust
561 /// # #[macro_use] extern crate nom;
562 /// # use nom::{Err,error::ErrorKind, IResult};
563 /// use nom::combinator::recognize;
564 /// use nom::character::complete::{char, alpha1};
565 /// use nom::sequence::separated_pair;
566 /// # fn main() {
567 ///
568 /// let parser = recognize(separated_pair(alpha1, char(','), alpha1));
569 ///
570 /// assert_eq!(parser("abcd,efgh"), Ok(("", "abcd,efgh")));
571 /// assert_eq!(parser("abcd;"),Err(Err::Error((";", ErrorKind::Char))));
572 /// # }
573 /// ```
recognize<I: Clone + Offset + Slice<RangeTo<usize>>, O, E: ParseError<I>, F>(parser: F) -> impl Fn(I) -> IResult<I, I, E> where F: Fn(I) -> IResult<I, O, E>,574 pub fn recognize<I: Clone + Offset + Slice<RangeTo<usize>>, O, E: ParseError<I>, F>(parser: F) -> impl Fn(I) -> IResult<I, I, E>
575 where
576 F: Fn(I) -> IResult<I, O, E>,
577 {
578 move |input: I| {
579 let i = input.clone();
580 match parser(i) {
581 Ok((i, _)) => {
582 let index = input.offset(&i);
583 Ok((i, input.slice(..index)))
584 },
585 Err(e) => Err(e),
586 }
587 }
588 }
589
590 #[doc(hidden)]
recognizec<I: Clone + Offset + Slice<RangeTo<usize>>, O, E: ParseError<I>, F>(input: I, parser: F) -> IResult<I, I, E> where F: Fn(I) -> IResult<I, O, E>,591 pub fn recognizec<I: Clone + Offset + Slice<RangeTo<usize>>, O, E: ParseError<I>, F>(input: I, parser: F) -> IResult<I, I, E>
592 where
593 F: Fn(I) -> IResult<I, O, E>,
594 {
595 recognize(parser)(input)
596 }
597
598 /// transforms an error to failure
599 ///
600 /// ```rust
601 /// # #[macro_use] extern crate nom;
602 /// # use nom::{Err,error::ErrorKind, IResult};
603 /// use nom::combinator::cut;
604 /// use nom::character::complete::alpha1;
605 /// # fn main() {
606 ///
607 /// let parser = cut(alpha1);
608 ///
609 /// assert_eq!(parser("abcd;"), Ok((";", "abcd")));
610 /// assert_eq!(parser("123;"), Err(Err::Failure(("123;", ErrorKind::Alpha))));
611 /// # }
612 /// ```
cut<I: Clone + Slice<RangeTo<usize>>, O, E: ParseError<I>, F>(parser: F) -> impl Fn(I) -> IResult<I, O, E> where F: Fn(I) -> IResult<I, O, E>,613 pub fn cut<I: Clone + Slice<RangeTo<usize>>, O, E: ParseError<I>, F>(parser: F) -> impl Fn(I) -> IResult<I, O, E>
614 where
615 F: Fn(I) -> IResult<I, O, E>,
616 {
617 move |input: I| {
618 let i = input.clone();
619 match parser(i) {
620 Err(Err::Error(e)) => Err(Err::Failure(e)),
621 rest => rest,
622 }
623 }
624 }
625
626 #[doc(hidden)]
cutc<I: Clone + Slice<RangeTo<usize>>, O, E: ParseError<I>, F>(input: I, parser: F) -> IResult<I, O, E> where F: Fn(I) -> IResult<I, O, E>,627 pub fn cutc<I: Clone + Slice<RangeTo<usize>>, O, E: ParseError<I>, F>(input: I, parser: F) -> IResult<I, O, E>
628 where
629 F: Fn(I) -> IResult<I, O, E>,
630 {
631 cut(parser)(input)
632 }
633
634 /// creates an iterator from input data and a parser
635 ///
636 /// call the iterator's [finish] method to get the remaining input if successful,
637 /// or the error value if we encountered an error
638 ///
639 /// ```rust
640 /// use nom::{combinator::iterator, IResult, bytes::complete::tag, character::complete::alpha1, sequence::terminated};
641 /// use std::collections::HashMap;
642 ///
643 /// let data = "abc|defg|hijkl|mnopqr|123";
644 /// let mut it = iterator(data, terminated(alpha1, tag("|")));
645 ///
646 /// let parsed = it.map(|v| (v, v.len())).collect::<HashMap<_,_>>();
647 /// let res: IResult<_,_> = it.finish();
648 ///
649 /// assert_eq!(parsed, [("abc", 3usize), ("defg", 4), ("hijkl", 5), ("mnopqr", 6)].iter().cloned().collect());
650 /// assert_eq!(res, Ok(("123", ())));
651 /// ```
iterator<Input, Output, Error, F>(input: Input, f: F) -> ParserIterator<Input, Error, F> where F: Fn(Input) -> IResult<Input, Output, Error>, Error: ParseError<Input>652 pub fn iterator<Input, Output, Error, F>(input: Input, f: F) -> ParserIterator<Input, Error, F>
653 where
654 F: Fn(Input) -> IResult<Input, Output, Error>,
655 Error: ParseError<Input> {
656
657 ParserIterator {
658 iterator: f,
659 input,
660 state: State::Running,
661 }
662 }
663
664 /// main structure associated to the [iterator] function
665 pub struct ParserIterator<I, E, F> {
666 iterator: F,
667 input: I,
668 state: State<E>,
669 }
670
671 impl<I: Clone, E: Clone, F> ParserIterator<I, E, F> {
672 /// returns the remaining input if parsing was successful, or the error if we encountered an error
finish(self) -> IResult<I, (), E>673 pub fn finish(self) -> IResult<I, (), E> {
674 match &self.state {
675 State::Running | State::Done => Ok((self.input.clone(), ())),
676 State::Failure(e) => Err(Err::Failure(e.clone())),
677 State::Incomplete(i) => Err(Err::Incomplete(i.clone())),
678 }
679 }
680 }
681
682 impl<'a, Input ,Output ,Error, F> core::iter::Iterator for &'a mut ParserIterator<Input, Error, F>
683 where
684 F: Fn(Input) -> IResult<Input, Output, Error>,
685 Input: Clone
686 {
687 type Item = Output;
688
next(&mut self) -> Option<Self::Item>689 fn next(&mut self) -> Option<Self::Item> {
690 if let State::Running = self.state {
691 let input = self.input.clone();
692
693 match (self.iterator)(input) {
694 Ok((i, o)) => {
695 self.input = i;
696 Some(o)
697 },
698 Err(Err::Error(_)) => {
699 self.state = State::Done;
700 None
701 },
702 Err(Err::Failure(e)) => {
703 self.state = State::Failure(e);
704 None
705 },
706 Err(Err::Incomplete(i)) => {
707 self.state = State::Incomplete(i);
708 None
709 },
710 }
711 } else {
712 None
713 }
714 }
715 }
716
717 enum State<E> {
718 Running,
719 Done,
720 Failure(E),
721 Incomplete(Needed),
722 }
723
724
725 #[cfg(test)]
726 mod tests {
727 use super::*;
728 use crate::internal::{Err, IResult, Needed};
729 use crate::error::ParseError;
730 use crate::bytes::complete::take;
731 use crate::number::complete::be_u8;
732
733 macro_rules! assert_parse(
734 ($left: expr, $right: expr) => {
735 let res: $crate::IResult<_, _, (_, ErrorKind)> = $left;
736 assert_eq!(res, $right);
737 };
738 );
739
740 /*#[test]
741 fn t1() {
742 let v1:Vec<u8> = vec![1,2,3];
743 let v2:Vec<u8> = vec![4,5,6];
744 let d = Ok((&v1[..], &v2[..]));
745 let res = d.flat_map(print);
746 assert_eq!(res, Ok((&v2[..], ())));
747 }*/
748
749
750 /*
751 #[test]
752 fn end_of_input() {
753 let not_over = &b"Hello, world!"[..];
754 let is_over = &b""[..];
755 named!(eof_test, eof!());
756
757 let res_not_over = eof_test(not_over);
758 assert_eq!(res_not_over, Err(Err::Error(error_position!(not_over, ErrorKind::Eof))));
759
760 let res_over = eof_test(is_over);
761 assert_eq!(res_over, Ok((is_over, is_over)));
762 }
763 */
764
765 #[test]
rest_on_slices()766 fn rest_on_slices() {
767 let input: &[u8] = &b"Hello, world!"[..];
768 let empty: &[u8] = &b""[..];
769 assert_parse!(rest(input), Ok((empty, input)));
770 }
771
772 #[test]
rest_on_strs()773 fn rest_on_strs() {
774 let input: &str = "Hello, world!";
775 let empty: &str = "";
776 assert_parse!(rest(input), Ok((empty, input)));
777 }
778
779 #[test]
rest_len_on_slices()780 fn rest_len_on_slices() {
781 let input: &[u8] = &b"Hello, world!"[..];
782 assert_parse!(rest_len(input), Ok((input, input.len())));
783 }
784
785 use crate::lib::std::convert::From;
786 impl From<u32> for CustomError {
from(_: u32) -> Self787 fn from(_: u32) -> Self {
788 CustomError
789 }
790 }
791
792 impl<I> ParseError<I> for CustomError {
from_error_kind(_: I, _: ErrorKind) -> Self793 fn from_error_kind(_: I, _: ErrorKind) -> Self {
794 CustomError
795 }
796
append(_: I, _: ErrorKind, _: CustomError) -> Self797 fn append(_: I, _: ErrorKind, _: CustomError) -> Self {
798 CustomError
799 }
800 }
801
802 struct CustomError;
803 #[allow(dead_code)]
custom_error(input: &[u8]) -> IResult<&[u8], &[u8], CustomError>804 fn custom_error(input: &[u8]) -> IResult<&[u8], &[u8], CustomError> {
805 //fix_error!(input, CustomError, alphanumeric)
806 crate::character::streaming::alphanumeric1(input)
807 }
808
809 #[test]
test_flat_map()810 fn test_flat_map() {
811 let input: &[u8] = &[3, 100, 101, 102, 103, 104][..];
812 assert_parse!(flat_map(be_u8, take)(input), Ok((&[103, 104][..], &[100, 101, 102][..])));
813 }
814
815 #[test]
test_map_opt()816 fn test_map_opt() {
817 let input: &[u8] = &[50][..];
818 assert_parse!(map_opt(be_u8, |u| if u < 20 {Some(u)} else {None})(input), Err(Err::Error((&[50][..], ErrorKind::MapOpt))));
819 assert_parse!(map_opt(be_u8, |u| if u > 20 {Some(u)} else {None})(input), Ok((&[][..], 50)));
820 }
821
822 #[test]
test_map_parser()823 fn test_map_parser() {
824 let input: &[u8] = &[100, 101, 102, 103, 104][..];
825 assert_parse!(map_parser(take(4usize), take(2usize))(input), Ok((&[104][..], &[100, 101][..])));
826 }
827
828 #[test]
test_all_consuming()829 fn test_all_consuming() {
830 let input: &[u8] = &[100, 101, 102][..];
831 assert_parse!(all_consuming(take(2usize))(input), Err(Err::Error((&[102][..], ErrorKind::Eof))));
832 assert_parse!(all_consuming(take(3usize))(input), Ok((&[][..], &[100, 101, 102][..])));
833 }
834
835 #[test]
836 #[allow(unused)]
test_verify_ref()837 fn test_verify_ref() {
838 use crate::bytes::complete::take;
839
840 let parser1 = verify(take(3u8), |s: &[u8]| s == &b"abc"[..]);
841
842 assert_eq!(parser1(&b"abcd"[..]), Ok((&b"d"[..], &b"abc"[..])));
843 assert_eq!(parser1(&b"defg"[..]), Err(Err::Error((&b"defg"[..], ErrorKind::Verify))));
844
845 fn parser2(i: &[u8]) -> IResult<&[u8], u32> {
846 verify(crate::number::streaming::be_u32, |val: &u32| *val < 3)(i)
847 }
848 }
849
850 #[test]
851 #[cfg(feature = "alloc")]
test_verify_alloc()852 fn test_verify_alloc() {
853 use crate::bytes::complete::take;
854 let parser1 = verify(map(take(3u8), |s: &[u8]| s.to_vec()), |s: &[u8]| s == &b"abc"[..]);
855
856 assert_eq!(parser1(&b"abcd"[..]), Ok((&b"d"[..], (&b"abc").to_vec())));
857 assert_eq!(parser1(&b"defg"[..]), Err(Err::Error((&b"defg"[..], ErrorKind::Verify))));
858 }
859 }
860