diff --git a/crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/import_from.py b/crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/import_from.py index 879fe9aeffb03..31555cb2b6e20 100644 --- a/crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/import_from.py +++ b/crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/import_from.py @@ -37,3 +37,7 @@ ) from tqdm . auto import tqdm + +# Regression test for https://github.com/astral-sh/ruff/issues/19138 +from y import(e as# +r) diff --git a/crates/ruff_python_formatter/src/comments/placement.rs b/crates/ruff_python_formatter/src/comments/placement.rs index 0ec2aa6d2fbe3..33fdab92313b3 100644 --- a/crates/ruff_python_formatter/src/comments/placement.rs +++ b/crates/ruff_python_formatter/src/comments/placement.rs @@ -312,6 +312,7 @@ fn handle_enclosed_comment<'a>( handle_leading_class_with_decorators_comment(comment, class_def) } AnyNodeRef::StmtImportFrom(import_from) => handle_import_from_comment(comment, import_from), + AnyNodeRef::Alias(alias) => handle_alias_from_comment(comment, alias, source), AnyNodeRef::StmtWith(with_) => handle_with_comment(comment, with_), AnyNodeRef::ExprCall(_) => handle_call_comment(comment), AnyNodeRef::ExprStringLiteral(_) => match comment.enclosing_parent() { @@ -1967,6 +1968,29 @@ fn handle_import_from_comment<'a>( } } +fn handle_alias_from_comment<'a>( + comment: DecoratedComment<'a>, + alias: &'a ast::Alias, + source: &str, +) -> CommentPlacement<'a> { + if let Some(asname) = alias.asname.as_ref() { + // Determine if the comment is between the `as` token and the alias name. + let mut tokens = + SimpleTokenizer::new(source, TextRange::new(alias.name.end(), asname.start())) + .skip_trivia(); + + if let Some(as_token) = tokens.find(|t| t.kind() == SimpleTokenKind::As) + && (comment.line_position().is_end_of_line() || comment.line_position().is_own_line()) + && as_token.end() <= comment.start() + && comment.end() <= asname.start() + { + return CommentPlacement::trailing(alias, comment); + } + } + + CommentPlacement::Default(comment) +} + /// Attach an enclosed end-of-line comment to a [`ast::StmtWith`]. /// /// For example, given: diff --git a/crates/ruff_python_formatter/tests/snapshots/format@statement__import_from.py.snap b/crates/ruff_python_formatter/tests/snapshots/format@statement__import_from.py.snap index 45626f76cd8cf..ee5b2a47bf923 100644 --- a/crates/ruff_python_formatter/tests/snapshots/format@statement__import_from.py.snap +++ b/crates/ruff_python_formatter/tests/snapshots/format@statement__import_from.py.snap @@ -44,6 +44,10 @@ from a import \ ) from tqdm . auto import tqdm + +# Regression test for https://github.com/astral-sh/ruff/issues/19138 +from y import(e as# +r) ``` ## Output @@ -120,4 +124,9 @@ from a import ( # comment ) from tqdm.auto import tqdm + +# Regression test for https://github.com/astral-sh/ruff/issues/19138 +from y import ( + e as r, # +) ```