spring-macros 0.4.1

spring-rs Procedural Macros implementation
Documentation
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{
    AngleBracketedGenericArguments, GenericArgument, Meta, MetaList, PathArguments, Token, Type,
    TypePath,
};

fn inject_error_tip() -> syn::Error {
    syn::Error::new(
        Span::call_site(),
        "inject Service only support Named-field Struct",
    )
}

enum InjectableType {
    Option,
    Component(syn::Path),
    Config(syn::Path),
    ComponentRef(syn::Path),
    ConfigRef(syn::Path),
    FuncCall(syn::ExprCall),
    PrototypeArg(syn::Type),
}

impl InjectableType {
    fn order(&self) -> u8 {
        match self {
            Self::Option => 0,
            Self::Component(_) => 1,
            Self::Config(_) => 2,
            Self::ComponentRef(_) => 3,
            Self::ConfigRef(_) => 4,
            Self::FuncCall(_) => 5,
            Self::PrototypeArg(_) => 6,
        }
    }

    fn is_arg(&self) -> bool {
        matches!(self, Self::PrototypeArg(_))
    }
}

enum InjectableAttr {
    Component,
    Config,
    FuncCall(syn::ExprCall),
}

struct Injectable {
    is_prototype: bool,
    ty: InjectableType,
    field_name: syn::Ident,
}

impl Injectable {
    fn new(field: syn::Field, is_prototype: bool) -> syn::Result<Self> {
        let ty = Self::compute_type(&field, is_prototype)?;
        let field_name = field.ident.ok_or_else(inject_error_tip)?;
        Ok(Self {
            is_prototype,
            ty,
            field_name,
        })
    }

    fn compute_type(field: &syn::Field, is_prototype: bool) -> syn::Result<InjectableType> {
        if let syn::Type::Path(path) = &field.ty {
            let ty = &path.path;
            let inject_attr = field
                .attrs
                .iter()
                .find(|attr| attr.path().is_ident("inject"));

            if let Some(inject_attr) = inject_attr {
                if let Meta::List(MetaList { tokens, .. }) = &inject_attr.meta {
                    let attr = syn::parse::<InjectableAttr>(tokens.clone().into())?;
                    return Ok(attr.make_type(ty));
                } else {
                    Err(syn::Error::new_spanned(
                inject_attr,
                "invalid inject definition, expected #[inject(component|config|func(args))]",
                    ))?;
                }
            }
            let last_path_segment = ty.segments.last().ok_or_else(inject_error_tip)?;
            if last_path_segment.ident == "ComponentRef" {
                return Ok(InjectableType::ComponentRef(Self::get_argument_type(
                    &last_path_segment.arguments,
                )?));
            }
            if last_path_segment.ident == "ConfigRef" {
                return Ok(InjectableType::ConfigRef(Self::get_argument_type(
                    &last_path_segment.arguments,
                )?));
            }
            if !is_prototype && last_path_segment.ident == "Option" {
                return Ok(InjectableType::Option);
            }
        }
        if is_prototype {
            Ok(InjectableType::PrototypeArg(field.ty.clone()))
        } else {
            let field_name = &field
                .ident
                .clone()
                .map(|ident| ident.to_string())
                .ok_or_else(inject_error_tip)?;
            Err(syn::Error::new_spanned(
            field,
            format!(
                "{field_name} field missing inject definition, expected #[inject(component|config|func(args))]",
            )))
        }
    }

    fn get_argument_type(path_args: &PathArguments) -> syn::Result<syn::Path> {
        if let PathArguments::AngleBracketed(AngleBracketedGenericArguments { args, .. }) =
            path_args
        {
            let ty = args.last().ok_or_else(inject_error_tip)?;
            if let GenericArgument::Type(Type::Path(TypePath { path, .. })) = ty {
                return Ok(path.clone());
            }
        }
        Err(inject_error_tip())
    }
}

impl syn::parse::Parse for InjectableAttr {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let name = input.parse::<syn::Path>()?;
        if name.is_ident("component") {
            return Ok(Self::Component);
        }
        if name.is_ident("config") {
            return Ok(Self::Config);
        }
        if name.is_ident("func") {
            input.parse::<Token![=]>()?;
            let func_call = input.parse::<syn::ExprCall>()?;
            return Ok(Self::FuncCall(func_call));
        }
        Err(syn::Error::new(
            Span::call_site(),
            "invalid inject definition, expected #[inject(component|config|func(args))]",
        ))
    }
}

impl InjectableAttr {
    fn make_type(self, ty: &syn::Path) -> InjectableType {
        match self {
            Self::Component => InjectableType::Component(ty.clone()),
            Self::Config => InjectableType::Config(ty.clone()),
            Self::FuncCall(func_call) => InjectableType::FuncCall(func_call),
        }
    }
}

impl ToTokens for Injectable {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            is_prototype,
            ty,
            field_name,
        } = self;
        match ty {
            InjectableType::Option => {
                tokens.extend(quote! {
                    let #field_name = None;
                });
            }
            InjectableType::Component(type_path) => {
                if *is_prototype {
                    tokens.extend(quote! {
                        let #field_name = ::spring::App::global().try_get_component::<#type_path>()?;
                    });
                } else {
                    tokens.extend(quote! {
                        let #field_name = app.try_get_component::<#type_path>()?;
                    });
                }
            }
            InjectableType::Config(type_path) => {
                if *is_prototype {
                    tokens.extend(quote! {
                        let #field_name = ::spring::App::global().get_config::<#type_path>()?;
                    });
                } else {
                    tokens.extend(quote! {
                        let #field_name = app.get_config::<#type_path>()?;
                    });
                }
            }
            InjectableType::ComponentRef(type_path) => {
                if *is_prototype {
                    tokens.extend(quote! {
                        let #field_name = ::spring::App::global().try_get_component_ref::<#type_path>()?;
                    });
                } else {
                    tokens.extend(quote! {
                        let #field_name = app.try_get_component_ref::<#type_path>()?;
                    });
                }
            }
            InjectableType::ConfigRef(type_path) => {
                if *is_prototype {
                    tokens.extend(quote! {
                        let #field_name = ::spring::config::ConfigRef::new(::spring::App::global().get_config::<#type_path>()?);
                    });
                } else {
                    tokens.extend(quote! {
                        let #field_name = ::spring::config::ConfigRef::new(app.get_config::<#type_path>()?);
                    });
                }
            }
            InjectableType::FuncCall(func_call) => {
                tokens.extend(quote! {
                    let #field_name = #func_call;
                });
            }
            InjectableType::PrototypeArg(type_path) => {
                // as func args
                tokens.extend(quote! {
                    #field_name: #type_path
                });
            }
        }
    }
}

struct Service {
    generics: syn::Generics,
    ident: proc_macro2::Ident,
    attr: Option<ServiceAttr>,
    fields: Vec<Injectable>,
}

enum ServiceAttr {
    Grpc(syn::Path),
    Prototype(syn::LitStr),
}

impl Service {
    fn new(input: syn::DeriveInput) -> syn::Result<Self> {
        let syn::DeriveInput {
            attrs,
            ident,
            generics,
            data,
            ..
        } = input;
        let service_attr = attrs
            .iter()
            .find(|a| a.path().is_ident("service"))
            .and_then(|attr| attr.parse_args_with(Self::parse_service_attr).ok());

        let is_prototype = matches!(&service_attr, Some(ServiceAttr::Prototype(_)));
        let mut fields = if let syn::Data::Struct(data) = data {
            data.fields
                .into_iter()
                .map(|f| Injectable::new(f, is_prototype))
                .collect::<syn::Result<Vec<_>>>()?
        } else {
            return Err(inject_error_tip());
        };
        fields.sort_by_key(|f| f.ty.order());

        // Put FuncCall at the end
        Ok(Self {
            generics,
            ident,
            attr: service_attr,
            fields,
        })
    }
    fn parse_service_attr(input: syn::parse::ParseStream) -> syn::Result<ServiceAttr> {
        let mut grpc: Option<syn::Path> = None;
        let mut prototype: Option<syn::LitStr> = None;

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;

            if input.peek(syn::Token![=]) {
                input.parse::<syn::Token![=]>()?;
                let value: syn::LitStr = input.parse()?;

                match ident.to_string().as_str() {
                    "grpc" => {
                        if grpc.is_some() || prototype.is_some() {
                            return Err(syn::Error::new_spanned(
                                ident,
                                "Only one of `grpc` or `prototype` is allowed",
                            ));
                        }
                        grpc = Some(value.parse()?);
                    }
                    "prototype" => {
                        if prototype.is_some() || grpc.is_some() {
                            return Err(syn::Error::new_spanned(
                                ident,
                                "Only one of `grpc` or `prototype` is allowed",
                            ));
                        }
                        prototype = Some(value);
                    }
                    other => {
                        return Err(syn::Error::new_spanned(
                            ident,
                            format!("Unknown key `{}` in #[service(...)], expected `grpc` or `prototype`", other),
                        ));
                    }
                }
            } else {
                // 标志形式:#[service(prototype)]
                match ident.to_string().as_str() {
                    "prototype" => {
                        if prototype.is_some() || grpc.is_some() {
                            return Err(syn::Error::new_spanned(
                                ident,
                                "Only one of `grpc` or `prototype` is allowed",
                            ));
                        }
                        prototype = Some(syn::LitStr::new("build", Span::call_site()));
                        // 默认build
                    }
                    "grpc" => {
                        return Err(syn::Error::new_spanned(
                            ident,
                            "`grpc` must have a value like `grpc = \"...\"`",
                        ));
                    }
                    other => {
                        return Err(syn::Error::new_spanned(
                            ident,
                            format!("Unknown key `{}` in #[service(...)]", other),
                        ));
                    }
                }
            }

            // 跳过逗号
            if input.peek(syn::Token![,]) {
                input.parse::<syn::Token![,]>()?;
            }
        }

        match (grpc, prototype) {
            (Some(path), None) => Ok(ServiceAttr::Grpc(path)),
            (None, Some(litstr_opt)) => Ok(ServiceAttr::Prototype(litstr_opt)),
            (None, None) => Err(syn::Error::new(
                input.span(),
                "Expected at least one of `grpc` or `prototype`",
            )),
            _ => unreachable!(),
        }
    }
}

impl ToTokens for Service {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            generics,
            ident,
            attr,
            fields,
        } = self;
        let field_names: Vec<&syn::Ident> = fields.iter().map(|f| &f.field_name).collect();

        let output = match attr {
            Some(ServiceAttr::Prototype(build)) => {
                let fn_name = syn::Ident::new(&build.value(), build.span());
                let (args, fields): (Vec<&Injectable>, Vec<&Injectable>) =
                    fields.iter().partition(|f| f.ty.is_arg());
                let syn::Generics {
                    lt_token,
                    params,
                    gt_token,
                    ..
                } = generics;
                quote! {
                    impl #lt_token #params #gt_token #ident #generics {
                        pub fn #fn_name(#(#args),*) -> ::spring::error::Result<Self> {
                            use ::spring::plugin::ComponentRegistry;
                            use ::spring::config::ConfigRegistry;
                            #(#fields)*
                            Ok(Self { #(#field_names),* })
                        }
                    }
                }
            }
            _ => {
                let service_registrar =
                    syn::Ident::new(&format!("__ServiceRegistrarFor_{ident}"), ident.span());
                let service_installer = match attr {
                    Some(ServiceAttr::Grpc(server)) => {
                        quote! {
                            use ::spring::plugin::MutableComponentRegistry;
                            use ::spring_grpc::GrpcConfigurator;
                            let service = #ident::build(app)?;
                            let grpc_server = #server::new(service.clone());
                            app.add_component(service).add_service(grpc_server);
                        }
                    }
                    _ => {
                        quote! {
                            use ::spring::plugin::MutableComponentRegistry;
                            app.add_component(#ident::build(app)?);
                        }
                    }
                };
                quote! {
                    impl ::spring::plugin::service::Service for #ident {
                        fn build<R>(app: &R) -> ::spring::error::Result<Self>
                        where
                            R: ::spring::plugin::ComponentRegistry + ::spring::config::ConfigRegistry
                        {
                            #(#fields)*
                            Ok(Self { #(#field_names),* })
                        }
                    }
                    #[allow(non_camel_case_types)]
                    struct #service_registrar;
                    impl ::spring::plugin::service::ServiceRegistrar for #service_registrar{
                        fn install_service(&self, app: &mut ::spring::app::AppBuilder)->::spring::error::Result<()> {
                            #service_installer
                            Ok(())
                        }
                    }
                    ::spring::submit_service!(#service_registrar);
                }
            }
        };
        tokens.extend(output);
    }
}

pub(crate) fn expand_derive(input: syn::DeriveInput) -> syn::Result<TokenStream> {
    Ok(Service::new(input)?.into_token_stream())
}