libreda-stream-parser 0.2.0

Very simple parser generator for parsing data streams.
Documentation
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// SPDX-FileCopyrightText: 2023 Thomas Kramer
// SPDX-License-Identifier: GPL-3.0-or-later

//! A simple library for parsing data streams.
//!
//! Parsing is splitted into two tasks
//! * Splitting an iterator into tokens. This is done by a [`Lexer`].
//! * Processing the tokens: The 'Tokenized' struct provides helper functions for processing the stream of tokens.
//!
//! # Example
//! ```
//! use itertools::{Itertools, PeekingNext};
//! use libreda_stream_parser::*;
//!
//! struct ArrayLexer {}
//!
//! impl Lexer for ArrayLexer {
//!     type Char = char;
//!
//!     fn consume_next_token(
//!         &mut self,
//!         input: &mut (impl Iterator<Item = Self::Char> + PeekingNext),
//!         mut output: impl FnMut(Self::Char),
//!     ) -> Result<(), ParserError<char>> {
//!         // Skip whitespace.
//!         let _n = input.peeking_take_while(|c| c.is_whitespace()).count();
//!
//!         let is_terminal_char = |c: char| -> bool {
//!             let terminals = "[],";
//!             c.is_whitespace() || terminals.contains(c)
//!         };
//!
//!         if let Some(c) = input.next() {
//!             output(c);
//!             // Continue reading token if `c` was no terminal character.
//!             if !is_terminal_char(c) {
//!                 input
//!                     .peeking_take_while(|&c| !is_terminal_char(c))
//!                     .for_each(output);
//!             }
//!         }
//!
//!         Ok(())
//!     }
//! }
//!
//! /// Parse an array of the form `[1.0, 2, 3.1324]`.
//! fn parse_array(data: &str) -> Result<Vec<f64>, ParserError<char>> {
//!     let mut tk = tokenize(data.chars(), ArrayLexer {});
//!
//!     tk.advance()?;
//!
//!     let mut arr: Vec<f64> = vec![];
//!
//!     tk.expect_str("[")?;
//!
//!     loop {
//!         if tk.test_str("]")? {
//!             break;
//!         }
//!
//!         let num = tk.take_and_parse()?;
//!         arr.push(num);
//!
//!         tk.expect_str(",")?;
//!     }
//!
//!     Ok(arr)
//! }
//!
//! let data = r#"
//!     [
//!         1.23,
//!         2.34,
//!         3.456,
//!     ]
//! "#;
//!
//! let arr = parse_array(data).expect("parsing failed");
//!
//! assert_eq!(arr, vec![1.23, 2.34, 3.456]);
//! ```

#![deny(missing_docs)]

use std::error::Error;
use std::fmt;
use std::iter::Peekable;
use std::num::ParseIntError;
use std::str::FromStr;

use itertools::PeekingNext;

/// Partition an input stream into tokens.
/// The lexer consumes one token from an input stream in each call of `consume_next_token`.
pub trait Lexer {
    /// Character datatype used by this lexer. Typically, this might be `char` or `u8`.
    type Char;

    /// Consume the next token from the iterator.
    fn consume_next_token(
        &mut self,
        input: &mut (impl Iterator<Item = Self::Char> + PeekingNext),
        output: impl FnMut(Self::Char),
    ) -> Result<(), ParserError<Self::Char>>;
}

/// Provide sequential access to tokens that are created on the fly by
/// splitting characters at whitespace.
pub struct Tokenized<I, L>
where
    I: Iterator,
{
    /// Underlying iterator over characters.
    iter: I,
    /// Tokenizer/lexer.
    lexer: L,
    has_current: bool,
    current_token: Option<Vec<I::Item>>,
}

// TODO: Implementing `StreamingIterator` from `streaming_iterator` could be a good fit.
impl<I, L> Iterator for Tokenized<I, L>
where
    I: Iterator + PeekingNext,
    L: Lexer<Char = I::Item>,
    I::Item: PartialEq + Eq + Clone + Copy + 'static,
{
    type Item = Vec<I::Item>;

    fn next(&mut self) -> Option<Self::Item> {
        self.next_ref().map(|e| e.to_vec())
    }
}

impl<I, L> Tokenized<I, L>
where
    I: Iterator + PeekingNext,
    L: Lexer<Char = I::Item>,
    I::Item: PartialEq + Eq + Clone + Copy + 'static,
{
    /// Go to the next token and return a reference to it, if any.
    pub fn next_ref(&mut self) -> Option<&[I::Item]> {
        self.advance().ok().and_then(|_| self.current_token_ref())
    }

    /// Consume the current token and return it.
    /// Note that the current token is undefined before calling `advance` the first time.
    pub fn take(&mut self) -> Result<Vec<I::Item>, ParserError<I::Item>> {
        let s = self.current_token();
        self.advance()?;
        if let Some(s) = s {
            Ok(s)
        } else {
            Err(ParserError::UnexpectedEndOfFile)
        }
    }

    /// Advance to the next token.
    pub fn advance(&mut self) -> Result<(), ParserError<I::Item>> {
        let mut buffer = self.current_token.take().unwrap_or_default();

        buffer.clear();

        self.lexer
            .consume_next_token(&mut self.iter, |c| buffer.push(c))?;

        let has_next = !buffer.is_empty();

        if has_next {
            self.current_token = Some(buffer);
        }

        self.has_current = has_next;
        Ok(())
    }

    /// Access the current token by reference without consuming it.
    pub fn current_token_ref(&self) -> Option<&[I::Item]> {
        if self.has_current {
            self.current_token.as_deref()
        } else {
            None
        }
    }

    /// Get a clone of the current token without consuming it.
    pub fn current_token(&self) -> Option<Vec<I::Item>> {
        self.current_token_ref().map(|s| s.to_vec())
    }

    /// Test if the current token equals to the expected token.
    /// Returns `Ok(())` if the token matches and advances the iterator.
    /// Returns the actual token otherwise.
    /// Note that the current token is undefined before calling `advance` the first time.
    pub fn expect(
        &mut self,
        s: impl IntoIterator<Item = I::Item> + Clone,
    ) -> Result<(), ParserError<I::Item>> {
        match &self.current_token {
            None => Err(ParserError::UnexpectedEndOfFile)?,
            Some(token) => {
                if token.iter().copied().eq(s.clone()) {
                    self.advance()?;
                    Ok(())
                } else {
                    Err(ParserError::UnexpectedToken(
                        s.into_iter().collect(),
                        self.current_token().unwrap().to_vec(),
                    ))
                }
            }
        }
    }

    /// Test if the current token matches with the string.
    /// The token is consumed only if it matches.
    /// Note that the current token is undefined before calling `advance` the first time.
    pub fn test(&mut self, s: &[I::Item]) -> Result<bool, ParserError<I::Item>> {
        let result = self.peeking_test(s)?;
        if result {
            self.advance()?;
        }
        Ok(result)
    }

    /// Test if the current token matches with the string.
    /// The token is not consumed.
    /// Note that the current token is undefined before calling `advance` the first time.
    pub fn peeking_test(&mut self, s: &[I::Item]) -> Result<bool, ParserError<I::Item>> {
        if self.current_token.is_none() {
            Err(ParserError::UnexpectedEndOfFile)?;
        }

        if self.current_token_ref() == Some(s) {
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Consume all tokens until and including `s`.
    pub fn skip_until(&mut self, s: &[I::Item]) -> Result<(), ParserError<I::Item>> {
        while !self.test(s)? {
            self.advance()?;
        }
        Ok(())
    }
}
impl<I, L> Tokenized<I, L>
where
    I: Iterator<Item = char> + PeekingNext,
    L: Lexer<Char = I::Item>,
{
    /// Get a clone of the current token without consuming it.
    /// Note that the current token is undefined before calling `advance` the first time.
    pub fn current_token_str(&self) -> Option<String> {
        self.current_token_ref().map(|s| s.iter().collect())
    }

    /// Consume the current token, convert it to a string and return it.
    pub fn take_str(&mut self) -> Result<String, ParserError<I::Item>> {
        let s = self.current_token_str();
        self.advance()?;
        if let Some(s) = s {
            Ok(s)
        } else {
            Err(ParserError::UnexpectedEndOfFile)
        }
    }

    /// Consume a token and try to convert it to `F` it using `FromStr`.
    /// Note that the current token is undefined before calling `advance` the first time.
    pub fn take_and_parse<F: FromStr>(&mut self) -> Result<F, ParserError<I::Item>> {
        let result = if let Some(token) = self.current_token_ref() {
            let string: String = token.iter().collect();

            if let Ok(parsed) = string.parse::<F>() {
                Ok(parsed)
            } else {
                Err(ParserError::InvalidLiteral(token.to_vec()))
            }
        } else {
            Err(ParserError::UnexpectedEndOfFile)
        };

        self.advance()?;

        result
    }

    /// Test if the current token equals to the expected token.
    /// Returns `Ok(())` if the token matches and advances the iterator.
    /// Returns the actual token otherwise.
    /// Note that the current token is undefined before calling `advance` the first time.
    pub fn expect_str(&mut self, s: &str) -> Result<(), ParserError<I::Item>> {
        match &self.current_token {
            None => Err(ParserError::UnexpectedEndOfFile)?,
            Some(token) => {
                if token.iter().copied().eq(s.chars()) {
                    self.advance()?;
                    Ok(())
                } else {
                    Err(ParserError::UnexpectedToken(
                        s.chars().collect(),
                        self.current_token().unwrap().to_vec(),
                    ))
                }
            }
        }
    }

    /// Test if the current token matches with the string.
    /// The token is consumed only if it matches.
    pub fn test_str(&mut self, s: &str) -> Result<bool, ParserError<I::Item>> {
        let result = self.peeking_test_str(s)?;
        if result {
            self.advance()?;
        }
        Ok(result)
    }

    /// Test if the current token matches with the string.
    /// The token is not consumed.
    pub fn peeking_test_str(&mut self, s: &str) -> Result<bool, ParserError<I::Item>> {
        match &self.current_token {
            None => Err(ParserError::UnexpectedEndOfFile)?,
            Some(token) => Ok(token.iter().copied().eq(s.chars())),
        }
    }

    /// Consume all tokens until and including `s`.
    pub fn skip_until_str(&mut self, s: &str) -> Result<(), ParserError<I::Item>> {
        while !self.test_str(s)? {
            self.advance()?;
        }
        Ok(())
    }
}

/// Split a stream of characters into tokens separated by whitespace.
/// Comments are ignored.
pub fn tokenize<I, L>(iter: I, lexer: L) -> Tokenized<Peekable<I>, L>
where
    I: Iterator<Item = char>,
{
    Tokenized {
        iter: iter.peekable(),
        lexer,
        has_current: false,
        current_token: None,
    }
}

/// Error type issued from lexer and parser.
#[derive(Clone, Debug)]
pub enum ParserError<C: 'static> {
    /// Reached end of file before end of library arrived.
    UnexpectedEndOfFile,
    /// Expected and actual token.
    UnexpectedToken(Vec<C>, Vec<C>),
    /// Unknown literal. The literal is given as a string.
    InvalidLiteral(Vec<C>),
    /// Failed to parse an integer.
    ParseIntError(ParseIntError),
}

impl<C: 'static + fmt::Display + fmt::Debug> Error for ParserError<C> {}

impl<C: fmt::Display + fmt::Debug> fmt::Display for ParserError<C> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParserError::UnexpectedEndOfFile => write!(f, "Unexpected end of file."),
            ParserError::UnexpectedToken(actual, exp) => {
                write!(f, "Unexpected token. '{actual:?}' instead of '{exp:?}'")
            }
            ParserError::InvalidLiteral(n) => write!(f, "Invalid literal: '{n:?}'."),
            ParserError::ParseIntError(e) => write!(f, "Illegal integer: '{e:?}'"),
        }
    }
}

impl<C> From<ParseIntError> for ParserError<C> {
    fn from(e: ParseIntError) -> Self {
        Self::ParseIntError(e)
    }
}

#[test]
fn test_tokenize_simple() {
    use itertools::Itertools;

    struct MyLexer {}

    impl Lexer for MyLexer {
        type Char = char;

        fn consume_next_token(
            &mut self,
            input: &mut (impl Iterator<Item = Self::Char> + PeekingNext),
            mut output: impl FnMut(Self::Char),
        ) -> Result<(), ParserError<char>> {
            if let Some(c) = input.next() {
                output(c);
                let take_whitespace = c.is_whitespace();

                input
                    .peeking_take_while(|c| c.is_whitespace() == take_whitespace)
                    .for_each(output);
            }

            Ok(())
        }
    }

    let data = "here \n are \t some words  ";

    let mut tk = tokenize(data.chars(), MyLexer {});

    tk.advance().unwrap();
    tk.expect_str("here").unwrap();
    tk.next();
    tk.expect_str("are").unwrap();
    tk.next();
    tk.expect_str("some").unwrap();
    tk.next();
    tk.expect_str("words").unwrap();
}