From 7a4b5ecee1bb59be186506011c9aa706729d590f Mon Sep 17 00:00:00 2001 From: Albar Date: Tue, 26 May 2026 20:37:51 -0400 Subject: [PATCH 01/24] feat!: fn_parameter_post_comment_alignment config option --- Configurations.md | 34 ++++++++++ src/attr.rs | 7 +- src/closures.rs | 6 +- src/config/mod.rs | 4 ++ src/config/options.rs | 11 +++ src/expr.rs | 12 +++- src/imports.rs | 6 +- src/items.rs | 25 +++++-- src/lists.rs | 67 ++++++++++++------- src/macros.rs | 6 +- src/matches.rs | 6 +- src/overflow.rs | 8 ++- src/patterns.rs | 12 +++- src/reorder.rs | 6 +- src/types.rs | 9 ++- src/vertical.rs | 7 +- ...ent_fn_parameter_post_comment_alignment.rs | 15 +++++ ...ace_fn_parameter_post_comment_alignment.rs | 22 ++++++ ...ent_fn_parameter_post_comment_alignment.rs | 15 +++++ ...ace_fn_parameter_post_comment_alignment.rs | 22 ++++++ 20 files changed, 256 insertions(+), 44 deletions(-) create mode 100644 tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs create mode 100644 tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs create mode 100644 tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs create mode 100644 tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs diff --git a/Configurations.md b/Configurations.md index 5d8704ed779..c5efbe6a8a9 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1251,6 +1251,40 @@ fn lorem() -> usize { See also: [`tab_spaces`](#tab_spaces). +## `fn_parameter_post_comment_alignment` + +Alignment of comments after function parameters + +- **Default value**: `SameIndent` +- **Possible values**: `SameIndent`, `SingleSpace` +- **Stable**: No + +#### `SameIndent` (default): + +Each comment has the same indentation. + +```rust +fn foo( + a: usize, // Cat + b: usize, // Dog + c: f32, // Bird +) { +} +``` + +#### `SingleSpace`: + +One space between the code and comment. + +```rust +fn foo( + a: usize, // Cat + b: usize, // Dog + c: f32, // Bird +) { +} +``` + ## `hex_literal_case` Control the case of the letters in hexadecimal literal values diff --git a/src/attr.rs b/src/attr.rs index ac9ce2e8796..21165a4b1cc 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -147,7 +147,12 @@ fn format_derive( .tactic(tactic) .trailing_separator(trailing_separator) .ends_with_newline(false); - let item_str = write_list(&all_items, &fmt).ok()?; + let item_str = write_list( + &all_items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) + .ok()?; debug!("item_str: '{}'", item_str); diff --git a/src/closures.rs b/src/closures.rs index 19cd0d9792c..e5dec828ae7 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -338,7 +338,11 @@ fn rewrite_closure_fn_decl( let fmt = ListFormatting::new(param_shape, context.config) .tactic(tactic) .preserve_newline(true); - let list_str = write_list(&item_vec, &fmt)?; + let list_str = write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?; let mut prefix = format!("{binder}{const_}{immovable}{coro}{capture_str}|{list_str}|"); if !ret_str.is_empty() { diff --git a/src/config/mod.rs b/src/config/mod.rs index 8abb7439257..f5aae819573 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -78,6 +78,8 @@ create_config! { "Format the bodies of declarative macro definitions"; skip_macro_invocations: SkipMacroInvocations, false, "Skip formatting the bodies of macros invoked with the following names."; + fn_parameter_post_comment_alignment: FnParameterPostCommentAlignmentConfig, false, + "Alignment of comments after function parameters"; hex_literal_case: HexLiteralCaseConfig, false, "Format hexadecimal integer literals"; float_literal_trailing_zero: FloatLiteralTrailingZeroConfig, false, "Add or remove trailing zero in floating-point literals"; @@ -779,6 +781,7 @@ format_strings = false format_macro_matchers = false format_macro_bodies = true skip_macro_invocations = [] +fn_parameter_post_comment_alignment = "SameIndent" hex_literal_case = "Preserve" float_literal_trailing_zero = "Preserve" empty_item_single_line = true @@ -871,6 +874,7 @@ format_strings = false format_macro_matchers = false format_macro_bodies = true skip_macro_invocations = [] +fn_parameter_post_comment_alignment = "SameIndent" hex_literal_case = "Preserve" float_literal_trailing_zero = "Preserve" empty_item_single_line = true diff --git a/src/config/options.rs b/src/config/options.rs index 00f9c3f7ec1..5e3d1839d9a 100644 --- a/src/config/options.rs +++ b/src/config/options.rs @@ -135,6 +135,15 @@ pub enum ImportGranularity { One, } +/// Controls how rustfmt should align post comments. +#[config_type] +pub enum PostCommentAlignment { + /// List each comment with the same indentation from the previous. + SameIndent, + /// Insert one space between the code and comment. + SingleSpace, +} + /// Controls how rustfmt should handle case in hexadecimal literals. #[config_type] pub enum HexLiteralCase { @@ -627,6 +636,8 @@ config_option_with_style_edition_default!( FormatMacroMatchers, bool, _ => false; FormatMacroBodies, bool, _ => true; SkipMacroInvocations, MacroSelectors, _ => MacroSelectors::default(); + FnParameterPostCommentAlignmentConfig, PostCommentAlignment, _ => + PostCommentAlignment::SameIndent; HexLiteralCaseConfig, HexLiteralCase, _ => HexLiteralCase::Preserve; FloatLiteralTrailingZeroConfig, FloatLiteralTrailingZero, _ => FloatLiteralTrailingZero::Preserve; diff --git a/src/expr.rs b/src/expr.rs index b79137c4442..0d324cfea42 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1869,7 +1869,11 @@ fn rewrite_struct_lit<'a>( force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(), ); - write_list(&item_vec, &fmt)? + write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )? }; let fields_str = @@ -2016,7 +2020,11 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>( let fmt = ListFormatting::new(nested_shape, context.config) .tactic(tactic) .ends_with_newline(false); - let list_str = write_list(&item_vec, &fmt)?; + let list_str = write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?; Ok(format!("({list_str})")) } diff --git a/src/imports.rs b/src/imports.rs index 2f26791639a..577e050f28c 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -1066,7 +1066,11 @@ fn rewrite_nested_use_tree( .preserve_newline(true) .nested(has_nested_list); - let list_str = write_list(&list_items, &fmt)?; + let list_str = write_list( + &list_items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?; let result = if (list_str.contains('\n') || list_str.len() > remaining_width diff --git a/src/items.rs b/src/items.rs index a2c0e8e0f50..760ca221ec3 100644 --- a/src/items.rs +++ b/src/items.rs @@ -652,7 +652,12 @@ impl<'a> FmtVisitor<'a> { .trailing_separator(self.config.trailing_comma()) .preserve_newline(true); - let list = write_list(&items, &fmt).ok()?; + let list = write_list( + &items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) + .ok()?; result.push_str(&list); result.push_str(&original_offset.to_string_with_newline(self.config)); result.push('}'); @@ -2899,7 +2904,11 @@ fn rewrite_params( .trailing_separator(trailing_separator) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - write_list(¶m_items, &fmt) + write_list( + ¶m_items, + &fmt, + context.config.fn_parameter_post_comment_alignment(), + ) } fn compute_budgets_for_params( @@ -3161,7 +3170,11 @@ fn rewrite_bounds_on_where_clause( .tactic(shape_tactic) .trailing_separator(comma_tactic) .preserve_newline(preserve_newline); - write_list(&items.collect::>(), &fmt) + write_list( + &items.collect::>(), + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) } fn rewrite_where_clause( @@ -3242,7 +3255,11 @@ fn rewrite_where_clause( .trailing_separator(comma_tactic) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - let preds_str = write_list(&item_vec, &fmt)?; + let preds_str = write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?; let end_length = if terminator == "{" { // If the brace is on the next line we don't need to count it otherwise it needs two diff --git a/src/lists.rs b/src/lists.rs index 9d811e5d9b5..ca6b720cdac 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -6,8 +6,8 @@ use std::iter::Peekable; use rustc_span::{BytePos, Span}; use crate::comment::{FindUncommented, find_comment_end, rewrite_comment}; -use crate::config::lists::*; use crate::config::{Config, IndentStyle}; +use crate::config::{PostCommentAlignment, lists::*}; use crate::rewrite::{ExceedsMaxWidthError, RewriteContext, RewriteError, RewriteResult}; use crate::shape::{Indent, Shape}; use crate::utils::{ @@ -261,7 +261,11 @@ where } // Format a list of commented items into a string. -pub(crate) fn write_list(items: I, formatting: &ListFormatting<'_>) -> RewriteResult +pub(crate) fn write_list( + items: I, + formatting: &ListFormatting<'_>, + post_comment_alignment_config: PostCommentAlignment, +) -> RewriteResult where I: IntoIterator + Clone, T: AsRef, @@ -467,34 +471,45 @@ where let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?; if !starts_with_newline(comment) { - if formatting.align_comments { - let mut comment_alignment = - post_comment_alignment(item_max_width, unicode_str_width(inner_item)); - if first_line_width(&formatted_comment) - + last_line_width(&result) - + comment_alignment - + 1 - > formatting.config.max_width() - { - item_max_width = None; - formatted_comment = rewrite_post_comment(&mut item_max_width)?; - comment_alignment = - post_comment_alignment(item_max_width, unicode_str_width(inner_item)); + match post_comment_alignment_config { + PostCommentAlignment::SameIndent => { + if formatting.align_comments { + let mut comment_alignment = post_comment_alignment( + item_max_width, + unicode_str_width(inner_item), + ); + if first_line_width(&formatted_comment) + + last_line_width(&result) + + comment_alignment + + 1 + > formatting.config.max_width() + { + item_max_width = None; + formatted_comment = rewrite_post_comment(&mut item_max_width)?; + comment_alignment = post_comment_alignment( + item_max_width, + unicode_str_width(inner_item), + ); + } + for _ in 0..=comment_alignment { + result.push(' '); + } + } + // An additional space for the missing trailing separator (or + // if we skipped alignment above). + if !formatting.align_comments + || (last + && item_max_width.is_some() + && !separate + && !formatting.separator.is_empty()) + { + result.push(' '); + } } - for _ in 0..=comment_alignment { + PostCommentAlignment::SingleSpace => { result.push(' '); } } - // An additional space for the missing trailing separator (or - // if we skipped alignment above). - if !formatting.align_comments - || (last - && item_max_width.is_some() - && !separate - && !formatting.separator.is_empty()) - { - result.push(' '); - } } else { result.push('\n'); result.push_str(indent_str); diff --git a/src/macros.rs b/src/macros.rs index 2d56021069c..3699bf2f4de 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -497,7 +497,11 @@ pub(crate) fn rewrite_macro_def( result += &arm_shape.indent.to_string_with_newline(context.config); } - match write_list(&branch_items, &fmt) { + match write_list( + &branch_items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) { Ok(ref s) => result += s, Err(_) => return snippet, } diff --git a/src/matches.rs b/src/matches.rs index 4741abbe465..12adc239e78 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -242,7 +242,11 @@ fn rewrite_match_arms( .separator("") .preserve_newline(true); - write_list(&arms_vec, &fmt) + write_list( + &arms_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) } fn rewrite_match_arm( diff --git a/src/overflow.rs b/src/overflow.rs index 4230c89b57b..6c327f68c67 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -663,8 +663,12 @@ impl<'a> Context<'a> { .trailing_separator(trailing_separator) .ends_with_newline(ends_with_newline); - write_list(&list_items, &fmt) - .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str)) + write_list( + &list_items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) + .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str)) } fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String { diff --git a/src/patterns.rs b/src/patterns.rs index df2a8dc5c6f..75c53235358 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -129,7 +129,11 @@ impl Rewrite for Pat { .separator(" |") .separator_place(context.config.binop_separator()) .ends_with_newline(false); - write_list(&items, &fmt) + write_list( + &items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) } PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape), PatKind::Ident(BindingMode(by_ref, mutability), ident, ref sub_pat) => { @@ -452,7 +456,11 @@ fn rewrite_struct_pat( let nested_shape = shape_for_tactic(tactic, h_shape, v_shape); let fmt = struct_lit_formatting(nested_shape, tactic, context, false); - let mut fields_str = write_list(&item_vec, &fmt)?; + let mut fields_str = write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?; let one_line_width = h_shape.map_or(0, |shape| shape.width); let has_trailing_comma = fmt.needs_trailing_separator(); diff --git a/src/reorder.rs b/src/reorder.rs index 6ef6e0bc969..8bbff59fc3e 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -76,7 +76,11 @@ fn wrap_reorderable_items( let fmt = ListFormatting::new(shape, context.config) .separator("") .align_comments(false); - write_list(list_items, &fmt) + write_list( + list_items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) } fn rewrite_reorderable_item( diff --git a/src/types.rs b/src/types.rs index 94ed42c6ea5..30057f39217 100644 --- a/src/types.rs +++ b/src/types.rs @@ -405,7 +405,14 @@ where .trailing_separator(trailing_separator) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - (write_list(&item_vec, &fmt)?, tactic) + ( + write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?, + tactic, + ) }; let args = if tactic == DefinitiveListTactic::Horizontal diff --git a/src/vertical.rs b/src/vertical.rs index 21e34d29710..5148a43df44 100644 --- a/src/vertical.rs +++ b/src/vertical.rs @@ -266,7 +266,12 @@ fn rewrite_aligned_items_inner( .tactic(tactic) .trailing_separator(separator_tactic) .preserve_newline(true); - write_list(&items, &fmt).ok() + write_list( + &items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) + .ok() } /// Returns the index in `fields` up to which a field belongs to the current group. diff --git a/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs new file mode 100644 index 00000000000..b0758caaef3 --- /dev/null +++ b/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs @@ -0,0 +1,15 @@ +// rustfmt-fn_parameter_post_comment_alignment: SameIndent + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +fn bar( + a: usize,/* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ +) { +} diff --git a/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs new file mode 100644 index 00000000000..639c5432d5d --- /dev/null +++ b/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs @@ -0,0 +1,22 @@ +// rustfmt-fn_parameter_post_comment_alignment: SingleSpace + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +fn bar( + a: usize,/* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ +) { + // `fn_parameter_post_comment_alignment` should not + // affect post comments for match statements. + match 0 { + 0 => todo!(), // IIIS + 1 => todo!(), // ASD + _ => {} // Meep + } +} diff --git a/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs new file mode 100644 index 00000000000..a1d1cb3419f --- /dev/null +++ b/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs @@ -0,0 +1,15 @@ +// rustfmt-fn_parameter_post_comment_alignment: SameIndent + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +fn bar( + a: usize, /* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ +) { +} diff --git a/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs new file mode 100644 index 00000000000..e6e95bcc07a --- /dev/null +++ b/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs @@ -0,0 +1,22 @@ +// rustfmt-fn_parameter_post_comment_alignment: SingleSpace + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +fn bar( + a: usize, /* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ +) { + // `fn_parameter_post_comment_alignment` should not + // affect post comments for match statements. + match 0 { + 0 => todo!(), // IIIS + 1 => todo!(), // ASD + _ => {} // Meep + } +} From 5630a2786ef45514739d5156970f84a8f96e3ca7 Mon Sep 17 00:00:00 2001 From: Albar Date: Sat, 30 May 2026 23:18:01 -0400 Subject: [PATCH 02/24] feat!: change fn_parameter_post_comment_alignment to post_comment_alignment --- Configurations.md | 16 +- src/attr.rs | 7 +- src/closures.rs | 6 +- src/comment.rs | 16 +- src/config/mod.rs | 8 +- src/config/options.rs | 8 +- src/expr.rs | 12 +- src/imports.rs | 6 +- src/items.rs | 29 +-- src/lists.rs | 171 +++++++++--------- src/macros.rs | 6 +- src/matches.rs | 6 +- src/overflow.rs | 8 +- src/patterns.rs | 12 +- src/reorder.rs | 12 +- src/types.rs | 9 +- src/vertical.rs | 7 +- ...ent_fn_parameter_post_comment_alignment.rs | 24 ++- ...ace_fn_parameter_post_comment_alignment.rs | 8 +- .../target/cfg_if/detect/os/linux/aarch64.rs | 14 +- tests/target/comments_unicode.rs | 6 +- .../struct_field_align_threshold/20.rs | 4 +- tests/target/enum.rs | 2 +- .../target/fn-args-with-last-line-comment.rs | 4 +- tests/target/fn-simple.rs | 2 +- tests/target/issue-2329.rs | 2 +- tests/target/issue-3198.rs | 6 +- ...ent_fn_parameter_post_comment_alignment.rs | 24 ++- ...ace_fn_parameter_post_comment_alignment.rs | 10 +- tests/target/issue-5568.rs | 6 +- tests/target/macros.rs | 4 +- tests/target/match.rs | 14 +- tests/target/multiple.rs | 4 +- tests/target/structs.rs | 12 +- tests/target/unions.rs | 8 +- 35 files changed, 231 insertions(+), 262 deletions(-) diff --git a/Configurations.md b/Configurations.md index c5efbe6a8a9..f0ff5a14dce 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1251,36 +1251,36 @@ fn lorem() -> usize { See also: [`tab_spaces`](#tab_spaces). -## `fn_parameter_post_comment_alignment` +## `post_comment_alignment` -Alignment of comments after function parameters +Alignment of post comments - **Default value**: `SameIndent` - **Possible values**: `SameIndent`, `SingleSpace` - **Stable**: No -#### `SameIndent` (default): +#### `SingleSpace`: -Each comment has the same indentation. +One space between the code and comment. ```rust fn foo( a: usize, // Cat b: usize, // Dog - c: f32, // Bird + c: f32, // Bird ) { } ``` -#### `SingleSpace`: +#### `SameIndent` (default): -One space between the code and comment. +Each comment has the same indentation. ```rust fn foo( a: usize, // Cat b: usize, // Dog - c: f32, // Bird + c: f32, // Bird ) { } ``` diff --git a/src/attr.rs b/src/attr.rs index 21165a4b1cc..c0655abb57e 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -147,12 +147,7 @@ fn format_derive( .tactic(tactic) .trailing_separator(trailing_separator) .ends_with_newline(false); - let item_str = write_list( - &all_items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) - .ok()?; + let item_str = write_list(all_items, &fmt).ok()?; debug!("item_str: '{}'", item_str); diff --git a/src/closures.rs b/src/closures.rs index e5dec828ae7..2421299d4fe 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -338,11 +338,7 @@ fn rewrite_closure_fn_decl( let fmt = ListFormatting::new(param_shape, context.config) .tactic(tactic) .preserve_newline(true); - let list_str = write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?; + let list_str = write_list(item_vec, &fmt)?; let mut prefix = format!("{binder}{const_}{immovable}{coro}{capture_str}|{list_str}|"); if !ret_str.is_empty() { diff --git a/src/comment.rs b/src/comment.rs index 241934a7d3d..b4431f58d66 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -742,10 +742,13 @@ impl<'a> CommentRewrite<'a> { &item_fmt, self.max_width.saturating_sub(ib.indent), ) { - Some(s) => self.result.push_str(&Self::join_block( - &s, - &format!("{}{}", self.comment_line_separator, ib.line_start), - )), + Some(s) => { + let r = Self::join_block( + &s, + &format!("{}{}", self.comment_line_separator, ib.line_start), + ); + self.result.push_str(&r) + } None => self.result.push_str(&Self::join_block( &ib.original_block_as_string(), &self.comment_line_separator, @@ -1083,7 +1086,10 @@ fn light_rewrite_comment( /// Trims comment characters and possibly a single space from the left of a string. /// Does not trim all whitespace. If a single space is trimmed from the left of the string, /// this function returns true. -fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a str, bool) { +pub(crate) fn left_trim_comment_line<'a>( + line: &'a str, + style: &CommentStyle<'_>, +) -> (&'a str, bool) { if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") diff --git a/src/config/mod.rs b/src/config/mod.rs index f5aae819573..cea1bf26aaa 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -78,8 +78,8 @@ create_config! { "Format the bodies of declarative macro definitions"; skip_macro_invocations: SkipMacroInvocations, false, "Skip formatting the bodies of macros invoked with the following names."; - fn_parameter_post_comment_alignment: FnParameterPostCommentAlignmentConfig, false, - "Alignment of comments after function parameters"; + post_comment_alignment: PostCommentAlignmentConfig, false, + "Alignment of post comments"; hex_literal_case: HexLiteralCaseConfig, false, "Format hexadecimal integer literals"; float_literal_trailing_zero: FloatLiteralTrailingZeroConfig, false, "Add or remove trailing zero in floating-point literals"; @@ -781,7 +781,7 @@ format_strings = false format_macro_matchers = false format_macro_bodies = true skip_macro_invocations = [] -fn_parameter_post_comment_alignment = "SameIndent" +post_comment_alignment = "SingleSpace" hex_literal_case = "Preserve" float_literal_trailing_zero = "Preserve" empty_item_single_line = true @@ -874,7 +874,7 @@ format_strings = false format_macro_matchers = false format_macro_bodies = true skip_macro_invocations = [] -fn_parameter_post_comment_alignment = "SameIndent" +post_comment_alignment = "SingleSpace" hex_literal_case = "Preserve" float_literal_trailing_zero = "Preserve" empty_item_single_line = true diff --git a/src/config/options.rs b/src/config/options.rs index 5e3d1839d9a..75a28b1ee53 100644 --- a/src/config/options.rs +++ b/src/config/options.rs @@ -138,10 +138,10 @@ pub enum ImportGranularity { /// Controls how rustfmt should align post comments. #[config_type] pub enum PostCommentAlignment { - /// List each comment with the same indentation from the previous. - SameIndent, /// Insert one space between the code and comment. SingleSpace, + /// List each comment with the same indentation from the previous. + SameIndent, } /// Controls how rustfmt should handle case in hexadecimal literals. @@ -636,8 +636,8 @@ config_option_with_style_edition_default!( FormatMacroMatchers, bool, _ => false; FormatMacroBodies, bool, _ => true; SkipMacroInvocations, MacroSelectors, _ => MacroSelectors::default(); - FnParameterPostCommentAlignmentConfig, PostCommentAlignment, _ => - PostCommentAlignment::SameIndent; + PostCommentAlignmentConfig, PostCommentAlignment, _ => + PostCommentAlignment::SingleSpace; HexLiteralCaseConfig, HexLiteralCase, _ => HexLiteralCase::Preserve; FloatLiteralTrailingZeroConfig, FloatLiteralTrailingZero, _ => FloatLiteralTrailingZero::Preserve; diff --git a/src/expr.rs b/src/expr.rs index 0d324cfea42..adcb5604bb3 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1869,11 +1869,7 @@ fn rewrite_struct_lit<'a>( force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(), ); - write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )? + write_list(item_vec, &fmt)? }; let fields_str = @@ -2020,11 +2016,7 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>( let fmt = ListFormatting::new(nested_shape, context.config) .tactic(tactic) .ends_with_newline(false); - let list_str = write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?; + let list_str = write_list(item_vec, &fmt)?; Ok(format!("({list_str})")) } diff --git a/src/imports.rs b/src/imports.rs index 577e050f28c..5f4ea96d0a6 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -1066,11 +1066,7 @@ fn rewrite_nested_use_tree( .preserve_newline(true) .nested(has_nested_list); - let list_str = write_list( - &list_items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?; + let list_str = write_list(list_items, &fmt)?; let result = if (list_str.contains('\n') || list_str.len() > remaining_width diff --git a/src/items.rs b/src/items.rs index 760ca221ec3..1481c2e584a 100644 --- a/src/items.rs +++ b/src/items.rs @@ -652,12 +652,7 @@ impl<'a> FmtVisitor<'a> { .trailing_separator(self.config.trailing_comma()) .preserve_newline(true); - let list = write_list( - &items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) - .ok()?; + let list = write_list(items, &fmt).ok()?; result.push_str(&list); result.push_str(&original_offset.to_string_with_newline(self.config)); result.push('}'); @@ -2793,7 +2788,7 @@ struct WhereClauseOption { suppress_comma: bool, // Force no trailing comma snuggle: WhereClauseSpace, allow_single_line: bool, // Try single line where-clause instead of vertical layout - veto_single_line: bool, // Disallow a single-line where-clause. + veto_single_line: bool, // Disallow a single-line where-clause. } impl WhereClauseOption { @@ -2904,11 +2899,7 @@ fn rewrite_params( .trailing_separator(trailing_separator) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - write_list( - ¶m_items, - &fmt, - context.config.fn_parameter_post_comment_alignment(), - ) + write_list(param_items, &fmt) } fn compute_budgets_for_params( @@ -2932,7 +2923,7 @@ fn compute_budgets_for_params( let overhead = if ret_str_len == 0 { 2 } else { 3 }; let mut used_space = indent.width() + result.len() + ret_str_len + overhead; match fn_brace_style { - FnBraceStyle::None => used_space += 1, // 1 = `;` + FnBraceStyle::None => used_space += 1, // 1 = `;` FnBraceStyle::SameLine => used_space += 2, // 2 = `{}` FnBraceStyle::NextLine => (), } @@ -3170,11 +3161,7 @@ fn rewrite_bounds_on_where_clause( .tactic(shape_tactic) .trailing_separator(comma_tactic) .preserve_newline(preserve_newline); - write_list( - &items.collect::>(), - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) + write_list(items.collect::>(), &fmt) } fn rewrite_where_clause( @@ -3255,11 +3242,7 @@ fn rewrite_where_clause( .trailing_separator(comma_tactic) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - let preds_str = write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?; + let preds_str = write_list(item_vec, &fmt)?; let end_length = if terminator == "{" { // If the brace is on the next line we don't need to count it otherwise it needs two diff --git a/src/lists.rs b/src/lists.rs index ca6b720cdac..308e0565247 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -146,15 +146,6 @@ impl ListItem { self.item.as_ref().map_or("", |s| s) } - pub(crate) fn is_different_group(&self) -> bool { - self.inner_as_ref().contains('\n') - || self.pre_comment.is_some() - || self - .post_comment - .as_ref() - .map_or(false, |s| s.contains('\n')) - } - pub(crate) fn is_multiline(&self) -> bool { self.inner_as_ref().contains('\n') || self @@ -261,15 +252,10 @@ where } // Format a list of commented items into a string. -pub(crate) fn write_list( - items: I, +pub(crate) fn write_list<'a, T: AsRef + 'a>( + items: Vec, formatting: &ListFormatting<'_>, - post_comment_alignment_config: PostCommentAlignment, -) -> RewriteResult -where - I: IntoIterator + Clone, - T: AsRef, -{ +) -> RewriteResult { let tactic = formatting.tactic; let sep_len = formatting.separator.len(); @@ -277,9 +263,9 @@ where // will be a trailing separator. let mut trailing_separator = formatting.needs_trailing_separator(); let mut result = String::with_capacity(128); - let cloned_items = items.clone(); + let item_max_width = + max_width_of_item_with_post_comment(items.iter().map(|item| item.as_ref())); let mut iter = items.into_iter().enumerate().peekable(); - let mut item_max_width: Option = None; let sep_place = SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator); let mut prev_item_had_post_comment = false; @@ -287,6 +273,7 @@ where let mut line_len = 0; let indent_str = &formatting.shape.indent.to_string(formatting.config); + let indent_str_width = unicode_str_width(indent_str); while let Some((i, item)) = iter.next() { let item = item.as_ref(); let inner_item = item.item.as_ref().or_else(|err| Err(err.clone()))?; @@ -307,7 +294,7 @@ where }; let mut item_last_line_width = unicode_str_width(item_last_line) + item_sep_len; if item_last_line.starts_with(&**indent_str) { - item_last_line_width -= unicode_str_width(indent_str); + item_last_line_width -= indent_str_width; } if !item.is_substantial() { @@ -400,7 +387,6 @@ where result.push(' ') } } - item_max_width = None; } if separate && sep_place.is_front() && !first { @@ -429,35 +415,80 @@ where if tactic != DefinitiveListTactic::Horizontal && item.post_comment.is_some() { let comment = item.post_comment.as_ref().unwrap(); - let overhead = last_line_width(&result) + first_line_width(comment.trim()); - - let rewrite_post_comment = |item_max_width: &mut Option| { - if item_max_width.is_none() && !last && !inner_item.contains('\n') { - *item_max_width = Some(max_width_of_item_with_post_comment( - &cloned_items, - i, - overhead, - formatting.config.max_width(), - )); - } + + let rewrite_post_comment = || { let overhead = if starts_with_newline(comment) { 0 - } else if let Some(max_width) = *item_max_width { - max_width + 2 } else { - // 1 = space between item and comment. - item_last_line_width + 1 + match formatting.config.post_comment_alignment() { + PostCommentAlignment::SingleSpace => { + // 1 = space between item and comment. + item_last_line_width + 1 + } + PostCommentAlignment::SameIndent => 3, + } }; let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1); let offset = formatting.shape.indent + overhead; let comment_shape = Shape::legacy(width, offset); let block_style = if !formatting.ends_with_newline && last { + // Does not end with a new line, + // and is the last item. Ex. `a: usize, /* Hello */ }` + // There is an item after the comment which means + // this comment must be block style to preserve the code. + // See test: `struct_lits_visual_multiline.rs` true } else if starts_with_newline(comment) { + // If the comment starts with a newline. + // it is a standalone comment and not a post comment. false + } else if formatting.config.wrap_comments() { + let longest_comment_length = comment + .trim() + .lines() + .map(|line| unicode_str_width(line)) + .max() + .unwrap_or(0); + let line_length = match formatting.config.post_comment_alignment() { + PostCommentAlignment::SingleSpace => { + // line indentation + // + one space between + // + length of current comment line + // + alignment and length of comment + indent_str_width + 1 + longest_comment_length + overhead + } + PostCommentAlignment::SameIndent => { + // length of longest code line + // + one space between + // + length of longest comment line + // + alignment + item_max_width + 1 + longest_comment_length + overhead + } + }; + if line_length > formatting.config.max_width() { + true + } else if comment.trim().contains('\n') { + let style = crate::comment::comment_style(comment.trim_start(), false); + style.is_block_comment() + } else { + let style = crate::comment::comment_style( + comment.trim_start(), + formatting.config.normalize_comments(), + ); + style.is_block_comment() + } } else { - comment.trim().contains('\n') || unicode_str_width(comment.trim()) > width + if comment.trim().contains('\n') { + let style = crate::comment::comment_style(comment.trim_start(), false); + style.is_block_comment() + } else { + let style = crate::comment::comment_style( + comment.trim_start(), + formatting.config.normalize_comments(), + ); + style.is_block_comment() + } }; rewrite_comment( @@ -468,10 +499,13 @@ where ) }; - let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?; + let mut formatted_comment = rewrite_post_comment()?; if !starts_with_newline(comment) { - match post_comment_alignment_config { + match formatting.config.post_comment_alignment() { + PostCommentAlignment::SingleSpace => { + result.push(' '); + } PostCommentAlignment::SameIndent => { if formatting.align_comments { let mut comment_alignment = post_comment_alignment( @@ -484,8 +518,7 @@ where + 1 > formatting.config.max_width() { - item_max_width = None; - formatted_comment = rewrite_post_comment(&mut item_max_width)?; + formatted_comment = rewrite_post_comment()?; comment_alignment = post_comment_alignment( item_max_width, unicode_str_width(inner_item), @@ -498,28 +531,17 @@ where // An additional space for the missing trailing separator (or // if we skipped alignment above). if !formatting.align_comments - || (last - && item_max_width.is_some() - && !separate - && !formatting.separator.is_empty()) + || (last && !separate && !formatting.separator.is_empty()) { result.push(' '); } } - PostCommentAlignment::SingleSpace => { - result.push(' '); - } } } else { result.push('\n'); result.push_str(indent_str); } - if formatted_comment.contains('\n') { - item_max_width = None; - } result.push_str(&formatted_comment); - } else { - item_max_width = None; } if formatting.preserve_newline @@ -527,7 +549,6 @@ where && tactic == DefinitiveListTactic::Vertical && item.new_lines { - item_max_width = None; result.push('\n'); } @@ -538,41 +559,17 @@ where Ok(result) } -fn max_width_of_item_with_post_comment( - items: &I, - i: usize, - overhead: usize, - max_budget: usize, -) -> usize -where - I: IntoIterator + Clone, - T: AsRef, -{ - let mut max_width = 0; - let mut first = true; - for item in items.clone().into_iter().skip(i) { - let item = item.as_ref(); - let inner_item_width = unicode_str_width(item.inner_as_ref()); - if !first - && (item.is_different_group() - || item.post_comment.is_none() - || inner_item_width + overhead > max_budget) - { - return max_width; - } - if max_width < inner_item_width { - max_width = inner_item_width; - } - if item.new_lines { - return max_width; - } - first = false; - } - max_width +fn max_width_of_item_with_post_comment<'a>(items: impl Iterator) -> usize { + items + .filter(|item| item.post_comment.is_some()) + .filter_map(|item| item.inner_as_ref().lines().last()) + .map(|item| unicode_str_width(item)) + .max() + .unwrap_or(0) } -fn post_comment_alignment(item_max_width: Option, inner_item_width: usize) -> usize { - item_max_width.unwrap_or(0).saturating_sub(inner_item_width) +fn post_comment_alignment(item_max_width: usize, inner_item_width: usize) -> usize { + item_max_width.saturating_sub(inner_item_width) } pub(crate) struct ListItems<'a, I, F1, F2, F3> diff --git a/src/macros.rs b/src/macros.rs index 3699bf2f4de..d8ea90a6cb1 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -497,11 +497,7 @@ pub(crate) fn rewrite_macro_def( result += &arm_shape.indent.to_string_with_newline(context.config); } - match write_list( - &branch_items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) { + match write_list(branch_items, &fmt) { Ok(ref s) => result += s, Err(_) => return snippet, } diff --git a/src/matches.rs b/src/matches.rs index 12adc239e78..8e714d33e00 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -242,11 +242,7 @@ fn rewrite_match_arms( .separator("") .preserve_newline(true); - write_list( - &arms_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) + write_list(arms_vec, &fmt) } fn rewrite_match_arm( diff --git a/src/overflow.rs b/src/overflow.rs index 6c327f68c67..00f2202131f 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -663,12 +663,8 @@ impl<'a> Context<'a> { .trailing_separator(trailing_separator) .ends_with_newline(ends_with_newline); - write_list( - &list_items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) - .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str)) + write_list(list_items, &fmt) + .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str)) } fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String { diff --git a/src/patterns.rs b/src/patterns.rs index 75c53235358..eb6c6999866 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -129,11 +129,7 @@ impl Rewrite for Pat { .separator(" |") .separator_place(context.config.binop_separator()) .ends_with_newline(false); - write_list( - &items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) + write_list(items, &fmt) } PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape), PatKind::Ident(BindingMode(by_ref, mutability), ident, ref sub_pat) => { @@ -456,11 +452,7 @@ fn rewrite_struct_pat( let nested_shape = shape_for_tactic(tactic, h_shape, v_shape); let fmt = struct_lit_formatting(nested_shape, tactic, context, false); - let mut fields_str = write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?; + let mut fields_str = write_list(item_vec, &fmt)?; let one_line_width = h_shape.map_or(0, |shape| shape.width); let has_trailing_comma = fmt.needs_trailing_separator(); diff --git a/src/reorder.rs b/src/reorder.rs index 8bbff59fc3e..38b2cfc0eba 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -70,17 +70,13 @@ fn compare_items(a: &ast::Item, b: &ast::Item, context: &RewriteContext<'_>) -> fn wrap_reorderable_items( context: &RewriteContext<'_>, - list_items: &[ListItem], + list_items: Vec, shape: Shape, ) -> RewriteResult { let fmt = ListFormatting::new(shape, context.config) .separator("") .align_comments(false); - write_list( - list_items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) + write_list(list_items, &fmt) } fn rewrite_reorderable_item( @@ -164,7 +160,7 @@ fn rewrite_reorderable_or_regroupable_items( } }) .collect(); - wrap_reorderable_items(context, &item_vec, nested_shape) + wrap_reorderable_items(context, item_vec, nested_shape) }) .collect::, RewriteError>>()?; @@ -189,7 +185,7 @@ fn rewrite_reorderable_or_regroupable_items( item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1, context)); let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect(); - wrap_reorderable_items(context, &item_vec, shape) + wrap_reorderable_items(context, item_vec, shape) } } } diff --git a/src/types.rs b/src/types.rs index 30057f39217..23adecb3e74 100644 --- a/src/types.rs +++ b/src/types.rs @@ -405,14 +405,7 @@ where .trailing_separator(trailing_separator) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - ( - write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?, - tactic, - ) + (write_list(item_vec, &fmt)?, tactic) }; let args = if tactic == DefinitiveListTactic::Horizontal diff --git a/src/vertical.rs b/src/vertical.rs index 5148a43df44..0c7f4c6e579 100644 --- a/src/vertical.rs +++ b/src/vertical.rs @@ -266,12 +266,7 @@ fn rewrite_aligned_items_inner( .tactic(tactic) .trailing_separator(separator_tactic) .preserve_newline(true); - write_list( - &items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) - .ok() + write_list(items, &fmt).ok() } /// Returns the index in `fields` up to which a field belongs to the current group. diff --git a/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs index b0758caaef3..3010a58d900 100644 --- a/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs +++ b/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_parameter_post_comment_alignment: SameIndent +// rustfmt-post_comment_alignment: SameIndent fn foo( a: usize, // Chirp @@ -13,3 +13,25 @@ fn bar( c: f32, /* Meow */ ) { } + +trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { + fn macos_stat_write_buf( + &mut self, + metadata: FileMetadata, + buf_op: &OpTy<'tcx, Tag>, + ) -> InterpResult<'tcx, i32> { + let imms = [ + immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec + immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime + immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec + immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime + immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec + immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime + immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec + immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size + immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks + ]; + + Ok(0) + } +} diff --git a/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs index 639c5432d5d..0c79b901776 100644 --- a/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs +++ b/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_parameter_post_comment_alignment: SingleSpace +// rustfmt-post_comment_alignment: SingleSpace fn foo( a: usize, // Chirp @@ -12,11 +12,9 @@ fn bar( b: usize, // Bark c: f32, /* Meow */ ) { - // `fn_parameter_post_comment_alignment` should not - // affect post comments for match statements. match 0 { - 0 => todo!(), // IIIS - 1 => todo!(), // ASD + 0 => todo!(), // Beep + 1 => todo!(), // Boop _ => {} // Meep } } diff --git a/tests/target/cfg_if/detect/os/linux/aarch64.rs b/tests/target/cfg_if/detect/os/linux/aarch64.rs index 8d874f2280f..60ef2070385 100644 --- a/tests/target/cfg_if/detect/os/linux/aarch64.rs +++ b/tests/target/cfg_if/detect/os/linux/aarch64.rs @@ -27,16 +27,16 @@ fn detect_features() -> cache::Initializer { /// /// [hwcap]: https://github.com/torvalds/linux/blob/master/arch/arm64/include/uapi/asm/hwcap.h struct AtHwcap { - fp: bool, // 0 + fp: bool, // 0 asimd: bool, // 1 // evtstrm: bool, // 2 - aes: bool, // 3 - pmull: bool, // 4 - sha1: bool, // 5 - sha2: bool, // 6 - crc32: bool, // 7 + aes: bool, // 3 + pmull: bool, // 4 + sha1: bool, // 5 + sha2: bool, // 6 + crc32: bool, // 7 atomics: bool, // 8 - fphp: bool, // 9 + fphp: bool, // 9 asimdhp: bool, // 10 // cpuid: bool, // 11 asimdrdm: bool, // 12 diff --git a/tests/target/comments_unicode.rs b/tests/target/comments_unicode.rs index 3e1b6b0a28f..c63d95e5b74 100644 --- a/tests/target/comments_unicode.rs +++ b/tests/target/comments_unicode.rs @@ -1,9 +1,9 @@ impl Default for WhitespaceCharacters { fn default() -> Self { Self { - space: '·', // U+00B7 - nbsp: '⍽', // U+237D - tab: '→', // U+2192 + space: '·', // U+00B7 + nbsp: '⍽', // U+237D + tab: '→', // U+2192 newline: '⏎', // U+23CE } } diff --git a/tests/target/configs/struct_field_align_threshold/20.rs b/tests/target/configs/struct_field_align_threshold/20.rs index 12a523e9d83..ab408d79303 100644 --- a/tests/target/configs/struct_field_align_threshold/20.rs +++ b/tests/target/configs/struct_field_align_threshold/20.rs @@ -76,7 +76,7 @@ struct NewType(Type, OtherType); struct NewInt( pub i32, SomeType, // inline comment - T, // sup + T, // sup ); struct Qux< @@ -219,7 +219,7 @@ struct Foo( where T: PartialEq; struct Foo( - TTTTTTTTTTTTTTTTT, // Foo + TTTTTTTTTTTTTTTTT, // Foo UUUUUUUUUUUUUUUUUUUUUUUU, // Bar // Baz TTTTTTTTTTTTTTTTTTT, diff --git a/tests/target/enum.rs b/tests/target/enum.rs index 83b30999725..c560b0431c7 100644 --- a/tests/target/enum.rs +++ b/tests/target/enum.rs @@ -92,7 +92,7 @@ where I: Iterator, { // Pre Comment - Left { list: I, root: T }, // Post-comment + Left { list: I, root: T }, // Post-comment Right { list: I, root: T }, // Post Comment } diff --git a/tests/target/fn-args-with-last-line-comment.rs b/tests/target/fn-args-with-last-line-comment.rs index 27e0e09653e..4fc5b5777cb 100644 --- a/tests/target/fn-args-with-last-line-comment.rs +++ b/tests/target/fn-args-with-last-line-comment.rs @@ -3,8 +3,8 @@ pub trait X { fn a(&self) -> &'static str; fn bcd( &self, - c: &str, // comment on this arg - d: u16, // comment on this arg + c: &str, // comment on this arg + d: u16, // comment on this arg e: &Vec, // comment on this arg ) -> Box; } diff --git a/tests/target/fn-simple.rs b/tests/target/fn-simple.rs index e725269360d..cdfd3863d73 100644 --- a/tests/target/fn-simple.rs +++ b/tests/target/fn-simple.rs @@ -2,7 +2,7 @@ fn simple( // pre-comment on a function!? - i: i32, // yes, it's possible! + i: i32, // yes, it's possible! response: NoWay, // hose ) { fn op( diff --git a/tests/target/issue-2329.rs b/tests/target/issue-2329.rs index e36e9546b24..1e8340f2e66 100644 --- a/tests/target/issue-2329.rs +++ b/tests/target/issue-2329.rs @@ -24,7 +24,7 @@ fn main() { let x = 1; // X println!( "x = {}", // xの値 - x, // X + x, // X ); // コメント } diff --git a/tests/target/issue-3198.rs b/tests/target/issue-3198.rs index 9291f181d03..343042f6491 100644 --- a/tests/target/issue-3198.rs +++ b/tests/target/issue-3198.rs @@ -21,7 +21,7 @@ impl TestTrait { fn baz_post( self: X<'a, 'b>, /* Important comment1 */ - a: i32, /* Important comment2 */ + a: i32, /* Important comment2 */ ) { } @@ -37,8 +37,8 @@ impl TestTrait { fn baz_tree_post( self: X<'a, 'b>, /* Important comment1 */ - a: i32, /* Important comment2 */ - b: i32, /* Important comment3 */ + a: i32, /* Important comment2 */ + b: i32, /* Important comment3 */ ) { } diff --git a/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs index a1d1cb3419f..98bc30b32ea 100644 --- a/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs +++ b/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_parameter_post_comment_alignment: SameIndent +// rustfmt-post_comment_alignment: SameIndent fn foo( a: usize, // Chirp @@ -13,3 +13,25 @@ fn bar( c: f32, /* Meow */ ) { } + +trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { + fn macos_stat_write_buf( + &mut self, + metadata: FileMetadata, + buf_op: &OpTy<'tcx, Tag>, + ) -> InterpResult<'tcx, i32> { + let imms = [ + immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec + immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime + immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec + immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime + immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec + immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime + immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec + immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size + immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks + ]; + + Ok(0) + } +} diff --git a/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs index e6e95bcc07a..6abe3882607 100644 --- a/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs +++ b/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_parameter_post_comment_alignment: SingleSpace +// rustfmt-post_comment_alignment: SingleSpace fn foo( a: usize, // Chirp @@ -12,11 +12,9 @@ fn bar( b: usize, // Bark c: f32, /* Meow */ ) { - // `fn_parameter_post_comment_alignment` should not - // affect post comments for match statements. match 0 { - 0 => todo!(), // IIIS - 1 => todo!(), // ASD - _ => {} // Meep + 0 => todo!(), // Beep + 1 => todo!(), // Boop + _ => {} // Meep } } diff --git a/tests/target/issue-5568.rs b/tests/target/issue-5568.rs index 03ca3a4523c..5b1333fe4b3 100644 --- a/tests/target/issue-5568.rs +++ b/tests/target/issue-5568.rs @@ -5,10 +5,10 @@ mod libs { fn mrbgems_sources() { [ "mrbgems/mruby-compiler/core/codegen.c", // Ruby parser and bytecode generation - "mrbgems/mruby-compiler/core/y.tab.c", // Ruby parser and bytecode generation + "mrbgems/mruby-compiler/core/y.tab.c", // Ruby parser and bytecode generation "mrbgems/mruby-metaprog/src/metaprog.c", // APIs on Kernel and Module for accessing classes and variables - "mrbgems/mruby-method/src/method.c", // `Method`, `UnboundMethod`, and method APIs on Kernel and Module - "mrbgems/mruby-pack/src/pack.c", // Array#pack and String#unpack + "mrbgems/mruby-method/src/method.c", // `Method`, `UnboundMethod`, and method APIs on Kernel and Module + "mrbgems/mruby-pack/src/pack.c", // Array#pack and String#unpack ] } } diff --git a/tests/target/macros.rs b/tests/target/macros.rs index 7b4574349df..beef5807f6a 100644 --- a/tests/target/macros.rs +++ b/tests/target/macros.rs @@ -30,7 +30,7 @@ fn main() { kaas!( // comments a, // post macro - b // another + b // another ); trailingcomma!(a, b, c,); @@ -1050,7 +1050,7 @@ x! {()} f!(match a { 4 => &[ (3, false), // Missing - (4, true) // I-frame + (4, true) // I-frame ][..], }); diff --git a/tests/target/match.rs b/tests/target/match.rs index 0e7815a814d..a3405602981 100644 --- a/tests/target/match.rs +++ b/tests/target/match.rs @@ -176,8 +176,8 @@ fn issue355() { vec![3; 4] } h => println!("a", b), // h comment - i => vec![1, 2], // i comment - j => vec![3; 4], // j comment + i => vec![1, 2], // i comment + j => vec![3; 4], // j comment // k comment k => println!("a", b), // l comment @@ -216,11 +216,11 @@ fn issue355() { y => vec![3; 4], // Brackets with comments tc => println! {"a", b}, // comment - uc => vec![1, 2], // comment - vc => vec![3; 4], // comment - wc => println!["a", b], // comment - xc => vec![1, 2], // comment - yc => vec![3; 4], // comment + uc => vec![1, 2], // comment + vc => vec![3; 4], // comment + wc => println!["a", b], // comment + xc => vec![1, 2], // comment + yc => vec![3; 4], // comment yd => looooooooooooooooooooooooooooooooooooooooooooooooooooooooong_func( aaaaaaaaaa, bbbbbbbbbb, cccccccccc, dddddddddd, ), diff --git a/tests/target/multiple.rs b/tests/target/multiple.rs index d2b9789930b..a11d71fae0b 100644 --- a/tests/target/multiple.rs +++ b/tests/target/multiple.rs @@ -35,7 +35,7 @@ where } fn baz< - 'a: 'b, // comment on 'a + 'a: 'b, // comment on 'a T: SomsssssssssssssssssssssssssssssssssssssssssssssssssssssseType, // comment on T >( a: A, @@ -67,7 +67,7 @@ impl Bar { fn foo( &mut self, a: sdfsdfcccccccccccccccccccccccccccccccccccccccccccccccccc, // comment on a - b: sdfasdfsdfasfs, // closing comment + b: sdfasdfsdfasfs, // closing comment ) -> isize { } diff --git a/tests/target/structs.rs b/tests/target/structs.rs index 4948e37a5a3..f29ed619bc6 100644 --- a/tests/target/structs.rs +++ b/tests/target/structs.rs @@ -63,7 +63,7 @@ struct NewType(Type, OtherType); struct NewInt( pub i32, SomeType, // inline comment - T, // sup + T, // sup ); struct Qux< @@ -206,7 +206,7 @@ struct Foo( where T: PartialEq; struct Foo( - TTTTTTTTTTTTTTTTT, // Foo + TTTTTTTTTTTTTTTTT, // Foo UUUUUUUUUUUUUUUUUUUUUUUU, // Bar // Baz TTTTTTTTTTTTTTTTTTT, @@ -274,18 +274,18 @@ fn foo() { struct Foo { aaaaa: u32, // a - b: u32, // b + b: u32, // b cc: u32, // cc xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: u32, // 1 - yy: u32, // comment2 + yy: u32, // comment2 zzz: u32, // comment3 aaaaaa: u32, // comment4 - bb: u32, // comment5 + bb: u32, // comment5 // separate dd: u32, // comment7 - c: u32, // comment6 + c: u32, // comment6 aaaaaaa: u32, /* multi * line diff --git a/tests/target/unions.rs b/tests/target/unions.rs index 8ed16b269c2..dc157a4195c 100644 --- a/tests/target/unions.rs +++ b/tests/target/unions.rs @@ -163,18 +163,18 @@ fn foo() { union Foo { aaaaa: u32, // a - b: u32, // b + b: u32, // b cc: u32, // cc xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: u32, // 1 - yy: u32, // comment2 + yy: u32, // comment2 zzz: u32, // comment3 aaaaaa: u32, // comment4 - bb: u32, // comment5 + bb: u32, // comment5 // separate dd: u32, // comment7 - c: u32, // comment6 + c: u32, // comment6 aaaaaaa: u32, /* multi * line From 7965e53ac307d34f63761bfb4401708c9762ed05 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 00:47:00 -0400 Subject: [PATCH 03/24] chore: revert unnecessary variable assignment --- src/comment.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/comment.rs b/src/comment.rs index b4431f58d66..7cd2a8e2bc7 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -742,13 +742,10 @@ impl<'a> CommentRewrite<'a> { &item_fmt, self.max_width.saturating_sub(ib.indent), ) { - Some(s) => { - let r = Self::join_block( - &s, - &format!("{}{}", self.comment_line_separator, ib.line_start), - ); - self.result.push_str(&r) - } + Some(s) => self.result.push_str(&Self::join_block( + &s, + &format!("{}{}", self.comment_line_separator, ib.line_start), + )), None => self.result.push_str(&Self::join_block( &ib.original_block_as_string(), &self.comment_line_separator, From 1d60f38a39f1d49da50de6ad9f8c27c1097b3650 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 14:55:43 -0400 Subject: [PATCH 04/24] chore!: more thorough tests --- ... => same_indent_post_comment_alignment.rs} | 20 ++++++++++- ...ace_fn_parameter_post_comment_alignment.rs | 20 ----------- .../single_space_post_comment_alignment.rs | 33 +++++++++++++++++++ ... => same_indent_post_comment_alignment.rs} | 20 ++++++++++- ...ace_fn_parameter_post_comment_alignment.rs | 20 ----------- .../single_space_post_comment_alignment.rs | 33 +++++++++++++++++++ 6 files changed, 104 insertions(+), 42 deletions(-) rename tests/source/issue-4108/{same_indent_fn_parameter_post_comment_alignment.rs => same_indent_post_comment_alignment.rs} (74%) delete mode 100644 tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs create mode 100644 tests/source/issue-4108/single_space_post_comment_alignment.rs rename tests/target/issue-4108/{same_indent_fn_parameter_post_comment_alignment.rs => same_indent_post_comment_alignment.rs} (74%) delete mode 100644 tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs create mode 100644 tests/target/issue-4108/single_space_post_comment_alignment.rs diff --git a/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/same_indent_post_comment_alignment.rs similarity index 74% rename from tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs rename to tests/source/issue-4108/same_indent_post_comment_alignment.rs index 3010a58d900..0dcf44cefee 100644 --- a/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs +++ b/tests/source/issue-4108/same_indent_post_comment_alignment.rs @@ -1,5 +1,11 @@ // rustfmt-post_comment_alignment: SameIndent +use std::collections::{ + HashSet, // I am a hash set! + HashMap, + BTreeMap, // I am a TREE!!!!!! +}; + fn foo( a: usize, // Chirp b: usize, // Bark @@ -7,11 +13,23 @@ fn foo( ) { } +enum Animal { + Cat,// THIS IS A BUTTERFLY! + Dog, // THIS IS ME. + Bird, /* OKOKOKOKOKOKOK */ +} + fn bar( a: usize,/* Chirp */ b: usize, // Bark c: f32, /* Meow */ -) { + animal: Animal, +) -> &str { + match animal { + Animal::Cat => "meow",// Is this a bird? + Animal::Dog => "bark", // Is this a cat? + Animal::Bird => "chirp",// Is this a dog? + } } trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { diff --git a/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs deleted file mode 100644 index 0c79b901776..00000000000 --- a/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs +++ /dev/null @@ -1,20 +0,0 @@ -// rustfmt-post_comment_alignment: SingleSpace - -fn foo( - a: usize, // Chirp - b: usize, // Bark - c: f32, // Meow -) { -} - -fn bar( - a: usize,/* Chirp */ - b: usize, // Bark - c: f32, /* Meow */ -) { - match 0 { - 0 => todo!(), // Beep - 1 => todo!(), // Boop - _ => {} // Meep - } -} diff --git a/tests/source/issue-4108/single_space_post_comment_alignment.rs b/tests/source/issue-4108/single_space_post_comment_alignment.rs new file mode 100644 index 00000000000..29a813abb5b --- /dev/null +++ b/tests/source/issue-4108/single_space_post_comment_alignment.rs @@ -0,0 +1,33 @@ +// rustfmt-post_comment_alignment: SingleSpace + +use std::collections::{ + BTreeMap, // I am a TREE!!!!!! + HashMap, + HashSet, // I am a hash set! +}; + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +enum Animal { + Cat, // THIS IS A BUTTERFLY! + Dog, // THIS IS ME. + Bird, /* OKOKOKOKOKOKOK */ +} + +fn bar( + a: usize, /* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ + animal: Animal, +) -> &str { + match animal { + Animal::Cat => "meow", // Is this a bird? + Animal::Dog => "bark", // Is this a cat? + Animal::Bird => "chirp", // Is this a dog? + } +} diff --git a/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/same_indent_post_comment_alignment.rs similarity index 74% rename from tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs rename to tests/target/issue-4108/same_indent_post_comment_alignment.rs index 98bc30b32ea..86140fa681d 100644 --- a/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs +++ b/tests/target/issue-4108/same_indent_post_comment_alignment.rs @@ -1,5 +1,11 @@ // rustfmt-post_comment_alignment: SameIndent +use std::collections::{ + BTreeMap, // I am a TREE!!!!!! + HashMap, + HashSet, // I am a hash set! +}; + fn foo( a: usize, // Chirp b: usize, // Bark @@ -7,11 +13,23 @@ fn foo( ) { } +enum Animal { + Cat, // THIS IS A BUTTERFLY! + Dog, // THIS IS ME. + Bird, /* OKOKOKOKOKOKOK */ +} + fn bar( a: usize, /* Chirp */ b: usize, // Bark c: f32, /* Meow */ -) { + animal: Animal, +) -> &str { + match animal { + Animal::Cat => "meow", // Is this a bird? + Animal::Dog => "bark", // Is this a cat? + Animal::Bird => "chirp", // Is this a dog? + } } trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { diff --git a/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs deleted file mode 100644 index 6abe3882607..00000000000 --- a/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs +++ /dev/null @@ -1,20 +0,0 @@ -// rustfmt-post_comment_alignment: SingleSpace - -fn foo( - a: usize, // Chirp - b: usize, // Bark - c: f32, // Meow -) { -} - -fn bar( - a: usize, /* Chirp */ - b: usize, // Bark - c: f32, /* Meow */ -) { - match 0 { - 0 => todo!(), // Beep - 1 => todo!(), // Boop - _ => {} // Meep - } -} diff --git a/tests/target/issue-4108/single_space_post_comment_alignment.rs b/tests/target/issue-4108/single_space_post_comment_alignment.rs new file mode 100644 index 00000000000..9ef2b002859 --- /dev/null +++ b/tests/target/issue-4108/single_space_post_comment_alignment.rs @@ -0,0 +1,33 @@ +// rustfmt-post_comment_alignment: SingleSpace + +use std::collections::{ + BTreeMap, // I am a TREE!!!!!! + HashMap, + HashSet, // I am a hash set! +}; + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +enum Animal { + Cat, // THIS IS A BUTTERFLY! + Dog, // THIS IS ME. + Bird, /* OKOKOKOKOKOKOK */ +} + +fn bar( + a: usize, /* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ + animal: Animal, +) -> &str { + match animal { + Animal::Cat => "meow", // Is this a bird? + Animal::Dog => "bark", // Is this a cat? + Animal::Bird => "chirp", // Is this a dog? + } +} From 6a62662502ec7f2add768ca3852acc45dfd13ff5 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 16:51:28 -0400 Subject: [PATCH 05/24] chore!: remove unncessary pub --- src/comment.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/comment.rs b/src/comment.rs index 7cd2a8e2bc7..241934a7d3d 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -1083,10 +1083,7 @@ fn light_rewrite_comment( /// Trims comment characters and possibly a single space from the left of a string. /// Does not trim all whitespace. If a single space is trimmed from the left of the string, /// this function returns true. -pub(crate) fn left_trim_comment_line<'a>( - line: &'a str, - style: &CommentStyle<'_>, -) -> (&'a str, bool) { +fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a str, bool) { if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") From 3fc6e29321443ae8d21d231eace1748dbbd762f5 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 16:54:00 -0400 Subject: [PATCH 06/24] chore!: remove unncessary lifetime --- src/lists.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lists.rs b/src/lists.rs index 308e0565247..e3deeb31d23 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -252,7 +252,7 @@ where } // Format a list of commented items into a string. -pub(crate) fn write_list<'a, T: AsRef + 'a>( +pub(crate) fn write_list>( items: Vec, formatting: &ListFormatting<'_>, ) -> RewriteResult { From d06396825c633c7db46041e586d0e135a7c1029c Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 16:56:58 -0400 Subject: [PATCH 07/24] chore: replace comment period with comma --- src/lists.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lists.rs b/src/lists.rs index e3deeb31d23..44eaa71bed4 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -440,7 +440,7 @@ pub(crate) fn write_list>( // See test: `struct_lits_visual_multiline.rs` true } else if starts_with_newline(comment) { - // If the comment starts with a newline. + // If the comment starts with a newline, // it is a standalone comment and not a post comment. false } else if formatting.config.wrap_comments() { From f92d7941c69347ea34fa23c609ce8cd9bd39d915 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 20:12:33 -0400 Subject: [PATCH 08/24] feat!: removed align_comments field from ListFormatting --- src/lists.rs | 38 +++----------------------------------- src/reorder.rs | 4 +--- 2 files changed, 4 insertions(+), 38 deletions(-) diff --git a/src/lists.rs b/src/lists.rs index 44eaa71bed4..9685d2be36c 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -29,8 +29,6 @@ pub(crate) struct ListFormatting<'a> { preserve_newline: bool, // Nested import lists get some special handling for the "Mixed" list type nested: bool, - // Whether comments should be visually aligned. - align_comments: bool, config: &'a Config, } @@ -45,7 +43,6 @@ impl<'a> ListFormatting<'a> { ends_with_newline: true, preserve_newline: false, nested: false, - align_comments: true, config, } } @@ -85,11 +82,6 @@ impl<'a> ListFormatting<'a> { self } - pub(crate) fn align_comments(mut self, align_comments: bool) -> Self { - self.align_comments = align_comments; - self - } - pub(crate) fn needs_trailing_separator(&self) -> bool { match self.trailing_separator { // We always put separator in front. @@ -507,32 +499,9 @@ pub(crate) fn write_list>( result.push(' '); } PostCommentAlignment::SameIndent => { - if formatting.align_comments { - let mut comment_alignment = post_comment_alignment( - item_max_width, - unicode_str_width(inner_item), - ); - if first_line_width(&formatted_comment) - + last_line_width(&result) - + comment_alignment - + 1 - > formatting.config.max_width() - { - formatted_comment = rewrite_post_comment()?; - comment_alignment = post_comment_alignment( - item_max_width, - unicode_str_width(inner_item), - ); - } - for _ in 0..=comment_alignment { - result.push(' '); - } - } - // An additional space for the missing trailing separator (or - // if we skipped alignment above). - if !formatting.align_comments - || (last && !separate && !formatting.separator.is_empty()) - { + let comment_alignment = + post_comment_alignment(item_max_width, unicode_str_width(inner_item)); + for _ in 0..=comment_alignment { result.push(' '); } } @@ -956,7 +925,6 @@ pub(crate) fn struct_lit_formatting<'a>( ends_with_newline, preserve_newline: true, nested: false, - align_comments: true, config: context.config, } } diff --git a/src/reorder.rs b/src/reorder.rs index 38b2cfc0eba..24b2aaa5793 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -73,9 +73,7 @@ fn wrap_reorderable_items( list_items: Vec, shape: Shape, ) -> RewriteResult { - let fmt = ListFormatting::new(shape, context.config) - .separator("") - .align_comments(false); + let fmt = ListFormatting::new(shape, context.config).separator(""); write_list(list_items, &fmt) } From 5887c12939e43675957e98bc32c89cc877c07220 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 20:37:39 -0400 Subject: [PATCH 09/24] chore: remove unnecessary imports --- src/lists.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/lists.rs b/src/lists.rs index 9685d2be36c..134fef592a7 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -10,10 +10,7 @@ use crate::config::{Config, IndentStyle}; use crate::config::{PostCommentAlignment, lists::*}; use crate::rewrite::{ExceedsMaxWidthError, RewriteContext, RewriteError, RewriteResult}; use crate::shape::{Indent, Shape}; -use crate::utils::{ - count_newlines, first_line_width, last_line_width, mk_sp, starts_with_newline, - unicode_str_width, -}; +use crate::utils::{count_newlines, mk_sp, starts_with_newline, unicode_str_width}; use crate::visitor::SnippetProvider; pub(crate) struct ListFormatting<'a> { @@ -491,7 +488,7 @@ pub(crate) fn write_list>( ) }; - let mut formatted_comment = rewrite_post_comment()?; + let formatted_comment = rewrite_post_comment()?; if !starts_with_newline(comment) { match formatting.config.post_comment_alignment() { From 2ad33388beaa01c16c6e30c8be825cab6fca32c2 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 20:57:06 -0400 Subject: [PATCH 10/24] chore: move functionality into is_block_comment_multiline_or_normalized function --- src/lists.rs | 41 +++++++++++++++++++---------------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/src/lists.rs b/src/lists.rs index 134fef592a7..5dbd37d05a0 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -421,6 +421,22 @@ pub(crate) fn write_list>( let offset = formatting.shape.indent + overhead; let comment_shape = Shape::legacy(width, offset); + fn is_block_comment_multiline_or_normalized( + comment: &str, + config: &Config, + ) -> bool { + if comment.trim().contains('\n') { + let style = crate::comment::comment_style(comment.trim_start(), false); + style.is_block_comment() + } else { + let style = crate::comment::comment_style( + comment.trim_start(), + config.normalize_comments(), + ); + style.is_block_comment() + } + } + let block_style = if !formatting.ends_with_newline && last { // Does not end with a new line, // and is the last item. Ex. `a: usize, /* Hello */ }` @@ -455,29 +471,10 @@ pub(crate) fn write_list>( item_max_width + 1 + longest_comment_length + overhead } }; - if line_length > formatting.config.max_width() { - true - } else if comment.trim().contains('\n') { - let style = crate::comment::comment_style(comment.trim_start(), false); - style.is_block_comment() - } else { - let style = crate::comment::comment_style( - comment.trim_start(), - formatting.config.normalize_comments(), - ); - style.is_block_comment() - } + line_length > formatting.config.max_width() + || is_block_comment_multiline_or_normalized(comment, formatting.config) } else { - if comment.trim().contains('\n') { - let style = crate::comment::comment_style(comment.trim_start(), false); - style.is_block_comment() - } else { - let style = crate::comment::comment_style( - comment.trim_start(), - formatting.config.normalize_comments(), - ); - style.is_block_comment() - } + is_block_comment_multiline_or_normalized(comment, formatting.config) }; rewrite_comment( From 0d45b67e4e3f2fd94bbcfc5d78d060431e276662 Mon Sep 17 00:00:00 2001 From: Albar Date: Mon, 1 Jun 2026 15:40:57 -0400 Subject: [PATCH 11/24] chore: change operation and comment for readability --- src/lists.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lists.rs b/src/lists.rs index 5dbd37d05a0..7461eecd5da 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -458,10 +458,10 @@ pub(crate) fn write_list>( let line_length = match formatting.config.post_comment_alignment() { PostCommentAlignment::SingleSpace => { // line indentation + // + alignment and length of current code line // + one space between // + length of current comment line - // + alignment and length of comment - indent_str_width + 1 + longest_comment_length + overhead + indent_str_width + overhead + 1 + longest_comment_length } PostCommentAlignment::SameIndent => { // length of longest code line From b14b493eabdcf9820c0d5d0816198c282e0a3251 Mon Sep 17 00:00:00 2001 From: Albar Date: Mon, 1 Jun 2026 15:56:52 -0400 Subject: [PATCH 12/24] chore: update Configurations.md default post_comment_alignment value --- Configurations.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Configurations.md b/Configurations.md index f0ff5a14dce..50ced51631e 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1255,8 +1255,8 @@ See also: [`tab_spaces`](#tab_spaces). Alignment of post comments -- **Default value**: `SameIndent` -- **Possible values**: `SameIndent`, `SingleSpace` +- **Default value**: `SingleSpace` +- **Possible values**: `SingleSpace`, `SameIndent` - **Stable**: No #### `SingleSpace`: From ba2076edd51b190cd82152edc4e6f19a004bad5a Mon Sep 17 00:00:00 2001 From: Albar Date: Tue, 26 May 2026 20:37:51 -0400 Subject: [PATCH 13/24] feat!: fn_parameter_post_comment_alignment config option --- Configurations.md | 34 ++++++++++ src/attr.rs | 7 +- src/closures.rs | 6 +- src/config/mod.rs | 4 ++ src/config/options.rs | 11 +++ src/expr.rs | 12 +++- src/imports.rs | 6 +- src/items.rs | 25 +++++-- src/lists.rs | 67 ++++++++++++------- src/macros.rs | 6 +- src/matches.rs | 6 +- src/overflow.rs | 8 ++- src/patterns.rs | 12 +++- src/reorder.rs | 6 +- src/types.rs | 9 ++- src/vertical.rs | 7 +- ...ent_fn_parameter_post_comment_alignment.rs | 15 +++++ ...ace_fn_parameter_post_comment_alignment.rs | 22 ++++++ ...ent_fn_parameter_post_comment_alignment.rs | 15 +++++ ...ace_fn_parameter_post_comment_alignment.rs | 22 ++++++ 20 files changed, 256 insertions(+), 44 deletions(-) create mode 100644 tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs create mode 100644 tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs create mode 100644 tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs create mode 100644 tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs diff --git a/Configurations.md b/Configurations.md index 976c2904894..4ed796c9b72 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1259,6 +1259,40 @@ fn lorem() -> usize { See also: [`tab_spaces`](#tab_spaces). +## `fn_parameter_post_comment_alignment` + +Alignment of comments after function parameters + +- **Default value**: `SameIndent` +- **Possible values**: `SameIndent`, `SingleSpace` +- **Stable**: No + +#### `SameIndent` (default): + +Each comment has the same indentation. + +```rust +fn foo( + a: usize, // Cat + b: usize, // Dog + c: f32, // Bird +) { +} +``` + +#### `SingleSpace`: + +One space between the code and comment. + +```rust +fn foo( + a: usize, // Cat + b: usize, // Dog + c: f32, // Bird +) { +} +``` + ## `hex_literal_case` Control the case of the letters in hexadecimal literal values diff --git a/src/attr.rs b/src/attr.rs index ac9ce2e8796..21165a4b1cc 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -147,7 +147,12 @@ fn format_derive( .tactic(tactic) .trailing_separator(trailing_separator) .ends_with_newline(false); - let item_str = write_list(&all_items, &fmt).ok()?; + let item_str = write_list( + &all_items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) + .ok()?; debug!("item_str: '{}'", item_str); diff --git a/src/closures.rs b/src/closures.rs index 19cd0d9792c..e5dec828ae7 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -338,7 +338,11 @@ fn rewrite_closure_fn_decl( let fmt = ListFormatting::new(param_shape, context.config) .tactic(tactic) .preserve_newline(true); - let list_str = write_list(&item_vec, &fmt)?; + let list_str = write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?; let mut prefix = format!("{binder}{const_}{immovable}{coro}{capture_str}|{list_str}|"); if !ret_str.is_empty() { diff --git a/src/config/mod.rs b/src/config/mod.rs index a3f9842cd4f..91f0b1cd046 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -81,6 +81,8 @@ create_config! { "Format the bodies of declarative macro definitions"; skip_macro_invocations: SkipMacroInvocations, false, "Skip formatting the bodies of macros invoked with the following names."; + fn_parameter_post_comment_alignment: FnParameterPostCommentAlignmentConfig, false, + "Alignment of comments after function parameters"; hex_literal_case: HexLiteralCaseConfig, true, "Format hexadecimal integer literals"; float_literal_trailing_zero: FloatLiteralTrailingZeroConfig, false, "Add or remove trailing zero in floating-point literals"; @@ -783,6 +785,7 @@ format_strings = false format_macro_matchers = false format_macro_bodies = true skip_macro_invocations = [] +fn_parameter_post_comment_alignment = "SameIndent" hex_literal_case = "Preserve" float_literal_trailing_zero = "Preserve" empty_item_single_line = true @@ -876,6 +879,7 @@ format_strings = false format_macro_matchers = false format_macro_bodies = true skip_macro_invocations = [] +fn_parameter_post_comment_alignment = "SameIndent" hex_literal_case = "Preserve" float_literal_trailing_zero = "Preserve" empty_item_single_line = true diff --git a/src/config/options.rs b/src/config/options.rs index 3f970ed4bd7..377a0507c73 100644 --- a/src/config/options.rs +++ b/src/config/options.rs @@ -160,6 +160,15 @@ pub enum ImportGranularity { One, } +/// Controls how rustfmt should align post comments. +#[config_type] +pub enum PostCommentAlignment { + /// List each comment with the same indentation from the previous. + SameIndent, + /// Insert one space between the code and comment. + SingleSpace, +} + /// Controls how rustfmt should handle case in hexadecimal literals. #[config_type] pub enum HexLiteralCase { @@ -653,6 +662,8 @@ config_option_with_style_edition_default!( FormatMacroMatchers, bool, _ => false; FormatMacroBodies, bool, _ => true; SkipMacroInvocations, MacroSelectors, _ => MacroSelectors::default(); + FnParameterPostCommentAlignmentConfig, PostCommentAlignment, _ => + PostCommentAlignment::SameIndent; HexLiteralCaseConfig, HexLiteralCase, _ => HexLiteralCase::Preserve; FloatLiteralTrailingZeroConfig, FloatLiteralTrailingZero, _ => FloatLiteralTrailingZero::Preserve; diff --git a/src/expr.rs b/src/expr.rs index 22634abb977..8d8e47905be 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1818,7 +1818,11 @@ fn rewrite_struct_lit<'a>( force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(), ); - write_list(&item_vec, &fmt)? + write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )? }; let fields_str = @@ -1965,7 +1969,11 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>( let fmt = ListFormatting::new(nested_shape, context.config) .tactic(tactic) .ends_with_newline(false); - let list_str = write_list(&item_vec, &fmt)?; + let list_str = write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?; Ok(format!("({list_str})")) } diff --git a/src/imports.rs b/src/imports.rs index c5a2a5de2f1..08ac4b489ef 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -1066,7 +1066,11 @@ fn rewrite_nested_use_tree( .preserve_newline(true) .nested(has_nested_list); - let list_str = write_list(&list_items, &fmt)?; + let list_str = write_list( + &list_items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?; let result = if (list_str.contains('\n') || list_str.len() > remaining_width diff --git a/src/items.rs b/src/items.rs index 484c5b50adf..2645904f5fd 100644 --- a/src/items.rs +++ b/src/items.rs @@ -652,7 +652,12 @@ impl<'a> FmtVisitor<'a> { .trailing_separator(self.config.trailing_comma()) .preserve_newline(true); - let list = write_list(&items, &fmt).ok()?; + let list = write_list( + &items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) + .ok()?; result.push_str(&list); result.push_str(&original_offset.to_string_with_newline(self.config)); result.push('}'); @@ -2902,7 +2907,11 @@ fn rewrite_params( .trailing_separator(trailing_separator) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - write_list(¶m_items, &fmt) + write_list( + ¶m_items, + &fmt, + context.config.fn_parameter_post_comment_alignment(), + ) } fn compute_budgets_for_params( @@ -3164,7 +3173,11 @@ fn rewrite_bounds_on_where_clause( .tactic(shape_tactic) .trailing_separator(comma_tactic) .preserve_newline(preserve_newline); - write_list(&items.collect::>(), &fmt) + write_list( + &items.collect::>(), + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) } fn rewrite_where_clause( @@ -3245,7 +3258,11 @@ fn rewrite_where_clause( .trailing_separator(comma_tactic) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - let preds_str = write_list(&item_vec, &fmt)?; + let preds_str = write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?; let end_length = if terminator == "{" { // If the brace is on the next line we don't need to count it otherwise it needs two diff --git a/src/lists.rs b/src/lists.rs index 9d811e5d9b5..ca6b720cdac 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -6,8 +6,8 @@ use std::iter::Peekable; use rustc_span::{BytePos, Span}; use crate::comment::{FindUncommented, find_comment_end, rewrite_comment}; -use crate::config::lists::*; use crate::config::{Config, IndentStyle}; +use crate::config::{PostCommentAlignment, lists::*}; use crate::rewrite::{ExceedsMaxWidthError, RewriteContext, RewriteError, RewriteResult}; use crate::shape::{Indent, Shape}; use crate::utils::{ @@ -261,7 +261,11 @@ where } // Format a list of commented items into a string. -pub(crate) fn write_list(items: I, formatting: &ListFormatting<'_>) -> RewriteResult +pub(crate) fn write_list( + items: I, + formatting: &ListFormatting<'_>, + post_comment_alignment_config: PostCommentAlignment, +) -> RewriteResult where I: IntoIterator + Clone, T: AsRef, @@ -467,34 +471,45 @@ where let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?; if !starts_with_newline(comment) { - if formatting.align_comments { - let mut comment_alignment = - post_comment_alignment(item_max_width, unicode_str_width(inner_item)); - if first_line_width(&formatted_comment) - + last_line_width(&result) - + comment_alignment - + 1 - > formatting.config.max_width() - { - item_max_width = None; - formatted_comment = rewrite_post_comment(&mut item_max_width)?; - comment_alignment = - post_comment_alignment(item_max_width, unicode_str_width(inner_item)); + match post_comment_alignment_config { + PostCommentAlignment::SameIndent => { + if formatting.align_comments { + let mut comment_alignment = post_comment_alignment( + item_max_width, + unicode_str_width(inner_item), + ); + if first_line_width(&formatted_comment) + + last_line_width(&result) + + comment_alignment + + 1 + > formatting.config.max_width() + { + item_max_width = None; + formatted_comment = rewrite_post_comment(&mut item_max_width)?; + comment_alignment = post_comment_alignment( + item_max_width, + unicode_str_width(inner_item), + ); + } + for _ in 0..=comment_alignment { + result.push(' '); + } + } + // An additional space for the missing trailing separator (or + // if we skipped alignment above). + if !formatting.align_comments + || (last + && item_max_width.is_some() + && !separate + && !formatting.separator.is_empty()) + { + result.push(' '); + } } - for _ in 0..=comment_alignment { + PostCommentAlignment::SingleSpace => { result.push(' '); } } - // An additional space for the missing trailing separator (or - // if we skipped alignment above). - if !formatting.align_comments - || (last - && item_max_width.is_some() - && !separate - && !formatting.separator.is_empty()) - { - result.push(' '); - } } else { result.push('\n'); result.push_str(indent_str); diff --git a/src/macros.rs b/src/macros.rs index 2d56021069c..3699bf2f4de 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -497,7 +497,11 @@ pub(crate) fn rewrite_macro_def( result += &arm_shape.indent.to_string_with_newline(context.config); } - match write_list(&branch_items, &fmt) { + match write_list( + &branch_items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) { Ok(ref s) => result += s, Err(_) => return snippet, } diff --git a/src/matches.rs b/src/matches.rs index 50c0db8ac06..2a469a2dbdf 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -242,7 +242,11 @@ fn rewrite_match_arms( .separator("") .preserve_newline(true); - write_list(&arms_vec, &fmt) + write_list( + &arms_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) } fn rewrite_match_arm( diff --git a/src/overflow.rs b/src/overflow.rs index 4230c89b57b..6c327f68c67 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -663,8 +663,12 @@ impl<'a> Context<'a> { .trailing_separator(trailing_separator) .ends_with_newline(ends_with_newline); - write_list(&list_items, &fmt) - .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str)) + write_list( + &list_items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) + .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str)) } fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String { diff --git a/src/patterns.rs b/src/patterns.rs index 2fad1d41ae9..5a8d65d6cbd 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -112,7 +112,11 @@ impl Rewrite for Pat { .separator(" |") .separator_place(context.config.binop_separator()) .ends_with_newline(false); - write_list(&items, &fmt) + write_list( + &items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) } PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape), PatKind::Ident(BindingMode(by_ref, mutability), ident, ref sub_pat) => { @@ -395,7 +399,11 @@ fn rewrite_struct_pat( let nested_shape = shape_for_tactic(tactic, h_shape, v_shape); let fmt = struct_lit_formatting(nested_shape, tactic, context, false); - let mut fields_str = write_list(&item_vec, &fmt)?; + let mut fields_str = write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?; let one_line_width = h_shape.map_or(0, |shape| shape.width); let has_trailing_comma = fmt.needs_trailing_separator(); diff --git a/src/reorder.rs b/src/reorder.rs index 6ef6e0bc969..8bbff59fc3e 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -76,7 +76,11 @@ fn wrap_reorderable_items( let fmt = ListFormatting::new(shape, context.config) .separator("") .align_comments(false); - write_list(list_items, &fmt) + write_list( + list_items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) } fn rewrite_reorderable_item( diff --git a/src/types.rs b/src/types.rs index 92a649bf634..bee6b9d9475 100644 --- a/src/types.rs +++ b/src/types.rs @@ -405,7 +405,14 @@ where .trailing_separator(trailing_separator) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - (write_list(&item_vec, &fmt)?, tactic) + ( + write_list( + &item_vec, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + )?, + tactic, + ) }; let args = if tactic == DefinitiveListTactic::Horizontal diff --git a/src/vertical.rs b/src/vertical.rs index fd9a4a7db6a..8a5aea3dc07 100644 --- a/src/vertical.rs +++ b/src/vertical.rs @@ -266,7 +266,12 @@ fn rewrite_aligned_items_inner( .tactic(tactic) .trailing_separator(separator_tactic) .preserve_newline(true); - write_list(&items, &fmt).ok() + write_list( + &items, + &fmt, + crate::config::PostCommentAlignment::SameIndent, + ) + .ok() } /// Returns the index in `fields` up to which a field belongs to the current group. diff --git a/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs new file mode 100644 index 00000000000..b0758caaef3 --- /dev/null +++ b/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs @@ -0,0 +1,15 @@ +// rustfmt-fn_parameter_post_comment_alignment: SameIndent + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +fn bar( + a: usize,/* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ +) { +} diff --git a/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs new file mode 100644 index 00000000000..639c5432d5d --- /dev/null +++ b/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs @@ -0,0 +1,22 @@ +// rustfmt-fn_parameter_post_comment_alignment: SingleSpace + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +fn bar( + a: usize,/* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ +) { + // `fn_parameter_post_comment_alignment` should not + // affect post comments for match statements. + match 0 { + 0 => todo!(), // IIIS + 1 => todo!(), // ASD + _ => {} // Meep + } +} diff --git a/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs new file mode 100644 index 00000000000..a1d1cb3419f --- /dev/null +++ b/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs @@ -0,0 +1,15 @@ +// rustfmt-fn_parameter_post_comment_alignment: SameIndent + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +fn bar( + a: usize, /* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ +) { +} diff --git a/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs new file mode 100644 index 00000000000..e6e95bcc07a --- /dev/null +++ b/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs @@ -0,0 +1,22 @@ +// rustfmt-fn_parameter_post_comment_alignment: SingleSpace + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +fn bar( + a: usize, /* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ +) { + // `fn_parameter_post_comment_alignment` should not + // affect post comments for match statements. + match 0 { + 0 => todo!(), // IIIS + 1 => todo!(), // ASD + _ => {} // Meep + } +} From fbf6a0a04a6cf8f9f01e48550168456cef7933ac Mon Sep 17 00:00:00 2001 From: Albar Date: Sat, 30 May 2026 23:18:01 -0400 Subject: [PATCH 14/24] feat!: change fn_parameter_post_comment_alignment to post_comment_alignment --- Configurations.md | 16 +- src/attr.rs | 7 +- src/closures.rs | 6 +- src/comment.rs | 16 +- src/config/mod.rs | 8 +- src/config/options.rs | 8 +- src/expr.rs | 12 +- src/imports.rs | 6 +- src/items.rs | 29 +-- src/lists.rs | 171 +++++++++--------- src/macros.rs | 6 +- src/matches.rs | 6 +- src/overflow.rs | 8 +- src/patterns.rs | 12 +- src/reorder.rs | 12 +- src/types.rs | 9 +- src/vertical.rs | 7 +- ...ent_fn_parameter_post_comment_alignment.rs | 24 ++- ...ace_fn_parameter_post_comment_alignment.rs | 8 +- .../target/cfg_if/detect/os/linux/aarch64.rs | 14 +- tests/target/comments_unicode.rs | 6 +- .../struct_field_align_threshold/20.rs | 4 +- tests/target/enum.rs | 2 +- .../target/fn-args-with-last-line-comment.rs | 4 +- tests/target/fn-simple.rs | 2 +- tests/target/issue-2329.rs | 2 +- tests/target/issue-3198.rs | 6 +- ...ent_fn_parameter_post_comment_alignment.rs | 24 ++- ...ace_fn_parameter_post_comment_alignment.rs | 10 +- tests/target/issue-5568.rs | 6 +- tests/target/macros.rs | 4 +- tests/target/match.rs | 14 +- tests/target/multiple.rs | 4 +- tests/target/structs.rs | 12 +- tests/target/unions.rs | 8 +- 35 files changed, 231 insertions(+), 262 deletions(-) diff --git a/Configurations.md b/Configurations.md index 4ed796c9b72..53dab946037 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1259,36 +1259,36 @@ fn lorem() -> usize { See also: [`tab_spaces`](#tab_spaces). -## `fn_parameter_post_comment_alignment` +## `post_comment_alignment` -Alignment of comments after function parameters +Alignment of post comments - **Default value**: `SameIndent` - **Possible values**: `SameIndent`, `SingleSpace` - **Stable**: No -#### `SameIndent` (default): +#### `SingleSpace`: -Each comment has the same indentation. +One space between the code and comment. ```rust fn foo( a: usize, // Cat b: usize, // Dog - c: f32, // Bird + c: f32, // Bird ) { } ``` -#### `SingleSpace`: +#### `SameIndent` (default): -One space between the code and comment. +Each comment has the same indentation. ```rust fn foo( a: usize, // Cat b: usize, // Dog - c: f32, // Bird + c: f32, // Bird ) { } ``` diff --git a/src/attr.rs b/src/attr.rs index 21165a4b1cc..c0655abb57e 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -147,12 +147,7 @@ fn format_derive( .tactic(tactic) .trailing_separator(trailing_separator) .ends_with_newline(false); - let item_str = write_list( - &all_items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) - .ok()?; + let item_str = write_list(all_items, &fmt).ok()?; debug!("item_str: '{}'", item_str); diff --git a/src/closures.rs b/src/closures.rs index e5dec828ae7..2421299d4fe 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -338,11 +338,7 @@ fn rewrite_closure_fn_decl( let fmt = ListFormatting::new(param_shape, context.config) .tactic(tactic) .preserve_newline(true); - let list_str = write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?; + let list_str = write_list(item_vec, &fmt)?; let mut prefix = format!("{binder}{const_}{immovable}{coro}{capture_str}|{list_str}|"); if !ret_str.is_empty() { diff --git a/src/comment.rs b/src/comment.rs index 05d7310122a..26a62ef0304 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -742,10 +742,13 @@ impl<'a> CommentRewrite<'a> { &item_fmt, self.max_width.saturating_sub(ib.indent), ) { - Some(s) => self.result.push_str(&Self::join_block( - &s, - &format!("{}{}", self.comment_line_separator, ib.line_start), - )), + Some(s) => { + let r = Self::join_block( + &s, + &format!("{}{}", self.comment_line_separator, ib.line_start), + ); + self.result.push_str(&r) + } None => self.result.push_str(&Self::join_block( &ib.original_block_as_string(), &self.comment_line_separator, @@ -1091,7 +1094,10 @@ fn light_rewrite_comment( /// Trims comment characters and possibly a single space from the left of a string. /// Does not trim all whitespace. If a single space is trimmed from the left of the string, /// this function returns true. -fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a str, bool) { +pub(crate) fn left_trim_comment_line<'a>( + line: &'a str, + style: &CommentStyle<'_>, +) -> (&'a str, bool) { if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") diff --git a/src/config/mod.rs b/src/config/mod.rs index 91f0b1cd046..d20e1f7379c 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -81,8 +81,8 @@ create_config! { "Format the bodies of declarative macro definitions"; skip_macro_invocations: SkipMacroInvocations, false, "Skip formatting the bodies of macros invoked with the following names."; - fn_parameter_post_comment_alignment: FnParameterPostCommentAlignmentConfig, false, - "Alignment of comments after function parameters"; + post_comment_alignment: PostCommentAlignmentConfig, false, + "Alignment of post comments"; hex_literal_case: HexLiteralCaseConfig, true, "Format hexadecimal integer literals"; float_literal_trailing_zero: FloatLiteralTrailingZeroConfig, false, "Add or remove trailing zero in floating-point literals"; @@ -785,7 +785,7 @@ format_strings = false format_macro_matchers = false format_macro_bodies = true skip_macro_invocations = [] -fn_parameter_post_comment_alignment = "SameIndent" +post_comment_alignment = "SingleSpace" hex_literal_case = "Preserve" float_literal_trailing_zero = "Preserve" empty_item_single_line = true @@ -879,7 +879,7 @@ format_strings = false format_macro_matchers = false format_macro_bodies = true skip_macro_invocations = [] -fn_parameter_post_comment_alignment = "SameIndent" +post_comment_alignment = "SingleSpace" hex_literal_case = "Preserve" float_literal_trailing_zero = "Preserve" empty_item_single_line = true diff --git a/src/config/options.rs b/src/config/options.rs index 377a0507c73..95d4cb65efe 100644 --- a/src/config/options.rs +++ b/src/config/options.rs @@ -163,10 +163,10 @@ pub enum ImportGranularity { /// Controls how rustfmt should align post comments. #[config_type] pub enum PostCommentAlignment { - /// List each comment with the same indentation from the previous. - SameIndent, /// Insert one space between the code and comment. SingleSpace, + /// List each comment with the same indentation from the previous. + SameIndent, } /// Controls how rustfmt should handle case in hexadecimal literals. @@ -662,8 +662,8 @@ config_option_with_style_edition_default!( FormatMacroMatchers, bool, _ => false; FormatMacroBodies, bool, _ => true; SkipMacroInvocations, MacroSelectors, _ => MacroSelectors::default(); - FnParameterPostCommentAlignmentConfig, PostCommentAlignment, _ => - PostCommentAlignment::SameIndent; + PostCommentAlignmentConfig, PostCommentAlignment, _ => + PostCommentAlignment::SingleSpace; HexLiteralCaseConfig, HexLiteralCase, _ => HexLiteralCase::Preserve; FloatLiteralTrailingZeroConfig, FloatLiteralTrailingZero, _ => FloatLiteralTrailingZero::Preserve; diff --git a/src/expr.rs b/src/expr.rs index 8d8e47905be..2ab0c403a1f 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1818,11 +1818,7 @@ fn rewrite_struct_lit<'a>( force_no_trailing_comma || has_base_or_rest || !context.use_block_indent(), ); - write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )? + write_list(item_vec, &fmt)? }; let fields_str = @@ -1969,11 +1965,7 @@ fn rewrite_tuple_in_visual_indent_style<'a, T: 'a + IntoOverflowableItem<'a>>( let fmt = ListFormatting::new(nested_shape, context.config) .tactic(tactic) .ends_with_newline(false); - let list_str = write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?; + let list_str = write_list(item_vec, &fmt)?; Ok(format!("({list_str})")) } diff --git a/src/imports.rs b/src/imports.rs index 08ac4b489ef..66e6e640f30 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -1066,11 +1066,7 @@ fn rewrite_nested_use_tree( .preserve_newline(true) .nested(has_nested_list); - let list_str = write_list( - &list_items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?; + let list_str = write_list(list_items, &fmt)?; let result = if (list_str.contains('\n') || list_str.len() > remaining_width diff --git a/src/items.rs b/src/items.rs index 2645904f5fd..65f3b9717e5 100644 --- a/src/items.rs +++ b/src/items.rs @@ -652,12 +652,7 @@ impl<'a> FmtVisitor<'a> { .trailing_separator(self.config.trailing_comma()) .preserve_newline(true); - let list = write_list( - &items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) - .ok()?; + let list = write_list(items, &fmt).ok()?; result.push_str(&list); result.push_str(&original_offset.to_string_with_newline(self.config)); result.push('}'); @@ -2796,7 +2791,7 @@ struct WhereClauseOption { suppress_comma: bool, // Force no trailing comma snuggle: WhereClauseSpace, allow_single_line: bool, // Try single line where-clause instead of vertical layout - veto_single_line: bool, // Disallow a single-line where-clause. + veto_single_line: bool, // Disallow a single-line where-clause. } impl WhereClauseOption { @@ -2907,11 +2902,7 @@ fn rewrite_params( .trailing_separator(trailing_separator) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - write_list( - ¶m_items, - &fmt, - context.config.fn_parameter_post_comment_alignment(), - ) + write_list(param_items, &fmt) } fn compute_budgets_for_params( @@ -2935,7 +2926,7 @@ fn compute_budgets_for_params( let overhead = if ret_str_len == 0 { 2 } else { 3 }; let mut used_space = indent.width() + result.len() + ret_str_len + overhead; match fn_brace_style { - FnBraceStyle::None => used_space += 1, // 1 = `;` + FnBraceStyle::None => used_space += 1, // 1 = `;` FnBraceStyle::SameLine => used_space += 2, // 2 = `{}` FnBraceStyle::NextLine => (), } @@ -3173,11 +3164,7 @@ fn rewrite_bounds_on_where_clause( .tactic(shape_tactic) .trailing_separator(comma_tactic) .preserve_newline(preserve_newline); - write_list( - &items.collect::>(), - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) + write_list(items.collect::>(), &fmt) } fn rewrite_where_clause( @@ -3258,11 +3245,7 @@ fn rewrite_where_clause( .trailing_separator(comma_tactic) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - let preds_str = write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?; + let preds_str = write_list(item_vec, &fmt)?; let end_length = if terminator == "{" { // If the brace is on the next line we don't need to count it otherwise it needs two diff --git a/src/lists.rs b/src/lists.rs index ca6b720cdac..308e0565247 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -146,15 +146,6 @@ impl ListItem { self.item.as_ref().map_or("", |s| s) } - pub(crate) fn is_different_group(&self) -> bool { - self.inner_as_ref().contains('\n') - || self.pre_comment.is_some() - || self - .post_comment - .as_ref() - .map_or(false, |s| s.contains('\n')) - } - pub(crate) fn is_multiline(&self) -> bool { self.inner_as_ref().contains('\n') || self @@ -261,15 +252,10 @@ where } // Format a list of commented items into a string. -pub(crate) fn write_list( - items: I, +pub(crate) fn write_list<'a, T: AsRef + 'a>( + items: Vec, formatting: &ListFormatting<'_>, - post_comment_alignment_config: PostCommentAlignment, -) -> RewriteResult -where - I: IntoIterator + Clone, - T: AsRef, -{ +) -> RewriteResult { let tactic = formatting.tactic; let sep_len = formatting.separator.len(); @@ -277,9 +263,9 @@ where // will be a trailing separator. let mut trailing_separator = formatting.needs_trailing_separator(); let mut result = String::with_capacity(128); - let cloned_items = items.clone(); + let item_max_width = + max_width_of_item_with_post_comment(items.iter().map(|item| item.as_ref())); let mut iter = items.into_iter().enumerate().peekable(); - let mut item_max_width: Option = None; let sep_place = SeparatorPlace::from_tactic(formatting.separator_place, tactic, formatting.separator); let mut prev_item_had_post_comment = false; @@ -287,6 +273,7 @@ where let mut line_len = 0; let indent_str = &formatting.shape.indent.to_string(formatting.config); + let indent_str_width = unicode_str_width(indent_str); while let Some((i, item)) = iter.next() { let item = item.as_ref(); let inner_item = item.item.as_ref().or_else(|err| Err(err.clone()))?; @@ -307,7 +294,7 @@ where }; let mut item_last_line_width = unicode_str_width(item_last_line) + item_sep_len; if item_last_line.starts_with(&**indent_str) { - item_last_line_width -= unicode_str_width(indent_str); + item_last_line_width -= indent_str_width; } if !item.is_substantial() { @@ -400,7 +387,6 @@ where result.push(' ') } } - item_max_width = None; } if separate && sep_place.is_front() && !first { @@ -429,35 +415,80 @@ where if tactic != DefinitiveListTactic::Horizontal && item.post_comment.is_some() { let comment = item.post_comment.as_ref().unwrap(); - let overhead = last_line_width(&result) + first_line_width(comment.trim()); - - let rewrite_post_comment = |item_max_width: &mut Option| { - if item_max_width.is_none() && !last && !inner_item.contains('\n') { - *item_max_width = Some(max_width_of_item_with_post_comment( - &cloned_items, - i, - overhead, - formatting.config.max_width(), - )); - } + + let rewrite_post_comment = || { let overhead = if starts_with_newline(comment) { 0 - } else if let Some(max_width) = *item_max_width { - max_width + 2 } else { - // 1 = space between item and comment. - item_last_line_width + 1 + match formatting.config.post_comment_alignment() { + PostCommentAlignment::SingleSpace => { + // 1 = space between item and comment. + item_last_line_width + 1 + } + PostCommentAlignment::SameIndent => 3, + } }; let width = formatting.shape.width.checked_sub(overhead).unwrap_or(1); let offset = formatting.shape.indent + overhead; let comment_shape = Shape::legacy(width, offset); let block_style = if !formatting.ends_with_newline && last { + // Does not end with a new line, + // and is the last item. Ex. `a: usize, /* Hello */ }` + // There is an item after the comment which means + // this comment must be block style to preserve the code. + // See test: `struct_lits_visual_multiline.rs` true } else if starts_with_newline(comment) { + // If the comment starts with a newline. + // it is a standalone comment and not a post comment. false + } else if formatting.config.wrap_comments() { + let longest_comment_length = comment + .trim() + .lines() + .map(|line| unicode_str_width(line)) + .max() + .unwrap_or(0); + let line_length = match formatting.config.post_comment_alignment() { + PostCommentAlignment::SingleSpace => { + // line indentation + // + one space between + // + length of current comment line + // + alignment and length of comment + indent_str_width + 1 + longest_comment_length + overhead + } + PostCommentAlignment::SameIndent => { + // length of longest code line + // + one space between + // + length of longest comment line + // + alignment + item_max_width + 1 + longest_comment_length + overhead + } + }; + if line_length > formatting.config.max_width() { + true + } else if comment.trim().contains('\n') { + let style = crate::comment::comment_style(comment.trim_start(), false); + style.is_block_comment() + } else { + let style = crate::comment::comment_style( + comment.trim_start(), + formatting.config.normalize_comments(), + ); + style.is_block_comment() + } } else { - comment.trim().contains('\n') || unicode_str_width(comment.trim()) > width + if comment.trim().contains('\n') { + let style = crate::comment::comment_style(comment.trim_start(), false); + style.is_block_comment() + } else { + let style = crate::comment::comment_style( + comment.trim_start(), + formatting.config.normalize_comments(), + ); + style.is_block_comment() + } }; rewrite_comment( @@ -468,10 +499,13 @@ where ) }; - let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?; + let mut formatted_comment = rewrite_post_comment()?; if !starts_with_newline(comment) { - match post_comment_alignment_config { + match formatting.config.post_comment_alignment() { + PostCommentAlignment::SingleSpace => { + result.push(' '); + } PostCommentAlignment::SameIndent => { if formatting.align_comments { let mut comment_alignment = post_comment_alignment( @@ -484,8 +518,7 @@ where + 1 > formatting.config.max_width() { - item_max_width = None; - formatted_comment = rewrite_post_comment(&mut item_max_width)?; + formatted_comment = rewrite_post_comment()?; comment_alignment = post_comment_alignment( item_max_width, unicode_str_width(inner_item), @@ -498,28 +531,17 @@ where // An additional space for the missing trailing separator (or // if we skipped alignment above). if !formatting.align_comments - || (last - && item_max_width.is_some() - && !separate - && !formatting.separator.is_empty()) + || (last && !separate && !formatting.separator.is_empty()) { result.push(' '); } } - PostCommentAlignment::SingleSpace => { - result.push(' '); - } } } else { result.push('\n'); result.push_str(indent_str); } - if formatted_comment.contains('\n') { - item_max_width = None; - } result.push_str(&formatted_comment); - } else { - item_max_width = None; } if formatting.preserve_newline @@ -527,7 +549,6 @@ where && tactic == DefinitiveListTactic::Vertical && item.new_lines { - item_max_width = None; result.push('\n'); } @@ -538,41 +559,17 @@ where Ok(result) } -fn max_width_of_item_with_post_comment( - items: &I, - i: usize, - overhead: usize, - max_budget: usize, -) -> usize -where - I: IntoIterator + Clone, - T: AsRef, -{ - let mut max_width = 0; - let mut first = true; - for item in items.clone().into_iter().skip(i) { - let item = item.as_ref(); - let inner_item_width = unicode_str_width(item.inner_as_ref()); - if !first - && (item.is_different_group() - || item.post_comment.is_none() - || inner_item_width + overhead > max_budget) - { - return max_width; - } - if max_width < inner_item_width { - max_width = inner_item_width; - } - if item.new_lines { - return max_width; - } - first = false; - } - max_width +fn max_width_of_item_with_post_comment<'a>(items: impl Iterator) -> usize { + items + .filter(|item| item.post_comment.is_some()) + .filter_map(|item| item.inner_as_ref().lines().last()) + .map(|item| unicode_str_width(item)) + .max() + .unwrap_or(0) } -fn post_comment_alignment(item_max_width: Option, inner_item_width: usize) -> usize { - item_max_width.unwrap_or(0).saturating_sub(inner_item_width) +fn post_comment_alignment(item_max_width: usize, inner_item_width: usize) -> usize { + item_max_width.saturating_sub(inner_item_width) } pub(crate) struct ListItems<'a, I, F1, F2, F3> diff --git a/src/macros.rs b/src/macros.rs index 3699bf2f4de..d8ea90a6cb1 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -497,11 +497,7 @@ pub(crate) fn rewrite_macro_def( result += &arm_shape.indent.to_string_with_newline(context.config); } - match write_list( - &branch_items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) { + match write_list(branch_items, &fmt) { Ok(ref s) => result += s, Err(_) => return snippet, } diff --git a/src/matches.rs b/src/matches.rs index 2a469a2dbdf..215b2fe181d 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -242,11 +242,7 @@ fn rewrite_match_arms( .separator("") .preserve_newline(true); - write_list( - &arms_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) + write_list(arms_vec, &fmt) } fn rewrite_match_arm( diff --git a/src/overflow.rs b/src/overflow.rs index 6c327f68c67..00f2202131f 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -663,12 +663,8 @@ impl<'a> Context<'a> { .trailing_separator(trailing_separator) .ends_with_newline(ends_with_newline); - write_list( - &list_items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) - .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str)) + write_list(list_items, &fmt) + .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str)) } fn wrap_items(&self, items_str: &str, shape: Shape, is_extendable: bool) -> String { diff --git a/src/patterns.rs b/src/patterns.rs index 5a8d65d6cbd..f80fca1e0bb 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -112,11 +112,7 @@ impl Rewrite for Pat { .separator(" |") .separator_place(context.config.binop_separator()) .ends_with_newline(false); - write_list( - &items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) + write_list(items, &fmt) } PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape), PatKind::Ident(BindingMode(by_ref, mutability), ident, ref sub_pat) => { @@ -399,11 +395,7 @@ fn rewrite_struct_pat( let nested_shape = shape_for_tactic(tactic, h_shape, v_shape); let fmt = struct_lit_formatting(nested_shape, tactic, context, false); - let mut fields_str = write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?; + let mut fields_str = write_list(item_vec, &fmt)?; let one_line_width = h_shape.map_or(0, |shape| shape.width); let has_trailing_comma = fmt.needs_trailing_separator(); diff --git a/src/reorder.rs b/src/reorder.rs index 8bbff59fc3e..38b2cfc0eba 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -70,17 +70,13 @@ fn compare_items(a: &ast::Item, b: &ast::Item, context: &RewriteContext<'_>) -> fn wrap_reorderable_items( context: &RewriteContext<'_>, - list_items: &[ListItem], + list_items: Vec, shape: Shape, ) -> RewriteResult { let fmt = ListFormatting::new(shape, context.config) .separator("") .align_comments(false); - write_list( - list_items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) + write_list(list_items, &fmt) } fn rewrite_reorderable_item( @@ -164,7 +160,7 @@ fn rewrite_reorderable_or_regroupable_items( } }) .collect(); - wrap_reorderable_items(context, &item_vec, nested_shape) + wrap_reorderable_items(context, item_vec, nested_shape) }) .collect::, RewriteError>>()?; @@ -189,7 +185,7 @@ fn rewrite_reorderable_or_regroupable_items( item_pair_vec.sort_by(|a, b| compare_items(a.1, b.1, context)); let item_vec: Vec<_> = item_pair_vec.into_iter().map(|pair| pair.0).collect(); - wrap_reorderable_items(context, &item_vec, shape) + wrap_reorderable_items(context, item_vec, shape) } } } diff --git a/src/types.rs b/src/types.rs index bee6b9d9475..c20bebff6b4 100644 --- a/src/types.rs +++ b/src/types.rs @@ -405,14 +405,7 @@ where .trailing_separator(trailing_separator) .ends_with_newline(tactic.ends_with_newline(context.config.indent_style())) .preserve_newline(true); - ( - write_list( - &item_vec, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - )?, - tactic, - ) + (write_list(item_vec, &fmt)?, tactic) }; let args = if tactic == DefinitiveListTactic::Horizontal diff --git a/src/vertical.rs b/src/vertical.rs index 8a5aea3dc07..d16cd45a2c9 100644 --- a/src/vertical.rs +++ b/src/vertical.rs @@ -266,12 +266,7 @@ fn rewrite_aligned_items_inner( .tactic(tactic) .trailing_separator(separator_tactic) .preserve_newline(true); - write_list( - &items, - &fmt, - crate::config::PostCommentAlignment::SameIndent, - ) - .ok() + write_list(items, &fmt).ok() } /// Returns the index in `fields` up to which a field belongs to the current group. diff --git a/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs index b0758caaef3..3010a58d900 100644 --- a/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs +++ b/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_parameter_post_comment_alignment: SameIndent +// rustfmt-post_comment_alignment: SameIndent fn foo( a: usize, // Chirp @@ -13,3 +13,25 @@ fn bar( c: f32, /* Meow */ ) { } + +trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { + fn macos_stat_write_buf( + &mut self, + metadata: FileMetadata, + buf_op: &OpTy<'tcx, Tag>, + ) -> InterpResult<'tcx, i32> { + let imms = [ + immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec + immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime + immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec + immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime + immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec + immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime + immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec + immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size + immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks + ]; + + Ok(0) + } +} diff --git a/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs index 639c5432d5d..0c79b901776 100644 --- a/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs +++ b/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_parameter_post_comment_alignment: SingleSpace +// rustfmt-post_comment_alignment: SingleSpace fn foo( a: usize, // Chirp @@ -12,11 +12,9 @@ fn bar( b: usize, // Bark c: f32, /* Meow */ ) { - // `fn_parameter_post_comment_alignment` should not - // affect post comments for match statements. match 0 { - 0 => todo!(), // IIIS - 1 => todo!(), // ASD + 0 => todo!(), // Beep + 1 => todo!(), // Boop _ => {} // Meep } } diff --git a/tests/target/cfg_if/detect/os/linux/aarch64.rs b/tests/target/cfg_if/detect/os/linux/aarch64.rs index 8d874f2280f..60ef2070385 100644 --- a/tests/target/cfg_if/detect/os/linux/aarch64.rs +++ b/tests/target/cfg_if/detect/os/linux/aarch64.rs @@ -27,16 +27,16 @@ fn detect_features() -> cache::Initializer { /// /// [hwcap]: https://github.com/torvalds/linux/blob/master/arch/arm64/include/uapi/asm/hwcap.h struct AtHwcap { - fp: bool, // 0 + fp: bool, // 0 asimd: bool, // 1 // evtstrm: bool, // 2 - aes: bool, // 3 - pmull: bool, // 4 - sha1: bool, // 5 - sha2: bool, // 6 - crc32: bool, // 7 + aes: bool, // 3 + pmull: bool, // 4 + sha1: bool, // 5 + sha2: bool, // 6 + crc32: bool, // 7 atomics: bool, // 8 - fphp: bool, // 9 + fphp: bool, // 9 asimdhp: bool, // 10 // cpuid: bool, // 11 asimdrdm: bool, // 12 diff --git a/tests/target/comments_unicode.rs b/tests/target/comments_unicode.rs index 3e1b6b0a28f..c63d95e5b74 100644 --- a/tests/target/comments_unicode.rs +++ b/tests/target/comments_unicode.rs @@ -1,9 +1,9 @@ impl Default for WhitespaceCharacters { fn default() -> Self { Self { - space: '·', // U+00B7 - nbsp: '⍽', // U+237D - tab: '→', // U+2192 + space: '·', // U+00B7 + nbsp: '⍽', // U+237D + tab: '→', // U+2192 newline: '⏎', // U+23CE } } diff --git a/tests/target/configs/struct_field_align_threshold/20.rs b/tests/target/configs/struct_field_align_threshold/20.rs index 12a523e9d83..ab408d79303 100644 --- a/tests/target/configs/struct_field_align_threshold/20.rs +++ b/tests/target/configs/struct_field_align_threshold/20.rs @@ -76,7 +76,7 @@ struct NewType(Type, OtherType); struct NewInt( pub i32, SomeType, // inline comment - T, // sup + T, // sup ); struct Qux< @@ -219,7 +219,7 @@ struct Foo( where T: PartialEq; struct Foo( - TTTTTTTTTTTTTTTTT, // Foo + TTTTTTTTTTTTTTTTT, // Foo UUUUUUUUUUUUUUUUUUUUUUUU, // Bar // Baz TTTTTTTTTTTTTTTTTTT, diff --git a/tests/target/enum.rs b/tests/target/enum.rs index 83b30999725..c560b0431c7 100644 --- a/tests/target/enum.rs +++ b/tests/target/enum.rs @@ -92,7 +92,7 @@ where I: Iterator, { // Pre Comment - Left { list: I, root: T }, // Post-comment + Left { list: I, root: T }, // Post-comment Right { list: I, root: T }, // Post Comment } diff --git a/tests/target/fn-args-with-last-line-comment.rs b/tests/target/fn-args-with-last-line-comment.rs index 27e0e09653e..4fc5b5777cb 100644 --- a/tests/target/fn-args-with-last-line-comment.rs +++ b/tests/target/fn-args-with-last-line-comment.rs @@ -3,8 +3,8 @@ pub trait X { fn a(&self) -> &'static str; fn bcd( &self, - c: &str, // comment on this arg - d: u16, // comment on this arg + c: &str, // comment on this arg + d: u16, // comment on this arg e: &Vec, // comment on this arg ) -> Box; } diff --git a/tests/target/fn-simple.rs b/tests/target/fn-simple.rs index e725269360d..cdfd3863d73 100644 --- a/tests/target/fn-simple.rs +++ b/tests/target/fn-simple.rs @@ -2,7 +2,7 @@ fn simple( // pre-comment on a function!? - i: i32, // yes, it's possible! + i: i32, // yes, it's possible! response: NoWay, // hose ) { fn op( diff --git a/tests/target/issue-2329.rs b/tests/target/issue-2329.rs index e36e9546b24..1e8340f2e66 100644 --- a/tests/target/issue-2329.rs +++ b/tests/target/issue-2329.rs @@ -24,7 +24,7 @@ fn main() { let x = 1; // X println!( "x = {}", // xの値 - x, // X + x, // X ); // コメント } diff --git a/tests/target/issue-3198.rs b/tests/target/issue-3198.rs index 9291f181d03..343042f6491 100644 --- a/tests/target/issue-3198.rs +++ b/tests/target/issue-3198.rs @@ -21,7 +21,7 @@ impl TestTrait { fn baz_post( self: X<'a, 'b>, /* Important comment1 */ - a: i32, /* Important comment2 */ + a: i32, /* Important comment2 */ ) { } @@ -37,8 +37,8 @@ impl TestTrait { fn baz_tree_post( self: X<'a, 'b>, /* Important comment1 */ - a: i32, /* Important comment2 */ - b: i32, /* Important comment3 */ + a: i32, /* Important comment2 */ + b: i32, /* Important comment3 */ ) { } diff --git a/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs index a1d1cb3419f..98bc30b32ea 100644 --- a/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs +++ b/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_parameter_post_comment_alignment: SameIndent +// rustfmt-post_comment_alignment: SameIndent fn foo( a: usize, // Chirp @@ -13,3 +13,25 @@ fn bar( c: f32, /* Meow */ ) { } + +trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { + fn macos_stat_write_buf( + &mut self, + metadata: FileMetadata, + buf_op: &OpTy<'tcx, Tag>, + ) -> InterpResult<'tcx, i32> { + let imms = [ + immty_from_uint_checked(access_nsec, long_layout)?, // st_atime_nsec + immty_from_uint_checked(modified_sec, time_t_layout)?, // st_mtime + immty_from_uint_checked(modified_nsec, long_layout)?, // st_mtime_nsec + immty_from_uint_checked(0u128, time_t_layout)?, // st_ctime + immty_from_uint_checked(0u128, long_layout)?, // st_ctime_nsec + immty_from_uint_checked(created_sec, time_t_layout)?, // st_birthtime + immty_from_uint_checked(created_nsec, long_layout)?, // st_birthtime_nsec + immty_from_uint_checked(metadata.size, off_t_layout)?, // st_size + immty_from_uint_checked(0u128, blkcnt_t_layout)?, // st_blocks + ]; + + Ok(0) + } +} diff --git a/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs index e6e95bcc07a..6abe3882607 100644 --- a/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs +++ b/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_parameter_post_comment_alignment: SingleSpace +// rustfmt-post_comment_alignment: SingleSpace fn foo( a: usize, // Chirp @@ -12,11 +12,9 @@ fn bar( b: usize, // Bark c: f32, /* Meow */ ) { - // `fn_parameter_post_comment_alignment` should not - // affect post comments for match statements. match 0 { - 0 => todo!(), // IIIS - 1 => todo!(), // ASD - _ => {} // Meep + 0 => todo!(), // Beep + 1 => todo!(), // Boop + _ => {} // Meep } } diff --git a/tests/target/issue-5568.rs b/tests/target/issue-5568.rs index 03ca3a4523c..5b1333fe4b3 100644 --- a/tests/target/issue-5568.rs +++ b/tests/target/issue-5568.rs @@ -5,10 +5,10 @@ mod libs { fn mrbgems_sources() { [ "mrbgems/mruby-compiler/core/codegen.c", // Ruby parser and bytecode generation - "mrbgems/mruby-compiler/core/y.tab.c", // Ruby parser and bytecode generation + "mrbgems/mruby-compiler/core/y.tab.c", // Ruby parser and bytecode generation "mrbgems/mruby-metaprog/src/metaprog.c", // APIs on Kernel and Module for accessing classes and variables - "mrbgems/mruby-method/src/method.c", // `Method`, `UnboundMethod`, and method APIs on Kernel and Module - "mrbgems/mruby-pack/src/pack.c", // Array#pack and String#unpack + "mrbgems/mruby-method/src/method.c", // `Method`, `UnboundMethod`, and method APIs on Kernel and Module + "mrbgems/mruby-pack/src/pack.c", // Array#pack and String#unpack ] } } diff --git a/tests/target/macros.rs b/tests/target/macros.rs index 7b4574349df..beef5807f6a 100644 --- a/tests/target/macros.rs +++ b/tests/target/macros.rs @@ -30,7 +30,7 @@ fn main() { kaas!( // comments a, // post macro - b // another + b // another ); trailingcomma!(a, b, c,); @@ -1050,7 +1050,7 @@ x! {()} f!(match a { 4 => &[ (3, false), // Missing - (4, true) // I-frame + (4, true) // I-frame ][..], }); diff --git a/tests/target/match.rs b/tests/target/match.rs index 0e7815a814d..a3405602981 100644 --- a/tests/target/match.rs +++ b/tests/target/match.rs @@ -176,8 +176,8 @@ fn issue355() { vec![3; 4] } h => println!("a", b), // h comment - i => vec![1, 2], // i comment - j => vec![3; 4], // j comment + i => vec![1, 2], // i comment + j => vec![3; 4], // j comment // k comment k => println!("a", b), // l comment @@ -216,11 +216,11 @@ fn issue355() { y => vec![3; 4], // Brackets with comments tc => println! {"a", b}, // comment - uc => vec![1, 2], // comment - vc => vec![3; 4], // comment - wc => println!["a", b], // comment - xc => vec![1, 2], // comment - yc => vec![3; 4], // comment + uc => vec![1, 2], // comment + vc => vec![3; 4], // comment + wc => println!["a", b], // comment + xc => vec![1, 2], // comment + yc => vec![3; 4], // comment yd => looooooooooooooooooooooooooooooooooooooooooooooooooooooooong_func( aaaaaaaaaa, bbbbbbbbbb, cccccccccc, dddddddddd, ), diff --git a/tests/target/multiple.rs b/tests/target/multiple.rs index d2b9789930b..a11d71fae0b 100644 --- a/tests/target/multiple.rs +++ b/tests/target/multiple.rs @@ -35,7 +35,7 @@ where } fn baz< - 'a: 'b, // comment on 'a + 'a: 'b, // comment on 'a T: SomsssssssssssssssssssssssssssssssssssssssssssssssssssssseType, // comment on T >( a: A, @@ -67,7 +67,7 @@ impl Bar { fn foo( &mut self, a: sdfsdfcccccccccccccccccccccccccccccccccccccccccccccccccc, // comment on a - b: sdfasdfsdfasfs, // closing comment + b: sdfasdfsdfasfs, // closing comment ) -> isize { } diff --git a/tests/target/structs.rs b/tests/target/structs.rs index 4948e37a5a3..f29ed619bc6 100644 --- a/tests/target/structs.rs +++ b/tests/target/structs.rs @@ -63,7 +63,7 @@ struct NewType(Type, OtherType); struct NewInt( pub i32, SomeType, // inline comment - T, // sup + T, // sup ); struct Qux< @@ -206,7 +206,7 @@ struct Foo( where T: PartialEq; struct Foo( - TTTTTTTTTTTTTTTTT, // Foo + TTTTTTTTTTTTTTTTT, // Foo UUUUUUUUUUUUUUUUUUUUUUUU, // Bar // Baz TTTTTTTTTTTTTTTTTTT, @@ -274,18 +274,18 @@ fn foo() { struct Foo { aaaaa: u32, // a - b: u32, // b + b: u32, // b cc: u32, // cc xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: u32, // 1 - yy: u32, // comment2 + yy: u32, // comment2 zzz: u32, // comment3 aaaaaa: u32, // comment4 - bb: u32, // comment5 + bb: u32, // comment5 // separate dd: u32, // comment7 - c: u32, // comment6 + c: u32, // comment6 aaaaaaa: u32, /* multi * line diff --git a/tests/target/unions.rs b/tests/target/unions.rs index 8ed16b269c2..dc157a4195c 100644 --- a/tests/target/unions.rs +++ b/tests/target/unions.rs @@ -163,18 +163,18 @@ fn foo() { union Foo { aaaaa: u32, // a - b: u32, // b + b: u32, // b cc: u32, // cc xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: u32, // 1 - yy: u32, // comment2 + yy: u32, // comment2 zzz: u32, // comment3 aaaaaa: u32, // comment4 - bb: u32, // comment5 + bb: u32, // comment5 // separate dd: u32, // comment7 - c: u32, // comment6 + c: u32, // comment6 aaaaaaa: u32, /* multi * line From 821398545584b90bcf512dcb0241976dd7d3544c Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 00:47:00 -0400 Subject: [PATCH 15/24] chore: revert unnecessary variable assignment --- src/comment.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/comment.rs b/src/comment.rs index 26a62ef0304..0eb141da806 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -742,13 +742,10 @@ impl<'a> CommentRewrite<'a> { &item_fmt, self.max_width.saturating_sub(ib.indent), ) { - Some(s) => { - let r = Self::join_block( - &s, - &format!("{}{}", self.comment_line_separator, ib.line_start), - ); - self.result.push_str(&r) - } + Some(s) => self.result.push_str(&Self::join_block( + &s, + &format!("{}{}", self.comment_line_separator, ib.line_start), + )), None => self.result.push_str(&Self::join_block( &ib.original_block_as_string(), &self.comment_line_separator, From b148c1b8a40c57de33ef5857e23615969019a9a5 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 14:55:43 -0400 Subject: [PATCH 16/24] chore!: more thorough tests --- ... => same_indent_post_comment_alignment.rs} | 20 ++++++++++- ...ace_fn_parameter_post_comment_alignment.rs | 20 ----------- .../single_space_post_comment_alignment.rs | 33 +++++++++++++++++++ ... => same_indent_post_comment_alignment.rs} | 20 ++++++++++- ...ace_fn_parameter_post_comment_alignment.rs | 20 ----------- .../single_space_post_comment_alignment.rs | 33 +++++++++++++++++++ 6 files changed, 104 insertions(+), 42 deletions(-) rename tests/source/issue-4108/{same_indent_fn_parameter_post_comment_alignment.rs => same_indent_post_comment_alignment.rs} (74%) delete mode 100644 tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs create mode 100644 tests/source/issue-4108/single_space_post_comment_alignment.rs rename tests/target/issue-4108/{same_indent_fn_parameter_post_comment_alignment.rs => same_indent_post_comment_alignment.rs} (74%) delete mode 100644 tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs create mode 100644 tests/target/issue-4108/single_space_post_comment_alignment.rs diff --git a/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/same_indent_post_comment_alignment.rs similarity index 74% rename from tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs rename to tests/source/issue-4108/same_indent_post_comment_alignment.rs index 3010a58d900..0dcf44cefee 100644 --- a/tests/source/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs +++ b/tests/source/issue-4108/same_indent_post_comment_alignment.rs @@ -1,5 +1,11 @@ // rustfmt-post_comment_alignment: SameIndent +use std::collections::{ + HashSet, // I am a hash set! + HashMap, + BTreeMap, // I am a TREE!!!!!! +}; + fn foo( a: usize, // Chirp b: usize, // Bark @@ -7,11 +13,23 @@ fn foo( ) { } +enum Animal { + Cat,// THIS IS A BUTTERFLY! + Dog, // THIS IS ME. + Bird, /* OKOKOKOKOKOKOK */ +} + fn bar( a: usize,/* Chirp */ b: usize, // Bark c: f32, /* Meow */ -) { + animal: Animal, +) -> &str { + match animal { + Animal::Cat => "meow",// Is this a bird? + Animal::Dog => "bark", // Is this a cat? + Animal::Bird => "chirp",// Is this a dog? + } } trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { diff --git a/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs deleted file mode 100644 index 0c79b901776..00000000000 --- a/tests/source/issue-4108/single_space_fn_parameter_post_comment_alignment.rs +++ /dev/null @@ -1,20 +0,0 @@ -// rustfmt-post_comment_alignment: SingleSpace - -fn foo( - a: usize, // Chirp - b: usize, // Bark - c: f32, // Meow -) { -} - -fn bar( - a: usize,/* Chirp */ - b: usize, // Bark - c: f32, /* Meow */ -) { - match 0 { - 0 => todo!(), // Beep - 1 => todo!(), // Boop - _ => {} // Meep - } -} diff --git a/tests/source/issue-4108/single_space_post_comment_alignment.rs b/tests/source/issue-4108/single_space_post_comment_alignment.rs new file mode 100644 index 00000000000..29a813abb5b --- /dev/null +++ b/tests/source/issue-4108/single_space_post_comment_alignment.rs @@ -0,0 +1,33 @@ +// rustfmt-post_comment_alignment: SingleSpace + +use std::collections::{ + BTreeMap, // I am a TREE!!!!!! + HashMap, + HashSet, // I am a hash set! +}; + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +enum Animal { + Cat, // THIS IS A BUTTERFLY! + Dog, // THIS IS ME. + Bird, /* OKOKOKOKOKOKOK */ +} + +fn bar( + a: usize, /* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ + animal: Animal, +) -> &str { + match animal { + Animal::Cat => "meow", // Is this a bird? + Animal::Dog => "bark", // Is this a cat? + Animal::Bird => "chirp", // Is this a dog? + } +} diff --git a/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/same_indent_post_comment_alignment.rs similarity index 74% rename from tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs rename to tests/target/issue-4108/same_indent_post_comment_alignment.rs index 98bc30b32ea..86140fa681d 100644 --- a/tests/target/issue-4108/same_indent_fn_parameter_post_comment_alignment.rs +++ b/tests/target/issue-4108/same_indent_post_comment_alignment.rs @@ -1,5 +1,11 @@ // rustfmt-post_comment_alignment: SameIndent +use std::collections::{ + BTreeMap, // I am a TREE!!!!!! + HashMap, + HashSet, // I am a hash set! +}; + fn foo( a: usize, // Chirp b: usize, // Bark @@ -7,11 +13,23 @@ fn foo( ) { } +enum Animal { + Cat, // THIS IS A BUTTERFLY! + Dog, // THIS IS ME. + Bird, /* OKOKOKOKOKOKOK */ +} + fn bar( a: usize, /* Chirp */ b: usize, // Bark c: f32, /* Meow */ -) { + animal: Animal, +) -> &str { + match animal { + Animal::Cat => "meow", // Is this a bird? + Animal::Dog => "bark", // Is this a cat? + Animal::Bird => "chirp", // Is this a dog? + } } trait EvalContextExtPrivate<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { diff --git a/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs b/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs deleted file mode 100644 index 6abe3882607..00000000000 --- a/tests/target/issue-4108/single_space_fn_parameter_post_comment_alignment.rs +++ /dev/null @@ -1,20 +0,0 @@ -// rustfmt-post_comment_alignment: SingleSpace - -fn foo( - a: usize, // Chirp - b: usize, // Bark - c: f32, // Meow -) { -} - -fn bar( - a: usize, /* Chirp */ - b: usize, // Bark - c: f32, /* Meow */ -) { - match 0 { - 0 => todo!(), // Beep - 1 => todo!(), // Boop - _ => {} // Meep - } -} diff --git a/tests/target/issue-4108/single_space_post_comment_alignment.rs b/tests/target/issue-4108/single_space_post_comment_alignment.rs new file mode 100644 index 00000000000..9ef2b002859 --- /dev/null +++ b/tests/target/issue-4108/single_space_post_comment_alignment.rs @@ -0,0 +1,33 @@ +// rustfmt-post_comment_alignment: SingleSpace + +use std::collections::{ + BTreeMap, // I am a TREE!!!!!! + HashMap, + HashSet, // I am a hash set! +}; + +fn foo( + a: usize, // Chirp + b: usize, // Bark + c: f32, // Meow +) { +} + +enum Animal { + Cat, // THIS IS A BUTTERFLY! + Dog, // THIS IS ME. + Bird, /* OKOKOKOKOKOKOK */ +} + +fn bar( + a: usize, /* Chirp */ + b: usize, // Bark + c: f32, /* Meow */ + animal: Animal, +) -> &str { + match animal { + Animal::Cat => "meow", // Is this a bird? + Animal::Dog => "bark", // Is this a cat? + Animal::Bird => "chirp", // Is this a dog? + } +} From 772af556400b508d6dda570af0dd4c0414b541af Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 16:51:28 -0400 Subject: [PATCH 17/24] chore!: remove unncessary pub --- src/comment.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/comment.rs b/src/comment.rs index 0eb141da806..05d7310122a 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -1091,10 +1091,7 @@ fn light_rewrite_comment( /// Trims comment characters and possibly a single space from the left of a string. /// Does not trim all whitespace. If a single space is trimmed from the left of the string, /// this function returns true. -pub(crate) fn left_trim_comment_line<'a>( - line: &'a str, - style: &CommentStyle<'_>, -) -> (&'a str, bool) { +fn left_trim_comment_line<'a>(line: &'a str, style: &CommentStyle<'_>) -> (&'a str, bool) { if line.starts_with("//! ") || line.starts_with("/// ") || line.starts_with("/*! ") From 9c7a433c0577b74e7c4e3fe78095031383ba43c6 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 16:54:00 -0400 Subject: [PATCH 18/24] chore!: remove unncessary lifetime --- src/lists.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lists.rs b/src/lists.rs index 308e0565247..e3deeb31d23 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -252,7 +252,7 @@ where } // Format a list of commented items into a string. -pub(crate) fn write_list<'a, T: AsRef + 'a>( +pub(crate) fn write_list>( items: Vec, formatting: &ListFormatting<'_>, ) -> RewriteResult { From 1967a9852afdf865d08ac7fb12aecc1f63223f88 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 16:56:58 -0400 Subject: [PATCH 19/24] chore: replace comment period with comma --- src/lists.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lists.rs b/src/lists.rs index e3deeb31d23..44eaa71bed4 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -440,7 +440,7 @@ pub(crate) fn write_list>( // See test: `struct_lits_visual_multiline.rs` true } else if starts_with_newline(comment) { - // If the comment starts with a newline. + // If the comment starts with a newline, // it is a standalone comment and not a post comment. false } else if formatting.config.wrap_comments() { From a691b21816be7cf45a66f4be8f6a806e9266f7a8 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 20:12:33 -0400 Subject: [PATCH 20/24] feat!: removed align_comments field from ListFormatting --- src/lists.rs | 38 +++----------------------------------- src/reorder.rs | 4 +--- 2 files changed, 4 insertions(+), 38 deletions(-) diff --git a/src/lists.rs b/src/lists.rs index 44eaa71bed4..9685d2be36c 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -29,8 +29,6 @@ pub(crate) struct ListFormatting<'a> { preserve_newline: bool, // Nested import lists get some special handling for the "Mixed" list type nested: bool, - // Whether comments should be visually aligned. - align_comments: bool, config: &'a Config, } @@ -45,7 +43,6 @@ impl<'a> ListFormatting<'a> { ends_with_newline: true, preserve_newline: false, nested: false, - align_comments: true, config, } } @@ -85,11 +82,6 @@ impl<'a> ListFormatting<'a> { self } - pub(crate) fn align_comments(mut self, align_comments: bool) -> Self { - self.align_comments = align_comments; - self - } - pub(crate) fn needs_trailing_separator(&self) -> bool { match self.trailing_separator { // We always put separator in front. @@ -507,32 +499,9 @@ pub(crate) fn write_list>( result.push(' '); } PostCommentAlignment::SameIndent => { - if formatting.align_comments { - let mut comment_alignment = post_comment_alignment( - item_max_width, - unicode_str_width(inner_item), - ); - if first_line_width(&formatted_comment) - + last_line_width(&result) - + comment_alignment - + 1 - > formatting.config.max_width() - { - formatted_comment = rewrite_post_comment()?; - comment_alignment = post_comment_alignment( - item_max_width, - unicode_str_width(inner_item), - ); - } - for _ in 0..=comment_alignment { - result.push(' '); - } - } - // An additional space for the missing trailing separator (or - // if we skipped alignment above). - if !formatting.align_comments - || (last && !separate && !formatting.separator.is_empty()) - { + let comment_alignment = + post_comment_alignment(item_max_width, unicode_str_width(inner_item)); + for _ in 0..=comment_alignment { result.push(' '); } } @@ -956,7 +925,6 @@ pub(crate) fn struct_lit_formatting<'a>( ends_with_newline, preserve_newline: true, nested: false, - align_comments: true, config: context.config, } } diff --git a/src/reorder.rs b/src/reorder.rs index 38b2cfc0eba..24b2aaa5793 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -73,9 +73,7 @@ fn wrap_reorderable_items( list_items: Vec, shape: Shape, ) -> RewriteResult { - let fmt = ListFormatting::new(shape, context.config) - .separator("") - .align_comments(false); + let fmt = ListFormatting::new(shape, context.config).separator(""); write_list(list_items, &fmt) } From a6224d7420ae414f8a651da81a0f1f085e7d5e81 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 20:37:39 -0400 Subject: [PATCH 21/24] chore: remove unnecessary imports --- src/lists.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/lists.rs b/src/lists.rs index 9685d2be36c..134fef592a7 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -10,10 +10,7 @@ use crate::config::{Config, IndentStyle}; use crate::config::{PostCommentAlignment, lists::*}; use crate::rewrite::{ExceedsMaxWidthError, RewriteContext, RewriteError, RewriteResult}; use crate::shape::{Indent, Shape}; -use crate::utils::{ - count_newlines, first_line_width, last_line_width, mk_sp, starts_with_newline, - unicode_str_width, -}; +use crate::utils::{count_newlines, mk_sp, starts_with_newline, unicode_str_width}; use crate::visitor::SnippetProvider; pub(crate) struct ListFormatting<'a> { @@ -491,7 +488,7 @@ pub(crate) fn write_list>( ) }; - let mut formatted_comment = rewrite_post_comment()?; + let formatted_comment = rewrite_post_comment()?; if !starts_with_newline(comment) { match formatting.config.post_comment_alignment() { From bd36b12cb157ca243d89a3023c289c6be510e925 Mon Sep 17 00:00:00 2001 From: Albar Date: Sun, 31 May 2026 20:57:06 -0400 Subject: [PATCH 22/24] chore: move functionality into is_block_comment_multiline_or_normalized function --- src/lists.rs | 41 +++++++++++++++++++---------------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/src/lists.rs b/src/lists.rs index 134fef592a7..5dbd37d05a0 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -421,6 +421,22 @@ pub(crate) fn write_list>( let offset = formatting.shape.indent + overhead; let comment_shape = Shape::legacy(width, offset); + fn is_block_comment_multiline_or_normalized( + comment: &str, + config: &Config, + ) -> bool { + if comment.trim().contains('\n') { + let style = crate::comment::comment_style(comment.trim_start(), false); + style.is_block_comment() + } else { + let style = crate::comment::comment_style( + comment.trim_start(), + config.normalize_comments(), + ); + style.is_block_comment() + } + } + let block_style = if !formatting.ends_with_newline && last { // Does not end with a new line, // and is the last item. Ex. `a: usize, /* Hello */ }` @@ -455,29 +471,10 @@ pub(crate) fn write_list>( item_max_width + 1 + longest_comment_length + overhead } }; - if line_length > formatting.config.max_width() { - true - } else if comment.trim().contains('\n') { - let style = crate::comment::comment_style(comment.trim_start(), false); - style.is_block_comment() - } else { - let style = crate::comment::comment_style( - comment.trim_start(), - formatting.config.normalize_comments(), - ); - style.is_block_comment() - } + line_length > formatting.config.max_width() + || is_block_comment_multiline_or_normalized(comment, formatting.config) } else { - if comment.trim().contains('\n') { - let style = crate::comment::comment_style(comment.trim_start(), false); - style.is_block_comment() - } else { - let style = crate::comment::comment_style( - comment.trim_start(), - formatting.config.normalize_comments(), - ); - style.is_block_comment() - } + is_block_comment_multiline_or_normalized(comment, formatting.config) }; rewrite_comment( From 89f8f019ce913a3125dd60d3d2f61d8bd8530dba Mon Sep 17 00:00:00 2001 From: Albar Date: Mon, 1 Jun 2026 15:40:57 -0400 Subject: [PATCH 23/24] chore: change operation and comment for readability --- src/lists.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lists.rs b/src/lists.rs index 5dbd37d05a0..7461eecd5da 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -458,10 +458,10 @@ pub(crate) fn write_list>( let line_length = match formatting.config.post_comment_alignment() { PostCommentAlignment::SingleSpace => { // line indentation + // + alignment and length of current code line // + one space between // + length of current comment line - // + alignment and length of comment - indent_str_width + 1 + longest_comment_length + overhead + indent_str_width + overhead + 1 + longest_comment_length } PostCommentAlignment::SameIndent => { // length of longest code line From c45165ce2b1af897804d5fde40e73cab78d4b899 Mon Sep 17 00:00:00 2001 From: Albar Date: Mon, 1 Jun 2026 15:56:52 -0400 Subject: [PATCH 24/24] chore: update Configurations.md default post_comment_alignment value --- Configurations.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Configurations.md b/Configurations.md index 53dab946037..84bcd7e7678 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1263,8 +1263,8 @@ See also: [`tab_spaces`](#tab_spaces). Alignment of post comments -- **Default value**: `SameIndent` -- **Possible values**: `SameIndent`, `SingleSpace` +- **Default value**: `SingleSpace` +- **Possible values**: `SingleSpace`, `SameIndent` - **Stable**: No #### `SingleSpace`: