#[cfg(test)]
mod tests;
use quote::{format_ident, quote, quote_spanned};
use crate::{
emit::leading,
model::{
Product, RecordModel, Upstream, default_downstream_name, default_in_name,
default_out_kind_name, default_out_name,
},
};
pub const PAIRED: &str = "Paired";
impl RecordModel {
pub(super) fn topology(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
let fan_in = self.fan_in();
let (product_types, product_impls) = self.product_faces();
let emits = self.emits_binding();
let audit = self.one_product_audit();
let notified = self.notify_audit();
(
quote! {
#fan_in
#product_types
},
quote! {
#product_impls
#emits
#audit
#notified
},
)
}
fn fan_in(&self) -> Option<proc_macro2::TokenStream> {
let subscriptions = self.subscriptions.as_ref().filter(|fan| fan.is_sum())?;
let (record, vis) = (&self.record, &self.vis);
let name = default_in_name(record);
let paired = format_ident!("{PAIRED}");
let doc = leading(&format!(
"What arrives at a [`{record}`]: one variant per flow it draws from."
));
let pairing_note = leading(
"The `Paired` variant is the KEYED GROUP: its members are joined by key and delivered \
COMPLETE, while every other variant arrives on its own the moment it does. The join that \
fills it is the driver's and is NOT BUILT — a declaration that writes `key` names its group \
here and waits for the intake that assembles one.",
);
let mut variants = Vec::new();
let mut group_written = false;
for upstream in &subscriptions.upstreams {
if upstream.keyed {
if group_written {
continue;
}
group_written = true;
let payloads = subscriptions
.keyed()
.map(|keyed| self.upstream_message(keyed));
let names = subscriptions
.keyed()
.map(|keyed| keyed.variant.to_string())
.collect::<Vec<_>>()
.join("`, `");
let doc = leading(&format!(
"One message from EACH of `{names}`, joined by key — complete, and delivered together. \
A group missing a member waits, with no deadline: the upstream's lag sweep is what \
re-pulls a flow that stopped."
));
variants.push(quote! {
#[doc = #doc]
#paired(#(#payloads),*),
});
continue;
}
let (variant, node) = (&upstream.variant, &upstream.node);
let payload = self.upstream_message(upstream);
let doc = leading(&format!(
"One message from `{}`, arriving on its own.",
path_text(node)
));
variants.push(quote! {
#[doc = #doc]
#variant(#payload),
});
}
Some(quote! {
#[doc = #doc]
#[doc = ""]
#[doc = #pairing_note]
#vis enum #name {
#(#variants)*
}
})
}
fn upstream_message(&self, upstream: &Upstream) -> proc_macro2::TokenStream {
let product = self.upstream_product(upstream);
if !upstream.notify {
return product;
}
let transformer = self.framework(&["transform"], "Transformer");
quote!(<#product as #transformer>::Key)
}
fn upstream_product(&self, upstream: &Upstream) -> proc_macro2::TokenStream {
let emits = self.framework(&["operator"], "Emits");
let node = &upstream.node;
let Some(out) = &upstream.out else {
return quote!(<#node as #emits>::Out);
};
let vocabulary = out_kind_path(node);
quote!(<#node as #emits<{ #vocabulary::#out as usize }>>::Out)
}
fn notify_audit(&self) -> Option<proc_macro2::TokenStream> {
let subscriptions = self.subscriptions.as_ref()?;
let notified: Vec<&Upstream> = subscriptions
.upstreams
.iter()
.filter(|upstream| upstream.notify)
.collect();
if notified.is_empty() {
return None;
}
let transformer = self.framework(&["transform"], "Transformer");
let audits = notified.iter().map(|upstream| {
let product = self.upstream_product(upstream);
let at = syn::spanned::Spanned::span(&upstream.node);
quote_spanned! {at=>
const _: fn() = __ig_is_notifiable::<#product>;
}
});
Some(quote! {
const _: () = {
fn __ig_is_notifiable<__INGRAPH_LANDED__: #transformer>() {}
#(#audits)*
};
})
}
fn product_faces(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
let Some(products) = self.products.as_ref().filter(|products| products.is_sum()) else {
return Default::default();
};
let products = &products.products;
let (record, vis) = (&self.record, &self.vis);
let (out, kind, downstream) = (
default_out_name(record),
default_out_kind_name(record),
default_downstream_name(record),
);
let out_doc = leading(&format!("What a [`{record}`] puts on an edge."));
let streamed = self.streaming.is_some();
let clone_note = leading(if streamed {
"It does NOT derive `Clone`, and that is this declaration's `stream` word cashed. A streaming \
node publishes through its own downstream set below, which asks `Sink::duplicate` PER \
PRODUCT — so a product with one subscriber is asked for no copy at all, and a derived `Clone` \
on the SUM would charge every product for whatever its neighbours happen to need. It would \
charge it at the `emits` word too: a product holding a decoded buffer or an open handle would \
fail to compile before any mount was written.\n\nEach product may have as MANY subscribers \
as it likes — the fan serves each one past the first a copy from that product's own door. A \
product whose payload has none to give serves one, and the launch refuses the second by name \
(`ProductSeatError::Occupied`), naming the payload as the fix."
} else {
"`Clone` because a fan-out is one message at several consumers: the driver moves the value \
into the last edge and clones it for the others, which is the bound the resident carries on \
every node's `Out`.\n\nIt is charged because it is SPENT — this declaration wrote no \
`stream`, so its mount publishes through `Downstream<Out>`, whose N edges of one product are \
the fan-out itself and whose own `Sink` impl takes the copy. A derived `Clone` calls each \
payload's own, so a product that holds a decoded buffer or an open handle and does not copy \
fails to compile at the `emits` word — which is where the cost is decided. The `stream` word \
is what takes the bound off: there the node's own set below asks for a copy per product \
rather than of the sum."
});
let clone = (!streamed).then(|| quote!(#[derive(::core::clone::Clone)]));
let out_variants = products.iter().map(|product| {
let (variant, ty) = (&product.variant, &product.ty);
let doc = leading(&format!("The `{variant}` product."));
quote! {
#[doc = #doc]
#variant(#ty),
}
});
let kind_doc = leading(&format!(
"WHICH product a [`{record}`] message is — the identity a body asks the connection state \
about."
));
let kind_variants = products.iter().map(|product| {
let variant = &product.variant;
quote!(#variant,)
});
let downstream_doc = leading(&format!(
"Where a [`{record}`]'s products go: one out-edge list per product, and a list's own \
emptiness is the connection state.\n\nA product may have SEVERAL subscribers — the ordinary \
topology, and what an A/B split, a canary rollout or a thumbnailer beside an embedder is — so \
each product holds a list rather than a seat. The fan is the lane's own: it moves the output \
into the LAST edge that carries it and asks `Sink::duplicate` for the ones before, which \
answers PER PRODUCT here. A product whose payload does not copy therefore serves exactly one \
subscriber, and a second is refused BY NAME at the launch rather than by dropping."
));
let fields = products.iter().map(|product| {
let (slot, ty) = (slot_name(product), &product.ty);
let outbox = self.framework(&["drive"], "Outbox");
let item = self.framework(&["drive"], "ItemId");
let doc = leading(&format!(
"Every consumer of `{}`, in the order the wiring seated them.",
product.variant
));
quote! {
#[doc = #doc]
#slot: ::std::vec::Vec<#outbox<#item, #ty>>,
}
});
let types = quote! {
#[doc = #out_doc]
#[doc = ""]
#[doc = #clone_note]
#clone
#vis enum #out {
#(#out_variants)*
}
#[doc = #kind_doc]
#[derive(
::core::fmt::Debug,
::core::clone::Clone,
::core::marker::Copy,
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::hash::Hash
)]
#vis enum #kind {
#(#kind_variants)*
}
#[doc = #downstream_doc]
#vis struct #downstream {
#(#fields)*
}
};
(types, self.downstream(&out, &kind, &downstream))
}
fn downstream(
&self,
out: &syn::Ident,
kind: &syn::Ident,
downstream: &syn::Ident,
) -> proc_macro2::TokenStream {
let products = self
.products
.as_ref()
.map(|products| products.products.as_slice())
.unwrap_or_default();
let (record, vis) = (&self.record, &self.vis);
let arity = products.len();
let sink = self.framework(&["drive"], "Sink");
let attaches = self.framework(&["drive"], "Attaches");
let attached = self.framework(&["drive"], "Attached");
let socket = self.framework(&["drive"], "Socket");
let wanted = self.framework(&["drive"], "Wanted");
let rings = self.framework(&["drive"], "Rings");
let outbox = self.framework(&["drive"], "Outbox");
let item_id = self.framework(&["drive"], "ItemId");
let item = self.framework(&["drive"], "Item");
let delivery = self.framework(&["drive"], "Delivery");
let payload = self.framework(&["drive"], "Payload");
let ack = self.framework(&["drive"], "AckSender");
let products_trait = self.framework(&["operator"], "Products");
let kind_trait = self.framework(&["operator"], "ProductKind");
let empty = products.iter().map(|product| {
let slot = slot_name(product);
quote!(#slot: ::std::vec::Vec::new(),)
});
let attachments = products.iter().map(|product| {
let (slot, ty, variant) = (slot_name(product), &product.ty, &product.variant);
let door = format_ident!("attach_{}", slot);
let doc = leading(&format!(
"Carry `{variant}` to `outbox` too — ONE MORE consumer of that product, and the list \
ceasing to be empty is what makes the product wanted.\n\nSeveral is the ordinary case. \
What the extra subscribers cost is a COPY apiece, taken through `Sink::duplicate` at the \
product's own door — so a product whose payload does not implement `Clone` serves one \
subscriber and the launch refuses the second by name."
));
quote! {
#[doc = #doc]
#[inline]
#vis fn #door(&mut self, outbox: #outbox<#item_id, #ty>) -> &mut Self {
self.#slot.push(outbox);
self
}
}
});
let lengths = products.iter().map(|product| {
let slot = slot_name(product);
quote!(self.#slot.len(),)
});
let widths = products.iter().map(|product| {
let slot = slot_name(product);
quote!(self.#slot.len())
});
let connected = products.iter().enumerate().map(|(index, product)| {
let slot = slot_name(product);
quote! {
if !self.#slot.is_empty() {
mask = mask.with(#index);
}
}
});
let carried = products.iter().enumerate().map(|(index, product)| {
let variant = &product.variant;
quote!((#index, #out::#variant(_)) => true,)
});
let ringers = products.iter().map(|product| {
let slot = slot_name(product);
quote! {
for edge in &self.#slot {
ringers.push(::std::boxed::Box::new(edge.nudge()) as ::std::boxed::Box<dyn #rings>);
}
}
});
let deliveries = products.iter().enumerate().map(|(index, product)| {
let (slot, ty, variant) = (slot_name(product), &product.ty, &product.variant);
quote! {
#index => {
let ::core::option::Option::Some(edge) = self.#slot.get(__ingraph_seat) else {
return false;
};
let mut taken: ::std::vec::Vec<#item<#ty>> =
::std::vec::Vec::with_capacity(batch.len());
for message in batch {
let (id, value) = message.into_parts();
match value {
#out::#variant(product) => taken.push(#item::new(id, product)),
_ => return false,
}
}
edge
.deliver_async(#delivery::new(#payload::Batch(taken), ack))
.await
.is_ok()
}
}
});
let indices = products.iter().enumerate().map(|(index, product)| {
let variant = &product.variant;
quote!(Self::#variant => #index,)
});
let doors = products.iter().map(|product| {
let (slot, ty, variant) = (slot_name(product), &product.ty, &product.variant);
let door = format_ident!("__ingraph_copies_{}", slot);
let doc = leading(&format!(
"Whether `{variant}` copies, and how — `Some` where its payload is `Clone` and `None` where \
it is not."
));
quote! {
#[doc = #doc]
#[inline]
#[allow(clippy::needless_borrow)]
fn #door() -> ::core::option::Option<fn(&#ty) -> #ty> {
(&__IngraphCopies::<#ty>(::core::marker::PhantomData)).__ingraph_door()
}
}
});
let duplicates = products.iter().map(|product| {
let (slot, variant) = (slot_name(product), &product.variant);
let door = format_ident!("__ingraph_copies_{}", slot);
quote! {
#out::#variant(__ingraph_value) => ::core::option::Option::map(
#door(),
|__ingraph_copy| #out::#variant(__ingraph_copy(__ingraph_value)),
),
}
});
let first_seats = products.iter().enumerate().map(|(index, product)| {
let (slot, ty) = (slot_name(product), &product.ty);
quote! {
if self.#slot.is_empty()
&& let ::core::option::Option::Some(__ingraph_edge) = #socket::opened::<#ty>(socket)
{
self.#slot.push(__ingraph_edge);
return ::core::result::Result::Ok(#attached::Seated(#index));
}
}
});
let more_seats = products.iter().enumerate().map(|(index, product)| {
let (slot, ty) = (slot_name(product), &product.ty);
let door = format_ident!("__ingraph_copies_{}", slot);
quote! {
if let ::core::option::Option::Some(__ingraph_edge) = #socket::opened::<#ty>(socket) {
if #door().is_some() {
self.#slot.push(__ingraph_edge);
return ::core::result::Result::Ok(#attached::Seated(#index));
}
if ::core::option::Option::is_none(&__ingraph_crowded) {
__ingraph_crowded = ::core::option::Option::Some(#index);
}
}
}
});
let new_doc = leading(&format!("A [`{record}`] publishing to nobody."));
quote! {
impl #downstream {
#[doc = #new_doc]
#[inline]
#[must_use]
#vis const fn new() -> Self {
Self { #(#empty)* }
}
#(#attachments)*
}
#[automatically_derived]
impl ::core::default::Default for #downstream {
#[inline]
fn default() -> Self {
Self::new()
}
}
struct __IngraphCopies<__INGRAPH_T__>(::core::marker::PhantomData<__INGRAPH_T__>);
trait __IngraphCopyDoor<__INGRAPH_T__> {
fn __ingraph_door(&self)
-> ::core::option::Option<fn(&__INGRAPH_T__) -> __INGRAPH_T__>;
}
impl<__INGRAPH_T__> __IngraphCopyDoor<__INGRAPH_T__> for __IngraphCopies<__INGRAPH_T__>
where
__INGRAPH_T__: ::core::clone::Clone,
{
#[inline]
fn __ingraph_door(&self)
-> ::core::option::Option<fn(&__INGRAPH_T__) -> __INGRAPH_T__>
{
::core::option::Option::Some(::core::clone::Clone::clone)
}
}
trait __IngraphMoveDoor<__INGRAPH_T__> {
fn __ingraph_door(&self)
-> ::core::option::Option<fn(&__INGRAPH_T__) -> __INGRAPH_T__>;
}
impl<__INGRAPH_T__> __IngraphMoveDoor<__INGRAPH_T__> for &__IngraphCopies<__INGRAPH_T__> {
#[inline]
fn __ingraph_door(&self)
-> ::core::option::Option<fn(&__INGRAPH_T__) -> __INGRAPH_T__>
{
::core::option::Option::None
}
}
#(#doors)*
#[automatically_derived]
impl #attaches for #downstream {
fn attach<__INGRAPH_SOCKET__>(
&mut self,
socket: &mut __INGRAPH_SOCKET__,
) -> ::core::result::Result<#attached, __INGRAPH_SOCKET__::Refusal>
where
__INGRAPH_SOCKET__: #socket,
{
#(#first_seats)*
let mut __ingraph_crowded: ::core::option::Option<usize> =
::core::option::Option::None;
#(#more_seats)*
::core::result::Result::Ok(match __ingraph_crowded {
::core::option::Option::Some(__ingraph_product) => {
#attached::Occupied(__ingraph_product)
}
::core::option::Option::None => #attached::Foreign,
})
}
}
#[automatically_derived]
impl #products_trait for #out {
type Kind = #kind;
}
#[automatically_derived]
impl #kind_trait for #kind {
const COUNT: usize = #arity;
#[inline]
fn index(self) -> usize {
match self {
#(#indices)*
}
}
}
impl #downstream {
#[inline]
fn __ingraph_seat_of(&self, edge: usize) -> ::core::option::Option<(usize, usize)> {
let __ingraph_lengths = [#(#lengths)*];
let mut __ingraph_rest = edge;
let mut __ingraph_product = 0usize;
while __ingraph_product < __ingraph_lengths.len() {
let __ingraph_width = __ingraph_lengths[__ingraph_product];
if __ingraph_rest < __ingraph_width {
return ::core::option::Option::Some((__ingraph_product, __ingraph_rest));
}
__ingraph_rest -= __ingraph_width;
__ingraph_product += 1;
}
::core::option::Option::None
}
}
#[automatically_derived]
impl #sink<#out> for #downstream {
#[inline]
fn arity(&self) -> usize {
#(#widths)+*
}
#[inline]
fn connected(&self) -> #wanted {
let mut mask = #wanted::none();
#(#connected)*
mask
}
#[inline]
fn carries(&self, edge: usize, output: &#out) -> bool {
let ::core::option::Option::Some((__ingraph_product, _)) = self.__ingraph_seat_of(edge)
else {
return false;
};
match (__ingraph_product, output) {
#(#carried)*
_ => false,
}
}
#[inline]
fn duplicate(&self, output: &#out) -> ::core::option::Option<#out> {
match output {
#(#duplicates)*
}
}
fn nudges(&self) -> ::std::vec::Vec<::std::boxed::Box<dyn #rings>> {
let mut ringers: ::std::vec::Vec<::std::boxed::Box<dyn #rings>> =
::std::vec::Vec::new();
#(#ringers)*
ringers
}
async fn deliver(
&mut self,
edge: usize,
batch: ::std::vec::Vec<#item<#out>>,
ack: #ack<#item_id>,
) -> bool {
let ::core::option::Option::Some((__ingraph_product, __ingraph_seat)) =
self.__ingraph_seat_of(edge)
else {
return false;
};
match __ingraph_product {
#(#deliveries)*
_ => false,
}
}
}
}
}
fn emits_binding(&self) -> proc_macro2::TokenStream {
let record = &self.record;
let emits = self.framework(&["operator"], "Emits");
let sole = self.framework(&["operator"], "SoleProduct");
let declared = self
.products
.as_ref()
.map(|products| products.products.as_slice())
.unwrap_or_default();
if declared.len() > 1 {
let rows = declared.iter().enumerate().map(|(index, product)| {
let ty = &product.ty;
quote! {
#[automatically_derived]
impl #emits<#index> for #record {
type Out = #ty;
}
}
});
return quote!(#(#rows)*);
}
let product = declared
.first()
.map_or_else(|| quote!(Self), |Product { ty, .. }| quote!(#ty));
quote! {
#[automatically_derived]
impl #emits for #record {
type Out = #product;
}
#[automatically_derived]
impl #sole for #record {}
}
}
fn one_product_audit(&self) -> Option<proc_macro2::TokenStream> {
let subscriptions = self.subscriptions.as_ref()?;
let unselected: Vec<&syn::Path> = subscriptions
.upstreams
.iter()
.filter(|upstream| upstream.out.is_none())
.map(|upstream| &upstream.node)
.collect();
if unselected.is_empty() {
return None;
}
let sole = self.framework(&["operator"], "SoleProduct");
Some(quote! {
const _: () = {
fn __ig_takes_one_product<__INGRAPH_UPSTREAM__: #sole>() {}
#(const _: fn() = __ig_takes_one_product::<#unselected>;)*
};
})
}
}
fn out_kind_path(node: &syn::Path) -> syn::Path {
let mut vocabulary = node.clone();
if let Some(last) = vocabulary.segments.last_mut() {
last.ident = default_out_kind_name(&last.ident);
last.arguments = syn::PathArguments::None;
}
vocabulary
}
fn slot_name(product: &Product) -> syn::Ident {
format_ident!("{}", snake(&product.variant.to_string()))
}
fn snake(word: &str) -> String {
let mut snake = String::with_capacity(word.len() + 4);
for (index, character) in word.char_indices() {
if character.is_uppercase() {
if index != 0 {
snake.push('_');
}
snake.extend(character.to_lowercase());
continue;
}
snake.push(character);
}
snake
}
fn path_text(path: &syn::Path) -> String {
path
.segments
.iter()
.map(|segment| segment.ident.to_string())
.collect::<Vec<_>>()
.join("::")
}