Skip to main content

ingraph_codegen/emit/
topology.rs

1//! The TOPOLOGY emission: what a node takes in, what it puts out, and the out-edges that carry
2//! it.
3//!
4//! Three declarations reach here and they are all about EDGES rather than about rows:
5//!
6//!   * `subscribe(upstream(…), …)` becomes the node's `In` — one `Paired` variant for the keyed
7//!     group and one per independent flow, each payload projected through the upstream's own
8//!     statement of what it emits;
9//!   * `emits = ["A", "B"]` becomes the node's `Out`, the vocabulary naming its arms, and the
10//!     DOWNSTREAM holding one out-edge slot per product;
11//!   * everything else — a node with one upstream, a node with one product — emits NOTHING new,
12//!     which is what keeps today's declarations compiling unchanged.
13//!
14//! # The two-derive wall, and the road across it
15//!
16//! A downstream declaration names `media::Frame` and cannot know what a `Frame` puts on the wire:
17//! two derives cannot see each other. So the payload is not a type this emission chooses — it is a
18//! PROJECTION the compiler resolves at the string the author wrote:
19//!
20//! ```text
21//! <media::Frame as Emits>::Out                                      // the sole product
22//! <vision::Detector as Emits<{ vision::DetectorOutKind::Boxes as usize }>>::Out
23//! ```
24//!
25//! The upstream's own expansion states both halves — an `Emits` row per product, and the
26//! `<Node>OutKind` vocabulary whose variant is the index — so the two declarations MEET at the
27//! projection. The author writes a WORD (`out = "Boxes"`) and the machinery counts an ORDINAL; the
28//! emission is the only party that maps between them, which is what keeps the word rename-proof.
29//!
30//! What a declaration that named no product gets instead is an AUDIT: `SoleProduct`, implemented by
31//! a node that emits exactly one, so leaving the product unsaid at a node that emits several is
32//! `E0277` at the string rather than a silent binding to whichever was declared first.
33//!
34//! # The PAIRING RUNTIME is not here, and its absence is stated rather than discovered
35//!
36//! `Paired` is a TYPE this emission declares. The join that fills it is the DRIVER's, and it is not
37//! built. Its contract is settled and written here so the build that lands it has nothing to
38//! re-decide:
39//!
40//!   * per-upstream channels and a select over them, rather than one inbox carrying a pre-made sum —
41//!     which is what keeps a slow upstream from delaying a fast one;
42//!   * a by-key buffer at the resident's intake for the keyed group: a message waits for its
43//!     counterparts, and the group is delivered COMPLETE or not at all;
44//!   * the straights pass THROUGH — an independent flow never waits on a pair that has not
45//!     assembled;
46//!   * a half-arrived pair waits INDEFINITELY. There is no timeout and no `PairPolicy` in v1: the
47//!     safety net is the upstream's own lag sweep, which re-pulls from the nearest durable upstream
48//!     when a watermark sticks, and a policy would be a knob before there was a case for one.
49//!
50//! A declaration that writes a keyed group therefore compiles, names its own fan-in type, and has
51//! no runtime that assembles one yet. The `In` type's own docs say so where an author will read it.
52
53#[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
66/// The variant an `In` enum gives the keyed group.
67///
68/// One word, fixed, because there is ONE group per container: `key` joins the group rather than
69/// opening one, so there is nothing for a name to tell apart. A straight upstream that would take
70/// this word is refused at the declaration, where it can still be edited.
71pub const PAIRED: &str = "Paired";
72
73impl RecordModel {
74  /// The whole topology expansion: the types at module scope, and the impls for the anonymous const.
75  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  /// The FAN-IN sum: one variant per thing that can arrive.
96  ///
97  /// Emitted only where the intake really is a sum — several upstreams, or a keyed group of any size.
98  /// One straight upstream is today's world, where the message type IS the input and an enum around
99  /// it would be a wrapper with one arm.
100  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  /// The message an upstream entry carries — the PROJECTION the two derives meet at.
165  ///
166  /// With no `out = "…"` the upstream emits one product and `Emits` unadorned names it. With one,
167  /// the
168  /// index is read off the upstream's OWN vocabulary: `<Node>OutKind` sits beside the node, so the
169  /// path is the node's with its last segment swapped — which is the one naming convention that
170  /// crosses the wall, and the reason the name is built by
171  /// [`default_out_kind_name`] rather than spelled here.
172  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    // THE NOTIFY RECEIPT: the entity's KEY, projected through the product's own answer about what
178    // its key is. The upstream emits `T` once and the WIRING projects at the send site, so this type
179    // is what arrives here and the author's `emit` never changed.
180    let transformer = self.framework(&["transform"], "Transformer");
181    quote!(<#product as #transformer>::Key)
182  }
183
184  /// The PRODUCT an upstream entry carries, before the receipt is applied — the projection proper.
185  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  /// THE NOTIFY FENCE: a product that has no key cannot be received as one.
196  ///
197  /// `notify` says *hand me this entity's key*, and only a product that ANSWERS what its key is can
198  /// be handed one — always true of what a store lands, true of a pure node's product exactly when
199  /// that product is a persisted entity. The claim is the declaration's and the check is rustc's, so
200  /// it is emitted as an audit rather than read here: two derives cannot see each other, and what
201  /// `media::Frame` even is is unknowable at this point.
202  ///
203  /// SPANNED AT THE NODE PATH the author wrote, which is what makes it a refusal a reader can act
204  /// on: the alternative is `E0277` inside the emitted `In` enum, at a span the declaration cannot
205  /// edit.
206  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  /// The PRODUCT face of a node that declares several: the sum, its vocabulary, and its downstream.
233  ///
234  /// A node with one product has none of this. Its `Out` is that type, its out-edges are the
235  /// framework's own holder, and the fan-out it already had is unchanged.
236  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    // THE COPY IS THE SET'S, so the derive follows the SET this declaration's own pair word picks.
250    // A `stream` declaration publishes through the node's own downstream set below, whose
251    // `Sink::duplicate` is resolved PER PRODUCT by the copy doors — so a derived `Clone` on the SUM
252    // would charge every product for whatever its neighbours need, at the `emits` word, and it is
253    // exactly what kept a demultiplexer's non-copying payloads out of a DECLARATION. The buffered
254    // and autonomous cells publish through `Downstream<Out>`, whose N edges of one product ARE the
255    // fan-out and which has no per-product door to ask, so there the derive stays.
256    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  /// Everything the product face implements: the downstream's own doors, the routing capability,
349  /// and the two type-level links a body reads the connection state through.
350  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              // Not this edge's product. Unreachable through the driver, which routes by
444              // `carries` — and answered `false` rather than dropped, so a hand-built call holds
445              // its items instead of losing them.
446              _ => 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    // THE PER-PRODUCT COPY DOOR, resolved at EXPANSION by the autoref probe.
462    //
463    // Whether a product's payload copies is a fact about a type this macro can NAME but cannot ask
464    // about: there is no `if T: Clone` in a declaration, and a `where` clause would move the cost
465    // onto the whole declaration rather than onto the one product that pays it. The probe answers it
466    // per product instead — the copying arm sits on `Copies<T>` behind `T: Clone` and is reached
467    // with no autoref, the moving arm sits on `&Copies<T>` and is reached with one, and method
468    // resolution takes the shorter road wherever the bound holds.
469    //
470    // It resolves to a CONSTANT: each door monomorphises to `Some(<a clone shim>)` or to `None`,
471    // so the `duplicate` below is a direct call or a folded-away `None` rather than a runtime test.
472    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          // THE BORROW IS THE MECHANISM — the probe counts autoref steps, so it is not noise.
485          (&__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    // THE SEATING WALK, in TWO passes and in declaration order.
501    //
502    // Pass one takes the first product with NO subscriber yet. Two products may share a Rust type —
503    // the framework cannot tell them apart, an edge carrying only its payload's type — and giving
504    // each of them a subscriber before doubling up on either is the reading a declaration that wrote
505    // two products most likely wanted.
506    //
507    // Pass two is the FAN: a product that already has subscribers takes another whenever its copy
508    // door answers `Some`, which is the ordinary road and needs no ceremony at all. A product whose
509    // door answers `None` cannot, and `crowded` is what remembers it — so a walk that finds no seat
510    // still says WHICH product was subscribed to twice, and the refusal names the payload as the fix.
511    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        /// WHICH product edge `edge` belongs to, and its place among that product's subscribers.
635        ///
636        /// The flat index a [`Sink`] speaks in is PRODUCT-MAJOR: every subscriber of the first
637        /// declared product, then every subscriber of the second, and so on. A product with no
638        /// subscriber contributes nothing, so the numbering closes over the edges that exist rather
639        /// than over the products that were declared.
640        #[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        /// EVERY EDGE, not every product: a product with several subscribers contributes one each,
660        /// and the driver's fan walks this number.
661        #[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        /// PER PRODUCT, which is the whole of what the seat bought: a `Clone` product hands the fan
686        /// a copy for every subscriber past the first, and a product that does not copy answers
687        /// `None` — the shape the launch already refused a second subscriber to.
688        #[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  /// What this node EMITS, stated for the downstream declarations that cannot see it.
723  ///
724  /// One `Emits<N>` row per product where several were declared. Where one was — named or left as
725  /// the declared struct itself — the row is joined by [`SoleProduct`](ingraph::SoleProduct), the
726  /// marker that makes an unselected subscription well formed.
727  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    // The ONE product: what `emits = "X"` named, or the declared struct itself — which is what this
751    // crate's edges have always moved, now said in the one place a downstream can read it.
752    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  /// The AUDIT a subscription that named no product discharges — one per such entry.
767  ///
768  /// It is [`subscription`](RecordModel::subscription)'s shape and for its reason: the
769  /// monomorphised function item is what discharges the bound, an initialiser is where naming it is
770  /// legal, and neither leaks a name into the declarer's scope. What it buys is the sentence — an
771  /// upstream that emits several products carries no `SoleProduct`, so the refusal lands at the
772  /// string the author wrote and names the word that fixes it.
773  ///
774  /// An entry that DID name a product needs none: its payload projection already names the
775  /// upstream's `Emits<N>` row, and a node that has no such row refuses there.
776  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
797/// The vocabulary path beside an upstream node: its own path with the last segment swapped for
798/// `<Node>OutKind`.
799///
800/// The ONE naming convention that crosses the two-derive wall, which is why it is assembled here
801/// from [`default_out_kind_name`] rather than written out at the call site — both sides of the wall
802/// read one function.
803fn 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
812/// A product's SLOT — its variant word in snake case, which is what the downstream's field and its
813/// door are named.
814fn slot_name(product: &Product) -> syn::Ident {
815  format_ident!("{}", snake(&product.variant.to_string()))
816}
817
818/// `CamelCase` into `snake_case`, for a field name derived from a variant word.
819fn 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
834/// A path as an author would read it back, for a doc comment naming a declaration they wrote.
835fn 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}