aboutsummaryrefslogtreecommitdiff
path: root/src/combinator/mod.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/combinator/mod.rs')
-rw-r--r--src/combinator/mod.rs53
1 files changed, 47 insertions, 6 deletions
diff --git a/src/combinator/mod.rs b/src/combinator/mod.rs
index 7071cc7..fe08d4a 100644
--- a/src/combinator/mod.rs
+++ b/src/combinator/mod.rs
@@ -218,7 +218,9 @@ where
}
}
-/// Optional parser: Will return `None` if not successful.
+/// Optional parser, will return `None` on [`Err::Error`].
+///
+/// To chain an error up, see [`cut`].
///
/// ```rust
/// # use nom::{Err,error::ErrorKind, IResult};
@@ -575,18 +577,55 @@ where
}
}
-/// transforms an error to failure
+/// Transforms an [`Err::Error`] (recoverable) to [`Err::Failure`] (unrecoverable)
+///
+/// This commits the parse result, preventing alternative branch paths like with
+/// [`nom::branch::alt`][crate::branch::alt].
///
+/// # Example
+///
+/// Without `cut`:
/// ```rust
/// # use nom::{Err,error::ErrorKind, IResult};
+/// # use nom::character::complete::{one_of, digit1};
+/// # use nom::combinator::rest;
+/// # use nom::branch::alt;
+/// # use nom::sequence::preceded;
+/// # fn main() {
+///
+/// fn parser(input: &str) -> IResult<&str, &str> {
+/// alt((
+/// preceded(one_of("+-"), digit1),
+/// rest
+/// ))(input)
+/// }
+///
+/// assert_eq!(parser("+10 ab"), Ok((" ab", "10")));
+/// assert_eq!(parser("ab"), Ok(("", "ab")));
+/// assert_eq!(parser("+"), Ok(("", "+")));
+/// # }
+/// ```
+///
+/// With `cut`:
+/// ```rust
+/// # use nom::{Err,error::ErrorKind, IResult, error::Error};
+/// # use nom::character::complete::{one_of, digit1};
+/// # use nom::combinator::rest;
+/// # use nom::branch::alt;
+/// # use nom::sequence::preceded;
/// use nom::combinator::cut;
-/// use nom::character::complete::alpha1;
/// # fn main() {
///
-/// let mut parser = cut(alpha1);
+/// fn parser(input: &str) -> IResult<&str, &str> {
+/// alt((
+/// preceded(one_of("+-"), cut(digit1)),
+/// rest
+/// ))(input)
+/// }
///
-/// assert_eq!(parser("abcd;"), Ok((";", "abcd")));
-/// assert_eq!(parser("123;"), Err(Err::Failure(("123;", ErrorKind::Alpha))));
+/// assert_eq!(parser("+10 ab"), Ok((" ab", "10")));
+/// assert_eq!(parser("ab"), Ok(("", "ab")));
+/// assert_eq!(parser("+"), Err(Err::Failure(Error { input: "", code: ErrorKind::Digit })));
/// # }
/// ```
pub fn cut<I, O, E: ParseError<I>, F>(mut parser: F) -> impl FnMut(I) -> IResult<I, O, E>
@@ -643,6 +682,8 @@ where
/// Call the iterator's [ParserIterator::finish] method to get the remaining input if successful,
/// or the error value if we encountered an error.
///
+/// On [`Err::Error`], iteration will stop. To instead chain an error up, see [`cut`].
+///
/// ```rust
/// use nom::{combinator::iterator, IResult, bytes::complete::tag, character::complete::alpha1, sequence::terminated};
/// use std::collections::HashMap;