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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use convert_case::{Case, Casing};
use proc_macro::TokenStream;
use quote::{format_ident, quote};

#[proc_macro_derive(ApiCategory, attributes(api))]
pub fn derive_api_category(input: TokenStream) -> TokenStream {
    let ast = syn::parse(input).unwrap();

    impl_api_category(&ast)
}

#[derive(Debug)]
enum ApiField {
    Property(syn::Ident),
    Flattened,
}

#[derive(Debug)]
struct ApiAttribute {
    field: ApiField,
    name: syn::Ident,
    raw_value: String,
    variant: syn::Ident,
    type_name: proc_macro2::TokenStream,
    with: Option<syn::Ident>,
}

fn impl_api_category(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;

    let enum_ = match &ast.data {
        syn::Data::Enum(data) => data,
        _ => panic!("ApiCategory can only be derived for enums"),
    };

    let mut category: Option<String> = None;
    for attr in &ast.attrs {
        if attr.path().is_ident("api") {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("category") {
                    let c: syn::LitStr = meta.value()?.parse()?;
                    category = Some(c.value());
                    Ok(())
                } else {
                    Err(meta.error("unknown attribute"))
                }
            })
            .unwrap();
        }
    }

    let category = category.expect("`category`");

    let fields: Vec<_> = enum_
        .variants
        .iter()
        .filter_map(|variant| {
            let mut r#type: Option<String> = None;
            let mut field: Option<ApiField> = None;
            let mut with: Option<proc_macro2::Ident> = None;
            for attr in &variant.attrs {
                if attr.path().is_ident("api") {
                    attr.parse_nested_meta(|meta| {
                        if meta.path.is_ident("type") {
                            let t: syn::LitStr = meta.value()?.parse()?;
                            r#type = Some(t.value());
                            Ok(())
                        } else if meta.path.is_ident("with") {
                            let w: syn::LitStr = meta.value()?.parse()?;
                            with = Some(quote::format_ident!("{}", w.value()));
                            Ok(())
                        } else if meta.path.is_ident("field") {
                            let f: syn::LitStr = meta.value()?.parse()?;
                            field = Some(ApiField::Property(quote::format_ident!("{}", f.value())));
                            Ok(())
                        } else if meta.path.is_ident("flatten") {
                            field = Some(ApiField::Flattened);
                            Ok(())
                        } else {
                            Err(meta.error("unsupported attribute"))
                        }
                    })
                    .unwrap();
                    let name = format_ident!("{}", variant.ident.to_string().to_case(Case::Snake));
                    let raw_value = variant.ident.to_string().to_lowercase();
                    return Some(ApiAttribute {
                        field: field.expect("field or flatten attribute must be specified"),
                        raw_value,
                        variant: variant.ident.clone(),
                        type_name: r#type.expect("type must be specified").parse().unwrap(),
                        name,
                        with,
                    });
                }
            }
            None
        })
        .collect();

    let accessors = fields.iter().map(
        |ApiAttribute {
             field,
             name,
             type_name,
             with,
             ..
         }| match (field, with) {
            (ApiField::Property(prop), None) => {
                let prop_str = prop.to_string();
                quote! {
                    pub fn #name(&self) -> serde_json::Result<#type_name> {
                        self.0.decode_field(#prop_str)
                    }
                }
            }
            (ApiField::Property(prop), Some(f)) => {
                let prop_str = prop.to_string();
                quote! {
                    pub fn #name(&self) -> serde_json::Result<#type_name> {
                        self.0.decode_field_with(#prop_str, #f)
                    }
                }
            }
            (ApiField::Flattened, None) => quote! {
                pub fn #name(&self) -> serde_json::Result<#type_name> {
                    self.0.decode()
                }
            },
            (ApiField::Flattened, Some(_)) => todo!(),
        },
    );

    let raw_values = fields.iter().map(
        |ApiAttribute {
             variant, raw_value, ..
         }| {
            quote! {
                #name::#variant => #raw_value
            }
        },
    );

    let gen = quote! {
        pub struct Response(crate::ApiResponse);

        impl Response {
            #(#accessors)*
        }

        impl crate::ApiCategoryResponse for Response {
            type Selection = #name;

            fn from_response(response: crate::ApiResponse) -> Self {
                Self(response)
            }
        }

        impl crate::ApiSelection for #name {
            fn raw_value(self) -> &'static str {
                match self {
                    #(#raw_values,)*
                }
            }

            fn category() -> &'static str {
                #category
            }
        }
    };

    gen.into()
}

#[proc_macro_derive(IntoOwned, attributes(into_owned))]
pub fn derive_into_owned(input: TokenStream) -> TokenStream {
    let ast = syn::parse(input).unwrap();

    impl_into_owned(&ast)
}

fn to_static_lt(ty: &mut syn::Type) -> bool {
    let mut res = false;
    match ty {
        syn::Type::Path(path) => {
            if let Some(syn::PathArguments::AngleBracketed(ab)) = path
                .path
                .segments
                .last_mut()
                .map(|s| &mut s.arguments)
                .as_mut()
            {
                for mut arg in &mut ab.args {
                    match &mut arg {
                        syn::GenericArgument::Type(ty) => {
                            if to_static_lt(ty) {
                                res = true;
                            }
                        }
                        syn::GenericArgument::Lifetime(lt) => {
                            lt.ident = syn::Ident::new("static", proc_macro2::Span::call_site());
                            res = true;
                        }
                        _ => (),
                    }
                }
            }
        }
        syn::Type::Reference(r) => {
            if let Some(lt) = r.lifetime.as_mut() {
                lt.ident = syn::Ident::new("static", proc_macro2::Span::call_site());
                res = true;
            }
            to_static_lt(&mut r.elem);
        }
        _ => (),
    };
    res
}

fn impl_into_owned(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

    let mut identity = false;
    for attr in &ast.attrs {
        if attr.path().is_ident("into_owned") {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("identity") {
                    identity = true;
                    Ok(())
                } else {
                    Err(meta.error("unknown attribute"))
                }
            })
            .unwrap();
        }
    }

    if identity {
        return quote! {
            impl #impl_generics crate::into_owned::IntoOwned for #name #ty_generics #where_clause {
                type Owned = Self;
                fn into_owned(self) -> Self::Owned {
                    self
                }
            }
        }
        .into();
    }

    let syn::Data::Struct(r#struct) = &ast.data else {
        panic!("Only stucts are supported");
    };

    let syn::Fields::Named(named_fields) = &r#struct.fields else {
        panic!("Only named fields are supported");
    };

    let vis = &ast.vis;

    for attr in &ast.attrs {
        if attr.path().is_ident("identity") {
            //
        }
    }

    let mut owned_fields = Vec::with_capacity(named_fields.named.len());
    let mut fields = Vec::with_capacity(named_fields.named.len());

    for field in &named_fields.named {
        let field_name = &field.ident.as_ref().unwrap();
        let mut ty = field.ty.clone();
        let vis = &field.vis;

        if to_static_lt(&mut ty) {
            owned_fields
                .push(quote! { #vis #field_name: <#ty as crate::into_owned::IntoOwned>::Owned });
            fields.push(
                quote! { #field_name: crate::into_owned::IntoOwned::into_owned(self.#field_name) },
            );
        } else {
            owned_fields.push(quote! { #vis #field_name: #ty });
            fields.push(quote! { #field_name: self.#field_name });
        };
    }

    let owned_name = syn::Ident::new(
        &format!("{}Owned", ast.ident),
        proc_macro2::Span::call_site(),
    );

    let gen = quote! {
        #[derive(Debug, Clone)]
        #vis struct #owned_name {
            #(#owned_fields,)*
        }
        impl #impl_generics crate::into_owned::IntoOwned for #name #ty_generics #where_clause {
            type Owned = #owned_name;
            fn into_owned(self) -> Self::Owned {
                #owned_name {
                    #(#fields,)*
                }
            }
        }
    };

    gen.into()
}