Skip to content

Commit

Permalink
Ruff 2025 style guide (#13906)
Browse files Browse the repository at this point in the history
Closes #13371
  • Loading branch information
MichaReiser authored Jan 3, 2025
1 parent 0837cdd commit 26800c0
Show file tree
Hide file tree
Showing 62 changed files with 1,789 additions and 3,880 deletions.
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.

32 changes: 3 additions & 29 deletions crates/ruff_python_formatter/src/expression/expr_f_string.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
use ruff_python_ast::{AnyNodeRef, ExprFString, StringLike};
use ruff_text_size::TextSlice;

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

#[derive(Default)]
pub struct FormatExprFString;
Expand All @@ -23,7 +22,7 @@ impl FormatNodeRule<ExprFString> for FormatExprFString {
// [`ruff_python_ast::FStringValue::single`] constructor.
let f_string = f_string_part.as_f_string().unwrap();

FormatFString::new(f_string, f_string_quoting(item, f.context().source())).fmt(f)
f_string.format().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 @@ -58,28 +57,3 @@ impl NeedsParentheses for ExprFString {
}
}
}

pub(crate) fn f_string_quoting(f_string: &ExprFString, source: &str) -> Quoting {
let unprefixed = source
.slice(f_string)
.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 = source.slice(expression);
if triple_quoted {
string_content.contains(r#"""""#) || string_content.contains("'''")
} else {
string_content.contains(['"', '\''])
}
})
{
Quoting::Preserve
} else {
Quoting::CanChange
}
}
8 changes: 4 additions & 4 deletions crates/ruff_python_formatter/src/expression/expr_subscript.rs
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

0 comments on commit 26800c0

Please # to comment.