Getting the list of all items with a custom attribute

Is it possible to get the list of all items in a binary with a given proc macro attribute? Similar to how the test framework main gets the list of all #[test] functions.

A somewhat related question: Is it possible to write some code in some of the submodules of a binary to register a bunch of names, such that main() when it starts up, gets access to the whole list of registered names?

What kind of list are you looking for?

  • You couldn't do this at runtime because rust has no reflection (Management of types during runtime) and therefore no idea of what macros were applied/things were inherited by the type/function/module/etc.
  • At compile time (Or before this) you could just search for everything that mentions the name of the attribute (Although not recommended for scalability issues)
1 Like

I need it at runtime, but I am okay with writing a custom attribute to accomplish this. So we have some compile time logic. Can the proc_macro_attribute function keep state across multiple calls somehow? If it can, it can construct a list, and later create an array to be embedded in main().

I wonder how cargo test gets the list of all functions marked as tests. Does it use some sort of compiler internals?

Yes, this can be done. See e.g.

Has nothing to do with cargo, the compiler has built-in support for unit tests. And yes, it uses special logic to collect all of the tests.

1 Like

Thanks for the pointer! If I understand it correctly, DEPS will contain all the 'dependency' attributes in the crate being compiled, right? Does this work correctly with incremental compilation etc, where all files are not processed during compilation?


I don't know. All my attributes are in a single file.

1 Like