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/.github/workflows/check_diff.yml b/src/tools/rustfmt/.github/workflows/check_diff.yml deleted file mode 100644 index 7f7bc62846a3c..0000000000000 --- a/src/tools/rustfmt/.github/workflows/check_diff.yml +++ /dev/null @@ -1,86 +0,0 @@ -name: Diff Check -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 - language_edition: - description: 'Rust language `edition` used to parse code' - required: true - default: 2015 - type: choice - options: - - 2015 - - 2018 - - 2021 - - 2024 - style_edition: - description: 'rustfmt `style_edition` used when formatting code.' - required: true - default: 2021 - type: choice - options: - - 2021 # 2015, 2018, and 2021 are all formatted the same since `style_edition` was added between 2021 and 2024 - - 2024 - 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: - runs-on: ubuntu-latest - - steps: - - name: checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - - name: Build check_diff binary - working-directory: ./check_diff - run: cargo build --release --locked - - - name: Run Diff Check - working-directory: ./check_diff - env: - CHECK_DIFF_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/check_diff ${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/.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/diff_check.yml b/src/tools/rustfmt/.github/workflows/diff_check.yml new file mode 100644 index 0000000000000..11d28a8ab471a --- /dev/null +++ b/src/tools/rustfmt/.github/workflows/diff_check.yml @@ -0,0 +1,58 @@ +name: Diff Check (Custom) +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 + language_edition: + description: 'Rust language `edition` used to parse code' + required: true + default: 2015 + type: choice + options: + - 2015 + - 2018 + - 2021 + - 2024 + style_edition: + description: 'rustfmt `style_edition` used when formatting code.' + required: true + default: 2021 + type: choice + options: + - 2021 # 2015, 2018, and 2021 are all formatted the same since `style_edition` was added between 2021 and 2024 + - 2024 + 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 ${{ 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..701618055da72 --- /dev/null +++ b/src/tools/rustfmt/.github/workflows/diff_check_common.yml @@ -0,0 +1,106 @@ +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 + result_artifact: + description: 'Upload job status as an artifact with the given name (if set)' + type: string + required: false + default: '' + +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 }} + GITHUB_EVENT_INPUTS_RELEASE_CHANNEL: ${{ inputs.release_channel }} + 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}" \ + --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 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}" 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 44d36898f216f..20986c8b74e48 100644 --- a/src/tools/rustfmt/.github/workflows/test.yml +++ b/src/tools/rustfmt/.github/workflows/test.yml @@ -54,27 +54,18 @@ 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 }} 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: | 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 }} 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/Contributing.md b/src/tools/rustfmt/Contributing.md index 9e37f15e62b2b..cf13b6b05f3c1 100644 --- a/src/tools/rustfmt/Contributing.md +++ b/src/tools/rustfmt/Contributing.md @@ -9,40 +9,266 @@ 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) +* [Pull Request lifecycle](#pull-request-lifecycle) +* [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 -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`. -[LLM usage policy]: https://forge.rust-lang.org/policies/llm-usage.html +General rule of thumb: -## Linting +* 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**. -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. +Some clear examples permitted by the [LLM usage policy]: -``` -# lint rustfmt-nightly (the package at the root of this repo) -cargo clippy -``` +* 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. -To Lint a package outside of the root one you will need to do one of: +Some clear examples prohibited by the [LLM usage policy]: -``` -# 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 -``` +* 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 ## 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. +## 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 +[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 @@ -350,6 +576,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). 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/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 87% rename from src/tools/rustfmt/check_diff/src/main.rs rename to src/tools/rustfmt/diff_check/src/main.rs index c48280f254d4b..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}; @@ -39,12 +39,19 @@ 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 +/// Inputs for the Diff Check script #[derive(Parser)] struct CliInputs { /// Git url of a rustfmt fork to compare against the latest main rustfmt @@ -74,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()?; @@ -103,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/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"] 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/src/comment.rs b/src/tools/rustfmt/src/comment.rs index f9875d6e4b101..618e1079b0c51 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, @@ -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( @@ -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. @@ -1401,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) @@ -1901,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/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/src/missed_spans.rs b/src/tools/rustfmt/src/missed_spans.rs index 94ca9238ac045..989a5dde8f9cd 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); @@ -356,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/src/test/mod.rs b/src/tools/rustfmt/src/test/mod.rs index 5d5be709e5fb5..b33d43cabffe2 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}; @@ -51,6 +50,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() { @@ -394,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"); } @@ -441,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"); } @@ -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"); @@ -849,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; @@ -862,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() { @@ -958,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, } @@ -1112,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); } } @@ -1130,7 +1156,7 @@ fn handle_result( if failures.is_empty() { Ok(()) } else { - Err(IdempotentCheckError::Mismatch(failures)) + Err(IdempotentCheckError::Mismatches(failures)) } } @@ -1186,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, } diff --git a/src/tools/rustfmt/tests/rustfmt/main.rs b/src/tools/rustfmt/tests/rustfmt/main.rs index c2e0c544c2b9c..06cc873a9a703 100644 --- a/src/tools/rustfmt/tests/rustfmt/main.rs +++ b/src/tools/rustfmt/tests/rustfmt/main.rs @@ -3,10 +3,10 @@ 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, 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. @@ -135,12 +135,22 @@ fn print_config_writes_to_file() { assert_eq!(exit_code, 0); } +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] fn print_config_merges_override_from_args() { let args = &[ "--print-config", "current", - ".", + // load the root `rustfmt.toml` (of rustfmt subtree) + &this_file(), "--config=color=Never,edition=2018", ]; @@ -154,12 +164,16 @@ fn print_config_merges_override_from_args() { assert_eq!(exit_code, 0); } +// 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] fn print_config_merges_multiple_overrides_from_args() { let args = &[ "--print-config", "current", - ".", + // load the root `rustfmt.toml` (of rustfmt subtree) + &this_file(), "--config", "color=never,edition=2018", "--config", @@ -223,6 +237,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 +299,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 +598,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 +} 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/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/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/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/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/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..2748ae995a364 --- /dev/null +++ b/src/tools/rustfmt/tests/source/issue-6612/hidden_code_in_doc_comment.rs @@ -0,0 +1,24 @@ +//@ 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; + +/// ``` +/// println!("1"); // comment +/// # println!("2"); +/// ``` +struct S4; 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/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/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/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/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/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/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_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! +} 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-5521.rs b/src/tools/rustfmt/tests/target/issue-5521.rs new file mode 100644 index 0000000000000..ca04f079101bf --- /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) {} +} 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 +", + }; +} 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..754d6b4dc229f --- /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..c2fee0a6ca4ac --- /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..1c5783179501e --- /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..8c11fa8146b30 --- /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..7334ab35f9385 --- /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() {} 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..eef652fe70cec --- /dev/null +++ b/src/tools/rustfmt/tests/target/issue-6612/hidden_code_in_doc_comment.rs @@ -0,0 +1,24 @@ +//@ 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; + +/// ``` +/// 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 new file mode 100644 index 0000000000000..e80c7cb479fe8 --- /dev/null +++ b/src/tools/rustfmt/tests/target/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-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() {} +} 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), + _ => (), + } +} 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 + }; +} 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 + {} +} 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"), + }; +} 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, +{ +} 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); 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 +//! # } +//! ``` 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/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..dd9146be22275 --- /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() -> () {} +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 {} +); +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; + 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; + 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; + 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/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 @@ - - + + 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"]