Skip to content

Commit

Permalink
Avoid emitting empty logical lines
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed May 16, 2023
1 parent f0465bf commit be8161c
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 5 deletions.
15 changes: 15 additions & 0 deletions crates/ruff/resources/test/fixtures/pycodestyle/E11.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,18 @@ def start():
#:
if False: #
print()
#:
if False:
print()

print()
#:
if False:
print()
if False:

print()
#:
if False:

print()
15 changes: 15 additions & 0 deletions crates/ruff/src/checkers/logical_lines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,5 +250,20 @@ f()"#
"f()",
];
assert_eq!(actual, expected);

let contents = r#"
if False:
print()
"#
.trim();
let lxr: Vec<LexResult> = lexer::lex(contents, Mode::Module).collect();
let locator = Locator::new(contents);
let actual: Vec<String> = LogicalLines::from_tokens(&lxr, &locator)
.into_iter()
.map(|line| line.text_trimmed().to_string())
.collect();
let expected = vec!["if False:", "print()", ""];
assert_eq!(actual, expected);
}
}
18 changes: 13 additions & 5 deletions crates/ruff/src/rules/pycodestyle/rules/logical_lines/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,7 @@ impl Whitespace {
struct CurrentLine {
flags: TokenFlags,
tokens_start: u32,
non_empty: bool,
}

/// Builder for [`LogicalLines`]
Expand All @@ -455,6 +456,10 @@ impl LogicalLinesBuilder {
fn push_token(&mut self, kind: TokenKind, range: TextRange) {
let line = &mut self.current_line;

if !matches!(kind, TokenKind::NonLogicalNewline) {
line.non_empty = true;
}

if matches!(kind, TokenKind::Comment) {
line.flags.insert(TokenFlags::COMMENT);
} else if kind.is_operator() {
Expand Down Expand Up @@ -500,15 +505,18 @@ impl LogicalLinesBuilder {
fn finish_line(&mut self) {
let end = self.tokens.len() as u32;
if self.current_line.tokens_start < end {
self.lines.push(Line {
flags: self.current_line.flags,
tokens_start: self.current_line.tokens_start,
tokens_end: end,
});
if self.current_line.non_empty {
self.lines.push(Line {
flags: self.current_line.flags,
tokens_start: self.current_line.tokens_start,
tokens_end: end,
});
}

self.current_line = CurrentLine {
flags: TokenFlags::default(),
tokens_start: end,
non_empty: false,
}
}
}
Expand Down

0 comments on commit be8161c

Please sign in to comment.