Prefer breaking the implicit string concatenation over breaking before % (#5947)

This commit is contained in:
Micha Reiser
2023-07-24 18:30:42 +02:00
committed by GitHub
parent 42d969f19f
commit fdb3c8852f
5 changed files with 637 additions and 80 deletions

View File

@@ -18,24 +18,48 @@ use crate::QuoteStyle;
pub(super) struct FormatString<'a> {
constant: &'a ExprConstant,
layout: StringLayout,
}
#[derive(Default, Copy, Clone, Debug)]
pub enum StringLayout {
#[default]
Default,
ImplicitConcatenatedBinaryLeftSide,
}
impl<'a> FormatString<'a> {
pub(super) fn new(constant: &'a ExprConstant) -> Self {
debug_assert!(constant.value.is_str());
Self { constant }
Self {
constant,
layout: StringLayout::Default,
}
}
pub(super) fn with_layout(mut self, layout: StringLayout) -> Self {
self.layout = layout;
self
}
}
impl<'a> Format<PyFormatContext<'_>> for FormatString<'a> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> {
let string_range = self.constant.range();
let string_content = f.context().locator().slice(string_range);
match self.layout {
StringLayout::Default => {
let string_range = self.constant.range();
let string_content = f.context().locator().slice(string_range);
if is_implicit_concatenation(string_content) {
in_parentheses_only_group(&FormatStringContinuation::new(self.constant)).fmt(f)
} else {
FormatStringPart::new(string_range).fmt(f)
if is_implicit_concatenation(string_content) {
in_parentheses_only_group(&FormatStringContinuation::new(self.constant)).fmt(f)
} else {
FormatStringPart::new(string_range).fmt(f)
}
}
StringLayout::ImplicitConcatenatedBinaryLeftSide => {
FormatStringContinuation::new(self.constant).fmt(f)
}
}
}
}