rust-lang / rust-lang/rust-analyzer

Producing well-formatted code during edits

Open
#923 5 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-formatting C-feature E-hard E-has-instructions fun S-actionable
Dominant language
Rust
Stars
16.9k
Forks
2.2k
Avg merge
1d 12h
Merged PRs (30d)
72

Description

Currently, we assists and fixes produced poorly formatted code: it uses exactly the same whitespace as specified during building of an edit, and it ignores indentation completely.

We need to figure out an API which will give us well-formatted edits.

I don't know how to handle this in a nice way, but I think something like this would work. Say, we want to handle add impl for a nested struct:

fn foo() {
    struct S {
        field: u32
    }
}

The assist initially produces some impl, and inserts it into the file "randomly". Note that insertion into the file is cheap, because trees are immutable. This will give us the following temporary file:

fn foo() {
    struct S {
        field: u32
    }impl S {}
}

We than find a freshly inserted node and reformat only this node, whihc gives use

fn foo() {
    struct S {
        field: u32
    }
    
    impl S {
    }
}

We using this reformatted node, we compute the final edit.

The code and tests for add impl example live in this file: https://github.com/rust-analyzer/rust-analyzer/blob/17aaece6b39c2fb525be0eccce4626fc622e8236/crates/ra_assists/src/add_impl.rs

There's a nascent formatting crate here: https://github.com/rust-analyzer/rust-analyzer/blob/17aaece6b39c2fb525be0eccce4626fc622e8236/crates/ra_fmt/src/lib.rs

I think, as a first step, we should only handle auto-indent.

Here's a Zulip stream to discuss the issue: https://rust-lang.zulipchat.com/#narrow/stream/185405-t-compiler.2Fwg-rls-2.2E0/topic/rust-analyzer.23923.3A.20producing.20nice.20code.20for.20refactorings

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 by reading the add impl code and tests in crates/ra_assists/src/add_impl.rs, then inspect the nascent formatter in crates/ra_fmt/src/lib.rs. Use the nested-struct example to understand the proposed temporary insertion and formatting flow. Done means the first-step auto-indent behavior is defined and covered by tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.