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
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
//! An AGGREGATE declaration's acceptance: the upstream it folds, what it groups by, what it
//! measures, and every family it does not claim.
//!
//! ```text
//! #[ingraph::aggregate(
//!   upstream(node = "demux::Track"),
//!   group(codec = "codec"),
//!   measure(count = counting, bytes(fold = summing, from = "size")),
//!   poll(recount, every = "10m", light),
//!   sqlite,
//! )]
//! pub struct CodecCensus {
//!   #[ingraph(group)]   codec: Codec,
//!   #[ingraph(measure)] count: ingraph::Count,
//!   #[ingraph(measure)] bytes: u64,
//! }
//! ```
//!
//! # A MEASURE ENTRY'S FULL FORM IS THE CITIZEN, and the sugar keeps only what omits nothing
//!
//! `<field>(fold = <fold>, from = "<upstream column>")` names every property one measure column has,
//! and it is where every further property will land. `<field> = <fold>` is the same entry with its
//! one required property written inline — legal exactly where nothing is being left out, which is
//! where the fold reads no column: `counting` answers how many rows a group holds and looks at none
//! of them, so `count = counting` is whole.
//!
//! A fold that DOES read a column has no seat in the short spelling, so `bytes = summing` is refused
//! by name pointing at the full form. That is the `delegate(…)` seat's own tooth one grammar over,
//! where a bare signature beside a named property earns the full spelling rather than a guess — and
//! it is why the column is not defaulted to the measure's own field name: a name this declaration
//! chose and a column the upstream owns are two facts, and a grammar that assumed they agree would
//! fold the wrong column, silently, wherever they did not. `group(…)` writes both spellings out for
//! the same reason even when they match.
//!
//! # THE GRAMMAR NAMES THE SENTENCE `SELECT count(*) FROM tracks GROUP BY codec`
//!
//! `upstream(…)` is the `FROM`, `group(…)` is the `GROUP BY`, `measure(…)` is the aggregate
//! functions — and beside them ride the two words SQL has no room for: the CLOCK that says when the
//! answer is recomputed, and the STORE it lands in.
//!
//! # `upstream(…)` IS THE EDGE ALONE HERE, which is where it differs from a derived index's
//!
//! A derived index holds one document per upstream MESSAGE and every field of that document is read
//! out of the message, so its `upstream(…)` carries the projection too and the projection is TOTAL.
//! An aggregate's row is about a GROUP: its group columns are read out of the upstream's rows and
//! its measure columns are FOLDED into being, so a projection covering every field would be
//! claiming a totality this kind does not have. The projection is therefore `group(…)`, which is
//! also the block that says which columns the key is minted from — one word for one fact — and a
//! projection entry written inside `upstream(…)` is refused pointing at it.
//!
//! # ONE WORD, TWO POSITIONS — and the block and the marker are cross-checked
//!
//! `group` and `measure` are each written twice: at the head, where the entry says WHERE a column
//! comes from or HOW it is folded, and on the field, where the marker says WHAT THE FIELD IS. That
//! is the house's own shape — `builder`, `key`, `lineage` and `record` all sit at two grains, and
//! `searchable` is a full-text field's marker and an entry inside a `vector`'s `knn(…)` — and it is
//! licensed by the split law: a word may be shared where it means the same thing at both grains.
//!
//! The redundancy is REAL and it is bought rather than tolerated. A role belongs on the thing that
//! has it, so the field wears it; the entry's value is a fact neither the field nor the type can
//! carry, so the head holds that. The two halves are then checked AGAINST each other, and a
//! declaration whose head and field disagree is refused by name rather than resolved by precedence
//! — which is the whole return on writing the word twice.
//!
//! # THREE WORDS ARE CARRIED UNREAD, and the journal is why
//!
//! `poll(…)`, the store words and `graphql(…)` are the RECORD grammar's. The emission mints the
//! `(group…, measure…)` row shape and hands it to the record pass — `#[ingraph::journal]`'s pattern
//! verbatim — so reading a database block or a clock's entries HERE would be a second authority for
//! one vocabulary, and two authorities for one vocabulary is how the two of them drift. What this
//! grammar knows is only which WORDS start one, which it needs anyway to refuse a declaration that
//! names no clock.
//!
//! # NOTHING HERE RESOLVES THE UPSTREAM, and that is the mechanism rather than a limitation
//!
//! Two macro expansions cannot see each other, so what `demux::Track` even IS is unknowable at this
//! point. Every claim the declaration makes about it is emitted for rustc to check, at the span of
//! the string the author wrote.

use ingraph_codegen::{
  aggregate::{AggregateModel, GROUP, Grouped, MEASURE, Measure, Measured, Mounted, Owed},
  model::{DatabaseKind, NodeKind, Projection, borrowed_key},
  prefix::EmissionPrefix,
};

use crate::{
  alias,
  attribute::{self, named, set_once},
  column,
  errors::Errors,
  parse::{database_kind, owns_one_storage, shipped},
  suggest, value,
};

#[cfg(test)]
mod tests;

/// The kind every sentence in this pass is written about.
///
/// A const rather than a parameter, unlike [`crate::index`]'s pass: that one serves three kinds
/// whose grammar is identical, and this one serves the single kind that has this grammar.
const KIND: NodeKind = NodeKind::Aggregate;

/// `upstream(…)` — the edge, and this grammar's only quoted node path.
const UPSTREAM: &str = "upstream";

/// `node = "…"`, the one entry `upstream(…)` takes here.
const NODE: &str = "node";

/// `fold = <fold>` — the measure entry's FULL FORM property that names what folds the group.
const FOLD: &str = "fold";

/// `from = "<upstream column>"` — the property that names the column the fold is handed.
///
/// The GROUP block's own law at the other role: a column of the upstream is named in a quoted
/// string, because it is the UPSTREAM's spelling rather than this declaration's. `group(…)` writes
/// it as the entry's whole value; a measure entry has a second property beside it, so here it is a
/// word.
const FROM: &str = "from";

/// `poll(…)` — the trigger word, carried verbatim and MANDATORY.
const POLL: &str = "poll";

/// `graphql(…)` — the wire face, carried verbatim and optional.
const GRAPHQL: &str = "graphql";

/// `table = "…"` — a store word's common entry, carried with the store words.
const TABLE: &str = "table";

/// `rename = "…"` — the other one.
const RENAME: &str = "rename";

/// Validate a decorated declaration into the model the emission 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<AggregateModel> {
  let aggregate = &input.ident;
  let mut errors = Errors::default();
  crate::host::refuse_a_moved_option_block(&input.attrs, &mut errors);
  let head = options(arguments, &mut errors);
  concrete(&input.generics, &mut errors);

  let fields = match named_fields(input) {
    Ok(fields) => fields,
    Err(terminal) => return Err(errors.seal(terminal)),
  };
  if fields.named.is_empty() {
    errors.push(syn::Error::new_spanned(aggregate, NO_FIELDS));
  }

  // The walk yields TWO answers per field — the type the model carries and the ROLE its marker
  // declared — and the pair is what the head's two blocks are checked against below. Kept in step
  // by construction, one push per field.
  let mut columns: Vec<Field> = Vec::new();
  for field in &fields.named {
    let Some(name) = field.ident.clone() else {
      continue;
    };
    // THE ONE-STORAGE LAW, caught by the derive rather than by the linker's namespace. Two storage
    // macros on one declaration are ordinarily undetectable, and are refused by the marker each
    // mints colliding in the declaring scope — but where a DERIVED INDEX ran first the collision
    // arrives earlier, because it rewrote the item and this pass is handed a declaration that
    // already carries the injected key.
    if name == borrowed_key(&EmissionPrefix::default()) {
      errors.push(syn::Error::new_spanned(
        &name,
        format!(
          "this declaration already carries a storage macro's injected key, so a second storage \
           macro is being asked to fold a row that has one. {}",
          owns_one_storage(KIND),
        ),
      ));
      continue;
    }
    // An aggregate declares no database blocks of its own here — the store words are carried to the
    // record pass whole — so the fence it is held to is the framework's own namespace and nothing
    // else, which is `Fence::default`'s stated case.
    column::refuse_framework_namespace(&alias::Fence::default(), &name, &mut errors);
    // THE ONE METHOD THIS KIND'S EMISSION MINTS, held against the accessor family the record pass
    // mints beside it. Reported rather than skipped, so a declaration wrong here and at its head
    // hears about both.
    if name == FOLD {
      errors.push(syn::Error::new_spanned(&name, mints_a_fold()));
    }
    let (projection, role, role_spoken) = markers(&field.attrs, &name, &mut errors);
    columns.push(Field {
      role,
      role_spoken,
      projection,
      ty: field.ty.clone(),
      name,
    });
  }

  // THE TWO BAILS, and both are about the UPSTREAM: with no upstream there is nothing for the group
  // projection to be read out of, and therefore no model to carry the columns that were checked on
  // the way here. Every field-level and block-level refusal above has already been recorded, so a
  // declaration that is wrong in both halves reports both.
  //
  // Both are ABSENCE checks, so both ride `head.whole` — see [`Head::whole`] for why a head the
  // reader could not finish makes every absence in it unclaimable.
  let Some(at) = head.upstream_at else {
    return Err(match head.whole {
      true => errors.seal(syn::Error::new_spanned(aggregate, NO_UPSTREAM)),
      false => errors.stopped(syn::Error::new_spanned(aggregate, UNREADABLE_HEAD)),
    });
  };
  let groups = grouped(
    &head.groups,
    head.group_at.as_ref(),
    head.whole,
    &columns,
    aggregate,
    &mut errors,
  );
  let measures = measured(
    &head.measures,
    head.measure_at.as_ref(),
    head.whole,
    &columns,
    aggregate,
    &mut errors,
  );
  unmatched(
    &columns,
    &head.group_spoken,
    &head.measure_spoken,
    head.whole,
    &mut errors,
  );
  if head.whole && !head.polled {
    errors.push(syn::Error::new_spanned(aggregate, NO_TRIGGER));
  }
  let Some(node) = head.node else {
    return Err(match head.whole {
      true => errors.seal(syn::Error::new_spanned(&at, UPSTREAM_TAKES_A_NODE)),
      false => errors.stopped(syn::Error::new_spanned(aggregate, UNREADABLE_HEAD)),
    });
  };

  errors.into_result(AggregateModel {
    aggregate: aggregate.clone(),
    vis: input.vis.clone(),
    krate: head.krate.unwrap_or_else(|| syn::parse_quote!(::ingraph)),
    krate_spelled: head.krate_spelled,
    upstream: node,
    groups,
    measures,
    triggers: head.triggers,
    stores: head.stores,
    graphql: head.graphql,
  })
}

/// MOUNT an accepted declaration: mint its key, hand its row to the record pass, and carry both
/// halves to the emission.
///
/// # It is `#[ingraph::journal]`'s pattern, and the ONE thing minted here is the KEY
///
/// A journal mints the whole row and refuses an author who wrote a field; an aggregate's author
/// wrote every column, so what this mints is the one part of the shape their two role words DECIDE
/// rather than write. `key = lineage ⊕ id` is this framework's only key spelling, so the group
/// projection lands as `lineage(fields(…))` over every group column but the last and `#[ingraph(id)]`
/// on that last one — a one-column group getting the id alone and no lineage, which is what a ROOT
/// record is. The result is a key whose columns are the group projection, in the order it was
/// written.
///
/// Everything else is CARRIED: the store words, `poll(…)` and `graphql(…)` reach the record grammar
/// exactly as the author wrote them, because that grammar owns every word inside one and two
/// authorities for one vocabulary is how the two of them drift. Their teeth arrive here, at the pass
/// that spends them — a storeless aggregate earns the record's own *a thing that holds rows names
/// where they land*, and a `poll(…)` entry that named no body word earns the poll grammar's.
///
/// # Errors
/// Whatever the record pass refused the mounted declaration with, at the tokens the author wrote:
/// the mount rewrites markers and adds a key, and it invents no token that could carry a caret of
/// its own.
pub(crate) fn mount(input: &syn::DeriveInput, aggregate: AggregateModel) -> syn::Result<Mounted> {
  let host = mounted(input, &aggregate);
  let record = crate::parse::parse(&host, &[record_options(&aggregate)], KIND)?;
  Ok(Mounted { record, aggregate })
}

/// The declaration the RECORD PASS reads: the author's item with its role markers replaced by the
/// row markers the mount decides.
///
/// EVERYTHING ELSE OF THE AUTHOR'S SURVIVES — the name, the visibility, their own derives, their
/// `cfg`s, their doc comments and every attribute this grammar does not own — because the item is
/// cloned and only its `#[ingraph(…)]`s are rewritten. What comes off is the two ROLE words, which
/// are this grammar's and mean nothing to the record's; what goes on is `id` at the key column and
/// the field's own PROJECTION, re-minted from the model rather than left in place so that the row
/// shape has one authority.
///
/// The item's own `#[ingraph(…)]` comes off for [`crate::journal`]'s stated reason: it has already
/// been reported by [`crate::host::refuse_a_moved_option_block`], and leaving it would have the
/// record pass reading the same host and reporting it twice.
fn mounted(input: &syn::DeriveInput, model: &AggregateModel) -> syn::DeriveInput {
  let key = model.groups.last().map(|grouped| &grouped.field);
  let mut host = input.clone();
  host.attrs.retain(|attr| !attr.path().is_ident("ingraph"));
  let syn::Data::Struct(data) = &mut host.data else {
    return host;
  };
  for field in &mut data.fields {
    field.attrs.retain(|attr| !attr.path().is_ident("ingraph"));
    let Some(name) = field.ident.clone() else {
      continue;
    };
    let mut words: Vec<syn::Ident> = Vec::new();
    if key == Some(&name) {
      words.push(syn::Ident::new("id", name.span()));
    }
    if let Some(word) = projection_word(model, &name) {
      words.push(syn::Ident::new(word, name.span()));
    }
    if !words.is_empty() {
      field.attrs.push(syn::parse_quote!(#[ingraph(#(#words),*)]));
    }
  }
  host
}

/// The projection word a column carries, or [`None`] where it takes the plain borrow.
///
/// Read off the MODEL rather than off the attribute that is being replaced, so the word that
/// reaches the record pass and the word this grammar recorded cannot come apart.
fn projection_word(model: &AggregateModel, field: &syn::Ident) -> Option<&'static str> {
  let projection = model
    .groups
    .iter()
    .map(|grouped| (&grouped.field, grouped.projection))
    .chain(
      model
        .measures
        .iter()
        .map(|measured| (&measured.field, measured.projection)),
    )
    .find_map(|(name, projection)| (name == field).then_some(projection))?;
  match projection {
    Projection::Borrowed => None,
    Projection::Copied => Some("copy"),
    Projection::Repeated => Some("repeated"),
    Projection::Optional => Some("optional"),
  }
}

/// The record options the mounted declaration is parsed under.
///
/// The minted `lineage(…)` is the whole of what this pass decides — see [`mount`] — and the four
/// carried words are handed on unchanged, in the order a reader of the declaration would meet them.
fn record_options(model: &AggregateModel) -> syn::Attribute {
  let mut written: Vec<proc_macro2::TokenStream> = Vec::new();
  // ONE group column is a ROOT record: its key is the id alone, and a `lineage(…)` naming no step
  // is refused by the record grammar as the empty path it would be.
  if let Some((_, steps)) = model
    .groups
    .split_last()
    .filter(|(_, steps)| !steps.is_empty())
  {
    let steps = steps.iter().map(|grouped| &grouped.field);
    written.push(quote::quote!(lineage(fields(#(#steps),*))));
  }
  if let Some(spelled) = &model.krate_spelled {
    written.push(quote::quote!(crate = #spelled));
  }
  for carried in [&model.triggers, &model.stores] {
    if !carried.is_empty() {
      written.push(carried.clone());
    }
  }
  if let Some(graphql) = &model.graphql {
    written.push(graphql.clone());
  }
  syn::parse_quote!(#[ingraph(#(#written),*)])
}

/// The refusal one of THIS kind's two role words earns on a declaration of another kind.
///
/// The wrong-kind COURTESY rather than an unknown entry, which is the rule every named refusal in
/// this crate is written under: an author who wrote `measure` on a record had a coherent idea, and
/// what they need told is which kind carries it — not that the word does not exist.
///
/// It lives beside the words rather than at each of the three grammars that spend it, so that one
/// vocabulary keeps one home and three copies of a sentence cannot become three sentences.
///
/// # It does NOT end in the one-storage law, and the omission is measured
///
/// Every other cross-kind refusal in this crate closes with [`owns_one_storage`], whose second
/// clause promises that *the storage node subscribes to this node and shares its key*. That is
/// exactly what an aggregate does NOT do — it mints its own key from the group columns, which is the
/// one answer this kind departs from a derived index on — so borrowing the law here would end a
/// true sentence with a false clause. The redirect is written out instead, and it says the thing the
/// law would have got wrong.
///
/// `written` is which of the word's two positions it was written at. The two differ in one clause
/// and in nothing else, so they are one sentence with a hole in it rather than two that could drift.
/// Neither names the FIELD: the refusal is spanned at the word, whose caret is already on the field
/// that wrote it, and the field's name is not threaded through the record grammar's marker reader —
/// which serves the standalone derives too, where there is no field to name.
pub(crate) fn wrong_kind(word: &str, kind: NodeKind, written: Written) -> String {
  let what = if word == GROUP {
    "which column a folded row is keyed by"
  } else {
    "how a group's rows are folded into one column"
  };
  let position = match written {
    Written::AtTheHead => format!("`{word}(…)` says"),
    Written::OnAField => format!("`{word}` marks this column as the one that says"),
  };
  format!(
    "{position} {what}, and {article} {noun} folds nothing — it holds whatever it is given, row for \
     row, so it has no group for a column to be about. The word is the `aggregate` kind's own, and \
     an aggregate is its OWN node: declare it with `#[ingraph::aggregate(…)]`, on a type whose \
     `upstream(…)` names this {noun}. Its rows are the folded ones and its key is the group columns \
     it projects, so it borrows nothing from this declaration's",
    article = kind.article(),
    noun = kind.noun(),
  )
}

/// WHERE one of the two role words was written, for [`wrong_kind`]'s one differing clause.
#[derive(Clone, Copy)]
pub(crate) enum Written {
  /// In the declaration's own attribute, where the word is a block.
  AtTheHead,
  /// On a field, where it is a bare marker.
  OnAField,
}

/// ONE FIELD, as the walk read it.
struct Field {
  /// The field's own name.
  name: syn::Ident,
  /// Its declared type.
  ty: syn::Type,
  /// How an accessor hands the column back, from the three projection words.
  projection: ingraph_codegen::prelude::Projection,
  /// The role its marker declared, with the token that declared it — or [`None`] where it wore
  /// none, which is refused after the walk and carried anyway so the head's entries still get their
  /// own answers.
  role: Option<(Role, syn::Path)>,
  /// Whether a ROLE WORD was written on this field at all, however badly.
  ///
  /// Beside [`role`](Self::role) rather than read off it, so that one mistake costs one error: a
  /// `group(rename = "…")` earns the sentence about the marker's shape and must not ALSO earn the
  /// no-role sentence, which would tell an author who did declare a role that they did not. The
  /// poll grammar's own device, one grammar over.
  role_spoken: bool,
}

/// WHICH of the two roles a field wears.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Role {
  /// `#[ingraph(group)]` — a column the row is keyed by.
  Group,
  /// `#[ingraph(measure)]` — a column the fold fills.
  Measure,
}

impl Role {
  /// The marker word this role is written with, which is also its head block's word.
  const fn word(self) -> &'static str {
    match self {
      Self::Group => GROUP,
      Self::Measure => MEASURE,
    }
  }

  /// What a column in this role IS, for the sentences that name one.
  const fn what(self) -> &'static str {
    match self {
      Self::Group => "a column the folded row is keyed by",
      Self::Measure => "a column the fold fills",
    }
  }
}

/// EVERYTHING THE HEAD SAID, in one value.
struct Head {
  /// `crate = "…"` as a path, or [`None`] for the default.
  krate: Option<syn::Path>,
  /// The same as the literal it was written as, for the record pass to be handed back.
  krate_spelled: Option<syn::LitStr>,
  /// `upstream(node = "…")`'s value.
  node: Option<syn::Path>,
  /// The `upstream` word's own token, where the declaration wrote the block at all.
  upstream_at: Option<syn::Path>,
  /// The `group(…)` entries in written order.
  groups: Vec<Entry<syn::Ident>>,
  /// The `group` word's own token, for a refusal about the block rather than an entry in it.
  group_at: Option<syn::Path>,
  /// Every field `group(…)` named, however badly its entry was written.
  ///
  /// Beside [`groups`](Self::groups) for the role marker's own reason, one grain out: an entry whose
  /// VALUE was refused earns that refusal and must not ALSO earn the marked-field-with-no-entry
  /// sentence, which would tell an author who did write an entry that they did not.
  group_spoken: Vec<syn::Ident>,
  /// The `measure(…)` entries in written order.
  measures: Vec<Entry<Folded>>,
  /// The `measure` word's own token.
  measure_at: Option<syn::Path>,
  /// Every field `measure(…)` named, however badly.
  measure_spoken: Vec<syn::Ident>,
  /// Every `poll(…)` entry as written, comma-joined.
  triggers: proc_macro2::TokenStream,
  /// Whether a `poll(…)` was written AT ALL, however badly.
  ///
  /// Beside [`triggers`](Self::triggers) rather than read off it, so that one mistake costs one
  /// error: a `poll` written as a bare word carries no tokens to join, and telling its author they
  /// named no clock would be telling them the opposite of what they did.
  polled: bool,
  /// The store words and their two common entries as written, comma-joined.
  stores: proc_macro2::TokenStream,
  /// `graphql(…)` as written.
  graphql: Option<proc_macro2::TokenStream>,
  /// Whether the head was read TO THE END.
  ///
  /// The `spoken` devices' law at the grain of the whole attribute. A parse failure ENDS the walk at
  /// the token that broke it, so every word after that token is UNREAD — and an absence check over
  /// unread tokens is a claim this pass cannot make. A malformed `measure(…)` entry followed by a
  /// `poll(…)` is the case that measured it: the walk stopped inside the block, the clock was never
  /// seen, and the declaration earned a SECOND refusal saying it named no clock when it named one.
  ///
  /// So `false` suppresses every refusal whose whole content is *this word is missing* —
  /// [`NO_TRIGGER`], the zero-group and zero-measure sentences, both upstream bails, and the
  /// marked-field-with-no-entry half of [`unmatched`]. Everything the reader DID see still refuses:
  /// the field markers, the entries that parsed, and the failure itself, which [`attribute::walk`]
  /// has already recorded.
  whole: bool,
}

impl Default for Head {
  /// A head nothing has been read into yet is WHOLE, and that is the only field with a default
  /// other than its type's.
  ///
  /// The flag answers *did the reader finish*, so the walk that has not started has nothing to
  /// suppress; `false` would make every declaration whose attribute is absent entirely — which is a
  /// legal way to write nothing at all — silently skip the refusals it should earn.
  fn default() -> Self {
    Self {
      krate: None,
      krate_spelled: None,
      node: None,
      upstream_at: None,
      groups: Vec::new(),
      group_at: None,
      group_spoken: Vec::new(),
      measures: Vec::new(),
      measure_at: None,
      measure_spoken: Vec::new(),
      triggers: proc_macro2::TokenStream::new(),
      polled: false,
      stores: proc_macro2::TokenStream::new(),
      graphql: None,
      whole: true,
    }
  }
}

/// ONE head entry that names a field of this declaration, and whatever that block's value is.
struct Entry<T> {
  /// The entry's own name: the field of this declaration it is about. No field is known to exist
  /// yet, which is why this is checked against the walk rather than during it.
  field: syn::Ident,
  /// What the entry said about that field — where a group column is read from, or what folds a
  /// measure.
  value: T,
}

/// WHAT ONE `measure(…)` ENTRY SAID — the fold, and the upstream column it is handed.
///
/// Two facts rather than one, which is the whole of what the group form bought: the fold is the
/// value the sugar spends its one position on, and the column is the property that had nowhere to go
/// before the entry had a block.
struct Folded {
  /// What folds the group's rows into this column.
  by: Measure,
  /// The upstream column the fold reads, where the entry named one — [`None`] being a fold over the
  /// group's ROWS rather than a gap. See [`Measured::from`].
  from: Option<syn::Ident>,
}

/// Walk the declaration-level attribute.
fn options(attrs: &[syn::Attribute], errors: &mut Errors) -> Head {
  let mut head = Head::default();
  let mut upstream_seen: Option<syn::Path> = None;
  let mut group_seen: Option<syn::Path> = None;
  let mut measure_seen: Option<syn::Path> = None;
  let mut graphql_seen: Option<syn::Path> = None;

  head.whole = 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. BOTH forms are kept for the journal's stated
    // reason: one authority for the path, and no round trip through a rendered path that could
    // differ from the one that was written.
    if meta.path.is_ident("crate") {
      match value::literal(&meta, CRATE_PATH)
        .and_then(|spelled| Ok((spelled.parse::<syn::Path>()?, spelled)))
      {
        Ok((path, spelled)) => {
          set_once(&mut head.krate, path, &meta.path, CRATE_ONCE, errors);
          head.krate_spelled.get_or_insert(spelled);
        }
        Err(e) => errors.push(syn::Error::new(e.span(), CRATE_PATH)),
      }
      return Ok(());
    }

    if meta.path.is_ident(UPSTREAM) {
      let at = meta.path.clone();
      head.upstream_at.get_or_insert_with(|| at.clone());
      if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
        errors.push(named(&meta, UPSTREAM_TAKES_A_NODE.to_owned()));
        return Ok(());
      }
      // A SECOND block is refused and DROPPED rather than walked: the first is what the rest of the
      // pass reads, which is `set_once`'s own law, and walking this one would earn the repeat
      // sentence a second `node` refusal beside it — one mistake, two errors.
      if upstream_seen.is_some() {
        errors.push(named(&meta, UPSTREAM_ONCE.to_owned()));
        return Ok(());
      }
      upstream_seen = Some(at);
      return meta.parse_nested_meta(|inner| upstream_entry(&inner, &mut head.node, errors));
    }

    if meta.path.is_ident(GROUP) {
      let at = meta.path.clone();
      head.group_at.get_or_insert_with(|| at.clone());
      if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
        // The block was written and holds nothing, which is the ZERO-GROUP refusal at the token
        // that earned it. A declaration that wrote no block at all earns the same sentence at its
        // own ident, in `grouped` — one rule, one wording, two carets.
        errors.push(named(&meta, no_group()));
        return Ok(());
      }
      // Dropped rather than walked, for the second `upstream(…)`'s reason: the first block is the
      // settled one, and walking this one would earn its entries a duplicate refusal apiece beside
      // the repeat sentence.
      if group_seen.is_some() {
        errors.push(named(&meta, GROUP_ONCE.to_owned()));
        return Ok(());
      }
      group_seen = Some(at);
      return meta.parse_nested_meta(|inner| {
        group_entry(&inner, &mut head.groups, &mut head.group_spoken, errors)
      });
    }

    if meta.path.is_ident(MEASURE) {
      let at = meta.path.clone();
      head.measure_at.get_or_insert_with(|| at.clone());
      if !attribute::has_block(&meta) || attribute::empty_group(&meta) {
        errors.push(named(&meta, no_measure()));
        return Ok(());
      }
      if measure_seen.is_some() {
        errors.push(named(&meta, MEASURE_ONCE.to_owned()));
        return Ok(());
      }
      measure_seen = Some(at);
      return meta.parse_nested_meta(|inner| {
        measure_entry(&inner, &mut head.measures, &mut head.measure_spoken, errors)
      });
    }

    // THE THREE CARRIED WORDS. Nothing here reads inside one — see the module note for why a second
    // authority for the record grammar's vocabulary is the thing being avoided.
    if meta.path.is_ident(POLL) {
      head.polled = true;
      attribute::carry(&meta, &mut head.triggers);
      return Ok(());
    }
    if meta.path.is_ident(GRAPHQL) {
      let mut carried = proc_macro2::TokenStream::new();
      attribute::carry(&meta, &mut carried);
      set_once(
        &mut graphql_seen,
        meta.path.clone(),
        &meta.path,
        GRAPHQL_ONCE,
        errors,
      );
      head.graphql.get_or_insert(carried);
      return Ok(());
    }
    if database_kind(&meta.path).is_some()
      || meta.path.is_ident(TABLE)
      || meta.path.is_ident(RENAME)
    {
      attribute::carry(&meta, &mut head.stores);
      return Ok(());
    }

    // THE WRAPPER, refused by name — the record's own sentence, one grammar over. An aggregate
    // holds rows, so the mistake is the layer rather than the rows.
    if meta.path.is_ident("persist") {
      errors.push(named(&meta, PERSIST_UNWRAPPED.to_owned()));
      return Ok(());
    }

    // THE WORDS THIS KIND DECIDES FOR ITSELF, each answered with what it would have decided. Refused
    // BY NAME rather than as unknown entries, for the reason every named refusal in this crate
    // exists: an author who writes one has a concrete idea, and the useful answer is where that idea
    // is already recorded.
    for (word, instead) in DECIDED {
      if meta.path.is_ident(word) {
        errors.push(named(
          &meta,
          format!(
            "`{word}` decides something an aggregate's own grammar has already decided: {instead}"
          ),
        ));
        return Ok(());
      }
    }

    // THE THREE OTHER STORAGES, refused for the one-storage law's reason exactly as a record
    // refuses them.
    for other in [NodeKind::Fulltext, NodeKind::Vector, NodeKind::Blob] {
      if meta.path.is_ident(other.as_str()) {
        errors.push(named(
          &meta,
          format!(
            "an aggregate owns no {held} — one is its OWN node, declared with the `{other}` macro \
             over the same upstream. {law}",
            held = other.noun(),
            other = other.as_str(),
            law = owns_one_storage(KIND),
          ),
        ));
        return Ok(());
      }
    }

    errors.push(attribute::unknown(
      &meta,
      &unknown_head(),
      &head_vocabulary(),
    ));
    Ok(())
  });

  head
}

/// One entry inside `upstream(…)`: the node, and nothing else.
fn upstream_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  node: &mut Option<syn::Path>,
  errors: &mut Errors,
) -> syn::Result<()> {
  if inner.path.is_ident(NODE) {
    match value::parse_literal::<syn::Path>(inner, NODE_IS_A_PATH) {
      Ok(path) => set_once(node, path, &inner.path, NODE_ONCE, errors),
      Err(e) => errors.push(e),
    }
    return Ok(());
  }
  // A PROJECTION, refused by name and sent to the block that takes one. The derived indexes read
  // exactly this shape inside `upstream(…)`, so an author arriving from one has a coherent idea
  // about the wrong block rather than an unknown word.
  errors.push(named(inner, projection_belongs_to_group(&inner.path)));
  Ok(())
}

/// One entry inside `group(…)`: a field of this declaration, and the upstream field it is read out
/// of.
fn group_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  entries: &mut Vec<Entry<syn::Ident>>,
  spoken: &mut Vec<syn::Ident>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let Some(field) = inner.path.get_ident().cloned() else {
    // An entry's name is one of THIS struct's field names, which is not a vocabulary — so there is
    // nothing here for a near miss to be near.
    errors.push(attribute::unknown(inner, ENTRY_NAMES_A_FIELD, &[]));
    return Ok(());
  };
  spoken.push(field.clone());
  let shape = group_entry_shape(&field);
  let from = match value::literal(inner, &shape).and_then(|spelled| {
    value::named_field(&spelled, &shape).map_err(|e| syn::Error::new(e.span(), shape.clone()))
  }) {
    Ok(from) => from,
    Err(e) => {
      errors.push(e);
      return Ok(());
    }
  };
  if entries.iter().any(|entry| entry.field == field) {
    errors.push(syn::Error::new_spanned(&inner.path, once(GROUP, &field)));
    return Ok(());
  }
  entries.push(Entry { field, value: from });
  Ok(())
}

/// One entry inside `measure(…)`: a field of this declaration, what folds a group into it, and the
/// upstream column that fold reads.
///
/// # TWO SPELLINGS, told apart by the ONE token that follows the field's name
///
/// A `(` opens the FULL FORM and an `=` opens the sugar, and nothing else can be either — so the
/// fork is total rather than a guess, exactly as the `delegate(…)` seat's is one grammar over. The
/// two are per ENTRY rather than per block: both spellings name the field first, so a block may hold
/// one of each and a declaration with a counted column and a summed one writes each in the shortest
/// spelling that omits nothing.
///
/// # MINT BARE, REFER QUOTED, read at one more position
///
/// A BARE word is one of the framework's own shipped folds; a QUOTED path is a fold the declaring
/// crate wrote. The two are read apart by looking at the value rather than by asking the author to
/// spell the distinction twice — an author choosing between them is choosing a value, not writing a
/// different entry. That axis is the FOLD's, so it reads the same in both spellings, by the same
/// reader.
///
/// # Errors
/// Whatever the full form's own walk hit, which is the one thing this reader cannot step over.
fn measure_entry(
  inner: &syn::meta::ParseNestedMeta<'_>,
  entries: &mut Vec<Entry<Folded>>,
  spoken: &mut Vec<syn::Ident>,
  errors: &mut Errors,
) -> syn::Result<()> {
  let Some(field) = inner.path.get_ident().cloned() else {
    errors.push(attribute::unknown(inner, ENTRY_NAMES_A_FIELD, &[]));
    return Ok(());
  };
  spoken.push(field.clone());
  let read = match attribute::has_block(inner) {
    true => full_form(inner, &field, errors)?,
    false => sugar(inner, &field, errors),
  };
  let Some(folded) = read else {
    return Ok(());
  };
  if entries.iter().any(|entry| entry.field == field) {
    errors.push(syn::Error::new_spanned(&inner.path, once(MEASURE, &field)));
    return Ok(());
  }
  entries.push(Entry {
    field,
    value: folded,
  });
  Ok(())
}

/// `<field> = <fold>` — the measure entry's SUGAR, and the one thing it is allowed to be.
///
/// The short spelling has exactly one position and spends it on the fold, so the only entries it can
/// state WHOLE are the ones with nothing else to state. A fold that reads a column is therefore
/// refused here rather than accepted with the column guessed: see [`sugar_omits_the_column`].
///
/// [`None`] is the refusal, already recorded.
fn sugar(
  inner: &syn::meta::ParseNestedMeta<'_>,
  field: &syn::Ident,
  errors: &mut Errors,
) -> Option<Folded> {
  let by = fold_value(inner, field, errors)?;
  if by.owed() == Owed::Column {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      sugar_omits_the_column(field, &by.as_written()),
    ));
    attribute::skip_entry(inner);
    return None;
  }
  // A TAIL after the fold — `count = counting("bytes")` is the shape the book's own sketch carried,
  // and reading the word and stopping would leave the block's walk to refuse the leftover with
  // syn's *expected `,`*, which names neither the rule nor the spelling that keeps it.
  if !value_was_the_whole_entry(inner) {
    errors.push(syn::Error::new_spanned(
      &inner.path,
      measure_entry_shape(field),
    ));
    attribute::skip_entry(inner);
    return None;
  }
  Some(Folded { by, from: None })
}

/// `<field>(fold = <fold>, from = "<upstream column>")` — the FULL FORM, every property by name.
///
/// [`None`] is the refusal, already recorded.
///
/// # Errors
/// Whatever the property walk hit — a token stream this reader has lost its place in cannot be
/// resynchronised, and the head's own [`Head::whole`] flag is what keeps that failure from earning a
/// second, false sentence about a word nobody read.
fn full_form(
  inner: &syn::meta::ParseNestedMeta<'_>,
  field: &syn::Ident,
  errors: &mut Errors,
) -> syn::Result<Option<Folded>> {
  if attribute::empty_group(inner) {
    errors.push(named(inner, empty_entry(field)));
    return Ok(None);
  }
  let mut written = FullForm::default();
  inner.parse_nested_meta(|property| {
    match MEASURE_PROPERTIES
      .iter()
      .find(|known| property.path.is_ident(known.word))
    {
      Some(known) => (known.read)(&property, &mut written, field, errors),
      None => {
        written.refused = true;
        errors.push(attribute::unknown(
          &property,
          &unknown_property(field),
          &property_words(),
        ));
      }
    }
    Ok(())
  })?;
  Ok(settled(written, inner, field, errors))
}

/// ONE property a measure entry's full form takes — the word an author writes, and the reader that
/// takes it.
///
/// # A TABLE, because the entry group IS the seat's growth point
///
/// The whole reason the full form exists beside the sugar is that a measure column's next
/// configurable fact has somewhere to land — so a chain of `is_ident` arms would make every such
/// arrival a small edit in four places: the arm, the near-miss vocabulary, the roster a refusal
/// prints, and the sentence that lists what an entry takes.
///
/// So the roster is DATA, which is the `cursor(…)` block's own shape one grammar over. A new
/// property is **one row here and one pair of fields on [`FullForm`]**; [`property_words`],
/// [`property_roster`] and the refusal an unknown word earns all derive from this array and are
/// restated nowhere.
struct MeasureProperty {
  /// The word, as it is written.
  word: &'static str,
  /// What it fills in — and what it refuses with, which is the property's own business.
  read: fn(&syn::meta::ParseNestedMeta<'_>, &mut FullForm, &syn::Ident, &mut Errors),
}

/// Everything a measure entry's full form takes today.
const MEASURE_PROPERTIES: &[MeasureProperty] = &[
  MeasureProperty {
    word: FOLD,
    read: read_fold,
  },
  MeasureProperty {
    word: FROM,
    read: read_from,
  },
];

/// What one full-form entry was read into.
#[derive(Default)]
struct FullForm {
  /// `fold = <fold>`, and the token that named it — the caret for a sentence about what the fold
  /// owes.
  by: Option<(Measure, syn::Path)>,
  /// Whether `fold` was written AT ALL, however badly.
  ///
  /// The `role_spoken` device at the property grain: an entry whose fold was refused BY NAME must
  /// not also earn the names-no-fold sentence, which would tell an author who did name one that they
  /// did not.
  fold_spoken: bool,
  /// `from = "…"`, and the token that named it — the caret for a sentence about a column the fold
  /// does not read.
  from: Option<(syn::Ident, syn::Path)>,
  /// Whether `from` was written at all, for [`fold_spoken`](Self::fold_spoken)'s reason.
  from_spoken: bool,
  /// Whether a property this entry does not know was written in it.
  ///
  /// The same device at the grain of the whole entry, and the same law the head's [`Head::whole`]
  /// states: a word the reader could not place is a word whose MEANING is unknown, so an absence
  /// check that would have read it cannot be run. `bytes(fold = summing, frm = "size")` is one
  /// mistake, and telling its author their entry also names no column would be the second half of
  /// their typo reported as a rule they broke.
  refused: bool,
}

/// The FOLD property's reader.
fn read_fold(
  property: &syn::meta::ParseNestedMeta<'_>,
  written: &mut FullForm,
  field: &syn::Ident,
  errors: &mut Errors,
) {
  if written.fold_spoken {
    errors.push(named(property, property_once(FOLD, field)));
    return;
  }
  written.fold_spoken = true;
  let Some(by) = fold_value(property, field, errors) else {
    return;
  };
  if !value_was_the_whole_entry(property) {
    errors.push(syn::Error::new_spanned(
      &property.path,
      measure_entry_shape(field),
    ));
    attribute::skip_entry(property);
    return;
  }
  written.by = Some((by, property.path.clone()));
}

/// The FROM property's reader — `group(…)`'s own value law at the other role.
fn read_from(
  property: &syn::meta::ParseNestedMeta<'_>,
  written: &mut FullForm,
  field: &syn::Ident,
  errors: &mut Errors,
) {
  if written.from_spoken {
    errors.push(named(property, property_once(FROM, field)));
    return;
  }
  written.from_spoken = true;
  let shape = from_shape(field);
  match value::literal(property, &shape).and_then(|spelled| {
    value::named_field(&spelled, &shape).map_err(|e| syn::Error::new(e.span(), shape.clone()))
  }) {
    Ok(column) => written.from = Some((column, property.path.clone())),
    Err(e) => errors.push(e),
  }
}

/// The two properties CHECKED AGAINST EACH OTHER, which is the only thing the full form decides that
/// neither property can decide alone.
///
/// A fold and a column are one claim: `counting` reads no column and `summing` reads one, so an
/// entry that pairs either with the wrong answer is refused at the token that made the pairing wrong
/// — the column for a fold that reads none, the fold for a fold whose column is missing. A fold the
/// declaring crate wrote is neither, and is accepted with whatever the entry named.
///
/// # THE ABSENCE HALVES RIDE THE SPOKEN FLAGS, and the presence half does not
///
/// *This entry names no fold* and *this entry names no column* are claims about what the entry did
/// NOT say, so a property that was written and refused — misspelled, unreadable, unknown to the
/// roster — takes them off the table: an author who wrote `frm = "size"` wrote the column, and
/// telling them they omitted it is their one typo reported as two rules. *This entry names a column
/// its fold does not read* is about a word that IS there and reads the same however the rest of the
/// entry went.
///
/// [`None`] is the refusal, already recorded.
fn settled(
  written: FullForm,
  at: &syn::meta::ParseNestedMeta<'_>,
  field: &syn::Ident,
  errors: &mut Errors,
) -> Option<Folded> {
  let Some((by, fold_at)) = written.by else {
    if !written.fold_spoken && !written.refused {
      errors.push(syn::Error::new_spanned(&at.path, names_no_fold(field)));
    }
    return None;
  };
  match (by.owed(), written.from) {
    (Owed::Column, None) => {
      if !written.from_spoken && !written.refused {
        errors.push(syn::Error::new_spanned(
          &fold_at,
          fold_owes_a_column(field, &by.as_written()),
        ));
      }
      None
    }
    (Owed::Nothing, Some((_, from_at))) => {
      errors.push(syn::Error::new_spanned(
        &from_at,
        fold_reads_no_column(field, &by.as_written()),
      ));
      None
    }
    (_, from) => Some(Folded {
      by,
      from: from.map(|(column, _)| column),
    }),
  }
}

/// The VALUE that names a fold — a shipped word BARE, or a declared type QUOTED.
///
/// Read by BOTH spellings, at the sugar's own position and at `fold = …` inside the full form, so
/// the two cannot come to accept different words or refuse with different sentences. That is the
/// `cursor(…)` seat's law one grammar over, where the shorthand is the group's one entry written
/// inline and never a second grammar.
///
/// [`None`] is the refusal, already recorded.
fn fold_value(
  entry: &syn::meta::ParseNestedMeta<'_>,
  field: &syn::Ident,
  errors: &mut Errors,
) -> Option<Measure> {
  let Ok(stream) = entry.value() else {
    errors.push(named(entry, measure_entry_shape(field)));
    return None;
  };
  if stream.peek(syn::LitStr) {
    // The QUOTED half. Nothing here resolves the path — the emission writes it, and a path naming
    // nothing is rustc's own refusal at the string the author wrote.
    return match stream
      .parse::<syn::LitStr>()
      .and_then(|spelled| spelled.parse::<syn::Path>())
    {
      Ok(path) => Some(Measure::Declared(path)),
      Err(e) => {
        errors.push(syn::Error::new(e.span(), DECLARED_IS_A_PATH));
        attribute::skip_entry(entry);
        None
      }
    };
  }
  if stream.peek(syn::Ident) {
    let Ok(word) = stream.parse::<syn::Ident>() else {
      errors.push(named(entry, measure_entry_shape(field)));
      return None;
    };
    return match Measure::shipped(&word.to_string()) {
      Some(shipped) => Some(shipped),
      None => {
        errors.push(syn::Error::new_spanned(&word, unknown_fold(&word)));
        attribute::skip_entry(entry);
        None
      }
    };
  }
  errors.push(named(entry, measure_entry_shape(field)));
  None
}

/// Whether an entry's VALUE was the whole of what it carried — the stream sitting at the separator
/// that ends the entry, or at the end of the block it is in.
///
/// Asked because a value this grammar reads by PEEKING can leave tokens behind: `= summing(…)` reads
/// as the word `summing` with a group after it, and a reader that stopped at the word would hand the
/// leftover to syn, whose sentence names the punctuation rather than the rule.
fn value_was_the_whole_entry(entry: &syn::meta::ParseNestedMeta<'_>) -> bool {
  entry.input.is_empty() || entry.input.peek(syn::Token![,])
}

/// The FIELD MARKERS: the three projection words, this kind's two ROLE words, and a named refusal
/// for every other family's.
///
/// The projections ride [`column::projection_markers`] for the reason every tier with columns does:
/// one marker says one thing about one field whichever grammar declared it, and the declared-twice
/// rule belongs with the walk rather than with each tier.
///
/// # EXACTLY ONE ROLE, and both halves of that are refusals
///
/// A field with NO role has no place in the row — its column is neither part of the key nor filled
/// by a fold, and there is nothing for the emission to do with it. A field with BOTH is a column
/// claiming to be its own key and its own answer. Neither is decidable from one entry, so the
/// second is refused inside the walk where the first marker is already in hand, and the first after
/// it, where the field's whole attribute has been read.
fn markers(
  attrs: &[syn::Attribute],
  field: &syn::Ident,
  errors: &mut Errors,
) -> (
  ingraph_codegen::prelude::Projection,
  Option<(Role, syn::Path)>,
  bool,
) {
  let mut role: Option<(Role, syn::Path)> = None;
  let mut spoken = false;
  let projection = column::projection_markers(attrs, field, errors, |meta, errors| {
    // `id` is refused PERMANENTLY rather than as a wait: an aggregate's key is minted from the group
    // columns, so a field claiming to be the id is claiming a seat this kind's own grammar fills.
    if meta.path.is_ident("id") {
      return column::Claim::Refused(syn::Error::new_spanned(
        &meta.path,
        mints_its_own_key(field),
      ));
    }

    // THE OTHER KINDS' ELECTION MARKERS, refused by name for the courtesy the house gives them
    // everywhere: an author who wrote one had a coherent idea about the wrong kind. Walked over the
    // KINDS rather than over a table of words, so the vocabulary keeps its one home.
    for owner in [NodeKind::Vector, NodeKind::Fulltext] {
      let Some(word) = owner.election() else {
        continue;
      };
      if meta.path.is_ident(word) {
        return column::Claim::Refused(syn::Error::new_spanned(
          &meta.path,
          election_is_another_kinds(word, owner, field),
        ));
      }
    }

    for this in [Role::Group, Role::Measure] {
      if !meta.path.is_ident(this.word()) {
        continue;
      }
      spoken = true;
      if attribute::has_block(meta) || attribute::has_value(meta) {
        return column::Claim::Refused(named(meta, role_is_bare(this, field)));
      }
      match &role {
        Some((seen, _)) if *seen == this => errors.push(syn::Error::new_spanned(
          &meta.path,
          format!(
            "`{word}` is declared more than once on `{field}` — one marker, one field",
            word = this.word(),
          ),
        )),
        Some((seen, _)) => errors.push(syn::Error::new_spanned(
          &meta.path,
          two_roles(*seen, this, field),
        )),
        None => role = Some((this, meta.path.clone())),
      }
      return column::Claim::Taken;
    }

    column::Claim::Refused(attribute::unknown(
      meta,
      &unknown_field(field),
      &field_vocabulary(),
    ))
  });
  (projection, role, spoken)
}

/// The `group(…)` entries matched against the fields they fill.
///
/// It runs whether or not the block was written, so the ZERO-GROUP refusal and the per-entry ones
/// are one pass: a declaration that wrote no block still learns what its `#[ingraph(group)]` fields
/// are missing.
///
/// `whole` is [`Head::whole`], and it gates the ZERO-GROUP half alone: the per-entry refusals are
/// about entries the reader DID read, and stay true however the walk ended.
fn grouped(
  entries: &[Entry<syn::Ident>],
  at: Option<&syn::Path>,
  whole: bool,
  columns: &[Field],
  aggregate: &syn::Ident,
  errors: &mut Errors,
) -> Vec<Grouped> {
  if whole && entries.is_empty() && at.is_none() {
    errors.push(syn::Error::new_spanned(aggregate, no_group()));
  }
  entries
    .iter()
    .filter_map(|entry| {
      let column = matched(entry, Role::Group, columns, aggregate, errors)?;
      Some(Grouped {
        field: entry.field.clone(),
        from: entry.value.clone(),
        ty: column.ty.clone(),
        projection: column.projection,
      })
    })
    .collect()
}

/// The `measure(…)` entries matched against the fields they fill — [`grouped`]'s twin.
fn measured(
  entries: &[Entry<Folded>],
  at: Option<&syn::Path>,
  whole: bool,
  columns: &[Field],
  aggregate: &syn::Ident,
  errors: &mut Errors,
) -> Vec<Measured> {
  if whole && entries.is_empty() && at.is_none() {
    errors.push(syn::Error::new_spanned(aggregate, no_measure()));
  }
  entries
    .iter()
    .filter_map(|entry| {
      let column = matched(entry, Role::Measure, columns, aggregate, errors)?;
      cardinality(&entry.value.by, column, errors);
      Some(Measured {
        field: entry.field.clone(),
        by: entry.value.by.clone(),
        from: entry.value.from.clone(),
        ty: column.ty.clone(),
        projection: column.projection,
      })
    })
    .collect()
}

/// A `counting` column is a CARDINALITY, and this framework carries every cardinality at `Count`.
///
/// # WHERE THE LINE IS DRAWN, and it is drawn by WHOSE FACT THE ANSWER IS
///
/// A measure's stored type has to equal what its fold answers, and the two folds this framework
/// ships know that answer from opposite sides. `counting` answers an `ingraph::Count` about items of
/// every type there is — a fact this crate OWNS, decided by the citizen it wrote — so a column of
/// any other type is a mistake the grammar can see, and it is refused HERE, at the field's own type,
/// with a sentence naming what to write instead. `summing` answers the UPSTREAM COLUMN's own type,
/// which is a fact this pass cannot reach: two macro expansions cannot see each other, so what
/// `from = "bytes"` even IS is unknowable until rustc resolves it. That one stays the emitted call's
/// `E0271`, at the span of the string its author wrote, and it is honest there rather than guessed
/// here.
///
/// A fold the declaring crate wrote is the third case and it is neither: its `Value` is its
/// author's, so nothing is checkable and nothing is refused — [`Owed::Theirs`]'s own posture, one
/// question later.
///
/// # `u64` IS ON THE REFUSED LIST NOW, and that is the 2026-08-27 ruling arriving here
///
/// It used to be the ANSWER. The citizen's `Value` was a bare `u64`, and a `u64` has no carrier in
/// SQLite or PostgreSQL — so a `counting` measure could be declared on MySQL and nowhere else. The
/// ruling minted `ingraph::Count`, a `u64` carrying the invariant that makes the narrowing honest
/// (*a cardinality counts rows that EXIST*, so it is bounded by the physical store), and moved the
/// citizen's answer onto it. So the width that was right is now the near miss, and it is the one an
/// author is likeliest to write: the refusal names it like every other.
///
/// # It fires on a NAMED PRIMITIVE and stays silent on everything else
///
/// The check is a spelling, and a spelling can only be trusted where it is unambiguous. `u32`,
/// `usize` and `i64` are the language's own words and name themselves wherever they appear — a
/// `count: u32` is the mistake this refusal exists for. An ALIAS is not: `type Tally = Count;` is a
/// perfectly good column and a pass that read its name would refuse it wrongly, which is the false
/// refusal the elected-field seat one kind over records as the reason its own check is a bound
/// rather than an allowlist. So an unrecognised spelling is left to the emitted call, where rustc
/// has the type this pass has only the name of — and `Count` itself is one of those unrecognised
/// spellings, which is why the ACCEPTANCE costs this list nothing: a path is not a primitive word.
fn cardinality(by: &Measure, column: &Field, errors: &mut Errors) {
  if !matches!(by, Measure::Counting) {
    return;
  }
  let syn::Type::Path(path) = &column.ty else {
    return;
  };
  let Some(last) = path.path.segments.last() else {
    return;
  };
  if !NARROWINGS.iter().any(|word| last.ident == word) {
    return;
  }
  errors.push(syn::Error::new_spanned(
    &column.ty,
    counting_is_wide(&column.name),
  ));
}

/// The primitive spellings a `counting` column is refused for — EVERY numeric width the language
/// names, plus the two non-numeric primitives an author might reach for by mistake.
///
/// The list has no exception in it any more, and that is what changed on 2026-08-27: the citizen's
/// answer is `ingraph::Count`, which is not a word the language names, so no primitive is the right
/// one and `u64` joined the other fourteen. See [`cardinality`] for the ruling.
///
/// A list of WORDS rather than of types, because that is all this pass has: see [`cardinality`] for
/// why an unlisted spelling is the emitted call's question and not this one's.
const NARROWINGS: [&str; 16] = [
  "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32",
  "f64", "bool", "char",
];

/// The refusal a column named after the emission's own method earns.
///
/// # It is a NAME COLLISION and not a namespace fence, so it names exactly one word
///
/// The framework's column fence catches `__…__` and the alias half, which are about the TABLE. This
/// is about the emitted `impl`: an aggregate's expansion mints `fold`, the record pass mints an
/// accessor family beside it, and a `copy` column takes the BARE field name — so `fold` written as a
/// column is `E0592`, *duplicate definitions*, reported at the attribute and inside an expansion its
/// author cannot edit. The word is refused whatever projection the column wears, because *only the
/// `copy` spelling collides* is a fact about this emission today and a rule an author would have to
/// re-derive the day another accessor took the bare name.
///
/// The measured word `fold` is the entry PROPERTY's too, and the two are the same word about the
/// same thing — what folds a group — which is why the sentence can point at one from the other.
fn mints_a_fold() -> String {
  format!(
    "`{FOLD}` is the method an aggregate's expansion MINTS — `<Aggregate>::{FOLD}(rows)` is the \
     recompute's arithmetic, every row of the upstream in and one row per group out — so a column \
     of that name would be two definitions of one name on one type, which rustc reports inside the \
     expansion rather than here. Rename the column: the word is already this grammar's, at \
     `measure(<field>({FOLD} = …))`, where it says what folds a group rather than naming one of the \
     folded columns"
  )
}

/// The refusal a `counting` column of the wrong type earns.
fn counting_is_wide(field: &syn::Ident) -> String {
  format!(
    "`{field}` is filled by `counting`, which answers HOW MANY ROWS a group holds — a CARDINALITY, \
     and this framework carries every cardinality at `ingraph::Count`. So the column's type is \
     `Count` and not this one: the fold's answer is the citizen's own fact rather than the \
     declaration's, and a column of another type would be the emission asking rustc to reshape a \
     count it has already made. Write `{field}: ingraph::Count`, or fold this column with a measure \
     whose answer is the type you want — a fold is a TYPE in this grammar, so one of your own is \
     `measure({field} = \"path::To::Fold\")` and needs no word admitted to any vocabulary. `Count` \
     is a `u64` that knows it counts rows that EXIST, which is what lets it store on SQLite and \
     PostgreSQL where a bare `u64` has no column at all"
  )
}

/// The field ONE head entry is about, where the declaration has one wearing the matching role.
///
/// Two refusals live here and they are different mistakes. A name that is no field of this struct is
/// an entry about nothing. A name that IS a field and wears the OTHER role is the head and the field
/// disagreeing — which is the whole return on writing the word twice, so it is refused by name
/// rather than settled by letting one half win.
fn matched<'a, T>(
  entry: &Entry<T>,
  role: Role,
  columns: &'a [Field],
  aggregate: &syn::Ident,
  errors: &mut Errors,
) -> Option<&'a Field> {
  let Some(column) = columns.iter().find(|column| column.name == entry.field) else {
    errors.push(syn::Error::new_spanned(
      &entry.field,
      format!(
        "`{block}(…)`'s entries name THIS declaration's fields, and `{field}` is not one of \
         `{aggregate}`'s",
        block = role.word(),
        field = entry.field,
      ),
    ));
    return None;
  };
  match &column.role {
    Some((worn, _)) if *worn == role => Some(column),
    Some((worn, at)) => {
      errors.push(syn::Error::new_spanned(
        at,
        format!(
          "`{field}` is named in `{block}(…)` and wears `#[ingraph({worn})]` — the head entry says \
           this column is {what}, and the marker says it is {other}, and a column is one of them. \
           The two words are written twice on purpose so that a disagreement is caught here instead \
           of becoming a row whose shape depends on which half was read",
          field = entry.field,
          block = role.word(),
          worn = worn.word(),
          what = role.what(),
          other = worn.what(),
        ),
      ));
      None
    }
    None => None,
  }
}

/// Every ROLE-BEARING field checked against the head — the other direction of [`matched`].
///
/// A field that wears a marker and is named in no entry is the half of the double declaration the
/// head forgot, and the two roles are missing DIFFERENT facts: a group column has no upstream field
/// to be read out of, and a measure has nothing to fold it. So the sentence is each role's own.
///
/// A field wearing NO role is refused here too, and last, because it is the same walk's answer to
/// the same question: which fields the head has an entry for. Its own sentence names both words,
/// there being no half of the pair to point at.
///
/// # `whole` gates the HEAD's half and not the field's
///
/// *This marked field has no head entry* is a claim about what the head does not say, and a head
/// the reader could not finish says nothing either way past where it stopped — see [`Head::whole`].
/// *This field wears no role* is a claim about the FIELD's own attribute, which was read in full
/// whatever the head did, so it stands.
fn unmatched(
  columns: &[Field],
  groups: &[syn::Ident],
  measures: &[syn::Ident],
  whole: bool,
  errors: &mut Errors,
) {
  for column in columns {
    let name = &column.name;
    let Some((role, at)) = &column.role else {
      if !column.role_spoken {
        errors.push(syn::Error::new_spanned(name, wears_no_role(name)));
      }
      continue;
    };
    let named_at_the_head = match role {
      Role::Group => groups.contains(name),
      Role::Measure => measures.contains(name),
    };
    if !whole || named_at_the_head {
      continue;
    }
    let missing = match role {
      Role::Group => {
        format!("`{name} = \"<upstream field>\"`, naming the upstream field it is read out of")
      }
      Role::Measure => format!(
        "`{name}({FOLD} = <fold>, {FROM} = \"<upstream column>\")`, naming what folds a group into \
         it and the column that fold reads — a fold is one of {folds}, or `\"path::to::Fold\"` for \
         one of your own — or the sugar `{name} = <fold>` where the fold reads no column",
        folds = shipped(Measure::SHIPPED.into_iter()),
      ),
    };
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{name}` wears `#[ingraph({word})]` and `{word}(…)` has no entry for it — the marker says \
         WHAT the column is and the head entry says the rest, so a marked field with no entry is \
         half a declaration. Write {missing}",
        word = role.word(),
      ),
    ));
  }
}

/// Aggregates are concrete, for the reason every declaration in this family is: a column's type is
/// read straight off the declaration, and a type parameter has none until it is substituted.
fn concrete(generics: &syn::Generics, errors: &mut Errors) {
  let why = "generic aggregates are not supported — the declaration must be concrete, because a \
             key column's type is read straight off it";
  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 named fields — the only shape an aggregate may take, since both head blocks
/// name a field BY NAME and both markers are worn by one.
fn named_fields(input: &syn::DeriveInput) -> syn::Result<&syn::FieldsNamed> {
  match &input.data {
    syn::Data::Struct(data) => match &data.fields {
      syn::Fields::Named(named) => Ok(named),
      syn::Fields::Unnamed(_) | syn::Fields::Unit => Err(syn::Error::new_spanned(
        &input.ident,
        "an aggregate must be a struct with named fields — `group(…)` and `measure(…)` each fill a \
         field BY NAME, and a positional one has none to be filled by",
      )),
    },
    syn::Data::Enum(_) | syn::Data::Union(_) => Err(syn::Error::new_spanned(
      &input.ident,
      "`#[ingraph::aggregate]` supports structs only",
    )),
  }
}

/// The refusal a declaration with no fields earns.
const NO_FIELDS: &str = "an aggregate with no fields folds nothing into nothing — its row is its \
                         group columns and its measures, and a row with neither is a table with no \
                         columns. Declare at least one `#[ingraph(group)]` field and one \
                         `#[ingraph(measure)]` field";

/// The refusal a declaration with no `upstream(…)` earns. TERMINAL: with no upstream there is
/// nothing for the group projection to be read out of.
const NO_UPSTREAM: &str = "an aggregate folds the rows of ONE upstream, and `upstream(…)` is where \
                           it names one — `upstream(node = \"path::To::Upstream\")`. It is not \
                           optional: an aggregate reads its upstream's TABLE rather than its \
                           messages, so without an upstream there is no table to read and nothing \
                           to group";

/// The refusal a declaration with no `poll(…)` earns.
///
/// # THE TRIGGERLESS VERDICT: a refusal, not a legal never-runs declaration
///
/// An aggregate RECOMPUTES WHOLE ON A TRIGGER, and the trigger is the only thing that ever writes
/// its table. A declaration with no clock therefore mounts a store that stays empty for the life of
/// the deployment, and every query over it answers zero rows — silently, and forever. That is the
/// swallowed authoring error this grammar refuses everywhere else, at its largest possible grain.
///
/// The word is MANDATORY rather than defaulted for the reason the framework refuses to default an
/// interval anywhere: how often a recount is affordable is a deployment's fact, and a macro that
/// picked one would be choosing a load profile on a deployment's behalf.
///
/// The freshness door the design recorded — a notify edge as an ALARM, an event nudging a recompute
/// — is named in the sentence rather than left out, because an author who wanted event-driven
/// freshness is exactly the author most likely to write no clock.
const NO_TRIGGER: &str = "an aggregate needs a `poll(…)` clock — it recomputes WHOLE on every \
                          trigger, and the trigger is the only thing that ever writes its rows, so \
                          a declaration with no clock mounts a table that stays empty and answers \
                          nothing forever. Write one: `poll(<name>, every = \"10m\", light)`, in \
                          the framework's own clock grammar. A notify edge used as an ALARM is the \
                          recorded freshness upgrade and is not built, so the clock is the one \
                          trigger there is";

/// The refusal a field wearing no role earns.
fn wears_no_role(field: &syn::Ident) -> String {
  format!(
    "`{field}` wears neither `#[ingraph({GROUP})]` nor `#[ingraph({MEASURE})]` — an aggregate's row \
     is its group columns and its measures, and every field is one or the other: a group column is \
     read out of the upstream's rows and keys the folded row, a measure is what a fold fills. There \
     is no third thing for a column of one to be, so a field with no role is a column the emission \
     has nothing to put in"
  )
}

/// The refusal a field wearing BOTH roles earns.
fn two_roles(first: Role, second: Role, field: &syn::Ident) -> String {
  format!(
    "`{field}` wears both `#[ingraph({first})]` and `#[ingraph({second})]`, and each names a \
     different column: a group column is READ out of the upstream's rows and keys the folded row, a \
     measure is what a fold FILLS. A column is one of them — a field that were both would be part \
     of the key that decides which rows it is folded from",
    first = first.word(),
    second = second.word(),
  )
}

/// The refusal a role marker written with a block or a value earns.
fn role_is_bare(role: Role, field: &syn::Ident) -> String {
  format!(
    "`{word}` is a BARE marker — its presence says `{field}` is {what}, which is the whole of what \
     the role declares. What that column is read from, or what folds it, is the head's `{word}(…)` \
     entry, because it is a fact about the upstream rather than about this field",
    word = role.word(),
    what = role.what(),
  )
}

/// The refusal an `#[ingraph(id)]` on an aggregate's field earns.
fn mints_its_own_key(field: &syn::Ident) -> String {
  format!(
    "`{field}` cannot be an aggregate's id, because an aggregate mints its key from its GROUP \
     COLUMNS — one row per group, addressed by the group it is about, so the key is `group(…)` and \
     there is no seat left for a declared id. A node that mints an id of its own is an `operator` \
     or a `record`"
  )
}

/// The refusal another kind's election marker earns on an aggregate's field.
fn election_is_another_kinds(word: &str, owner: NodeKind, field: &syn::Ident) -> String {
  format!(
    "`{word}` elects `{field}` into a query an aggregate runs none of — an aggregate FOLDS its \
     upstream's rows into one row per group and is read as the record it is, so no field of one is \
     run over by a ranking at all. The marker is the `{owner}` kind's own, and an index over these \
     rows is its OWN node: declare it with the `{owner}` macro, on a type whose `upstream(…)` names \
     this aggregate. {law}",
    owner = owner.as_str(),
    law = owns_one_storage(KIND),
  )
}

/// The refusal a projection entry inside `upstream(…)` earns.
fn projection_belongs_to_group(path: &syn::Path) -> String {
  let word = suggest::word(path).unwrap_or_else(|| "that entry".to_owned());
  format!(
    "`upstream(…)` names the EDGE on an aggregate and takes `{NODE} = \"…\"` alone — the projection \
     is `{GROUP}(…)`, because only the group columns are read out of the upstream's rows and a \
     measure's column is FOLDED into being, so a projection here would claim a totality this kind \
     does not have. A derived index's `upstream(…)` carries both, and that is the difference. Write \
     `{GROUP}({word} = \"<upstream field>\")`"
  )
}

/// The refusal an unknown bare word inside a `measure(…)` entry earns.
fn unknown_fold(word: &syn::Ident) -> String {
  format!(
    "`{word}` is no fold this framework ships — the shipped ones are {shipped}, written BARE \
     because they are the framework's own, and every other fold there is arrives QUOTED as the type \
     that implements it: `\"path::to::Fold\"`. The bare vocabulary is closed because a word is a \
     promise this crate can write the whole binding; the quoted form is the open half and needs no \
     admission{near}",
    shipped = shipped(Measure::SHIPPED.into_iter()),
    near = suggest::did_you_mean(&word.to_string(), Measure::SHIPPED),
  )
}

/// The refusal a `<field> = <value>` in `group(…)` whose value is not a field name earns.
fn group_entry_shape(field: &syn::Ident) -> String {
  format!(
    "`{field} = \"<upstream field>\"` names the upstream field this group column is read out of, in \
     a string literal — the entry's own name is the field being filled, and its value is where the \
     value comes from"
  )
}

/// The refusal a `measure(…)` entry whose shape is neither spelling earns, naming both.
fn measure_entry_shape(field: &syn::Ident) -> String {
  format!(
    "`{field}` is one measure column, and it is written in its FULL FORM — `{field}({FOLD} = \
     <fold>, {FROM} = \"<upstream column>\")`, every property of the column by name — or in the \
     sugar `{field} = <fold>`, which is that same entry where the fold reads no column and so \
     nothing is left out. A FOLD is one of the framework's own, written bare ({shipped}), or one of \
     yours, written QUOTED as the type that implements it (`\"path::to::Fold\"`)",
    shipped = shipped(Measure::SHIPPED.into_iter()),
  )
}

/// The refusal a fold that READS A COLUMN earns when it is written in the sugar, which has no seat
/// for one.
///
/// The `delegate(…)` seat's mixed-form tooth at this position: the short spelling is kept for the
/// entries it can state WHOLE, and an entry with a property to declare writes the form that has a
/// name for every property. Nothing is lost by the split — the two spellings sit side by side in one
/// block, per entry.
fn sugar_omits_the_column(field: &syn::Ident, fold: &str) -> String {
  format!(
    "`{field} = {fold}` leaves out the column `{fold}` folds — the sugar spends its ONE position on \
     the fold and has no seat for anything else, so it is the spelling for entries with nothing \
     else to say. Write the FULL FORM, where every property of the column has a name: \
     `{field}({FOLD} = {fold}, {FROM} = \"<upstream column>\")`. The short spelling stays exactly \
     where it omits nothing — `{counting}` counts the group's ROWS and reads no column, so \
     `<field> = {counting}` is a whole entry",
    counting = Measure::SHIPPED[0],
  )
}

/// The refusal a fold that reads a column earns when the FULL FORM named none.
///
/// # The column is NOT defaulted to the measure's own field name
///
/// A measure's name is this declaration's and the column is the UPSTREAM's, and the two agreeing is
/// a coincidence rather than a rule — so a grammar that filled the seat from the field name would
/// fold the wrong column, silently, in every declaration where they differ, which is the swallowed
/// authoring error this whole grammar is written against. `group(…)` writes both spellings out for
/// the same reason even where they match.
fn fold_owes_a_column(field: &syn::Ident, fold: &str) -> String {
  format!(
    "`{fold}` folds an upstream COLUMN and `{field}(…)` names none — write `{FROM} = \"<upstream \
     column>\"` beside the fold: `{field}({FOLD} = {fold}, {FROM} = \"<upstream column>\")`. It is \
     not filled in from `{field}`: a measure's own name belongs to this declaration and the column \
     belongs to the upstream, so a grammar that assumed the two agree would fold the wrong column \
     wherever they did not — and say nothing. `{GROUP}(…)` spells both out for the same reason even \
     when they match"
  )
}

/// The refusal a fold that reads NO column earns when the entry named one.
fn fold_reads_no_column(field: &syn::Ident, fold: &str) -> String {
  format!(
    "`{FROM}` names the upstream column a fold READS, and `{fold}` reads none — it answers how many \
     rows the group holds, whatever those rows are, so there is no column for this entry to name. \
     Drop the property: `{field}({FOLD} = {fold})` is the entry entire, and `{field} = {fold}` is \
     that same entry in the sugar, which omits nothing here"
  )
}

/// The refusal a full-form entry that named no fold earns.
fn names_no_fold(field: &syn::Ident) -> String {
  format!(
    "`{field}(…)` names no fold, and a measure column is what a FOLD fills — `{FROM}` alone says \
     which column is read and nothing about what becomes of it. Write `{FOLD} = <fold>` in the \
     entry: `{field}({FOLD} = <fold>, {FROM} = \"<upstream column>\")`, with the fold one of \
     {shipped} or a `\"path::to::Fold\"` of your own",
    shipped = shipped(Measure::SHIPPED.into_iter()),
  )
}

/// The refusal an entry written as an EMPTY group earns.
fn empty_entry(field: &syn::Ident) -> String {
  format!(
    "`{field}()` says nothing, which is not a measure — {}",
    measure_entry_shape(field)
  )
}

/// The refusal a property written twice in one entry earns.
fn property_once(word: &str, field: &syn::Ident) -> String {
  format!(
    "`{word}` is declared more than once in `{field}(…)` — one entry answers each property once, \
     and a second answer to one question is not a second measure: a column of its own takes an \
     entry of its own"
  )
}

/// The refusal an unknown property inside a full-form entry earns, naming the roster.
fn unknown_property(field: &syn::Ident) -> String {
  format!(
    "unknown property in `{field}(…)` — {roster}. What a measure column IS comes from its `#[ingraph({MEASURE})]` \
     marker and its declared type, so what is left for the entry to say is what folds the group and \
     which column that fold reads",
    roster = property_roster(),
  )
}

/// The full form's vocabulary, for a near miss to be measured against.
fn property_words() -> Vec<&'static str> {
  MEASURE_PROPERTIES
    .iter()
    .map(|property| property.word)
    .collect()
}

/// The full form's roster, as a sentence names it.
fn property_roster() -> String {
  format!(
    "a measure entry knows {}",
    shipped(MEASURE_PROPERTIES.iter().map(|property| property.word))
  )
}

/// The refusal a `{FROM}` whose value is not an upstream column name earns.
fn from_shape(field: &syn::Ident) -> String {
  format!(
    "`{FROM} = \"<upstream column>\"` names the upstream column `{field}`'s fold reads, in a string \
     literal — the column belongs to the upstream rather than to this declaration, which is why it \
     is quoted here exactly as it is in `{GROUP}(…)`"
  )
}

/// The refusal one field named twice in one block earns.
fn once(block: &str, field: &syn::Ident) -> String {
  format!("`{field}` is named more than once in `{block}(…)` — one field, one entry")
}

/// The refusal a declaration with no group earns, at whichever caret is honest.
fn no_group() -> String {
  format!(
    "an aggregate needs at least one `{GROUP}(…)` entry — it holds ONE ROW PER GROUP and mints its \
     key from the group columns, so a declaration with none has no key to address a row by and no \
     shape for the one keyless row it would hold. Write `{GROUP}(<field> = \"<upstream field>\")` \
     for each column the rows are grouped by"
  )
}

/// The refusal a declaration with no measure earns.
fn no_measure() -> String {
  format!(
    "an aggregate needs at least one `{MEASURE}(…)` entry — folding is what the kind IS, and a \
     declaration that folds nothing is a list of the upstream's distinct groups, which a query over \
     the upstream already answers. Write `{MEASURE}(<field>({FOLD} = <fold>, {FROM} = \"<upstream \
     column>\"))` for each column a fold fills"
  )
}

/// The sentence a head the reader could not finish would stop on, where NOTHING ELSE was recorded.
///
/// Never reached in practice — the failure that ends a walk is pushed by [`attribute::walk`] before
/// this guard is consulted, so [`Errors::stopped`] always has that sentence to close on. It is
/// written out rather than reached for with a panic, because a derive that aborts tells its author
/// nothing at all.
const UNREADABLE_HEAD: &str = "this aggregate's head could not be read to the end";

/// The refusal an entry naming no single word earns, in either block.
const ENTRY_NAMES_A_FIELD: &str = "an entry names ONE of this declaration's fields, so the entry's \
                                   own name is that field's name — a path with several segments \
                                   names no field of anything";

/// The refusal a `node` this grammar cannot read gets.
const NODE_IS_A_PATH: &str =
  "`node = \"…\"` names the upstream node, as a type path in a string literal";

/// The refusal a second `node` gets.
const NODE_ONCE: &str =
  "`node` is declared more than once in `upstream(…)` — one entry names one upstream";

/// The refusal a second `upstream(…)` gets.
///
/// Multi-upstream aggregation is BLOCKED rather than unwritten: it wants an intake keyed by group
/// across two tables, which is a seat the framework does not have — so the sentence says which,
/// rather than reading as a word nobody got round to.
const UPSTREAM_ONCE: &str = "`upstream` is declared more than once — an aggregate folds ONE \
                             upstream's rows. Folding two together needs a by-key intake across two \
                             tables, which is a seat this framework has not built, so v1 is \
                             single-upstream by ruling rather than by omission";

/// The refusal an `upstream` with nothing in it gets.
const UPSTREAM_TAKES_A_NODE: &str = "`upstream(…)` needs `node = \"path::To::Upstream\"` — naming \
                                     the node whose rows are folded is the only thing it does on an \
                                     aggregate, the projection being `group(…)`'s";

/// The refusal a second `group(…)` gets.
const GROUP_ONCE: &str =
  "`group` is declared more than once — one block carries every column the rows are grouped by";

/// The refusal a second `measure(…)` gets.
const MEASURE_ONCE: &str =
  "`measure` is declared more than once — one block carries every column a fold fills";

/// The refusal a second `graphql(…)` gets.
const GRAPHQL_ONCE: &str =
  "`graphql` is declared more than once — one declaration has one wire face";

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

/// The refusal a `crate` this grammar cannot read gets.
const CRATE_PATH: &str = "`#[ingraph::aggregate(crate = \"…\")]` must be a path to the `ingraph` \
                          crate, in a string literal";

/// The refusal a quoted fold that is not a path gets.
const DECLARED_IS_A_PATH: &str = "a fold of your own is named as a TYPE PATH in a string literal — \
                                  `\"app::Median\"`. Nothing here resolves it: the path is emitted \
                                  and the compiler resolves it where it lands";

/// The refusal the retired wrapper gets — the record's own sentence, one grammar over.
const PERSIST_UNWRAPPED: &str = "`persist(…)` is gone — an aggregate holds rows and names its \
                                 stores BARE at the head, so write \
                                 `#[ingraph::aggregate(…, sqlite)]` and keep every word that was \
                                 inside each database's own block. Storage is the essence of a \
                                 thing that holds rows, and an essence does not wrap; `graphql(…)`, \
                                 which is OPTIONAL, still does";

/// The record words an aggregate's own grammar has already decided, each with what it decided.
const DECIDED: [(&str, &str); 3] = [
  (
    "lineage",
    "the path is the GROUP columns, which `group(…)` already names — an aggregate's row is about a \
     group, and the group is what addresses it",
  ),
  (
    "key",
    "the key is the group columns, which `key = lineage ⊕ id` already spells over them — and there \
     is no id beside them, an aggregate minting no id of its own",
  ),
  (
    "subscribe",
    "an aggregate reads its upstream's TABLE rather than its messages, which is what makes it \
     immune to the duplicate delivery every edge in this framework permits — so its edge is \
     `upstream(node = \"…\")` and it takes no message feed at all",
  ),
];

/// The refusal an unrecognised head entry gets, naming the whole grammar.
fn unknown_head() -> String {
  format!(
    "unknown `ingraph` aggregate attribute — an aggregate takes `{UPSTREAM}(node = \"…\")`, \
     `{GROUP}(<field> = \"<upstream field>\", …)`, `{MEASURE}(<field>({FOLD} = <fold>, {FROM} = \
     \"<upstream column>\"), …)`, `{POLL}(…)`, its STORE WORDS bare ({stores}, with `{TABLE} = \
     \"…\"` and `{RENAME} = \"…\"` beside them), `{GRAPHQL}(…)` and `crate = \"…\"`, and nothing \
     else",
    stores = shipped(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str)),
  )
}

/// The head's own words, for a near miss. A word the sentence refuses BY NAME is not in it.
pub(crate) fn head_vocabulary() -> Vec<&'static str> {
  [
    UPSTREAM, GROUP, MEASURE, POLL, GRAPHQL, TABLE, RENAME, "crate",
  ]
  .into_iter()
  .chain(DatabaseKind::ALL.into_iter().map(DatabaseKind::as_str))
  .collect()
}

/// The refusal an unrecognised FIELD entry gets.
fn unknown_field(field: &syn::Ident) -> String {
  format!(
    "unknown `ingraph` field attribute — a field of an aggregate takes its ROLE (`{GROUP}` or \
     `{MEASURE}`, exactly one) and the projection words ({projections}), and nothing else. \
     `{field}`'s storage is the row table's, which the declaration names at its head, so a \
     per-database word here would be configuring a column of a row this declaration does not write \
     by hand",
    projections = shipped(column::PROJECTIONS.into_iter()),
  )
}

/// A field's own words, for a near miss.
pub(crate) fn field_vocabulary() -> Vec<&'static str> {
  [GROUP, MEASURE]
    .into_iter()
    .chain(column::PROJECTIONS)
    .collect()
}