Don't "flatten" nested if expressions when formatting (#6996)

This commit is contained in:
Victor Hugo Gomes 2023-08-30 01:11:58 -03:00 committed by GitHub
parent b404e54f33
commit 31947af6a3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 305 additions and 25 deletions

View file

@ -39,3 +39,72 @@ d1 = [
("b") else # 2
("c")
]
e1 = (
a
if True # 1
else b
if False # 2
else c
)
# Flattening nested if-expressions.
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else FlatValuesListIterable
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
(NamedValuesListIterable
if named
else FlatValuesListIterable)
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else (FlatValuesListIterable
if flat
else ValuesListIterable)
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else FlatValuesListIterable(1,)
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else FlatValuesListIterable + FlatValuesListIterable + FlatValuesListIterable + FlatValuesListIterable
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else (FlatValuesListIterable + FlatValuesListIterable + FlatValuesListIterable + FlatValuesListIterable
if flat
else ValuesListIterable)
)

View file

@ -1,16 +1,46 @@
use ruff_formatter::{format_args, write};
use ruff_formatter::{write, FormatRuleWithOptions};
use ruff_python_ast::node::AnyNodeRef;
use ruff_python_ast::ExprIfExp;
use ruff_python_ast::{Expr, ExprIfExp};
use crate::comments::leading_comments;
use crate::expression::parentheses::{
in_parentheses_only_group, in_parentheses_only_soft_line_break_or_space, NeedsParentheses,
OptionalParentheses,
in_parentheses_only_group, in_parentheses_only_soft_line_break_or_space,
is_expression_parenthesized, NeedsParentheses, OptionalParentheses,
};
use crate::prelude::*;
#[derive(Default, Copy, Clone)]
pub enum ExprIfExpLayout {
#[default]
Default,
/// The [`ExprIfExp`] is nested inside another [`ExprIfExp`], so it should not be given a new
/// group. For example, avoid grouping the `else` clause in:
/// ```python
/// clone._iterable_class = (
/// NamedValuesListIterable
/// if named
/// else FlatValuesListIterable
/// if flat
/// else ValuesListIterable
/// )
/// ```
Nested,
}
#[derive(Default)]
pub struct FormatExprIfExp;
pub struct FormatExprIfExp {
layout: ExprIfExpLayout,
}
impl FormatRuleWithOptions<ExprIfExp, PyFormatContext<'_>> for FormatExprIfExp {
type Options = ExprIfExpLayout;
fn with_options(mut self, options: Self::Options) -> Self {
self.layout = options;
self
}
}
impl FormatNodeRule<ExprIfExp> for FormatExprIfExp {
fn fmt_fields(&self, item: &ExprIfExp, f: &mut PyFormatter) -> FormatResult<()> {
@ -22,25 +52,33 @@ impl FormatNodeRule<ExprIfExp> for FormatExprIfExp {
} = item;
let comments = f.context().comments().clone();
// We place `if test` and `else orelse` on a single line, so the `test` and `orelse` leading
// comments go on the line before the `if` or `else` instead of directly ahead `test` or
// `orelse`
write!(
f,
[in_parentheses_only_group(&format_args![
body.format(),
in_parentheses_only_soft_line_break_or_space(),
leading_comments(comments.leading(test.as_ref())),
text("if"),
space(),
test.format(),
in_parentheses_only_soft_line_break_or_space(),
leading_comments(comments.leading(orelse.as_ref())),
text("else"),
space(),
orelse.format()
])]
)
let inner = format_with(|f: &mut PyFormatter| {
// We place `if test` and `else orelse` on a single line, so the `test` and `orelse` leading
// comments go on the line before the `if` or `else` instead of directly ahead `test` or
// `orelse`
write!(
f,
[
body.format(),
in_parentheses_only_soft_line_break_or_space(),
leading_comments(comments.leading(test.as_ref())),
text("if"),
space(),
test.format(),
in_parentheses_only_soft_line_break_or_space(),
leading_comments(comments.leading(orelse.as_ref())),
text("else"),
space(),
]
)?;
FormatOrElse { orelse }.fmt(f)
});
match self.layout {
ExprIfExpLayout::Default => in_parentheses_only_group(&inner).fmt(f),
ExprIfExpLayout::Nested => inner.fmt(f),
}
}
}
@ -53,3 +91,21 @@ impl NeedsParentheses for ExprIfExp {
OptionalParentheses::Multiline
}
}
#[derive(Debug)]
struct FormatOrElse<'a> {
orelse: &'a Expr,
}
impl Format<PyFormatContext<'_>> for FormatOrElse<'_> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> {
match self.orelse {
Expr::IfExp(expr)
if !is_expression_parenthesized(expr.into(), f.context().source()) =>
{
write!(f, [expr.format().with_options(ExprIfExpLayout::Nested)])
}
_ => write!(f, [in_parentheses_only_group(&self.orelse.format())]),
}
}
}

View file

@ -136,6 +136,15 @@ def something():
for some_boolean_variable in some_iterable
)
@@ -86,5 +78,7 @@
clone._iterable_class = (
NamedValuesListIterable
if named
- else FlatValuesListIterable if flat else ValuesListIterable
+ else FlatValuesListIterable
+ if flat
+ else ValuesListIterable
)
```
## Ruff Output
@ -221,7 +230,9 @@ def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else FlatValuesListIterable if flat else ValuesListIterable
else FlatValuesListIterable
if flat
else ValuesListIterable
)
```

View file

@ -45,6 +45,75 @@ d1 = [
("b") else # 2
("c")
]
e1 = (
a
if True # 1
else b
if False # 2
else c
)
# Flattening nested if-expressions.
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else FlatValuesListIterable
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
(NamedValuesListIterable
if named
else FlatValuesListIterable)
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else (FlatValuesListIterable
if flat
else ValuesListIterable)
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else FlatValuesListIterable(1,)
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else FlatValuesListIterable + FlatValuesListIterable + FlatValuesListIterable + FlatValuesListIterable
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else (FlatValuesListIterable + FlatValuesListIterable + FlatValuesListIterable + FlatValuesListIterable
if flat
else ValuesListIterable)
)
```
## Output
@ -96,6 +165,81 @@ d1 = [
# 2
else ("c")
]
e1 = (
a
if True # 1
else b
if False # 2
else c
)
# Flattening nested if-expressions.
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else FlatValuesListIterable
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
(NamedValuesListIterable if named else FlatValuesListIterable)
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else (FlatValuesListIterable if flat else ValuesListIterable)
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else FlatValuesListIterable(
1,
)
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else FlatValuesListIterable
+ FlatValuesListIterable
+ FlatValuesListIterable
+ FlatValuesListIterable
if flat
else ValuesListIterable
)
def something():
clone._iterable_class = (
NamedValuesListIterable
if named
else (
FlatValuesListIterable
+ FlatValuesListIterable
+ FlatValuesListIterable
+ FlatValuesListIterable
if flat
else ValuesListIterable
)
)
```