Skip to content

unreachable_pub lint thinks a pub fn in a pub(crate) struct is public #110922

Closed
@mpalmer

Description

@mpalmer

I tried this code:

// src/foo.rs
pub(crate) struct Foo();

impl Foo {
    pub fn foo() {
        println!("foo!");
    }
}

// src/lib.rs
#[warn(unreachable_pub)]

mod foo;

use foo::Foo;

pub fn bar() {
    Foo::foo();
}

I expected that this code would compile without warnings, because the Foo struct isn't visible outside the crate, and thus its associated functions won't be visible either (I'm making a bit of an assumption on this point; maybe you can access a private struct's functions outside the crate, and I just don't know enough Rust to know how?)

Instead, the compiler output this warning:

   Compiling pub_crate v0.1.0 ([...]/pub_crate)
warning: unreachable `pub` item
 --> src/foo.rs:4:5
  |
4 |     pub fn foo() {
  |     ---^^^^^^^^^
  |     |
  |     help: consider restricting its visibility: `pub(crate)`
  |
note: the lint level is defined here
 --> src/lib.rs:1:8
  |
1 | #[warn(unreachable_pub)]
  |        ^^^^^^^^^^^^^^^

warning: `pub_crate` (lib) generated 1 warning (run `cargo fix --lib -p pub_crate` to apply 1 suggestion)
    Finished dev [unoptimized + debuginfo] target(s) in 0.11s

Meta

rustc --version --verbose:

rustc 1.69.0 (84c898d65 2023-04-16)
binary: rustc
commit-hash: 84c898d65adf2f39a5a98507f1fe0ce10a2b8dbc
commit-date: 2023-04-16
host: x86_64-unknown-linux-gnu
release: 1.69.0
LLVM version: 15.0.7

The output is the same if I run with rustup run nightly cargo build, where rustup run nightly rustc --version --verbose says:

rustc 1.71.0-nightly (1a6ae3d69 2023-04-27)
binary: rustc
commit-hash: 1a6ae3d692cfb52b21d0f45ba50b659486e53d6c
commit-date: 2023-04-27
host: x86_64-unknown-linux-gnu
release: 1.71.0-nightly
LLVM version: 16.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsA-visibilityArea: Visibility / privacyC-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions