Format implicit string continuation (#5328)

This commit is contained in:
Micha Reiser 2023-06-26 14:41:47 +02:00 committed by GitHub
parent 313711aaf9
commit 49cabca3e7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 443 additions and 60 deletions

View file

@ -2,14 +2,25 @@ use crate::comments::Comments;
use crate::expression::parentheses::{
default_expression_needs_parentheses, NeedsParentheses, Parentheses, Parenthesize,
};
use crate::expression::string::FormatString;
use crate::expression::string::{FormatString, StringLayout};
use crate::prelude::*;
use crate::{not_yet_implemented_custom_text, verbatim_text, FormatNodeRule};
use ruff_formatter::write;
use ruff_formatter::{write, FormatRuleWithOptions};
use rustpython_parser::ast::{Constant, ExprConstant};
#[derive(Default)]
pub struct FormatExprConstant;
pub struct FormatExprConstant {
string_layout: StringLayout,
}
impl FormatRuleWithOptions<ExprConstant, PyFormatContext<'_>> for FormatExprConstant {
type Options = StringLayout;
fn with_options(mut self, options: Self::Options) -> Self {
self.string_layout = options;
self
}
}
impl FormatNodeRule<ExprConstant> for FormatExprConstant {
fn fmt_fields(&self, item: &ExprConstant, f: &mut PyFormatter) -> FormatResult<()> {
@ -29,7 +40,7 @@ impl FormatNodeRule<ExprConstant> for FormatExprConstant {
Constant::Int(_) | Constant::Float(_) | Constant::Complex { .. } => {
write!(f, [verbatim_text(item)])
}
Constant::Str(_) => FormatString::new(item).fmt(f),
Constant::Str(_) => FormatString::new(item, self.string_layout).fmt(f),
Constant::Bytes(_) => {
not_yet_implemented_custom_text(r#"b"NOT_YET_IMPLEMENTED_BYTE_STRING""#).fmt(f)
}
@ -44,14 +55,6 @@ impl FormatNodeRule<ExprConstant> for FormatExprConstant {
_node: &ExprConstant,
_f: &mut PyFormatter,
) -> FormatResult<()> {
// TODO(konstin): Reactivate when string formatting works, currently a source of unstable
// formatting, e.g.:
// magic_methods = (
// "enter exit "
// # we added divmod and rdivmod here instead of numerics
// # because there is no idivmod
// "divmod rdivmod neg pos abs invert "
// )
Ok(())
}
}
@ -64,6 +67,14 @@ impl NeedsParentheses for ExprConstant {
comments: &Comments,
) -> Parentheses {
match default_expression_needs_parentheses(self.into(), parenthesize, source, comments) {
Parentheses::Optional if self.value.is_str() && parenthesize.is_if_breaks() => {
// Custom handling that only adds parentheses for implicit concatenated strings.
if parenthesize.is_if_breaks() {
Parentheses::Custom
} else {
Parentheses::Optional
}
}
Parentheses::Optional => Parentheses::Never,
parentheses => parentheses,
}