use quote::{format_ident, quote};
use syn::ext::IdentExt as _;
#[cfg(test)]
mod tests;
pub struct IdModel {
pub vis: syn::Visibility,
pub subject: syn::Ident,
pub krate: syn::Path,
pub inner: syn::Type,
}
impl IdModel {
fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
crate::emit::framework(&self.krate, module, name)
}
fn vendored(&self, name: &str) -> String {
crate::emit::vendored(&self.krate, name)
}
#[must_use]
pub fn reading_name(&self) -> syn::Ident {
format_ident!("{}Wire", self.subject)
}
fn sdl(&self) -> String {
self.subject.unraw().to_string()
}
fn owes(&self, bound: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
let inner = &self.inner;
quote!(#inner: #bound)
}
fn key_delegation(&self) -> proc_macro2::TokenStream {
let subject = &self.subject;
let inner = &self.inner;
let delegates = self.framework(&["id"], "DelegatesId");
quote! {
#[automatically_derived]
unsafe impl #delegates for #subject {
type Inner = #inner;
#[inline]
fn delegate(&self) -> &#inner {
&self.0
}
}
}
}
fn identity(&self) -> proc_macro2::TokenStream {
let subject = &self.subject;
let inner = &self.inner;
let name = subject.to_string();
let debug = self.owes(quote!(::core::fmt::Debug));
let clone = self.owes(quote!(::core::clone::Clone));
let partial_eq = self.owes(quote!(::core::cmp::PartialEq));
let eq = self.owes(quote!(::core::cmp::Eq));
let hash = self.owes(quote!(::core::hash::Hash));
quote! {
#[automatically_derived]
impl ::core::fmt::Debug for #subject where #debug {
#[inline]
fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
let mut __ingraph_tuple = ::core::fmt::Formatter::debug_tuple(__ingraph_f, #name);
::core::fmt::DebugTuple::field(&mut __ingraph_tuple, &self.0);
::core::fmt::DebugTuple::finish(&mut __ingraph_tuple)
}
}
#[automatically_derived]
impl ::core::clone::Clone for #subject where #clone {
#[inline]
fn clone(&self) -> Self {
Self(<#inner as ::core::clone::Clone>::clone(&self.0))
}
}
#[automatically_derived]
impl ::core::cmp::PartialEq for #subject where #partial_eq {
#[inline]
fn eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
<#inner as ::core::cmp::PartialEq>::eq(&self.0, &__ingraph_other.0)
}
}
#[automatically_derived]
impl ::core::cmp::Eq for #subject where #eq {}
#[automatically_derived]
impl ::core::hash::Hash for #subject where #hash {
#[inline]
fn hash<__IngraphHasher>(&self, __ingraph_state: &mut __IngraphHasher)
where
__IngraphHasher: ::core::hash::Hasher,
{
<#inner as ::core::hash::Hash>::hash(&self.0, __ingraph_state);
}
}
}
}
fn text(&self) -> proc_macro2::TokenStream {
let subject = &self.subject;
let inner = &self.inner;
let display = self.owes(quote!(::core::fmt::Display));
let from_str = self.owes(quote!(::core::str::FromStr));
let crossing = if self.inner_is_string() {
quote!()
} else {
quote! {
#[automatically_derived]
impl ::core::convert::From<#subject> for ::std::string::String where #display {
#[inline]
fn from(__ingraph_id: #subject) -> Self {
::std::string::ToString::to_string(&__ingraph_id)
}
}
}
};
quote! {
#[automatically_derived]
impl ::core::fmt::Display for #subject where #display {
#[inline]
fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
<#inner as ::core::fmt::Display>::fmt(&self.0, __ingraph_f)
}
}
#[automatically_derived]
impl ::core::str::FromStr for #subject where #from_str {
type Err = <#inner as ::core::str::FromStr>::Err;
#[inline]
fn from_str(__ingraph_text: &::core::primitive::str) -> ::core::result::Result<Self, Self::Err> {
::core::result::Result::map(
<#inner as ::core::str::FromStr>::from_str(__ingraph_text),
Self,
)
}
}
#[automatically_derived]
impl ::core::convert::From<#inner> for #subject {
#[inline]
fn from(__ingraph_inner: #inner) -> Self {
Self(__ingraph_inner)
}
}
#[automatically_derived]
impl ::core::convert::From<#subject> for #inner {
#[inline]
fn from(__ingraph_id: #subject) -> Self {
__ingraph_id.0
}
}
#crossing
}
}
fn inner_is_string(&self) -> bool {
const SPELLINGS: [&str; 4] = [
"String",
"std :: string :: String",
":: std :: string :: String",
"alloc :: string :: String",
];
let written = quote::ToTokens::to_token_stream(&self.inner).to_string();
SPELLINGS.contains(&written.as_str())
}
fn storage(&self) -> proc_macro2::TokenStream {
let subject = &self.subject;
let inner = &self.inner;
let cursor_value = self.framework(&["cursor"], "CursorValue");
let column_kind = self.framework(&["column"], "ColumnKind");
let column_eq = self.framework(&["column"], "ColumnEq");
let owed_eq = self.owes(quote!(#column_eq));
let order_leaves = self.framework(&["column"], "DeclaredLeaves");
let stored_as = self.framework(&["column"], "StoredAs");
let assemble = self.framework(&["column"], "Assemble");
let id_column = self.framework(&["id"], "IdColumn");
let carrier = self.framework(&["comparison", "sql"], "Carrier");
let path = self.framework(&["comparison"], "Path");
let gate = self.framework(&["gate"], "if_sqlx");
let database = self.framework(&["sqlx"], "Database");
let query_builder = self.framework(&["sqlx"], "QueryBuilder");
let result = self.framework(&["sqlx"], "Result");
let sqlx_error = self.framework(&["sqlx"], "Error");
let row = self.framework(&["sqlx"], "Row");
let cursor = self.owes(quote!(#cursor_value));
let seam = quote!(#id_column<__IngraphDb>);
let stored = quote!(<#inner as #seam>::Stored);
let row_seam = quote!(#id_column<<__IngraphRow as #row>::Database>);
let row_stored = quote!(<#inner as #row_seam>::Stored);
quote! {
#[automatically_derived]
impl #cursor_value for #subject where #cursor {
#[inline]
fn write_cursor(&self, __ingraph_out: &mut ::std::vec::Vec<::core::primitive::u8>) {
<#inner as #cursor_value>::write_cursor(&self.0, __ingraph_out)
}
#[inline]
fn read_cursor(__ingraph_bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
::core::option::Option::map(
<#inner as #cursor_value>::read_cursor(__ingraph_bytes),
Self,
)
}
}
#[automatically_derived]
impl #column_kind for #subject {}
#[automatically_derived]
impl #column_eq for #subject where #owed_eq {
#[inline]
fn column_eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
<#inner as #column_eq>::column_eq(&self.0, &__ingraph_other.0)
}
}
#[automatically_derived]
impl #order_leaves for #subject {}
#[automatically_derived]
impl<__IngraphDb> #seam for #subject
where
#inner: #seam,
{
type Stored = #stored;
type Refusal = <#inner as #seam>::Refusal;
#[inline]
fn to_stored(&self) -> Self::Stored {
<#inner as #seam>::to_stored(&self.0)
}
#[inline]
fn from_stored(
__ingraph_stored: Self::Stored,
) -> ::core::result::Result<Self, Self::Refusal> {
::core::result::Result::map(<#inner as #seam>::from_stored(__ingraph_stored), Self)
}
}
#[automatically_derived]
impl<__IngraphDb> #stored_as<__IngraphDb> for #subject
where
#inner: #seam,
#stored: #stored_as<__IngraphDb>,
{
const WORDS: &'static [&'static ::core::primitive::str] =
<#stored as #stored_as<__IngraphDb>>::WORDS;
}
#gate! {
#[automatically_derived]
impl<__IngraphDb> #carrier<__IngraphDb> for #subject
where
__IngraphDb: #database,
#inner: #seam,
#stored: #carrier<__IngraphDb>,
{
#[inline]
fn push_bind(&self, __ingraph_qb: &mut #query_builder<__IngraphDb>) {
<#stored as #carrier<__IngraphDb>>::push_bind(
&<#inner as #seam>::to_stored(&self.0),
__ingraph_qb,
);
}
}
#[automatically_derived]
impl<'__ingraph, __IngraphRow> #assemble<'__ingraph, __IngraphRow> for #subject
where
__IngraphRow: #row,
#inner: #row_seam,
#row_stored: #assemble<'__ingraph, __IngraphRow>,
{
fn assemble(
__ingraph_row: &'__ingraph __IngraphRow,
__ingraph_under: ::core::option::Option<&#path<'_>>,
) -> #result<Self> {
let __ingraph_stored = <#row_stored as #assemble<'__ingraph, __IngraphRow>>::assemble(
__ingraph_row,
__ingraph_under,
)?;
::core::result::Result::map(
::core::result::Result::map_err(
<#inner as #row_seam>::from_stored(__ingraph_stored),
|__ingraph_refused| {
#sqlx_error::Decode(::std::boxed::Box::new(__ingraph_refused))
},
),
Self,
)
}
}
}
}
}
fn wire(
&self,
) -> (
proc_macro2::TokenStream,
proc_macro2::TokenStream,
proc_macro2::TokenStream,
) {
let subject = &self.subject;
let inner = &self.inner;
let vis = &self.vis;
let reading = self.reading_name();
let filter_name = format!("{}Filter", self.sdl());
let ag = self.framework(&[], "async_graphql");
let gate = self.framework(&["gate"], "if_async_graphql");
let shelf = self.vendored("async_graphql");
let sdl = self.sdl();
let input = self.framework(&["graphql"], "ToGraphqlInput");
let output = self.framework(&["graphql"], "ToGraphqlOutput");
let scalar_wire = self.framework(&["graphql"], "ScalarWire");
let scalar_filter = self.framework(&["graphql"], "ScalarFilter");
let composite_filter_marker = self.framework(&["marker"], "CompositeFilterMarker");
let composite_marker = self.framework(&["marker"], "CompositeMarker");
let default_marker = self.framework(&["marker"], "DefaultMarker");
let clone = self.owes(quote!(::core::clone::Clone));
let display = self.owes(quote!(::core::fmt::Display));
let from_str = self.owes(quote!(::core::str::FromStr));
let doc = format!(
" How a [`{subject}`] crosses when the framework's own ordering filter holds it — the reading \
that gives `ScalarFilter<{subject}, {reading}>` a face.\n\n Uninhabited: it is a NAME the \
filter is parameterised by and never a value anything builds."
);
let declaration = quote! {
#[doc = #doc]
#vis enum #reading {}
};
let rows = quote! {
#[automatically_derived]
impl #input for #subject where #clone {
type Input = Self;
type Error = ::core::convert::Infallible;
#[inline]
fn cross(__ingraph_input: Self::Input) -> ::core::result::Result<Self, Self::Error> {
::core::result::Result::Ok(__ingraph_input)
}
#[inline]
fn carry(__ingraph_operand: &Self) -> Self::Input {
::core::clone::Clone::clone(__ingraph_operand)
}
}
#[automatically_derived]
impl #output for #subject {
type Output<'__ingraph>
= &'__ingraph Self
where
Self: '__ingraph;
#[inline]
fn to_graphql_output(__ingraph_value: &Self) -> &Self {
__ingraph_value
}
}
#[automatically_derived]
impl #scalar_wire<#subject> for #reading where #clone {
const NAME: &'static ::core::primitive::str = #filter_name;
type Carrier = #subject;
type Error = ::core::convert::Infallible;
#[inline]
fn cross(
__ingraph_carrier: Self::Carrier,
) -> ::core::result::Result<#subject, Self::Error> {
::core::result::Result::Ok(__ingraph_carrier)
}
#[inline]
fn carry(__ingraph_operand: &#subject) -> Self::Carrier {
::core::clone::Clone::clone(__ingraph_operand)
}
}
#[automatically_derived]
impl #composite_filter_marker for #subject {
type Filter = #scalar_filter<#subject, #reading>;
type ColumnFilter = #scalar_filter<#subject, #reading>;
}
#[automatically_derived]
impl #default_marker for #subject {
type Marker = #composite_marker<#subject>;
}
};
let scalar = quote! {
#gate! {
#[#ag::Scalar(crate = #shelf, name = #sdl)]
impl #ag::ScalarType for #subject
where
#display,
#from_str,
<#inner as ::core::str::FromStr>::Err: ::core::fmt::Display,
{
fn parse(__ingraph_value: #ag::Value) -> #ag::InputValueResult<Self> {
match &__ingraph_value {
#ag::Value::String(__ingraph_text) => ::core::result::Result::map_err(
<Self as ::core::str::FromStr>::from_str(__ingraph_text),
#ag::InputValueError::custom,
),
_ => ::core::result::Result::Err(#ag::InputValueError::expected_type(
::core::clone::Clone::clone(&__ingraph_value),
)),
}
}
fn is_valid(__ingraph_value: &#ag::Value) -> ::core::primitive::bool {
match __ingraph_value {
#ag::Value::String(__ingraph_text) => ::core::result::Result::is_ok(
&<Self as ::core::str::FromStr>::from_str(__ingraph_text),
),
_ => false,
}
}
fn to_value(&self) -> #ag::Value {
#ag::Value::String(::std::string::ToString::to_string(self))
}
}
}
};
(declaration, rows, scalar)
}
fn inherent(&self) -> proc_macro2::TokenStream {
let subject = &self.subject;
let inner = &self.inner;
let vis = &self.vis;
let new = format!(
" The [`{subject}`] `inner` names.\n\n `const`, and it validates nothing: this door carries no \
constructor invariant — see `#[derive(ingraph::Id)]`."
);
let into_inner = format!(" The value this [`{subject}`] IS, taken.");
let as_inner = format!(" The value this [`{subject}`] IS, borrowed.");
let from_ref = format!(
" View `inner` as a [`{subject}`], borrowing rather than moving.\n\n Free under \
`#[repr(transparent)]` — the two have one layout. Legal because this door carries no \
constructor invariant to walk around."
);
let from_slice = format!(
" View a slice of held values as a slice of [`{subject}`]s.\n\n The reference cast one length \
further out: the elements have identical layout, so the slice does."
);
let as_inner_slice = format!(
" View a slice of [`{subject}`]s as a slice of the values they are.\n\n An associated function \
rather than a method, because the receiver is the SLICE and not one wrapper."
);
quote! {
impl #subject {
#[doc = #new]
#[inline]
#[must_use]
#vis const fn new(__ingraph_inner: #inner) -> Self {
Self(__ingraph_inner)
}
#[doc = #into_inner]
#[inline]
#[must_use]
#vis fn into_inner(self) -> #inner {
self.0
}
#[doc = #as_inner]
#[inline]
#[must_use]
#vis const fn as_inner(&self) -> &#inner {
&self.0
}
#[doc = #from_ref]
#[inline]
#[must_use]
#vis const fn from_ref(__ingraph_inner: &#inner) -> &Self {
unsafe { ::core::mem::transmute::<&#inner, &Self>(__ingraph_inner) }
}
#[doc = #from_slice]
#[inline]
#[must_use]
#vis const fn from_slice(__ingraph_inner: &[#inner]) -> &[Self] {
unsafe { ::core::mem::transmute::<&[#inner], &[Self]>(__ingraph_inner) }
}
#[doc = #as_inner_slice]
#[inline]
#[must_use]
#vis const fn as_inner_slice(__ingraph_this: &[Self]) -> &[#inner] {
unsafe { ::core::mem::transmute::<&[Self], &[#inner]>(__ingraph_this) }
}
}
}
}
#[must_use]
pub fn emit(&self) -> proc_macro2::TokenStream {
let (reading, wire, scalar) = self.wire();
let inherent = self.inherent();
let key = self.key_delegation();
let identity = self.identity();
let text = self.text();
let storage = self.storage();
quote! {
#reading
#inherent
const _: () = {
#key
#identity
#text
#storage
#wire
};
#scalar
}
}
}