Rewrite placement logic (#6040)

## Summary
This is a rewrite of the main comment placement logic. `place_comment`
now has three parts:

- place own line comments
  - between branches
  - after a branch
- place end-of-line comments
  - after colon
  - after a branch
- place comments for specific nodes (that include module level comments)

The rewrite fixed three bugs: `class A: # trailing comment` comments now
stay end-of-line, `try: # comment` remains end-of-line and deeply
indented try-else-finally comments remain with the right nested
statement.

It will be much easier to give more alternative branches nodes since
this is abstracted away by `is_node_with_body` and the first/last child
helpers. Adding new node types can now be done by adding an entry to the
`place_comment` match. The code went from 1526 lines before #6033 to
1213 lines now.

It thinks it easier to just read the new `placement.rs` rather than
reviewing the diff.

## Test Plan

The existing fixtures staying the same or improving plus new ones for
the bug fixes.
This commit is contained in:
konsti 2023-07-26 18:21:23 +02:00 committed by GitHub
parent 2cf00fee96
commit 13f9a16e33
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 541 additions and 673 deletions

View file

@ -5,7 +5,6 @@ use crate::prelude::*;
use crate::{FormatNodeRule, PyFormatter};
use ruff_formatter::FormatRuleWithOptions;
use ruff_formatter::{write, Buffer, FormatResult};
use ruff_python_ast::node::AstNode;
use rustpython_ast::ExceptHandlerExceptHandler;
#[derive(Copy, Clone, Default)]
@ -45,7 +44,7 @@ impl FormatNodeRule<ExceptHandlerExceptHandler> for FormatExceptHandlerExceptHan
} = item;
let comments_info = f.context().comments().clone();
let dangling_comments = comments_info.dangling_comments(item.as_any_node_ref());
let dangling_comments = comments_info.dangling_comments(item);
write!(
f,
@ -75,7 +74,7 @@ impl FormatNodeRule<ExceptHandlerExceptHandler> for FormatExceptHandlerExceptHan
[
text(":"),
trailing_comments(dangling_comments),
block_indent(&body.format())
block_indent(&body.format()),
]
)
}