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
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
//! The MIRROR MODE: what `#[derive(ingraph::Enum)]` expands into when the declaration wears
//! `#[ingraph(remote = "…")]`.
//!
//! A mirror is a vocabulary somebody ELSE declared, restated here so the framework has a local type
//! to write impls on. The declaration writes the variants out — identifiers, nothing else — and this
//! module writes everything that follows from them.
//!
//! ```ignore
//! // `upstream::Codec` is the vocabulary another crate declares — `h264`, `vp9`, `av1` and an
//! // escape of its own. `ingraph-derive/tests/enum_remote.rs` declares one and COMPILES this
//! // example, which is what makes it an example rather than a sketch.
//! #[derive(Clone, PartialEq, Eq, ingraph::Enum)]
//! #[ingraph(remote = "upstream::Codec")]
//! pub enum Codec {
//!   H264,
//!   Vp9,
//!   #[ingraph(other)]
//!   Other(ingraph::Utf8Bytes),
//! }
//! ```
//!
//! # ONE SOURCE for the words, and it is upstream
//!
//! The restatement is IDENTIFIERS ONLY. Every word — the one a column stores, the one a client
//! writes, the one a cursor carries — comes from the upstream's own
//! [`Display`](core::fmt::Display) and [`FromStr`](core::str::FromStr), through this mirror's
//! `remote()`. There is no second table here for the upstream's to drift from, which is also why a
//! mirror takes no per-face `rename` and no per-face `text`/`integer` form: an upstream vocabulary
//! spells itself, in one word, in every face.
//!
//! The cost is stated rather than hidden: rendering a mirror MATERIALIZES the upstream value, and
//! for the escape variant that means parsing its word back through the upstream's own grammar. That
//! is the price of the single source, and it is what makes a mirror's rendering byte-identical to
//! the upstream's — folding, casing and all.
//!
//! # The ESCAPE variant is the OPENNESS, declared
//!
//! `#[ingraph(other)]` marks the one variant carrying a word rather than restating a name, and its
//! presence is the declaration SAYING the upstream vocabulary is open. Both directions of that claim
//! are enforced by the compiler at the site the claim is spent:
//!
//! - **an escape whose upstream can REFUSE a word** hits the emitted totality bound — a trait whose
//!   whole body is a named `#[diagnostic::on_unimplemented]` — because an open vocabulary is exactly
//!   one whose parse cannot fail;
//! - **no escape, over an upstream that has one** hits `E0004` at the `From<Remote>` arm list, which
//!   is exhaustive precisely because there is nowhere for an unnamed variant to go. rustc names the
//!   uncovered patterns, which is the upstream's own escape or its `#[non_exhaustive]`.
//!
//! A variant this mirror simply FORGOT is the same `E0004` on a closed upstream, and on an open one
//! it lands in the escape instead of failing to compile — deliberately, so an upstream release
//! adding a variant does not break a build. What names the absence there is a per-variant round-trip
//! pin at TEST time, which is where an open mirror's completeness is checked and the only place it
//! can be.
//!
//! # …and the escape takes ONE of THREE postures
//!
//! The bound above reads the upstream's `FromStr::Err`, and a vocabulary census walked into what
//! that cannot express: a crate whose parse is behaviourally total — an unknown word rides its own
//! escape — while its error type serves a no-alloc tier that really can refuse. Nine types read as
//! CLOSED to the bound, truthfully about the type and uselessly about the crate, and every one of
//! them hands out a `fn other(impl AsRef<str>) -> Self` that is total in the way that matters.
//!
//! So `#[ingraph(other)]` grows two mutually exclusive cells, spelled with the conversion family's
//! own word pair, and a declaration says where the totality LIVES:
//!
//! ```ignore
//! #[ingraph(other)]                                    // the upstream's TYPE says it
//! #[ingraph(other(from = "upstream::Codec::other"))]    // a total GATE says it
//! #[ingraph(other(try_from = "upstream::Codec::try_other"))]   // …and this one can refuse
//! ```
//!
//! | posture | totality lives in | `FromStr::Err` | `<Enum>ParseError` | `error(rename = "…")` |
//! |---|---|---|---|---|
//! | `other` | `<Remote as FromStr>::Err`, under a bound | `Infallible` | absent | REFUSED |
//! | `other(from = "…")` | the gate's SIGNATURE | `Infallible` | absent | REFUSED |
//! | `other(try_from = "…")` | nowhere — the door can refuse | `<Enum>ParseError` | cast | legal |
//! | *no escape* — a closed mirror | nowhere | `<Enum>ParseError` | cast | legal |
//!
//! **Every posture PARSES FIRST**, the gate being a fallback rather than a replacement: a word the
//! upstream names reaches the variant that names it, and only what the upstream turned away is
//! handed to the gate. A door that went straight to the gate would round-trip nothing.
//!
//! The third posture is HALF-OPEN — open outward, where the `From<Remote>` wildcard still absorbs an
//! upstream value this mirror does not restate, and closed inward, where a word neither the parse nor
//! the gate accepts is a refusal. Its gate refuses with `<Remote as FromStr>::Err` and no other type,
//! and that law is what collapses the two refusals into one for the wrapping to name.
//!
//! # What it emits
//!
//! | item | condition |
//! |---|---|
//! | `EnumFilterMarker`, `DefaultMarker`, `DefaultVecMarker` | always |
//! | `From<Remote>` and `From<Self> for Remote` | always |
//! | `remote()`, `VARIANTS`, `is_<variant>` | always |
//! | one forwarding method per `delegate(fn …)` | per declared signature |
//! | `Display` and `FromStr`, both through the upstream | always |
//! | `CursorValue`, over the upstream's word | always |
//! | `<Enum>ParseError` | wherever the parse CAN refuse — a closed or half-open mirror |
//! | `sqlx::Type`, `sqlx::Encode`, `sqlx::Decode`, `Carrier`, at TEXT | per SQL backend, GATED |
//! | a custom SCALAR, plus the two crossings | behind the BINDING gate |
//! | an OBJECT face beside them, and the scalar at `<Enum>Input` | one published delegate or more |
//!
//! # TWO RECEIVERS, and the second WRITES BACK
//!
//! `delegate(fn m(&self) -> T)` forwards: materialize the upstream, call, hand the answer back.
//! `delegate(fn m(&mut self) -> T)` cannot — the materialized value is a temporary — so its body
//! materializes, mutates and CONVERTS HOME through this mirror's own `From`. Two conversions per
//! call, stated rather than hidden, and total in both shapes of mirror: an open one's conversion
//! home has a wildcard arm folding an unnamed upstream value into the escape, and a closed one's is
//! exhaustive over the upstream's own variants.
//!
//! # The wire face is a SCALAR, where a declared vocabulary's is an `enum`
//!
//! A mirror's value set is the upstream's, so an SDL `enum` here would publish a member list this
//! crate cannot keep true — every upstream release could add one, and a client's introspection would
//! be authoritative and wrong. The scalar publishes the GRAMMAR instead and leaves the vocabulary
//! where it is declared: one word in, one word out, both through the upstream's own parse and
//! rendering.
//!
//! That is the classification rather than a local trade: a vocabulary is ONE reading, so it crosses
//! as a scalar; a bit set is MANY readings at once, so it crosses as an object. A closed mirror
//! takes the scalar too — consistency over introspection, with a true `enum` face left as a future
//! opt-in rather than a second shape decided per declaration.
//!
//! # …until a delegate is PUBLISHED, and then the OUTPUT seat is an object
//!
//! `#[graphql(<backend>)]` on a `delegate(fn …)` entry is an ADJECTIVE on a noun: the entry is still
//! a function, and the attribute says that function also reaches a schema. One of them changes what
//! this mirror renders as, because a word cannot carry a selection set:
//!
//! ```ignore
//! #[ingraph(remote = "upstream::Codec", delegate(
//!   fn to_u32(&self) -> Option<u32>,             // Rust alone
//!   #[graphql(async_graphql)]
//!   fn is_lossless(&self) -> bool,               // published as `isLossless`
//!   #[graphql(async_graphql(rename = "intra"))]
//!   fn is_all_intra(&self) -> bool,              // published as `intra`
//! ))]
//! ```
//!
//! | published | the output seat | the input seat |
//! |---|---|---|
//! | none | `scalar Codec` | the same scalar |
//! | one or more | `type Codec { text, … }` | `scalar CodecInput` |
//!
//! `text` is the word the scalar used to BE — the canonical slug, this vocabulary's `Display`, which
//! is the upstream's. The naming law is the declared union's, restated rather than reinvented and for
//! the union's own reason: both faces are impls on ONE Rust type, and async-graphql's registry is
//! keyed by the GraphQL NAME — so two faces under one word would not collide loudly, the second
//! registration would simply be dropped and the schema would silently be missing a face.
//!
//! A mirror that publishes NOTHING is untouched by any of this, down to the token: the scalar arm
//! below emits exactly what it emitted before the axis existed.

use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned as _;

use super::{DatabaseKind, Delegate, EnumModel, EnumVariant, Escape, GraphqlKind, Remote};

#[cfg(test)]
mod tests;

impl EnumModel {
  /// The whole expansion for a MIRROR.
  ///
  /// Two blocks, as the declared mode has: everything the declaring scope is owed no name for sits
  /// in an anonymous `const`, and the wire face is its own so the binding gate can wrap the whole of
  /// it. The refusal type stands outside both, and only a mirror whose parse CAN refuse has one — it
  /// is named in signatures a caller writes (`FromStr::Err`), and a mirror that promises every word
  /// parses answers with [`Infallible`](core::convert::Infallible), which is already a name
  /// everybody has.
  pub(super) fn emit_mirror(&self, remote: &Remote) -> proc_macro2::TokenStream {
    let error = self.refuses().then(|| self.refusal());
    let total = self.door(remote);
    let markers = self.markers();
    let conversions = self.conversions(remote);
    let face = self.mirror_face(remote);
    let parsing = self.mirror_parsing(remote);
    let cursor = self.mirror_cursor();
    let key = self.key_delegation();
    let width = self.width_row();
    let read = self.read_row();
    let storage = DatabaseKind::ALL
      .into_iter()
      .map(|database| self.mirror_storage(database));
    let wire = self.scalar_wire();
    quote! {
      #error

      const _: () = {
        #total
        #markers
        #conversions
        #face
        #parsing
        #cursor
        #key
        #width
        #read
        #(#storage)*
      };

      #wire
    }
  }

  /// The DOOR a word goes through to become an upstream value — one per posture, and absent from a
  /// CLOSED mirror, which never turns a word into one.
  ///
  /// Every mirror with an escape has exactly one of these, and all three write the SAME function
  /// name ([`spend`](Self::spend)): the readers below name the door rather than the posture, so one
  /// declaration's choice reaches the escape's arm, the slug map and this vocabulary's own `FromStr`
  /// without any of the three asking which of the three it got.
  ///
  /// | posture | the door | and it |
  /// |---|---|---|
  /// | bare `other` | the upstream's own `FromStr`, under a totality bound | cannot refuse |
  /// | `other(from = "…")` | that parse, falling to an UNCONDITIONAL gate | cannot refuse |
  /// | `other(try_from = "…")` | that parse, falling to a gate that CAN | refuses as its upstream does |
  ///
  /// **Every posture PARSES FIRST.** A gate is a fallback and never a replacement, which is what
  /// keeps a word the upstream does name reaching the variant that names it — a mirror that went
  /// straight to the gate would round-trip nothing, because every value would come back through the
  /// escape.
  fn door(&self, remote: &Remote) -> Option<proc_macro2::TokenStream> {
    Some(match self.posture()? {
      Escape::Total => self.total_from_str(remote),
      Escape::Gate(gate) => self.unconditional_gate(remote, gate),
      Escape::TryGate(gate) => self.refusable_gate(remote, gate),
    })
  }

  /// The TOTALITY obligation a bare `#[ingraph(other)]` spends, and the sentence a declaration gets
  /// for claiming an openness the upstream's own TYPE has not got.
  ///
  /// A bare escape is a promise that EVERY word parses — the ones this mirror does not name land in
  /// the escape — and a vocabulary whose parse can refuse has not made it. The promise is spent
  /// turning a word into an upstream value with no failure to report, so the obligation is a trait
  /// with the unwrap in its BODY rather than an assertion beside it: there is no way to reach the
  /// escape's arm without discharging it. [`spend`](Self::spend) is the one function that names the
  /// bound, so one mistake earns one sentence.
  ///
  /// `#[diagnostic::on_unimplemented]` is what makes it a NAMED refusal rather than a type error
  /// inside somebody else's expansion. Local to the anonymous `const`, so nothing here reaches the
  /// framework's shelf for a trait whose whole life is three lines of this expansion.
  ///
  /// **This is the posture the two gates exist for the absence of.** The bound reads the upstream's
  /// `FromStr::Err`, and a crate whose parse is behaviourally total while its error type serves a
  /// tier that really can refuse reads as closed here — truthfully, about the type, and uselessly,
  /// about the crate. `other(from = "…")` is where such a declaration says where the totality
  /// actually lives.
  fn total_from_str(&self, remote: &Remote) -> proc_macro2::TokenStream {
    let name = &self.name;
    let path = &remote.path;
    let spend = self.spend();
    let message = format!(
      "`{{Self}}` is a REFUSAL, so the vocabulary it comes from is closed — and `{name}` declares \
       an `#[ingraph(other)]` escape, which is a promise every word parses"
    );
    let note = "an open vocabulary is one whose `FromStr` cannot fail: a word it does not know \
                becomes its own escape rather than a refusal, so `FromStr::Err` is \
                `core::convert::Infallible`. Drop the `#[ingraph(other)]` variant and this mirror's \
                `From` becomes exhaustive over the upstream's own variants, which is what makes an \
                upstream that grows one a compile error here rather than a silent absence";
    let outer = format!(
      "`{{Self}}` cannot be mirrored as an OPEN vocabulary — `{name}` declares an \
       `#[ingraph(other)]` escape, and that is a promise every word parses"
    );
    quote! {
      // The obligation is a TRAIT BOUND on the refusal type rather than an equality on
      // `FromStr::Err`, and that is the diagnostic rather than taste: a `where Err = Infallible`
      // fails as `E0271`, which is an associated-type mismatch and carries no
      // `#[diagnostic::on_unimplemented]` of anybody's. An unsatisfied bound does carry one, so the
      // sentence a declaration gets is this one instead of a note about a projection.
      #[diagnostic::on_unimplemented(
        message = #message,
        label = "a parse that can produce this is a parse that can refuse",
        note = #note,
      )]
      trait __IngraphNever {
        fn never(self) -> ::core::convert::Infallible;
      }

      impl __IngraphNever for ::core::convert::Infallible {
        fn never(self) -> ::core::convert::Infallible {
          self
        }
      }

      #[diagnostic::on_unimplemented(message = #outer, note = #note)]
      trait __IngraphTotalFromStr: ::core::str::FromStr {
        fn total(text: &::core::primitive::str) -> Self;
      }

      impl<T> __IngraphTotalFromStr for T
      where
        T: ::core::str::FromStr,
        <T as ::core::str::FromStr>::Err: __IngraphNever,
      {
        fn total(text: &::core::primitive::str) -> Self {
          match <Self as ::core::str::FromStr>::from_str(text) {
            ::core::result::Result::Ok(value) => value,
            ::core::result::Result::Err(refused) => match __IngraphNever::never(refused) {},
          }
        }
      }

      fn #spend(text: &::core::primitive::str) -> #path {
        <#path as __IngraphTotalFromStr>::total(text)
      }
    }
  }

  /// `other(from = "…")` — the door whose totality is a SIGNATURE.
  ///
  /// The gate is `fn(impl AsRef<str>) -> Remote`: it answers with an upstream value and has no
  /// failure to report, so the mirror is as open as a bare `other` and declares no refusal type. The
  /// declaration is pointing at a totality the upstream's error type does not express, which is the
  /// whole reason this cell exists — and the pointing is CHECKED, at the gate's own token, rather
  /// than taken on trust.
  ///
  /// # The check is a marker, and it is a marker for the reason the totality bound is one
  ///
  /// A gate answering with a `Result` is the mistake this cell invites, and written as a bare call
  /// in a `Remote` position it would be `E0308` — a mismatch, correct and silent about the rule.
  /// [`gate_marker`](Self::gate_marker) is implemented for the upstream type and nothing else, so
  /// the same mistake is an unsatisfied bound carrying a sentence that names the OTHER cell: a gate
  /// that can refuse is what `try_from` is for.
  fn unconditional_gate(&self, remote: &Remote, gate: &syn::Path) -> proc_macro2::TokenStream {
    let name = &self.name;
    let path = &remote.path;
    let spend = self.spend();
    let marker = self.gate_marker();
    let message = format!(
      "`{{Self}}` is what `{name}`'s `other(from = \"…\")` gate answers with, and an UNCONDITIONAL \
       gate answers with the mirrored vocabulary itself"
    );
    let note = "`other(from = \"…\")` names a gate of the shape `fn(impl AsRef<str>) -> Remote` — \
                total, with no failure to report — and that signature is where an open mirror's \
                promise that every word parses is kept. A gate answering with a `Result` is a gate \
                that can REFUSE: write it as `other(try_from = \"…\")`, which is the same door with \
                this vocabulary's own `ParseError` cast around the refusal";
    let called = quote_spanned! {gate.span()=> #gate(text)};
    quote! {
      #[diagnostic::on_unimplemented(
        message = #message,
        label = "an unconditional gate answers with an upstream value, not with a result",
        note = #note,
      )]
      trait #marker {
        fn __ingraph_gated(self) -> #path;
      }

      impl #marker for #path {
        #[inline]
        fn __ingraph_gated(self) -> #path {
          self
        }
      }

      // PARSE FIRST. The gate is the fallback and never the whole door: a word the upstream names
      // has to reach the variant that names it, or nothing would round-trip.
      fn #spend(text: &::core::primitive::str) -> #path {
        match <#path as ::core::str::FromStr>::from_str(text) {
          ::core::result::Result::Ok(__ingraph_value) => __ingraph_value,
          ::core::result::Result::Err(_) => #marker::__ingraph_gated(#called),
        }
      }
    }
  }

  /// `other(try_from = "…")` — the door that can REFUSE, and the HALF-OPEN mirror it makes.
  ///
  /// Open outward and closed inward. The `From<Remote>` arm list keeps the wildcard that absorbs an
  /// upstream value this mirror does not restate, so an upstream release growing a variant is still
  /// harmless; and a WORD neither the upstream's parse nor the gate accepts is a refusal, reported
  /// as this vocabulary's own `<Enum>ParseError` through exactly the machinery a closed mirror
  /// reports its upstream's refusal with. That is also why `error(rename = "…")` is legal in this
  /// posture and in neither of the other two: the knob moves a type that only exists where there is
  /// a refusal to name.
  ///
  /// # The SAME-TYPE law, and why it is the thing that makes the posture coherent
  ///
  /// The gate's `Err` must BE `<Remote as FromStr>::Err`. Under that law the door composes to a
  /// function of exactly `from_str`'s own type — so the half-open reader below is the CLOSED
  /// mirror's, to the token, with the door spent where the closed one spends the upstream's parse.
  /// Without it there would be two refusals reaching one wrapping, and the emission would have to
  /// invent a join between two error types it cannot see.
  ///
  /// The law is emitted as the PROJECTION rather than as a name, which is what makes it enforceable
  /// at all: this side cannot see the upstream's declaration, so it writes
  /// `<Remote as FromStr>::Err` and lets the compiler settle whether the declaration's gate agrees.
  fn refusable_gate(&self, remote: &Remote, gate: &syn::Path) -> proc_macro2::TokenStream {
    let name = &self.name;
    let path = &remote.path;
    let spend = self.spend();
    let marker = self.gate_marker();
    let refusal = self.upstream_refusal(remote);
    let message = format!(
      "`{{Self}}` is what `{name}`'s `other(try_from = \"…\")` gate answers with, and a REFUSABLE \
       gate refuses exactly as the vocabulary it opens does"
    );
    let note = "`other(try_from = \"…\")` names a gate of the shape `fn(impl AsRef<str>) -> \
                Result<Remote, <Remote as FromStr>::Err>`, and the error type is not a choice: the \
                door parses first and falls to the gate, so the two refusals become one and there \
                is one type for this vocabulary's own `ParseError` to be cast around. A gate that \
                refuses with a type of its own has to map it — `Result::map_err` at the gate, or an \
                error type the upstream already answers with";
    let called = quote_spanned! {gate.span()=> #gate(text)};
    quote! {
      #[diagnostic::on_unimplemented(
        message = #message,
        label = "this refusal is not the one the mirrored vocabulary's own parse answers with",
        note = #note,
      )]
      trait #marker {
        fn __ingraph_gated(self) -> ::core::result::Result<#path, #refusal>;
      }

      impl #marker for ::core::result::Result<#path, #refusal> {
        #[inline]
        fn __ingraph_gated(self) -> Self {
          self
        }
      }

      // PARSE FIRST, exactly as the total postures do — the gate answers only for the words the
      // upstream's own parse turned away.
      fn #spend(
        text: &::core::primitive::str,
      ) -> ::core::result::Result<#path, #refusal> {
        match <#path as ::core::str::FromStr>::from_str(text) {
          ::core::result::Result::Ok(__ingraph_value) => ::core::result::Result::Ok(__ingraph_value),
          ::core::result::Result::Err(_) => #marker::__ingraph_gated(#called),
        }
      }
    }
  }

  /// The upstream's OWN refusal, as a projection — the one type a half-open door answers with.
  ///
  /// Written rather than named because this side cannot see the upstream's declaration, and written
  /// ONCE because the gate's signature, the door's signature and the marker's self type are three
  /// spellings of one obligation.
  fn upstream_refusal(&self, remote: &Remote) -> proc_macro2::TokenStream {
    let path = &remote.path;
    quote!(<#path as ::core::str::FromStr>::Err)
  }

  /// What a gate's return type is checked through. Inside the anonymous `const`, so it collides with
  /// nothing — and named alike in both gated postures, there being at most one gate per mirror.
  fn gate_marker(&self) -> syn::Ident {
    format_ident!("__IngraphGate")
  }

  /// The ONE function a mirror's door is spent in.
  ///
  /// Three readers want a word turned into an upstream value — the escape's arm in `remote()`, the
  /// slug map, and this vocabulary's own `FromStr` — and each naming the posture itself would report
  /// the same refusal three times over one mistake, and would have to know which of the three
  /// postures it got.
  fn spend(&self) -> syn::Ident {
    format_ident!("__ingraph_upstream")
  }

  /// Both directions of the mirror, by VARIANT NAME.
  ///
  /// The two impls are the whole of what a mirror is FOR, and neither carries a table of upstream
  /// words: each arm names an upstream variant, so a mirror that misspells one is `E0599` at that
  /// arm and a mirror that renames one says so with `#[ingraph(rename = "…")]`.
  ///
  /// `From<Remote>` is where the openness lands. With an escape it takes a wildcard, so an upstream
  /// release adding a variant is absorbed rather than fatal; without one it is exhaustive, and an
  /// upstream that has more variants than this mirror names is `E0004` at the match.
  ///
  /// The outward leg is `remote()` restated as a conversion — one body, so the two cannot disagree.
  fn conversions(&self, remote: &Remote) -> proc_macro2::TokenStream {
    let name = &self.name;
    let path = &remote.path;
    let arms = self.restated().map(|variant| {
      let ident = &variant.ident;
      let upstream = variant.upstream();
      quote!(#path::#upstream => #name::#ident,)
    });
    let wild = self.escape().map(|escape| {
      let ident = &escape.ident;
      quote! {
        __ingraph_unknown => #name::#ident(::core::convert::Into::into(
          ::std::string::String::as_str(&::std::string::ToString::to_string(&__ingraph_unknown)),
        )),
      }
    });
    quote! {
      #[automatically_derived]
      impl ::core::convert::From<#path> for #name {
        fn from(__ingraph_value: #path) -> Self {
          match __ingraph_value {
            #(#arms)*
            #wild
          }
        }
      }

      #[automatically_derived]
      impl ::core::convert::From<#name> for #path {
        #[inline]
        fn from(__ingraph_value: #name) -> Self {
          #name::remote(&__ingraph_value)
        }
      }
    }
  }

  /// The MATERIALIZATION gate, the variant list, the predicates and whatever the declaration asked
  /// to borrow.
  ///
  /// `remote()` is present on every mirror and takes `&self`, handing back the upstream value BY
  /// VALUE: a vocabulary is a small `Copy`-shaped thing in practice, and a borrow of an upstream
  /// value is not something a restatement HAS to lend — the escape variant holds a word, not an
  /// upstream value, so there is nothing there to point at. That is also why the reference family —
  /// `AsRef`, `Deref`, `Borrow` — is absent from this mode and cannot be sound in it.
  ///
  /// `VARIANTS` lists the RESTATED variants only. The escape carries a word, so it is not a
  /// constant and has no place in a `&'static [Self]`; what the list is for is the per-variant
  /// round-trip pin, which walks the names this mirror claims.
  ///
  /// # The escape's arm, and the one posture where it can have no answer
  ///
  /// `remote()` is TOTAL in every posture, and it has to be: it is the single materialization gate,
  /// and the rendering, the binds, the cursor and every delegated call read through it. Two of the
  /// three doors are total, so their arm is the door and nothing more. A HALF-OPEN door can refuse,
  /// and a word it refuses has no upstream value at all — so that arm STOPS.
  ///
  /// It stops rather than substituting, which is the journal row's own posture one declaration over:
  /// where a crossing cannot report, handing back a value nobody wrote is worse than not answering.
  /// The arm is unreachable for every value this framework builds — a parse, a decode and a cursor
  /// all go through the same door, and the `From<Remote>` arm carries the upstream's own rendering
  /// of a real upstream value — so what reaches it is a hand-built escape carrying a word this
  /// vocabulary refuses, and the sentence says exactly that.
  fn mirror_face(&self, remote: &Remote) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let name = &self.name;
    let path = &remote.path;
    let variants = self.restated().map(|variant| {
      let ident = &variant.ident;
      quote!(Self::#ident)
    });
    let arms = self.restated().map(|variant| {
      let ident = &variant.ident;
      let upstream = variant.upstream();
      quote!(Self::#ident => #path::#upstream,)
    });
    let spend = self.spend();
    let escape = self.escape().map(|escape| {
      let ident = &escape.ident;
      let word = quote! {
        ::core::convert::AsRef::<::core::primitive::str>::as_ref(__ingraph_word)
      };
      if self.refuses() {
        // The HALF-OPEN arm, and the one place in this mode where a value has no answer. See the
        // method note for why it stops rather than substituting one.
        let stopped = format!(
          "`{name}::{ident}` holds a word this vocabulary's own door refuses, so there is no \
           upstream value for it to materialize as. `{name}::remote` answers with an upstream \
           value rather than with a result — every rendering, every bind and every delegated call \
           reads through it — so substituting a variant here would hand back a value nobody wrote. \
           Only `other(try_from = \"…\")` builds a door that can refuse, and every word reaching \
           this escape through a parse, a decode or a cursor has already passed it: this one was \
           built by hand"
        );
        quote! {
          Self::#ident(__ingraph_word) => match #spend(#word) {
            ::core::result::Result::Ok(__ingraph_value) => __ingraph_value,
            // A STATIC sentence, for the reason the stored-word refusal below carries one: the
            // upstream's refusal type is not known to be renderable here, and this crate has no
            // format machinery on the shelf to render it with.
            ::core::result::Result::Err(_) => ::core::panic!(#stopped),
          },
        }
      } else {
        quote! {
          Self::#ident(__ingraph_word) => #spend(#word),
        }
      }
    });
    let predicates = self.variants.iter().map(|variant| self.predicate(variant));
    // The SEAT's forwarding half, for every entry that did not waive it. `on = self` is that waiver
    // — see [`delegate`](Self::delegate) for what the word is FOR — and an entry carrying it reaches
    // this walk with nothing to mint: its method is the declaration's own already.
    let delegates = remote
      .delegates
      .iter()
      .filter(|delegate| delegate.on_self.is_none())
      .map(|delegate| self.delegate(delegate));
    let variants_doc = format!(
      "Every RESTATED variant of [`{name}`], in declaration order.\n\nThe escape is absent: it \
       carries a word rather than a name, so it is no constant. This is the list a per-variant \
       round-trip pin walks."
    );
    let remote_doc = format!(
      "The upstream value this mirrors, by value.\n\nEvery word [`{name}`] renders or parses goes \
       through here, so the grammar is the upstream's alone. The escape variant PARSES its word \
       back, which is what makes a mirror's rendering byte-identical to the upstream's."
    );
    quote! {
      #[automatically_derived]
      impl #name {
        #[doc = #variants_doc]
        #vis const VARIANTS: &'static [Self] = &[#(#variants),*];

        #[doc = #remote_doc]
        #[must_use]
        #vis fn remote(&self) -> #path {
          match self {
            #(#arms)*
            #escape
          }
        }

        #(#predicates)*

        #(#delegates)*
      }
    }
  }

  /// One variant's predicate. The escape's pattern carries its word, so it is matched with one.
  ///
  /// Shared with [`own`](super::own): a predicate is about the VARIANT and asks nothing about where
  /// the words come from.
  pub(super) fn predicate(&self, variant: &EnumVariant) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let name = &self.name;
    let ident = &variant.ident;
    let predicate = variant.predicate();
    let pattern = if variant.escape.is_some() {
      quote!(Self::#ident(..))
    } else {
      quote!(Self::#ident)
    };
    let doc = format!("Whether this is [`{name}::{ident}`].");
    quote! {
      #[doc = #doc]
      #[inline]
      #[must_use]
      #vis const fn #predicate(&self) -> ::core::primitive::bool {
        ::core::matches!(self, #pattern)
      }
    }
  }

  /// One `delegate(fn …)` entry, forwarded onto the materialized upstream value.
  ///
  /// The declaration writes the SIGNATURE and this writes the body, which is the only division Rust
  /// admits: a forwarding method needs a written return type, there is no `typeof`, and the upstream
  /// is a type this side cannot look inside. So the restatement law the whole mode is built on —
  /// *say it once, and everything else is generated* — reaches the borrowed methods too.
  ///
  /// The call is METHOD-CALL syntax rather than a qualified path, and that is what makes the knob
  /// worth having: an upstream's inherent method and an upstream's trait method both resolve, with
  /// no word here for a declaration to have to know which it asked for. A name the upstream has not
  /// got is `E0599` at the body, naming that type.
  ///
  /// The VISIBILITY is the enum's, and it is not the declaration's to write: a [`syn::Signature`]
  /// carries none, which is the restatement being exactly a signature rather than an item.
  ///
  /// # TWO RECEIVERS, two bodies
  ///
  /// `&self` FORWARDS: materialize, call, hand the answer back. `&mut self` cannot — the
  /// materialized value is a temporary, and a mutation of it would be dropped — so its body
  /// MATERIALIZES, MUTATES and WRITES BACK, which is the only shape a restatement admits. A
  /// consuming `self` and a receiverless signature are refused at the DOOR, where the refusal lands
  /// on the token the declaration wrote rather than inside an expansion it cannot edit.
  ///
  /// The write-back is total in BOTH shapes of mirror, which is what makes the knob safe to offer:
  /// an OPEN mirror's `From<Remote>` has a wildcard arm folding an unnamed upstream value into the
  /// escape, and a CLOSED one's is exhaustive over the upstream's own variants. So every value the
  /// upstream method could have left behind has somewhere to land.
  ///
  /// # `on = self` — the entry the mode mints for and the author did not want minted
  ///
  /// The forwarding body calls the method on the MATERIALIZED UPSTREAM, which is right for the case
  /// the mode exists to serve and wrong for exactly one: a method the author wrote on the MIRROR.
  /// There the mint is `E0599` — the upstream has no such method — or, where the author's own
  /// inherent one is beside it, `E0592` for the duplicate, and neither report is answerable from the
  /// declaration's own tokens. `on = self` skips this walk for that entry, leaving the author's
  /// method where they wrote it.
  ///
  /// The PROMOTED half is untouched, and that is the same fact one declaration over: the resolver's
  /// arm calls `#name::#method(self)` — a qualified call on the mirror itself, never on the
  /// materialized value — so resolution answers it identically whether the method is a mint's or the
  /// author's own. See [`mirror_object`](Self::mirror_object) for the arm.
  fn delegate(&self, delegate: &Delegate) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let name = &self.name;
    let signature = &delegate.signature;
    let method = &signature.ident;
    let arguments = signature.inputs.iter().skip(1).filter_map(|argument| {
      let syn::FnArg::Typed(typed) = argument else {
        return None;
      };
      match typed.pat.as_ref() {
        syn::Pat::Ident(bound) => Some(bound.ident.clone()),
        _ => None,
      }
    });
    let body = if delegate.exclusive {
      quote! {
        let mut __ingraph_remote = #name::remote(&*self);
        let __ingraph_answer = __ingraph_remote.#method(#(#arguments),*);
        *self = <Self as ::core::convert::From<_>>::from(__ingraph_remote);
        __ingraph_answer
      }
    } else {
      quote! {
        let __ingraph_remote = #name::remote(self);
        __ingraph_remote.#method(#(#arguments),*)
      }
    };
    let doc = if delegate.exclusive {
      format!(
        "Forwarded to the upstream vocabulary, through [`{name}::remote`] — and WRITTEN BACK.\n\nThe \
         upstream value is materialized, mutated, and converted home, so a call costs TWO \
         conversions where a shared-receiver delegate costs one. A mirror stores a word rather than \
         an upstream value; there is nothing here to mutate in place."
      )
    } else {
      format!("Forwarded to the upstream vocabulary, through [`{name}::remote`].")
    };
    quote! {
      #[doc = #doc]
      #[inline]
      #vis #signature {
        #body
      }
    }
  }

  /// The RENDERING and the PARSE, both the upstream's.
  ///
  /// [`Display`](core::fmt::Display) writes whatever the materialized upstream writes, and
  /// [`FromStr`](core::str::FromStr) reads whatever it reads — so a mirror and its upstream agree on
  /// every word by construction rather than by a pin.
  ///
  /// The refusal type FORKS on whether this mirror's parse CAN refuse, which is the whole of
  /// *`ParseError` is dispatched* — and the fork has three inputs and two outcomes:
  ///
  /// | posture | `FromStr::Err` | what the reader spends |
  /// |---|---|---|
  /// | bare `other`, `other(from = "…")` | [`Infallible`](core::convert::Infallible) | the door, which cannot refuse |
  /// | `other(try_from = "…")` | `<Enum>ParseError` | the door, which can |
  /// | no escape — a CLOSED mirror | `<Enum>ParseError` | the upstream's own parse |
  ///
  /// **The last two rows are ONE emission.** A half-open mirror casts its refusal, wraps the door's
  /// with it and answers with it through the same tokens a closed mirror uses on its upstream's —
  /// the SAME-TYPE law being what makes the door's type equal `from_str`'s, so there is nothing for
  /// the two to differ by but which function the reader calls. `error(rename = "…")` moves the type
  /// in both, exactly as it does in the declared mode.
  fn mirror_parsing(&self, remote: &Remote) -> proc_macro2::TokenStream {
    let name = &self.name;
    let path = &remote.path;
    let reader = self.slug_map();
    let spend = self.spend();
    let (err, body, from_str) = if self.refuses() {
      // A door where a posture built one, and the upstream's own parse where none was needed —
      // which is the ONE token a half-open mirror and a closed one differ by.
      let parse = if self.escape().is_some() {
        quote!(#spend(text))
      } else {
        quote!(<#path as ::core::str::FromStr>::from_str(text))
      };
      let error = self.error();
      (
        quote!(#error),
        quote! {
          match #parse {
            ::core::result::Result::Ok(value) => {
              ::core::option::Option::Some(::core::convert::From::from(value))
            }
            ::core::result::Result::Err(_) => ::core::option::Option::None,
          }
        },
        quote! {
          match #reader(text) {
            ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
            ::core::option::Option::None => ::core::result::Result::Err(#error(())),
          }
        },
      )
    } else {
      (
        quote!(::core::convert::Infallible),
        quote! {
          ::core::option::Option::Some(::core::convert::From::from(#spend(text)))
        },
        quote! {
          ::core::result::Result::Ok(::core::convert::From::from(#spend(text)))
        },
      )
    };
    quote! {
      // ONE reader, for the reason the declared mode writes one per namespace: the cursor, the
      // stored form and this vocabulary's own `FromStr` all read the same words, and two parses
      // over one grammar are two things that can come to disagree.
      fn #reader(text: &::core::primitive::str) -> ::core::option::Option<#name> {
        #body
      }

      #[automatically_derived]
      impl ::core::fmt::Display for #name {
        #[inline]
        fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
          ::core::fmt::Display::fmt(&#name::remote(self), f)
        }
      }

      #[automatically_derived]
      impl ::core::str::FromStr for #name {
        type Err = #err;

        fn from_str(text: &::core::primitive::str) -> ::core::result::Result<Self, Self::Err> {
          #from_str
        }
      }
    }
  }

  /// The keyset cursor's codec, over the upstream's word.
  ///
  /// The declared mode's argument, unchanged: a cursor is minted by one process and handed back to
  /// another that may be talking to a different dialect, so the codec belongs to the TYPE. A mirror
  /// has one word in every face, which makes that trivially true here.
  fn mirror_cursor(&self) -> proc_macro2::TokenStream {
    let reader = self.slug_map();
    self.word_cursor(
      &quote! {
        ::std::string::String::as_bytes(&::std::string::ToString::to_string(self))
      },
      &quote!(#reader(text)),
    )
  }

  /// The keyset cursor over a vocabulary whose stored form is a WORD, in whichever mode it is.
  ///
  /// `written` are the bytes a position is minted from and `read` is the [`Option`] a client's bytes
  /// come back through. Everything else — the codec belonging to the TYPE rather than to a dialect,
  /// the UTF-8 check on bytes that are a client's — is the same fact twice, so it is written once.
  pub(super) fn word_cursor(
    &self,
    written: &proc_macro2::TokenStream,
    read: &proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    let name = &self.name;
    let cursor_value = self.framework(&["cursor"], "CursorValue");
    quote! {
      #[automatically_derived]
      impl #cursor_value for #name {
        fn write_cursor(&self, out: &mut ::std::vec::Vec<::core::primitive::u8>) {
          out.extend_from_slice(#written);
        }

        fn read_cursor(bytes: &[::core::primitive::u8]) -> ::core::option::Option<Self> {
          match ::core::str::from_utf8(bytes) {
            ::core::result::Result::Ok(text) => #read,
            ::core::result::Result::Err(_) => ::core::option::Option::None,
          }
        }
      }
    }
  }

  /// The reverse map every parse into a mirror goes through.
  fn slug_map(&self) -> syn::Ident {
    format_ident!("__ingraph_of_slug")
  }

  /// One backend's storage rows, at TEXT and only at text.
  ///
  /// A mirror stores its WORD, and there is no form knob for it: an upstream discriminant is not
  /// this crate's to depend on — a release may renumber it — and the escape variant has no
  /// discriminant at all. A word also makes the escape a storage citizen for free, which is what
  /// lets a column survive an upstream that grew a variant.
  ///
  /// The bind is OWNED where a declared vocabulary's is a `&'static str`, and that is the word being
  /// dynamic rather than a change of posture: the escape holds a runtime word, `encode_by_ref` takes
  /// `&self` at an anonymous lifetime, and a borrow of `self` cannot be handed to a `'q` bind. One
  /// allocation per bound operand is the cost, paid only by the declarations that mirror.
  fn mirror_storage(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
    let reader = self.slug_map();
    self.text_storage(
      database,
      &quote!(::std::string::ToString::to_string(self)),
      &quote!(#reader(stored)),
    )
  }

  /// One backend's storage rows for a vocabulary stored as TEXT, in whichever mode it is.
  ///
  /// `bound` is the owned word a value goes out as and `read` is the [`Option`] a stored word comes
  /// back through. The four rows, the gate, the widening-free `str` type info and the sentence a row
  /// holding an unreadable word earns are the same facts in both modes, so they are written once.
  ///
  /// The `None` arm is emitted whether or not the reader can actually produce one. It is dead under
  /// every TOTAL door — the two open mirror postures and an open vocabulary this crate declares —
  /// and it is what a closed or half-open declaration needs, which is a row holding a word this
  /// vocabulary has never had.
  pub(super) fn text_storage(
    &self,
    database: DatabaseKind,
    bound: &proc_macro2::TokenStream,
    read: &proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    if !database.is_sql() {
      return quote!();
    }
    let name = &self.name;
    let gate = self.framework(&["gate"], &database.gate().to_string());
    let backend = self.backend(database);
    let carrier = self.framework(&["comparison", "sql"], "Carrier");
    let query_builder = self.framework(&["sqlx"], "QueryBuilder");
    let sqlx_type = self.framework(&["sqlx"], "Type");
    let encode = self.framework(&["sqlx"], "Encode");
    let decode = self.framework(&["sqlx"], "Decode");
    let database_trait = self.framework(&["sqlx"], "Database");
    let is_null = self.framework(&["sqlx", "encode"], "IsNull");
    let error = self.framework(&["sqlx", "error"], "BoxDynError");
    let refused = format!("{name}: the stored text names no variant of this vocabulary");
    let stored_as = self.framework(&["column"], "StoredAs");
    quote! {
      #gate! {
        // The WORD a `CREATE TABLE` declares a column of this vocabulary with — `String`'s own,
        // because TEXT is what this whole family stores: an open vocabulary's escape carries a
        // runtime word and a mirror's is upstream's grammar, and neither has an integer form to
        // choose instead. `String` rather than `str`, for the reason the encode above names
        // `String`: `str` answers a WIDTH and nothing else, and has no `StoredAs` row by design.
        #[automatically_derived]
        impl #stored_as<#backend> for #name {
          const WORDS: &'static [&'static ::core::primitive::str] =
            <::std::string::String as #stored_as<#backend>>::WORDS;
        }

        #[automatically_derived]
        impl #sqlx_type<#backend> for #name {
          fn type_info() -> <#backend as #database_trait>::TypeInfo {
            <::core::primitive::str as #sqlx_type<#backend>>::type_info()
          }

          fn compatible(ty: &<#backend as #database_trait>::TypeInfo) -> ::core::primitive::bool {
            <::core::primitive::str as #sqlx_type<#backend>>::compatible(ty)
          }
        }

        #[automatically_derived]
        impl<'__ingraph> #encode<'__ingraph, #backend> for #name {
          fn encode_by_ref(
            &self,
            buf: &mut <#backend as #database_trait>::ArgumentBuffer,
          ) -> ::core::result::Result<#is_null, #error> {
            <::std::string::String as #encode<'__ingraph, #backend>>::encode(#bound, buf)
          }
        }

        #[automatically_derived]
        impl<'__ingraph> #decode<'__ingraph, #backend> for #name {
          fn decode(
            value: <#backend as #database_trait>::ValueRef<'__ingraph>,
          ) -> ::core::result::Result<Self, #error> {
            let stored =
              <&'__ingraph ::core::primitive::str as #decode<'__ingraph, #backend>>::decode(value)?;
            match #read {
              ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
              // Unreachable under every TOTAL door — and written for every declaration, because the
              // arm a closed or half-open one needs is the one that says what a row holding a word
              // this vocabulary has never had should do.
              ::core::option::Option::None => ::core::result::Result::Err(#error::from(#refused)),
            }
          }
        }

        #[automatically_derived]
        impl #carrier<#backend> for #name {
          fn push_bind(&self, qb: &mut #query_builder<#backend>) {
            qb.push_bind(#bound);
          }
        }
      }
    }
  }

  /// The WIRE face: the scalar, whatever the promotion added, and the two crossings, behind the
  /// binding gate.
  ///
  /// Both legs go through this vocabulary's own [`FromStr`](core::str::FromStr) and
  /// [`Display`](core::fmt::Display), so the word a client writes, the word a column stores and the
  /// word a cursor carries are one grammar, upstream's. The refusal a bad word gets is this
  /// vocabulary's own sentence, whichever mode declared it: an open mirror's `Err` is
  /// [`Infallible`](core::convert::Infallible) and that arm is dead, a closed one's is its
  /// `<Enum>ParseError` — and both render through `Display`, which is what lets ONE body serve the
  /// two.
  ///
  /// # The PROMOTION, and what it moves
  ///
  /// A mirror whose `delegate(…)` PUBLISHES nothing is a scalar in both positions, and that is the
  /// shape this mode has always had. One published method changes the OUTPUT seat and only the
  /// output seat: the mirror renders as an OBJECT under its own name — `text` plus one field per
  /// published method — and the scalar retreats to the INPUT seat under `<Enum>Input`. The naming
  /// law is the declared union's, restated rather than reinvented, and for the union's own reason:
  /// two schema types on one Rust type, and a schema has one namespace for type names.
  ///
  /// The two crossing rows are unmoved by any of it. A mirror still crosses INWARD as itself and
  /// OUTWARD as a borrow of itself; what changed is which SDL type each of those two is.
  ///
  /// # An OPEN vocabulary this crate declares takes exactly this face
  ///
  /// It publishes a scalar for the mirror's own reason, one grain over: a schema `enum` promises its
  /// members are the whole set, and a roster with an escape has said in its own declaration that
  /// they are not. It has no `delegate(…)` to publish either — delegation forwards onto an upstream
  /// value, and there is no upstream — so [`promoted`](EnumModel::promoted) is empty and this
  /// function's PROMOTED half expands to nothing. That is why [`own`](super::own) calls this rather
  /// than carrying a second copy of the scalar.
  pub(super) fn scalar_wire(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let gate = self.framework(&["gate"], "if_async_graphql");
    let input = self.framework(&["graphql"], "ToGraphqlInput");
    let output = self.framework(&["graphql"], "ToGraphqlOutput");
    let promoted: Vec<&Delegate> = self.promoted(GraphqlKind::AsyncGraphql).collect();
    let scalar = self.mirror_scalar(&promoted);
    let object = self.mirror_object(&promoted);
    quote! {
      const _: () = {
        #gate! {
          #scalar

          #object

          #[automatically_derived]
          impl #input for #name {
            type Input = Self;
            type Error = ::core::convert::Infallible;

            #[inline]
            fn cross(
              __ingraph_value: Self,
            ) -> ::core::result::Result<Self, ::core::convert::Infallible> {
              ::core::result::Result::Ok(__ingraph_value)
            }

            #[inline]
            fn carry(__ingraph_value: &Self) -> Self {
              ::core::clone::Clone::clone(__ingraph_value)
            }
          }

          #[automatically_derived]
          impl #output for #name {
            type Output<'__ingraph> = &'__ingraph Self;

            #[inline]
            fn to_graphql_output(__ingraph_value: &Self) -> &Self {
              __ingraph_value
            }
          }
        }
      };
    }
  }

  /// The SCALAR, at whichever seat the promotion left it.
  ///
  /// UNPROMOTED it is async-graphql's own attribute over an `impl ScalarType`, which is the shape
  /// the element door already spends and for the same two dividends: the OUTPUT leg is whichever
  /// `resolve` shape that build compiled — the `boxed-trait` fork a hand-written `async fn` can only
  /// pick one side of — and the registry entry is the library's own.
  ///
  /// PROMOTED, the attribute cannot be used at all and that is `E0119` rather than a preference: it
  /// writes an `OutputType` for this type, and the object face beside it writes the same impl. So
  /// the input half is written out — the library's own body, at `MetaTypeId::Scalar` and under
  /// `<Enum>Input` — and `ScalarType` stays, un-attributed, as the ONE pair of bodies both halves
  /// read.
  fn mirror_scalar(&self, promoted: &[&Delegate]) -> proc_macro2::TokenStream {
    let name = &self.name;
    let ag = self.framework(&[], "async_graphql");
    let shelf = crate::emit::vendored(&self.krate, "async_graphql");
    let scalar = quote! {
      impl #ag::ScalarType for #name {
        fn parse(__ingraph_value: #ag::Value) -> #ag::InputValueResult<Self> {
          let __ingraph_text = ::core::result::Result::map_err(
            <::std::string::String as #ag::InputType>::parse(
              ::core::option::Option::Some(__ingraph_value),
            ),
            #ag::InputValueError::propagate,
          )?;
          ::core::result::Result::map_err(
            <Self as ::core::str::FromStr>::from_str(&__ingraph_text),
            |__ingraph_refused| #ag::InputValueError::custom(__ingraph_refused),
          )
        }

        fn to_value(&self) -> #ag::Value {
          #ag::Value::String(::std::string::ToString::to_string(self))
        }
      }
    };
    if promoted.is_empty() {
      let sdl = self.sdl_name();
      return quote! {
        #[#ag::Scalar(crate = #shelf, name = #sdl)]
        #scalar
      };
    }

    // The INPUT TWIN's name is composed off the SCHEMA base rather than off the Rust ident, so
    // `graphql(rename = "…")` moves both faces of a promoted mirror together. Leaving it on the Rust
    // name would publish the renamed object beside an input scalar still wearing the old stem, which
    // is the half-working rename the naming laws refuse.
    let sdl = crate::union::input_sdl_name(&self.sdl_name());
    quote! {
      #scalar

      #[automatically_derived]
      impl #ag::InputType for #name {
        type RawValueType = Self;

        #[inline]
        fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
          ::std::borrow::Cow::Borrowed(#sdl)
        }

        fn create_type_info(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String {
          #ag::registry::Registry::create_input_type::<Self, _>(
            __ingraph_registry,
            #ag::registry::MetaTypeId::Scalar,
            |_| #ag::registry::MetaType::Scalar {
              name: ::std::string::String::from(#sdl),
              description: ::core::option::Option::None,
              is_valid: ::core::option::Option::Some(::std::sync::Arc::new(
                |__ingraph_value| <Self as #ag::ScalarType>::is_valid(__ingraph_value),
              )),
              visible: ::core::option::Option::None,
              inaccessible: false,
              tags: ::std::vec::Vec::new(),
              specified_by_url: ::core::option::Option::None,
              directive_invocations: ::std::vec::Vec::new(),
              requires_scopes: ::std::vec::Vec::new(),
            },
          )
        }

        #[inline]
        fn parse(
          __ingraph_value: ::core::option::Option<#ag::Value>,
        ) -> #ag::InputValueResult<Self> {
          <Self as #ag::ScalarType>::parse(
            ::core::option::Option::unwrap_or_default(__ingraph_value),
          )
        }

        #[inline]
        fn to_value(&self) -> #ag::Value {
          <Self as #ag::ScalarType>::to_value(self)
        }

        #[inline]
        fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
          ::core::option::Option::Some(self)
        }
      }
    }
  }

  /// The OBJECT face a PROMOTED mirror renders as — nothing at all for one that published nothing.
  ///
  /// HAND-EMITTED, exactly as the declared union's two faces are, and for the same wall: a derive
  /// may only APPEND, so there is nowhere to put `#[Object]` on somebody else's enum, and
  /// `#[cfg_attr]` cannot stand in because that predicate asks whether the DECLARING crate has a
  /// feature called `async-graphql`. What the hand emission also buys is this crate's posture on
  /// prose — `description: None` on the type and on every field, as a FACT of the emission.
  ///
  /// # There is no helper method, and the rename is a STRING
  ///
  /// `resolve_field` matches the requested field's word and calls the enum's OWN delegated method in
  /// the arm. So a `rename` moves two string literals — the match arm and the registry entry — and
  /// nothing else: no mangled resolver, no second name for the Rust method to be reached under, and
  /// no way for the published word and the resolved word to disagree.
  ///
  /// That the arm calls `#name::#method(self)` — the MIRROR, never the materialized upstream — is
  /// also what makes [`Delegate::on_self`](crate::delegate::Delegate::on_self) cost this face
  /// nothing: the word waives the forwarding mint, and resolution answers this call the same way
  /// whether the method it reaches is that mint or the one the author wrote on the enum.
  ///
  /// # `text` is the word the scalar used to BE
  ///
  /// An object cannot render as a word, so the word becomes a field. It is the canonical slug —
  /// this vocabulary's own `Display`, which is the upstream's — and it crosses through `String`'s
  /// own output row like any other text a face returns.
  fn mirror_object(&self, promoted: &[&Delegate]) -> proc_macro2::TokenStream {
    if promoted.is_empty() {
      return quote!();
    }
    let name = &self.name;
    let ag = self.framework(&[], "async_graphql");
    let sdl = self.sdl_name();
    let witness = self.wire_witness();
    let text = super::TEXT_FIELD;

    let text_ty: syn::Type = syn::parse_quote!(::std::string::String);
    let text_crossed = self.crossed(&text_ty, &quote!(&__ingraph_word));
    let fields = core::iter::once(self.published_field(text, &text_ty)).chain(promoted.iter().map(
      |delegate| {
        let word = delegate
          .word(GraphqlKind::AsyncGraphql)
          .expect("a promoted delegate publishes at this backend");
        self.published_field(&word, &self.returned(delegate))
      },
    ));
    let arms = promoted.iter().map(|delegate| {
      let word = delegate
        .word(GraphqlKind::AsyncGraphql)
        .expect("a promoted delegate publishes at this backend");
      let method = &delegate.signature.ident;
      let crossed = self.crossed(&self.returned(delegate), &quote!(&__ingraph_answer));
      quote! {
        #word => {
          let __ingraph_answer = #name::#method(self);
          #ag::ServerResult::map(
            #ag::OutputType::resolve(
              &#crossed,
              &#ag::Context::with_selection_set(
                __ingraph_ctx,
                &__ingraph_ctx.item.node.selection_set,
              ),
              __ingraph_ctx.item,
            ).await,
            ::core::option::Option::Some,
          )
        }
      }
    });

    quote! {
      #witness

      #[automatically_derived]
      impl #ag::resolver_utils::ContainerType for #name {
        async fn resolve_field(
          &self,
          __ingraph_ctx: &#ag::Context<'_>,
        ) -> #ag::ServerResult<::core::option::Option<#ag::Value>> {
          match #ag::Name::as_str(&__ingraph_ctx.item.node.name.node) {
            #text => {
              let __ingraph_word = ::std::string::ToString::to_string(self);
              #ag::ServerResult::map(
                #ag::OutputType::resolve(
                  &#text_crossed,
                  &#ag::Context::with_selection_set(
                    __ingraph_ctx,
                    &__ingraph_ctx.item.node.selection_set,
                  ),
                  __ingraph_ctx.item,
                ).await,
                ::core::option::Option::Some,
              )
            }
            #(#arms)*
            _ => ::core::result::Result::Ok(::core::option::Option::None),
          }
        }
      }

      #[automatically_derived]
      impl #ag::OutputType for #name {
        fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
          ::std::borrow::Cow::Borrowed(#sdl)
        }

        fn create_type_info(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String {
          #ag::registry::Registry::create_output_type::<Self, _>(
            __ingraph_registry,
            #ag::registry::MetaTypeId::Object,
            |__ingraph_registry| #ag::registry::MetaType::Object {
              name: ::std::string::String::from(#sdl),
              description: ::core::option::Option::None,
              fields: {
                let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
                #(#fields)*
                __ingraph_fields
              },
              cache_control: ::core::default::Default::default(),
              extends: false,
              shareable: false,
              resolvable: true,
              keys: ::core::option::Option::None,
              visible: ::core::option::Option::None,
              inaccessible: false,
              interface_object: false,
              tags: ::std::vec::Vec::new(),
              is_subscription: false,
              rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
              directive_invocations: ::std::vec::Vec::new(),
              requires_scopes: ::std::vec::Vec::new(),
            },
          )
        }

        async fn resolve(
          &self,
          __ingraph_ctx: &#ag::ContextSelectionSet<'_>,
          _: &#ag::Positioned<#ag::parser::types::Field>,
        ) -> #ag::ServerResult<#ag::Value> {
          #ag::resolver_utils::resolve_container(__ingraph_ctx, self).await
        }
      }

      #[automatically_derived]
      impl #ag::ObjectType for #name {}
    }
  }

  /// ONE registry entry, for the published word and the type it is returned at.
  ///
  /// The type is a PROJECTION through the marker below, spanned at the return type the declaration
  /// wrote — so a method returning something with no output face is refused there rather than inside
  /// this expansion. `Option<T>` publishes NULLABLE and everything else publishes non-null, which is
  /// async-graphql's own `qualified_type_name` and nothing this emission decides.
  fn published_field(&self, word: &str, returned: &syn::Type) -> proc_macro2::TokenStream {
    let ag = self.framework(&[], "async_graphql");
    let marker = self.wire_marker();
    let ty = quote_spanned! {returned.span()=>
      <#returned as #marker>::__ingraph_wire_type(__ingraph_registry)
    };
    quote! {
      #ag::indexmap::IndexMap::insert(
        &mut __ingraph_fields,
        ::std::string::String::from(#word),
        #ag::registry::MetaField {
          name: ::std::string::String::from(#word),
          description: ::core::option::Option::None,
          args: #ag::indexmap::IndexMap::new(),
          ty: #ty,
          deprecation: #ag::registry::Deprecation::NoDeprecated,
          cache_control: ::core::default::Default::default(),
          external: false,
          requires: ::core::option::Option::None,
          provides: ::core::option::Option::None,
          visible: ::core::option::Option::None,
          shareable: false,
          inaccessible: false,
          tags: ::std::vec::Vec::new(),
          override_from: ::core::option::Option::None,
          compute_complexity: ::core::option::Option::None,
          directive_invocations: ::std::vec::Vec::new(),
          requires_scopes: ::std::vec::Vec::new(),
        },
      );
    }
  }

  /// The type one delegated method answers with, at the declaration's own span.
  ///
  /// A signature with no `->` answers with `()`, which has no output face — so a published method
  /// that returns nothing is the marker's own refusal, at the method's name, rather than a silent
  /// field of no type.
  fn returned(&self, delegate: &Delegate) -> syn::Type {
    match &delegate.signature.output {
      syn::ReturnType::Type(_, ty) => (**ty).clone(),
      syn::ReturnType::Default => {
        syn::parse_quote_spanned!(delegate.signature.ident.span()=> ())
      }
    }
  }

  /// One value, crossed into the form a wire face returns it in — the marker's OTHER operation.
  ///
  /// Spanned WHOLE at the return type, marker and method call included, and that is what collapses
  /// the two mentions into ONE diagnostic: rustc emits a diagnostic identical in message and span
  /// once, and a projection whose trait position carried the macro's own span would report a second
  /// sentence there, in the library's words rather than this framework's.
  fn crossed(
    &self,
    returned: &syn::Type,
    value: &proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    let marker = self.wire_marker();
    quote_spanned! {returned.span()=>
      <#returned as #marker>::__ingraph_wire_value(#value)
    }
  }

  /// What the return-type marker is called. Inside the gated `const`, so it collides with nothing.
  fn wire_marker(&self) -> syn::Ident {
    format_ident!("__IngraphWire")
  }

  /// The marker every published return type is asked for through — the NAMED REFUSAL a type with no
  /// output face earns.
  ///
  /// Two operations rather than a bare bound: the registry entry and the resolver arm both name the
  /// crossing, so a bare marker would leave this framework's sentence beside two of the library's.
  /// Routed through the marker and spanned WHOLE at the return type the declaration wrote, both
  /// sites put their caret on the token an author edits. The union's input seat carries the same
  /// construction and the same argument.
  ///
  /// **Two mentions here are two diagnostics, and that is measured** — `tests/enum_delegate_seats/`
  /// carries the golden and the four arrangements that were compiled to reach it. The union's marker
  /// collapses three mentions into one because its blanket impl carries ONE simple bound; this one
  /// carries a higher-ranked bound over a generic associated type, and rustc titles one of the two
  /// obligations with that bound rather than with the marker.
  ///
  /// `do_not_recommend` on the blanket impl is what keeps the second sentence this framework's:
  /// without it the report descends through the impl and names `ToGraphqlOutput`, which is true and
  /// is not the sentence a declaration's author needs — and the measurement is that dropping it
  /// costs a third diagnostic rather than saving one.
  ///
  /// The bound is `'static` because REGISTRATION has no value to borrow from — the field's SDL type
  /// is asked of the type alone — and a delegated method answers with an owned value in any case:
  /// the upstream it was called on is a temporary this expansion materialized.
  fn wire_witness(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let ag = self.framework(&[], "async_graphql");
    let crossing = self.framework(&["graphql"], "ToGraphqlOutput");
    let marker = self.wire_marker();
    let message = format!(
      "`{{Self}}` is what a method `{name}` PUBLISHES answers with, and it does not cross into an \
       output position"
    );
    let note = format!(
      "a published `delegate(fn …)` becomes a field of the `{name}` object, so its return type \
       needs an `ingraph::ToGraphqlOutput` row — the map every wire face returns through. Return a \
       type that has one, or drop the `#[graphql(…)]` and keep the method as Rust"
    );
    quote! {
      #[diagnostic::on_unimplemented(
        message = #message,
        label = "this type has no output crossing",
        note = #note,
      )]
      trait #marker: ::core::marker::Sized + 'static {
        /// The form a value of this type crosses into an output position as.
        type Crossed<'__ingraph>: #ag::OutputType
        where
          Self: '__ingraph;

        fn __ingraph_wire_type(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String;

        fn __ingraph_wire_value(&self) -> Self::Crossed<'_>;
      }

      #[diagnostic::do_not_recommend]
      impl<__IngraphReturned> #marker for __IngraphReturned
      where
        __IngraphReturned: #crossing + 'static,
        for<'__ingraph> <__IngraphReturned as #crossing>::Output<'__ingraph>: #ag::OutputType,
      {
        type Crossed<'__ingraph> = <__IngraphReturned as #crossing>::Output<'__ingraph>;

        #[inline]
        fn __ingraph_wire_type(
          __ingraph_registry: &mut #ag::registry::Registry,
        ) -> ::std::string::String {
          <Self::Crossed<'static> as #ag::OutputType>::create_type_info(__ingraph_registry)
        }

        #[inline]
        fn __ingraph_wire_value(&self) -> Self::Crossed<'_> {
          <Self as #crossing>::to_graphql_output(self)
        }
      }
    }
  }
}