Can a proc macro know the fully qualified name of the item it's operating on?

⚓ Rust    📅 2026-06-24    👤 surdeus    👁️ 1      

surdeus

I ran into what I think might be a limitation of the enum_dispatch crate, which, in my use case, ends up generating code like

mod a {
  use crate::b::B;

  enum Foo {
    B(B)
  }
}

mod b {
  use crate::c::Demo;

  struct B;

  impl Demo for B {
    fn demo(&self) { todo!(); }
  }
}

mod c {
  trait Demo {
    fn demo(&self);
  }

  // Generated code below this line
  impl Demo for Foo {
    fn demo(&self) {
      match Self::B(b) => Demo::demo(b),
    }
  }
  // Generated code above this line
}

This won't compile - the generated code in c references Foo, but Foo is only defined in a and is not imported in c. enum_dispatch generates the code this way because it needs both the enum definition and the trait definition available before it can generate trait impls, but it appears to be using the unqualified name of the trait when generating the impl, even if it's elsewhere in the program.

I'm under the impression that proc macros only have access to the item they're operating on, and therefore that the fully-qualified name, which would be needed to generate the correct impl blocks, is not available. Is that the case? If it is, I can abandon this idea and leave the hand-written impls (which don't have this issue) in place; if it's not, then I might try to fix enum_dispatch to generate fully-qualified names.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed