rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

`module_inception` false positive for private sub-module

Open Nemo157 opened this issue 1 year ago • 4 comments

Summary

When splitting a public module up into sub-modules for code-organization purposes, you can commonly have a sub-module with the same name as the public module. This is fine for a private module since the repetition isn't exposed to the outside world.

Lint Name

module_inception

Reproducer

I tried this code:

pub mod foo {
    mod foo {
        pub struct Foo;
    }

    // other private modules
    
    pub use self::foo::Foo;
    // other re-exports
}

I saw this happen:

warning: module has the same name as its containing module
 --> src/lib.rs:2:5
  |
2 | /     mod foo {
3 | |         pub struct Foo;
4 | |     }
  | |_____^
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#module_inception
  = note: `#[warn(clippy::module_inception)]` on by default

I expected to see this happen: no warning

Version

No response

Additional Labels

No response

Nemo157 avatar Aug 12 '24 09:08 Nemo157

(even with the config allow-private-module-inception enabled the warning occurs, and IMO that config should be on by default).

Nemo157 avatar Aug 12 '24 09:08 Nemo157

At "Why is this bad?" section mentioned that it was done intentionally

The expectation is that items inside the inner mod foo { .. } are then available through foo::x, but they are only available through foo::foo::x. If this is done on purpose, it would be better to choose a more representative module name. https://rust-lang.github.io/rust-clippy/master/index.html#/module_inception

As allow-private-module-inception you use public but as mentioned at name this allowing private

alex-semenyuk avatar Aug 12 '24 10:08 alex-semenyuk

The item is not available at foo::foo::Foo though, that is a private module, it makes no impact on the public API.

That part of the lint description seems to be targeted at beginner rust programmers that don't understand the module system and wrote this code by mistake, which it could be helpful for; but IMO the lint is a net-negative for experienced programmers.

Nemo157 avatar Aug 12 '24 10:08 Nemo157

Thinking about this a little more, the intent of this lint afaict is to catch beginners coming from languages like C# or C++ where you re-declare the current module in the current file too. Given that intent, I think it should only apply when there's an inline module of the same name as the current module, having an outlined module of the same name is very unlikely to be the same kind of beginners mistake. (Which wouldn't fix my initial example, but would fix the actual case it was based on).

Nemo157 avatar Aug 13 '24 08:08 Nemo157