flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
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
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
//! Messages declared once: [`wire!`](crate::wire!) takes a record or enum
//! definition and gives the type, its [`Wire`] codec and its [`Shape`].
//!
//! The codec is the value encoding's rules (`abi.md`, *The value
//! encoding*) applied by calls into [`crate::primitives`], in declaration
//! order, with no [`Value`] in between: a record is its fields in order, an
//! enum is its constructor's number and then its payload's parts, an
//! `Option` is `None` or `Some` and its value, a list is its count and its
//! items. Every field's form is its Rust type's ([`WireForm`]):
//! [`flow_value::Int`] is an `Int`, `bool` a `Bool`, `String` a `Text`,
//! [`flow_value::Bytes`] and `[u8; N]` `Bytes`, [`flow_value::Instant`] an `Instant`,
//! `Option<T>`, `Result<T, E>`, `Vec<T>` and a pair `(A, B)` are `Option`,
//! `Result`, `List` and a tuple, `Box<T>` is `T`, and another declared
//! type is itself. Four forms have no Flow type: `u64`, a number written as
//! itself, [`RunId`] and [`CallRef`], a text their own parse admits, and
//! [`Rest`], the bytes left in a message, which only a last field may be.
//!
//! A message is read by the walk every value decoder shares (the crate's
//! `build` module), its frames on the heap: each type's [`Wire::open`]
//! reads its own head, such as a constructor's number or a list's count, and
//! gives the value or its parts to open and how they are joined. A message
//! nests as deeply as its bytes do, since a description's nesting has no
//! limit (`abi.md`, *Type descriptions*), and the native stack stays the same
//! however deep it is.
//!
//! A [`Shape`] is the declaration as data: its name, and its fields or its
//! constructors with their numbers. [`Shape::project`] makes the Flow type of
//! a shape with neither form, declared in a catalog, so a declared message
//! is a Flow value too, which [`Shaped::write_at`] writes a message as. A
//! constructor's number is its position unless the declaration gives it,
//! as `Name { .. } = 1`. An enum may name a fieldless companion, its
//! constructors' kinds, which says which constructor a value is and finds
//! one by its number. Where the constructor is told apart outside the bytes,
//! an enum is written as its payload alone ([`Keyed`]).

use std::any::Any;
use std::collections::HashMap;
use std::num::NonZeroU64;
use std::ops::Range;
use std::sync::Arc;

use flow_span::{CallRef, RunId, TaskPath};
use flow_types::{
    Body, Constructor, Decl, DeclId, EnumShape, Identity, ModulePath, OptionCtor, Payload,
    RecordShape, Segments, Tree,
};

use crate::binary::{read_instant, write_instant};
use crate::build::{Begun, Frame, Walk, build};
use crate::bytes::{
    ERR, NONE, OK, Reader, SOME, wide, write_bytes, write_int, write_text, write_uint,
};
use crate::catalog::Catalog;
use crate::error::{DecodeError, DecodeErrorKind, EncodeError, Place};
use crate::limits::Limits;

mod shaped;

pub use crate::binary::{ValueReader, ValueWriter};
pub use crate::crossing::Fields;
pub use flow_types::Type;
pub use flow_value::Value;
pub use shaped::{Param, instant_of};

/// How a field or payload part is written, as its Rust type says: the
/// one mapping from a Rust type to a Flow type's shape, which a message's
/// codec and a toolkit's contract both read.
#[derive(Clone, Copy, Debug)]
pub enum WireForm {
    /// [`flow_value::Int`]: a signed number, a Flow `Int`.
    Int,
    /// [`flow_value::Decimal`]: a Flow `Decimal`.
    Decimal,
    /// `bool`: one byte, `0` or `1`.
    Bool,
    /// `String`: a text.
    Text,
    /// [`flow_value::Bytes`]: a run of bytes.
    Bytes,
    /// [`flow_value::Duration`]: std's `duration.Duration`.
    Duration,
    /// [`flow_value::Instant`]: std's `time.Instant`.
    Instant,
    /// `()`: `Unit`, written as nothing.
    Unit,
    /// [`std::convert::Infallible`]: `Never`, which has no values.
    Never,
    /// [`RunId`]: a text that is a run's id, which no Flow type checks.
    RunId,
    /// [`CallRef`]: a text that is a call's id, which no Flow type checks.
    CallRef,
    /// `u64`: a number, which no Flow type writes.
    Number,
    /// [`Rest`]: every byte left in the message, unframed.
    Rest,
    /// `Option<T>`, of `T`'s form.
    Option(fn() -> WireForm),
    /// `Vec<T>`, a list of `T`'s form.
    List(fn() -> WireForm),
    /// A set of `T`'s form.
    Set(fn() -> WireForm),
    /// A dictionary of these key and value forms.
    Dict(fn() -> WireForm, fn() -> WireForm),
    /// A tuple of these forms, in order.
    Tuple(&'static [fn() -> WireForm]),
    /// A declared type with no type parameters.
    Declared(fn() -> &'static Shape),
    /// The declaration's type parameter at this position.
    Param(usize),
    /// A declared type with type parameters, applied to these arguments.
    Applied(fn() -> &'static Shape, &'static [fn() -> WireForm]),
    /// A std declaration, of this module and name, applied to these
    /// arguments: a prelude one, such as `Result`, has the empty module.
    Std {
        /// The std module that declares it; empty for the prelude.
        module: &'static str,
        /// Its name.
        name: &'static str,
        /// The forms of its type arguments.
        args: &'static [fn() -> WireForm],
    },
}

/// A declared message: its name, and what it is made of.
#[derive(Debug)]
pub struct Shape {
    /// The type's name, which is its Flow type's.
    pub name: &'static str,
    /// Its type parameters' names, in order.
    pub params: &'static [&'static str],
    /// Its fields or its constructors.
    pub layout: Layout,
    /// What a declaration's text says beside its shape, when it has one.
    pub notes: Option<&'static Notes>,
}

/// What a declaration's text says beside its shape: where its Rust type is
/// defined, its doc comment, and each member's.
#[derive(Debug)]
pub struct Notes {
    /// The Rust module that defines it, as `module_path!()` spells it.
    pub module: &'static str,
    /// The file that defines it, as `file!()` spells it.
    pub file: &'static str,
    /// The line it is defined at.
    pub line: u32,
    /// Its doc comment's text, one line each.
    pub docs: &'static str,
    /// A record's fields, an enum's constructors or a newtype's one field,
    /// in declaration order.
    pub members: &'static [Note],
}

/// What a declaration's text says of one member.
#[derive(Debug)]
pub struct Note {
    /// Its doc comment's text, one line each.
    pub docs: &'static str,
    /// Whether it is public.
    pub public: bool,
    /// A constructor's named fields.
    pub fields: &'static [Note],
}

/// What a declared message is made of.
#[derive(Debug)]
pub enum Layout {
    /// A record of these fields, in order.
    Record(&'static [Field]),
    /// An enum of these constructors, in declaration order.
    Enum(&'static [Ctor]),
    /// A newtype over this form.
    Newtype(WireForm),
    /// A host type, whose values are the host's tokens.
    Host,
}

/// A named field of a record or a payload.
#[derive(Debug)]
pub struct Field {
    /// The field's name.
    pub name: &'static str,
    /// How it is written.
    pub form: WireForm,
}

/// A constructor of a declared enum.
#[derive(Debug)]
pub struct Ctor {
    /// The constructor's name.
    pub name: &'static str,
    /// The number its value is written with.
    pub number: u64,
    /// Its payload.
    pub parts: Parts,
}

/// A constructor's payload.
#[derive(Debug)]
pub enum Parts {
    /// None.
    Empty,
    /// Parts by position, of these forms.
    Positional(&'static [WireForm]),
    /// Named fields.
    Named(&'static [Field]),
}

/// A Rust type mapped to a Flow type: its [`WireForm`], and its values
/// written and read at the Flow type its form projects to, part by part,
/// as the value encoding has them.
pub trait Shaped: Sized + 'static {
    /// How a value of it is written.
    const FORM: WireForm;

    /// Writes it as a value of `ty`, the Flow type its form projects to in
    /// `out`'s catalog.
    ///
    /// # Errors
    ///
    /// An [`EncodeError`] when its form has no Flow type, `ty` is not that
    /// type, or the value is out of a form its type holds it to.
    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError>;

    /// Reads one, a value of `ty` in `input`'s catalog.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when `ty` is not the type its form projects to, or
    /// the bytes are not a value of `ty` that is one of its own.
    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError>;
}

/// A part of an aggregate a [`ValueWriter`] writes: any [`Shaped`] value,
/// whatever its Rust type.
pub trait Part {
    /// Writes it as a value of `ty`, as [`Shaped::write_at`] does.
    ///
    /// # Errors
    ///
    /// As [`Shaped::write_at`].
    fn write_part(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError>;
}

impl<T: Shaped> Part for T {
    fn write_part(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        self.write_at(out, ty)
    }
}

/// A type with a binary form of its own: written and read part by part, as
/// its [`WireForm`] says.
pub trait Wire: Shaped {
    /// Appends the bytes it writes before its parts to `out`, and pushes
    /// its parts to `parts` in the order they are written after them.
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>);

    /// Appends its bytes to `out`: its head, and then each part's bytes in
    /// order, written over a stack on the heap, so a value nested however
    /// deep is written on a native stack of fixed size.
    fn write(&self, out: &mut Vec<u8>) {
        write_parts(out, vec![self]);
    }

    /// Reads its head at `reader`: the value itself when it has no parts,
    /// else its parts to read and what joins them.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when the bytes there are not one's head.
    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError>;

    /// Reads one from `reader`, leaving the reader just past it.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when the bytes there are not one's.
    fn read(reader: &mut Reader<'_>) -> Result<Self, DecodeError> {
        let opened = Self::open(reader)?;
        built(reader, opened)
    }

    /// Its bytes.
    fn bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        self.write(&mut out);
        out
    }

    /// The one value `bytes` hold, and nothing else.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when the bytes are not one's, or bytes are left
    /// over.
    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
        whole(bytes, Self::open)
    }
}

/// A [`Wire`] value as the writer's stack holds it, whatever its Rust type.
pub trait AnyWire {
    /// As [`Wire::write_head`].
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>);
}

impl<T: Wire> AnyWire for T {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
        Wire::write_head(self, out, parts);
    }
}

/// Appends the bytes of each of `parts` to `out`, in order: a head, then
/// its parts' bytes before the next part's.
fn write_parts(out: &mut Vec<u8>, mut parts: Vec<&dyn AnyWire>) {
    parts.reverse();
    while let Some(next) = parts.pop() {
        let at = parts.len();
        next.write_head(out, &mut parts);
        parts[at..].reverse();
    }
}

/// The value `opened` began at `reader`, its parts read from there.
fn built<T: 'static>(reader: &mut Reader<'_>, opened: Opened) -> Result<T, DecodeError> {
    let built = build(
        &mut Reading {
            reader,
            path: Place::default(),
        },
        opened.0,
    )?;
    Ok(Joined(vec![built].into_iter()).part())
}

/// The one value `bytes` hold, begun by `open`, and nothing else.
fn whole<T: 'static>(
    bytes: &[u8],
    open: impl FnOnce(&mut Reader<'_>) -> Result<Opened, DecodeError>,
) -> Result<T, DecodeError> {
    let mut reader = Reader::new(bytes);
    let opened = open(&mut reader)?;
    let value = built(&mut reader, opened)?;
    if reader.is_empty() {
        Ok(value)
    } else {
        Err(DecodeError::of(
            &Place::default(),
            DecodeErrorKind::Mismatch,
            format!("has {} bytes left over", reader.remaining()),
        ))
    }
}

/// The values of `T` written one after another in `bytes` with no count
/// before them, as a file appended to value by value holds them, each with
/// the range of bytes it was read from; and, when the rest does not read as
/// one, the byte it starts at: a tail a write did not finish, bytes that
/// are not a `T`, or a `T` that reads no bytes and so cannot go on.
pub fn stream<T: Wire>(bytes: &[u8]) -> (Vec<(Range<usize>, T)>, Option<usize>) {
    let mut reader = Reader::new(bytes);
    let mut values = Vec::new();
    while !reader.is_empty() {
        let at = reader.position();
        let Ok(value) = T::read(&mut reader) else {
            return (values, Some(at));
        };
        if reader.position() == at {
            return (values, Some(at));
        }
        values.push((at..reader.position(), value));
    }
    (values, None)
}

/// What opens one value at a reader: [`Wire::open`] of its type.
pub type Open = fn(&mut Reader<'_>) -> Result<Opened, DecodeError>;

/// What makes one value of the parts its open listed, in their order.
pub type Join = fn(&mut Joined) -> Box<dyn Any>;

/// A value whose reading has begun: built, or its parts still to read.
#[derive(Debug)]
pub struct Opened(Begun<Pending, Join, Box<dyn Any>>);

/// The parts of a value still to read: each opened by its own type, the
/// next last, or this many items of one type.
#[derive(Debug)]
enum Pending {
    Each(Vec<Open>),
    Items(Open, usize),
}

impl Opened {
    /// A value with no parts, built.
    pub fn built<T: 'static>(value: T) -> Self {
        Self(Begun::Done(Box::new(value)))
    }

    /// A value of `opens.len()` parts, opened in order, then joined.
    #[must_use]
    pub fn parts(join: Join, opens: &[Open]) -> Self {
        Self(Frame::open(
            join,
            Pending::Each(opens.iter().rev().copied().collect()),
            opens.len(),
            0,
        ))
    }

    /// A value of `count` parts, each opened by `open`, then joined; room
    /// is set aside only for as many as `reader` has bytes left.
    fn items(join: Join, open: Open, count: usize, reader: &Reader<'_>) -> Self {
        Self(Frame::open(
            join,
            Pending::Items(open, count),
            count.min(reader.remaining()),
            0,
        ))
    }
}

/// A message being read from its bytes, by the walk every decoder shares.
struct Reading<'r, 'b> {
    reader: &'r mut Reader<'b>,
    path: Place,
}

impl Walk<Pending, Join, Box<dyn Any>> for Reading<'_, '_> {
    type Error = DecodeError;

    fn path(&mut self) -> &mut Place {
        &mut self.path
    }

    fn next(
        &mut self,
        frame: &mut Frame<Pending, Join, Box<dyn Any>>,
    ) -> Result<Option<Begun<Pending, Join, Box<dyn Any>>>, DecodeError> {
        let open = match &mut frame.parts {
            Pending::Each(opens) => opens.pop(),
            Pending::Items(open, left) => {
                let open = *open;
                left.checked_sub(1).map(|rest| {
                    *left = rest;
                    open
                })
            }
        };
        open.map(|open| open(self.reader).map(|opened| opened.0))
            .transpose()
    }

    fn steps(_: &Frame<Pending, Join, Box<dyn Any>>) -> usize {
        0
    }

    fn finish(
        &mut self,
        frame: Frame<Pending, Join, Box<dyn Any>>,
    ) -> Result<Box<dyn Any>, DecodeError> {
        Ok((frame.make)(&mut Joined(frame.values.into_iter())))
    }
}

/// The parts of a value, built, in the order its open listed them.
#[derive(Debug)]
pub struct Joined(std::vec::IntoIter<Box<dyn Any>>);

impl Joined {
    /// The next part, a `T`.
    ///
    /// # Panics
    ///
    /// When no part is left or it is not a `T`: a join takes exactly the
    /// parts its open listed.
    pub fn part<T: 'static>(&mut self) -> T {
        *self
            .0
            .next()
            .and_then(|part| part.downcast().ok())
            .expect("a join takes the parts its open listed")
    }

    /// Every part left, each a `T`.
    fn rest<T: 'static>(&mut self) -> Vec<T> {
        let mut items = Vec::with_capacity(self.0.len());
        while self.0.len() > 0 {
            items.push(self.part());
        }
        items
    }
}

/// A type [`wire!`](crate::wire!) or [`wire_impl!`](crate::wire_impl!)
/// declared, whose [`Shape`] is data.
pub trait Declared: Shaped {
    /// Its declaration, the only one.
    const SHAPE: Shape;

    /// Its shape.
    fn shape() -> &'static Shape {
        &Self::SHAPE
    }
}

/// An enum written as one constructor's payload alone, its constructor
/// told apart outside the bytes, as a host note's name tells which note it
/// is (`trace.md`, *Host notes*). [`wire!`](crate::wire!) gives it to
/// every enum, whose [`Wire::write`] is its constructor's number and then
/// this.
pub trait Keyed: Declared + Wire {
    /// Pushes its payload's parts to `parts`, in the order they are
    /// written, without its constructor's number.
    fn payload<'a>(&'a self, parts: &mut Vec<&'a dyn AnyWire>);

    /// Opens the payload of the constructor written with `number`, the
    /// number read at byte `at`.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when no constructor is written with `number`.
    fn open_payload(number: u64, at: usize) -> Result<Opened, DecodeError>;

    /// Its payload's bytes.
    fn payload_bytes(&self) -> Vec<u8> {
        let mut parts = Vec::new();
        self.payload(&mut parts);
        let mut out = Vec::new();
        write_parts(&mut out, parts);
        out
    }

    /// The one value of the constructor written with `number` whose
    /// payload `bytes` hold, and nothing else.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when no constructor is written with `number`,
    /// the bytes are not its payload's, or bytes are left over.
    fn decode_payload(number: u64, bytes: &[u8]) -> Result<Self, DecodeError> {
        whole(bytes, |_| Self::open_payload(number, 0))
    }
}

/// `T`'s form, as a [`WireForm`] holds a part's.
pub fn form_of<T: Shaped>() -> WireForm {
    T::FORM
}

/// Whether no form in `forms` but the last is [`WireForm::Rest`], which
/// [`wire!`](crate::wire!) holds every declaration to.
pub const fn rest_is_last(forms: &[WireForm]) -> bool {
    let mut at = 0;
    while at + 1 < forms.len() {
        if matches!(forms[at], WireForm::Rest) {
            return false;
        }
        at += 1;
    }
    true
}

/// Whether no two of `ctors` have one number, which [`wire!`](crate::wire!)
/// holds every enum to.
pub const fn numbers_are_distinct(ctors: &[Ctor]) -> bool {
    let mut at = 0;
    while at < ctors.len() {
        let mut other = at + 1;
        while other < ctors.len() {
            if ctors[at].number == ctors[other].number {
                return false;
            }
            other += 1;
        }
        at += 1;
    }
    true
}

/// The refusal of a constructor number `shape` has no constructor for,
/// read at byte `at`.
pub fn unknown(shape: &Shape, number: u64, at: usize) -> DecodeError {
    DecodeError::of(
        &Place::default(),
        DecodeErrorKind::Mismatch,
        format!(
            "names constructor {number}, which {} does not have, at byte {at}",
            shape.name
        ),
    )
}

/// A message's texts and bytes are bounded by its own length.
pub const MESSAGE: Limits = Limits {
    text_bytes: usize::MAX,
    ..Limits::LANGUAGE
};

/// The position of the constructor a declared message writes with `number`
/// among its type's constructors, which number them from 0.
///
/// # Panics
///
/// Never on a 64-bit target; on a narrower one, for a number past its
/// `usize`.
pub fn position(number: u64) -> usize {
    usize::try_from(number).expect("a constructor number fits a usize")
}

// === The forms ==============================================================

impl Shaped for flow_value::Int {
    const FORM: WireForm = WireForm::Int;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.int(ty, self)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.int(ty)
    }
}

impl Wire for flow_value::Int {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        write_int(out, self.as_bigint());
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        Ok(Opened::built(flow_value::Int::from(reader.int(&MESSAGE)?)))
    }
}

impl Shaped for bool {
    const FORM: WireForm = WireForm::Bool;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.bool(ty, *self)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.bool(ty)
    }
}

impl Wire for bool {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        out.push(u8::from(*self));
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        Ok(Opened::built(reader.bool()?))
    }
}

impl Shaped for String {
    const FORM: WireForm = WireForm::Text;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.text(ty, self)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.text(ty).map(str::to_owned)
    }
}

impl Wire for String {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        write_text(out, self);
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        Ok(Opened::built(reader.text(&MESSAGE)?.to_owned()))
    }
}

impl Shaped for flow_value::Bytes {
    const FORM: WireForm = WireForm::Bytes;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.bytes(ty, self.as_slice())
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.bytes(ty).map(flow_value::Bytes::new)
    }
}

impl Wire for flow_value::Bytes {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        write_bytes(out, self.as_slice());
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        Ok(Opened::built(flow_value::Bytes::new(
            reader.bytes(&MESSAGE)?,
        )))
    }
}

/// An OS string is written as its bytes, as `Bytes` is, never through a
/// lossy text: the platform's own encoding of it, which off Unix is a superset
/// of UTF-8. Off Unix it reads back only when those bytes are UTF-8, and is
/// refused otherwise.
impl Shaped for std::ffi::OsString {
    const FORM: WireForm = WireForm::Bytes;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.bytes(ty, self.as_encoded_bytes())
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        os_string(input.bytes(ty))
    }
}

impl Wire for std::ffi::OsString {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        write_bytes(out, self.as_encoded_bytes());
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        os_string(reader.bytes(&MESSAGE)).map(Opened::built)
    }
}

/// The OS string written as the bytes read.
#[cfg(unix)]
fn os_string(bytes: Result<&[u8], DecodeError>) -> Result<std::ffi::OsString, DecodeError> {
    use std::os::unix::ffi::OsStringExt as _;
    bytes.map(|bytes| std::ffi::OsString::from_vec(bytes.to_vec()))
}

/// The OS string written as the bytes read, which must be UTF-8: the one
/// encoding of an OS string read here without unsafe code.
#[cfg(not(unix))]
fn os_string(bytes: Result<&[u8], DecodeError>) -> Result<std::ffi::OsString, DecodeError> {
    std::str::from_utf8(bytes?)
        .map(std::ffi::OsString::from)
        .map_err(|_| {
            DecodeError::of(
                &Place::default(),
                DecodeErrorKind::Mismatch,
                "holds an OS string that is not UTF-8, which this platform does not read"
                    .to_owned(),
            )
        })
}

impl Shaped for flow_value::Instant {
    const FORM: WireForm = WireForm::Instant;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.instant(ty, self)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.instant(ty)
    }
}

impl Wire for flow_value::Instant {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        write_instant(out, self);
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        Ok(Opened::built(read_instant(reader, &Limits::LANGUAGE)?))
    }
}

/// A run of exactly `N` bytes, written as `Bytes` are: a run of any other
/// length is not one.
impl<const N: usize> Shaped for [u8; N] {
    const FORM: WireForm = WireForm::Bytes;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.bytes(ty, self)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.bytes(ty)?.try_into().map_err(|_| input.mismatch(ty))
    }
}

impl<const N: usize> Wire for [u8; N] {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        write_bytes(out, self);
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        let at = reader.position();
        let bytes: [u8; N] = reader.bytes(&MESSAGE)?.try_into().map_err(|_| {
            DecodeError::of(
                &Place::default(),
                DecodeErrorKind::Mismatch,
                format!("has bytes at byte {at} that are not {N} long"),
            )
        })?;
        Ok(Opened::built(bytes))
    }
}

/// A digest is written as its 32 bytes.
impl Shaped for crate::Digest {
    const FORM: WireForm = WireForm::Bytes;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        self.0.write_at(out, ty)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        <[u8; 32]>::read_at(input, ty).map(crate::Digest)
    }
}

impl Wire for crate::Digest {
    fn write_head<'a>(&'a self, _: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
        parts.push(&self.0);
    }

    fn open(_: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        Ok(Opened::parts(
            |parts| -> Box<dyn Any> { Box::new(crate::Digest(parts.part())) },
            &[<[u8; 32]>::open],
        ))
    }
}

/// A form no Flow type has: its values are none of a Flow type's.
macro_rules! unshaped {
    ($rust:ty, $form:expr) => {
        impl Shaped for $rust {
            const FORM: WireForm = $form;

            fn write_at(
                &self,
                out: &mut ValueWriter<'_, '_>,
                ty: &Type,
            ) -> Result<(), EncodeError> {
                Err(out.refuse(ty))
            }

            fn read_at(
                input: &mut ValueReader<'_, '_, '_>,
                ty: &Type,
            ) -> Result<Self, DecodeError> {
                Err(input.mismatch(ty))
            }
        }
    };
}

unshaped!(RunId, WireForm::RunId);

/// A run id is its 16 bits, most significant byte first, with no length
/// (`abi.md`, *Numbers and text*).
impl Wire for RunId {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        out.extend_from_slice(&self.bits());
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        let mut bits = [0; 16];
        bits.copy_from_slice(reader.take(16)?);
        Ok(Opened::built(RunId::from_bits(bits)))
    }
}

unshaped!(CallRef, WireForm::CallRef);

/// A call id is written as history writes it (`trace.md`, *Facts*): its
/// segment, its task id and its counter.
impl Wire for CallRef {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        write_uint(out, self.segment());
        write_task(out, self.task());
        write_uint(out, self.index().get());
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        let segment = reader.uint()?;
        let task = read_task(reader)?;
        let at = reader.position();
        let index = NonZeroU64::new(reader.uint()?)
            .ok_or_else(|| zero(at, "a call's counter, which counts from 1"))?;
        Ok(Opened::built(CallRef::new(segment, task, index)))
    }
}

/// Writes `task`'s id: how many spawn counters its path has, then those
/// counters (`trace.md`, *Facts*).
pub fn write_task(out: &mut Vec<u8>, task: &TaskPath) {
    write_uint(out, wide(task.counts().len()));
    for count in task.counts() {
        write_uint(out, count.get());
    }
}

/// Reads a task id [`write_task`] wrote.
///
/// # Errors
///
/// A [`DecodeError`] when the input ends inside it or a counter is `0`.
pub fn read_task(reader: &mut Reader<'_>) -> Result<TaskPath, DecodeError> {
    let at = reader.position();
    let count = reader.count()?;
    if count > reader.remaining() {
        return Err(DecodeError::of(
            &Place::default(),
            DecodeErrorKind::Syntax { at },
            format!("has a task id of {count} counters at byte {at}, past its end"),
        ));
    }
    let mut counts = Vec::with_capacity(count);
    for _ in 0..count {
        let at = reader.position();
        counts.push(
            NonZeroU64::new(reader.uint()?)
                .ok_or_else(|| zero(at, "a spawn counter, which counts from 1"))?,
        );
    }
    Ok(TaskPath::new(counts))
}

/// The error of a `0` at byte `at` where `what` stands.
fn zero(at: usize, what: &str) -> DecodeError {
    DecodeError::of(
        &Place::default(),
        DecodeErrorKind::Mismatch,
        format!("has 0 for {what}, at byte {at}"),
    )
}

unshaped!(u64, WireForm::Number);

impl Wire for u64 {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        write_uint(out, *self);
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        Ok(Opened::built(reader.uint()?))
    }
}

/// Every byte left in a message, unframed: a part whose type the message's
/// head names, read once the head is.
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct Rest(pub Vec<u8>);

unshaped!(Rest, WireForm::Rest);

impl Wire for Rest {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
        out.extend_from_slice(&self.0);
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        Ok(Opened::built(Rest(
            reader.take(reader.remaining())?.to_vec(),
        )))
    }
}

impl<T: Shaped> Shaped for Box<T> {
    const FORM: WireForm = T::FORM;

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        T::write_at(self, out, ty)
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        T::read_at(input, ty).map(Box::new)
    }
}

impl<T: Wire> Wire for Box<T> {
    fn write_head<'a>(&'a self, _: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
        parts.push(&**self);
    }

    fn open(_: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        Ok(Opened::parts(
            |parts| -> Box<dyn Any> { Box::new(Box::new(parts.part::<T>())) },
            &[T::open],
        ))
    }
}

impl<T: Shaped> Shaped for Option<T> {
    const FORM: WireForm = WireForm::Option(form_of::<T>);

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        let ctors = &out.catalog().option().ctors;
        match self {
            None => out.variant(ty, ctors.index(OptionCtor::None), &[]),
            Some(value) => out.variant(ty, ctors.index(OptionCtor::Some), &[value]),
        }
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        if !matches!(ty, Type::Option(_)) {
            return Err(input.mismatch(ty));
        }
        input.variant(ty, |input, index, payload| {
            match input.catalog().option().ctors.which(index) {
                Some(OptionCtor::None) => Ok(None),
                Some(OptionCtor::Some) => payload.read(input).map(Some),
                None => Err(input.mismatch(ty)),
            }
        })
    }
}

impl<T: Wire> Wire for Option<T> {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
        match self {
            None => write_uint(out, NONE),
            Some(item) => {
                write_uint(out, SOME);
                parts.push(item);
            }
        }
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        let at = reader.position();
        match reader.uint()? {
            NONE => Ok(Opened::built(None::<T>)),
            SOME => Ok(Opened::parts(
                |parts| -> Box<dyn Any> { Box::new(Some(parts.part::<T>())) },
                &[T::open],
            )),
            other => Err(DecodeError::of(
                &Place::default(),
                DecodeErrorKind::Mismatch,
                format!("names constructor {other}, which Option does not have, at byte {at}"),
            )),
        }
    }
}

/// std's `Result`: `Ok` then `Err`, as std declares them, whichever
/// numbers a catalog gives them.
impl<T: Shaped, E: Shaped> Shaped for Result<T, E> {
    const FORM: WireForm = WireForm::Std {
        module: "",
        name: "Result",
        args: &[form_of::<T>, form_of::<E>],
    };

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        match self {
            Ok(value) => out.variant(ty, position(OK), &[value]),
            Err(error) => out.variant(ty, position(ERR), &[error]),
        }
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.variant(ty, |input, at, payload| match wide(at) {
            OK => payload.read(input).map(Ok),
            ERR => payload.read(input).map(Err),
            _ => Err(input.mismatch(ty)),
        })
    }
}

impl<T: Wire, E: Wire> Wire for Result<T, E> {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
        match self {
            Ok(value) => {
                write_uint(out, OK);
                parts.push(value);
            }
            Err(error) => {
                write_uint(out, ERR);
                parts.push(error);
            }
        }
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        let at = reader.position();
        match reader.uint()? {
            OK => Ok(Opened::parts(
                |parts| -> Box<dyn Any> { Box::new(Ok::<T, E>(parts.part::<T>())) },
                &[T::open],
            )),
            ERR => Ok(Opened::parts(
                |parts| -> Box<dyn Any> { Box::new(Err::<T, E>(parts.part::<E>())) },
                &[E::open],
            )),
            other => Err(DecodeError::of(
                &Place::default(),
                DecodeErrorKind::Mismatch,
                format!("names constructor {other}, which Result does not have, at byte {at}"),
            )),
        }
    }
}

impl<T: Shaped> Shaped for Vec<T> {
    const FORM: WireForm = WireForm::List(form_of::<T>);

    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
        out.list(ty, self.iter())
    }

    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
        input.list(ty)
    }
}

impl<T: Wire> Wire for Vec<T> {
    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
        write_uint(out, wide(self.len()));
        parts.extend(self.iter().map(|item| -> &dyn AnyWire { item }));
    }

    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        let count = reader.count()?;
        Ok(Opened::items(
            |parts| -> Box<dyn Any> { Box::new(parts.rest::<T>()) },
            T::open,
            count,
            reader,
        ))
    }
}

impl<A: Wire, B: Wire> Wire for (A, B) {
    fn write_head<'a>(&'a self, _: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
        parts.push(&self.0);
        parts.push(&self.1);
    }

    fn open(_: &mut Reader<'_>) -> Result<Opened, DecodeError> {
        Ok(Opened::parts(
            |parts| -> Box<dyn Any> { Box::new((parts.part::<A>(), parts.part::<B>())) },
            &[A::open, B::open],
        ))
    }
}

// === Projection =============================================================

/// The declarations a projection makes, each shape's by its address: two
/// shapes of one name are two declarations.
type Ids = HashMap<*const Shape, DeclId>;

impl Shape {
    /// Its constructors; none for a record.
    pub fn ctors(&self) -> &'static [Ctor] {
        match self.layout {
            Layout::Record(_) | Layout::Newtype(_) | Layout::Host => &[],
            Layout::Enum(ctors) => ctors,
        }
    }

    /// Each constructor's name as a constant spells it, the shape's name
    /// and the constructor's in capitals joined by `_`, and its number:
    /// `TERM_JSON_VALUE` for `Term::JsonValue`. A toolkit in another
    /// language takes its numbers from these.
    pub fn constants(&self) -> Vec<(String, u64)> {
        let constant = |name: &str| {
            let mut out = String::new();
            for (at, letter) in name.chars().enumerate() {
                if letter.is_uppercase() && at > 0 {
                    out.push('_');
                }
                out.push(letter.to_ascii_uppercase());
            }
            out
        };
        self.ctors()
            .iter()
            .map(|ctor| {
                (
                    format!("{}_{}", constant(self.name), constant(ctor.name)),
                    ctor.number,
                )
            })
            .collect()
    }

    /// `catalog` with this shape and every shape it reaches declared, and
    /// the type this shape is there, as [`project`] gives them.
    ///
    /// # Panics
    ///
    /// As [`project`]'s.
    pub fn project(&'static self, catalog: &Catalog) -> Option<(Catalog, Type)> {
        let (extended, ids) = declared(vec![self], catalog)?;
        Some((
            extended,
            Type::Named(ids[&std::ptr::from_ref(self)], Vec::new()),
        ))
    }

    /// Calls `visit` with each part's form, in declaration order.
    fn each_form(&self, mut visit: impl FnMut(WireForm)) {
        match self.layout {
            Layout::Record(fields) => fields.iter().for_each(|field| visit(field.form)),
            Layout::Newtype(base) => visit(base),
            Layout::Host => {}
            Layout::Enum(ctors) => {
                for ctor in ctors {
                    match ctor.parts {
                        Parts::Empty => {}
                        Parts::Positional(forms) => forms.iter().copied().for_each(&mut visit),
                        Parts::Named(fields) => fields.iter().for_each(|field| visit(field.form)),
                    }
                }
            }
        }
    }

    /// This shape's declaration, of lexical ordinal `ordinal`, each shape
    /// it names by its id in `ids`.
    fn decl(&self, ordinal: u32, ids: &Ids, catalog: &Catalog) -> Option<Decl> {
        let ty = |form| projected(form, ids, catalog);
        let body = match self.layout {
            Layout::Record(fields) => Body::Record(
                RecordShape::new(self.name, fields.iter().map(|field| field.name)),
                fields
                    .iter()
                    .map(|field| ty(field.form))
                    .collect::<Option<_>>()?,
            ),
            Layout::Enum(ctors) => {
                let mut constructors = Vec::new();
                let mut payloads = Vec::new();
                for (at, ctor) in ctors.iter().enumerate() {
                    if ctor.number != wide(at) {
                        return None;
                    }
                    let (payload, parts) = match ctor.parts {
                        Parts::Empty => (Payload::None, Vec::new()),
                        Parts::Positional(forms) => (
                            Payload::Positional(forms.len()),
                            forms.iter().map(|form| ty(*form)).collect::<Option<_>>()?,
                        ),
                        Parts::Named(fields) => (
                            Payload::Named(
                                fields.iter().map(|field| Arc::from(field.name)).collect(),
                            ),
                            fields
                                .iter()
                                .map(|field| ty(field.form))
                                .collect::<Option<_>>()?,
                        ),
                    };
                    constructors.push(Constructor::new(ctor.name, payload));
                    payloads.push(parts);
                }
                Body::Enum(EnumShape::new(self.name, constructors), payloads)
            }
            Layout::Newtype(base) => Body::Newtype(ty(base)?),
            Layout::Host => Body::Host,
        };
        Some(Decl {
            lexical_ordinal: ordinal,
            identity: Identity {
                origin: ModulePath::new(Tree::Local, None, Segments::from_names(["abi"])?),
                version: None,
                name: self.name.to_owned(),
            },
            doc: None,
            members: Vec::new(),
            params: self.params.iter().map(|name| (*name).to_owned()).collect(),
            opaque: false,
            body,
        })
    }
}

/// `catalog` with the shape a value of `form`'s Rust type is declared
/// after its own declarations, with every shape it reaches, in first-reach
/// order, and the Flow type of `form` there. `Option` is std's, whose
/// constructors the catalog found by name, and a std form names the
/// declaration of its module and name that `catalog` holds; a std form of
/// no module, such as `Result`'s, names the std declaration of its name.
/// Shapes of one name are told apart by their lexical ordinals, in the
/// order they are reached. `None` when a shape it reaches has a form with
/// no Flow type, such as a [`WireForm::Number`] or a [`WireForm::Rest`],
/// names a std declaration `catalog` does not hold, or numbers a
/// constructor other than by its position: no Flow type writes those bytes.
///
/// # Panics
///
/// When the catalog and the shapes hold more declarations than a 32-bit
/// id numbers.
pub fn project(form: WireForm, catalog: &Catalog) -> Option<(Catalog, Type)> {
    let mut roots = Vec::new();
    reaches(form, &mut roots);
    let (extended, ids) = declared(roots, catalog)?;
    let ty = projected(form, &ids, catalog)?;
    Some((extended, ty))
}

/// `catalog` with `roots` and every shape they reach declared after its
/// own declarations, in first-reach order, and the id each shape has.
fn declared(roots: Vec<&'static Shape>, catalog: &Catalog) -> Option<(Catalog, Ids)> {
    let first = catalog.decls().len();
    let mut order: Vec<&'static Shape> = Vec::new();
    let mut ids = Ids::new();
    let mut pending: Vec<&'static Shape> = roots.into_iter().rev().collect();
    while let Some(shape) = pending.pop() {
        if ids.contains_key(&std::ptr::from_ref(shape)) {
            continue;
        }
        let id = u32::try_from(first + order.len()).expect("a catalog fits 32-bit ids");
        ids.insert(std::ptr::from_ref(shape), DeclId(id));
        order.push(shape);
        let mut reached = Vec::new();
        shape.each_form(|form| reaches(form, &mut reached));
        pending.extend(reached.into_iter().rev());
    }
    let mut ordinals: HashMap<&str, u32> = HashMap::new();
    let decls = order
        .iter()
        .map(|shape| {
            let ordinal = ordinals.entry(shape.name).or_default();
            *ordinal += 1;
            shape.decl(*ordinal, &ids, catalog)
        })
        .collect::<Option<Vec<Decl>>>()?;
    Some((catalog.extended(decls), ids))
}

/// The std declaration `catalog` holds for the std form of `module` and
/// `name`; a form of no module names a declaration of std's prelude.
fn std_decl(catalog: &Catalog, module: &str, name: &str) -> Option<DeclId> {
    catalog.decls().find_map(|(id, decl)| {
        let origin = &decl.identity.origin;
        (*origin.tree() == Tree::Std
            && decl.identity.name == name
            && (module.is_empty() || *origin.segments() == module))
            .then_some(id)
    })
}

/// Pushes the declared shapes `form` names onto `reached`, in order.
fn reaches(form: WireForm, reached: &mut Vec<&'static Shape>) {
    match form {
        WireForm::Int
        | WireForm::Decimal
        | WireForm::Bool
        | WireForm::Text
        | WireForm::Bytes
        | WireForm::Duration
        | WireForm::Instant
        | WireForm::Unit
        | WireForm::Never
        | WireForm::RunId
        | WireForm::CallRef
        | WireForm::Number
        | WireForm::Rest
        | WireForm::Param(_) => {}
        WireForm::Option(item) | WireForm::List(item) | WireForm::Set(item) => {
            reaches(item(), reached);
        }
        WireForm::Dict(key, value) => {
            reaches(key(), reached);
            reaches(value(), reached);
        }
        WireForm::Tuple(parts) | WireForm::Std { args: parts, .. } => {
            for part in parts {
                reaches(part(), reached);
            }
        }
        WireForm::Declared(shape) => reached.push(shape()),
        WireForm::Applied(shape, args) => {
            reached.push(shape());
            for arg in args {
                reaches(arg(), reached);
            }
        }
    }
}

/// The Flow type of `form`, each shape it names by its id in `ids` and
/// each std form by its declaration in `catalog`.
fn projected(form: WireForm, ids: &Ids, catalog: &Catalog) -> Option<Type> {
    let all = |forms: &[fn() -> WireForm]| {
        forms
            .iter()
            .map(|part| projected(part(), ids, catalog))
            .collect::<Option<Vec<Type>>>()
    };
    Some(match form {
        WireForm::Int => Type::Int,
        WireForm::Decimal => Type::Decimal,
        WireForm::Bool => Type::Bool,
        WireForm::Text => Type::Text,
        WireForm::Bytes => Type::Bytes,
        WireForm::Duration => Type::Duration,
        WireForm::Instant => Type::Instant,
        WireForm::Unit => Type::Unit,
        WireForm::Never => Type::Never,
        WireForm::RunId | WireForm::CallRef | WireForm::Number | WireForm::Rest => return None,
        WireForm::Std {
            module: "json",
            name: "Value",
            args: [],
        } => Type::Json,
        WireForm::Std { module, name, args } => {
            Type::Named(std_decl(catalog, module, name)?, all(args)?)
        }
        WireForm::Option(item) => Type::option(projected(item(), ids, catalog)?),
        WireForm::List(item) => Type::list(projected(item(), ids, catalog)?),
        WireForm::Set(item) => Type::set(projected(item(), ids, catalog)?),
        WireForm::Dict(key, value) => Type::dict(
            projected(key(), ids, catalog)?,
            projected(value(), ids, catalog)?,
        ),
        WireForm::Tuple(parts) => Type::Tuple(all(parts)?),
        WireForm::Param(at) => Type::Param(u32::try_from(at).ok()?),
        WireForm::Declared(shape) => Type::Named(ids[&std::ptr::from_ref(shape())], Vec::new()),
        WireForm::Applied(shape, args) => {
            Type::Named(ids[&std::ptr::from_ref(shape())], all(args)?)
        }
    })
}

// === The macro ==============================================================

/// Declares a record or an enum once: the type itself, its
/// [`Wire`](crate::wire::Wire) codec and its [`Shape`](crate::wire::Shape).
/// Doc comments and attributes pass through.
///
/// ```
/// use flow_abi::wire::{Keyed, Wire};
///
/// flow_abi::wire! {
///     /// What a request asks for.
///     #[derive(Clone, Debug, PartialEq)]
///     pub enum Request {
///         /// What the server is doing.
///         Status,
///         /// Move, by three flags.
///         Move(bool, String, bool),
///         /// Stop, and why.
///         Stop { reason: String } = 5,
///     }
///     /// Which request one is.
///     pub enum RequestKind;
/// }
///
/// let stop = Request::Stop { reason: "done".to_owned() };
/// assert_eq!(stop.bytes(), [5, 4, b'd', b'o', b'n', b'e']);
/// assert_eq!(Request::decode(&stop.bytes()), Ok(stop.clone()));
/// assert_eq!(stop.payload_bytes(), [4, b'd', b'o', b'n', b'e']);
/// assert_eq!(Request::decode_payload(5, &stop.payload_bytes()), Ok(stop));
/// let moved = Request::Move(true, "a".to_owned(), false);
/// assert_eq!(moved.bytes(), [1, 1, 1, b'a', 0]);
/// assert_eq!(Request::decode(&moved.bytes()), Ok(moved));
/// assert_eq!(RequestKind::of(5), Some(RequestKind::Stop));
/// assert_eq!(RequestKind::Status.number(), 0);
/// ```
///
/// A constructor's number is its position unless given after `=`. An enum
/// may take type parameters, each a part's type, and may name after it a
/// fieldless companion enum of its constructors' kinds, which for an enum
/// with type parameters needs each to have a default; an enum whose
/// constructors carry nothing names itself, `enum Self;`.
///
/// A declaration that could not read back what it writes does not compile:
/// a [`Rest`](crate::wire::Rest) before the last part of a record, a named
/// payload or a positional one,
///
/// ```compile_fail,E0080
/// flow_abi::wire! {
///     pub enum Message {
///         Case(flow_abi::wire::Rest, String),
///     }
/// }
/// ```
///
/// and two constructors of one number.
///
/// ```compile_fail,E0080
/// flow_abi::wire! {
///     pub enum Message {
///         A = 5,
///         B = 5,
///     }
/// }
/// ```
#[macro_export]
macro_rules! wire {
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            $( $(#[$field_meta:meta])* $field_vis:vis $field:ident : $ty:ty ),* $(,)?
        }
    ) => {
        $(#[$meta])*
        $vis struct $name {
            $( $(#[$field_meta])* $field_vis $field : $ty ),*
        }

        const _: () = assert!(
            $crate::wire::rest_is_last(&[$( <$ty as $crate::wire::Shaped>::FORM ),*]),
            "only a message's last field may be its rest"
        );

        impl $crate::wire::Declared for $name {
            const SHAPE: $crate::wire::Shape = $crate::wire::Shape {
                name: stringify!($name),
                params: &[],
                layout: $crate::wire::Layout::Record(&[$(
                    $crate::wire::Field {
                        name: stringify!($field),
                        form: <$ty as $crate::wire::Shaped>::FORM,
                    }
                ),*]),
                notes: None,
            };
        }

        impl $crate::wire::Shaped for $name {
            const FORM: $crate::wire::WireForm =
                $crate::wire::WireForm::Declared(<Self as $crate::wire::Declared>::shape);

            fn write_at(
                &self,
                out: &mut $crate::wire::ValueWriter<'_, '_>,
                ty: &$crate::wire::Type,
            ) -> Result<(), $crate::EncodeError> {
                out.record(ty, &[$( &self.$field ),*])
            }

            fn read_at(
                input: &mut $crate::wire::ValueReader<'_, '_, '_>,
                ty: &$crate::wire::Type,
            ) -> Result<Self, $crate::DecodeError> {
                input.record(ty, |input, fields| {
                    let _ = (&input, &fields);
                    Ok(Self { $( $field: fields.read::<$ty>(input)?, )* })
                })
            }
        }

        impl $crate::wire::Wire for $name {
            fn write_head<'a>(
                &'a self,
                _: &mut Vec<u8>,
                parts: &mut Vec<&'a dyn $crate::wire::AnyWire>,
            ) {
                let _ = &parts;
                $( parts.push(&self.$field); )*
            }

            fn open(
                _: &mut $crate::primitives::Reader<'_>,
            ) -> Result<$crate::wire::Opened, $crate::DecodeError> {
                Ok($crate::wire::Opened::parts(
                    |parts| -> Box<dyn ::std::any::Any> {
                        Box::new(Self { $( $field: parts.part::<$ty>(), )* })
                    },
                    &[$( <$ty as $crate::wire::Wire>::open ),*],
                ))
            }
        }
    };

    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident $( < $( $gen:ident $( = $default:ty )? ),+ > )? {
            $(
                $(#[$variant_meta:meta])*
                $variant:ident
                $( ( $($part:ty),+ $(,)? ) )?
                $( { $( $(#[$member_meta:meta])* $member:ident : $member_ty:ty ),* $(,)? } )?
                $( = $number:literal )?
            ),* $(,)?
        }
        $($kind:tt)*
    ) => {
        $(#[$meta])*
        $vis enum $name $( < $( $gen $( = $default )? ),+ > )? {
            $(
                $(#[$variant_meta])*
                $variant
                $( ( $($part),+ ) )?
                $( { $( $(#[$member_meta])* $member : $member_ty ),* } )?
            ),*
        }

        $crate::wire!(@enum $name [$( $($gen),+ )?] [out head catalog ty parts] [0u64] [] [] [] [] [] $(
            $variant
            $( ( $($part),+ ) )?
            $( { $( $member : $member_ty ),* } )?
            $( = $number )?;
        )*);

        $crate::wire!(@kind $name [$( $($gen),+ )?] [$( $(#[$variant_meta])* $variant )*]
            $($kind)*);
    };

    (@number $at:expr) => { $at };
    (@number $at:expr, $number:literal) => { $number };

    // No companion of kinds.
    (@kind $name:ident $gens:tt [$( $(#[$variant_meta:meta])* $variant:ident )*]) => {};

    // An enum whose constructors carry nothing, its own kinds.
    (@kind $name:ident [] [$( $(#[$variant_meta:meta])* $variant:ident )*] enum Self;) => {
        $crate::wire!(@kinds $name $name [$( $variant )*]);
    };

    // The companion of kinds; an enum with type parameters names its
    // companion's constructors by the shape its defaults give it.
    (@kind $name:ident [$( $gen:ident ),*] [$( $(#[$variant_meta:meta])* $variant:ident )*]
        $(#[$kind_meta:meta])* $kind_vis:vis enum $kind:ident;
    ) => {
        $(#[$kind_meta])*
        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
        $kind_vis enum $kind {
            $( $(#[$variant_meta])* $variant ),*
        }

        $crate::wire!(@kinds $name $kind [$( $variant )*]);

        impl<$( $gen ),*> $name<$( $gen ),*> {
            /// Which constructor it is.
            pub fn kind(&self) -> $kind {
                match self {
                    $( Self::$variant { .. } => $kind::$variant, )*
                }
            }
        }
    };

    (@kinds $name:ident $kind:ident [$( $variant:ident )*]) => {
        impl $kind {
            /// Every kind, in declaration order.
            pub const ALL: &'static [$kind] = &[$( $kind::$variant ),*];

            /// Its constructor's declaration.
            pub fn ctor(self) -> &'static $crate::wire::Ctor {
                let at = $crate::wire!(@position self $kind [] 0usize; $( $variant )*);
                &<$name as $crate::wire::Declared>::shape().ctors()[at]
            }

            /// The number its constructor is written with.
            pub fn number(self) -> u64 {
                self.ctor().number
            }

            /// The kind whose constructor is written with `number`, if any.
            pub fn of(number: u64) -> Option<$kind> {
                let at = <$name as $crate::wire::Declared>::shape()
                    .ctors()
                    .iter()
                    .position(|ctor| ctor.number == number)?;
                Some(Self::ALL[at])
            }
        }
    };

    // A kind's position among its enum's constructors, by one match: an
    // enum that is its own kinds may give its constructors numbers, which
    // are then its discriminants, so a cast would give the number and not
    // the position.
    (@position $self:ident $kind:ident [$( $arms:tt )*] $at:expr;) => {
        match $self { $( $arms )* }
    };
    (@position $self:ident $kind:ident [$( $arms:tt )*] $at:expr; $variant:ident $( $rest:ident )*) => {
        $crate::wire!(@position $self $kind [$( $arms )* $kind::$variant => $at,] $at + 1; $( $rest )*)
    };

    // A constructor with no payload.
    (@enum $name:ident $gens:tt [$out:ident $head:ident $catalog:ident $ty:ident $parts:ident] [$at:expr]
        [$($shape:tt)*] [$($write:tt)*] [$($open:tt)*] [$($value:tt)*] [$($of:tt)*]
        $variant:ident $( = $number:literal )?; $($rest:tt)*
    ) => {
        $crate::wire!(@enum $name $gens [$out $head $catalog $ty $parts] [$at + 1]
            [$($shape)* $crate::wire::Ctor {
                name: stringify!($variant),
                number: $crate::wire!(@number $at $(, $number)?),
                parts: $crate::wire::Parts::Empty,
            },]
            [$($write)* Self::$variant => {
                $head($out, $crate::wire!(@number $at $(, $number)?));
            }]
            [$($open)* number if number == $crate::wire!(@number $at $(, $number)?) => {
                $crate::wire::Opened::built(Self::$variant)
            }]
            [$($value)* Self::$variant => $catalog.variant(
                $ty, $crate::wire::position($crate::wire!(@number $at $(, $number)?)), &[],
            ),]
            [$($of)* index if u64::try_from(index).ok() == Some($at) => Self::$variant,]
            $($rest)*
        );
    };

    // A constructor of parts by position: each part gets a name of its own,
    // one at a time, and then the constructor is declared.
    (@enum $name:ident $gens:tt $context:tt $at:tt $shape:tt $write:tt $open:tt $value:tt $of:tt
        $variant:ident ( $($part:ty),+ ) $( = $number:literal )?; $($rest:tt)*
    ) => {
        $crate::wire!(@positional [$name $gens $context $at $shape $write $open $value $of]
            [$variant [$($number)?]] [] [$($part),+] $($rest)*
        );
    };

    (@positional $state:tt $variant:tt [$($named:tt)*] [$part:ty $(, $more:ty)*]
        $($rest:tt)*
    ) => {
        $crate::wire!(@positional $state $variant [$($named)* (part: $part)] [$($more),*]
            $($rest)*
        );
    };

    (@positional
        [$name:ident $gens:tt [$out:ident $head:ident $catalog:ident $ty:ident $parts:ident] [$at:expr]
            [$($shape:tt)*] [$($write:tt)*] [$($open:tt)*] [$($value:tt)*] [$($of:tt)*]]
        [$variant:ident [$($number:literal)?]] [$( ($each:ident : $each_ty:ty) )+] []
        $($rest:tt)*
    ) => {
        $crate::wire!(@enum $name $gens [$out $head $catalog $ty $parts] [$at + 1]
            [$($shape)* $crate::wire::Ctor {
                name: stringify!($variant),
                number: $crate::wire!(@number $at $(, $number)?),
                parts: $crate::wire::Parts::Positional(&[
                    $( <$each_ty as $crate::wire::Shaped>::FORM, )+
                ]),
            },]
            [$($write)* Self::$variant($($each),+) => {
                $head($out, $crate::wire!(@number $at $(, $number)?));
                $( $parts.push($each); )+
            }]
            [$($open)* number if number == $crate::wire!(@number $at $(, $number)?) => {
                const {
                    assert!(
                        $crate::wire::rest_is_last(
                            &[$( <$each_ty as $crate::wire::Shaped>::FORM ),+],
                        ),
                        "only a message's last field may be its rest"
                    );
                }
                $crate::wire::Opened::parts(
                    |parts| -> Box<dyn ::std::any::Any> {
                        Box::new(Self::$variant($( parts.part::<$each_ty>() ),+))
                    },
                    &[$( <$each_ty as $crate::wire::Wire>::open ),+],
                )
            }]
            [$($value)* Self::$variant($($each),+) => $catalog.variant(
                $ty, $crate::wire::position($crate::wire!(@number $at $(, $number)?)), &[$($each),+],
            ),]
            [$($of)* index if u64::try_from(index).ok() == Some($at) => Self::$variant(
                $( $parts.read::<$each_ty>($catalog)? ),+
            ),]
            $($rest)*
        );
    };

    // A constructor of named fields.
    (@enum $name:ident $gens:tt [$out:ident $head:ident $catalog:ident $ty:ident $parts:ident] [$at:expr]
        [$($shape:tt)*] [$($write:tt)*] [$($open:tt)*] [$($value:tt)*] [$($of:tt)*]
        $variant:ident { $( $member:ident : $member_ty:ty ),* } $( = $number:literal )?;
        $($rest:tt)*
    ) => {
        $crate::wire!(@enum $name $gens [$out $head $catalog $ty $parts] [$at + 1]
            [$($shape)* $crate::wire::Ctor {
                name: stringify!($variant),
                number: $crate::wire!(@number $at $(, $number)?),
                parts: $crate::wire::Parts::Named(&[$(
                    $crate::wire::Field {
                        name: stringify!($member),
                        form: <$member_ty as $crate::wire::Shaped>::FORM,
                    }
                ),*]),
            },]
            [$($write)* Self::$variant { $($member),* } => {
                $head($out, $crate::wire!(@number $at $(, $number)?));
                $( $parts.push($member); )*
            }]
            [$($open)* number if number == $crate::wire!(@number $at $(, $number)?) => {
                const {
                    assert!(
                        $crate::wire::rest_is_last(
                            &[$( <$member_ty as $crate::wire::Shaped>::FORM ),*],
                        ),
                        "only a message's last field may be its rest"
                    );
                }
                $crate::wire::Opened::parts(
                    |parts| -> Box<dyn ::std::any::Any> {
                        Box::new(Self::$variant { $( $member: parts.part::<$member_ty>(), )* })
                    },
                    &[$( <$member_ty as $crate::wire::Wire>::open ),*],
                )
            }]
            [$($value)* Self::$variant { $($member),* } => $catalog.variant(
                $ty, $crate::wire::position($crate::wire!(@number $at $(, $number)?)), &[$($member),*],
            ),]
            [$($of)* index if u64::try_from(index).ok() == Some($at) => Self::$variant {
                $( $member: $parts.read::<$member_ty>($catalog)?, )*
            },]
            $($rest)*
        );
    };

    // Every constructor taken: the impls.
    (@enum $name:ident [$($gen:ident),*] [$out:ident $head:ident $catalog:ident $ty:ident $parts:ident] [$at:expr]
        [$($shape:tt)*] [$($write:tt)*] [$($open:tt)*] [$($value:tt)*] [$($of:tt)*]
    ) => {
        impl<$($gen: $crate::wire::Shaped),*> $crate::wire::Declared for $name<$($gen),*> {
            const SHAPE: $crate::wire::Shape = $crate::wire::Shape {
                name: stringify!($name),
                params: &[],
                layout: $crate::wire::Layout::Enum(&[$($shape)*]),
                notes: None,
            };
        }

        impl<$($gen: $crate::wire::Shaped),*> $crate::wire::Shaped for $name<$($gen),*> {
            const FORM: $crate::wire::WireForm =
                $crate::wire::WireForm::Declared(<Self as $crate::wire::Declared>::shape);

            fn write_at(
                &self,
                $catalog: &mut $crate::wire::ValueWriter<'_, '_>,
                $ty: &$crate::wire::Type,
            ) -> Result<(), $crate::EncodeError> {
                match self {
                    $($value)*
                }
            }

            fn read_at(
                $catalog: &mut $crate::wire::ValueReader<'_, '_, '_>,
                $ty: &$crate::wire::Type,
            ) -> Result<Self, $crate::DecodeError> {
                $catalog.variant($ty, |$catalog, index, $parts| {
                    let _ = (&$catalog, &$parts);
                    Ok(match index {
                        $($of)*
                        _ => return Err($catalog.mismatch($ty)),
                    })
                })
            }
        }

        impl<$($gen: $crate::wire::Wire),*> $crate::wire::Keyed for $name<$($gen),*> {
            fn payload<'a>(&'a self, $parts: &mut Vec<&'a dyn $crate::wire::AnyWire>) {
                let $out = &mut Vec::new();
                let $head = |_: &mut Vec<u8>, _: u64| {};
                let _ = (&$out, &$parts);
                match self {
                    $($write)*
                }
            }

            fn open_payload(
                number: u64,
                at: usize,
            ) -> Result<$crate::wire::Opened, $crate::DecodeError> {
                const {
                    assert!(
                        $crate::wire::numbers_are_distinct(&[$($shape)*]),
                        "no two constructors may have one number"
                    );
                }
                Ok(match number {
                    $($open)*
                    other => {
                        return Err($crate::wire::unknown(
                            <Self as $crate::wire::Declared>::shape(),
                            other,
                            at,
                        ));
                    }
                })
            }
        }

        impl<$($gen: $crate::wire::Wire),*> $crate::wire::Wire for $name<$($gen),*> {
            fn write_head<'a>(
                &'a self,
                $out: &mut Vec<u8>,
                $parts: &mut Vec<&'a dyn $crate::wire::AnyWire>,
            ) {
                let $head = $crate::primitives::write_uint;
                let _ = &$parts;
                match self {
                    $($write)*
                }
            }

            fn open(
                reader: &mut $crate::primitives::Reader<'_>,
            ) -> Result<$crate::wire::Opened, $crate::DecodeError> {
                let at = reader.position();
                <Self as $crate::wire::Keyed>::open_payload(reader.uint()?, at)
            }
        }
    };
}

/// Gives a record, an enum or a newtype defined elsewhere its
/// [`Shape`](crate::wire::Shape) and its [`Shaped`](crate::wire::Shaped)
/// mapping, from its field list: `#[derive(Flow)]` expands to it. The
/// type's parameters come with their positions, and any bounds its
/// definition puts on them in brackets after `where`; each field, constructor
/// part and constructor field with its Flow name, and each part with the
/// name its value is bound to; and a constructor with its number, which is
/// its position, and whether its payload is `Empty`, `Positional` or
/// `Named`. Fields of `PhantomData` are listed after `phantom`, and
/// what the declaration's text says beside its shape after `notes`.
///
/// ```
/// use flow_abi::wire::{Declared, Layout, Shaped, WireForm};
///
/// pub struct Pair<T> {
///     pub first: T,
///     pub rest: Vec<T>,
/// }
/// pub enum Turn {
///     Stop,
///     Move(bool),
///     Say { text: String },
/// }
///
/// flow_abi::wire_impl! {
///     impl Pair [T = 0] record {
///         first "first": T,
///         rest "rest": Vec<T>,
///     } phantom []
/// }
/// flow_abi::wire_impl! {
///     impl Turn [] enum {
///         Stop = 0 Empty {},
///         Move = 1 Positional { 0 (flag) "": bool },
///         Say = 2 Named { text (text) "text": String },
///     }
/// }
///
/// assert!(matches!(<Pair<bool> as Shaped>::FORM, WireForm::Applied(..)));
/// assert!(matches!(<Turn as Declared>::shape().layout, Layout::Enum(ctors) if ctors.len() == 3));
/// ```
#[macro_export]
macro_rules! wire_impl {
    (
        impl $name:ident [$( $gen:ident = $index:literal ),*] $( where [$( $pred:tt )*] )? record {
            $( $field:tt $flow:literal : $ty:ty ),* $(,)?
        } phantom [$( $phantom:tt ),*] $( notes $notes:expr )?
    ) => {
        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Declared for $name<$( $gen ),*>
        where $( $( $pred )* )?
        {
            const SHAPE: $crate::wire::Shape = $crate::wire::Shape {
                name: stringify!($name),
                params: &[$( stringify!($gen) ),*],
                layout: $crate::wire::Layout::Record(&[$(
                    $crate::wire::Field {
                        name: $flow,
                        form: <$ty as $crate::wire::Shaped>::FORM,
                    }
                ),*]),
                notes: $crate::wire_impl!(@notes $( $notes )?),
            };
        }

        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Shaped for $name<$( $gen ),*>
        where $( $( $pred )* )?
        {
            const FORM: $crate::wire::WireForm =
                $crate::wire_impl!(@form $name [$( $gen = $index ),*]);

            fn write_at(
                &self,
                out: &mut $crate::wire::ValueWriter<'_, '_>,
                ty: &$crate::wire::Type,
            ) -> Result<(), $crate::EncodeError> {
                out.record(ty, &[$( &self.$field ),*])
            }

            fn read_at(
                input: &mut $crate::wire::ValueReader<'_, '_, '_>,
                ty: &$crate::wire::Type,
            ) -> Result<Self, $crate::DecodeError> {
                input.record(ty, |input, fields| {
                    let _ = (&input, &fields);
                    Ok(Self {
                        $( $field: fields.read::<$ty>(input)?, )*
                        $( $phantom: ::core::marker::PhantomData, )*
                    })
                })
            }
        }
    };

    (
        impl $name:ident [$( $gen:ident = $index:literal ),*] $( where [$( $pred:tt )*] )? enum {
            $(
                $variant:ident = $number:literal $kind:ident {
                    $( $member:tt ($bind:ident) $member_flow:literal : $member_ty:ty ),* $(,)?
                }
            ),* $(,)?
        } $( notes $notes:expr )?
    ) => {
        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Declared for $name<$( $gen ),*>
        where $( $( $pred )* )?
        {
            const SHAPE: $crate::wire::Shape = $crate::wire::Shape {
                name: stringify!($name),
                params: &[$( stringify!($gen) ),*],
                layout: $crate::wire::Layout::Enum(&[$(
                    $crate::wire::Ctor {
                        name: stringify!($variant),
                        number: $number,
                        parts: $crate::wire_impl!(@parts $kind [$( $member_flow : $member_ty ),*]),
                    }
                ),*]),
                notes: $crate::wire_impl!(@notes $( $notes )?),
            };
        }

        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Shaped for $name<$( $gen ),*>
        where $( $( $pred )* )?
        {
            const FORM: $crate::wire::WireForm =
                $crate::wire_impl!(@form $name [$( $gen = $index ),*]);

            fn write_at(
                &self,
                out: &mut $crate::wire::ValueWriter<'_, '_>,
                ty: &$crate::wire::Type,
            ) -> Result<(), $crate::EncodeError> {
                match self {
                    $( Self::$variant { $( $member: $bind ),* } => out.variant(
                        ty,
                        $crate::wire::position($number),
                        &[$( $bind ),*],
                    ), )*
                }
            }

            fn read_at(
                input: &mut $crate::wire::ValueReader<'_, '_, '_>,
                ty: &$crate::wire::Type,
            ) -> Result<Self, $crate::DecodeError> {
                input.variant(ty, |input, index, fields| {
                    let _ = (&input, &fields);
                    Ok(match index {
                        $( $number => Self::$variant {
                            $( $member: fields.read::<$member_ty>(input)?, )*
                        }, )*
                        _ => return Err(input.mismatch(ty)),
                    })
                })
            }
        }
    };

    (
        impl $name:ident [$( $gen:ident = $index:literal ),*] $( where [$( $pred:tt )*] )? newtype {
            $field:tt : $ty:ty
        } phantom [$( $phantom:tt ),*] $( notes $notes:expr )?
    ) => {
        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Declared for $name<$( $gen ),*>
        where $( $( $pred )* )?
        {
            const SHAPE: $crate::wire::Shape = $crate::wire::Shape {
                name: stringify!($name),
                params: &[$( stringify!($gen) ),*],
                layout: $crate::wire::Layout::Newtype(<$ty as $crate::wire::Shaped>::FORM),
                notes: $crate::wire_impl!(@notes $( $notes )?),
            };
        }

        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Shaped for $name<$( $gen ),*>
        where $( $( $pred )* )?
        {
            const FORM: $crate::wire::WireForm =
                $crate::wire_impl!(@form $name [$( $gen = $index ),*]);

            fn write_at(
                &self,
                out: &mut $crate::wire::ValueWriter<'_, '_>,
                ty: &$crate::wire::Type,
            ) -> Result<(), $crate::EncodeError> {
                out.newtype(ty, &self.$field)
            }

            fn read_at(
                input: &mut $crate::wire::ValueReader<'_, '_, '_>,
                ty: &$crate::wire::Type,
            ) -> Result<Self, $crate::DecodeError> {
                Ok(Self {
                    $field: input.newtype::<$ty>(ty)?,
                    $( $phantom: ::core::marker::PhantomData, )*
                })
            }
        }
    };

    (@notes) => { None };
    (@notes $notes:expr) => { Some(&$notes) };

    (@form $name:ident []) => {
        $crate::wire::WireForm::Declared(<Self as $crate::wire::Declared>::shape)
    };
    (@form $name:ident [$( $gen:ident = $index:literal ),+]) => {
        $crate::wire::WireForm::Applied(
            <$name<$( $crate::wire::Param<$index> ),+> as $crate::wire::Declared>::shape,
            &[$( $crate::wire::form_of::<$gen> ),+],
        )
    };

    (@parts Empty []) => { $crate::wire::Parts::Empty };
    (@parts Positional [$( $flow:literal : $ty:ty ),+]) => {
        $crate::wire::Parts::Positional(&[$( <$ty as $crate::wire::Shaped>::FORM ),+])
    };
    (@parts Named [$( $flow:literal : $ty:ty ),*]) => {
        $crate::wire::Parts::Named(&[$(
            $crate::wire::Field {
                name: $flow,
                form: <$ty as $crate::wire::Shaped>::FORM,
            }
        ),*])
    };
}