Generalize comment-after-bracket handling to lists, sets, etc. (#6320)

## Summary

We already support preserving the end-of-line comment in calls and type
parameters, as in:

```python
foo(  # comment
    bar,
)
```

This PR adds the same behavior for lists, sets, comprehensions, etc.,
such that we preserve:

```python
[  # comment
    1,
    2,
    3,
]
```

And related cases.
This commit is contained in:
Charlie Marsh 2023-08-03 21:28:05 -04:00 committed by GitHub
parent d3aa8b4ee0
commit 1d8759d5df
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 265 additions and 99 deletions

View file

@ -1,8 +1,9 @@
use ruff_python_ast::node::AnyNodeRef;
use ruff_python_ast::{ExprSet, Ranged};
use ruff_python_ast::node::AnyNodeRef;
use crate::expression::parentheses::{parenthesized, NeedsParentheses, OptionalParentheses};
use crate::expression::parentheses::{
parenthesized_with_dangling_comments, NeedsParentheses, OptionalParentheses,
};
use crate::prelude::*;
use crate::FormatNodeRule;
@ -21,7 +22,15 @@ impl FormatNodeRule<ExprSet> for FormatExprSet {
.finish()
});
parenthesized("{", &joined, "}").fmt(f)
let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item);
parenthesized_with_dangling_comments("{", dangling, &joined, "}").fmt(f)
}
fn fmt_dangling_comments(&self, _node: &ExprSet, _f: &mut PyFormatter) -> FormatResult<()> {
// Handled as part of `fmt_fields`
Ok(())
}
}