Skip to content

Commit

Permalink
preserve comments within headers but don't reformat the header
Browse files Browse the repository at this point in the history
These changes would allow rustfmt to retain the existing comments and
still allow it to format whatever content comes after the AST node.
  • Loading branch information
ytmimi committed Mar 13, 2024
1 parent dd301b0 commit 0ac9a58
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use rustc_ast as ast;
use rustc_span::symbol::Ident;
use rustc_span::Span;

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

// FIXME(ytmimi) Don't apply any formatting if the header contains comments.
// the rustfmt team needs to decide how to handle comments within the header
if comments_in_header(context, &parts) {
let span = header_span(&parts).expect("If we have comments we have headers");
return context.snippet(span).to_owned();
}

// Empty `HeaderPart`s are ignored.
let mut parts = parts.into_iter().filter(|x| !x.snippet.is_empty());
let Some(part) = parts.next() else {
Expand Down Expand Up @@ -51,6 +58,23 @@ pub(crate) fn format_header(
result
}

/// Get the span of the entire header
fn header_span(parts: &[HeaderPart]) -> Option<Span> {
let first = parts.first()?;
let last = parts.last()?;
Some(first.span.with_hi(last.span.hi()))
}

/// Check if there are any comments in the header parts
fn comments_in_header(context: &RewriteContext<'_>, parts: &[HeaderPart]) -> bool {
let Some(span) = header_span(parts) else {
return false;
};

let snippet = context.snippet(span);
contains_comment(snippet)
}

#[derive(Debug)]
pub(crate) struct HeaderPart {
/// snippet of this part without surrounding space
Expand Down

0 comments on commit 0ac9a58

Please sign in to comment.