Skip to content

Commit

Permalink
Avoid emitting empty logical lines (#4452)
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh authored May 16, 2023
1 parent 4b05ca1 commit 7e0d018
Show file tree
Hide file tree
Showing 4 changed files with 45 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);
}
}
15 changes: 10 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 @@ -500,11 +500,16 @@ 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,
});
let is_empty = self.tokens[self.current_line.tokens_start as usize..end as usize]
.iter()
.all(|token| token.kind.is_newline());
if !is_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(),
Expand Down
5 changes: 5 additions & 0 deletions crates/ruff_python_ast/src/token_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,11 @@ pub enum TokenKind {
}

impl TokenKind {
#[inline]
pub const fn is_newline(&self) -> bool {
matches!(self, TokenKind::Newline | TokenKind::NonLogicalNewline)
}

#[inline]
pub const fn is_unary(&self) -> bool {
matches!(self, TokenKind::Plus | TokenKind::Minus | TokenKind::Star)
Expand Down

0 comments on commit 7e0d018

Please sign in to comment.