use heck::ToSnakeCase as _;
use quote::{format_ident, quote};
use syn::ext::IdentExt as _;
use crate::model::GraphqlKind;
#[cfg(test)]
mod tests;
mod wire;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Face {
Predicate,
Unwrap,
UnwrapRef,
UnwrapMut,
TryUnwrap,
TryUnwrapRef,
TryUnwrapMut,
}
impl Face {
pub const ALL: [Self; 7] = [
Self::Predicate,
Self::Unwrap,
Self::UnwrapRef,
Self::UnwrapMut,
Self::TryUnwrap,
Self::TryUnwrapRef,
Self::TryUnwrapMut,
];
#[must_use]
pub fn name(self, word: &syn::Ident) -> syn::Ident {
match self {
Self::Predicate => format_ident!("is_{word}"),
Self::Unwrap => format_ident!("unwrap_{word}"),
Self::UnwrapRef => format_ident!("unwrap_{word}_ref"),
Self::UnwrapMut => format_ident!("unwrap_{word}_mut"),
Self::TryUnwrap => format_ident!("try_unwrap_{word}"),
Self::TryUnwrapRef => format_ident!("try_unwrap_{word}_ref"),
Self::TryUnwrapMut => format_ident!("try_unwrap_{word}_mut"),
}
}
}
#[must_use]
pub fn word(ident: &syn::Ident) -> syn::Ident {
use syn::ext::IdentExt as _;
format_ident!("{}", ident.unraw().to_string().to_snake_case())
}
#[must_use]
pub fn default_unwrap_error_name(base: &syn::Ident) -> syn::Ident {
format_ident!("{base}UnwrapError")
}
#[must_use]
pub fn default_input_sdl_name(base: &syn::Ident) -> String {
input_sdl_name(&base.unraw().to_string())
}
#[must_use]
pub fn input_sdl_name(base: &str) -> String {
format!("{base}Input")
}
#[must_use]
pub fn seat(ident: &syn::Ident) -> String {
use heck::ToLowerCamelCase as _;
ident.unraw().to_string().to_lower_camel_case()
}
#[derive(Debug, Clone)]
pub struct UnionMember {
pub ident: syn::Ident,
pub ty: syn::Type,
}
impl UnionMember {
#[must_use]
pub fn name(&self) -> String {
use syn::ext::IdentExt as _;
self.ident.unraw().to_string()
}
#[must_use]
pub fn word(&self) -> syn::Ident {
word(&self.ident)
}
}
#[derive(Debug, Clone, Default)]
pub struct UnionInput {
pub rename: Option<syn::LitStr>,
}
#[derive(Debug, Clone, Default)]
pub struct UnionOutput {
pub rename: Option<syn::LitStr>,
}
#[derive(Debug, Clone)]
pub struct UnionSkin {
pub kind: GraphqlKind,
pub output: Option<UnionOutput>,
pub input: Option<UnionInput>,
}
impl UnionSkin {
#[must_use]
pub fn output_sdl(&self, base: &syn::Ident) -> String {
match self
.output
.as_ref()
.and_then(|output| output.rename.as_ref())
{
Some(declared) => declared.value(),
None => base.unraw().to_string(),
}
}
#[must_use]
pub fn input_sdl(&self, base: &syn::Ident) -> String {
match self.input.as_ref().and_then(|input| input.rename.as_ref()) {
Some(declared) => declared.value(),
None if self.output.is_some() => input_sdl_name(&self.output_sdl(base)),
None => base.unraw().to_string(),
}
}
}
#[derive(Debug, Clone)]
pub struct UnionModel {
pub krate: syn::Path,
pub vis: syn::Visibility,
pub name: syn::Ident,
pub members: Vec<UnionMember>,
pub error: Option<syn::Ident>,
pub graphql: Vec<UnionSkin>,
}
impl UnionModel {
#[must_use]
pub fn error(&self) -> syn::Ident {
self
.error
.clone()
.unwrap_or_else(|| default_unwrap_error_name(&self.name))
}
#[must_use]
pub fn emit(&self) -> proc_macro2::TokenStream {
let equipped = self.equipped().emit();
let wire = self.graphql_faces();
quote! {
#equipped
#wire
}
}
fn equipped(&self) -> Equipped<'_> {
Equipped {
vis: &self.vis,
name: &self.name,
members: &self.members,
error: self.error(),
}
}
}
pub(crate) struct Equipped<'a> {
pub(crate) vis: &'a syn::Visibility,
pub(crate) name: &'a syn::Ident,
pub(crate) members: &'a [UnionMember],
pub(crate) error: syn::Ident,
}
impl Equipped<'_> {
pub(crate) fn emit(&self) -> proc_macro2::TokenStream {
let error = self.refusal();
let held = self.held();
let face = self.face();
quote! {
#error
const _: () = {
#held
#face
};
}
}
fn refusal(&self) -> proc_macro2::TokenStream {
let vis = self.vis;
let name = self.name;
let error = &self.error;
let sentence = format!("`{name}`: asked for `{{}}`, held `{{}}`");
let doc = format!(
"The refusal an unwrap into a variant a [`{name}`] is not holding answers with.\n\nSealed \
rather than empty: its fields are private, so nothing outside this module builds one, and it \
carries the pair that says what went wrong — the variant asked for and the variant held."
);
let asked = format!("The variant the call asked [`{name}`] for.");
let held = format!("The variant that [`{name}`] was holding instead.");
quote! {
#[doc = #doc]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#vis struct #error {
asked: &'static ::core::primitive::str,
held: &'static ::core::primitive::str,
}
#[automatically_derived]
impl #error {
#[doc = #asked]
#[inline]
#[must_use]
#vis const fn asked(&self) -> &'static ::core::primitive::str {
self.asked
}
#[doc = #held]
#[inline]
#[must_use]
#vis const fn held(&self) -> &'static ::core::primitive::str {
self.held
}
}
#[automatically_derived]
impl ::core::fmt::Display for #error {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
::core::write!(f, #sentence, self.asked, self.held)
}
}
#[automatically_derived]
impl ::core::error::Error for #error {}
}
}
fn has_a_wrong_variant(&self) -> bool {
self.members.len() > 1
}
fn held(&self) -> proc_macro2::TokenStream {
if !self.has_a_wrong_variant() {
return quote!();
}
let name = self.name;
let held = self.held_fn();
let arms = self.members.iter().map(|member| {
let ident = &member.ident;
let word = member.name();
quote!(#name::#ident(_) => #word,)
});
quote! {
fn #held(value: &#name) -> &'static ::core::primitive::str {
match value { #(#arms)* }
}
}
}
fn held_fn(&self) -> syn::Ident {
format_ident!("__ingraph_held")
}
fn face(&self) -> proc_macro2::TokenStream {
let name = self.name;
let members = self.members.iter().map(|member| self.member(member));
quote! {
#[automatically_derived]
impl #name {
#(#members)*
}
}
}
fn member(&self, member: &UnionMember) -> proc_macro2::TokenStream {
let vis = self.vis;
let name = self.name;
let error = &self.error;
let held = self.held_fn();
let ident = &member.ident;
let ty = &member.ty;
let word = member.word();
let asked = member.name();
let predicate = Face::Predicate.name(&word);
let unwrap = Face::Unwrap.name(&word);
let unwrap_ref = Face::UnwrapRef.name(&word);
let unwrap_mut = Face::UnwrapMut.name(&word);
let try_unwrap = Face::TryUnwrap.name(&word);
let try_unwrap_ref = Face::TryUnwrapRef.name(&word);
let try_unwrap_mut = Face::TryUnwrapMut.name(&word);
let is_doc = format!("Whether this is [`{name}::{ident}`].");
let owned_doc = format!("The member [`{name}::{ident}`] carries.");
let borrow_doc = format!("A borrow of the member [`{name}::{ident}`] carries.");
let exclusive_doc = format!("An exclusive borrow of the member [`{name}::{ident}`] carries.");
let panics = format!(
"# Panics\nWhen another variant is held. The message names the variant asked for and the one \
held, which is [`{error}`]'s own sentence."
);
let refuses = format!(
"# Errors\n[`{error}`] when another variant is held, naming both. The value this was called \
on is DROPPED: one refusal serves all three receivers, and a receiver that only borrows has \
nothing owned to hand back."
);
let borrowed_refuses =
format!("# Errors\n[`{error}`] when another variant is held, naming both.");
let (owned_held, borrowed_held, refused) = if self.has_a_wrong_variant() {
(
quote!(let held = #held(&self);),
quote!(let held = #held(self);),
quote!(_ => ::core::result::Result::Err(#error { asked: #asked, held }),),
)
} else {
(quote!(), quote!(), quote!())
};
quote! {
#[doc = #is_doc]
#[inline]
#[must_use]
#vis const fn #predicate(&self) -> ::core::primitive::bool {
::core::matches!(self, Self::#ident(_))
}
#[doc = #owned_doc]
#[doc = ""]
#[doc = #panics]
#[inline]
#[must_use]
#vis fn #unwrap(self) -> #ty {
match self.#try_unwrap() {
::core::result::Result::Ok(member) => member,
::core::result::Result::Err(refused) => ::core::panic!("{}", refused),
}
}
#[doc = #borrow_doc]
#[doc = ""]
#[doc = #panics]
#[inline]
#[must_use]
#vis fn #unwrap_ref(&self) -> &#ty {
match self.#try_unwrap_ref() {
::core::result::Result::Ok(member) => member,
::core::result::Result::Err(refused) => ::core::panic!("{}", refused),
}
}
#[doc = #exclusive_doc]
#[doc = ""]
#[doc = #panics]
#[inline]
#[must_use]
#vis fn #unwrap_mut(&mut self) -> &mut #ty {
match self.#try_unwrap_mut() {
::core::result::Result::Ok(member) => member,
::core::result::Result::Err(refused) => ::core::panic!("{}", refused),
}
}
#[doc = #owned_doc]
#[doc = ""]
#[doc = #refuses]
#[inline]
#vis fn #try_unwrap(self) -> ::core::result::Result<#ty, #error> {
#owned_held
match self {
Self::#ident(member) => ::core::result::Result::Ok(member),
#refused
}
}
#[doc = #borrow_doc]
#[doc = ""]
#[doc = #borrowed_refuses]
#[inline]
#vis fn #try_unwrap_ref(&self) -> ::core::result::Result<&#ty, #error> {
#borrowed_held
match self {
Self::#ident(member) => ::core::result::Result::Ok(member),
#refused
}
}
#[doc = #exclusive_doc]
#[doc = ""]
#[doc = #borrowed_refuses]
#[inline]
#vis fn #try_unwrap_mut(&mut self) -> ::core::result::Result<&mut #ty, #error> {
#borrowed_held
match self {
Self::#ident(member) => ::core::result::Result::Ok(member),
#refused
}
}
}
}
}