Skip to content

module_path! expansion incorrect for modules without canonical path #146624

@cyqsimon

Description

@cyqsimon

When module_path! is used inside a module without a canonical path, it expands to an incorrect module path.

fn main() {
    print_inner_path(); // prints `<CRATE_NAME>::fn_inner`
    // according to `module_path` this should work; obviously it shouldn't and doesn't
    //dbg!(crate::fn_inner::PATH);
}
fn print_inner_path() {
    pub mod fn_inner {
        pub const PATH: &str = module_path!();
    }
    println!("module path: {}", fn_inner::PATH);
}

Playground

I consider this expansion incorrect because it doesn't indicate that fn_inner is in fact a nested module in a function and is not externally reachable. There's also the possibility that there exists a reachable module at the same level with the same name, from which module_path! would expand to the same thing despite being two distinct modules. See comment.

I'm not sure what the appropriate output/action would be in this situation. A placeholder text or empty string maybe? Although this sounds very wrong. Or maybe compile error. Regardless, at minimum I think the documentation for module_path! should be updated to address this limitation/bug.

Meta

rustc --version --verbose:

rustc 1.92.0-nightly (52618eb33 2025-09-14)
binary: rustc
commit-hash: 52618eb338609df44978b0ca4451ab7941fd1c7a
commit-date: 2025-09-14
host: x86_64-unknown-linux-gnu
release: 1.92.0-nightly
LLVM version: 21.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsA-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions