markab_parser/order_parser/
parser.rs1use crate::{
2 equal::Equal,
3 map_parser::MapParser,
4 order_parser::{
5 OrderParserError,
6 OrderParserRequirement,
7 },
8 Parser,
9};
10use either::{
11 Either,
12 Left,
13 Right,
14};
15use std::marker::PhantomData;
16
17#[derive(Debug)]
18pub struct OrderParser<'a, P1, P2>
19where
20 P1: Parser<'a>,
21 P2: Parser<'a>,
22{
23 first: P1,
24 second: P2,
25 _a: PhantomData<&'a ()>,
26}
27
28impl<'a, P1, P2> OrderParser<'a, P1, P2>
29where
30 P1: Parser<'a>,
31 P2: Parser<'a>,
32{
33 pub fn new(first: P1, second: P2) -> Self
34 {
35 Self {
36 first,
37 second,
38 _a: PhantomData,
39 }
40 }
41}
42
43impl<'a, P1, P2> OrderParser<'a, P1, P2>
44where
45 P1: Parser<'a>,
46 P2: Parser<'a>,
47 P2::Output: Equal<P1::Output>,
48{
49 pub fn merge(self) -> MapParser<'a, Self, P1::Output>
50 {
51 self.map(&|res| {
52 match res
53 {
54 Left(first) => first,
55 Right(second) => second.ident(),
56 }
57 })
58 }
59}
60
61impl<'a, P1, P2> Parser<'a> for OrderParser<'a, P1, P2>
62where
63 P1: Parser<'a>,
64 P2: Parser<'a>,
65{
66 type Error = OrderParserError<'a, P1, P2>;
67 type Output = Either<P1::Output, P2::Output>;
68 type Requirement = OrderParserRequirement<'a, P1, P2>;
69 type RequirementContext = ();
70
71 fn parse(&self, src: &'a str, pos: &mut usize) -> Result<Self::Output, Self::Error>
72 {
73 let from = *pos;
74 let first = match self.first.parse(src, pos)
75 {
76 Ok(res) => return Ok(Left(res)),
77 Err(err) => err,
78 };
79 let second = match self.second.parse(src, pos)
80 {
81 Ok(res) => return Ok(Right(res)),
82 Err(err) => err,
83 };
84 Err(OrderParserError::new(
85 from,
86 self.requirement(None),
87 (first, second),
88 ))
89 }
90
91 fn skip(&self, src: &'a str, pos: &mut usize) -> Result<(), Self::Error>
92 {
93 let from = *pos;
94 match self.first.skip(src, pos)
95 {
96 Ok(()) => Ok(()),
97 Err(first) =>
98 {
99 self.second.skip(src, pos).map_err(|second| {
100 OrderParserError::new(from, self.requirement(None), (first, second))
101 })
102 }
103 }
104 }
105
106 fn requirement(&self, _: Option<&Self::RequirementContext>) -> Self::Requirement
107 {
108 OrderParserRequirement::new(self.first.requirement(None), self.second.requirement(None))
109 }
110}