Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 14 additions & 17 deletions compiler/rustc_lexer/src/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::str::Chars;

/// Peekable iterator over a char sequence.
///
/// Next characters can be peeked via `nth_char` method,
/// Next characters can be peeked via `peek` method,
/// and position can be shifted forward via `bump` method.
pub(crate) struct Cursor<'a> {
initial_len: usize,
Expand Down Expand Up @@ -37,22 +37,17 @@ impl<'a> Cursor<'a> {
}
}

/// Returns nth character relative to the current cursor position.
/// If requested position doesn't exist, `EOF_CHAR` is returned.
/// Peeks the next symbol from the input stream without consuming it.
/// If it doesn't exist, `EOF_CHAR` is returned.
/// However, getting `EOF_CHAR` doesn't always mean actual end of file,
/// it should be checked with `is_eof` method.
fn nth_char(&self, n: usize) -> char {
self.chars().nth(n).unwrap_or(EOF_CHAR)
}

/// Peeks the next symbol from the input stream without consuming it.
pub(crate) fn first(&self) -> char {
self.nth_char(0)
pub(crate) fn peek(&self) -> char {
self.chars.clone().nth(0).unwrap_or(EOF_CHAR)
}

/// Peeks the second symbol from the input stream without consuming it.
pub(crate) fn second(&self) -> char {
self.nth_char(1)
pub(crate) fn peek_second(&self) -> char {
self.chars.clone().nth(1).unwrap_or(EOF_CHAR)
}

/// Checks if there is nothing more to consume.
Expand All @@ -65,11 +60,6 @@ impl<'a> Cursor<'a> {
self.initial_len - self.chars.as_str().len()
}

/// Returns a `Chars` iterator over the remaining characters.
fn chars(&self) -> Chars<'a> {
self.chars.clone()
}

/// Moves to the next character.
pub(crate) fn bump(&mut self) -> Option<char> {
let c = self.chars.next()?;
Expand All @@ -81,4 +71,11 @@ impl<'a> Cursor<'a> {

Some(c)
}

/// Eats symbols while predicate returns true or until the end of file is reached.
pub(crate) fn bump_while(&mut self, mut predicate: impl FnMut(char) -> bool) {
while predicate(self.peek()) && !self.is_eof() {
self.bump();
}
}
}
Loading