use crate::{
error::{Error, ErrorDisplay},
prelude::{
debug, pand, pbetween, pbind, pdelim, pdelim1, pfoldl, pignore_then, pinto, pmany, pmany1,
pmap_error, pmap_with_span, pnot, por, ppadded, pseq, pthen_ignore, puntil_end,
},
};
pub type Span = (usize, usize);
#[derive(Clone, Debug)]
pub struct PInput<'a, T: PartialEq + Clone + 'a> {
pub tokens: &'a [T],
pub loc: usize,
}
#[derive(Clone)]
pub struct PSuccess<'a, T, O>
where
T: PartialEq + Clone,
{
pub val: O,
pub rest: PInput<'a, T>,
}
pub trait ParserCore<'a, K, O>
where
K: PartialEq + Clone + 'a,
{
fn parse(&self, i: PInput<'a, K>) -> Result<PSuccess<'a, K, O>, Error<'a, K>>;
}
pub trait Parser<'a, K: PartialEq + Clone + 'a, O: Clone + 'a>:
ParserCore<'a, K, O> + Sized + Clone
{
fn then<O2, T>(self, p2: T) -> impl Parser<'a, K, (O, O2)>
where
T: Parser<'a, K, O2>,
O2: Clone + 'a,
{
pseq(self, p2)
}
fn or<T>(self, p2: T) -> impl Parser<'a, K, O>
where
T: Parser<'a, K, O>,
{
por(self, p2)
}
fn map<O2, F>(self, f: F) -> impl Parser<'a, K, O2>
where
F: Fn(O) -> O2 + 'static,
O2: Clone + 'a,
{
pbind(self, f)
}
fn between<A, P1, P2>(self, l: P1, r: P2) -> impl Parser<'a, K, O>
where
A: Clone + 'a,
P1: Parser<'a, K, A>,
P2: Parser<'a, K, A>,
{
pbetween(l, self, r)
}
fn many(self) -> impl Parser<'a, K, Vec<O>> {
pmany(self)
}
fn many1(self) -> impl Parser<'a, K, Vec<O>> {
pmany1(self)
}
fn delimited_by<PD, A>(self, delim: PD) -> impl Parser<'a, K, Vec<O>>
where
A: Clone + 'a,
PD: Parser<'a, K, A>,
{
pdelim(self, delim)
}
fn delimited_by1<PD, A>(self, delim: PD) -> impl Parser<'a, K, Vec<O>>
where
A: Clone + 'a,
PD: Parser<'a, K, A>,
{
pdelim1(self, delim)
}
fn not(self) -> impl Parser<'a, K, ()> {
pnot(self)
}
fn padded_by<P, A>(self, pad: P) -> impl Parser<'a, K, O>
where
A: Clone + 'a,
P: Parser<'a, K, A> + Clone,
{
ppadded(self, pad)
}
fn into_<Out>(self, out: Out) -> impl Parser<'a, K, Out>
where
Out: PartialEq + Clone + 'a,
{
pinto(self, out)
}
fn debug(self, label: &'static str) -> impl Parser<'a, K, O>
where
K: ErrorDisplay,
{
debug(self, label)
}
fn and<P2, A>(self, second: P2) -> impl Parser<'a, K, O>
where
A: Clone + 'a,
P2: Parser<'a, K, A>,
{
pand(self, second)
}
fn until_end(self) -> impl Parser<'a, K, O> {
puntil_end(self)
}
fn foldl<TP, F, I, O2>(self, tail: TP, f: F) -> impl Parser<'a, K, O>
where
O2: Clone + 'a,
I: IntoIterator<Item = O2> + Clone + 'a,
TP: Parser<'a, K, I>,
F: Fn(O, O2) -> O + Clone + 'a,
{
pfoldl(self, tail, f)
}
fn ignore_then<P2, OO>(self, then: P2) -> impl Parser<'a, K, OO>
where
OO: Clone + 'a,
P2: Parser<'a, K, OO>,
{
pignore_then(self, then)
}
fn then_ignore<P2, OO>(self, ignore: P2) -> impl Parser<'a, K, O>
where
OO: Clone + 'a,
P2: Parser<'a, K, OO>,
{
pthen_ignore(self, ignore)
}
fn map_with_span<F, O1>(self, f: F) -> impl Parser<'a, K, O1>
where
F: Fn(O, Span) -> O1 + 'static,
O1: Clone + 'a,
{
pmap_with_span(self, f)
}
fn map_error<F>(self, f: F) -> impl Parser<'a, K, O>
where
F: Fn(Error<'a, K>) -> Error<'a, K> + 'static,
{
pmap_error(self, f)
}
}