Skip to main content

mago_syntax/parser/
stream.rs

1use std::fmt::Debug;
2
3use mago_allocator::prelude::*;
4
5use mago_database::file::FileId;
6use mago_database::file::HasFileId;
7use mago_span::Position;
8use mago_span::Span;
9use mago_syntax_core::parser::LookaheadBuf;
10
11use crate::cst::sequence::Sequence;
12use crate::cst::trivia::Trivia;
13use crate::cst::trivia::TriviaKind;
14use crate::error::Expected;
15use crate::error::ParseError;
16use crate::error::SyntaxError;
17use crate::lexer::Lexer;
18use crate::token::Token;
19use crate::token::TokenKind;
20
21#[derive(Debug)]
22pub struct TokenStream<'input, 'arena, A>
23where
24    'input: 'arena,
25    A: Arena,
26{
27    arena: &'arena A,
28    lexer: Lexer<'input>,
29    buffer: LookaheadBuf<Token<'input>, 4>,
30    trivia: Vec<'arena, Trivia<'input>, A>,
31    position: Position,
32    file_id: FileId,
33    elide_detached_whitespace: bool,
34    after_comment: bool,
35}
36
37impl<'input, 'arena, A> TokenStream<'input, 'arena, A>
38where
39    A: Arena,
40{
41    pub fn new(
42        arena: &'arena A,
43        lexer: Lexer<'input>,
44        elide_detached_whitespace: bool,
45    ) -> TokenStream<'input, 'arena, A> {
46        let position = lexer.current_position();
47        let file_id_cached = lexer.file_id();
48
49        TokenStream {
50            arena,
51            lexer,
52            buffer: LookaheadBuf::new(),
53            trivia: Vec::new_in(arena),
54            position,
55            file_id: file_id_cached,
56            elide_detached_whitespace,
57            after_comment: false,
58        }
59    }
60
61    /// Returns the current position of the stream within the source file.
62    ///
63    /// This position represents the end location of the most recently
64    /// consumed significant token via `advance()` or `consume()`.
65    #[inline]
66    #[must_use]
67    pub const fn current_position(&self) -> Position {
68        self.position
69    }
70
71    /// Returns whether the stream has consumed all tokens up to EOF.
72    ///
73    /// # Errors
74    ///
75    /// Returns a [`SyntaxError`] if the lexer fails to produce the next token.
76    #[inline]
77    pub fn has_reached_eof(&mut self) -> Result<bool, SyntaxError> {
78        Ok(self.fill_buffer(1)?.is_none())
79    }
80
81    /// Consumes and returns the next significant token.
82    ///
83    /// # Errors
84    ///
85    /// Returns a [`ParseError`] if EOF is reached or a lexer error occurs.
86    #[inline]
87    pub fn consume(&mut self) -> Result<Token<'input>, ParseError> {
88        match self.advance() {
89            Some(Ok(token)) => Ok(token),
90            Some(Err(error)) => Err(error.into()),
91            None => Err(self.unexpected(None, &[])),
92        }
93    }
94
95    /// Consumes the next token only if it matches the expected kind.
96    ///
97    /// Returns the token if it matches, otherwise returns an error.
98    ///
99    /// # Errors
100    ///
101    /// Returns a [`ParseError`] if the next token's kind does not match `kind`, or if EOF is reached.
102    #[inline]
103    pub fn eat(&mut self, kind: TokenKind) -> Result<Token<'input>, ParseError> {
104        // Fast path: head already buffered. Avoids the Result<Option<...>>
105        // round trip from `peek_kind` plus a follow-up `lookahead` on the
106        // happy path.
107        if let Some(token) = self.buffer.get(0) {
108            if token.kind == kind {
109                let _ = self.buffer.pop_front();
110
111                self.position = Position::new(token.start.offset + token.value.len() as u32);
112                return Ok(token);
113            }
114
115            return Err(self.unexpected_kind(Some(token), kind));
116        }
117
118        // Slow path: buffer empty, fill it.
119        let current_kind = self.peek_kind(0)?;
120        match current_kind {
121            Some(k) if k == kind => self.consume(),
122            Some(_) => match self.lookahead(0)? {
123                Some(token) => Err(self.unexpected_kind(Some(token), kind)),
124                None => Err(self.unexpected_kind(None, kind)),
125            },
126            None => Err(self.unexpected_kind(None, kind)),
127        }
128    }
129
130    /// Consumes and returns the span of the next significant token.
131    ///
132    /// This is a convenience method equivalent to `consume()?.span_for(file_id())`.
133    ///
134    /// # Errors
135    ///
136    /// Returns a [`ParseError`] if EOF is reached or a lexer error occurs.
137    #[inline]
138    pub fn consume_span(&mut self) -> Result<Span, ParseError> {
139        let file_id = self.file_id();
140        self.consume().map(|t| t.span_for(file_id))
141    }
142
143    /// Consumes the next token only if it matches the expected kind, returning its span.
144    ///
145    /// This is a convenience method equivalent to `eat(kind)?.span_for(file_id())`.
146    ///
147    /// # Errors
148    ///
149    /// Returns a [`ParseError`] if the next token's kind does not match `kind`, or if EOF is reached.
150    #[inline]
151    pub fn eat_span(&mut self, kind: TokenKind) -> Result<Span, ParseError> {
152        let file_id = self.file_id();
153        self.eat(kind).map(|t| t.span_for(file_id))
154    }
155
156    /// Advances the stream to the next token in the input source code and returns it.
157    ///
158    /// If the stream has already read the entire input source code, this method will return `None`.
159    ///
160    /// # Returns
161    ///
162    /// The next token in the input source code, or `None` if the lexer has reached the end of the input.
163    #[inline]
164    pub fn advance(&mut self) -> Option<Result<Token<'input>, SyntaxError>> {
165        match self.fill_buffer(1) {
166            Ok(Some(_)) => {
167                if let Some(token) = self.buffer.pop_front() {
168                    // Compute end position from start + value length
169                    self.position = Position::new(token.start.offset + token.value.len() as u32);
170                    Some(Ok(token))
171                } else {
172                    None
173                }
174            }
175            Ok(None) => None,
176            Err(error) => Some(Err(error)),
177        }
178    }
179
180    /// Checks if the next token matches the given kind without consuming it.
181    ///
182    /// Returns `false` if at EOF.
183    ///
184    /// # Errors
185    ///
186    /// Returns a [`ParseError`] if the lexer fails to produce the next token.
187    #[inline]
188    pub fn is_at(&mut self, kind: TokenKind) -> Result<bool, ParseError> {
189        if let Some(token) = self.buffer.get(0) {
190            return Ok(token.kind == kind);
191        }
192
193        Ok(self.peek_kind(0)? == Some(kind))
194    }
195
196    /// Peeks at the nth (0-indexed) significant token ahead without consuming it.
197    ///
198    /// Returns `Ok(None)` if EOF is reached before the nth token.
199    ///
200    /// # Errors
201    ///
202    /// Returns a [`ParseError`] if the lexer fails to produce a token while filling the lookahead buffer.
203    #[inline]
204    pub fn lookahead(&mut self, n: usize) -> Result<Option<Token<'input>>, ParseError> {
205        if n < self.buffer.len() {
206            return Ok(self.buffer.get(n));
207        }
208
209        match self.fill_buffer(n + 1) {
210            Ok(Some(_)) => Ok(self.buffer.get(n)),
211            Ok(None) => Ok(None),
212            Err(error) => Err(error.into()),
213        }
214    }
215
216    /// Peeks at the kind of the nth (0-indexed) significant token ahead.
217    ///
218    /// More efficient than `lookahead(n)?.map(|t| t.kind)` as it avoids
219    /// copying the full token when only the kind is needed.
220    ///
221    /// # Errors
222    ///
223    /// Returns a [`ParseError`] if the lexer fails to produce a token while filling the lookahead buffer.
224    #[inline]
225    pub fn peek_kind(&mut self, n: usize) -> Result<Option<TokenKind>, ParseError> {
226        if n < self.buffer.len() {
227            return Ok(self.buffer.get(n).map(|t| t.kind));
228        }
229
230        match self.fill_buffer(n + 1) {
231            Ok(Some(_)) => Ok(self.buffer.get(n).map(|t| t.kind)),
232            Ok(None) => Ok(None),
233            Err(error) => Err(error.into()),
234        }
235    }
236
237    /// Creates a `ParseError` for an unexpected token or EOF, given one or more expected kinds.
238    #[inline]
239    #[must_use]
240    pub fn unexpected(&self, found: Option<Token<'_>>, expected: &'static [TokenKind]) -> ParseError {
241        self.unexpected_with(found, Expected::OneOf(expected))
242    }
243
244    /// Creates a `ParseError` for an unexpected token or EOF when a single, runtime-known kind was expected.
245    #[inline]
246    #[must_use]
247    pub fn unexpected_kind(&self, found: Option<Token<'_>>, expected: TokenKind) -> ParseError {
248        self.unexpected_with(found, Expected::Exactly(expected))
249    }
250
251    #[inline]
252    #[must_use]
253    fn unexpected_with(&self, found: Option<Token<'_>>, expected: Expected) -> ParseError {
254        if let Some(token) = found {
255            ParseError::UnexpectedToken(expected, token.kind, token.span_for(self.file_id()))
256        } else {
257            ParseError::UnexpectedEndOfFile(expected, self.file_id(), self.current_position())
258        }
259    }
260
261    /// Consumes the comments collected by the lexer and returns them.
262    #[inline]
263    pub fn get_trivia(&mut self) -> Sequence<'arena, Trivia<'arena>> {
264        let mut trivia = Vec::new_in(self.arena);
265        std::mem::swap(&mut self.trivia, &mut trivia);
266
267        Sequence::new(trivia)
268    }
269
270    /// Fills the token buffer until at least `n` tokens are available, unless the lexer returns EOF.
271    ///
272    /// Trivia tokens are collected separately and are not stored in the main token buffer.
273    #[inline]
274    fn fill_buffer(&mut self, n: usize) -> Result<Option<usize>, SyntaxError> {
275        if self.buffer.len() >= n {
276            return Ok(Some(n));
277        }
278
279        self.fill_buffer_slow(n)
280    }
281
282    #[inline(never)]
283    fn fill_buffer_slow(&mut self, n: usize) -> Result<Option<usize>, SyntaxError> {
284        while self.buffer.len() < n {
285            match self.lexer.advance() {
286                Some(result) => {
287                    let token = result?;
288                    let trivia_kind = match token.kind {
289                        TokenKind::Whitespace => Some(TriviaKind::WhiteSpace),
290                        TokenKind::HashComment => Some(TriviaKind::HashComment),
291                        TokenKind::SingleLineComment => Some(TriviaKind::SingleLineComment),
292                        TokenKind::MultiLineComment => Some(TriviaKind::MultiLineComment),
293                        TokenKind::DocBlockComment => Some(TriviaKind::DocBlockComment),
294                        _ => None,
295                    };
296
297                    if let Some(kind) = trivia_kind {
298                        if kind == TriviaKind::WhiteSpace {
299                            if self.after_comment || !self.elide_detached_whitespace {
300                                self.trivia.push(Trivia {
301                                    kind,
302                                    span: token.span_for(self.file_id),
303                                    value: token.value,
304                                });
305                            }
306                        } else {
307                            self.after_comment = true;
308                            self.trivia.push(Trivia { kind, span: token.span_for(self.file_id), value: token.value });
309                        }
310
311                        continue;
312                    }
313
314                    self.after_comment = false;
315                    self.buffer.push_back(token);
316                }
317                None => return Ok(None),
318            }
319        }
320
321        Ok(Some(n))
322    }
323}
324
325impl<A> HasFileId for TokenStream<'_, '_, A>
326where
327    A: Arena,
328{
329    #[inline]
330    fn file_id(&self) -> FileId {
331        self.file_id
332    }
333}