use crate::{
error::{ParseResult, StdParseResult},
lib::marker::PhantomData,
stream::Stream,
Parser,
};
impl<'a, Input: Stream, O> Parser<Input>
for dyn FnMut(&mut Input) -> StdParseResult<O, Input> + 'a
{
type Output = O;
type PartialState = ();
#[inline]
fn parse_lazy(&mut self, input: &mut Input) -> ParseResult<O, Input::Error> {
self(input).into()
}
}
#[derive(Copy, Clone)]
pub struct FnParser<Input, F>(F, PhantomData<fn(Input) -> Input>);
pub fn parser<Input, O, F>(f: F) -> FnParser<Input, F>
where
Input: Stream,
F: FnMut(&mut Input) -> StdParseResult<O, Input>,
{
FnParser(f, PhantomData)
}
impl<Input, O, F> Parser<Input> for FnParser<Input, F>
where
Input: Stream,
F: FnMut(&mut Input) -> StdParseResult<O, Input>,
{
type Output = O;
type PartialState = ();
#[inline]
fn parse_lazy(&mut self, input: &mut Input) -> ParseResult<O, Input::Error> {
(self.0)(input).into()
}
}
impl<Input, O> Parser<Input> for fn(&mut Input) -> StdParseResult<O, Input>
where
Input: Stream,
{
type Output = O;
type PartialState = ();
#[inline]
fn parse_lazy(&mut self, input: &mut Input) -> ParseResult<O, Input::Error> {
self(input).into()
}
}
#[derive(Copy)]
pub struct EnvParser<E, Input, T>
where
Input: Stream,
{
env: E,
parser: fn(E, &mut Input) -> StdParseResult<T, Input>,
}
impl<E, Input, T> Clone for EnvParser<E, Input, T>
where
Input: Stream,
E: Clone,
{
fn clone(&self) -> Self {
EnvParser {
env: self.env.clone(),
parser: self.parser,
}
}
}
impl<Input, E, O> Parser<Input> for EnvParser<E, Input, O>
where
E: Clone,
Input: Stream,
{
type Output = O;
type PartialState = ();
#[inline]
fn parse_lazy(&mut self, input: &mut Input) -> ParseResult<O, Input::Error> {
(self.parser)(self.env.clone(), input).into()
}
}
pub fn env_parser<E, Input, O>(
env: E,
parser: fn(E, &mut Input) -> StdParseResult<O, Input>,
) -> EnvParser<E, Input, O>
where
E: Clone,
Input: Stream,
{
EnvParser { env, parser }
}