Getting the list of all items with a custom attribute

#1

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?

0 Likes

#2

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

#3

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?

0 Likes

#4

Yes, this can be done. See e.g. https://github.com/fortanix/rust-sgx/blob/jb/sgx-detect/sgxs-tools/src/sgx_detect/proc_macro.rs#L122-L294

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

#5

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?

0 Likes

#6

Yes

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

1 Like