Cover Black's is_aritmetic_like formatting (#5738)

This commit is contained in:
Micha Reiser 2023-07-14 17:54:58 +02:00 committed by GitHub
parent 513de13c46
commit 8187bf9f7e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 159 additions and 96 deletions

View file

@ -1,9 +1,9 @@
use crate::comments::trailing_comments;
use crate::expression::parentheses::Parentheses;
use crate::expression::parentheses::{parenthesized, Parentheses};
use crate::prelude::*;
use crate::trivia::{SimpleTokenizer, TokenKind};
use ruff_formatter::{format_args, write};
use ruff_formatter::write;
use ruff_text_size::TextRange;
use rustpython_parser::ast::{Ranged, StmtClassDef};
@ -32,16 +32,14 @@ impl FormatNodeRule<StmtClassDef> for FormatStmtClassDef {
write!(f, [text("class"), space(), name.format()])?;
if !(bases.is_empty() && keywords.is_empty()) {
write!(
f,
[group(&format_args![
text("("),
soft_block_indent(&FormatInheritanceClause {
class_definition: item
}),
text(")")
])]
)?;
parenthesized(
"(",
&FormatInheritanceClause {
class_definition: item,
},
")",
)
.fmt(f)?;
}
let comments = f.context().comments().clone();

View file

@ -1,4 +1,5 @@
use rustpython_parser::ast::StmtExpr;
use rustpython_parser::ast;
use rustpython_parser::ast::{Expr, Operator, StmtExpr};
use crate::expression::maybe_parenthesize_expression;
use crate::expression::parentheses::Parenthesize;
@ -12,6 +13,25 @@ impl FormatNodeRule<StmtExpr> for FormatStmtExpr {
fn fmt_fields(&self, item: &StmtExpr, f: &mut PyFormatter) -> FormatResult<()> {
let StmtExpr { value, .. } = item;
maybe_parenthesize_expression(value, item, Parenthesize::Optional).fmt(f)
if is_arithmetic_like(value) {
maybe_parenthesize_expression(value, item, Parenthesize::Optional).fmt(f)
} else {
value.format().fmt(f)
}
}
}
const fn is_arithmetic_like(expression: &Expr) -> bool {
matches!(
expression,
Expr::BinOp(ast::ExprBinOp {
op: Operator::BitOr
| Operator::BitXor
| Operator::LShift
| Operator::RShift
| Operator::Add
| Operator::Sub,
..
})
)
}