Search code examples
rustrust-macros

Directly parse data on nested proc macro


Suppose this:

#[route(base_path="/api")]
pub struct Type;

impl Type {
  
   #[route(path="/v1/handler")]
   pub fn handler() {}

   #[route(path="/v1/handler2")]
   pub fn handler2() {}
}

I want to parse in any kind of data struct some mapping between the base_path and the path attached to the methods on the impl block. Imagine any HashMap<K, V> where base_path are the keys and path it's related values.

// pseudo struct internal data representation
[
    {
        struct: MyRestController, 
        base_path: "/api", 
        paths: [
            "handler", "handler2"
        ]
    },
    // other types registered
]

Is it possible to know with the proc-macro attached to the struct, detect the attributes attached to the methods on the impl block and made the parse in one type? (When the macro attached to the struct runs).


Solution

  • You probably want to write your macro so that it expects the following:

    pub struct Type;
    
    #[route(base_path="/api")]
    impl Type {
      
       #[route(path="/v1/handler")]
       pub fn handler() {}
    
       #[route(path="/v1/handler2")]
       pub fn handler2() {}
    }
    

    That is, it wouldn't know anything about the struct itself (i.e. its fields), but it will have full access to the impl block, including attributes on individual functions.