Add a with_dangling_comments to the parenthesized formatter (#6402)

See: https://github.com/astral-sh/ruff/pull/6376#discussion_r1285514328.
This commit is contained in:
Charlie Marsh 2023-08-07 15:12:12 -04:00 committed by GitHub
parent bb96647d66
commit 8919b6ad9a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 60 additions and 82 deletions

View file

@ -116,25 +116,6 @@ where
}
}
/// Formats `content` enclosed by the `left` and `right` parentheses, along with any dangling
/// comments on the opening parenthesis itself.
pub(crate) fn parenthesized_with_dangling_comments<'content, 'ast, Content>(
left: &'static str,
comments: &'content [SourceComment],
content: &'content Content,
right: &'static str,
) -> FormatParenthesized<'content, 'ast>
where
Content: Format<PyFormatContext<'ast>>,
{
FormatParenthesized {
left,
comments,
content: Argument::new(content),
right,
}
}
pub(crate) struct FormatParenthesized<'content, 'ast> {
left: &'static str,
comments: &'content [SourceComment],
@ -142,6 +123,24 @@ pub(crate) struct FormatParenthesized<'content, 'ast> {
right: &'static str,
}
impl<'content, 'ast> FormatParenthesized<'content, 'ast> {
/// Inserts any dangling comments that should be placed immediately after the open parenthesis.
/// For example:
/// ```python
/// [ # comment
/// 1,
/// 2,
/// 3,
/// ]
/// ```
pub(crate) fn with_dangling_comments(
self,
comments: &'content [SourceComment],
) -> FormatParenthesized<'content, 'ast> {
FormatParenthesized { comments, ..self }
}
}
impl<'ast> Format<PyFormatContext<'ast>> for FormatParenthesized<'_, 'ast> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> {
let inner = format_with(|f| {