mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-30 07:07:42 +00:00

## 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.
295 lines
9.4 KiB
Rust
295 lines
9.4 KiB
Rust
use std::cmp::Ordering;
|
|
use std::fmt::{Formatter, Write};
|
|
use std::fs;
|
|
use std::path::Path;
|
|
|
|
use annotate_snippets::display_list::{DisplayList, FormatOptions};
|
|
use annotate_snippets::snippet::{AnnotationType, Slice, Snippet, SourceAnnotation};
|
|
|
|
use ruff_python_ast::visitor::preorder::{walk_module, PreorderVisitor, TraversalSignal};
|
|
use ruff_python_ast::{AnyNodeRef, Mod};
|
|
use ruff_python_parser::{parse_unchecked, Mode, ParseErrorType};
|
|
use ruff_source_file::{LineIndex, OneIndexed, SourceCode};
|
|
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
|
|
|
|
#[test]
|
|
fn valid_syntax() {
|
|
insta::glob!("../resources", "valid/**/*.py", test_valid_syntax);
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_syntax() {
|
|
insta::glob!("../resources", "invalid/**/*.py", test_invalid_syntax);
|
|
}
|
|
|
|
#[test]
|
|
fn inline_ok() {
|
|
insta::glob!("../resources/inline", "ok/**/*.py", test_valid_syntax);
|
|
}
|
|
|
|
#[test]
|
|
fn inline_err() {
|
|
insta::glob!("../resources/inline", "err/**/*.py", test_invalid_syntax);
|
|
}
|
|
|
|
/// Asserts that the parser generates no syntax errors for a valid program.
|
|
/// Snapshots the AST.
|
|
fn test_valid_syntax(input_path: &Path) {
|
|
let source = fs::read_to_string(input_path).expect("Expected test file to exist");
|
|
let parsed = parse_unchecked(&source, Mode::Module);
|
|
|
|
if !parsed.is_valid() {
|
|
let line_index = LineIndex::from_source_text(&source);
|
|
let source_code = SourceCode::new(&source, &line_index);
|
|
|
|
let mut message = "Expected no syntax errors for a valid program but the parser generated the following errors:\n".to_string();
|
|
|
|
for error in parsed.errors() {
|
|
writeln!(
|
|
&mut message,
|
|
"{}\n",
|
|
CodeFrame {
|
|
range: error.location,
|
|
error,
|
|
source_code: &source_code,
|
|
}
|
|
)
|
|
.unwrap();
|
|
}
|
|
|
|
panic!("{input_path:?}: {message}");
|
|
}
|
|
|
|
validate_ast(parsed.syntax(), source.text_len(), input_path);
|
|
|
|
let mut output = String::new();
|
|
writeln!(&mut output, "## AST").unwrap();
|
|
writeln!(&mut output, "\n```\n{:#?}\n```", parsed.syntax()).unwrap();
|
|
|
|
insta::with_settings!({
|
|
omit_expression => true,
|
|
input_file => input_path,
|
|
prepend_module_to_snapshot => false,
|
|
}, {
|
|
insta::assert_snapshot!(output);
|
|
});
|
|
}
|
|
|
|
/// Assert that the parser generates at least one syntax error for the given input file.
|
|
/// Snapshots the AST and the error messages.
|
|
fn test_invalid_syntax(input_path: &Path) {
|
|
let source = fs::read_to_string(input_path).expect("Expected test file to exist");
|
|
let parsed = parse_unchecked(&source, Mode::Module);
|
|
|
|
assert!(
|
|
!parsed.is_valid(),
|
|
"{input_path:?}: Expected parser to generate at least one syntax error for a program containing syntax errors."
|
|
);
|
|
|
|
validate_ast(parsed.syntax(), source.text_len(), input_path);
|
|
|
|
let mut output = String::new();
|
|
writeln!(&mut output, "## AST").unwrap();
|
|
writeln!(&mut output, "\n```\n{:#?}\n```", parsed.syntax()).unwrap();
|
|
|
|
writeln!(&mut output, "## Errors\n").unwrap();
|
|
|
|
let line_index = LineIndex::from_source_text(&source);
|
|
let source_code = SourceCode::new(&source, &line_index);
|
|
|
|
for error in parsed.errors() {
|
|
writeln!(
|
|
&mut output,
|
|
"{}\n",
|
|
CodeFrame {
|
|
range: error.location,
|
|
error,
|
|
source_code: &source_code,
|
|
}
|
|
)
|
|
.unwrap();
|
|
}
|
|
|
|
insta::with_settings!({
|
|
omit_expression => true,
|
|
input_file => input_path,
|
|
prepend_module_to_snapshot => false,
|
|
}, {
|
|
insta::assert_snapshot!(output);
|
|
});
|
|
}
|
|
|
|
// Test that is intentionally ignored by default.
|
|
// Use it for quickly debugging a parser issue.
|
|
#[test]
|
|
#[ignore]
|
|
#[allow(clippy::print_stdout)]
|
|
fn parser_quick_test() {
|
|
let source = "\
|
|
def foo()
|
|
pass
|
|
";
|
|
|
|
let parsed = parse_unchecked(source, Mode::Module);
|
|
|
|
println!("AST:\n----\n{:#?}", parsed.syntax());
|
|
println!("Tokens:\n-------\n{:#?}", parsed.tokens());
|
|
|
|
if !parsed.is_valid() {
|
|
println!("Errors:\n-------");
|
|
|
|
let line_index = LineIndex::from_source_text(source);
|
|
let source_code = SourceCode::new(source, &line_index);
|
|
|
|
for error in parsed.errors() {
|
|
// Sometimes the code frame doesn't show the error message, so we print
|
|
// the message as well.
|
|
println!("Syntax Error: {error}");
|
|
println!(
|
|
"{}\n",
|
|
CodeFrame {
|
|
range: error.location,
|
|
error,
|
|
source_code: &source_code,
|
|
}
|
|
);
|
|
}
|
|
|
|
println!();
|
|
}
|
|
}
|
|
|
|
struct CodeFrame<'a> {
|
|
range: TextRange,
|
|
error: &'a ParseErrorType,
|
|
source_code: &'a SourceCode<'a, 'a>,
|
|
}
|
|
|
|
impl std::fmt::Display for CodeFrame<'_> {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
// Copied and modified from ruff_linter/src/message/text.rs
|
|
let content_start_index = self.source_code.line_index(self.range.start());
|
|
let mut start_index = content_start_index.saturating_sub(2);
|
|
|
|
// Trim leading empty lines.
|
|
while start_index < content_start_index {
|
|
if !self.source_code.line_text(start_index).trim().is_empty() {
|
|
break;
|
|
}
|
|
start_index = start_index.saturating_add(1);
|
|
}
|
|
|
|
let content_end_index = self.source_code.line_index(self.range.end());
|
|
let mut end_index = content_end_index
|
|
.saturating_add(2)
|
|
.min(OneIndexed::from_zero_indexed(self.source_code.line_count()));
|
|
|
|
// Trim trailing empty lines.
|
|
while end_index > content_end_index {
|
|
if !self.source_code.line_text(end_index).trim().is_empty() {
|
|
break;
|
|
}
|
|
|
|
end_index = end_index.saturating_sub(1);
|
|
}
|
|
|
|
let start_offset = self.source_code.line_start(start_index);
|
|
let end_offset = self.source_code.line_end(end_index);
|
|
|
|
let annotation_range = self.range - start_offset;
|
|
let source = self
|
|
.source_code
|
|
.slice(TextRange::new(start_offset, end_offset));
|
|
|
|
let start_char = source[TextRange::up_to(annotation_range.start())]
|
|
.chars()
|
|
.count();
|
|
|
|
let char_length = source[annotation_range].chars().count();
|
|
let label = format!("Syntax Error: {error}", error = self.error);
|
|
|
|
let snippet = Snippet {
|
|
title: None,
|
|
slices: vec![Slice {
|
|
source,
|
|
line_start: start_index.get(),
|
|
annotations: vec![SourceAnnotation {
|
|
label: &label,
|
|
annotation_type: AnnotationType::Error,
|
|
range: (start_char, start_char + char_length),
|
|
}],
|
|
// The origin (file name, line number, and column number) is already encoded
|
|
// in the `label`.
|
|
origin: None,
|
|
fold: false,
|
|
}],
|
|
footer: Vec::new(),
|
|
opt: FormatOptions::default(),
|
|
};
|
|
|
|
writeln!(f, "{message}", message = DisplayList::from(snippet))
|
|
}
|
|
}
|
|
|
|
/// Verifies that:
|
|
/// * the range of the parent node fully encloses all its child nodes
|
|
/// * the ranges are strictly increasing when traversing the nodes in pre-order.
|
|
/// * all ranges are within the length of the source code.
|
|
fn validate_ast(root: &Mod, source_len: TextSize, test_path: &Path) {
|
|
walk_module(&mut ValidateAstVisitor::new(source_len, test_path), root);
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct ValidateAstVisitor<'a> {
|
|
parents: Vec<AnyNodeRef<'a>>,
|
|
previous: Option<AnyNodeRef<'a>>,
|
|
source_length: TextSize,
|
|
test_path: &'a Path,
|
|
}
|
|
|
|
impl<'a> ValidateAstVisitor<'a> {
|
|
fn new(source_length: TextSize, test_path: &'a Path) -> Self {
|
|
Self {
|
|
parents: Vec::new(),
|
|
previous: None,
|
|
source_length,
|
|
test_path,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<'ast> PreorderVisitor<'ast> for ValidateAstVisitor<'ast> {
|
|
fn enter_node(&mut self, node: AnyNodeRef<'ast>) -> TraversalSignal {
|
|
assert!(
|
|
node.end() <= self.source_length,
|
|
"{path}: The range of the node exceeds the length of the source code. Node: {node:#?}",
|
|
path = self.test_path.display()
|
|
);
|
|
|
|
if let Some(previous) = self.previous {
|
|
assert_ne!(previous.range().ordering(node.range()), Ordering::Greater,
|
|
"{path}: The ranges of the nodes are not strictly increasing when traversing the AST in pre-order.\nPrevious node: {previous:#?}\n\nCurrent node: {node:#?}\n\nRoot: {root:#?}",
|
|
path = self.test_path.display(),
|
|
root = self.parents.first()
|
|
);
|
|
}
|
|
|
|
if let Some(parent) = self.parents.last() {
|
|
assert!(parent.range().contains_range(node.range()),
|
|
"{path}: The range of the parent node does not fully enclose the range of the child node.\nParent node: {parent:#?}\n\nChild node: {node:#?}\n\nRoot: {root:#?}",
|
|
path = self.test_path.display(),
|
|
root = self.parents.first()
|
|
);
|
|
}
|
|
|
|
self.parents.push(node);
|
|
|
|
TraversalSignal::Traverse
|
|
}
|
|
|
|
fn leave_node(&mut self, node: AnyNodeRef<'ast>) {
|
|
self.parents.pop().expect("Expected tree to be balanced");
|
|
|
|
self.previous = Some(node);
|
|
}
|
|
}
|