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
//! The FACTS emission: what a node states about itself, so a root that cannot read its tokens can
//! name them anyway.
//!
//! ```text
//! impl Declared for Scene {
//!   const EFFECT: Effect = Effect::Lands;
//!   const HOLDS_LANE: bool = true;
//!   const UPSTREAMS: &'static [Upstream] = &[
//!     Upstream::of::<media::Shot>("media::Shot").channelled(ChannelOptions::Bounded(512)),
//!   ];
//!   type Attribution<O> = RootProjection<O>;
//!   type Options = scene::Options;
//!   type Pair = Buffered;
//!   type Wires<O> = Downstream<O>;
//! }
//! ```
//!
//! Every one of those is a fact the ROOT's own declaration has no access to — a root sees a field's
//! type path and nothing else — and every one is a fact this declaration already carries. So the
//! word crosses as an IMPL rather than as a token read: nobody parses anybody's declaration, and the
//! compiler resolves the meeting at the projection the root writes.
//!
//! # What each fact is READ OFF, and the two that are derived rather than declared
//!
//! * **`UPSTREAMS`** — the subscribe words, in declaration order, which is the order the wiring walk
//!   numbers a node's edges in. Each entry carries the upstream's identity plus the per-upstream words
//!   that already exist: `changes(<db>)` becomes the [`Listen`] arm and its feeder, `channel = …`
//!   becomes the author's shipped depth. The single-word form `subscribe = "…"` is ONE entry, and a
//!   fusion's `upstream(…)` entries are entries too — three spellings, one table, because the launch
//!   floor has one question.
//! * **`Options`** — the `options = "…"` word, or `()` where the declaration wrote none. `()` is a
//!   statement and not a gap: a node with no knobs IS configured by the unit type, which is what its
//!   `AsyncConstructor` already spells.
//! * **`EFFECT` and `HOLDS_LANE` are DERIVED from the node's KIND**, because no word states either.
//!   A kind with a storage block lands through a lane it owns; an operator computes and lands
//!   nothing of its own. That is the same table [`NodeKind::stores`] already answers, read once
//!   rather than restated — and where a future word lets a pure node say that a storage
//!   co-subscriber makes it durable, it overrides these two and nothing else moves.
//!
//! # What is NOT emitted, and it is a seat rather than an omission
//!
//! `DEMANDS` stays at its default. A node's resource demands are `Shared<R>` fields on the value the
//! constructor builds, and no word or field scan in this grammar reaches them — the `resource` word
//! that exists is the ROOT's, naming the catalog rather than any node's reach into it. The seat is
//! live and hand-writable, and the crate's own arrangements fill it; the day a node-side word
//! arrives, this is where it lands.
//!
//! `DRIVER` stays at its default for the same shape of reason: the engine follows the operator's
//! mobility and no grammar says so yet.

use quote::quote;

use crate::{
  emit::leading,
  model::{
    ChangesFeed, ChannelOptions, RecordModel, Upstream, Upstreams, default_channels_name,
    default_downstream_name,
  },
};

#[cfg(test)]
mod tests;

impl RecordModel {
  /// The facts impl — this node's own statement of everything a launch needs and a root cannot see.
  pub(super) fn declared(&self) -> proc_macro2::TokenStream {
    let record = &self.record;
    let declared = self.framework(&["drive"], "Declared");
    let effect = self.framework(&["drive"], "Effect");
    let upstream = self.framework(&["drive"], "Upstream");
    let grant = self.framework(&["drive"], "Grant");

    let (arm, lane) = if self.kind.stores() {
      (quote!(Lands), quote!(true))
    } else {
      (quote!(Pure), quote!(false))
    };
    let upstreams = self.declared_sources();
    let options = self
      .options
      .as_ref()
      .map_or_else(|| quote!(()), |path| quote!(#path));
    // The SHELF, or the framework's empty one where there is no container to tune. Written in as
    // many words at both arms, because associated-type defaults are not stable — see the trait.
    let channels = self.subscriptions.as_ref().map_or_else(
      || {
        let unchanneled = self.framework(&["drive"], "Unchanneled");
        quote!(#unchanneled)
      },
      |_| {
        let shelf = default_channels_name(&self.record);
        quote!(#shelf)
      },
    );

    let effect_doc = leading(&format!(
      "What a [`{record}`]'s outputs become — read off the kind it was declared under."
    ));
    let lane_doc = leading(&format!(
      "Whether a [`{record}`] holds a write lane of its own — read off the same kind."
    ));
    let sources_doc = leading(&format!(
      "Every upstream a [`{record}`] draws from, in declaration order."
    ));
    let grants_doc = leading(&format!(
      "Every store a [`{record}`] granted itself the right to write, in declaration order."
    ));
    let grants = self.declared_grants();
    let goodbye = self.declared_goodbye();
    let mode = self.declared_mode();
    let pair = self.declared_pair();
    let wires = self.declared_wires();
    let attribution = self.declared_attribution();
    let tracing = self.declared_tracing();

    quote! {
      #[automatically_derived]
      impl #declared for #record {
        #[doc = #effect_doc]
        const EFFECT: #effect = #effect::#arm;

        #[doc = #lane_doc]
        const HOLDS_LANE: bool = #lane;

        #[doc = #sources_doc]
        const UPSTREAMS: &'static [#upstream] = &[#(#upstreams,)*];

        #[doc = #grants_doc]
        const GRANTS: &'static [#grant] = &[#(#grants,)*];

        type Channels = #channels;
        type Options = #options;
        #pair
        #wires
        #attribution
        #mode

        #goodbye
        #tracing
      }
    }
  }

  /// The `receipt = "…"` word's whole runtime half — the SIBLING impl on the MESSAGE, or nothing at
  /// all.
  ///
  /// ```text
  /// impl Receipts for SceneOpen {
  ///   type Receipt = media::SceneId;
  /// }
  /// ```
  ///
  /// # The self type is the DECLARED MESSAGE, which is the whole of the re-key
  ///
  /// The impl used to sit on the CONSUMER — *this node hands back a `SceneId`* — and the subject was
  /// wrong. A receipt answers the item that was GIVEN, so the question belongs to the message: every
  /// seat on the far end of that edge answers the same one, and a second seat over the same message
  /// would otherwise declare the type again and be able to disagree. The word is kind-gated to the
  /// rungs that mint a message (`NodeKind::mints_a_message`), so the self type here is always a
  /// value a producer can hold.
  ///
  /// What it buys the producer is the inference: `Acked<M>` carries the message it was opened
  /// with, so `feed.give_acked(open)?.receipt()` projects through this impl with no turbofish and no
  /// node named — a producer cannot name the consumer of its own edge, and always knows what it
  /// gave.
  ///
  /// # It is a SEPARATE impl and not a member of [`declared`](Self::declared), on purpose
  ///
  /// Every seat in the facts trait is a fact EVERY declaration has, which is why they can live in one
  /// impl a root reads through one projection. A receipt is a fact almost no declaration has — a
  /// handful of asked-for messages in a corpus of a hundred — so folding it in would give every
  /// silent declaration a member to fill, and the only thing it could fill it with is a stand-in for
  /// *not applicable*. `Receipts` is the opt-in sibling instead: the word emits an impl, and silence
  /// emits NOTHING, so a message nobody waits on carries no line, no seat and no bound.
  ///
  /// # The path is the AUTHOR'S, verbatim, and that is what makes the refusal land at the word
  ///
  /// Nothing here resolves it — the type is written into the impl as the declaration spelled it, and
  /// [`syn::LitStr::parse`] has already respanned every token of that path onto the string literal.
  /// So a `receipt = "media::NoSuchId"` is `E0412` with the caret on the string the author wrote,
  /// rather than a resolution failure somewhere inside an expansion.
  pub(super) fn receipts(&self) -> Option<proc_macro2::TokenStream> {
    let receipt = self.receipt.as_ref()?;
    let record = &self.record;
    let receipts = self.framework(&["operator"], "Receipts");
    let doc = leading(&format!(
      "A [`{record}`] wrote `receipt = \"…\"`, so an acked give OF ONE is answered with this type — \
       what a consumer states through `Emitter::receipt_of::<{record}>` and what the producer's \
       `Acked::receipt` reads back, neither of them naming it twice."
    ));
    Some(quote! {
      #[automatically_derived]
      impl #receipts for #record {
        #[doc = #doc]
        type Receipt = #receipt;
      }
    })
  }

  /// The MODE WORD's runtime half — the mode this declaration chose, as the SEAT a mount binds on.
  ///
  /// The `teardown` word's crossing verbatim, one axis over: the word is read by THIS macro, the
  /// root that mounts the node cannot see it, and a member of the facts trait is how the fact
  /// travels.
  ///
  /// # ONE line at both arms, because the mode has ONE seat
  ///
  /// It used to be two at the awaited arm — the type, plus a `const SYNC` in the shape a root's
  /// fold reads. The const is gone and nothing was lost with it: a fold reads
  /// `<Node as Driven<<Node as Declared>::Mode>>::SYNC`, which is this type picking the blanket row
  /// and that row answering. Two members stating one fact is a pair an emission could come to write
  /// inconsistently; one member cannot.
  ///
  /// The type cannot be defaulted the way the const was: associated-type defaults are not stable,
  /// so every impl states its mode in as many words and a bare declaration emits `type Mode =
  /// Block;` rather than nothing.
  ///
  /// What the mount does with the type is BIND it — `O: Driven<<O as Declared>::Mode>` — which is
  /// what stops the word from ever being a claim the body contradicts: a declaration that says
  /// `async` over a blocking body asks for a `Driven<Async>` row nothing filled, and is `E0277` at
  /// the mount.
  fn declared_mode(&self) -> proc_macro2::TokenStream {
    let record = &self.record;
    // WHICH PAIR the mode indexes. The two words are on two axes and they multiply: `stream` picks
    // the pair, `async` picks the half, and the SEAT is one either way — a mode is which half of
    // whichever pair a declaration chose, so the streaming node states `Block` and `Async` in
    // exactly the same words a buffered one does. Only the sentence differs, and it differs because
    // the trait a reader is being sent to differs.
    let (verb, blocking, awaited, row) = if self.streaming.is_some() {
      (
        "run",
        "a `StreamOperator`",
        "an `AsyncStreamOperator`",
        "Streams",
      )
    } else if self.autonomous.is_some() {
      (
        "run",
        "an `AutonomousOperator`",
        "an `AsyncAutonomousOperator`",
        "Runs",
      )
    } else {
      ("accept", "an `Operator`", "an `AsyncOperator`", "Driven")
    };
    if self.asynchronous.is_none() {
      let doc = leading(&format!(
        "A [`{record}`] wrote no mode word, so its `{verb}` is the blocking face's — {blocking} \
         body, called by either engine and answering without a future."
      ));
      let block = self.framework(&["operator"], "Block");
      return quote! {
        #[doc = #doc]
        type Mode = #block;
      };
    }
    let mode_doc = leading(&format!(
      "A [`{record}`] wrote `async`, so its `{verb}` is the awaited face's — {awaited} body, \
       driven by `block_on` on the thread engine and awaited on the async one. A root folding its \
       mounts' syncness folds the `false` this mode's `{row}` row carries."
    ));
    let asynchronous = self.framework(&["operator"], "Async");
    quote! {
      #[doc = #mode_doc]
      type Mode = #asynchronous;
    }
  }

  /// The `stream` word's runtime half — the PAIR this declaration's body wears, as the seat the
  /// facts trait carries.
  ///
  /// [`declared_mode`](Self::declared_mode)'s twin one axis over, and the same shape for the same
  /// reason: the root that mounts this node cannot see the word, so the fact travels as a member of
  /// the facts trait and the root's one emitted line names `Worn<Pair, Mode>`.
  ///
  /// # ONE line at both arms, because the seat has NO DEFAULT
  ///
  /// This shipped as `const STREAMS: bool = true`, emitted only at the `stream` arm and left to the
  /// trait's own default at the bare one — the `teardown` word's economy, borrowed. The design-law
  /// audit refused it: *no const ever states a mode*, and a defaulted const is the one member an
  /// author can leave WRONG, because the default stands silently and nothing checks it against the
  /// body. The seat is a TYPE now and associated-type defaults are not stable, so both arms state
  /// their pair in as many words — which is also what makes a hand-written node's escape hatch one
  /// line rather than a silence.
  ///
  /// # THREE ARMS, because the axis is a VOCABULARY
  ///
  /// `autonomous` seats the third value, and the arm is the second one's verbatim: a word this
  /// macro already reads, a type the root's emission already names through the seat, and no change
  /// anywhere else. A `const STREAMS: bool` could not have taken a third value at all — which is
  /// the correction above, cashed.
  fn declared_pair(&self) -> proc_macro2::TokenStream {
    let record = &self.record;
    if self.autonomous.is_some() {
      let doc = leading(&format!(
        "A [`{record}`] wrote `autonomous`, so its body wears the AUTONOMOUS kind — the node owns \
         its own loop over its inbound edges, its downstream set and its stop, and what mounts it \
         is `Blueprint::autonomous` rather than `Blueprint::node`."
      ));
      let autonomous = self.framework(&["drive"], "Autonomous");
      return quote! {
        #[doc = #doc]
        type Pair = #autonomous;
      };
    }
    if self.streaming.is_none() {
      let doc = leading(&format!(
        "A [`{record}`] wrote no `stream`, so its body wears the BUFFERED pair — an `accept` per \
         delivery, mounted at `Blueprint::node`."
      ));
      let buffered = self.framework(&["drive"], "Buffered");
      return quote! {
        #[doc = #doc]
        type Pair = #buffered;
      };
    }
    let doc = leading(&format!(
      "A [`{record}`] wrote `stream`, so its body wears the STREAMING pair — one delivery is a \
       whole life, streamed out through a bounded `Feed`, and what mounts it is `Blueprint::stream` \
       rather than `Blueprint::node`."
    ));
    let streaming = self.framework(&["drive"], "Streaming");
    quote! {
      #[doc = #doc]
      type Pair = #streaming;
    }
  }

  /// The `emits` word's WIRING half — the downstream set this node publishes through, as the third
  /// seat the facts trait carries.
  ///
  /// [`declared_pair`](Self::declared_pair)'s twin one axis over, and the same shape for the same
  /// reason: the root that mounts this node cannot see how many products its declaration named, so
  /// the fact travels as a member of the facts trait and the wiring walk reads
  /// `<N as Declared>::Wires<Out>`.
  ///
  /// # TWO ARMS, and the parameter is what makes the ordinary one writable at all
  ///
  /// A declaration that emits ONE thing publishes through the framework's own `Downstream<Out>` —
  /// one product over N edges, the fan-out itself — and the emission cannot NAME that `Out`: it is
  /// the operator's associated type, and this macro runs over declarations whose body may not be
  /// written yet (a store record has no face at all). So the seat takes the product as a parameter
  /// and this arm answers `Downstream<O>`, which names nothing of the node's.
  ///
  /// A declaration that wrote `emits = […]` answers its OWN emitted set — one edge list per
  /// product, typed at the products the word named — and ignores the parameter, because those types
  /// are already written into the set's slots.
  ///
  /// # It is what struck the `Clone` off the streamed sum
  ///
  /// A node's own set takes no fan-out copy, so a STREAMING multi-product declaration's `Out` sum no
  /// longer derives one — see [`product_faces`](RecordModel::product_faces), where the arm that
  /// decides is the same `stream` word this one reads.
  fn declared_wires(&self) -> proc_macro2::TokenStream {
    let record = &self.record;
    if self.products.as_ref().is_some_and(|p| p.is_sum()) {
      let set = default_downstream_name(record);
      let doc = leading(&format!(
        "A [`{record}`] wrote `emits = […]`, so it publishes through its own [`{set}`] — one edge \
         list per declared product, each consumer on the edge it opened, and as many per product as \
         subscribed. The product parameter is the ONE-product road's and is unread here: this set's \
         slots are typed at the products the word named."
      ));
      return quote! {
        #[doc = #doc]
        type Wires<__INGRAPH_OUT__> = #set;
      };
    }
    let downstream = self.framework(&["drive"], "Downstream");
    let doc = leading(&format!(
      "A [`{record}`] emits ONE thing, so it publishes through the framework's own fan-out set — N \
       edges of that one product, the copy taken at the set rather than asked of any driver."
    ));
    quote! {
      #[doc = #doc]
      type Wires<__INGRAPH_OUT__> = #downstream<__INGRAPH_OUT__>;
    }
  }

  /// The `attributed` word's WIRING half — the projection this node attributes its outputs
  /// through, as the fourth seat the facts trait carries.
  ///
  /// [`declared_wires`](Self::declared_wires)'s twin one member over, and the same shape for the
  /// same reason: the root that mounts this node cannot ask whether the node's output is a declared
  /// record — it sees a type it can name and cannot test — so the fact travels as a member of the
  /// facts trait and `Wiring::resident` installs whatever the seat names.
  ///
  /// # TWO ARMS, and the parameter is what makes the attributed one writable at all
  ///
  /// The projection for a node emitting `Out` is `RootProjection<Out>`, and this emission cannot
  /// NAME that `Out`: it is the operator's associated type, and this macro runs over declarations
  /// whose body may not be written yet. So the seat takes the product as a parameter and the
  /// `attributed` arm answers `RootProjection<O>`, which names nothing of the node's — the
  /// [`declared_wires`](Self::declared_wires) device verbatim.
  ///
  /// A declaration that wrote NO word answers `()` and ignores the parameter, which is the whole of
  /// what *costs nothing for a node that attributes nothing* means: the empty program, a zero-sized
  /// field, and a bound satisfied for every payload there is.
  ///
  /// # The RECORD's own projection impl is emitted either way, and that is deliberate
  ///
  /// [`root_projection`](RecordModel::root_projection) rides on every declaration, because having a
  /// root is a property of having a key rather than a thing a declaration opts into. What this word
  /// chooses is not whether the projection EXISTS but whether this node INSTALLS one — a node may
  /// emit somebody else's record, or a `String`, and the two questions are not the same.
  fn declared_attribution(&self) -> proc_macro2::TokenStream {
    let record = &self.record;
    if !self.attributed {
      let doc = leading(&format!(
        "A [`{record}`] wrote no `attributed`, so it attributes its outputs to nothing — the unit \
         projection, whose `Attributes` impl is the empty program and whose value is zero-sized. \
         Its observations stay counter-grade, which is the shipped posture for every node that \
         emits a payload with no declared root. The product parameter is the attributed road's and \
         is unread here."
      ));
      return quote! {
        #[doc = #doc]
        type Attribution<__INGRAPH_OUT__> = ();
      };
    }
    let projection = self.framework(&["drive"], "RootProjection");
    let doc = leading(&format!(
      "A [`{record}`] wrote `attributed`, so the launch installs the framework's root projection \
       over whatever this node emits — the key's FIRST column, read off the `Attributes` impl that \
       output's own declaration emitted. An output no record declared has no such impl, and the \
       mount is where that is refused."
    ));
    quote! {
      #[doc = #doc]
      type Attribution<__INGRAPH_OUT__> = #projection<__INGRAPH_OUT__>;
    }
  }

  /// The `tracing(level = …)` word's runtime half — the level this node's framework spans open at.
  ///
  /// **BEHIND THE GATE, which is the word's whole ruled posture.** The word parses in every build
  /// and reaches the model in every build: a declaration is a fixed text, and a level nobody ships
  /// is refused at the token wherever it was written. What rides `ingraph`'s own `tracing` feature
  /// is the EMISSION, and this is it — with the gate shut the const is discarded unparsed, and
  /// `Declared::TRACING`'s own default is what nothing then reads.
  ///
  /// A declaration that wrote NO word emits nothing here either, which is the economy the `teardown`
  /// word keeps one function down: the trait's default states `Info`, so the ONE place the default
  /// lives is the trait, and a silent node cannot come to disagree with it.
  ///
  /// The gate is a MACRO and not a `#[cfg]`, for the reason every gate in this emitter is: a
  /// `#[cfg(feature = "tracing")]` written inside an expansion asks whether the DECLARING crate has
  /// a feature by that name, which is a different manifest and usually no feature at all.
  fn declared_tracing(&self) -> Option<proc_macro2::TokenStream> {
    let level = self.tracing?;
    let record = &self.record;
    let gate = self.framework(&["gate"], "if_tracing");
    let ty = self.framework(&["drive"], "TracingLevel");
    let variant = level.variant();
    let doc = leading(&format!(
      "A [`{record}`] wrote `tracing(level = {word})`, so its framework spans open at that level.",
      word = level.as_str(),
    ));
    Some(quote! {
      #gate! {
        #[doc = #doc]
        const TRACING: #ty = #ty::#variant;
      }
    })
  }

  /// The `teardown` word's runtime half — the fact, and the goodbye it names.
  ///
  /// **THIS IS THE ONLY PLACE THE WORD CAN BE CASHED.** A root's derive mounts this node and cannot
  /// see the word; the ignition walks a whole catalog with one line per mount and cannot name
  /// `AsyncTeardown` for the one declaration that wrote it. So the word crosses as a defaulted member of
  /// the facts trait: the node's own derive, which is the one party that reads the word AND can name
  /// the impl, writes the override, and everything downstream stays generic over `Declared` alone.
  ///
  /// A declaration without the word emits NOTHING here, which is the whole of what *zero cost for
  /// unmarked nodes* means: the trait's own default states `false` and drops, and no channel,
  /// allocation or turn signal exists for a node that has nothing to say.
  ///
  /// `Box::pin` is written at the CONCRETE type, so a goodbye is boxed where its type is still known
  /// — the same principle one organ up, where the async engine's road boxes at the body rather than
  /// in the chain.
  fn declared_goodbye(&self) -> Option<proc_macro2::TokenStream> {
    if !self.teardown {
      return None;
    }
    let record = &self.record;
    let goodbye = self.framework(&["drive"], "Goodbye");
    let teardown = self.framework(&["drive"], "AsyncTeardown");
    let fact_doc = leading(&format!(
      "A [`{record}`] wrote `teardown`, so its value is enrolled in the shutdown's goodbye chain."
    ));
    let goodbye_doc = leading(&format!(
      "A [`{record}`]'s own `AsyncTeardown` impl, boxed for the chain to drive."
    ));
    Some(quote! {
      #[doc = #fact_doc]
      const TEARDOWN: bool = true;

      #[doc = #goodbye_doc]
      #[inline]
      fn goodbye(self) -> #goodbye {
        ::std::boxed::Box::pin(<#record as #teardown>::teardown(self))
      }
    })
  }

  /// One `Upstream` per declared upstream, in the order the declaration wrote them.
  ///
  /// The three spellings meet here. `subscribe(…)`'s entries carry the per-upstream words and are the
  /// richest; `subscribe = "…"` is one bare entry; a fusion's `upstream(…)` entries name upstreams
  /// with no words of their own. A declaration writes at most one of the three — the grammar refuses
  /// the pairs — so the chain below reads whichever is there.
  fn declared_sources(&self) -> Vec<proc_macro2::TokenStream> {
    if let Some(subscription) = self.subscriptions.as_ref() {
      return subscription
        .upstreams
        .iter()
        .map(|upstream| self.declared_source(upstream))
        .collect();
    }
    self
      .subscribe
      .iter()
      .chain(self.upstreams.iter().flat_map(Upstreams::upstreams))
      .map(|node| self.bare_source(node))
      .collect()
  }

  /// A `upstream(…)` entry, with every per-upstream word it wrote.
  fn declared_source(&self, upstream: &Upstream) -> proc_macro2::TokenStream {
    let listen = upstream.changes.as_ref().map(|feed| self.changes(feed));
    let channel = upstream.channel.map(|spec| self.channelled(spec));
    let bare = self.bare_source(&upstream.node);
    quote!(#bare #listen #channel)
  }

  /// The entry with no words on it — the shape all three spellings share.
  fn bare_source(&self, node: &syn::Path) -> proc_macro2::TokenStream {
    let upstream = self.framework(&["drive"], "Upstream");
    // The path as the DECLARATION wrote it, for the sentence a refusal makes. `to_token_stream`
    // rather than a hand-walk of the segments: what a reader wants back is what they typed.
    let named = quote!(#node).to_string();
    quote!(#upstream::of::<#node>(#named))
  }

  /// `changes(<db>)` / `changes(<db>(external))` as the listen arm it means.
  ///
  /// **The bridge the `changes` word was waiting for.** The word has been parsed, modelled and spent
  /// by the runtime since it landed, and nothing carried a DECLARATION's listen arm into a launch —
  /// so the feeder check only ever fired for a hand-built plan. This is what makes it fire for an
  /// emitted graph: a declared `changes(<db>)` states [`Feeder::InGraph`], and the validate walk's
  /// three-road refusal starts answering for declarations.
  fn changes(&self, feed: &ChangesFeed) -> proc_macro2::TokenStream {
    let listen = self.framework(&["drive"], "Listen");
    let feeder = self.framework(&["drive"], "Feeder");
    let arm = if feed.external {
      quote!(External)
    } else {
      quote!(InGraph)
    };
    quote!(.listening(#listen::Changes(#feeder::#arm)))
  }

  /// `channel = bounded(n)` / `channel = unbounded` as the depth its author shipped.
  fn channelled(&self, spec: ChannelOptions) -> proc_macro2::TokenStream {
    let channel = self.framework(&["drive"], "ChannelOptions");
    let arm = match spec {
      ChannelOptions::Bounded(capacity) => quote!(#channel::Bounded(#capacity)),
      ChannelOptions::Unbounded => quote!(#channel::Unbounded),
    };
    quote!(.channelled(#arm))
  }
}