mirror of
https://github.com/astral-sh/ruff.git
synced 2025-07-19 02:55:20 +00:00
Maintain synchronicity between the lexer and the parser (#11457)
## Summary This PR updates the entire parser stack in multiple ways: ### Make the lexer lazy * https://github.com/astral-sh/ruff/pull/11244 * https://github.com/astral-sh/ruff/pull/11473 Previously, Ruff's lexer would act as an iterator. The parser would collect all the tokens in a vector first and then process the tokens to create the syntax tree. The first task in this project is to update the entire parsing flow to make the lexer lazy. This includes the `Lexer`, `TokenSource`, and `Parser`. For context, the `TokenSource` is a wrapper around the `Lexer` to filter out the trivia tokens[^1]. Now, the parser will ask the token source to get the next token and only then the lexer will continue and emit the token. This means that the lexer needs to be aware of the "current" token. When the `next_token` is called, the current token will be updated with the newly lexed token. The main motivation to make the lexer lazy is to allow re-lexing a token in a different context. This is going to be really useful to make the parser error resilience. For example, currently the emitted tokens remains the same even if the parser can recover from an unclosed parenthesis. This is important because the lexer emits a `NonLogicalNewline` in parenthesized context while a normal `Newline` in non-parenthesized context. This different kinds of newline is also used to emit the indentation tokens which is important for the parser as it's used to determine the start and end of a block. Additionally, this allows us to implement the following functionalities: 1. Checkpoint - rewind infrastructure: The idea here is to create a checkpoint and continue lexing. At a later point, this checkpoint can be used to rewind the lexer back to the provided checkpoint. 2. Remove the `SoftKeywordTransformer` and instead use lookahead or speculative parsing to determine whether a soft keyword is a keyword or an identifier 3. Remove the `Tok` enum. The `Tok` enum represents the tokens emitted by the lexer but it contains owned data which makes it expensive to clone. The new `TokenKind` enum just represents the type of token which is very cheap. This brings up a question as to how will the parser get the owned value which was stored on `Tok`. This will be solved by introducing a new `TokenValue` enum which only contains a subset of token kinds which has the owned value. This is stored on the lexer and is requested by the parser when it wants to process the data. For example:8196720f80/crates/ruff_python_parser/src/parser/expression.rs (L1260-L1262)
[^1]: Trivia tokens are `NonLogicalNewline` and `Comment` ### Remove `SoftKeywordTransformer` * https://github.com/astral-sh/ruff/pull/11441 * https://github.com/astral-sh/ruff/pull/11459 * https://github.com/astral-sh/ruff/pull/11442 * https://github.com/astral-sh/ruff/pull/11443 * https://github.com/astral-sh/ruff/pull/11474 For context, https://github.com/RustPython/RustPython/pull/4519/files#diff-5de40045e78e794aa5ab0b8aacf531aa477daf826d31ca129467703855408220 added support for soft keywords in the parser which uses infinite lookahead to classify a soft keyword as a keyword or an identifier. This is a brilliant idea as it basically wraps the existing Lexer and works on top of it which means that the logic for lexing and re-lexing a soft keyword remains separate. The change here is to remove `SoftKeywordTransformer` and let the parser determine this based on context, lookahead and speculative parsing. * **Context:** The transformer needs to know the position of the lexer between it being at a statement position or a simple statement position. This is because a `match` token starts a compound statement while a `type` token starts a simple statement. **The parser already knows this.** * **Lookahead:** Now that the parser knows the context it can perform lookahead of up to two tokens to classify the soft keyword. The logic for this is mentioned in the PR implementing it for `type` and `match soft keyword. * **Speculative parsing:** This is where the checkpoint - rewind infrastructure helps. For `match` soft keyword, there are certain cases for which we can't classify based on lookahead. The idea here is to create a checkpoint and keep parsing. Based on whether the parsing was successful and what tokens are ahead we can classify the remaining cases. Refer to #11443 for more details. If the soft keyword is being parsed in an identifier context, it'll be converted to an identifier and the emitted token will be updated as well. Refer8196720f80/crates/ruff_python_parser/src/parser/expression.rs (L487-L491)
. The `case` soft keyword doesn't require any special handling because it'll be a keyword only in the context of a match statement. ### Update the parser API * https://github.com/astral-sh/ruff/pull/11494 * https://github.com/astral-sh/ruff/pull/11505 Now that the lexer is in sync with the parser, and the parser helps to determine whether a soft keyword is a keyword or an identifier, the lexer cannot be used on its own. The reason being that it's not sensitive to the context (which is correct). This means that the parser API needs to be updated to not allow any access to the lexer. Previously, there were multiple ways to parse the source code: 1. Passing the source code itself 2. Or, passing the tokens Now that the lexer and parser are working together, the API corresponding to (2) cannot exists. The final API is mentioned in this PR description: https://github.com/astral-sh/ruff/pull/11494. ### Refactor the downstream tools (linter and formatter) * https://github.com/astral-sh/ruff/pull/11511 * https://github.com/astral-sh/ruff/pull/11515 * https://github.com/astral-sh/ruff/pull/11529 * https://github.com/astral-sh/ruff/pull/11562 * https://github.com/astral-sh/ruff/pull/11592 And, the final set of changes involves updating all references of the lexer and `Tok` enum. This was done in two-parts: 1. Update all the references in a way that doesn't require any changes from this PR i.e., it can be done independently * https://github.com/astral-sh/ruff/pull/11402 * https://github.com/astral-sh/ruff/pull/11406 * https://github.com/astral-sh/ruff/pull/11418 * https://github.com/astral-sh/ruff/pull/11419 * https://github.com/astral-sh/ruff/pull/11420 * https://github.com/astral-sh/ruff/pull/11424 2. Update all the remaining references to use the changes made in this PR For (2), there were various strategies used: 1. Introduce a new `Tokens` struct which wraps the token vector and add methods to query a certain subset of tokens. These includes: 1. `up_to_first_unknown` which replaces the `tokenize` function 2. `in_range` and `after` which replaces the `lex_starts_at` function where the former returns the tokens within the given range while the latter returns all the tokens after the given offset 2. Introduce a new `TokenFlags` which is a set of flags to query certain information from a token. Currently, this information is only limited to any string type token but can be expanded to include other information in the future as needed. https://github.com/astral-sh/ruff/pull/11578 3. Move the `CommentRanges` to the parsed output because this information is common to both the linter and the formatter. This removes the need for `tokens_and_ranges` function. ## Test Plan - [x] Update and verify the test snapshots - [x] Make sure the entire test suite is passing - [x] Make sure there are no changes in the ecosystem checks - [x] Run the fuzzer on the parser - [x] Run this change on dozens of open-source projects ### Running this change on dozens of open-source projects Refer to the PR description to get the list of open source projects used for testing. Now, the following tests were done between `main` and this branch: 1. Compare the output of `--select=E999` (syntax errors) 2. Compare the output of default rule selection 3. Compare the output of `--select=ALL` **Conclusion: all output were same** ## What's next? The next step is to introduce re-lexing logic and update the parser to feed the recovery information to the lexer so that it can emit the correct token. This moves us one step closer to having error resilience in the parser and provides Ruff the possibility to lint even if the source code contains syntax errors.
This commit is contained in:
parent
c69a789aa5
commit
bf5b62edac
262 changed files with 8174 additions and 6132 deletions
|
@ -1,115 +1,189 @@
|
|||
use std::iter::FusedIterator;
|
||||
|
||||
use ruff_python_trivia::CommentRanges;
|
||||
use ruff_text_size::{TextRange, TextSize};
|
||||
|
||||
use crate::lexer::{LexResult, LexicalError, Spanned};
|
||||
use crate::{Tok, TokenKind};
|
||||
use crate::lexer::{Lexer, LexerCheckpoint, LexicalError, Token, TokenFlags, TokenValue};
|
||||
use crate::{Mode, TokenKind};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct TokenSource {
|
||||
tokens: std::vec::IntoIter<LexResult>,
|
||||
errors: Vec<LexicalError>,
|
||||
/// Token source for the parser that skips over any trivia tokens.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct TokenSource<'src> {
|
||||
/// The underlying source for the tokens.
|
||||
lexer: Lexer<'src>,
|
||||
|
||||
/// A vector containing all the tokens emitted by the lexer. This is returned when the parser
|
||||
/// is finished consuming all the tokens. Note that unlike the emitted tokens, this vector
|
||||
/// holds both the trivia and non-trivia tokens.
|
||||
tokens: Vec<Token>,
|
||||
|
||||
/// A vector containing the range of all the comment tokens emitted by the lexer.
|
||||
comments: Vec<TextRange>,
|
||||
}
|
||||
|
||||
impl TokenSource {
|
||||
pub(crate) fn new(tokens: Vec<LexResult>) -> Self {
|
||||
Self {
|
||||
tokens: tokens.into_iter(),
|
||||
errors: Vec::new(),
|
||||
impl<'src> TokenSource<'src> {
|
||||
/// Create a new token source for the given lexer.
|
||||
pub(crate) fn new(lexer: Lexer<'src>) -> Self {
|
||||
// TODO(dhruvmanila): Use `allocate_tokens_vec`
|
||||
TokenSource {
|
||||
lexer,
|
||||
tokens: vec![],
|
||||
comments: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the position of the current token.
|
||||
/// Create a new token source from the given source code which starts at the given offset.
|
||||
pub(crate) fn from_source(source: &'src str, mode: Mode, start_offset: TextSize) -> Self {
|
||||
let lexer = Lexer::new(source, mode, start_offset);
|
||||
let mut source = TokenSource::new(lexer);
|
||||
|
||||
// Initialize the token source so that the current token is set correctly.
|
||||
source.do_bump();
|
||||
source
|
||||
}
|
||||
|
||||
/// Returns the kind of the current token.
|
||||
pub(crate) fn current_kind(&self) -> TokenKind {
|
||||
self.lexer.current_kind()
|
||||
}
|
||||
|
||||
/// Returns the range of the current token.
|
||||
pub(crate) fn current_range(&self) -> TextRange {
|
||||
self.lexer.current_range()
|
||||
}
|
||||
|
||||
/// Returns the flags for the current token.
|
||||
pub(crate) fn current_flags(&self) -> TokenFlags {
|
||||
self.lexer.current_flags()
|
||||
}
|
||||
|
||||
/// Calls the underlying [`take_value`] method on the lexer. Refer to its documentation
|
||||
/// for more info.
|
||||
///
|
||||
/// This is the position before any whitespace or comments.
|
||||
pub(crate) fn position(&self) -> Option<TextSize> {
|
||||
let first = self.tokens.as_slice().first()?;
|
||||
|
||||
let range = match first {
|
||||
Ok((_, range)) => *range,
|
||||
Err(error) => error.location(),
|
||||
};
|
||||
|
||||
Some(range.start())
|
||||
/// [`take_value`]: Lexer::take_value
|
||||
pub(crate) fn take_value(&mut self) -> TokenValue {
|
||||
self.lexer.take_value()
|
||||
}
|
||||
|
||||
/// Returns the end of the last token
|
||||
pub(crate) fn end(&self) -> Option<TextSize> {
|
||||
let last = self.tokens.as_slice().last()?;
|
||||
|
||||
let range = match last {
|
||||
Ok((_, range)) => *range,
|
||||
Err(error) => error.location(),
|
||||
};
|
||||
|
||||
Some(range.end())
|
||||
/// Returns the next non-trivia token without consuming it.
|
||||
///
|
||||
/// Use [`peek2`] to get the next two tokens.
|
||||
///
|
||||
/// [`peek2`]: TokenSource::peek2
|
||||
pub(crate) fn peek(&mut self) -> TokenKind {
|
||||
let checkpoint = self.lexer.checkpoint();
|
||||
let next = self.next_non_trivia_token();
|
||||
self.lexer.rewind(checkpoint);
|
||||
next
|
||||
}
|
||||
|
||||
/// Returns the next token kind and its range without consuming it.
|
||||
pub(crate) fn peek(&self) -> Option<(TokenKind, TextRange)> {
|
||||
let mut iter = self.tokens.as_slice().iter();
|
||||
/// Returns the next two non-trivia tokens without consuming it.
|
||||
///
|
||||
/// Use [`peek`] to only get the next token.
|
||||
///
|
||||
/// [`peek`]: TokenSource::peek
|
||||
pub(crate) fn peek2(&mut self) -> (TokenKind, TokenKind) {
|
||||
let checkpoint = self.lexer.checkpoint();
|
||||
let first = self.next_non_trivia_token();
|
||||
let second = self.next_non_trivia_token();
|
||||
self.lexer.rewind(checkpoint);
|
||||
(first, second)
|
||||
}
|
||||
|
||||
/// Bumps the token source to the next non-trivia token.
|
||||
///
|
||||
/// It pushes the given kind to the token vector with the current token range.
|
||||
pub(crate) fn bump(&mut self, kind: TokenKind) {
|
||||
self.tokens
|
||||
.push(Token::new(kind, self.current_range(), self.current_flags()));
|
||||
self.do_bump();
|
||||
}
|
||||
|
||||
/// Bumps the token source to the next non-trivia token without adding the current token to the
|
||||
/// token vector. It does add the trivia tokens to the token vector.
|
||||
fn do_bump(&mut self) {
|
||||
loop {
|
||||
let next = iter.next()?;
|
||||
|
||||
if next.as_ref().is_ok_and(is_trivia) {
|
||||
let kind = self.lexer.next_token();
|
||||
if is_trivia(kind) {
|
||||
if kind == TokenKind::Comment {
|
||||
self.comments.push(self.current_range());
|
||||
}
|
||||
self.tokens
|
||||
.push(Token::new(kind, self.current_range(), self.current_flags()));
|
||||
continue;
|
||||
}
|
||||
|
||||
break Some(match next {
|
||||
Ok((token, range)) => (TokenKind::from_token(token), *range),
|
||||
Err(error) => (TokenKind::Unknown, error.location()),
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish(self) -> Vec<LexicalError> {
|
||||
/// Returns the next non-trivia token without adding it to the token vector.
|
||||
fn next_non_trivia_token(&mut self) -> TokenKind {
|
||||
loop {
|
||||
let kind = self.lexer.next_token();
|
||||
if is_trivia(kind) {
|
||||
continue;
|
||||
}
|
||||
break kind;
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a checkpoint to which the token source can later return to using [`Self::rewind`].
|
||||
pub(crate) fn checkpoint(&self) -> TokenSourceCheckpoint<'src> {
|
||||
TokenSourceCheckpoint {
|
||||
lexer_checkpoint: self.lexer.checkpoint(),
|
||||
tokens_position: self.tokens.len(),
|
||||
comments_position: self.comments.len(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore the token source to the given checkpoint.
|
||||
pub(crate) fn rewind(&mut self, checkpoint: TokenSourceCheckpoint<'src>) {
|
||||
let TokenSourceCheckpoint {
|
||||
lexer_checkpoint,
|
||||
tokens_position,
|
||||
comments_position,
|
||||
} = checkpoint;
|
||||
|
||||
self.lexer.rewind(lexer_checkpoint);
|
||||
self.tokens.truncate(tokens_position);
|
||||
self.comments.truncate(comments_position);
|
||||
}
|
||||
|
||||
/// Consumes the token source, returning the collected tokens, comment ranges, and any errors
|
||||
/// encountered during lexing. The token collection includes both the trivia and non-trivia
|
||||
/// tokens.
|
||||
pub(crate) fn finish(mut self) -> (Vec<Token>, CommentRanges, Vec<LexicalError>) {
|
||||
assert_eq!(
|
||||
self.tokens.as_slice(),
|
||||
&[],
|
||||
"TokenSource was not fully consumed."
|
||||
self.current_kind(),
|
||||
TokenKind::EndOfFile,
|
||||
"TokenSource was not fully consumed"
|
||||
);
|
||||
|
||||
self.errors
|
||||
}
|
||||
}
|
||||
|
||||
impl FromIterator<LexResult> for TokenSource {
|
||||
#[inline]
|
||||
fn from_iter<T: IntoIterator<Item = LexResult>>(iter: T) -> Self {
|
||||
Self::new(Vec::from_iter(iter))
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for TokenSource {
|
||||
type Item = Spanned;
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
loop {
|
||||
let next = self.tokens.next()?;
|
||||
|
||||
match next {
|
||||
Ok(token) => {
|
||||
if is_trivia(&token) {
|
||||
continue;
|
||||
}
|
||||
|
||||
break Some(token);
|
||||
}
|
||||
|
||||
Err(error) => {
|
||||
let location = error.location();
|
||||
self.errors.push(error);
|
||||
break Some((Tok::Unknown, location));
|
||||
}
|
||||
}
|
||||
// The `EndOfFile` token shouldn't be included in the token stream, it's mainly to signal
|
||||
// the parser to stop. This isn't in `do_bump` because it only needs to be done once.
|
||||
if let Some(last) = self.tokens.pop() {
|
||||
assert_eq!(last.kind(), TokenKind::EndOfFile);
|
||||
}
|
||||
|
||||
let comment_ranges = CommentRanges::new(self.comments);
|
||||
(self.tokens, comment_ranges, self.lexer.finish())
|
||||
}
|
||||
}
|
||||
|
||||
impl FusedIterator for TokenSource {}
|
||||
|
||||
const fn is_trivia(result: &Spanned) -> bool {
|
||||
matches!(result, (Tok::Comment(_) | Tok::NonLogicalNewline, _))
|
||||
pub(crate) struct TokenSourceCheckpoint<'src> {
|
||||
lexer_checkpoint: LexerCheckpoint<'src>,
|
||||
tokens_position: usize,
|
||||
comments_position: usize,
|
||||
}
|
||||
|
||||
/// Allocates a [`Vec`] with an approximated capacity to fit all tokens
|
||||
/// of `contents`.
|
||||
///
|
||||
/// See [#9546](https://github.com/astral-sh/ruff/pull/9546) for a more detailed explanation.
|
||||
#[allow(dead_code)]
|
||||
fn allocate_tokens_vec(contents: &str) -> Vec<Token> {
|
||||
let lower_bound = contents.len().saturating_mul(15) / 100;
|
||||
Vec::with_capacity(lower_bound)
|
||||
}
|
||||
|
||||
fn is_trivia(token: TokenKind) -> bool {
|
||||
matches!(token, TokenKind::Comment | TokenKind::NonLogicalNewline)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue