use quote::{quote, quote_spanned};
use syn::spanned::Spanned as _;
use super::{UnionModel, UnionSkin};
use crate::model::GraphqlKind;
#[cfg(test)]
mod tests;
impl UnionModel {
pub(super) fn graphql_faces(&self) -> proc_macro2::TokenStream {
let skins = self.graphql.iter().map(|skin| self.skin(skin));
quote!(#(#skins)*)
}
fn skin(&self, skin: &UnionSkin) -> proc_macro2::TokenStream {
let gate = self.framework(&["gate"], "if_async_graphql");
let (seats, input) = match skin.input {
Some(_) => (self.seat_trait(), self.input_face(skin)),
None => (quote!(), quote!()),
};
let output = if skin.output.is_some() {
self.output_face(skin)
} else {
quote!()
};
match skin.kind {
GraphqlKind::AsyncGraphql => quote! {
const _: () = {
#gate! {
#seats
#output
#input
}
};
},
}
}
fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
crate::emit::framework(&self.krate, module, name)
}
fn async_graphql(&self) -> proc_macro2::TokenStream {
self.framework(&[], "async_graphql")
}
fn output_face(&self, skin: &UnionSkin) -> proc_macro2::TokenStream {
let name = &self.name;
let ag = self.async_graphql();
let sdl = skin.output_sdl(name);
let variants = self.members.iter().map(|member| &member.ident);
let names = self.members.iter().map(|member| {
let ty = &member.ty;
quote_spanned!(ty.span()=> <#ty as #ag::OutputType>::type_name())
});
let arms = self.members.iter().map(|member| {
let ident = &member.ident;
let ty = &member.ty;
let named = quote_spanned!(ty.span()=> <#ty as #ag::OutputType>::type_name());
quote!(Self::#ident(_) => #named,)
});
let registered = self.members.iter().map(|member| {
let ty = &member.ty;
quote_spanned! {ty.span()=>
<#ty as #ag::OutputType>::create_type_info(__ingraph_registry);
}
});
quote! {
#[automatically_derived]
impl #ag::resolver_utils::ContainerType for #name {
async fn resolve_field(
&self,
_ctx: &#ag::Context<'_>,
) -> #ag::ServerResult<::core::option::Option<#ag::Value>> {
::core::result::Result::Ok(::core::option::Option::None)
}
fn collect_all_fields<'__ingraph_member>(
&'__ingraph_member self,
__ingraph_ctx: &#ag::ContextSelectionSet<'__ingraph_member>,
__ingraph_fields: &mut #ag::resolver_utils::Fields<'__ingraph_member>,
) -> #ag::ServerResult<()> {
match self {
#(Self::#variants(__ingraph_arm) => #ag::resolver_utils::ContainerType::collect_all_fields(
__ingraph_arm,
__ingraph_ctx,
__ingraph_fields,
),)*
}
}
}
#[automatically_derived]
impl #ag::OutputType for #name {
fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
::std::borrow::Cow::Borrowed(#sdl)
}
fn introspection_type_name(&self) -> ::std::borrow::Cow<'static, ::core::primitive::str> {
match self { #(#arms)* }
}
fn create_type_info(
__ingraph_registry: &mut #ag::registry::Registry,
) -> ::std::string::String {
__ingraph_registry.create_output_type::<Self, _>(
#ag::registry::MetaTypeId::Union,
|__ingraph_registry| {
#(#registered)*
#ag::registry::MetaType::Union {
name: ::std::string::String::from(#sdl),
description: ::core::option::Option::None,
possible_types: {
let mut __ingraph_arms = #ag::indexmap::IndexSet::new();
#(__ingraph_arms.insert(::std::borrow::Cow::into_owned(#names));)*
__ingraph_arms
},
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
directive_invocations: ::std::vec::Vec::new(),
}
},
)
}
async fn resolve(
&self,
__ingraph_ctx: &#ag::ContextSelectionSet<'_>,
_field: &#ag::Positioned<#ag::parser::types::Field>,
) -> #ag::ServerResult<#ag::Value> {
#ag::resolver_utils::resolve_container(__ingraph_ctx, self).await
}
}
#[automatically_derived]
impl #ag::UnionType for #name {}
}
}
fn seat_trait(&self) -> proc_macro2::TokenStream {
let ag = self.async_graphql();
let seat = self.seat_marker();
let name = &self.name;
let message = format!(
"`{{Self}}` is a member of `{name}`, which declares a GraphQL INPUT face, and has no \
`async_graphql::InputType` of its own"
);
let note = format!(
"an `@oneOf` input object's seats ARE its members' own input types, so every member of \
`{name}` needs one — give this member an input face, or drop `input` from its \
`graphql(async_graphql(…))` block and declare `{name}` for output alone"
);
quote! {
#[diagnostic::on_unimplemented(
message = #message,
label = "this member has no GraphQL input face",
note = #note,
)]
trait #seat: ::core::marker::Sized {
fn __ingraph_seat_type(
__ingraph_registry: &mut #ag::registry::Registry,
) -> ::std::string::String;
fn __ingraph_seat_parse<__IngraphUnion: #ag::InputType>(
__ingraph_value: ::core::option::Option<#ag::Value>,
) -> ::core::result::Result<Self, #ag::InputValueError<__IngraphUnion>>;
fn __ingraph_seat_value(&self) -> #ag::Value;
}
#[diagnostic::do_not_recommend]
impl<__IngraphMember: #ag::InputType> #seat for __IngraphMember {
#[inline]
fn __ingraph_seat_type(
__ingraph_registry: &mut #ag::registry::Registry,
) -> ::std::string::String {
<::core::option::Option<Self> as #ag::InputType>::create_type_info(__ingraph_registry)
}
#[inline]
fn __ingraph_seat_parse<__IngraphUnion: #ag::InputType>(
__ingraph_value: ::core::option::Option<#ag::Value>,
) -> ::core::result::Result<Self, #ag::InputValueError<__IngraphUnion>> {
<Self as #ag::InputType>::parse(__ingraph_value)
.map_err(#ag::InputValueError::propagate)
}
#[inline]
fn __ingraph_seat_value(&self) -> #ag::Value {
<Self as #ag::InputType>::to_value(self)
}
}
}
}
fn seat_marker(&self) -> syn::Ident {
quote::format_ident!("__IngraphSeat")
}
fn input_face(&self, skin: &UnionSkin) -> proc_macro2::TokenStream {
let name = &self.name;
let ag = self.async_graphql();
let seat = self.seat_marker();
let sdl = skin.input_sdl(name);
let fields = self.members.iter().map(|member| {
let ty = &member.ty;
let word = super::seat(&member.ident);
let seated = quote_spanned! {ty.span()=>
<#ty as #seat>::__ingraph_seat_type(__ingraph_registry)
};
quote! {
__ingraph_fields.insert(
::std::string::String::from(#word),
#ag::registry::MetaInputValue {
name: ::std::string::String::from(#word),
description: ::core::option::Option::None,
ty: #seated,
deprecation: #ag::registry::Deprecation::NoDeprecated,
default_value: ::core::option::Option::None,
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
is_secret: false,
directive_invocations: ::std::vec::Vec::new(),
},
);
}
});
let reads = self.members.iter().map(|member| {
let ident = &member.ident;
let ty = &member.ty;
let word = super::seat(&member.ident);
let seated = quote_spanned! {ty.span()=>
<#ty as #seat>::__ingraph_seat_parse::<Self>(
#ag::indexmap::IndexMap::swap_remove(&mut __ingraph_object, #word),
)
};
quote! {
if #ag::indexmap::IndexMap::contains_key(&__ingraph_object, #word)
&& __ingraph_object.len() == 1
{
let __ingraph_chosen = #seated?;
return ::core::result::Result::Ok(Self::#ident(__ingraph_chosen));
}
}
});
let writes = self.members.iter().map(|member| {
let ident = &member.ident;
let ty = &member.ty;
let word = super::seat(&member.ident);
let seated = quote_spanned! {ty.span()=>
<#ty as #seat>::__ingraph_seat_value(__ingraph_chosen)
};
quote! {
Self::#ident(__ingraph_chosen) => {
__ingraph_map.insert(#ag::Name::new(#word), #seated);
}
}
});
quote! {
#[automatically_derived]
impl #ag::InputType for #name {
type RawValueType = Self;
#[inline]
fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
::std::borrow::Cow::Borrowed(#sdl)
}
fn create_type_info(
__ingraph_registry: &mut #ag::registry::Registry,
) -> ::std::string::String {
__ingraph_registry.create_input_type::<Self, _>(
#ag::registry::MetaTypeId::InputObject,
|__ingraph_registry| #ag::registry::MetaType::InputObject {
name: ::std::string::String::from(#sdl),
description: ::core::option::Option::None,
input_fields: {
let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
#(#fields)*
__ingraph_fields
},
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
oneof: true,
directive_invocations: ::std::vec::Vec::new(),
},
)
}
fn parse(
__ingraph_value: ::core::option::Option<#ag::Value>,
) -> #ag::InputValueResult<Self> {
if let ::core::option::Option::Some(#ag::Value::Object(mut __ingraph_object)) =
__ingraph_value
{
#(#reads)*
return ::core::result::Result::Err(#ag::InputValueError::expected_type(
#ag::Value::Object(__ingraph_object),
));
}
::core::result::Result::Err(#ag::InputValueError::expected_type(
::core::option::Option::unwrap_or_default(__ingraph_value),
))
}
fn to_value(&self) -> #ag::Value {
let mut __ingraph_map = #ag::indexmap::IndexMap::new();
match self { #(#writes)* }
#ag::Value::Object(__ingraph_map)
}
#[inline]
fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
::core::option::Option::Some(self)
}
}
#[automatically_derived]
impl #ag::InputObjectType for #name {}
#[automatically_derived]
impl #ag::OneofObjectType for #name {}
}
}
}