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
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 {
type_: syn::Ident,
field: ApiField,
name: syn::Ident,
raw_value: String,
variant: syn::Ident,
}
fn get_lit_string(lit: syn::Lit) -> String {
match lit {
syn::Lit::Str(lit) => lit.value(),
_ => panic!("Expected api attribute to be a string"),
}
}
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;
ast.attrs
.iter()
.filter(|a| a.path.is_ident("api"))
.for_each(|a| {
if let Ok(syn::Meta::List(l)) = a.parse_meta() {
for nested in l.nested {
match nested {
syn::NestedMeta::Meta(syn::Meta::NameValue(m))
if m.path.is_ident("category") =>
{
category = Some(get_lit_string(m.lit))
}
_ => panic!("unknown api attribute"),
}
}
}
});
let category = category.expect("`category`");
let fields: Vec<_> = enum_
.variants
.iter()
.filter_map(|variant| {
for attr in &variant.attrs {
if attr.path.is_ident("api") {
let meta = attr.parse_meta();
match meta {
Ok(syn::Meta::List(l)) => {
let mut type_: Option<String> = None;
let mut field: Option<ApiField> = None;
for nested in l.nested.into_iter() {
match nested {
syn::NestedMeta::Meta(syn::Meta::NameValue(m))
if m.path.is_ident("type") =>
{
if type_.is_none() {
type_ = Some(get_lit_string(m.lit));
} else {
panic!("type can only be specified once");
}
}
syn::NestedMeta::Meta(syn::Meta::NameValue(m))
if m.path.is_ident("field") =>
{
if field.is_none() {
field = Some(ApiField::Property(quote::format_ident!(
"{}",
get_lit_string(m.lit)
)));
} else {
panic!("field/flatten can only be specified once");
}
}
syn::NestedMeta::Meta(syn::Meta::Path(m))
if m.is_ident("flatten") =>
{
if field.is_none() {
field = Some(ApiField::Flattened);
} else {
panic!("field/flatten can only be specified once");
}
}
_ => panic!("Couldn't parse api attribute"),
}
}
let name =
format_ident!("{}", variant.ident.to_string().to_case(Case::Snake));
let raw_value = variant.ident.to_string().to_lowercase();
return Some(ApiAttribute {
type_: quote::format_ident!("{}", type_.expect("type")),
field: field.expect("one of field/flatten"),
name,
raw_value,
variant: variant.ident.clone(),
});
}
_ => panic!("Couldn't parse api attribute"),
}
}
}
None
})
.collect();
let accessors = fields.iter().map(
|ApiAttribute {
type_, field, name, ..
}| match field {
ApiField::Property(prop) => {
let prop_str = prop.to_string();
quote! {
pub fn #name(&self) -> serde_json::Result<#type_> {
self.0.decode_field(#prop_str)
}
}
}
ApiField::Flattened => quote! {
pub fn #name(&self) -> serde_json::Result<#type_> {
self.0.decode()
}
},
},
);
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()
}