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
#![crate_type = "proc-macro"]
extern crate proc_macro;
extern crate syn;
#[macro_use]
extern crate quote;
use proc_macro::TokenStream;
use syn::{Body, VariantData};
#[proc_macro_derive(QueryParams)]
pub fn derive_query_params(input: TokenStream) -> TokenStream {
let input = input.to_string();
let ast = syn::parse_derive_input(&input).unwrap();
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let query_params = gen_serialization_query_params(&ast.body);
let gen = quote! {
impl #impl_generics #name #ty_generics #where_clause {
fn to_query_params(&self) -> String {
#query_params
}
}
};
gen.parse().expect(format!("An error occurred when parsing the tokens generate for {} struct",name).as_str())
}
fn gen_serialization_query_params(body: &Body) -> quote::Tokens {
match *body {
Body::Struct(VariantData::Struct(ref fs)) => {
let query_params: Vec<quote::Tokens> = get_print_fields(fs);
quote! {
let mut buf = String::from("?");
(#(#query_params),*);
let len_query_params = buf.len();
buf.truncate(len_query_params - 1);
return buf;
}
}
Body::Struct(VariantData::Tuple(_)) => panic!("#[derive(QueryParams)] is only defined for structs, not tuple"),
Body::Struct(VariantData::Unit) => panic!("#[derive(QueryParams)] is only defined for structs, not unit"),
Body::Enum(_) => panic!("#[derive(QueryParams)] is only defined for structs, not enum"),
}
}
fn get_print_fields(fields: &Vec<syn::Field>) -> Vec<quote::Tokens> {
fields.iter()
.map(|f| (&f.ident, &f.ty))
.map(|(ident, ty)| match ty {
&syn::Ty::Path(_, ref path) => (ident, extract_type_name(path)),
_ => unimplemented!(),
})
.map(|(ident, path)| match path {
"Vec" => vec_to_query_params(ident),
"Option" => option_to_query_params(ident),
_ => primitive_to_query_params(ident),
})
.collect()
}
#[inline]
fn extract_type_name(path: &syn::Path) -> &str {
path.segments.last().unwrap().ident.as_ref()
}
fn vec_to_query_params(ident: &Option<syn::Ident>) -> quote::Tokens {
quote! {
buf.push_str((format!("{}={}&",
stringify!(#ident),
self.#ident
.iter()
.fold(String::new(), |acc, ref val| acc + &val.to_string() + ","))
.as_str()
)
.replace(",&", "&")
.as_str())
}
}
fn option_to_query_params(ident: &Option<syn::Ident>) -> quote::Tokens {
quote! {
if self.#ident.is_some() {
buf.push_str(format!("{}={}&", stringify!(#ident), self.#ident.as_ref().unwrap()).as_str())
}
}
}
fn primitive_to_query_params(ident: &Option<syn::Ident>) -> quote::Tokens {
quote!{
buf.push_str(format!("{}={}&", stringify!(#ident), self.#ident).as_str())
}
}