1#[cfg(test)]
54mod tests;
55
56use quote::{format_ident, quote, quote_spanned};
57
58use crate::{
59 emit::leading,
60 model::{
61 Product, RecordModel, Upstream, default_downstream_name, default_in_name,
62 default_out_kind_name, default_out_name,
63 },
64};
65
66pub const PAIRED: &str = "Paired";
72
73impl RecordModel {
74 pub(super) fn topology(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
76 let fan_in = self.fan_in();
77 let (product_types, product_impls) = self.product_faces();
78 let emits = self.emits_binding();
79 let audit = self.one_product_audit();
80 let notified = self.notify_audit();
81 (
82 quote! {
83 #fan_in
84 #product_types
85 },
86 quote! {
87 #product_impls
88 #emits
89 #audit
90 #notified
91 },
92 )
93 }
94
95 fn fan_in(&self) -> Option<proc_macro2::TokenStream> {
101 let subscriptions = self.subscriptions.as_ref().filter(|fan| fan.is_sum())?;
102 let (record, vis) = (&self.record, &self.vis);
103 let name = default_in_name(record);
104 let paired = format_ident!("{PAIRED}");
105 let doc = leading(&format!(
106 "What arrives at a [`{record}`]: one variant per flow it draws from."
107 ));
108 let pairing_note = leading(
109 "The `Paired` variant is the KEYED GROUP: its members are joined by key and delivered \
110 COMPLETE, while every other variant arrives on its own the moment it does. The join that \
111 fills it is the driver's and is NOT BUILT — a declaration that writes `key` names its group \
112 here and waits for the intake that assembles one.",
113 );
114
115 let mut variants = Vec::new();
116 let mut group_written = false;
117 for upstream in &subscriptions.upstreams {
118 if upstream.keyed {
119 if group_written {
120 continue;
121 }
122 group_written = true;
123 let payloads = subscriptions
124 .keyed()
125 .map(|keyed| self.upstream_message(keyed));
126 let names = subscriptions
127 .keyed()
128 .map(|keyed| keyed.variant.to_string())
129 .collect::<Vec<_>>()
130 .join("`, `");
131 let doc = leading(&format!(
132 "One message from EACH of `{names}`, joined by key — complete, and delivered together. \
133 A group missing a member waits, with no deadline: the upstream's lag sweep is what \
134 re-pulls a flow that stopped."
135 ));
136 variants.push(quote! {
137 #[doc = #doc]
138 #paired(#(#payloads),*),
139 });
140 continue;
141 }
142 let (variant, node) = (&upstream.variant, &upstream.node);
143 let payload = self.upstream_message(upstream);
144 let doc = leading(&format!(
145 "One message from `{}`, arriving on its own.",
146 path_text(node)
147 ));
148 variants.push(quote! {
149 #[doc = #doc]
150 #variant(#payload),
151 });
152 }
153
154 Some(quote! {
155 #[doc = #doc]
156 #[doc = ""]
157 #[doc = #pairing_note]
158 #vis enum #name {
159 #(#variants)*
160 }
161 })
162 }
163
164 fn upstream_message(&self, upstream: &Upstream) -> proc_macro2::TokenStream {
173 let product = self.upstream_product(upstream);
174 if !upstream.notify {
175 return product;
176 }
177 let transformer = self.framework(&["transform"], "Transformer");
181 quote!(<#product as #transformer>::Key)
182 }
183
184 fn upstream_product(&self, upstream: &Upstream) -> proc_macro2::TokenStream {
186 let emits = self.framework(&["operator"], "Emits");
187 let node = &upstream.node;
188 let Some(out) = &upstream.out else {
189 return quote!(<#node as #emits>::Out);
190 };
191 let vocabulary = out_kind_path(node);
192 quote!(<#node as #emits<{ #vocabulary::#out as usize }>>::Out)
193 }
194
195 fn notify_audit(&self) -> Option<proc_macro2::TokenStream> {
207 let subscriptions = self.subscriptions.as_ref()?;
208 let notified: Vec<&Upstream> = subscriptions
209 .upstreams
210 .iter()
211 .filter(|upstream| upstream.notify)
212 .collect();
213 if notified.is_empty() {
214 return None;
215 }
216 let transformer = self.framework(&["transform"], "Transformer");
217 let audits = notified.iter().map(|upstream| {
218 let product = self.upstream_product(upstream);
219 let at = syn::spanned::Spanned::span(&upstream.node);
220 quote_spanned! {at=>
221 const _: fn() = __ig_is_notifiable::<#product>;
222 }
223 });
224 Some(quote! {
225 const _: () = {
226 fn __ig_is_notifiable<__INGRAPH_LANDED__: #transformer>() {}
227 #(#audits)*
228 };
229 })
230 }
231
232 fn product_faces(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
237 let Some(products) = self.products.as_ref().filter(|products| products.is_sum()) else {
238 return Default::default();
239 };
240 let products = &products.products;
241 let (record, vis) = (&self.record, &self.vis);
242 let (out, kind, downstream) = (
243 default_out_name(record),
244 default_out_kind_name(record),
245 default_downstream_name(record),
246 );
247
248 let out_doc = leading(&format!("What a [`{record}`] puts on an edge."));
249 let streamed = self.streaming.is_some();
257 let clone_note = leading(if streamed {
258 "It does NOT derive `Clone`, and that is this declaration's `stream` word cashed. A streaming \
259 node publishes through its own downstream set below, which asks `Sink::duplicate` PER \
260 PRODUCT — so a product with one subscriber is asked for no copy at all, and a derived `Clone` \
261 on the SUM would charge every product for whatever its neighbours happen to need. It would \
262 charge it at the `emits` word too: a product holding a decoded buffer or an open handle would \
263 fail to compile before any mount was written.\n\nEach product may have as MANY subscribers \
264 as it likes — the fan serves each one past the first a copy from that product's own door. A \
265 product whose payload has none to give serves one, and the launch refuses the second by name \
266 (`ProductSeatError::Occupied`), naming the payload as the fix."
267 } else {
268 "`Clone` because a fan-out is one message at several consumers: the driver moves the value \
269 into the last edge and clones it for the others, which is the bound the resident carries on \
270 every node's `Out`.\n\nIt is charged because it is SPENT — this declaration wrote no \
271 `stream`, so its mount publishes through `Downstream<Out>`, whose N edges of one product are \
272 the fan-out itself and whose own `Sink` impl takes the copy. A derived `Clone` calls each \
273 payload's own, so a product that holds a decoded buffer or an open handle and does not copy \
274 fails to compile at the `emits` word — which is where the cost is decided. The `stream` word \
275 is what takes the bound off: there the node's own set below asks for a copy per product \
276 rather than of the sum."
277 });
278 let clone = (!streamed).then(|| quote!(#[derive(::core::clone::Clone)]));
279 let out_variants = products.iter().map(|product| {
280 let (variant, ty) = (&product.variant, &product.ty);
281 let doc = leading(&format!("The `{variant}` product."));
282 quote! {
283 #[doc = #doc]
284 #variant(#ty),
285 }
286 });
287 let kind_doc = leading(&format!(
288 "WHICH product a [`{record}`] message is — the identity a body asks the connection state \
289 about."
290 ));
291 let kind_variants = products.iter().map(|product| {
292 let variant = &product.variant;
293 quote!(#variant,)
294 });
295 let downstream_doc = leading(&format!(
296 "Where a [`{record}`]'s products go: one out-edge list per product, and a list's own \
297 emptiness is the connection state.\n\nA product may have SEVERAL subscribers — the ordinary \
298 topology, and what an A/B split, a canary rollout or a thumbnailer beside an embedder is — so \
299 each product holds a list rather than a seat. The fan is the lane's own: it moves the output \
300 into the LAST edge that carries it and asks `Sink::duplicate` for the ones before, which \
301 answers PER PRODUCT here. A product whose payload does not copy therefore serves exactly one \
302 subscriber, and a second is refused BY NAME at the launch rather than by dropping."
303 ));
304 let fields = products.iter().map(|product| {
305 let (slot, ty) = (slot_name(product), &product.ty);
306 let outbox = self.framework(&["drive"], "Outbox");
307 let item = self.framework(&["drive"], "ItemId");
308 let doc = leading(&format!(
309 "Every consumer of `{}`, in the order the wiring seated them.",
310 product.variant
311 ));
312 quote! {
313 #[doc = #doc]
314 #slot: ::std::vec::Vec<#outbox<#item, #ty>>,
315 }
316 });
317
318 let types = quote! {
319 #[doc = #out_doc]
320 #[doc = ""]
321 #[doc = #clone_note]
322 #clone
323 #vis enum #out {
324 #(#out_variants)*
325 }
326
327 #[doc = #kind_doc]
328 #[derive(
329 ::core::fmt::Debug,
330 ::core::clone::Clone,
331 ::core::marker::Copy,
332 ::core::cmp::PartialEq,
333 ::core::cmp::Eq,
334 ::core::hash::Hash
335 )]
336 #vis enum #kind {
337 #(#kind_variants)*
338 }
339
340 #[doc = #downstream_doc]
341 #vis struct #downstream {
342 #(#fields)*
343 }
344 };
345 (types, self.downstream(&out, &kind, &downstream))
346 }
347
348 fn downstream(
351 &self,
352 out: &syn::Ident,
353 kind: &syn::Ident,
354 downstream: &syn::Ident,
355 ) -> proc_macro2::TokenStream {
356 let products = self
357 .products
358 .as_ref()
359 .map(|products| products.products.as_slice())
360 .unwrap_or_default();
361 let (record, vis) = (&self.record, &self.vis);
362 let arity = products.len();
363
364 let sink = self.framework(&["drive"], "Sink");
365 let attaches = self.framework(&["drive"], "Attaches");
366 let attached = self.framework(&["drive"], "Attached");
367 let socket = self.framework(&["drive"], "Socket");
368 let wanted = self.framework(&["drive"], "Wanted");
369 let rings = self.framework(&["drive"], "Rings");
370 let outbox = self.framework(&["drive"], "Outbox");
371 let item_id = self.framework(&["drive"], "ItemId");
372 let item = self.framework(&["drive"], "Item");
373 let delivery = self.framework(&["drive"], "Delivery");
374 let payload = self.framework(&["drive"], "Payload");
375 let ack = self.framework(&["drive"], "AckSender");
376 let products_trait = self.framework(&["operator"], "Products");
377 let kind_trait = self.framework(&["operator"], "ProductKind");
378
379 let empty = products.iter().map(|product| {
380 let slot = slot_name(product);
381 quote!(#slot: ::std::vec::Vec::new(),)
382 });
383 let attachments = products.iter().map(|product| {
384 let (slot, ty, variant) = (slot_name(product), &product.ty, &product.variant);
385 let door = format_ident!("attach_{}", slot);
386 let doc = leading(&format!(
387 "Carry `{variant}` to `outbox` too — ONE MORE consumer of that product, and the list \
388 ceasing to be empty is what makes the product wanted.\n\nSeveral is the ordinary case. \
389 What the extra subscribers cost is a COPY apiece, taken through `Sink::duplicate` at the \
390 product's own door — so a product whose payload does not implement `Clone` serves one \
391 subscriber and the launch refuses the second by name."
392 ));
393 quote! {
394 #[doc = #doc]
395 #[inline]
396 #vis fn #door(&mut self, outbox: #outbox<#item_id, #ty>) -> &mut Self {
397 self.#slot.push(outbox);
398 self
399 }
400 }
401 });
402 let lengths = products.iter().map(|product| {
403 let slot = slot_name(product);
404 quote!(self.#slot.len(),)
405 });
406 let widths = products.iter().map(|product| {
407 let slot = slot_name(product);
408 quote!(self.#slot.len())
409 });
410 let connected = products.iter().enumerate().map(|(index, product)| {
411 let slot = slot_name(product);
412 quote! {
413 if !self.#slot.is_empty() {
414 mask = mask.with(#index);
415 }
416 }
417 });
418 let carried = products.iter().enumerate().map(|(index, product)| {
419 let variant = &product.variant;
420 quote!((#index, #out::#variant(_)) => true,)
421 });
422 let ringers = products.iter().map(|product| {
423 let slot = slot_name(product);
424 quote! {
425 for edge in &self.#slot {
426 ringers.push(::std::boxed::Box::new(edge.nudge()) as ::std::boxed::Box<dyn #rings>);
427 }
428 }
429 });
430 let deliveries = products.iter().enumerate().map(|(index, product)| {
431 let (slot, ty, variant) = (slot_name(product), &product.ty, &product.variant);
432 quote! {
433 #index => {
434 let ::core::option::Option::Some(edge) = self.#slot.get(__ingraph_seat) else {
435 return false;
436 };
437 let mut taken: ::std::vec::Vec<#item<#ty>> =
438 ::std::vec::Vec::with_capacity(batch.len());
439 for message in batch {
440 let (id, value) = message.into_parts();
441 match value {
442 #out::#variant(product) => taken.push(#item::new(id, product)),
443 _ => return false,
447 }
448 }
449 edge
450 .deliver_async(#delivery::new(#payload::Batch(taken), ack))
451 .await
452 .is_ok()
453 }
454 }
455 });
456 let indices = products.iter().enumerate().map(|(index, product)| {
457 let variant = &product.variant;
458 quote!(Self::#variant => #index,)
459 });
460
461 let doors = products.iter().map(|product| {
473 let (slot, ty, variant) = (slot_name(product), &product.ty, &product.variant);
474 let door = format_ident!("__ingraph_copies_{}", slot);
475 let doc = leading(&format!(
476 "Whether `{variant}` copies, and how — `Some` where its payload is `Clone` and `None` where \
477 it is not."
478 ));
479 quote! {
480 #[doc = #doc]
481 #[inline]
482 #[allow(clippy::needless_borrow)]
483 fn #door() -> ::core::option::Option<fn(&#ty) -> #ty> {
484 (&__IngraphCopies::<#ty>(::core::marker::PhantomData)).__ingraph_door()
486 }
487 }
488 });
489 let duplicates = products.iter().map(|product| {
490 let (slot, variant) = (slot_name(product), &product.variant);
491 let door = format_ident!("__ingraph_copies_{}", slot);
492 quote! {
493 #out::#variant(__ingraph_value) => ::core::option::Option::map(
494 #door(),
495 |__ingraph_copy| #out::#variant(__ingraph_copy(__ingraph_value)),
496 ),
497 }
498 });
499
500 let first_seats = products.iter().enumerate().map(|(index, product)| {
512 let (slot, ty) = (slot_name(product), &product.ty);
513 quote! {
514 if self.#slot.is_empty()
515 && let ::core::option::Option::Some(__ingraph_edge) = #socket::opened::<#ty>(socket)
516 {
517 self.#slot.push(__ingraph_edge);
518 return ::core::result::Result::Ok(#attached::Seated(#index));
519 }
520 }
521 });
522 let more_seats = products.iter().enumerate().map(|(index, product)| {
523 let (slot, ty) = (slot_name(product), &product.ty);
524 let door = format_ident!("__ingraph_copies_{}", slot);
525 quote! {
526 if let ::core::option::Option::Some(__ingraph_edge) = #socket::opened::<#ty>(socket) {
527 if #door().is_some() {
528 self.#slot.push(__ingraph_edge);
529 return ::core::result::Result::Ok(#attached::Seated(#index));
530 }
531 if ::core::option::Option::is_none(&__ingraph_crowded) {
532 __ingraph_crowded = ::core::option::Option::Some(#index);
533 }
534 }
535 }
536 });
537
538 let new_doc = leading(&format!("A [`{record}`] publishing to nobody."));
539 quote! {
540 impl #downstream {
541 #[doc = #new_doc]
542 #[inline]
543 #[must_use]
544 #vis const fn new() -> Self {
545 Self { #(#empty)* }
546 }
547
548 #(#attachments)*
549 }
550
551 #[automatically_derived]
552 impl ::core::default::Default for #downstream {
553 #[inline]
554 fn default() -> Self {
555 Self::new()
556 }
557 }
558
559 struct __IngraphCopies<__INGRAPH_T__>(::core::marker::PhantomData<__INGRAPH_T__>);
560
561 trait __IngraphCopyDoor<__INGRAPH_T__> {
562 fn __ingraph_door(&self)
563 -> ::core::option::Option<fn(&__INGRAPH_T__) -> __INGRAPH_T__>;
564 }
565
566 impl<__INGRAPH_T__> __IngraphCopyDoor<__INGRAPH_T__> for __IngraphCopies<__INGRAPH_T__>
567 where
568 __INGRAPH_T__: ::core::clone::Clone,
569 {
570 #[inline]
571 fn __ingraph_door(&self)
572 -> ::core::option::Option<fn(&__INGRAPH_T__) -> __INGRAPH_T__>
573 {
574 ::core::option::Option::Some(::core::clone::Clone::clone)
575 }
576 }
577
578 trait __IngraphMoveDoor<__INGRAPH_T__> {
579 fn __ingraph_door(&self)
580 -> ::core::option::Option<fn(&__INGRAPH_T__) -> __INGRAPH_T__>;
581 }
582
583 impl<__INGRAPH_T__> __IngraphMoveDoor<__INGRAPH_T__> for &__IngraphCopies<__INGRAPH_T__> {
584 #[inline]
585 fn __ingraph_door(&self)
586 -> ::core::option::Option<fn(&__INGRAPH_T__) -> __INGRAPH_T__>
587 {
588 ::core::option::Option::None
589 }
590 }
591
592 #(#doors)*
593
594 #[automatically_derived]
595 impl #attaches for #downstream {
596 fn attach<__INGRAPH_SOCKET__>(
597 &mut self,
598 socket: &mut __INGRAPH_SOCKET__,
599 ) -> ::core::result::Result<#attached, __INGRAPH_SOCKET__::Refusal>
600 where
601 __INGRAPH_SOCKET__: #socket,
602 {
603 #(#first_seats)*
604 let mut __ingraph_crowded: ::core::option::Option<usize> =
605 ::core::option::Option::None;
606 #(#more_seats)*
607 ::core::result::Result::Ok(match __ingraph_crowded {
608 ::core::option::Option::Some(__ingraph_product) => {
609 #attached::Occupied(__ingraph_product)
610 }
611 ::core::option::Option::None => #attached::Foreign,
612 })
613 }
614 }
615
616 #[automatically_derived]
617 impl #products_trait for #out {
618 type Kind = #kind;
619 }
620
621 #[automatically_derived]
622 impl #kind_trait for #kind {
623 const COUNT: usize = #arity;
624
625 #[inline]
626 fn index(self) -> usize {
627 match self {
628 #(#indices)*
629 }
630 }
631 }
632
633 impl #downstream {
634 #[inline]
641 fn __ingraph_seat_of(&self, edge: usize) -> ::core::option::Option<(usize, usize)> {
642 let __ingraph_lengths = [#(#lengths)*];
643 let mut __ingraph_rest = edge;
644 let mut __ingraph_product = 0usize;
645 while __ingraph_product < __ingraph_lengths.len() {
646 let __ingraph_width = __ingraph_lengths[__ingraph_product];
647 if __ingraph_rest < __ingraph_width {
648 return ::core::option::Option::Some((__ingraph_product, __ingraph_rest));
649 }
650 __ingraph_rest -= __ingraph_width;
651 __ingraph_product += 1;
652 }
653 ::core::option::Option::None
654 }
655 }
656
657 #[automatically_derived]
658 impl #sink<#out> for #downstream {
659 #[inline]
662 fn arity(&self) -> usize {
663 #(#widths)+*
664 }
665
666 #[inline]
667 fn connected(&self) -> #wanted {
668 let mut mask = #wanted::none();
669 #(#connected)*
670 mask
671 }
672
673 #[inline]
674 fn carries(&self, edge: usize, output: &#out) -> bool {
675 let ::core::option::Option::Some((__ingraph_product, _)) = self.__ingraph_seat_of(edge)
676 else {
677 return false;
678 };
679 match (__ingraph_product, output) {
680 #(#carried)*
681 _ => false,
682 }
683 }
684
685 #[inline]
689 fn duplicate(&self, output: &#out) -> ::core::option::Option<#out> {
690 match output {
691 #(#duplicates)*
692 }
693 }
694
695 fn nudges(&self) -> ::std::vec::Vec<::std::boxed::Box<dyn #rings>> {
696 let mut ringers: ::std::vec::Vec<::std::boxed::Box<dyn #rings>> =
697 ::std::vec::Vec::new();
698 #(#ringers)*
699 ringers
700 }
701
702 async fn deliver(
703 &mut self,
704 edge: usize,
705 batch: ::std::vec::Vec<#item<#out>>,
706 ack: #ack<#item_id>,
707 ) -> bool {
708 let ::core::option::Option::Some((__ingraph_product, __ingraph_seat)) =
709 self.__ingraph_seat_of(edge)
710 else {
711 return false;
712 };
713 match __ingraph_product {
714 #(#deliveries)*
715 _ => false,
716 }
717 }
718 }
719 }
720 }
721
722 fn emits_binding(&self) -> proc_macro2::TokenStream {
728 let record = &self.record;
729 let emits = self.framework(&["operator"], "Emits");
730 let sole = self.framework(&["operator"], "SoleProduct");
731 let declared = self
732 .products
733 .as_ref()
734 .map(|products| products.products.as_slice())
735 .unwrap_or_default();
736
737 if declared.len() > 1 {
738 let rows = declared.iter().enumerate().map(|(index, product)| {
739 let ty = &product.ty;
740 quote! {
741 #[automatically_derived]
742 impl #emits<#index> for #record {
743 type Out = #ty;
744 }
745 }
746 });
747 return quote!(#(#rows)*);
748 }
749
750 let product = declared
753 .first()
754 .map_or_else(|| quote!(Self), |Product { ty, .. }| quote!(#ty));
755 quote! {
756 #[automatically_derived]
757 impl #emits for #record {
758 type Out = #product;
759 }
760
761 #[automatically_derived]
762 impl #sole for #record {}
763 }
764 }
765
766 fn one_product_audit(&self) -> Option<proc_macro2::TokenStream> {
777 let subscriptions = self.subscriptions.as_ref()?;
778 let unselected: Vec<&syn::Path> = subscriptions
779 .upstreams
780 .iter()
781 .filter(|upstream| upstream.out.is_none())
782 .map(|upstream| &upstream.node)
783 .collect();
784 if unselected.is_empty() {
785 return None;
786 }
787 let sole = self.framework(&["operator"], "SoleProduct");
788 Some(quote! {
789 const _: () = {
790 fn __ig_takes_one_product<__INGRAPH_UPSTREAM__: #sole>() {}
791 #(const _: fn() = __ig_takes_one_product::<#unselected>;)*
792 };
793 })
794 }
795}
796
797fn out_kind_path(node: &syn::Path) -> syn::Path {
804 let mut vocabulary = node.clone();
805 if let Some(last) = vocabulary.segments.last_mut() {
806 last.ident = default_out_kind_name(&last.ident);
807 last.arguments = syn::PathArguments::None;
808 }
809 vocabulary
810}
811
812fn slot_name(product: &Product) -> syn::Ident {
815 format_ident!("{}", snake(&product.variant.to_string()))
816}
817
818fn snake(word: &str) -> String {
820 let mut snake = String::with_capacity(word.len() + 4);
821 for (index, character) in word.char_indices() {
822 if character.is_uppercase() {
823 if index != 0 {
824 snake.push('_');
825 }
826 snake.extend(character.to_lowercase());
827 continue;
828 }
829 snake.push(character);
830 }
831 snake
832}
833
834fn path_text(path: &syn::Path) -> String {
836 path
837 .segments
838 .iter()
839 .map(|segment| segment.ident.to_string())
840 .collect::<Vec<_>>()
841 .join("::")
842}