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 leading_comments = match self {
FormatLeadingComments::Node(node) => comments.leading_comments(*node),
FormatLeadingComments::Node(node) => comments.leading(*node),
FormatLeadingComments::Comments(comments) => comments,
};
@ -124,7 +124,7 @@ impl Format<PyFormatContext<'_>> for FormatTrailingComments<'_> {
let comments = f.context().comments().clone();
let trailing_comments = match self {
FormatTrailingComments::Node(node) => comments.trailing_comments(*node),
FormatTrailingComments::Node(node) => comments.trailing(*node),
FormatTrailingComments::Comments(comments) => comments,
};
@ -198,7 +198,7 @@ impl Format<PyFormatContext<'_>> for FormatDanglingComments<'_> {
let dangling_comments = match self {
Self::Comments(comments) => comments,
Self::Node(node) => comments.dangling_comments(*node),
Self::Node(node) => comments.dangling(*node),
};
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).
#[inline]
pub(crate) fn has_leading_comments<T>(&self, node: T) -> bool
pub(crate) fn has_leading<T>(&self, node: T) -> bool
where
T: Into<AnyNodeRef<'a>>,
{
!self.leading_comments(node).is_empty()
!self.leading(node).is_empty()
}
/// Returns the `node`'s [leading comments](self#leading-comments).
#[inline]
pub(crate) fn leading_comments<T>(&self, node: T) -> &[SourceComment]
pub(crate) fn leading<T>(&self, node: T) -> &[SourceComment]
where
T: Into<AnyNodeRef<'a>>,
{
@ -351,15 +351,15 @@ impl<'a> Comments<'a> {
}
/// 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
T: Into<AnyNodeRef<'a>>,
{
!self.dangling_comments(node).is_empty()
!self.dangling(node).is_empty()
}
/// 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
T: Into<AnyNodeRef<'a>>,
{
@ -370,7 +370,7 @@ impl<'a> Comments<'a> {
/// Returns the `node`'s [trailing comments](self#trailing-comments).
#[inline]
pub(crate) fn trailing_comments<T>(&self, node: T) -> &[SourceComment]
pub(crate) fn trailing<T>(&self, node: T) -> &[SourceComment]
where
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).
#[inline]
pub(crate) fn has_trailing_comments<T>(&self, node: T) -> bool
pub(crate) fn has_trailing<T>(&self, node: T) -> bool
where
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).
#[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
T: Into<AnyNodeRef<'a>>,
{
self.trailing_comments(node)
self.trailing(node)
.iter()
.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`.
pub(crate) fn leading_trailing_comments<T>(
&self,
node: T,
) -> impl Iterator<Item = &SourceComment>
pub(crate) fn leading_trailing<T>(&self, node: T) -> impl Iterator<Item = &SourceComment>
where
T: Into<AnyNodeRef<'a>>,
{
let node = node.into();
self.leading_comments(node)
.iter()
.chain(self.trailing_comments(node).iter())
let comments = self.leading_dangling_trailing(node);
comments.leading.iter().chain(comments.trailing)
}
/// 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>(
&self,
node: T,
) -> LeadingDanglingTrailingComments
pub(crate) fn leading_dangling_trailing<T>(&self, node: T) -> LeadingDanglingTrailingComments
where
T: Into<AnyNodeRef<'a>>,
{
@ -426,30 +418,12 @@ impl<'a> Comments<'a> {
.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)]
#[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)]
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;
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.
#[cfg(debug_assertions)]
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();
}
@ -505,7 +479,7 @@ struct MarkVerbatimCommentsAsFormattedVisitor<'a>(&'a Comments<'a>);
impl<'a> PreorderVisitor<'a> for MarkVerbatimCommentsAsFormattedVisitor<'a> {
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();
}

View file

@ -45,7 +45,7 @@ impl FormatNodeRule<ExprAttribute> for FormatExprAttribute {
);
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
.partition_point(|comment| comment.line_position().is_end_of_line());
let (trailing_dot_comments, leading_attribute_comments) =
@ -88,7 +88,7 @@ impl FormatNodeRule<ExprAttribute> for FormatExprAttribute {
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)?;
}
@ -171,10 +171,10 @@ impl NeedsParentheses for ExprAttribute {
OptionalParentheses::Multiline
} else if context
.comments()
.dangling_comments(self)
.dangling(self)
.iter()
.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
} else {

View file

@ -29,10 +29,7 @@ impl FormatNodeRule<ExprBinOp> for FormatExprBinOp {
match Self::layout(item, f.context()) {
BinOpLayout::LeftString(expression) => {
let right_has_leading_comment = f
.context()
.comments()
.has_leading_comments(item.right.as_ref());
let right_has_leading_comment = comments.has_leading(item.right.as_ref());
let format_right_and_op = format_with(|f| {
if right_has_leading_comment {
@ -98,7 +95,7 @@ impl FormatNodeRule<ExprBinOp> for FormatExprBinOp {
right,
} = current;
let operator_comments = comments.dangling_comments(current);
let operator_comments = comments.dangling(current);
let needs_space = !is_simple_power_expression(current);
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.
if comments.has_leading_comments(right.as_ref())
|| !operator_comments.is_empty()
{
if comments.has_leading(right.as_ref()) || !operator_comments.is_empty() {
hard_line_break().fmt(f)?;
} else if needs_space {
space().fmt(f)?;
@ -171,8 +166,8 @@ impl FormatExprBinOp {
if bin_op.op == Operator::Mod
&& context.node_level().is_parenthesized()
&& !comments.has_dangling_comments(constant)
&& !comments.has_dangling_comments(bin_op)
&& !comments.has_dangling(constant)
&& !comments.has_dangling(bin_op)
{
BinOpLayout::LeftString(constant)
} else {

View file

@ -50,7 +50,7 @@ impl FormatNodeRule<ExprBoolOp> for FormatExprBoolOp {
FormatValue { value: first }.fmt(f)?;
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
if leading_value_comments.is_empty() {
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());
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() {
write!(f, [in_parentheses_only_soft_line_break_or_space()])?;
} else {

View file

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

View file

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

View file

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

View file

@ -30,12 +30,12 @@ impl FormatNodeRule<ExprIfExp> for FormatExprIfExp {
[in_parentheses_only_group(&format_args![
body.format(),
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"),
space(),
test.format(),
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"),
space(),
orelse.format()

View file

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

View file

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

View file

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

View file

@ -27,7 +27,7 @@ impl FormatNodeRule<ExprSetComp> for FormatExprSetComp {
});
let comments = f.context().comments().clone();
let dangling = comments.dangling_comments(item);
let dangling = comments.dangling(item);
write!(
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
// slice of dangling comments
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
let first_colon_partition_index =
slice_dangling_comments.partition_point(|x| x.slice().start() < first_colon.start());
@ -102,7 +102,7 @@ impl FormatNodeRule<ExprSlice> for FormatExprSlice {
// 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)?;
write!(f, [upper.format(), line_suffix_boundary()])?;
} else {
@ -134,7 +134,7 @@ impl FormatNodeRule<ExprSlice> for FormatExprSlice {
space().fmt(f)?;
}
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)?;
step.format().fmt(f)?;
} else if !dangling_step_comments.is_empty() {

View file

@ -21,7 +21,7 @@ impl FormatNodeRule<ExprStarred> for FormatExprStarred {
} = item;
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()])
}

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 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!(
dangling_comments.len() <= 1,
"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;
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
//

View file

@ -39,7 +39,7 @@ impl FormatNodeRule<ExprUnaryOp> for FormatExprUnaryOp {
// (not # comment
// 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 =
leading_operand_comments.partition_point(|p| p.line_position().is_end_of_line());
let (trailing_operator_comments, leading_operand_comments) =

View file

@ -108,7 +108,20 @@ impl FormatRule<Expr, PyFormatContext<'_>> for FormatExpr {
if parenthesize {
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, ")")
.with_dangling_comments(
open_parenthesis_comment
@ -167,8 +180,8 @@ impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {
let preserve_parentheses = parenthesize.is_optional()
&& is_expression_parenthesized((*expression).into(), f.context().source());
let has_comments = comments.has_leading_comments(*expression)
|| comments.has_trailing_own_line_comments(*expression);
let has_comments =
comments.has_leading(*expression) || comments.has_trailing_own_line(*expression);
// 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
@ -655,11 +668,7 @@ pub(crate) fn has_own_parentheses(
Expr::List(ast::ExprList { elts, .. })
| Expr::Set(ast::ExprSet { elts, .. })
| Expr::Tuple(ast::ExprTuple { elts, .. }) => {
if !elts.is_empty()
|| context
.comments()
.has_dangling_comments(AnyNodeRef::from(expr))
{
if !elts.is_empty() || context.comments().has_dangling(AnyNodeRef::from(expr)) {
Some(OwnParentheses::NonEmpty)
} else {
Some(OwnParentheses::Empty)
@ -667,22 +676,14 @@ pub(crate) fn has_own_parentheses(
}
Expr::Dict(ast::ExprDict { keys, .. }) => {
if !keys.is_empty()
|| context
.comments()
.has_dangling_comments(AnyNodeRef::from(expr))
{
if !keys.is_empty() || context.comments().has_dangling(AnyNodeRef::from(expr)) {
Some(OwnParentheses::NonEmpty)
} else {
Some(OwnParentheses::Empty)
}
}
Expr::Call(ast::ExprCall { arguments, .. }) => {
if !arguments.is_empty()
|| context
.comments()
.has_dangling_comments(AnyNodeRef::from(expr))
{
if !arguments.is_empty() || context.comments().has_dangling(AnyNodeRef::from(expr)) {
Some(OwnParentheses::NonEmpty)
} else {
Some(OwnParentheses::Empty)

View file

@ -160,7 +160,7 @@ impl Format<PyFormatContext<'_>> for FormatStringContinuation<'_> {
let comments = f.context().comments().clone();
let locator = f.context().locator();
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_content = locator.slice(string_range);

View file

@ -49,7 +49,7 @@ where
fn fmt(&self, node: &N, f: &mut PyFormatter) -> FormatResult<()> {
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()) {
suppressed_node(node.as_any_node_ref()).fmt(f)
@ -161,7 +161,7 @@ pub fn format_node<'a>(
formatted
.context()
.comments()
.assert_formatted_all_comments(SourceCode::new(source));
.assert_all_formatted(SourceCode::new(source));
Ok(formatted)
}

View file

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

View file

@ -15,7 +15,7 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
impl Format<PyFormatContext<'_>> for Spacer<'_> {
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)
} else {
space().fmt(f)
@ -36,13 +36,13 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
}
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(
dangling_item_comments
.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| {
if before_in_comments.is_empty() {
@ -73,7 +73,7 @@ impl FormatNodeRule<Comprehension> for FormatComprehension {
let joined = format_with(|f| {
let mut joiner = f.join_with(soft_line_break_or_space());
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
.split_at(

View file

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

View file

@ -22,7 +22,7 @@ impl FormatNodeRule<MatchCase> for FormatMatchCase {
} = item;
let comments = f.context().comments().clone();
let dangling_item_comments = comments.dangling_comments(item);
let dangling_item_comments = comments.dangling(item);
write!(
f,
@ -33,7 +33,7 @@ impl FormatNodeRule<MatchCase> for FormatMatchCase {
&format_with(|f| {
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() {
parenthesized(
"(",

View file

@ -63,7 +63,7 @@ impl FormatNodeRule<Parameters> for FormatParameters {
let (slash, star) = find_parameter_separators(f.context().source(), item);
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.:
// ```python

View file

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

View file

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

View file

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

View file

@ -39,7 +39,7 @@ impl FormatNodeRule<StmtFor> for FormatStmtFor {
} = item;
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 or_else_comments_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 dangling_comments = comments.dangling_comments(item);
let dangling_comments = comments.dangling(item);
let trailing_definition_comments_start =
dangling_comments.partition_point(|comment| comment.line_position().is_own_line());
@ -64,9 +64,8 @@ impl FormatNodeRule<StmtFunctionDef> for FormatStmtFunctionDef {
write!(f, [space(), text("->"), space()])?;
if return_annotation.is_tuple_expr() {
let parentheses = if comments
.has_leading_comments(return_annotation.as_ref())
{
let parentheses =
if comments.has_leading(return_annotation.as_ref()) {
Parentheses::Always
} else {
Parentheses::Never
@ -75,8 +74,7 @@ impl FormatNodeRule<StmtFunctionDef> for FormatStmtFunctionDef {
f,
[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.
// This avoids an instability in cases like:
// ```python

View file

@ -14,10 +14,7 @@ impl FormatNodeRule<StmtGlobal> for FormatStmtGlobal {
// 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
// move the comment "off" of the `global` statement.
if f.context()
.comments()
.has_trailing_comments(item.as_any_node_ref())
{
if f.context().comments().has_trailing(item.as_any_node_ref()) {
let joined = format_with(|f| {
f.join_with(format_args![text(","), space()])
.entries(item.names.iter().formatted())

View file

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

View file

@ -59,7 +59,7 @@ impl FormatNodeRule<StmtImportFrom> for FormatStmtImportFrom {
// )
// ```
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() {
parenthesize_if_expands(&names).fmt(f)

View file

@ -21,7 +21,7 @@ impl FormatNodeRule<StmtMatch> for FormatStmtMatch {
} = item;
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.
debug_assert!(dangling_item_comments.len() <= 1);
@ -53,7 +53,7 @@ impl FormatNodeRule<StmtMatch> for FormatStmtMatch {
f,
[block_indent(&format_args!(
leading_alternate_branch_comments(
comments.leading_comments(case),
comments.leading(case),
last_case.body.last(),
),
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
// `nonlocal` statement has a trailing comment, in which case, breaking the names would
// move the comment "off" of the `nonlocal` statement.
if f.context()
.comments()
.has_trailing_comments(item.as_any_node_ref())
{
if f.context().comments().has_trailing(item.as_any_node_ref()) {
let joined = format_with(|f| {
f.join_with(format_args![text(","), space()])
.entries(item.names.iter().formatted())

View file

@ -63,13 +63,13 @@ impl FormatNodeRule<StmtTry> for FormatStmtTry {
} = item;
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)?;
let mut previous_node = body.last();
for handler in handlers {
let handler_comments = comments_info.leading_comments(handler);
let handler_comments = comments_info.leading(handler);
write!(
f,
[

View file

@ -22,7 +22,7 @@ impl FormatNodeRule<StmtWhile> for FormatStmtWhile {
} = item;
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 or_else_comments_start =

View file

@ -33,7 +33,7 @@ impl FormatNodeRule<StmtWith> for FormatStmtWith {
// ...
// ```
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| {
item.items
.first()
@ -86,9 +86,7 @@ impl FormatNodeRule<StmtWith> for FormatStmtWith {
} else if let [item] = item.items.as_slice() {
// This is similar to `maybe_parenthesize_expression`, but we're not dealing with an
// expression here, it's a `WithItem`.
if comments.has_leading_comments(item)
|| comments.has_trailing_own_line_comments(item)
{
if comments.has_leading(item) || comments.has_trailing_own_line(item) {
optional_parentheses(&item.format()).fmt(f)?;
} else {
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.
let first = match self.kind {
SuiteKind::Other => {
if is_class_or_function_definition(first)
&& !comments.has_leading_comments(first)
{
if is_class_or_function_definition(first) && !comments.has_leading(first) {
// Add an empty line for any nested functions or classes defined within
// non-function or class compound statements, e.g., this is stable formatting:
// ```python
@ -97,7 +95,7 @@ impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
SuiteKind::Class => {
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
{
// 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),
};
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
.leading
@ -158,8 +156,8 @@ impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
match self.kind {
SuiteKind::TopLevel if source_type.is_stub() => {
// Preserve the empty line if the definitions are separated by a comment
if comments.has_trailing_comments(preceding)
|| comments.has_leading_comments(following)
if comments.has_trailing(preceding)
|| comments.has_leading(following)
{
empty_line().fmt(f)?;
} 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
// 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.
let start = if let Some(first_leading) =
comments.leading_comments(following).first()
let start = if let Some(first_leading) = comments.leading(following).first()
{
first_leading.slice().start()
} 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
.leading
@ -401,7 +398,7 @@ impl<'a> DocstringStmt<'a> {
impl Format<PyFormatContext<'_>> for DocstringStmt<'_> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> {
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()) {
suppressed_node(self.0).fmt(f)

View file

@ -22,7 +22,7 @@ impl FormatNodeRule<TypeParams> for FormatTypeParams {
// c,
// ] = ...
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)])?;
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 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
.next()
@ -88,7 +88,7 @@ pub(crate) fn write_suppressed_statements_starting_with_trailing_comment<'a>(
let source = f.context().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 =
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(
format_off_comment,
SuiteChildStatement::Other(first_suppressed),
comments.leading_comments(first_suppressed),
comments.leading(first_suppressed),
statements,
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,
// recurse and format the trailing comments and the following statements as suppressed.
return if comments
.trailing_comments(statement)
.trailing(statement)
.iter()
.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));
for range in CommentRangeIter::in_suppression(comments.trailing_comments(statement), source)
{
for range in CommentRangeIter::in_suppression(comments.trailing(statement), source) {
match range {
// All leading comments are suppressed
// ```python
@ -393,10 +392,10 @@ fn write_suppressed_statements<'a>(
if let Some(next_statement) = statements.next() {
statement = SuiteChildStatement::Other(next_statement);
leading_node_comments = comments.leading_comments(next_statement);
leading_node_comments = comments.leading(next_statement);
} else {
let end = comments
.trailing_comments(statement)
.trailing(statement)
.last()
.map_or(statement.end(), Ranged::end);
@ -903,7 +902,7 @@ pub(crate) struct FormatSuppressedNode<'a> {
impl Format<PyFormatContext<'_>> for FormatSuppressedNode<'_> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> {
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
for comment in node_comments.leading {
@ -948,7 +947,7 @@ pub(crate) fn write_suppressed_clause_header(
let comments = f.context().comments();
header.visit(&mut |child| {
for comment in comments.leading_trailing_comments(child) {
for comment in comments.leading_trailing(child) {
comment.mark_formatted();
}
comments.mark_verbatim_node_comments_formatted(child);