rust-lang / rust-lang/rust-analyzer

Format on save does not format if `rustfmt` has internal error

Open
#14,563 0 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-ide C-enhancement
Dominant language
Rust
Stars
16.9k
Forks
2.2k
Avg merge
1d 12h
Merged PRs (30d)
72

Description

rustfmt will sometimes output internal errors, even when it successfully formats the code. This happens particularly frequently when using let-else. If you happen to write some code with a trailing whitespace in a let-else block, then rustfmt will format everything else in the file and output an error about not removing trailing whitespace.

Rust-analyzer will ignore rustfmt's output if there is any sort of error, even if rustfmt actually formats the document. This means that some documents will randomly become unformattable,

I think the way to solve this is to look to see if there are any errors that aren't marked with the [internal] marker and ignore the error if all errors are [internal].

Reproducer: (note the whitespace after the else)

fn main() {
let opt = Some("hello world");
    let Some(a) = opt else { 
        return;
    };
}

With RA_LOG set to warn, this produces the following output:

[WARN rust_analyzer::handlers] rustfmt exited with status 1 command="rustfmt" "--edition" "2021" captured_stderr=error[internal]: left behind trailing whitespace
 --> <stdin>:3:3:29
  |
3 |     let Some(a) = opt else { 
  |                             ^
  |

warning: rustfmt has failed to format. See previous 1 errors.

Relevant code: https://github.com/rust-lang/rust-analyzer/blob/f85fc285088129a131ecb83398d9f66922e0830e/crates/rust-analyzer/src/handlers.rs#L1871

rust-analyzer version: rust-analyzer version: 0.3.1472-standalone (01120f121 2023-04-07)

rustc version: rustc 1.69.0-nightly (001a77fac 2023-01-30)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in crates/rust-analyzer/src/handlers.rs around the rustfmt handling at line 1871, and reproduce the let-else example with RA_LOG set to warn. Check how rustfmt stderr and exit status are interpreted; done means formatting is accepted when all reported errors are marked [internal], while other errors still prevent applying the output.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.