Hi Rustceans ,
I'm having trouble with proc_marcos and Derive. I'm trying to add a field on an existing struct with derive. But obviously my implementation doesn't work.
I already take a look at this question but without success.
Here's what I'm trying to achieve :
use proc_macro_issue_minimal_example::AddField;
#[derive(AddField)]
struct Foo {}
// Foo should be expanded to :
// struct Foo {
// pub a: String
// }
let bar = Foo { a: "lorem ipsum".to_string()};
But the compiler throw an error :
error[E0560]: struct `Foo` has no field named `a`
--> tests/01-shoud-add-struct-field.rs:17:25
|
17 | let bar = Foo { a: "lorem ipsum".to_string()};
| ^ `Foo` does not have this field
Here's my current implementation :
use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput, parse::Parser};
use quote::quote;
#[proc_macro_derive(AddField, attributes(unimarc))]
pub fn derive(input: TokenStream) -> TokenStream {
let mut ast = parse_macro_input!(input as DeriveInput);
match &mut ast.data {
syn::Data::Struct(ref mut struct_data) => {
match &mut struct_data.fields {
syn::Fields::Named(fields) => {
fields
.named
.push(syn::Field::parse_named.parse2(quote! { pub a: String }).unwrap());
}
_ => {
()
}
}
// I tried
//
// return quote! {
// #ast
// }.into();
//
// But it fails with error : `Foo` redefined here previous definition of the type `Foo` here
//
// So instead I return an empty TokenStream but the field is not added
TokenStream::new()
}
_ => panic!("AddField has to be used with structs "),
}
}
I created a minimal (not) working example with tests on GitHub : https://github.com/eonm-abes/proc-macro-issue-minimal-example
Thank you,
Best Regards