Skip to content

Commit

Permalink
add the value combinator as a function
Browse files Browse the repository at this point in the history
  • Loading branch information
Geal committed Jun 19, 2019
1 parent 5ce22d8 commit 608aa8f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 11 deletions.
13 changes: 2 additions & 11 deletions src/combinator/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -683,19 +683,10 @@ macro_rules! verify (
#[macro_export(local_inner_macros)]
macro_rules! value (
($i:expr, $res:expr, $submac:ident!( $($args:tt)* )) => (
{
use $crate::lib::std::result::Result::*;

match $submac!($i, $($args)*) {
Ok((i,_)) => {
Ok((i, $res))
},
Err(e) => Err(e),
}
}
$crate::combinator::valuec($i, $res, |i| $submac!(i, $($args)*))
);
($i:expr, $res:expr, $f:expr) => (
value!($i, $res, call!($f))
$crate::combinator::valuec($i, $res, $f)
);
($i:expr, $res:expr) => (
{
Expand Down
32 changes: 32 additions & 0 deletions src/combinator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,38 @@ where
verify(first, second)(input)
}

/// returns the provided value if the child parser succeeds
///
/// ```rust
/// # #[macro_use] extern crate nom;
/// # use nom::{Err,error::ErrorKind, IResult};
/// use nom::combinator::value;
/// use nom::character::complete::alpha1;
/// # fn main() {
///
/// let parser = value(1234, alpha1);
///
/// assert_eq!(parser("abcd"), Ok(("", 1234)));
/// assert_eq!(parser("123abcd;"), Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
/// # }
/// ```
pub fn 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>,
{
move |input: I| {
parser(input).map(|(i, _)| (i, val.clone()))
}
}

#[doc(hidden)]
pub fn 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>,
{
value(val, parser)(input)
}

/// succeeds if the child parser returns an error
///
/// ```rust
Expand Down

0 comments on commit 608aa8f

Please sign in to comment.