diff --git a/src/annotated.rs b/src/annotated.rs new file mode 100644 index 0000000..9a0e07e --- /dev/null +++ b/src/annotated.rs @@ -0,0 +1,45 @@ +use std::marker::PhantomData; + +use crate::{ParseResult, Parser}; + +pub struct AnnotatedParser +where + P: Parser, +{ + inner: P, + name: Option, + phantom: PhantomData<(I, O, E)>, +} + +impl Parser for AnnotatedParser +where + P: Parser, +{ + fn parse(&self, input: I) -> ParseResult { + self.inner.parse(input) + } + + fn name(&self) -> Option { + self.name.clone() + } +} + +impl AnnotatedParser +where + P: Parser, +{ + pub fn new(inner: P) -> Self { + Self { + inner, + name: None, + phantom: PhantomData, + } + } + + pub fn with_name(self, name: &str) -> Self { + Self { + name: Some(name.to_string()), + ..self + } + } +} diff --git a/src/lib.rs b/src/lib.rs index bfe9e72..681a09f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ #![allow(dead_code)] //TODO eventually turn this off +mod annotated; mod choice; mod combinators; mod map; diff --git a/src/parser.rs b/src/parser.rs index 1675d63..2b4f9cf 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -1,6 +1,4 @@ -use std::marker::PhantomData; - -use crate::{map, seq2, surrounded_by}; +use crate::{annotated::AnnotatedParser, map, seq2, surrounded_by}; pub type ParseResult = Result<(O, I), (E, I)>; @@ -20,28 +18,6 @@ where } } -pub struct NamedParser -where - P: Parser, -{ - inner: P, - name: String, - phantom: PhantomData<(I, O, E)>, -} - -impl Parser for NamedParser -where - P: Parser, -{ - fn parse(&self, input: I) -> ParseResult { - self.inner.parse(input) - } - - fn name(&self) -> Option { - Some(self.name.clone()) - } -} - pub trait ParserExtension: Parser { fn map(self, map_fn: F) -> impl Parser where @@ -52,15 +28,11 @@ pub trait ParserExtension: Parser { fn then_ignore>(self, next: P) -> impl Parser; fn ignore_then>(self, next: P) -> impl Parser; fn surrounded_by(self, surrounding: impl Parser) -> impl Parser; - fn to_named(self, name: &str) -> NamedParser + fn to_named(self, name: &str) -> AnnotatedParser where Self: Sized, { - NamedParser { - inner: self, - name: name.to_string(), - phantom: PhantomData, - } + AnnotatedParser::new(self).with_name(name) } }