diff --git a/src/chains.rs b/src/chains.rs index 77e8341970f..d3beb8907b9 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -591,13 +591,20 @@ impl Rewrite for Chain { formatter.format_last_child(context, shape, child_shape)?; let result = formatter.join_rewrites(context, child_shape)?; - wrap_str( - result, - context.config.max_width(), - context.config.tab_spaces(), - shape, - ) - .max_width_error(shape.width, full_span) + let max_width = if context.config.style_edition() >= StyleEdition::Edition2027 { + // Keep formatting the chain when a nested expression contains an unavoidable, + // pre-existing overflow, but do not allow the rewrite to make it any wider. + crate::comment::filter_normal_code(context.snippet(full_span)) + .lines() + .map(utils::unicode_str_width) + .max() + .unwrap_or(0) + .max(context.config.max_width()) + } else { + context.config.max_width() + }; + wrap_str(result, max_width, context.config.tab_spaces(), shape) + .max_width_error(shape.width, full_span) } } diff --git a/tests/source/issue_6977_style_edition_2024.rs b/tests/source/issue_6977_style_edition_2024.rs new file mode 100644 index 00000000000..9d9ce30a5c3 --- /dev/null +++ b/tests/source/issue_6977_style_edition_2024.rs @@ -0,0 +1,11 @@ +// rustfmt-style_edition: 2024 + +fn main() { + some_struct.foo(format!( + "{}", if true { + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } else { + "" + }, + )); +} diff --git a/tests/source/issue_6977_style_edition_2027.rs b/tests/source/issue_6977_style_edition_2027.rs new file mode 100644 index 00000000000..fe5bdc9a0fd --- /dev/null +++ b/tests/source/issue_6977_style_edition_2027.rs @@ -0,0 +1,11 @@ +// rustfmt-style_edition: 2027 + +fn main() { + some_struct.foo(format!( + "{}", if true { + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } else { + "" + }, + )); +} diff --git a/tests/target/issue_6977_style_edition_2024.rs b/tests/target/issue_6977_style_edition_2024.rs new file mode 100644 index 00000000000..9d9ce30a5c3 --- /dev/null +++ b/tests/target/issue_6977_style_edition_2024.rs @@ -0,0 +1,11 @@ +// rustfmt-style_edition: 2024 + +fn main() { + some_struct.foo(format!( + "{}", if true { + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } else { + "" + }, + )); +} diff --git a/tests/target/issue_6977_style_edition_2027.rs b/tests/target/issue_6977_style_edition_2027.rs new file mode 100644 index 00000000000..8af0f1392f0 --- /dev/null +++ b/tests/target/issue_6977_style_edition_2027.rs @@ -0,0 +1,12 @@ +// rustfmt-style_edition: 2027 + +fn main() { + some_struct.foo(format!( + "{}", + if true { + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + } else { + "" + }, + )); +}