~lthms/typed-urls

ref: 88801d6a51eba5734c80d4ade65b321a01552b81 typed-urls/typed-urls-derive/src/lib.rs -rw-r--r-- 7.6 KiB
88801d6aThomas Letan Remove the Routing trait in favor of the more logical TypedUrl 9 months ago
                                                                                
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
#[macro_use]
extern crate syn;
#[macro_use]
extern crate quote;

use std::collections::HashMap;

use proc_macro::TokenStream;
use syn::export::{Span, TokenStream2 as Quote};
use syn::{
    Attribute, Data, DataEnum, DeriveInput, Fields, Ident, Lit, LitStr, Meta,
    MetaNameValue, Type, Variant,
};

#[proc_macro_derive(TypedUrl, attributes(routefmt))]
pub fn derive_typed_url_main(input : TokenStream) -> TokenStream {
    let ast : DeriveInput = parse_macro_input!(input as DeriveInput);

    let res = derive_typed_url_boilerplate(&ast);

    res.into()
}

fn find_format(attrs : &Vec<Attribute>) -> LitStr {
    for attr in attrs {
        if attr.path.is_ident("routefmt") {
            match attr.parse_meta().unwrap() {
                Meta::NameValue(MetaNameValue {
                    lit: Lit::Str(str), ..
                }) => return str,
                _ => break,
            }
        } else {
            continue;
        }
    }

    panic!("Missing attribute `routefmt'")
}

fn format_table(ast : &DataEnum) -> HashMap<Ident, LitStr> {
    let mut res = HashMap::with_capacity(ast.variants.len());

    for variant in ast.variants.iter() {
        let ident = variant.ident.clone();
        let fmt = find_format(&variant.attrs);

        res.insert(ident, fmt);
    }

    res
}

fn get_fields_name(ast : &Variant) -> Vec<Ident> {
    match ast.fields {
        Fields::Named(ref named_fields) => named_fields
            .named
            .iter()
            .map(|x| x.ident.clone().unwrap())
            .collect::<Vec<Ident>>(),
        Fields::Unit => Vec::new(),
        _ => panic!("Unnamed fields are not supported"),
    }
}

fn get_typed_fields(ast : &Variant) -> Vec<(Type, Ident)> {
    match ast.fields {
        Fields::Named(ref named_fields) => named_fields
            .named
            .iter()
            .map(|x| (x.ty.clone(), x.ident.clone().unwrap()))
            .collect::<Vec<_>>(),
        Fields::Unit => Vec::new(),
        _ => panic!("Unnamed fields are not supported"),
    }
}

fn fields_table(ast : &DataEnum) -> HashMap<Ident, Vec<Ident>> {
    let mut res = HashMap::with_capacity(ast.variants.len());

    for variant in ast.variants.iter() {
        let ident = variant.ident.clone();
        let fields = get_fields_name(&variant);

        res.insert(ident, fields);
    }

    res
}

fn typed_fields_table(ast : &DataEnum) -> HashMap<Ident, Vec<(Type, Ident)>> {
    let mut res = HashMap::with_capacity(ast.variants.len());

    for variant in ast.variants.iter() {
        let ident = variant.ident.clone();
        let fields = get_typed_fields(&variant);

        res.insert(ident, fields);
    }

    res
}

fn derive_enum_display_impl(
    name : &Ident,
    ast : &DataEnum,
    fmts : &HashMap<Ident, LitStr>,
    fields : &HashMap<Ident, Vec<Ident>>,
) -> Quote {
    let mut match_bodies = vec![];

    for variant in ast.variants.iter() {
        let ident = variant.ident.clone();
        let fmt = fmts.get(&ident).unwrap();
        let flds = fields.get(&ident).unwrap();

        match_bodies.push(quote! {
            #name::#ident { #(#flds),* } => write!(f, #fmt, #(#flds),*)
        });
    }

    quote! {
        impl std::fmt::Display for #name {
            fn fmt(&self, f : &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self {
                    #(#match_bodies),*
                }
            }
        }
    }
}

fn ident_to_litstr(
    prefix : &str,
    id : &Ident,
    suffix : &str,
) -> LitStr {
    LitStr::new(&format!("{}{}{}", prefix, id, suffix), Span::call_site())
}

fn derive_route_display_impl(
    ast : &DataEnum,
    fmts : &HashMap<Ident, LitStr>,
    fields : &HashMap<Ident, Vec<Ident>>,
) -> Quote {
    let mut match_bodies = vec![];

    for variant in ast.variants.iter() {
        let ident = variant.ident.clone();
        let fmt = fmts.get(&ident).unwrap();
        let flds = fields
            .get(&ident)
            .unwrap()
            .iter()
            .map(|x| ident_to_litstr("{", x, "}"))
            .collect::<Vec<LitStr>>();

        match_bodies.push(quote! {
            Route::#ident => write!(f, #fmt, #(#flds),*)
        });
    }

    quote! {
        impl std::fmt::Display for Route {
            fn fmt(&self, f : &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self {
                    #(#match_bodies),*
                }
            }
        }
    }
}

fn derive_typed_url_boilerplate(ast : &DeriveInput) -> Quote {
    let enum_name = &ast.ident;
    let enum_ast = get_enum_data(&ast);

    let fields = fields_table(&enum_ast);
    let typed_field = typed_fields_table(&enum_ast);
    let fmts = format_table(&enum_ast);

    let route_enum = derive_route_enum(enum_ast);
    let route_display = derive_route_display_impl(enum_ast, &fmts, &fields);
    let routes = derive_routes_array(enum_ast);

    let enum_typed_url_impl =
        derive_enum_typed_url_impl(enum_name, enum_ast, &typed_field, &fields);

    let enum_display =
        derive_enum_display_impl(enum_name, &enum_ast, &fmts, &fields);

    quote! {
        #route_enum
        #route_display
        #routes

        #enum_display
        #enum_typed_url_impl
    }
}

fn get_enum_data(input : &DeriveInput) -> &DataEnum {
    match input.data {
        Data::Enum(ref data) => data,
        _ => panic!("Should be an enum"),
    }
}

fn derive_route_enum(enum_ast : &DataEnum) -> Quote {
    let idents = enum_ast
        .variants
        .iter()
        .map(|x| {
            let tok = &x.ident;
            quote! { #tok }
        })
        .collect::<Vec<_>>();

    quote! {
        #[derive(Debug, Clone)]
        pub enum Route {
            #(#idents),*
        }
    }
}

fn derive_enum_from_route(
    name : &Ident,
    enum_ast : &DataEnum,
    tf : &HashMap<Ident, Vec<(Type, Ident)>>,
    uf : &HashMap<Ident, Vec<Ident>>,
) -> Quote {
    let mut match_bodies = vec![];

    for variant in enum_ast.variants.iter() {
        let ident = variant.ident.clone();
        let typed_fields = tf.get(&ident).unwrap();
        let untyped_fields = uf.get(&ident).unwrap();

        let mut arg_fetch = vec![];

        for (ty, field) in typed_fields.iter() {
            let fname = ident_to_litstr("", field, "");

            arg_fetch.push(quote! {
                let #field = args.get(#fname).and_then(<#ty as UrlPathParam>::from_value)?;
            })
        }

        match_bodies.push(quote! {
            Route::#ident => {
                #(#arg_fetch)*
                Some(#name::#ident { #(#untyped_fields),* })
            }
        });
    }

    quote! {
        fn from_route(
            route : &Self::Route,
            args : &std::collections::HashMap<String, serde_json::Value>,
        ) -> Option<#name> {
            use typed_urls::UrlPathParam;
            match route {
                #(#match_bodies),*
            }
        }
    }
}

fn derive_enum_typed_url_impl(
    name : &Ident,
    enum_ast : &DataEnum,
    tf : &HashMap<Ident, Vec<(Type, Ident)>>,
    uf : &HashMap<Ident, Vec<Ident>>,
) -> Quote {
    let from_route_impl = derive_enum_from_route(name, enum_ast, tf, uf);

    quote! {
        impl typed_urls::TypedUrl for #name {
            type Route = Route;

            #from_route_impl

            fn routes() -> &'static [Self::Route] {
                ROUTES
            }
        }
    }
}

fn derive_routes_array(enum_ast : &DataEnum) -> Quote {
    let idents = enum_ast
        .variants
        .iter()
        .map(|x| {
            let tok = &x.ident;
            quote! { #tok }
        })
        .collect::<Vec<_>>();

    quote! {
        const ROUTES : &[Route] = &[
            #(Route::#idents),*
        ];
    }
}