use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{Expr, ExprClosure, Ident, PathArguments, Token, Type, TypeParamBound, bracketed, token};
use ulo_handler_codegen::util::wrap_async;
use crate::module_attr::module_def_param;
use crate::shared::scope::ScopeArg;
use crate::shared::{check_factory_params, ulo};
pub(crate) type Qualifier = Option<Box<Type>>;
pub(crate) enum ProviderEntry {
Provide { ty: Type, qualifier: Qualifier },
ProvideAs { ty: Type, as_ty: Type, qualifier: Qualifier },
TryValue { expr: Expr, qualifier: Qualifier },
Value { expr: Expr, qualifier: Qualifier },
With { key: Option<Type>, scope: Option<ScopeArg>, closure: ExprClosure },
Contribute { into: Type, items: Vec<Contribution> },
}
pub(crate) enum Contribution {
Type(Type),
Value(Expr),
TryValue(Expr),
With { scope: Option<ScopeArg>, closure: ExprClosure },
}
const CLOSURE_QUALIFIER: &str = "a closure binding takes no `@` qualifier; write the binding in a `ModuleDef` \
with `.qualified::<Q>()`, or bind a value, `Db(..) @ Primary`";
const CONTRIBUTION_QUALIFIER: &str = "an `into` item takes no `@` qualifier; a qualified collection is written in a \
`ModuleDef`, `m.contribute::<K>().qualified::<Q>()`";
const CONTRIBUTION_FORMS: &str =
"an `into` entry is a type, `value = expr`, `with = |..| ..` or `with(<scope>) = |..| ..`";
impl Parse for ProviderEntry {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
if is_with(input) {
input.parse::<Ident>()?;
let (scope, closure) = parse_with(input)?;
refuse_qualifier(input, CLOSURE_QUALIFIER)?;
return Ok(ProviderEntry::With { key: None, scope, closure });
}
if is_keyed_with(input) {
let key: Type = input.parse()?;
if written_as_role_key(&key) {
return Err(syn::Error::new_spanned(
key,
"a role key takes contributions, and `K: with = ..` binds a single instance; \
a global enhancer is written `into AnyGuard<Http>: [with = ..]`",
));
}
input.parse::<Token![:]>()?;
input.parse::<Ident>()?;
let (scope, closure) = parse_with(input)?;
refuse_qualifier(input, CLOSURE_QUALIFIER)?;
return Ok(ProviderEntry::With { key: Some(key), scope, closure });
}
if is_contribution(input) {
input.parse::<Ident>()?;
let into: Type = input.parse()?;
input.parse::<Token![:]>()?;
let content;
bracketed!(content in input);
let items = Punctuated::<Contribution, Token![,]>::parse_terminated(&content)?.into_iter().collect();
return Ok(ProviderEntry::Contribute { into, items });
}
let fork = input.fork();
if fork.parse::<Type>().is_ok_and(|ty| is_type_entry(&ty))
&& (fork.is_empty() || fork.peek(Token![,]) || fork.peek(Token![as]) || fork.peek(Token![@]))
{
let ty: Type = input.parse()?;
if input.peek(Token![as]) {
input.parse::<Token![as]>()?;
let as_ty: Type = input.parse()?;
if written_as_role_key(&as_ty) {
return Err(syn::Error::new_spanned(
as_ty,
"a role key takes contributions, and `as` binds a single instance; \
a global enhancer is written `into AnyGuard<Http>: [AuthGuard]`",
));
}
let qualifier = parse_qualifier(input)?;
return Ok(ProviderEntry::ProvideAs { ty, as_ty, qualifier });
}
let qualifier = parse_qualifier(input)?;
return Ok(ProviderEntry::Provide { ty, qualifier });
}
Ok(match input.parse::<Expr>()? {
Expr::Try(expr) => ProviderEntry::TryValue { expr: *expr.expr, qualifier: parse_qualifier(input)? },
Expr::Closure(closure) => {
check_factory_params(&closure)?;
refuse_qualifier(input, CLOSURE_QUALIFIER)?;
ProviderEntry::With { key: None, scope: None, closure }
}
expr => ProviderEntry::Value { expr, qualifier: parse_qualifier(input)? },
})
}
}
impl Parse for Contribution {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let item = Self::parse_item(input)?;
refuse_qualifier(input, CONTRIBUTION_QUALIFIER)?;
Ok(item)
}
}
impl Contribution {
fn parse_item(input: ParseStream<'_>) -> syn::Result<Self> {
if input.peek(Ident) && input.peek2(token::Paren) {
let fork = input.fork();
let key: Ident = fork.parse()?;
if key == "with" {
input.parse::<Ident>()?;
let scope = ScopeArg::parse_parenthesized(input)?;
input.parse::<Token![=]>()?;
return Ok(Contribution::With { scope: Some(scope), closure: parse_with_closure(input)? });
}
if key == "value" {
return Err(syn::Error::new(
key.span(),
"a `value` is built once and shared, so it takes no scope; write `value = ..`",
));
}
}
if input.peek(Ident) && input.peek2(Token![=]) && !input.peek2(Token![==]) && !input.peek2(Token![=>]) {
let key: Ident = input.parse()?;
input.parse::<Token![=]>()?;
if key == "value" {
return Ok(match input.parse::<Expr>()? {
Expr::Try(expr) => Contribution::TryValue(*expr.expr),
expr => Contribution::Value(expr),
});
}
if key == "with" {
return Ok(Contribution::With { scope: None, closure: parse_with_closure(input)? });
}
return Err(syn::Error::new(key.span(), CONTRIBUTION_FORMS));
}
let fork = input.fork();
if fork.parse::<Type>().is_ok_and(|ty| !is_call(&ty)) && (fork.is_empty() || fork.peek(Token![,]) || fork.peek(Token![@])) {
return Ok(Contribution::Type(input.parse()?));
}
let expr: Expr = input.parse()?;
Err(syn::Error::new_spanned(expr, format!("{CONTRIBUTION_FORMS}; an expression is contributed with `value = ..`")))
}
}
pub(crate) fn parse_qualifier(input: ParseStream<'_>) -> syn::Result<Qualifier> {
if !input.peek(Token![@]) {
return Ok(None);
}
input.parse::<Token![@]>()?;
let qualifier: Type = input.parse()?;
if input.peek(Token![@]) {
return Err(syn::Error::new(input.span(), "an entry takes one `@` qualifier"));
}
Ok(Some(Box::new(qualifier)))
}
fn refuse_qualifier(input: ParseStream<'_>, reason: &str) -> syn::Result<()> {
if input.peek(Token![@]) { Err(syn::Error::new(input.span(), reason)) } else { Ok(()) }
}
fn parse_with(input: ParseStream<'_>) -> syn::Result<(Option<ScopeArg>, ExprClosure)> {
let scope = if input.peek(token::Paren) { Some(ScopeArg::parse_parenthesized(input)?) } else { None };
input.parse::<Token![=]>()?;
Ok((scope, parse_with_closure(input)?))
}
fn is_with(input: ParseStream<'_>) -> bool {
let fork = input.fork();
let Ok(ident) = fork.parse::<Ident>() else { return false };
ident == "with" && ((fork.peek(Token![=]) && !fork.peek(Token![==]) && !fork.peek(Token![=>])) || fork.peek(token::Paren))
}
fn is_keyed_with(input: ParseStream<'_>) -> bool {
let fork = input.fork();
if fork.parse::<Type>().is_err() || !fork.peek(Token![:]) || fork.peek(Token![::]) {
return false;
}
let _ = fork.parse::<Token![:]>();
fork.parse::<Ident>().is_ok_and(|ident| ident == "with")
}
fn parse_with_closure(input: ParseStream<'_>) -> syn::Result<ExprClosure> {
match input.parse::<Expr>()? {
Expr::Closure(closure) => {
check_factory_params(&closure)?;
Ok(closure)
}
other => Err(syn::Error::new_spanned(
other,
"`with` takes a closure whose parameters are injection points, \
as in `with = |cfg: Dep<MetricsConfig>| MetricsPlugin::new(cfg)`",
)),
}
}
impl ProviderEntry {
pub(crate) fn lower(&self) -> TokenStream {
let ulo = ulo();
let m = module_def_param();
match self {
ProviderEntry::Provide { ty, qualifier } => {
let qualified = qualified(qualifier);
let refuse = refuse_controller(ty);
quote_spanned! {ty.span()=>
#refuse
#m.provide::<#ty>()#qualified;
}
}
ProviderEntry::ProvideAs { ty, as_ty, qualifier } => {
let qualified = qualified(qualifier);
let refuse = refuse_controller(ty);
quote_spanned! {ty.span()=>
#refuse
#m.provide::<#ty>().also_as::<#as_ty>(|a| a)#qualified;
}
}
ProviderEntry::TryValue { expr, qualifier } => {
let expr = unbraced(expr);
let qualified = qualified(qualifier);
refuse_controller_value(&expr, quote_spanned! {expr.span()=> #m.try_value(#expr)#qualified })
}
ProviderEntry::Value { expr, qualifier } => {
let expr = unbraced(expr);
let qualified = qualified(qualifier);
refuse_controller_value(&expr, quote_spanned! {expr.span()=> #m.value(#expr)#qualified })
}
ProviderEntry::With { key, scope, closure } => {
let closure = wrap_async(closure);
let scope = scope.map_or_else(|| quote!(#ulo::scope::Auto), |scope| scope.path());
let bind = match key {
None => quote!(__ulo_bind::<#scope>(&mut *#m)),
Some(key) => quote!(__ulo_bind_as::<#key, #scope, _>(&mut *#m, |a| a)),
};
quote_spanned! {closure.span()=>
{
#[allow(unused_imports)]
use #ulo::__private::factory::{FallibleBinding as _, PlainBinding as _};
(&#ulo::__private::factory::Probe::new(#closure)).#bind;
}
}
}
ProviderEntry::Contribute { into, items } => {
let contributions = items.iter().map(|item| item.lower(into));
quote_spanned! {into.span()=>
{
#[allow(unused_imports)]
use #ulo::__private::contribution_key::{KeyArm as _, MetadataArm as _};
(&#ulo::__private::contribution_key::Probe::<#into>::new()).__ulo_check_contribution_key();
}
#(#contributions)*
}
}
}
}
}
fn refuse_controller_value(expr: &Expr, bind: TokenStream) -> TokenStream {
let ulo = ulo();
let handle = Ident::new("handle", Span::mixed_site());
quote_spanned! {expr.span()=>
{
let #handle = #bind;
#[allow(unused_imports)]
use #ulo::__private::controller_entry::{ControllerArm as _, ProviderArm as _};
(&#ulo::__private::controller_entry::Probe::of_handle(&#handle)).__ulo_check_provider();
}
}
}
fn refuse_controller(ty: &Type) -> TokenStream {
let ulo = ulo();
quote_spanned! {ty.span()=>
{
#[allow(unused_imports)]
use #ulo::__private::controller_entry::{ControllerArm as _, ProviderArm as _};
(&#ulo::__private::controller_entry::Probe::<#ty>::new()).__ulo_check_provider();
}
}
}
fn unbraced(expr: &Expr) -> &Expr {
if let Expr::Block(block) = expr
&& block.attrs.is_empty()
&& block.label.is_none()
&& let [syn::Stmt::Expr(inner, None)] = block.block.stmts.as_slice()
{
return inner;
}
expr
}
pub(crate) fn qualified(qualifier: &Qualifier) -> TokenStream {
match qualifier.as_deref() {
Some(q) => quote_spanned!(q.span()=> .qualified::<#q>()),
None => TokenStream::new(),
}
}
impl Contribution {
fn lower(&self, into: &Type) -> TokenStream {
let ulo = ulo();
let m = module_def_param();
match self {
Contribution::Type(ty) => {
let refuse = refuse_controller(ty);
quote_spanned! {ty.span()=>
#refuse
#m.contribute::<#into>().provide::<#ty>(|a| a);
}
}
Contribution::Value(expr) => quote_spanned! {expr.span()=>
#m.contribute::<#into>().value(#ulo::__private::Arc::new({
let v = #expr;
#[allow(unused_imports)]
use #ulo::__private::controller_entry::{ControllerArm as _, ProviderArm as _};
(&#ulo::__private::controller_entry::Probe::of(&v)).__ulo_check_provider();
v
}));
},
Contribution::TryValue(expr) => quote_spanned! {expr.span()=>
#m.contribute::<#into>().try_value(::core::result::Result::map(
#expr,
|v| -> #ulo::__private::Arc<#into> {
#[allow(unused_imports)]
use #ulo::__private::controller_entry::{ControllerArm as _, ProviderArm as _};
(&#ulo::__private::controller_entry::Probe::of(&v)).__ulo_check_provider();
#ulo::__private::Arc::new(v)
},
));
},
Contribution::With { scope, closure } => {
let closure = wrap_async(closure);
let scope = scope.map_or_else(|| quote!(#ulo::scope::Auto), |scope| scope.path());
quote_spanned! {closure.span()=>
{
#[allow(unused_imports)]
use #ulo::__private::factory::{FallibleContribution as _, PlainContribution as _};
(&#ulo::__private::factory::Probe::new(#closure))
.__ulo_contribute_with::<#into, #scope, _>(&mut *#m, |a| a);
}
}
}
}
}
}
fn written_as_role_key(ty: &Type) -> bool {
const ALIASES: &[&str] = &["AnyGuard", "AnyInterceptor", "AnyErrorHandler"];
const TWINS: &[&str] = &["ErasedGuard", "ErasedInterceptor", "ErasedErrorHandler"];
let ends_in = |path: &syn::Path, names: &[&str]| {
path.segments.last().is_some_and(|segment| names.iter().any(|name| segment.ident == *name))
};
match ty {
Type::Group(group) => written_as_role_key(&group.elem),
Type::Paren(paren) => written_as_role_key(&paren.elem),
Type::Path(path) => path.qself.is_none() && ends_in(&path.path, ALIASES),
Type::TraitObject(object) => object
.bounds
.iter()
.any(|bound| matches!(bound, TypeParamBound::Trait(t) if ends_in(&t.path, TWINS))),
_ => false,
}
}
fn is_contribution(input: ParseStream<'_>) -> bool {
let fork = input.fork();
let Ok(ident) = fork.parse::<Ident>() else { return false };
ident == "into" && fork.parse::<Type>().is_ok() && fork.peek(Token![:]) && !fork.peek(Token![::])
}
fn is_type_entry(ty: &Type) -> bool {
matches!(ty, Type::Path(_)) && !is_call(ty)
}
fn is_call(ty: &Type) -> bool {
match ty {
Type::Group(group) => is_call(&group.elem),
Type::Path(path) => {
path.path.segments.iter().any(|segment| matches!(segment.arguments, PathArguments::Parenthesized(_)))
}
_ => false,
}
}