aboutsummaryrefslogtreecommitdiff
path: root/macros/src/injectable
diff options
context:
space:
mode:
authorHampusM <hampus@hampusmat.com>2023-08-03 15:09:46 +0200
committerHampusM <hampus@hampusmat.com>2023-08-03 15:15:29 +0200
commita3ccc2713bb5315123814cadd6c50275eee38e1c (patch)
tree22d50e174f3181bbddfd50840408e85e5a4adaac /macros/src/injectable
parent14f1fc1837675e1771e220f848b46213462ae804 (diff)
feat: add constructor name flag to injectable macro
Diffstat (limited to 'macros/src/injectable')
-rw-r--r--macros/src/injectable/dependency.rs22
-rw-r--r--macros/src/injectable/implementation.rs120
-rw-r--r--macros/src/injectable/macro_args.rs47
3 files changed, 111 insertions, 78 deletions
diff --git a/macros/src/injectable/dependency.rs b/macros/src/injectable/dependency.rs
index 33c4583..85cad58 100644
--- a/macros/src/injectable/dependency.rs
+++ b/macros/src/injectable/dependency.rs
@@ -6,14 +6,12 @@ use crate::injectable::named_attr_input::NamedAttrInput;
use crate::util::error::diagnostic_error_enum;
use crate::util::syn_path::SynPathExt;
-/// Interface for a representation of a dependency of a injectable type.
-///
-/// Found as a argument in the 'new' method of the type.
+/// Interface for a dependency of a `Injectable`.
#[cfg_attr(test, mockall::automock)]
pub trait IDependency: Sized
{
- /// Build a new `Dependency` from a argument in a 'new' method.
- fn build(new_method_arg: &FnArg) -> Result<Self, DependencyError>;
+ /// Build a new `Dependency` from a argument in a constructor method.
+ fn build(ctor_method_arg: &FnArg) -> Result<Self, DependencyError>;
/// Returns the interface type.
fn get_interface(&self) -> &Type;
@@ -27,7 +25,7 @@ pub trait IDependency: Sized
/// Representation of a dependency of a injectable type.
///
-/// Found as a argument in the 'new' method of the type.
+/// Found as a argument in the constructor method of a `Injectable`.
#[derive(Debug, PartialEq, Eq)]
pub struct Dependency
{
@@ -38,16 +36,16 @@ pub struct Dependency
impl IDependency for Dependency
{
- fn build(new_method_arg: &FnArg) -> Result<Self, DependencyError>
+ fn build(ctor_method_arg: &FnArg) -> Result<Self, DependencyError>
{
- let typed_new_method_arg = match new_method_arg {
+ let typed_ctor_method_arg = match ctor_method_arg {
FnArg::Typed(typed_arg) => Ok(typed_arg),
FnArg::Receiver(receiver_arg) => Err(DependencyError::UnexpectedSelf {
self_token_span: receiver_arg.self_token.span,
}),
}?;
- let dependency_type_path = match typed_new_method_arg.ty.as_ref() {
+ let dependency_type_path = match typed_ctor_method_arg.ty.as_ref() {
Type::Path(arg_type_path) => Ok(arg_type_path),
Type::Reference(ref_type_path) => match ref_type_path.elem.as_ref() {
Type::Path(arg_type_path) => Ok(arg_type_path),
@@ -63,7 +61,7 @@ impl IDependency for Dependency
let ptr_path_segment = dependency_type_path.path.segments.last().map_or_else(
|| {
Err(DependencyError::MissingType {
- arg_span: typed_new_method_arg.span(),
+ arg_span: typed_ctor_method_arg.span(),
})
},
Ok,
@@ -88,7 +86,7 @@ impl IDependency for Dependency
})
}?;
- let arg_attrs = &typed_new_method_arg.attrs;
+ let arg_attrs = &typed_ctor_method_arg.attrs;
let opt_named_attr = arg_attrs.iter().find(|attr| {
attr.path.get_ident().map_or_else(
@@ -103,7 +101,7 @@ impl IDependency for Dependency
if let Some(named_attr_tokens) = opt_named_attr_tokens {
Some(parse2::<NamedAttrInput>(named_attr_tokens.clone()).map_err(
|err| DependencyError::InvalidNamedAttrInput {
- arg_span: typed_new_method_arg.span(),
+ arg_span: typed_ctor_method_arg.span(),
err,
},
)?)
diff --git a/macros/src/injectable/implementation.rs b/macros/src/injectable/implementation.rs
index 3d73cd0..0ea623c 100644
--- a/macros/src/injectable/implementation.rs
+++ b/macros/src/injectable/implementation.rs
@@ -31,13 +31,16 @@ pub struct InjectableImpl<Dep: IDependency>
pub generics: Generics,
pub original_impl: ItemImpl,
- new_method: ImplItemMethod,
+ constructor_method: ImplItemMethod,
}
impl<Dep: IDependency> InjectableImpl<Dep>
{
#[cfg(not(tarpaulin_include))]
- pub fn parse(input: TokenStream) -> Result<Self, InjectableImplError>
+ pub fn parse(
+ input: TokenStream,
+ constructor: &Ident,
+ ) -> Result<Self, InjectableImplError>
{
let mut item_impl = parse2::<ItemImpl>(input).map_err(|err| {
InjectableImplError::NotAImplementation {
@@ -53,79 +56,88 @@ impl<Dep: IDependency> InjectableImpl<Dep>
let item_impl_span = item_impl.self_ty.span();
- let new_method = find_impl_method_by_name_mut(&mut item_impl, "new").ok_or(
- InjectableImplError::MissingNewMethod {
- implementation_span: item_impl_span,
- },
- )?;
+ let constructor_method =
+ find_impl_method_by_name_mut(&mut item_impl, constructor).ok_or(
+ InjectableImplError::MissingConstructorMethod {
+ constructor: constructor.clone(),
+ implementation_span: item_impl_span,
+ },
+ )?;
- let dependencies = Self::build_dependencies(new_method).map_err(|err| {
- InjectableImplError::ContainsAInvalidDependency {
- implementation_span: item_impl_span,
- err,
- }
- })?;
+ let dependencies =
+ Self::build_dependencies(constructor_method).map_err(|err| {
+ InjectableImplError::ContainsAInvalidDependency {
+ implementation_span: item_impl_span,
+ err,
+ }
+ })?;
- Self::remove_method_argument_attrs(new_method);
+ Self::remove_method_argument_attrs(constructor_method);
- let new_method = new_method.clone();
+ let constructor_method = constructor_method.clone();
Ok(Self {
dependencies,
self_type: item_impl.self_ty.as_ref().clone(),
generics: item_impl.generics.clone(),
original_impl: item_impl,
- new_method,
+ constructor_method,
})
}
pub fn validate(&self) -> Result<(), InjectableImplError>
{
- if matches!(self.new_method.sig.output, ReturnType::Default) {
- return Err(InjectableImplError::InvalidNewMethodReturnType {
- new_method_output_span: self.new_method.sig.output.span(),
+ if matches!(self.constructor_method.sig.output, ReturnType::Default) {
+ return Err(InjectableImplError::InvalidConstructorMethodReturnType {
+ ctor_method_output_span: self.constructor_method.sig.output.span(),
expected: "Self".to_string(),
found: "()".to_string(),
});
}
- if let ReturnType::Type(_, ret_type) = &self.new_method.sig.output {
+ if let ReturnType::Type(_, ret_type) = &self.constructor_method.sig.output {
if let Type::Path(path_type) = ret_type.as_ref() {
if path_type
.path
.get_ident()
.map_or_else(|| true, |ident| *ident != "Self")
{
- return Err(InjectableImplError::InvalidNewMethodReturnType {
- new_method_output_span: self.new_method.sig.output.span(),
- expected: "Self".to_string(),
- found: ret_type.to_token_stream().to_string(),
- });
+ return Err(
+ InjectableImplError::InvalidConstructorMethodReturnType {
+ ctor_method_output_span: self
+ .constructor_method
+ .sig
+ .output
+ .span(),
+ expected: "Self".to_string(),
+ found: ret_type.to_token_stream().to_string(),
+ },
+ );
}
} else {
- return Err(InjectableImplError::InvalidNewMethodReturnType {
- new_method_output_span: self.new_method.sig.output.span(),
+ return Err(InjectableImplError::InvalidConstructorMethodReturnType {
+ ctor_method_output_span: self.constructor_method.sig.output.span(),
expected: "Self".to_string(),
found: ret_type.to_token_stream().to_string(),
});
}
}
- if let Some(unsafety) = self.new_method.sig.unsafety {
- return Err(InjectableImplError::NewMethodUnsafe {
+ if let Some(unsafety) = self.constructor_method.sig.unsafety {
+ return Err(InjectableImplError::ConstructorMethodUnsafe {
unsafety_span: unsafety.span,
});
}
- if let Some(asyncness) = self.new_method.sig.asyncness {
- return Err(InjectableImplError::NewMethodAsync {
+ if let Some(asyncness) = self.constructor_method.sig.asyncness {
+ return Err(InjectableImplError::ConstructorMethodAsync {
asyncness_span: asyncness.span,
});
}
- if !self.new_method.sig.generics.params.is_empty() {
- return Err(InjectableImplError::NewMethodGeneric {
- generics_span: self.new_method.sig.generics.span(),
+ if !self.constructor_method.sig.generics.params.is_empty() {
+ return Err(InjectableImplError::ConstructorMethodGeneric {
+ generics_span: self.constructor_method.sig.generics.span(),
});
}
Ok(())
@@ -209,6 +221,7 @@ impl<Dep: IDependency> InjectableImpl<Dep>
{
let generics = &self.generics;
let self_type = &self.self_type;
+ let constructor = &self.constructor_method.sig.ident;
quote! {
#maybe_doc_hidden
@@ -243,7 +256,7 @@ impl<Dep: IDependency> InjectableImpl<Dep>
#maybe_prevent_circular_deps
- Ok(syrette::ptr::TransientPtr::new(Self::new(
+ Ok(syrette::ptr::TransientPtr::new(Self::#constructor(
#(#get_dep_method_calls),*
)))
})
@@ -264,6 +277,7 @@ impl<Dep: IDependency> InjectableImpl<Dep>
{
let generics = &self.generics;
let self_type = &self.self_type;
+ let constructor = &self.constructor_method.sig.ident;
quote! {
#maybe_doc_hidden
@@ -290,7 +304,7 @@ impl<Dep: IDependency> InjectableImpl<Dep>
#maybe_prevent_circular_deps
- return Ok(syrette::ptr::TransientPtr::new(Self::new(
+ return Ok(syrette::ptr::TransientPtr::new(Self::#constructor(
#(#get_dep_method_calls),*
)));
}
@@ -444,13 +458,13 @@ impl<Dep: IDependency> InjectableImpl<Dep>
}
fn build_dependencies(
- new_method: &ImplItemMethod,
+ ctor_method: &ImplItemMethod,
) -> Result<Vec<Dep>, DependencyError>
{
- let new_method_args = &new_method.sig.inputs;
+ let ctor_method_args = &ctor_method.sig.inputs;
let dependencies_result: Result<Vec<_>, _> =
- new_method_args.iter().map(Dep::build).collect();
+ ctor_method_args.iter().map(Dep::build).collect();
let deps = dependencies_result?;
@@ -515,41 +529,45 @@ pub enum InjectableImplError
trait_path_span: Span
},
- #[error("Missing a 'new' method"), span = implementation_span]
+ #[
+ error("No constructor method '{constructor}' found in impl"),
+ span = implementation_span
+ ]
#[note("Required by the 'injectable' attribute macro")]
- MissingNewMethod {
+ MissingConstructorMethod {
+ constructor: Ident,
implementation_span: Span
},
#[
error(concat!(
- "Invalid 'new' method return type. Expected it to be '{}'. ",
+ "Invalid constructor method return type. Expected it to be '{}'. ",
"Found '{}'"
), expected, found),
- span = new_method_output_span
+ span = ctor_method_output_span
]
- InvalidNewMethodReturnType
+ InvalidConstructorMethodReturnType
{
- new_method_output_span: Span,
+ ctor_method_output_span: Span,
expected: String,
found: String
},
- #[error("'new' method is not allowed to be unsafe"), span = unsafety_span]
+ #[error("Constructor method is not allowed to be unsafe"), span = unsafety_span]
#[note("Required by the 'injectable' attribute macro")]
- NewMethodUnsafe {
+ ConstructorMethodUnsafe {
unsafety_span: Span
},
- #[error("'new' method is not allowed to be async"), span = asyncness_span]
+ #[error("Constructor method is not allowed to be async"), span = asyncness_span]
#[note("Required by the 'injectable' attribute macro")]
- NewMethodAsync {
+ ConstructorMethodAsync {
asyncness_span: Span
},
- #[error("'new' method is not allowed to have generics"), span = generics_span]
+ #[error("Constructor method is not allowed to have generics"), span = generics_span]
#[note("Required by the 'injectable' attribute macro")]
- NewMethodGeneric {
+ ConstructorMethodGeneric {
generics_span: Span
},
diff --git a/macros/src/injectable/macro_args.rs b/macros/src/injectable/macro_args.rs
index 6964352..ee398fc 100644
--- a/macros/src/injectable/macro_args.rs
+++ b/macros/src/injectable/macro_args.rs
@@ -7,8 +7,12 @@ use crate::macro_flag::MacroFlag;
use crate::util::error::diagnostic_error_enum;
use crate::util::iterator_ext::IteratorExt;
-pub const INJECTABLE_MACRO_FLAGS: &[&str] =
- &["no_doc_hidden", "async", "no_declare_concrete_interface"];
+pub const INJECTABLE_MACRO_FLAGS: &[&str] = &[
+ "no_doc_hidden",
+ "async",
+ "no_declare_concrete_interface",
+ "constructor",
+];
pub struct InjectableMacroArgs
{
@@ -21,9 +25,9 @@ impl InjectableMacroArgs
pub fn check_flags(&self) -> Result<(), InjectableMacroArgsError>
{
for flag in &self.flags {
- if !INJECTABLE_MACRO_FLAGS.contains(&flag.flag.to_string().as_str()) {
+ if !INJECTABLE_MACRO_FLAGS.contains(&flag.name().to_string().as_str()) {
return Err(InjectableMacroArgsError::UnknownFlag {
- flag_ident: flag.flag.clone(),
+ flag_ident: flag.name().clone(),
});
}
}
@@ -32,8 +36,8 @@ impl InjectableMacroArgs
self.flags.iter().find_duplicate()
{
return Err(InjectableMacroArgsError::DuplicateFlag {
- first_flag_ident: dupe_flag_first.flag.clone(),
- last_flag_span: dupe_flag_second.flag.span(),
+ first_flag_ident: dupe_flag_first.name().clone(),
+ last_flag_span: dupe_flag_second.name().span(),
});
}
@@ -111,9 +115,10 @@ mod tests
use proc_macro2::Span;
use quote::{format_ident, quote};
- use syn::{parse2, LitBool};
+ use syn::{parse2, Lit, LitBool};
use super::*;
+ use crate::macro_flag::MacroFlagValue;
use crate::test_utils;
#[test]
@@ -174,12 +179,18 @@ mod tests
injectable_macro_args.flags,
Punctuated::from_iter([
MacroFlag {
- flag: format_ident!("no_doc_hidden"),
- is_on: LitBool::new(true, Span::call_site())
+ name: format_ident!("no_doc_hidden"),
+ value: MacroFlagValue::Literal(Lit::Bool(LitBool::new(
+ true,
+ Span::call_site()
+ )))
},
MacroFlag {
- flag: format_ident!("async"),
- is_on: LitBool::new(false, Span::call_site())
+ name: format_ident!("async"),
+ value: MacroFlagValue::Literal(Lit::Bool(LitBool::new(
+ false,
+ Span::call_site()
+ )))
}
])
);
@@ -202,12 +213,18 @@ mod tests
injectable_macro_args.flags,
Punctuated::from_iter([
MacroFlag {
- flag: format_ident!("async"),
- is_on: LitBool::new(false, Span::call_site())
+ name: format_ident!("async"),
+ value: MacroFlagValue::Literal(Lit::Bool(LitBool::new(
+ false,
+ Span::call_site()
+ )))
},
MacroFlag {
- flag: format_ident!("no_declare_concrete_interface"),
- is_on: LitBool::new(false, Span::call_site())
+ name: format_ident!("no_declare_concrete_interface"),
+ value: MacroFlagValue::Literal(Lit::Bool(LitBool::new(
+ false,
+ Span::call_site()
+ )))
}
])
);