ayrat555 / frankenstein

Telegram bot API client for Rust
Do What The F*ck You Want To Public License
268 stars 28 forks source link

Use consistent builder derive configs across API types #213

Closed Veetaha closed 1 month ago

Veetaha commented 1 month ago

I found a really handy crate that allows you to define derive/attribute aliases etc. without defining a separate proc macro crate. This crate doesn't even depend on syn/quote/proc-macro2. The compile time is still the same for me (~17 seconds from scratch) after this change. This crate uses a bit of macro tricks where one macro generates another macro and thus can preserve some state.

With this approach it's possible to define the builder attribute alias in a single place and remove all the manual #[builder(into)] attributes from all the API struct fields. Note that I deliberately didn't touch the Client builder syntax just to keep things simple there. I only modified api_params.rs and objects.rs.

I think I'll add this to bon docs as a "global builder config" pattern.


Also, another suggestion is that you can use serde_with::skip_serializing_none to avoid manually adding #[serde(skip_serializing_if = "Option::is_none")] on every Option field. This can even be combined with the marco_rules_attribute crate to make the code even cleaner.

You can further develop the idea of using the macro_rules_attribute to reduce the boilerplate. E.g. move common derives such as Debug, Clone, ::serde::Serialize, ::Deserialize as well as #[skip_serializing_none] to the aliases.

Veetaha commented 1 month ago

cc @EdJoPaTo this is what you wanted. No more manual #[builder(into)] attributes and a suggestion to remove manual #[serde(skip_serializing_if = "Option::is_none")] attributes as well (I'll leave the serde exercise to you though).

EdJoPaTo commented 1 month ago

I like the basic idea of this! We can improve it a bit then I think this is a good simplification.

ayrat555 commented 1 month ago

@EdJoPaTo for me it's looking good. wanted to get your review because you were strongly involved in the migration to the bon crate