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
//! Validating an interface declaration into the model the emitter consumes.
//!
//! The fourth consumer of the shared parsing layer, and the first that reads a list Rust's own
//! attribute grammar cannot hold:
//!
//! ```text
//! #[ingraph(
//!   crate = "path::to::ingraph",
//!   unwrap_error(rename = "NoSuchMedia"),
//!   persist(sqlite, postgres),                                  // which databases the pins are checked at
//!   graphql(computed(error = "media::ComputeError")),           // the ONE computed cell, db-less
//!   fields(
//!     title: String,                                            // short form: every default
//!     mask(type = "Mask", copy,
//!          persist(sqlite(type = "u32"), postgres(type = "int4"))),
//!     created_at(type = "Timestamp",
//!                members(Audio(field = "imported_at"))),      // what ONE member calls it
//!     display_label(type = "String", graphql(computed)),
//!     checksum(type = "u64", copy, graphql(try_computed)),
//!   ),
//! )]
//! ```
//!
//! # The AXIS LAW: a domain block, then a database block, then entries
//!
//! `persist(…)` and `graphql(…)` are DOMAINS; a database opens a block INSIDE one; the entries are
//! that cell's. So a database name written where a domain belongs is refused BY NAME wherever it
//! appears — at the interface level, at a field's, and inside `graphql(…)` — rather than swept into
//! "unknown entry", because an author who writes `sqlite(type = "u32")` on a field has a concrete
//! idea and the useful answer is which block it belongs in.
//!
//! The one ruled exception is the computed cell. `graphql(computed(error = "…"))` carries no
//! database because the crossing it types has none: a computed value is DERIVED from the member
//! rather than read out of a row, so there is nothing per database for it to differ about.
//!
//! A field's `members(…)` block extends the axis one step — interface field block ▸ MEMBERS ▸ one
//! block per variant ▸ entries — and the step is INTERFACE-SPECIFIC: a record grows no member axis,
//! having no members.
//!
//! POSITION decides what a key is, and nothing else does. Outside `members(…)` every key is a word
//! this grammar owns; inside it every key is a VARIANT, matched token-for-token against the enum's
//! own. So a variant spelled `type` is reachable — it is a key inside the container and a grammar
//! word outside it — and one spelled in lower case is reachable too, where a rule reading the first
//! letter had a corner it could not address.
//!
//! # `fields(…)` is parsed by hand, and it has to be
//!
//! `title: String` is not `#[meta]` syntax — a nested meta entry is a path, then optionally `=
//! value` or `(…)`, and a `:` is none of those. So the list's tokens are taken verbatim and parsed
//! as a punctuated sequence of this grammar's own entries; a STRUCTURED entry's options are then
//! handed back to [`syn::meta::parser`], which is the same reader the rest of the grammar goes
//! through. Two forms, one reader for everything inside the second.
//!
//! # An entry is read exactly when something reads it
//!
//! A field's `graphql(input(…))` and an interface-level `persist(<db>(<leg>(error = "…")))` were
//! both ADMITTED AND REFUSED — real entries of the settled design whose CONSUMERS had not landed.
//! Both have one now. `persist(<db>(try_into(error = "…")))` types what the emitted HYDRATION
//! answers with; a field's `graphql(input(comparison(<db>(try_into = "…"))))` is the function that
//! field's OPERANDS enter storage through, and the interface-level
//! `graphql(input(comparison(<db>(try_into(error = "…")))))` beside it is what the whole crossing
//! refuses with. The other three legs stay refused in both positions, because an interface performs
//! no crossing in their direction, and a field's `graphql(output(…))` stays refused because the face
//! that would spend it is not written yet — the FACT it waited on, a member's object publishing each
//! field under its domain name, is in place now and the face is not.
//!
//! Recognised, so a refusal names the shape and says when it arrives; refused, so an author is never
//! left believing a rule was declared that nothing reads.
//!
//! # The two operand cells sit at different LEVELS, and the split is what each answers
//!
//! Which FUNCTION carries a value across is a fact about a COLUMN — a `u64` pinned at a big-endian
//! blob has no `TryFrom` between the two — so the converter is the field's. What the whole crossing
//! REFUSES with is one type for every column, because `TryFromFilter::Error` is one associated type,
//! so the cell is the interface's. A per-field error cell could not be spelled without either
//! picking one column's refusal to be the crossing's or inventing a sum nobody declared.

use ingraph_codegen::{
  interface::{
    InterfaceDatabase, InterfaceError, InterfaceField, InterfaceModel, MemberColumn, Operand, Pin,
    Tier,
  },
  model::{AliasOptions, DatabaseKind},
  prefix::EmissionPrefix,
  union::UnionMember,
};
use quote::ToTokens as _;
use syn::{ext::IdentExt as _, parse::Parser as _};

use crate::{
  alias,
  attribute::{self, set_once},
  errors::Errors,
  members::{self, Family},
  parse::SORTABLE,
  value,
};

#[cfg(test)]
mod member_field_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tower_tests;

/// The interface's own words for the rules [`crate::members`] enforces.
///
/// The SHAPES are the union's and the LAWS are not: a union refuses two variants of one type
/// because GraphQL's type validation says a union's members are unique, and an interface refuses it
/// because a promise stated twice over one member is stated once.
const FAMILY: Family = Family {
  derive: "#[ingraph::interface]",
  noun: "interface",
  possessive: "An interface's",
  not_an_enum: "an interface IS its member set, one variant per member, and a struct declares no \
                alternatives at all",
  empty: "an interface is a promise ABOUT its members, so one with none promises nothing of \
          anybody; Rust's own law is that an enum with no variants has no value to be",
  several: "An interface is a choice BETWEEN member types with one contract over them, so an \
            alternative holding two of them is a member nothing promised anything about. Declare \
            the pair as a type of its own and carry that",
  positional: "A variant's one member is the whole of what it holds, so there is nothing for a \
               field name to tell it apart from.",
  variant_entry: "a variant takes none. A member is named by the TYPE it carries, and every fact \
                  about the set is stated once in `fields(…)`",
  duplicate: "an interface states its contract over each member ONCE, so a type reached through \
              two variants would carry the same promise twice and no fan-out could say which \
              variant it answered from",
  generic: "an interface's members are the TYPES its variants carry, and a parameter is not one \
            until it is substituted; the contract it states over them names the members' own \
            columns, which do not exist before that",
};

/// 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,
  arguments: &[syn::Attribute],
) -> syn::Result<InterfaceModel> {
  let mut errors = Errors::default();
  crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
  let options = options(arguments, &mut errors);
  members::concrete(&FAMILY, &input.generics, &mut errors);

  let members = match members::members(&FAMILY, input, &mut errors) {
    Ok(members) => members,
    Err(terminal) => return Err(errors.seal(terminal)),
  };
  members::collisions(&FAMILY, &members, &mut errors);

  let fields = fields_model(&input.ident, &members, options.fields, &mut errors);

  let model = InterfaceModel {
    prefix: EmissionPrefix::default(),
    vis: input.vis.clone(),
    name: input.ident.clone(),
    krate: options
      .krate
      .unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    members,
    fields,
    error: options.error,
    computed_error: options.computed_error,
    persist: options.persist,
    errors: options.errors,
    operand_errors: options.operand_errors,
    plural: options.plural.as_ref().map(syn::LitStr::value),
    connection: options.connection.as_ref().map(syn::LitStr::value),
    edge: options.edge.as_ref().map(syn::LitStr::value),
  };
  emitted_names(&model, &mut errors);
  errors.into_result(model)
}

/// What the interface-level attribute carried.
#[derive(Default)]
struct Options {
  krate: Option<syn::Path>,
  error: Option<syn::Ident>,
  computed_error: Option<syn::Path>,
  persist: Vec<InterfaceDatabase>,
  errors: Vec<InterfaceError>,
  operand_errors: Vec<InterfaceError>,
  /// `graphql(plural = "…")` — the naming tower's middle tier, carried as the literal it was
  /// written as so a refusal lands where its author wrote it.
  plural: Option<syn::LitStr>,
  /// `graphql(connection(rename = "…"))` — the tower's top, for the page.
  connection: Option<syn::LitStr>,
  /// `graphql(edge(rename = "…"))` — the tower's top, for one edge of it.
  edge: Option<syn::LitStr>,
  /// `None` where no `fields(…)` block was written at all, which is its own refusal.
  fields: Option<Vec<Entry>>,
}

/// One entry of `fields(…)`, in whichever of its two forms it was written.
///
/// The STRUCTURED form's options are kept as tokens rather than walked here, so the two forms are
/// separated by one parser and read by another — which is what lets the second be
/// [`syn::meta::parser`] rather than a hand-rolled option reader.
struct Entry {
  name: syn::Ident,
  shape: Shape,
}

enum Shape {
  /// `name: Type` — the domain type, and every other answer defaulted.
  ///
  /// BOXED, because a [`syn::Type`] is several times the size of a token stream and an entry is one
  /// of the two: an unboxed variant makes every entry in the list as large as the largest type a
  /// declaration could spell.
  Short(Box<syn::Type>),
  /// `name(…)` — the options, verbatim.
  Structured(proc_macro2::TokenStream),
}

impl syn::parse::Parse for Entry {
  fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
    // `parse_any`, so a field spelled with a Rust keyword — `type`, `match` — is readable as the
    // name it is: what this list names are the members' own columns, and rustc's grammar has
    // nothing to say about those.
    let name = input.call(syn::Ident::parse_any)?;
    if input.peek(syn::Token![:]) {
      input.parse::<syn::Token![:]>()?;
      return Ok(Self {
        name,
        shape: Shape::Short(Box::new(input.parse()?)),
      });
    }
    if input.peek(syn::token::Paren) {
      let options;
      syn::parenthesized!(options in input);
      return Ok(Self {
        name,
        shape: Shape::Structured(options.parse()?),
      });
    }
    Err(syn::Error::new_spanned(&name, FIELD_SHAPE))
  }
}

/// The refusal an entry of `fields(…)` gets when it is neither of the two forms.
const FIELD_SHAPE: &str = "a field is `<name>: <Type>` or `<name>(type = \"<Type>\", …)` — the short \
                           form takes every default, and the long one is where a pin, a projection \
                           or a tier is written";

/// The refusal an interface with nothing to promise gets.
const NO_FIELDS: &str = "an interface with no fields is a UNION — it states nothing about its \
                         members, so nothing about it needs a contract, and `#[derive(ingraph::Union)]` \
                         equips exactly that declaration";

/// Walk the interface's own attributes.
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Options {
  let mut options = Options::default();
  let mut persist_seen = None;
  let mut graphql_seen = None;
  let mut computed_seen = None;
  let mut input_seen = None;
  let mut fields_seen = None;

  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,
        "`#[ingraph(crate = \"…\")]` must be a path to the `ingraph` crate, in a string literal",
      ) {
        Ok(path) => set_once(
          &mut options.krate,
          path,
          &meta.path,
          "`crate` is declared more than once — one declaration names one crate",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }

    if let Some(walked) = members::refusal_knob(&meta, &mut options.error, errors) {
      return walked;
    }

    if meta.path.is_ident("persist") {
      return attribute::block(
        &meta,
        &mut persist_seen,
        "`persist(…)` is declared more than once — one block names the databases",
        errors,
        |inner, errors| {
          interface_database(&inner, &mut options.persist, &mut options.errors, errors)
        },
      );
    }

    if meta.path.is_ident("graphql") {
      return attribute::block(
        &meta,
        &mut graphql_seen,
        "`graphql(…)` is declared more than once — one block per domain",
        errors,
        |inner, errors| {
          if inner.path.is_ident("computed") {
            return attribute::block(
              &inner,
              &mut computed_seen,
              "`computed(…)` is declared more than once in `graphql(…)` — one cell, one type",
              errors,
              |cell, errors| {
                if cell.path.is_ident("error") {
                  match value::parse_literal::<syn::Path>(&cell, COMPUTED_ERROR) {
                    Ok(path) => set_once(
                      &mut options.computed_error,
                      path,
                      &cell.path,
                      "`error` is declared more than once in `graphql(computed(…))` — one cell, \
                       one type",
                      errors,
                    ),
                    Err(e) => errors.push(e),
                  }
                  return Ok(());
                }
                errors.push(misplaced_database(&cell).unwrap_or_else(|| {
                  attribute::unknown(
                    &cell,
                    "unknown entry in `graphql(computed(…))` — it takes `error = \"…\"` and \
                     nothing else. A computed value is derived from the member rather than read \
                     out of a row, so the crossing names no database and there is nothing per \
                     database for a cell to differ about",
                    &["error"],
                  )
                }));
                Ok(())
              },
            );
          }
          if inner.path.is_ident("input") {
            return attribute::block(
              &inner,
              &mut input_seen,
              "`input(…)` is declared more than once in `graphql(…)` — one block per position",
              errors,
              |position, errors| operand_position(&position, &mut options.operand_errors, errors),
            );
          }
          if inner.path.is_ident("output") {
            errors.push(attribute::unknown(
              &inner,
              &format!(
                "`output(<db>(try_from(error = \"…\")))` types the crossing a member's ROW makes \
                 onto the wire, and {AN_OUTPUT_FACE_ARRIVES_WITH_THE_ACCESSOR}"
              ),
              // `output` was spelled right and is refused as the wait it is.
              &[],
            ));
            return Ok(());
          }
          // The NAMING TOWER, uniform with a record's — B-27's D-6. The PLURAL is a WORD rather
          // than a name, so it is held to the wire floor at the literal's own span; the two page
          // names are SDL entities, so they are string-kind and GraphQL's Name grammar is their
          // only fence — the #250 classification, applied to the second front end that has a page.
          if inner.path.is_ident("plural") {
            match value::literal(&inner, crate::parse::PLURAL_WORD) {
              Ok(word) => {
                crate::wire::refuse_invalid_name(&word.value(), &word, errors);
                set_once(
                  &mut options.plural,
                  word,
                  &inner.path,
                  "`plural` is declared more than once in `graphql(…)` — one option, one value",
                  errors,
                );
              }
              Err(e) => errors.push(e),
            }
            return Ok(());
          }
          if inner.path.is_ident("connection") {
            return attribute::sdl_name_block(
              &inner,
              &mut options.connection,
              "connection",
              errors,
            );
          }
          if inner.path.is_ident("edge") {
            return attribute::sdl_name_block(&inner, &mut options.edge, "edge", errors);
          }
          errors.push(misplaced_database(&inner).unwrap_or_else(|| {
            attribute::unknown(
              &inner,
              "unknown entry in `graphql(…)` at the interface level — it takes \
               `computed(error = \"…\")`, `input(comparison(<db>(try_into(error = \"…\"))))`, \
               `plural = \"…\"`, and a block per SDL page name (`connection`, `edge`). A field's \
               own wire facts are written on the field",
              &["computed", "input", "plural", "connection", "edge"],
            )
          }));
          Ok(())
        },
      );
    }

    if meta.path.is_ident("fields") {
      set_once(
        &mut fields_seen,
        meta.path.clone(),
        &meta.path,
        "`fields(…)` is declared more than once — one list carries the whole contract",
        errors,
      );
      match attribute::verbatim(&meta).map(|tokens| {
        syn::punctuated::Punctuated::<Entry, syn::Token![,]>::parse_terminated.parse2(tokens)
      }) {
        Ok(Ok(entries)) => options.fields = Some(entries.into_iter().collect()),
        Ok(Err(e)) | Err(e) => {
          errors.push(e);
          options.fields = Some(Vec::new());
        }
      }
      return Ok(());
    }

    errors.push(misplaced_database(&meta).unwrap_or_else(|| {
      attribute::unknown(
        &meta,
        "unknown entry in `#[ingraph(…)]` on an interface — it takes `crate = \"…\"`, \
         `unwrap_error(rename = \"…\")`, `persist(…)`, `graphql(…)` and `fields(…)`",
        &["crate", "unwrap_error", "persist", "graphql", "fields"],
      )
    }));
    Ok(())
  });

  options
}

/// The refusal the computed cell's `error` gets when it is not a path.
const COMPUTED_ERROR: &str = "`error` must be a path to the type a fallible computed field answers \
                              with, in a string literal";

/// ONE database inside the interface's own `persist(…)`.
///
/// The block is a SELECTION and nothing else today: an interface owns no table, so what naming a
/// database does is put it among the ones a row equation is checked at. The per-leg error cells the
/// settled design puts here are recognised and refused — see [`A_CELL_ARRIVES_WITH_THE_FIND_HALF`].
fn interface_database(
  inner: &syn::meta::ParseNestedMeta<'_>,
  selected: &mut Vec<InterfaceDatabase>,
  cells: &mut Vec<InterfaceError>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let Some(kind) = database_kind(&inner.path) else {
    errors.push(attribute::unknown(
      inner,
      &format!(
        "unknown entry in `persist(…)` on an interface — every entry names a DATABASE, because \
         what the block does is select the ones the contract's pins are checked at: {list}",
        list = shipped()
      ),
      &DatabaseKind::ALL.map(DatabaseKind::as_str),
    ));
    return Ok(());
  };
  if selected.iter().any(|database| database.kind == kind) {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      format!(
        "`{kind}` is declared more than once in `persist(…)` — one block per database",
        kind = kind.as_str()
      ),
    ));
    attribute::skip_entry(inner);
    return Ok(());
  }
  selected.push(InterfaceDatabase {
    kind,
    aliases: AliasOptions::default(),
  });
  let at = selected.len() - 1;
  let scope = format!("`{}(…)`", kind.as_str());
  let mut leg_seen = None;
  let mut alias_seen = None;
  attribute::options(inner, |leg| {
    if leg.path.is_ident("alias") {
      return alias::block(
        &leg,
        &mut selected[at].aliases,
        &mut alias_seen,
        &scope,
        alias::Depth::Unsized("an interface"),
        errors,
      );
    }
    if leg.path.is_ident(ADMITTED_LEG) {
      return attribute::block(
        &leg,
        &mut leg_seen,
        "`try_into(…)` is declared more than once for this database — one leg, one type",
        errors,
        |cell, errors| {
          if cell.path.is_ident("error") {
            match value::parse_literal::<syn::Path>(&cell, HYDRATION_ERROR) {
              Ok(error) => cells.push(InterfaceError { kind, error }),
              Err(e) => errors.push(e),
            }
            return Ok(());
          }
          errors.push(misplaced_database(&cell).unwrap_or_else(|| {
            attribute::unknown(
              &cell,
              "unknown entry in `persist(<db>(try_into(…)))` — the leg takes `error = \"…\"` and \
               nothing else",
              &["error"],
            )
          }));
          Ok(())
        },
      );
    }
    if let Some(word) = REFUSED_LEGS.iter().find(|word| leg.path.is_ident(word)) {
      errors.push(attribute::unknown(
        &leg,
        &format!(
          "`{word}(error = \"…\")` is an interface's per-leg refusal cell, and \
           {A_CELL_ARRIVES_WITH_THE_FIND_HALF}"
        ),
        // A leg word this grammar names, matched exactly and refused as the wait it is.
        &[],
      ));
      return Ok(());
    }
    errors.push(attribute::unknown(
      &leg,
      &format!(
        "unknown entry in `persist(<db>(…))` on an interface — a database block here selects the \
         database, names the namespace its synthetic words are minted in with `alias(…)`, and \
         carries the per-leg cells `{legs}`, each taking `error = \"…\"`; only `{ADMITTED_LEG}` \
         is read today",
        legs = LEGS.join("`, `")
      ),
      &["alias"].into_iter().chain(LEGS).collect::<Vec<_>>(),
    ));
    Ok(())
  })
}

/// `input(…)` at the interface level — the POSITION axis, which admits `comparison` and nothing
/// else.
///
/// The refusals are the record grammar's, restated because they are the same rule: an ORDER input
/// carries a direction and a subject and never a value, so it has no operand to cross and no cell to
/// type it with; and a cursor is an opaque engine round trip that already speaks the stored
/// vocabulary.
fn operand_position(
  position: &syn::meta::ParseNestedMeta<'_>,
  cells: &mut Vec<InterfaceError>,
  errors: &mut Errors,
) -> syn::Result<()> {
  if position.path.is_ident("comparison") {
    let mut databases: Vec<DatabaseKind> = Vec::new();
    return attribute::options(position, |database| {
      operand_database(&database, &mut databases, cells, errors)
    });
  }
  for (word, why) in [
    (
      "orderby",
      "an order input carries a DIRECTION and a subject, never a value — so there is no operand \
       here for a crossing to carry and no refusal for a cell to name",
    ),
    (
      "pagination",
      "a cursor is an opaque engine round trip whose slots already hold the types a database \
       stores — nothing about one crosses at the wire",
    ),
  ] {
    if position.path.is_ident(word) {
      errors.push(attribute::unknown(
        position,
        &format!("`{word}(…)` is not a position `input(…)` admits: {why}"),
        // A position word this grammar names, matched exactly and answered by reason.
        &[],
      ));
      return Ok(());
    }
  }
  errors.push(misplaced_database(position).unwrap_or_else(|| {
    attribute::unknown(
      position,
      "unknown entry in `graphql(input(…))` — the position axis admits `comparison(…)` alone, a \
       filter's operands being the only wire values that cross into storage",
      &["comparison"],
    )
  }));
  Ok(())
}

/// ONE database inside `graphql(input(comparison(…)))` — the leg that types what CROSSING a wire
/// filter into that database's predicate refuses with.
///
/// The `try_into` leg, and the direction is the verb rule's: a filter's operands LEAVE the wire for
/// the types a database stores. The other three are refused for [`REFUSED_LEGS`]'s reason, one axis
/// over — an interface performs no crossing in their direction here either.
fn operand_database(
  database: &syn::meta::ParseNestedMeta<'_>,
  seen: &mut Vec<DatabaseKind>,
  cells: &mut Vec<InterfaceError>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let Some(kind) = database_kind(&database.path) else {
    errors.push(attribute::unknown(
      database,
      &format!(
        "unknown entry in `graphql(input(comparison(…)))` — every entry names a DATABASE, a \
         predicate being per database: {list}",
        list = shipped()
      ),
      &DatabaseKind::ALL.map(DatabaseKind::as_str),
    ));
    return Ok(());
  };
  if seen.contains(&kind) {
    errors.push(syn::Error::new_spanned(
      &database.path,
      format!(
        "`{kind}` is declared more than once in `input(comparison(…))` — one block per database",
        kind = kind.as_str()
      ),
    ));
    attribute::skip_entry(database);
    return Ok(());
  }
  seen.push(kind);
  let mut leg_seen = None;
  attribute::options(database, |leg| {
    if leg.path.is_ident(ADMITTED_LEG) {
      return attribute::block(
        &leg,
        &mut leg_seen,
        "`try_into(…)` is declared more than once for this database — one leg, one type",
        errors,
        |cell, errors| {
          if cell.path.is_ident("error") {
            match value::parse_literal::<syn::Path>(&cell, OPERAND_ERROR) {
              Ok(error) => cells.push(InterfaceError { kind, error }),
              Err(e) => errors.push(e),
            }
            return Ok(());
          }
          errors.push(misplaced_database(&cell).unwrap_or_else(|| {
            attribute::unknown(
              &cell,
              "unknown entry in `input(comparison(<db>(try_into(…))))` at the interface level — \
               the leg takes `error = \"…\"` and nothing else. The CONVERTER is a field's own, \
               because which function carries a value is a fact about that column",
              &["error"],
            )
          }));
          Ok(())
        },
      );
    }
    if let Some(word) = REFUSED_LEGS.iter().find(|word| leg.path.is_ident(word)) {
      errors.push(attribute::unknown(
        &leg,
        &format!(
          "`{word}(…)` is not the leg an operand takes — a filter's values LEAVE the wire for the \
           types a database stores, which is `{ADMITTED_LEG}`, and an interface performs no \
           crossing in the other direction"
        ),
        &[],
      ));
      return Ok(());
    }
    errors.push(attribute::unknown(
      &leg,
      &format!(
        "unknown entry in `input(comparison(<db>(…)))` at the interface level — the database block \
         carries `{ADMITTED_LEG}(error = \"…\")`, which types what crossing a wire filter into this \
         database's predicate refuses with"
      ),
      &[ADMITTED_LEG],
    ));
    Ok(())
  })
}

/// The refusal the operand cell's `error` gets when it is not a path.
const OPERAND_ERROR: &str = "`error` must be a path to the type this database's operand crossing \
                             answers with, in a string literal";

/// The clause the OUTPUT position's refusal ends with — the stored output face's blocker, said where
/// an author would write for it.
///
/// The MISSING FACT is no longer missing. A member's wire object publishes each field under that
/// field's own DOMAIN name — member and accessor both — so an interface can now reach a member's
/// object by the one name it knows, and a member renaming its schema field no longer takes the field
/// out of the contract's reach. What is still absent is the FACE: nothing here reads a member's
/// object yet, so a cell typing that crossing would be a rule its author believes they declared.
const AN_OUTPUT_FACE_ARRIVES_WITH_THE_ACCESSOR: &str = "arrives with the interface's own output face — a member's wire object publishes every field under \
   its DOMAIN name now, so the fact this waited on is in place and what is left is the face itself; \
   until something here reads a member's object there is no crossing for a cell to type";

/// The refusal the hydration cell's `error` gets when it is not a path.
const HYDRATION_ERROR: &str = "`error` must be a path to the type this database's hydration answers \
                               with, in a string literal";

/// The four words that open a CONVERSION LEG, each of which takes an `error = "…"` cell.
///
/// The per-leg shape rather than one flat `error` per database: which leg refused is what a caller
/// catches, so the type it answers with is the leg's.
const LEGS: [&str; 4] = ["from", "try_from", "into", "try_into"];

/// The ONE leg whose consumer exists: `try_into`, which is the READ direction the verb rule names —
/// a page's rows leave storage for the members' own wire outputs, and the emitted hydration is the
/// crossing that performs it.
///
/// It was admitted-and-refused until that consumer landed, which is the standing posture: an entry
/// is read exactly when something reads it.
const ADMITTED_LEG: &str = "try_into";

/// The three that stay refused, for [`A_CELL_ARRIVES_WITH_THE_FIND_HALF`]'s reason: an interface
/// performs no crossing in any of those directions, so a type named for one is a rule its author
/// believes they declared.
const REFUSED_LEGS: [&str; 3] = ["from", "try_from", "into"];

/// The clause every ADMITTED-AND-REFUSED entry ends with.
///
/// One sentence, said once: what these entries type is a crossing the READ side spends, and the
/// read side is the find half. Refused rather than accepted, because an entry nobody reads is a
/// rule its author believes they declared.
const A_CELL_ARRIVES_WITH_THE_FIND_HALF: &str = "arrives with the find half — what it types is a crossing nothing in this round performs, and an \
   entry nobody reads is a rule its author believes they declared";

/// The database a block names, if it names one.
fn database_kind(path: &syn::Path) -> Option<DatabaseKind> {
  DatabaseKind::ALL
    .into_iter()
    .find(|kind| path.is_ident(kind.as_str()))
}

/// The databases a declaration may name, as a SENTENCE lists them.
fn shipped() -> String {
  let quoted: Vec<String> = DatabaseKind::ALL
    .into_iter()
    .map(|kind| format!("`{}`", kind.as_str()))
    .collect();
  match quoted.split_last() {
    Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
    None => String::new(),
  }
}

/// The AXIS LAW's refusal: a database name written where a DOMAIN belongs.
///
/// `None` where the entry is not a database at all, so a caller falls through to whatever its own
/// scope does not recognise. Named rather than swept into "unknown entry", because an author who
/// writes one has a concrete idea and the useful answer is which block it belongs in.
fn misplaced_database(inner: &syn::meta::ParseNestedMeta<'_>) -> Option<syn::Error> {
  let kind = database_kind(&inner.path)?;
  let error = syn::Error::new_spanned(
    inner.path.to_token_stream(),
    format!(
      "`{kind}` is a DATABASE and this is not a database's scope — a database block sits inside a \
       DOMAIN, as in `persist({kind}(…))`. The axis is domain, then database, then the cell's own \
       entries, and it is the same at every level of this grammar",
      kind = kind.as_str()
    ),
  );
  attribute::skip_entry(inner);
  Some(error)
}

/// The `fields(…)` list as the model carries it, with every field-level rule checked.
fn fields_model(
  interface: &syn::Ident,
  members: &[UnionMember],
  entries: Option<Vec<Entry>>,
  errors: &mut Errors,
) -> Vec<InterfaceField> {
  let Some(entries) = entries else {
    errors.push(syn::Error::new_spanned(interface, NO_FIELDS));
    return Vec::new();
  };
  if entries.is_empty() {
    errors.push(syn::Error::new_spanned(interface, NO_FIELDS));
    return Vec::new();
  }

  let mut fields: Vec<InterfaceField> = Vec::with_capacity(entries.len());
  for entry in entries {
    if let Some(first) = fields.iter().find(|field| field.name == entry.name) {
      errors.push(syn::Error::new_spanned(
        &entry.name,
        format!(
          "`{name}` is declared more than once in `fields(…)` — one field, one promise, and \
           `{first}` already carries this name",
          name = entry.name,
          first = first.name,
        ),
      ));
      continue;
    }
    if let Some(field) = field_model(entry, members, errors) {
      fields.push(field);
    }
  }
  fields
}

/// ONE field, in whichever of the two forms it was written.
fn field_model(
  entry: Entry,
  members: &[UnionMember],
  errors: &mut Errors,
) -> Option<InterfaceField> {
  let name = entry.name;
  let tokens = match entry.shape {
    Shape::Short(ty) => {
      return Some(InterfaceField {
        name,
        ty: *ty,
        tier: Tier::Stored,
        marker: None,
        copy: false,
        pins: Vec::new(),
        wire: None,
        operands: Vec::new(),
        members: Vec::new(),
      });
    }
    Shape::Structured(tokens) => tokens,
  };

  let mut ty: Option<syn::Type> = None;
  // Whether a `type` entry was WRITTEN, which is a different question from whether one was READ. A
  // field whose `type = …` could not be read has already been refused at the value it wrote; saying
  // a second time that it names no type would report a mistake it did not make, at a span that is
  // not where the one it did make is.
  let mut type_written = false;
  let mut word: Option<crate::parse::Written> = None;
  let mut copy = None;
  let mut pins: Vec<Pin> = Vec::new();
  let mut persist: Option<Written<()>> = None;
  let mut computed: Option<Written<Tier>> = None;
  let mut wire: Option<syn::Type> = None;
  let mut input_seen: Option<syn::Path> = None;
  let mut operands: Vec<Operand> = Vec::new();
  let mut columns: Vec<MemberColumn> = Vec::new();
  let mut renamed_at: Option<syn::Path> = None;
  let mut members_seen: Option<syn::Path> = None;
  let mut graphql_seen = None;
  // Which entry was written FIRST, counted rather than read off a span: the tier refusal points at
  // the later of the two, and a byte range is not something a token from a macro expansion has.
  let mut written = 0_usize;

  let walked = syn::meta::parser(|option| {
    written += 1;
    if option.path.is_ident("type") {
      type_written = true;
      match value::parse_literal::<syn::Type>(&option, FIELD_TYPE) {
        Ok(declared) => set_once(
          &mut ty,
          declared,
          &option.path,
          "`type` is declared more than once on a field — one field, one type",
          errors,
        ),
        // The value stays in the stream when it was not a string literal, so the walk has to be
        // moved past it — a bare `type = String` would otherwise cost a second, worse-worded error
        // at the token after the one the refusal already points at.
        Err(e) => {
          errors.push(e);
          attribute::skip_entry(&option);
        }
      }
      return Ok(());
    }

    if option.path.is_ident("copy") {
      set_once(
        &mut copy,
        option.path.clone(),
        &option.path,
        "`copy` is declared more than once on a field — one claim, one field",
        errors,
      );
      attribute::skip_entry(&option);
      return Ok(());
    }

    if option.path.is_ident("persist") {
      let mut seen = persist.as_ref().map(|block| block.at.clone());
      let walked = attribute::block(
        &option,
        &mut seen,
        "`persist(…)` is declared more than once on a field — one block per domain",
        errors,
        |database, errors| field_pin(&name, &database, &mut pins, errors),
      );
      persist.get_or_insert(Written {
        value: (),
        at: option.path.clone(),
        written,
      });
      return walked;
    }

    if option.path.is_ident("graphql") {
      return attribute::block(
        &option,
        &mut graphql_seen,
        "`graphql(…)` is declared more than once on a field — one block per domain",
        errors,
        |inner, errors| {
          field_wire(
            &inner,
            written,
            &mut computed,
            &mut wire,
            &mut input_seen,
            &mut operands,
            errors,
          )
        },
      );
    }

    if option.path.is_ident("members") {
      set_once(
        &mut members_seen,
        option.path.clone(),
        &option.path,
        "`members(…)` is declared more than once on a field — one block carries every member",
        errors,
      );
      // An EMPTY `members()` is answered here rather than walked, for the reason
      // `attribute::empty_group` gives: syn refuses one on its own terms, which would cost a
      // deliberate mistake a second, worse-worded error.
      if !attribute::has_block(&option) || attribute::empty_group(&option) {
        errors.push(syn::Error::new_spanned(&option.path, NO_MEMBERS));
        attribute::skip_entry(&option);
        return Ok(());
      }
      renamed_at.get_or_insert(option.path.clone());
      return option
        .parse_nested_meta(|block| member_column(&name, &block, members, &mut columns, errors));
    }

    // LAST among the recognised entries, so a word this grammar ships is read as the label it is
    // and everything else still reaches the sentences below — the ORDER the record's own field
    // walk takes, for its reason: no other entry of a field block shares a name with a label word,
    // so the position costs nothing and says which reading wins.
    if crate::parse::begins_a_label(&option.path) {
      let at = option.path.clone();
      if let Some(declared) = crate::parse::label(&option, errors) {
        set_once(
          &mut word,
          declared,
          &at,
          "an interpretation word is declared more than once on a field — one word, one pin",
          errors,
        );
      }
      return Ok(());
    }

    // The old spelling, refused BY NAME. What tells it apart is not its case but the fact that it
    // names a VARIANT — asked of the enum's own list, which is the same question the container's
    // own keys are put to.
    if let Some(member) = named_member(&option.path, members) {
      errors.push(attribute::unknown(
        &option,
        &format!(
          "`{member}` is a MEMBER and this is the field's own scope — a member block lives inside \
           `members(…)` now: write `members({member}(field = \"…\"))`. POSITION is what decides a \
           key here, so outside that container every key is a word this grammar owns and inside it \
           every key is a variant"
        ),
        // A variant name matched against the enum's own list — spelled right by definition.
        &[],
      ));
      return Ok(());
    }

    errors.push(misplaced_database(&option).unwrap_or_else(|| {
      attribute::unknown(
        &option,
        &format!(
          "unknown entry on a field of `fields(…)` — it takes `type = \"<Type>\"`, `copy`, \
           `persist(…)`, `graphql(…)`, `members(…)`, and {vocabulary}",
          vocabulary = crate::parse::label_vocabulary(),
        ),
        &crate::parse::label_words()
          .into_iter()
          .chain(["type", "copy", "persist", "graphql", "members"])
          .collect::<Vec<_>>(),
      )
    }));
    Ok(())
  })
  .parse2(tokens);
  if let Err(e) = walked {
    errors.push(e);
  }

  let tier = tiered(&name, computed, persist, errors);
  // A derivation hands back an OWNED value, so there is nothing for a projection claim to move —
  // and an entry nobody reads is a rule its author believes they declared.
  if let (true, Some(at)) = (tier.computed(), copy.as_ref()) {
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{name}` is COMPUTED and claims `copy` — a derivation produces its value rather than \
         holding one, so the contract hands it back owned whatever its type is and there is no \
         borrow for the claim to displace"
      ),
    ));
  }
  // A derived value is not read out of anything, so there is no column for a member to call by
  // another name — the refusal is the tier collision's one level in.
  if let (true, Some(at)) = (tier.computed(), renamed_at.as_ref()) {
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{name}` is COMPUTED and names a member's column — a value every member derives is read \
         out of no column at all, so there is nothing here for a member to call something else. \
         Drop the member block, or drop the `computed` word and let the members' rows carry it"
      ),
    ));
    columns.clear();
  }
  let Some(ty) = ty else {
    if !type_written {
      errors.push(syn::Error::new_spanned(&name, FIELD_TYPE));
    }
    return None;
  };
  // A derived value never reaches a predicate — the filter's fields are the STORED tier — so an
  // operand crossing on a computed field types a hop nothing takes.
  if tier.computed() && !operands.is_empty() {
    errors.push(syn::Error::new_spanned(
      &name,
      format!(
        "`{name}` is COMPUTED and names an operand crossing — a value every member derives is a \
         column nowhere, so it is statically absent from the filter and no operand of it ever \
         enters storage. Drop the `input(comparison(…))` block, or drop the `computed` word and \
         let the members' rows carry it"
      ),
    ));
    operands.clear();
  }
  // A word says how a STORED column is read — which filter kind its operands take, and whether the
  // member's row holds one value or a list of them. A derived value is read out of no column at all,
  // so the word has nothing here to interpret, and an entry nobody reads is a rule its author
  // believes they declared.
  let marker = match (tier.computed(), word) {
    (true, Some(declared)) => {
      errors.push(declared.refuse(format!(
        "`{name}` is COMPUTED and names an interpretation word — a value every member derives is a \
         column nowhere, so there is no stored reading for a word to pick. Drop the word, or drop \
         the `computed` word and let the members' rows carry it"
      )));
      None
    }
    (true, None) | (false, None) => None,
    (false, Some(declared)) => Some(declared.marker()),
  };
  Some(InterfaceField {
    name,
    ty,
    tier,
    marker,
    copy: copy.is_some(),
    pins,
    wire,
    operands,
    members: columns,
  })
}

/// The member an entry's key names, if it names one.
///
/// Asked of the enum's OWN LIST rather than of the key's shape, which is the whole of what makes
/// position the deciding rule: nothing about a word's spelling says whether it is a variant, and
/// the declaration that would know is in the same `DeriveInput`. Unraw'd on both sides, `r#` being
/// Rust's escape for a word that collides with its grammar and no part of the name.
///
/// Two callers, opposite in what they do with the answer: the container reads a key it FOUND, and
/// the field's own scope refuses a key it found there.
fn named_member<'a>(path: &syn::Path, members: &'a [UnionMember]) -> Option<&'a syn::Ident> {
  let key = path.get_ident()?;
  members
    .iter()
    .map(|member| &member.ident)
    .find(|ident| ident.unraw() == key.unraw())
}

/// ONE member's column for one field — a block inside `members(…)`, keyed by a VARIANT.
///
/// # Every hop is backed by the same derive input
///
/// The key is checked TOKEN-FOR-TOKEN against the enum's own variants, verbatim case: a member set
/// and its contract arrive in one `DeriveInput`, so there is no boundary here to cross and no
/// spelling to guess at. What the variant then names is the payload type it carries, and what that
/// type projects to is the member's row — so the ident this block declares is the one both the
/// contract's field access and the row equation spell.
fn member_column(
  field: &syn::Ident,
  block: &syn::meta::ParseNestedMeta<'_>,
  members: &[UnionMember],
  columns: &mut Vec<MemberColumn>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let Some(key) = block.path.get_ident() else {
    errors.push(attribute::unknown(block, MEMBER_SHAPE, &[]));
    return Ok(());
  };
  let Some(member) = named_member(&block.path, members) else {
    errors.push(syn::Error::new_spanned(
      key,
      format!(
        "`{key}` is not a member variant of this interface — the members are {names}{near}",
        names = variants(members),
        // The one DECLARED vocabulary in this crate rather than a framework one: the position's
        // words are this enum's own variants, which arrive in the same `DeriveInput`.
        near = crate::suggest::did_you_mean(
          &key.to_string(),
          members.iter().map(|member| member.ident.to_string())
        ),
      ),
    ));
    attribute::skip_entry(block);
    return Ok(());
  };
  if columns.iter().any(|column| column.variant == *member) {
    errors.push(syn::Error::new_spanned(
      key,
      format!(
        "`{key}` is declared more than once on `{field}` — one member, one column, and a variant \
         that carried this field under two names would carry it under neither"
      ),
    ));
    attribute::skip_entry(block);
    return Ok(());
  }
  let variant = member.clone();
  let mut column: Option<syn::Ident> = None;
  let walked = attribute::options(block, |entry| {
    if entry.path.is_ident("field") {
      // The RAW-IDENT tolerance: a member's column may be legally called `r#type`, and the word the
      // schema and the database know it by is `type` — so both spellings name it. Both failures
      // answer with the same sentence, exactly as they did before the tolerance landed.
      match value::literal(&entry, MEMBER_FIELD)
        .and_then(|literal| value::named_field(&literal, MEMBER_FIELD))
      {
        Ok(named) => set_once(
          &mut column,
          named,
          &entry.path,
          "`field` is declared more than once in a member block — one member, one column",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &entry,
      "unknown entry in a member block — it takes `field = \"…\"` and nothing else. What a member \
       may differ about is the COLUMN it carries the field under; its type is the contract's, and \
       its pins are the interface's",
      &["field"],
    ));
    Ok(())
  });
  match column {
    Some(column) => columns.push(MemberColumn { variant, column }),
    None => errors.push(syn::Error::new_spanned(key, MEMBER_SHAPE)),
  }
  walked
}

/// The refusal a member block gets when it names no column.
const MEMBER_SHAPE: &str = "a member block is `<Variant>(field = \"…\")`, inside `members(…)` — \
                            naming the column that member carries the field under is the only thing \
                            it is for";

/// The refusal a `members(…)` naming nobody gets.
const NO_MEMBERS: &str = "`members(…)` names no member — the block is where a member says it \
                          carries this field under another name, so one with nothing in it says \
                          nothing. Omit it, and every member carries the field under the \
                          interface's own name";

/// The refusal a member's column gets when it is not an identifier.
///
/// An IDENT, unlike a record column's `rename`: what this names is a RUST FIELD — on the member's
/// own struct and on its row — and both are reached by field access, which no mangling can stand in
/// for.
const MEMBER_FIELD: &str = "`field` must be the column this member carries the field under, as an identifier in a string \
   literal";

/// The declaration's variants, as a SENTENCE lists them.
fn variants(members: &[UnionMember]) -> String {
  let quoted: Vec<String> = members
    .iter()
    .map(|member| format!("`{}`", member.ident))
    .collect();
  match quoted.split_last() {
    Some((last, [])) => last.clone(),
    Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
    None => String::new(),
  }
}

/// The refusal a field with no type gets, and the one an unreadable `type = …` gets.
///
/// A STRING, as every typed value in this grammar is written: the per-database pin's `type`, the
/// wire form's, the record's `ref(type = "…")`. This site was the one deviation — a bare token,
/// where the cells one level in already went through [`value::parse_literal`] — so the sentence
/// names the SPELLING rather than only the fact. The mistake it answers is a `type = String` that
/// the grammar used to take, and an author who reads it has to be told what to write instead.
const FIELD_TYPE: &str = "a field names its type — `<name>: <Type>` in the short form, `type = \
                          \"<Type>\"` in the long one, in a string literal as every other `type` \
                          in this grammar is written";

/// One entry as it was WRITTEN: what it said, the token it said it at, and how far into the field
/// it came.
///
/// The position is what the tier refusal points at the later of two entries with. Counted rather
/// than read off a span, because a token that arrived through a macro expansion has no byte range
/// to compare.
struct Written<T> {
  value: T,
  at: syn::Path,
  written: usize,
}

/// Which TIER the field is in, and the refusal when a declaration claims two.
///
/// Both directions get their own sentence, because the two mistakes are different: a computed field
/// that also pins a column has claimed a row holds what a member derives, and a pinned column that
/// is also computed has claimed a member derives what its row holds. The refusal is spanned at the
/// entry that arrived SECOND, which is the one an author added to a field that already read
/// correctly.
fn tiered(
  name: &syn::Ident,
  computed: Option<Written<Tier>>,
  persist: Option<Written<()>>,
  errors: &mut Errors,
) -> Tier {
  let Some(computed) = computed else {
    return Tier::Stored;
  };
  let Some(persist) = persist else {
    return computed.value;
  };
  if computed.written < persist.written {
    errors.push(syn::Error::new_spanned(
      &persist.at,
      format!(
        "`{name}` is COMPUTED and pinned — a value a member derives is not a column its row holds, \
         so there is nothing here for a database to store it as. Drop the pin, or drop the \
         `computed` word and let the members' rows carry it"
      ),
    ));
  } else {
    errors.push(syn::Error::new_spanned(
      &computed.at,
      format!(
        "`{name}` is PINNED and computed — a column the members' rows hold is not a value they \
         derive, so there is nothing here for a derivation to answer. Drop the word, or drop the \
         `persist(…)` block and let every member derive it"
      ),
    ));
  }
  computed.value
}

/// ONE database's pin for one field.
fn field_pin(
  field: &syn::Ident,
  database: &syn::meta::ParseNestedMeta<'_>,
  pins: &mut Vec<Pin>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let Some(kind) = database_kind(&database.path) else {
    // An interface PIN is a promise about every arm, and an arm's collection terms are always
    // edge-form — there is no per-arm companion column for a pin to project. The RECORD's storage
    // word is therefore refused HERE with what it is waiting on, rather than reaching the
    // every-entry-names-a-database sentence, which would answer a real word as a misspelling.
    if database.path.is_ident(SORTABLE) {
      errors.push(attribute::named(
        database,
        SORTABLE_IS_A_RECORDS_WORD.to_owned(),
      ));
      return Ok(());
    }
    errors.push(attribute::unknown(
      database,
      &format!(
        "unknown entry in `persist(…)` on a field — every entry names a DATABASE, because a stored \
         type is one database's: {list}",
        list = shipped()
      ),
      &DatabaseKind::ALL.map(DatabaseKind::as_str),
    ));
    return Ok(());
  };
  if pins.iter().any(|pin| pin.kind == kind) {
    errors.push(syn::Error::new_spanned(
      &database.path,
      format!(
        "`{kind}` is declared more than once in `{field}`'s `persist(…)` — one block per database",
        kind = kind.as_str()
      ),
    ));
    attribute::skip_entry(database);
    return Ok(());
  }
  let mut stored: Option<syn::Type> = None;
  let walked = attribute::options(database, |cell| {
    if cell.path.is_ident("type") {
      match value::parse_literal::<syn::Type>(&cell, PIN_TYPE) {
        Ok(declared) => set_once(
          &mut stored,
          declared,
          &cell.path,
          "`type` is declared more than once in a database's block — one column, one stored type",
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &cell,
      "unknown entry in `persist(<db>(…))` on a field — it takes `type = \"…\"`, the type this \
       database keeps the column at. A field with no entry here is stored at the type it was \
       declared with",
      &["type"],
    ));
    Ok(())
  });
  pins.push(Pin { kind, stored });
  walked
}

/// The refusal a per-database pin gets when it is not a type.
const PIN_TYPE: &str = "`type` must be the type this database stores the column at, in a string \
                        literal";

/// The refusal `persist(sortable)` gets on an interface PIN, with what the widening is waiting on.
///
/// The seat moved with the word — it used to be caught in the pin's LABEL, `sortable` having lived
/// inside a collection's parentheses — and the sentence did not: an arm's companion is a column of
/// ONE member's table, and the union's derived table selects no such column from any arm.
const SORTABLE_IS_A_RECORDS_WORD: &str = "`sortable` is a RECORD's word — an interface pin promises \
                                          a shared reading across every arm, and projecting an \
                                          arm's companion column through the union is a widening \
                                          this framework has not built. The pin's collection terms \
                                          are the degrade law's, as they were.";

/// A field's `graphql(…)` — the tier words, the wire form, and the position blocks the find half
/// consumes.
fn field_wire(
  inner: &syn::meta::ParseNestedMeta<'_>,
  written: usize,
  computed: &mut Option<Written<Tier>>,
  wire: &mut Option<syn::Type>,
  input: &mut Option<syn::Path>,
  operands: &mut Vec<Operand>,
  errors: &mut Errors,
) -> syn::Result<()> {
  for (word, tier) in [
    ("computed", Tier::Computed),
    ("try_computed", Tier::TryComputed),
  ] {
    if inner.path.is_ident(word) {
      set_once(
        computed,
        Written {
          value: tier,
          at: inner.path.clone(),
          written,
        },
        &inner.path,
        "a field is COMPUTED once — `computed` and `try_computed` are the same claim about whether \
         deriving it can fail, and there is no third answer",
        errors,
      );
      attribute::skip_entry(inner);
      return Ok(());
    }
  }

  if inner.path.is_ident("type") {
    match value::parse_literal::<syn::Type>(inner, WIRE_TYPE) {
      Ok(declared) => set_once(
        wire,
        declared,
        &inner.path,
        "`type` is declared more than once in `graphql(…)` — one field, one wire form",
        errors,
      ),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }

  if inner.path.is_ident("input") {
    return attribute::block(
      inner,
      input,
      "`input(…)` is declared more than once on a field — one block per position",
      errors,
      |position, errors| field_operand_position(&position, operands, errors),
    );
  }

  if inner.path.is_ident("output") {
    errors.push(attribute::unknown(
      inner,
      &format!(
        "`output(<db>(from = \"…\"))` is a field's own row-to-wire crossing, and \
         {AN_OUTPUT_FACE_ARRIVES_WITH_THE_ACCESSOR}"
      ),
      &[],
    ));
    return Ok(());
  }

  errors.push(misplaced_database(inner).unwrap_or_else(|| {
    attribute::unknown(
      inner,
      "unknown entry in `graphql(…)` on a field — it takes `type = \"…\"`, \
       `input(comparison(<db>(try_into = \"…\")))`, and one of `computed` or `try_computed`",
      &["type", "input", "computed", "try_computed"],
    )
  }));
  Ok(())
}

/// `input(…)` on a FIELD — the same position axis the interface's own block has, over the entry
/// that is the field's rather than the declaration's.
fn field_operand_position(
  position: &syn::meta::ParseNestedMeta<'_>,
  operands: &mut Vec<Operand>,
  errors: &mut Errors,
) -> syn::Result<()> {
  if position.path.is_ident("comparison") {
    return attribute::options(position, |database| {
      field_operand(&database, operands, errors)
    });
  }
  errors.push(misplaced_database(position).unwrap_or_else(|| {
    attribute::unknown(
      position,
      "unknown entry in `graphql(input(…))` on a field — the position axis admits `comparison(…)` \
       alone, a filter's operands being the only wire values that cross into storage",
      &["comparison"],
    )
  }));
  Ok(())
}

/// ONE database's operand converter for one field: `try_into = "…"`.
///
/// The FUNCTION rather than a type, and it is the field's rather than the declaration's, because
/// which function carries a value across is a fact about that column: a `u64` pinned at a
/// big-endian blob has no `TryFrom` between the two, and the declaration is what supplies the hop.
/// The REFUSAL the whole crossing answers with is the interface's, one cell for every column, which
/// is what `graphql(input(comparison(<db>(try_into(error = "…")))))` types.
fn field_operand(
  database: &syn::meta::ParseNestedMeta<'_>,
  operands: &mut Vec<Operand>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let Some(kind) = database_kind(&database.path) else {
    errors.push(attribute::unknown(
      database,
      &format!(
        "unknown entry in `graphql(input(comparison(…)))` on a field — every entry names a \
         DATABASE, an operand crossing into one being per database: {list}",
        list = shipped()
      ),
      &DatabaseKind::ALL.map(DatabaseKind::as_str),
    ));
    return Ok(());
  };
  if operands.iter().any(|operand| operand.kind == kind) {
    errors.push(syn::Error::new_spanned(
      &database.path,
      format!(
        "`{kind}` is declared more than once for this field's operand — one database, one crossing",
        kind = kind.as_str()
      ),
    ));
    attribute::skip_entry(database);
    return Ok(());
  }
  let mut seen = None;
  attribute::options(database, |leg| {
    if leg.path.is_ident(ADMITTED_LEG) {
      set_once(
        &mut seen,
        leg.path.clone(),
        &leg.path,
        "`try_into` is declared more than once for this database — one leg, one function",
        errors,
      );
      match value::parse_literal::<syn::Path>(&leg, OPERAND_CONVERT) {
        Ok(convert) => operands.push(Operand { kind, convert }),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if let Some(word) = REFUSED_LEGS.iter().find(|word| leg.path.is_ident(word)) {
      errors.push(attribute::unknown(
        &leg,
        &format!(
          "`{word} = \"…\"` is not the leg an operand takes — a filter's values LEAVE the wire for \
           the types a database stores, which is `{ADMITTED_LEG}`"
        ),
        &[],
      ));
      return Ok(());
    }
    errors.push(attribute::unknown(
      &leg,
      &format!(
        "unknown entry in `input(comparison(<db>(…)))` on a field — the database block takes \
         `{ADMITTED_LEG} = \"…\"`, the function this field's operands enter storage through"
      ),
      &[ADMITTED_LEG],
    ));
    Ok(())
  })
}

/// The refusal a field's operand converter gets when it is not a path.
const OPERAND_CONVERT: &str = "`try_into` must be a path to the function this field's operands \
                               enter storage through, in a string literal";

/// The refusal a wire form gets when it is not a type.
const WIRE_TYPE: &str = "`type` must be the form this field takes on the wire, in a string literal";

/// The names this expansion puts in the DECLARING SCOPE, and the two ways they can clash.
///
/// Asked of the MODEL rather than rebuilt here, for the reason the union's own check asks its own:
/// a suffix convention spelled on this side would be a second copy of what the emitter writes.
///
/// The enum's own name is added HERE rather than by the model, because it is a fact about the scope
/// the expansion lands in rather than about the emission — the same split
/// [`InterfaceModel::emitted_types`](ingraph_codegen::interface::InterfaceModel::emitted_types)
/// draws.
fn emitted_names(model: &InterfaceModel, errors: &mut Errors) {
  // What each name IS, in the order the emission declares them — the enum first, because it is
  // already in the scope the expansion lands in. Each emitted name arrives WITH its role rather than
  // beside a parallel list of them: a list zipped against the types would silently stop checking the
  // day the emission grew one, which is exactly what the projection did to it.
  let mut seen: Vec<(syn::Ident, String)> =
    vec![(model.name.clone(), "the interface's own name".to_owned())];
  for declared in model.emitted_types() {
    if let Some((_, held)) = seen.iter().find(|(already, _)| *already == declared.name) {
      let at = model
        .error
        .as_ref()
        .map_or_else(|| model.name.span(), syn::Ident::span);
      errors.push(syn::Error::new(
        at,
        format!(
          "`{name}` would be {role}, and it is already {held} — an interface lands its refusal, its \
           two contract traits and its own projection in the declaring scope, so each needs a name \
           of its own",
          name = declared.name,
          role = declared.role,
        ),
      ));
      continue;
    }
    seen.push((declared.name, declared.role.to_string()));
  }
}