Skip to content

Commit

Permalink
Use space separator between if and ( in comprehensions
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaReiser committed Jul 10, 2024
1 parent bf3d903 commit 02d8264
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions crates/ruff_python_formatter/src/other/comprehension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,30 @@ use ruff_text_size::{Ranged, TextRange};

use crate::comments::{leading_comments, trailing_comments};
use crate::expression::expr_tuple::TupleParentheses;
use crate::expression::parentheses::is_expression_parenthesized;
use crate::prelude::*;

#[derive(Default)]
pub struct FormatComprehension;

impl FormatNodeRule<Comprehension> for FormatComprehension {
fn fmt_fields(&self, item: &Comprehension, f: &mut PyFormatter) -> FormatResult<()> {
struct Spacer<'a>(&'a Expr);
struct Spacer<'a> {
expression: &'a Expr,
preserve_parentheses: bool,
}

impl Format<PyFormatContext<'_>> for Spacer<'_> {
fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> {
if f.context().comments().has_leading(self.0) {
let has_leading_comments = f.context().comments().has_leading(self.expression);
let will_be_parenthesized = self.preserve_parentheses
&& is_expression_parenthesized(
self.expression.into(),
f.context().comments().ranges(),
f.context().source(),
);

if has_leading_comments && !will_be_parenthesized {
soft_line_break_or_space().fmt(f)
} else {
space().fmt(f)
Expand Down Expand Up @@ -68,13 +80,19 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
[
token("for"),
trailing_comments(before_target_comments),
Spacer(target),
Spacer {
expression: target,
preserve_parentheses: false
},
ExprTupleWithoutParentheses(target),
in_spacer,
leading_comments(before_in_comments),
token("in"),
trailing_comments(trailing_in_comments),
Spacer(iter),
Spacer {
expression: iter,
preserve_parentheses: true
},
iter.format(),
]
)?;
Expand All @@ -99,7 +117,10 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
leading_comments(own_line_if_comments),
token("if"),
trailing_comments(end_of_line_if_comments),
Spacer(if_case),
Spacer {
expression: if_case,
preserve_parentheses: true
},
if_case.format(),
));

Expand Down

0 comments on commit 02d8264

Please sign in to comment.