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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
//! The POLLING emission: the context ONE CLOCK's ticks are lent, the lending that holds a node's
//! whole apparatus, and the sweep entry each `light` clock seats.
//!
//! `poll(<name>, every = "…", write = "media::Media", handler = "app::Scraper", async(inline))`
//! becomes four things:
//!
//!   * **`<Node><Poll>Grants<…>`** — one context PER GRANTING CLOCK, holding one handle per grant
//!     that entry wrote, under the granted node's MOUNT NAME.
//!   * **`impl AsyncLands<Granted>` and `impl Lands<Granted>` for `<Node><Poll>Grants<…>`**, once
//!     per grant per family, forwarding to the handle that grant holds. A tick calls the framework's
//!     own write socket ON THE CONTEXT.
//!   * **`<Node>Polling<…>`** — the LENDING: one field per granting clock, per mounted citizen, per
//!     detached executor and per at-most-one cell, and the value a deployment hands
//!     `Resident::polling`.
//!   * **`<Node>Sweeps<…>`** — the SWEEP TRAIT, one entry per `light` clock, plus the `Seats` impl
//!     that routes a tick's position to whatever owns it.
//!
//! # The THRESHOLD is has-POLLS, and the split is by PRESENCE
//!
//! Every polling node gets an apparatus, because every clock now declares an execution role and
//! something has to route it. What varies is what the apparatus HOLDS: a node that granted nothing
//! and mounted nothing lends `<Node>Polling(())` — the empty-struct law — and a node whose every
//! clock mounts a citizen emits NO sweep trait at all, because there is no body left for an author
//! to write.
//!
//! An entry that wrote `handler = "…"` routes to its citizen and does NOT enter `<Node>Sweeps`; an
//! entry that wrote `light` is a `<Node>Sweeps` method. That is the whole of the split, entry by
//! entry — every entry names one of the two words, so the split is read off a declaration rather
//! than inferred from a silence — and a node may mix the two freely.
//!
//! # The TEETH are an UNSATISFIED BOUND, PER CLOCK, and that is the whole design
//!
//! There is no `AsyncLands<Transcript>` impl for the context of a clock that did not grant it, so a tick
//! that reaches for one is `E0277` — *the trait bound `ReaperHourlyGrants<…>: AsyncLands<Transcript>` is
//! not satisfied* — reported at the line that reached, and no runtime check anywhere answers the
//! question.
//!
//! The refusal NAMES THE CLOCK THAT DOES HOLD IT, and the naming law is why: `rustc` lists the types
//! that satisfy the bound beside the one that does not, so `ReaperNightlyGrants<…>` appears in the
//! sentence and the poll's own word is inside it. Nothing is asserted about the sentence that the
//! declaration did not put in the type's name.
//!
//! # BOTH WRITE FAMILIES, each conditional on the handle
//!
//! A sync tick has no await to spend, so it reaches a store through `Lands` and an async one
//! through `AsyncLands`. Which roads a given handle has is the deployment ENGINE's fact — a tantivy
//! writer answers without awaiting, an sqlx pool does not — so the emission forwards both families
//! and each forward is bounded on the handle's own impl. A `block` entry over an async-only handle
//! is `E0277` at the line that wrote, with `Lands`' own `on_unimplemented` naming both
//! roads. None of it is decidable in the grammar, which is why the grammar decides none of it.
//!
//! # Least privilege is STRUCTURAL
//!
//! Deleting a `poll(…)` entry deletes its grants, because the grants were never anywhere else. A
//! store two clocks both write is written twice — the ruling's explicit repetition over implicit
//! sharing — and mints two contexts, each holding its own handle: the two clocks can be given two
//! different handles onto one store, and neither can reach the other's.
//!
//! # A bound is NAMEABLE and COMPOSABLE where an absent method was neither
//!
//! A helper written once and called from any sweep spells what it needs —
//!
//! ```ignore
//! async fn archive<C>(ctx: &mut C) where C: AsyncLands<Media> + AsyncLands<KeyframeVec> { … }
//! ```
//!
//! — and every context granted both satisfies it, whichever clock of whichever declaration minted
//! it. Under per-clock contexts that bound says something sharper than it did: a helper demanding
//! two stores is callable only from a clock granted BOTH, which is the correctness the word buys and
//! not a limitation of it.
//!
//! # The handle is the AUTHOR's type, and the bound is stated where it is SPENT
//!
//! One type parameter per grant, and the STRUCT states no bound on any of them: what a write handle
//! IS belongs to the party that opened it, and a context is built, held and printed by parties that
//! never write through it. The `AsyncLands` bound sits on the forwarding impl instead — the one place it
//! buys anything — so a handle satisfies it exactly where a tick spends it.
//!
//! # There is ONE write verb, and this is not a second one
//!
//! The forward is the socket, not a lane. `AsyncLands`' own note divides the two: a SOCKET answers *which
//! of these items are durable* over a batch the framework handed it, and an ENGINE answers *this
//! entry is written*. A grant hands the socket through, so the composition a node's write already
//! took — lane calls engine — is the composition a tick's write takes.
//!
//! # ONE `Info` AND ONE `Error` FOR THE NODE, and the citizens join it
//!
//! A resident has one observation stream and one effect table, so `<Node>Sweeps` carries one pair
//! for the whole node — and an INLINE mounted citizen is bound to that same pair on the route's own
//! impl, which makes a disagreement `E0271` at the deployment naming both types. A DETACHED citizen
//! is exempt and structurally so: its answer never comes back to the seat, so there is nothing for
//! it to agree with.
//!
//! Where a node is ALL-MOUNTED the pair has no sweep trait to come from, so the FIRST inline citizen
//! anchors it and the rest are bound to that. Where every clock detaches there is nothing to answer
//! at all, and the pair is `()` and `Infallible`.
//!
//! # Why the runtime seam is implemented BY THE LENDING
//!
//! Because the alternative does not compile. The derive sits on the RECORD and the operator is
//! another type entirely, so the bridge from a tick's position to a per-clock entry can only be
//! written as a blanket over the operator — and `impl<O> Seats<ReaperPolling<…>> for O` is `E0210`,
//! the uncovered type parameter standing before the first local type. The lending is local, so the
//! impl written the other way round is legal, and that is why `Seats`' receiver is the context and
//! its argument is the operator.
//!
//! What TYPES the grant instead is the launch: `Declared::GRANTS` names each granted node by
//! identity AND by the clock that holds it, and the join refuses a grant on a node the root does not
//! mount or on one that keeps no store. The two halves are the whole check — an unsatisfied bound
//! here, a named refusal there.

use quote::{format_ident, quote};

use crate::{
  emit::leading,
  model::{
    Grant, PollEntry, PollMode, RecordModel, default_polling_name, default_sweeps_name,
    poll_grants_name,
  },
};

/// ONE of a node's clocks, as the polling emission sees it — the SEAT a tick of that clock lands at.
///
/// EVERY clock gets one, granting or not and mounted or not, and that is not tidiness: the lending
/// owns a polling node's whole sweep seam, so a clock left off this list would be a tick with
/// nowhere to go. What varies is only what the seat HOLDS.
struct Seat<'a> {
  /// Its POSITION in the whole schedule — the number a tick carries, and the route's own key.
  position: usize,
  /// The entry itself — its minted name, its variant word, its mode and its mount.
  entry: &'a PollEntry,
  /// What this clock is lent, or `None` where its entry wrote no `write` word.
  lent: Option<Lent<'a>>,
  /// The field its mounted citizen sits in, or `None` where the entry mounted none.
  handler: Option<syn::Ident>,
  /// The type parameter and field its executor takes, where the mode detaches.
  executor: Option<Executor>,
  /// The field its at-most-one cell sits in — the sync-detached modes that did not write
  /// `concurrent`, and nothing else.
  cell: Option<syn::Ident>,
}

/// A GRANTING clock's own half: what it was granted, and the types that carry it.
struct Lent<'a> {
  /// Its grants, in the order the entry wrote them.
  grants: &'a [Grant],
  /// The type parameter each grant's handle takes, in the same order.
  handles: Vec<syn::Ident>,
  /// This clock's own context type.
  context: syn::Ident,
}

/// A DETACHED clock's executor: the parameter a deployment may displace, and the field it sits in.
struct Executor {
  /// The type parameter — `<Poll>Executor`, defaulted to the shipped citizen where the word selects
  /// one.
  parameter: syn::Ident,
  /// The field the value sits in.
  field: syn::Ident,
  /// Whether it is the ASYNC seam. The two differ in the bound the route states and in whether the
  /// parameter can carry a default: `spawn` and `rayon` name shipped citizens, and `async(spawn)`
  /// names a runtime the framework cannot guess.
  asynchronous: bool,
  /// The shipped citizen this word selects, where the word selects one.
  shipped: Option<&'static str>,
}

/// The framework paths the route spells, resolved once at the top and handed down.
///
/// A struct rather than a dozen arguments because they travel together and are read together: every
/// one of them is `#krate::__private::drive::…`, and the shelf is the one thing an emitted path may
/// depend on.
struct Vocabulary {
  seats: proc_macro2::TokenStream,
  source: proc_macro2::TokenStream,
  swept: proc_macro2::TokenStream,
  async_tick: proc_macro2::TokenStream,
  tick: proc_macro2::TokenStream,
  spawn: proc_macro2::TokenStream,
  async_spawn: proc_macro2::TokenStream,
}

impl RecordModel {
  /// The polling expansion: the per-clock contexts, the lending and the sweep trait at module
  /// scope, and their doors for the anonymous const.
  pub(super) fn polling_face(&self) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    // Nothing at all for a node with no clock. Every POLLING node gets an apparatus, which is the
    // threshold the mode words widened: a clock declares where it runs, so there is always
    // something to route even where nothing was granted and nothing was mounted.
    if self.polls.is_none() {
      return Default::default();
    }
    let seats = self.seats();
    let (record, vis) = (&self.record, &self.vis);

    let mut types = proc_macro2::TokenStream::new();
    let mut doors = proc_macro2::TokenStream::new();
    for seat in &seats {
      let (context, sockets) = self.clock_face(seat);
      types.extend(context);
      doors.extend(sockets);
    }

    // The LENDING's parameters: every granting clock's handles in declaration order, then the
    // executors. The ASYNC executors come before the sync ones because only the sync words name a
    // shipped citizen to default to, and a defaulted parameter cannot precede an undefaulted one.
    let parameters = self.parameters(&seats);
    let declaration = self.declared_parameters(&seats, &parameters);
    let lending = default_polling_name(record);
    let fields: Vec<proc_macro2::TokenStream> = seats
      .iter()
      .flat_map(|seat| self.lending_fields(seat))
      .collect();
    let sealed = fields.is_empty();

    let doc = leading(&format!(
      "What a [`{record}`]'s ticks are LENT — one clock's context per `poll(…)` entry that wrote a \
       `write` word, the citizen each mounted entry runs, and the executor each detached one runs \
       on."
    ));
    let seat_note = leading(
      "A tick reaches ONE of these seats, the one its own clock owns, and the runtime is what \
       picks: a sweep never sees this value. A clock that granted nothing and mounted nothing holds \
       no field here and needs none. What it all buys is that deleting a clock deletes its grants \
       and its citizen, because they were never anywhere else.",
    );
    let sealed_note = leading(
      "SEALED and EMPTY, because no clock of this node was granted a store or mounted a citizen — \
       there is no state a deployment could put here and none it could take out. It exists so that \
       `Resident::polling` takes the same kind of value from every polling node, and so that a \
       later `write` or `handler` word is a field rather than a new type.",
    );

    types.extend(if sealed {
      quote! {
        #[doc = #doc]
        #[doc = ""]
        #[doc = #sealed_note]
        #[derive(::core::fmt::Debug, ::core::default::Default)]
        #vis struct #lending(());
      }
    } else {
      {
        let declared = angled(&declaration);
        quote! {
          #[doc = #doc]
          #[doc = ""]
          #[doc = #seat_note]
          #vis struct #lending #declared {
            #(#fields)*
          }
        }
      }
    });
    if !sealed {
      doors.extend(self.lending_debug(&lending, &seats, &parameters));
    }
    // The SWEEP TRAIT is a MODULE-SCOPE item and not a door, because an author implements it: a
    // trait inside the anonymous const would be a seam nobody outside the expansion could name.
    types.extend(self.sweep_trait(&seats));
    doors.extend(self.lending_doors(&lending, &seats, &parameters, sealed));
    (types, doors)
  }

  /// EVERY clock this node declares, in declaration order, each with its position and whatever its
  /// words asked the lending to hold.
  ///
  /// All of them, not only the granting ones, because the sweep trait and the route are the node's
  /// WHOLE sweep seam: a clock left off this list would be a tick the route could not answer.
  ///
  /// The handle parameter names are minted ACROSS the whole node rather than per clock, because they
  /// all end up on the lending: two clocks both granted `Media` would otherwise both want
  /// `MediaHandle` there. So a name is qualified by the clock's own word the moment it would repeat,
  /// and left bare where it does not — the common declaration reads `ReaperPolling<MediaHandle>` and
  /// only a graph that really does grant one store twice pays for the distinction.
  fn seats(&self) -> Vec<Seat<'_>> {
    let Some(polls) = self.polls.as_ref() else {
      return Vec::new();
    };
    let mut minted: Vec<syn::Ident> = Vec::new();
    let mut seats = Vec::with_capacity(polls.entries.len());
    for (position, entry) in polls.entries.iter().enumerate() {
      let lent = entry.grants.as_ref().map(|grants| {
        let grants = grants.grants.as_slice();
        let handles = grants
          .iter()
          .map(|grant| {
            let bare = handle(grant, None);
            let name = if minted.contains(&bare) {
              handle(grant, Some(&entry.variant))
            } else {
              bare
            };
            minted.push(name.clone());
            name
          })
          .collect();
        Lent {
          grants,
          handles,
          context: poll_grants_name(&self.record, &entry.variant),
        }
      });
      let handler = entry
        .mounted()
        .then(|| format_ident!("{}_handler", entry.name));
      let executor = entry.mode.detached().then(|| Executor {
        parameter: format_ident!("{}Executor", entry.variant),
        field: format_ident!("{}_executor", entry.name),
        asynchronous: !entry.mode.blocking(),
        shipped: match entry.mode {
          PollMode::Spawn => Some("Thread"),
          PollMode::Rayon => Some("Rayon"),
          _ => None,
        },
      });
      let cell = (entry.mode.lapses() && !entry.concurrent)
        .then(|| format_ident!("{}_in_flight", entry.name));
      seats.push(Seat {
        position,
        entry,
        lent,
        handler,
        executor,
        cell,
      });
    }
    seats
  }

  /// The lending's type parameters, in the order they are declared.
  fn parameters<'a>(&self, seats: &'a [Seat<'a>]) -> Vec<&'a syn::Ident> {
    let mut parameters: Vec<&syn::Ident> = seats
      .iter()
      .filter_map(|seat| seat.lent.as_ref())
      .flat_map(|lent| lent.handles.iter())
      .collect();
    let engines = || seats.iter().filter_map(|seat| seat.executor.as_ref());
    parameters.extend(
      engines()
        .filter(|engine| engine.asynchronous)
        .chain(engines().filter(|engine| !engine.asynchronous))
        .map(|engine| &engine.parameter),
    );
    parameters
  }

  /// The same list as the STRUCT declares it — with the shipped citizen as each sync executor's
  /// default, which is what makes displacing one a matter of naming another type.
  fn declared_parameters(
    &self,
    seats: &[Seat<'_>],
    parameters: &[&syn::Ident],
  ) -> Vec<proc_macro2::TokenStream> {
    parameters
      .iter()
      .map(|parameter| {
        let shipped = seats
          .iter()
          .filter_map(|seat| seat.executor.as_ref())
          .find(|engine| &&engine.parameter == parameter)
          .and_then(|engine| engine.shipped);
        match shipped {
          Some(shipped) => {
            let citizen = self.framework(&["drive"], shipped);
            quote!(#parameter = #citizen)
          }
          None => quote!(#parameter),
        }
      })
      .collect()
  }

  /// ONE GRANTING clock's context and its sockets.
  fn clock_face(&self, seat: &Seat<'_>) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let (record, vis) = (&self.record, &self.vis);
    let Some(Lent {
      grants,
      handles,
      context,
    }) = seat.lent.as_ref()
    else {
      return Default::default();
    };
    let name = &seat.entry.name;

    let doc = leading(&format!(
      "What a [`{record}`]'s `{name}` ticks are LENT — one write socket per grant the `{name}` \
       entry wrote, holding the handle that grant reaches."
    ));
    let teeth_note = leading(&format!(
      "A store the `{name}` entry did NOT grant has no `AsyncLands` impl here, so a tick reaching for \
       one is `E0277` at the line that reached — INCLUDING a store a sibling clock was granted, \
       which is the whole of what seating the word in the entry buys. The capability is a bound \
       this type satisfies rather than anything checked at run time."
    ));
    let held_note = leading(
      "One type parameter per grant, in the order the entry granted them, because what a write \
       handle IS belongs to whoever opened it. The bound sits on the forwarding impl, where it is \
       spent. The runtime holds this value inside the node's lending and lends it per tick; the \
       node struct holds only its own state.",
    );
    let clone_note = leading(
      "`Clone` is derived so that a DETACHED clock can be handed an owned context per tick. The \
       bound falls on the handles, so a context whose handles are not cloneable simply has no \
       `Clone` — and a detached mode over it is refused at the declaration that wrote the word.",
    );
    let fields = grants.iter().zip(handles).map(|(grant, handle)| {
      let mount = grant.mount.safe();
      let doc = leading(&format!(
        "The handle `{}`'s store is written through.",
        path_text(&grant.node),
      ));
      quote! {
        #[doc = #doc]
        #mount: #handle,
      }
    });

    let types = quote! {
      #[doc = #doc]
      #[doc = ""]
      #[doc = #teeth_note]
      #[doc = ""]
      #[doc = #held_note]
      #[doc = ""]
      #[doc = #clone_note]
      #[derive(::core::fmt::Debug, ::core::clone::Clone)]
      #vis struct #context<#(#handles),*> {
        #(#fields)*
      }
    };

    let taken = grants.iter().zip(handles).map(|(grant, handle)| {
      let mount = grant.mount.safe();
      quote!(#mount: #handle)
    });
    let held = grants.iter().map(|grant| {
      let mount = grant.mount.safe();
      quote!(#mount,)
    });
    let new_doc = leading(&format!(
      "Hold these handles for a [`{record}`]'s `{name}` ticks, in the order the entry granted \
       them.\n\nBuilding one is the moment a deployment decides what each of this clock's grants \
       actually reaches — and two clocks granted one store build two of these, so they may be given \
       two different handles onto it."
    ));
    let sockets = self.clock_sockets(context, grants, handles);

    let doors = quote! {
      impl<#(#handles),*> #context<#(#handles),*> {
        #[doc = #new_doc]
        // One argument per grant, so a clock granted eight stores passes the lint's seven. The
        // arity is the `write` word's, and a declaration is not refactored by a lint.
        #[allow(clippy::too_many_arguments)]
        #[inline]
        #[must_use]
        #vis const fn new(#(#taken),*) -> Self {
          Self { #(#held)* }
        }
      }

      #sockets
    };
    (types, doors)
  }

  /// One `AsyncLands<Granted>` and one `Lands<Granted>` forward per grant — the grant, as the two
  /// bounds a tick can spend.
  ///
  /// BOTH FAMILIES, each conditional on the handle's own impl, because which of the two roads a
  /// store has is the deployment ENGINE's fact and not the declaration's. A tantivy-backed row
  /// answers without awaiting and a pool-backed one does not; the grammar cannot tell, so it decides
  /// nothing and the TYPE layer adjudicates at the line that wrote.
  ///
  /// There is NO accessor. A grant hands the socket through rather than handing the handle out,
  /// which is the read lane's shape one arm over — `Serves` is a capability an arm holds and calls,
  /// and nothing on that side lends its lane to a caller either. Two doors onto one grant would be
  /// two vocabularies for one act, and the second would be the weaker: a `&Handle` getter is a
  /// method on ONE context type, so no helper could ever ask for it by name.
  ///
  /// The handle's bound is stated HERE and not on the struct, which is where it buys something: a
  /// context is built, moved and printed by parties that never write through it, and only this impl
  /// needs to know that the handle can land.
  ///
  /// The associated error is the HANDLE's. Nothing is wrapped, because nothing is added — the
  /// forward is the same call one field in, and inventing an error type here would put a name the
  /// deployment never wrote between it and its own store.
  fn clock_sockets(
    &self,
    context: &syn::Ident,
    grants: &[Grant],
    handles: &[syn::Ident],
  ) -> proc_macro2::TokenStream {
    let async_lands = self.framework(&["drive"], "AsyncLands");
    let lands = self.framework(&["drive"], "Lands");
    let commit = self.framework(&["drive"], "Commit");
    let sockets = grants.iter().zip(handles).map(|(grant, handle)| {
      let (mount, node) = (grant.mount.safe(), &grant.node);
      let named = path_text(node);
      let doc = leading(&format!(
        "The `write = \"{named}\"` grant, as the write socket this clock's ASYNC ticks call.\n\nA \
         clock that did not grant `{named}` mints no impl, so reaching for it is an unsatisfied \
         bound at the line that reached rather than a permission refused at run time."
      ));
      let blocking_doc = leading(&format!(
        "The `write = \"{named}\"` grant, as the write socket this clock's SYNC ticks call.\n\nIt \
         exists only where the handle a deployment installed can land without awaiting — the \
         engine's own fact — so a `block`, `spawn` or `rayon` tick over an async-only handle is an \
         unsatisfied bound naming both roads."
      ));
      quote! {
        #[doc = #doc]
        impl<#(#handles),*> #async_lands<#node> for #context<#(#handles),*>
        where
          #handle: #async_lands<#node>,
        {
          type Error = <#handle as #async_lands<#node>>::Error;

          #[inline]
          fn land(
            &mut self,
            items: &[#node],
          ) -> impl ::core::future::Future<Output = #commit<Self::Error>> + ::core::marker::Send
          {
            <#handle as #async_lands<#node>>::land(&mut self.#mount, items)
          }
        }

        #[doc = #blocking_doc]
        impl<#(#handles),*> #lands<#node> for #context<#(#handles),*>
        where
          #handle: #lands<#node>,
        {
          type Error = <#handle as #lands<#node>>::Error;

          #[inline]
          fn land(&mut self, items: &[#node]) -> #commit<Self::Error> {
            <#handle as #lands<#node>>::land(&mut self.#mount, items)
          }
        }
      }
    });
    quote!(#(#sockets)*)
  }

  /// The SWEEP TRAIT: **one entry per `light` CLOCK**, ONE `Info` and ONE `Error` for the node.
  ///
  /// A module-scope item, because it is what an AUTHOR implements. It is the framework's own word
  /// one scope down, as `<Node>Due` and `<Node>Channels` are, and it is per node because only the
  /// declaration knows how many clocks there are — a framework trait cannot grow a method per entry.
  ///
  /// # The PRESENCE SPLIT
  ///
  /// A clock that mounted a citizen has no entry here, because its body is not the operator's. A
  /// node whose every clock mounted one emits NO TRAIT AT ALL — the presence law, and it is not
  /// tidiness: an empty trait would be a seam an author is invited to implement and can say nothing
  /// through.
  ///
  /// # The entry's FACE is the mode's
  ///
  /// `block` gives a plain `fn` answering a `Result`; `async(inline)` gives one answering a `Send`
  /// future. The dual-mode law at the emitted seam: what a body's world is, is what the declaration
  /// said, and the signature an author writes against says it back. The detached modes have no entry
  /// here at all, because the grammar refuses them without a mount — the node's own value cannot be
  /// handed to a thread.
  fn sweep_trait(&self, seats: &[Seat<'_>]) -> proc_macro2::TokenStream {
    let (record, vis) = (&self.record, &self.vis);
    let sweeping: Vec<&Seat<'_>> = seats.iter().filter(|seat| !seat.entry.mounted()).collect();
    if sweeping.is_empty() {
      return proc_macro2::TokenStream::new();
    }
    let sweeps = default_sweeps_name(record);
    let generics = angled(&swept_held(seats));
    let answer = quote! {
      impl ::core::future::Future<Output = ::core::result::Result<Self::Info, Self::Error>>
         + ::core::marker::Send
    };
    let entries = sweeping.iter().map(|seat| {
      let name = &seat.entry.name;
      let world = if seat.entry.mode.blocking() {
        "It runs where the driver runs, so its answer is a plain `Result`."
      } else {
        "It is awaited in the driver's own loop."
      };
      let taken = seat.lent.as_ref().map(|lent| {
        let (context, handles) = (&lent.context, &lent.handles);
        quote!(, grants: &mut #context<#(#handles),*>)
      });
      let granted = match seat.lent.as_ref() {
        Some(lent) => format!(
          "Its context lands {} and nothing else.",
          lent
            .grants
            .iter()
            .map(|grant| format!("`{}`", path_text(&grant.node)))
            .collect::<Vec<_>>()
            .join(", ")
        ),
        None => "Its entry granted nothing, so it is lent nothing — a clock that only looks, or \
                 that works through what the node value already holds."
          .to_owned(),
      };
      let doc = leading(&format!(
        "The `{name}` clock came due, and it runs `{}`. {granted}\n\n{world}\n\nNo position is \
         passed, because there is nothing left to tell apart: this entry IS the clock.",
        seat.entry.mode.as_str()
      ));
      if seat.entry.mode.blocking() {
        quote! {
          #[doc = #doc]
          fn #name(&mut self #taken) -> ::core::result::Result<Self::Info, Self::Error>;
        }
      } else {
        quote! {
          #[doc = #doc]
          fn #name(&mut self #taken) -> #answer;
        }
      }
    });
    let sweeps_doc = leading(&format!(
      "What a [`{record}`]'s operator does when one of its `light` clocks comes due — one entry \
       per such clock, each lent that clock's own grants, and a clock that granted nothing lent \
       nothing."
    ));
    let split_note = leading(
      "A clock that wrote `handler = \"…\"` has NO entry here: its body is a citizen the deployment \
       built rather than a method on the node. A node whose every clock mounted one emits no trait \
       at all.",
    );
    let answer_note = leading(
      "ONE `Info` and ONE `Error` for the whole node, because the resident has one observation \
       stream and one effect table. Two clocks answering in two types is not a thing that can be \
       true, so it is not a thing that can be written: a second `type Info` in this impl is \
       `E0201`. An INLINE mounted citizen is bound to this same pair on the route, so it cannot \
       disagree either.",
    );
    let missing_note = leading(
      "A clock whose entry is never written is `E0046` at the impl block, missing the poll's own \
       word — the declaration's `light` clocks and the operator's entries are the same list, \
       checked by the compiler at the place an author would fix it.",
    );

    quote! {
      #[doc = #sweeps_doc]
      #[doc = ""]
      #[doc = #split_note]
      #[doc = ""]
      #[doc = #answer_note]
      #[doc = ""]
      #[doc = #missing_note]
      #vis trait #sweeps #generics {
        /// What one sweep has to say about itself — the info the observation it becomes carries.
        type Info;

        /// What a sweep can fail with.
        type Error;

        #(#entries)*
      }
    }
  }

  /// The lending's `Debug`, HAND-WRITTEN — because a derive would bound the app's own types.
  ///
  /// A citizen and a third-party executor are CONCRETE fields, so `#[derive(Debug)]` would demand
  /// `Debug` of both unconditionally: a scraper that never wanted to be printable would stop being a
  /// legal mount for the benefit of one line. [`Cadence`](ingraph)'s own note states the trade one
  /// layer over and makes the same one — a ringer is printed as its recurrence, and a lending is
  /// printed as what it lends.
  ///
  /// So the walk names the per-clock CONTEXTS, whose parameters this impl bounds where they are
  /// spent, and hides the rest behind `finish_non_exhaustive` — which is honest rather than
  /// evasive: the citizen is the deployment's own value, and the reader of a wiring dump is after
  /// which clock reaches which store.
  fn lending_debug(
    &self,
    lending: &syn::Ident,
    seats: &[Seat<'_>],
    parameters: &[&syn::Ident],
  ) -> proc_macro2::TokenStream {
    let generics = angled(parameters);
    let named = lending.to_string();
    let handles: Vec<&syn::Ident> = seats
      .iter()
      .filter_map(|seat| seat.lent.as_ref())
      .flat_map(|lent| lent.handles.iter())
      .collect();
    let shown = seats.iter().filter(|seat| seat.lent.is_some()).map(|seat| {
      let (field, spelled) = (&seat.entry.name, seat.entry.name.to_string());
      quote!(.field(#spelled, &self.#field))
    });
    // EVERY seat that holds something a context does not: a citizen, an executor, a cell. The
    // ellipsis is what says they are there without asking their types for anything.
    let hidden = seats
      .iter()
      .any(|seat| seat.handler.is_some() || seat.executor.is_some() || seat.cell.is_some());
    let ending = if hidden {
      quote!(.finish_non_exhaustive())
    } else {
      quote!(.finish())
    };

    // The `where` is written only where there is something to say — a bare `where {` parses, but it
    // is a spelling nobody writes by hand and an expansion should not either.
    let printable = (!handles.is_empty()).then(|| quote!(where #(#handles: ::core::fmt::Debug,)*));

    quote! {
      impl #generics ::core::fmt::Debug for #lending #generics
      #printable
      {
        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
          f.debug_struct(#named)
            #(#shown)*
            #ending
        }
      }
    }
  }

  /// The fields ONE seat asks the lending to hold: its context, its citizen, its executor, its cell.
  fn lending_fields(&self, seat: &Seat<'_>) -> Vec<proc_macro2::TokenStream> {
    let name = &seat.entry.name;
    let mut fields = Vec::new();
    if let Some(lent) = seat.lent.as_ref() {
      let (context, handles) = (&lent.context, &lent.handles);
      let doc = leading(&format!("What the `{name}` clock's ticks are lent."));
      fields.push(quote! {
        #[doc = #doc]
        #name: #context<#(#handles),*>,
      });
    }
    if let (Some(field), Some(mounted)) = (seat.handler.as_ref(), seat.entry.body.citizen()) {
      let doc = leading(&format!(
        "The citizen the `{name}` clock ticks — `handler = \"{}\"`.",
        path_text(mounted)
      ));
      fields.push(quote! {
        #[doc = #doc]
        #field: #mounted,
      });
    }
    if let Some(engine) = seat.executor.as_ref() {
      let (field, parameter) = (&engine.field, &engine.parameter);
      let doc = leading(&format!(
        "Where the `{name}` clock's detached ticks run. The `{}` word selects {}; a deployment \
         holding a pool of its own names that type here instead, which is what makes the executor a \
         seam rather than a vocabulary.",
        seat.entry.mode.as_str(),
        match engine.shipped {
          Some(shipped) => format!("the shipped `{shipped}`"),
          None => "whichever executor the deployment installed".to_owned(),
        }
      ));
      fields.push(quote! {
        #[doc = #doc]
        #field: #parameter,
      });
    }
    if let Some(cell) = seat.cell.as_ref() {
      let cell_type = self.framework(&["drive"], "AtMostOne");
      let doc = leading(&format!(
        "AT MOST ONE `{name}` tick in flight. The default for a detached SYNC clock, because a \
         thread that waits is a stack: a tick arriving while its predecessor still runs is skipped, \
         and says so. `concurrent` on the entry removes this field."
      ));
      fields.push(quote! {
        #[doc = #doc]
        #cell: #cell_type,
      });
    }
    fields
  }

  /// The lending's doors: the constructor, and the seam the runtime drives.
  fn lending_doors(
    &self,
    lending: &syn::Ident,
    seats: &[Seat<'_>],
    parameters: &[&syn::Ident],
    sealed: bool,
  ) -> proc_macro2::TokenStream {
    let (record, vis) = (&self.record, &self.vis);
    let generics = angled(parameters);
    let new_doc = leading(&format!(
      "Hold one context per granting clock, one citizen per mounted clock and one executor per \
       detached clock, in the order [`{record}`] declared them.\n\nThis is the value handed to \
       `Resident::polling`. Each clock's context was built separately, which is where a deployment \
       decided what that clock reaches; each executor is named here, which is where a deployment \
       displaces a shipped one."
    ));

    let constructor = if sealed {
      let sealed_doc = leading(&format!(
        "The lending a [`{record}`] needs — which is nothing, because no clock of it was granted a \
         store or mounted a citizen."
      ));
      quote! {
        impl #lending {
          #[doc = #sealed_doc]
          #[inline]
          #[must_use]
          #vis const fn new() -> Self {
            Self(())
          }
        }
      }
    } else {
      let taken = seats.iter().flat_map(Seat::taken);
      let stored = seats.iter().flat_map(Seat::stored);
      // `const` exactly where every field is a value the caller passed. An at-most-one cell holds an
      // `Arc`, which no const context can allocate, so a node with one gets an ordinary `fn` —
      // deciding it here rather than dropping `const` everywhere keeps the plain case plain.
      let constness = seats
        .iter()
        .all(|seat| seat.cell.is_none())
        .then(|| quote!(const));
      quote! {
        impl #generics #lending #generics {
          #[doc = #new_doc]
          // A clock apiece for its context, its citizen and its executor, so a node with several
          // clocks passes the lint's seven quickly. The same allow the emitted key and lineage
          // constructors carry, for the same reason: the arity is the DECLARATION's, and a
          // declaration is not refactored by a lint.
          #[allow(clippy::too_many_arguments)]
          #[inline]
          #[must_use]
          #vis #constness fn new(#(#taken),*) -> Self {
            Self { #(#stored)* }
          }
        }
      }
    };

    let seam = self.route(lending, seats, parameters, sealed);
    quote! {
      #constructor
      #seam
    }
  }

  /// THE ROUTE: a tick's position, to whatever owns it — an operator's sweep entry, or a mounted
  /// citizen, run where the entry's word said.
  ///
  /// Positions are the WHOLE schedule's, and so is this table: EVERY clock has an arm, because the
  /// lending is a polling node's whole sweep seam and a clock without one would be a tick with
  /// nowhere to go.
  fn route(
    &self,
    lending: &syn::Ident,
    seats: &[Seat<'_>],
    parameters: &[&syn::Ident],
    sealed: bool,
  ) -> proc_macro2::TokenStream {
    let record = &self.record;
    let sweeps = default_sweeps_name(record);
    let words = Vocabulary {
      seats: self.framework(&["drive"], "Seats"),
      source: self.framework(&["drive"], "PollUpstream"),
      swept: self.framework(&["drive"], "Swept"),
      async_tick: self.framework(&["drive"], "AsyncTick"),
      tick: self.framework(&["drive"], "Tick"),
      spawn: self.framework(&["drive"], "Spawn"),
      async_spawn: self.framework(&["drive"], "AsyncSpawn"),
    };
    let send = quote!(::core::marker::Send);
    // The handles and the list they make, kept apart because the bound below needs the HANDLES: a
    // trait reference that binds as well as takes has one argument list holding both, and a closed
    // list cannot be reopened.
    let swept = swept_held(seats);
    let swept_generics = angled(&swept);
    let sweeping = seats.iter().any(|seat| !seat.entry.mounted());

    // THE NODE'S ONE PAIR, and WHICH SIDE ANCHORS IT is forced rather than chosen. A mounted
    // citizen is a CONCRETE type, so `<Scraper as AsyncTick<…>>::Info` normalizes to whatever that impl
    // said and a where-clause tying it to `<O as Sweeps>::Info` cannot be read backwards — the arm
    // would produce `usize` where the signature promised the operator's own type. Anchored the
    // other way it normalizes: `<O as Sweeps>::Info` is a projection over a PARAMETER, so the same
    // clause resolves it to the citizen's. So the FIRST INLINE CITIZEN anchors wherever there is
    // one, the sweep trait anchors where there is not, and a node whose every clock detaches
    // answers nothing at all — nothing it runs comes back to this seat.
    let anchor = seats
      .iter()
      .find(|seat| seat.entry.mounted() && !seat.entry.mode.detached());
    let (info, error) = if let Some(seat) = anchor {
      let mounted = seat.entry.body.citizen().expect("a mounted seat");
      let (face, context) = (seat.face(&words), seat.context());
      (
        quote!(<#mounted as #face<#context>>::Info),
        quote!(<#mounted as #face<#context>>::Error),
      )
    } else if sweeping {
      (
        quote!(<O as #sweeps #swept_generics>::Info),
        quote!(<O as #sweeps #swept_generics>::Error),
      )
    } else {
      (quote!(()), quote!(::core::convert::Infallible))
    };

    let mut bounds: Vec<proc_macro2::TokenStream> = vec![match (sweeping, anchor.is_some()) {
      // The operator's own entries answer in the pair a CITIZEN anchored, which is where the node's
      // one-answer law is enforced when both roads are on one node: an author whose sweep entries
      // answer in a type the mounted citizen does not is refused at the impl, naming both.
      //
      // ONE ARGUMENT LIST, arguments then bindings — the shape the citizens' own bound below has
      // always been written in (`#face<#context, Info = …, Error = …>`), and the reason this arm
      // spells the handles rather than reusing `swept_generics`: appending the pair to a list that
      // closed already emits `<Node>Sweeps<Handle><Info = …>`, two lists, which does not parse. A
      // node with a granting UNMOUNTED clock beside an inline mounted one is the only shape that
      // reaches this arm with handles in hand, and it lost its whole expansion to that `<`.
      (true, true) => quote!(O: #sweeps<#(#swept,)* Info = #info, Error = #error> + #send),
      (true, false) => quote!(O: #sweeps #swept_generics + #send),
      (false, _) => quote!(O: #send),
    }];
    for handle in seats
      .iter()
      .filter_map(|seat| seat.lent.as_ref())
      .flat_map(|lent| lent.handles.iter())
    {
      bounds.push(quote!(#handle: #send));
    }
    for seat in seats {
      if let Some(engine) = seat.executor.as_ref() {
        let (parameter, seam) = (
          &engine.parameter,
          if engine.asynchronous {
            &words.async_spawn
          } else {
            &words.spawn
          },
        );
        bounds.push(quote!(#parameter: #seam + #send));
      }
      let Some(mounted) = seat.entry.body.citizen() else {
        continue;
      };
      let (face, context) = (seat.face(&words), seat.context());
      if seat.entry.mode.detached() {
        // A DETACHED tick leaves with owned values, so the citizen and its context are CLONED per
        // tick. What that costs is stated rather than hidden: what the detached body changes in its
        // own copy does not flow back, so a citizen keeping state across ticks writes `block` or
        // `async(inline)` — or keeps that state behind a handle, which a clone shares rather than
        // copies.
        bounds.push(quote!(#mounted: #face<#context> + ::core::clone::Clone + #send + 'static));
        if seat.lent.is_some() {
          bounds.push(quote!(#context: ::core::clone::Clone + #send + 'static));
        }
      } else if anchor.is_some_and(|first| first.position == seat.position) {
        // THE ANCHOR itself takes the bare bound. Tying it to a pair READ OFF IT would be
        // `<Scraper as AsyncTick<…>>::Info == <Scraper as AsyncTick<…>>::Info`, which is `E0275` — the
        // solver following its own tail.
        bounds.push(quote!(#mounted: #face<#context>));
      } else {
        // EVERY OTHER INLINE citizen answers the seat too, so it answers in the same pair. A
        // handler whose own `Info` or `Error` differs is `E0271` at the deployment, naming both.
        bounds.push(quote!(#mounted: #face<#context, Info = #info, Error = #error>));
      }
    }

    let arms = seats
      .iter()
      .map(|seat| seat.arm(&sweeps, &swept_generics, &words));
    let unrouted = format!(
      "a `{record}` tick from a position its own schedule never minted — the arms below are every \
       clock the declaration wrote, so reaching this line means a source was rung against the wrong \
       node"
    );
    let seats_doc = leading(
      "Seat `operator` at the clock that rang, and run what that clock declared.\n\nEvery clock the \
       declaration wrote has an arm: an unmounted one calls the operator's own entry, a mounted one \
       runs its citizen, and the entry's mode decides whether that happens here or on an \
       executor.\n\nThe receiver is the LENDING and not the operator, and that is forced rather \
       than chosen: the bridge from a position to a per-clock entry can only be a blanket over the \
       operator, and such an impl is `E0210` — an uncovered type parameter before the first local \
       type. Written this way round the self type is local and the impl is legal.",
    );
    let operator = if sweeping {
      quote!(operator)
    } else {
      quote!(_operator)
    };
    let generics = angled(parameters);
    let (subject, all) = if sealed {
      (quote!(#lending), quote!(<O>))
    } else {
      (quote!(#lending #generics), quote!(<O, #(#parameters),*>))
    };
    let (seats_trait, source, swept) = (&words.seats, &words.source, &words.swept);

    quote! {
      impl #all #seats_trait<O> for #subject
      where
        // `Send` on the operator, on every handle and on every executor, because the seam's own
        // answer is a `Send` future and this body holds them across an await. The bound costs
        // nothing that was not already spent — a resident is moved to a thread or a task, so a
        // lending that was not `Send` could never have been driven — and it is stated HERE, where
        // it is spent, rather than on the types, which are built and printed by parties that never
        // await anything.
        #(#bounds,)*
      {
        type Error = #error;
        type Info = #info;

        #[doc = #seats_doc]
        async fn seat(
          &mut self,
          #operator: &mut O,
          source: #source,
        ) -> ::core::result::Result<#swept<Self::Info>, Self::Error> {
          match source.index() {
            #(#arms)*
            _ => ::core::unreachable!(#unrouted),
          }
        }
      }
    }
  }

  /// One `Grant` per granted store, clock by clock and grant by grant, in the order the declaration
  /// wrote them — the launch's half of the check, and the only half a walk over the whole catalog
  /// can make.
  ///
  /// Each row carries the CLOCK that holds it, so the collect-all refusals are per-poll-seated: an
  /// author reading *`reaper`'s `nightly` clock grants itself `write = "…"`* is told which entry to
  /// go and fix, which under one shared list there was no way to say.
  ///
  /// A MOUNTED clock's grants are here too, for the same reason: the launch checks the PERMISSION,
  /// and who spends it — the operator's own entry or a citizen the deployment built — changes
  /// nothing about whether the root mounts the granted node.
  pub(super) fn declared_grants(&self) -> Vec<proc_macro2::TokenStream> {
    let grant = self.framework(&["drive"], "Grant");
    self
      .polls
      .iter()
      .flat_map(|polls| polls.granting())
      .flat_map(|(_, entry)| {
        let clock = entry.name.to_string();
        entry
          .grants
          .iter()
          .flat_map(|grants| &grants.grants)
          .map(move |granted| (clock.clone(), granted))
      })
      .map(|(clock, granted)| {
        let node = &granted.node;
        let named = path_text(node);
        quote!(#grant::of::<#node>(#clock, #named))
      })
      .collect()
  }
}

impl Seat<'_> {
  /// Which citizen trait this seat's mount is bound to — the mode's own answer, and the whole of
  /// what makes a wrong mount `E0277` at the word.
  fn face<'a>(&self, words: &'a Vocabulary) -> &'a proc_macro2::TokenStream {
    if self.entry.mode.blocking() {
      &words.tick
    } else {
      &words.async_tick
    }
  }

  /// The `Ctx` this seat's citizen names — its own grants context, or `()` where it was lent
  /// nothing.
  fn context(&self) -> proc_macro2::TokenStream {
    match self.lent.as_ref() {
      Some(lent) => {
        let (context, handles) = (&lent.context, &lent.handles);
        quote!(#context<#(#handles),*>)
      }
      None => quote!(()),
    }
  }

  /// The constructor arguments this seat takes, in the order its words are read.
  fn taken(&self) -> Vec<proc_macro2::TokenStream> {
    let mut taken = Vec::new();
    if let Some(lent) = self.lent.as_ref() {
      let (name, context, handles) = (&self.entry.name, &lent.context, &lent.handles);
      taken.push(quote!(#name: #context<#(#handles),*>));
    }
    if let (Some(field), Some(mounted)) = (self.handler.as_ref(), self.entry.body.citizen()) {
      taken.push(quote!(#field: #mounted));
    }
    if let Some(engine) = self.executor.as_ref() {
      let (field, parameter) = (&engine.field, &engine.parameter);
      taken.push(quote!(#field: #parameter));
    }
    taken
  }

  /// The fields this seat stores, including the cell nobody passes.
  fn stored(&self) -> Vec<proc_macro2::TokenStream> {
    let mut stored = Vec::new();
    if self.lent.is_some() {
      let name = &self.entry.name;
      stored.push(quote!(#name,));
    }
    if let Some(field) = self.handler.as_ref() {
      stored.push(quote!(#field,));
    }
    if let Some(engine) = self.executor.as_ref() {
      let field = &engine.field;
      stored.push(quote!(#field,));
    }
    if let Some(cell) = self.cell.as_ref() {
      stored.push(quote!(#cell: ::core::default::Default::default(),));
    }
    stored
  }

  /// This seat's arm of the route — the whole of what the entry's words decided, as one match arm.
  fn arm(
    &self,
    sweeps: &syn::Ident,
    swept_generics: &proc_macro2::TokenStream,
    words: &Vocabulary,
  ) -> proc_macro2::TokenStream {
    let (index, name, swept) = (self.position, &self.entry.name, &words.swept);
    let Some(mounted) = self.entry.body.citizen() else {
      // THE OPERATOR'S OWN ENTRY. A clock lent nothing is called with nothing, and the mode decides
      // whether the call is awaited.
      let lent = self.lent.as_ref().map(|_| quote!(, &mut self.#name));
      let call = quote!(<O as #sweeps #swept_generics>::#name(operator #lent));
      return if self.entry.mode.blocking() {
        quote!(#index => #call.map(#swept::Ran),)
      } else {
        quote!(#index => #call.await.map(#swept::Ran),)
      };
    };
    let handler = self
      .handler
      .as_ref()
      .expect("a mounted seat holds a citizen");
    let (face, context) = (self.face(words), self.context());
    let tick = quote!(<#mounted as #face<#context>>::tick);
    // The ungranted context is a LOCAL `()` rather than a `&mut ()` written into the call, so
    // nothing about the arm depends on how long a temporary lives across an await.
    let ungranted = self.lent.is_none().then(|| quote!(let mut ungranted = ();));
    let lent = match self.lent.as_ref() {
      Some(_) => quote!(&mut self.#name),
      None => quote!(&mut ungranted),
    };

    if !self.entry.mode.detached() {
      // INLINE: the tick runs HERE, so its answer is the seat's answer.
      let call = if self.entry.mode.blocking() {
        quote!(#tick(&mut self.#handler, #lent))
      } else {
        quote!(#tick(&mut self.#handler, #lent).await)
      };
      return quote! {
        #index => {
          #ungranted
          #call.map(#swept::Ran)
        }
      };
    }

    // DETACHED: the tick leaves with owned clones, so the seat claims the cell where the default
    // stands, hands the work over and says `Dispatched`. The body's own answer is DROPPED where it
    // is produced — nothing out there holds a tap, and the resident has already moved on. That is
    // the trade the word buys, and it is why a body whose outcome must be watched runs inline.
    let engine = self.executor.as_ref().expect("a detached seat holds one");
    let field = &engine.field;
    let claim = self.cell.as_ref().map(|cell| {
      quote! {
        let claim = match self.#cell.claim() {
          ::core::option::Option::Some(claim) => claim,
          ::core::option::Option::None => {
            return ::core::result::Result::Ok(#swept::Lapped);
          }
        };
      }
    });
    let held = self.cell.as_ref().map(|_| quote!(let _claim = claim;));
    let grants = match self.lent.as_ref() {
      Some(_) => quote!(let mut grants = ::core::clone::Clone::clone(&self.#name);),
      None => quote!(let mut grants = ();),
    };
    let (spawn, async_spawn) = (&words.spawn, &words.async_spawn);
    if engine.asynchronous {
      quote! {
        #index => {
          #claim
          let mut handler = ::core::clone::Clone::clone(&self.#handler);
          #grants
          #async_spawn::spawn(&self.#field, async move {
            #held
            let _ = #tick(&mut handler, &mut grants).await;
          });
          ::core::result::Result::Ok(#swept::Dispatched)
        }
      }
    } else {
      quote! {
        #index => {
          #claim
          let mut handler = ::core::clone::Clone::clone(&self.#handler);
          #grants
          #spawn::spawn(&self.#field, move || {
            #held
            let _ = #tick(&mut handler, &mut grants);
          });
          ::core::result::Result::Ok(#swept::Dispatched)
        }
      }
    }
  }
}

/// The handle parameters the SWEEP TRAIT takes — the unmounted granting clocks' and no others.
///
/// Narrower than the lending's, which is the presence law read one level down: a handle only a
/// mounted citizen reaches is not a parameter the operator's own trait has any use for.
fn swept_held<'a>(seats: &'a [Seat<'a>]) -> Vec<&'a syn::Ident> {
  seats
    .iter()
    .filter(|seat| !seat.entry.mounted())
    .filter_map(|seat| seat.lent.as_ref())
    .flat_map(|lent| lent.handles.iter())
    .collect()
}

/// A generic list, or NOTHING where there is none — because `Foo<>` is a spelling this emission
/// should not produce even where the compiler tolerates it.
fn angled<T: quote::ToTokens>(parameters: &[T]) -> proc_macro2::TokenStream {
  if parameters.is_empty() {
    proc_macro2::TokenStream::new()
  } else {
    quote!(<#(#parameters),*>)
  }
}

/// The type parameter ONE grant's handle takes — the granted node's last segment plus `Handle`, and
/// the clock's own word in front of it where the bare name is already taken.
///
/// Derived from the segment rather than from the folded mount so that the parameter reads as the
/// type it stands for (`MediaHandle`, not `MediaWrite` or `H0`). The per-entry mount collision
/// refusal keeps two grants inside one clock from agreeing; the qualifier is what keeps two CLOCKS
/// granted the same store from colliding on the lending, which the ruling made legal.
fn handle(grant: &Grant, clock: Option<&syn::Ident>) -> syn::Ident {
  let segment = &grant
    .node
    .segments
    .last()
    .expect("a path has at least one segment")
    .ident;
  match clock {
    Some(clock) => format_ident!("{clock}{segment}Handle"),
    None => format_ident!("{segment}Handle"),
  }
}

/// A granted path as the declaration wrote it, for a doc line and for the launch's own sentence.
fn path_text(path: &syn::Path) -> String {
  path
    .segments
    .iter()
    .map(|segment| segment.ident.to_string())
    .collect::<Vec<_>>()
    .join("::")
}

/// The route's bound on the operator, over the 2×2 of MOUNT by GRANT — the crossing that decides
/// how many argument lists the sweep trait's reference carries.
#[cfg(test)]
mod bound_tests;
/// What the polling emission puts in the DECLARING SCOPE, held against the collision rule's own
/// table. Beside the suite below, which reads what each of those types IS.
#[cfg(test)]
mod registered_tests;
#[cfg(test)]
mod tests;