From 8b18899f2d1d2efa8b85c8bd378966f91040ab4f Mon Sep 17 00:00:00 2001 From: dylwil3 Date: Tue, 11 Nov 2025 14:41:17 -0600 Subject: [PATCH] less aggressively use preceding node as last_child --- .../src/comments/placement.rs | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/ruff_python_formatter/src/comments/placement.rs b/crates/ruff_python_formatter/src/comments/placement.rs index 60e19fc4e7..6d3163f49b 100644 --- a/crates/ruff_python_formatter/src/comments/placement.rs +++ b/crates/ruff_python_formatter/src/comments/placement.rs @@ -716,7 +716,7 @@ fn handle_own_line_comment_after_branch<'a>( // pass // ``` // - // Otherwise, the preceding node is the last statement in the body + // Otherwise, the preceding node may be the last statement in the body // of the preceding branch, in which case we can take it as our // `last_child` here - e.g. // @@ -728,7 +728,26 @@ fn handle_own_line_comment_after_branch<'a>( // else: // pass // ``` - let last_child = preceding.last_child_in_body().unwrap_or(preceding); + let last_child = match preceding.last_child_in_body() { + Some(last) => last, + None if matches!( + comment.enclosing_node(), + AnyNodeRef::StmtIf(_) + | AnyNodeRef::StmtWhile(_) + | AnyNodeRef::StmtFor(_) + | AnyNodeRef::StmtMatch(_) + | AnyNodeRef::ElifElseClause(_) + | AnyNodeRef::StmtTry(_) + | AnyNodeRef::MatchCase(_) + | AnyNodeRef::ExceptHandlerExceptHandler(_) + ) => + { + preceding + } + _ => { + return CommentPlacement::Default(comment); + } + }; // We only care about the length because indentations with mixed spaces and tabs are only valid if // the indent-level doesn't depend on the tab width (the indent level must be the same if the tab width is 1 or 8).