Introduce parenthesized helper (#5565)

This commit is contained in:
Micha Reiser 2023-07-07 11:28:25 +02:00 committed by GitHub
parent bf4b96c5de
commit 40ddc1604c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 60 additions and 64 deletions

View file

@ -1,5 +1,7 @@
use crate::comments::Comments;
use crate::prelude::*;
use crate::trivia::{first_non_trivia_token, first_non_trivia_token_rev, Token, TokenKind};
use ruff_formatter::{format_args, write, Argument, Arguments};
use ruff_python_ast::node::AnyNodeRef;
use rustpython_parser::ast::Ranged;
@ -119,3 +121,37 @@ pub(crate) fn is_expression_parenthesized(expr: AnyNodeRef, contents: &str) -> b
})
)
}
pub(crate) fn parenthesized<'content, 'ast, Content>(
left: &'static str,
content: &'content Content,
right: &'static str,
) -> FormatParenthesized<'content, 'ast>
where
Content: Format<PyFormatContext<'ast>>,
{
FormatParenthesized {
left,
content: Argument::new(content),
right,
}
}
pub(crate) struct FormatParenthesized<'content, 'ast> {
left: &'static str,
content: Argument<'content, PyFormatContext<'ast>>,
right: &'static str,
}
impl<'ast> Format<PyFormatContext<'ast>> for FormatParenthesized<'_, 'ast> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> {
write!(
f,
[group(&format_args![
text(self.left),
&soft_block_indent(&Arguments::from(&self.content)),
text(self.right)
])]
)
}
}