ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
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
//! The ONE DOOR onto a vocabulary — validating a unit-variant enum into the model the emitter
//! consumes, whole: the storage citizenship a COLUMN of it needs, the filter semantics, and the wire
//! face a SCHEMA needs.
//!
//! # One organ, one word
//!
//! There were two, and the second was deleted rather than kept: `#[ingraph::enumeration]` gave a
//! vocabulary its storage rows and `#[derive(ingraph::GraphqlEnum)]` gave it a schema face, on the
//! reading that those are two organs and a declaration should be able to take one without the other.
//! Each defence of that split fell on re-derivation:
//!
//! - **Schema presence is REACHABILITY.** An enum no wire type names never enters an SDL — a schema
//!   is walked from its roots — so a second macro was never the gatekeeper it looked like.
//! - **Unused storage impls on a pure-wire enum are harmless.** They name no driver a build did not
//!   compile, and nothing walks them.
//! - **The wire face is behind the BINDING GATE anyway**, so a build without `async-graphql` expands
//!   it to nothing at all.
//!
//! What the split DID cost was real: a silent composition-order trap (a derive written below the
//! attribute read a declaration whose markers the attribute's echo had already stripped, which is
//! indistinguishable from a declaration that renamed nothing), two entry points onto one model, and
//! one set of `#[ingraph(…)]` markers read by two grammars. All three die with the second word, and
//! none of them needed a rule to die: they were the coexistence, not consequences of it.
//!
//! # The grammar, whole
//!
//! Everything the attribute took inside its own parentheses is written in the derive's helper
//! attribute beside the enum, verbatim:
//!
//! ```ignore
//! #[derive(Debug, Clone, Copy, PartialEq, Eq, ingraph::Enum)]
//! #[ingraph(crate = "vendored::ingraph", sqlite(text), error(rename = "NoSuchCodec"))]
//! #[repr(u8)]
//! pub enum Codec {
//!   #[ingraph(rename = "h.264", sqlite(rename = "h264"), graphql(rename = "H264"))]
//!   H264,
//!   Vp9,
//! }
//! ```
//!
//! `#[repr(…)]` stays where the AUTHOR wrote it and is read there: it decides a stored column's
//! width, which is a fact about the Rust type rather than an option of this derive.
//!
//! # The wire face's block holds TWO words, and they answer different questions
//!
//! ```ignore
//! #[ingraph(graphql(text, rename = "Codec"))]
//! ```
//!
//! `text`/`integer` is the FORM — what a face stores — and is refused on a mirror or an open
//! vocabulary, both of which store a word in every face and so have no form to name.
//! `rename = "…"` is what a SCHEMA calls this vocabulary, and it is legal in all four cells of the
//! mode table: a closed vocabulary moves its `enum`, an open one and a mirror move their `scalar`,
//! and a name is as much a commitment in one shape as in the other.
//!
//! The word is EMISSION-ONLY. The Rust type keeps its name, the refusal type answers to
//! `error(rename = "…")`, and the stored words stay the per-variant per-face family's — which is
//! exactly why the four database blocks refuse a `rename` at this grain BY NAME: a column holds one
//! member at a time, so a stored face has a variant's word and no type name of its own.
//!
//! # One word, FOUR CELLS — and the declaration's own SHAPE picks one
//!
//! There is no word for the mode, and there was never a question one could have answered. Two
//! structural facts decide everything: whether `#[ingraph(remote = "…")]` names an upstream, and
//! whether a variant wears `#[ingraph(other)]`.
//!
//! | | no escape | an `#[ingraph(other)]` escape |
//! |---|---|---|
//! | **no `remote`** | a CLOSED vocabulary this crate declares | an OPEN one this crate declares |
//! | **`remote = "…"`** | a closed MIRROR | an open mirror |
//!
//! The top-left cell is the base state and the one everything below is written about: a declaration
//! that says neither word gets it, and is unaffected by the other three existing. `remote` decides
//! who owns the WORDS; the escape decides whether the variants are the whole SET. Both are read off
//! the tokens, so a declaration cannot describe itself as one thing and be another.
//!
//! `#[ingraph(remote = "…")]` says the declaration RESTATES a vocabulary another crate owns rather
//! than being one:
//!
//! ```ignore
//! // `upstream::Codec` is the vocabulary another crate declares, and
//! // `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", delegate(fn lossless(&self) -> bool))]
//! pub enum Codec {
//!   H264,
//!   #[ingraph(rename = "Vp9")]
//!   Vp9Profile0,
//!   #[ingraph(other)]
//!   Other(ingraph::Utf8Bytes),
//! }
//! ```
//!
//! A mirror restates IDENTIFIERS and delegates every word to the upstream's own `Display` and
//! `FromStr`, so the knobs that move WORDS have nothing to move: the per-face blocks are refused in
//! either position, and `rename` names the upstream VARIANT a restatement claims. `#[ingraph(other)]`
//! marks the escape and is the declaration SAYING the upstream vocabulary is open — exactly one, or
//! none, and the claim is then spent against the upstream itself where the compiler settles it.
//! `ingraph-codegen`'s `enumeration::remote` is where the emission and that settlement are written
//! up.
//!
//! # …and the FOURTH cell, where the words are this crate's and the set is not closed
//!
//! ```ignore
//! #[derive(Clone, PartialEq, Eq, Hash, ingraph::Enum)]
//! pub enum BodyJoint {
//!   Nose,
//!   LeftShoulder,                 // `left_shoulder` — the household fold of the Rust name
//!   #[ingraph(rename = "i2of5")]  // …and the escape from the arithmetic
//!   InterleavedTwoOfFive,
//!   #[ingraph(other)]
//!   Other(ingraph::Utf8Bytes),
//! }
//! ```
//!
//! A roster read out of a vendor's documentation, a protobuf or a model card has no Rust value
//! behind it — so there is nothing to delegate a word to and nothing for an openness claim to be
//! spent against. What follows is all of the mode:
//!
//! - **the two GATED cells are refused**, naming the absent upstream. The door is the roster walked
//!   under the framework's FOLD, which is total by construction, so `FromStr::Err` is `Infallible`,
//!   nothing stands beside the enum, and `error(rename = "…")` is refused for the mirror's reason;
//! - **the words are this crate's**, so `rename` moves one and the default is the Rust name in the
//!   lower-case household — where a CLOSED vocabulary's word is its variant's name verbatim;
//! - **the form knobs go**, exactly as a mirror's do: the escape carries a runtime word with no
//!   discriminant behind it, so one word in every face is the only shape a face can have.
//!
//! `ingraph-codegen`'s `enumeration::own` is where that emission is written up.
//!
//! # The escape's TWO CELLS, and where a declaration says the totality LIVES
//!
//! Spent against the upstream's TYPE, the claim reads `<Remote as FromStr>::Err` — and a vocabulary
//! census found nine types whose parse is total in behaviour and refusable in type, because one
//! error serves a no-alloc tier that really is closed and an alloc tier that is not. Each of the
//! nine hands out a total `fn other(impl AsRef<str>) -> Self`, and the type says nothing about it.
//!
//! So the marker takes ONE optional cell, spelled with the conversion family's own word pair:
//!
//! ```ignore
//! #[ingraph(other)]                                          // the upstream's TYPE says it
//! #[ingraph(other(from = "upstream::Colour::other"))]         // a total GATE says it
//! #[ingraph(other(try_from = "upstream::Mount::try_other"))]  // …and this one can refuse
//! ```
//!
//! The third is HALF-OPEN: its door can refuse, so a refusal type is declared beside the enum and
//! `error(rename = "…")` — refused in both open postures — becomes legal exactly there. The gate's
//! `Err` must be the upstream's own, which is what leaves one refusal for that type to be cast
//! around. Every posture PARSES FIRST and reaches its gate only for what the parse turned away.
//!
//! # The refusals carry the weight
//!
//! A vocabulary is the kind whose SHAPE is the declaration — unit variants, at least one, no
//! parameters — and each of those is refused here, spanned at the token that broke it, rather than
//! surfacing later as a type error inside an expansion. The per-face rules join them, and each is a
//! thing that would otherwise fail silently or fail inside the expansion at a span the declaration
//! cannot edit: two variants colliding in one namespace, a rename under a face that stores numbers,
//! a repr width no dialect holds, a wire name that is not a GraphQL name, two variants whose
//! predicates are one method, and a refusal type renamed onto the vocabulary itself.

use std::collections::BTreeMap;

use ingraph_codegen::{
  delegate::Delegate,
  enumeration::{
    EnumModel, EnumVariant, Escape, IntegerWidth, Namespace, Remote, StorageForm, TEXT_FIELD,
  },
  method::{Emitted, Origin},
  model::GraphqlKind,
};

use crate::{
  attribute::{self, set_once},
  errors::Errors,
  value, wire,
};

#[cfg(test)]
mod tests;

/// The word this door is spelled with, for the sentences that name it.
const WORD: &str = "#[derive(ingraph::Enum)]";

/// What `crate = "…"` has to be.
const CRATE_PATH: &str =
  "`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal";

/// The refusal for a crate named twice.
const CRATE_ONCE: &str = "`crate` is declared more than once — one declaration names one crate";

/// What `remote = "…"` has to be.
const REMOTE_PATH: &str = "`#[ingraph(remote = \"…\")]` must be a path to the vocabulary this one \
                           mirrors, in a string literal";

/// The refusal for a mirrored vocabulary named twice.
const REMOTE_ONCE: &str =
  "`remote` is declared more than once — one declaration mirrors one vocabulary";

/// The word an escape names a TOTAL gate with — the conversion family's own, and the one
/// `persist(…)` reads one declaration over.
const TOTAL_DOOR: &str = "from";

/// The word an escape names a gate that can REFUSE with.
const REFUSABLE_DOOR: &str = "try_from";

/// What `other = "…"` earns. The marker takes a BLOCK where it takes anything at all.
const ESCAPE_SHAPE: &str = "`other` is a MARKER, and where it carries anything it carries a BLOCK — `other(from = \"…\")` or \
   `other(try_from = \"…\")`, naming the gate a word this mirror does not name goes through. A bare \
   `other` says the upstream's own parse is total, and `other = \"…\"` says nothing this grammar \
   reads";

/// What an empty `other()` earns.
const EMPTY_DOOR: &str = "`other(…)` names the GATE a word this mirror does not name goes through — `from = \"…\"` where \
   that gate cannot refuse, `try_from = \"…\"` where it can. An empty block names neither, and a \
   BARE `other` is already how a declaration says the upstream's own parse is total";

/// What a word inside `other(…)` that is neither cell earns.
const UNKNOWN_DOOR: &str = "unknown entry in `other(…)` — an escape opens ONE door, named `from = \"…\"` where the gate \
   cannot refuse or `try_from = \"…\"` where it can";

/// The refusal a second `other` on ONE variant earns.
const ESCAPE_ONCE: &str = "`other` is declared more than once on this variant";

/// What either GATED cell earns on a declaration with no upstream.
const NO_GATE_WITHOUT_AN_UPSTREAM: &str = "`other(…)` names the gate a word goes through to become an UPSTREAM value, and this declaration \
   has no upstream — it mirrors nothing, so its words are its own. Its door is the roster walked \
   under the framework's fold, which is TOTAL by construction: a word no member answers to becomes \
   this escape, `FromStr::Err` is `core::convert::Infallible`, and there is no refusal for a gate \
   to be the way around. A BARE `#[ingraph(other)]` is the whole marker here; \
   `#[ingraph(remote = \"…\")]` on the enum is what gives the cells something to be a gate ONTO";

/// What a cell whose value is not a path earns.
const DOOR_PATH: &str = "`other(from = \"…\")` and `other(try_from = \"…\")` take a PATH to the gate function, in a \
   string literal — `\"upstream::Codec::other\"` and the like. The gate is called where the \
   upstream's own parse turned a word away, and a name the upstream has not got is `E0599` at this \
   token";

/// Which of the FOUR cells a declaration is — read off its own SHAPE, and never off a word.
///
/// There is no `vocabulary`, no `own` and no `escape` entry in this grammar, and there was never a
/// question one could have answered: two structural facts already decide everything, and a word
/// beside them would be a second source able to disagree with the declaration it describes.
///
/// | | no escape | an `#[ingraph(other)]` escape |
/// |---|---|---|
/// | **no `remote`** | a CLOSED vocabulary this crate declares | an OPEN one — the fourth cell |
/// | **`remote = "…"`** | a closed MIRROR | an open mirror |
///
/// Every reader below forks on one of the two axes, never on the pair: what [`mirrors`](Self::mirrors)
/// decides is who owns the WORDS, and what [`open`](Self::open) decides is whether the variants are
/// the whole SET.
#[derive(Clone, Copy, PartialEq, Eq)]
struct Mode {
  /// `#[ingraph(remote = "…")]` — the declaration RESTATES a vocabulary another crate owns, and
  /// every word is that crate's.
  mirrors: bool,
  /// A variant wears `#[ingraph(other)]` — the declaration SAYS the set is open, and a word outside
  /// it is carried rather than refused.
  open: bool,
}

impl Mode {
  /// Whether what a face STORES is a word rather than a discriminant.
  ///
  /// True of every mirror — an upstream discriminant is not this crate's to depend on, a release
  /// being free to renumber it — and of every OPEN vocabulary, whose escape has no discriminant at
  /// all. It is the one question the form knobs, the `#[repr(…)]` walk and the per-face name family
  /// all fork on, and they fork on it TOGETHER: a vocabulary storing a word has one word in every
  /// face, so there is nothing per-face left to say.
  const fn stores_a_word(self) -> bool {
    self.mirrors || self.open
  }
}

/// Does any variant wear `#[ingraph(other)]`?
///
/// Asked BEFORE the walk, because it is one half of the MODE and the mode is what the walk's own
/// refusals are written against. It reads tokens and records nothing: a malformed attribute is the
/// walk's to report, and a second sentence over the same tokens would say less than that one does.
fn declares_an_escape(input: &syn::DeriveInput) -> bool {
  let syn::Data::Enum(data) = &input.data else {
    return false;
  };
  let mut found = false;

  for variant in &data.variants {
    for attr in variant
      .attrs
      .iter()
      .filter(|attr| attr.path().is_ident("ingraph"))
    {
      let _ = attr.parse_nested_meta(|meta| {
        found |= meta.path.is_ident("other");
        attribute::skip_entry(&meta);
        Ok(())
      });
    }
  }

  found
}

/// Validate a decorated enum into the model the emitter consumes.
///
/// # Errors
/// A [`syn::Error`] carrying EVERY rule the pass could still see violated, each spanned at the
/// token that violated it, so one compile reports the whole declaration's problems.
pub(crate) fn parse(input: &syn::DeriveInput) -> syn::Result<EnumModel> {
  let mut errors = Errors::default();
  let Options {
    krate,
    forms,
    faces,
    wire_name,
    error,
    remote,
    delegates,
    delegate,
  } = options(&input.attrs, &mut errors);
  let mode = Mode {
    mirrors: remote.is_some(),
    open: declares_an_escape(input),
  };
  // `#[repr(…)]` is the AUTHOR'S OWN attribute and stays on the item: it decides a stored column's
  // width and is read where it is written, not moved into this derive's own block. A vocabulary
  // storing a WORD has no discriminant of its own to be a width of, so the walk is not run there —
  // a `#[repr(…)]` on one is a fact about the Rust type and nothing this derive reads.
  let width = (!mode.stores_a_word())
    .then(|| width(&input.attrs, &forms, &mut errors))
    .flatten();
  concrete(&input.generics, &mut errors);

  let variants = match variants(input, &forms, mode, &mut errors) {
    Ok(variants) => variants,
    Err(terminal) => return Err(errors.seal(terminal)),
  };
  one_word_everywhere(mode, &faces, &mut errors);
  escapes(mode, &variants, &mut errors);
  // ONE sentence about the block or one about an entry in it, never both: a declaration that
  // mirrors nothing has the whole seat refused, and telling it an entry inside the seat has no
  // reader would be a second sentence about a block that is already gone.
  if mode.mirrors {
    refuse_a_waived_entry_that_publishes_nothing(&delegates, &mut errors);
  } else {
    borrowed(delegate.as_ref(), &mut errors);
  }
  the_refusal_a_parse_answers_with(mode, &variants, error.as_ref(), &mut errors);
  collisions(&variants, &forms, mode, &mut errors);
  // The enum's OWN schema name, checked unconditionally because the wire face is emitted
  // unconditionally: a type whose name is outside GraphQL's Name grammar would register a schema no
  // client could name. Where `graphql(rename = "…")` moved it the LITERAL is what is checked, at its
  // own span, and the Rust name is then nobody's business on the wire; where nothing moved it the
  // name is the Rust one unraw'd. A mirror's face is a SCALAR rather than an `enum`, and a scalar's
  // type name rides the same grammar.
  match wire_name.as_ref() {
    Some(word) => wire::refuse_invalid_name(&word.value(), word, &mut errors),
    None => wire::refuse_invalid_name(
      &syn::ext::IdentExt::unraw(&input.ident).to_string(),
      &input.ident,
      &mut errors,
    ),
  }

  let model = EnumModel {
    krate: krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    vis: input.vis.clone(),
    name: input.ident.clone(),
    width,
    variants,
    forms,
    wire_name: wire_name.map(|word| word.value()),
    error,
    remote: remote.map(|path| Remote { path, delegates }),
  };
  refusal_name(&model, &mut errors);
  published_fields(&model, &mut errors);
  emitted_methods(&model, &mut errors);
  errors.into_result(model)
}

/// What the enum-level `#[ingraph(…)]` carries.
struct Options {
  /// `crate = "…"`.
  krate: Option<syn::Path>,
  /// The per-namespace form OVERRIDES. A namespace with no block takes its own default.
  forms: BTreeMap<Namespace, StorageForm>,
  /// Every face block the declaration wrote ABOUT A FORM, at its own span — what a mirror's refusal
  /// points at, where [`forms`](Self::forms) carries only the blocks that named one.
  ///
  /// A `graphql(rename = "…")` block is NOT one of these and is deliberately absent: the form knobs
  /// and the wire NAME fork on opposite questions. What a face stores is settled by the mode — a
  /// mirror and an open vocabulary store a word in every face, which is what the form refusal says —
  /// while what a schema calls this vocabulary is a live question in all four cells, a scalar's name
  /// being as much a commitment as an `enum`'s.
  faces: Vec<syn::Path>,
  /// `graphql(rename = "…")` — what a SCHEMA calls this vocabulary.
  wire_name: Option<syn::LitStr>,
  /// `error(rename = "…")` — what the emitted REFUSAL type is called.
  error: Option<syn::Ident>,
  /// `remote = "…"` — the upstream vocabulary this one mirrors.
  remote: Option<syn::Path>,
  /// `delegate(fn … , …)` — the upstream methods this mirror forwards.
  delegates: Vec<Delegate>,
  /// Where a `delegate(…)` block was written, for the refusal a declaration that mirrors nothing
  /// gets.
  delegate: Option<syn::Path>,
}

/// Walk the enum-level attribute.
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
  let mut krate = None;
  let mut forms = BTreeMap::new();
  let mut faces = Vec::new();
  let mut wire_name = None;
  let mut error = None;
  let mut remote = None;
  let mut delegates = Vec::new();
  let mut delegate = None;
  let mut seen: BTreeMap<Namespace, ()> = BTreeMap::new();

  attribute::walk(attrs, errors, |meta, errors| {
    // `crate` is a keyword; syn's nested-meta path parser takes it with `Ident::parse_any`, so it
    // arrives here as an ordinary one-segment path.
    if meta.path.is_ident("crate") {
      match value::parse_literal::<syn::Path>(&meta, CRATE_PATH) {
        Ok(path) => set_once(&mut krate, path, &meta.path, CRATE_ONCE, errors),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // The word that picks the MODE. A path rather than a literal from here on: the emission names
    // the upstream type in a dozen positions, and re-parsing it once is what makes a value that
    // cannot BE a type a refusal here rather than a syntax error inside an expansion.
    if meta.path.is_ident("remote") {
      match value::parse_literal::<syn::Path>(&meta, REMOTE_PATH) {
        Ok(path) => set_once(&mut remote, path, &meta.path, REMOTE_ONCE, errors),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // The one entry in this grammar whose contents are RUST rather than meta, and it has to be:
    // there is no `typeof` in the language, so a forwarding method's return type is written by the
    // declaration that asks for it. Accumulated across blocks — a second `delegate(…)` names more
    // methods rather than replacing the first — where every other repeated block here is a second
    // answer to one question.
    if meta.path.is_ident(crate::delegate::WORD) {
      if delegate.is_none() {
        delegate = Some(meta.path.clone());
      }
      return crate::delegate::block(&meta, &mut delegates, &MIRROR, errors);
    }

    // The one EMITTED type a vocabulary declares into the scope beside the enum, and so the one
    // whose name a declaration may need to move. Read by the shared block reader the record's
    // `key(…)` and `row(…)` go through, which is what makes the two grammars spell this rule alike.
    if meta.path.is_ident("error") {
      return attribute::rename_block(&meta, &mut error, "error", errors);
    }

    if let Some(namespace) = namespace(&meta.path) {
      if seen.insert(namespace, ()).is_some() {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          format!(
            "`{}(…)` is declared more than once — one declaration names one form for one face",
            namespace.as_str()
          ),
        ));
      }
      let mut form = None;
      // Whether this block said anything about a FORM — which is what makes it a face block for the
      // mode refusal to point at. A block holding nothing but `rename = "…"` names no form, and a
      // mirror or an open vocabulary is entitled to write one.
      let mut about_a_form = !attribute::has_block(&meta) || attribute::empty_group(&meta);
      let walked = attribute::options(&meta, |inner| {
        if inner.path.is_ident("rename") {
          return the_wire_name(&inner, namespace, &mut wire_name, errors);
        }
        about_a_form = true;
        match this_form(&inner.path) {
          Some(named) => set_once(
            &mut form,
            named,
            &inner.path,
            "a face takes ONE form — a second is a second answer to one question",
            errors,
          ),
          None => errors.push(attribute::unknown(
            &inner,
            &format!(
              "unknown entry in `{}(…)` — a face takes one of {}{}",
              namespace.as_str(),
              listed(&StorageForm::ALL.map(StorageForm::as_str)),
              if namespace == Namespace::Graphql {
                ", and `rename = \"…\"`, the name a SCHEMA publishes this vocabulary under"
              } else {
                ""
              }
            ),
            &if namespace == Namespace::Graphql {
              StorageForm::ALL
                .map(StorageForm::as_str)
                .into_iter()
                .chain(core::iter::once("rename"))
                .collect::<Vec<_>>()
            } else {
              StorageForm::ALL.map(StorageForm::as_str).to_vec()
            },
          )),
        }
        Ok(())
      });
      if about_a_form {
        faces.push(meta.path.clone());
      }
      if let Some(form) = form {
        forms.insert(namespace, form);
      }
      return walked;
    }

    errors.push(attribute::unknown(
      &meta,
      &format!(
        "unknown entry in `#[ingraph(…)]` on an enum — a vocabulary takes `crate = \"…\"`, \
         `remote = \"…\"`, `delegate(fn …)`, `error(rename = \"…\")` and one block per face, {}. \
         The wire face's block takes a `rename = \"…\"` beside its form, which is what a SCHEMA \
         calls this vocabulary",
        listed(&Namespace::ALL.map(Namespace::as_str))
      ),
      &["crate", "remote", "delegate", "error"]
        .into_iter()
        .chain(Namespace::ALL.map(Namespace::as_str))
        .collect::<Vec<_>>(),
    ));
    Ok(())
  });

  Options {
    krate,
    forms,
    faces,
    wire_name,
    error,
    remote,
    delegates,
    delegate,
  }
}

/// What a MIRROR's delegate refusals say — the tier's own half of a grammar two declarations share.
const MIRROR: crate::delegate::Delegation<'static> = crate::delegate::Delegation {
  receiver: "a delegated method BORROWS its receiver — `&self` forwards onto a materialized \
             upstream value, and `&mut self` writes the mutation back through this mirror's own \
             `From`. There is no `self` for one to consume, the mirror being the caller's rather \
             than the upstream's, and a signature with no receiver has nothing to forward from",
  exclusive: "a published delegate takes `&self` — a resolver READS, and a `&mut self` entry's body \
              materializes the upstream value, mutates it and writes a NEW value back into the row \
              it was called on. Drop the `#[graphql(…)]` to keep the method, or take the receiver \
              by shared reference to keep the field",
};

/// `graphql(rename = "…")` — WHAT A SCHEMA CALLS THIS VOCABULARY, read off the wire face's own
/// block.
///
/// # It is the wire face's word and no other face's
///
/// The four database namespaces name a STORED form, and a stored word is a variant's rather than a
/// declaration's: a column holds one member at a time, so there is nothing at this position for a
/// database to have a name FOR. The word a stored face does spell is `#[ingraph(sqlite(rename =
/// "…"))]` on a VARIANT, and that is where a `rename` written here is sent — by name, because an
/// author who wrote one had a coherent idea and the useful answer names the position that carries
/// it.
///
/// # STRING-kind, and the fence is GraphQL's Name grammar alone
///
/// Nothing in Rust is called this. Both wire shapes a vocabulary takes — the `enum` a closed one
/// publishes and the `scalar` an open one or a mirror does — carry the word as a LITERAL into a
/// registry entry, so a Rust keyword is an ordinary word here and `graphql(rename = "type")` has to
/// be writable. That is the 2026-08-13 ruling, and it is why this reader is
/// [`value::literal`] rather than the ident-kind [`attribute::rename_block`] the neighbouring
/// `error(rename = "…")` takes: an error is a Rust TYPE and this is a schema entity.
///
/// The word is fenced where it SETTLES rather than here — [`parse`] asks
/// [`wire::refuse_invalid_name`] of whichever name reaches the schema — so one bad word earns one
/// sentence at one span whether it was written or derived.
fn the_wire_name(
  option: &syn::meta::ParseNestedMeta<'_>,
  namespace: Namespace,
  slot: &mut Option<syn::LitStr>,
  errors: &mut Errors,
) -> syn::Result<()> {
  if namespace != Namespace::Graphql {
    errors.push(attribute::named(
      option,
      format!(
        "`{ns}` STORES this vocabulary and does not name it — a column holds one member at a time, \
         so a face over a database has a per-variant WORD and no type name of its own. What this \
         face's `rename` moves is a VARIANT's stored word, written on the variant: \
         `#[ingraph({ns}(rename = \"…\"))]`. The name a SCHEMA publishes the vocabulary under is \
         `graphql(rename = \"…\")`, one face over",
        ns = namespace.as_str(),
      ),
    ));
    attribute::skip_entry(option);
    return Ok(());
  }
  match value::literal(option, attribute::SDL_NAME) {
    Ok(word) => set_once(
      slot,
      word,
      &option.path,
      "`rename` is declared more than once in `graphql(…)` — one declaration has one schema name",
      errors,
    ),
    Err(e) => errors.push(e),
  }
  Ok(())
}

/// The namespace a word names, or nothing.
fn namespace(path: &syn::Path) -> Option<Namespace> {
  Namespace::ALL
    .into_iter()
    .find(|namespace| path.is_ident(namespace.as_str()))
}

/// The form a word names, or nothing.
fn this_form(path: &syn::Path) -> Option<StorageForm> {
  StorageForm::ALL
    .into_iter()
    .find(|form| path.is_ident(form.as_str()))
}

/// A set of words, as a sentence lists them.
pub(crate) fn listed(words: &[&str]) -> String {
  words
    .iter()
    .map(|word| format!("`{word}`"))
    .collect::<Vec<_>>()
    .join(", ")
}

/// The stored width the declaration's `#[repr(…)]` names, and the refusal for one no dialect holds.
///
/// The walk is over INTEGER hints only. `#[repr(C)]`, `align(…)`, `packed` and `transparent` say
/// something about layout and nothing about a stored width, so an enum carrying one is not a
/// declaration this derive has anything to object to — it takes the default width like any other.
///
/// A width the house cannot carry is refused only where it would actually be STORED: a vocabulary
/// whose every face takes the text form never renders a discriminant, so a `#[repr(u64)]` there is a
/// fact about the Rust type and nothing else. That is also what makes the refusal actionable, since
/// naming the text form is one of the two ways out it offers.
fn width(
  attrs: &[syn::Attribute],
  forms: &BTreeMap<Namespace, StorageForm>,
  errors: &mut Errors,
) -> Option<IntegerWidth> {
  let stored_as_a_number = Namespace::ALL.into_iter().any(|namespace| {
    forms
      .get(&namespace)
      .copied()
      .unwrap_or_else(|| namespace.default_form())
      == StorageForm::Integer
  });
  let mut width = None;

  for attr in attrs.iter().filter(|attr| attr.path().is_ident("repr")) {
    let _ = attr.parse_nested_meta(|meta| {
      let Some(word) = meta.path.get_ident().map(ToString::to_string) else {
        return Ok(());
      };
      if !IntegerWidth::is_repr_word(&word) {
        attribute::skip_entry(&meta);
        return Ok(());
      }
      match IntegerWidth::named(&word) {
        Some(named) => width = Some(named),
        None if stored_as_a_number => errors.push(syn::Error::new_spanned(
          &meta.path,
          format!(
            "`#[repr({word})]` is not a width a vocabulary can be stored at — the framework's \
             carrier table covers {}, and no wider: MySQL alone has a native `u64`, no dialect \
             carries a 128-bit integer, and `usize`/`isize` name no fixed width for a column to \
             be. Declare a width every dialect holds, or give each face the `text` form",
            listed(&IntegerWidth::ALL.map(IntegerWidth::as_str))
          ),
        )),
        None => {}
      }
      Ok(())
    });
  }

  width
}

/// Vocabularies are concrete. Every row the emitter writes names the enum ITSELF, and a unit
/// variant has no field a parameter could reach anyway.
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
  const WHY: &str = "generic vocabularies are not supported — every row this derive emits names \
                     the enum itself, and a parameter has no type until it is substituted; a unit \
                     variant has no field to carry one in either";
  if !generics.params.is_empty() {
    errors.push(syn::Error::new_spanned(generics, WHY));
  } else if let Some(clause) = &generics.where_clause {
    errors.push(syn::Error::new_spanned(clause, WHY));
  }
}

/// The declaration's variants — the only shape a vocabulary may take.
///
/// A variant carrying data is ACCUMULATED rather than terminal, so one compile names every
/// offending variant instead of the first; the model is discarded either way, because
/// [`Errors::into_result`] refuses to hand one back once anything was recorded.
fn variants(
  input: &syn::DeriveInput,
  forms: &BTreeMap<Namespace, StorageForm>,
  mode: Mode,
  errors: &mut Errors,
) -> syn::Result<Vec<EnumVariant>> {
  let syn::Data::Enum(data) = &input.data else {
    return Err(syn::Error::new_spanned(
      &input.ident,
      if mode.mirrors {
        format!(
          "`{WORD}` with `remote = \"…\"` supports enums only — a mirror RESTATES its upstream's \
           variants, one for one, and a struct has none to restate"
        )
      } else {
        format!(
          "`{WORD}` supports enums only — a vocabulary is a closed set of names, and a struct \
           declares no such set"
        )
      },
    ));
  };

  if data.variants.is_empty() {
    return Err(syn::Error::new_spanned(
      &input.ident,
      format!(
        "an enum with no variants declares no vocabulary — there is no value to store, no member \
         to ask for, and the emitted filter would guard a column no row could ever hold. A schema \
         could not carry it either: GraphQL's own rule is that *an Enum type must define one or \
         more unique enum values*, so `{WORD}` has nothing to emit for one"
      ),
    ));
  }

  let mut parsed = Vec::with_capacity(data.variants.len());
  for variant in &data.variants {
    let mut read = names(variant, forms, mode, errors);
    match (&variant.fields, read.escape.is_some()) {
      (syn::Fields::Unit, false) => {}
      // The ESCAPE is the one variant that may carry anything, and what it carries is a WORD: one
      // unnamed field, of whichever text carrier the declaration picked. The TOKEN is kept, because
      // one emitted row — the key delegation — needs the type WRITTEN rather than reached through
      // `From<&str>`/`AsRef<str>`: it is that row's `Inner`.
      (syn::Fields::Unnamed(fields), true) if fields.unnamed.len() == 1 => {
        read.carrier = Some(fields.unnamed[0].ty.clone());
      }
      (_, true) => errors.push(syn::Error::new_spanned(
        &variant.ident,
        if mode.mirrors {
          format!(
            "`{}` is marked `#[ingraph(other)]` and must carry EXACTLY ONE unnamed field — the \
             WORD of an upstream value this mirror does not name. Any text carrier that is \
             `From<&str>` and `AsRef<str>` holds one, `Utf8Bytes` and `SmolStr` among them, and the \
             compiler names the obligation at the field's own type",
            variant.ident
          )
        } else {
          format!(
            "`{}` is marked `#[ingraph(other)]` and must carry EXACTLY ONE unnamed field — the \
             WORD this vocabulary does not name. Any text carrier that is `From<&str>` and \
             `AsRef<str>` holds one, `Utf8Bytes` and `SmolStr` among them, and the compiler names \
             the obligation at the field's own type",
            variant.ident
          )
        },
      )),
      (_, false) => errors.push(syn::Error::new_spanned(
        &variant.ident,
        match (mode.mirrors, mode.open) {
          // The CLOSED cell, and the sentence carries the accident: a declaration that meant to
          // open its vocabulary and forgot the marker lands here, one word away from the shape it
          // wanted, and being told to reach for a different derive would send it the wrong way.
          (false, false) => format!(
            "`{WORD}` takes UNIT variants only — `{}` carries data. A vocabulary this crate \
             declares is a CLOSED SET: the filter is membership over the variants, the stored form \
             is one name or one discriminant, and a wire value is one word in a document — a \
             payload fits none of the three. TWO ways out, and which one is right depends on what \
             the payload IS: a WORD this vocabulary does not name is the ESCAPE, and \
             `#[ingraph(other)]` on this variant is what says so — it opens the vocabulary, and the \
             field becomes the word it carries. Anything else is a UNION, and \
             `#[derive(ingraph::Union)]` is the word for one",
            variant.ident
          ),
          // The OPEN cell. The escape already exists here, so the accident above is not available
          // as a reading and the sentence does not offer it.
          (false, true) => format!(
            "`{}` carries data, and this vocabulary already has its escape. A roster's members are \
             NAMES — the stored form is one word, the filter is membership over them and the list a \
             client reads is `VARIANTS` — so the one variant that may carry anything is the \
             `#[ingraph(other)]` one, and what it carries is the word this vocabulary does not \
             name",
            variant.ident
          ),
          (true, _) => format!(
            "`{}` carries data. A mirror RESTATES its upstream's variants — IDENTIFIERS, nothing \
             else, the words being the upstream's own — so the one variant that may carry anything \
             is the `#[ingraph(other)]` escape, and what it carries is a word",
            variant.ident
          ),
        },
      )),
    }
    parsed.push(read);
  }
  Ok(parsed)
}

/// One variant's names: the global `rename`, and whatever a face renamed it to.
///
/// `rename` names a different thing in each mode, and that is the single-source rule rather than an
/// overload: a DECLARED vocabulary owns its words, so the knob moves the canonical WORD; a MIRROR
/// owns none — the upstream's `Display` spells every one of them — so the knob moves the only thing
/// a restatement can get wrong, which is the upstream IDENTIFIER this variant claims to be.
fn names(
  variant: &syn::Variant,
  forms: &BTreeMap<Namespace, StorageForm>,
  mode: Mode,
  errors: &mut Errors,
) -> EnumVariant {
  let mut rename = None;
  let mut upstream = None;
  let mut escape: Option<(syn::Path, Escape)> = None;
  let mut names: BTreeMap<Namespace, String> = BTreeMap::new();
  let mut seen: BTreeMap<Namespace, ()> = BTreeMap::new();

  attribute::walk(&variant.attrs, errors, |meta, errors| {
    if meta.path.is_ident("rename") {
      if mode.mirrors {
        match value::parse_literal::<syn::Ident>(
          &meta,
          "`rename = \"…\"` must be an identifier, in a string literal — on a mirror it names the \
           UPSTREAM variant this one restates, not a word: the words are the upstream's own",
        ) {
          Ok(named) => set_once(
            &mut upstream,
            named,
            &meta.path,
            "`rename` is declared more than once — one variant restates one upstream variant",
            errors,
          ),
          Err(e) => errors.push(e),
        }
        return Ok(());
      }
      match value::literal(
        &meta,
        "`rename = \"…\"` must be a string literal — the word every face defaults to",
      ) {
        Ok(word) => set_once(
          &mut rename,
          word.value(),
          &meta.path,
          "`rename` is declared more than once — one declaration names one canonical word",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    // The ESCAPE marker, and whichever DOOR the declaration opened it with. The marker is legal in
    // BOTH modes — its presence is the second axis of the mode, not a mirror's private word — and
    // what forks is where an escape's openness may LIVE. `named` swallows the cell, so one mistake
    // costs one sentence.
    if meta.path.is_ident("other") {
      if attribute::has_value(&meta) {
        errors.push(attribute::named(&meta, ESCAPE_SHAPE.to_owned()));
        return Ok(());
      }
      // The two GATED cells name a function turning a word into an UPSTREAM value, and a
      // vocabulary this crate declares has none. Its door is its own roster walked under the fold,
      // which is total by construction — there is no error type for a gate to be the escape from.
      if !mode.mirrors && attribute::has_block(&meta) {
        errors.push(attribute::named(
          &meta,
          NO_GATE_WITHOUT_AN_UPSTREAM.to_owned(),
        ));
        set_once(
          &mut escape,
          (meta.path.clone(), Escape::Total),
          &meta.path,
          ESCAPE_ONCE,
          errors,
        );
        return Ok(());
      }
      let posture = door(&meta, errors);
      set_once(
        &mut escape,
        (meta.path.clone(), posture),
        &meta.path,
        ESCAPE_ONCE,
        errors,
      );
      return Ok(());
    }

    if let Some(namespace) = namespace(&meta.path) {
      if mode.stores_a_word() {
        errors.push(attribute::named(
          &meta,
          if mode.mirrors {
            format!(
              "`{face}(…)` spells this variant for ONE face, and a mirror spells it one way \
               everywhere — the upstream's own word, through its `Display`. A word written here \
               would be a second source for a grammar that has one",
              face = namespace.as_str()
            )
          } else {
            format!(
              "`{face}(…)` spells this variant for ONE face, and an OPEN vocabulary spells it one \
               way everywhere. What forces that is the ESCAPE: it carries a runtime word and has no \
               per-face spelling for a face to differ in, so a word written here would be one this \
               vocabulary could store for a named member and not for an unnamed one. \
               `#[ingraph(rename = \"…\")]` moves the word in every face at once",
              face = namespace.as_str()
            )
          },
        ));
        return Ok(());
      }
      if seen.insert(namespace, ()).is_some() {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          format!(
            "`{}(…)` is declared more than once on this variant — one declaration names one word \
             for one face",
            namespace.as_str()
          ),
        ));
      }
      let mut renamed: Option<syn::LitStr> = None;
      let walked = attribute::options(&meta, |inner| {
        if inner.path.is_ident("rename") {
          match value::literal(
            &inner,
            "`rename = \"…\"` must be a string literal — the word this face spells the variant as",
          ) {
            Ok(word) => set_once(
              &mut renamed,
              word,
              &inner.path,
              "`rename` is declared more than once in one face — a face spells a variant one way",
              errors,
            ),
            Err(e) => errors.push(e),
          }
          return Ok(());
        }
        errors.push(attribute::unknown(
          &inner,
          &format!(
            "unknown entry in `{}(…)` on a variant — a face takes `rename = \"…\"`",
            namespace.as_str()
          ),
          &["rename"],
        ));
        Ok(())
      });
      if let Some(word) = renamed {
        // The FORM is what decides whether a face has a name at all, so a word written for one
        // that stores numbers is refused rather than silently kept: nothing downstream would read
        // it, and an entry nobody reads is a rule its author believes they declared.
        let form = forms
          .get(&namespace)
          .copied()
          .unwrap_or_else(|| namespace.default_form());
        if form == StorageForm::Integer {
          errors.push(syn::Error::new_spanned(
            &word,
            format!(
              "`{face}` stores the discriminant, so it has no name to rename — that face's form is \
               `{form}`{by}. Declare `#[ingraph({face}(text))]` on the enum to give it a word, or \
               drop this rename",
              face = namespace.as_str(),
              form = form.as_str(),
              by = if forms.contains_key(&namespace) {
                ", as this declaration says"
              } else {
                " by default"
              },
            ),
          ));
        }
        if namespace == Namespace::Graphql {
          wire::refuse_invalid_name(&word.value(), &word, errors);
        }
        names.insert(namespace, word.value());
      }
      return walked;
    }

    errors.push(attribute::unknown(
      &meta,
      &format!(
        "unknown entry in `#[ingraph(…)]` on a variant — it takes `rename = \"…\"`, `other` and one \
         block per face, {}",
        listed(&Namespace::ALL.map(Namespace::as_str))
      ),
      &["rename", "other"]
        .into_iter()
        .chain(Namespace::ALL.map(Namespace::as_str))
        .collect::<Vec<_>>(),
    ));
    Ok(())
  });

  // The escape names NOTHING for a rename to move — it is where the words this vocabulary does not
  // know land, and such a word is CARRIED rather than spelled — so a declaration writing both is
  // told so rather than having one of the two silently ignored.
  if let Some((at, _)) = escape.as_ref()
    && (upstream.is_some() || rename.is_some())
  {
    errors.push(syn::Error::new_spanned(
      at,
      if mode.mirrors {
        format!(
          "`{}` is marked `#[ingraph(other)]` and renamed — the escape mirrors no upstream \
           variant, so there is none for `rename` to name. It is the variant an upstream word this \
           mirror does not know lands in, and that word is carried rather than spelled here",
          variant.ident
        )
      } else {
        format!(
          "`{}` is marked `#[ingraph(other)]` and renamed — the escape has no canonical word for \
           `rename` to move. It is the variant a word this vocabulary does not name lands in, and \
           that word is the one it CARRIES: `as_str` hands it back, a column stores it and a cursor \
           pages past it. The roster's own members are what `rename` spells",
          variant.ident
        )
      },
    ));
  }

  EnumVariant {
    ident: variant.ident.clone(),
    rename,
    names,
    upstream,
    escape: escape.map(|(_, posture)| posture),
    // Filled by the FIELD SHAPE check in `variants`, which is where the escape's one unnamed field
    // is established. Reading it here would mean reading it twice and disagreeing once.
    carrier: None,
  }
}

/// The escape's POSTURE: the bare marker, or the ONE cell naming the gate a word goes through.
///
/// The word pair is the CONVERSION FAMILY'S — `from` where the gate cannot refuse, `try_from` where
/// it can — which is the pair `persist(…)` reads one declaration over. Reading alike is the whole
/// argument for it: what the two words mean is already known to anybody who has read this grammar
/// anywhere else, and the difference between them is the only thing this cell says.
///
/// The three answers are not three shapes of one knob. A bare `other` reads the totality off the
/// UPSTREAM'S TYPE, `from` reads it off a GATE'S SIGNATURE, and `try_from` admits there is none —
/// which is what casts a refusal type beside the enum and makes `error(rename = "…")` legal.
///
/// A cell that could not be read leaves the posture BARE, so the rest of the pass reads a settled
/// declaration; its refusal is already recorded, and [`Errors::into_result`] discards the model
/// either way.
fn door(meta: &syn::meta::ParseNestedMeta<'_>, errors: &mut Errors) -> Escape {
  if !attribute::has_block(meta) {
    return Escape::Total;
  }
  if attribute::empty_group(meta) {
    errors.push(attribute::named(meta, EMPTY_DOOR.to_owned()));
    return Escape::Total;
  }

  let mut declared: Option<(&'static str, Escape)> = None;
  let walked = meta.parse_nested_meta(|inner| {
    let refusable = if inner.path.is_ident(TOTAL_DOOR) {
      false
    } else if inner.path.is_ident(REFUSABLE_DOOR) {
      true
    } else {
      errors.push(attribute::unknown(
        &inner,
        UNKNOWN_DOOR,
        &[TOTAL_DOOR, REFUSABLE_DOOR],
      ));
      return Ok(());
    };
    let word = if refusable {
      REFUSABLE_DOOR
    } else {
      TOTAL_DOOR
    };
    let gate = match value::parse_literal::<syn::Path>(&inner, DOOR_PATH) {
      Ok(gate) => gate,
      Err(e) => {
        errors.push(e);
        return Ok(());
      }
    };
    match declared.as_ref() {
      Some((first, _)) if *first == word => errors.push(syn::Error::new_spanned(
        &inner.path,
        format!("`{word}` is declared more than once on this escape — one escape opens one door"),
      )),
      // The two cells are MUTUALLY EXCLUSIVE, and the sentence is the conversion family's own one
      // declaration over: either the door can refuse or it cannot, and there is no third answer.
      Some((first, _)) => errors.push(syn::Error::new_spanned(
        &inner.path,
        format!(
          "`{first}` and `{word}` are both declared on this escape — a door either can refuse a \
           word or it cannot, and there is no third answer. `{TOTAL_DOOR}` keeps this mirror OPEN, \
           its gate answering with an upstream value; `{REFUSABLE_DOOR}` makes it HALF-OPEN, \
           casting this vocabulary's own `ParseError` around what the gate turns away"
        ),
      )),
      None => {
        declared = Some((
          word,
          if refusable {
            Escape::TryGate(gate)
          } else {
            Escape::Gate(gate)
          },
        ));
      }
    }
    Ok(())
  });
  if let Err(e) = walked {
    errors.push(e);
  }

  declared.map_or(Escape::Total, |(_, posture)| posture)
}

/// **A vocabulary storing a WORD spells it one way everywhere**, so the enum-level face blocks have
/// nothing to name.
///
/// One rule, two reasons that meet at the same place. A MIRROR stores its upstream's own rendering,
/// and an upstream discriminant is not this crate's to depend on — a release may renumber it. An
/// OPEN vocabulary this crate declares stores its own word, and its ESCAPE has no discriminant at
/// all; a form knob would ask a face to store a number for the members and something else for the
/// word that is not one.
fn one_word_everywhere(mode: Mode, faces: &[syn::Path], errors: &mut Errors) {
  if !mode.stores_a_word() {
    return;
  }

  for face in faces {
    let named = face
      .get_ident()
      .map_or_else(|| "this face".to_owned(), ToString::to_string);
    errors.push(syn::Error::new_spanned(
      face,
      if mode.mirrors {
        format!(
          "`{named}(…)` names a FORM for one face, and a mirror has none to name: what it stores \
           is the upstream's own rendering, the same word in every face. An upstream discriminant \
           is not this crate's to depend on — a release may renumber it — and the \
           `#[ingraph(other)]` escape has none at all"
        )
      } else {
        format!(
          "`{named}(…)` names a FORM for one face, and an OPEN vocabulary has none to name: what \
           it stores is its own word, the same one in every face. The `#[ingraph(other)]` escape is \
           what settles it — the word it carries is a runtime value with no discriminant behind it, \
           so a face storing numbers could hold the members and not the one that is not a member. \
           Drop the escape and this vocabulary is CLOSED, where the form knobs are"
        )
      },
    ));
  }
}

/// **EXACTLY ONE ESCAPE, or none** — the law that is the mode's second axis, in both modes.
///
/// Its presence says the vocabulary is OPEN and its absence says it is CLOSED. On a MIRROR both
/// claims are then spent against the upstream itself by the emission, where the compiler settles
/// them (see [`ingraph_codegen::enumeration::remote`]); on a vocabulary this crate declares the
/// claim is simply true, the declaration being the only authority there is.
///
/// Two escapes would be two answers to *where does a word this vocabulary does not name go*, and
/// that is refused here, at the second one, with both named.
fn escapes(mode: Mode, variants: &[EnumVariant], errors: &mut Errors) {
  let mut escapes = variants.iter().filter(|variant| variant.escape.is_some());
  let Some(first) = escapes.next() else {
    return;
  };

  for extra in escapes {
    errors.push(syn::Error::new_spanned(
      &extra.ident,
      format!(
        "`{}` and `{first}` are both marked `#[ingraph(other)]` — {who} has ONE escape, and two \
         would be two answers to where a word this vocabulary does not name goes",
        extra.ident,
        first = first.ident,
        who = if mode.mirrors {
          "a mirror"
        } else {
          "a vocabulary"
        },
      ),
    ));
  }
}

/// `error(rename = "…")` moves a type only a declaration that CAN refuse declares.
///
/// The whole of the question is which door the declaration built. A CLOSED vocabulary refuses by
/// construction, in either mode, and so does the HALF-OPEN mirror whose gate can. The two TOTAL
/// postures promise every word parses — the upstream's own type where the marker is bare, a total
/// gate's signature where `other(from = "…")` names one — and so does the fold's own door, which is
/// the only posture a vocabulary this crate declares can take. There `FromStr::Err` is `Infallible`,
/// nothing stands beside the enum, and the knob has nothing to move.
fn the_refusal_a_parse_answers_with(
  mode: Mode,
  variants: &[EnumVariant],
  error: Option<&syn::Ident>,
  errors: &mut Errors,
) {
  let Some(at) = error else {
    return;
  };
  let escape = variants.iter().find_map(|variant| variant.escape.as_ref());
  if escape.is_none_or(Escape::refuses) {
    return;
  }

  errors.push(syn::Error::new(
    at.span(),
    if mode.mirrors {
      format!(
        "`error(rename = \"…\")` names the refusal type a parse answers with, and this mirror has \
         none: the `#[ingraph(other)]` escape says every word parses — the upstream's own parse \
         where the marker is bare, the gate's signature where `other({TOTAL_DOOR} = \"…\")` names \
         one — so `FromStr::Err` is `core::convert::Infallible` and this expansion declares no type \
         beside the enum for the knob to move. `other({REFUSABLE_DOOR} = \"…\")` is the posture \
         whose door CAN refuse, and the one this knob is for"
      )
    } else {
      "`error(rename = \"…\")` names the refusal type a parse answers with, and this vocabulary \
       has none: the `#[ingraph(other)]` escape says every word parses — a word no member answers \
       to becomes the escape carrying its folded spelling — so `FromStr::Err` is \
       `core::convert::Infallible` and this expansion declares no type beside the enum for the knob \
       to move. Drop the escape and the vocabulary is CLOSED, which is where a parse can refuse and \
       where this knob is for"
        .to_owned()
    },
  ));
}

/// The FIELDS a promotion puts into a schema, and the two ways a declaration can make two of them
/// one.
///
/// The words are asked of the MODEL rather than rebuilt here, for the reason the refusal type's name
/// is: a spelling on this side is a second copy of what the emitter publishes, and two copies of a
/// derived name is how one of them drifts.
///
/// A published method also takes NO ARGUMENTS, and that is a wall rather than a knob: a GraphQL
/// field's arguments are a grammar this axis does not have, and a body calling a method with the
/// arguments missing is `E0061` inside an expansion the declaration cannot edit.
fn published_fields(model: &EnumModel, errors: &mut Errors) {
  for kind in GraphqlKind::ALL {
    let mut taken: BTreeMap<String, ()> = BTreeMap::new();
    taken.insert(TEXT_FIELD.to_owned(), ());

    for delegate in model.promoted(kind) {
      let at = published_at(delegate, kind);
      if delegate.signature.inputs.len() > 1 {
        errors.push(syn::Error::new(
          at,
          format!(
            "a published `delegate(fn …)` takes its receiver and nothing else — `{kind}` renders it \
             as a FIELD, and a field's arguments are a grammar this axis has not got. Drop the \
             `#[graphql(…)]` to keep the method as Rust",
            kind = kind.as_str(),
          ),
        ));
        continue;
      }
      let Some(word) = delegate.word(kind) else {
        continue;
      };
      if taken.insert(word.clone(), ()).is_none() {
        continue;
      }
      errors.push(syn::Error::new(
        at,
        if word == TEXT_FIELD {
          format!(
            "this field would be called `{TEXT_FIELD}`, which is the word a promoted mirror \
             publishes its own SLUG at — an object cannot render AS a word, so the word is a field \
             and the name is taken. `#[graphql({kind}(rename = \"…\"))]` moves this one",
            kind = kind.as_str(),
          )
        } else {
          format!(
            "two published methods are both called `{word}` — a schema has one namespace for an \
             object's fields, and lower camel case folds two Rust spellings into one word. \
             `#[{kind}(rename = \"…\")]` tells them apart",
            kind = kind.as_str(),
          )
        },
      ));
    }
  }
}

/// Where a published method's refusal is SPANNED: the `rename` that chose the word, else the
/// method's own name.
///
/// The token that made the decision, which is the one an author edits to answer the refusal.
fn published_at(delegate: &Delegate, kind: GraphqlKind) -> proc_macro2::Span {
  delegate
    .wire
    .iter()
    .find(|skin| skin.kind == kind)
    .and_then(|skin| skin.rename.as_ref())
    .map_or_else(|| delegate.signature.ident.span(), syn::LitStr::span)
}

/// **A WAIVED ENTRY THAT PUBLISHES NOTHING HAS NO READER**, refused at the restatement that named it.
///
/// # What an entry BUYS, which is this tier's question and not the shared door's
///
/// A `delegate(…)` entry buys one of two things: the inherent FORWARDING method — materialize the
/// upstream, call, hand the answer back — or the FIELD of the promoted object. `on = self` waives
/// the first, for the case the word exists to serve: a method the author wrote on the MIRROR, where
/// the mint would call it on an upstream that has not got it (`E0599`) or land a second definition
/// beside the author's own (`E0592`).
///
/// With the mint waived and nothing published the entry buys neither, and a word nobody reads is a
/// rule its author believes they declared. So it is refused by name, and the sentence offers the two
/// ways out.
///
/// # The mirror's half of a law the field fragment states in two sentences
///
/// One seat over the same predicate answers TWO shapes, because that tier has a mode fork this one
/// has not: a fragment mints only where it WRAPS, so an entry there is readerless either by the mode
/// or by this word. A mirror always wraps — `delegate(…)` on a declaration that mirrors nothing is
/// refused whole, one function down — so the word is the only thing that can empty an entry here.
///
/// The companion verdict, `on = self` where NO mint exists to suppress, is unreachable at this tier
/// for that same reason and is not restated: every declaration that may write the seat has a mint
/// for the word to waive.
fn refuse_a_waived_entry_that_publishes_nothing(delegates: &[Delegate], errors: &mut Errors) {
  for delegate in delegates
    .iter()
    .filter(|entry| entry.on_self.is_some() && entry.wire.is_empty())
  {
    let method = &delegate.signature.ident;
    errors.push(syn::Error::new_spanned(
      method,
      format!(
        "`{method}` publishes nothing and `on = self` waives its forwarding half, so the entry has \
         no reader. Without the word a plain entry earns its keep — it mints the method that \
         materializes the upstream and calls it there — and with it the method is already yours, on \
         your own `impl`, leaving the seat's whole content the field of the promoted object. Write \
         `#[graphql(<backend>)]` on the entry to publish it, or drop the entry: the method is \
         reached exactly as before either way"
      ),
    ));
  }
}

/// The one entry a declaration that mirrors NOTHING may not write.
fn borrowed(delegate: Option<&syn::Path>, errors: &mut Errors) {
  let Some(at) = delegate else {
    return;
  };
  errors.push(syn::Error::new_spanned(
    at,
    "`delegate(…)` forwards a method onto a MIRRORED upstream value, and this declaration mirrors \
     nothing — the methods of a vocabulary this crate declares are its own to write, in an `impl` \
     beside it. `#[ingraph(remote = \"…\")]` on the enum is what gives this word something to \
     forward to",
  ));
}

/// The one type this expansion declares beside the enum, and the one name it may not take.
///
/// Asked of the MODEL rather than rebuilt here, for the reason the record's `emitted_names` asks
/// its own: a suffix convention spelled on this side would be a second copy of what the emitter
/// writes, and two copies of a derived name is how one of them drifts.
///
/// It fires only on a DECLARED rename, and that is arithmetic rather than a choice — the default is
/// `<Enum>ParseError`, which is strictly longer than the enum's own name and so can never be it.
/// The collisions this pass cannot see are unchanged by the knob's existence: a scope's other
/// contents are not the derive's to know, so a refusal type landing on one of them is rustc's
/// duplicate definition exactly as it was before, and the rename is what answers it.
fn refusal_name(model: &EnumModel, errors: &mut Errors) {
  let Some(at) = model.error.as_ref() else {
    return;
  };
  if model.error() != model.name {
    return;
  }
  errors.push(syn::Error::new(
    at.span(),
    format!(
      "the refusal type would be named `{name}`, which is already the vocabulary's own name — the \
       expansion declares it beside the enum, so it needs a name of its own",
      name = model.name
    ),
  ));
}

/// The two collisions an expansion cannot survive: one namespace spelling two variants alike, and
/// two variants deriving one predicate.
///
/// Both are duplicate definitions, unreachable arms or a value that names two variants coming back,
/// at a span the declaration cannot edit — so they are refused here, with both variants named.
fn collisions(
  variants: &[EnumVariant],
  forms: &BTreeMap<Namespace, StorageForm>,
  mode: Mode,
  errors: &mut Errors,
) {
  // A MIRROR has no words of its own for two variants to collide in — every face reads the
  // upstream's `Display` — so the word half of this pass has nothing to compare. What it has
  // INSTEAD is the restatement: two variants naming one upstream variant is the same collision one
  // layer up, and it lands as an unreachable arm in a `From` the declaration cannot edit.
  if mode.mirrors {
    let mut taken: BTreeMap<String, &syn::Ident> = BTreeMap::new();
    for variant in variants.iter().filter(|variant| variant.escape.is_none()) {
      let upstream = variant.upstream().to_string();
      match taken.get(&upstream) {
        Some(first) => errors.push(syn::Error::new_spanned(
          &variant.ident,
          format!(
            "`{}` and `{first}` both restate `{upstream}` — the mirror's `From` would carry two \
             arms for one upstream variant, and the second names a value the first already took",
            variant.ident
          ),
        )),
        None => {
          taken.insert(upstream, &variant.ident);
        }
      }
    }
    predicates(variants, errors);
    return;
  }

  // An OPEN vocabulary this crate declares has ONE word per member, in every face, and it is the
  // household fold rather than the Rust spelling. So the canonical list is the one compared and
  // there is nothing per-face beside it — a face block is refused on such a declaration, and the
  // wire face publishes a scalar whose values are text rather than a member list.
  //
  // The ESCAPE is out of the comparison in both directions: it names no member, so there is no word
  // of its own to collide, and a `rename` on it is already refused where it was written.
  if mode.open {
    let mut taken: BTreeMap<String, &syn::Ident> = BTreeMap::new();
    for variant in variants.iter().filter(|variant| variant.escape.is_none()) {
      let word = variant.folded();
      match taken.get(&word) {
        Some(first) => errors.push(syn::Error::new_spanned(
          &variant.ident,
          format!(
            "`{}` and `{first}` are both `{word}` — a roster spells each member once, or a word \
             read back names two of them and the door hands out whichever comes first",
            variant.ident
          ),
        )),
        None => {
          taken.insert(word, &variant.ident);
        }
      }
    }
    predicates(variants, errors);
    return;
  }

  // The canonical namespace always exists — `FromStr` parses it and the cursor pages through it —
  // so it is checked whether or not any face takes the text form. A STORED face is checked where it
  // HAS words: an integer face has none, and its variants' canonical words are already checked
  // here.
  //
  // The WIRE face is checked unconditionally, and that is the one door's doing rather than a second
  // rule: the GraphQL face is emitted for every declaration now, and its values are names whatever
  // form the `graphql(…)` block names — so a declaration flipping that face to `integer` still
  // publishes a set of words a document has to be able to tell apart.
  let mut faces = vec![(
    "the canonical".to_owned(),
    false,
    variants.iter().map(EnumVariant::canonical).collect(),
  )];
  faces.extend(
    Namespace::ALL
      .into_iter()
      .filter(|namespace| {
        *namespace == Namespace::Graphql
          || forms
            .get(namespace)
            .copied()
            .unwrap_or_else(|| namespace.default_form())
            == StorageForm::Text
      })
      .map(|namespace| {
        (
          format!("the `{}`", namespace.as_str()),
          namespace == Namespace::Graphql,
          variants
            .iter()
            .map(|variant| variant.name(namespace))
            .collect::<Vec<_>>(),
        )
      }),
  );

  for (face, on_the_wire, words) in faces {
    let mut taken: BTreeMap<&str, &syn::Ident> = BTreeMap::new();
    for (variant, spelled) in variants.iter().zip(&words) {
      let Some(first) = taken.get(spelled.as_str()) else {
        taken.insert(spelled, &variant.ident);
        continue;
      };
      // Two faces, two sentences, because what BREAKS differs: a stored word that names two
      // variants is a row nobody can read back, and a wire word that does is a document nobody can
      // write.
      let sentence = if on_the_wire {
        format!(
          "`{}` and `{first}` are both `{spelled}` on the wire — a GraphQL enum's values are \
           UNIQUE, and a document naming this one would have two variants to mean",
          variant.ident
        )
      } else {
        format!(
          "`{}` and `{first}` are both `{spelled}` in {face} namespace — a face spells each \
           variant once, or a value read back names two of them",
          variant.ident
        )
      };
      errors.push(syn::Error::new_spanned(&variant.ident, sentence));
    }
  }

  predicates(variants, errors);
}

/// **EVERY NAME A MIRROR'S EXPANSION PUTS IN ITS OWN NAMESPACE, AND THE RULE THAT NO TWO MAY SHARE
/// ONE** — the collision walk the record and the field fragment already run, at the vocabulary tier.
///
/// # What is new here is that a declaration can WRITE one of the names
///
/// A mirror's expansion declares `VARIANTS`, `remote()` and one predicate per variant, and every one
/// of those is a word this emitter chose. `delegate(fn …)` is the seat that changed it: an entry
/// RESTATES a method name its author picked, and that name lands in the same inherent namespace. So
/// `delegate(fn is_bayer(&self) -> bool)` on a mirror with a `Bayer` variant is two methods called
/// `is_bayer`, and `delegate(fn remote(&self) -> u8)` takes the materialization gate.
///
/// Each is `E0592` rather than anything silent, so what this buys is not a caught bug but a MOVED
/// error: rustc reports the duplicate at `#[derive(ingraph::Enum)]`, a span the author cannot edit,
/// and its message never names the entry that caused it.
///
/// The names are NOT listed here. They are `ingraph-codegen`'s, asked for through
/// [`EnumModel::emitted_methods`](ingraph_codegen::enumeration::EnumModel::emitted_methods), because
/// a list kept on this side would be a second copy of what the emitter writes and two copies of a
/// derived-name list is how one of them drifts. That enumeration is pinned against the emission
/// itself, by `ingraph-codegen`'s `the_enumeration_names_exactly_the_items_the_emission_declares`.
///
/// # ONE SIDE MUST BE A DELEGATED ENTRY, and that is a deferral rather than a narrowing
///
/// The only pair this walk could see that involves no entry is two VARIANTS whose predicates fold
/// together, and [`predicates`] already refuses that — at the second variant's own ident, which is a
/// better caret than anything reachable from here. Reporting it again would bury the rule that was
/// actually broken under a restatement of it, which is the record walk's own argument for skipping
/// the pairs its duplicate-column rule owns.
///
/// What that leaves is every pair with an entry on at least one side, and the record's
/// `origin != origin` guard is deliberately NOT copied for it: there, two methods of one origin are
/// a duplicate COLUMN name with a refusal of its own, and here two entries of one name have no other
/// reader at all. A mirror did not refuse them before this walk — `published_fields` compares the
/// SCHEMA word of published entries, which is a different axis and a different namespace — so the
/// duplicate lands here, and the second entry is the one the caret goes to.
///
/// # A WAIVED entry is walked, and it has to be
///
/// `on = self` waives the forwarding mint, so the expansion writes nothing for that entry — and the
/// method still exists, on the `impl` the author wrote, occupying the name exactly as a mint would.
/// The enumeration answers which names are TAKEN rather than which tokens the emitter produced, so a
/// waived entry meeting a predicate is `E0592` between the author's own `impl` and this expansion's,
/// and it is refused here for the same reason a minted one is.
fn emitted_methods(model: &EnumModel, errors: &mut Errors) {
  let emitted = model.emitted_methods();
  let mut taken: Vec<&Emitted> = Vec::new();
  for candidate in &emitted {
    if let Some(first) = taken.iter().find(|earlier| {
      earlier.name == candidate.name
        && (matches!(earlier.origin, Origin::Delegate(_))
          || matches!(candidate.origin, Origin::Delegate(_)))
    }) {
      // TWO TAILS, because what an author DOES about it differs and the rest of the sentence does
      // not. Two entries meeting is a choice between them; an entry meeting one of this mode's own
      // names is a choice with only one movable side, and the tail says which.
      let fix = if matches!(first.origin, Origin::Delegate(_)) {
        "Rename one of them, or drop the second: two entries of one name are two methods of one \
         name, and the seat restates a method rather than declaring it twice."
      } else {
        "Rename the entry: it RESTATES a method you wrote, where a predicate is built from a \
         variant's own name and `remote` and `VARIANTS` are words the mode fixes."
      };
      let why = format!(
        "`{owner}` would declare `{name}` twice — {first}, and {second} — and rustc reports that \
         duplicate inside the expansion, where nothing names the entry that caused it. {fix}",
        owner = candidate.owner_name,
        name = candidate.name,
        first = first.origin,
        second = candidate.origin,
      );
      // At the DECLARED token, which is the ENTRY's — the emitter builds every other name here
      // through `format_ident!`, whose span is the call site, and that is the very span `E0592`
      // already reports at. One side is always an entry, so one side always HAS such a token and
      // the fallback cannot fire; it is written rather than asserted because a refusal path is the
      // last place to put a panic, and the enum's own ident is what a future pair with no declared
      // token on either side would want anyway.
      errors.push(
        match candidate.origin.column().or_else(|| first.origin.column()) {
          Some(at) => syn::Error::new_spanned(at, why),
          None => syn::Error::new_spanned(&candidate.owner_name, why),
        },
      );
    }
    taken.push(candidate);
  }
}

/// Two variants deriving ONE `is_<variant>`, which is a duplicate definition at a span the
/// declaration cannot edit. Asked in either mode: the predicates are Rust names, and a mirror has
/// them for the same reason a declared vocabulary does.
fn predicates(variants: &[EnumVariant], errors: &mut Errors) {
  let mut predicates: BTreeMap<String, &syn::Ident> = BTreeMap::new();
  for variant in variants {
    let predicate = variant.predicate().to_string();
    if let Some(first) = predicates.get(&predicate) {
      errors.push(syn::Error::new_spanned(
        &variant.ident,
        format!(
          "`{}` and `{first}` both derive `{predicate}` — the emitted predicates would be two \
           methods of one name",
          variant.ident
        ),
      ));
    } else {
      predicates.insert(predicate, &variant.ident);
    }
  }
}