Skip to content

Commit

Permalink
Fix expected-indentation errors with end-of-line comments (#4438)
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed May 16, 2023
1 parent 6049aab commit 8134ec2
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 4 deletions.
9 changes: 9 additions & 0 deletions crates/ruff/resources/test/fixtures/pycodestyle/E11.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,12 @@ def start():
#: E117 W191
def start():
print()
#: E112
if False: #
print()
#:
if False:
print()
#:
if False: #
print()
25 changes: 21 additions & 4 deletions crates/ruff/src/rules/pycodestyle/rules/logical_lines/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ impl<'a> LogicalLines<'a> {
let mut builder = LogicalLinesBuilder::with_capacity(tokens.len());
let mut parens: u32 = 0;

for (token, range) in tokens.iter().flatten() {
let mut iter = tokens.iter().flatten().peekable();
while let Some((token, range)) = iter.next() {
let token_kind = TokenKind::from_token(token);
builder.push_token(token_kind, *range);

Expand All @@ -100,9 +101,25 @@ impl<'a> LogicalLines<'a> {
TokenKind::Rbrace | TokenKind::Rpar | TokenKind::Rsqb => {
parens -= 1;
}
TokenKind::Newline | TokenKind::NonLogicalNewline | TokenKind::Comment
if parens == 0 =>
{
TokenKind::Comment if parens == 0 => {
// If a comment is followed by a newline, ignore it, and we'll build the line
// when we process the newline. Otherwise, we'll end up creating one logical
// line here, and then another, empty logical line when we process the newline.
//
// The lexer will always emit a newline after a comment _unless_ the comment
// appears at the start of a logical line.
if let Some((token, ..)) = iter.peek() {
let token_kind = TokenKind::from_token(token);
if matches!(
token_kind,
TokenKind::Newline | TokenKind::NonLogicalNewline
) {
continue;
}
}
builder.finish_line();
}
TokenKind::Newline | TokenKind::NonLogicalNewline if parens == 0 => {
builder.finish_line();
}
_ => {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,14 @@ E11.py:9:1: E112 Expected an indented block
13 | print()
|

E11.py:45:1: E112 Expected an indented block
|
45 | #: E112
46 | if False: #
47 | print()
| E112
48 | #:
49 | if False:
|


Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ E11.py:42:1: E117 Over-indented
43 | def start():
44 | print()
| ^^^^^^^^ E117
45 | #: E112
46 | if False: #
|


0 comments on commit 8134ec2

Please sign in to comment.