use core::marker::PhantomData;
use crate::Compare;
use crate::CompareResult;
use crate::Emit;
use crate::FindToken;
use crate::IsStreaming;
use crate::Mode;
use crate::Offset;
use crate::OutputM;
use crate::branch::alt;
use crate::combinator::opt;
use crate::error::ErrorKind;
use crate::{AsChar, Err, Input, Needed, Parser, error::ParseError};
#[cfg(test)]
mod tests;
pub fn char<I, Error: ParseError<I>>(c: char) -> impl Parser<I, Output = char, Error = Error>
where
I: Input,
<I as Input>::Item: AsChar,
{
Char { c, e: PhantomData }
}
pub struct Char<E> {
c: char,
e: PhantomData<E>,
}
impl<I, Error: ParseError<I>> Parser<I> for Char<Error>
where
I: Input,
<I as Input>::Item: AsChar,
{
type Output = char;
type Error = Error;
#[inline(always)]
fn process<OM: crate::OutputMode>(
&mut self,
i: I,
) -> crate::PResult<OM, I, Self::Output, Self::Error> {
match (i).iter_elements().next().map(|t| {
let b = t.as_char() == self.c;
(&self.c, b)
}) {
None => {
if OM::Incomplete::is_streaming() {
Err(Err::Incomplete(Needed::new(self.c.len() - i.input_len())))
} else {
Err(Err::Error(OM::Error::bind(|| Error::from_char(i, self.c))))
}
}
Some((_, false)) => Err(Err::Error(OM::Error::bind(|| Error::from_char(i, self.c)))),
Some((c, true)) => Ok((i.take_from(c.len()), OM::Output::bind(|| c.as_char()))),
}
}
}
pub fn satisfy<F, I, Error: ParseError<I>>(
predicate: F,
) -> impl Parser<I, Output = char, Error = Error>
where
I: Input,
<I as Input>::Item: AsChar,
F: Fn(char) -> bool,
{
Satisfy {
predicate,
make_error: |i: I| Error::from_error_kind(i, ErrorKind::Satisfy),
}
}
pub struct Satisfy<F, MakeError> {
predicate: F,
make_error: MakeError,
}
impl<I, Error: ParseError<I>, F, MakeError> Parser<I> for Satisfy<F, MakeError>
where
I: Input,
<I as Input>::Item: AsChar,
F: Fn(char) -> bool,
MakeError: Fn(I) -> Error,
{
type Output = char;
type Error = Error;
#[inline(always)]
fn process<OM: crate::OutputMode>(
&mut self,
i: I,
) -> crate::PResult<OM, I, Self::Output, Self::Error> {
match (i).iter_elements().next().map(|t| {
let c = t.as_char();
let b = (self.predicate)(c);
(c, b)
}) {
None => {
if OM::Incomplete::is_streaming() {
Err(Err::Incomplete(Needed::Unknown))
} else {
Err(Err::Error(OM::Error::bind(|| (self.make_error)(i))))
}
}
Some((_, false)) => Err(Err::Error(OM::Error::bind(|| (self.make_error)(i)))),
Some((c, true)) => Ok((i.take_from(c.len()), OM::Output::bind(|| c.as_char()))),
}
}
}
pub fn one_of<I, T, Error: ParseError<I>>(list: T) -> impl Parser<I, Output = char, Error = Error>
where
I: Input,
<I as Input>::Item: AsChar,
T: FindToken<char>,
{
Satisfy {
predicate: move |c: char| list.find_token(c),
make_error: move |i| Error::from_error_kind(i, ErrorKind::OneOf),
}
}
pub fn none_of<I, T, Error: ParseError<I>>(list: T) -> impl Parser<I, Output = char, Error = Error>
where
I: Input,
<I as Input>::Item: AsChar,
T: FindToken<char>,
{
Satisfy {
predicate: move |c: char| !list.find_token(c),
make_error: move |i| Error::from_error_kind(i, ErrorKind::NoneOf),
}
}
pub fn crlf<I, Error: ParseError<I>>() -> impl Parser<I, Output = I, Error = Error>
where
I: Input + Compare<&'static str>,
{
CrLf { e: PhantomData }
}
pub struct CrLf<E> {
e: PhantomData<E>,
}
impl<I, Error: ParseError<I>> Parser<I> for CrLf<Error>
where
I: Input + Compare<&'static str>,
{
type Output = I;
type Error = Error;
fn process<OM: crate::OutputMode>(
&mut self,
i: I,
) -> crate::PResult<OM, I, Self::Output, Self::Error> {
match i.compare("\r\n") {
CompareResult::Ok => {
let (rest, i) = i.take_split(2);
Ok((rest, OM::Output::bind(|| i)))
}
CompareResult::Incomplete if OM::Incomplete::is_streaming() => {
Err(Err::Incomplete(Needed::new(2)))
}
_ => Err(Err::Error(OM::Error::bind(|| {
Error::from_error_kind(i, ErrorKind::CrLf)
}))),
}
}
}
pub fn not_line_ending<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input + Compare<&'static str>,
<I as Input>::Item: AsChar,
{
NotLineEnding { e: PhantomData }
}
pub struct NotLineEnding<E> {
e: PhantomData<E>,
}
impl<I, E> Parser<I> for NotLineEnding<E>
where
I: Input + Compare<&'static str>,
<I as Input>::Item: AsChar,
E: ParseError<I>,
{
type Output = I;
type Error = E;
fn process<OM: crate::OutputMode>(
&mut self,
input: I,
) -> crate::PResult<OM, I, Self::Output, Self::Error> {
match input.position(|item| {
let c = item.as_char();
c == '\r' || c == '\n'
}) {
None if OM::Incomplete::is_streaming() => Err(Err::Incomplete(Needed::Unknown)),
None => {
let (rest, result) = input.take_split(input.input_len());
Ok((rest, OM::Output::bind(|| result)))
}
Some(index) => {
let mut it = input.take_from(index).iter_elements();
let nth = it.next().unwrap().as_char();
if nth == '\r' {
let sliced = input.take_from(index);
let comp = sliced.compare("\r\n");
match comp {
CompareResult::Ok => {
let (rest, result) = input.take_split(index);
Ok((rest, OM::Output::bind(|| result)))
}
CompareResult::Incomplete if OM::Incomplete::is_streaming() => {
Err(Err::Incomplete(Needed::Unknown))
}
_ => Err(Err::Error(OM::Error::bind(|| {
E::from_error_kind(input, ErrorKind::Tag)
}))),
}
} else {
let (rest, result) = input.take_split(index);
Ok((rest, OM::Output::bind(|| result)))
}
}
}
}
}
pub fn line_ending<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input + Offset + Compare<&'static str>,
<I as Input>::Item: AsChar,
{
crate::combinator::recognize(char('\n')).or(crlf())
}
pub fn newline<I, E: ParseError<I>>() -> impl Parser<I, Output = char, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
char('\n')
}
pub fn tab<I, E: ParseError<I>>() -> impl Parser<I, Output = char, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
char('\t')
}
pub fn anychar<I, E: ParseError<I>>() -> impl Parser<I, Output = char, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
AnyChar { e: PhantomData }
}
pub struct AnyChar<E> {
e: PhantomData<E>,
}
impl<I, Error: ParseError<I>> Parser<I> for AnyChar<Error>
where
I: Input,
<I as Input>::Item: AsChar,
{
type Output = char;
type Error = Error;
fn process<OM: crate::OutputMode>(
&mut self,
i: I,
) -> crate::PResult<OM, I, Self::Output, Self::Error> {
match (i).iter_elements().next() {
None => {
if OM::Incomplete::is_streaming() {
Err(Err::Incomplete(Needed::new(1)))
} else {
Err(Err::Error(OM::Error::bind(|| {
Error::from_error_kind(i, ErrorKind::Eof)
})))
}
}
Some(c) => Ok((i.take_from(c.len()), OM::Output::bind(|| c.as_char()))),
}
}
}
pub fn alpha0<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars0 {
e: PhantomData,
p: |c: char| c.is_alpha(),
}
}
pub fn alpha1<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars1 {
e: PhantomData,
p: |c: char| c.is_alpha(),
ek: ErrorKind::Alpha,
}
}
pub fn digit0<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars0 {
e: PhantomData,
p: |c: char| c.is_dec_digit(),
}
}
pub fn digit1<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars1 {
e: PhantomData,
p: |c: char| c.is_dec_digit(),
ek: ErrorKind::Digit,
}
}
pub fn hex_digit0<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars0 {
e: PhantomData,
p: |c: char| c.is_hex_digit(),
}
}
pub fn hex_digit1<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars1 {
e: PhantomData,
p: |c: char| c.is_hex_digit(),
ek: ErrorKind::HexDigit,
}
}
pub fn oct_digit0<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars0 {
e: PhantomData,
p: |c: char| c.is_oct_digit(),
}
}
pub fn oct_digit1<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars1 {
e: PhantomData,
p: |c: char| c.is_oct_digit(),
ek: ErrorKind::OctDigit,
}
}
pub fn bin_digit0<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars0 {
e: PhantomData,
p: |c: char| c.is_bin_digit(),
}
}
pub fn bin_digit1<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars1 {
e: PhantomData,
p: |c: char| c.is_bin_digit(),
ek: ErrorKind::BinDigit,
}
}
pub fn alphanumeric0<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars0 {
e: PhantomData,
p: |c: char| c.is_alphanum(),
}
}
pub fn alphanumeric1<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars1 {
e: PhantomData,
p: |c: char| c.is_alphanum(),
ek: ErrorKind::AlphaNumeric,
}
}
pub fn space0<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar + Clone,
{
RecognizeChars0 {
e: PhantomData,
p: |c| c == ' ' || c == '\t',
}
}
pub fn space1<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars1 {
e: PhantomData,
p: |c| c == ' ' || c == '\t',
ek: ErrorKind::Space,
}
}
pub fn multispace0<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars0 {
e: PhantomData,
p: |c| c == ' ' || c == '\t' || c == '\r' || c == '\n',
}
}
pub fn multispace1<I, E: ParseError<I>>() -> impl Parser<I, Output = I, Error = E>
where
I: Input,
<I as Input>::Item: AsChar,
{
RecognizeChars1 {
e: PhantomData,
p: |c| c == ' ' || c == '\t' || c == '\r' || c == '\n',
ek: ErrorKind::MultiSpace,
}
}
pub struct RecognizeChars0<P, E> {
e: PhantomData<E>,
p: P,
}
impl<I, P, Error: ParseError<I>> Parser<I> for RecognizeChars0<P, Error>
where
I: Input,
P: Fn(char) -> bool,
<I as Input>::Item: AsChar,
{
type Output = I;
type Error = Error;
fn process<OM: crate::OutputMode>(
&mut self,
i: I,
) -> crate::PResult<OM, I, Self::Output, Self::Error> {
i.split_at_position_mode::<OM, _, _>(|item| {
let c = item.as_char();
!(self.p)(c)
})
}
}
pub struct RecognizeChars1<P, E> {
e: PhantomData<E>,
p: P,
ek: ErrorKind,
}
impl<I, P, Error: ParseError<I>> Parser<I> for RecognizeChars1<P, Error>
where
I: Input,
P: Fn(char) -> bool,
<I as Input>::Item: AsChar,
{
type Output = I;
type Error = Error;
fn process<OM: crate::OutputMode>(
&mut self,
i: I,
) -> crate::PResult<OM, I, Self::Output, Self::Error> {
i.split_at_position_mode1::<OM, _, _>(
|item| {
let c = item.as_char();
!(self.p)(c)
},
self.ek,
)
}
}
pub(crate) fn sign<I, E: ParseError<I>>() -> impl Parser<I, Output = bool, Error = E>
where
I: Clone + Input + for<'a> Compare<&'a [u8]>,
{
Sign { e: PhantomData }
}
pub(crate) struct Sign<E> {
e: PhantomData<E>,
}
impl<I, E> Parser<I> for Sign<E>
where
E: ParseError<I>,
I: Clone + Input + for<'a> Compare<&'a [u8]>,
{
type Output = bool;
type Error = E;
fn process<OM: crate::OutputMode>(
&mut self,
input: I,
) -> crate::PResult<OM, I, Self::Output, Self::Error> {
use crate::bytes::tag;
use crate::combinator::value;
let (i, sign) = opt(alt((
value(false, tag(&b"-"[..])),
value(true, tag(&b"+"[..])),
)))
.map(|b| b.unwrap_or(true))
.process::<OM>(input)?;
Ok((i, sign))
}
}
#[doc(hidden)]
macro_rules! ints {
($($t:tt)+) => {
$(
pub fn $t<I, E: ParseError<I>>() -> impl Parser<I, Output = $t, Error = E>
where
I: Input + Clone,
<I as Input>::Item: AsChar,
I: for <'a> Compare<&'a[u8]>,
{
SInt::<$t, E> {
i: PhantomData,
e: PhantomData
}
}
)+
}
}
ints! { i8 i16 i32 i64 i128 isize }
pub struct SInt<Int, E> {
i: PhantomData<Int>,
e: PhantomData<E>,
}
impl<Int, I, E> Parser<I> for SInt<Int, E>
where
Int: num_traits::CheckedMul
+ num_traits::CheckedAdd
+ num_traits::CheckedSub
+ num_traits::Zero
+ num_traits::NumCast,
I: Input + Clone + for<'a> Compare<&'a [u8]>,
<I as Input>::Item: AsChar,
E: ParseError<I>,
{
type Output = Int;
type Error = E;
fn process<OM: crate::OutputMode>(
&mut self,
input: I,
) -> crate::PResult<OM, I, Self::Output, Self::Error> {
let (i, sign) = sign().process::<OutputM<Emit, OM::Error, OM::Incomplete>>(input.clone())?;
if i.input_len() == 0 {
if OM::Incomplete::is_streaming() {
return Err(Err::Incomplete(Needed::new(1)));
}
return Err(Err::Error(OM::Error::bind(|| {
E::from_error_kind(input, ErrorKind::Digit)
})));
}
let mut value = num_traits::zero();
let mut pos = 0;
for c in i.iter_elements() {
match c.as_char().to_digit(10).and_then(|d| num_traits::cast(d)) {
None => {
if pos == 0 {
return Err(Err::Error(OM::Error::bind(|| {
E::from_error_kind(input, ErrorKind::Digit)
})));
}
return Ok((i.take_from(pos), OM::Output::bind(|| value)));
}
Some(d) => match value
.checked_mul(&num_traits::cast(10).unwrap())
.and_then(|v| {
if sign {
v.checked_add(&d)
} else {
v.checked_sub(&d)
}
}) {
None => {
return Err(Err::Error(OM::Error::bind(|| {
E::from_error_kind(input, ErrorKind::Digit)
})));
}
Some(v) => {
pos += c.len();
value = v;
}
},
}
}
if OM::Incomplete::is_streaming() {
Err(Err::Incomplete(Needed::new(1)))
} else {
Ok((i.take_from(i.input_len()), OM::Output::bind(|| value)))
}
}
}
#[doc(hidden)]
macro_rules! uints {
($($t:tt)+) => {
$(
pub fn $t<I, E: ParseError<I>>() -> impl Parser<I, Output = $t, Error = E>
where
I: Input + Clone,
<I as Input>::Item: AsChar,
I: for <'a> Compare<&'a[u8]>,
{
UInt::<$t, E> {
i: PhantomData,
e: PhantomData
}
}
)+
}
}
uints! { u8 u16 u32 u64 u128 usize }
pub struct UInt<Int, E> {
i: PhantomData<Int>,
e: PhantomData<E>,
}
impl<Int, I, E> Parser<I> for UInt<Int, E>
where
Int: num_traits::CheckedMul
+ num_traits::CheckedAdd
+ num_traits::CheckedSub
+ num_traits::Zero
+ num_traits::NumCast,
I: Input + Clone + for<'a> Compare<&'a [u8]>,
<I as Input>::Item: AsChar,
E: ParseError<I>,
{
type Output = Int;
type Error = E;
fn process<OM: crate::OutputMode>(
&mut self,
input: I,
) -> crate::PResult<OM, I, Self::Output, Self::Error> {
let i = input.clone();
if i.input_len() == 0 {
if OM::Incomplete::is_streaming() {
return Err(Err::Incomplete(Needed::new(1)));
}
return Err(Err::Error(OM::Error::bind(|| {
E::from_error_kind(input, ErrorKind::Digit)
})));
}
let mut value = num_traits::zero();
let mut pos = 0;
for c in i.iter_elements() {
match c.as_char().to_digit(10).and_then(|d| num_traits::cast(d)) {
None => {
if pos == 0 {
return Err(Err::Error(OM::Error::bind(|| {
E::from_error_kind(input, ErrorKind::Digit)
})));
}
return Ok((i.take_from(pos), OM::Output::bind(|| value)));
}
Some(d) => match value
.checked_mul(&num_traits::cast(10).unwrap())
.and_then(|v| v.checked_add(&d))
{
None => {
return Err(Err::Error(OM::Error::bind(|| {
E::from_error_kind(input, ErrorKind::Digit)
})));
}
Some(v) => {
pos += c.len();
value = v;
}
},
}
}
if OM::Incomplete::is_streaming() {
Err(Err::Incomplete(Needed::new(1)))
} else {
Ok((i.take_from(i.input_len()), OM::Output::bind(|| value)))
}
}
}