Can proc_macro_derive access constants contained in an enum?

I would like to write a derive macro that would create a function to return the constants defined on an enum or a struct as a vector of tuples containing the name of each constant and its value.

trait ConstantsDefinedOnStruct {
    fn constants_defined_on_struct() -> Vec<(&str, usize)> // The name and value of each constant

struct StructWithConstants{}

impl StructWithConstants {
    pub const ONE: usize = 1

// Hoping that StructWithConstants now implements ::constants_defined_on_struct() which returns vec![("ONE", 1)]

Elsewhere, to implement the macro:

pub fn constants_defined_on_struct(input: TokenStream) -> TokenStream {
    println!("macro input: {:#?}", input); // Can't see the constants?

But here I get stuck. Where in the TokenStream would I find the constants implemented on the struct?

I'd be very grateful for any pointers.

Macros run before the compiler knows what a struct is, let alone what its constants are. Everything you need to know needs to be on the thing with the macro.

Thank you @alice. That makes sense and my understanding of when the macros run was incorrect.

From that I think that I need to define an attribute? macro to the implementation that has the constants defined.

I will see where I can get to from there.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.