mirror of
https://github.com/astral-sh/ruff.git
synced 2025-09-28 04:45:01 +00:00
Maybe parenthesize long constants and names (#6816)
This commit is contained in:
parent
e4c13846e3
commit
04a9a8dd03
20 changed files with 357 additions and 368 deletions
|
@ -5,7 +5,7 @@ use ruff_python_ast::{Constant, ExprConstant, Ranged};
|
|||
use ruff_text_size::{TextLen, TextRange};
|
||||
|
||||
use crate::expression::number::{FormatComplex, FormatFloat, FormatInt};
|
||||
use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses};
|
||||
use crate::expression::parentheses::{should_use_best_fit, NeedsParentheses, OptionalParentheses};
|
||||
use crate::expression::string::{
|
||||
AnyString, FormatString, StringLayout, StringPrefix, StringQuotes,
|
||||
};
|
||||
|
@ -79,13 +79,16 @@ impl NeedsParentheses for ExprConstant {
|
|||
_parent: AnyNodeRef,
|
||||
context: &PyFormatContext,
|
||||
) -> OptionalParentheses {
|
||||
if self.value.is_implicit_concatenated() {
|
||||
// Don't wrap triple quoted strings
|
||||
if is_multiline_string(self, context.source()) {
|
||||
OptionalParentheses::Never
|
||||
} else {
|
||||
OptionalParentheses::Multiline
|
||||
}
|
||||
if is_multiline_string(self, context.source())
|
||||
|| self.value.is_none()
|
||||
|| self.value.is_bool()
|
||||
|| self.value.is_ellipsis()
|
||||
{
|
||||
OptionalParentheses::Never
|
||||
} else if self.value.is_implicit_concatenated() {
|
||||
OptionalParentheses::Multiline
|
||||
} else if should_use_best_fit(self, context) {
|
||||
OptionalParentheses::BestFit
|
||||
} else {
|
||||
OptionalParentheses::Never
|
||||
}
|
||||
|
@ -99,7 +102,8 @@ pub(super) fn is_multiline_string(constant: &ExprConstant, source: &str) -> bool
|
|||
let quotes =
|
||||
StringQuotes::parse(&contents[TextRange::new(prefix.text_len(), contents.text_len())]);
|
||||
|
||||
quotes.is_some_and(StringQuotes::is_triple) && contents.contains(['\n', '\r'])
|
||||
quotes.is_some_and(StringQuotes::is_triple)
|
||||
&& memchr::memchr2(b'\n', b'\r', contents.as_bytes()).is_some()
|
||||
} else {
|
||||
false
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue