From c861b6bb6eb7351381cce8f385d319ede6cfcb5e Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Mon, 2 Nov 2026 20:51:13 +0800 Subject: [PATCH 01/41] ci(test): remove dead mingw PATH workflow steps The `matrix.channel` var is never set since or commit `26fb3fa737816532c17559552fb5ad0cbeeb610a` since 2021. --- src/tools/rustfmt/.github/workflows/test.yml | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/tools/rustfmt/.github/workflows/test.yml b/src/tools/rustfmt/.github/workflows/test.yml index 44d36898f216f..dc295d8bfbda4 100644 --- a/src/tools/rustfmt/.github/workflows/test.yml +++ b/src/tools/rustfmt/.github/workflows/test.yml @@ -59,17 +59,6 @@ jobs: MATRIX_TARGET: ${{ matrix.target }} shell: powershell - - name: Add mingw32 to path for i686-gnu - run: | - echo "C:\msys64\mingw32\bin" >> $GITHUB_PATH - if: matrix.target == 'i686-pc-windows-gnu' && matrix.channel == 'nightly' - shell: bash - - - name: Add mingw64 to path for x86_64-gnu - run: echo "C:\msys64\mingw64\bin" >> $GITHUB_PATH - if: matrix.target == 'x86_64-pc-windows-gnu' && matrix.channel == 'nightly' - shell: bash - - name: install rustup if: ${{ matrix.os != 'windows-latest' }} run: | From 0baba0a571aff566c7b734bdd298b9fcddf7f572 Mon Sep 17 00:00:00 2001 From: Matthew Hughes Date: Wed, 28 Oct 2026 21:16:39 +0000 Subject: [PATCH 02/41] Allow reading args from `@path` That is, something like $ printf "--config path/to/config.toml\n--check\n" > @args-file $ rustfmt @args-file path/to/format.rs # same as: rustfmt --config path/to/config.toml --check path/to/format.rs The motivation for this is that `cargo fmt` collects the list of files to be formatted and passes them to `rustfmt` as arguments. But this list can get so long that it reaches OS limits, see rust-lang/rustfmt#6934. The process for making this change was: 1. Go and look for inspiration from other tools 2. Find out the `rustdoc` supports this pattern[1] so just re-use its approach[2] Conveniently, that approach uses helpers from internal compiler crates that are also available to us. Note, those helpers expect UTF-8 everywhere, which is what the current code also does, but this will be an additional place to consider in the future if we want to move away from that (see rustfmt/issues#7210). Link: https://doc.rust-lang.org/rustdoc/command-line-arguments.html#path-load-command-line-flags-from-a-path [1] Link: https://github.com/rust-lang/rust/blob/ab019e71a1a1f4688bcc4d5bf06d2c5a424a31a5/src/librustdoc/lib.rs#L827 [2] --- src/tools/rustfmt/README.md | 9 ++ src/tools/rustfmt/src/bin/main.rs | 18 +++- src/tools/rustfmt/tests/rustfmt/main.rs | 92 ++++++++++++++++++- .../rustfmt/sources/args_file/.gitattributes | 2 + .../args_file/args_full_carriage_return | 4 + .../sources/args_file/args_full_tab_indent | 4 + .../sources/args_file/args_hex_uppercase | 2 + .../rustfmt/sources/args_file/args_tab_indent | 2 + .../sources/args_file/hex_lowercase.rs | 3 + .../rustfmt/sources/args_file/rustfmt.toml | 1 + .../sources/args_file/space_indents.rs | 3 + 11 files changed, 137 insertions(+), 3 deletions(-) create mode 100644 src/tools/rustfmt/tests/rustfmt/sources/args_file/.gitattributes create mode 100644 src/tools/rustfmt/tests/rustfmt/sources/args_file/args_full_carriage_return create mode 100644 src/tools/rustfmt/tests/rustfmt/sources/args_file/args_full_tab_indent create mode 100644 src/tools/rustfmt/tests/rustfmt/sources/args_file/args_hex_uppercase create mode 100644 src/tools/rustfmt/tests/rustfmt/sources/args_file/args_tab_indent create mode 100644 src/tools/rustfmt/tests/rustfmt/sources/args_file/hex_lowercase.rs create mode 100644 src/tools/rustfmt/tests/rustfmt/sources/args_file/rustfmt.toml create mode 100644 src/tools/rustfmt/tests/rustfmt/sources/args_file/space_indents.rs diff --git a/src/tools/rustfmt/README.md b/src/tools/rustfmt/README.md index 97796407d5410..2e0b3c42e289b 100644 --- a/src/tools/rustfmt/README.md +++ b/src/tools/rustfmt/README.md @@ -88,6 +88,15 @@ Please see `cargo fmt --help` for usage information. You can specify the path to your own `rustfmt` binary for cargo to use by setting the`RUSTFMT` environment variable. This was added in v1.4.22, so you must have this version or newer to leverage this feature (`cargo fmt --version`) +`rustfmt` supports args-files, using `@`: + +``` +$ printf -- "--check\npath/to/file.rs\n" > args_file +$ rustfmt @args_file +# the above is equivalent to +$ rustfmt --check path/to/file.rs +``` + ### Running `rustfmt` directly To format individual files or arbitrary codes from stdin, the `rustfmt` binary should be used. Some diff --git a/src/tools/rustfmt/src/bin/main.rs b/src/tools/rustfmt/src/bin/main.rs index 0653ad3d93758..b662959adaad9 100644 --- a/src/tools/rustfmt/src/bin/main.rs +++ b/src/tools/rustfmt/src/bin/main.rs @@ -25,6 +25,10 @@ const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rustfmt/issues/new?la // N.B. these crates are loaded from the sysroot, so they need extern crate. extern crate rustc_driver; +extern crate rustc_session; + +use rustc_session::EarlyDiagCtxt; +use rustc_session::config::ErrorOutputType; fn main() { rustc_driver::install_ice_hook(BUG_REPORT_URL, |_| ()); @@ -241,7 +245,13 @@ fn is_nightly() -> bool { // Returned i32 is an exit code fn execute(opts: &Options) -> Result { - let matches = opts.parse(env::args().skip(1))?; + let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default()); + let cmdline_args = env::args().skip(1).collect::>(); + // if we saw a `@path` arg, read arguments from that file and merge them with the other + // arguments. + let args = rustc_driver::args::arg_expand_all(&early_dcx, &cmdline_args); + + let matches = opts.parse(&args)?; let options = GetOptsOptions::from_matches(&matches)?; match determine_operation(&matches)? { @@ -448,7 +458,11 @@ fn print_usage_to_stdout(opts: &Options, reason: &str) { format!("{reason}\n\n") }; let msg = format!("{sep}Format Rust code\n\nusage: rustfmt [options] ..."); - println!("{}", opts.usage(&msg)); + print!("{}", opts.usage(&msg)); + println!( + " @path Read newline separated options from the file at `path`. \ + Can be specified more than once." + ); } fn print_help_file_lines() { diff --git a/src/tools/rustfmt/tests/rustfmt/main.rs b/src/tools/rustfmt/tests/rustfmt/main.rs index 04ef79db920e3..03a23a2653af8 100644 --- a/src/tools/rustfmt/tests/rustfmt/main.rs +++ b/src/tools/rustfmt/tests/rustfmt/main.rs @@ -6,7 +6,7 @@ use std::io::Write; use std::path::Path; use std::process::{Command, Stdio}; -use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test, rustfmt_only_ci_test}; +use rustfmt_config_proc_macro::{nightly_only_test, rustfmt_only_ci_test, stable_only_test}; /// Run the rustfmt executable with environment vars set and return its output. /// If `input` is given, it is piped to the executable's stdin. @@ -223,6 +223,7 @@ fn rustfmt_usage_text() { -V, --version Show version information -h, --help [=TOPIC] Show this message or help about a specific topic: `config` + @path Read newline separated options from the file at `path`. Can be specified more than once. "); assert_eq!(exit_code, 0); } @@ -284,6 +285,7 @@ fn rustfmt_nightly_usage_text() { -V, --version Show version information -h, --help [=TOPIC] Show this message or help about a specific topic: `config` or `file-lines` + @path Read newline separated options from the file at `path`. Can be specified more than once. "); assert_eq!(exit_code, 0); } @@ -582,3 +584,91 @@ fn cfg_select_parser_recovery_ice_7087() { assert_eq!(source, stdout); assert_eq!(exit_code, 0); } + +#[test] +fn test_args_file_all_args() { + let src_file = Path::new("tests/rustfmt/sources/args_file/space_indents.rs"); + let args_file = Path::new("tests/rustfmt/sources/args_file/args_full_tab_indent"); + let args = &[ + &format!("@{}", args_file.to_str().unwrap()), + src_file.to_str().unwrap(), + ]; + + let (stdout, stderr, exit_code) = rustfmt(args); + + assert_eq!(stderr, ""); + assert_eq!( + stdout, + format!("{}\n", src_file.canonicalize().unwrap().display()), + ); + assert_eq!(exit_code, 1); +} + +#[test] +fn test_args_file_merge_with_cmd_args() { + let src_file = Path::new("tests/rustfmt/sources/args_file/space_indents.rs"); + let args_file = Path::new("tests/rustfmt/sources/args_file/args_tab_indent"); + let args = &[ + "--check", + "--files-with-diff", + &format!("@{}", args_file.to_str().unwrap()), + src_file.to_str().unwrap(), + ]; + + let (stdout, stderr, exit_code) = rustfmt(args); + + assert_eq!(stderr, ""); + assert_eq!( + stdout, + format!("{}\n", src_file.canonicalize().unwrap().display()), + ); + assert_eq!(exit_code, 1); +} + +#[test] +fn test_args_file_multiple_files_merged() { + let first_src_file = Path::new("tests/rustfmt/sources/args_file/space_indents.rs"); + let second_src_file = Path::new("tests/rustfmt/sources/args_file/hex_lowercase.rs"); + let first_args_file = Path::new("tests/rustfmt/sources/args_file/args_tab_indent"); + let second_args_file = Path::new("tests/rustfmt/sources/args_file/args_hex_uppercase"); + let args = &[ + "--check", + "--files-with-diff", + &format!("@{}", first_args_file.to_str().unwrap()), + &format!("@{}", second_args_file.to_str().unwrap()), + first_src_file.to_str().unwrap(), + second_src_file.to_str().unwrap(), + ]; + + let (stdout, stderr, exit_code) = rustfmt(args); + + assert_eq!(stderr, ""); + assert_eq!( + stdout, + format!( + "{}\n{}\n", + first_src_file.canonicalize().unwrap().display(), + second_src_file.canonicalize().unwrap().display() + ), + ); + assert_eq!(exit_code, 1); +} + +#[test] +fn test_args_file_carriage_return() { + let src_file = Path::new("tests/rustfmt/sources/args_file/space_indents.rs"); + let args_file = Path::new("tests/rustfmt/sources/args_file/args_full_carriage_return"); + let args = &[ + &format!("@{}", args_file.to_str().unwrap()), + src_file.to_str().unwrap(), + ]; + + let (stdout, stderr, exit_code) = rustfmt(args); + + assert_eq!(stderr, ""); + assert_eq!( + stdout, + format!("{}\n", src_file.canonicalize().unwrap().display()), + ); + assert_eq!(exit_code, 1); +} diff --git a/src/tools/rustfmt/tests/rustfmt/sources/args_file/.gitattributes b/src/tools/rustfmt/tests/rustfmt/sources/args_file/.gitattributes new file mode 100644 index 0000000000000..2b39a27d8ec15 --- /dev/null +++ b/src/tools/rustfmt/tests/rustfmt/sources/args_file/.gitattributes @@ -0,0 +1,2 @@ +# prevent git doing any conversion of the CRLF line endings in this file +/args_full_carriage_return -text diff --git a/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_full_carriage_return b/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_full_carriage_return new file mode 100644 index 0000000000000..986d4bf7bd33d --- /dev/null +++ b/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_full_carriage_return @@ -0,0 +1,4 @@ +--check +--files-with-diff +--config +hard_tabs=true diff --git a/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_full_tab_indent b/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_full_tab_indent new file mode 100644 index 0000000000000..f8ef6f4fca80d --- /dev/null +++ b/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_full_tab_indent @@ -0,0 +1,4 @@ +--check +--files-with-diff +--config +hard_tabs=true diff --git a/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_hex_uppercase b/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_hex_uppercase new file mode 100644 index 0000000000000..a8f5541463a73 --- /dev/null +++ b/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_hex_uppercase @@ -0,0 +1,2 @@ +--config +hex_literal_case=Upper diff --git a/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_tab_indent b/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_tab_indent new file mode 100644 index 0000000000000..4b473e24fc2c4 --- /dev/null +++ b/src/tools/rustfmt/tests/rustfmt/sources/args_file/args_tab_indent @@ -0,0 +1,2 @@ +--config +hard_tabs=true diff --git a/src/tools/rustfmt/tests/rustfmt/sources/args_file/hex_lowercase.rs b/src/tools/rustfmt/tests/rustfmt/sources/args_file/hex_lowercase.rs new file mode 100644 index 0000000000000..cef85b7c3472f --- /dev/null +++ b/src/tools/rustfmt/tests/rustfmt/sources/args_file/hex_lowercase.rs @@ -0,0 +1,3 @@ +fn f() { + let _: usize = 0xdeadbeef; +} diff --git a/src/tools/rustfmt/tests/rustfmt/sources/args_file/rustfmt.toml b/src/tools/rustfmt/tests/rustfmt/sources/args_file/rustfmt.toml new file mode 100644 index 0000000000000..636bc1a8abf95 --- /dev/null +++ b/src/tools/rustfmt/tests/rustfmt/sources/args_file/rustfmt.toml @@ -0,0 +1 @@ +# intentionally empty diff --git a/src/tools/rustfmt/tests/rustfmt/sources/args_file/space_indents.rs b/src/tools/rustfmt/tests/rustfmt/sources/args_file/space_indents.rs new file mode 100644 index 0000000000000..211d2de3c959e --- /dev/null +++ b/src/tools/rustfmt/tests/rustfmt/sources/args_file/space_indents.rs @@ -0,0 +1,3 @@ +fn f() { + // comment +} From 5288ba8cd43460aa6b82d1d445e1891a017aec67 Mon Sep 17 00:00:00 2001 From: Matthew Hughes Date: Wed, 4 Nov 2026 10:07:25 +0800 Subject: [PATCH 03/41] Add pre-fix tests for rust-lang/rustfmt#6612 That issue was about ````rust /// ``` /// println!("1"); // comment /// # println!("2") /// ``` ```` becoming ````rust /// ``` /// println!("1"); // comment /// /// # println!("2") /// ``` ```` under UO `format_code_in_doc_comments=true`. Co-authored-by: Jieyou Xu --- .../issue-6612/hidden_code_in_doc_comment.rs | 18 +++++++++++++++++ .../source/issue-6612/mixed_comment_types.rs | 12 +++++++++++ .../issue-6612/hidden_code_in_doc_comment.rs | 20 +++++++++++++++++++ .../target/issue-6612/mixed_comment_types.rs | 14 +++++++++++++ 4 files changed, 64 insertions(+) create mode 100644 src/tools/rustfmt/tests/source/issue-6612/hidden_code_in_doc_comment.rs create mode 100644 src/tools/rustfmt/tests/source/issue-6612/mixed_comment_types.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6612/mixed_comment_types.rs diff --git a/src/tools/rustfmt/tests/source/issue-6612/hidden_code_in_doc_comment.rs b/src/tools/rustfmt/tests/source/issue-6612/hidden_code_in_doc_comment.rs new file mode 100644 index 0000000000000..675acdb4cb1cc --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6612/hidden_code_in_doc_comment.rs @@ -0,0 +1,18 @@ +//@ rustfmt-format_code_in_doc_comments: true +//@ rustfmt-style_edition: 2024 + +/// ``` +/// println!("1"); // comment +/// # println!("2"); +/// ``` +struct S; + +/// println!("1"); // comment +/// # println!("2"); +struct S2; + +/// ``` +/// println!("1"); // comment +///# println!("2"); +/// ``` +struct S3; diff --git a/src/tools/rustfmt/tests/source/issue-6612/mixed_comment_types.rs b/src/tools/rustfmt/tests/source/issue-6612/mixed_comment_types.rs new file mode 100644 index 0000000000000..e80c7cb479fe8 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6612/mixed_comment_types.rs @@ -0,0 +1,12 @@ +//@ rustfmt-style_edition: 2024 + +fn wat1() { + println!("1"); // double slash comment + /* another comment type */ +} + +fn wat1() { + println!("1"); // double slash comment + /* another comment type */ + //# yet another type +} diff --git a/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs b/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs new file mode 100644 index 0000000000000..a95acca530292 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs @@ -0,0 +1,20 @@ +//@ rustfmt-format_code_in_doc_comments: true +//@ rustfmt-style_edition: 2024 + +/// ``` +/// println!("1"); // comment +/// +/// # println!("2"); +/// ``` +struct S; + +/// println!("1"); // comment +/// # println!("2"); +struct S2; + +/// ``` +/// println!("1"); // comment +/// +/// # println!("2"); +/// ``` +struct S3; diff --git a/src/tools/rustfmt/tests/target/issue-6612/mixed_comment_types.rs b/src/tools/rustfmt/tests/target/issue-6612/mixed_comment_types.rs new file mode 100644 index 0000000000000..051ac57c3359d --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6612/mixed_comment_types.rs @@ -0,0 +1,14 @@ +//@ rustfmt-style_edition: 2024 + +fn wat1() { + println!("1"); // double slash comment + + /* another comment type */ +} + +fn wat1() { + println!("1"); // double slash comment + + /* another comment type */ + //# yet another type +} From 727dbd512a891230b7b6a2df64ddf28af36a32fd Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Fri, 6 Nov 2026 14:26:51 +0800 Subject: [PATCH 04/41] Add additional test case which errored with trailing whitespace --- .../tests/source/issue-6612/hidden_code_in_doc_comment.rs | 6 ++++++ .../tests/target/issue-6612/hidden_code_in_doc_comment.rs | 7 +++++++ 2 files changed, 13 insertions(+) diff --git a/src/tools/rustfmt/tests/source/issue-6612/hidden_code_in_doc_comment.rs b/src/tools/rustfmt/tests/source/issue-6612/hidden_code_in_doc_comment.rs index 675acdb4cb1cc..2748ae995a364 100644 --- a/src/tools/rustfmt/tests/source/issue-6612/hidden_code_in_doc_comment.rs +++ b/src/tools/rustfmt/tests/source/issue-6612/hidden_code_in_doc_comment.rs @@ -16,3 +16,9 @@ struct S2; ///# println!("2"); /// ``` struct S3; + +/// ``` +/// println!("1"); // comment +/// # println!("2"); +/// ``` +struct S4; diff --git a/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs b/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs index a95acca530292..24734e56e4cfa 100644 --- a/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs +++ b/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs @@ -18,3 +18,10 @@ struct S2; /// # println!("2"); /// ``` struct S3; + +/// ``` +/// println!("1"); // comment +/// +/// # println!("2"); +/// ``` +struct S4; From 429bb51ac1c11a4a72a8df63c730c55f404bbae7 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Fri, 6 Nov 2026 14:41:21 +0800 Subject: [PATCH 05/41] Add style edition 2021 regression test This errored with leftover trailing whitespace previously on SE 2024. --- .../rustfmt/tests/target/issue-5391/style_edition_2021.rs | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 src/tools/rustfmt/tests/target/issue-5391/style_edition_2021.rs diff --git a/src/tools/rustfmt/tests/target/issue-5391/style_edition_2021.rs b/src/tools/rustfmt/tests/target/issue-5391/style_edition_2021.rs new file mode 100644 index 0000000000000..71cb9c660786a --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-5391/style_edition_2021.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2021 + +mod example { + pub const CUSTOM_ERROR_MSG_BUFFER_SIZE: usize = 4096; // one kernel page?! + //^ must be pub due to being used in a macro! +} From be03998183c8d3cae5711c290a0dd28a03b44730 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 20 Jun 2022 10:44:28 -0400 Subject: [PATCH 06/41] Derive Debug for `comment::CommentStyle` --- src/tools/rustfmt/src/comment.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rustfmt/src/comment.rs b/src/tools/rustfmt/src/comment.rs index f9875d6e4b101..6e04b72b1a116 100644 --- a/src/tools/rustfmt/src/comment.rs +++ b/src/tools/rustfmt/src/comment.rs @@ -26,7 +26,7 @@ fn is_custom_comment(comment: &str) -> bool { } } -#[derive(Copy, Clone, PartialEq, Eq)] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) enum CommentStyle<'a> { DoubleSlash, TripleSlash, From aead0f9e5fa7bc03e00504739d2f42c4c14c9d49 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 20 Jun 2022 10:46:08 -0400 Subject: [PATCH 07/41] Remove each comment's leading whitespace in `comment::rewrite_comment` Fixes 5391 and 6612 Previously, leading whitespace at the start of custom comments (`CommentStyle::Custom`) would lead `consume_same_line_comments` to not return the correct byte position for the end of the comment. This issue cascaded into a situation where an extra indented newline was inserted into rustfmts output causing a `"left behind trailing whitespace"` error. Removing leading whitespace helps to properly identify the end of the comment and properly rewrite the comment. --- src/tools/rustfmt/src/comment.rs | 2 +- .../source/issue-5391/style_edition_2024.rs | 6 + .../comment_after_trailing_comment.rs | 123 ++++++++++++++++++ .../target/issue-5391/style_edition_2024.rs | 6 + .../issue-6612/hidden_code_in_doc_comment.rs | 3 - .../target/issue-6612/mixed_comment_types.rs | 2 - 6 files changed, 136 insertions(+), 6 deletions(-) create mode 100644 src/tools/rustfmt/tests/source/issue-5391/style_edition_2024.rs create mode 100644 src/tools/rustfmt/tests/target/issue-5391/comment_after_trailing_comment.rs create mode 100644 src/tools/rustfmt/tests/target/issue-5391/style_edition_2024.rs diff --git a/src/tools/rustfmt/src/comment.rs b/src/tools/rustfmt/src/comment.rs index 6e04b72b1a116..516cc730256ed 100644 --- a/src/tools/rustfmt/src/comment.rs +++ b/src/tools/rustfmt/src/comment.rs @@ -249,7 +249,7 @@ pub(crate) fn rewrite_comment( shape: Shape, config: &Config, ) -> RewriteResult { - identify_comment(orig, block_style, shape, config, false) + identify_comment(orig.trim_start(), block_style, shape, config, false) } fn identify_comment( diff --git a/src/tools/rustfmt/tests/source/issue-5391/style_edition_2024.rs b/src/tools/rustfmt/tests/source/issue-5391/style_edition_2024.rs new file mode 100644 index 0000000000000..9c7333fffcfcc --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-5391/style_edition_2024.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2024 + +mod example { + pub const CUSTOM_ERROR_MSG_BUFFER_SIZE: usize = 4096; // one kernel page?! + //^ must be pub due to being used in a macro! +} diff --git a/src/tools/rustfmt/tests/target/issue-5391/comment_after_trailing_comment.rs b/src/tools/rustfmt/tests/target/issue-5391/comment_after_trailing_comment.rs new file mode 100644 index 0000000000000..6f5e896fc4496 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-5391/comment_after_trailing_comment.rs @@ -0,0 +1,123 @@ +//@ rustfmt-style_edition: 2024 + +fn custom_comments() { + // Custom comment is the last element of the block + { + let x = 0; // X + //.Y + } + + // Custom comment is not the last element of the block + { + let x = 0; // X + //.Y + println!("hello world!"); + } + + // Variations on custom comment tests with and without extra text + { + let x = 0; // X + //~Y + } + { + let x = 0; // X + //~Y + println!("hello world!"); + } + { + let x = 0; // X + //.Y Some more text + } + { + let x = 0; // X + //.Y Some more text + println!("hello world!"); + } + { + let x = 0; // X + //~Y Some more text + } + { + let x = 0; // X + //~Y Some more text + println!("hello world!"); + } +} + +fn double_slash_comments() { + // DoubleSlash comment is the last element of the block + { + let x = 0; // X + // .Y + } + + // DoubleSlash comment is not the the last element of the block + { + let x = 0; // X + // .Y + println!("hello world!"); + } + { + let x = 0; // X + // ~Y + } + { + let x = 0; // X + // ~Y + println!("hello world!"); + } + { + let x = 0; // X + //Y + } + { + let x = 0; // X + //Y + println!("hello world!"); + } + { + let x = 0; // X + // Y + } + { + let x = 0; // X + // Y + println!("hello world!"); + } +} + +// Compiler UI Test Error Annotations that use custom comments +// https://rustc-dev-guide.rust-lang.org/tests/ui.html#error-annotation-examples +mod compiler_ui_test_error_annotations { + /// Use the //~ ERROR idiom: + fn positioned_on_error_line() { + let x = (1, 2, 3); + match x { + (_a, _x @ ..) => {} //~ ERROR `_x @` is not allowed in a tuple + _ => {} + } + } + + /// Use the //~^ idiom with number of carets in the string to indicate the number of lines above + fn positioned_below_error_line() { + let x = (1, 2, 3); + match x { + (_a, _x @ ..) => {} // <- the error is on this line + _ => {} + } + //~^^^ ERROR `_x @` is not allowed in a tuple + } + + struct Binder(i32, i32, i32); + + /// Use the //~| idiom to define the same error line as the error annotation line above + fn use_same_error_line_as_defined_on_error_annotation_line_above() { + let x = Binder(1, 2, 3); + match x { + Binder(_a, _x @ ..) => {} // <- the error is on this line + _ => {} + } + //~^^^ ERROR `_x @` is not allowed in a tuple struct + //~| ERROR this pattern has 1 field, but the corresponding tuple struct has 3 fields [E0023] + } +} diff --git a/src/tools/rustfmt/tests/target/issue-5391/style_edition_2024.rs b/src/tools/rustfmt/tests/target/issue-5391/style_edition_2024.rs new file mode 100644 index 0000000000000..fc9afe4641c02 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-5391/style_edition_2024.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2024 + +mod example { + pub const CUSTOM_ERROR_MSG_BUFFER_SIZE: usize = 4096; // one kernel page?! + //^ must be pub due to being used in a macro! +} diff --git a/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs b/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs index 24734e56e4cfa..eef652fe70cec 100644 --- a/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs +++ b/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs @@ -3,7 +3,6 @@ /// ``` /// println!("1"); // comment -/// /// # println!("2"); /// ``` struct S; @@ -14,14 +13,12 @@ struct S2; /// ``` /// println!("1"); // comment -/// /// # println!("2"); /// ``` struct S3; /// ``` /// println!("1"); // comment -/// /// # println!("2"); /// ``` struct S4; diff --git a/src/tools/rustfmt/tests/target/issue-6612/mixed_comment_types.rs b/src/tools/rustfmt/tests/target/issue-6612/mixed_comment_types.rs index 051ac57c3359d..e80c7cb479fe8 100644 --- a/src/tools/rustfmt/tests/target/issue-6612/mixed_comment_types.rs +++ b/src/tools/rustfmt/tests/target/issue-6612/mixed_comment_types.rs @@ -2,13 +2,11 @@ fn wat1() { println!("1"); // double slash comment - /* another comment type */ } fn wat1() { println!("1"); // double slash comment - /* another comment type */ //# yet another type } From 20e71c277f0370a990dcc701529facee5389e64c Mon Sep 17 00:00:00 2001 From: Roland Xu Date: Fri, 6 Nov 2026 16:46:33 +0800 Subject: [PATCH 08/41] test: cover empty where clauses across style editions Co-authored-by: Jieyou Xu --- .../empty-where-ret-ty-style-edition-2024.rs | 83 ++++++++++++++ .../empty-where-ret-ty-style-edition-2027.rs | 83 ++++++++++++++ .../empty-where-ret-ty-style-edition-2024.rs | 106 ++++++++++++++++++ .../empty-where-ret-ty-style-edition-2027.rs | 106 ++++++++++++++++++ 4 files changed, 378 insertions(+) create mode 100644 src/tools/rustfmt/tests/source/where-clause/empty-where-ret-ty-style-edition-2024.rs create mode 100644 src/tools/rustfmt/tests/source/where-clause/empty-where-ret-ty-style-edition-2027.rs create mode 100644 src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2024.rs create mode 100644 src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2027.rs diff --git a/src/tools/rustfmt/tests/source/where-clause/empty-where-ret-ty-style-edition-2024.rs b/src/tools/rustfmt/tests/source/where-clause/empty-where-ret-ty-style-edition-2024.rs new file mode 100644 index 0000000000000..439407bf79778 --- /dev/null +++ b/src/tools/rustfmt/tests/source/where-clause/empty-where-ret-ty-style-edition-2024.rs @@ -0,0 +1,83 @@ +//@ rustfmt-style_edition: 2024 + +fn implicit_ret_ty_1() where {} +fn implicit_ret_ty_2() /* comment */ where {} +fn implicit_ret_ty_3() where /* comment */ {} +fn implicit_ret_ty_4() /* comment */ where /* comment */ {} + +fn foo() -> () where {} +fn bar() -> () /* comment */ where {} +fn baz() -> () where /* comment */ {} +fn qux() -> () /* comment */ where /* comment */ {} + +fn implicit_line_before() // c1 +where {} +fn implicit_line_after() where // c2 +{} +fn implicit_line_both() // c1 +where // c2 +{} + +fn explicit_line_before() -> () // c1 +where {} +fn explicit_line_after() -> () where // c2 +{} +fn line_comments() -> () // c1 +where // c2 +{} + +foo! { + fn implicit_ret_ty() where {} +} + +bar! { + fn explicit_ret_ty() -> () where {} +} + +i1!(fn implicit_ret_ty_1() where {}); +i2!(fn implicit_ret_ty_2() /* comment */ where {}); +i3!(fn implicit_ret_ty_3() where /* comment */ {}); +i4!(fn implicit_ret_ty_4() /* comment */ where /* comment */ {}); + +i1!(fn explicit_ret_ty_1() -> i32 where {}); +i2!(fn explicit_ret_ty_2() -> i32 /* comment */ where {}); +i3!(fn explicit_ret_ty_3() -> i32 where /* comment */ {}); +i4!(fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */ {}); + +extern "C" { + fn implicit_ret_ty_1() where; + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; +} + +trait MyTrait { + fn implicit_ret_ty_1() where; + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; +} + +macro_rules! m1 { + () => { + fn implicit_ret_ty_1() where; + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; + }; +} diff --git a/src/tools/rustfmt/tests/source/where-clause/empty-where-ret-ty-style-edition-2027.rs b/src/tools/rustfmt/tests/source/where-clause/empty-where-ret-ty-style-edition-2027.rs new file mode 100644 index 0000000000000..b77d089626b22 --- /dev/null +++ b/src/tools/rustfmt/tests/source/where-clause/empty-where-ret-ty-style-edition-2027.rs @@ -0,0 +1,83 @@ +//@ rustfmt-style_edition: 2027 + +fn implicit_ret_ty_1() where {} +fn implicit_ret_ty_2() /* comment */ where {} +fn implicit_ret_ty_3() where /* comment */ {} +fn implicit_ret_ty_4() /* comment */ where /* comment */ {} + +fn foo() -> () where {} +fn bar() -> () /* comment */ where {} +fn baz() -> () where /* comment */ {} +fn qux() -> () /* comment */ where /* comment */ {} + +fn implicit_line_before() // c1 +where {} +fn implicit_line_after() where // c2 +{} +fn implicit_line_both() // c1 +where // c2 +{} + +fn explicit_line_before() -> () // c1 +where {} +fn explicit_line_after() -> () where // c2 +{} +fn line_comments() -> () // c1 +where // c2 +{} + +foo! { + fn implicit_ret_ty() where {} +} + +bar! { + fn explicit_ret_ty() -> () where {} +} + +i1!(fn implicit_ret_ty_1() where {}); +i2!(fn implicit_ret_ty_2() /* comment */ where {}); +i3!(fn implicit_ret_ty_3() where /* comment */ {}); +i4!(fn implicit_ret_ty_4() /* comment */ where /* comment */ {}); + +i1!(fn explicit_ret_ty_1() -> i32 where {}); +i2!(fn explicit_ret_ty_2() -> i32 /* comment */ where {}); +i3!(fn explicit_ret_ty_3() -> i32 where /* comment */ {}); +i4!(fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */ {}); + +extern "C" { + fn implicit_ret_ty_1() where; + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; +} + +trait MyTrait { + fn implicit_ret_ty_1() where; + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; +} + +macro_rules! m1 { + () => { + fn implicit_ret_ty_1() where; + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; + }; +} diff --git a/src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2024.rs b/src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2024.rs new file mode 100644 index 0000000000000..bf2cc0c6f4d52 --- /dev/null +++ b/src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2024.rs @@ -0,0 +1,106 @@ +//@ rustfmt-style_edition: 2024 + +fn implicit_ret_ty_1() {} +fn implicit_ret_ty_2() /* comment */ where {} +fn implicit_ret_ty_3() where /* comment */ {} +fn implicit_ret_ty_4() /* comment */ where /* comment */ {} + +fn foo() -> () where {} +fn bar() -> () /* comment */ where {} +fn baz() -> () where /* comment */ {} +fn qux() -> () /* comment */ where /* comment */ {} + +fn implicit_line_before() // c1 +where +{ +} +fn implicit_line_after() where // c2 +{ +} +fn implicit_line_both() // c1 +where // c2 +{ +} + +fn explicit_line_before() -> () // c1 +where { +} +fn explicit_line_after() -> () where // c2 +{ +} +fn line_comments() -> () // c1 +where // c2 +{ +} + +foo! { + fn implicit_ret_ty() where {} +} + +bar! { + fn explicit_ret_ty() -> () where {} +} + +i1!( + fn implicit_ret_ty_1() {} +); +i2!( + fn implicit_ret_ty_2() /* comment */ where {} +); +i3!( + fn implicit_ret_ty_3() where /* comment */ {} +); +i4!( + fn implicit_ret_ty_4() /* comment */ where /* comment */ {} +); + +i1!( + fn explicit_ret_ty_1() -> i32 where {} +); +i2!( + fn explicit_ret_ty_2() -> i32 /* comment */ where {} +); +i3!( + fn explicit_ret_ty_3() -> i32 where /* comment */ {} +); +i4!( + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */ {} +); + +extern "C" { + fn implicit_ret_ty_1(); + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; +} + +trait MyTrait { + fn implicit_ret_ty_1(); + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; +} + +macro_rules! m1 { + () => { + fn implicit_ret_ty_1(); + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; + }; +} diff --git a/src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2027.rs b/src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2027.rs new file mode 100644 index 0000000000000..255bf221e5c30 --- /dev/null +++ b/src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2027.rs @@ -0,0 +1,106 @@ +//@ rustfmt-style_edition: 2027 + +fn implicit_ret_ty_1() {} +fn implicit_ret_ty_2() /* comment */ where {} +fn implicit_ret_ty_3() where /* comment */ {} +fn implicit_ret_ty_4() /* comment */ where /* comment */ {} + +fn foo() -> () where {} +fn bar() -> () /* comment */ where {} +fn baz() -> () where /* comment */ {} +fn qux() -> () /* comment */ where /* comment */ {} + +fn implicit_line_before() // c1 +where +{ +} +fn implicit_line_after() where // c2 +{ +} +fn implicit_line_both() // c1 +where // c2 +{ +} + +fn explicit_line_before() -> () // c1 +where { +} +fn explicit_line_after() -> () where // c2 +{ +} +fn line_comments() -> () // c1 +where // c2 +{ +} + +foo! { + fn implicit_ret_ty() where {} +} + +bar! { + fn explicit_ret_ty() -> () where {} +} + +i1!( + fn implicit_ret_ty_1() {} +); +i2!( + fn implicit_ret_ty_2() /* comment */ where {} +); +i3!( + fn implicit_ret_ty_3() where /* comment */ {} +); +i4!( + fn implicit_ret_ty_4() /* comment */ where /* comment */ {} +); + +i1!( + fn explicit_ret_ty_1() -> i32 where {} +); +i2!( + fn explicit_ret_ty_2() -> i32 /* comment */ where {} +); +i3!( + fn explicit_ret_ty_3() -> i32 where /* comment */ {} +); +i4!( + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */ {} +); + +extern "C" { + fn implicit_ret_ty_1(); + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; +} + +trait MyTrait { + fn implicit_ret_ty_1(); + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; +} + +macro_rules! m1 { + () => { + fn implicit_ret_ty_1(); + fn implicit_ret_ty_2() /* comment */ where; + fn implicit_ret_ty_3() where /* comment */; + fn implicit_ret_ty_4() /* comment */ where /* comment */; + + fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_2() -> i32 /* comment */ where; + fn explicit_ret_ty_3() -> i32 where /* comment */; + fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; + }; +} From b57438616bc27dfa6709ca369d58527d6db938c1 Mon Sep 17 00:00:00 2001 From: Roland Xu Date: Fri, 6 Nov 2026 16:46:46 +0800 Subject: [PATCH 09/41] fix: remove uncommented empty where clauses after return types Co-authored-by: Jieyou Xu --- src/tools/rustfmt/src/items.rs | 42 +++++++++++-------- .../empty-where-ret-ty-style-edition-2027.rs | 10 ++--- 2 files changed, 29 insertions(+), 23 deletions(-) diff --git a/src/tools/rustfmt/src/items.rs b/src/tools/rustfmt/src/items.rs index 449cca87afe4a..2e9bcb4dc604d 100644 --- a/src/tools/rustfmt/src/items.rs +++ b/src/tools/rustfmt/src/items.rs @@ -2720,27 +2720,33 @@ fn rewrite_fn_base( } // Comment between return type and the end of the decl. - let snippet_lo = fd.output.span().hi(); if where_clause.predicates.is_empty() { + let snippet_lo = fd.output.span().hi(); let snippet_hi = span.hi(); let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi)); - // Try to preserve the layout of the original snippet. - let original_starts_with_newline = snippet - .find(|c| c != ' ') - .map_or(false, |i| starts_with_newline(&snippet[i..])); - let original_ends_with_newline = snippet - .rfind(|c| c != ' ') - .map_or(false, |i| snippet[i..].ends_with('\n')); - let snippet = snippet.trim(); - if !snippet.is_empty() { - result.push(if original_starts_with_newline { - '\n' - } else { - ' ' - }); - result.push_str(snippet); - if original_ends_with_newline { - force_new_line_for_brace = true; + let remove_empty_where = context.config.style_edition() >= StyleEdition::Edition2027 + && where_clause.has_where_token + && !contains_comment(snippet); + + if !remove_empty_where { + // Try to preserve the layout of the original snippet. + let original_starts_with_newline = snippet + .find(|c| c != ' ') + .map_or(false, |i| starts_with_newline(&snippet[i..])); + let original_ends_with_newline = snippet + .rfind(|c| c != ' ') + .map_or(false, |i| snippet[i..].ends_with('\n')); + let snippet = snippet.trim(); + if !snippet.is_empty() { + result.push(if original_starts_with_newline { + '\n' + } else { + ' ' + }); + result.push_str(snippet); + if original_ends_with_newline { + force_new_line_for_brace = true; + } } } } diff --git a/src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2027.rs b/src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2027.rs index 255bf221e5c30..dd9146be22275 100644 --- a/src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2027.rs +++ b/src/tools/rustfmt/tests/target/where-clause/empty-where-ret-ty-style-edition-2027.rs @@ -5,7 +5,7 @@ fn implicit_ret_ty_2() /* comment */ where {} fn implicit_ret_ty_3() where /* comment */ {} fn implicit_ret_ty_4() /* comment */ where /* comment */ {} -fn foo() -> () where {} +fn foo() -> () {} fn bar() -> () /* comment */ where {} fn baz() -> () where /* comment */ {} fn qux() -> () /* comment */ where /* comment */ {} @@ -55,7 +55,7 @@ i4!( ); i1!( - fn explicit_ret_ty_1() -> i32 where {} + fn explicit_ret_ty_1() -> i32 {} ); i2!( fn explicit_ret_ty_2() -> i32 /* comment */ where {} @@ -73,7 +73,7 @@ extern "C" { fn implicit_ret_ty_3() where /* comment */; fn implicit_ret_ty_4() /* comment */ where /* comment */; - fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_1() -> i32; fn explicit_ret_ty_2() -> i32 /* comment */ where; fn explicit_ret_ty_3() -> i32 where /* comment */; fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; @@ -85,7 +85,7 @@ trait MyTrait { fn implicit_ret_ty_3() where /* comment */; fn implicit_ret_ty_4() /* comment */ where /* comment */; - fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_1() -> i32; fn explicit_ret_ty_2() -> i32 /* comment */ where; fn explicit_ret_ty_3() -> i32 where /* comment */; fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; @@ -98,7 +98,7 @@ macro_rules! m1 { fn implicit_ret_ty_3() where /* comment */; fn implicit_ret_ty_4() /* comment */ where /* comment */; - fn explicit_ret_ty_1() -> i32 where; + fn explicit_ret_ty_1() -> i32; fn explicit_ret_ty_2() -> i32 /* comment */ where; fn explicit_ret_ty_3() -> i32 where /* comment */; fn explicit_ret_ty_4() -> i32 /* comment */ where /* comment */; From 56eb83296139fe2b8a3640fa73bad6a768c76985 Mon Sep 17 00:00:00 2001 From: SzilvasiPeter Date: Fri, 6 Nov 2026 11:12:03 +0100 Subject: [PATCH 10/41] feat: add icu4x and all unicode-rs repo to check_diff --- src/tools/rustfmt/check_diff/src/main.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/tools/rustfmt/check_diff/src/main.rs b/src/tools/rustfmt/check_diff/src/main.rs index c48280f254d4b..d283700c41770 100644 --- a/src/tools/rustfmt/check_diff/src/main.rs +++ b/src/tools/rustfmt/check_diff/src/main.rs @@ -39,9 +39,16 @@ const REPOS: &[&str] = &[ "https://github.com/SergioBenitez/Rocket.git", "https://github.com/Stebalien/tempfile.git", // Unicode / international text coverage (see rustfmt#5884) - "https://github.com/unicode-rs/unicode-width.git", - "https://github.com/unicode-rs/unicode-segmentation.git", + "https://github.com/unicode-org/icu4x.git", + "https://github.com/unicode-rs/rust-caseless.git", + "https://github.com/unicode-rs/unicode-charname", "https://github.com/unicode-rs/unicode-normalization.git", + "https://github.com/unicode-rs/unicode-properties", + "https://github.com/unicode-rs/unicode-security.git", + "https://github.com/unicode-rs/unicode-segmentation.git", + "https://github.com/unicode-rs/unicode-script.git", + "https://github.com/unicode-rs/unicode-width.git", + "https://github.com/unicode-rs/unicode-xid.git", ]; /// Inputs for the check_diff script From 9e1bd4758edcbb06dadb70ef98aaf42a9cd2e6ee Mon Sep 17 00:00:00 2001 From: Nicole LeGare Date: Thu, 5 Nov 2026 12:38:00 -0800 Subject: [PATCH 11/41] Add regression tests for trailing multiline block comments Capture the pre-fix output for wrapping, normalization, and style editions, including the malformed comments produced by the existing formatter. --- .../rustfmt/tests/source/issue-6339/bare_lines.rs | 10 ++++++++++ .../source/issue-6339/bare_lines_normalize_comments.rs | 7 +++++++ .../source/issue-6339/bare_lines_style_edition_2027.rs | 6 ++++++ .../source/issue-6339/bare_lines_wrap_comments.rs | 6 ++++++ .../tests/source/issue-6339/closing_delimiter.rs | 6 ++++++ .../issue-6339/first_line_trailing_whitespace.rs | 6 ++++++ .../issue-6339/single_line_normalize_comments.rs | 6 ++++++ .../tests/source/issue-6339/wrap_comments_false.rs | 7 +++++++ .../tests/source/issue-6339/wrap_comments_true.rs | 7 +++++++ .../rustfmt/tests/target/issue-6339/bare_lines.rs | 10 ++++++++++ .../target/issue-6339/bare_lines_normalize_comments.rs | 7 +++++++ .../target/issue-6339/bare_lines_style_edition_2027.rs | 6 ++++++ .../target/issue-6339/bare_lines_wrap_comments.rs | 6 ++++++ .../tests/target/issue-6339/closing_delimiter.rs | 6 ++++++ .../issue-6339/first_line_trailing_whitespace.rs | 6 ++++++ .../issue-6339/single_line_normalize_comments.rs | 6 ++++++ .../tests/target/issue-6339/wrap_comments_false.rs | 7 +++++++ .../tests/target/issue-6339/wrap_comments_true.rs | 7 +++++++ 18 files changed, 122 insertions(+) create mode 100644 src/tools/rustfmt/tests/source/issue-6339/bare_lines.rs create mode 100644 src/tools/rustfmt/tests/source/issue-6339/bare_lines_normalize_comments.rs create mode 100644 src/tools/rustfmt/tests/source/issue-6339/bare_lines_style_edition_2027.rs create mode 100644 src/tools/rustfmt/tests/source/issue-6339/bare_lines_wrap_comments.rs create mode 100644 src/tools/rustfmt/tests/source/issue-6339/closing_delimiter.rs create mode 100644 src/tools/rustfmt/tests/source/issue-6339/first_line_trailing_whitespace.rs create mode 100644 src/tools/rustfmt/tests/source/issue-6339/single_line_normalize_comments.rs create mode 100644 src/tools/rustfmt/tests/source/issue-6339/wrap_comments_false.rs create mode 100644 src/tools/rustfmt/tests/source/issue-6339/wrap_comments_true.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6339/bare_lines.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6339/bare_lines_normalize_comments.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6339/bare_lines_style_edition_2027.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6339/bare_lines_wrap_comments.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6339/closing_delimiter.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6339/first_line_trailing_whitespace.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6339/single_line_normalize_comments.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6339/wrap_comments_false.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6339/wrap_comments_true.rs diff --git a/src/tools/rustfmt/tests/source/issue-6339/bare_lines.rs b/src/tools/rustfmt/tests/source/issue-6339/bare_lines.rs new file mode 100644 index 0000000000000..761f05bc6b5b6 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6339/bare_lines.rs @@ -0,0 +1,10 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: false + +fn main() {} /* first + second + third */ + +fn long_first_line() {} /* this is a long first line that exceeds 100 columns and should remain on the same line +hello + world */ diff --git a/src/tools/rustfmt/tests/source/issue-6339/bare_lines_normalize_comments.rs b/src/tools/rustfmt/tests/source/issue-6339/bare_lines_normalize_comments.rs new file mode 100644 index 0000000000000..c34409462caba --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6339/bare_lines_normalize_comments.rs @@ -0,0 +1,7 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: false +//@ rustfmt-normalize_comments: true + +fn main() {} /* first + second + third */ diff --git a/src/tools/rustfmt/tests/source/issue-6339/bare_lines_style_edition_2027.rs b/src/tools/rustfmt/tests/source/issue-6339/bare_lines_style_edition_2027.rs new file mode 100644 index 0000000000000..87fb70326d7b8 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6339/bare_lines_style_edition_2027.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2027 +//@ rustfmt-wrap_comments: false + +fn main() {} /* first + second + third */ diff --git a/src/tools/rustfmt/tests/source/issue-6339/bare_lines_wrap_comments.rs b/src/tools/rustfmt/tests/source/issue-6339/bare_lines_wrap_comments.rs new file mode 100644 index 0000000000000..97bb699178fc2 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6339/bare_lines_wrap_comments.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: true + +fn main() {} /* first + second + third */ diff --git a/src/tools/rustfmt/tests/source/issue-6339/closing_delimiter.rs b/src/tools/rustfmt/tests/source/issue-6339/closing_delimiter.rs new file mode 100644 index 0000000000000..a01382eef2d66 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6339/closing_delimiter.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: false + +fn main() {} /* first + second + */ diff --git a/src/tools/rustfmt/tests/source/issue-6339/first_line_trailing_whitespace.rs b/src/tools/rustfmt/tests/source/issue-6339/first_line_trailing_whitespace.rs new file mode 100644 index 0000000000000..cd3a2c471c7c9 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6339/first_line_trailing_whitespace.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: false + +fn main() {} /* first + * second + */ diff --git a/src/tools/rustfmt/tests/source/issue-6339/single_line_normalize_comments.rs b/src/tools/rustfmt/tests/source/issue-6339/single_line_normalize_comments.rs new file mode 100644 index 0000000000000..0ed76ad493b16 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6339/single_line_normalize_comments.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-normalize_comments: true + +fn a() {} /* trailing */ + +fn b() {} // trailing diff --git a/src/tools/rustfmt/tests/source/issue-6339/wrap_comments_false.rs b/src/tools/rustfmt/tests/source/issue-6339/wrap_comments_false.rs new file mode 100644 index 0000000000000..b60f12d52a0da --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6339/wrap_comments_false.rs @@ -0,0 +1,7 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: false + +use rustc_middle::ty::{self, Region, Ty, TyCtxt}; /* xx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + * xxxxxxxxxxxxx */ + +fn main() {} diff --git a/src/tools/rustfmt/tests/source/issue-6339/wrap_comments_true.rs b/src/tools/rustfmt/tests/source/issue-6339/wrap_comments_true.rs new file mode 100644 index 0000000000000..59bec6cf8f858 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6339/wrap_comments_true.rs @@ -0,0 +1,7 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: true + +use rustc_middle::ty::{self, Region, Ty, TyCtxt}; /* xx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + * xxxxxxxxxxxxx */ + +fn main() {} diff --git a/src/tools/rustfmt/tests/target/issue-6339/bare_lines.rs b/src/tools/rustfmt/tests/target/issue-6339/bare_lines.rs new file mode 100644 index 0000000000000..c0928522b0c9d --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6339/bare_lines.rs @@ -0,0 +1,10 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: false + +fn main() {} /* first +second +third */ + +fn long_first_line() {} /* this is a long first line that exceeds 100 columns and should remain on the same line +hello +world */ diff --git a/src/tools/rustfmt/tests/target/issue-6339/bare_lines_normalize_comments.rs b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_normalize_comments.rs new file mode 100644 index 0000000000000..944e47d791a46 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_normalize_comments.rs @@ -0,0 +1,7 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: false +//@ rustfmt-normalize_comments: true + +fn main() {} /* first +// second +// third diff --git a/src/tools/rustfmt/tests/target/issue-6339/bare_lines_style_edition_2027.rs b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_style_edition_2027.rs new file mode 100644 index 0000000000000..df3fbf20b7af1 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_style_edition_2027.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2027 +//@ rustfmt-wrap_comments: false + +fn main() {} /* first +second +third */ diff --git a/src/tools/rustfmt/tests/target/issue-6339/bare_lines_wrap_comments.rs b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_wrap_comments.rs new file mode 100644 index 0000000000000..5b1fedd491284 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_wrap_comments.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: true + +fn main() {} /* first +//second +//third diff --git a/src/tools/rustfmt/tests/target/issue-6339/closing_delimiter.rs b/src/tools/rustfmt/tests/target/issue-6339/closing_delimiter.rs new file mode 100644 index 0000000000000..8c63e29c32a0b --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6339/closing_delimiter.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: false + +fn main() {} /* first +second + */ diff --git a/src/tools/rustfmt/tests/target/issue-6339/first_line_trailing_whitespace.rs b/src/tools/rustfmt/tests/target/issue-6339/first_line_trailing_whitespace.rs new file mode 100644 index 0000000000000..2e5cf56412a16 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6339/first_line_trailing_whitespace.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: false + +fn main() {} /* first + * second + */ diff --git a/src/tools/rustfmt/tests/target/issue-6339/single_line_normalize_comments.rs b/src/tools/rustfmt/tests/target/issue-6339/single_line_normalize_comments.rs new file mode 100644 index 0000000000000..0ed76ad493b16 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6339/single_line_normalize_comments.rs @@ -0,0 +1,6 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-normalize_comments: true + +fn a() {} /* trailing */ + +fn b() {} // trailing diff --git a/src/tools/rustfmt/tests/target/issue-6339/wrap_comments_false.rs b/src/tools/rustfmt/tests/target/issue-6339/wrap_comments_false.rs new file mode 100644 index 0000000000000..f8bd707f5429d --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6339/wrap_comments_false.rs @@ -0,0 +1,7 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: false + +use rustc_middle::ty::{self, Region, Ty, TyCtxt}; /* xx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + * xxxxxxxxxxxxx */ + +fn main() {} diff --git a/src/tools/rustfmt/tests/target/issue-6339/wrap_comments_true.rs b/src/tools/rustfmt/tests/target/issue-6339/wrap_comments_true.rs new file mode 100644 index 0000000000000..295a3109e2b4e --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6339/wrap_comments_true.rs @@ -0,0 +1,7 @@ +//@ rustfmt-style_edition: 2024 +//@ rustfmt-wrap_comments: true + +use rustc_middle::ty::{self, Region, Ty, TyCtxt}; /* xx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +// xxxxxxxxxxxxx + +fn main() {} From 7af0cb9cc569463f7984a04807aff8724a0a8e7c Mon Sep 17 00:00:00 2001 From: Nicole LeGare Date: Thu, 5 Nov 2026 12:38:00 -0800 Subject: [PATCH 12/41] Fix trailing multiline block comments while preserving older style editions --- src/tools/rustfmt/src/missed_spans.rs | 11 ++++++++++- .../issue-6339/bare_lines_normalize_comments.rs | 2 +- .../issue-6339/bare_lines_style_edition_2027.rs | 2 +- .../target/issue-6339/bare_lines_wrap_comments.rs | 4 ++-- .../issue-6339/single_line_normalize_comments.rs | 2 +- .../tests/target/issue-6339/wrap_comments_true.rs | 2 +- 6 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/tools/rustfmt/src/missed_spans.rs b/src/tools/rustfmt/src/missed_spans.rs index 94ca9238ac045..8fd9cc026e6a4 100644 --- a/src/tools/rustfmt/src/missed_spans.rs +++ b/src/tools/rustfmt/src/missed_spans.rs @@ -274,7 +274,16 @@ impl<'a> FmtVisitor<'a> { let comment_shape = Shape::indented(comment_indent, self.config).comment(self.config); - if on_same_line { + // Style Edition 2024 has stable behavior where first line is preserved for + // trailing block comments. We preserve SE 2024 stable behavior here but rewrite + // block comment as a whole on SE 2027+, or in case where SE 2024 was producing + // broken code. + let can_preserve_first_line = subslice.starts_with("//") + || (self.config.style_edition() == StyleEdition::Edition2024 + && !self.config.wrap_comments() + && !self.config.normalize_comments()); + + if on_same_line && can_preserve_first_line { match subslice.find('\n') { None => { self.push_str(subslice); diff --git a/src/tools/rustfmt/tests/target/issue-6339/bare_lines_normalize_comments.rs b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_normalize_comments.rs index 944e47d791a46..754d6b4dc229f 100644 --- a/src/tools/rustfmt/tests/target/issue-6339/bare_lines_normalize_comments.rs +++ b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_normalize_comments.rs @@ -2,6 +2,6 @@ //@ rustfmt-wrap_comments: false //@ rustfmt-normalize_comments: true -fn main() {} /* first +fn main() {} // first // second // third diff --git a/src/tools/rustfmt/tests/target/issue-6339/bare_lines_style_edition_2027.rs b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_style_edition_2027.rs index df3fbf20b7af1..c2fee0a6ca4ac 100644 --- a/src/tools/rustfmt/tests/target/issue-6339/bare_lines_style_edition_2027.rs +++ b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_style_edition_2027.rs @@ -3,4 +3,4 @@ fn main() {} /* first second -third */ + third */ diff --git a/src/tools/rustfmt/tests/target/issue-6339/bare_lines_wrap_comments.rs b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_wrap_comments.rs index 5b1fedd491284..1c5783179501e 100644 --- a/src/tools/rustfmt/tests/target/issue-6339/bare_lines_wrap_comments.rs +++ b/src/tools/rustfmt/tests/target/issue-6339/bare_lines_wrap_comments.rs @@ -2,5 +2,5 @@ //@ rustfmt-wrap_comments: true fn main() {} /* first -//second -//third +second + third */ diff --git a/src/tools/rustfmt/tests/target/issue-6339/single_line_normalize_comments.rs b/src/tools/rustfmt/tests/target/issue-6339/single_line_normalize_comments.rs index 0ed76ad493b16..8c11fa8146b30 100644 --- a/src/tools/rustfmt/tests/target/issue-6339/single_line_normalize_comments.rs +++ b/src/tools/rustfmt/tests/target/issue-6339/single_line_normalize_comments.rs @@ -1,6 +1,6 @@ //@ rustfmt-style_edition: 2024 //@ rustfmt-normalize_comments: true -fn a() {} /* trailing */ +fn a() {} // trailing fn b() {} // trailing diff --git a/src/tools/rustfmt/tests/target/issue-6339/wrap_comments_true.rs b/src/tools/rustfmt/tests/target/issue-6339/wrap_comments_true.rs index 295a3109e2b4e..7334ab35f9385 100644 --- a/src/tools/rustfmt/tests/target/issue-6339/wrap_comments_true.rs +++ b/src/tools/rustfmt/tests/target/issue-6339/wrap_comments_true.rs @@ -2,6 +2,6 @@ //@ rustfmt-wrap_comments: true use rustc_middle::ty::{self, Region, Ty, TyCtxt}; /* xx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -// xxxxxxxxxxxxx + * xxxxxxxxxxxxx */ fn main() {} From 2c09421358e7db1393b850d05718d532f889c288 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 7 Nov 2026 16:12:54 +0800 Subject: [PATCH 13/41] docs: add TL;DR LLM usage policy to contributing docs --- src/tools/rustfmt/Contributing.md | 53 +++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/src/tools/rustfmt/Contributing.md b/src/tools/rustfmt/Contributing.md index 9e37f15e62b2b..31f763b4948e0 100644 --- a/src/tools/rustfmt/Contributing.md +++ b/src/tools/rustfmt/Contributing.md @@ -12,8 +12,57 @@ Conduct](CODE_OF_CONDUCT.md). ## LLM policy -rustfmt follows the same [LLM usage policy] as `rust-lang/rust`. Please read it before using LLM -assistance when participating in `rust-lang/rustfmt`. +rustfmt follows the same [LLM usage policy] as `rust-lang/rust`. Please read it +before using LLM assistance when participating in `rust-lang/rustfmt`. + +General rule of thumb: + +* It's fine to use LLMs to answer your own questions, analyze, distill, refine, + check, suggest, review. But not to create. +* LLMs work best when used as an assistive tool to help you write *better*, not + *faster*. +* We are a community of contributors and not just a code repository. We are + interested in hearing your thoughts, in your words, not LLM output. If we want + answers from LLMs, we can just use LLMs ourselves. +* **You must understand your changes, and be able to explain your thought + process, tradeoffs and uncertainties to the reviewers. It's okay to be unsure, + but that should be communicated**. +* **Disclosure of LLM usage is required for anything you post or submit**. + +Some clear examples permitted by the [LLM usage policy]: + +* Asking an LLM questions to understand the codebase. +* Asking an LLM to review your changes privately. +* Trivial changes, for example typo or Markdown link fixes, with disclosure. + +Some clear examples prohibited by the [LLM usage policy]: + +* Proxying LLM output unquoted to reviewers or other contributors. +* LLM-created comments, docs, diagnostics, issue bodies, Pull Request (PR) + descriptions and other forms of communication. +* LLM-created code changes except for those conditionally allowed under the + [*experimental rules*](#experimental-rules). + +Reviewers may ask for a rewrite or rework, or close the contribution, if they +find it burdensome to review. + +### Experimental rules + +We leave room for experimentation with code changes originally generated by +LLMs. Such a PR requires: + +1. A **pre-arranged consenting reviewer**. You can ask in [`#t-rustfmt` Zulip + channel][rustfmt-zulip] and discuss the approach there. Reviewers are **not** + obligated to consent. +2. The pre-arranged reviewer must be the reviewer assigned to the PR. You can + write `r? ` on the PR to request a specific reviewer. +3. LLM usage must be disclosed, and the `llm-assisted` label must be applied. + You can add it via `@rustbot label: +llm-assisted`. +4. The change must be high-quality and well-tested. +5. The author must review their own changes. An LLM review **must not** + substitute for human review. + +Please consult the full [LLM usage policy] for nuances. [LLM usage policy]: https://forge.rust-lang.org/policies/llm-usage.html From 671e1ddf35825cac65f0f3c402cff91893e69302 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 7 Nov 2026 16:16:02 +0800 Subject: [PATCH 14/41] docs: move linting section slightly below The test case ones / hacking ones should probably come first. --- src/tools/rustfmt/Contributing.md | 43 +++++++++++++++---------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/src/tools/rustfmt/Contributing.md b/src/tools/rustfmt/Contributing.md index 31f763b4948e0..ca9363407501b 100644 --- a/src/tools/rustfmt/Contributing.md +++ b/src/tools/rustfmt/Contributing.md @@ -66,33 +66,11 @@ Please consult the full [LLM usage policy] for nuances. [LLM usage policy]: https://forge.rust-lang.org/policies/llm-usage.html -## Linting - -This project supports linting via -[`clippy`](https://doc.rust-lang.org/stable/clippy/index.html). You can either -run it directly, or use an integration through your editor. - -``` -# lint rustfmt-nightly (the package at the root of this repo) -cargo clippy -``` - -To Lint a package outside of the root one you will need to do one of: - -``` -# pass the manifest path -cargo clippy --manifest-path ./config_proc_macro/Config.toml -# or run the command from within the package -cd ./config_proc_macro -cargo clippy -``` - ## Test and file issues It would be really useful to have people use rustfmt on their projects and file issues where it does something you don't expect. - ## Create test cases Having a strong test suite for a tool like this is essential. It is very easy @@ -399,6 +377,27 @@ accessing the correct field on the config struct, e.g., `config.max_width()`. Mo functions have a `Config`, or one can be accessed via a visitor or context of some kind. +## Linting + +This project supports linting via +[`clippy`](https://doc.rust-lang.org/stable/clippy/index.html). You can either +run it directly, or use an integration through your editor. + +``` +# lint rustfmt-nightly (the package at the root of this repo) +cargo clippy +``` + +To Lint a package outside of the root one you will need to do one of: + +``` +# pass the manifest path +cargo clippy --manifest-path ./config_proc_macro/Config.toml +# or run the command from within the package +cd ./config_proc_macro +cargo clippy +``` + ## Subtree syncs Refer to [*Subtree sync procedure*](./Subtree%20sync%20procedure.md). From d89e7548ec8f5a184011573ab1831af211ba2fe7 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 7 Nov 2026 17:00:20 +0800 Subject: [PATCH 15/41] docs: add fuzzing guidelines to contributing docs --- src/tools/rustfmt/Contributing.md | 82 +++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/src/tools/rustfmt/Contributing.md b/src/tools/rustfmt/Contributing.md index ca9363407501b..ce99fb4a3ab70 100644 --- a/src/tools/rustfmt/Contributing.md +++ b/src/tools/rustfmt/Contributing.md @@ -71,6 +71,88 @@ Please consult the full [LLM usage policy] for nuances. It would be really useful to have people use rustfmt on their projects and file issues where it does something you don't expect. +## Fuzzing guidelines + +rustfmt broadly follows the same fuzzing guidelines as rustc. Please consult the +[rustc-dev-guide fuzzing guidelines] *before* opening issues uncovered via +fuzzing. + +The guidelines apply to fuzzed issues regardless of methodology, including ones +found via LLMs. The [LLM usage policy](#llm-policy) applies. + +### Bug types + +We are primarily interested in: + +* Panics +* Internal Compiler Errors (ICE) +* Non-idempotent formatting (formatting the output again changes it) +* Formatting that changes semantic meaning +* Input that parses but no longer parses after formatting +* Formatting that drops code or comments + +#### Out of scope + +* Code that fails to parse (as rustfmt intentionally does not format it) +* `error_on_line_overflow` errors on lines that rustfmt cannot shorten + +### In a nutshell + +*Please do*: + +* Ensure the bug is still present on the latest nightly rustfmt and latest + `main` +* Include a reasonably minimal, standalone example along with any bug report +* Include all of the information requested in the bug report template +* Search for existing reports with similar behavior, and check if it is a + duplicate +* Try to minimize rustfmt configuration options and flags required to reproduce + the bug +* Add `S-found-by-fuzzing` label in the bug report: `@rustbot label: + +S-found-by-fuzzing` +* If the test case requires unstable configuration options to reproduce failure, + add relevant `UO-*` labels: `@rustbot label: +UO-` + +*Please don't*: + +* Use bots, scripts or agents to automatically file issues +* File large quantities of fuzzed issues without discussing this beforehand with + the rustfmt team in the [`#t-rustfmt` Zulip channel][rustfmt-zulip] +* Seed your fuzzer with inputs that are known to crash rustfmt (i.e. already + reported on the issue tracker) + +### Discussion + +If you are not sure if a bug is a duplicate, report it and link to the issues +that you think are related. + +### Building a corpus + +When building a corpus, be sure to avoid collecting samples that are already +known to crash rustfmt. A fuzzer that is seeded with such tests is more likely +to generate bugs with the same root cause. + +### Extra credit + +Here are a few things you can do to help rustfmt after filing a bug: + +* For regressions: bisect the bug to figure out when it was introduced. If you + find the regressing PR / commit, you can mark the issue with the label + `S-has-bisection`. If not, consider applying `E-needs-bisection` instead. +* Fix "distractions": problems with the test case that don't contribute to + triggering the bug, for example unrelated syntax errors or extra items. +* Minimize the test case. If successful, you can label the issue with + `S-has-mcve`. Otherwise, you can apply `E-needs-mcve`. + +### Minimization + +It is helpful to carefully minimize the fuzzer-generated input. When minimizing, +be careful to preserve the original error, and avoid introducing distracting +problems such as additional syntax errors. + +[rustc-dev-guide fuzzing guidelines]: + https://rustc-dev-guide.rust-lang.org/fuzzing.html#fuzzing + ## Create test cases Having a strong test suite for a tool like this is essential. It is very easy From d73a51b4571e2895851f817c163da5a36ba01ab8 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 7 Nov 2026 17:03:04 +0800 Subject: [PATCH 16/41] docs: add a TOC to contributing docs --- src/tools/rustfmt/Contributing.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/tools/rustfmt/Contributing.md b/src/tools/rustfmt/Contributing.md index ce99fb4a3ab70..ee1fbd9dd3dfb 100644 --- a/src/tools/rustfmt/Contributing.md +++ b/src/tools/rustfmt/Contributing.md @@ -9,6 +9,22 @@ or file new issues specifically to get help. All contributors are expected to follow our [Code of Conduct](CODE_OF_CONDUCT.md). +## Table of contents + +* [LLM policy](#llm-policy) + * [Experimental rules](#experimental-rules) +* [Test and file issues](#test-and-file-issues) +* [Fuzzing guidelines](#fuzzing-guidelines) +* [Create test cases](#create-test-cases) + * [Updating snapshots](#updating-snapshots) +* [Debugging](#debugging) +* [Hack!](#hack) + * [Guidelines](#guidelines) + * [Run Rustfmt from source code](#run-rustfmt-from-source-code) + * [Gate formatting changes](#gate-formatting-changes) + * [A quick tour of Rustfmt](#a-quick-tour-of-rustfmt) +* [Linting](#linting) +* [Subtree syncs](#subtree-syncs) ## LLM policy From f02cae1acc18df5800ecc5bfae5a072e234b2b0d Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Sat, 7 Nov 2026 17:50:56 +0800 Subject: [PATCH 17/41] docs: describe PR lifecycle in contributing docs --- src/tools/rustfmt/Contributing.md | 101 ++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/src/tools/rustfmt/Contributing.md b/src/tools/rustfmt/Contributing.md index ee1fbd9dd3dfb..cf13b6b05f3c1 100644 --- a/src/tools/rustfmt/Contributing.md +++ b/src/tools/rustfmt/Contributing.md @@ -14,6 +14,7 @@ Conduct](CODE_OF_CONDUCT.md). * [LLM policy](#llm-policy) * [Experimental rules](#experimental-rules) * [Test and file issues](#test-and-file-issues) +* [Pull Request lifecycle](#pull-request-lifecycle) * [Fuzzing guidelines](#fuzzing-guidelines) * [Create test cases](#create-test-cases) * [Updating snapshots](#updating-snapshots) @@ -87,6 +88,106 @@ Please consult the full [LLM usage policy] for nuances. It would be really useful to have people use rustfmt on their projects and file issues where it does something you don't expect. +## Pull Request lifecycle + +### Before review + +#### Opening a PR + +All Pull Requests (PRs) should be filed against the `main` branch. + +You should build and run tests locally before submitting the PR. + +```console +cargo test +``` + +#### PR description + +Write a PR description that makes it easy for the reviewer to understand what is +being changed and why. Tips: + +* Strive to be concise. + * For trivial bugs, just a simple "Fixes #123456" is often sufficient. + * Don't repeat what's obvious from the diff itself or already checked by CI, + such as which files changed or that `cargo test` passes. +* Link to relevant issues and discussions. + * You can use GitHub's feature of [closing issues using + keywords](https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/linking-a-pull-request-to-an-issue) + in the PR description. +* Describe what behavior is being changed or fixed. +* (If applicable) describe the impact on formatting. Does your change affect: + * Only unstable options? If so, which ones? + * Stable options? If so, which ones? For which values of the stable options? + * Stable default formatting? If so, which style edition(s)? +* (If applicable) for non-trivial fixes, discuss your solution. + * How does your solution address the problem? + * What are the tradeoffs and shortcomings of your approach? +* (If applicable) note unresolved questions. + +#### CI + +* PRs automatically receive CI testing: + * The main test suites. + * A subset of clippy lints enabled for the rustfmt repository. +* Reviewers may additionally run Diff Check on your PR against a selection of + ecosystem repositories. + +### PR review + +#### Explicitly assigning a reviewer + +You don't need to explicitly request a reviewer. + +If a reviewer signalled that they want to specifically be assigned to a PR, you +can assign them via `r? @`. + +#### Waiting for reviews + +Reviewers are often working at capacity, and many of them are contributing on a +volunteer basis. There is limited review bandwidth, so please bear with us and +be patient. + +> [!NOTE] +> +> In order to minimize review delays, pull request authors and assigned +> reviewers should ensure that the PR status label stays updated, invoking these +> commands when appropriate: +> +> * `@rustbot author`: the review is finished, and the PR author should check +> the comments and take action accordingly. +> * `@rustbot ready`: the author is ready for a review, and this PR will be +> queued again in the reviewer’s queue. + +### After merge + +#### Reverting a PR + +If a PR is found to have caused a meaningful unanticipated regression, the best +policy is to revert it quickly and re-land it later once a fix and regression +test are added. + +A "meaningful regression" in this case is up to the judgment of the person +approving the revert. + +We prefer a reliability posture and revert in case of uncertainty. This has +three main benefits: + +* It allows bleeding-edge users (especially nightly or beta) to continue to use + and report bugs on HEAD with a higher degree of certainty about where new bugs + are introduced. +* It takes pressure off the original PR author and the team, so that no one + feels they must fix it *immediately*. +* It might prevent the significant bug or regression from reaching another + nightly/beta/stable build. + +> [!NOTE] +> +> Fear not! Regressions *will* happen. Please rest assured that this does not +> represent a negative judgment of your contribution or ability to contribute +> positively to rustfmt in the future. We simply want to prioritize keeping +> existing use cases working and keeping rustfmt stable for everyone. + ## Fuzzing guidelines rustfmt broadly follows the same fuzzing guidelines as rustc. Please consult the From b272a9638d86ca8029ca5daed394e46d259a7e83 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 9 Nov 2026 20:50:18 -0500 Subject: [PATCH 18/41] test: rework `--print-config current` tests and add #[nightly_only_test] annotation These tests were changed to use `file!()` instead of `.`. Using `file!()` will ensure that rustfmt's `rustfmt.toml` is loaded even when running in r-l/r's CI. As a result, we now need to use `#[nightly_only_test]` since unstable option's are set in rustfmt's `rustfmt.toml`. Although this doesn't fully address the `--print-config current` issue, preventing the wrong `rustfmt.toml` from loading should help us prevent another case like rust-lang/rust 165713. --- src/tools/rustfmt/tests/rustfmt/main.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/tools/rustfmt/tests/rustfmt/main.rs b/src/tools/rustfmt/tests/rustfmt/main.rs index 03a23a2653af8..5f650519dadd5 100644 --- a/src/tools/rustfmt/tests/rustfmt/main.rs +++ b/src/tools/rustfmt/tests/rustfmt/main.rs @@ -135,12 +135,16 @@ fn print_config_writes_to_file() { assert_eq!(exit_code, 0); } +// Can only run this test on nightly becuase the call to `file!` below +// will cause the root `rustfmt.toml` to be loaded, which sets nightly-only options. +#[nightly_only_test] #[test] fn print_config_merges_override_from_args() { let args = &[ "--print-config", "current", - ".", + // running with `file!` will load the root `rustfmt.toml` + file!(), "--config=color=Never,edition=2018", ]; @@ -154,12 +158,16 @@ fn print_config_merges_override_from_args() { assert_eq!(exit_code, 0); } +// Can only run this test on nightly becuase the call to `file!` below +// will cause the root `rustfmt.toml` to be loaded, which sets nightly-only options. +#[nightly_only_test] #[test] fn print_config_merges_multiple_overrides_from_args() { let args = &[ "--print-config", "current", - ".", + // running with `file!` will load the root `rustfmt.toml` + file!(), "--config", "color=never,edition=2018", "--config", From 589d9980fe8ab6a338a03e92e35bed195e6f0fae Mon Sep 17 00:00:00 2001 From: Alexey Date: Mon, 19 Oct 2026 06:28:27 +0300 Subject: [PATCH 19/41] Don't split link destinations when wrap_comments is enabled --- src/tools/rustfmt/Configurations.md | 1 + src/tools/rustfmt/src/comment.rs | 15 ++++++++++++++- src/tools/rustfmt/tests/target/issue-7177.rs | 18 ++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 src/tools/rustfmt/tests/target/issue-7177.rs diff --git a/src/tools/rustfmt/Configurations.md b/src/tools/rustfmt/Configurations.md index f0773dd150096..7356e2bfc29cc 100644 --- a/src/tools/rustfmt/Configurations.md +++ b/src/tools/rustfmt/Configurations.md @@ -3301,6 +3301,7 @@ Break comments to fit on the line Note that no wrapping will happen if: 1. The comment is the start of a markdown header doc comment 2. A URL was found in the comment +3. An inline link like fragment was found in the comment - **Default value**: `false` - **Possible values**: `true`, `false` diff --git a/src/tools/rustfmt/src/comment.rs b/src/tools/rustfmt/src/comment.rs index 516cc730256ed..0f45112bba7ed 100644 --- a/src/tools/rustfmt/src/comment.rs +++ b/src/tools/rustfmt/src/comment.rs @@ -842,13 +842,16 @@ impl<'a> CommentRewrite<'a> { // 1) wrap_comments = true is configured // 2) The comment is not the start of a markdown header doc comment // 3) The comment width exceeds the shape's width - // 4) No URLS were found in the comment + // 4) No URLs were found in the comment + // 5) No inline links were found (the pattern is `](...)`) + // 6) The comment is not a table item // If this changes, the documentation in ../Configurations.md#wrap_comments // should be changed accordingly. let should_wrap_comment = self.fmt.config.wrap_comments() && !is_markdown_header_doc_comment && unicode_str_width(line) > self.fmt.shape.width && !has_url(line) + && !is_inline_link(line) && !is_table_item(line); if should_wrap_comment { @@ -979,6 +982,16 @@ fn trim_custom_comment_prefix(s: &str) -> String { .join("\n") } +/// Returns `true` if the given string includes link-like fragments. +/// The pattern is `](...)` +fn is_inline_link(s: &str) -> bool { + if let Some(start) = s.find("](") { + let after = &s[start + 2..]; + return after.contains(')'); + } + false +} + /// Returns `true` if the given string MAY include URLs or alike. fn has_url(s: &str) -> bool { // A regex matching reference doc links. diff --git a/src/tools/rustfmt/tests/target/issue-7177.rs b/src/tools/rustfmt/tests/target/issue-7177.rs new file mode 100644 index 0000000000000..f6de651539413 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-7177.rs @@ -0,0 +1,18 @@ +//@ rustfmt-wrap_comments: true + +pub mod email { + /// A. [`queue_user_requested_email_otp`](fn@super::queue_user_requested_email_otp), over the channel. + pub fn a() {} + + /// B. [`queue_user_requested_email_otp`](struct@super::QueueUserRequestedEmailOtp), over the channel. + pub fn b() {} + + /// C. [`queue_user_requested_email_otp`](super::queue_user_requested_email_otp_abc), over the channel. + pub fn c() {} + + /// D. [`queue_user_requested_email_otp`](some/path/queue_user_requested_email_otp.html), over it. + pub fn d() {} + + /// E. [`queue_user_requested_email_otp`](https://example.com/queue_user_requested_email), over it. + pub fn e() {} +} From df4a692fea443a3b05abff28ee4d0415fb84b08f Mon Sep 17 00:00:00 2001 From: shulaoda <165626830+shulaoda@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:03:49 +0800 Subject: [PATCH 20/41] test: snapshot current whitespace before a skipped impl item --- src/tools/rustfmt/tests/source/issue-5521.rs | 29 ++++++++++++++++++++ src/tools/rustfmt/tests/target/issue-5521.rs | 29 ++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 src/tools/rustfmt/tests/source/issue-5521.rs create mode 100644 src/tools/rustfmt/tests/target/issue-5521.rs diff --git a/src/tools/rustfmt/tests/source/issue-5521.rs b/src/tools/rustfmt/tests/source/issue-5521.rs new file mode 100644 index 0000000000000..db349d01aa5de --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-5521.rs @@ -0,0 +1,29 @@ +// Whitespace on the otherwise blank line before a `#[rustfmt::skip]` item has to be +// removed regardless of how many whitespace characters it is made of. +impl Even for Foo { + const FAIL: &'static str = ""; + + #[rustfmt::skip] + fn to_style(&self, template: &str) {} +} + +impl Odd for Foo { + const FAIL: &'static str = ""; + + #[rustfmt::skip] + fn to_style(&self, template: &str) {} +} + +impl Single for Foo { + const FAIL: &'static str = ""; + + #[rustfmt::skip] + fn to_style(&self, template: &str) {} +} + +impl Tabs for Foo { + const FAIL: &'static str = ""; + + #[rustfmt::skip] + fn to_style(&self, template: &str) {} +} diff --git a/src/tools/rustfmt/tests/target/issue-5521.rs b/src/tools/rustfmt/tests/target/issue-5521.rs new file mode 100644 index 0000000000000..1b9882a56236f --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-5521.rs @@ -0,0 +1,29 @@ +// Whitespace on the otherwise blank line before a `#[rustfmt::skip]` item has to be +// removed regardless of how many whitespace characters it is made of. +impl Even for Foo { + const FAIL: &'static str = ""; + + #[rustfmt::skip] + fn to_style(&self, template: &str) {} +} + +impl Odd for Foo { + const FAIL: &'static str = ""; + + #[rustfmt::skip] + fn to_style(&self, template: &str) {} +} + +impl Single for Foo { + const FAIL: &'static str = ""; + + #[rustfmt::skip] + fn to_style(&self, template: &str) {} +} + +impl Tabs for Foo { + const FAIL: &'static str = ""; + + #[rustfmt::skip] + fn to_style(&self, template: &str) {} +} From 19bbac1560fd1c70fced56f7561bba8308b9dfef Mon Sep 17 00:00:00 2001 From: Matthew Hughes Date: Sat, 31 Oct 2026 15:51:50 +0000 Subject: [PATCH 21/41] tests: fix up some line endings There are some test files that used `newline_style=Windows` but never actually added those line endings in the corresponding `target`. In these cases carriage returns are added to the `target` files, but not the `source` ones we also assert that we do indeed convert the line endings. The files `tests/{target,source}/configs/enum_discrim_align_threshold/40.rs` had CRLF line endings, but no corresponding `newline_style` option and the feature does not depend on line endings, so these were converted back to use Unix line endings The `empty_file` test was split up since the behaviour depends on the system we're running on: `formatting::newline_style::auto_detect_newline_style` defaults to `Native` when it can't determine which style to use, when the file is empty we hit this behaviour. And `CRLF` endings were removed from `tests/writemode/target/stdin.xml`, these endings were added with 34d374ee5d23951d166ca3f51d477ddf6526a2fa but looks to be accidental, nothing about the library code change in that commit required these endings. --- src/tools/rustfmt/.gitattributes | 9 ++- src/tools/rustfmt/src/test/mod.rs | 3 + .../enum_discrim_align_threshold/40.rs | 68 +++++++++---------- .../enum_discrim_align_threshold/40.rs | 68 +++++++++---------- .../tests/target/format_strings/issue-3263.rs | 52 +++++++------- src/tools/rustfmt/tests/target/issue-2641.rs | 6 +- src/tools/rustfmt/tests/target/issue-2728.rs | 16 ++--- src/tools/rustfmt/tests/target/issue-2810.rs | 28 ++++---- src/tools/rustfmt/tests/target/issue-3265.rs | 28 ++++---- .../preserves_carriage_return_for_windows.rs | 4 +- .../rustfmt/tests/writemode/target/stdin.xml | 4 +- 11 files changed, 147 insertions(+), 139 deletions(-) diff --git a/src/tools/rustfmt/.gitattributes b/src/tools/rustfmt/.gitattributes index 91df4f0eb18dc..5b9b5bf1afbec 100644 --- a/src/tools/rustfmt/.gitattributes +++ b/src/tools/rustfmt/.gitattributes @@ -1,7 +1,12 @@ * text=auto eol=lf tests/source/issue-3494/crlf.rs -text tests/source/comment_crlf_newline.rs -text -tests/source/configs/enum_discrim_align_threshold/40.rs -text tests/target/issue-3494/crlf.rs -text tests/target/comment_crlf_newline.rs -text -tests/target/configs/enum_discrim_align_threshold/40.rs -text + +tests/target/format_strings/issue-3263.rs -text +tests/target/issue-3265.rs -text +tests/target/issue-2810.rs -text +tests/target/issue-2728.rs -text +tests/target/issue-2641.rs -text +tests/target/preserves_carriage_return_for_windows.rs -text diff --git a/src/tools/rustfmt/src/test/mod.rs b/src/tools/rustfmt/src/test/mod.rs index 5d5be709e5fb5..177326b67d4bb 100644 --- a/src/tools/rustfmt/src/test/mod.rs +++ b/src/tools/rustfmt/src/test/mod.rs @@ -51,6 +51,9 @@ const FILE_SKIP_LIST: &[&str] = &[ "cfg_mod/foo.rs", "cfg_mod/wasm32.rs", "skip/foo.rs", + // BUG rustfmt#7238: empty file formatting on Windows is not idempotent + #[cfg(windows)] + "empty_file.rs", ]; fn init_log() { diff --git a/src/tools/rustfmt/tests/source/configs/enum_discrim_align_threshold/40.rs b/src/tools/rustfmt/tests/source/configs/enum_discrim_align_threshold/40.rs index db67c4409c25b..f010604a6acc0 100644 --- a/src/tools/rustfmt/tests/source/configs/enum_discrim_align_threshold/40.rs +++ b/src/tools/rustfmt/tests/source/configs/enum_discrim_align_threshold/40.rs @@ -1,34 +1,34 @@ -//@ rustfmt-enum_discrim_align_threshold: 40 - -enum Standard { - A = 1, - Bcdef = 2, -} - -enum NoDiscrims { - ThisIsAFairlyLongEnumVariantWithoutDiscrimLongerThan40, - A = 1, - ThisIsAnotherFairlyLongEnumVariantWithoutDiscrimLongerThan40, - Bcdef = 2, -} - -enum TooLong { - ThisOneHasDiscrimAaaaaaaaaaaaaaaaaaaaaaChar40 = 10, - A = 1, - Bcdef = 2, -} - -enum Borderline { - ThisOneHasDiscrimAaaaaaaaaaaaaaaaaaaaaa = 10, - A = 1, - Bcdef = 2, -} - -// Live specimen from #1686 -enum LongWithSmallDiff { - SceneColorimetryEstimates = 0x73636F65, - SceneAppearanceEstimates = 0x73617065, - FocalPlaneColorimetryEstimates = 0x66706365, - ReflectionHardcopyOriginalColorimetry = 0x72686F63, - ReflectionPrintOutputColorimetry = 0x72706F63, -} \ No newline at end of file +//@ rustfmt-enum_discrim_align_threshold: 40 + +enum Standard { + A = 1, + Bcdef = 2, +} + +enum NoDiscrims { + ThisIsAFairlyLongEnumVariantWithoutDiscrimLongerThan40, + A = 1, + ThisIsAnotherFairlyLongEnumVariantWithoutDiscrimLongerThan40, + Bcdef = 2, +} + +enum TooLong { + ThisOneHasDiscrimAaaaaaaaaaaaaaaaaaaaaaChar40 = 10, + A = 1, + Bcdef = 2, +} + +enum Borderline { + ThisOneHasDiscrimAaaaaaaaaaaaaaaaaaaaaa = 10, + A = 1, + Bcdef = 2, +} + +// Live specimen from #1686 +enum LongWithSmallDiff { + SceneColorimetryEstimates = 0x73636F65, + SceneAppearanceEstimates = 0x73617065, + FocalPlaneColorimetryEstimates = 0x66706365, + ReflectionHardcopyOriginalColorimetry = 0x72686F63, + ReflectionPrintOutputColorimetry = 0x72706F63, +} diff --git a/src/tools/rustfmt/tests/target/configs/enum_discrim_align_threshold/40.rs b/src/tools/rustfmt/tests/target/configs/enum_discrim_align_threshold/40.rs index 14f68ecc6c48b..af739a9985c68 100644 --- a/src/tools/rustfmt/tests/target/configs/enum_discrim_align_threshold/40.rs +++ b/src/tools/rustfmt/tests/target/configs/enum_discrim_align_threshold/40.rs @@ -1,34 +1,34 @@ -//@ rustfmt-enum_discrim_align_threshold: 40 - -enum Standard { - A = 1, - Bcdef = 2, -} - -enum NoDiscrims { - ThisIsAFairlyLongEnumVariantWithoutDiscrimLongerThan40, - A = 1, - ThisIsAnotherFairlyLongEnumVariantWithoutDiscrimLongerThan40, - Bcdef = 2, -} - -enum TooLong { - ThisOneHasDiscrimAaaaaaaaaaaaaaaaaaaaaaChar40 = 10, - A = 1, - Bcdef = 2, -} - -enum Borderline { - ThisOneHasDiscrimAaaaaaaaaaaaaaaaaaaaaa = 10, - A = 1, - Bcdef = 2, -} - -// Live specimen from #1686 -enum LongWithSmallDiff { - SceneColorimetryEstimates = 0x73636F65, - SceneAppearanceEstimates = 0x73617065, - FocalPlaneColorimetryEstimates = 0x66706365, - ReflectionHardcopyOriginalColorimetry = 0x72686F63, - ReflectionPrintOutputColorimetry = 0x72706F63, -} +//@ rustfmt-enum_discrim_align_threshold: 40 + +enum Standard { + A = 1, + Bcdef = 2, +} + +enum NoDiscrims { + ThisIsAFairlyLongEnumVariantWithoutDiscrimLongerThan40, + A = 1, + ThisIsAnotherFairlyLongEnumVariantWithoutDiscrimLongerThan40, + Bcdef = 2, +} + +enum TooLong { + ThisOneHasDiscrimAaaaaaaaaaaaaaaaaaaaaaChar40 = 10, + A = 1, + Bcdef = 2, +} + +enum Borderline { + ThisOneHasDiscrimAaaaaaaaaaaaaaaaaaaaaa = 10, + A = 1, + Bcdef = 2, +} + +// Live specimen from #1686 +enum LongWithSmallDiff { + SceneColorimetryEstimates = 0x73636F65, + SceneAppearanceEstimates = 0x73617065, + FocalPlaneColorimetryEstimates = 0x66706365, + ReflectionHardcopyOriginalColorimetry = 0x72686F63, + ReflectionPrintOutputColorimetry = 0x72706F63, +} diff --git a/src/tools/rustfmt/tests/target/format_strings/issue-3263.rs b/src/tools/rustfmt/tests/target/format_strings/issue-3263.rs index a53ca7117faaf..a3faa7d825ca8 100644 --- a/src/tools/rustfmt/tests/target/format_strings/issue-3263.rs +++ b/src/tools/rustfmt/tests/target/format_strings/issue-3263.rs @@ -1,26 +1,26 @@ -//@ rustfmt-format_strings: true -//@ rustfmt-newline_style: Windows - -#[test] -fn compile_empty_program() { - let result = get_result(); - let expected = "; ModuleID = \'foo\' - -; Function Attrs: nounwind -declare void @llvm.memset.p0i8.i32(i8* nocapture, i8, i32, i32, i1) #0 - -declare i32 @write(i32, i8*, i32) - -declare i32 @putchar(i32) - -declare i32 @getchar() - -define i32 @main() { -entry: - ret i32 0 -} - -attributes #0 = { nounwind } -"; - assert_eq!(result, CString::new(expected).unwrap()); -} +//@ rustfmt-format_strings: true +//@ rustfmt-newline_style: Windows + +#[test] +fn compile_empty_program() { + let result = get_result(); + let expected = "; ModuleID = \'foo\' + +; Function Attrs: nounwind +declare void @llvm.memset.p0i8.i32(i8* nocapture, i8, i32, i32, i1) #0 + +declare i32 @write(i32, i8*, i32) + +declare i32 @putchar(i32) + +declare i32 @getchar() + +define i32 @main() { +entry: + ret i32 0 +} + +attributes #0 = { nounwind } +"; + assert_eq!(result, CString::new(expected).unwrap()); +} diff --git a/src/tools/rustfmt/tests/target/issue-2641.rs b/src/tools/rustfmt/tests/target/issue-2641.rs index fbf5326c330db..12d9e7906e8bb 100644 --- a/src/tools/rustfmt/tests/target/issue-2641.rs +++ b/src/tools/rustfmt/tests/target/issue-2641.rs @@ -1,3 +1,3 @@ -macro_rules! a { - () => {{}}; -} +macro_rules! a { + () => {{}}; +} diff --git a/src/tools/rustfmt/tests/target/issue-2728.rs b/src/tools/rustfmt/tests/target/issue-2728.rs index 24d9af4fd34ac..fd195ac8ec08e 100644 --- a/src/tools/rustfmt/tests/target/issue-2728.rs +++ b/src/tools/rustfmt/tests/target/issue-2728.rs @@ -1,8 +1,8 @@ -//@ rustfmt-wrap_comments: true -//@ rustfmt-newline_style: Windows - -//! ```rust -//! extern crate uom; -//! ``` - -fn main() {} +//@ rustfmt-wrap_comments: true +//@ rustfmt-newline_style: Windows + +//! ```rust +//! extern crate uom; +//! ``` + +fn main() {} diff --git a/src/tools/rustfmt/tests/target/issue-2810.rs b/src/tools/rustfmt/tests/target/issue-2810.rs index 79d3f1946177d..5e90ff87a03b2 100644 --- a/src/tools/rustfmt/tests/target/issue-2810.rs +++ b/src/tools/rustfmt/tests/target/issue-2810.rs @@ -1,14 +1,14 @@ -//@ rustfmt-newline_style: Windows - -#[macro_export] -macro_rules! hmmm___ffi_error { - ($result:ident) => { - pub struct $result { - success: bool, - } - - impl $result { - pub fn foo(self) {} - } - }; -} +//@ rustfmt-newline_style: Windows + +#[macro_export] +macro_rules! hmmm___ffi_error { + ($result:ident) => { + pub struct $result { + success: bool, + } + + impl $result { + pub fn foo(self) {} + } + }; +} diff --git a/src/tools/rustfmt/tests/target/issue-3265.rs b/src/tools/rustfmt/tests/target/issue-3265.rs index b3c4bb60d9a2d..8f2b7c1ded262 100644 --- a/src/tools/rustfmt/tests/target/issue-3265.rs +++ b/src/tools/rustfmt/tests/target/issue-3265.rs @@ -1,14 +1,14 @@ -//@ rustfmt-newline_style: Windows -#[cfg(test)] -mod test { - summary_test! { - tokenize_recipe_interpolation_eol, - "foo: # some comment - {{hello}} -", - "foo: \ - {{hello}} \ - {{ahah}}", - "N:#$>^{N}$<.", - } -} +//@ rustfmt-newline_style: Windows +#[cfg(test)] +mod test { + summary_test! { + tokenize_recipe_interpolation_eol, + "foo: # some comment + {{hello}} +", + "foo: \ + {{hello}} \ + {{ahah}}", + "N:#$>^{N}$<.", + } +} diff --git a/src/tools/rustfmt/tests/target/preserves_carriage_return_for_windows.rs b/src/tools/rustfmt/tests/target/preserves_carriage_return_for_windows.rs index 230275bf7253e..8ce3939ddcec7 100644 --- a/src/tools/rustfmt/tests/target/preserves_carriage_return_for_windows.rs +++ b/src/tools/rustfmt/tests/target/preserves_carriage_return_for_windows.rs @@ -1,2 +1,2 @@ -//@ rustfmt-newline_style: Windows -// Foo Bar +//@ rustfmt-newline_style: Windows +// Foo Bar diff --git a/src/tools/rustfmt/tests/writemode/target/stdin.xml b/src/tools/rustfmt/tests/writemode/target/stdin.xml index a7301bbc553c3..84091d36f30c0 100644 --- a/src/tools/rustfmt/tests/writemode/target/stdin.xml +++ b/src/tools/rustfmt/tests/writemode/target/stdin.xml @@ -1,2 +1,2 @@ - - + + From de113abe09c24567ddfb8f67bb2ff849663b9e47 Mon Sep 17 00:00:00 2001 From: Matthew Hughes Date: Sat, 31 Oct 2026 15:51:50 +0000 Subject: [PATCH 22/41] system/idempotence tests: also assert on line endings While working on rust-lang/rustfmt#7220 I got curious about how the integration tests handle line endings, specifically CRLF, and it turns out they don't. Given we have features that explicitly add/remove these line endings we should ensure the tests correctly cover this case to avoid regressions. We use `diff::lines` to generate diffs, and this calls `str::lines` under the hood, which strip any trailing `\r\n` or `\n`. So the only way we can tell that line-endings differ is by comparing the two contents, previously we performed this comparison in a way that would ignore if one file had `\r\n` endings and another had `\n` endings. This meant we never actually asserted that we saw the expected line endings. Note: we can only tell the files have differing line endings, not the lines where this occurs. It _could_ be a future improvement to make this more specific, but I think the approach is reasonable since there aren't any tests (or really any use case) for mixed line-endings in a single file. This reflects the behaviour of how we report such errors with e.g. `emitter::diff::DiffEmitter::emit_formatted_file` --- src/tools/rustfmt/src/test/mod.rs | 108 +++++++++++++----------------- 1 file changed, 46 insertions(+), 62 deletions(-) diff --git a/src/tools/rustfmt/src/test/mod.rs b/src/tools/rustfmt/src/test/mod.rs index 177326b67d4bb..e98d71dc8ff62 100644 --- a/src/tools/rustfmt/src/test/mod.rs +++ b/src/tools/rustfmt/src/test/mod.rs @@ -3,11 +3,10 @@ use std::collections::HashMap; use std::env; use std::fs; use std::io::{self, BufRead, BufReader, Read, Write}; -use std::iter::Peekable; use std::mem; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -use std::str::{Chars, FromStr}; +use std::str::FromStr; use std::thread; use crate::config::{Color, Config, EmitMode, FileName, NewlineStyle}; @@ -397,10 +396,9 @@ fn assert_output(source: &Path, expected_filename: &Path) { .read_to_string(&mut expected_text) .expect("Failed reading target"); - let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE); - if !compare.is_empty() { + if let Some(diff) = Diff::from_output(&expected_text, &output) { let mut failures = HashMap::new(); - failures.insert(source.to_owned(), compare); + failures.insert(source.to_owned(), diff); print_mismatches_default_message(failures); panic!("Text does not match expected output"); } @@ -444,10 +442,9 @@ fn assert_stdin_output( .expect("Failed reading target"); let output = String::from_utf8(buf).unwrap(); - let compare = make_diff(&expected_text, &output, DIFF_CONTEXT_SIZE); - if !compare.is_empty() { + if let Some(diff) = Diff::from_output(&expected_text, &output) { let mut failures = HashMap::new(); - failures.insert(source.to_owned(), compare); + failures.insert(source.to_owned(), diff); print_mismatches_default_message(failures); panic!("Text does not match expected output"); } @@ -852,7 +849,7 @@ fn check_files(files: Vec, opt_config: &Option) -> (Vec reports.push(report), Err(err) => { - if let IdempotentCheckError::Mismatch(msg) = err { + if let IdempotentCheckError::Mismatches(msg) = err { print_mismatches_default_message(msg); } fails += 1; @@ -865,11 +862,24 @@ fn check_files(files: Vec, opt_config: &Option) -> (Vec>) { - for (file_name, diff) in result { - let mismatch_msg_formatter = - |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num); - print_diff(diff, &mismatch_msg_formatter, &Default::default()); +fn print_mismatches_default_message(result: HashMap) { + for (file_name, mismatch) in result { + match mismatch { + Diff::Mismatches(diff) => { + let mismatch_msg_formatter = + |line_num| format!("\nMismatch at {}:{}:", file_name.display(), line_num); + print_diff(diff, &mismatch_msg_formatter, &Default::default()); + } + Diff::LineEndings() => { + let color = Config::default().color(); + let mut writer = OutputWriter::new(color); + let msg = format!( + "{}: line endings mismatch (maybe missing carriage returns?)", + file_name.display() + ); + writer.writeln(&msg, Some(term::color::RED)); + } + } } if let Some(mut t) = term::stdout() { @@ -961,8 +971,27 @@ fn format_file>(filepath: P, config: Config) -> (bool, SourceFi (parsing_errors, source_file, result) } +enum Diff { + Mismatches(Vec), + LineEndings(), +} + +impl Diff { + fn from_output(expected: &str, got: &str) -> Option { + if expected == got { + return None; + } + let mismatches = make_diff(expected, got, DIFF_CONTEXT_SIZE); + if mismatches.is_empty() { + Some(Self::LineEndings()) + } else { + Some(Self::Mismatches(mismatches)) + } + } +} + enum IdempotentCheckError { - Mismatch(HashMap>), + Mismatches(HashMap), Parse, } @@ -1115,17 +1144,11 @@ fn handle_result( let read_error = format!("failed reading target {target:?}"); f.read_to_string(&mut text).expect(&read_error); - // Ignore LF and CRLF difference for Windows. - if !string_eq_ignore_newline_repr(&fmt_text, &text) { + if let Some(diff) = Diff::from_output(&text, &fmt_text) { if std::env::var_os("RUSTC_BLESS").is_some_and(|v| v != "0") { std::fs::write(target, fmt_text).unwrap(); continue; } - let diff = make_diff(&text, &fmt_text, DIFF_CONTEXT_SIZE); - assert!( - !diff.is_empty(), - "Empty diff? Maybe due to a missing a newline at the end of a file?" - ); failures.insert(file_name, diff); } } @@ -1133,7 +1156,7 @@ fn handle_result( if failures.is_empty() { Ok(()) } else { - Err(IdempotentCheckError::Mismatch(failures)) + Err(IdempotentCheckError::Mismatches(failures)) } } @@ -1189,45 +1212,6 @@ fn rustfmt_diff_no_diff_test() { assert_eq!(diff, vec![]); } -// Compare strings without distinguishing between CRLF and LF -fn string_eq_ignore_newline_repr(left: &str, right: &str) -> bool { - let left = CharsIgnoreNewlineRepr(left.chars().peekable()); - let right = CharsIgnoreNewlineRepr(right.chars().peekable()); - left.eq(right) -} - -struct CharsIgnoreNewlineRepr<'a>(Peekable>); - -impl<'a> Iterator for CharsIgnoreNewlineRepr<'a> { - type Item = char; - - fn next(&mut self) -> Option { - self.0.next().map(|c| { - if c == '\r' { - if *self.0.peek().unwrap_or(&'\0') == '\n' { - self.0.next(); - '\n' - } else { - '\r' - } - } else { - c - } - }) - } -} - -#[test] -fn string_eq_ignore_newline_repr_test() { - init_log(); - assert!(string_eq_ignore_newline_repr("", "")); - assert!(!string_eq_ignore_newline_repr("", "abc")); - assert!(!string_eq_ignore_newline_repr("abc", "")); - assert!(string_eq_ignore_newline_repr("a\nb\nc\rd", "a\nb\r\nc\rd")); - assert!(string_eq_ignore_newline_repr("a\r\n\r\n\r\nb", "a\n\n\nb")); - assert!(!string_eq_ignore_newline_repr("a\r\nbcd", "a\nbcdefghijk")); -} - struct TempFile { path: PathBuf, } From cbb4ecbd802e7b8e56f1490cb968867a7632191e Mon Sep 17 00:00:00 2001 From: shulaoda <165626830+shulaoda@users.noreply.github.com> Date: Sun, 2 Aug 2026 04:25:30 +0800 Subject: [PATCH 23/41] Fix idempotency issue with raw strings --- src/tools/rustfmt/src/comment.rs | 15 ++++++++++++++- src/tools/rustfmt/tests/source/issue-6161.rs | 8 ++++++++ src/tools/rustfmt/tests/target/issue-6161.rs | 8 ++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 src/tools/rustfmt/tests/source/issue-6161.rs create mode 100644 src/tools/rustfmt/tests/target/issue-6161.rs diff --git a/src/tools/rustfmt/src/comment.rs b/src/tools/rustfmt/src/comment.rs index 0f45112bba7ed..618e1079b0c51 100644 --- a/src/tools/rustfmt/src/comment.rs +++ b/src/tools/rustfmt/src/comment.rs @@ -1414,7 +1414,6 @@ where match chr { '"' => { if sharps == 0 { - char_kind = FullCodeCharKind::Normal; CharClassesStatus::Normal } else if is_raw_string_suffix(&mut self.base, sharps) { CharClassesStatus::RawStringSuffix(sharps) @@ -1914,6 +1913,20 @@ mod test { assert_eq!(None, iter.next()); } + #[test] + fn char_classes_hashless_raw_string() { + let mut iter = CharClasses::new("r\"a\nb\",".chars()); + + assert_eq!((FullCodeCharKind::InString, 'r'), iter.next().unwrap()); + assert_eq!((FullCodeCharKind::InString, '"'), iter.next().unwrap()); + assert_eq!((FullCodeCharKind::InString, 'a'), iter.next().unwrap()); + assert_eq!((FullCodeCharKind::InString, '\n'), iter.next().unwrap()); + assert_eq!((FullCodeCharKind::InString, 'b'), iter.next().unwrap()); + assert_eq!((FullCodeCharKind::InString, '"'), iter.next().unwrap()); + assert_eq!((FullCodeCharKind::Normal, ','), iter.next().unwrap()); + assert_eq!(None, iter.next()); + } + #[test] fn comment_code_slices() { let input = "code(); /* test */ 1 + 1"; diff --git a/src/tools/rustfmt/tests/source/issue-6161.rs b/src/tools/rustfmt/tests/source/issue-6161.rs new file mode 100644 index 0000000000000..7bf46dd11d4ad --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6161.rs @@ -0,0 +1,8 @@ +fn f() { +my_macro! { + m => + "a": r"bb + ccc +", +}; +} diff --git a/src/tools/rustfmt/tests/target/issue-6161.rs b/src/tools/rustfmt/tests/target/issue-6161.rs new file mode 100644 index 0000000000000..2ba75c7387194 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6161.rs @@ -0,0 +1,8 @@ +fn f() { + my_macro! { + m => + "a": r"bb + ccc +", + }; +} From 0f686aeec52085aa3ed07cde8b71f55ba6c8913e Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Sun, 15 Nov 2026 15:58:45 -0500 Subject: [PATCH 24/41] test: add regression test for issue 4003 --- src/tools/rustfmt/tests/target/issue_4003.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 src/tools/rustfmt/tests/target/issue_4003.rs diff --git a/src/tools/rustfmt/tests/target/issue_4003.rs b/src/tools/rustfmt/tests/target/issue_4003.rs new file mode 100644 index 0000000000000..de08994a79b2f --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue_4003.rs @@ -0,0 +1,10 @@ +//@ rustfmt-match_arm_blocks: false + +fn main() { + match pos_iter.peek() { + Some(pos) if pos.0 != 0 => + add_paragraphs_to_map(&doc[0..pos.0], 0, current_level, &mut paragraphs), + None => add_paragraphs_to_map(doc, 0, current_level, &mut paragraphs), + _ => (), + } +} From 71840ed132cb2484775b0f454c236ecbac8f1235 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Sun, 15 Nov 2026 16:00:37 -0500 Subject: [PATCH 25/41] test: add regression test for issue 4844 --- src/tools/rustfmt/tests/source/issue_4844.rs | 10 ++++++++++ src/tools/rustfmt/tests/target/issue_4844.rs | 12 ++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 src/tools/rustfmt/tests/source/issue_4844.rs create mode 100644 src/tools/rustfmt/tests/target/issue_4844.rs diff --git a/src/tools/rustfmt/tests/source/issue_4844.rs b/src/tools/rustfmt/tests/source/issue_4844.rs new file mode 100644 index 0000000000000..d6aaedaaee2cd --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue_4844.rs @@ -0,0 +1,10 @@ +//@ rustfmt-control_brace_style: AlwaysNextLine +//@ rustfmt-match_arm_blocks: false + +fn main() { + let fooooooo = "100000000000000000000000"; + let _bar = match fooooooo { + "100000000000000000000000" => fooooooo.len() == 1 && fooooooo.contains("222222222222222222"), + _ => unreachable!("Should not happen"), + }; +} diff --git a/src/tools/rustfmt/tests/target/issue_4844.rs b/src/tools/rustfmt/tests/target/issue_4844.rs new file mode 100644 index 0000000000000..de1f2f1aa36a0 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue_4844.rs @@ -0,0 +1,12 @@ +//@ rustfmt-control_brace_style: AlwaysNextLine +//@ rustfmt-match_arm_blocks: false + +fn main() { + let fooooooo = "100000000000000000000000"; + let _bar = match fooooooo + { + "100000000000000000000000" => + fooooooo.len() == 1 && fooooooo.contains("222222222222222222"), + _ => unreachable!("Should not happen"), + }; +} From dd265a0384a93d65bb3f6c34965cacc1a1ab3f60 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Sun, 15 Nov 2026 16:01:30 -0500 Subject: [PATCH 26/41] test: add regression test for issue 4575 --- src/tools/rustfmt/tests/source/issue_4575.rs | 17 +++++++++++++++++ src/tools/rustfmt/tests/target/issue_4575.rs | 17 +++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 src/tools/rustfmt/tests/source/issue_4575.rs create mode 100644 src/tools/rustfmt/tests/target/issue_4575.rs diff --git a/src/tools/rustfmt/tests/source/issue_4575.rs b/src/tools/rustfmt/tests/source/issue_4575.rs new file mode 100644 index 0000000000000..cfc5a05862545 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue_4575.rs @@ -0,0 +1,17 @@ +//@ rustfmt-hard_tabs: true + +fn main() { + let condition_a = true; + let condition_b = false; + let x = 123.456789 + + if condition_a { + x + y + z + w + } else { + 123.456789 + } + + if condition_b { + x - y - z - w + } else { + 123.456789 + }; +} diff --git a/src/tools/rustfmt/tests/target/issue_4575.rs b/src/tools/rustfmt/tests/target/issue_4575.rs new file mode 100644 index 0000000000000..a3fba79485117 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue_4575.rs @@ -0,0 +1,17 @@ +//@ rustfmt-hard_tabs: true + +fn main() { + let condition_a = true; + let condition_b = false; + let x = 123.456789 + + if condition_a { + x + y + z + w + } else { + 123.456789 + } + + if condition_b { + x - y - z - w + } else { + 123.456789 + }; +} From c38505605626dee283983602426ac091f1a4c1bf Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Sun, 15 Nov 2026 16:02:10 -0500 Subject: [PATCH 27/41] test: add regression test for issue 5373 --- src/tools/rustfmt/tests/target/issue_5373.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 src/tools/rustfmt/tests/target/issue_5373.rs diff --git a/src/tools/rustfmt/tests/target/issue_5373.rs b/src/tools/rustfmt/tests/target/issue_5373.rs new file mode 100644 index 0000000000000..db317a9ab27ef --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue_5373.rs @@ -0,0 +1,11 @@ +fn foo() +where + for T: Clone, +{ +} + +fn bar() +where + T: for Clone, +{ +} From 2dc247379bb9e6061f9d248ad3667806e7015480 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Sun, 15 Nov 2026 16:03:47 -0500 Subject: [PATCH 28/41] test: add regression test for issue 5465 --- src/tools/rustfmt/tests/rustfmt/main.rs | 1 + src/tools/rustfmt/tests/target/issue_5465.rs | 1 + 2 files changed, 2 insertions(+) create mode 100644 src/tools/rustfmt/tests/target/issue_5465.rs diff --git a/src/tools/rustfmt/tests/rustfmt/main.rs b/src/tools/rustfmt/tests/rustfmt/main.rs index 5f650519dadd5..2e2f7fd453293 100644 --- a/src/tools/rustfmt/tests/rustfmt/main.rs +++ b/src/tools/rustfmt/tests/rustfmt/main.rs @@ -376,6 +376,7 @@ fn dont_emit_ICE() { "tests/target/issue_6082.rs", "tests/target/issue_6069.rs", "tests/target/issue-6105.rs", + "tests/target/issue_5465.rs", ]; let panic_re = regex::Regex::new("thread.*panicked").unwrap(); diff --git a/src/tools/rustfmt/tests/target/issue_5465.rs b/src/tools/rustfmt/tests/target/issue_5465.rs new file mode 100644 index 0000000000000..679ad30a71c0d --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue_5465.rs @@ -0,0 +1 @@ +m!(a. X::Y); From 4fef4cdd38a0b370f1b2cefcc4132d3e6e83de3e Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Sun, 15 Nov 2026 16:14:17 -0500 Subject: [PATCH 29/41] test: add regression test for issue 6016 --- src/tools/rustfmt/tests/target/issue_6016.rs | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 src/tools/rustfmt/tests/target/issue_6016.rs diff --git a/src/tools/rustfmt/tests/target/issue_6016.rs b/src/tools/rustfmt/tests/target/issue_6016.rs new file mode 100644 index 0000000000000..0b8a36ec4b451 --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue_6016.rs @@ -0,0 +1,9 @@ +//@ rustfmt-format_code_in_doc_comments: true + +//! Test test +//! +//! ``` +//! # fn main() { +//! println!("hello"); // Comment +//! # } +//! ``` From ee069a40f7e3f2bfe891b2617436a411e5f6d341 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Sun, 15 Nov 2026 16:18:04 -0500 Subject: [PATCH 30/41] test: add regression test for issue 4804 --- src/tools/rustfmt/tests/source/issue_4804.rs | 7 +++++++ src/tools/rustfmt/tests/target/issue_4804.rs | 7 +++++++ 2 files changed, 14 insertions(+) create mode 100644 src/tools/rustfmt/tests/source/issue_4804.rs create mode 100644 src/tools/rustfmt/tests/target/issue_4804.rs diff --git a/src/tools/rustfmt/tests/source/issue_4804.rs b/src/tools/rustfmt/tests/source/issue_4804.rs new file mode 100644 index 0000000000000..0560d9889e330 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue_4804.rs @@ -0,0 +1,7 @@ +//@ rustfmt-edition: 2024 + +fn trimGood() { + if let Some(q) = last && i != 0 { + + } +} diff --git a/src/tools/rustfmt/tests/target/issue_4804.rs b/src/tools/rustfmt/tests/target/issue_4804.rs new file mode 100644 index 0000000000000..f9b3d0fcfc23a --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue_4804.rs @@ -0,0 +1,7 @@ +//@ rustfmt-edition: 2024 + +fn trimGood() { + if let Some(q) = last + && i != 0 + {} +} From f4b11eac1e1458cf1d86e1b2be7f6eef9cd73ef1 Mon Sep 17 00:00:00 2001 From: shulaoda <165626830+shulaoda@users.noreply.github.com> Date: Sun, 26 Jul 2026 03:00:49 +0800 Subject: [PATCH 31/41] fix: don't leave trailing whitespace before a skipped impl item --- src/tools/rustfmt/src/missed_spans.rs | 4 ++-- src/tools/rustfmt/tests/target/issue-5521.rs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/tools/rustfmt/src/missed_spans.rs b/src/tools/rustfmt/src/missed_spans.rs index 8fd9cc026e6a4..989a5dde8f9cd 100644 --- a/src/tools/rustfmt/src/missed_spans.rs +++ b/src/tools/rustfmt/src/missed_spans.rs @@ -365,8 +365,8 @@ impl<'a> FmtVisitor<'a> { status.cur_line += 1; status.line_start = i + 1; - } else if c.is_whitespace() && status.last_wspace.is_none() { - status.last_wspace = Some(i); + } else if c.is_whitespace() { + status.last_wspace.get_or_insert(i); } else { status.last_wspace = None; } diff --git a/src/tools/rustfmt/tests/target/issue-5521.rs b/src/tools/rustfmt/tests/target/issue-5521.rs index 1b9882a56236f..ca04f079101bf 100644 --- a/src/tools/rustfmt/tests/target/issue-5521.rs +++ b/src/tools/rustfmt/tests/target/issue-5521.rs @@ -2,14 +2,14 @@ // removed regardless of how many whitespace characters it is made of. impl Even for Foo { const FAIL: &'static str = ""; - + #[rustfmt::skip] fn to_style(&self, template: &str) {} } impl Odd for Foo { const FAIL: &'static str = ""; - + #[rustfmt::skip] fn to_style(&self, template: &str) {} } @@ -23,7 +23,7 @@ impl Single for Foo { impl Tabs for Foo { const FAIL: &'static str = ""; - + #[rustfmt::skip] fn to_style(&self, template: &str) {} } From 8c84d1ea29c8590675269cb8806a123d65e33519 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Tue, 17 Nov 2026 09:58:11 +0800 Subject: [PATCH 32/41] refactor: consistently use "Diff Check" Rather than use "check_diff" in some places but "Diff Check" in other places. Was mildly annoying me :) --- .../rustfmt/.github/workflows/clippy.yml | 2 +- .../{check_diff.yml => diff_check.yml} | 10 +++--- src/tools/rustfmt/ci/src/build_and_test.rs | 2 +- .../rustfmt/ci/src/clippy_config_check.rs | 2 +- .../{check_diff => diff_check}/.gitignore | 0 .../{check_diff => diff_check}/Cargo.lock | 30 ++++++++-------- .../{check_diff => diff_check}/Cargo.toml | 2 +- .../{check_diff => diff_check}/src/lib.rs | 36 +++++++++---------- .../{check_diff => diff_check}/src/main.rs | 14 ++++---- .../tests/bash_commands.rs | 2 +- .../tests/diff_check.rs} | 14 ++++---- .../{check_diff => diff_check}/tests/git.rs | 2 +- src/tools/rustfmt/src/test/mod.rs | 2 +- src/tools/rustfmt/triagebot.toml | 2 +- 14 files changed, 60 insertions(+), 60 deletions(-) rename src/tools/rustfmt/.github/workflows/{check_diff.yml => diff_check.yml} (92%) rename src/tools/rustfmt/{check_diff => diff_check}/.gitignore (100%) rename src/tools/rustfmt/{check_diff => diff_check}/Cargo.lock (99%) rename src/tools/rustfmt/{check_diff => diff_check}/Cargo.toml (97%) rename src/tools/rustfmt/{check_diff => diff_check}/src/lib.rs (96%) rename src/tools/rustfmt/{check_diff => diff_check}/src/main.rs (95%) rename src/tools/rustfmt/{check_diff => diff_check}/tests/bash_commands.rs (88%) rename src/tools/rustfmt/{check_diff/tests/check_diff.rs => diff_check/tests/diff_check.rs} (87%) rename src/tools/rustfmt/{check_diff => diff_check}/tests/git.rs (94%) diff --git a/src/tools/rustfmt/.github/workflows/clippy.yml b/src/tools/rustfmt/.github/workflows/clippy.yml index fc3eb8916a6bd..a5689e5011150 100644 --- a/src/tools/rustfmt/.github/workflows/clippy.yml +++ b/src/tools/rustfmt/.github/workflows/clippy.yml @@ -31,9 +31,9 @@ jobs: matrix: package: - . # rustfmt - - check_diff - ci - config_proc_macro + - diff_check steps: - name: checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/src/tools/rustfmt/.github/workflows/check_diff.yml b/src/tools/rustfmt/.github/workflows/diff_check.yml similarity index 92% rename from src/tools/rustfmt/.github/workflows/check_diff.yml rename to src/tools/rustfmt/.github/workflows/diff_check.yml index 7f7bc62846a3c..d37ff65bbe5ff 100644 --- a/src/tools/rustfmt/.github/workflows/check_diff.yml +++ b/src/tools/rustfmt/.github/workflows/diff_check.yml @@ -54,14 +54,14 @@ jobs: with: persist-credentials: false - - name: Build check_diff binary - working-directory: ./check_diff + - name: Build diff_check binary + working-directory: ./diff_check run: cargo build --release --locked - name: Run Diff Check - working-directory: ./check_diff + working-directory: ./diff_check env: - CHECK_DIFF_LOG: info + DIFF_CHECK_LOG: info GITHUB_EVENT_INPUTS_COMMIT_HASH: ${{ github.event.inputs.commit_hash }} GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS: ${{ github.event.inputs.rustfmt_configs }} GITHUB_EVENT_INPUTS_CLONE_URL: ${{ github.event.inputs.clone_url }} @@ -80,7 +80,7 @@ jobs: OPTIONS+="--rustfmt-config ${GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS} " fi - target/release/check_diff ${GITHUB_EVENT_INPUTS_CLONE_URL} ${GITHUB_EVENT_INPUTS_BRANCH_NAME} \ + target/release/diff_check ${GITHUB_EVENT_INPUTS_CLONE_URL} ${GITHUB_EVENT_INPUTS_BRANCH_NAME} \ --edition ${GITHUB_EVENT_INPUTS_LANGUAGE_EDITION} \ --style-edition ${GITHUB_EVENT_INPUTS_STYLE_EDITION} \ $OPTIONS diff --git a/src/tools/rustfmt/ci/src/build_and_test.rs b/src/tools/rustfmt/ci/src/build_and_test.rs index 3033577596d08..5368c0372b595 100644 --- a/src/tools/rustfmt/ci/src/build_and_test.rs +++ b/src/tools/rustfmt/ci/src/build_and_test.rs @@ -43,7 +43,7 @@ pub fn runner() -> Result<(), String> { // Build and test config_proc_macro run_tests_in_dir(&env, "config_proc_macro")?; - run_tests_in_dir(&env, "check_diff")?; + run_tests_in_dir(&env, "diff_check")?; Ok(()) } diff --git a/src/tools/rustfmt/ci/src/clippy_config_check.rs b/src/tools/rustfmt/ci/src/clippy_config_check.rs index c4c59f692f637..791b4970a7940 100644 --- a/src/tools/rustfmt/ci/src/clippy_config_check.rs +++ b/src/tools/rustfmt/ci/src/clippy_config_check.rs @@ -4,9 +4,9 @@ use itertools::Itertools; const CARGO_TOMLS: &[&'static str] = &[ "Cargo.toml", - "check_diff/Cargo.toml", "ci/Cargo.toml", "config_proc_macro/Cargo.toml", + "diff_check/Cargo.toml", ]; pub(crate) fn runner() -> Result<(), String> { diff --git a/src/tools/rustfmt/check_diff/.gitignore b/src/tools/rustfmt/diff_check/.gitignore similarity index 100% rename from src/tools/rustfmt/check_diff/.gitignore rename to src/tools/rustfmt/diff_check/.gitignore diff --git a/src/tools/rustfmt/check_diff/Cargo.lock b/src/tools/rustfmt/diff_check/Cargo.lock similarity index 99% rename from src/tools/rustfmt/check_diff/Cargo.lock rename to src/tools/rustfmt/diff_check/Cargo.lock index 1c76fa1e9faa5..33dc913796b8c 100644 --- a/src/tools/rustfmt/check_diff/Cargo.lock +++ b/src/tools/rustfmt/diff_check/Cargo.lock @@ -82,21 +82,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" -[[package]] -name = "check_diff" -version = "0.1.0" -dependencies = [ - "clap", - "crossbeam-channel", - "diffy", - "ignore", - "tempfile", - "toml", - "tracing", - "tracing-subscriber", - "walkdir", -] - [[package]] name = "clap" version = "4.5.4" @@ -177,6 +162,21 @@ version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +[[package]] +name = "diff_check" +version = "0.1.0" +dependencies = [ + "clap", + "crossbeam-channel", + "diffy", + "ignore", + "tempfile", + "toml", + "tracing", + "tracing-subscriber", + "walkdir", +] + [[package]] name = "diffy" version = "0.4.0" diff --git a/src/tools/rustfmt/check_diff/Cargo.toml b/src/tools/rustfmt/diff_check/Cargo.toml similarity index 97% rename from src/tools/rustfmt/check_diff/Cargo.toml rename to src/tools/rustfmt/diff_check/Cargo.toml index b18aa0c39d02a..5820be3dddcfc 100644 --- a/src/tools/rustfmt/check_diff/Cargo.toml +++ b/src/tools/rustfmt/diff_check/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "check_diff" +name = "diff_check" version = "0.1.0" edition = "2021" diff --git a/src/tools/rustfmt/check_diff/src/lib.rs b/src/tools/rustfmt/diff_check/src/lib.rs similarity index 96% rename from src/tools/rustfmt/check_diff/src/lib.rs rename to src/tools/rustfmt/diff_check/src/lib.rs index 23ef06c03a01d..c1de7743e1bc8 100644 --- a/src/tools/rustfmt/check_diff/src/lib.rs +++ b/src/tools/rustfmt/diff_check/src/lib.rs @@ -148,7 +148,7 @@ pub enum CreateDiffError { } #[derive(Debug)] -pub enum CheckDiffError { +pub enum DiffCheckError { /// Git related errors FailedGit(GitError), /// Error for generic commands @@ -162,15 +162,15 @@ pub enum CheckDiffError { IO(std::io::Error), } -impl From for CheckDiffError { +impl From for DiffCheckError { fn from(error: io::Error) -> Self { - CheckDiffError::IO(error) + DiffCheckError::IO(error) } } -impl From for CheckDiffError { +impl From for DiffCheckError { fn from(error: GitError) -> Self { - CheckDiffError::FailedGit(error) + DiffCheckError::FailedGit(error) } } @@ -265,7 +265,7 @@ where } impl RustfmtRunner { - fn get_binary_version(&self) -> Result { + fn get_binary_version(&self) -> Result { let Ok(command) = Command::new(&self.binary_path) .env( dynamic_library_path_env_var_name(), @@ -274,7 +274,7 @@ impl RustfmtRunner { .args(["--version"]) .output() else { - return Err(CheckDiffError::FailedBinaryVersioning( + return Err(DiffCheckError::FailedBinaryVersioning( self.binary_path.clone(), )); }; @@ -572,22 +572,22 @@ pub fn change_directory_to_path(dest: &Path) -> io::Result<()> { Ok(()) } -pub fn get_dynamic_library_path(dir: &Path) -> Result { +pub fn get_dynamic_library_path(dir: &Path) -> Result { let Ok(command) = Command::new("rustc") .current_dir(dir) .args(["--print", "sysroot"]) .output() else { - return Err(CheckDiffError::FailedCommand("Error getting sysroot")); + return Err(DiffCheckError::FailedCommand("Error getting sysroot")); }; let mut sysroot = buffer_into_utf8_lossy(command.stdout); sysroot.push_str("/lib"); Ok(sysroot) } -pub fn get_cargo_version() -> Result { +pub fn get_cargo_version() -> Result { let Ok(command) = Command::new("cargo").args(["--version"]).output() else { - return Err(CheckDiffError::FailedCargoVersion( + return Err(DiffCheckError::FailedCargoVersion( "Failed to obtain cargo version", )); }; @@ -604,7 +604,7 @@ pub fn build_rustfmt_from_src>( style_edition: StyleEdition, config: Option<&[T]>, release_channel: ReleaseChannel, -) -> Result { +) -> Result { // Because we're building standalone binaries we need to set the dynamic library path // so each rustfmt binary can find it's runtime dependencies. let dynamic_library_path = get_dynamic_library_path(dir)?; @@ -617,7 +617,7 @@ pub fn build_rustfmt_from_src>( .args(["build", "--locked", "-q", "--release", "--bin", "rustfmt"]) .output() else { - return Err(CheckDiffError::FailedSourceBuild( + return Err(DiffCheckError::FailedSourceBuild( "Error building rustfmt from source", )); }; @@ -646,7 +646,7 @@ pub fn compile_rustfmt>( commit_hash: Option, config: Option<&[T]>, release_channel: ReleaseChannel, -) -> Result, CheckDiffError> { +) -> Result, DiffCheckError> { const RUSTFMT_REPO: &str = "https://github.com/rust-lang/rustfmt.git"; let checkout_ref = commit_hash.as_ref().unwrap_or(&feature_branch); @@ -769,7 +769,7 @@ where } } -/// Encapsulate the logic used to clone repositories for the diff check +/// Encapsulate the logic used to clone repositories for the Diff Check pub fn clone_repositories_for_diff_check( repositories: &[&str], ) -> Vec> { @@ -818,7 +818,7 @@ pub fn clone_repositories_for_diff_check( /// Calculates the number of errors when running the compiled binary and the target binary on the /// repo specified with the specific configs. -pub fn check_diff_for_file<'repo, P: AsRef, F: AsRef>( +pub fn diff_check_for_file<'repo, P: AsRef, F: AsRef>( diff_checker: &DiffChecker, repo: &'repo Repository

, file: F, @@ -885,7 +885,7 @@ pub fn get_repo_name(git_url: &str) -> &str { repo_name } -pub fn check_diff<'repo, P, S, T>( +pub fn diff_check<'repo, P, S, T>( diff_checker: &DiffChecker, repositories: &'repo [Repository

], worker_threads: std::num::NonZeroU8, @@ -924,7 +924,7 @@ where let rx = rx.clone(); s.spawn(move || { while let Ok((file, repo)) = rx.recv() { - if let Err(e) = check_diff_for_file(diff_checker, repo, file) { + if let Err(e) = diff_check_for_file(diff_checker, repo, file) { // Push errors to report on later errors.lock().unwrap().push(e); } diff --git a/src/tools/rustfmt/check_diff/src/main.rs b/src/tools/rustfmt/diff_check/src/main.rs similarity index 95% rename from src/tools/rustfmt/check_diff/src/main.rs rename to src/tools/rustfmt/diff_check/src/main.rs index d283700c41770..36bd1ba0ef588 100644 --- a/src/tools/rustfmt/check_diff/src/main.rs +++ b/src/tools/rustfmt/diff_check/src/main.rs @@ -1,11 +1,11 @@ use std::io::Error; use std::process::ExitCode; -use check_diff::{ - Edition, ReleaseChannel, StyleEdition, check_diff, clone_repositories_for_diff_check, - compile_rustfmt, -}; use clap::Parser; +use diff_check::{ + Edition, ReleaseChannel, StyleEdition, clone_repositories_for_diff_check, compile_rustfmt, + diff_check, +}; use tempfile::tempdir; use tracing::{error, info}; @@ -51,7 +51,7 @@ const REPOS: &[&str] = &[ "https://github.com/unicode-rs/unicode-xid.git", ]; -/// Inputs for the check_diff script +/// Inputs for the Diff Check script #[derive(Parser)] struct CliInputs { /// Git url of a rustfmt fork to compare against the latest main rustfmt @@ -81,7 +81,7 @@ struct CliInputs { fn main() -> Result { tracing_subscriber::fmt() - .with_env_filter(tracing_subscriber::EnvFilter::from_env("CHECK_DIFF_LOG")) + .with_env_filter(tracing_subscriber::EnvFilter::from_env("DIFF_CHECK_LOG")) .init(); let args = CliInputs::parse(); let tmp_dir = tempdir()?; @@ -110,7 +110,7 @@ fn main() -> Result { let repositories = clone_repositories_for_diff_check(REPOS); info!("Starting the Diff Check"); - let errors = check_diff(&diff_checker, &repositories, args.worker_threads); + let errors = diff_check(&diff_checker, &repositories, args.worker_threads); if errors.is_empty() { info!("No diff found 😊"); diff --git a/src/tools/rustfmt/check_diff/tests/bash_commands.rs b/src/tools/rustfmt/diff_check/tests/bash_commands.rs similarity index 88% rename from src/tools/rustfmt/check_diff/tests/bash_commands.rs rename to src/tools/rustfmt/diff_check/tests/bash_commands.rs index 38ee34ef50354..04d881f31950a 100644 --- a/src/tools/rustfmt/check_diff/tests/bash_commands.rs +++ b/src/tools/rustfmt/diff_check/tests/bash_commands.rs @@ -1,4 +1,4 @@ -use check_diff::change_directory_to_path; +use diff_check::change_directory_to_path; use std::env; use tempfile::Builder; diff --git a/src/tools/rustfmt/check_diff/tests/check_diff.rs b/src/tools/rustfmt/diff_check/tests/diff_check.rs similarity index 87% rename from src/tools/rustfmt/check_diff/tests/check_diff.rs rename to src/tools/rustfmt/diff_check/tests/diff_check.rs index 8e0e9333d7c71..c009401c185fa 100644 --- a/src/tools/rustfmt/check_diff/tests/check_diff.rs +++ b/src/tools/rustfmt/diff_check/tests/diff_check.rs @@ -1,6 +1,6 @@ -use check_diff::{ - CheckDiffError, CodeFormatter, DiffChecker, FormatCodeError, Repository, RustFmtFileFinder, - check_diff, +use diff_check::{ + CodeFormatter, DiffCheckError, DiffChecker, FormatCodeError, Repository, RustFmtFileFinder, + diff_check, }; use std::fs::File; use tempfile::Builder; @@ -66,7 +66,7 @@ fn search_for_files_correctly_nested() -> Result<(), Box> } #[test] -fn check_diff_test_no_formatting_difference() -> Result<(), CheckDiffError> { +fn diff_check_test_no_formatting_difference() -> Result<(), DiffCheckError> { let diff_checker = DiffChecker::new(DoNothingFormatter, DoNothingFormatter); let dir = Builder::new().tempdir_in("").unwrap(); @@ -76,13 +76,13 @@ fn check_diff_test_no_formatting_difference() -> Result<(), CheckDiffError> { let repos = [repo]; let workers = std::num::NonZeroU8::new(1).unwrap(); - let errors = check_diff(&diff_checker, &repos, workers); + let errors = diff_check(&diff_checker, &repos, workers); assert_eq!(errors.len(), 0); Ok(()) } #[test] -fn check_diff_test_formatting_difference() -> Result<(), CheckDiffError> { +fn diff_check_test_formatting_difference() -> Result<(), DiffCheckError> { let diff_checker = DiffChecker::new(DoNothingFormatter, AddWhiteSpaceFormatter); let dir = Builder::new().tempdir_in("").unwrap(); let file_path = dir.path().join("test.rs"); @@ -91,7 +91,7 @@ fn check_diff_test_formatting_difference() -> Result<(), CheckDiffError> { let repos = [repo]; let workers = std::num::NonZeroU8::new(1).unwrap(); - let errors = check_diff(&diff_checker, &repos, workers); + let errors = diff_check(&diff_checker, &repos, workers); assert_ne!(errors.len(), 0); Ok(()) } diff --git a/src/tools/rustfmt/check_diff/tests/git.rs b/src/tools/rustfmt/diff_check/tests/git.rs similarity index 94% rename from src/tools/rustfmt/check_diff/tests/git.rs rename to src/tools/rustfmt/diff_check/tests/git.rs index 677c3840e1e37..801e1b4748286 100644 --- a/src/tools/rustfmt/check_diff/tests/git.rs +++ b/src/tools/rustfmt/diff_check/tests/git.rs @@ -1,4 +1,4 @@ -use check_diff::clone_git_repo; +use diff_check::clone_git_repo; use tempfile::Builder; diff --git a/src/tools/rustfmt/src/test/mod.rs b/src/tools/rustfmt/src/test/mod.rs index e98d71dc8ff62..b33d43cabffe2 100644 --- a/src/tools/rustfmt/src/test/mod.rs +++ b/src/tools/rustfmt/src/test/mod.rs @@ -487,7 +487,7 @@ fn self_tests() { files.push(path); } // for crates that need to be included but lies outside src - let external_crates = vec!["check_diff", "config_proc_macro", "ci"]; + let external_crates = vec!["diff_check", "config_proc_macro", "ci"]; for external_crate in external_crates { let mut path = PathBuf::from(external_crate); path.push("src"); diff --git a/src/tools/rustfmt/triagebot.toml b/src/tools/rustfmt/triagebot.toml index 7197066a41a98..e5007b50a14cb 100644 --- a/src/tools/rustfmt/triagebot.toml +++ b/src/tools/rustfmt/triagebot.toml @@ -57,8 +57,8 @@ exclude_labels = [ [autolabel."A-CI"] trigger_files = [ ".github/workflows", - "check_diff", "ci", + "diff_check", ] [autolabel."A-meta"] From afb52e892b76fc570377f36833e0e5d5cfcc5717 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Tue, 17 Nov 2026 10:31:49 +0800 Subject: [PATCH 33/41] ci: explicitly install rust toolchain Instead of relying on implicit toolchain installation via `rustup target add`. See . I was observing the warning in CI, example run . ``` warn: the missing active toolchain `nightly-2026-11-02-aarch64-apple-darwin` has been auto-installed warn: auto-installation is deprecated for most `rustup` commands warn: scripts relying on this behavior in `rustup` may stop working in the future warn: to install the active toolchain, use `rustup install` instead warn: see for more info info: downloading component rust-std ``` --- src/tools/rustfmt/.github/workflows/rustdoc_check.yml | 1 + src/tools/rustfmt/.github/workflows/test.yml | 2 ++ 2 files changed, 3 insertions(+) diff --git a/src/tools/rustfmt/.github/workflows/rustdoc_check.yml b/src/tools/rustfmt/.github/workflows/rustdoc_check.yml index e2b5e5a68ed71..f93de25fb5d5f 100644 --- a/src/tools/rustfmt/.github/workflows/rustdoc_check.yml +++ b/src/tools/rustfmt/.github/workflows/rustdoc_check.yml @@ -20,6 +20,7 @@ jobs: run: | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup-init.sh sh rustup-init.sh -y --default-toolchain none + rustup toolchain install rustup target add x86_64-unknown-linux-gnu - name: document rustfmt diff --git a/src/tools/rustfmt/.github/workflows/test.yml b/src/tools/rustfmt/.github/workflows/test.yml index dc295d8bfbda4..20986c8b74e48 100644 --- a/src/tools/rustfmt/.github/workflows/test.yml +++ b/src/tools/rustfmt/.github/workflows/test.yml @@ -54,6 +54,7 @@ jobs: Invoke-WebRequest https://win.rustup.rs/ -OutFile rustup-init.exe .\rustup-init.exe -y --default-host=x86_64-pc-windows-msvc --default-toolchain=none del rustup-init.exe + rustup toolchain install rustup target add ${env:MATRIX_TARGET} env: MATRIX_TARGET: ${{ matrix.target }} @@ -64,6 +65,7 @@ jobs: run: | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup-init.sh sh rustup-init.sh -y --default-toolchain none + rustup toolchain install rustup target add ${MATRIX_TARGET} env: MATRIX_TARGET: ${{ matrix.target }} From 7a89c4d140cdf75c1025a9fb91d3e8fdb58bc35e Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Tue, 17 Nov 2026 13:52:11 +0800 Subject: [PATCH 34/41] refactor: extract common workflow for diff check --- .../rustfmt/.github/workflows/diff_check.yml | 50 +++--------- .../.github/workflows/diff_check_common.yml | 78 +++++++++++++++++++ 2 files changed, 89 insertions(+), 39 deletions(-) create mode 100644 src/tools/rustfmt/.github/workflows/diff_check_common.yml diff --git a/src/tools/rustfmt/.github/workflows/diff_check.yml b/src/tools/rustfmt/.github/workflows/diff_check.yml index d37ff65bbe5ff..11d28a8ab471a 100644 --- a/src/tools/rustfmt/.github/workflows/diff_check.yml +++ b/src/tools/rustfmt/.github/workflows/diff_check.yml @@ -1,4 +1,4 @@ -name: Diff Check +name: Diff Check (Custom) on: workflow_dispatch: inputs: @@ -46,41 +46,13 @@ permissions: jobs: diff_check: - runs-on: ubuntu-latest - - steps: - - name: checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - name: Build diff_check binary - working-directory: ./diff_check - run: cargo build --release --locked - - - name: Run Diff Check - working-directory: ./diff_check - env: - DIFF_CHECK_LOG: info - GITHUB_EVENT_INPUTS_COMMIT_HASH: ${{ github.event.inputs.commit_hash }} - GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS: ${{ github.event.inputs.rustfmt_configs }} - GITHUB_EVENT_INPUTS_CLONE_URL: ${{ github.event.inputs.clone_url }} - GITHUB_EVENT_INPUTS_BRANCH_NAME: ${{ github.event.inputs.branch_name }} - GITHUB_EVENT_INPUTS_LANGUAGE_EDITION: ${{ github.event.inputs.language_edition }} - GITHUB_EVENT_INPUTS_STYLE_EDITION: ${{ github.event.inputs.style_edition }} - shell: bash - run: | - OPTIONS="" - - if [[ -n "${GITHUB_EVENT_INPUTS_COMMIT_HASH}" ]]; then - OPTIONS+="--commit-hash ${GITHUB_EVENT_INPUTS_COMMIT_HASH} " - fi - - if [[ -n "${GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS}" ]]; then - OPTIONS+="--rustfmt-config ${GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS} " - fi - - target/release/diff_check ${GITHUB_EVENT_INPUTS_CLONE_URL} ${GITHUB_EVENT_INPUTS_BRANCH_NAME} \ - --edition ${GITHUB_EVENT_INPUTS_LANGUAGE_EDITION} \ - --style-edition ${GITHUB_EVENT_INPUTS_STYLE_EDITION} \ - $OPTIONS + name: "Diff Check {Edition ${{ inputs.language_edition }}, Style Edition ${{ inputs.style_edition }}}" + uses: $/.github/workflows/diff_check_common.yml + with: + clone_url: ${{ inputs.clone_url }} + branch_name: ${{ inputs.branch_name }} + language_edition: ${{ inputs.language_edition }} + style_edition: ${{ inputs.style_edition }} + commit_hash: ${{ inputs.commit_hash }} + rustfmt_configs: ${{ inputs.rustfmt_configs }} + release_channel: ${{ inputs.release_channel }} diff --git a/src/tools/rustfmt/.github/workflows/diff_check_common.yml b/src/tools/rustfmt/.github/workflows/diff_check_common.yml new file mode 100644 index 0000000000000..4016fcc2f4fb1 --- /dev/null +++ b/src/tools/rustfmt/.github/workflows/diff_check_common.yml @@ -0,0 +1,78 @@ +name: Diff Check (Common) +on: + workflow_call: + inputs: + clone_url: + description: 'Git url of a rustfmt fork to compare against the latest rustfmt' + type: string + required: true + branch_name: + description: 'Name of the feature branch on the forked repo' + type: string + required: true + language_edition: + description: 'Rust language `edition` used to parse code' + type: string + required: true + style_edition: + description: 'rustfmt `style_edition` used when formatting code.' + type: string + required: true + commit_hash: + description: 'Optional commit hash from the feature branch' + type: string + required: false + rustfmt_configs: + description: 'Optional comma separated list of rustfmt config options to pass when running the feature branch' + type: string + required: false + release_channel: + description: 'Configure which release channel to use when compiling rustfmt' + type: string + required: false + default: stable + +permissions: + contents: read + +jobs: + diff_check: + name: "Diff Check {Edition ${{ inputs.language_edition }}, Style Edition ${{ inputs.style_edition }}}" + runs-on: ubuntu-latest + + steps: + - name: checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Build diff_check binary + working-directory: ./diff_check + run: cargo build --release --locked + + - name: Run Diff Check + working-directory: ./diff_check + env: + DIFF_CHECK_LOG: info + GITHUB_EVENT_INPUTS_COMMIT_HASH: ${{ inputs.commit_hash }} + GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS: ${{ inputs.rustfmt_configs }} + GITHUB_EVENT_INPUTS_CLONE_URL: ${{ inputs.clone_url }} + GITHUB_EVENT_INPUTS_BRANCH_NAME: ${{ inputs.branch_name }} + GITHUB_EVENT_INPUTS_LANGUAGE_EDITION: ${{ inputs.language_edition }} + GITHUB_EVENT_INPUTS_STYLE_EDITION: ${{ inputs.style_edition }} + shell: bash + run: | + OPTIONS="" + + if [[ -n "${GITHUB_EVENT_INPUTS_COMMIT_HASH}" ]]; then + OPTIONS+="--commit-hash ${GITHUB_EVENT_INPUTS_COMMIT_HASH} " + fi + + if [[ -n "${GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS}" ]]; then + OPTIONS+="--rustfmt-config ${GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS} " + fi + + target/release/diff_check ${GITHUB_EVENT_INPUTS_CLONE_URL} ${GITHUB_EVENT_INPUTS_BRANCH_NAME} \ + --edition ${GITHUB_EVENT_INPUTS_LANGUAGE_EDITION} \ + --style-edition ${GITHUB_EVENT_INPUTS_STYLE_EDITION} \ + $OPTIONS From dc2c67a0b3664542a49be07e774f99489ddf972c Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Tue, 17 Nov 2026 13:56:22 +0800 Subject: [PATCH 35/41] fix: use double-quote for non-option args to prevent globbing and word splitting Ran `actionlint` against the workflow. --- src/tools/rustfmt/.github/workflows/diff_check_common.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/tools/rustfmt/.github/workflows/diff_check_common.yml b/src/tools/rustfmt/.github/workflows/diff_check_common.yml index 4016fcc2f4fb1..059d066003aad 100644 --- a/src/tools/rustfmt/.github/workflows/diff_check_common.yml +++ b/src/tools/rustfmt/.github/workflows/diff_check_common.yml @@ -72,7 +72,9 @@ jobs: OPTIONS+="--rustfmt-config ${GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS} " fi - target/release/diff_check ${GITHUB_EVENT_INPUTS_CLONE_URL} ${GITHUB_EVENT_INPUTS_BRANCH_NAME} \ - --edition ${GITHUB_EVENT_INPUTS_LANGUAGE_EDITION} \ - --style-edition ${GITHUB_EVENT_INPUTS_STYLE_EDITION} \ + target/release/diff_check \ + "${GITHUB_EVENT_INPUTS_CLONE_URL}" \ + "${GITHUB_EVENT_INPUTS_BRANCH_NAME}" \ + --edition "${GITHUB_EVENT_INPUTS_LANGUAGE_EDITION}" \ + --style-edition "${GITHUB_EVENT_INPUTS_STYLE_EDITION}" \ $OPTIONS From 9766cac5dece82c021b016ecbb9bb801e557e485 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Tue, 17 Nov 2026 13:59:45 +0800 Subject: [PATCH 36/41] fix: use bash array instead of plain string concats Flagged by `actionlint`. --- src/tools/rustfmt/.github/workflows/diff_check_common.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/tools/rustfmt/.github/workflows/diff_check_common.yml b/src/tools/rustfmt/.github/workflows/diff_check_common.yml index 059d066003aad..91a75cb401c4e 100644 --- a/src/tools/rustfmt/.github/workflows/diff_check_common.yml +++ b/src/tools/rustfmt/.github/workflows/diff_check_common.yml @@ -62,14 +62,14 @@ jobs: GITHUB_EVENT_INPUTS_STYLE_EDITION: ${{ inputs.style_edition }} shell: bash run: | - OPTIONS="" + OPTIONS=() if [[ -n "${GITHUB_EVENT_INPUTS_COMMIT_HASH}" ]]; then - OPTIONS+="--commit-hash ${GITHUB_EVENT_INPUTS_COMMIT_HASH} " + OPTIONS+=(--commit-hash "${GITHUB_EVENT_INPUTS_COMMIT_HASH}") fi if [[ -n "${GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS}" ]]; then - OPTIONS+="--rustfmt-config ${GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS} " + OPTIONS+=(--rustfmt-config "${GITHUB_EVENT_INPUTS_RUSTFMT_CONFIGS}") fi target/release/diff_check \ @@ -77,4 +77,4 @@ jobs: "${GITHUB_EVENT_INPUTS_BRANCH_NAME}" \ --edition "${GITHUB_EVENT_INPUTS_LANGUAGE_EDITION}" \ --style-edition "${GITHUB_EVENT_INPUTS_STYLE_EDITION}" \ - $OPTIONS + "${OPTIONS[@]}" From 006f599f1675436d7eec504602e8aa0a9ef910f8 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Tue, 17 Nov 2026 14:03:26 +0800 Subject: [PATCH 37/41] fix: actually respect release channel option --- src/tools/rustfmt/.github/workflows/diff_check_common.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/tools/rustfmt/.github/workflows/diff_check_common.yml b/src/tools/rustfmt/.github/workflows/diff_check_common.yml index 91a75cb401c4e..a5f1aa9b3188c 100644 --- a/src/tools/rustfmt/.github/workflows/diff_check_common.yml +++ b/src/tools/rustfmt/.github/workflows/diff_check_common.yml @@ -60,6 +60,7 @@ jobs: GITHUB_EVENT_INPUTS_BRANCH_NAME: ${{ inputs.branch_name }} GITHUB_EVENT_INPUTS_LANGUAGE_EDITION: ${{ inputs.language_edition }} GITHUB_EVENT_INPUTS_STYLE_EDITION: ${{ inputs.style_edition }} + GITHUB_EVENT_INPUTS_RELEASE_CHANNEL: ${{ inputs.release_channel }} shell: bash run: | OPTIONS=() @@ -77,4 +78,5 @@ jobs: "${GITHUB_EVENT_INPUTS_BRANCH_NAME}" \ --edition "${GITHUB_EVENT_INPUTS_LANGUAGE_EDITION}" \ --style-edition "${GITHUB_EVENT_INPUTS_STYLE_EDITION}" \ + --release-channel "${GITHUB_EVENT_INPUTS_RELEASE_CHANNEL}" \ "${OPTIONS[@]}" From 0a75d4530b5f1ccea62e8887cfbfe66ad1e71cd0 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Tue, 17 Nov 2026 14:14:02 +0800 Subject: [PATCH 38/41] ci: prepare optional matrix job artifact upload So that if we have a matrix of preset Diff Check jobs we can know outcomes of each matrix job. --- .../.github/workflows/diff_check_common.yml | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/tools/rustfmt/.github/workflows/diff_check_common.yml b/src/tools/rustfmt/.github/workflows/diff_check_common.yml index a5f1aa9b3188c..701618055da72 100644 --- a/src/tools/rustfmt/.github/workflows/diff_check_common.yml +++ b/src/tools/rustfmt/.github/workflows/diff_check_common.yml @@ -31,6 +31,11 @@ on: type: string required: false default: stable + result_artifact: + description: 'Upload job status as an artifact with the given name (if set)' + type: string + required: false + default: '' permissions: contents: read @@ -80,3 +85,22 @@ jobs: --style-edition "${GITHUB_EVENT_INPUTS_STYLE_EDITION}" \ --release-channel "${GITHUB_EVENT_INPUTS_RELEASE_CHANNEL}" \ "${OPTIONS[@]}" + + # A matrix of reusable workflow jobs give only one combined outcome, so we + # need to track outcome of individual matrix jobs. + - name: Record result + if: ${{ always() && inputs.result_artifact != '' }} + env: + JOB_STATUS: ${{ job.status }} + run: echo "${JOB_STATUS}" > "${RUNNER_TEMP}/result.txt" + + - name: Upload result + if: ${{ always() && inputs.result_artifact != '' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ${{ inputs.result_artifact }} + path: ${{ runner.temp }}/result.txt + retention-days: 1 + # Allow overwriting so that rerunning a matrix job can upload artifact + # with same name. + overwrite: true From 2f1cbd5d24920f02ef34d572851a488605e07d26 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Tue, 17 Nov 2026 14:57:06 +0800 Subject: [PATCH 39/41] ci: add preset workflow for Edition {2021,2024} x Style Edition {2021,2024} --- .../.github/workflows/diff_check_preset.yml | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 src/tools/rustfmt/.github/workflows/diff_check_preset.yml diff --git a/src/tools/rustfmt/.github/workflows/diff_check_preset.yml b/src/tools/rustfmt/.github/workflows/diff_check_preset.yml new file mode 100644 index 0000000000000..7fb0d61362729 --- /dev/null +++ b/src/tools/rustfmt/.github/workflows/diff_check_preset.yml @@ -0,0 +1,105 @@ +name: Diff Check (Preset) +on: + workflow_dispatch: + inputs: + clone_url: + description: 'Git url of a rustfmt fork to compare against the latest rustfmt' + required: true + branch_name: + description: 'Name of the feature branch on the forked repo' + required: true + commit_hash: + description: 'Optional commit hash from the feature branch' + required: false + rustfmt_configs: + description: 'Optional comma separated list of rustfmt config options to pass when running the feature branch' + required: false + release_channel: + description: 'Configure which release channel to use when compiling rustfmt' + default: stable + type: choice + options: + - stable + - beta + - nightly + +permissions: + contents: read + +jobs: + diff_check: + name: "Diff Check {Edition ${{ matrix.language_edition }}, Style Edition ${{ matrix.style_edition }}}" + strategy: + # We want to run each matrix job to conclusion so we get a full table. + fail-fast: false + # By default, we want to run Diff Check against Edition `{CURRENT - 1, + # CURRENT}` x Style Edition `{CURRENT - 1, CURRENT}` as a preset. + # + # Update the matrix once a new language edition / new style edition is + # stable. Keep in sync with "Write summary" step below. + matrix: + language_edition: ['2021', '2024'] + style_edition: ['2021', '2024'] + uses: $/.github/workflows/diff_check_common.yml + with: + clone_url: ${{ inputs.clone_url }} + branch_name: ${{ inputs.branch_name }} + commit_hash: ${{ inputs.commit_hash }} + language_edition: ${{ matrix.language_edition }} + style_edition: ${{ matrix.style_edition }} + rustfmt_configs: ${{ inputs.rustfmt_configs }} + release_channel: ${{ inputs.release_channel }} + result_artifact: diff-check-result-ed${{ matrix.language_edition }}-se${{ matrix.style_edition }} + + summary: + name: "Render Diff Check matrix summary" + needs: diff_check + if: ${{ always() }} + runs-on: ubuntu-latest + + steps: + - name: Download results + # Note that no artifact exists if all matrix jobs were cancelled early. + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: diff-check-result-* + path: ${{ runner.temp }}/results + + - name: Write summary + env: + CLONE_URL: ${{ inputs.clone_url }} + BRANCH_NAME: ${{ inputs.branch_name }} + COMMIT_HASH: ${{ inputs.commit_hash }} + RUSTFMT_CONFIGS: ${{ inputs.rustfmt_configs }} + RELEASE_CHANNEL: ${{ inputs.release_channel }} + shell: bash + run: | + results_dir="${RUNNER_TEMP}/results" + { + echo "## Diff Check (Preset)" + echo + echo "- Repo: \`${CLONE_URL}\`" + echo "- Branch: \`${BRANCH_NAME}\`" + echo "- Commit: \`${COMMIT_HASH:-branch tip}\`" + echo "- Release channel: \`${RELEASE_CHANNEL}\`" + echo "- rustfmt configs: \`${RUSTFMT_CONFIGS:-none}\`" + echo + echo "| Language Edition | Style Edition | Result |" + echo "|---|---|---|" + # Keep in sync with the `diff_check` matrix. + for language_edition in 2021 2024; do + for style in 2021 2024; do + file="${results_dir}/diff-check-result-ed${language_edition}-se${style}/result.txt" + status="" + [[ -f "${file}" ]] && status=$(< "${file}") + case "${status}" in + success) result="✅" ;; + failure) result="❌" ;; + cancelled) result="CANCELLED" ;; + *) result="NO RESULT" ;; + esac + echo "| ${language_edition} | ${style} | ${result} |" + done + done + } >> "${GITHUB_STEP_SUMMARY}" From 260ba2f5c9114ddcd1824fcfb39832bf43c13711 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 18 Nov 2026 10:52:40 +0800 Subject: [PATCH 40/41] Prepare for merging from rust-lang/rust This updates the rust-toolchain.toml file to nightly-2026-11-18 (59cbdee2e7b3ee50e44b460561c43c9e3023d9f0). --- src/tools/rustfmt/rust-toolchain.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rustfmt/rust-toolchain.toml b/src/tools/rustfmt/rust-toolchain.toml index 0a85b69efd3e9..9d6c5748c14d0 100644 --- a/src/tools/rustfmt/rust-toolchain.toml +++ b/src/tools/rustfmt/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2026-11-02" +channel = "nightly-2026-11-18" components = ["llvm-tools", "rustc-dev"] From 3bfcc4fba9fc43dd0b6f2de5cb491f3c953ceb49 Mon Sep 17 00:00:00 2001 From: Jieyou Xu Date: Wed, 18 Nov 2026 14:21:19 +0800 Subject: [PATCH 41/41] fix: use `CARGO_MANIFEST_DIR` to conjure a predictable absolute path Rather then `file!()` because that tends to produce a relative path if the compiler was handed a relative path, and then things explode if CWD for the rustfmt test itself is not strictly at the root of the r-l/r checkout. --- src/tools/rustfmt/tests/rustfmt/main.rs | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/tools/rustfmt/tests/rustfmt/main.rs b/src/tools/rustfmt/tests/rustfmt/main.rs index e5501761d9f72..06cc873a9a703 100644 --- a/src/tools/rustfmt/tests/rustfmt/main.rs +++ b/src/tools/rustfmt/tests/rustfmt/main.rs @@ -3,7 +3,7 @@ use std::env; use std::fs::File; use std::io::Write; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use rustfmt_config_proc_macro::{nightly_only_test, rustfmt_only_ci_test, stable_only_test}; @@ -135,7 +135,13 @@ fn print_config_writes_to_file() { assert_eq!(exit_code, 0); } -// Can only run this test on nightly becuase the call to `file!` below +fn this_file() -> String { + let p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let p = p.join("tests/rustfmt/main.rs"); + p.into_os_string().into_string().expect("assumes UTF-8 path") +} + +// Can only run this test on nightly because the call to `file!` below // will cause the root `rustfmt.toml` to be loaded, which sets nightly-only options. #[nightly_only_test] #[test] @@ -143,8 +149,8 @@ fn print_config_merges_override_from_args() { let args = &[ "--print-config", "current", - // running with `file!` will load the root `rustfmt.toml` - file!(), + // load the root `rustfmt.toml` (of rustfmt subtree) + &this_file(), "--config=color=Never,edition=2018", ]; @@ -158,7 +164,7 @@ fn print_config_merges_override_from_args() { assert_eq!(exit_code, 0); } -// Can only run this test on nightly becuase the call to `file!` below +// Can only run this test on nightly because the call to `file!` below // will cause the root `rustfmt.toml` to be loaded, which sets nightly-only options. #[nightly_only_test] #[test] @@ -166,8 +172,8 @@ fn print_config_merges_multiple_overrides_from_args() { let args = &[ "--print-config", "current", - // running with `file!` will load the root `rustfmt.toml` - file!(), + // load the root `rustfmt.toml` (of rustfmt subtree) + &this_file(), "--config", "color=never,edition=2018", "--config",