TedDriggs / darling

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

Question: how do I know if my attribute was applied? #262

Closed vrurg closed 8 months ago

vrurg commented 8 months ago

First of all, a complete Rust beginner is here. So, dumb questions possible. :)

I'm training myself by implementing a functionality that plan to use later in a bigger project. So far, I was managing myself and came down to an intermediate design involving FromDeriveInput and FromField. The point is to be able to support something like:

#[derive(MyFields)]
struct Foo {
    #[other_attr(...)]
    #[myattr]
    f1: ...,
    #[myattr(opt1,opt2="bar")]
    f2: ...,
}

The field receiver is something like:

#[derive(Debug, FromField)]
#[darling(attributes(myattr), forward_attrs)]
struct MyFieldReceiver {
    attrs: Vec<syn::Attribute>,

    opt1: Option<...>, opt2: Option<...>,
}

Now, no matter if I used just forward_attrs, or do explicit forward_attrs(myattr), I can only see the other_attr where it's used, but never can figure out if myattr was there or not.

TedDriggs commented 8 months ago

darling doesn't have native support for using attributes like you showed here; the presence of myattr in attributes means that darling will consume it without forwarding. There's been past discussions on this, but the best approach so far has been to use forward_attrs and then to manually pass the contents to FromAttributes if you need to parse the insides of the attribute body.

One question that usually trips people up who are trying to make this API: What is the expected behavior of the following?

#[derive(MyFields)]
struct Foo {
    #[other_attr(...)]
    #[myattr]
    f1: ...,
    #[myattr(opt1,opt2="bar")]
    #[myattr]
    f2: ...,
}
vrurg commented 8 months ago

use forward_attrs and then to manually pass the contents to FromAttributes

OK, makes sense. Thank you!

What is the expected behavior of the following?

Intriguing... Though in my view it's to be left up to the macro/trait developer. They'd know better what semantics works best in their case.

TedDriggs commented 8 months ago

Though in my view it's to be left up to the macro/trait developer. They'd know better what semantics works best in their case.

And that's allowed... at the expense of having to do additional work. Darling is designed to be opinionated about its input format by default, like serde_json is.