Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ruff 2025 style guide #13906

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
1 change: 0 additions & 1 deletion crates/ruff_python_formatter/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ def rustfmt(code: str) -> str:
# `FStringLiteralElement`, `FStringFormatSpec` and `FStringExpressionElement` are handled by the `FString`
# implementation.
if node in (
"FString",
"FStringLiteralElement",
"FStringExpressionElement",
"FStringFormatSpec",
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
[
{
"quote_style": "preserve",
"preview": "enabled"
"quote_style": "preserve"
},
{
"quote_style": "preserve",
"preview": "enabled",
"target_version": "py312"
}
]
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
[
{
"preview": "enabled",
"source_type": "Stub"
}
]

This file was deleted.

35 changes: 2 additions & 33 deletions crates/ruff_python_formatter/src/expression/expr_f_string.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
use ruff_python_ast::{AnyNodeRef, ExprFString, StringLike};
use ruff_source_file::Locator;
use ruff_text_size::Ranged;

use crate::expression::parentheses::{
in_parentheses_only_group, NeedsParentheses, OptionalParentheses,
};
use crate::other::f_string_part::FormatFStringPart;
use crate::prelude::*;
use crate::string::implicit::FormatImplicitConcatenatedStringFlat;
use crate::string::{implicit::FormatImplicitConcatenatedString, Quoting, StringLikeExtensions};
use crate::string::{implicit::FormatImplicitConcatenatedString, StringLikeExtensions};

#[derive(Default)]
pub struct FormatExprFString;
Expand All @@ -18,11 +16,7 @@ impl FormatNodeRule<ExprFString> for FormatExprFString {
let ExprFString { value, .. } = item;

if let [f_string_part] = value.as_slice() {
FormatFStringPart::new(
f_string_part,
f_string_quoting(item, &f.context().locator()),
)
.fmt(f)
FormatFStringPart::new(f_string_part).fmt(f)
} else {
// Always join fstrings that aren't parenthesized and thus, are always on a single line.
if !f.context().node_level().is_parenthesized() {
Expand Down Expand Up @@ -72,28 +66,3 @@ impl NeedsParentheses for ExprFString {
}
}
}

pub(crate) fn f_string_quoting(f_string: &ExprFString, locator: &Locator) -> Quoting {
let unprefixed = locator
.slice(f_string.range())
.trim_start_matches(|c| c != '"' && c != '\'');
let triple_quoted = unprefixed.starts_with(r#"""""#) || unprefixed.starts_with(r"'''");

if f_string
.value
.elements()
.filter_map(|element| element.as_expression())
.any(|expression| {
let string_content = locator.slice(expression.range());
if triple_quoted {
string_content.contains(r#"""""#) || string_content.contains("'''")
} else {
string_content.contains(['"', '\''])
}
})
{
Quoting::Preserve
} else {
Quoting::CanChange
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use crate::expression::parentheses::{
};
use crate::expression::CallChainLayout;
use crate::prelude::*;
use crate::preview::is_empty_parameters_no_unnecessary_parentheses_around_return_value_enabled;

#[derive(Default)]
pub struct FormatExprSubscript {
Expand Down Expand Up @@ -108,13 +107,14 @@ impl NeedsParentheses for ExprSubscript {
if function.returns.as_deref().is_some_and(|returns| {
AnyNodeRef::ptr_eq(returns.into(), self.into())
}) {
if is_empty_parameters_no_unnecessary_parentheses_around_return_value_enabled(context) &&
function.parameters.is_empty() && !context.comments().has(&*function.parameters) {
if function.parameters.is_empty()
&& !context.comments().has(&*function.parameters)
{
// Apply the `optional_parentheses` layout when the subscript
// is in a return type position of a function without parameters.
// This ensures the subscript is parenthesized if it has a very
// long name that goes over the line length limit.
return OptionalParentheses::Multiline
return OptionalParentheses::Multiline;
}

// Don't use the best fitting layout for return type annotation because it results in the
Expand Down
75 changes: 15 additions & 60 deletions crates/ruff_python_formatter/src/expression/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ use crate::expression::parentheses::{
OptionalParentheses, Parentheses, Parenthesize,
};
use crate::prelude::*;
use crate::preview::{
is_empty_parameters_no_unnecessary_parentheses_around_return_value_enabled,
is_f_string_formatting_enabled, is_hug_parens_with_braces_and_square_brackets_enabled,
};
use crate::preview::is_hug_parens_with_braces_and_square_brackets_enabled;

mod binary_like;
pub(crate) mod expr_attribute;
Expand Down Expand Up @@ -388,18 +385,12 @@ impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {
// is parenthesized. Unless, it's the `Parenthesize::IfBreaksParenthesizedNested` layout
// where parenthesizing nested `maybe_parenthesized_expression` is explicitly desired.
_ if f.context().node_level().is_parenthesized() => {
if !is_empty_parameters_no_unnecessary_parentheses_around_return_value_enabled(
f.context(),
) {
OptionalParentheses::Never
} else if matches!(parenthesize, Parenthesize::IfBreaksParenthesizedNested) {
return parenthesize_if_expands(
&expression.format().with_options(Parentheses::Never),
)
.with_indent(!is_expression_huggable(expression, f.context()))
.fmt(f);
return if matches!(parenthesize, Parenthesize::IfBreaksParenthesizedNested) {
parenthesize_if_expands(&expression.format().with_options(Parentheses::Never))
.with_indent(!is_expression_huggable(expression, f.context()))
.fmt(f)
} else {
return expression.format().with_options(Parentheses::Never).fmt(f);
expression.format().with_options(Parentheses::Never).fmt(f)
}
}
needs_parentheses => needs_parentheses,
Expand All @@ -409,13 +400,12 @@ impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {

match needs_parentheses {
OptionalParentheses::Multiline => match parenthesize {
Parenthesize::IfBreaksParenthesized | Parenthesize::IfBreaksParenthesizedNested if !is_empty_parameters_no_unnecessary_parentheses_around_return_value_enabled(f.context()) => {
parenthesize_if_expands(&unparenthesized).fmt(f)
}

Parenthesize::IfRequired => unparenthesized.fmt(f),

Parenthesize::Optional | Parenthesize::IfBreaks | Parenthesize::IfBreaksParenthesized | Parenthesize::IfBreaksParenthesizedNested => {
Parenthesize::Optional
| Parenthesize::IfBreaks
| Parenthesize::IfBreaksParenthesized
| Parenthesize::IfBreaksParenthesizedNested => {
if can_omit_optional_parentheses(expression, f.context()) {
optional_parentheses(&unparenthesized).fmt(f)
} else {
Expand All @@ -424,9 +414,6 @@ impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {
}
},
OptionalParentheses::BestFit => match parenthesize {
Parenthesize::IfBreaksParenthesized | Parenthesize::IfBreaksParenthesizedNested if !is_empty_parameters_no_unnecessary_parentheses_around_return_value_enabled(f.context()) =>
parenthesize_if_expands(&unparenthesized).fmt(f),

Parenthesize::IfBreaksParenthesized | Parenthesize::IfBreaksParenthesizedNested => {
// Can-omit layout is relevant for `"abcd".call`. We don't want to add unnecessary
// parentheses in this case.
Expand Down Expand Up @@ -454,15 +441,11 @@ impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {
}
},
OptionalParentheses::Never => match parenthesize {
Parenthesize::IfBreaksParenthesized | Parenthesize::IfBreaksParenthesizedNested if !is_empty_parameters_no_unnecessary_parentheses_around_return_value_enabled(f.context()) => {
parenthesize_if_expands(&unparenthesized)
.with_indent(!is_expression_huggable(expression, f.context()))
.fmt(f)
}

Parenthesize::Optional | Parenthesize::IfBreaks | Parenthesize::IfRequired | Parenthesize::IfBreaksParenthesized | Parenthesize::IfBreaksParenthesizedNested => {
unparenthesized.fmt(f)
}
Parenthesize::Optional
| Parenthesize::IfBreaks
| Parenthesize::IfRequired
| Parenthesize::IfBreaksParenthesized
| Parenthesize::IfBreaksParenthesizedNested => unparenthesized.fmt(f),
},

OptionalParentheses::Always => {
Expand Down Expand Up @@ -766,32 +749,6 @@ impl<'input> CanOmitOptionalParenthesesVisitor<'input> {
return;
}

Expr::StringLiteral(ast::ExprStringLiteral { value, .. })
if value.is_implicit_concatenated() =>
{
if !is_f_string_formatting_enabled(self.context) {
self.update_max_precedence(OperatorPrecedence::String);
}

return;
}
Expr::BytesLiteral(ast::ExprBytesLiteral { value, .. })
if value.is_implicit_concatenated() =>
{
if !is_f_string_formatting_enabled(self.context) {
self.update_max_precedence(OperatorPrecedence::String);
}

return;
}
Expr::FString(ast::ExprFString { value, .. }) if value.is_implicit_concatenated() => {
if !is_f_string_formatting_enabled(self.context) {
self.update_max_precedence(OperatorPrecedence::String);
}

return;
}

// Non terminal nodes that don't have a termination token.
Expr::Named(_) | Expr::Generator(_) | Expr::Tuple(_) => {}

Expand Down Expand Up @@ -1193,8 +1150,6 @@ enum OperatorPrecedence {
BitwiseXor,
BitwiseOr,
Comparator,
// Implicit string concatenation
String,
BooleanOperation,
Conditional,
}
Expand Down
28 changes: 28 additions & 0 deletions crates/ruff_python_formatter/src/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2935,6 +2935,34 @@ impl<'ast> IntoFormat<PyFormatContext<'ast>> for ast::TypeParamParamSpec {
}
}

impl FormatRule<ast::FString, PyFormatContext<'_>> for crate::other::f_string::FormatFString {
#[inline]
fn fmt(&self, node: &ast::FString, f: &mut PyFormatter) -> FormatResult<()> {
FormatNodeRule::<ast::FString>::fmt(self, node, f)
}
}
impl<'ast> AsFormat<PyFormatContext<'ast>> for ast::FString {
type Format<'a> = FormatRefWithRule<
'a,
ast::FString,
crate::other::f_string::FormatFString,
PyFormatContext<'ast>,
>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, crate::other::f_string::FormatFString::default())
}
}
impl<'ast> IntoFormat<PyFormatContext<'ast>> for ast::FString {
type Format = FormatOwnedWithRule<
ast::FString,
crate::other::f_string::FormatFString,
PyFormatContext<'ast>,
>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, crate::other::f_string::FormatFString::default())
}
}

impl FormatRule<ast::StringLiteral, PyFormatContext<'_>>
for crate::other::string_literal::FormatStringLiteral
{
Expand Down
15 changes: 6 additions & 9 deletions crates/ruff_python_formatter/src/other/comprehension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use crate::comments::{leading_comments, trailing_comments};
use crate::expression::expr_tuple::TupleParentheses;
use crate::expression::parentheses::is_expression_parenthesized;
use crate::prelude::*;
use crate::preview::is_comprehension_leading_expression_comments_same_line_enabled;

#[derive(Default)]
pub struct FormatComprehension;
Expand Down Expand Up @@ -36,14 +35,12 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
// )
// ]
// ```
let will_be_parenthesized =
is_comprehension_leading_expression_comments_same_line_enabled(f.context())
&& self.preserve_parentheses
&& is_expression_parenthesized(
self.expression.into(),
f.context().comments().ranges(),
f.context().source(),
);
let will_be_parenthesized = self.preserve_parentheses
&& is_expression_parenthesized(
self.expression.into(),
f.context().comments().ranges(),
f.context().source(),
);

if has_leading_comments && !will_be_parenthesized {
soft_line_break_or_space().fmt(f)
Expand Down
Loading
Loading