Skip to content

Mod item in procedural macro output looks for the wrong source file #58818

Closed
@dtolnay

Description

@dtolnay

I have this crate layout:

  • Cargo.toml
  • src/
    • main.rs
    • parent/
      • child.rs

where child.rs is an empty file and main.rs is:

mod parent {
    mod child;
}

fn main() {}

This compiles successfully and we end up with a module at crate::parent::child backed by the file src/parent/child.rs.

But if mod child; goes anywhere near a proc macro, it no longer works.

mod parent {
    repro::noop! { mod child; }
}

fn main() {}

where noop! is this macro:

#[proc_macro]
pub fn noop(input: TokenStream) -> TokenStream {
    input
}

The error is:

error[E0583]: file not found for module `child`
 --> src/main.rs:2:5
  |
2 |     repro::noop! { mod child; }
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: name the file either child.rs or child/mod.rs inside the directory "src"

so it is looking for a file corresponding to mod child as though the mod child were not contained inside of mod parent. I hit this while working on https://github.com/dtolnay/automod.

The same problem does not occur if noop! is defined as a macro_rules macro.

Repro script

#!/bin/bash

cargo new repro

echo >>repro/Cargo.toml '
[lib]
proc-macro = true
'

echo >repro/src/lib.rs '
extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro]
pub fn noop(input: TokenStream) -> TokenStream {
    input
}
'

echo >repro/src/main.rs '
mod parent {
    repro::noop! { mod child; }
}

fn main() {}
'

mkdir repro/src/parent
touch repro/src/parent/child.rs

cargo check --manifest-path repro/Cargo.toml

Mentioning @petrochenkov who may know what is going wrong or whether there is a simple rustc fix.

Metadata

Metadata

Assignees

Labels

A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)C-bugCategory: This is a bug.E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.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