Skip to main content

skullbrain_lexer/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod lexer;
4mod token;
5
6#[cfg(test)]
7mod tests;
8
9use std::iter::FusedIterator;
10
11pub(crate) use grammar::*;
12pub(crate) use lexer::*;
13pub use token::*;
14
15/// Provides constants of language tokens, particularly keywords and special symbols.
16pub mod grammar {
17    #![allow(missing_docs)]
18    include!(concat!(env!("OUT_DIR"), "/grammar.rs"));
19}
20
21/// Traverses a character stream and produces tokens.
22pub struct Lexer<I>
23where
24    I: Iterator<Item = char> + FusedIterator,
25{
26    cursor: LexerCursor<I>,
27    buffered_token: Option<Token>,
28}
29
30impl<I> Lexer<I>
31where
32    I: Iterator<Item = char> + FusedIterator,
33{
34    /// Creates a new Lexer that will process the given character iterator.
35    pub fn new(iter: I) -> Self {
36        Self {
37            cursor: LexerCursor::new(iter),
38            buffered_token: None,
39        }
40    }
41}
42
43impl<I> Iterator for Lexer<I>
44where
45    I: Iterator<Item = char> + FusedIterator,
46{
47    type Item = Token;
48
49    /// Returns the next token in the stream.
50    ///
51    /// This method properly handles the cursor's tuple return type by:
52    /// 1. First returning any buffered token from previous iterations
53    /// 2. When processing new tokens from the cursor:
54    ///    - If there's only one token, return it directly
55    ///    - If there's a pair (token, unknown_token), buffer the token and return the unknown_token first
56    fn next(&mut self) -> Option<Self::Item> {
57        match self.buffered_token.take() {
58            Some(tok) => Some(tok),
59            None => match self.cursor.next()? {
60                (tok, unknown_token) if unknown_token.is_none() => Some(tok),
61                (tok, unknown_token) => {
62                    debug_assert!(self.buffered_token.is_none());
63                    self.buffered_token = Some(tok);
64                    unknown_token
65                }
66            },
67        }
68    }
69}