rust-lang / rust-lang/rust

`decl_macro` can call `pub fn` methods of private types.

Open
#155,631 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-decl-macros-2-0 A-hygiene A-macros A-method-lookup A-visibility C-bug F-decl_macro T-compiler T-lang
Dominant language
Rust
Stars
119k
Forks
16.2k
PR merge metrics
PR metrics pending

Description

I tried this code:

#![feature(decl_macro)]
macro my_macro($val:expr) {
    $val.method()
}

pub mod module {
    struct Thing;
    impl Thing {
        pub fn method(&self) -> bool {
            true
        }
    }
    pub fn weird() -> bool {
        super::my_macro!(Thing)
    }
}

The method is a pub fn. However, it is implemented on a private type. Therefore, it should not be callable from outside the module. So, this code shouldn't compile. Instead, this code compiles without errors.

Changing pub fn method to fn method causes the following error, as expected:

error[E0624]: method `method` is private
  --> src/lib.rs:3:10
   |
 3 |     $val.method()
   |          ^^^^^^ private method
...
 9 |         fn method(&self) -> bool {
   |         ------------------------ private method defined here
...
14 |         super::my_macro!(Thing)
   |         ----------------------- in this macro invocation
   |
   = note: this error originates in the macro `super::my_macro` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0624`.

This behavior also seems to apply to built-in macros. See https://github.com/rust-lang/rust/pull/155598#discussion_r3121501324

Meta

Reproducible on the playground with 1.97.0-nightly (2026-04-20 66da6cae1a6f12e95854)

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 provided playground reproduction using decl_macro, then trace the compiler's macro expansion and privacy checking for the pub fn method on the private Thing type. Compare the behavior with the non-public method and the mentioned built-in macro case; done means the reproduction is rejected for the expected privacy violation without regressing valid macro calls.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.