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
//! Coi-derive simplifies implementing the traits provided in the [coi] crate.
//!
//! [coi]: https://docs.rs/coi

extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::{Ident, TokenTree};
use quote::{format_ident, quote};
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input, parse_quote, Attribute, Data, DeriveInput, Error, Expr, Fields, Result,
    Token, Type, Visibility,
};

struct Provides {
    vis: Visibility,
    ty: Type,
    with: Expr,
}

impl Parse for Provides {
    fn parse(input: ParseStream) -> Result<Self> {
        let vis = input.parse()?;
        let ty = input.parse()?;
        input.parse().and_then(|ident: Ident| {
            if ident.eq("with") {
                Ok(())
            } else {
                Err(Error::new(ident.span(), "expected `with`"))
            }
        })?;
        // FIXME(pfaria) we need to limit the kinds of exprs allowed here. Quite a few will
        // fail to compile
        let with = input.parse()?;
        Ok(Provides { vis, ty, with })
    }
}

struct InjectableField {
    name: Ident,
    ty: Type,
}

impl Parse for InjectableField {
    fn parse(input: ParseStream) -> Result<Self> {
        let name = input.parse()?;
        let _colon_separator: Token![:] = input.parse()?;
        let arc: Ident = input.parse()?;
        if !arc.eq("Arc") {
            return Err(Error::new_spanned(arc, "expected `Arc<...>`"));
        }
        let _left_angle: Token![<] = input.parse()?;
        let ty = input.parse()?;
        let _right_angle: Token![>] = input.parse()?;
        Ok(InjectableField { name, ty })
    }
}

/// Generates an impl for `Inject` and also generates a "Provider" struct with its own
/// `Provide` impl.
///
/// This derive proc macro impls `Inject` on the struct it modifies, and also processes two
/// attributes:
/// - `#[provides]` - Only one of these is allowed per `#[derive(Inject)]`. It takes the form
/// ```rust,ignore
/// #[provides(<vis> <ty> with <expr>)]
/// ```
/// It generates a provider struct with visibility `<vis>`
/// that impls `Provide` with an output type of `Arc<<ty>>`. It will construct `<ty>` with `<expr>`,
/// and all params to `<expr>` must match the struct fields marked with `#[inject]` (see the next
/// bullet item). `<vis>` must match the visibility of `<ty>` or you will get code that might not
/// compile.
/// - `#[inject]` - All fields marked `#[inject]` are resolved in the `provide` fn described above.
/// Given a field `<field_name>: <field_ty>`, this attribute will cause the following resolution to
/// be generated:
/// ```rust,ignore
/// let <field_name> = container.resolve::<<field_ty>>("<field_name>");
/// ```
/// Because of this, it's important that the field name MUST match the string that's used to
/// register the provider in the `ContainerBuilder`.
///
/// ## Examples
///
/// Private trait and no dependencies
/// ```rust
/// use coi::Inject;
/// trait Priv: Inject {}
///
/// #[derive(Inject)]
/// #[provides(dyn Priv with SimpleStruct)]
/// # pub
/// struct SimpleStruct;
///
/// impl Priv for SimpleStruct {}
/// ```
///
/// Public trait and dependency
/// ```rust
/// use coi::Inject;
/// use std::sync::Arc;
/// pub trait Pub: Inject {}
/// pub trait Dependency: Inject {}
///
/// #[derive(Inject)]
/// #[provides(pub dyn Pub with NewStruct::new(dependency))]
/// # pub
/// struct NewStruct {
///     #[inject]
///     dependency: Arc<dyn Dependency>,
/// }
///
/// impl NewStruct {
///     fn new(dependency: Arc<dyn Dependency>) -> Self {
///         Self {
///             dependency
///         }
///     }
/// }
///
/// impl Pub for NewStruct {}
/// ```
///
/// Struct injection
/// ```rust
/// use coi::Inject;
/// #[derive(Inject)]
/// #[provides(pub InjectableStruct with InjectableStruct)]
/// # pub
/// struct InjectableStruct;
/// ```
///
/// If you need some form of constructor fn that takes arguments that are not injected, then you
/// need to manually implement the `Provide` trait, and this derive will not be usable.
#[proc_macro_derive(Inject, attributes(provides, inject))]
pub fn inject_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let data_struct = match input.data {
        Data::Struct(data_struct) => data_struct,
        _ => {
            return Error::new_spanned(input, "#[derive(Inject)] only supports structs")
                .to_compile_error()
                .into()
        }
    };
    let provider = format_ident!("{}Provider", input.ident);
    let attr = match input.attrs.into_iter().find(|attr| {
        attr.path
            .segments
            .first()
            .map(|p| p.ident.eq("provides"))
            .unwrap_or(false)
    }) {
        None => {
            return Error::new_spanned(
                input.ident,
                "#[derive(Inject)] requires a `provides` attribute",
            )
            .to_compile_error()
            .into()
        }
        Some(attr) => attr,
    };

    let args: Vec<_> = match data_struct.fields {
        Fields::Named(named_fields) => {
            let injectable_fields: Vec<_> = named_fields
                .named
                .into_iter()
                .map(|field| -> Result<InjectableField> {
                    let field_name = field.ident.unwrap();
                    let field_ty = field.ty;
                    Ok(parse_quote! {
                        #field_name: #field_ty
                    })
                })
                .collect();

            if injectable_fields.iter().any(|f| f.is_err()) {
                return injectable_fields
                    .into_iter()
                    .fold(Ok(()), |acc, f| match f {
                        Ok(_) => acc,
                        Err(e) => match acc {
                            Ok(()) => Err(e),
                            Err(mut e2) => {
                                e2.combine(e);
                                Err(e2)
                            }
                        },
                    })
                    .unwrap_err()
                    .to_compile_error()
                    .into();
            }

            injectable_fields.into_iter().map(Result::unwrap).collect()
        }
        // FIXME(pfaria) add support for unnamed fields by allowing the name to be
        // specified as part of the attribute params
        Fields::Unnamed(_) => {
            return Error::new_spanned(data_struct.fields, "unnamed fields cannot be injected")
                .to_compile_error()
                .into()
        }
        Fields::Unit => vec![],
    };
    let container = format_ident!("{}", if args.is_empty() { "_" } else { "container" });

    let (async_trait, async_token, await_call): (Vec<Attribute>, Vec<Token![async]>, Vec<_>) =
        if cfg!(feature = "async") {
            (
                vec![parse_quote! {# [::coi::async_trait]}],
                vec![parse_quote! {async}],
                {
                    let dot = quote! {.};
                    let await_tok = quote! {await};
                    let quoted = quote! {#dot #await_tok};
                    vec![quoted]
                },
            )
        } else {
            (vec![], vec![], vec![])
        };

    let resolve: Vec<_> = args
        .into_iter()
        .map(|field| {
            let ident = field.name;
            let ty = field.ty;
            let key = format!("{}", ident);
            quote! {
                let #ident = #container.resolve::<#ty>(#key) #( #await_call )* ?;
            }
        })
        .collect();

    let attr2 = attr.clone();
    let mut token_iter = attr2.tokens.into_iter();
    let provides = match token_iter.next() {
        Some(TokenTree::Group(group)) => {
            let token_stream = TokenStream::from(group.stream());
            parse_macro_input!(token_stream as Provides)
        }
        Some(s) => {
            return Error::new_spanned(s, "expected `(ty with expr)`")
                .to_compile_error()
                .into()
        }
        _ => {
            return Error::new_spanned(attr, "expected `(ty with expr)`")
                .to_compile_error()
                .into()
        }
    };
    let vis = provides.vis;
    let ty = provides.ty;
    let provides_with = provides.with;

    if let Some(s) = token_iter.next() {
        return Error::new_spanned(
            s,
            "Only expected the format #[provides `Interface` with `provider`]",
        )
        .to_compile_error()
        .into();
    }

    let input_ident = input.ident;

    let expanded = quote! {
        impl Inject for #input_ident {}

        #vis struct #provider;

        #( #async_trait )*
        impl ::coi::Provide for #provider {
            type Output = #ty;

            #( #async_token )* fn provide(
                &self,
                #container: &mut ::coi::Container,
            ) -> ::coi::Result<::std::sync::Arc<Self::Output>> {
                #( #resolve )*
                Ok(::std::sync::Arc::new(#provides_with) as ::std::sync::Arc<#ty>)
            }
        }
    };
    TokenStream::from(expanded)
}