Rename Comments methods (#6649)

This commit is contained in:
Micha Reiser 2023-08-18 08:37:01 +02:00 committed by GitHub
parent 3ceb6fbeb0
commit 0cea4975fc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
44 changed files with 128 additions and 172 deletions

View file

@ -33,7 +33,7 @@ impl Format<PyFormatContext<'_>> for FormatLeadingComments<'_> {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let leading_comments = match self { let leading_comments = match self {
FormatLeadingComments::Node(node) => comments.leading_comments(*node), FormatLeadingComments::Node(node) => comments.leading(*node),
FormatLeadingComments::Comments(comments) => comments, FormatLeadingComments::Comments(comments) => comments,
}; };
@ -124,7 +124,7 @@ impl Format<PyFormatContext<'_>> for FormatTrailingComments<'_> {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let trailing_comments = match self { let trailing_comments = match self {
FormatTrailingComments::Node(node) => comments.trailing_comments(*node), FormatTrailingComments::Node(node) => comments.trailing(*node),
FormatTrailingComments::Comments(comments) => comments, FormatTrailingComments::Comments(comments) => comments,
}; };
@ -198,7 +198,7 @@ impl Format<PyFormatContext<'_>> for FormatDanglingComments<'_> {
let dangling_comments = match self { let dangling_comments = match self {
Self::Comments(comments) => comments, Self::Comments(comments) => comments,
Self::Node(node) => comments.dangling_comments(*node), Self::Node(node) => comments.dangling(*node),
}; };
let mut first = true; let mut first = true;

View file

@ -332,16 +332,16 @@ impl<'a> Comments<'a> {
/// Returns `true` if the given `node` has any [leading comments](self#leading-comments). /// Returns `true` if the given `node` has any [leading comments](self#leading-comments).
#[inline] #[inline]
pub(crate) fn has_leading_comments<T>(&self, node: T) -> bool pub(crate) fn has_leading<T>(&self, node: T) -> bool
where where
T: Into<AnyNodeRef<'a>>, T: Into<AnyNodeRef<'a>>,
{ {
!self.leading_comments(node).is_empty() !self.leading(node).is_empty()
} }
/// Returns the `node`'s [leading comments](self#leading-comments). /// Returns the `node`'s [leading comments](self#leading-comments).
#[inline] #[inline]
pub(crate) fn leading_comments<T>(&self, node: T) -> &[SourceComment] pub(crate) fn leading<T>(&self, node: T) -> &[SourceComment]
where where
T: Into<AnyNodeRef<'a>>, T: Into<AnyNodeRef<'a>>,
{ {
@ -351,15 +351,15 @@ impl<'a> Comments<'a> {
} }
/// Returns `true` if node has any [dangling comments](self#dangling-comments). /// Returns `true` if node has any [dangling comments](self#dangling-comments).
pub(crate) fn has_dangling_comments<T>(&self, node: T) -> bool pub(crate) fn has_dangling<T>(&self, node: T) -> bool
where where
T: Into<AnyNodeRef<'a>>, T: Into<AnyNodeRef<'a>>,
{ {
!self.dangling_comments(node).is_empty() !self.dangling(node).is_empty()
} }
/// Returns the [dangling comments](self#dangling-comments) of `node` /// Returns the [dangling comments](self#dangling-comments) of `node`
pub(crate) fn dangling_comments<T>(&self, node: T) -> &[SourceComment] pub(crate) fn dangling<T>(&self, node: T) -> &[SourceComment]
where where
T: Into<AnyNodeRef<'a>>, T: Into<AnyNodeRef<'a>>,
{ {
@ -370,7 +370,7 @@ impl<'a> Comments<'a> {
/// Returns the `node`'s [trailing comments](self#trailing-comments). /// Returns the `node`'s [trailing comments](self#trailing-comments).
#[inline] #[inline]
pub(crate) fn trailing_comments<T>(&self, node: T) -> &[SourceComment] pub(crate) fn trailing<T>(&self, node: T) -> &[SourceComment]
where where
T: Into<AnyNodeRef<'a>>, T: Into<AnyNodeRef<'a>>,
{ {
@ -381,43 +381,35 @@ impl<'a> Comments<'a> {
/// Returns `true` if the given `node` has any [trailing comments](self#trailing-comments). /// Returns `true` if the given `node` has any [trailing comments](self#trailing-comments).
#[inline] #[inline]
pub(crate) fn has_trailing_comments<T>(&self, node: T) -> bool pub(crate) fn has_trailing<T>(&self, node: T) -> bool
where where
T: Into<AnyNodeRef<'a>>, T: Into<AnyNodeRef<'a>>,
{ {
!self.trailing_comments(node).is_empty() !self.trailing(node).is_empty()
} }
/// Returns `true` if the given `node` has any [trailing own line comments](self#trailing-comments). /// Returns `true` if the given `node` has any [trailing own line comments](self#trailing-comments).
#[inline] #[inline]
pub(crate) fn has_trailing_own_line_comments<T>(&self, node: T) -> bool pub(crate) fn has_trailing_own_line<T>(&self, node: T) -> bool
where where
T: Into<AnyNodeRef<'a>>, T: Into<AnyNodeRef<'a>>,
{ {
self.trailing_comments(node) self.trailing(node)
.iter() .iter()
.any(|comment| comment.line_position().is_own_line()) .any(|comment| comment.line_position().is_own_line())
} }
/// Returns an iterator over the [leading](self#leading-comments) and [trailing comments](self#trailing-comments) of `node`. /// Returns an iterator over the [leading](self#leading-comments) and [trailing comments](self#trailing-comments) of `node`.
pub(crate) fn leading_trailing_comments<T>( pub(crate) fn leading_trailing<T>(&self, node: T) -> impl Iterator<Item = &SourceComment>
&self,
node: T,
) -> impl Iterator<Item = &SourceComment>
where where
T: Into<AnyNodeRef<'a>>, T: Into<AnyNodeRef<'a>>,
{ {
let node = node.into(); let comments = self.leading_dangling_trailing(node);
self.leading_comments(node) comments.leading.iter().chain(comments.trailing)
.iter()
.chain(self.trailing_comments(node).iter())
} }
/// Returns an iterator over the [leading](self#leading-comments), [dangling](self#dangling-comments), and [trailing](self#trailing) comments of `node`. /// Returns an iterator over the [leading](self#leading-comments), [dangling](self#dangling-comments), and [trailing](self#trailing) comments of `node`.
pub(crate) fn leading_dangling_trailing_comments<T>( pub(crate) fn leading_dangling_trailing<T>(&self, node: T) -> LeadingDanglingTrailingComments
&self,
node: T,
) -> LeadingDanglingTrailingComments
where where
T: Into<AnyNodeRef<'a>>, T: Into<AnyNodeRef<'a>>,
{ {
@ -426,30 +418,12 @@ impl<'a> Comments<'a> {
.leading_dangling_trailing(&NodeRefEqualityKey::from_ref(node.into())) .leading_dangling_trailing(&NodeRefEqualityKey::from_ref(node.into()))
} }
/// Returns any comments on the open parenthesis of a `node`.
///
/// For example, `# comment` in:
/// ```python
/// ( # comment
/// foo.bar
/// )
/// ```
#[inline]
pub(crate) fn open_parenthesis_comment<T>(&self, node: T) -> Option<&SourceComment>
where
T: Into<AnyNodeRef<'a>>,
{
self.leading_comments(node)
.first()
.filter(|comment| comment.line_position.is_end_of_line())
}
#[inline(always)] #[inline(always)]
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
pub(crate) fn assert_formatted_all_comments(&self, _source_code: SourceCode) {} pub(crate) fn assert_all_formatted(&self, _source_code: SourceCode) {}
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
pub(crate) fn assert_formatted_all_comments(&self, source_code: SourceCode) { pub(crate) fn assert_all_formatted(&self, source_code: SourceCode) {
use std::fmt::Write; use std::fmt::Write;
let mut output = String::new(); let mut output = String::new();
@ -481,7 +455,7 @@ impl<'a> Comments<'a> {
/// normally if `node` is the first or last node of a suppression range. /// normally if `node` is the first or last node of a suppression range.
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
pub(crate) fn mark_verbatim_node_comments_formatted(&self, node: AnyNodeRef) { pub(crate) fn mark_verbatim_node_comments_formatted(&self, node: AnyNodeRef) {
for dangling in self.dangling_comments(node) { for dangling in self.dangling(node) {
dangling.mark_formatted(); dangling.mark_formatted();
} }
@ -505,7 +479,7 @@ struct MarkVerbatimCommentsAsFormattedVisitor<'a>(&'a Comments<'a>);
impl<'a> PreorderVisitor<'a> for MarkVerbatimCommentsAsFormattedVisitor<'a> { impl<'a> PreorderVisitor<'a> for MarkVerbatimCommentsAsFormattedVisitor<'a> {
fn enter_node(&mut self, node: AnyNodeRef<'a>) -> TraversalSignal { fn enter_node(&mut self, node: AnyNodeRef<'a>) -> TraversalSignal {
for comment in self.0.leading_dangling_trailing_comments(node) { for comment in self.0.leading_dangling_trailing(node) {
comment.mark_formatted(); comment.mark_formatted();
} }

View file

@ -45,7 +45,7 @@ impl FormatNodeRule<ExprAttribute> for FormatExprAttribute {
); );
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_comments = comments.dangling_comments(item); let dangling_comments = comments.dangling(item);
let leading_attribute_comments_start = dangling_comments let leading_attribute_comments_start = dangling_comments
.partition_point(|comment| comment.line_position().is_end_of_line()); .partition_point(|comment| comment.line_position().is_end_of_line());
let (trailing_dot_comments, leading_attribute_comments) = let (trailing_dot_comments, leading_attribute_comments) =
@ -88,7 +88,7 @@ impl FormatNodeRule<ExprAttribute> for FormatExprAttribute {
value.format().fmt(f)?; value.format().fmt(f)?;
} }
if comments.has_trailing_own_line_comments(value.as_ref()) { if comments.has_trailing_own_line(value.as_ref()) {
hard_line_break().fmt(f)?; hard_line_break().fmt(f)?;
} }
@ -171,10 +171,10 @@ impl NeedsParentheses for ExprAttribute {
OptionalParentheses::Multiline OptionalParentheses::Multiline
} else if context } else if context
.comments() .comments()
.dangling_comments(self) .dangling(self)
.iter() .iter()
.any(|comment| comment.line_position().is_own_line()) .any(|comment| comment.line_position().is_own_line())
|| context.comments().has_trailing_own_line_comments(self) || context.comments().has_trailing_own_line(self)
{ {
OptionalParentheses::Always OptionalParentheses::Always
} else { } else {

View file

@ -29,10 +29,7 @@ impl FormatNodeRule<ExprBinOp> for FormatExprBinOp {
match Self::layout(item, f.context()) { match Self::layout(item, f.context()) {
BinOpLayout::LeftString(expression) => { BinOpLayout::LeftString(expression) => {
let right_has_leading_comment = f let right_has_leading_comment = comments.has_leading(item.right.as_ref());
.context()
.comments()
.has_leading_comments(item.right.as_ref());
let format_right_and_op = format_with(|f| { let format_right_and_op = format_with(|f| {
if right_has_leading_comment { if right_has_leading_comment {
@ -98,7 +95,7 @@ impl FormatNodeRule<ExprBinOp> for FormatExprBinOp {
right, right,
} = current; } = current;
let operator_comments = comments.dangling_comments(current); let operator_comments = comments.dangling(current);
let needs_space = !is_simple_power_expression(current); let needs_space = !is_simple_power_expression(current);
let before_operator_space = if needs_space { let before_operator_space = if needs_space {
@ -117,9 +114,7 @@ impl FormatNodeRule<ExprBinOp> for FormatExprBinOp {
)?; )?;
// Format the operator on its own line if the right side has any leading comments. // Format the operator on its own line if the right side has any leading comments.
if comments.has_leading_comments(right.as_ref()) if comments.has_leading(right.as_ref()) || !operator_comments.is_empty() {
|| !operator_comments.is_empty()
{
hard_line_break().fmt(f)?; hard_line_break().fmt(f)?;
} else if needs_space { } else if needs_space {
space().fmt(f)?; space().fmt(f)?;
@ -171,8 +166,8 @@ impl FormatExprBinOp {
if bin_op.op == Operator::Mod if bin_op.op == Operator::Mod
&& context.node_level().is_parenthesized() && context.node_level().is_parenthesized()
&& !comments.has_dangling_comments(constant) && !comments.has_dangling(constant)
&& !comments.has_dangling_comments(bin_op) && !comments.has_dangling(bin_op)
{ {
BinOpLayout::LeftString(constant) BinOpLayout::LeftString(constant)
} else { } else {

View file

@ -50,7 +50,7 @@ impl FormatNodeRule<ExprBoolOp> for FormatExprBoolOp {
FormatValue { value: first }.fmt(f)?; FormatValue { value: first }.fmt(f)?;
for value in values { for value in values {
let leading_value_comments = comments.leading_comments(value); let leading_value_comments = comments.leading(value);
// Format the expressions leading comments **before** the operator // Format the expressions leading comments **before** the operator
if leading_value_comments.is_empty() { if leading_value_comments.is_empty() {
write!(f, [in_parentheses_only_soft_line_break_or_space()])?; write!(f, [in_parentheses_only_soft_line_break_or_space()])?;

View file

@ -29,7 +29,7 @@ impl FormatNodeRule<ExprCompare> for FormatExprCompare {
assert_eq!(comparators.len(), ops.len()); assert_eq!(comparators.len(), ops.len());
for (operator, comparator) in ops.iter().zip(comparators) { for (operator, comparator) in ops.iter().zip(comparators) {
let leading_comparator_comments = comments.leading_comments(comparator); let leading_comparator_comments = comments.leading(comparator);
if leading_comparator_comments.is_empty() { if leading_comparator_comments.is_empty() {
write!(f, [in_parentheses_only_soft_line_break_or_space()])?; write!(f, [in_parentheses_only_soft_line_break_or_space()])?;
} else { } else {

View file

@ -43,7 +43,7 @@ impl Format<PyFormatContext<'_>> for KeyValuePair<'_> {
) )
} else { } else {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let leading_value_comments = comments.leading_comments(self.value); let leading_value_comments = comments.leading(self.value);
write!( write!(
f, f,
[ [
@ -67,7 +67,7 @@ impl FormatNodeRule<ExprDict> for FormatExprDict {
debug_assert_eq!(keys.len(), values.len()); debug_assert_eq!(keys.len(), values.len());
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
if values.is_empty() { if values.is_empty() {
return empty_parenthesized("{", dangling, "}").fmt(f); return empty_parenthesized("{", dangling, "}").fmt(f);

View file

@ -29,7 +29,7 @@ impl FormatNodeRule<ExprDictComp> for FormatExprDictComp {
}); });
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
write!( write!(
f, f,

View file

@ -51,7 +51,7 @@ impl FormatNodeRule<ExprGeneratorExp> for FormatExprGeneratorExp {
}); });
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
if self.parentheses == GeneratorExpParentheses::StripIfOnlyFunctionArg if self.parentheses == GeneratorExpParentheses::StripIfOnlyFunctionArg
&& dangling.is_empty() && dangling.is_empty()

View file

@ -30,12 +30,12 @@ impl FormatNodeRule<ExprIfExp> for FormatExprIfExp {
[in_parentheses_only_group(&format_args![ [in_parentheses_only_group(&format_args![
body.format(), body.format(),
in_parentheses_only_soft_line_break_or_space(), in_parentheses_only_soft_line_break_or_space(),
leading_comments(comments.leading_comments(test.as_ref())), leading_comments(comments.leading(test.as_ref())),
text("if"), text("if"),
space(), space(),
test.format(), test.format(),
in_parentheses_only_soft_line_break_or_space(), in_parentheses_only_soft_line_break_or_space(),
leading_comments(comments.leading_comments(orelse.as_ref())), leading_comments(comments.leading(orelse.as_ref())),
text("else"), text("else"),
space(), space(),
orelse.format() orelse.format()

View file

@ -21,7 +21,7 @@ impl FormatNodeRule<ExprList> for FormatExprList {
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
if elts.is_empty() { if elts.is_empty() {
return empty_parenthesized("[", dangling, "]").fmt(f); return empty_parenthesized("[", dangling, "]").fmt(f);

View file

@ -27,7 +27,7 @@ impl FormatNodeRule<ExprListComp> for FormatExprListComp {
}); });
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
write!( write!(
f, f,

View file

@ -22,7 +22,7 @@ impl FormatNodeRule<ExprNamedExpr> for FormatExprNamedExpr {
// This context, a dangling comment is an end-of-line comment on the same line as the `:=`. // This context, a dangling comment is an end-of-line comment on the same line as the `:=`.
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
write!( write!(
f, f,

View file

@ -22,7 +22,7 @@ impl FormatNodeRule<ExprSet> for FormatExprSet {
}); });
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
parenthesized("{", &joined, "}") parenthesized("{", &joined, "}")
.with_dangling_comments(dangling) .with_dangling_comments(dangling)

View file

@ -27,7 +27,7 @@ impl FormatNodeRule<ExprSetComp> for FormatExprSetComp {
}); });
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
write!( write!(
f, f,

View file

@ -39,7 +39,7 @@ impl FormatNodeRule<ExprSlice> for FormatExprSlice {
// to handle newlines and spacing, or the node is None and we insert the corresponding // to handle newlines and spacing, or the node is None and we insert the corresponding
// slice of dangling comments // slice of dangling comments
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let slice_dangling_comments = comments.dangling_comments(item.as_any_node_ref()); let slice_dangling_comments = comments.dangling(item.as_any_node_ref());
// Put the dangling comments (where the nodes are missing) into buckets // Put the dangling comments (where the nodes are missing) into buckets
let first_colon_partition_index = let first_colon_partition_index =
slice_dangling_comments.partition_point(|x| x.slice().start() < first_colon.start()); slice_dangling_comments.partition_point(|x| x.slice().start() < first_colon.start());
@ -102,7 +102,7 @@ impl FormatNodeRule<ExprSlice> for FormatExprSlice {
// Upper // Upper
if let Some(upper) = upper { if let Some(upper) = upper {
let upper_leading_comments = comments.leading_comments(upper.as_ref()); let upper_leading_comments = comments.leading(upper.as_ref());
leading_comments_spacing(f, upper_leading_comments)?; leading_comments_spacing(f, upper_leading_comments)?;
write!(f, [upper.format(), line_suffix_boundary()])?; write!(f, [upper.format(), line_suffix_boundary()])?;
} else { } else {
@ -134,7 +134,7 @@ impl FormatNodeRule<ExprSlice> for FormatExprSlice {
space().fmt(f)?; space().fmt(f)?;
} }
if let Some(step) = step { if let Some(step) = step {
let step_leading_comments = comments.leading_comments(step.as_ref()); let step_leading_comments = comments.leading(step.as_ref());
leading_comments_spacing(f, step_leading_comments)?; leading_comments_spacing(f, step_leading_comments)?;
step.format().fmt(f)?; step.format().fmt(f)?;
} else if !dangling_step_comments.is_empty() { } else if !dangling_step_comments.is_empty() {

View file

@ -21,7 +21,7 @@ impl FormatNodeRule<ExprStarred> for FormatExprStarred {
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
write!(f, [text("*"), dangling_comments(dangling), value.format()]) write!(f, [text("*"), dangling_comments(dangling), value.format()])
} }

View file

@ -37,7 +37,7 @@ impl FormatNodeRule<ExprSubscript> for FormatExprSubscript {
let call_chain_layout = self.call_chain_layout.apply_in_node(item, f); let call_chain_layout = self.call_chain_layout.apply_in_node(item, f);
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_comments = comments.dangling_comments(item.as_any_node_ref()); let dangling_comments = comments.dangling(item.as_any_node_ref());
debug_assert!( debug_assert!(
dangling_comments.len() <= 1, dangling_comments.len() <= 1,
"A subscript expression can only have a single dangling comment, the one after the bracket" "A subscript expression can only have a single dangling comment, the one after the bracket"

View file

@ -107,7 +107,7 @@ impl FormatNodeRule<ExprTuple> for FormatExprTuple {
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
// Handle the edge cases of an empty tuple and a tuple with one element // Handle the edge cases of an empty tuple and a tuple with one element
// //

View file

@ -39,7 +39,7 @@ impl FormatNodeRule<ExprUnaryOp> for FormatExprUnaryOp {
// (not # comment // (not # comment
// a) // a)
// ``` // ```
let leading_operand_comments = comments.leading_comments(operand.as_ref()); let leading_operand_comments = comments.leading(operand.as_ref());
let trailing_operator_comments_end = let trailing_operator_comments_end =
leading_operand_comments.partition_point(|p| p.line_position().is_end_of_line()); leading_operand_comments.partition_point(|p| p.line_position().is_end_of_line());
let (trailing_operator_comments, leading_operand_comments) = let (trailing_operator_comments, leading_operand_comments) =

View file

@ -108,7 +108,20 @@ impl FormatRule<Expr, PyFormatContext<'_>> for FormatExpr {
if parenthesize { if parenthesize {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let open_parenthesis_comment = comments.open_parenthesis_comment(expression);
// Any comments on the open parenthesis of a `node`.
//
// For example, `# comment` in:
// ```python
// ( # comment
// foo.bar
// )
// ```
let open_parenthesis_comment = comments
.leading(expression)
.first()
.filter(|comment| comment.line_position().is_end_of_line());
parenthesized("(", &format_expr, ")") parenthesized("(", &format_expr, ")")
.with_dangling_comments( .with_dangling_comments(
open_parenthesis_comment open_parenthesis_comment
@ -167,8 +180,8 @@ impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {
let preserve_parentheses = parenthesize.is_optional() let preserve_parentheses = parenthesize.is_optional()
&& is_expression_parenthesized((*expression).into(), f.context().source()); && is_expression_parenthesized((*expression).into(), f.context().source());
let has_comments = comments.has_leading_comments(*expression) let has_comments =
|| comments.has_trailing_own_line_comments(*expression); comments.has_leading(*expression) || comments.has_trailing_own_line(*expression);
// If the expression has comments, we always want to preserve the parentheses. This also // If the expression has comments, we always want to preserve the parentheses. This also
// ensures that we correctly handle parenthesized comments, and don't need to worry about // ensures that we correctly handle parenthesized comments, and don't need to worry about
@ -655,11 +668,7 @@ pub(crate) fn has_own_parentheses(
Expr::List(ast::ExprList { elts, .. }) Expr::List(ast::ExprList { elts, .. })
| Expr::Set(ast::ExprSet { elts, .. }) | Expr::Set(ast::ExprSet { elts, .. })
| Expr::Tuple(ast::ExprTuple { elts, .. }) => { | Expr::Tuple(ast::ExprTuple { elts, .. }) => {
if !elts.is_empty() if !elts.is_empty() || context.comments().has_dangling(AnyNodeRef::from(expr)) {
|| context
.comments()
.has_dangling_comments(AnyNodeRef::from(expr))
{
Some(OwnParentheses::NonEmpty) Some(OwnParentheses::NonEmpty)
} else { } else {
Some(OwnParentheses::Empty) Some(OwnParentheses::Empty)
@ -667,22 +676,14 @@ pub(crate) fn has_own_parentheses(
} }
Expr::Dict(ast::ExprDict { keys, .. }) => { Expr::Dict(ast::ExprDict { keys, .. }) => {
if !keys.is_empty() if !keys.is_empty() || context.comments().has_dangling(AnyNodeRef::from(expr)) {
|| context
.comments()
.has_dangling_comments(AnyNodeRef::from(expr))
{
Some(OwnParentheses::NonEmpty) Some(OwnParentheses::NonEmpty)
} else { } else {
Some(OwnParentheses::Empty) Some(OwnParentheses::Empty)
} }
} }
Expr::Call(ast::ExprCall { arguments, .. }) => { Expr::Call(ast::ExprCall { arguments, .. }) => {
if !arguments.is_empty() if !arguments.is_empty() || context.comments().has_dangling(AnyNodeRef::from(expr)) {
|| context
.comments()
.has_dangling_comments(AnyNodeRef::from(expr))
{
Some(OwnParentheses::NonEmpty) Some(OwnParentheses::NonEmpty)
} else { } else {
Some(OwnParentheses::Empty) Some(OwnParentheses::Empty)

View file

@ -160,7 +160,7 @@ impl Format<PyFormatContext<'_>> for FormatStringContinuation<'_> {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let locator = f.context().locator(); let locator = f.context().locator();
let quote_style = f.options().quote_style(); let quote_style = f.options().quote_style();
let mut dangling_comments = comments.dangling_comments(self.string); let mut dangling_comments = comments.dangling(self.string);
let string_range = self.string.range(); let string_range = self.string.range();
let string_content = locator.slice(string_range); let string_content = locator.slice(string_range);

View file

@ -49,7 +49,7 @@ where
fn fmt(&self, node: &N, f: &mut PyFormatter) -> FormatResult<()> { fn fmt(&self, node: &N, f: &mut PyFormatter) -> FormatResult<()> {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let node_comments = comments.leading_dangling_trailing_comments(node.as_any_node_ref()); let node_comments = comments.leading_dangling_trailing(node.as_any_node_ref());
if self.is_suppressed(node_comments.trailing, f.context()) { if self.is_suppressed(node_comments.trailing, f.context()) {
suppressed_node(node.as_any_node_ref()).fmt(f) suppressed_node(node.as_any_node_ref()).fmt(f)
@ -161,7 +161,7 @@ pub fn format_node<'a>(
formatted formatted
.context() .context()
.comments() .comments()
.assert_formatted_all_comments(SourceCode::new(source)); .assert_all_formatted(SourceCode::new(source));
Ok(formatted) Ok(formatted)
} }

View file

@ -24,7 +24,7 @@ impl FormatNodeRule<Arguments> for FormatArguments {
// ``` // ```
if item.args.is_empty() && item.keywords.is_empty() { if item.args.is_empty() && item.keywords.is_empty() {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
return write!(f, [empty_parenthesized("(", dangling, ")")]); return write!(f, [empty_parenthesized("(", dangling, ")")]);
} }
@ -77,7 +77,7 @@ impl FormatNodeRule<Arguments> for FormatArguments {
// c, // c,
// ) // )
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_comments = comments.dangling_comments(item.as_any_node_ref()); let dangling_comments = comments.dangling(item.as_any_node_ref());
write!( write!(
f, f,

View file

@ -15,7 +15,7 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
impl Format<PyFormatContext<'_>> for Spacer<'_> { impl Format<PyFormatContext<'_>> for Spacer<'_> {
fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> { fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> {
if f.context().comments().has_leading_comments(self.0) { if f.context().comments().has_leading(self.0) {
soft_line_break_or_space().fmt(f) soft_line_break_or_space().fmt(f)
} else { } else {
space().fmt(f) space().fmt(f)
@ -36,13 +36,13 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
} }
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_item_comments = comments.dangling_comments(item); let dangling_item_comments = comments.dangling(item);
let (before_target_comments, before_in_comments) = dangling_item_comments.split_at( let (before_target_comments, before_in_comments) = dangling_item_comments.split_at(
dangling_item_comments dangling_item_comments
.partition_point(|comment| comment.slice().end() < target.start()), .partition_point(|comment| comment.slice().end() < target.start()),
); );
let trailing_in_comments = comments.dangling_comments(iter); let trailing_in_comments = comments.dangling(iter);
let in_spacer = format_with(|f| { let in_spacer = format_with(|f| {
if before_in_comments.is_empty() { if before_in_comments.is_empty() {
@ -73,7 +73,7 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
let joined = format_with(|f| { let joined = format_with(|f| {
let mut joiner = f.join_with(soft_line_break_or_space()); let mut joiner = f.join_with(soft_line_break_or_space());
for if_case in ifs { for if_case in ifs {
let dangling_if_comments = comments.dangling_comments(if_case); let dangling_if_comments = comments.dangling(if_case);
let (own_line_if_comments, end_of_line_if_comments) = dangling_if_comments let (own_line_if_comments, end_of_line_if_comments) = dangling_if_comments
.split_at( .split_at(

View file

@ -46,7 +46,7 @@ impl FormatNodeRule<ExceptHandlerExceptHandler> for FormatExceptHandlerExceptHan
} = item; } = item;
let comments_info = f.context().comments().clone(); let comments_info = f.context().comments().clone();
let dangling_comments = comments_info.dangling_comments(item); let dangling_comments = comments_info.dangling(item);
write!( write!(
f, f,

View file

@ -22,7 +22,7 @@ impl FormatNodeRule<MatchCase> for FormatMatchCase {
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_item_comments = comments.dangling_comments(item); let dangling_item_comments = comments.dangling(item);
write!( write!(
f, f,
@ -33,7 +33,7 @@ impl FormatNodeRule<MatchCase> for FormatMatchCase {
&format_with(|f| { &format_with(|f| {
write!(f, [text("case"), space()])?; write!(f, [text("case"), space()])?;
let leading_pattern_comments = comments.leading_comments(pattern); let leading_pattern_comments = comments.leading(pattern);
if !leading_pattern_comments.is_empty() { if !leading_pattern_comments.is_empty() {
parenthesized( parenthesized(
"(", "(",

View file

@ -63,7 +63,7 @@ impl FormatNodeRule<Parameters> for FormatParameters {
let (slash, star) = find_parameter_separators(f.context().source(), item); let (slash, star) = find_parameter_separators(f.context().source(), item);
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item); let dangling = comments.dangling(item);
// First dangling comment: trailing the opening parenthesis, e.g.: // First dangling comment: trailing the opening parenthesis, e.g.:
// ```python // ```python

View file

@ -19,7 +19,7 @@ impl FormatNodeRule<WithItem> for FormatWithItem {
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let trailing_as_comments = comments.dangling_comments(item); let trailing_as_comments = comments.dangling(item);
write!( write!(
f, f,

View file

@ -63,7 +63,7 @@ impl Format<PyFormatContext<'_>> for FormatTargets<'_> {
if let Some((first, rest)) = self.targets.split_first() { if let Some((first, rest)) = self.targets.split_first() {
let comments = f.context().comments(); let comments = f.context().comments();
let parenthesize = if comments.has_leading_comments(first) { let parenthesize = if comments.has_leading(first) {
ParenthesizeTarget::Always ParenthesizeTarget::Always
} else if has_own_parentheses(first, f.context()).is_some() { } else if has_own_parentheses(first, f.context()).is_some() {
ParenthesizeTarget::Never ParenthesizeTarget::Never

View file

@ -25,7 +25,7 @@ impl FormatNodeRule<StmtClassDef> for FormatStmtClassDef {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_comments = comments.dangling_comments(item); let dangling_comments = comments.dangling(item);
let trailing_definition_comments_start = let trailing_definition_comments_start =
dangling_comments.partition_point(|comment| comment.line_position().is_own_line()); dangling_comments.partition_point(|comment| comment.line_position().is_own_line());
@ -93,11 +93,11 @@ impl FormatNodeRule<StmtClassDef> for FormatStmtClassDef {
// ``` // ```
if arguments.is_empty() if arguments.is_empty()
&& comments && comments
.dangling_comments(arguments) .dangling(arguments)
.iter() .iter()
.all(|comment| comment.line_position().is_end_of_line()) .all(|comment| comment.line_position().is_end_of_line())
{ {
let dangling = comments.dangling_comments(arguments); let dangling = comments.dangling(arguments);
write!(f, [trailing_comments(dangling)])?; write!(f, [trailing_comments(dangling)])?;
} else { } else {
write!(f, [arguments.format()])?; write!(f, [arguments.format()])?;

View file

@ -39,7 +39,7 @@ impl FormatNodeRule<StmtFor> for FormatStmtFor {
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_comments = comments.dangling_comments(item); let dangling_comments = comments.dangling(item);
let body_start = body.first().map_or(iter.end(), Stmt::start); let body_start = body.first().map_or(iter.end(), Stmt::start);
let or_else_comments_start = let or_else_comments_start =
dangling_comments.partition_point(|comment| comment.slice().end() < body_start); dangling_comments.partition_point(|comment| comment.slice().end() < body_start);

View file

@ -29,7 +29,7 @@ impl FormatNodeRule<StmtFunctionDef> for FormatStmtFunctionDef {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_comments = comments.dangling_comments(item); let dangling_comments = comments.dangling(item);
let trailing_definition_comments_start = let trailing_definition_comments_start =
dangling_comments.partition_point(|comment| comment.line_position().is_own_line()); dangling_comments.partition_point(|comment| comment.line_position().is_own_line());
@ -64,19 +64,17 @@ impl FormatNodeRule<StmtFunctionDef> for FormatStmtFunctionDef {
write!(f, [space(), text("->"), space()])?; write!(f, [space(), text("->"), space()])?;
if return_annotation.is_tuple_expr() { if return_annotation.is_tuple_expr() {
let parentheses = if comments let parentheses =
.has_leading_comments(return_annotation.as_ref()) if comments.has_leading(return_annotation.as_ref()) {
{ Parentheses::Always
Parentheses::Always } else {
} else { Parentheses::Never
Parentheses::Never };
};
write!( write!(
f, f,
[return_annotation.format().with_options(parentheses)] [return_annotation.format().with_options(parentheses)]
)?; )?;
} else if comments.has_trailing_comments(return_annotation.as_ref()) } else if comments.has_trailing(return_annotation.as_ref()) {
{
// Intentionally parenthesize any return annotations with trailing comments. // Intentionally parenthesize any return annotations with trailing comments.
// This avoids an instability in cases like: // This avoids an instability in cases like:
// ```python // ```python

View file

@ -14,10 +14,7 @@ impl FormatNodeRule<StmtGlobal> for FormatStmtGlobal {
// Join the `global` names, breaking across continuation lines if necessary, unless the // Join the `global` names, breaking across continuation lines if necessary, unless the
// `global` statement has a trailing comment, in which case, breaking the names would // `global` statement has a trailing comment, in which case, breaking the names would
// move the comment "off" of the `global` statement. // move the comment "off" of the `global` statement.
if f.context() if f.context().comments().has_trailing(item.as_any_node_ref()) {
.comments()
.has_trailing_comments(item.as_any_node_ref())
{
let joined = format_with(|f| { let joined = format_with(|f| {
f.join_with(format_args![text(","), space()]) f.join_with(format_args![text(","), space()])
.entries(item.names.iter().formatted()) .entries(item.names.iter().formatted())

View file

@ -22,7 +22,7 @@ impl FormatNodeRule<StmtIf> for FormatStmtIf {
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let trailing_colon_comment = comments.dangling_comments(item); let trailing_colon_comment = comments.dangling(item);
write!( write!(
f, f,
@ -73,8 +73,8 @@ pub(crate) fn format_elif_else_clause(
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let trailing_colon_comment = comments.dangling_comments(item); let trailing_colon_comment = comments.dangling(item);
let leading_comments = comments.leading_comments(item); let leading_comments = comments.leading(item);
write!( write!(
f, f,

View file

@ -59,7 +59,7 @@ impl FormatNodeRule<StmtImportFrom> for FormatStmtImportFrom {
// ) // )
// ``` // ```
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let parenthesized_comments = comments.dangling_comments(item.as_any_node_ref()); let parenthesized_comments = comments.dangling(item.as_any_node_ref());
if parenthesized_comments.is_empty() { if parenthesized_comments.is_empty() {
parenthesize_if_expands(&names).fmt(f) parenthesize_if_expands(&names).fmt(f)

View file

@ -21,7 +21,7 @@ impl FormatNodeRule<StmtMatch> for FormatStmtMatch {
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_item_comments = comments.dangling_comments(item); let dangling_item_comments = comments.dangling(item);
// There can be at most one dangling comment after the colon in a match statement. // There can be at most one dangling comment after the colon in a match statement.
debug_assert!(dangling_item_comments.len() <= 1); debug_assert!(dangling_item_comments.len() <= 1);
@ -53,7 +53,7 @@ impl FormatNodeRule<StmtMatch> for FormatStmtMatch {
f, f,
[block_indent(&format_args!( [block_indent(&format_args!(
leading_alternate_branch_comments( leading_alternate_branch_comments(
comments.leading_comments(case), comments.leading(case),
last_case.body.last(), last_case.body.last(),
), ),
case.format() case.format()

View file

@ -14,10 +14,7 @@ impl FormatNodeRule<StmtNonlocal> for FormatStmtNonlocal {
// Join the `nonlocal` names, breaking across continuation lines if necessary, unless the // Join the `nonlocal` names, breaking across continuation lines if necessary, unless the
// `nonlocal` statement has a trailing comment, in which case, breaking the names would // `nonlocal` statement has a trailing comment, in which case, breaking the names would
// move the comment "off" of the `nonlocal` statement. // move the comment "off" of the `nonlocal` statement.
if f.context() if f.context().comments().has_trailing(item.as_any_node_ref()) {
.comments()
.has_trailing_comments(item.as_any_node_ref())
{
let joined = format_with(|f| { let joined = format_with(|f| {
f.join_with(format_args![text(","), space()]) f.join_with(format_args![text(","), space()])
.entries(item.names.iter().formatted()) .entries(item.names.iter().formatted())

View file

@ -63,13 +63,13 @@ impl FormatNodeRule<StmtTry> for FormatStmtTry {
} = item; } = item;
let comments_info = f.context().comments().clone(); let comments_info = f.context().comments().clone();
let mut dangling_comments = comments_info.dangling_comments(item); let mut dangling_comments = comments_info.dangling(item);
(_, dangling_comments) = format_case(item, CaseKind::Try, None, dangling_comments, f)?; (_, dangling_comments) = format_case(item, CaseKind::Try, None, dangling_comments, f)?;
let mut previous_node = body.last(); let mut previous_node = body.last();
for handler in handlers { for handler in handlers {
let handler_comments = comments_info.leading_comments(handler); let handler_comments = comments_info.leading(handler);
write!( write!(
f, f,
[ [

View file

@ -22,7 +22,7 @@ impl FormatNodeRule<StmtWhile> for FormatStmtWhile {
} = item; } = item;
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_comments = comments.dangling_comments(item.as_any_node_ref()); let dangling_comments = comments.dangling(item.as_any_node_ref());
let body_start = body.first().map_or(test.end(), Stmt::start); let body_start = body.first().map_or(test.end(), Stmt::start);
let or_else_comments_start = let or_else_comments_start =

View file

@ -33,7 +33,7 @@ impl FormatNodeRule<StmtWith> for FormatStmtWith {
// ... // ...
// ``` // ```
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_comments = comments.dangling_comments(item.as_any_node_ref()); let dangling_comments = comments.dangling(item.as_any_node_ref());
let partition_point = dangling_comments.partition_point(|comment| { let partition_point = dangling_comments.partition_point(|comment| {
item.items item.items
.first() .first()
@ -86,9 +86,7 @@ impl FormatNodeRule<StmtWith> for FormatStmtWith {
} else if let [item] = item.items.as_slice() { } else if let [item] = item.items.as_slice() {
// This is similar to `maybe_parenthesize_expression`, but we're not dealing with an // This is similar to `maybe_parenthesize_expression`, but we're not dealing with an
// expression here, it's a `WithItem`. // expression here, it's a `WithItem`.
if comments.has_leading_comments(item) if comments.has_leading(item) || comments.has_trailing_own_line(item) {
|| comments.has_trailing_own_line_comments(item)
{
optional_parentheses(&item.format()).fmt(f)?; optional_parentheses(&item.format()).fmt(f)?;
} else { } else {
item.format().fmt(f)?; item.format().fmt(f)?;

View file

@ -70,9 +70,7 @@ impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
// Format the first statement in the body, which often has special formatting rules. // Format the first statement in the body, which often has special formatting rules.
let first = match self.kind { let first = match self.kind {
SuiteKind::Other => { SuiteKind::Other => {
if is_class_or_function_definition(first) if is_class_or_function_definition(first) && !comments.has_leading(first) {
&& !comments.has_leading_comments(first)
{
// Add an empty line for any nested functions or classes defined within // Add an empty line for any nested functions or classes defined within
// non-function or class compound statements, e.g., this is stable formatting: // non-function or class compound statements, e.g., this is stable formatting:
// ```python // ```python
@ -97,7 +95,7 @@ impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
SuiteKind::Class => { SuiteKind::Class => {
if let Some(docstring) = DocstringStmt::try_from_statement(first) { if let Some(docstring) = DocstringStmt::try_from_statement(first) {
if !comments.has_leading_comments(first) if !comments.has_leading(first)
&& lines_before(first.start(), source) > 1 && lines_before(first.start(), source) > 1
{ {
// Allow up to one empty line before a class docstring, e.g., this is // Allow up to one empty line before a class docstring, e.g., this is
@ -118,7 +116,7 @@ impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
SuiteKind::TopLevel => SuiteChildStatement::Other(first), SuiteKind::TopLevel => SuiteChildStatement::Other(first),
}; };
let first_comments = comments.leading_dangling_trailing_comments(first); let first_comments = comments.leading_dangling_trailing(first);
let (mut preceding, mut after_class_docstring) = if first_comments let (mut preceding, mut after_class_docstring) = if first_comments
.leading .leading
@ -158,8 +156,8 @@ impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
match self.kind { match self.kind {
SuiteKind::TopLevel if source_type.is_stub() => { SuiteKind::TopLevel if source_type.is_stub() => {
// Preserve the empty line if the definitions are separated by a comment // Preserve the empty line if the definitions are separated by a comment
if comments.has_trailing_comments(preceding) if comments.has_trailing(preceding)
|| comments.has_leading_comments(following) || comments.has_leading(following)
{ {
empty_line().fmt(f)?; empty_line().fmt(f)?;
} else { } else {
@ -220,8 +218,7 @@ impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
// which is 0 instead of 1, the number of lines between the trailing comment and // which is 0 instead of 1, the number of lines between the trailing comment and
// the leading comment. This is why the suite handling counts the lines before the // the leading comment. This is why the suite handling counts the lines before the
// start of the next statement or before the first leading comments for compound statements. // start of the next statement or before the first leading comments for compound statements.
let start = if let Some(first_leading) = let start = if let Some(first_leading) = comments.leading(following).first()
comments.leading_comments(following).first()
{ {
first_leading.slice().start() first_leading.slice().start()
} else { } else {
@ -294,7 +291,7 @@ impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
} }
} }
let following_comments = comments.leading_dangling_trailing_comments(following); let following_comments = comments.leading_dangling_trailing(following);
if following_comments if following_comments
.leading .leading
@ -401,7 +398,7 @@ impl<'a> DocstringStmt<'a> {
impl Format<PyFormatContext<'_>> for DocstringStmt<'_> { impl Format<PyFormatContext<'_>> for DocstringStmt<'_> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let node_comments = comments.leading_dangling_trailing_comments(self.0); let node_comments = comments.leading_dangling_trailing(self.0);
if FormatStmtExpr.is_suppressed(node_comments.trailing, f.context()) { if FormatStmtExpr.is_suppressed(node_comments.trailing, f.context()) {
suppressed_node(self.0).fmt(f) suppressed_node(self.0).fmt(f)

View file

@ -22,7 +22,7 @@ impl FormatNodeRule<TypeParams> for FormatTypeParams {
// c, // c,
// ] = ... // ] = ...
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let dangling_comments = comments.dangling_comments(item.as_any_node_ref()); let dangling_comments = comments.dangling(item.as_any_node_ref());
write!(f, [trailing_comments(dangling_comments)])?; write!(f, [trailing_comments(dangling_comments)])?;
let items = format_with(|f| { let items = format_with(|f| {

View file

@ -36,7 +36,7 @@ pub(crate) fn write_suppressed_statements_starting_with_leading_comment<'a>(
let source = f.context().source(); let source = f.context().source();
let mut leading_comment_ranges = let mut leading_comment_ranges =
CommentRangeIter::outside_suppression(comments.leading_comments(first_suppressed), source); CommentRangeIter::outside_suppression(comments.leading(first_suppressed), source);
let before_format_off = leading_comment_ranges let before_format_off = leading_comment_ranges
.next() .next()
@ -88,7 +88,7 @@ pub(crate) fn write_suppressed_statements_starting_with_trailing_comment<'a>(
let source = f.context().source(); let source = f.context().source();
let indentation = Indentation::from_stmt(last_formatted.statement(), source); let indentation = Indentation::from_stmt(last_formatted.statement(), source);
let trailing_node_comments = comments.trailing_comments(last_formatted); let trailing_node_comments = comments.trailing(last_formatted);
let mut trailing_comment_ranges = let mut trailing_comment_ranges =
CommentRangeIter::outside_suppression(trailing_node_comments, source); CommentRangeIter::outside_suppression(trailing_node_comments, source);
@ -192,7 +192,7 @@ pub(crate) fn write_suppressed_statements_starting_with_trailing_comment<'a>(
write_suppressed_statements( write_suppressed_statements(
format_off_comment, format_off_comment,
SuiteChildStatement::Other(first_suppressed), SuiteChildStatement::Other(first_suppressed),
comments.leading_comments(first_suppressed), comments.leading(first_suppressed),
statements, statements,
f, f,
) )
@ -300,7 +300,7 @@ fn write_suppressed_statements<'a>(
// Suppression ends here. Test if the node has a trailing suppression comment and, if so, // Suppression ends here. Test if the node has a trailing suppression comment and, if so,
// recurse and format the trailing comments and the following statements as suppressed. // recurse and format the trailing comments and the following statements as suppressed.
return if comments return if comments
.trailing_comments(statement) .trailing(statement)
.iter() .iter()
.any(|comment| comment.is_suppression_off_comment(source)) .any(|comment| comment.is_suppression_off_comment(source))
{ {
@ -325,8 +325,7 @@ fn write_suppressed_statements<'a>(
comments.mark_verbatim_node_comments_formatted(AnyNodeRef::from(statement)); comments.mark_verbatim_node_comments_formatted(AnyNodeRef::from(statement));
for range in CommentRangeIter::in_suppression(comments.trailing_comments(statement), source) for range in CommentRangeIter::in_suppression(comments.trailing(statement), source) {
{
match range { match range {
// All leading comments are suppressed // All leading comments are suppressed
// ```python // ```python
@ -393,10 +392,10 @@ fn write_suppressed_statements<'a>(
if let Some(next_statement) = statements.next() { if let Some(next_statement) = statements.next() {
statement = SuiteChildStatement::Other(next_statement); statement = SuiteChildStatement::Other(next_statement);
leading_node_comments = comments.leading_comments(next_statement); leading_node_comments = comments.leading(next_statement);
} else { } else {
let end = comments let end = comments
.trailing_comments(statement) .trailing(statement)
.last() .last()
.map_or(statement.end(), Ranged::end); .map_or(statement.end(), Ranged::end);
@ -903,7 +902,7 @@ pub(crate) struct FormatSuppressedNode<'a> {
impl Format<PyFormatContext<'_>> for FormatSuppressedNode<'_> { impl Format<PyFormatContext<'_>> for FormatSuppressedNode<'_> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> { fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> {
let comments = f.context().comments().clone(); let comments = f.context().comments().clone();
let node_comments = comments.leading_dangling_trailing_comments(self.node); let node_comments = comments.leading_dangling_trailing(self.node);
// Mark all comments as formatted that fall into the node range // Mark all comments as formatted that fall into the node range
for comment in node_comments.leading { for comment in node_comments.leading {
@ -948,7 +947,7 @@ pub(crate) fn write_suppressed_clause_header(
let comments = f.context().comments(); let comments = f.context().comments();
header.visit(&mut |child| { header.visit(&mut |child| {
for comment in comments.leading_trailing_comments(child) { for comment in comments.leading_trailing(child) {
comment.mark_formatted(); comment.mark_formatted();
} }
comments.mark_verbatim_node_comments_formatted(child); comments.mark_verbatim_node_comments_formatted(child);