mirror of
https://github.com/astral-sh/ruff.git
synced 2025-10-01 14:21:53 +00:00
Create dedicated Body
nodes in the formatter CST (#3223)
This commit is contained in:
parent
cd6413ca09
commit
2261e194a0
23 changed files with 1239 additions and 611 deletions
|
@ -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)]
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue