Preserve trailing statement semicolons when using fmt: skip (#8273)

This commit is contained in:
Micha Reiser 2023-10-30 09:07:14 +09:00 committed by GitHub
parent e799f90782
commit 2c84f911c4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 85 additions and 3 deletions

View file

@ -1,5 +1,7 @@
use ruff_formatter::{FormatOwnedWithRule, FormatRefWithRule};
use ruff_python_ast::Stmt;
use ruff_python_ast::{AnyNodeRef, Stmt};
use ruff_python_trivia::{SimpleToken, SimpleTokenKind, SimpleTokenizer};
use ruff_text_size::{Ranged, TextRange};
use crate::prelude::*;
@ -81,3 +83,25 @@ impl<'ast> IntoFormat<PyFormatContext<'ast>> for Stmt {
FormatOwnedWithRule::new(self, FormatStmt)
}
}
/// Returns the range of the semicolon terminating the statement or `None` if the statement
/// isn't terminated by a semicolon.
pub(super) fn trailing_semicolon(node: AnyNodeRef, source: &str) -> Option<TextRange> {
debug_assert!(node.is_statement());
let tokenizer = SimpleTokenizer::starts_at(node.end(), source);
let next_token = tokenizer
.take_while(|token| !token.kind().is_comment())
.find(|token| !token.kind().is_trivia());
if let Some(SimpleToken {
kind: SimpleTokenKind::Semi,
range,
}) = next_token
{
Some(range)
} else {
None
}
}