Add formatting of type parameters in class and function definitions (#6161)

Part of #5062 
Closes https://github.com/astral-sh/ruff/issues/5931

Implements formatting of a sequence of type parameters in a dedicated
struct for reuse by classes, functions, and type aliases (preparing for
#5929). Adds formatting of type parameters in class and function
definitions — previously, they were just elided.
This commit is contained in:
Zanie Blue 2023-08-02 15:29:28 -05:00 committed by GitHub
parent 9425ed72a0
commit 1a60d1e3c6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 825 additions and 172 deletions

View file

@ -1,10 +1,11 @@
use ruff_formatter::write;
use ruff_formatter::{write, Buffer};
use ruff_python_ast::{Ranged, StmtClassDef};
use ruff_python_trivia::{lines_after, skip_trailing_trivia};
use crate::comments::{leading_comments, trailing_comments};
use crate::prelude::*;
use crate::statement::suite::SuiteKind;
use crate::FormatNodeRule;
#[derive(Default)]
pub struct FormatStmtClassDef;
@ -16,7 +17,7 @@ impl FormatNodeRule<StmtClassDef> for FormatStmtClassDef {
name,
arguments,
body,
type_params: _,
type_params,
decorator_list,
} = item;
@ -58,6 +59,10 @@ impl FormatNodeRule<StmtClassDef> for FormatStmtClassDef {
write!(f, [text("class"), space(), name.format()])?;
if let Some(type_params) = type_params.as_deref() {
write!(f, [type_params.format()])?;
}
if let Some(arguments) = arguments.as_deref() {
// Drop empty parentheses, e.g., in:
// ```python

View file

@ -80,15 +80,13 @@ impl FormatRule<AnyFunctionDefinition<'_>, PyFormatContext<'_>> for FormatAnyFun
let name = item.name();
write!(
f,
[
text("def"),
space(),
name.format(),
item.arguments().format(),
]
)?;
write!(f, [text("def"), space(), name.format()])?;
if let Some(type_params) = item.type_params() {
write!(f, [type_params.format()])?;
}
write!(f, [item.arguments().format()])?;
if let Some(return_annotation) = item.returns() {
write!(