From 918e3d042b24a4a767a2fae6cae0027ccc57a004 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Sat, 27 Jan 2024 16:16:54 -0800 Subject: [PATCH] Parser traits in submodule --- src/lib.rs | 46 ++-------------------------------------------- src/parser.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 44 deletions(-) create mode 100644 src/parser.rs diff --git a/src/lib.rs b/src/lib.rs index 9f2e596..a60747e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,59 +2,17 @@ mod choice; mod combinators; mod map; +mod parser; mod primitives; mod sequence; pub use choice::*; pub use combinators::*; pub use map::*; +pub use parser::{ParseResult, Parser, ParserExtension}; pub use primitives::*; pub use sequence::*; -type ParseResult = Result<(O, I), (E, I)>; - -pub trait Parser { - fn parse(&self, input: I) -> ParseResult; -} - -impl Parser for F -where - F: Fn(I) -> ParseResult, -{ - fn parse(&self, input: I) -> ParseResult { - self(input) - } -} - -pub trait ParserExtension: Parser { - fn map(self, map_fn: F) -> impl Parser - where - F: Fn(O) -> O2; - - fn to(self, item: O2) -> impl Parser; - fn then>(self, next: P) -> impl Parser; -} - -impl ParserExtension for T -where - T: Parser, -{ - fn map(self, map_fn: F) -> impl Parser - where - F: Fn(O) -> O2, - { - map(self, map_fn) - } - - fn to(self, item: O2) -> impl Parser { - self.map(move |_| item.clone()) - } - - fn then>(self, next: P) -> impl Parser { - seq2(self, next) - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/parser.rs b/src/parser.rs new file mode 100644 index 0000000..14ab5a5 --- /dev/null +++ b/src/parser.rs @@ -0,0 +1,45 @@ +use crate::{map, seq2}; + +pub type ParseResult = Result<(O, I), (E, I)>; + +pub trait Parser { + fn parse(&self, input: I) -> ParseResult; +} + +impl Parser for F +where + F: Fn(I) -> ParseResult, +{ + fn parse(&self, input: I) -> ParseResult { + self(input) + } +} + +pub trait ParserExtension: Parser { + fn map(self, map_fn: F) -> impl Parser + where + F: Fn(O) -> O2; + + fn to(self, item: O2) -> impl Parser; + fn then>(self, next: P) -> impl Parser; +} + +impl ParserExtension for T +where + T: Parser, +{ + fn map(self, map_fn: F) -> impl Parser + where + F: Fn(O) -> O2, + { + map(self, map_fn) + } + + fn to(self, item: O2) -> impl Parser { + self.map(move |_| item.clone()) + } + + fn then>(self, next: P) -> impl Parser { + seq2(self, next) + } +}