rustfmt icon indicating copy to clipboard operation
rustfmt copied to clipboard

rustfmt eats attributes while formatting functions with variadic parameters

Open mejrs opened this issue 6 months ago • 1 comments

If you format...

#[allow()]
unsafe extern "C" {
    #[allow()]
    pub fn foo(#[allow()] arg: *mut u8, #[allow()]...);
}

Then it will format into

#[allow()]
unsafe extern "C" {
    #[allow()]
    pub fn foo(#[allow()] arg: *mut u8, ...);
}

(The choice of attribute seems irrelevant, I've used allow because it compiles in any position).

Note that this position is explicitly documented at https://doc.rust-lang.org/nightly/reference/attributes.html#r-attributes.allowed-position

mejrs avatar May 11 '25 16:05 mejrs

Thanks for the report. confirming I can reproduce the issue with rustfmt 1.8.0-nightly (fd0ea742f8 2025-04-12).

I believe the issue is that we're forgetting to take the attribute into account when rewriting the variadic parameter: https://github.com/rust-lang/rustfmt/blob/bf5f0eac9bf2d0bca50d3ba6a5c0548e713e6a5d/src/items.rs#L2345

I think this could be fixed with the following change, thought some additional test cases would be needed to verify that.

-            self.ty.rewrite_result(context, shape)
+            combine_strs_with_missing_comments(
+                context,
+                &param_attrs_result,
+                &self.ty.rewrite_result(context, shape)?,
+                span,
+                shape,
+                !has_multiple_attr_lines && !has_doc_comments,
+            )

ytmimi avatar Jun 05 '25 01:06 ytmimi