ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! The TOPOLOGY emission: what a node takes in, what it puts out, and the out-edges that carry
//! it.
//!
//! Three declarations reach here and they are all about EDGES rather than about rows:
//!
//!   * `subscribe(upstream(…), …)` becomes the node's `In` — one `Paired` variant for the keyed
//!     group and one per independent flow, each payload projected through the upstream's own
//!     statement of what it emits;
//!   * `emits = ["A", "B"]` becomes the node's `Out`, the vocabulary naming its arms, and the
//!     DOWNSTREAM holding one out-edge slot per product;
//!   * everything else — a node with one upstream, a node with one product — emits NOTHING new,
//!     which is what keeps today's declarations compiling unchanged.
//!
//! # The two-derive wall, and the road across it
//!
//! A downstream declaration names `media::Frame` and cannot know what a `Frame` puts on the wire:
//! two derives cannot see each other. So the payload is not a type this emission chooses — it is a
//! PROJECTION the compiler resolves at the string the author wrote:
//!
//! ```text
//! <media::Frame as Emits>::Out                                      // the sole product
//! <vision::Detector as Emits<{ vision::DetectorOutKind::Boxes as usize }>>::Out
//! ```
//!
//! The upstream's own expansion states both halves — an `Emits` row per product, and the
//! `<Node>OutKind` vocabulary whose variant is the index — so the two declarations MEET at the
//! projection. The author writes a WORD (`out = "Boxes"`) and the machinery counts an ORDINAL; the
//! emission is the only party that maps between them, which is what keeps the word rename-proof.
//!
//! What a declaration that named no product gets instead is an AUDIT: `SoleProduct`, implemented by
//! a node that emits exactly one, so leaving the product unsaid at a node that emits several is
//! `E0277` at the string rather than a silent binding to whichever was declared first.
//!
//! # The PAIRING RUNTIME is not here, and its absence is stated rather than discovered
//!
//! `Paired` is a TYPE this emission declares. The join that fills it is the DRIVER's, and it is not
//! built. Its contract is settled and written here so the build that lands it has nothing to
//! re-decide:
//!
//!   * per-upstream channels and a select over them, rather than one inbox carrying a pre-made sum —
//!     which is what keeps a slow upstream from delaying a fast one;
//!   * a by-key buffer at the resident's intake for the keyed group: a message waits for its
//!     counterparts, and the group is delivered COMPLETE or not at all;
//!   * the straights pass THROUGH — an independent flow never waits on a pair that has not
//!     assembled;
//!   * a half-arrived pair waits INDEFINITELY. There is no timeout and no `PairPolicy` in v1: the
//!     safety net is the upstream's own lag sweep, which re-pulls from the nearest durable upstream
//!     when a watermark sticks, and a policy would be a knob before there was a case for one.
//!
//! A declaration that writes a keyed group therefore compiles, names its own fan-in type, and has
//! no runtime that assembles one yet. The `In` type's own docs say so where an author will read it.

#[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,
  },
};

/// The variant an `In` enum gives the keyed group.
///
/// One word, fixed, because there is ONE group per container: `key` joins the group rather than
/// opening one, so there is nothing for a name to tell apart. A straight upstream that would take
/// this word is refused at the declaration, where it can still be edited.
pub const PAIRED: &str = "Paired";

impl RecordModel {
  /// The whole topology expansion: the types at module scope, and the impls for the anonymous const.
  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
      },
    )
  }

  /// The FAN-IN sum: one variant per thing that can arrive.
  ///
  /// Emitted only where the intake really is a sum — several upstreams, or a keyed group of any size.
  /// One straight upstream is today's world, where the message type IS the input and an enum around
  /// it would be a wrapper with one arm.
  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)*
      }
    })
  }

  /// The message an upstream entry carries — the PROJECTION the two derives meet at.
  ///
  /// With no `out = "…"` the upstream emits one product and `Emits` unadorned names it. With one,
  /// the
  /// index is read off the upstream's OWN vocabulary: `<Node>OutKind` sits beside the node, so the
  /// path is the node's with its last segment swapped — which is the one naming convention that
  /// crosses the wall, and the reason the name is built by
  /// [`default_out_kind_name`] rather than spelled here.
  fn upstream_message(&self, upstream: &Upstream) -> proc_macro2::TokenStream {
    let product = self.upstream_product(upstream);
    if !upstream.notify {
      return product;
    }
    // THE NOTIFY RECEIPT: the entity's KEY, projected through the product's own answer about what
    // its key is. The upstream emits `T` once and the WIRING projects at the send site, so this type
    // is what arrives here and the author's `emit` never changed.
    let transformer = self.framework(&["transform"], "Transformer");
    quote!(<#product as #transformer>::Key)
  }

  /// The PRODUCT an upstream entry carries, before the receipt is applied — the projection proper.
  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)
  }

  /// THE NOTIFY FENCE: a product that has no key cannot be received as one.
  ///
  /// `notify` says *hand me this entity's key*, and only a product that ANSWERS what its key is can
  /// be handed one — always true of what a store lands, true of a pure node's product exactly when
  /// that product is a persisted entity. The claim is the declaration's and the check is rustc's, so
  /// it is emitted as an audit rather than read here: two derives cannot see each other, and what
  /// `media::Frame` even is is unknowable at this point.
  ///
  /// SPANNED AT THE NODE PATH the author wrote, which is what makes it a refusal a reader can act
  /// on: the alternative is `E0277` inside the emitted `In` enum, at a span the declaration cannot
  /// edit.
  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)*
      };
    })
  }

  /// The PRODUCT face of a node that declares several: the sum, its vocabulary, and its downstream.
  ///
  /// A node with one product has none of this. Its `Out` is that type, its out-edges are the
  /// framework's own holder, and the fan-out it already had is unchanged.
  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."));
    // THE COPY IS THE SET'S, so the derive follows the SET this declaration's own pair word picks.
    // A `stream` declaration publishes through the node's own downstream set below, whose
    // `Sink::duplicate` is resolved PER PRODUCT by the copy doors — so a derived `Clone` on the SUM
    // would charge every product for whatever its neighbours need, at the `emits` word, and it is
    // exactly what kept a demultiplexer's non-copying payloads out of a DECLARATION. The buffered
    // and autonomous cells publish through `Downstream<Out>`, whose N edges of one product ARE the
    // fan-out and which has no per-product door to ask, so there the derive stays.
    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))
  }

  /// Everything the product face implements: the downstream's own doors, the routing capability,
  /// and the two type-level links a body reads the connection state through.
  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)),
              // Not this edge's product. Unreachable through the driver, which routes by
              // `carries` — and answered `false` rather than dropped, so a hand-built call holds
              // its items instead of losing them.
              _ => 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,)
    });

    // THE PER-PRODUCT COPY DOOR, resolved at EXPANSION by the autoref probe.
    //
    // Whether a product's payload copies is a fact about a type this macro can NAME but cannot ask
    // about: there is no `if T: Clone` in a declaration, and a `where` clause would move the cost
    // onto the whole declaration rather than onto the one product that pays it. The probe answers it
    // per product instead — the copying arm sits on `Copies<T>` behind `T: Clone` and is reached
    // with no autoref, the moving arm sits on `&Copies<T>` and is reached with one, and method
    // resolution takes the shorter road wherever the bound holds.
    //
    // It resolves to a CONSTANT: each door monomorphises to `Some(<a clone shim>)` or to `None`,
    // so the `duplicate` below is a direct call or a folded-away `None` rather than a runtime test.
    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> {
          // THE BORROW IS THE MECHANISM — the probe counts autoref steps, so it is not noise.
          (&__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)),
        ),
      }
    });

    // THE SEATING WALK, in TWO passes and in declaration order.
    //
    // Pass one takes the first product with NO subscriber yet. Two products may share a Rust type —
    // the framework cannot tell them apart, an edge carrying only its payload's type — and giving
    // each of them a subscriber before doubling up on either is the reading a declaration that wrote
    // two products most likely wanted.
    //
    // Pass two is the FAN: a product that already has subscribers takes another whenever its copy
    // door answers `Some`, which is the ordinary road and needs no ceremony at all. A product whose
    // door answers `None` cannot, and `crowded` is what remembers it — so a walk that finds no seat
    // still says WHICH product was subscribed to twice, and the refusal names the payload as the fix.
    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 {
        /// WHICH product edge `edge` belongs to, and its place among that product's subscribers.
        ///
        /// The flat index a [`Sink`] speaks in is PRODUCT-MAJOR: every subscriber of the first
        /// declared product, then every subscriber of the second, and so on. A product with no
        /// subscriber contributes nothing, so the numbering closes over the edges that exist rather
        /// than over the products that were declared.
        #[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 {
        /// EVERY EDGE, not every product: a product with several subscribers contributes one each,
        /// and the driver's fan walks this number.
        #[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,
          }
        }

        /// PER PRODUCT, which is the whole of what the seat bought: a `Clone` product hands the fan
        /// a copy for every subscriber past the first, and a product that does not copy answers
        /// `None` — the shape the launch already refused a second subscriber to.
        #[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,
          }
        }
      }
    }
  }

  /// What this node EMITS, stated for the downstream declarations that cannot see it.
  ///
  /// One `Emits<N>` row per product where several were declared. Where one was — named or left as
  /// the declared struct itself — the row is joined by [`SoleProduct`](ingraph::SoleProduct), the
  /// marker that makes an unselected subscription well formed.
  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)*);
    }

    // The ONE product: what `emits = "X"` named, or the declared struct itself — which is what this
    // crate's edges have always moved, now said in the one place a downstream can read it.
    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 {}
    }
  }

  /// The AUDIT a subscription that named no product discharges — one per such entry.
  ///
  /// It is [`subscription`](RecordModel::subscription)'s shape and for its reason: the
  /// monomorphised function item is what discharges the bound, an initialiser is where naming it is
  /// legal, and neither leaks a name into the declarer's scope. What it buys is the sentence — an
  /// upstream that emits several products carries no `SoleProduct`, so the refusal lands at the
  /// string the author wrote and names the word that fixes it.
  ///
  /// An entry that DID name a product needs none: its payload projection already names the
  /// upstream's `Emits<N>` row, and a node that has no such row refuses there.
  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>;)*
      };
    })
  }
}

/// The vocabulary path beside an upstream node: its own path with the last segment swapped for
/// `<Node>OutKind`.
///
/// The ONE naming convention that crosses the two-derive wall, which is why it is assembled here
/// from [`default_out_kind_name`] rather than written out at the call site — both sides of the wall
/// read one function.
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
}

/// A product's SLOT — its variant word in snake case, which is what the downstream's field and its
/// door are named.
fn slot_name(product: &Product) -> syn::Ident {
  format_ident!("{}", snake(&product.variant.to_string()))
}

/// `CamelCase` into `snake_case`, for a field name derived from a variant word.
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
}

/// A path as an author would read it back, for a doc comment naming a declaration they wrote.
fn path_text(path: &syn::Path) -> String {
  path
    .segments
    .iter()
    .map(|segment| segment.ident.to_string())
    .collect::<Vec<_>>()
    .join("::")
}