Repeated structure

This commit is contained in:
Greg Shuflin 2024-01-26 22:11:55 -08:00
parent 9efd9d78d1
commit 0e26ef1ea6

View File

@ -1,15 +1,44 @@
use crate::Parser; use std::marker::PhantomData;
use crate::{ParseResult, Parser};
pub fn repeated<P, I, O, E>(parser: P) -> impl Parser<I, Vec<O>, E> pub fn repeated<P, I, O, E>(parser: P) -> impl Parser<I, Vec<O>, E>
where where
P: Parser<I, O, E>, P: Parser<I, O, E>,
{ {
move |input: I| { Repeated::new(parser)
}
struct Repeated<P, I, O, E>
where
P: Parser<I, O, E>,
{
inner_parser: P,
phantom: PhantomData<(I, O, E)>,
}
impl<P, I, O, E> Repeated<P, I, O, E>
where
P: Parser<I, O, E>,
{
fn new(inner_parser: P) -> Self {
Self {
inner_parser,
phantom: PhantomData,
}
}
}
impl<P, I, O, E> Parser<I, Vec<O>, E> for Repeated<P, I, O, E>
where
P: Parser<I, O, E>,
{
fn parse(&self, input: I) -> ParseResult<I, Vec<O>, E> {
let mut acc = input; let mut acc = input;
let mut results = vec![]; let mut results = vec![];
loop { loop {
match parser.parse(acc) { match self.inner_parser.parse(acc) {
Ok((item, rest)) => { Ok((item, rest)) => {
results.push(item); results.push(item);
acc = rest; acc = rest;