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
441
442
443
444
445
446
447
448
449
//! [<img alt="github" src="https://img.shields.io/badge/github-udoprog/async--injector-8da0cb?style=for-the-badge&logo=github" height="20">](https://github.com/udoprog/async-injector)
//! [<img alt="crates.io" src="https://img.shields.io/crates/v/async-injector-derive.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/async-injector-derive)
//! [<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-async--injector--derive-66c2a5?style=for-the-badge&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/async-injector-derive)
//! [<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/udoprog/async-injector/ci.yml?branch=main&style=for-the-badge" height="20">](https://github.com/udoprog/async-injector/actions?query=branch%3Amain)
//!
//! Macros for [async-injector](https://docs.rs/async-injector).
//!
//! This provides the [Provider] derive, which can be used to automatically
//! construct and inject dependencies. See its documentation for how to use.
//!
//! [Provider]: https://docs.rs/async-injector/latest/async_injector/derive.Provider.html

#![recursion_limit = "256"]

extern crate proc_macro;

use darling::FromMeta;
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::spanned::Spanned as _;
use syn::*;

/// Helper derive to implement a provider.
///
/// The `Provider` derive can only be used on struct. Each field designates a
/// value that must either be injected, or provided during construction.
///
/// ```rust
/// use async_injector::Provider;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// enum Tag {
///     Table,
///     Url,
/// }
///
/// #[derive(Provider)]
/// struct Deps {
///     fixed: String,
///     #[dependency(optional, tag = "Tag::Table")]
///     table: Option<String>,
///     #[dependency(tag = "Tag::Url")]
///     url: String,
///     #[dependency]
///     connection_limit: u32,
/// }
/// ```
///
/// This generates another struct named `DepsProvider`, with the following api:
///
/// ```rust,no_run
/// use async_injector::{Error, Injector};
///
/// # struct Deps {}
/// impl Deps {
///     /// Construct a new provider.
///     async fn provider(injector: &Injector, fixed: String) -> Result<DepsProvider, Error>
///     # { todo!() }
/// }
///
/// struct DepsProvider {
///     /* private fields */
/// }
///
/// impl DepsProvider {
///     /// Try to construct the current value. Returns [None] unless all
///     /// required dependencies are available.
///     fn build(&mut self) -> Option<Deps>
///     # { todo!() }
///
///     /// Wait until we can successfully build the complete provided
///     /// value.
///     async fn wait(&mut self) -> Deps
///     # { todo!() }
///
///     /// Wait until the provided value has changed. Either some
///     /// dependencies are no longer available at which it returns `None`,
///     /// or all dependencies are available after which we return the
///     /// build value.
///     async fn wait_for_update(&mut self) -> Option<Deps>
///     # { todo!() }
/// }
/// ```
///
/// The `provider` associated function takes the reference to an injector as its
/// first argument and any fields which are not marked as a `#[dependency]`.
/// These are called fixed fields.
///
/// <br>
///
/// # The `#[dependency]` field attribute
///
/// The `#[dependency]` attribute can be used to mark fields which need to be
/// injected. It takes an optional `#[dependency(tag = "..")]`, which allows you
/// to specify the tag to use when constructing the injected [Key].
///
/// ```rust
/// use async_injector::Provider;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// enum Tag {
///     First,
/// }
///
/// #[derive(Provider)]
/// struct Params {
///     #[dependency(tag = "Tag::First")]
///     tagged: String,
///     #[dependency]
///     number: u32,
/// }
/// ```
///
/// Optional fields use the [Option] type and must be marked with the `optional`
/// meta attribute.
///
/// ```rust
/// use async_injector::Provider;
///
/// #[derive(Provider)]
/// struct Params {
///     #[dependency(optional)]
///     table: Option<String>,
/// }
/// ```
///
/// [Key]: https://docs.rs/async-injector/0/async_injector/struct.Key.html
#[proc_macro_derive(Provider, attributes(dependency))]
pub fn provider_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let ast = syn::parse_macro_input!(input as DeriveInput);

    match implement(&ast) {
        Ok(stream) => stream,
        Err(e) => e.to_compile_error(),
    }
    .into()
}

/// Derive to implement the `Provider` trait.
fn implement(ast: &DeriveInput) -> syn::Result<TokenStream> {
    let st = match ast.data {
        Data::Struct(ref st) => st,
        _ => panic!("`Provider` attribute is only supported on structs"),
    };

    let config = provider_config(st)?;
    let (provider, provider_ident, fixed_args, fixed_idents) = impl_provider(ast, &config);

    let vis = &ast.vis;
    let ident = &ast.ident;
    let generics = &ast.generics;

    let output = quote! {
        impl #generics #ident #generics {
            /// Construct a new provider for this type.
            #vis async fn provider(injector: &::async_injector::Injector #(, #fixed_args)*) -> Result<#provider_ident #generics, ::async_injector::Error> {
                #provider_ident::new(injector #(, #fixed_idents)*).await
            }
        }

        #provider
    };

    Ok(output)
}

/// Build a provider configuration.
fn provider_config(st: &DataStruct) -> syn::Result<ProviderConfig<'_>> {
    let fields = provider_fields(st)?;
    Ok(ProviderConfig { fields })
}

/// Extracts provider fields.
fn provider_fields(st: &DataStruct) -> syn::Result<Vec<ProviderField<'_>>> {
    let mut fields = Vec::new();

    for field in &st.fields {
        let ident = field.ident.as_ref().expect("missing identifier for field");

        let mut dependency = None;

        for a in &field.attrs {
            let meta = match a.parse_meta() {
                Ok(meta) => meta,
                _ => continue,
            };

            if meta.path().is_ident("dependency") {
                if dependency.is_some() {
                    return Err(syn::Error::new(
                        meta.span(),
                        "multiple #[dependency] attributes are not supported",
                    ));
                }

                let d = if let Meta::Path(_) = meta {
                    DependencyAttr::default()
                } else {
                    match DependencyAttr::from_meta(&meta) {
                        Ok(d) => d,
                        Err(e) => panic!("bad #[dependency(..)] attribute: {}", e),
                    }
                };

                dependency = Some((meta.span(), d));
                continue;
            }
        }

        let dependency = match dependency {
            Some((span, dep)) => Some(Dependency {
                span,
                tag: dep.tag.map(|t| {
                    syn::parse_str::<TokenStream>(&t).expect("`tag` to be valid expression")
                }),
                optional: dep.optional,
                ty: if dep.optional {
                    optional_ty(&field.ty)
                } else {
                    &field.ty
                },
            }),
            None => None,
        };

        fields.push(ProviderField {
            ident,
            field,
            dependency,
        })
    }

    Ok(fields)
}

/// Build the provider type.
///
/// The factory is responsible for building providers that builds instances of
/// the provided type.
///
/// This step is necessary to support "fixed" fields, i.e. fields who's value
/// are provided at build time.
fn impl_provider<'a>(
    ast: &DeriveInput,
    config: &ProviderConfig<'a>,
) -> (TokenStream, Ident, Vec<TokenStream>, Vec<Ident>) {
    let provider_ident = Ident::new(&format!("{}Provider", ast.ident), Span::call_site());

    let mut provider_fields = Vec::new();
    let mut constructor_assign = Vec::new();
    let mut constructor_fields = Vec::new();
    let mut injected_update = Vec::new();
    let mut provider_extract = Vec::new();
    let mut initialized_fields = Vec::new();

    let mut fixed_args = Vec::new();
    let mut fixed_idents = Vec::new();

    for f in &config.fields {
        let field_ident = f.ident;
        let field_stream = Ident::new(&format!("{}_stream", field_ident), Span::call_site());
        let field_value = Ident::new(&format!("{}_value", field_ident), Span::call_site());

        if let Some(dep) = &f.dependency {
            let field_ty = dep.ty;

            provider_fields.push(quote!(#field_stream: ::async_injector::Stream<#field_ty>));
            provider_fields.push(quote!(#field_value: Option<#field_ty>));

            let key = match &dep.tag {
                Some(tag) => quote!(::async_injector::Key::<#field_ty>::tagged(#tag)?),
                None => quote!(::async_injector::Key::<#field_ty>::of()),
            };

            constructor_assign.push(quote! {
                let (#field_stream, #field_value) = __injector.stream_key(#key).await;
            });

            constructor_fields.push(field_stream.clone());
            constructor_fields.push(field_value.clone());

            injected_update.push(quote! {
                #field_value = self.#field_stream.recv() => {
                    self.#field_value = #field_value;
                }
            });

            if dep.optional {
                initialized_fields.push(quote_spanned! { f.field.span() =>
                    #field_ident: self.#field_value.as_ref().map(Clone::clone),
                });
            } else {
                provider_extract.push(quote_spanned! { f.field.span() =>
                    let #field_value = match self.#field_value.as_ref() {
                        Some(#field_value) => #field_value,
                        None => return None,
                    };
                });

                initialized_fields.push(quote_spanned! { dep.span =>
                    #field_ident: #field_value.clone(),
                });
            };
        } else {
            let field_ty = &f.field.ty;

            provider_fields.push(quote!(#field_ident: #field_ty));

            initialized_fields.push(quote_spanned! { f.field.span() =>
                #field_ident: self.#field_ident.clone(),
            });

            constructor_fields.push(field_ident.clone());

            fixed_args.push(quote!(#field_ident: #field_ty));
            fixed_idents.push(field_ident.clone());
        }
    }

    let ident = &ast.ident;

    let vis = &ast.vis;
    let generics = &ast.generics;
    let args = &fixed_args;

    let provider = quote_spanned! { ast.span() =>
        #vis struct #provider_ident #generics {
            /// Whether or not the injector has been initialized.
            __init: bool,
            #(#provider_fields,)*
        }

        impl #generics #provider_ident #generics {
            /// Construct a new provider.
            #vis async fn new(__injector: &::async_injector::Injector #(, #args)*) -> Result<#provider_ident #generics, ::async_injector::Error> {
                #(#constructor_assign)*

                Ok(#provider_ident {
                    __init: true,
                    #(#constructor_fields,)*
                })
            }

            /// Try to construct the current value. Returns [None] unless all
            /// required dependencies are available.
            #[allow(dead_code)]
            #vis fn build(&self) -> Option<#ident #generics> {
                #(#provider_extract)*

                Some(#ident {
                    #(#initialized_fields)*
                })
            }

            /// Wait until the provided value has changed. Either some
            /// dependencies are no longer available at which it returns `None`,
            /// or all dependencies are available after which we return the
            /// build value.
            #[allow(dead_code)]
            #vis async fn wait_for_update(&mut self) -> Option<#ident #generics> {
                if self.__init {
                    self.__init = false;
                } else {
                    self.wait_internal().await;
                }

                self.build()
            }

            /// Wait until we can successfully build the complete provided
            /// value.
            #[allow(dead_code)]
            #vis async fn wait(&mut self) -> #ident #generics {
                loop {
                    if let Some(value) = self.wait_for_update().await {
                        return value;
                    }
                }
            }

            async fn wait_internal(&mut self) {
                ::async_injector::derive::select! {
                    #(#injected_update)*
                }
            }
        }
    };

    (provider, provider_ident, fixed_args, fixed_idents)
}

/// Extract the optional type argument from the given type.
fn optional_ty(ty: &Type) -> &Type {
    match ty {
        Type::Path(ref path) => {
            let last = path.path.segments.last().expect("missing path segment");

            if last.ident != "Option" {
                panic!("optional field must be of type: Option<T>");
            }

            let arguments = match &last.arguments {
                PathArguments::AngleBracketed(ref arguments) => &arguments.args,
                other => panic!("bad path arguments: {:?}", other),
            };

            let first = arguments.iter().next().expect("at least one argument");

            match first {
                GenericArgument::Type(ref ty) => ty,
                _ => panic!("expected type generic argument"),
            }
        }
        _ => {
            panic!("expected optional type to be a path");
        }
    }
}

struct ProviderConfig<'a> {
    fields: Vec<ProviderField<'a>>,
}

struct ProviderField<'a> {
    ident: &'a Ident,
    field: &'a Field,
    dependency: Option<Dependency<'a>>,
}

#[derive(Debug)]
struct Dependency<'a> {
    span: Span,
    /// Use a string tag.
    tag: Option<TokenStream>,
    optional: bool,
    ty: &'a Type,
}

/// #[dependency(...)] attribute
#[derive(Debug, Default, FromMeta)]
#[darling(default)]
struct DependencyAttr {
    /// Use a string tag.
    tag: Option<String>,
    /// If the field is optional.
    optional: bool,
}