Is it possible for a procedural macro derive to add derives from other crates to the struct that it is derived upon?
#[derive(Combined)]
struct Foo;
#[macro_use] extern crate quote;
extern crate proc_macro2;
extern crate proc_macro;
extern crate syn;
use proc_macro::TokenStream;
#[proc_macro_derive(Combined)]
pub fn my_macro(input: TokenStream) -> TokenStream {
let input: DeriveInput = syn::parse(input).unwrap();
let ident = input.ident;
let expanded = quote! {
#[derive(Clone, Debug)]
struct #ident;
};
expanded.into()
}
While this cannot be done conveniently with proc_macro_derive
it can be done with proc_macro_attribute
and seeing as the other answer already uses a derive attribute this solution may be better for your use case:
extern crate proc_macro;
extern crate proc_macro2;
#[macro_use]
extern crate quote;
extern crate syn;
use proc_macro2::TokenStream;
#[proc_macro_attribute]
pub fn add_derive(_metadata: proc_macro::TokenStream, input: proc_macro::TokenStream)
-> proc_macro::TokenStream {
let input: TokenStream = input.into();
let output = quote! {
#[derive(Debug, Serialize, Deserialize, etc, ...)]
#input
};
output.into()
}
Then to use this macro:
#[add_derive]
pub struct TestStruct { ... }
Notably, attribute macros replace token streams whereas derive macros are suited for appending to token streams: Rust Reference: Procedural Macros
With some sub-optimal work-arounds - yes!
The first issue I encountered while implementing this was the duplicate definitions for the struct - having more than one definition just won't work. To get around this, I used a custom attribute that must be specified which will be the name of the struct in the generated code:
#![feature(custom_attribute)]
#[macro_use] extern crate quote;
extern crate proc_macro;
extern crate proc_macro2;
extern crate syn;
use syn::DeriveInput;
use proc_macro::TokenStream;
use proc_macro2::{Ident, Span};
use syn::{Attribute, Meta, Lit};
#[proc_macro_derive(Combined)]
#[attribute(ActualName)]
pub fn my_macro(input: TokenStream) -> TokenStream {
let mut input: DeriveInput = syn::parse(input).unwrap();
for attr in input.attrs.iter().map(Attribute::interpret_meta).filter(|x| x.is_some()).map(|x| x.unwrap()) {
if &attr.name().to_string()[..] != "ActualName" { continue }
let name;
match attr {
Meta::Word(ident) => { panic!("ActualName must be a name-value pair (i.e. #[ActualName = \"hey\"])"); },
Meta::List(_) => { panic!("ActualName must be a name-value pair (i.e. #[ActualName = \"hey\"])"); },
Meta::NameValue(meta_name_value) => {
match meta_name_value.lit {
Lit::Str(lit_str) => { name = lit_str.value(); },
_ => { panic!("ActualName must be a string"); }
};
}
};
input.ident = Ident::new(&name[..], Span::call_site());
let expanded = quote! {
#[derive(Clone, Debug)]
#input
};
return expanded.into()
}
panic!("You must specify the ActualName attribute (i.e. #[Derive(Combined), ActualName = \"...\"]")
}
After putting this code in your derive crate, the following sample of code will work:
#![feature(custom_attribute)]
#[macro_use]
extern crate derive_combined;
#[derive(Combined)]
#[ActualName = "Stuff"]
struct Stuff_ {
pub a: i32,
pub b: i64,
}
fn main() {
println!("{:?}", Stuff { a: 10, b: 10 }.clone());
}
If you have any questions about implementing this, this is the tutorial I followed. If that doesn't help feel free to ask.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With