diff --git a/Configurations.md b/Configurations.md index 976c2904894..84bcd7e7678 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1259,6 +1259,40 @@ fn lorem() -> usize { See also: [`tab_spaces`](#tab_spaces). +## `post_comment_alignment` + +Alignment of post comments + +- **Default value**: `SingleSpace` +- **Possible values**: `SingleSpace`, `SameIndent` +- **Stable**: No + +#### `SingleSpace`: + +One space between the code and comment. + +```rust +fn foo( + a: usize, // Cat + b: usize, // Dog + c: f32, // Bird +) { +} +``` + +#### `SameIndent` (default): + +Each comment has the same indentation. + +```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..c0655abb57e 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -147,7 +147,7 @@ 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).ok()?; debug!("item_str: '{}'", item_str); diff --git a/src/closures.rs b/src/closures.rs index 19cd0d9792c..2421299d4fe 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -338,7 +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)?; + 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/config/mod.rs b/src/config/mod.rs index a3f9842cd4f..d20e1f7379c 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."; + 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"; @@ -783,6 +785,7 @@ format_strings = false format_macro_matchers = false format_macro_bodies = true skip_macro_invocations = [] +post_comment_alignment = "SingleSpace" 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 = [] +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 3f970ed4bd7..95d4cb65efe 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 { + /// 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. #[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(); + PostCommentAlignmentConfig, PostCommentAlignment, _ => + PostCommentAlignment::SingleSpace; HexLiteralCaseConfig, HexLiteralCase, _ => HexLiteralCase::Preserve; FloatLiteralTrailingZeroConfig, FloatLiteralTrailingZero, _ => FloatLiteralTrailingZero::Preserve; diff --git a/src/expr.rs b/src/expr.rs index 22634abb977..2ab0c403a1f 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1818,7 +1818,7 @@ 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)? }; let fields_str = @@ -1965,7 +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)?; + let list_str = write_list(item_vec, &fmt)?; Ok(format!("({list_str})")) } diff --git a/src/imports.rs b/src/imports.rs index c5a2a5de2f1..66e6e640f30 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -1066,7 +1066,7 @@ 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)?; let result = if (list_str.contains('\n') || list_str.len() > remaining_width diff --git a/src/items.rs b/src/items.rs index 484c5b50adf..65f3b9717e5 100644 --- a/src/items.rs +++ b/src/items.rs @@ -652,7 +652,7 @@ 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).ok()?; result.push_str(&list); result.push_str(&original_offset.to_string_with_newline(self.config)); result.push('}'); @@ -2791,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 { @@ -2902,7 +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) + write_list(param_items, &fmt) } fn compute_budgets_for_params( @@ -2926,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 => (), } @@ -3164,7 +3164,7 @@ 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) } fn rewrite_where_clause( @@ -3245,7 +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)?; + 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 9d811e5d9b5..7461eecd5da 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -6,14 +6,11 @@ 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::{ - 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> { @@ -29,8 +26,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 +40,6 @@ impl<'a> ListFormatting<'a> { ends_with_newline: true, preserve_newline: false, nested: false, - align_comments: true, config, } } @@ -85,11 +79,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. @@ -146,15 +135,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,11 +241,10 @@ where } // Format a list of commented items into a string. -pub(crate) fn write_list(items: I, formatting: &ListFormatting<'_>) -> RewriteResult -where - I: IntoIterator + Clone, - T: AsRef, -{ +pub(crate) fn write_list>( + items: Vec, + formatting: &ListFormatting<'_>, +) -> RewriteResult { let tactic = formatting.tactic; let sep_len = formatting.separator.len(); @@ -273,9 +252,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; @@ -283,6 +262,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()))?; @@ -303,7 +283,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() { @@ -396,7 +376,6 @@ where result.push(' ') } } - item_max_width = None; } if separate && sep_place.is_front() && !first { @@ -425,35 +404,77 @@ 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); + 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 */ }` + // 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 + // + alignment and length of current code line + // + one space between + // + length of current comment line + indent_str_width + overhead + 1 + longest_comment_length + } + PostCommentAlignment::SameIndent => { + // length of longest code line + // + one space between + // + length of longest comment line + // + alignment + item_max_width + 1 + longest_comment_length + overhead + } + }; + line_length > formatting.config.max_width() + || is_block_comment_multiline_or_normalized(comment, formatting.config) } else { - comment.trim().contains('\n') || unicode_str_width(comment.trim()) > width + is_block_comment_multiline_or_normalized(comment, formatting.config) }; rewrite_comment( @@ -464,47 +485,26 @@ where ) }; - let mut formatted_comment = rewrite_post_comment(&mut item_max_width)?; + let formatted_comment = rewrite_post_comment()?; 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)); - } - for _ in 0..=comment_alignment { + match formatting.config.post_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(' '); + PostCommentAlignment::SameIndent => { + let comment_alignment = + post_comment_alignment(item_max_width, unicode_str_width(inner_item)); + for _ in 0..=comment_alignment { + 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 @@ -512,7 +512,6 @@ where && tactic == DefinitiveListTactic::Vertical && item.new_lines { - item_max_width = None; result.push('\n'); } @@ -523,41 +522,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> @@ -944,7 +919,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/macros.rs b/src/macros.rs index 2d56021069c..d8ea90a6cb1 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -497,7 +497,7 @@ 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) { Ok(ref s) => result += s, Err(_) => return snippet, } diff --git a/src/matches.rs b/src/matches.rs index 50c0db8ac06..215b2fe181d 100644 --- a/src/matches.rs +++ b/src/matches.rs @@ -242,7 +242,7 @@ fn rewrite_match_arms( .separator("") .preserve_newline(true); - write_list(&arms_vec, &fmt) + write_list(arms_vec, &fmt) } fn rewrite_match_arm( diff --git a/src/overflow.rs b/src/overflow.rs index 4230c89b57b..00f2202131f 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -663,7 +663,7 @@ impl<'a> Context<'a> { .trailing_separator(trailing_separator) .ends_with_newline(ends_with_newline); - write_list(&list_items, &fmt) + write_list(list_items, &fmt) .map(|items_str| (tactic == DefinitiveListTactic::Horizontal, items_str)) } diff --git a/src/patterns.rs b/src/patterns.rs index 2fad1d41ae9..f80fca1e0bb 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -112,7 +112,7 @@ impl Rewrite for Pat { .separator(" |") .separator_place(context.config.binop_separator()) .ends_with_newline(false); - write_list(&items, &fmt) + 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) => { @@ -395,7 +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)?; + 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 6ef6e0bc969..24b2aaa5793 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -70,12 +70,10 @@ 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); + let fmt = ListFormatting::new(shape, context.config).separator(""); write_list(list_items, &fmt) } @@ -160,7 +158,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>>()?; @@ -185,7 +183,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 92a649bf634..c20bebff6b4 100644 --- a/src/types.rs +++ b/src/types.rs @@ -405,7 +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)?, tactic) + (write_list(item_vec, &fmt)?, tactic) }; let args = if tactic == DefinitiveListTactic::Horizontal diff --git a/src/vertical.rs b/src/vertical.rs index fd9a4a7db6a..d16cd45a2c9 100644 --- a/src/vertical.rs +++ b/src/vertical.rs @@ -266,7 +266,7 @@ fn rewrite_aligned_items_inner( .tactic(tactic) .trailing_separator(separator_tactic) .preserve_newline(true); - write_list(&items, &fmt).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_post_comment_alignment.rs b/tests/source/issue-4108/same_indent_post_comment_alignment.rs new file mode 100644 index 00000000000..0dcf44cefee --- /dev/null +++ b/tests/source/issue-4108/same_indent_post_comment_alignment.rs @@ -0,0 +1,55 @@ +// 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 + 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? + } +} + +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_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/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_post_comment_alignment.rs b/tests/target/issue-4108/same_indent_post_comment_alignment.rs new file mode 100644 index 00000000000..86140fa681d --- /dev/null +++ b/tests/target/issue-4108/same_indent_post_comment_alignment.rs @@ -0,0 +1,55 @@ +// 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 + 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? + } +} + +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_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? + } +} 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