Skip to content

Commit

Permalink
Avoid unnecessary comments check in maybe_parenthesize_expression (#…
Browse files Browse the repository at this point in the history
…7686)

## Summary

No-op refactor, but we can evaluate early if the first part of
`preserve_parentheses || has_comments` is `true`, and thus avoid looking
up the node comments.

## Test Plan

`cargo test`
  • Loading branch information
charliermarsh authored Sep 28, 2023
1 parent f53c410 commit 1c02fcd
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions crates/ruff_python_formatter/src/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,22 +187,27 @@ impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {
parenthesize,
} = self;

let comments = f.context().comments();
let preserve_parentheses = parenthesize.is_optional()
&& is_expression_parenthesized(
(*expression).into(),
f.context().comments().ranges(),
f.context().source(),
);

let node_comments = comments.leading_dangling_trailing(*expression);
// If we want to preserve parentheses, short-circuit.
if preserve_parentheses {
return expression.format().with_options(Parentheses::Always).fmt(f);
}

let has_comments = node_comments.has_leading() || node_comments.has_trailing_own_line();
let node_comments = f
.context()
.comments()
.leading_dangling_trailing(*expression);

// If the expression has comments, we always want to preserve the parentheses. This also
// ensures that we correctly handle parenthesized comments, and don't need to worry about
// them in the implementation below.
if preserve_parentheses || has_comments {
if node_comments.has_leading() || node_comments.has_trailing_own_line() {
return expression.format().with_options(Parentheses::Always).fmt(f);
}

Expand Down Expand Up @@ -252,11 +257,9 @@ impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {
// The group id is necessary because the nested expressions may reference it.
let group_id = f.group_id("optional_parentheses");
let f = &mut WithNodeLevel::new(NodeLevel::Expression(Some(group_id)), f);
ruff_formatter::prelude::best_fit_parenthesize(
&expression.format().with_options(Parentheses::Never),
)
.with_group_id(Some(group_id))
.fmt(f)
best_fit_parenthesize(&expression.format().with_options(Parentheses::Never))
.with_group_id(Some(group_id))
.fmt(f)
}
}
},
Expand Down

0 comments on commit 1c02fcd

Please sign in to comment.