derive_with/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::{format_ident, quote};
use syn::parse::Parse;
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::{Attribute, Index, Meta, Token};

/// A custom derive implementation for `#[derive(With)]`
///
/// # Get started
///
/// 1.Generate with-constructor for each field
/// ```rust
/// use derive_with::With;
///
/// #[derive(With, Default)]
/// pub struct Foo {
///     pub a: i32,
///     pub b: String,
/// }
///
/// #[derive(With, Default)]
/// pub struct Bar (i32, String);
///
/// #[test]
/// fn test_struct() {
///     let foo = Foo::default().with_a(1).with_b(1.to_string());
///     assert_eq!(foo.a, 1);
///     assert_eq!(foo.b, "1".to_string());
///
///     let bar = Bar::default().with_0(1).with_1(1.to_string());
///     assert_eq!(bar.0, 1);
///     assert_eq!(bar.1, "1".to_string());
/// }
/// ```
///
/// 2.Generate with-constructor for specific fields
/// ```rust
/// use derive_with::With;
///
/// #[derive(With, Default)]
/// #[with(a)]
/// pub struct Foo {
///     pub a: i32,
///     pub b: String,
/// }
///
/// #[derive(With, Default)]
/// #[with(1)]
/// pub struct Bar (i32, String);
///
/// #[test]
/// fn test_struct() {
///     let foo = Foo::default().with_a(1);
///     assert_eq!(foo.a, 1);
///
///     let bar = Bar::default().with_1(1.to_string());
///     assert_eq!(bar.1, "1".to_string());
/// }
/// ```
#[proc_macro_derive(With, attributes(with))]
pub fn derive(input: TokenStream) -> TokenStream {
    let ast: syn::DeriveInput = syn::parse(input).expect("Couldn't parse item");
    let result = match ast.data {
        syn::Data::Struct(ref s) => with_for_struct(&ast, &s.fields),
        syn::Data::Enum(_) => panic!("doesn't work with enums yet"),
        syn::Data::Union(_) => panic!("doesn't work with unions yet"),
    };
    result.into()
}

fn with_for_struct(ast: &syn::DeriveInput, fields: &syn::Fields) -> proc_macro2::TokenStream {
    match *fields {
        syn::Fields::Named(ref fields) => with_constructor_for_named(ast, &fields.named),
        syn::Fields::Unnamed(ref fields) => with_constructor_for_unnamed(ast, &fields.unnamed),
        syn::Fields::Unit => panic!("Unit structs are not supported"),
    }
}

fn with_constructor_for_named(
    ast: &syn::DeriveInput,
    fields: &Punctuated<syn::Field, Token![,]>,
) -> proc_macro2::TokenStream {
    let name = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
    let with_args = parse_with_args::<Ident>(&ast.attrs);

    let mut constructors = quote!();
    for field in fields {
        let field_name = field.ident.as_ref().unwrap();
        if !contains_field(&with_args, field_name) {
            continue;
        }
        let field_type = &field.ty;
        let constructor_name = format_ident!("with_{}", field_name);

        let constructor = quote! {
            pub fn #constructor_name(mut self, #field_name: impl Into<#field_type>) -> Self {
                self.#field_name = #field_name.into();
                self
            }
        };
        constructors = quote! {
            #constructors
            #constructor
        };
    }
    quote! {
        impl #impl_generics #name #ty_generics #where_clause {
            #constructors
        }
    }
}

fn with_constructor_for_unnamed(
    ast: &syn::DeriveInput,
    fields: &Punctuated<syn::Field, Token![,]>,
) -> proc_macro2::TokenStream {
    let name = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
    let with_args = parse_with_args::<Index>(&ast.attrs);

    let mut constructors = quote!();
    for (index, field) in fields.iter().enumerate() {
        let index = syn::Index::from(index);
        if !contains_field(&with_args, &index) {
            continue;
        }
        let field_type = &field.ty;
        let param_name = format_ident!("field_{}", index);
        let constructor_name = format_ident!("with_{}", index);

        let constructor = quote! {
            pub fn #constructor_name(mut self, #param_name: impl Into<#field_type>) -> Self {
                self.#index = #param_name.into();
                self
            }
        };
        constructors = quote! {
            #constructors
            #constructor
        };
    }
    quote! {
        impl #impl_generics #name #ty_generics #where_clause {
            #constructors
        }
    }
}

fn parse_with_args<T: Parse>(attrs: &Vec<Attribute>) -> Option<Punctuated<T, Comma>> {
    if let Some(attr) = attrs.iter().find(|attr| attr.path().is_ident("with")) {
        match &attr.meta {
            Meta::List(list) => Some(
                list.parse_args_with(Punctuated::<T, Comma>::parse_terminated)
                    .expect("Couldn't parse with args"),
            ),
            _ => panic!("`with` attribute should like `#[with(a, b, c)]`"),
        }
    } else {
        None
    }
}

fn contains_field<T: Parse + PartialEq>(
    with_args: &Option<Punctuated<T, Comma>>,
    item: &T,
) -> bool {
    with_args.is_none() || with_args.as_ref().unwrap().iter().any(|arg| arg == item)
}