Skip to content

Commit

Permalink
Refactor wrap to chained boolean
Browse files Browse the repository at this point in the history
  • Loading branch information
zanieb committed Aug 7, 2023
1 parent 9870470 commit f437e48
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
15 changes: 9 additions & 6 deletions crates/ruff_python_formatter/src/expression/expr_bool_op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@ use ruff_python_ast::{BoolOp, Expr, ExprBoolOp};
#[derive(Default)]
pub struct FormatExprBoolOp {
parentheses: Option<Parentheses>,
wrap: Option<bool>,
chained: bool,
}

pub struct BoolOpLayout {
pub(crate) parentheses: Option<Parentheses>,
pub(crate) wrap: Option<bool>,
pub(crate) chained: bool,
}

impl FormatRuleWithOptions<ExprBoolOp, PyFormatContext<'_>> for FormatExprBoolOp {
type Options = BoolOpLayout;
fn with_options(mut self, options: Self::Options) -> Self {
self.parentheses = options.parentheses;
self.wrap = options.wrap;
self.chained = options.chained;
self
}
}
Expand All @@ -45,11 +45,13 @@ impl FormatNodeRule<ExprBoolOp> for FormatExprBoolOp {
};

if let Expr::BoolOp(value) = first {
// Mark chained boolean operations e.g. `x and y or z`
// and avoid creating a new group
write!(
f,
[value.format().with_options(BoolOpLayout {
parentheses: None,
wrap: Some(true),
chained: true,
})]
)?;
} else {
Expand All @@ -75,7 +77,7 @@ impl FormatNodeRule<ExprBoolOp> for FormatExprBoolOp {
f,
[value.format().with_options(BoolOpLayout {
parentheses: None,
wrap: Some(true),
chained: true,
})]
)?;
} else {
Expand All @@ -86,7 +88,8 @@ impl FormatNodeRule<ExprBoolOp> for FormatExprBoolOp {
Ok(())
});

if self.wrap.is_some_and(|value| value) {
if self.chained {
// Chained boolean operations should not be given a new group
inner.fmt(f)
} else {
in_parentheses_only_group(&inner).fmt(f)
Expand Down
2 changes: 1 addition & 1 deletion crates/ruff_python_formatter/src/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl FormatRule<Expr, PyFormatContext<'_>> for FormatExpr {
.format()
.with_options(BoolOpLayout {
parentheses: Some(parentheses),
wrap: None,
chained: false,
})
.fmt(f),
Expr::NamedExpr(expr) => expr.format().fmt(f),
Expand Down

0 comments on commit f437e48

Please sign in to comment.