rust-lang / rust-lang/rust-clippy

"clippy::single_component_path_imports" False positive on swapped namespaces to enable mocking.

Open
#11,925 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

Imagine you have a 3rd part dependency on module module3.
My component depends on an exported member from that namespace, for example, module3::Foo.
I want to test my component's internal logic without instantiating module3::Foo.
To do so, I mock module3::Foo with mockall. I will now use module3 for actual builds, while use mock::module3 as module3 for test builds.
Lint single_component_path_imports is going to complain about my first use.

Lint Name

single_component_path_imports

Reproducer

I tried this code:

#[cfg(not(test))]
use module3;

#[cfg(test)]
use mock::module3 as module3;

fn computation(foo: module3::Foo) -> u32 { .. }

fn run_computation() {
  let foo =  module3::Foo::new();
  let c = computation(foo);
}

#[cfg(test)]
fn run_test_computation(foo: module::Foo) {
  let foo =  module3::Foo::new();
  let c = computation(foo);
  assert_eq!(c, 100);
}

I saw this happen:

warning: this import is redundant
  --> main.rs
   |
   | use module3;
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove it entirely
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_component_path_imports

I do not know if it is reasonable to expect the lint to deduce that the namespaces are swapped. However it definitely produces a warning where I did not expect it.

Version
rustc 1.74.0 (79e9716c9 2023-11-13)
binary: rustc
commit-hash: 79e9716c980570bfd1f666e3b16ac583f0168962
commit-date: 2023-11-13
host: aarch64-apple-darwin
release: 1.74.0
LLVM version: 17.0.4
Additional Labels

No response

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 with the single_component_path_imports lint implementation and reproduce the warning using the Rust snippet in the issue. Investigate how the lint handles cfg-gated imports with swapped namespaces. Done means the reported false positive has an agreed behavior and regression coverage for the reproducer.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.