use quote::{format_ident, quote};
use syn::ext::IdentExt as _;
use crate::name::RustSafeName;
#[cfg(test)]
mod tests;
struct Operation {
member: &'static str,
wire: &'static str,
list: bool,
}
const fn one(member: &'static str, wire: &'static str) -> Operation {
Operation {
member,
wire,
list: false,
}
}
const fn many(member: &'static str, wire: &'static str) -> Operation {
Operation {
member,
wire,
list: true,
}
}
const MEMBERSHIP: [Operation; 2] = [many("in_", "in"), many("not_in", "notIn")];
const ORDERED: [Operation; 6] = [
one("eq", "eq"),
one("ne", "ne"),
one("gt", "gt"),
one("gte", "gte"),
one("lt", "lt"),
one("lte", "lte"),
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElementFamily {
Scalar,
String,
Bytes,
Enum,
}
impl ElementFamily {
pub const ALL: [Self; 4] = [Self::Scalar, Self::String, Self::Bytes, Self::Enum];
pub const fn word(self) -> &'static str {
match self {
Self::Scalar => "scalar",
Self::String => "string",
Self::Bytes => "bytes",
Self::Enum => "enum",
}
}
const fn filter(self) -> &'static str {
match self {
Self::Scalar => "ScalarFilter",
Self::String => "TextFilter",
Self::Bytes => "BytesFilter",
Self::Enum => "EnumFilter",
}
}
const fn reading(self) -> &'static str {
match self {
Self::Scalar => "ScalarFilterMarker",
Self::String => "StringFilterMarker",
Self::Bytes => "BytesFilterMarker",
Self::Enum => "EnumFilterMarker",
}
}
const fn marker(self) -> &'static str {
match self {
Self::Scalar => "ScalarMarker",
Self::String => "StringMarker",
Self::Bytes => "BytesMarker",
Self::Enum => "EnumMarker",
}
}
fn operations(self) -> Vec<Operation> {
let mut slots = Vec::new();
match self {
Self::Scalar => slots.extend(ORDERED),
Self::Enum => slots.push(one("eq", "eq")),
Self::Bytes | Self::String => {
slots.extend(ORDERED);
slots.push(one("contains", "contains"));
if self == Self::String {
slots.push(one("contains_nocase", "containsNocase"));
}
slots.push(one("not_contains", "notContains"));
if self == Self::String {
slots.extend([
one("not_contains_nocase", "notContainsNocase"),
one("starts_with", "startsWith"),
one("starts_with_nocase", "startsWithNocase"),
one("not_starts_with", "notStartsWith"),
one("not_starts_with_nocase", "notStartsWithNocase"),
one("ends_with", "endsWith"),
one("ends_with_nocase", "endsWithNocase"),
one("not_ends_with", "notEndsWith"),
one("not_ends_with_nocase", "notEndsWithNocase"),
]);
}
}
}
if self == Self::Enum {
slots.push(one("ne", "ne"));
}
slots.extend(MEMBERSHIP);
slots
}
}
pub struct ElementModel {
pub vis: syn::Visibility,
pub subject: syn::Ident,
pub krate: syn::Path,
pub filter: RustSafeName,
pub family: ElementFamily,
pub member: syn::Member,
pub inner: syn::Type,
pub wire_name: Option<String>,
}
impl ElementModel {
fn framework(&self, module: &[&str], item: &str) -> proc_macro2::TokenStream {
crate::emit::framework(&self.krate, module, item)
}
fn held(&self) -> proc_macro2::TokenStream {
let kind = self.framework(&["graphql"], self.family.filter());
let subject = &self.subject;
quote!(#kind<#subject>)
}
fn sdl(&self) -> String {
self
.wire_name
.clone()
.unwrap_or_else(|| self.subject.unraw().to_string())
}
pub fn emit(&self) -> proc_macro2::TokenStream {
let declaration = self.declaration();
let face = self.inherent();
let contract = self.emptiness();
let lowering = self.lowering();
let operands = self.operand_map();
let readings = self.readings();
let wire = self.wire();
quote! {
#declaration
#face
#contract
#lowering
#operands
#readings
#wire
}
}
fn declaration(&self) -> proc_macro2::TokenStream {
let vis = &self.vis;
let name = self.filter.safe();
let held = self.held();
let subject = &self.subject;
let doc = format!(
"The `{}` reading of [`{subject}`], as a client writes one — the framework's own {} filter \
over an element this crate declares.",
self.family.word(),
self.family.word()
);
quote! {
#[doc = #doc]
#[derive(Debug, Clone, PartialEq)]
#vis struct #name(pub(crate) #held);
#[automatically_derived]
impl ::core::default::Default for #name {
#[inline]
fn default() -> Self {
Self::new()
}
}
}
}
fn inherent(&self) -> proc_macro2::TokenStream {
let name = self.filter.safe();
let held = self.held();
let subject = &self.subject;
let slots = self.family.operations().into_iter().map(|slot| {
let member = format_ident!("{}", slot.member);
let with = format_ident!("with_{}", slot.member);
let maybe = format_ident!("maybe_{}", slot.member);
let read = format!(
"The `{}` operand{}, or `None` while the operator is absent.",
slot.wire,
if slot.list { "s" } else { "" }
);
let set = format!("Set `{}` to `Some(value)` (consuming).", slot.wire);
let assign = format!("Assign the raw `{}` option (consuming).", slot.wire);
if slot.list {
quote! {
#[doc = #read]
#[inline]
pub fn #member(&self) -> ::core::option::Option<&[#subject]> {
self.0.#member()
}
#[doc = #set]
#[must_use]
#[inline]
pub fn #with(self, value: impl ::core::convert::Into<::std::boxed::Box<[#subject]>>) -> Self {
Self(self.0.#with(value))
}
#[doc = #assign]
#[must_use]
#[inline]
pub fn #maybe(
self,
value: ::core::option::Option<impl ::core::convert::Into<::std::boxed::Box<[#subject]>>>,
) -> Self {
Self(self.0.#maybe(value))
}
}
} else {
quote! {
#[doc = #read]
#[inline]
pub fn #member(&self) -> ::core::option::Option<&#subject> {
self.0.#member()
}
#[doc = #set]
#[must_use]
#[inline]
pub fn #with(self, value: #subject) -> Self {
Self(self.0.#with(value))
}
#[doc = #assign]
#[must_use]
#[inline]
pub fn #maybe(self, value: ::core::option::Option<#subject>) -> Self {
Self(self.0.#maybe(value))
}
}
}
});
quote! {
#[automatically_derived]
impl #name {
#[inline]
#[must_use]
pub const fn new() -> Self {
Self(<#held>::new())
}
#[inline]
#[must_use]
pub const fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[inline]
#[must_use]
pub const fn get(&self) -> &#held {
&self.0
}
#[inline]
#[must_use]
pub fn into_inner(self) -> #held {
self.0
}
#(#slots)*
}
}
}
fn emptiness(&self) -> proc_macro2::TokenStream {
let name = self.filter.safe();
let contract = self.framework(&["graphql"], "GraphqlFilter");
quote! {
#[automatically_derived]
impl #contract for #name {
#[inline]
fn is_empty(&self) -> bool {
Self::is_empty(self)
}
}
}
}
fn lowering(&self) -> proc_macro2::TokenStream {
let name = self.filter.safe();
let held = self.held();
let backend = self.framework(&["comparison"], "Backend");
let map = self.framework(&["comparison"], "ToDatabaseComparison");
let value = crate::emit::parameter("V");
let db = crate::emit::parameter("DB");
quote! {
#[automatically_derived]
impl<#value, #db> #map<#value, #db> for #name
where
#db: #backend,
#held: #map<#value, #db>,
{
type Comparison = <#held as #map<#value, #db>>::Comparison;
}
}
}
fn operand_map(&self) -> proc_macro2::TokenStream {
let name = self.filter.safe();
let held = self.held();
let subject = &self.subject;
let map = self.framework(&["graphql"], "TryMapFilter");
let stored = crate::emit::parameter("STORED");
let refusal = crate::emit::parameter("REFUSAL");
let convert = crate::emit::parameter("CONVERT");
quote! {
#[automatically_derived]
impl<#stored> #map<#subject, #stored> for #name {
type Mapped = <#held as #map<#subject, #stored>>::Mapped;
#[inline]
fn try_map_filter<#refusal, #convert>(
self,
__ingraph_convert: #convert,
) -> ::core::result::Result<Self::Mapped, #refusal>
where
#convert: ::core::ops::FnMut(#subject) -> ::core::result::Result<#stored, #refusal>,
{
<#held as #map<#subject, #stored>>::try_map_filter(
Self::into_inner(self),
__ingraph_convert,
)
}
}
}
}
fn readings(&self) -> proc_macro2::TokenStream {
let name = self.filter.safe();
let subject = &self.subject;
let reading = self.framework(&["marker"], self.family.reading());
let default = self.framework(&["marker"], "DefaultMarker");
let marker = self.framework(&["marker"], self.family.marker());
quote! {
#[automatically_derived]
impl #reading for #subject {
type Filter = #name;
}
#[automatically_derived]
impl #default for #subject {
type Marker = #marker<#subject>;
}
}
}
fn wire(&self) -> proc_macro2::TokenStream {
let gate = self.framework(&["gate"], "if_async_graphql");
let scalar = self.scalar();
let input = self.input_crossing();
let output = self.output_crossing();
let face = self.filter_face();
quote! {
const _: () = {
#gate! {
#scalar
#input
#output
#face
}
};
}
}
fn scalar(&self) -> proc_macro2::TokenStream {
let subject = &self.subject;
let inner = &self.inner;
let ag = self.framework(&[], "async_graphql");
let shelf = crate::emit::vendored(&self.krate, "async_graphql");
let sdl = self.sdl();
let build = match &self.member {
syn::Member::Named(ident) => quote!(|__ingraph_inner| Self { #ident: __ingraph_inner }),
syn::Member::Unnamed(_) => quote!(Self),
};
let member = &self.member;
quote! {
#[#ag::Scalar(crate = #shelf, name = #sdl)]
impl #ag::ScalarType for #subject {
fn parse(__ingraph_value: #ag::Value) -> #ag::InputValueResult<Self> {
::core::result::Result::map_err(
::core::result::Result::map(
<#inner as #ag::InputType>::parse(::core::option::Option::Some(__ingraph_value)),
#build,
),
#ag::InputValueError::propagate,
)
}
fn to_value(&self) -> #ag::Value {
<#inner as #ag::InputType>::to_value(&self.#member)
}
}
}
}
fn input_crossing(&self) -> proc_macro2::TokenStream {
let subject = &self.subject;
let crossing = self.framework(&["graphql"], "ToGraphqlInput");
quote! {
#[automatically_derived]
impl #crossing for #subject {
type Input = Self;
type Error = ::core::convert::Infallible;
#[inline]
fn cross(
__ingraph_value: Self,
) -> ::core::result::Result<Self, ::core::convert::Infallible> {
::core::result::Result::Ok(__ingraph_value)
}
#[inline]
fn carry(__ingraph_value: &Self) -> Self {
::core::clone::Clone::clone(__ingraph_value)
}
}
}
}
fn output_crossing(&self) -> proc_macro2::TokenStream {
let subject = &self.subject;
let crossing = self.framework(&["graphql"], "ToGraphqlOutput");
quote! {
#[automatically_derived]
impl #crossing for #subject {
type Output<'__ingraph> = &'__ingraph Self;
#[inline]
fn to_graphql_output(__ingraph_value: &Self) -> &Self {
__ingraph_value
}
}
}
}
fn filter_face(&self) -> proc_macro2::TokenStream {
let name = self.filter.safe();
let subject = &self.subject;
let held = self.held();
let ag = self.framework(&[], "async_graphql");
let nullable_face = self.framework(&["graphql"], "NullableFace");
let sent = self.framework(&["graphql", "filter"], "sent");
let sent_ty = self.framework(&["graphql", "filter"], "Sent");
let sdl = self.filter.external().to_owned();
let slots = self.family.operations();
let bare = slots
.first()
.expect("an element family publishes at least one operator slot")
.wire;
let fields = slots.iter().map(|slot| {
let wire = slot.wire;
let ty = Self::slot_type("e!(#subject), slot.list);
quote! {
__ingraph_fields.insert(
::std::string::String::from(#wire),
#ag::registry::MetaInputValue {
name: ::std::string::String::from(#wire),
description: ::core::option::Option::None,
ty: <#ty as #ag::InputType>::create_type_info(__ingraph_registry),
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 = slots.iter().map(|slot| {
let wire = slot.wire;
let maybe = format_ident!("maybe_{}", slot.member);
let ty = Self::slot_type("e!(#subject), slot.list);
quote! {
__ingraph_held = __ingraph_held.#maybe(
::core::result::Result::map_err(
<#ty as #ag::InputType>::parse(
#ag::indexmap::IndexMap::get(&__ingraph_object, #wire).cloned(),
),
#ag::InputValueError::propagate,
)?,
);
}
});
let writes = slots.iter().map(|slot| {
let wire = slot.wire;
let member = format_ident!("{}", slot.member);
let held = if slot.list {
quote!(self.0.#member().map(<::std::boxed::Box<[#subject]>>::from))
} else {
quote!(self.0.#member().cloned())
};
quote! {
__ingraph_map.insert(#ag::Name::new(#wire), #ag::InputType::to_value(&#held));
}
});
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: <Self as #nullable_face>::bare_fields(__ingraph_registry),
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
oneof: false,
directive_invocations: ::std::vec::Vec::new(),
},
)
}
fn parse(
__ingraph_value: ::core::option::Option<#ag::Value>,
) -> #ag::InputValueResult<Self> {
let __ingraph_object = match #sent(__ingraph_value) {
#sent_ty::Longhand(__ingraph_object) => __ingraph_object,
#sent_ty::Bare(__ingraph_bare) => {
let mut __ingraph_object = #ag::indexmap::IndexMap::new();
#ag::indexmap::IndexMap::insert(
&mut __ingraph_object,
#ag::Name::new(#bare),
__ingraph_bare,
);
__ingraph_object
}
#sent_ty::Null => {
return ::core::result::Result::Err(#ag::InputValueError::expected_type(
#ag::Value::Null,
));
}
#sent_ty::Refused(__ingraph_sent) => {
return ::core::result::Result::Err(#ag::InputValueError::expected_type(
__ingraph_sent,
));
}
};
let mut __ingraph_held = <#held>::new();
#(#reads)*
::core::result::Result::Ok(Self(__ingraph_held))
}
fn to_value(&self) -> #ag::Value {
#ag::Value::Object(<Self as #nullable_face>::bare_values(self))
}
#[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 #nullable_face for #name {
fn bare_fields(
__ingraph_registry: &mut #ag::registry::Registry,
) -> #ag::indexmap::IndexMap<::std::string::String, #ag::registry::MetaInputValue> {
let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
#(#fields)*
__ingraph_fields
}
fn bare_values(&self) -> #ag::indexmap::IndexMap<#ag::Name, #ag::Value> {
let mut __ingraph_map = #ag::indexmap::IndexMap::new();
#(#writes)*
__ingraph_map
}
}
}
}
fn slot_type(subject: &proc_macro2::TokenStream, list: bool) -> proc_macro2::TokenStream {
if list {
quote!(::core::option::Option<::std::boxed::Box<[#subject]>>)
} else {
quote!(::core::option::Option<#subject>)
}
}
}