use proc_macro2::TokenStream;
use quote::{ToTokens as _, format_ident, quote, quote_spanned};
use syn::spanned::Spanned as _;
use super::{DeclaredError, ExchangeModel, MutationModel};
#[cfg(test)]
mod tests;
impl MutationModel {
#[must_use]
pub fn response_name(&self) -> syn::Ident {
format_ident!("{}Response", self.name)
}
#[must_use]
pub fn error_name(&self) -> syn::Ident {
format_ident!("{}Error", self.name)
}
#[must_use]
pub fn face_name(&self) -> syn::Ident {
format_ident!("handle_{}", crate::emit::snake(&self.name.to_string()))
}
#[must_use]
pub fn awaited(&self) -> bool {
!self.all_sync()
}
pub(super) fn assembly(&self) -> TokenStream {
let response = self.response();
let error = self.error();
let rendering = self.rendering();
let calls = self.calls();
let assembled = self.assembled();
quote! {
#response
#error
#rendering
#calls
#assembled
}
}
fn response(&self) -> TokenStream {
let krate = &self.krate;
let vis = &self.vis;
let name = self.response_name();
let arms = self.exchanges.iter().map(|exchange| {
let variant = exchange.variant();
let ty = &exchange.ty;
let doc = crate::emit::leading(&format!(
"What the `{field}` exchange answered.",
field = exchange.named(),
));
quote! {
#[doc = #doc]
#variant(<#ty as #krate::__private::source::Mutation>::Response)
}
});
let doc = crate::emit::leading(&format!(
"What [`{node}`]'s assembled face answers with — one arm per exchange it declared.\n\nThe \
node-level response sum, revived: the WIRE answers per field and never through this type, \
and what it serves is every other caller of \
[`{node}::{face}`]({node}::{face}).",
node = self.name,
face = self.face_name(),
));
let debugged = self.exchanges.iter().map(|exchange| {
let variant = exchange.variant();
let printed = variant.to_string();
quote!(Self::#variant(_) => ::core::fmt::Formatter::write_str(__ingraph_f, #printed))
});
let debug = if self.exchanges.is_empty() {
quote!(match *self {})
} else {
quote!(match self { #(#debugged,)* })
};
quote! {
#[doc = #doc]
#vis enum #name {
#(#arms),*
}
impl ::core::fmt::Debug for #name {
fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
#debug
}
}
}
}
fn error(&self) -> TokenStream {
let vis = &self.vis;
let name = self.error_name();
let arms = self.fallible().map(|exchange| {
let variant = exchange.variant();
let doc = crate::emit::leading(&format!(
"The `{field}` exchange refused.",
field = exchange.named(),
));
let payload = match &exchange.handler.error {
Some(DeclaredError::Rich { ty, .. }) => quote!((#ty)),
_ => TokenStream::new(),
};
quote! {
#[doc = #doc]
#variant #payload
}
});
let doc = crate::emit::leading(&format!(
"How [`{node}`]'s assembled face refuses — one arm per exchange that declared a failure.\n\nA \
node whose every exchange is the `Never` tier gets an enum with NO variants, which is the \
honest answer rather than an omission: there is no way for such a node to fail, so there is \
no value of this type.",
node = self.name,
));
quote! {
#[doc = #doc]
#vis enum #name {
#(#arms),*
}
}
}
fn rendering(&self) -> TokenStream {
let name = self.error_name();
let empty = self.fallible().next().is_none();
let (display, debug, code) = if empty {
(
quote!(match *self {}),
quote!(match *self {}),
quote!(match *self {}),
)
} else {
let displayed = self.fallible().map(|exchange| exchange.displayed());
let debugged = self.fallible().map(|exchange| {
let variant = exchange.variant();
let printed = variant.to_string();
let bound = exchange.binds_a_payload().then(|| quote!((_)));
quote!(Self::#variant #bound => ::core::fmt::Formatter::write_str(__ingraph_f, #printed))
});
let coded = self.fallible().map(|exchange| {
let variant = exchange.variant();
let bound = exchange.binds_a_payload().then(|| quote!((_)));
let word = match exchange.declared_code() {
Some(code) => quote!(::core::option::Option::Some(#code)),
None => quote!(::core::option::Option::None),
};
quote!(Self::#variant #bound => #word)
});
(
quote!(match self { #(#displayed,)* }),
quote!(match self { #(#debugged,)* }),
quote!(match self { #(#coded,)* }),
)
};
let doc = crate::emit::leading(
"The heading this failure renders under, where its declaration wrote a `code` word.\n\nThe \
same fact `Fallibility::code` carries in the declaration record, reachable from the value \
itself — which is what a caller mapping this sum onto a transport's own vocabulary needs.",
);
quote! {
impl ::core::fmt::Display for #name {
fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
#display
}
}
impl ::core::fmt::Debug for #name {
fn fmt(&self, __ingraph_f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
#debug
}
}
impl ::core::error::Error for #name {}
impl #name {
#[doc = #doc]
#[must_use]
pub const fn code(&self) -> ::core::option::Option<&'static str> {
#code
}
}
}
}
fn calls(&self) -> TokenStream {
let name = &self.name;
let calls = self.exchanges.iter().map(|exchange| exchange.call(self));
quote! {
impl #name {
#(#calls)*
}
}
}
fn assembled(&self) -> TokenStream {
let vis = &self.vis;
let name = &self.name;
let face = self.face_name();
let command = self.command_name();
let response = self.response_name();
let error = self.error_name();
let granted = self.granted();
let parameters = granted
.iter()
.map(|(held, resource)| quote!(#held: &#resource));
let awaited = self.awaited().then(|| quote!(async));
let arms = self
.exchanges
.iter()
.map(|exchange| exchange.arm(self, &granted));
let body = if self.exchanges.is_empty() {
quote!(match __ingraph_cmd {})
} else {
quote!(match __ingraph_cmd { #(#arms)* })
};
let doc = crate::emit::leading(&format!(
"Run whatever this node was told — [`{node}`]'s TOTAL CAPABILITY, in one \
{face_kind}function.\n\nOne arm per declared exchange, each calling that exchange's own \
handler at the signature its `error(…)` word chose. The face is {face_kind}because \
`ALL_SYNC` is `{all_sync}` — the OR law: a node whose every handler is blocking assembles \
into a blocking function, and one awaited handler makes the whole face awaited.\n\nThe WIRE \
does not come through here. A schema publishes one root field per exchange and calls that \
exchange's handler directly; what this serves is every other caller — a first-party \
transport, a test, and the source-side party holding a command off its own `Control` \
line.\n\n# Errors\n\nWhichever of [`{error}`]({error})'s arms the exchange that ran declared.",
node = self.name,
face_kind = if self.awaited() {
"awaited "
} else {
"blocking "
},
all_sync = self.all_sync(),
));
quote! {
impl #name {
#[doc = #doc]
#vis #awaited fn #face(
#(#parameters,)*
__ingraph_cmd: #command,
) -> ::core::result::Result<#response, #error> {
#body
}
}
}
}
fn fallible(&self) -> impl Iterator<Item = &ExchangeModel> {
self
.exchanges
.iter()
.filter(|exchange| exchange.handler.error.is_some())
}
fn granted(&self) -> Vec<(syn::Ident, syn::Path)> {
let mut taken: Vec<String> = vec!["cmd".to_owned()];
let mut granted: Vec<(syn::Ident, syn::Path)> = Vec::new();
for resource in self
.exchanges
.iter()
.flat_map(|exchange| &exchange.handler.context)
{
if granted
.iter()
.any(|(_, held)| super::path_word(held) == super::path_word(resource))
{
continue;
}
let bare = resource.segments.last().map_or_else(
|| "granted".to_owned(),
|segment| crate::emit::snake(&segment.ident.to_string()),
);
let mut held = bare.clone();
let mut at = 1;
while taken.contains(&held) {
held = format!("{bare}_{at}");
at += 1;
}
taken.push(held.clone());
granted.push((format_ident!("{held}"), resource.clone()));
}
granted
}
}
impl ExchangeModel {
#[must_use]
pub fn call_name(&self) -> syn::Ident {
format_ident!("__ingraph_exchange_{}", self.named())
}
fn binds_a_payload(&self) -> bool {
matches!(&self.handler.error, Some(DeclaredError::Rich { .. }))
}
fn declared_code(&self) -> Option<&syn::LitStr> {
match &self.handler.error {
Some(DeclaredError::Rich { code, .. } | DeclaredError::Canned { code, .. }) => code.as_ref(),
None => None,
}
}
fn displayed(&self) -> TokenStream {
let variant = self.variant();
let head = self.declared_code().map(|code| {
let head = format!("{code}: ", code = code.value());
quote!(::core::fmt::Formatter::write_str(__ingraph_f, #head)?;)
});
match &self.handler.error {
Some(DeclaredError::Rich { .. }) => quote! {
Self::#variant(__ingraph_refusal) => {
#head
::core::fmt::Display::fmt(__ingraph_refusal, __ingraph_f)
}
},
Some(DeclaredError::Canned { message, code }) => {
let sentence = match code {
Some(code) => format!(
"{code}: {message}",
code = code.value(),
message = message.value()
),
None => message.value(),
};
quote!(Self::#variant => ::core::fmt::Formatter::write_str(__ingraph_f, #sentence))
}
None => TokenStream::new(),
}
}
fn call(&self, model: &MutationModel) -> TokenStream {
let krate = &model.krate;
let mutation = crate::emit::framework(krate, &["source"], "Mutation");
let ty = &self.ty;
let name = self.call_name();
let path = &self.handler.path;
let granted: Vec<syn::Ident> = (0..self.handler.context.len())
.map(|at| format_ident!("__ingraph_granted_{at}"))
.collect();
let parameters = granted
.iter()
.zip(&self.handler.context)
.map(|(held, resource)| quote!(#held: &#resource));
let awaited = self.handler.awaited.then(|| quote!(.await));
let face = self.handler.awaited.then(|| quote!(async));
let call = quote_spanned! {path.span()=>
#path(#(#granted,)* __ingraph_request) #awaited
};
let tier = match &self.handler.error {
None => quote!(<#ty as #mutation>::Response),
Some(DeclaredError::Rich { ty: failure, .. }) => {
let failure = failure.to_token_stream();
quote!(::core::result::Result<<#ty as #mutation>::Response, #failure>)
}
Some(DeclaredError::Canned { .. }) => {
quote!(::core::result::Result<<#ty as #mutation>::Response, ()>)
}
};
let doc = crate::emit::leading(&format!(
"The `{field}` exchange's handler, called at the signature its declaration chose.\n\nHidden, \
and there is exactly ONE of it: the wire's resolver and the assembled face both spend this \
call, so a body that wears another signature is refused once, at the `handler` word.",
field = self.named(),
));
quote! {
#[doc = #doc]
#[doc(hidden)]
#face fn #name(
#(#parameters,)*
__ingraph_request: <#ty as #mutation>::Request,
) -> #tier {
let __ingraph_outcome: #tier = #call;
__ingraph_outcome
}
}
}
fn arm(&self, model: &MutationModel, granted: &[(syn::Ident, syn::Path)]) -> TokenStream {
let command = model.command_name();
let response = model.response_name();
let error = model.error_name();
let variant = self.variant();
let call = self.call_name();
let arguments = self.handler.context.iter().map(|resource| {
granted
.iter()
.find(|(_, held)| super::path_word(held) == super::path_word(resource))
.map_or_else(|| quote!(#resource), |(held, _)| quote!(#held))
});
let awaited = self.handler.awaited.then(|| quote!(.await));
let ran = quote!(Self::#call(#(#arguments,)* __ingraph_request) #awaited);
match &self.handler.error {
None => quote! {
#command::#variant(__ingraph_request) => ::core::result::Result::Ok(
#response::#variant(#ran)
),
},
Some(DeclaredError::Rich { .. }) => quote! {
#command::#variant(__ingraph_request) => match #ran {
::core::result::Result::Ok(__ingraph_answer) =>
::core::result::Result::Ok(#response::#variant(__ingraph_answer)),
::core::result::Result::Err(__ingraph_refusal) =>
::core::result::Result::Err(#error::#variant(__ingraph_refusal)),
},
},
Some(DeclaredError::Canned { .. }) => quote! {
#command::#variant(__ingraph_request) => match #ran {
::core::result::Result::Ok(__ingraph_answer) =>
::core::result::Result::Ok(#response::#variant(__ingraph_answer)),
::core::result::Result::Err(()) =>
::core::result::Result::Err(#error::#variant),
},
},
}
}
}