kalosm_sample/structured_parser/
then.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use std::sync::Arc;

use crate::{CreateParserState, ParseResult, ParseStatus, Parser};

/// State of a sequence parser.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum SequenceParserState<P1, P2, O1> {
    /// The first parser is incomplete.
    FirstParser(P1),
    /// The first parser is finished, and the second parser is incomplete.
    SecondParser(P2, O1),
}

impl<P1, P2, O1> SequenceParserState<P1, P2, O1> {
    /// Create a new sequence parser state.
    pub fn new(state1: P1) -> Self {
        Self::FirstParser(state1)
    }
}

impl<P1: Default, P2, O1> Default for SequenceParserState<P1, P2, O1> {
    fn default() -> Self {
        SequenceParserState::FirstParser(Default::default())
    }
}

impl<P1: CreateParserState, P2: CreateParserState> CreateParserState for SequenceParser<P1, P2> {
    fn create_parser_state(&self) -> <Self as Parser>::PartialState {
        SequenceParserState::FirstParser(self.parser1.create_parser_state())
    }
}

/// A parser for a sequence of two parsers.
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone)]
pub struct SequenceParser<P1, P2> {
    parser1: P1,
    parser2: P2,
}

impl<P1, P2> SequenceParser<P1, P2> {
    /// Create a new sequence parser.
    pub fn new(parser1: P1, parser2: P2) -> Self {
        Self { parser1, parser2 }
    }
}

impl<P1: Parser, P2: CreateParserState> Parser for SequenceParser<P1, P2> {
    type Output = (P1::Output, P2::Output);
    type PartialState = SequenceParserState<P1::PartialState, P2::PartialState, P1::Output>;

    fn parse<'a>(
        &self,
        state: &Self::PartialState,
        input: &'a [u8],
    ) -> crate::ParseResult<ParseStatus<'a, Self::PartialState, Self::Output>> {
        match state {
            SequenceParserState::FirstParser(p1) => {
                let result = self.parser1.parse(p1, input)?;
                match result {
                    ParseStatus::Finished {
                        result: o1,
                        remaining,
                    } => {
                        let second_parser_state = self.parser2.create_parser_state();
                        let result = self.parser2.parse(&second_parser_state, remaining)?;
                        match result {
                            ParseStatus::Finished { result, remaining } => {
                                Ok(ParseStatus::Finished {
                                    result: (o1, result),
                                    remaining,
                                })
                            }
                            ParseStatus::Incomplete {
                                new_state: p2,
                                required_next,
                            } => {
                                let new_state = SequenceParserState::SecondParser(p2, o1);
                                Ok(ParseStatus::Incomplete {
                                    new_state,
                                    required_next,
                                })
                            }
                        }
                    }
                    ParseStatus::Incomplete {
                        new_state: p1,
                        required_next,
                    } => {
                        let new_state = SequenceParserState::FirstParser(p1);
                        Ok(ParseStatus::Incomplete {
                            new_state,
                            required_next,
                        })
                    }
                }
            }
            SequenceParserState::SecondParser(p2, o1) => {
                let result = self.parser2.parse(p2, input)?;
                match result {
                    ParseStatus::Finished { result, remaining } => Ok(ParseStatus::Finished {
                        result: (o1.clone(), result),
                        remaining,
                    }),
                    ParseStatus::Incomplete {
                        new_state: p2,
                        required_next,
                    } => {
                        let new_state = SequenceParserState::SecondParser(p2, o1.clone());
                        Ok(ParseStatus::Incomplete {
                            new_state,
                            required_next,
                        })
                    }
                }
            }
        }
    }
}

#[test]
fn sequence_parser() {
    use crate::{LiteralParser, LiteralParserOffset};
    let parser = SequenceParser {
        parser1: LiteralParser::new("Hello, "),
        parser2: LiteralParser::new("world!"),
    };
    let state = SequenceParserState::FirstParser(LiteralParserOffset::default());
    assert_eq!(
        parser.parse(&state, b"Hello, world!"),
        Ok(ParseStatus::Finished {
            result: ((), ()),
            remaining: &[]
        })
    );
    assert_eq!(
        parser.parse(&state, b"Hello, "),
        Ok(ParseStatus::Incomplete {
            new_state: SequenceParserState::SecondParser(LiteralParserOffset::new(0), ()),
            required_next: "world!".into()
        })
    );
    assert_eq!(
        parser.parse(
            &parser
                .parse(&state, b"Hello, ")
                .unwrap()
                .unwrap_incomplete()
                .0,
            b"world!"
        ),
        Ok(ParseStatus::Finished {
            result: ((), ()),
            remaining: &[]
        })
    );
    assert!(parser.parse(&state, b"Goodbye, world!").is_err(),);
}

/// State of a then lazy parser.
#[derive(Debug, PartialEq, Eq)]
pub enum ThenLazyParserState<P1: Parser, P2: Parser> {
    /// The first parser is incomplete.
    FirstParser(P1::PartialState),
    /// The first parser is finished, and the second parser is incomplete.
    SecondParser {
        /// The result of the first parser.
        first_output: P1::Output,
        /// The second parser.
        second_parser: Arc<P2>,
        /// The state of the second parser.
        second_state: P2::PartialState,
    },
}

impl<P1: Parser, P2: Parser> Clone for ThenLazyParserState<P1, P2>
where
    P1::PartialState: Clone,
    P2::PartialState: Clone,
{
    fn clone(&self) -> Self {
        match self {
            Self::FirstParser(first_state) => Self::FirstParser(first_state.clone()),
            Self::SecondParser {
                first_output,
                second_parser,
                second_state,
            } => Self::SecondParser {
                first_output: first_output.clone(),
                second_parser: second_parser.clone(),
                second_state: second_state.clone(),
            },
        }
    }
}

impl<P1: Parser, P2: Parser> ThenLazyParserState<P1, P2> {
    /// Create a new then lazy parser state.
    pub fn new(first_state: P1::PartialState) -> Self {
        Self::FirstParser(first_state)
    }
}

impl<P1: Parser, P2: Parser> Default for ThenLazyParserState<P1, P2>
where
    P1::PartialState: Default,
{
    fn default() -> Self {
        Self::FirstParser(Default::default())
    }
}

/// A parser that is initialized lazily based on the state of the previous parser.
pub struct ThenLazy<P1, F> {
    parser1: P1,
    parser_fn: F,
}

impl<P1: Parser, P2: CreateParserState, F: Fn(&P1::Output) -> P2> ThenLazy<P1, F> {
    /// Create a new parser that is lazily initialized based on the output of the first parser.
    pub fn new(parser1: P1, parser_fn: F) -> Self {
        Self { parser1, parser_fn }
    }
}

impl<P1: CreateParserState, P2: CreateParserState, F: Fn(&P1::Output) -> P2> CreateParserState
    for ThenLazy<P1, F>
{
    fn create_parser_state(&self) -> <Self as Parser>::PartialState {
        ThenLazyParserState::FirstParser(self.parser1.create_parser_state())
    }
}

impl<P1: Parser, P2: CreateParserState, F: Fn(&P1::Output) -> P2> Parser for ThenLazy<P1, F> {
    type Output = (P1::Output, P2::Output);
    type PartialState = ThenLazyParserState<P1, P2>;

    fn parse<'a>(
        &self,
        state: &Self::PartialState,
        input: &'a [u8],
    ) -> ParseResult<ParseStatus<'a, Self::PartialState, Self::Output>> {
        match state {
            ThenLazyParserState::FirstParser(p1) => {
                let result = self.parser1.parse(p1, input)?;
                match result {
                    ParseStatus::Finished {
                        result: o1,
                        remaining,
                    } => {
                        let parser2 = Arc::new((self.parser_fn)(&o1));
                        let second_parser_state = parser2.create_parser_state();
                        let result = parser2.parse(&second_parser_state, remaining)?;
                        match result {
                            ParseStatus::Finished { result, remaining } => {
                                Ok(ParseStatus::Finished {
                                    result: (o1, result),
                                    remaining,
                                })
                            }
                            ParseStatus::Incomplete {
                                new_state: p2,
                                required_next,
                            } => {
                                let new_state = ThenLazyParserState::SecondParser {
                                    first_output: o1.clone(),
                                    second_parser: parser2.clone(),
                                    second_state: p2,
                                };
                                Ok(ParseStatus::Incomplete {
                                    new_state,
                                    required_next,
                                })
                            }
                        }
                    }
                    ParseStatus::Incomplete {
                        new_state: p1,
                        required_next,
                    } => {
                        let new_state = ThenLazyParserState::FirstParser(p1);
                        Ok(ParseStatus::Incomplete {
                            new_state,
                            required_next,
                        })
                    }
                }
            }
            ThenLazyParserState::SecondParser {
                first_output,
                second_parser,
                second_state,
            } => {
                let result = second_parser.parse(second_state, input)?;
                match result {
                    ParseStatus::Finished { result, remaining } => Ok(ParseStatus::Finished {
                        result: (first_output.clone(), result),
                        remaining,
                    }),
                    ParseStatus::Incomplete {
                        new_state: p2,
                        required_next,
                    } => {
                        let new_state = ThenLazyParserState::SecondParser {
                            first_output: first_output.clone(),
                            second_parser: second_parser.clone(),
                            second_state: p2,
                        };
                        Ok(ParseStatus::Incomplete {
                            new_state,
                            required_next,
                        })
                    }
                }
            }
        }
    }
}