Maybe parenthesize long constants and names (#6816)

This commit is contained in:
Micha Reiser 2023-08-24 11:47:57 +02:00 committed by GitHub
parent e4c13846e3
commit 04a9a8dd03
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 357 additions and 368 deletions

View file

@ -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
}