Create dedicated Body nodes in the formatter CST (#3223)

This commit is contained in:
Charlie Marsh 2023-02-27 17:55:05 -05:00 committed by GitHub
parent cd6413ca09
commit 2261e194a0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 1239 additions and 611 deletions

View file

@ -4,17 +4,55 @@ use ruff_text_size::{TextRange, TextSize};
use crate::context::ASTFormatContext;
use crate::core::types::Range;
use crate::cst::Stmt;
use crate::cst::{Body, Stmt};
use crate::shared_traits::AsFormat;
use crate::trivia::{Relationship, TriviaKind};
#[derive(Copy, Clone)]
pub struct Block<'a> {
body: &'a [Stmt],
body: &'a Body,
}
impl Format<ASTFormatContext<'_>> for Block<'_> {
fn fmt(&self, f: &mut Formatter<ASTFormatContext<'_>>) -> FormatResult<()> {
for (i, stmt) in self.body.iter().enumerate() {
for (i, stmt) in self.body.node.iter().enumerate() {
if i > 0 {
write!(f, [hard_line_break()])?;
}
write!(f, [stmt.format()])?;
}
for trivia in &self.body.trivia {
if matches!(trivia.relationship, Relationship::Dangling) {
match trivia.kind {
TriviaKind::EmptyLine => {
write!(f, [empty_line()])?;
}
TriviaKind::OwnLineComment(range) => {
write!(f, [literal(range), hard_line_break()])?;
}
_ => {}
}
}
}
Ok(())
}
}
#[inline]
pub fn block(body: &Body) -> Block {
Block { body }
}
#[derive(Copy, Clone)]
pub struct Statements<'a> {
suite: &'a [Stmt],
}
impl Format<ASTFormatContext<'_>> for Statements<'_> {
fn fmt(&self, f: &mut Formatter<ASTFormatContext<'_>>) -> FormatResult<()> {
for (i, stmt) in self.suite.iter().enumerate() {
if i > 0 {
write!(f, [hard_line_break()])?;
}
@ -24,9 +62,8 @@ impl Format<ASTFormatContext<'_>> for Block<'_> {
}
}
#[inline]
pub fn block(body: &[Stmt]) -> Block {
Block { body }
pub fn statements(suite: &[Stmt]) -> Statements {
Statements { suite }
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]