pub trait Parser<I, O, E> {
Show 20 methods
fn parse(&mut self, input: I) -> IResult<I, O, E>;
fn by_ref(&mut self) -> ByRef<'_, Self>
where
Self: Sized,
{ ... }
fn value<O2>(self, val: O2) -> Value<Self, O, O2>
where
Self: Sized,
O2: Clone,
{ ... }
fn output_into<O2: From<O>>(self) -> OutputInto<Self, O, O2>
where
Self: Sized,
{ ... }
fn recognize(self) -> Recognize<Self, O>
where
Self: Sized,
{ ... }
fn with_recognized(self) -> WithRecognized<Self, O>
where
Self: Sized,
{ ... }
fn span(self) -> Span<Self, O>
where
Self: Sized,
I: Location + Clone,
{ ... }
fn with_span(self) -> WithSpan<Self, O>
where
Self: Sized,
I: Location + Clone,
{ ... }
fn map<G, O2>(self, g: G) -> Map<Self, G, O>
where
G: Fn(O) -> O2,
Self: Sized,
{ ... }
fn map_res<G, O2, E2>(self, g: G) -> MapRes<Self, G, O>
where
Self: Sized,
G: FnMut(O) -> Result<O2, E2>,
{ ... }
fn map_opt<G, O2>(self, g: G) -> MapOpt<Self, G, O>
where
Self: Sized,
G: FnMut(O) -> Option<O2>,
{ ... }
fn flat_map<G, H, O2>(self, g: G) -> FlatMap<Self, G, O>
where
G: FnMut(O) -> H,
H: Parser<I, O2, E>,
Self: Sized,
{ ... }
fn and_then<G, O2>(self, g: G) -> AndThen<Self, G, O>
where
G: Parser<O, O2, E>,
Self: Sized,
{ ... }
fn verify<G, O2: ?Sized>(self, second: G) -> Verify<Self, G, O2>
where
Self: Sized,
G: Fn(&O2) -> bool,
{ ... }
fn context<C>(self, context: C) -> Context<Self, O, C>
where
Self: Sized,
C: Clone,
E: ContextError<I, C>,
{ ... }
fn complete(self) -> Complete<Self>
where
Self: Sized,
{ ... }
fn err_into<E2: From<E>>(self) -> ErrInto<Self, E, E2>
where
Self: Sized,
{ ... }
fn dbg_err<C>(self, context: C) -> DbgErr<Self, O, C>
where
C: Display,
Self: Sized,
{ ... }
fn and<G, O2>(self, g: G) -> And<Self, G>
where
G: Parser<I, O2, E>,
Self: Sized,
{ ... }
fn or<G>(self, g: G) -> Or<Self, G>
where
G: Parser<I, O, E>,
Self: Sized,
{ ... }
}
Expand description
All nom parsers implement this trait
The simplest way to implement a Parser
is with a function
use nom8::prelude::*;
fn success(input: &str) -> IResult<&str, ()> {
let output = ();
Ok((input, output))
}
let (input, output) = success.parse("Hello").unwrap();
assert_eq!(input, "Hello"); // We didn't consume any input
which can be made stateful by returning a function
use nom8::prelude::*;
fn success<O: Clone>(output: O) -> impl FnMut(&str) -> IResult<&str, O> {
move |input: &str| {
let output = output.clone();
Ok((input, output))
}
}
let (input, output) = success("World").parse("Hello").unwrap();
assert_eq!(input, "Hello"); // We didn't consume any input
assert_eq!(output, "World");
Additionally, some basic types implement Parser
as well, including
u8
andchar
, seenom8::character::char
&[u8]
and&str
, seenom8::character::char
Required Methods
Provided Methods
Treat &mut Self
as a parser
This helps when needing to move a Parser
when all you have is a &mut Parser
.
Example
Because parsers are FnMut
, they can be called multiple times. This prevents moving f
into length_data
and g
into
complete
:
pub fn length_value<'i, O, E: ParseError<&'i [u8]>>(
mut f: impl Parser<&'i [u8], usize, E>,
mut g: impl Parser<&'i [u8], O, E>
) -> impl FnMut(&'i [u8]) -> IResult<&'i [u8], O, E> {
move |i: &'i [u8]| {
let (i, data) = length_data(f).parse(i)?;
let (_, o) = g.complete().parse(data)?;
Ok((i, o))
}
}
By adding by_ref
, we can make this work:
pub fn length_value<'i, O, E: ParseError<&'i [u8]>>(
mut f: impl Parser<&'i [u8], usize, E>,
mut g: impl Parser<&'i [u8], O, E>
) -> impl FnMut(&'i [u8]) -> IResult<&'i [u8], O, E> {
move |i: &'i [u8]| {
let (i, data) = length_data(f.by_ref()).parse(i)?;
let (_, o) = g.by_ref().complete().parse(data)?;
Ok((i, o))
}
}
Returns the provided value if the child parser succeeds.
Example
use nom8::character::alpha1;
let mut parser = alpha1.value(1234);
assert_eq!(parser.parse("abcd"), Ok(("", 1234)));
assert_eq!(parser.parse("123abcd;"), Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
sourcefn output_into<O2: From<O>>(self) -> OutputInto<Self, O, O2>where
Self: Sized,
fn output_into<O2: From<O>>(self) -> OutputInto<Self, O, O2>where
Self: Sized,
Convert the parser’s output to another type using std::convert::From
Example
use nom8::character::alpha1;
fn parser1(i: &str) -> IResult<&str, &str> {
alpha1(i)
}
let mut parser2 = parser1.output_into();
// the parser converts the &str output of the child parser into a Vec<u8>
let bytes: IResult<&str, Vec<u8>> = parser2.parse("abcd");
assert_eq!(bytes, Ok(("", vec![97, 98, 99, 100])));
If the child parser was successful, return the consumed input as produced value.
Example
use nom8::character::{alpha1};
use nom8::sequence::separated_pair;
let mut parser = separated_pair(alpha1, ',', alpha1).recognize();
assert_eq!(parser.parse("abcd,efgh"), Ok(("", "abcd,efgh")));
assert_eq!(parser.parse("abcd;"),Err(Err::Error((";", ErrorKind::OneOf))));
sourcefn with_recognized(self) -> WithRecognized<Self, O>where
Self: Sized,
fn with_recognized(self) -> WithRecognized<Self, O>where
Self: Sized,
if the child parser was successful, return the consumed input with the output as a tuple. Functions similarly to recognize except it returns the parser output as well.
This can be useful especially in cases where the output is not the same type as the input, or the input is a user defined type.
Returned tuple is of the format (produced output, consumed input)
.
Example
use nom8::character::{alpha1};
use nom8::bytes::tag;
use nom8::sequence::separated_pair;
fn inner_parser(input: &str) -> IResult<&str, bool> {
tag("1234").value(true).parse(input)
}
let mut consumed_parser = separated_pair(alpha1, ',', alpha1).value(true).with_recognized();
assert_eq!(consumed_parser.parse("abcd,efgh1"), Ok(("1", (true, "abcd,efgh"))));
assert_eq!(consumed_parser.parse("abcd;"),Err(Err::Error((";", ErrorKind::OneOf))));
// the second output (representing the consumed input)
// should be the same as that of the `recognize` parser.
let mut recognize_parser = inner_parser.recognize();
let mut consumed_parser = inner_parser.with_recognized().map(|(output, consumed)| consumed);
assert_eq!(recognize_parser.parse("1234"), consumed_parser.parse("1234"));
assert_eq!(recognize_parser.parse("abcd"), consumed_parser.parse("abcd"));
If the child parser was successful, return the location of the consumed input as produced value.
Example
use nom8::input::Located;
use nom8::character::alpha1;
use nom8::sequence::separated_pair;
let mut parser = separated_pair(alpha1.span(), ',', alpha1.span());
assert_eq!(parser.parse(Located::new("abcd,efgh")).finish(), Ok((0..4, 5..9)));
assert_eq!(parser.parse(Located::new("abcd;")),Err(Err::Error((Located::new("abcd;").slice(4..), ErrorKind::OneOf))));
if the child parser was successful, return the location of consumed input with the output as a tuple. Functions similarly to Parser::span except it returns the parser output as well.
This can be useful especially in cases where the output is not the same type as the input, or the input is a user defined type.
Returned tuple is of the format (produced output, consumed input)
.
Example
use nom8::input::Located;
use nom8::character::alpha1;
use nom8::bytes::tag;
use nom8::sequence::separated_pair;
fn inner_parser(input: Located<&str>) -> IResult<Located<&str>, bool> {
tag("1234").value(true).parse(input)
}
let mut consumed_parser = separated_pair(alpha1.value(1).with_span(), ',', alpha1.value(2).with_span());
assert_eq!(consumed_parser.parse(Located::new("abcd,efgh")).finish(), Ok(((1, 0..4), (2, 5..9))));
assert_eq!(consumed_parser.parse(Located::new("abcd;")),Err(Err::Error((Located::new("abcd;").slice(4..), ErrorKind::OneOf))));
// the second output (representing the consumed input)
// should be the same as that of the `span` parser.
let mut recognize_parser = inner_parser.span();
let mut consumed_parser = inner_parser.with_span().map(|(output, consumed)| consumed);
assert_eq!(recognize_parser.parse(Located::new("1234")), consumed_parser.parse(Located::new("1234")));
assert_eq!(recognize_parser.parse(Located::new("abcd")), consumed_parser.parse(Located::new("abcd")));
Maps a function over the result of a parser
Example
use nom8::{Err,error::ErrorKind, IResult,Parser};
use nom8::character::digit1;
let mut parser = digit1.map(|s: &str| s.len());
// the parser will count how many characters were returned by digit1
assert_eq!(parser.parse("123456"), Ok(("", 6)));
// this will fail if digit1 fails
assert_eq!(parser.parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
Applies a function returning a Result
over the result of a parser.
Example
use nom8::character::digit1;
let mut parse = digit1.map_res(|s: &str| s.parse::<u8>());
// the parser will convert the result of digit1 to a number
assert_eq!(parse.parse("123"), Ok(("", 123)));
// this will fail if digit1 fails
assert_eq!(parse.parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
// this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
assert_eq!(parse.parse("123456"), Err(Err::Error(("123456", ErrorKind::MapRes))));
Applies a function returning an Option
over the result of a parser.
Example
use nom8::character::digit1;
let mut parse = digit1.map_opt(|s: &str| s.parse::<u8>().ok());
// the parser will convert the result of digit1 to a number
assert_eq!(parse.parse("123"), Ok(("", 123)));
// this will fail if digit1 fails
assert_eq!(parse.parse("abc"), Err(Err::Error(("abc", ErrorKind::Digit))));
// this will fail if the mapped function fails (a `u8` is too small to hold `123456`)
assert_eq!(parse.parse("123456"), Err(Err::Error(("123456", ErrorKind::MapOpt))));
Creates a second parser from the output of the first one, then apply over the rest of the input
Example
use nom8::bytes::take;
use nom8::number::u8;
let mut length_data = u8.flat_map(take);
assert_eq!(length_data.parse(&[2, 0, 1, 2][..]), Ok((&[2][..], &[0, 1][..])));
assert_eq!(length_data.parse(&[4, 0, 1, 2][..]), Err(Err::Error((&[0, 1, 2][..], ErrorKind::Eof))));
Applies a second parser over the output of the first one
Example
use nom8::character::digit1;
use nom8::bytes::take;
let mut digits = take(5u8).and_then(digit1);
assert_eq!(digits.parse("12345"), Ok(("", "12345")));
assert_eq!(digits.parse("123ab"), Ok(("", "123")));
assert_eq!(digits.parse("123"), Err(Err::Error(("123", ErrorKind::Eof))));
Returns the result of the child parser if it satisfies a verification function.
The verification function takes as argument a reference to the output of the parser.
Example
let mut parser = alpha1.verify(|s: &str| s.len() == 4);
assert_eq!(parser.parse("abcd"), Ok(("", "abcd")));
assert_eq!(parser.parse("abcde"), Err(Err::Error(("abcde", ErrorKind::Verify))));
assert_eq!(parser.parse("123abcd;"),Err(Err::Error(("123abcd;", ErrorKind::Alpha))));
If parsing fails, add context to the error
This is used mainly to add user friendly information to errors when backtracking through a parse tree.
Transforms Incomplete
into Error
Example
let mut parser = take(5u8).complete();
assert_eq!(parser.parse(Streaming("abcdefg")), Ok((Streaming("fg"), "abcde")));
assert_eq!(parser.parse(Streaming("abcd")), Err(Err::Error((Streaming("abcd"), ErrorKind::Complete))));
Convert the parser’s error to another type using std::convert::From
Prints a message and the input if the parser fails.
The message prints the Error
or Incomplete
and the parser’s calling code.
It also displays the input in hexdump format
use nom8::prelude::*;
use nom8::{IResult, bytes::tag};
fn f(i: &[u8]) -> IResult<&[u8], &[u8]> {
tag("abcd").dbg_err("alpha tag").parse(i)
}
let a = &b"efghijkl"[..];
f(a);
Will print the following message:
alpha tag: Error(Position(0, [101, 102, 103, 104, 105, 106, 107, 108])) at:
00000000 65 66 67 68 69 6a 6b 6c efghijkl
Replaced with `nom8::sequence::tuple
Applies a second parser after the first one, return their results as a tuple
WARNING: Deprecated, replaced with nom8::sequence::tuple
Trait Implementations
sourceimpl<'a, I, O, E> Parser<I, O, E> for Box<dyn Parser<I, O, E> + 'a>
impl<'a, I, O, E> Parser<I, O, E> for Box<dyn Parser<I, O, E> + 'a>
sourcefn parse(&mut self, input: I) -> IResult<I, O, E>
fn parse(&mut self, input: I) -> IResult<I, O, E>
Result
containing
either the remaining input and the output value, or an error Read moresourcefn by_ref(&mut self) -> ByRef<'_, Self>where
Self: Sized,
fn by_ref(&mut self) -> ByRef<'_, Self>where
Self: Sized,
&mut Self
as a parser Read moresourcefn value<O2>(self, val: O2) -> Value<Self, O, O2>where
Self: Sized,
O2: Clone,
fn value<O2>(self, val: O2) -> Value<Self, O, O2>where
Self: Sized,
O2: Clone,
sourcefn output_into<O2: From<O>>(self) -> OutputInto<Self, O, O2>where
Self: Sized,
fn output_into<O2: From<O>>(self) -> OutputInto<Self, O, O2>where
Self: Sized,
std::convert::From
Read moresourcefn recognize(self) -> Recognize<Self, O>where
Self: Sized,
fn recognize(self) -> Recognize<Self, O>where
Self: Sized,
sourcefn with_recognized(self) -> WithRecognized<Self, O>where
Self: Sized,
fn with_recognized(self) -> WithRecognized<Self, O>where
Self: Sized,
sourcefn map<G, O2>(self, g: G) -> Map<Self, G, O>where
G: Fn(O) -> O2,
Self: Sized,
fn map<G, O2>(self, g: G) -> Map<Self, G, O>where
G: Fn(O) -> O2,
Self: Sized,
sourcefn map_res<G, O2, E2>(self, g: G) -> MapRes<Self, G, O>where
Self: Sized,
G: FnMut(O) -> Result<O2, E2>,
fn map_res<G, O2, E2>(self, g: G) -> MapRes<Self, G, O>where
Self: Sized,
G: FnMut(O) -> Result<O2, E2>,
Result
over the result of a parser. Read moresourcefn map_opt<G, O2>(self, g: G) -> MapOpt<Self, G, O>where
Self: Sized,
G: FnMut(O) -> Option<O2>,
fn map_opt<G, O2>(self, g: G) -> MapOpt<Self, G, O>where
Self: Sized,
G: FnMut(O) -> Option<O2>,
Option
over the result of a parser. Read moresourcefn flat_map<G, H, O2>(self, g: G) -> FlatMap<Self, G, O>where
G: FnMut(O) -> H,
H: Parser<I, O2, E>,
Self: Sized,
fn flat_map<G, H, O2>(self, g: G) -> FlatMap<Self, G, O>where
G: FnMut(O) -> H,
H: Parser<I, O2, E>,
Self: Sized,
sourcefn and_then<G, O2>(self, g: G) -> AndThen<Self, G, O>where
G: Parser<O, O2, E>,
Self: Sized,
fn and_then<G, O2>(self, g: G) -> AndThen<Self, G, O>where
G: Parser<O, O2, E>,
Self: Sized,
sourcefn verify<G, O2: ?Sized>(self, second: G) -> Verify<Self, G, O2>where
Self: Sized,
G: Fn(&O2) -> bool,
fn verify<G, O2: ?Sized>(self, second: G) -> Verify<Self, G, O2>where
Self: Sized,
G: Fn(&O2) -> bool,
sourcefn context<C>(self, context: C) -> Context<Self, O, C>where
Self: Sized,
C: Clone,
E: ContextError<I, C>,
fn context<C>(self, context: C) -> Context<Self, O, C>where
Self: Sized,
C: Clone,
E: ContextError<I, C>,
sourcefn err_into<E2: From<E>>(self) -> ErrInto<Self, E, E2>where
Self: Sized,
fn err_into<E2: From<E>>(self) -> ErrInto<Self, E, E2>where
Self: Sized,
std::convert::From
sourcefn dbg_err<C>(self, context: C) -> DbgErr<Self, O, C>where
C: Display,
Self: Sized,
fn dbg_err<C>(self, context: C) -> DbgErr<Self, O, C>where
C: Display,
Self: Sized,
Implementations on Foreign Types
sourceimpl<I, E> Parser<I, u8, E> for u8where
I: Slice<RangeFrom<usize>> + InputIter<Item = u8> + InputLength + InputIsStreaming<false>,
E: ParseError<I>,
impl<I, E> Parser<I, u8, E> for u8where
I: Slice<RangeFrom<usize>> + InputIter<Item = u8> + InputLength + InputIsStreaming<false>,
E: ParseError<I>,
This is a shortcut for one_of
.
Example
fn parser(i: &[u8]) -> IResult<&[u8], u8> {
b'a'.parse(i)
}
assert_eq!(parser(&b"abc"[..]), Ok((&b"bc"[..], b'a')));
assert_eq!(parser(&b" abc"[..]), Err(Err::Error(Error::new(&b" abc"[..], ErrorKind::OneOf))));
assert_eq!(parser(&b"bc"[..]), Err(Err::Error(Error::new(&b"bc"[..], ErrorKind::OneOf))));
assert_eq!(parser(&b""[..]), Err(Err::Error(Error::new(&b""[..], ErrorKind::OneOf))));
sourceimpl<I, E> Parser<I, <I as InputIter>::Item, E> for charwhere
I: Slice<RangeFrom<usize>> + InputIter + InputLength + InputIsStreaming<false>,
<I as InputIter>::Item: AsChar + Copy,
E: ParseError<I>,
impl<I, E> Parser<I, <I as InputIter>::Item, E> for charwhere
I: Slice<RangeFrom<usize>> + InputIter + InputLength + InputIsStreaming<false>,
<I as InputIter>::Item: AsChar + Copy,
E: ParseError<I>,
This is a shortcut for one_of
.
Example
fn parser(i: &str) -> IResult<&str, char> {
'a'.parse(i)
}
assert_eq!(parser("abc"), Ok(("bc", 'a')));
assert_eq!(parser(" abc"), Err(Err::Error(Error::new(" abc", ErrorKind::OneOf))));
assert_eq!(parser("bc"), Err(Err::Error(Error::new("bc", ErrorKind::OneOf))));
assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::OneOf))));
sourceimpl<'s, I, E: ParseError<I>> Parser<I, <I as IntoOutput>::Output, E> for &'s [u8]where
I: InputTake + InputLength + Compare<&'s [u8]> + InputIsStreaming<false>,
I: IntoOutput,
impl<'s, I, E: ParseError<I>> Parser<I, <I as IntoOutput>::Output, E> for &'s [u8]where
I: InputTake + InputLength + Compare<&'s [u8]> + InputIsStreaming<false>,
I: IntoOutput,
This is a shortcut for tag
.
Example
fn parser(s: &[u8]) -> IResult<&[u8], &[u8]> {
alt((&"Hello"[..], take(5usize))).parse(s)
}
assert_eq!(parser(&b"Hello, World!"[..]), Ok((&b", World!"[..], &b"Hello"[..])));
assert_eq!(parser(&b"Something"[..]), Ok((&b"hing"[..], &b"Somet"[..])));
assert_eq!(parser(&b"Some"[..]), Err(Err::Error(Error::new(&b"Some"[..], ErrorKind::Eof))));
assert_eq!(parser(&b""[..]), Err(Err::Error(Error::new(&b""[..], ErrorKind::Eof))));
fn parse(&mut self, i: I) -> IResult<I, <I as IntoOutput>::Output, E>
sourceimpl<'s, I, E: ParseError<I>, const N: usize> Parser<I, <I as IntoOutput>::Output, E> for &'s [u8; N]where
I: InputTake + InputLength + Compare<&'s [u8; N]> + InputIsStreaming<false>,
I: IntoOutput,
impl<'s, I, E: ParseError<I>, const N: usize> Parser<I, <I as IntoOutput>::Output, E> for &'s [u8; N]where
I: InputTake + InputLength + Compare<&'s [u8; N]> + InputIsStreaming<false>,
I: IntoOutput,
This is a shortcut for tag
.
Example
fn parser(s: &[u8]) -> IResult<&[u8], &[u8]> {
alt((b"Hello", take(5usize))).parse(s)
}
assert_eq!(parser(&b"Hello, World!"[..]), Ok((&b", World!"[..], &b"Hello"[..])));
assert_eq!(parser(&b"Something"[..]), Ok((&b"hing"[..], &b"Somet"[..])));
assert_eq!(parser(&b"Some"[..]), Err(Err::Error(Error::new(&b"Some"[..], ErrorKind::Eof))));
assert_eq!(parser(&b""[..]), Err(Err::Error(Error::new(&b""[..], ErrorKind::Eof))));
fn parse(&mut self, i: I) -> IResult<I, <I as IntoOutput>::Output, E>
sourceimpl<'s, I, E: ParseError<I>> Parser<I, <I as IntoOutput>::Output, E> for &'s strwhere
I: InputTake + InputLength + Compare<&'s str> + InputIsStreaming<false>,
I: IntoOutput,
impl<'s, I, E: ParseError<I>> Parser<I, <I as IntoOutput>::Output, E> for &'s strwhere
I: InputTake + InputLength + Compare<&'s str> + InputIsStreaming<false>,
I: IntoOutput,
This is a shortcut for tag
.
Example
fn parser(s: &str) -> IResult<&str, &str> {
alt(("Hello", take(5usize))).parse(s)
}
assert_eq!(parser("Hello, World!"), Ok((", World!", "Hello")));
assert_eq!(parser("Something"), Ok(("hing", "Somet")));
assert_eq!(parser("Some"), Err(Err::Error(Error::new("Some", ErrorKind::Eof))));
assert_eq!(parser(""), Err(Err::Error(Error::new("", ErrorKind::Eof))));