1
votes

I'm writing a procedural macro which would accept a name of a trait and generate a newtype struct which stores an implementor of that trait (T) and implements the trait by using the implementation on T. In effect, this newtype structure isolates one trait of an object and "seals inside" the implementations for all other traits.

In order to work correctly, the macro needs to locate the trait in scope of the call site (which is easily done by referring to the trait the same way as the invocation does), generate a name for the newtype based on the trait name (in my case, Only{trait_name}, eg. OnlyDisplay), get a list of methods and associated functions/types/constants in the trait and implement them with self.{method_name}({parameters}) (for methods) or Self::{assoc_name} for associated members. This step is what confuses me: neither the Syn crate nor proc_macro provide methods for locating traits by their Idents and introspecting them afterwards.

So, how do I locate a trait by an Ident in the current scope and get a list of everything in its definition?

2

2 Answers

2
votes

Short answer: You can't. By the time a proc-macro is executed, all the compiler knows is the tokenization of the source; that is, it knows that the source parses. The compiler does not know anything about types, which idents refer to what and how to make sense of any of those.

You may want to update your question regarding what your intention is: What are you actually trying to accomplish?

1
votes

You can’t. Macros are expanded before any semantic analysis is done and names aren’t resolved at that point.

Your best bet would be to do something like serde’s remote attribute and repeat the trait definition.