Skip to content

Commit 3db08e1

Browse files
committed
preserve comments within headers but don't reformat the header
These changes would allow rustfmt to retain the existing comments and still allow it to format whatever content comes after the AST node.
1 parent dd301b0 commit 3db08e1

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/header.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use rustc_ast as ast;
1111
use rustc_span::symbol::Ident;
1212
use rustc_span::Span;
1313

14-
use crate::comment::combine_strs_with_missing_comments;
14+
use crate::comment::{combine_strs_with_missing_comments, contains_comment};
1515
use crate::rewrite::RewriteContext;
1616
use crate::shape::Shape;
1717
use crate::utils::rewrite_ident;
@@ -24,6 +24,13 @@ pub(crate) fn format_header(
2424
debug!(?parts, "format_header");
2525
let shape = shape.infinite_width();
2626

27+
// FIXME(ytmimi) Don't apply any formatting if the header contains comments.
28+
// the rustfmt team needs to decide how to handle comments within the header
29+
if comments_in_header(context, &parts) {
30+
let span = header_span(&parts).expect("If we have comments we have headers");
31+
return context.snippet(span).to_owned();
32+
}
33+
2734
// Empty `HeaderPart`s are ignored.
2835
let mut parts = parts.into_iter().filter(|x| !x.snippet.is_empty());
2936
let Some(part) = parts.next() else {
@@ -51,6 +58,23 @@ pub(crate) fn format_header(
5158
result
5259
}
5360

61+
/// Get the Span of the entire header
62+
fn header_span(parts: &[HeaderPart]) -> Option<Span> {
63+
let first = parts.first()?;
64+
let last = parts.last()?;
65+
Some(first.span.with_hi(last.span.hi()))
66+
}
67+
68+
/// Check if there are any comments in the header parts
69+
fn comments_in_header(context: &RewriteContext<'_>, parts: &[HeaderPart]) -> bool {
70+
let Some(span) = header_span(parts) else {
71+
return false;
72+
};
73+
74+
let snippet = context.snippet(span);
75+
contains_comment(snippet)
76+
}
77+
5478
#[derive(Debug)]
5579
pub(crate) struct HeaderPart {
5680
/// snippet of this part without surrounding space

0 commit comments

Comments
 (0)