async-graphql/derive/src/union.rs

188 lines
7.2 KiB
Rust
Raw Normal View History

2020-03-08 01:21:29 +00:00
use crate::args;
2020-09-28 09:44:00 +00:00
use crate::utils::{get_crate_name, get_rustdoc, GeneratorResult};
use darling::ast::{Data, Style};
2020-03-08 01:21:29 +00:00
use proc_macro::TokenStream;
use quote::quote;
use std::collections::HashSet;
2020-09-28 09:44:00 +00:00
use syn::{Error, Type};
2020-03-08 01:21:29 +00:00
2020-09-28 09:44:00 +00:00
pub fn generate(union_args: &args::Union) -> GeneratorResult<TokenStream> {
let crate_name = get_crate_name(union_args.internal);
2020-09-28 09:44:00 +00:00
let ident = &union_args.ident;
let generics = &union_args.generics;
let s = match &union_args.data {
Data::Enum(s) => s,
_ => {
2020-09-28 09:44:00 +00:00
return Err(Error::new_spanned(&ident, "Union can only be applied to an enum.").into())
}
2020-03-08 01:21:29 +00:00
};
let mut enum_names = Vec::new();
let mut enum_items = HashSet::new();
2020-03-08 01:21:29 +00:00
let mut type_into_impls = Vec::new();
let gql_typename = union_args.name.clone().unwrap_or_else(|| ident.to_string());
2020-03-19 09:20:12 +00:00
2020-09-28 09:44:00 +00:00
let desc = get_rustdoc(&union_args.attrs)?
.map(|s| quote! { Some(#s) })
2020-03-08 01:21:29 +00:00
.unwrap_or_else(|| quote! {None});
2020-03-08 01:21:29 +00:00
let mut registry_types = Vec::new();
let mut possible_types = Vec::new();
let mut get_introspection_typename = Vec::new();
2020-09-12 09:29:52 +00:00
let mut collect_all_fields = Vec::new();
2020-03-08 01:21:29 +00:00
2020-09-28 09:44:00 +00:00
for variant in s {
let enum_name = &variant.ident;
2020-09-28 09:44:00 +00:00
let ty = match variant.fields.style {
Style::Tuple if variant.fields.fields.len() == 1 => &variant.fields.fields[0],
Style::Tuple => {
return Err(Error::new_spanned(
2020-09-28 09:44:00 +00:00
enum_name,
"Only single value variants are supported",
2020-09-28 09:44:00 +00:00
)
.into())
}
2020-09-28 09:44:00 +00:00
Style::Unit => {
return Err(
Error::new_spanned(enum_name, "Empty variants are not supported").into(),
)
}
2020-09-28 09:44:00 +00:00
Style::Struct => {
return Err(Error::new_spanned(
2020-09-28 09:44:00 +00:00
enum_name,
"Variants with named fields are not supported",
2020-09-28 09:44:00 +00:00
)
.into())
}
};
2020-09-28 09:44:00 +00:00
if let Type::Path(p) = &ty {
// This validates that the field type wasn't already used
if !enum_items.insert(p) {
2020-09-28 09:44:00 +00:00
return Err(
Error::new_spanned(&ty, "This type already used in another variant").into(),
);
}
2020-03-08 01:21:29 +00:00
enum_names.push(enum_name);
2020-09-28 09:44:00 +00:00
if !variant.flatten {
type_into_impls.push(quote! {
#crate_name::static_assertions::assert_impl_one!(#p: #crate_name::type_mark::TypeMarkObject);
#[allow(clippy::all, clippy::pedantic)]
impl #generics ::std::convert::From<#p> for #ident #generics {
fn from(obj: #p) -> Self {
#ident::#enum_name(obj)
}
2020-03-08 01:21:29 +00:00
}
});
} else {
type_into_impls.push(quote! {
#crate_name::static_assertions::assert_impl_one!(#p: #crate_name::type_mark::TypeMarkEnum);
#[allow(clippy::all, clippy::pedantic)]
impl #generics ::std::convert::From<#p> for #ident #generics {
fn from(obj: #p) -> Self {
#ident::#enum_name(obj)
}
}
});
}
2020-03-08 01:21:29 +00:00
registry_types.push(quote! {
2020-03-19 09:20:12 +00:00
<#p as #crate_name::Type>::create_type_info(registry);
2020-03-08 01:21:29 +00:00
});
2020-09-28 09:44:00 +00:00
if !variant.flatten {
possible_types.push(quote! {
possible_types.insert(<#p as #crate_name::Type>::type_name().to_string());
});
} else {
possible_types.push(quote! {
if let Some(#crate_name::registry::MetaType::Union { possible_types: possible_types2, .. }) =
registry.types.remove(&*<#p as #crate_name::Type>::type_name()) {
possible_types.extend(possible_types2);
}
});
}
2020-09-28 09:44:00 +00:00
if !variant.flatten {
get_introspection_typename.push(quote! {
#ident::#enum_name(obj) => <#p as #crate_name::Type>::type_name()
});
} else {
get_introspection_typename.push(quote! {
#ident::#enum_name(obj) => <#p as #crate_name::Type>::introspection_type_name(obj)
});
}
2020-09-12 09:29:52 +00:00
collect_all_fields.push(quote! {
#ident::#enum_name(obj) => obj.collect_all_fields(ctx, fields)
});
2020-03-08 01:21:29 +00:00
} else {
2020-09-28 09:44:00 +00:00
return Err(Error::new_spanned(ty, "Invalid type").into());
2020-03-08 01:21:29 +00:00
}
}
let expanded = quote! {
#(#type_into_impls)*
#[allow(clippy::all, clippy::pedantic)]
2020-03-19 09:20:12 +00:00
impl #generics #crate_name::Type for #ident #generics {
fn type_name() -> ::std::borrow::Cow<'static, str> {
::std::borrow::Cow::Borrowed(#gql_typename)
2020-03-08 01:21:29 +00:00
}
fn introspection_type_name(&self) -> ::std::borrow::Cow<'static, str> {
match self {
#(#get_introspection_typename),*
}
}
2020-03-08 01:21:29 +00:00
fn create_type_info(registry: &mut #crate_name::registry::Registry) -> String {
registry.create_type::<Self, _>(|registry| {
#(#registry_types)*
#crate_name::registry::MetaType::Union {
2020-03-19 09:33:33 +00:00
name: #gql_typename.to_string(),
2020-03-08 01:21:29 +00:00
description: #desc,
2020-03-10 10:07:47 +00:00
possible_types: {
let mut possible_types = #crate_name::indexmap::IndexSet::new();
2020-03-10 10:07:47 +00:00
#(#possible_types)*
possible_types
}
2020-03-08 01:21:29 +00:00
}
})
}
}
#[allow(clippy::all, clippy::pedantic)]
2020-03-08 01:21:29 +00:00
#[#crate_name::async_trait::async_trait]
2020-09-12 09:29:52 +00:00
impl #generics #crate_name::resolver_utils::ObjectType for #ident #generics {
async fn resolve_field(&self, ctx: &#crate_name::Context<'_>) -> #crate_name::Result<#crate_name::serde_json::Value> {
Err(#crate_name::QueryError::FieldNotFound {
2020-09-12 16:42:15 +00:00
field_name: ctx.item.node.name.to_string(),
2020-03-08 01:21:29 +00:00
object: #gql_typename.to_string(),
2020-09-12 16:42:15 +00:00
}.into_error(ctx.item.pos))
2020-03-08 01:21:29 +00:00
}
2020-09-12 09:29:52 +00:00
fn collect_all_fields<'a>(&'a self, ctx: &#crate_name::ContextSelectionSet<'a>, fields: &mut #crate_name::resolver_utils::Fields<'a>) -> #crate_name::Result<()> {
match self {
#(#collect_all_fields),*
}
2020-03-08 01:21:29 +00:00
}
}
2020-03-19 09:20:12 +00:00
#[allow(clippy::all, clippy::pedantic)]
2020-03-19 09:20:12 +00:00
#[#crate_name::async_trait::async_trait]
impl #generics #crate_name::OutputValueType for #ident #generics {
2020-09-06 05:38:31 +00:00
async fn resolve(&self, ctx: &#crate_name::ContextSelectionSet<'_>, _field: &#crate_name::Positioned<#crate_name::parser::types::Field>) -> #crate_name::Result<#crate_name::serde_json::Value> {
2020-09-12 09:29:52 +00:00
#crate_name::resolver_utils::resolve_object(ctx, self).await
2020-03-19 09:20:12 +00:00
}
}
impl #generics #crate_name::type_mark::TypeMarkEnum for #ident #generics {}
2020-03-08 01:21:29 +00:00
};
Ok(expanded.into())
}