Skip to content

Commit

Permalink
Implement re-lexing logic for better error recovery (#11845)
Browse files Browse the repository at this point in the history
## Summary

This PR implements the re-lexing logic in the parser.

This logic is only applied when recovering from an error during list
parsing. The logic is as follows:
1. During list parsing, if an unexpected token is encountered and it
detects that an outer context can understand it and thus recover from
it, it invokes the re-lexing logic in the lexer
2. This logic first checks if the lexer is in a parenthesized context
and returns if it's not. Thus, the logic is a no-op if the lexer isn't
in a parenthesized context
3. It then reduces the nesting level by 1. It shouldn't reset it to 0
because otherwise the recovery from nested list parsing will be
incorrect
4. Then, it tries to find last newline character going backwards from
the current position of the lexer. This avoids any whitespaces but if it
encounters any character other than newline or whitespace, it aborts.
5. Now, if there's a newline character, then it needs to be re-lexed in
a logical context which means that the lexer needs to emit it as a
`Newline` token instead of `NonLogicalNewline`.
6. If the re-lexing gives a different token than the current one, the
token source needs to update it's token collection to remove all the
tokens which comes after the new current position.

It turns out that the list parsing isn't that happy with the results so
it requires some re-arranging such that the following two errors are
raised correctly:
1. Expected comma
2. Recovery context error

For (1), the following scenarios needs to be considered:
* Missing comma between two elements
* Half parsed element because the grammar doesn't allow it (for example,
named expressions)

For (2), the following scenarios needs to be considered:
1. If the parser is at a comma which means that there's a missing
element otherwise the comma would've been consumed by the first `eat`
call above. And, the parser doesn't take the re-lexing route on a comma
token.
2. If it's the first element and the current token is not a comma which
means that it's an invalid element.

resolves: #11640 

## Test Plan

- [x] Update existing test snapshots and validate them
- [x] Add additional test cases specific to the re-lexing logic and
validate the snapshots
- [x] Run the fuzzer on 3000+ valid inputs
- [x] Run the fuzzer on invalid inputs
- [x] Run the parser on various open source projects
- [x] Make sure the ecosystem changes are none
  • Loading branch information
dhruvmanila authored Jun 17, 2024
1 parent 1f654ee commit 8499abf
Show file tree
Hide file tree
Showing 43 changed files with 1,585 additions and 204 deletions.
3 changes: 3 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ crates/ruff_linter/resources/test/fixtures/pycodestyle/W391_3.py text eol=crlf
crates/ruff_python_formatter/resources/test/fixtures/ruff/docstring_code_examples_crlf.py text eol=crlf
crates/ruff_python_formatter/tests/snapshots/format@docstring_code_examples_crlf.py.snap text eol=crlf

crates/ruff_python_parser/resources/invalid/re_lex_logical_token_windows_eol.py text eol=crlf
crates/ruff_python_parser/resources/invalid/re_lex_logical_token_mac_eol.py text eol=cr

crates/ruff_python_parser/resources/inline linguist-generated=true

ruff.schema.json linguist-generated=true text=auto eol=lf
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
call(**x := 1)
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# The comma between the first two elements is expected in `parse_list_expression`.
[0, 1 2]
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[0, 1, , 2]
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
call(= 1)
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# The first element is parsed by `parse_list_like_expression` and the comma after
# the first element is expected by `parse_list_expression`
[0]
[0, 1]
[0, 1,]
[0, 1, 2]
[0, 1, 2,]
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# No indentation before the function definition
if call(foo
def bar():
pass


# Indented function definition
if call(foo
def bar():
pass


# There are multiple non-logical newlines (blank lines) in the `if` body
if call(foo


def bar():
pass


# There are trailing whitespaces in the blank line inside the `if` body
if call(foo

def bar():
pass


# The lexer is nested with multiple levels of parentheses
if call(foo, [a, b
def bar():
pass


# The outer parenthesis is closed but the inner bracket isn't
if call(foo, [a, b)
def bar():
pass


# The parser tries to recover from an unclosed `]` when the current token is `)`. This
# test is to make sure it emits a `NonLogicalNewline` token after `b`.
if call(foo, [a,
b
)
def bar():
pass
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
if call(foo, [a, b def bar(): pass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
if call(foo, [a, b
def bar():
pass
112 changes: 112 additions & 0 deletions crates/ruff_python_parser/src/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1307,6 +1307,118 @@ impl<'src> Lexer<'src> {
}
}

/// Re-lex the current token in the context of a logical line.
///
/// Returns a boolean indicating whether the lexer's position has changed. This could result
/// into the new current token being different than the previous current token but is not
/// necessarily true. If the return value is `true` then the caller is responsible for updating
/// it's state accordingly.
///
/// This method is a no-op if the lexer isn't in a parenthesized context.
///
/// ## Explanation
///
/// The lexer emits two different kinds of newline token based on the context. If it's in a
/// parenthesized context, it'll emit a [`NonLogicalNewline`] token otherwise it'll emit a
/// regular [`Newline`] token. Based on the type of newline token, the lexer will consume and
/// emit the indentation tokens appropriately which affects the structure of the code.
///
/// For example:
/// ```py
/// if call(foo
/// def bar():
/// pass
/// ```
///
/// Here, the lexer emits a [`NonLogicalNewline`] token after `foo` which means that the lexer
/// doesn't emit an `Indent` token before the `def` keyword. This leads to an AST which
/// considers the function `bar` as part of the module block and the `if` block remains empty.
///
/// This method is to facilitate the parser if it recovers from these kind of scenarios so that
/// the lexer can then re-lex a [`NonLogicalNewline`] token to a [`Newline`] token which in
/// turn helps the parser to build the correct AST.
///
/// In the above snippet, it would mean that this method would move the lexer back to the
/// newline character after the `foo` token and emit it as a [`Newline`] token instead of
/// [`NonLogicalNewline`]. This means that the next token emitted by the lexer would be an
/// `Indent` token.
///
/// There are cases where the lexer's position will change but the re-lexed token will remain
/// the same. This is to help the parser to add the error message at an appropriate location.
/// Consider the following example:
///
/// ```py
/// if call(foo, [a, b
/// def bar():
/// pass
/// ```
///
/// Here, the parser recovers from two unclosed parenthesis. The inner unclosed `[` will call
/// into the re-lexing logic and reduce the nesting level from 2 to 1. And, the re-lexing logic
/// will move the lexer at the newline after `b` but still emit a [`NonLogicalNewline`] token.
/// Only after the parser recovers from the outer unclosed `(` does the re-lexing logic emit
/// the [`Newline`] token.
///
/// [`Newline`]: TokenKind::Newline
/// [`NonLogicalNewline`]: TokenKind::NonLogicalNewline
pub(crate) fn re_lex_logical_token(&mut self) -> bool {
if self.nesting == 0 {
return false;
}

// Reduce the nesting level because the parser recovered from an error inside list parsing
// i.e., it recovered from an unclosed parenthesis (`(`, `[`, or `{`).
self.nesting -= 1;

let current_position = self.current_range().start();
let reverse_chars = self.source[..current_position.to_usize()].chars().rev();
let mut new_position = current_position;
let mut has_newline = false;

for ch in reverse_chars {
if is_python_whitespace(ch) {
new_position -= ch.text_len();
} else if matches!(ch, '\n' | '\r') {
has_newline |= true;
new_position -= ch.text_len();
} else {
break;
}
}

// The lexer should only be moved if there's a newline character which needs to be
// re-lexed.
if new_position != current_position && has_newline {
// Earlier we reduced the nesting level unconditionally. Now that we know the lexer's
// position is going to be moved back, the lexer needs to be put back into a
// parenthesized context if the current token is a closing parenthesis.
//
// ```py
// (a, [b,
// c
// )
// ```
//
// Here, the parser would request to re-lex the token when it's at `)` and can recover
// from an unclosed `[`. This method will move the lexer back to the newline character
// after `c` which means it goes back into parenthesized context.
if matches!(
self.current_kind,
TokenKind::Rpar | TokenKind::Rsqb | TokenKind::Rbrace
) {
self.nesting += 1;
}

self.cursor = Cursor::new(self.source);
self.cursor.skip_bytes(new_position.to_usize());
self.state = State::Other;
self.next_token();
true
} else {
false
}
}

#[inline]
fn token_range(&self) -> TextRange {
let end = self.offset();
Expand Down
116 changes: 86 additions & 30 deletions crates/ruff_python_parser/src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -473,11 +473,6 @@ impl<'src> Parser<'src> {
loop {
progress.assert_progressing(self);

// The end of file marker ends all lists.
if self.at(TokenKind::EndOfFile) {
break;
}

if recovery_context_kind.is_list_element(self) {
parse_element(self);
} else if recovery_context_kind.is_list_terminator(self) {
Expand Down Expand Up @@ -533,54 +528,96 @@ impl<'src> Parser<'src> {
.recovery_context
.union(RecoveryContext::from_kind(recovery_context_kind));

let mut first_element = true;
let mut trailing_comma_range: Option<TextRange> = None;

loop {
progress.assert_progressing(self);

// The end of file marker ends all lists.
if self.at(TokenKind::EndOfFile) {
break;
}

if recovery_context_kind.is_list_element(self) {
parse_element(self);

// Only unset this when we've completely parsed a single element. This is mainly to
// raise the correct error in case the first element isn't valid and the current
// token isn't a comma. Without this knowledge, the parser would later expect a
// comma instead of raising the context error.
first_element = false;

let maybe_comma_range = self.current_token_range();
if self.eat(TokenKind::Comma) {
trailing_comma_range = Some(maybe_comma_range);
continue;
}
trailing_comma_range = None;
}

if recovery_context_kind.is_list_terminator(self) {
break;
}
// test_ok comma_separated_regular_list_terminator
// # The first element is parsed by `parse_list_like_expression` and the comma after
// # the first element is expected by `parse_list_expression`
// [0]
// [0, 1]
// [0, 1,]
// [0, 1, 2]
// [0, 1, 2,]
if recovery_context_kind.is_regular_list_terminator(self) {
break;
}

// test_err comma_separated_missing_comma_between_elements
// # The comma between the first two elements is expected in `parse_list_expression`.
// [0, 1 2]
if recovery_context_kind.is_list_element(self) {
// This is a special case to expect a comma between two elements and should be
// checked before running the error recovery. This is because the error recovery
// will always run as the parser is currently at a list element.
self.expect(TokenKind::Comma);
} else if recovery_context_kind.is_list_terminator(self) {
continue;
}

// Run the error recovery: If the token is recognised as an element or terminator of an
// enclosing list, then we try to re-lex in the context of a logical line and break out
// of list parsing.
if self.is_enclosing_list_element_or_terminator() {
self.tokens.re_lex_logical_token();
break;
} else {
// Not a recognised element. Add an error and either skip the token or break
// parsing the list if the token is recognised as an element or terminator of an
// enclosing list.
let error = recovery_context_kind.create_error(self);
self.add_error(error, self.current_token_range());
}

// Run the error recovery: This also handles the case when an element is missing
// between two commas: `a,,b`
if self.is_enclosing_list_element_or_terminator() {
break;
}
if first_element || self.at(TokenKind::Comma) {
// There are two conditions when we need to add the recovery context error:
//
// 1. If the parser is at a comma which means that there's a missing element
// otherwise the comma would've been consumed by the first `eat` call above.
// And, the parser doesn't take the re-lexing route on a comma token.
// 2. If it's the first element and the current token is not a comma which means
// that it's an invalid element.

// test_err comma_separated_missing_element_between_commas
// [0, 1, , 2]

// test_err comma_separated_missing_first_element
// call(= 1)
self.add_error(
recovery_context_kind.create_error(self),
self.current_token_range(),
);

if self.at(TokenKind::Comma) {
trailing_comma_range = Some(self.current_token_range());
trailing_comma_range = if self.at(TokenKind::Comma) {
Some(self.current_token_range())
} else {
trailing_comma_range = None;
}
None
};
} else {
// Otherwise, there should've been a comma at this position. This could be because
// the element isn't consumed completely by `parse_element`.

self.bump_any();
// test_err comma_separated_missing_comma
// call(**x := 1)
self.expect(TokenKind::Comma);

trailing_comma_range = None;
}

self.bump_any();
}

if let Some(trailing_comma_range) = trailing_comma_range {
Expand Down Expand Up @@ -885,13 +922,32 @@ impl RecoveryContextKind {
}

/// Returns `true` if the parser is at a token that terminates the list as per the context.
///
/// This token could either end the list or is only present for better error recovery. Refer to
/// [`is_regular_list_terminator`] to only check against the former.
///
/// [`is_regular_list_terminator`]: RecoveryContextKind::is_regular_list_terminator
fn is_list_terminator(self, p: &Parser) -> bool {
self.list_terminator_kind(p).is_some()
}

/// Returns `true` if the parser is at a token that terminates the list as per the context but
/// the token isn't part of the error recovery set.
fn is_regular_list_terminator(self, p: &Parser) -> bool {
matches!(
self.list_terminator_kind(p),
Some(ListTerminatorKind::Regular)
)
}

/// Checks the current token the parser is at and returns the list terminator kind if the token
/// terminates the list as per the context.
fn list_terminator_kind(self, p: &Parser) -> Option<ListTerminatorKind> {
// The end of file marker ends all lists.
if p.at(TokenKind::EndOfFile) {
return Some(ListTerminatorKind::Regular);
}

match self {
// The parser must consume all tokens until the end
RecoveryContextKind::ModuleStatements => None,
Expand Down
19 changes: 18 additions & 1 deletion crates/ruff_python_parser/src/token_source.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use ruff_text_size::{TextRange, TextSize};
use ruff_text_size::{Ranged, TextRange, TextSize};

use crate::lexer::{Lexer, LexerCheckpoint, LexicalError, Token, TokenFlags, TokenValue};
use crate::{Mode, TokenKind};
Expand Down Expand Up @@ -58,6 +58,23 @@ impl<'src> TokenSource<'src> {
self.lexer.take_value()
}

/// Calls the underlying [`re_lex_logical_token`] method on the lexer and updates the token
/// vector accordingly.
///
/// [`re_lex_logical_token`]: Lexer::re_lex_logical_token
pub(crate) fn re_lex_logical_token(&mut self) {
if self.lexer.re_lex_logical_token() {
let current_start = self.current_range().start();
while self
.tokens
.last()
.is_some_and(|last| last.start() >= current_start)
{
self.tokens.pop();
}
}
}

/// Returns the next non-trivia token without consuming it.
///
/// Use [`peek2`] to get the next two tokens.
Expand Down
Loading

0 comments on commit 8499abf

Please sign in to comment.