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
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
//! The VOCABULARY face: what a unit-variant enum expands into.
//!
//! A vocabulary is not a node. It owns no storage, subscribes to nothing and carries no key — it is
//! a VALUE a record's column holds, and the whole of what it needs is the rows that say how a column
//! of it is read, the rows that say how one is stored, and the words its faces spell it as.
//!
//! # Storage is MACHINE-FACING, and the wire is not
//!
//! A database stores the DISCRIMINANT and a schema shows the NAME, and neither is a knob a
//! declaration has to reach for: a column exists for a machine and a wire face exists for a person,
//! so those are the defaults and a per-backend block is what overrides one.
//!
//! ```ignore
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, ingraph::Enum)]
//! #[repr(u8)]
//! pub enum Grade { Low, High, Archived = 9 }
//! ```
//!
//! stores `0`, `1` and `9` in every database this build compiled, shows `LOW`, `HIGH` and
//! `ARCHIVED` on the wire, and declares none of it. The crossing is what joins the two: a filter's
//! operand arrives as the enum, so the user's text is translated at the FILTER and never reaches an
//! integer column as text.
//!
//! # The width follows `#[repr(…)]`, through the house carrier rules
//!
//! `#[repr(u8)]` is a `u8` column. What that means per dialect is not this module's invention: the
//! framework's own carrier table already widens where a dialect has no such type — `u8` and `i8`
//! bind as `SMALLINT` on Postgres, `u16` as `INT`, `u32` as `BIGINT` — and a vocabulary's rows take
//! the same widening, which is why they are per-backend rather than one dialect-generic row.
//!
//! Absent a `#[repr(…)]`, the width is `i64`, and that is measured rather than picked for room. A
//! fieldless enum with no repr hint has discriminants of type `isize`, so `Grade::High = 3_000_000_000`
//! is a legal declaration on every 64-bit target; a narrower default would store it through an `as`
//! cast that silently wraps, and a wrong number in somebody's database is exactly what a DEFAULT must
//! not be able to produce. `i64` is also native on all three dialects — SQLite's `INTEGER`,
//! Postgres's and MySQL's `BIGINT` — so the safe width costs no widening anywhere.
//!
//! # The set of rows, measured against what a working enum column actually needs
//!
//! | impl | who demands it | gated |
//! |---|---|---|
//! | `EnumFilterMarker` | the column's FILTER — `EnumMarker<T>` resolves through it | no |
//! | `DefaultMarker` | the INFERENCE, so a column needs no `enum` word to be read as one | no |
//! | `CursorValue` | the KEYSET cursor, which every persisted column is audited for | no |
//! | `sqlx::Type` | the emitted `FromRow`, once per column | per backend |
//! | `sqlx::Decode` | the emitted `FromRow`, once per column | per backend |
//! | `sqlx::Encode` | the write side of the same binding — an authority names both directions | per backend |
//! | `Carrier` | the comparison's LOWERING, which is what binds an operand into a query | per backend |
//!
//! The last four are the six-row template the vocabulary's first round measured, now written once
//! per COMPILED-IN backend behind [`crate::model::DatabaseKind`]'s gate. What a gate makes an
//! emission mean is `ingraph`'s crate note, under *The four gates*: an impl exists per declared ∩
//! compiled-in backend, and a build without a driver has no impl rather than a deferred one.
//!
//! `ingraph-derive`'s `tests/enums.rs` is where the set is checked: it declares such a column and
//! drives the whole circle through a live database, so a row that were merely plausible would fail
//! there rather than pass a token comparison.
//!
//! # The FACE is hand-emitted, and it is backend-free
//!
//! `is_<variant>`, `VARIANTS`, `as_str`, one `as_<namespace>_str` per TEXT face, `FromStr` over the
//! canonical namespace and one `TryFrom<&…Name>` per text face. None of it names a backend, so
//! none of it rides a gate — what decides whether a namespace has a face is its FORM, since a
//! backend storing a discriminant has no text for a name type to hold.
//!
//! No `derive_more`, and no derive of any kind: the methods are this crate's emission, so the
//! expanded code names no foreign path and the errors are the vocabulary's own.
//!
//! # The REFUSAL type is the ONE name this expansion puts in the declaring scope, so it is the one
//! that can be renamed
//!
//! Everything else sits inside an anonymous `const`, where it can collide with nothing anybody
//! wrote. The refusal cannot: it is named in signatures a caller writes — `FromStr::Err`,
//! `TryFrom::Error` — so it stands beside the enum, and a scope that already holds a
//! `<Enum>ParseError` gets a duplicate definition at a span the declaration cannot edit.
//! `error(rename = "…")` is the way out, and it is the ESCAPE from that collision rather than a
//! spelling preference: the DEFAULT is unchanged, a declaration that names nothing is unaffected,
//! and a scope with nothing in the way never has to know the knob exists.
//!
//! Renaming the type does NOT move the sentence it prints. The message names the VOCABULARY —
//! *`Codec`: no variant answers to this name* — because what failed is a parse into the enum, and
//! the type carrying the refusal is an implementation detail of how that is reported.
//!
//! # MongoDB is measured and stores NOTHING yet
//!
//! `MongoEnumComparison` exists and `MongoCarrier` is the row that would feed it, so the second
//! backend is not blocked on a design. What is missing is a lane that can compile the row:
//! `ingraph-derive`'s dev-dependency on `ingraph` carries no `mongo`, so a MongoDB storage row would
//! ship with no configuration in this workspace able to build it. Its NAMESPACE is here regardless —
//! `mongo(text)` gives a declaration `as_mongo_str` and `TryFrom<&MongoName>`, which is exactly
//! what the hand-written `impl MongoCarrier` that trait's doc asks for is written in terms of.
//!
//! # The wire face rides in the SAME emission, behind the binding gate
//!
//! [`wire`] writes it and [`EnumModel::emit`] carries it — one organ, one word. There were two
//! doors and the second was deleted: schema presence is REACHABILITY (an enum no wire type names
//! never enters an SDL), so a macro was never the gatekeeper the split took it for, and what the
//! split cost — a silent composition-order trap, two entry points onto one model — was the
//! coexistence rather than a consequence of it.
//!
//! **The era rule never held that face, and the note that said so was stale.** A GraphQL face is a
//! VENDORED trait impl rather than a framework one — `#krate::__private::async_graphql::InputType`
//! IS `::async_graphql::InputType`, a third-party trait on a third-party release cadence — and
//! `ingraph-codegen`'s own `framework_rooted` has exempted the vendored segment since the order door
//! landed. What actually held it was THE WALL: a filter over a declarer's enum had no `InputType`,
//! and the row that supplies it is `graphql::filter::r#enum`'s single generic impl.

use std::collections::BTreeMap;

use heck::{ToShoutySnakeCase as _, ToSnakeCase as _};
use quote::{format_ident, quote};

use crate::{
  method::{Emitted, Origin, Owner},
  model::{DatabaseKind, GraphqlKind},
};

mod own;
mod remote;
#[cfg(test)]
mod tests;
mod wire;

/// What a face spells one variant AS.
///
/// The two the comparison layer already names — `SqlEnumComparison`'s own doc reads *"the type this
/// database stores the column as — a text name or an integer discriminant, whichever the field
/// declared"* — and no third, because a third would be a form no comparison kind can lower.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum StorageForm {
  /// The variant's NAME in this namespace.
  ///
  /// Verbatim, and never cased: a stored name is a value in somebody's database, and a mangling
  /// rule that changed would rewrite every row. A raw identifier stores unraw'd — `r#type` is
  /// `type` — because the `r#` is Rust's way of saying the word, not part of it. The one namespace
  /// that does case its default is the wire, for the reason [`Namespace::Graphql`] gives.
  Text,
  /// The variant's DISCRIMINANT, at the declaration's own width.
  ///
  /// The declaration's own number — `Grade::High = 9` stores 9 — because the discriminant is a
  /// number the declaration can already spell, and a second numbering invented here would disagree
  /// with it.
  Integer,
}

impl StorageForm {
  /// Every form, in the order a refusal lists them.
  pub const ALL: [Self; 2] = [Self::Text, Self::Integer];

  /// The word a declaration writes.
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::Text => "text",
      Self::Integer => "integer",
    }
  }
}

/// One face a vocabulary has: four databases and the wire.
///
/// A namespace is not merely a place a name is written — it is the TYPE the name is carried as, so
/// that a conversion out of one cannot be handed a name from another. `ingraph`'s `name` module
/// carries the five types and the argument for them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Namespace {
  /// SQLite's stored word.
  Sqlite,
  /// PostgreSQL's stored word.
  Postgres,
  /// MySQL's stored word.
  Mysql,
  /// MongoDB's stored word.
  Mongo,
  /// The member a GraphQL enum exposes.
  Graphql,
}

impl Namespace {
  /// Every namespace, in the order a refusal lists them.
  pub const ALL: [Self; 5] = [
    Self::Sqlite,
    Self::Postgres,
    Self::Mysql,
    Self::Mongo,
    Self::Graphql,
  ];

  /// The word a declaration writes for this namespace's block.
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::Sqlite => "sqlite",
      Self::Postgres => "postgres",
      Self::Mysql => "mysql",
      Self::Mongo => "mongo",
      Self::Graphql => "graphql",
    }
  }

  /// The database this namespace belongs to, or nothing for the wire.
  pub const fn database(self) -> Option<DatabaseKind> {
    match self {
      Self::Sqlite => Some(DatabaseKind::Sqlite),
      Self::Postgres => Some(DatabaseKind::Postgres),
      Self::Mysql => Some(DatabaseKind::Mysql),
      Self::Mongo => Some(DatabaseKind::Mongo),
      Self::Graphql => None,
    }
  }

  /// The form this namespace takes when a declaration says nothing.
  ///
  /// Storage is for machines and a schema is for people, which is the whole of the split: a column
  /// holds the discriminant, and the wire holds the name.
  pub const fn default_form(self) -> StorageForm {
    match self {
      Self::Sqlite | Self::Postgres | Self::Mysql | Self::Mongo => StorageForm::Integer,
      Self::Graphql => StorageForm::Text,
    }
  }

  /// This namespace's name TYPE, on `ingraph`'s `name` shelf.
  pub const fn name_type(self) -> &'static str {
    match self {
      Self::Sqlite => "SqliteName",
      Self::Postgres => "PostgresName",
      Self::Mysql => "MysqlName",
      Self::Mongo => "MongoName",
      Self::Graphql => "GraphqlName",
    }
  }

  /// The accessor a TEXT face gets — `as_sqlite_str`, `as_graphql_str`.
  ///
  /// Mechanical from [`as_str`](Self::as_str), which is the word the declaration writes, so the
  /// block a reader wrote and the method they reach for cannot drift apart.
  pub fn accessor(self) -> syn::Ident {
    format_ident!("as_{}_str", self.as_str())
  }

  /// The word this namespace spells `canonical` as when the declaration renamed nothing.
  ///
  /// Verbatim for a stored word and SHOUTED for the wire. The asymmetry is the ecosystem's rather
  /// than this crate's: a GraphQL enum's members are `SCREAMING_SNAKE_CASE` by convention, so a face
  /// spelling one `Vp9` would be the one schema that did not. A stored word has no such convention,
  /// and a mangling rule that changed here would rewrite somebody's rows.
  ///
  /// The agreement that round owed is PAID, and paid by construction rather than by a pin: the
  /// GraphQL face [`wire`] emits reads [`EnumVariant::name`] under [`Namespace::Graphql`], which is
  /// this function, so the word `as_graphql_str` hands a caller and the value a client writes are one
  /// string from one table. There is no second casing rule to disagree with `heck`'s, because there
  /// is no derive applying one — the face is written out. `rename` is the escape from either.
  pub fn default_name(self, canonical: &str) -> String {
    match self {
      Self::Sqlite | Self::Postgres | Self::Mysql | Self::Mongo => canonical.to_owned(),
      Self::Graphql => canonical.to_shouty_snake_case(),
    }
  }
}

/// The width a vocabulary's discriminant is stored at — every integer `#[repr(…)]` the house's
/// carrier table can carry, and no other.
///
/// `u64` is deliberately absent, and its absence is the table's rather than an oversight: MySQL has
/// a native `u64` and SQLite and Postgres have none, so a `u64`-wide vocabulary would be storable in
/// one of the three dialects. `usize` and `isize` are absent because they name no fixed width at
/// all, and `i128`/`u128` because no dialect carries one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum IntegerWidth {
  /// `i8`.
  I8,
  /// `i16`.
  I16,
  /// `i32`.
  I32,
  /// `i64` — also the width a declaration with no `#[repr(…)]` takes.
  I64,
  /// `u8`.
  U8,
  /// `u16`.
  U16,
  /// `u32`.
  U32,
}

impl IntegerWidth {
  /// Every width, in the order a refusal lists them.
  pub const ALL: [Self; 7] = [
    Self::I8,
    Self::I16,
    Self::I32,
    Self::I64,
    Self::U8,
    Self::U16,
    Self::U32,
  ];

  /// The width a declaration with no integer `#[repr(…)]` takes — see the module note for why it is
  /// the widest rather than the narrowest.
  pub const DEFAULT: Self = Self::I64;

  /// Rust's integer `#[repr(…)]` hints this framework cannot store, in the order a refusal lists
  /// them.
  pub const UNCARRIED: [&'static str; 5] = ["u64", "u128", "i128", "usize", "isize"];

  /// The primitive this width is.
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::I8 => "i8",
      Self::I16 => "i16",
      Self::I32 => "i32",
      Self::I64 => "i64",
      Self::U8 => "u8",
      Self::U16 => "u16",
      Self::U32 => "u32",
    }
  }

  /// The width this word names, when it is one this framework carries.
  pub fn named(word: &str) -> Option<Self> {
    Self::ALL.into_iter().find(|width| width.as_str() == word)
  }

  /// Whether `word` is one of Rust's INTEGER repr hints at all, carried here or not.
  ///
  /// The question a `#[repr(…)]` walk asks before refusing: `C`, `align(…)`, `packed` and
  /// `transparent` are hints about LAYOUT that say nothing about a stored width, and an enum
  /// carrying one is not a declaration this framework has anything to object to.
  pub fn is_repr_word(word: &str) -> bool {
    Self::named(word).is_some() || Self::UNCARRIED.contains(&word)
  }

  /// The primitive this database actually binds — the house widening, which only Postgres does.
  ///
  /// It is the framework's own `widened_carriers!` table restated for a vocabulary: Postgres has no
  /// unsigned types and no `TINYINT`, so `i8` and `u8` bind as `i16`, `u16` as `i32` and `u32` as
  /// `i64`. Every widening is lossless by construction — the target holds the source's whole range —
  /// which is what makes an `as` cast to it exact rather than merely plausible.
  pub const fn wire(self, database: DatabaseKind) -> Self {
    match database {
      DatabaseKind::Postgres => match self {
        Self::I8 | Self::U8 => Self::I16,
        Self::U16 => Self::I32,
        Self::U32 => Self::I64,
        Self::I16 | Self::I32 | Self::I64 => self,
      },
      DatabaseKind::Sqlite | DatabaseKind::Mysql | DatabaseKind::Mongo => self,
    }
  }
}

/// One variant, with whatever the declaration renamed it to.
#[derive(Debug, Clone)]
pub struct EnumVariant {
  /// The variant as Rust spells it, `r#` and all.
  pub ident: syn::Ident,
  /// The GLOBAL `rename`, which moves the canonical word every namespace defaults from.
  ///
  /// A MIRROR has none — see [`upstream`](Self::upstream), which is what its `rename` names
  /// instead.
  pub rename: Option<String>,
  /// The per-namespace renames, each overriding the canonical word in that one face.
  ///
  /// Always empty on a MIRROR: an upstream vocabulary spells itself, in one word, in every face.
  pub names: BTreeMap<Namespace, String>,
  /// On a MIRROR, the upstream variant this one restates, when it is not spelled alike.
  pub upstream: Option<syn::Ident>,
  /// The POSTURE of the `#[ingraph(other)]` escape — the one variant carrying a WORD rather than
  /// naming a member — and [`None`] on every other variant.
  ///
  /// Its presence is the declaration saying the vocabulary is OPEN, in either mode. A vocabulary
  /// this crate DECLARES takes [`Escape::Total`] and nothing else: the two gated postures point at a
  /// totality living in somebody else's crate, and an open vocabulary with no upstream has no such
  /// place for one to live.
  pub escape: Option<Escape>,
  /// The TEXT CARRIER an escape holds its word in — the marked variant's one unnamed field, as the
  /// declaration wrote it — and [`None`] on every other variant.
  ///
  /// The carrier is the declaration's choice and this crate names no type for it: the door builds
  /// one through [`From<&str>`](From) and reads one through [`AsRef<str>`](AsRef), so any text type
  /// satisfying that pair holds a word. What is recorded here is the TOKEN, because one row needs
  /// the type written rather than merely reachable through a bound — the key delegation, whose
  /// `Inner` IS this type. Every other reader of an escape goes through the two traits and needs no
  /// name at all.
  ///
  /// [`None`] beside a [`Some`] escape is a model that marked an escape and recorded no carrier;
  /// the key row is what it costs, and the derive never builds one — see
  /// [`key_delegation`](EnumModel::key_delegation).
  pub carrier: Option<syn::Type>,
}

/// HOW a mirror turns a word its upstream does not name into an upstream value — the three postures
/// `#[ingraph(other)]` takes, and the whole of what a mirror's openness can be.
///
/// The escape's presence says the upstream vocabulary is OPEN. What this says is where that openness
/// LIVES, and the three answers are not interchangeable: one is a fact about the upstream's type, one
/// is a fact about a function's signature, and one admits that the door itself can refuse.
///
/// # Why there are three, and not one
///
/// The first posture was the only one, and a vocabulary census walked into what it cannot express. A
/// crate whose parse is behaviourally total but whose `FromStr::Err` is a shared refusal type — one
/// error type serving a no-alloc tier that really can refuse and an alloc tier that cannot — reads as
/// CLOSED to a bound on that type, while the same crate hands out a `fn other(impl AsRef<str>) ->
/// Self` that is total in the only way that matters. Nine types were unmirrorable for that reason
/// alone. The gate is what lets a declaration point at the totality instead of asking the type
/// system to find it.
#[derive(Debug, Clone)]
pub enum Escape {
  /// Bare `#[ingraph(other)]` — the UPSTREAM'S OWN parse is total, and its `FromStr::Err` is where
  /// that is said.
  ///
  /// The strongest of the three and the one that needs no gate: the claim is spent as a bound on
  /// `<Remote as FromStr>::Err`, and the compiler settles it. Nothing about this posture moved when
  /// the other two arrived.
  Total,
  /// `#[ingraph(other(from = "…"))]` — an UNCONDITIONAL gate, `fn(impl AsRef<str>) -> Remote`.
  ///
  /// The totality is the GATE'S SIGNATURE rather than the upstream's error type, and the mirror is
  /// as open as a bare `other`: its `FromStr::Err` is [`Infallible`](core::convert::Infallible) and
  /// no refusal type is declared beside the enum. The door parses FIRST and falls to the gate only
  /// on a refusal, so every word the upstream does name still reaches its own variant.
  Gate(syn::Path),
  /// `#[ingraph(other(try_from = "…"))]` — a gate that can REFUSE, which makes the mirror HALF-OPEN.
  ///
  /// Open outward: the `From<Remote>` arm list still carries the wildcard that absorbs an upstream
  /// value this mirror does not restate. Closed inward: a word neither the upstream's parse nor the
  /// gate accepts is a refusal, reported as this vocabulary's own `<Enum>ParseError` exactly as a
  /// closed mirror reports its upstream's — which is why `error(rename = "…")` is legal here and in
  /// neither of the other two.
  ///
  /// The gate's `Err` must BE `<Remote as FromStr>::Err`, and that law is what makes the posture
  /// coherent rather than merely permitted: under it the door composes to a function with the same
  /// type as `from_str` itself, so there is one refusal for the wrapping to name.
  TryGate(syn::Path),
}

impl Escape {
  /// The gate this posture spends, and [`None`] for the one that has none.
  #[must_use]
  pub const fn gate(&self) -> Option<&syn::Path> {
    match self {
      Self::Total => None,
      Self::Gate(path) | Self::TryGate(path) => Some(path),
    }
  }

  /// Whether the door this posture builds can REFUSE a word — the ONE question every fork in the
  /// emission asks, and the reason the three postures are a type rather than two booleans.
  #[must_use]
  pub const fn refuses(&self) -> bool {
    matches!(self, Self::TryGate(_))
  }
}

impl EnumVariant {
  /// The CANONICAL word: the global rename, else the variant's own name unraw'd.
  ///
  /// The `r#` is Rust's escape for a word that collides with its grammar and no part of the name, so
  /// a variant called `r#type` is canonically `type` — which is what a schema and a hand-written row
  /// would spell.
  pub fn canonical(&self) -> String {
    use syn::ext::IdentExt as _;

    self
      .rename
      .clone()
      .unwrap_or_else(|| self.ident.unraw().to_string())
  }

  /// The word one namespace spells this variant as: its own rename, else that namespace's default
  /// over the canonical word.
  pub fn name(&self, namespace: Namespace) -> String {
    self
      .names
      .get(&namespace)
      .cloned()
      .unwrap_or_else(|| namespace.default_name(&self.canonical()))
  }

  /// The word an OPEN vocabulary spells this variant with: its `rename`, else the Rust name in the
  /// framework's own lower-case household — `LeftShoulder` is `left_shoulder`.
  ///
  /// # Why an open vocabulary defaults DIFFERENTLY from a closed one
  ///
  /// A closed vocabulary's word is its variant's name verbatim, because the set IS the declaration
  /// and a client reading an SDL `enum` sees exactly the members it publishes. An open one publishes
  /// a SCALAR, so its words meet the outside world as text — from a producer's protobuf, a label
  /// file, a Swift enum — and the house register's answer for text is lower case. Defaulting to the
  /// Rust spelling would put a `Pascal` word in a position every other producer writes in snake.
  ///
  /// The default is what the five vocabularies this mode was measured against already spell by
  /// hand: all forty-three of their words are `to_snake_case` of the variant name, exactly. `rename`
  /// is the escape from the arithmetic, not a knob a declaration is expected to reach for.
  pub fn folded(&self) -> String {
    use syn::ext::IdentExt as _;

    self
      .rename
      .clone()
      .unwrap_or_else(|| self.ident.unraw().to_string().to_snake_case())
  }

  /// The predicate this variant gets — `is_low`, `is_h264`.
  ///
  /// Over the RUST spelling rather than the canonical word, because the method is Rust and its
  /// reader is looking at the variant: a `#[ingraph(rename = "lo")]` moves what a database stores
  /// and not what the enum is called.
  pub fn predicate(&self) -> syn::Ident {
    use syn::ext::IdentExt as _;

    format_ident!("is_{}", self.ident.unraw().to_string().to_snake_case())
  }

  /// The UPSTREAM variant a mirror's variant restates — the declared `rename`, else its own name.
  ///
  /// The mirror's two `From` arms are written from this, so a name that answers to nothing upstream
  /// is `E0599` at the arm naming it. That is the whole enforcement, and it is the compiler's: a
  /// derive cannot see the upstream declaration, and a table of upstream names kept here would be a
  /// second copy of somebody else's enum.
  pub fn upstream(&self) -> syn::Ident {
    self.upstream.clone().unwrap_or_else(|| self.ident.clone())
  }
}

/// The UPSTREAM vocabulary a declaration mirrors, and what it asked to borrow from it.
///
/// A mirror RESTATES the upstream's variants — identifiers only — and delegates the whole slug
/// grammar to the upstream's own [`FromStr`](core::str::FromStr) and [`Display`](core::fmt::Display).
/// That is the single-source rule this mode is built on: there is no second table of words here for
/// the upstream's to drift from.
#[derive(Debug, Clone)]
pub struct Remote {
  /// The upstream type, as the declaration wrote it.
  pub path: syn::Path,
  /// The methods forwarded onto the materialized upstream value, each restated by the declaration.
  ///
  /// The signature is the DECLARATION'S because Rust has no `typeof`: a forwarding method needs a
  /// written return type, and the one place that type is known is the declaration doing the asking.
  pub delegates: Vec<Delegate>,
}

pub use crate::delegate::{Delegate, DelegateSkin};

/// The field a PROMOTED mirror publishes its own word at.
///
/// The one thing an object face must still be able to answer that the scalar answered by BEING the
/// word: `text` is the canonical slug, rendered exactly as the upstream renders it. Named here
/// rather than spelled at each of the three sites that need it — the emitted registry entry, the
/// emitted resolver arm, and the front end refusing a published method that would collide with it.
pub const TEXT_FIELD: &str = "text";

/// One vocabulary's declaration, validated.
///
/// Public fields for the reason [`RecordModel`](crate::model::RecordModel)'s are: nothing here
/// parses, so a front end that is not the derive builds the same struct and reaches the same
/// emitter.
#[derive(Debug, Clone)]
pub struct EnumModel {
  /// Where `ingraph` lives, for the shelf every emitted path is rooted at.
  pub krate: syn::Path,
  /// The declaration's visibility, which every emitted item takes.
  pub vis: syn::Visibility,
  /// The declared enum's own name.
  pub name: syn::Ident,
  /// The integer `#[repr(…)]` the declaration carries, when it carries one.
  pub width: Option<IntegerWidth>,
  /// Its variants, in declaration order. Never empty — an enum with none has no value.
  pub variants: Vec<EnumVariant>,
  /// The per-namespace form OVERRIDES. A namespace with no entry takes
  /// [`Namespace::default_form`].
  pub forms: BTreeMap<Namespace, StorageForm>,
  /// `graphql(rename = "…")` — what a SCHEMA calls this vocabulary, where the declaration moved it.
  ///
  /// `None` is the Rust name unraw'd, which is what [`EnumModel::sdl_name`] resolves.
  ///
  /// EMISSION-ONLY, and that is the whole of its reach: nothing in Rust and nothing in a database
  /// reads this word, so a declaration writing one keeps every minted type name, every accessor and
  /// every stored word it had. It is a `String` rather than a [`syn::Ident`] because nothing in Rust
  /// is called this — see [`EnumModel::sdl_name`] for the grammar it is held to instead.
  pub wire_name: Option<String>,
  /// What the emitted REFUSAL type is called, when the declaration named it.
  ///
  /// `None` is `<Enum>ParseError`, which is what [`EnumModel::error`] resolves. The knob exists for
  /// a COLLISION rather than for taste — see the module note — so the default is not a thing anyone
  /// has to reach for, and a declaration that names nothing is unaffected by the knob's existence.
  pub error: Option<syn::Ident>,
  /// The UPSTREAM vocabulary this declaration mirrors, when it mirrors one.
  ///
  /// `None` is the whole of today's mode and nothing about it moves: a vocabulary that names no
  /// upstream owns its own words, stores a discriminant and publishes a GraphQL `enum`. See
  /// [`remote`](self::remote) for what the other mode is and why it is a different emission rather
  /// than a flag through this one.
  pub remote: Option<Remote>,
}

impl EnumModel {
  /// The form one namespace takes: the declared override, else the namespace's own default.
  #[must_use]
  pub fn form(&self, namespace: Namespace) -> StorageForm {
    self
      .forms
      .get(&namespace)
      .copied()
      .unwrap_or_else(|| namespace.default_form())
  }

  /// The width the discriminant is stored at: the declared `#[repr(…)]`, else
  /// [`IntegerWidth::DEFAULT`].
  #[must_use]
  pub fn width(&self) -> IntegerWidth {
    self.width.unwrap_or(IntegerWidth::DEFAULT)
  }

  /// The refusal type this declaration's parses answer with — the declared name, else
  /// `GradeParseError`.
  ///
  /// The ONE authority on what that type is called: the emission writes this, and a front end's
  /// collision check asks it rather than rebuilding the suffix convention on its own side.
  #[must_use]
  pub fn error(&self) -> syn::Ident {
    self
      .error
      .clone()
      .unwrap_or_else(|| format_ident!("{}ParseError", self.name))
  }

  /// The ESCAPE variant, on a vocabulary that has one.
  ///
  /// Its presence is what says the vocabulary is OPEN — the second axis of [`emit`](Self::emit)'s
  /// four cells — and every fork in [`remote`]'s and [`own`]'s emissions reads it here rather than
  /// re-deriving the question from the variant list.
  #[must_use]
  pub fn escape(&self) -> Option<&EnumVariant> {
    self
      .variants
      .iter()
      .find(|variant| variant.escape.is_some())
  }

  /// The escape's POSTURE — which of [`Escape`]'s three the declaration wrote.
  ///
  /// Asked here rather than unwrapped at each of the six sites that fork on it, for the reason
  /// [`escape`](Self::escape) is: one question, one place it is answered.
  #[must_use]
  pub fn posture(&self) -> Option<&Escape> {
    self.escape().and_then(|variant| variant.escape.as_ref())
  }

  /// Whether this vocabulary's own parse can REFUSE a word.
  ///
  /// True of anything CLOSED — a vocabulary this crate declares, whose variants ARE the set, and a
  /// closed mirror, which reports its upstream's refusal as its own — and of a HALF-OPEN mirror,
  /// whose gate can refuse. False of the two postures that promise every word parses, which is every
  /// OPEN vocabulary this crate declares and the two total mirror postures. It is what decides
  /// whether a refusal type is declared beside the enum at all, and therefore whether
  /// `error(rename = "…")` has anything to move.
  #[must_use]
  pub fn refuses(&self) -> bool {
    self.posture().is_none_or(Escape::refuses)
  }

  /// Every variant that NAMES a member — the whole list, minus the escape.
  ///
  /// On a mirror those are the upstream names it restates; on a vocabulary this crate declares they
  /// are the roster's own. What they share is being the list a `&'static [Self]` can hold, the escape
  /// carrying a runtime word and therefore being no constant.
  pub fn restated(&self) -> impl Iterator<Item = &EnumVariant> {
    self
      .variants
      .iter()
      .filter(|variant| variant.escape.is_none())
  }

  /// The delegated methods PUBLISHED at one backend, in declaration order.
  ///
  /// The whole of the promotion law's antecedent: a mirror with none of these renders as a scalar in
  /// both positions — today's shape, unmoved — and a mirror with one or more renders its OUTPUT seat
  /// as an OBJECT and its input seat as a scalar called `<Enum>Input`. Asked HERE rather than
  /// re-derived at each of the four sites that fork on it, so a mirror cannot be promoted in one and
  /// not another.
  ///
  /// Empty for a DECLARED vocabulary, which delegates nothing: the accessor answers about the model
  /// rather than about the mode, so a caller needs no second question first.
  pub fn promoted(&self, kind: GraphqlKind) -> impl Iterator<Item = &Delegate> {
    self
      .remote
      .iter()
      .flat_map(|remote| remote.delegates.iter())
      .filter(move |delegate| delegate.wire.iter().any(|skin| skin.kind == kind))
  }

  /// Every name a MIRROR's expansion puts in the enum's own value namespace, in emission order.
  ///
  /// # What it is FOR, and why it stops at the mirror
  ///
  /// A `delegate(fn …)` entry restates a method name the author chose, and a mirror's expansion
  /// declares names of its own beside it — so the two can meet, and rustc reports the meeting as
  /// `E0592` at the derive, a span the author cannot edit and a message that never names the entry.
  /// This is the list a front end moves that report with, and the seat that makes it necessary is the
  /// MIRROR's alone: a declared vocabulary has no `delegate(…)`, so nothing an author wrote is in its
  /// namespace to collide with, and enumerating its names would be a model nothing spends.
  ///
  /// Empty for a declared vocabulary, therefore, and empty in the [`promoted`](Self::promoted) sense:
  /// the accessor answers about the model rather than about the mode, so a caller needs no second
  /// question first.
  ///
  /// # The list, and where each row comes from
  ///
  /// [`mirror_face`](remote) is the one inherent impl a mirror emits, and it declares four kinds of
  /// name in this order:
  ///
  /// | row | [`Origin`] |
  /// |---|---|
  /// | `VARIANTS`, the restated roster | [`Origin::Roster`] |
  /// | `remote()`, the materialization gate | [`Origin::Materialization`] |
  /// | one `is_…` per variant, the ESCAPE included | [`Origin::Predicate`] |
  /// | one forwarding method per MINTED delegate | [`Origin::Delegate`] |
  ///
  /// `VARIANTS` is an associated CONST and is here all the same: Rust's value namespace holds consts
  /// and functions together, so a delegate spelled `VARIANTS` is a duplicate definition exactly as a
  /// second `remote` would be.
  ///
  /// # A WAIVED entry is enumerated, and it is the one row the emission does not write
  ///
  /// `on = self` waives the forwarding mint, so nothing is emitted for that entry — but the word says
  /// the method exists on this type, written by the author's own hand, and that method occupies the
  /// namespace exactly as a mint would. The question this list answers is which names are TAKEN, not
  /// which tokens this emitter wrote, so a waived entry is a row. It is the one asymmetry, and the
  /// pin against the emission is stated over declarations that carry no waiver for that reason.
  #[must_use]
  pub fn emitted_methods(&self) -> Vec<Emitted> {
    let Some(remote) = self.remote.as_ref() else {
      return Vec::new();
    };
    let fixed = [
      (format_ident!("VARIANTS"), Origin::Roster),
      (format_ident!("remote"), Origin::Materialization),
    ];
    let predicates = self.variants.iter().map(|variant| {
      (
        variant.predicate(),
        Origin::Predicate(variant.ident.clone()),
      )
    });
    let delegated = remote.delegates.iter().map(|delegate| {
      let method = delegate.signature.ident.clone();
      (method.clone(), Origin::Delegate(method))
    });
    fixed
      .into_iter()
      .chain(predicates)
      .chain(delegated)
      .map(|(name, origin)| Emitted {
        owner: Owner::Record,
        owner_name: self.name.clone(),
        name,
        origin,
      })
      .collect()
  }

  /// The whole expansion: the refusal type, then the rows, the face and the wire.
  ///
  /// The impls sit in anonymous `const _: () = { … };` blocks, as a record's do — it changes nothing
  /// about reaching them and it gives the per-backend mapping functions a scope where they can
  /// collide with nothing the declaring module wrote. The refusal type cannot: it is named in
  /// signatures a caller writes.
  ///
  /// The WIRE face is a second block rather than a member of this one, because the whole of it sits
  /// behind the binding gate: a build without `async-graphql` expands the block's contents to
  /// nothing, and keeping it separate is what lets that be true of a gate wrapping the block's whole
  /// body rather than of a `cfg` sprinkled through this one.
  ///
  /// # FOUR CELLS, and the declaration's own SHAPE picks one
  ///
  /// There is no word for the mode. Two structural facts decide it — whether `remote = "…"` names an
  /// upstream, and whether a variant wears `#[ingraph(other)]` — and the four combinations are the
  /// whole grammar:
  ///
  /// | | no escape | an `#[ingraph(other)]` escape |
  /// |---|---|---|
  /// | **no `remote`** | a CLOSED vocabulary this crate declares — below | an OPEN one, [`own`] |
  /// | **`remote = "…"`** | a closed MIRROR, [`remote`] | an open mirror, [`remote`] |
  ///
  /// The forks are not four emissions. A mirror's words are its upstream's, so its face, parses,
  /// stored form and wire all differ and [`remote`] writes them; an open vocabulary this crate
  /// declares owns its words like the closed one below and stores them like a mirror, so [`own`]
  /// writes the half that is neither and shares the rest with both.
  #[must_use]
  pub fn emit(&self) -> proc_macro2::TokenStream {
    if let Some(remote) = self.remote.as_ref() {
      return self.emit_mirror(remote);
    }
    if let Some(escape) = self.escape() {
      return self.emit_open(escape);
    }
    let error = self.refusal();
    let reading = self.reading();
    let face = self.face();
    let parsing = self.parsing();
    let key = self.key_delegation();
    let storage = DatabaseKind::ALL
      .into_iter()
      .map(|database| self.storage_rows(database));
    let width = self.width_row();
    let read = self.read_row();
    let wire = self.graphql_face();
    quote! {
      #error

      const _: () = {
        #reading
        #face
        #parsing
        #key
        #width
        #read
        #(#storage)*
      };

      #wire
    }
  }

  /// KEY ADMISSION: the row that lets a column of this vocabulary be a record's `#[ingraph(id)]` or
  /// an aggregate's group projection, and it costs a declaration NO word.
  ///
  /// The id vocabulary is sealed and admits a type from outside it on one law — TRANSPARENCY, stated
  /// as `unsafe impl DelegatesId`. A closed vocabulary satisfies that law exactly: its value IS one
  /// of a fixed set of words, the words are the declaration's own canonical spellings, and the front
  /// end already refuses two variants that would share one — so the map from value to word is a
  /// bijection. Writing the row here is what makes the ergonomics claim true: a declarer reaches for
  /// `#[derive(ingraph::Enum)]` for the column faces and gets the KEY face in the same line.
  ///
  /// # An OPEN vocabulary gets the row too, and its `Inner` is the CARRIER the declaration wrote
  ///
  /// The first cut of this row stopped at the closed shape, on the argument that an escape carries a
  /// RUNTIME word — no `&'static` for that arm, and no single `Inner` both arms could share. The
  /// first half is true and the second is not, and the difference is one token: the escape's payload
  /// TYPE is written at the declaration, so the emission can name it.
  /// [`open_key_delegation`](Self::open_key_delegation) is what that buys — `Inner` is the carrier,
  /// the named arms hold `static`s OF THE CARRIER, and the escape arm hands back the field it already
  /// holds.
  ///
  /// Which matters because the escape is not an exotic corner: it is the vocab train's STANDARD
  /// shape. Every mirrored household — `AudioCodec`, `PixelFormat`, `ColorPrimaries` — restates the
  /// members it names and carries `Other(Utf8Bytes)` for the ones it does not, so a boundary drawn at
  /// the escape would have excluded the common case and admitted the rare one.
  ///
  /// # `Utf8Bytes`, behind a `LazyLock`, and both halves are measured
  ///
  /// The CLOSED row's text member is `Utf8Bytes` because that is this house's text carrier wherever
  /// one is reached for, and because a word that fits the inline capacity is held without allocating
  /// at all — which every variant name does. An OPEN one takes the declaration's carrier instead, for
  /// the reason above; nothing else about the row differs.
  ///
  /// The `LazyLock` is the dependency floor rather than a preference. The trait hands back a BORROW
  /// and a unit variant holds no field, so the word has to live in a `static`; `from_static` became
  /// `const fn` in `smol-bytes` 0.1.4, and this crate's floor is `0.1`, which a PATCH floor is not
  /// written to raise. So the word is initialised once, on first use, and every call after that is a
  /// load. Where the floor rises to a minor version carrying the `const` constructor, the `LazyLock`
  /// becomes a plain `static` and nothing else here moves.
  ///
  /// # This word and the CURSOR's are both injective, and need not be the same word
  ///
  /// A declared vocabulary's cursor pages by `as_str`, which IS the canonical word, so those two
  /// agree by construction. A MIRROR's cursor pages by the upstream's own `Display`, which is a call
  /// rather than a constant and therefore cannot be a `static` — so its segment is the mirror's own
  /// canonical word instead. Nothing requires the two to match: a `u64`'s cursor is eight big-endian
  /// bytes and its segment is decimal, and what each duty owes is injectivity in ITS OWN form.
  fn key_delegation(&self) -> proc_macro2::TokenStream {
    if let Some(escape) = self.escape() {
      return self.open_key_delegation(escape);
    }
    let name = &self.name;
    let delegates = self.framework(&["id"], "DelegatesId");
    let text = self.framework(&["smol_bytes"], "Utf8Bytes");
    let arms = self.variants.iter().map(|variant| {
      let ident = &variant.ident;
      let word = variant.canonical();
      quote! {
        Self::#ident => {
          static __INGRAPH_WORD: ::std::sync::LazyLock<#text> =
            ::std::sync::LazyLock::new(|| <#text>::from_static(#word));
          ::std::sync::LazyLock::force(&__INGRAPH_WORD)
        }
      }
    });
    quote! {
      // SAFETY: a closed vocabulary IS its word. Every variant is a unit — no payload, no width and
      // no second field a key would have to tell apart — and the canonical words are checked
      // distinct at the declaration, so two values are equal exactly when their words are. The body
      // is a match over `self` and nothing else, so it is pure and answers one word per value.
      #[automatically_derived]
      unsafe impl #delegates for #name {
        type Inner = #text;

        #[inline]
        fn delegate(&self) -> &#text {
          match self {
            #(#arms)*
          }
        }
      }
    }
  }

  /// KEY ADMISSION for an OPEN vocabulary — the second arm of [`key_delegation`], in either mode.
  ///
  /// `Inner` is the CARRIER the declaration wrote on its escape, and the two kinds of arm meet in it:
  /// a named member hands back a `static` holding its own word, and the escape hands back the word it
  /// is already carrying. One `Inner`, one borrow per arm, and no allocation on either road.
  ///
  /// # A non-carrier payload fails at the DECLARATION, and this row is where the sentence lives
  ///
  /// This emission knows the payload's token and nothing else about it. It builds a word through
  /// [`carrier_obligation`](Self::carrier_obligation) — `From<&'static str>` wearing a name, which is
  /// half the pair `new` and the mirror's `From<Remote>` arm already build escapes with, so a type
  /// that holds a word for this vocabulary at all satisfies it.
  ///
  /// The NAME is the point. A payload that is not a text carrier was already `E0277` at the
  /// declaration, twice, and both reports landed on the DERIVE's own token and named `From<&str>` and
  /// `AsRef<str>` with nothing to connect either to an escape. This row's is the third and the only
  /// one that lands on the FIELD the author wrote — so the report naming the author's own token is
  /// also the one that says what a carrier is.
  ///
  /// A payload that IS a text carrier but is not a member of the sealed id set compiles, says a true
  /// thing about itself, and is refused at the KEY POSITION, which is the delegation law's own posture
  /// for a chain that grounds in nothing.
  ///
  /// # What the named arm's WORD is, and why it is the face's rather than the model's
  ///
  /// It is the word this vocabulary's own face spells that variant with, wherever that word is a
  /// constant:
  ///
  /// | mode | the named arm's word | and it is |
  /// |---|---|---|
  /// | a vocabulary this crate DECLARES | [`folded`](EnumVariant::folded) | exactly `as_str`, so the key word, the stored word and the cursor word are ONE word |
  /// | a MIRROR | [`canonical`](EnumVariant::canonical) | the mirror's own name — its face word is the upstream's `Display`, which is a call and cannot be a `static` |
  ///
  /// # INJECTIVITY, and where each mode's is held
  ///
  /// A key's whole obligation is that two values equal exactly when their delegates are, so the two
  /// KINDS of arm must not collide — an escape whose carried word is some member's word would put two
  /// distinct values on one row.
  ///
  /// **A vocabulary this crate declares holds it by construction, through its own door.** `new`
  /// walks the roster under `folds_to` BEFORE it builds an escape, so a word that folds to a member's
  /// word reaches that member and never becomes an escape; and what the escape carries is
  /// `name::folded` of the arriving spelling, which is separator-free lower-case, while a member's
  /// word is its `folded` spelling. The two arms therefore cannot meet on a value the door built.
  ///
  /// **A mirror holds it the same way, one crate over.** The `From<Remote>` arm list routes every
  /// upstream value this mirror RESTATES to its own named arm, and only what is left reaches the
  /// wildcard that builds an escape — so an escape carries the rendering of an upstream value the
  /// mirror does not name, and a named arm's word is a Rust identifier this declaration wrote. Two
  /// named arms cannot collide either: they are distinct identifiers, and `rename` does not move a
  /// mirror's canonical word.
  ///
  /// **A HAND-BUILT escape is the one shadowing, and it is not new.** Nothing stops a declaring crate
  /// writing `Codec::Other("aac".into())` beside `Codec::Aac` in its own source, and such a value is
  /// already indistinguishable from the member at the STORED COLUMN, at the CURSOR and on the WIRE —
  /// an open vocabulary's `as_str` answers the carried word verbatim, and a mirror renders through
  /// `remote()`, which parses the word straight back onto the member. So the key row inherits exactly
  /// the invariant the rest of the vocabulary already rides on, adds no new hazard, and the door is
  /// what upholds it — which is what the `unsafe` on the emitted impl asserts.
  fn open_key_delegation(&self, escape: &EnumVariant) -> proc_macro2::TokenStream {
    // A model that marked an escape and recorded no carrier has nothing to write `Inner` with. The
    // derive always records one — the front end refuses an escape that is not exactly one unnamed
    // field — so this is the OTHER front end's cell, and what it costs is the key row alone.
    let Some(carrier) = escape.carrier.as_ref() else {
      return quote!();
    };
    let name = &self.name;
    let escaped = &escape.ident;
    let delegates = self.framework(&["id"], "DelegatesId");
    let mirrors = self.remote.is_some();
    let arms = self
      .restated()
      .map(|variant| {
        let ident = &variant.ident;
        let word = if mirrors {
          variant.canonical()
        } else {
          variant.folded()
        };
        quote! {
          Self::#ident => {
            static __INGRAPH_WORD: ::std::sync::LazyLock<#carrier> = ::std::sync::LazyLock::new(
              || <#carrier as __IngraphCarriesAWord>::__ingraph_word(#word),
            );
            ::std::sync::LazyLock::force(&__INGRAPH_WORD)
          }
        }
      })
      .collect::<Vec<_>>();
    let obligation = (!arms.is_empty()).then(|| self.carrier_obligation());
    quote! {
      #obligation

      // SAFETY: an open vocabulary IS a word too — one of the roster's, or the one the escape
      // carries. Every named variant is a unit and the escape holds exactly one field, so there is
      // no second field, tag or width a key would have to tell apart, and the two kinds of arm
      // cannot collide on a value this vocabulary's own door built — see the method note for where
      // each mode's injectivity is held. The body is a match over `self` and nothing else, so it is
      // pure and answers one word per value.
      #[automatically_derived]
      unsafe impl #delegates for #name {
        type Inner = #carrier;

        #[inline]
        fn delegate(&self) -> &#carrier {
          match self {
            #(#arms)*
            Self::#escaped(__ingraph_word) => __ingraph_word,
          }
        }
      }
    }
  }

  /// What an escape's CARRIER has to be, declared BESIDE the key row so the refusal for a payload
  /// that is not one carries a sentence.
  ///
  /// The obligation itself is `From<&'static str>`, which is half the pair the door already spends —
  /// so this asks a declaration for nothing it was not already asked for, and a carrier that holds a
  /// word at all satisfies it. What the trait adds is a NAME for the obligation, and a name is what
  /// `#[diagnostic::on_unimplemented]` attaches to.
  ///
  /// # Declared in the EXPANSION rather than in the framework, and the reason is a golden
  ///
  /// A trait on this crate's own shelf would be reported at two different paths on two toolchains —
  /// stable names where it is DEFINED and nightly the re-export an expansion travels — which is the
  /// divergence class `ci/nightly-divergences.md` exists for, arriving in a lane that has none. A
  /// trait declared inside the expansion has one spelling everywhere, so the refusal's golden is the
  /// same text on both chains. It is also the device the mirror's totality claim already uses
  /// (`__IngraphTotalFromStr`), so this is the house's own shape rather than a second one.
  ///
  /// # [`do_not_recommend`](diagnostic::do_not_recommend) on the blanket, and it is load-bearing
  ///
  /// Unmarked, the refusal peels to the blanket's own `where` clause — *the trait bound
  /// `u32: From<&'static str>` is not satisfied* — and the sentence below becomes a *required for*
  /// note under it, which is the message buried rather than said. Marked, the report is the root
  /// bound and its own notes, which is the same reason `composed_slot_shape`'s second fixture reaches
  /// for the attribute.
  ///
  /// # Emitted only where there is a WORD to build
  ///
  /// A vocabulary whose only variant is the escape has no named arm, hence no `static`, hence nothing
  /// to spend the bound on — and an unspent obligation would be an unused trait in a declaring
  /// crate's own module, which is a `dead_code` warning somebody else has to silence.
  fn carrier_obligation(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let message = "`{Self}` cannot carry an `#[ingraph(other)]` escape's word";
    let carrier = format!(
      "an escape holds a WORD, so its field's type has to be a TEXT CARRIER: buildable from one \
       (`From<&str>`) and readable back as one (`AsRef<str>`). `ingraph::Utf8Bytes` is the house's, \
       and `String` and `SmolStr` are carriers too — `{name}`'s escape is where the choice is \
       written, and it is the whole of what this vocabulary asks of it"
    );
    let key = "the bound is spent by the KEY row, which is what lets a vocabulary stand at an \
               `#[ingraph(id)]` or an aggregate's group column with no extra word: the named \
               members delegate to `static`s of the carrier and the escape delegates the word it \
               carries, so the carrier is also what such a key ADDRESSES by. A text carrier that is \
               not a member of the sealed id vocabulary compiles here and is refused at the KEY \
               POSITION instead — see `ingraph::Id`";
    quote! {
      #[diagnostic::on_unimplemented(
        message = #message,
        label = "not a text carrier",
        note = #carrier,
        note = #key,
      )]
      trait __IngraphCarriesAWord {
        fn __ingraph_word(word: &'static ::core::primitive::str) -> Self;
      }

      #[diagnostic::do_not_recommend]
      impl<T: ::core::convert::From<&'static ::core::primitive::str>> __IngraphCarriesAWord for T {
        #[inline]
        fn __ingraph_word(word: &'static ::core::primitive::str) -> Self {
          ::core::convert::From::from(word)
        }
      }
    }
  }

  /// The enum's COLUMN WIDTH: one, whichever form it stores as.
  ///
  /// Outside every gate and stated once, where the carrier rows are per backend and inside theirs.
  /// That is `ColumnKind` carrying no dialect: a declared enum is one column as text and one as an
  /// integer, so the fact has no backend to vary with — and a build compiling no SQL family still
  /// needs the row, because the trait it satisfies names no database either.
  ///
  /// It takes the DEFAULT and states nothing, which is the whole content of *this is one column*.
  fn width_row(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let column_kind = self.framework(&["column"], "ColumnKind");
    let column_eq = self.framework(&["column"], "ColumnEq");
    quote! {
      #[automatically_derived]
      impl #column_kind for #name {}

      // The SAMENESS row beside the width row, outside every gate for that row's reason: two words
      // of a vocabulary are one column value or they are not, and no dialect changes the answer.
      //
      // Its body is the enum's OWN `PartialEq`, which is the trait a stored vocabulary has always
      // owed — an emitted row derived `PartialEq` over its declared field types until this face
      // existed. What moved is where the demand is MADE: here, at the declaration that wrote the
      // enum, instead of inside a record's expansion the author cannot edit.
      #[automatically_derived]
      impl #column_eq for #name {
        #[inline]
        fn column_eq(&self, __ingraph_other: &Self) -> ::core::primitive::bool {
          ::core::cmp::PartialEq::eq(self, __ingraph_other)
        }
      }
    }
  }

  /// How a holder's row READS one of these back: as the one column its width says it is.
  ///
  /// It is the third of the three facts a stored type states — the width above, this, and the per
  /// backend `Carrier` below — and a declared enum needs all three the moment a record stores one:
  /// an emitted decode writes ONE uniform spelling per field, because `codec: Codec` and
  /// `tb: Timebase` are the same tokens, so the type is what answers whether that spelling fetches
  /// one column or several.
  ///
  /// Generic over the ROW and stated once, where the carrier rows are per backend: what varies per
  /// dialect is the `Decode` this delegates to, and stating it as an obligation is what lets one impl
  /// serve every dialect the declaration's own rows cover.
  ///
  /// The FAMILY gate rather than a dialect's, and rather than none: the trait is `sqlx::Row`'s
  /// vocabulary, so a build with no SQL family has no trait for this to implement — while a build
  /// with two would get this impl twice if it rode the per-dialect gates the storage rows ride.
  fn read_row(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let gate = self.framework(&["gate"], "if_sqlx");
    let assemble = self.framework(&["column"], "Assemble");
    let plain_column = self.framework(&["column"], "plain_column");
    let path = self.framework(&["comparison"], "Path");
    let row_trait = self.framework(&["sqlx"], "Row");
    let decode = self.framework(&["sqlx"], "Decode");
    let sqlx_type = self.framework(&["sqlx"], "Type");
    let column_index = self.framework(&["sqlx"], "ColumnIndex");
    let result = self.framework(&["sqlx"], "Result");
    let row = crate::emit::parameter("ROW");
    quote! {
      #gate! {
        #[automatically_derived]
        impl<'__ingraph, #row> #assemble<'__ingraph, #row> for #name
        where
          #row: #row_trait,
          #name: #decode<'__ingraph, <#row as #row_trait>::Database>
            + #sqlx_type<<#row as #row_trait>::Database>,
          for<'__ingraph_name> &'__ingraph_name ::core::primitive::str: #column_index<#row>,
        {
          #[inline]
          fn assemble(
            __row: &'__ingraph #row,
            __ingraph_under: ::core::option::Option<&#path<'_>>,
          ) -> #result<Self> {
            #plain_column(__row, __ingraph_under)
          }
        }
      }
    }
  }

  /// A path to one of the names the framework SHELVES, reached the ONE way emitted code may reach
  /// them — the same rule and the same shape [`RecordModel`](crate::model::RecordModel)'s emission
  /// obeys.
  fn framework(&self, module: &[&str], name: &str) -> proc_macro2::TokenStream {
    let krate = &self.krate;
    let module = module.iter().map(|segment| format_ident!("{segment}"));
    let name = format_ident!("{name}");
    quote!(#krate::__private #(:: #module)* :: #name)
  }

  /// The name type one namespace's word is carried as.
  fn name_type(&self, namespace: Namespace) -> proc_macro2::TokenStream {
    self.framework(&["name"], namespace.name_type())
  }

  /// The refusal every parse into this vocabulary answers with.
  ///
  /// OPAQUE — a private unit field, so nothing outside the declaring module constructs one and
  /// nothing anywhere reads a detail out of it. What went wrong is already known at the call site:
  /// the text handed in names no variant, and there is no second way to fail.
  fn refusal(&self) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let name = &self.name;
    let error = self.error();
    let sentence = format!("`{name}`: no variant answers to this name");
    let doc = format!(
      "The refusal a text that names no variant of [`{name}`] gets.\n\nOpaque: it carries no \
       detail, because there is only one way to fail — the word is not one of this vocabulary's."
    );
    // Every std name QUALIFIED, derive macros included — an expansion lands in a module the
    // framework does not control, and a bare `Debug` there resolves to whatever that module wrote.
    // This block was the one place in the emitter that still spelled them bare.
    quote! {
      #[doc = #doc]
      #[derive(
        ::core::fmt::Debug,
        ::core::clone::Clone,
        ::core::marker::Copy,
        ::core::cmp::PartialEq,
        ::core::cmp::Eq
      )]
      #vis struct #error(());

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

      #[automatically_derived]
      impl ::core::error::Error for #error {}
    }
  }

  /// The rows that say how a COLUMN of this type is READ: its filter, the interpretation a column
  /// inherits when it names no word, the interpretation a COLLECTION of it inherits, and the codec a
  /// keyset cursor pages past it with.
  ///
  /// All four are ungated framework rows. The first two are what makes a vocabulary filterable at
  /// all; the last is what the storability audit demands of every persisted column, since a page
  /// resumes by binding the last row's values back.
  ///
  /// # The `Vec` row, and the two positions it serves
  ///
  /// `DefaultVecMarker` is what every type the framework registers itself takes from `to_filter!`,
  /// and a declared vocabulary is as registerable as any of them — so a `Vec<TheirEnum>` naming no
  /// word had no default reading where a `Vec<i64>` had one. It is a LIST, which is `to_filter!`'s
  /// own default for every element that does not say otherwise, and a word on the field still beats
  /// it.
  ///
  /// It pays TWICE, and that is why it is emitted rather than left as a gap: the OUTPUT crossing
  /// reads its collection fork off this same row, so this one line is what gives a `Vec` of the
  /// vocabulary both a filter and a wire form. A second emitted row on an element-keyed output trait
  /// used to carry the output half; that trait is retired, and the fact it stated is this one.
  fn reading(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let markers = self.markers();
    let cursor_value = self.framework(&["cursor"], "CursorValue");
    let canonical = self.canonical_map();
    quote! {
      #markers

      // The CANONICAL word rather than the stored one, and it has to be: a cursor is minted by one
      // process and handed back to another, which may be talking to a different dialect — so the
      // codec belongs to the TYPE and cannot be per-backend, where a stored form now is. Its bytes
      // are checked coming back for the reason every row in that module checks its own: the bytes
      // are a client's.
      #[automatically_derived]
      impl #cursor_value for #name {
        fn write_cursor(&self, out: &mut ::std::vec::Vec<::core::primitive::u8>) {
          out.extend_from_slice(Self::as_str(self).as_bytes());
        }

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

  /// The three INTERPRETATION rows a vocabulary is filtered through, in either mode.
  ///
  /// What `to_filter!` writes for a type the framework itself registers, written here for a type it
  /// cannot see: the family the value is read under, the filter that family carries, and what a
  /// `Vec` of it means. A MIRROR earns them unchanged — its operand is a variant set whichever crate
  /// declared the vocabulary, so the reading is the same one and only the WORDS come from elsewhere.
  fn markers(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let filter_marker = self.framework(&["marker"], "EnumFilterMarker");
    let filter = self.framework(&["graphql"], "EnumFilter");
    let default_marker = self.framework(&["marker"], "DefaultMarker");
    let default_vec_marker = self.framework(&["marker"], "DefaultVecMarker");
    let list_marker = self.framework(&["marker"], "ListMarker");
    let marker = self.framework(&["marker"], "EnumMarker");
    quote! {
      #[automatically_derived]
      impl #filter_marker for #name {
        type Filter = #filter<#name>;
      }

      #[automatically_derived]
      impl #default_marker for #name {
        type Marker = #marker<#name>;
      }

      #[automatically_derived]
      impl #default_vec_marker for #name {
        type Marker = #list_marker<::std::vec::Vec<#name>, #marker<#name>>;
      }
    }
  }

  /// The METHOD face: the variant list, the predicates, the canonical word and one accessor per
  /// text namespace.
  ///
  /// Hand-emitted rather than derived. What a `derive_more` would bring is a foreign crate path in
  /// somebody's expanded code and a foreign error type in the signatures — and the vocabulary is the
  /// one kind whose whole content is its own names, so the family is written here and the paths are
  /// this emitter's.
  fn face(&self) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let name = &self.name;
    let variants = self.variants.iter().map(|variant| {
      let variant = &variant.ident;
      quote!(Self::#variant)
    });
    let predicates = self.variants.iter().map(|variant| {
      let ident = &variant.ident;
      let predicate = variant.predicate();
      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, Self::#ident)
        }
      }
    });
    let canonical = self.arms(|variant| {
      let word = variant.canonical();
      quote!(#word)
    });
    let accessors = Namespace::ALL
      .into_iter()
      .filter(|namespace| self.form(*namespace) == StorageForm::Text)
      .map(|namespace| self.accessor(namespace));
    let variants_doc = format!(
      "Every variant of [`{name}`], in DECLARATION order.\n\nThe order is the declaration's, so a \
       schema rendered from this reads as the enum does."
    );
    let canonical_doc = format!(
      "This variant's CANONICAL word — its global `rename`, else the name [`{name}`] spells it \
       with.\n\nThe namespace [`FromStr`](core::str::FromStr) parses, and the one every face \
       defaults from."
    );
    quote! {
      #[automatically_derived]
      impl #name {
        #[doc = #variants_doc]
        #vis const VARIANTS: &'static [Self] = &[#(#variants),*];

        #[doc = #canonical_doc]
        #[inline]
        #[must_use]
        #vis const fn as_str(&self) -> &'static ::core::primitive::str {
          match self { #canonical }
        }

        #(#accessors)*

        #(#predicates)*
      }
    }
  }

  /// One namespace's accessor, handing back ITS name type.
  ///
  /// A TEXT face only. An integer face has no word for a name type to hold, so the method is absent
  /// rather than answering with the discriminant's rendering — the form decides the face, and a
  /// caller asking a machine-facing backend for a name is asking for something that is not there.
  fn accessor(&self, namespace: Namespace) -> proc_macro2::TokenStream {
    let vis = &self.vis;
    let accessor = namespace.accessor();
    let name_type = self.name_type(namespace);
    let arms = self.arms(|variant| {
      let word = variant.name(namespace);
      quote!(#word)
    });
    let doc = format!(
      "This variant's word in the `{}` namespace.\n\nPresent because that face takes the TEXT \
       form; a face storing the discriminant has none.",
      namespace.as_str()
    );
    quote! {
      #[doc = #doc]
      #[inline]
      #[must_use]
      #vis const fn #accessor(&self) -> &'static #name_type {
        #name_type::new(match self { #arms })
      }
    }
  }

  /// The PARSING half of the face: `FromStr` over the canonical namespace, and one
  /// `TryFrom<&…Name>` per text namespace.
  ///
  /// One impl per namespace and no coherence collision between them, which is the whole reason the
  /// names are types: `TryFrom<&str>` could be written once and would have to pick a face.
  fn parsing(&self) -> proc_macro2::TokenStream {
    let name = &self.name;
    let error = self.error();
    let canonical = self.canonical_map();
    let canonical_map = self.reverse_map(&canonical, EnumVariant::canonical);
    let texts: Vec<Namespace> = Namespace::ALL
      .into_iter()
      .filter(|namespace| self.form(*namespace) == StorageForm::Text)
      .collect();
    let maps = texts.iter().map(|namespace| {
      self.reverse_map(&self.reader(*namespace), |variant| variant.name(*namespace))
    });
    let conversions = texts.iter().map(|namespace| self.conversion(*namespace));
    quote! {
      #canonical_map
      #(#maps)*

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

        fn from_str(text: &::core::primitive::str) -> ::core::result::Result<Self, Self::Err> {
          match #canonical(text) {
            ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
            ::core::option::Option::None => ::core::result::Result::Err(#error(())),
          }
        }
      }

      #(#conversions)*
    }
  }

  /// One namespace's conversion, over a BORROW of its name type.
  ///
  /// The reference is not a choice: a name type is a `#[repr(transparent)]` view of a `str` and
  /// therefore unsized, where `TryFrom`'s type parameter carries an implicit `Sized` bound. It also
  /// costs nothing — every reader of one of these already holds a borrow, `new` handing back a
  /// `&Self` and the accessor above a `&'static Self`.
  ///
  /// The word reaches the map through the `Deref` coercion, at an argument position whose type is
  /// known — which is how every reader of one of these takes it.
  fn conversion(&self, namespace: Namespace) -> proc_macro2::TokenStream {
    let name = &self.name;
    let error = self.error();
    let name_type = self.name_type(namespace);
    let reader = self.reader(namespace);
    quote! {
      #[automatically_derived]
      impl ::core::convert::TryFrom<&#name_type> for #name {
        type Error = #error;

        fn try_from(name: &#name_type) -> ::core::result::Result<Self, Self::Error> {
          match #reader(name) {
            ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
            ::core::option::Option::None => ::core::result::Result::Err(#error(())),
          }
        }
      }
    }
  }

  /// The reverse map for the CANONICAL namespace — what `FromStr` and the cursor both read through.
  fn canonical_map(&self) -> syn::Ident {
    format_ident!("__ingraph_of_canonical")
  }

  /// The reverse map for ONE namespace — what its conversion and, where that namespace stores text,
  /// its `Decode` both read through.
  fn reader(&self, namespace: Namespace) -> syn::Ident {
    format_ident!("__ingraph_of_{}", namespace.as_str())
  }

  /// One word-to-variant map, written ONCE per namespace and called from every reader of it.
  ///
  /// Two readers of one namespace with a `match` each is two tables that can come to disagree, and
  /// the disagreement is invisible: each is correct in isolation, and what breaks is only the pair.
  ///
  /// A `match` on the words rather than a chain of comparisons, so two variants sharing a word in
  /// one namespace would be an `unreachable_patterns` warning at the declaration — the parser
  /// refuses that case outright, and this is what would catch a front end that did not.
  fn reverse_map(
    &self,
    reader: &syn::Ident,
    of: impl Fn(&EnumVariant) -> String,
  ) -> proc_macro2::TokenStream {
    let name = &self.name;
    let arms = self.variants.iter().map(|variant| {
      let ident = &variant.ident;
      let word = of(variant);
      quote!(#word => ::core::option::Option::Some(#name::#ident),)
    });
    quote! {
      fn #reader(text: &::core::primitive::str) -> ::core::option::Option<#name> {
        match text {
          #(#arms)*
          _ => ::core::option::Option::None,
        }
      }
    }
  }

  /// One arm per variant, `Self::V => <what>`.
  fn arms(
    &self,
    of: impl Fn(&EnumVariant) -> proc_macro2::TokenStream,
  ) -> proc_macro2::TokenStream {
    let arms = self.variants.iter().map(|variant| {
      let ident = &variant.ident;
      let value = of(variant);
      quote!(Self::#ident => #value,)
    });
    quote!(#(#arms)*)
  }

  /// One backend's four storage rows, behind its gate — or nothing, where the backend stores no
  /// vocabulary yet.
  fn storage_rows(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
    let Some(namespace) = Namespace::ALL
      .into_iter()
      .find(|namespace| namespace.database() == Some(database))
    else {
      return quote!();
    };
    if !database.is_sql() {
      // MongoDB, whose row has a design and no lane — see the module note. Its NAMESPACE is emitted
      // above with the others, which is what a hand-written `MongoCarrier` is written in terms of.
      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");

    // The WORD a `CREATE TABLE` declares this column with, asked of the form this backend stores —
    // one road for both forms and no word spelled here. `String` rather than `str` for the text
    // arm: `str` answers a WIDTH and nothing else and has no `StoredAs` row by design, where the
    // owned form is what every dialect's text column is declared as. See `StoredAs`, where the
    // spelling law is.
    let stored_as = self.framework(&["column"], "StoredAs");
    let (stored, borrowed, maps, bind, of_stored, refused, declared) = match self.form(namespace) {
      StorageForm::Text => {
        let accessor = namespace.accessor();
        let reader = self.reader(namespace);
        (
          quote!(::core::primitive::str),
          // The bind is the BORROWED view of a `&'static str`, never an owned copy: `push_bind`
          // takes its lifetime free, so a static needs no allocation to reach a query. It is the
          // bargain `borrowed_carriers!` already makes for `String`.
          quote!(&'__ingraph ::core::primitive::str),
          quote!(),
          // Both directions reach the FACE's own tables rather than a second pair written here: the
          // word this backend stores IS the word its accessor hands out and its conversion reads,
          // and two matches over one namespace are two things that can come to disagree.
          //
          // The typed `let` is what takes the accessor's `&'static <Face>Name` down to the `&str`
          // sqlx binds — a name is a `#[repr(transparent)]` view, so this is the `Deref` coercion
          // and not a conversion. It is written out because `push_bind` INFERS its parameter, which
          // is the one position on this path where a coercion has no expected type to fire against.
          quote!({
            let stored: &'static ::core::primitive::str = #name::#accessor(self);
            stored
          }),
          quote!(#reader(stored)),
          format!("{name}: the stored text names no variant of this enum"),
          quote!(::std::string::String),
        )
      }
      StorageForm::Integer => {
        let width = self.width().wire(database);
        let primitive = format_ident!("{}", width.as_str());
        let stored_fn = format_ident!("__ingraph_{}_stored", namespace.as_str());
        let of_stored_fn = format_ident!("__ingraph_{}_of_stored", namespace.as_str());
        (
          quote!(::core::primitive::#primitive),
          quote!(::core::primitive::#primitive),
          self.integer_maps(&stored_fn, &of_stored_fn, &primitive),
          quote!(#stored_fn(self)),
          quote!(#of_stored_fn(stored)),
          format!("{name}: the stored discriminant names no variant of this enum"),
          quote!(::core::primitive::#primitive),
        )
      }
    };

    quote! {
      #gate! {
        #maps

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

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

        // Only `encode_by_ref` is written. `produces` is the per-VALUE type override and
        // `size_hint` the buffer estimate, and the stored form answers both from its own impl
        // already — there is no vocabulary-level answer either could carry that would differ.
        #[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> {
            <#borrowed as #encode<'__ingraph, #backend>>::encode(#bind, 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 = <#borrowed as #decode<'__ingraph, #backend>>::decode(value)?;
            match #of_stored {
              ::core::option::Option::Some(value) => ::core::result::Result::Ok(value),
              // A static message rather than one quoting the stored value: the row that would
              // interpolate it is the one holding a value the schema says should not be there, and
              // this crate has no format machinery on the shelf to render it with.
              ::core::option::Option::None => ::core::result::Result::Err(#error::from(#refused)),
            }
          }
        }

        // The FOURTH face, beside the width above and the three crossings here: what a
        // `CREATE TABLE` declares this column as. It is the STORED FORM's own word rather than one
        // chosen here — a text-stored enum is declared exactly as a `String` column and an
        // integer-stored one exactly as its width — so a vocabulary that changes form changes its
        // declaration with it and neither can be moved alone.
        //
        // Per DATABASE and inside this gate, where the width row above is one impl over every
        // dialect: a width is not a dialect's fact and a WORD is nothing else.
        #[automatically_derived]
        impl #stored_as<#backend> for #name {
          const WORDS: &'static [&'static ::core::primitive::str] =
            <#declared as #stored_as<#backend>>::WORDS;
        }

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

  /// The CONCRETE backend type one database is.
  ///
  /// The one place a vocabulary's emission names a backend, and what buys the exception is the gate
  /// around it — the same trade [`DatabaseBackend::vocabulary`](crate::emit) makes for a record's
  /// storability audit, and for the same reason: a concrete impl is where a column's crossing is
  /// actually checked.
  fn backend(&self, database: DatabaseKind) -> proc_macro2::TokenStream {
    match database {
      DatabaseKind::Sqlite => self.framework(&["sqlx"], "Sqlite"),
      DatabaseKind::Postgres => self.framework(&["sqlx"], "Postgres"),
      DatabaseKind::Mysql => self.framework(&["sqlx"], "MySql"),
      DatabaseKind::Mongo => self.framework(&["comparison", "mongo"], "Mongo"),
    }
  }

  /// Both directions of the INTEGER form, at the width this backend binds.
  ///
  /// Every arm casts the VARIANT rather than the matched value, which is what keeps the
  /// declaration's own `= 9` authoritative: `Grade::High as u8` is the discriminant the declaration
  /// wrote, where a literal written here would be a second numbering free to disagree with it.
  /// Casting the variant PATH rather than `*value` is also what keeps the emission from requiring
  /// [`Copy`]. The cast is exact by construction — the width is the declaration's `#[repr(…)]`, or
  /// wider where the dialect has no such type.
  ///
  /// The reverse uses guards rather than patterns, because `Grade::High as u8` is a constant
  /// EXPRESSION and not a pattern. Nothing is lost to first-wins: rustc already refuses an enum
  /// whose two variants share a discriminant.
  fn integer_maps(
    &self,
    stored: &syn::Ident,
    of_stored: &syn::Ident,
    primitive: &syn::Ident,
  ) -> proc_macro2::TokenStream {
    let name = &self.name;
    let forward = self.variants.iter().map(|variant| {
      let ident = &variant.ident;
      quote!(#name::#ident => #name::#ident as ::core::primitive::#primitive)
    });
    let reverse = self.variants.iter().map(|variant| {
      let ident = &variant.ident;
      quote! {
        value if value == #name::#ident as ::core::primitive::#primitive => {
          ::core::option::Option::Some(#name::#ident)
        }
      }
    });
    quote! {
      fn #stored(value: &#name) -> ::core::primitive::#primitive {
        match value {
          #(#forward,)*
        }
      }

      fn #of_stored(
        value: ::core::primitive::#primitive,
      ) -> ::core::option::Option<#name> {
        match value {
          #(#reverse,)*
          _ => ::core::option::Option::None,
        }
      }
    }
  }
}