TedDriggs / darling

A Rust proc-macro attribute parser
MIT License
983 stars 66 forks source link

Attribute macros with field attributes #255

Closed Fyko closed 11 months ago

Fyko commented 11 months ago

Howdy! I've been poking around some issues, namely #156 and #165, trying to figure out how to build a strong attribute macro. This is what I had in mind:

#[derive(Debug, PartialEq, FromDeriveInput)] // i know FromDeriveInput here is wrong
#[darling(attributes(read_query), supports(struct_named))]
pub struct ReadQueryDerive {
    pub ident: syn::Ident,
    pub data: ast::Data<util::Ignored, ReadQueryDeriveVariable>,

    pub query: Option<String>,
    pub query_nocheck: Option<String>,
    pub return_type: syn::Type,
}

#[derive(Debug, PartialEq, FromField)]
#[darling(attributes(read_query))]
pub struct ReadQueryDeriveVariable {
    pub ident: Option<Ident>,
    pub ty: Type,
    #[darling(default)]
    pub shard_key: bool,
}

and what I hope to parse being:

#[read_query(query = "myquere here", return_type = MyReturnType)]
struct MyQuery {
    #[read_query(shard_key)]
    pub id: i32
}

I previously used FromMeta before needing to parse attributes on field members. I can't find any examples or paths to reach this goal without also needing to derive a proc macro above the read_query attribute.

TedDriggs commented 11 months ago

I'm not sure that FromDeriveInput is actually wrong here - notice that darling never knows what trait name you're deriving, so I think it's fine to use it for this use-case. You would pass to #[darling(attributes(...))] whichever attributes you want to read at the struct level, and I think you'd be fine.

You'd then use a custom type that derives FromField to get access to the usage of read_query on the fields.

Fyko commented 11 months ago

Thanks for getting back to me. My codesample works, but I'm trying to figure out if I could go without adding a proc_macro_derive, rather using proc_macro_attribute.

TedDriggs commented 11 months ago

I think you’re trying to do this, right?

Fyko commented 11 months ago

Yes!