rust-lang / rust-lang/rust-analyzer

Add new imports to the narrowest-scoped existing `use` block

Open
#14,861 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-ide C-feature
Dominant language
Rust
Stars
16.9k
Forks
2.2k
Avg merge
1d 13h
Merged PRs (30d)
69

Description

Proposal

Starting with the following code:

use std::io::Read;

fn foo() {
    use std::io::BufReader;

    BufRead::
}

Using the LSP code assistance feature to import the type on that final line of code (BufRead::) will result in the addition of a new import to the list of using statements at the top of the file.

I propose that rust-analyzer should search/track each ascending enclosing scope for a use header and append any new use statements to the first one (the nearest/narrowest scoped) it finds instead of always appending to the module-level imports at the top of the document.

Rationale

Generally my code will use the module-level use statement for imports, but sometimes I am working on functionality that is extremely specific to the particular method/impl I'm working on and these are the cases where I'll manually start a new use block relevant specifically to the current code. I think that it's fair to assume in the presence of an existing more-narrowly-scoped use block that applies to the current code that the developer wishes to append new imports to this use block rather the global/module-level use block at the top of the document.

I am, of course, not suggesting that rust-analyzer default to creating a new use block in the narrowest scope that supports such a use block, only that in the presence of one rust-analyzer should append to it.

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

Begin at rust-analyzer's LSP code assistance import feature described in the issue and locate the entry point that adds imports. Trace how the target scope is selected and verify the behavior with the existing import-assistance checks. Done means a new import is appended to the nearest existing applicable use block rather than always the module-level block.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.