mirror of
https://github.com/astral-sh/ruff.git
synced 2025-08-11 14:18:04 +00:00
Avoid parenthesizing multiline strings in binary expressions (#6973)
This commit is contained in:
parent
e2b2b1759f
commit
eb552da8a9
6 changed files with 315 additions and 40 deletions
|
@ -330,6 +330,17 @@ impl<'a> Comments<'a> {
|
|||
Self::new(map)
|
||||
}
|
||||
|
||||
/// Returns `true` if the given `node` has any comments.
|
||||
#[inline]
|
||||
pub(crate) fn has<T>(&self, node: T) -> bool
|
||||
where
|
||||
T: Into<AnyNodeRef<'a>>,
|
||||
{
|
||||
self.data
|
||||
.comments
|
||||
.has(&NodeRefEqualityKey::from_ref(node.into()))
|
||||
}
|
||||
|
||||
/// Returns `true` if the given `node` has any [leading comments](self#leading-comments).
|
||||
#[inline]
|
||||
pub(crate) fn has_leading<T>(&self, node: T) -> bool
|
||||
|
|
|
@ -10,7 +10,8 @@ use ruff_python_ast::{
|
|||
};
|
||||
|
||||
use crate::comments::{trailing_comments, trailing_node_comments, SourceComment};
|
||||
use crate::expression::expr_constant::ExprConstantLayout;
|
||||
use crate::expression::expr_constant::{is_multiline_string, ExprConstantLayout};
|
||||
use crate::expression::has_parentheses;
|
||||
use crate::expression::parentheses::{
|
||||
in_parentheses_only_group, in_parentheses_only_soft_line_break,
|
||||
in_parentheses_only_soft_line_break_or_space, is_expression_parenthesized, parenthesized,
|
||||
|
@ -263,10 +264,23 @@ impl NeedsParentheses for ExprBinOp {
|
|||
fn needs_parentheses(
|
||||
&self,
|
||||
parent: AnyNodeRef,
|
||||
_context: &PyFormatContext,
|
||||
context: &PyFormatContext,
|
||||
) -> OptionalParentheses {
|
||||
if parent.is_expr_await() && !self.op.is_pow() {
|
||||
OptionalParentheses::Always
|
||||
} else if let Expr::Constant(constant) = self.left.as_ref() {
|
||||
// Multiline strings are guaranteed to never fit, avoid adding unnecessary parentheses
|
||||
if !constant.value.is_implicit_concatenated()
|
||||
&& is_multiline_string(constant, context.source())
|
||||
&& has_parentheses(&self.right, context).is_some()
|
||||
&& !context.comments().has_dangling(self)
|
||||
&& !context.comments().has(self.left.as_ref())
|
||||
&& !context.comments().has(self.right.as_ref())
|
||||
{
|
||||
OptionalParentheses::Never
|
||||
} else {
|
||||
OptionalParentheses::Multiline
|
||||
}
|
||||
} else {
|
||||
OptionalParentheses::Multiline
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue