1extern crate proc_macro;
2
3mod types;
4
5use proc_macro::TokenStream;
6use quote::{format_ident, quote};
7use types::InjectionType;
8
9struct ComponentParams {
12 vis: syn::Visibility,
13 no_new: bool,
14}
15
16impl syn::parse::Parse for ComponentParams {
17 fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
18 let mut params = ComponentParams {
19 vis: syn::Visibility::Inherited,
20 no_new: false,
21 };
22
23 while !input.is_empty() {
24 if input.peek(syn::Token![pub]) {
25 params.vis = input.parse()?;
26 } else {
27 let ident = input.parse::<syn::Ident>()?;
28 match ident.to_string().as_str() {
29 "no_new" => params.no_new = true,
30 s => {
31 return Err(syn::Error::new(
32 ident.span(),
33 format!("Unexpected parameter: {s}"),
34 ))
35 }
36 }
37 }
38
39 if !input.is_empty() {
40 input.parse::<syn::Token![,]>()?; }
42 }
43 Ok(params)
44 }
45}
46
47#[proc_macro_attribute]
50pub fn component(attr: TokenStream, item: TokenStream) -> TokenStream {
51 let params = syn::parse_macro_input!(attr as ComponentParams);
52
53 let ast: syn::Item = syn::parse(item).unwrap();
54 match ast {
55 syn::Item::Struct(struct_ast) => component_from_struct(params, struct_ast),
56 syn::Item::Impl(impl_ast) => component_from_impl(params, impl_ast),
57 _ => {
58 panic!("The #[component] macro can only be used on struct definition or an impl block")
59 }
60 }
61}
62
63#[proc_macro_attribute]
66pub fn scope(_args: TokenStream, item: TokenStream) -> TokenStream {
67 item
68}
69
70#[proc_macro_attribute]
73pub fn interface(_args: TokenStream, item: TokenStream) -> TokenStream {
74 item
75}
76
77#[proc_macro_attribute]
80pub fn meta(_args: TokenStream, item: TokenStream) -> TokenStream {
81 item
82}
83
84fn component_from_struct(params: ComponentParams, mut ast: syn::ItemStruct) -> TokenStream {
87 let impl_name = &ast.ident;
88 let impl_type = syn::parse2(quote! { #impl_name }).unwrap();
89 let impl_generics = syn::parse2(quote! {}).unwrap();
90
91 let args: Vec<_> = ast
92 .fields
93 .iter_mut()
94 .map(|f| {
95 (
96 f.ident.clone().unwrap(),
97 f.ty.clone(),
98 extract_attr_explicit(&mut f.attrs),
99 )
100 })
101 .collect();
102
103 let scope_type =
104 get_scope(&ast.attrs).unwrap_or_else(|| syn::parse_str("::dill::Transient").unwrap());
105
106 let interfaces = get_interfaces(&ast.attrs);
107 let meta = get_meta(&ast.attrs);
108
109 let mut gen: TokenStream = quote! { #ast }.into();
110
111 if !params.no_new {
112 gen.extend(implement_new(&impl_type, &args));
113 }
114
115 let builder: TokenStream = implement_builder(
116 &ast.vis,
117 &impl_type,
118 &impl_generics,
119 scope_type,
120 interfaces,
121 meta,
122 args,
123 !params.no_new,
124 );
125
126 gen.extend(builder);
127 gen
128}
129
130fn component_from_impl(params: ComponentParams, mut ast: syn::ItemImpl) -> TokenStream {
133 let impl_generics = &ast.generics;
134 let impl_type = &ast.self_ty;
135 let new = get_new(&mut ast.items).expect(
136 "When using #[component] macro on the impl block it's expected to contain a new() \
137 function. Otherwise use #[derive(Builder)] on the struct.",
138 );
139
140 let args: Vec<_> = new
141 .sig
142 .inputs
143 .iter_mut()
144 .map(|arg| match arg {
145 syn::FnArg::Typed(targ) => targ,
146 _ => panic!("Unexpected argument in new() function"),
147 })
148 .map(|arg| {
149 (
150 match arg.pat.as_ref() {
151 syn::Pat::Ident(ident) => ident.ident.clone(),
152 _ => panic!("Unexpected format of arguments in new() function"),
153 },
154 arg.ty.as_ref().clone(),
155 extract_attr_explicit(&mut arg.attrs),
156 )
157 })
158 .collect();
159
160 let scope_type =
161 get_scope(&ast.attrs).unwrap_or_else(|| syn::parse_str("::dill::Transient").unwrap());
162
163 let interfaces = get_interfaces(&ast.attrs);
164 let meta = get_meta(&ast.attrs);
165
166 let mut gen: TokenStream = quote! { #ast }.into();
167 let builder: TokenStream = implement_builder(
168 ¶ms.vis,
169 impl_type,
170 impl_generics,
171 scope_type,
172 interfaces,
173 meta,
174 args,
175 true,
176 );
177
178 gen.extend(builder);
179 gen
180}
181
182#[allow(clippy::too_many_arguments)]
185fn implement_new(impl_type: &syn::Type, args: &[(syn::Ident, syn::Type, bool)]) -> TokenStream {
186 let arg_decl = args.iter().map(|(name, ty, _)| quote! {#name: #ty});
187 let arg_name = args.iter().map(|(name, _, _)| name);
188
189 quote! {
190 impl #impl_type {
191 #[allow(clippy::too_many_arguments)]
192 pub fn new(
193 #(#arg_decl),*
194 ) -> Self {
195 Self {
196 #(#arg_name),*
197 }
198 }
199 }
200 }
201 .into()
202}
203
204#[allow(clippy::too_many_arguments)]
207fn implement_builder(
208 impl_vis: &syn::Visibility,
209 impl_type: &syn::Type,
210 _impl_generics: &syn::Generics,
211 scope_type: syn::Path,
212 interfaces: Vec<syn::Type>,
213 meta: Vec<syn::ExprStruct>,
214 args: Vec<(syn::Ident, syn::Type, bool)>,
215 has_new: bool,
216) -> TokenStream {
217 let builder_name = format_ident!("{}Builder", quote! { #impl_type }.to_string());
218
219 let arg_name: Vec<_> = args.iter().map(|(name, _, _)| name).collect();
220
221 let meta_provide: Vec<_> = meta
222 .iter()
223 .enumerate()
224 .map(|(i, e)| implement_meta_provide(i, e))
225 .collect();
226 let meta_vars: Vec<_> = meta
227 .iter()
228 .enumerate()
229 .map(|(i, e)| implement_meta_var(i, e))
230 .collect();
231
232 let mut arg_override_fn_field = Vec::new();
233 let mut arg_override_fn_field_ctor = Vec::new();
234 let mut arg_override_setters = Vec::new();
235 let mut arg_prepare_dependency = Vec::new();
236 let mut arg_provide_dependency = Vec::new();
237 let mut arg_check_dependency = Vec::new();
238
239 for (name, typ, is_explicit) in &args {
240 let (
241 override_fn_field,
242 override_fn_field_ctor,
243 override_setters,
244 prepare_dependency,
245 provide_dependency,
246 check_dependency,
247 ) = implement_arg(name, typ, &builder_name, *is_explicit);
248
249 arg_override_fn_field.push(override_fn_field);
250 arg_override_fn_field_ctor.push(override_fn_field_ctor);
251 arg_override_setters.push(override_setters);
252 arg_prepare_dependency.push(prepare_dependency);
253 arg_provide_dependency.push(provide_dependency);
254 arg_check_dependency.push(check_dependency);
255 }
256
257 let explicit_arg_decl: Vec<_> = args
258 .iter()
259 .filter(|(_, _, is_explicit)| *is_explicit)
260 .map(|(ident, ty, _)| quote! { #ident: #ty })
261 .collect();
262 let explicit_arg_provide: Vec<_> = args
263 .iter()
264 .filter(|(_, _, is_explicit)| *is_explicit)
265 .map(|(ident, _, _)| quote! { #ident })
266 .collect();
267
268 let ctor = if !has_new {
269 quote! {
270 #impl_type {
271 #( #arg_name: #arg_provide_dependency, )*
272 }
273 }
274 } else {
275 quote! {
276 #impl_type::new(#( #arg_provide_dependency, )*)
277 }
278 };
279
280 let component_or_explicit_factory = if explicit_arg_decl.is_empty() {
281 quote! {
282 impl ::dill::Component for #impl_type {
283 type Builder = #builder_name;
284
285 fn register(cat: &mut ::dill::CatalogBuilder) {
286 cat.add_builder(Self::builder());
287
288 #(
289 cat.bind::<#interfaces, #impl_type>();
290 )*
291 }
292
293 fn builder() -> Self::Builder {
294 #builder_name::new()
295 }
296 }
297 }
298 } else {
299 quote! {
300 impl #impl_type {
301 #[allow(clippy::too_many_arguments)]
302 pub fn builder(
303 #(#explicit_arg_decl),*
304 ) -> #builder_name {
305 #builder_name::new(
306 #(#explicit_arg_provide),*
307 )
308 }
309 }
310 }
311 };
312
313 let builder = quote! {
314 #impl_vis struct #builder_name {
315 dill_builder_scope: #scope_type,
316 #(#arg_override_fn_field),*
317 }
318
319 impl #builder_name {
320 #( #meta_vars )*
321
322 pub fn new(
323 #(#explicit_arg_decl),*
324 ) -> Self {
325 Self {
326 dill_builder_scope: #scope_type::new(),
327 #(#arg_override_fn_field_ctor),*
328 }
329 }
330
331 #( #arg_override_setters )*
332
333 fn build(&self, cat: &::dill::Catalog) -> Result<#impl_type, ::dill::InjectionError> {
334 use ::dill::DependencySpec;
335 #( #arg_prepare_dependency )*
336 Ok(#ctor)
337 }
338 }
339
340 impl ::dill::Builder for #builder_name {
341 fn instance_type_id(&self) -> ::std::any::TypeId {
342 ::std::any::TypeId::of::<#impl_type>()
343 }
344
345 fn instance_type_name(&self) -> &'static str {
346 ::std::any::type_name::<#impl_type>()
347 }
348
349 fn interfaces(&self, clb: &mut dyn FnMut(&::dill::InterfaceDesc) -> bool) {
350 #(
351 if !clb(&::dill::InterfaceDesc {
352 type_id: ::std::any::TypeId::of::<#interfaces>(),
353 type_name: ::std::any::type_name::<#interfaces>(),
354 }) { return }
355 )*
356 }
357
358 fn metadata<'a>(&'a self, clb: & mut dyn FnMut(&'a dyn std::any::Any) -> bool) {
359 #( #meta_provide )*
360 }
361
362 fn get_any(&self, cat: &::dill::Catalog) -> Result<::std::sync::Arc<dyn ::std::any::Any + Send + Sync>, ::dill::InjectionError> {
363 Ok(::dill::TypedBuilder::get(self, cat)?)
364 }
365
366 fn check(&self, cat: &::dill::Catalog) -> Result<(), ::dill::ValidationError> {
367 use ::dill::DependencySpec;
368
369 let mut errors = Vec::new();
370 #(
371 if let Err(err) = #arg_check_dependency {
372 errors.push(err);
373 }
374 )*
375 if errors.len() != 0 {
376 Err(::dill::ValidationError { errors })
377 } else {
378 Ok(())
379 }
380 }
381 }
382
383 impl ::dill::TypedBuilder<#impl_type> for #builder_name {
384 fn get(&self, cat: &::dill::Catalog) -> Result<std::sync::Arc<#impl_type>, ::dill::InjectionError> {
385 use ::dill::Scope;
386
387 if let Some(inst) = self.dill_builder_scope.get() {
388 return Ok(inst.downcast().unwrap());
389 }
390
391 let inst = ::std::sync::Arc::new(self.build(cat)?);
392
393 self.dill_builder_scope.set(inst.clone());
394 Ok(inst)
395 }
396 }
397
398 #(
399 impl ::dill::TypedBuilderCast<#interfaces> for #builder_name
401 {
402 fn cast(self) -> impl ::dill::TypedBuilder<#interfaces> {
403 struct _B(#builder_name);
404
405 impl ::dill::Builder for _B {
406 fn instance_type_id(&self) -> ::std::any::TypeId {
407 self.0.instance_type_id()
408 }
409 fn instance_type_name(&self) -> &'static str {
410 self.0.instance_type_name()
411 }
412 fn interfaces(&self, clb: &mut dyn FnMut(&::dill::InterfaceDesc) -> bool) {
413 self.0.interfaces(clb)
414 }
415 fn metadata<'a>(&'a self, clb: &mut dyn FnMut(&'a dyn std::any::Any) -> bool) {
416 self.0.metadata(clb)
417 }
418 fn get_any(&self, cat: &::dill::Catalog) -> Result<std::sync::Arc<dyn std::any::Any + Send + Sync>, ::dill::InjectionError> {
419 self.0.get_any(cat)
420 }
421 fn check(&self, cat: &::dill::Catalog) -> Result<(), ::dill::ValidationError> {
422 self.0.check(cat)
423 }
424 }
425
426 impl ::dill::TypedBuilder<#interfaces> for _B {
427 fn get(&self, cat: &::dill::Catalog) -> Result<::std::sync::Arc<#interfaces>, ::dill::InjectionError> {
428 match self.0.get(cat) {
429 Ok(v) => Ok(v),
430 Err(e) => Err(e),
431 }
432 }
433 }
434
435 _B(self)
436 }
437 }
438 )*
439 };
440
441 quote! {
442 #component_or_explicit_factory
443
444 #builder
445 }
446 .into()
447}
448
449fn implement_arg(
452 name: &syn::Ident,
453 typ: &syn::Type,
454 builder: &syn::Ident,
455 is_explicit: bool,
456) -> (
457 proc_macro2::TokenStream, proc_macro2::TokenStream, proc_macro2::TokenStream, proc_macro2::TokenStream, proc_macro2::TokenStream, proc_macro2::TokenStream, ) {
464 let override_fn_name = format_ident!("arg_{}_fn", name);
465
466 let injection_type = if is_explicit {
467 InjectionType::Value { typ: typ.clone() }
468 } else {
469 types::deduce_injection_type(typ)
470 };
471
472 let override_fn_field = if is_explicit {
475 quote! { #name: #typ }
476 } else {
477 match &injection_type {
478 InjectionType::Reference { .. } => proc_macro2::TokenStream::new(),
479 _ => quote! {
480 #override_fn_name: Option<Box<dyn Fn(&::dill::Catalog) -> Result<#typ, ::dill::InjectionError> + Send + Sync>>
481 },
482 }
483 };
484
485 let override_fn_field_ctor = if is_explicit {
488 quote! { #name: #name }
489 } else {
490 match &injection_type {
491 InjectionType::Reference { .. } => proc_macro2::TokenStream::new(),
492 _ => quote! { #override_fn_name: None },
493 }
494 };
495
496 let override_setters = if is_explicit {
498 proc_macro2::TokenStream::new()
499 } else {
500 match &injection_type {
501 InjectionType::Reference { .. } => proc_macro2::TokenStream::new(),
502 _ => {
503 let setter_val_name = format_ident!("with_{}", name);
504 let setter_fn_name = format_ident!("with_{}_fn", name);
505 quote! {
506 pub fn #setter_val_name(mut self, val: #typ) -> #builder {
507 self.#override_fn_name = Some(Box::new(move |_| Ok(val.clone())));
508 self
509 }
510
511 pub fn #setter_fn_name(
512 mut self,
513 fun: impl Fn(&::dill::Catalog) -> Result<#typ, ::dill::InjectionError> + 'static + Send + Sync
514 ) -> #builder {
515 self.#override_fn_name = Some(Box::new(fun));
516 self
517 }
518 }
519 }
520 }
521 };
522
523 let check_dependency = if is_explicit {
525 quote! { Ok(()) }
526 } else {
527 let do_check_dependency = get_do_check_dependency(&injection_type);
528 match &injection_type {
529 InjectionType::Reference { .. } => quote! { #do_check_dependency },
530 _ => quote! {
531 match &self.#override_fn_name {
532 Some(_) => Ok(()),
533 _ => #do_check_dependency,
534 }
535 },
536 }
537 };
538
539 let prepare_dependency = if is_explicit {
541 proc_macro2::TokenStream::new()
542 } else {
543 let do_get_dependency = get_do_get_dependency(&injection_type);
544 match &injection_type {
545 InjectionType::Reference { .. } => quote! { let #name = #do_get_dependency; },
546 _ => quote! {
547 let #name = match &self.#override_fn_name {
548 Some(fun) => fun(cat)?,
549 _ => #do_get_dependency,
550 };
551 },
552 }
553 };
554
555 let provide_dependency = if is_explicit {
557 quote! { self.#name.clone() }
558 } else {
559 match &injection_type {
560 InjectionType::Reference { .. } => quote! { #name.as_ref() },
561 _ => quote! { #name },
562 }
563 };
564
565 (
566 override_fn_field,
567 override_fn_field_ctor,
568 override_setters,
569 prepare_dependency,
570 provide_dependency,
571 check_dependency,
572 )
573}
574
575fn get_do_check_dependency(injection_type: &InjectionType) -> proc_macro2::TokenStream {
578 match injection_type {
579 InjectionType::Arc { inner } => quote! { ::dill::OneOf::<#inner>::check(cat) },
580 InjectionType::Reference { inner } => quote! { ::dill::OneOf::<#inner>::check(cat) },
581 InjectionType::Option { element } => match element.as_ref() {
582 InjectionType::Arc { inner } => {
583 quote! { ::dill::Maybe::<::dill::OneOf::<#inner>>::check(cat) }
584 }
585 InjectionType::Value { typ } => {
586 quote! { ::dill::Maybe::<::dill::OneOf::<#typ>>::check(cat) }
587 }
588 _ => {
589 unimplemented!("Currently only Option<Arc<Iface>> and Option<Value> are supported")
590 }
591 },
592 InjectionType::Lazy { element } => match element.as_ref() {
593 InjectionType::Arc { inner } => {
594 quote! { ::dill::specs::Lazy::<::dill::OneOf::<#inner>>::check(cat) }
595 }
596 _ => unimplemented!("Currently only Lazy<Arc<Iface>> is supported"),
597 },
598 InjectionType::Vec { item } => match item.as_ref() {
599 InjectionType::Arc { inner } => quote! { ::dill::AllOf::<#inner>::check(cat) },
600 _ => unimplemented!("Currently only Vec<Arc<Iface>> is supported"),
601 },
602 InjectionType::Value { typ } => quote! { ::dill::OneOf::<#typ>::check(cat) },
603 }
604}
605
606fn get_do_get_dependency(injection_type: &InjectionType) -> proc_macro2::TokenStream {
607 match injection_type {
608 InjectionType::Arc { inner } => quote! { ::dill::OneOf::<#inner>::get(cat)? },
609 InjectionType::Reference { inner } => quote! { ::dill::OneOf::<#inner>::get(cat)? },
610 InjectionType::Option { element } => match element.as_ref() {
611 InjectionType::Arc { inner } => {
612 quote! { ::dill::Maybe::<::dill::OneOf::<#inner>>::get(cat)? }
613 }
614 InjectionType::Value { typ } => {
615 quote! { ::dill::Maybe::<::dill::OneOf::<#typ>>::get(cat)?.map(|v| v.as_ref().clone()) }
616 }
617 _ => {
618 unimplemented!("Currently only Option<Arc<Iface>> and Option<Value> are supported")
619 }
620 },
621 InjectionType::Lazy { element } => match element.as_ref() {
622 InjectionType::Arc { inner } => {
623 quote! { ::dill::specs::Lazy::<::dill::OneOf::<#inner>>::get(cat)? }
624 }
625 _ => unimplemented!("Currently only Lazy<Arc<Iface>> is supported"),
626 },
627 InjectionType::Vec { item } => match item.as_ref() {
628 InjectionType::Arc { inner } => quote! { ::dill::AllOf::<#inner>::get(cat)? },
629 _ => unimplemented!("Currently only Vec<Arc<Iface>> is supported"),
630 },
631 InjectionType::Value { typ } => {
632 quote! { ::dill::OneOf::<#typ>::get(cat).map(|v| v.as_ref().clone())? }
633 }
634 }
635}
636
637fn implement_meta_var(index: usize, expr: &syn::ExprStruct) -> proc_macro2::TokenStream {
640 let ident = format_ident!("_meta_{index}");
641 let typ = &expr.path;
642 quote! {
643 const #ident: #typ = #expr;
644 }
645}
646
647fn implement_meta_provide(index: usize, _expr: &syn::ExprStruct) -> proc_macro2::TokenStream {
648 let ident = format_ident!("_meta_{index}");
649 quote! {
650 if !clb(&Self::#ident) { return }
651 }
652}
653
654fn get_scope(attrs: &Vec<syn::Attribute>) -> Option<syn::Path> {
658 let mut scope = None;
659
660 for attr in attrs {
661 if is_dill_attr(attr, "scope") {
662 attr.parse_nested_meta(|meta| {
663 scope = Some(meta.path);
664 Ok(())
665 })
666 .unwrap();
667 }
668 }
669
670 scope
671}
672
673fn get_interfaces(attrs: &Vec<syn::Attribute>) -> Vec<syn::Type> {
677 let mut interfaces = Vec::new();
678
679 for attr in attrs {
680 if is_dill_attr(attr, "interface") {
681 let iface = attr.parse_args().unwrap();
682 interfaces.push(iface);
683 }
684 }
685
686 interfaces
687}
688
689fn get_meta(attrs: &Vec<syn::Attribute>) -> Vec<syn::ExprStruct> {
693 let mut meta = Vec::new();
694
695 for attr in attrs {
696 if is_dill_attr(attr, "meta") {
697 let expr = attr.parse_args().unwrap();
698 meta.push(expr);
699 }
700 }
701
702 meta
703}
704
705fn is_dill_attr<I: ?Sized>(attr: &syn::Attribute, ident: &I) -> bool
708where
709 syn::Ident: PartialEq<I>,
710{
711 if attr.path().is_ident(ident) {
712 true
713 } else {
714 attr.path().segments.len() == 2
715 && &attr.path().segments[0].ident == "dill"
716 && attr.path().segments[1].ident == *ident
717 }
718}
719
720fn get_new(impl_items: &mut [syn::ImplItem]) -> Option<&mut syn::ImplItemFn> {
724 impl_items
725 .iter_mut()
726 .filter_map(|i| match i {
727 syn::ImplItem::Fn(m) => Some(m),
728 _ => None,
729 })
730 .find(|m| m.sig.ident == "new")
731}
732
733fn extract_attr_explicit(attrs: &mut Vec<syn::Attribute>) -> bool {
736 let mut present = false;
737 attrs.retain_mut(|attr| {
738 if is_attr_explicit(attr) {
739 present = true;
740 false
741 } else {
742 true
743 }
744 });
745 present
746}
747
748fn is_attr_explicit(attr: &syn::Attribute) -> bool {
749 if !is_dill_attr(attr, "component") {
750 return false;
751 }
752 let syn::Meta::List(meta) = &attr.meta else {
753 return false;
754 };
755 meta.tokens.to_string().contains("explicit")
756}