From 5141cdadd99d6106c855b58d2e6e6576f56a6041 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Tue, 30 Jan 2024 00:03:02 -0800 Subject: [PATCH] Generalized to AnnotatedParser --- src/annotated.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/parser.rs | 34 +++------------------------------- 3 files changed, 49 insertions(+), 31 deletions(-) create mode 100644 src/annotated.rs 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) } }