typespace 0.0.1-alpha.1

Model Rust types for code generation
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
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
// Copyright 2026 Oxide Computer Company

//! Semantic model of Rust types for code generation.
//!
//! The crate is organized around the code generation lifecycle: consumers
//! create a [`TypespaceBuilder`] from [`settings::Settings`], assemble types
//! from the [`build`] module's vocabulary, insert them with
//! [`TypespaceBuilder::insert`], and call [`TypespaceBuilder::finalize`] to
//! produce a [`Typespace`]. A finalized typespace renders code via
//! [`Typespace::to_codespace`] and answers queries through the [`view`]
//! module's types.
//!
//! # Using Typespace
//!
//! Here's a small example, constructing a single named type:
//!
//! ```
//! use typespace::build::{Struct, StructProperty, StructPropertyState, Type};
//! use typespace::settings::Settings;
//! use typespace::{no_cycles, TypespaceBuilder, TypespaceTrait};
//!
//! let settings = Settings::minimal()
//!     .with_required_trait(TypespaceTrait::Serialize)
//!     .with_required_trait(TypespaceTrait::Deserialize);
//! let mut builder = TypespaceBuilder::<String>::new(settings);
//!
//! // Ids are the consumer's to choose. These two types are unnamed, so
//! // they render inline wherever they are referenced rather.
//! builder.insert("str".to_string(), Type::String)?;
//! builder.insert("u32".to_string(), Type::Integer("u32".to_string()))?;
//!
//! let pet = Struct::new()
//!     .name("Pet")
//!     .properties([
//!         StructProperty::new("name", "str".to_string()),
//!         StructProperty::new("age", "u32".to_string())
//!             .with_state(StructPropertyState::Default),
//!         StructProperty::new("breed", "str".to_string())
//!             .with_state(StructPropertyState::Optional),
//!     ])
//!     .build()?;
//! builder.insert("Pet".to_string(), pet)?;
//!
//! // finalize resolves traits and breaks containment cycles. This graph
//! // has no cycles, so `no_cycles` asserts none are found.
//! let code: codespace::Codespace =
//!     builder.finalize(no_cycles)?.to_codespace();
//! let rust = code.into_stream();
//!
//! # assert!(rust.to_string().contains("pub struct Pet"));
//! # Ok::<(), typespace::error::Error<String>>(())
//! ```
//!
//! The produces Rust code like this:
//! ```
//! #[derive(::serde::Deserialize, ::serde::Serialize)]
//! pub struct Pet {
//!     pub name: ::std::string::String,
//!     #[serde(default)]
//!     pub age: u32,
//!     pub breed: Option<::std::string::String>,
//! }
//! ```
//!
//! # Details
//!
//! ## Named and unnamed types
//!
//! Typespace allows the construction of named and unnamed types. Named types
//! are custom type definitions that result in a generated type definition such
//! as a `struct Foo { .. }`  or `enum Bar { .. }`; unnamed types include
//! anonymous tuples with a collection of types or a parameterized `Vec`. Named
//! types get their own generated type block with associated `impl` blocks;
//! unnamed types are rendered inline.
//!
//! ## Struct fields: optionality and defaults
//!
//! A struct field (or a field of a struct-style enum variant) has several
//! associated states.
//!
//! - Required: the field must always be present; this is modeled as a bare
//!   type with no special `serde` attributes.
//! - Optional: the field may be absent; the specific `serde` attributes
//!   may depend on [`settings::Settings`].
//! - Default: the field if absent takes its value from the `Default` impl for
//!   the field's type (`#[serde(default)]`).
//! - DefaultValue: the field if absent takes its value from the specific,
//!   specified value (that is produced by a generated function).
//!
//! In addition, [`settings::Settings`] provides for special handling
//! of fields that are both Optional and represented by the Rust `Option` type.
//! Such a field may be absent, `null`, or another value. See
//! [`settings::OptionalNullable`].
//!
//! ## Type defaults
//!
//! In addition to a field having a default value, any generated `struct` or
//! `enum` type (a named type, as above) may have an explicit default value.
//! This causes an implementation of the `Default` trait to be generated for
//! the type (if `Default` is one of the output traits).
//!
//! ## Trait resolution
//!
//! Consumers may specify relevant traits for the Rust code output. *Required*
//! traits are generated for each type. If a type is unable to satisfy that
//! requirement, construction of the [`Typespace`] fails during
//! [`TypespaceBuilder::finalize`]. *Desired* traits are generated if
//! possible--if a type is unable to implement a particular trait, that's
//! ignored during `finalize`.
//!
//! Trait resolution occurs in two main passes. A forward pass propagates
//! required traits to all types and, in the case of failure, produces a list
//! of all unsatisfiable conditions along with their reasons (for debugging). A
//! reverse pass (i.e. from types that don't implement a given trait to the
//! types that refer to it) "poisons" desired traits so that they are absent
//! from types whose transitive references wouldn't support them.
//!
//! ## Breaking containment cycles
//!
//! Also during finalization, containment cycles in the type graph are broken
//! by inserting `Box` types. No attempt is made to optimize exactly how cycles
//! are broken (e.g. to minimize the number of inserted `Box`es), but in
//! practice the generated code has not suffered.
//!
//! # Generation
//!
//! Code generation has some nuances, enumerated here:
//!
//! ## Never vs. Absent
//!
//! A [`Type::Never`] represents a type that can never be instantiated. It is
//! typically rendered as `::json_serde::Never` (an `enum` with no variants).
//! However, if a `Never` type appears as an
//! [`Optional`](build::StructPropertyState) field in a `struct` (or
//! `struct`-like `enum` variant), it is rendered as `::json_serde::Absent` to
//! ensure proper handling by `serde` and `schemars`.
//!
//! ## Special `enum`s
//!
//! A tagged `enum` composed *only* of unit variants is treated like a value;
//! the generated type implements each of the following traits (if they're in
//! the specified trait set): `Eq`, `PartialEq`, `Ord`, `PartialOrd`, `Hash`,
//! `Clone`, `Copy`, `Display`, and `FromStr`.
//!
//! An untagged `enum` composed exclusively of
//! [`Item`](build::VariantDetails::Item) variants may implement `Display` and
//! `FromStr` if the type for each item also does so.
//!
//! ## Generated modules
//!
//! Some default values require the generation of a function to produce those
//! values. Those functions live in a generated `defaults` module.
//!
//! With [`Settings::with_struct_builder`] enabled, the generated builder
//! machinery lives in a `builder` module.
//!
//! If there are types that include implementations of fallible conversions, the
//! `error` mod is generated to contain the error.
//!
//! ## When `Default` requires `serde_json`
//!
//! Types or fields may have associated default values. The value is
//! constructed by generated code explicitly (i.e. without `Deserialize`). The
//! exception is Native types. Since the construction of a native type
//! is--necessarily--beyond the knowledge of typespace, the generated code
//! constructs it with a call to `serde_json::from_str`.
//!
//! # Dependencies of generated code
//!
//! Rendered code can reference crates that typespace itself does not depend
//! on. Crates containing generating code must declare them as dependencies.
//! Which crates are needed depends on the constructs in the output:
//!
//! - [serde](https://crates.io/crates/serde), with the `derive` feature:
//!   required by generated structs, enums, newtype structs, unit structs, and
//!   tuple structs whose trait set holds [`TypespaceTrait::Serialize`] or
//!   [`TypespaceTrait::Deserialize`]; each is emitted with serde derives or
//!   hand-written `Serialize`/`Deserialize` impls. Settings that require
//!   neither trait produce no derive, no impl, and no `#[serde(..)]`
//!   attribute (and so no dependency).
//! - [serde_json](https://crates.io/crates/serde_json): required when
//!   the output contains a [`build::Type::JsonValue`] (rendered as
//!   `::serde_json::Value`), in several situations that involve
//!   serializing or deserializing a type from a JSON value such as default
//!   value handling and deserializing various types (see above), or when
//!   a `schemars::JsonSchema` implementation requires it.
//! - [regress](https://crates.io/crates/regress): required if the
//!   output contains a [`build::NewtypeStruct`] whose
//!   [`build::NewtypeConstraints::String`] carries a pattern. Each
//!   pattern renders a `::regress::Regex` in a `LazyLock`, checked on
//!   conversion.
//! - [jsonschema](https://crates.io/crates/jsonschema): required if
//!   the output contains a [`build::NewtypeStruct`] whose
//!   [`build::NewtypeConstraints::JsonSchema`] carries a schema. The
//!   conversion validates the value against that schema.
//! - [json-serde](https://crates.io/crates/json-serde): required if
//!   the output contains any of:
//!   - a property with [`build::StructPropertyState::Optional`] whose
//!     type is not an `Option` (deserialized with
//!     `::json_serde::deserialize_some`, which distinguishes an absent
//!     field from a present one and rejects `null`);
//!   - a property with [`build::StructPropertyState::Optional`] whose
//!     type is an `Option`, when
//!     [`settings::OptionalNullable::DoubleOption`] is selected
//!     (also `::json_serde::deserialize_some`);
//!   - a [`build::TupleStruct`] with a `rest` field (its serde impls use
//!     `::json_serde::FlattenedSequenceSerializer` and
//!     `::json_serde::FlattenedSequenceDeserializer`);
//!   - the [`build::Type::Never`] (rendered as ::json_serde::Never or--if
//!     optional-- `::json_serde::Absent`);
//!   - a custom type to represent a field whose value may be absent,
//!     null, or a type value, specified with
//!     [`settings::OptionalNullable::CustomType`].
//!
//!   `Absent` is emitted (as needed) independent of what the trait set holds.
//!   The rest are only used for `serde::Deserialize` and `serde::Serialize`.
//!
//! Generated code also reproduces, verbatim, every type path the consumer
//! supplies: the `name` of a [`build::Native`]. For example, a converter might
//! inject `uuid::Uuid` or `chrono` types. The crates behind those paths are
//! dependencies chosen by the consumer that builds the typespace, not by
//! typespace, and the consumer should document them.

pub mod build;
pub(crate) mod cycles;
mod default;
pub mod error;
pub(crate) mod output;
pub(crate) mod serde_attrs;
pub mod settings;
pub(crate) mod trait_resolution;
pub(crate) mod value_tokens;
pub mod view;

// Binds the name `typespace` to this crate itself, so the absolute
// `::typespace::...` paths that `typespace_builder!` emits (see
// typespace-test-macro's builder module) resolve from any module in
// this crate, including nested `#[cfg(test)]` modules, exactly as
// they would from an external crate depending on `typespace`.
extern crate self as typespace;

use std::collections::{BTreeMap, BTreeSet, btree_map::Entry};

use proc_macro2::TokenStream;
use quote::{ToTokens, format_ident, quote};

use crate::build::{
    Enum, JsonValue, Native, NewtypeStruct, Struct, StructProperty, StructPropertySerde,
    StructPropertyState, TupleStruct, Type, TypeAlias, TypeCommonBuilt, UnitStruct, VariantDetails,
    all_named_types,
};
use crate::default::{SharedDefaultFn, shared_default_fn};
use crate::error::Error;
use crate::output::Outputspace;
use crate::serde_attrs::{SerdeAttrs, SerdeDerives};
use crate::settings::{OptionalNullable, Settings, Std};

/// A trait that typespace tracks for generated and native types.
///
/// Uses of a type impose trait requirements that
/// [`TypespaceBuilder::finalize`] propagates: a type used as a map key must
/// implement `Eq`, `PartialEq`, `Ord`, and `PartialOrd` (and so must every
/// type it contains). Generated types absorb propagated requirements and emit
/// the corresponding derives; a [`build::Native`] type must already declare
/// the required traits among its `impls` (or leave them unknown). A
/// requirement that a type cannot satisfy--`Ord` on a float, say--produces an
/// error.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Deserialize, strum::EnumIter,
)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub enum TypespaceTrait {
    Deserialize,
    Serialize,
    Clone,
    /// A marker trait: derivable only when every constituent is `Copy`,
    /// which rules out anything holding a `String` or a
    /// `serde_json::Value`. `Copy` implies `Clone`, so requiring or
    /// desiring it brings `Clone` along.
    Copy,
    Debug,
    Display,
    FromStr,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Default,
    /// A map's key is treated as bound by this trait, which schemars 1.x
    /// requires and schemars 0.8 does not: 0.8 renders a map key as a
    /// schema string whatever the key type is, so its map impls bound
    /// only the value. typespace tracks one JsonSchema across both, and
    /// states the stronger form, so a 0.8 consumer whose map key lacks
    /// the trait is refused a typespace that would have compiled.
    JsonSchema,
}

impl TypespaceTrait {
    pub(crate) fn render(&self, settings: &Settings) -> proc_macro2::TokenStream {
        if settings.std == Std::FullyQualified {
            match self {
                // TypespaceTrait::Clone => quote! { ::std::clone::Clone },
                // TypespaceTrait::Debug => quote! { ::std::fmt::Debug },
                TypespaceTrait::Clone => quote! { Clone },
                // TypespaceTrait::Copy => quote! { ::std::marker::Copy },
                TypespaceTrait::Copy => quote! { Copy },
                TypespaceTrait::Debug => quote! { Debug },
                TypespaceTrait::Serialize => quote! { ::serde::Serialize },
                TypespaceTrait::Deserialize => quote! { ::serde::Deserialize },
                TypespaceTrait::JsonSchema => quote! { schemars::JsonSchema },
                // TypespaceTrait::Eq => quote! { ::std::cmp::Eq },
                // TypespaceTrait::PartialEq => quote! { ::std::cmp::PartialEq },
                // TypespaceTrait::Hash => quote! { ::std::hash::Hash },
                // TypespaceTrait::Ord => quote! { ::std::cmp::Ord },
                // TypespaceTrait::PartialOrd => quote! { ::std::cmp::PartialOrd },
                TypespaceTrait::Ord => quote! { Ord },
                TypespaceTrait::PartialOrd => quote! { PartialOrd },
                TypespaceTrait::Eq => quote! { Eq },
                TypespaceTrait::PartialEq => quote! { PartialEq },
                TypespaceTrait::Hash => quote! { Hash },
                TypespaceTrait::Display => quote! { ::std::fmt::Display },
                TypespaceTrait::FromStr => quote! { ::std::str::FromStr },
                // TypespaceTrait::Default => quote! { ::std::default::Default },
                TypespaceTrait::Default => quote! { Default },
            }
        } else {
            match self {
                TypespaceTrait::Clone => quote! { Clone },
                TypespaceTrait::Copy => quote! { Copy },
                TypespaceTrait::Debug => quote! { Debug },
                TypespaceTrait::Serialize => quote! { ::serde::Serialize },
                TypespaceTrait::Deserialize => quote! { ::serde::Deserialize },
                TypespaceTrait::JsonSchema => quote! { ::schemars::JsonSchema },
                TypespaceTrait::Ord => quote! { Ord },
                TypespaceTrait::PartialOrd => quote! { PartialOrd },
                TypespaceTrait::Eq => quote! { Eq },
                TypespaceTrait::PartialEq => quote! { PartialEq },
                TypespaceTrait::Hash => quote! { Hash },
                TypespaceTrait::Display => quote! { Display },
                TypespaceTrait::FromStr => quote! { FromStr },
                TypespaceTrait::Default => quote! { Default },
            }
        }
    }
}

impl std::fmt::Display for TypespaceTrait {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            TypespaceTrait::Clone => "Clone",
            TypespaceTrait::Copy => "Copy",
            TypespaceTrait::Debug => "Debug",
            TypespaceTrait::Serialize => "Serialize",
            TypespaceTrait::Deserialize => "Deserialize",
            TypespaceTrait::JsonSchema => "JsonSchema",
            TypespaceTrait::Display => "Display",
            TypespaceTrait::FromStr => "FromStr",
            TypespaceTrait::Eq => "Eq",
            TypespaceTrait::PartialEq => "PartialEq",
            TypespaceTrait::Ord => "Ord",
            TypespaceTrait::PartialOrd => "PartialOrd",
            TypespaceTrait::Hash => "Hash",
            TypespaceTrait::Default => "Default",
        };
        f.write_str(name)
    }
}

/// An unordered collection of [`TypespaceTrait`] values.
///
/// Build one with [`TypespaceTraitSet::empty`] and [`TypespaceTraitSet::add`],
/// or collect from an iterator of traits.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, serde::Deserialize)]
pub struct TypespaceTraitSet(BTreeSet<TypespaceTrait>);

impl FromIterator<TypespaceTrait> for TypespaceTraitSet {
    fn from_iter<T: IntoIterator<Item = TypespaceTrait>>(iter: T) -> Self {
        Self(iter.into_iter().collect())
    }
}

impl IntoIterator for TypespaceTraitSet {
    type Item = TypespaceTrait;
    type IntoIter = std::collections::btree_set::IntoIter<TypespaceTrait>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl TypespaceTraitSet {
    pub fn empty() -> Self {
        Self(Default::default())
    }

    pub fn contains(&self, tt: &TypespaceTrait) -> bool {
        self.0.contains(tt)
    }

    pub fn add(&mut self, tt: TypespaceTrait) {
        self.0.insert(tt);
    }

    pub fn remove(&mut self, tt: TypespaceTrait) -> bool {
        self.0.remove(&tt)
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn iter(&self) -> impl Iterator<Item = &TypespaceTrait> {
        self.0.iter()
    }

    pub fn difference<'a>(
        &'a self,
        other: &'a Self,
    ) -> impl Iterator<Item = &'a TypespaceTrait> + 'a {
        self.0.difference(&other.0)
    }
}

/// What a [`build::Native`] or a configured container
/// ([`settings::ContainerType`]) declares about one trait.
///
/// A container is hand-authored in [`settings::Settings`], so its author is
/// expected to know the container completely and use [`Never`](Self::Never),
/// [`Always`](Self::Always), or [`IfParameters`](Self::IfParameters)
/// exclusively; declaring [`Unknown`](Self::Unknown) there is a configuration
/// error, rejected during finalization. A native type, however, may come from
/// an external source, so `Unknown` is permitted.
///
/// The two trait resolution phases read [`Unknown`](Self::Unknown) in opposite
/// directions: a requirement for it passes, because refusing to generate for a
/// valid schema is worse than a compile error naming the real missing impl,
/// and a desired trait is never granted from it, because granting one on a
/// guess emits a derive nobody asked for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TraitProvision {
    /// No impl exists, irrespective of what the type parameters implement.
    Never,
    /// The type implements the trait independent of its type parameters.
    Always,
    /// The type implements the trait when every type parameter does.
    IfParameters,
    /// The disposition of the trait is unknown.
    Unknown,
}

/// Accumulator for the type graph prior to finalization.
///
/// Create one with [`settings::Settings`] by calling [`TypespaceBuilder::new`]
/// (or [`TypespaceBuilder::default`] for default settings), insert every
/// type--each named type along with every built-in and container type it
/// references--under a caller-chosen ID with [`TypespaceBuilder::insert`],
/// then call [`TypespaceBuilder::finalize`] to validate the graph and produce
/// a [`Typespace`].
pub struct TypespaceBuilder<Id> {
    types: BTreeMap<Id, Type<Id>>,
    settings: Settings,
}

impl<Id> Default for TypespaceBuilder<Id> {
    /// A builder with default [`settings::Settings`].
    fn default() -> Self {
        Self::new(Settings::typical())
    }
}

impl<Id> TypespaceBuilder<Id> {
    /// Create a builder whose finalization and rendering are governed
    /// by `settings`.
    pub fn new(settings: Settings) -> Self {
        Self {
            types: Default::default(),
            settings,
        }
    }
}

/// What rendering a value obliges of some other type.
#[derive(Debug, Clone)]
pub(crate) struct Obligation<Id> {
    /// The trait the target must implement. This is not always the
    /// trait being asked about where the obligation is weighed: a
    /// value renders inside one type's impl and may oblige a
    /// different trait of what it constructs.
    pub(crate) required: TypespaceTrait,
    /// The hops from the type whose value this is to the target.
    pub(crate) path: Vec<error::PathStep<Id>>,
    /// The type that must implement `required`.
    pub(crate) target: Id,
}

/// What checking every attached default value learned.
///
/// Both halves hold requirements that apply only if the owner renders
/// the value. They differ in which trait makes it render. `whole_type`
/// is conditional on `Default`, since the value lives inside a
/// `Default` impl, so `feasibility` evaluates its obligations when it
/// answers for that trait. `deserialized` is conditional on
/// `Deserialize`, since a property's own value renders as a
/// `defaults::` function that only a deserialize path calls.
#[derive(Debug)]
pub(crate) struct DefaultChecks<Id> {
    /// Per type carrying a whole-type default, what rendering that
    /// value obliges, with each obligation's path running from the
    /// type named by the key to its target.
    pub(crate) whole_type: BTreeMap<Id, Vec<Obligation<Id>>>,
    /// Each native a property-level default value reaches, against the
    /// type whose value first reached it.
    // TODO 9/12/2026
    // required_resolution seeds these unconditionally, so a type that
    // never deserializes still pays for the natives in its property
    // defaults. They belong with whole_type's obligations, under a
    // `Deserialize` antecedent in place of `Default`'s.
    pub(crate) deserialized: BTreeMap<Id, Id>,
}

impl<Id> Default for DefaultChecks<Id> {
    fn default() -> Self {
        Self {
            whole_type: BTreeMap::new(),
            deserialized: BTreeMap::new(),
        }
    }
}

impl<Id: Clone + Ord + std::fmt::Debug + std::fmt::Display> TypespaceBuilder<Id> {
    /// Add a type under the given ID.
    ///
    /// The IDs that `typ` refers to need not be present yet, but each
    /// must be inserted before [`finalize`](Self::finalize) is called.
    /// Fails with [`error::Error::DuplicateTypeId`] if a type with
    /// this ID was already inserted, and re-runs the shape checks that
    /// `build()` applies (rejecting, for example, a shape value smuggled
    /// into a [`Type`] variant without being built).
    pub fn insert(&mut self, id: Id, typ: Type<Id>) -> Result<(), Error<Id>> {
        // The shapes' build() methods validate names, but Type's
        // variants are not sealed against direct construction; re-run
        // the checks here so no unvalidated shape can enter the
        // typespace.
        typ.validate_built()?;
        match self.types.entry(id) {
            Entry::Vacant(e) => {
                e.insert(typ);
                Ok(())
            }
            Entry::Occupied(e) => {
                // Duplicate insertions are a caller error.
                Err(Error::DuplicateTypeId {
                    type_id: e.key().clone(),
                })
            }
        }
    }

    /// Whether a type has already been inserted under the given ID.
    pub fn contains_type(&self, id: &Id) -> bool {
        self.types.contains_key(id)
    }

    /// Render the Rust identifier of an inserted type before
    /// finalization.
    ///
    /// Rendering honors the builder's settings (container overrides,
    /// `std` syntax). Finalization-only effects are necessarily
    /// absent: no cycle-breaking boxes exist yet.
    ///
    /// # Panics
    ///
    /// Panics if `id`--or any type ID it references transitively
    /// through container types--has not been inserted.
    pub fn ident(&self, id: &Id) -> TokenStream {
        self.renderer().render_ident(id)
    }

    /// Like [`TypespaceBuilder::ident`], with named types qualified by
    /// the module `scope`.
    ///
    /// # Panics
    ///
    /// Panics under the same conditions as [`TypespaceBuilder::ident`].
    pub fn ident_in(&self, id: &Id, scope: &str) -> TokenStream {
        self.renderer().render_ident_with_scope(id, Some(scope))
    }

    /// Render the identifier of an inserted type as a function
    /// parameter type, before finalization.
    ///
    /// Types the caller owns cheaply pass by value and the rest are
    /// borrowed; see
    /// [`Type::parameter_ident`](crate::view::Type::parameter_ident)
    /// for the rule, for what `scope` qualifies, and for where
    /// `lifetime` is named.
    ///
    /// # Panics
    ///
    /// Panics under the same conditions as [`TypespaceBuilder::ident`].
    pub fn parameter_ident(
        &self,
        id: &Id,
        scope: Option<&str>,
        lifetime: Option<&str>,
    ) -> TokenStream {
        self.renderer().render_parameter_ident(id, scope, lifetime)
    }

    fn renderer(&self) -> TypespaceRenderer<'_, Id> {
        TypespaceRenderer::new(&self.types, &self.settings)
    }

    /// Reject unparseable extra derives so that rendering--which is
    /// infallible--can rely on them parsing.
    fn check_derives(&self) -> Result<(), Error<Id>> {
        for derive in &self.settings.extra_derives {
            if let Err(err) = syn::parse_str::<syn::Path>(derive) {
                return Err(Error::InvalidDerive {
                    derive: derive.clone(),
                    message: err.to_string(),
                });
            }
        }
        Ok(())
    }

    /// Verify that each configured container declares what it demands
    /// of every type parameter the position it renders supplies, and
    /// that it answers for every trait outright rather than deferring
    /// to [`TraitProvision::Unknown`], which is only meaningful for a
    /// machine-authored [`build::Native`].
    fn check_containers(&self) -> Result<(), Error<Id>> {
        let custom_optional = match &self.settings.optional_nullable {
            OptionalNullable::CustomType(container) => Some(("optional-nullable", container, 1)),
            _ => None,
        };
        [
            ("map", &self.settings.map_type, 2),
            ("set", &self.settings.set_type, 1),
            ("vec", &self.settings.vec_type, 1),
        ]
        .into_iter()
        .chain(custom_optional)
        .try_for_each(|(position, container, parameters)| {
            if let Some(trait_) = container.provisions().find_map(|(trait_, provision)| {
                matches!(provision, TraitProvision::Unknown).then_some(trait_)
            }) {
                return Err(Error::ContainerProvisionUnknown {
                    position,
                    path: settings::path_text(container.path()),
                    trait_,
                });
            }
            match container.obligations().len() {
                declared if declared == parameters => Ok(()),
                declared => Err(Error::ContainerParameterCount {
                    position,
                    path: settings::path_text(container.path()),
                    declared,
                    parameters,
                }),
            }
        })
    }

    /// Verify that every type ID referenced by a type is actually
    /// present; later steps rely on lookups of child IDs succeeding.
    /// Verify that a declared optional-nullable wrapper claims an
    /// unconditional `Default`.
    ///
    /// `feasibility` exempts an optional property from its own
    /// `Default` obligation without consulting the wrapper that renders
    /// in its place. The exemption is sound only where the wrapper
    /// claims `Default` unconditionally, so a declaration claiming less
    /// is refused here rather than resolved against.
    fn check_optional_nullable_default(&self) -> Result<(), Error<Id>> {
        let OptionalNullable::CustomType(container) = &self.settings.optional_nullable else {
            return Ok(());
        };
        let provision = container.provision(TypespaceTrait::Default);
        if provision == TraitProvision::Always {
            return Ok(());
        }
        Err(Error::OptionalNullableWrapperDefault {
            path: crate::settings::path_text(container.path()),
            provision,
        })
    }

    fn check_references(&self) -> Result<(), Error<Id>> {
        for (type_id, typ) in &self.types {
            for child_id in typ.children() {
                if !self.types.contains_key(&child_id) {
                    return Err(Error::UnknownTypeId {
                        type_id: type_id.clone(),
                        child_id,
                    });
                }
            }
        }
        Ok(())
    }

    /// Verify that no two named types share a name.
    ///
    /// Names come from the consumer, which is responsible for collision-free
    /// naming.
    fn check_type_names(&self) -> Result<(), Error<Id>> {
        let mut names = BTreeMap::<&str, &Id>::new();
        for (type_id, typ) in &self.types {
            if let Some(common) = typ.common() {
                let name = common.built_name();
                if let Some(first) = names.insert(name, type_id) {
                    return Err(Error::DuplicateTypeName {
                        name: name.to_string(),
                        first: first.clone(),
                        second: type_id.clone(),
                    });
                }
            }
        }
        Ok(())
    }

    /// Check every attached default value, and collect the natives the
    /// values reach.
    ///
    /// Generated code constructs a native-typed position of a default value by
    /// deserializing it, so each collected native must implement
    /// `Deserialize`. The map records each native against the type whose value
    /// first reached it; trait resolution seeds the requirement from the map,
    /// and reports a conflict when the native does not declare the trait.
    fn check_type_defaults(&self) -> Result<DefaultChecks<Id>, Error<Id>> {
        let mut checks = DefaultChecks::default();
        for (type_id, typ) in &self.types {
            // A whole-type default value renders inside the `Default`
            // impl, which trait resolution may never grant. What it
            // obliges is therefore conditional on that grant, so it is
            // handed to `feasibility` rather than seeded here.
            if let Some(common) = typ.common()
                && let Some(JsonValue(default)) = &common.default
            {
                let obligations = self.check_default(default, type_id)?;
                if !obligations.is_empty() {
                    checks.whole_type.insert(type_id.clone(), obligations);
                }
            }

            // A property's own default value renders as a `defaults::`
            // function that only a deserialize path calls. Its natives
            // are seeded as requirements even so.
            let mut natives = BTreeSet::new();
            match typ {
                Type::Struct(struct_info) => {
                    natives.extend(struct_info.check_field_defaults(self)?)
                }
                Type::Enum(enum_info) => natives.extend(enum_info.check_field_defaults(self)?),
                _ => (),
            }
            for native in natives {
                checks
                    .deserialized
                    .entry(native)
                    .or_insert_with(|| type_id.clone());
            }
        }
        Ok(checks)
    }

    /// Per-type structural validation: rules a single type's own
    /// declaration must satisfy, judged without reference to any other
    /// type.
    ///
    /// It holds one rule, that a struct cannot both deny unknown
    /// fields and flatten a property. Two more belong here:
    ///
    /// - a flattened property's type must be an object, which is what
    ///   makes flattening meaningful at all;
    /// - the Never-position rules, which `check_never_positions` holds
    ///   separately though they are per-type in exactly this sense.
    ///
    /// Add rules here rather than as new `check_*` methods.
    fn check_type_structure(&self) -> Result<(), Error<Id>> {
        for typ in self.types.values() {
            let Type::Struct(struct_info) = typ else {
                continue;
            };
            if !struct_info.deny_unknown_fields {
                continue;
            }
            // serde decides deny_unknown_fields in the outer struct's
            // deserializer, which cannot know whether a flattened type
            // claims a given key, so the pair has no implementable
            // meaning. Naming the first flattened property in
            // declaration order is enough to locate the problem.
            if let Some(prop) = struct_info
                .properties
                .iter()
                .find(|prop| matches!(prop.json_name, StructPropertySerde::Flatten))
            {
                return Err(Error::FlattenWithDenyUnknownFields {
                    type_name: struct_info.common.built_name().to_string(),
                    property: prop.rust_name.clone(),
                });
            }
        }
        Ok(())
    }

    /// Reject `Type::Never` in any position that requires a value.
    ///
    /// `Never` renders as `::json_serde::Never`, a type that can be
    /// neither serialized nor deserialized, so it says something only
    /// where the construct holding it can leave it out: a struct
    /// property that may be absent
    /// ([`StructPropertyState::Optional`]), including a struct-shaped
    /// enum variant's field; either side of a map; and the element of a
    /// vec, a set, or a zero-length array, each of which may be empty.
    /// An `Option<Never>` is a value of its own--`None`--and so is
    /// legal wherever a value is required.
    ///
    /// Every other position demands a value that can never be produced,
    /// which makes the type holding it a type with no values at all: a
    /// property that must be present or fall back to a default, a
    /// tuple component, the element of a non-empty fixed-size array, a
    /// tuple struct field, and an enum variant's item or tuple payload.
    /// These report [`Error::NeverInValuePosition`].
    ///
    /// A transparent wrapper--a `Box`, a type alias, or a
    /// `#[serde(transparent)]` newtype struct--requires a value as
    /// well, and reports [`Error::NeverInTransparentWrapper`] instead.
    /// Each of these wrappers is transparent on the wire, so wrapping
    /// `Never` in one produces a field that is wire-identical to a bare
    /// `Never` property but escapes the property-side skip logic, which
    /// only recognizes a property whose immediate type is
    /// `Type::Never`. None of the three wrappers add expressive power
    /// over a bare `Never`--each is just another name for
    /// "nothing"--and the dedicated error says so rather than teaching
    /// rendering to see through them.
    ///
    /// Only the immediate type in each position is checked; there is no
    /// recursion. None is needed: every type in the graph is checked
    /// here, so every position in the graph is checked. A chain such as
    /// `type B = A` where `type A = !` bottoms out at a wrapper that
    /// directly contains `Never` (`A`), and that wrapper alone fails
    /// this check, which fails validation for the whole graph.
    fn check_never_positions(&self) -> Result<(), Error<Id>> {
        match self
            .types
            .iter()
            .find_map(|(type_id, typ)| self.never_position(type_id, typ))
        {
            Some(err) => Err(err),
            None => Ok(()),
        }
    }

    /// The error for a position of `typ` that requires a value and whose
    /// type is `Type::Never`, or `None` if `typ` has no such position.
    /// `type_id` is the id of `typ`, reported as the type that holds the
    /// position. See `check_never_positions` for the rule this applies.
    fn never_position(&self, type_id: &Id, typ: &Type<Id>) -> Option<Error<Id>> {
        let is_never = |id: &Id| matches!(self.types.get(id), Some(Type::Never));
        let value_position = |position: &'static str, name: String| Error::NeverInValuePosition {
            position,
            name,
            type_id: type_id.clone(),
        };
        let transparent_wrapper = |wrapper: &'static str| Error::NeverInTransparentWrapper {
            wrapper,
            type_id: type_id.clone(),
        };
        // The Rust name of the first property that requires a value--any
        // state but Optional--and whose type is Never.
        let never_property = |properties: &[StructProperty<Id>]| {
            properties
                .iter()
                .find(|prop| {
                    !matches!(prop.state, StructPropertyState::Optional) && is_never(&prop.type_id)
                })
                .map(|prop| prop.rust_name.clone())
        };
        // The index of the first component that is Never.
        let never_component = |components: &[Id]| {
            components
                .iter()
                .position(is_never)
                .map(|index| index.to_string())
        };

        match typ {
            Type::Struct(Struct { properties, .. }) => {
                never_property(properties).map(|name| value_position("property", name))
            }

            Type::Enum(Enum { variants, .. }) => variants.iter().find_map(|variant| {
                let variant_name = &variant.rust_name;
                match &variant.details {
                    VariantDetails::Unit => None,
                    VariantDetails::Item(id) => is_never(id)
                        .then(|| value_position("variant payload", variant_name.clone())),
                    VariantDetails::Tuple(components) => never_component(components).map(|index| {
                        value_position(
                            "variant payload component",
                            format!("{variant_name}.{index}"),
                        )
                    }),
                    VariantDetails::Struct(properties) => never_property(properties).map(|name| {
                        value_position("variant property", format!("{variant_name}.{name}"))
                    }),
                }
            }),

            // The rest type holds the items beyond the positional
            // fields; it is required exactly as they are, so it counts
            // as the field one past the last.
            Type::TupleStruct(TupleStruct { fields, rest, .. }) => never_component(fields)
                .or_else(|| {
                    rest.as_ref()
                        .filter(|id| is_never(id))
                        .map(|_| fields.len().to_string())
                })
                .map(|index| value_position("tuple struct field", index)),

            Type::Tuple(components) => {
                never_component(components).map(|index| value_position("tuple component", index))
            }

            // An array of length zero holds no element, so the empty
            // array is its one value; any other length demands elements.
            Type::Array(id, length) => (*length > 0 && is_never(id))
                .then(|| value_position("array element", "item".to_string())),

            Type::Box(inner) => is_never(inner).then(|| transparent_wrapper("Box")),
            Type::TypeAlias(TypeAlias { target, .. }) => {
                is_never(target).then(|| transparent_wrapper("type alias"))
            }
            Type::NewtypeStruct(NewtypeStruct { inner, .. }) => {
                is_never(inner).then(|| transparent_wrapper("newtype struct"))
            }

            // The positions that absorb a Never: an Option of it has the
            // value None, and a vec, a set, or a map of it may be empty.
            Type::Option(_) | Type::Vec(_) | Type::Set(_) | Type::Map(_, _) => None,

            // A native type's parameters are the consumer's to
            // interpret; typespace cannot tell whether one absorbs a
            // Never the way a vec does.
            Type::Native(_) => None,

            // Types with no position that could hold a Never.
            Type::UnitStruct(_)
            | Type::Unit
            | Type::Boolean
            | Type::Integer(_)
            | Type::Float(_)
            | Type::String
            | Type::JsonValue
            | Type::Never => None,
        }
    }

    /// Finalize the typespace.
    ///
    /// Verifies the individual validity of types and the overall consistency
    /// of the type graph including type referenced and settings.
    ///
    /// Propagates all trait settings to types, producing an error if required
    /// traits cannot be implement for a given type.
    ///
    /// Breaks containment cycles by inserting a `Box<T>` type, making use of
    /// the provided `make_box_id` parameter to generate a new `Id` (with the
    /// `Id` of the type to be boxed as its input). Pass [`no_cycles`] to
    /// assert that the graph contains no containment cycles.
    pub fn finalize<F>(self, make_box_id: F) -> Result<Typespace<Id>, Error<Id>>
    where
        F: FnMut(&Id) -> Id,
    {
        // Finalization can be decomposed into a few phases:
        // 1. Local validation -- check the legality of various configured
        //    settings, check for unspecified references, check type names and
        //    structure, etc.
        // 2. Breaking containment cycles (and checking for illegal,
        //    anonymous-only cycles)
        // 3. Trait resolution to populate the post-finalization cache of
        //    traits for each named type.

        // Validate that derives are parseable as Rust paths.
        // TODO 9/1/2026
        // We should cache this and save it in the finalized Typespace rather
        // than saving the raw settings.
        self.check_derives()?;

        // Validate that each container declares an obligation for every
        // type parameter it is rendered with.
        self.check_containers()?;
        self.check_optional_nullable_default()?;

        // Ensure that every referenced type ID has been initialized.
        self.check_references()?;

        // Check the uniqueness of type names.
        self.check_type_names()?;

        // Disallow never (!) from being used in positions where a value would
        // be required.
        // TODO 9/1/2026 I hate this; I think we should be doing general type
        // validation for which this is one kind of validation. There may be
        // multiple passes: per-type and then intra-type.
        self.check_never_positions()?;

        // Per-type structural rules. Before check_type_defaults,
        // because the default-value walk assumes a struct that denies
        // unknown fields has no flattened property.
        self.check_type_structure()?;

        // Check type defaults. The walk also reports what rendering each
        // value obliges of other types, which splits two ways. A
        // whole-type value renders inside the Default impl, so
        // feasibility weighs its obligations when it answers for that
        // trait. A property-level value's natives are constructed by
        // deserialization, and resolve_traits seeds Deserialize from
        // them.
        let default_checks = self.check_type_defaults()?;

        let Self {
            mut types,
            settings,
        } = self;

        build_commons(&mut types);
        cycles::break_cycles(&mut types, make_box_id);
        cycles::check_anonymous_cycles(&types)?;

        // After break_cycles, because a newtype's inner may have become
        // a freshly minted Box, which has no FromStr at all; before
        // resolve_traits, because both required and desired resolution
        // consult `feasibility`, which reads the answer.
        trait_resolution::resolve_from_string_irrefutable(&mut types);
        trait_resolution::resolve_traits(&mut types, &settings, &default_checks)?;

        Ok(Typespace { types, settings })
    }
}

/// A `make_box_id` argument for [`TypespaceBuilder::finalize`] that
/// asserts the type graph contains no containment cycles: it panics if
/// finalization ever needs to insert a `Box`.
pub fn no_cycles<Id>(_: &Id) -> Id {
    panic!("unexpected cycle in typespace")
}

/// A finalized, validated collection of types.
///
/// Produced by [`TypespaceBuilder::finalize`]. Render every named type
/// with [`Typespace::to_codespace`], or inspect individual types
/// without rendering via [`Typespace::get_type`] and
/// [`Typespace::iter_types`].
pub struct Typespace<Id> {
    pub(crate) types: BTreeMap<Id, Type<Id>>,
    /// The settings supplied at finalization, which govern rendering.
    pub settings: Settings,
}

impl<Id: Clone + Ord + std::fmt::Debug + std::fmt::Display> Typespace<Id> {
    /// Look up a type by its id.
    ///
    /// # Panics
    ///
    /// Panics if `id` does not name a type in the typespace; every ID
    /// accepted at insert time (plus the box IDs generated during
    /// finalization) is valid.
    pub fn get_type(&self, id: &Id) -> view::Type<'_, Id> {
        let (id, typ) = self.types.get_key_value(id).expect("invalid type id");
        view::Type {
            typespace: self,
            id,
            typ,
        }
    }

    /// Iterate over all types in the typespace.
    pub fn iter_types(&self) -> impl Iterator<Item = view::Type<'_, Id>> {
        self.types.iter().map(|(id, typ)| view::Type {
            typespace: self,
            id,
            typ,
        })
    }

    /// Render every named type into a [`codespace::Codespace`].
    ///
    /// Each named type becomes one item keyed by its name; generated
    /// helper functions (serde default functions, for example) are
    /// routed to their own modules. Output is deterministic and
    /// unformatted; turning the codespace into a token stream or files
    /// is the caller's job from here.
    pub fn to_codespace(&self) -> codespace::Codespace {
        TypespaceRenderer::new(&self.types, &self.settings).render()
    }
}

pub(crate) struct TypespaceRenderer<'a, Id> {
    pub(crate) types: &'a BTreeMap<Id, Type<Id>>,
    pub(crate) settings: &'a Settings,
}

impl<'a, Id: Clone + Ord + std::fmt::Debug + std::fmt::Display> TypespaceRenderer<'a, Id> {
    pub(crate) fn new(types: &'a BTreeMap<Id, Type<Id>>, settings: &'a Settings) -> Self {
        Self { types, settings }
    }

    fn render(&self) -> codespace::Codespace {
        let mut out = Outputspace::default();

        for (id, typ) in self.types {
            match typ {
                Type::Struct(s) => {
                    let name = s.common.built_name().to_string();
                    let tokens = s.render(id, self, &mut out);
                    out.cs().add_item(name, tokens);
                }
                Type::Enum(e) => {
                    let name = e.common.built_name().to_string();
                    let tokens = e.render(id, self, &mut out);
                    out.cs().add_item(name, tokens);
                }
                Type::UnitStruct(u) => {
                    let name = u.common.built_name().to_string();
                    out.cs().add_item(name, u.render(self));
                }
                Type::TupleStruct(t) => {
                    let name = t.common.built_name().to_string();
                    out.cs().add_item(name, t.render(id, self));
                }
                Type::NewtypeStruct(n) => {
                    let name = n.common.built_name().to_string();
                    let tokens = n.render(id, self, &mut out);
                    out.cs().add_item(name, tokens);
                }
                Type::TypeAlias(a) => {
                    let name = a.common.built_name().to_string();
                    out.cs().add_item(name, a.render(self));
                }
                _ => {}
            }
        }

        if out.cs().get_root_mod().has_mod("builder") {
            out.cs()
                .get_root_mod()
                .get_mod("builder")
                .add_docs(" Types for composing complex structures.");
        }

        out.into_codespace()
    }

    pub(crate) fn add_error_mod(&self, out: &mut Outputspace) {
        // We only need the error mod once and we carefully control its
        // contents.
        if !out.cs().get_root_mod().has_mod("error") {
            let mut error_mod = codespace::Mod::default();
            error_mod.add_docs(" Error types.");
            error_mod.add_item(
                "",
                quote! {
                    /// Error from a `TryFrom` or `FromStr` implementation.
                    pub struct ConversionError(::std::borrow::Cow<'static, str>);

                    impl ::std::error::Error for ConversionError {}
                    impl ::std::fmt::Display for ConversionError {
                        fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>)
                            -> Result<(), ::std::fmt::Error>
                        {
                            ::std::fmt::Display::fmt(&self.0, f)
                        }
                    }

                    impl ::std::fmt::Debug for ConversionError {
                        fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>)
                            -> Result<(), ::std::fmt::Error>
                        {
                            ::std::fmt::Debug::fmt(&self.0, f)
                        }
                    }
                    impl From<&'static str> for ConversionError {
                        fn from(value: &'static str) -> Self {
                            Self(value.into())
                        }
                    }
                    impl From<String> for ConversionError {
                        fn from(value: String) -> Self {
                            Self(value.into())
                        }
                    }
                },
            );
            let _ = out.cs().get_root_mod().replace_mod("error", error_mod);
        }
    }

    pub(crate) fn render_ident(&self, id: &Id) -> TokenStream {
        self.render_ident_impl(id, None, false)
    }

    pub(crate) fn render_ident_with_scope(&self, id: &Id, scope: Option<&str>) -> TokenStream {
        self.render_ident_impl(id, scope, false)
    }

    pub(crate) fn render_raw_type(&self, id: &Id) -> TokenStream {
        self.render_ident_impl(id, None, true)
    }

    /// Whether a type gets a generated builder.
    ///
    /// A builder is generated for structs when
    /// [`Settings::with_struct_builder`](settings::Settings::with_struct_builder)
    /// is set. Rendering asks this before it emits one, so the query and the
    /// generated code cannot disagree.
    pub(crate) fn has_builder(&self, id: &Id) -> bool {
        self.settings.struct_builder
            && matches!(
                self.types.get(id).expect("invalid type id"),
                Type::Struct(_)
            )
    }

    /// Render the identifier of a type's generated builder, if present,
    /// optionally scoped to a module.
    ///
    /// Builders live in a `mod builder`, so the identifier is `builder::Name`,
    /// or `scope::builder::Name` under a scope.
    pub(crate) fn render_builder_ident(&self, id: &Id, scope: Option<&str>) -> Option<TokenStream> {
        self.has_builder(id).then(|| {
            let name_ident = format_ident!(
                "{}",
                self.types
                    .get(id)
                    .expect("invalid type id")
                    .name()
                    .expect("a struct has a name")
            );
            let scope_ident = scope.map(|scope| {
                let scope_ident = format_ident!("{scope}");
                quote! { #scope_ident:: }
            });
            quote! { #scope_ident builder::#name_ident }
        })
    }

    /// Render the identifier of a type as it reads in parameter
    /// position, optionally scoped to a module and optionally carrying
    /// an explicit lifetime on each reference it introduces.
    ///
    /// A caller passes what it owns cheaply and borrows the rest:
    /// primitives, the unit type, and an enum whose variants are all
    /// unit variants go by value, a `String` becomes a `&str`, and
    /// every other owned type is prefixed with `&`. An `Option` and a
    /// tuple keep their own syntax and apply the rule to what they
    /// hold, so an `Option<String>` reads as `Option<&str>`.
    pub(crate) fn render_parameter_ident(
        &self,
        id: &Id,
        scope: Option<&str>,
        lifetime: Option<&str>,
    ) -> TokenStream {
        let lifetime_tok = lifetime
            .map(|name| syn::Lifetime::new(&format!("'{name}"), proc_macro2::Span::call_site()));

        match self.types.get(id).expect("invalid type id") {
            // An all-unit-variant enum is value-like, so it passes by
            // value rather than by reference.
            Type::Enum(type_enum) if type_enum.every_variant_is_unit() => {
                self.render_ident_with_scope(id, scope)
            }

            Type::Enum(_)
            | Type::Struct(_)
            | Type::UnitStruct(_)
            | Type::TupleStruct(_)
            | Type::NewtypeStruct(_)
            | Type::TypeAlias(_)
            | Type::Native(_)
            | Type::Box(_)
            | Type::Vec(_)
            | Type::Map(..)
            | Type::Set(_)
            | Type::Array(..)
            | Type::JsonValue => {
                let ident = self.render_ident_with_scope(id, scope);
                quote! { & #lifetime_tok #ident }
            }

            // The borrowed form of a String is a &str, not a &String.
            Type::String => quote! { & #lifetime_tok str },

            // An Option holds a borrow of its content. Nested Options
            // collapse to one level, since the inner one says nothing
            // the outer one has not already said.
            Type::Option(inner_id) => {
                let inner = self.render_parameter_ident(inner_id, scope, lifetime);
                match self.types.get(inner_id).expect("invalid type id") {
                    Type::Option(_) => inner,
                    _ => {
                        let option_type = match &self.settings.std {
                            Std::FullyQualified => quote! { ::std::option::Option },
                            Std::Unqualified => quote! { Option },
                        };
                        quote! { #option_type<#inner> }
                    }
                }
            }

            // A tuple borrows element by element.
            Type::Tuple(inner_ids) => {
                let inner = inner_ids
                    .iter()
                    .map(|inner_id| self.render_parameter_ident(inner_id, scope, lifetime))
                    .collect::<Vec<_>>();
                // A one-element tuple needs its trailing comma, which
                // is what separates it from a parenthesized type.
                if inner.len() == 1 {
                    quote! { ( #( #inner, )* ) }
                } else {
                    quote! { ( #( #inner ),* ) }
                }
            }

            Type::Unit | Type::Boolean | Type::Integer(_) | Type::Float(_) | Type::Never => {
                self.render_ident_with_scope(id, scope)
            }
        }
    }

    /// Render `String` per the configured [`Std`] syntax.
    ///
    /// Bespoke impls that need the `String` don't have an ID they can use to
    /// render it.
    pub(crate) fn render_std_string(&self) -> TokenStream {
        match &self.settings.std {
            Std::FullyQualified => quote! { ::std::string::String },
            Std::Unqualified => quote! { String },
        }
    }

    /// Render the derive attribute given the computed traits for a type and
    /// the extra derives from settings.
    ///
    /// `comparison_exempt` marks a type as one of the two forms whose
    /// derive list keeps `Copy`, `Eq`, `PartialEq`, `Ord`, `PartialOrd`,
    /// and `Hash` under `typify_compat`: an enum whose variants are all
    /// unit variants, or a newtype wrapping a `String`. Under that
    /// setting, every other type has those six traits trimmed from the
    /// rendered list here, even where trait resolution granted them
    /// because some container depends on this type having them (a map
    /// key needs `Eq`/`Hash`, or `Ord`, for the container itself to
    /// derive them). The trim happens only here, at render, so that
    /// dependency keeps flowing through trait resolution undisturbed;
    /// this function does not add back a manual implementation to cover
    /// what it withholds, matching typify, which never wrote one for
    /// these six traits outside its two exceptions.
    ///
    /// `Copy` reaches only the first of those two forms in practice: a
    /// newtype wrapping a `String` never carries `Copy` into rendering,
    /// since a `String` is not `Copy` and trait resolution drops it
    /// long before this point.
    pub(crate) fn render_derives(
        &self,
        traits: &TypespaceTraitSet,
        extra_derives: &[String],
        comparison_exempt: bool,
    ) -> Option<TokenStream> {
        // Verify that traits that require manual implementation aren't
        // included as derives. If this happens it indicates that either the
        // finalize step didn't detect an unsatisfiable situation, or that the
        // caller (a renderer for a type) neglected to implement (and remove)
        // one of these traits.
        [TypespaceTrait::Display, TypespaceTrait::FromStr]
            .into_iter()
            .for_each(|manual_trait| {
                if traits.contains(&manual_trait) {
                    panic!(
                        "trying to derive {manual_trait} which requires a \
                        manual implementation; this is a bug",
                    )
                }
            });

        // TYPIFY COMPAT
        // typify derives these six only for an all-unit enum or a
        // string newtype; everywhere else it never derives or
        // implements them, even where a container elsewhere depends
        // on the type having them. typify_compat matches that outside
        // of the two exempted forms, without touching what trait
        // resolution computed.
        //
        // Copy's rule is narrower: typify grants it to the all-unit
        // enum alone, never to a string newtype. The shared exemption
        // is still right for it, because a string newtype wraps a
        // String and `provides` withholds Copy from String, so trait
        // resolution has already dropped it before rendering sees the
        // type.
        const WITHHELD_TRAITS: [TypespaceTrait; 6] = [
            TypespaceTrait::Copy,
            TypespaceTrait::Eq,
            TypespaceTrait::PartialEq,
            TypespaceTrait::Ord,
            TypespaceTrait::PartialOrd,
            TypespaceTrait::Hash,
        ];
        // typify collects every derive, its own and the caller's alike,
        // into one `BTreeSet<&str>`, so the attribute it writes is sorted
        // by rendered path and carries each derive once. Keying a
        // `BTreeMap` on the rendered path does the same here: the trait
        // derives and the extra derives sort together rather than the
        // extras trailing the rest, and a path named both ways appears
        // once.
        let derives = traits
            .iter()
            .filter(|tt| {
                comparison_exempt || !self.settings.typify_compat || !WITHHELD_TRAITS.contains(*tt)
            })
            .map(|tt| tt.render(self.settings))
            // TODO 8/20/2026
            // I think that we should validate (and maybe render) these extra
            // derives from settings during finalization and store them in the
            // TypespaceRenderer.
            .chain(
                self.settings
                    .extra_derives
                    .iter()
                    .chain(extra_derives.iter())
                    .map(|derive| {
                        syn::parse_str::<syn::Path>(derive)
                            .expect("invalid derive path")
                            .to_token_stream()
                    }),
            )
            .map(|tokens| (tokens.to_string(), tokens))
            .collect::<BTreeMap<_, _>>();

        (!derives.is_empty()).then(|| {
            let derives = derives.values();
            quote! {
                #[derive( #( #derives ),* )]
            }
        })
    }

    pub(crate) fn render_attrs<'b>(
        &'b self,
        extra_attrs: &'b [String],
    ) -> impl Iterator<Item = TokenStream> + 'b {
        self.settings
            .extra_attrs
            .iter()
            .chain(extra_attrs.iter())
            .map(|attr| attr.parse().unwrap())
    }

    pub(crate) fn render_ident_impl(
        &self,
        id: &Id,
        scope: Option<&str>,
        base_type: bool,
    ) -> TokenStream {
        let ty = self.types.get(id).unwrap();
        match ty {
            Type::Enum(Enum { common, .. })
            | Type::Struct(Struct { common, .. })
            | Type::UnitStruct(UnitStruct { common, .. })
            | Type::TupleStruct(TupleStruct { common, .. })
            | Type::NewtypeStruct(NewtypeStruct { common, .. })
            | Type::TypeAlias(TypeAlias { common, .. }) => {
                let name = common.built_name();
                let name_ident = format_ident!("{name}");

                if let Some(scope) = scope {
                    let scope_ident = format_ident!("{scope}");
                    quote! { #scope_ident::#name_ident }
                } else {
                    name_ident.into_token_stream()
                }
            }

            Type::Native(Native {
                container,
                parameters,
            }) => {
                let path = container.path();
                let parameters = (!base_type && !parameters.is_empty()).then(|| {
                    let parameter_idents = parameters
                        .iter()
                        .map(|param_id| self.render_ident_with_scope(param_id, scope));
                    quote! {
                        < #( #parameter_idents ),* >
                    }
                });
                quote! {
                    #path #parameters
                }
            }

            Type::Array(schema_ref, n) => {
                let inner_ident = self.render_ident_with_scope(schema_ref, scope);
                quote! {
                    [#inner_ident; #n]
                }
            }
            Type::Tuple(schema_refs) => {
                let inner_idents = schema_refs
                    .iter()
                    .map(|id| self.render_ident_with_scope(id, scope));
                quote! {
                    ( #( #inner_idents ),* )
                }
            }

            Type::Option(option_id) => {
                let option_type = match &self.settings.std {
                    Std::FullyQualified => quote! { ::std::option::Option },
                    Std::Unqualified => quote! { Option },
                };
                if base_type {
                    option_type
                } else {
                    let option_ident = self.render_ident_with_scope(option_id, scope);
                    quote! {
                        #option_type<#option_ident>
                    }
                }
            }
            Type::Box(boxed_id) => {
                let box_type = match &self.settings.std {
                    Std::FullyQualified => quote! { ::std::boxed::Box },
                    Std::Unqualified => quote! { Box },
                };
                if base_type {
                    box_type
                } else {
                    let boxed_ident = self.render_ident_with_scope(boxed_id, scope);
                    quote! {
                        #box_type<#boxed_ident>
                    }
                }
            }
            Type::Set(inner_id) => {
                // Without an override, a set renders as a Vec:
                // deduplication is not enforced, but no trait demands
                // are made of the element type either.
                let set_type = self.settings.set_type.rendered_path(&self.settings.std);
                if base_type {
                    quote! { #set_type }
                } else {
                    let inner_ident = self.render_ident_with_scope(inner_id, scope);
                    quote! {
                        #set_type<#inner_ident>
                    }
                }
            }
            Type::Vec(inner_id) => {
                let vec_type = self.settings.vec_type.rendered_path(&self.settings.std);
                if base_type {
                    quote! { #vec_type }
                } else {
                    let inner_ident = self.render_ident_with_scope(inner_id, scope);
                    quote! {
                        #vec_type<#inner_ident>
                    }
                }
            }
            Type::Map(key_id, value_id) => {
                // A string-to-JSON-value map renders as ::serde_json::Map
                // regardless of the configured map type, matching the map
                // type inside ::serde_json::Value itself.
                let key_ty = self.types.get(key_id).unwrap();
                let value_ty = self.types.get(value_id).unwrap();
                let map_type =
                    if matches!(key_ty, Type::String) && matches!(value_ty, Type::JsonValue) {
                        quote! { ::serde_json::Map }
                    } else {
                        let path = self.settings.map_type.rendered_path(&self.settings.std);
                        quote! { #path }
                    };
                if base_type {
                    map_type
                } else {
                    let key_ident = self.render_ident_with_scope(key_id, scope);
                    let value_ident = self.render_ident_with_scope(value_id, scope);
                    quote! {
                        #map_type<#key_ident, #value_ident>
                    }
                }
            }
            Type::Boolean => quote! { bool },
            Type::Integer(name) | Type::Float(name) => syn::parse_str::<syn::TypePath>(name)
                .unwrap()
                .to_token_stream(),
            Type::String => match &self.settings.std {
                Std::FullyQualified => quote! { ::std::string::String },
                Std::Unqualified => quote! { String },
            },
            Type::JsonValue => quote! { ::serde_json::Value },
            Type::Never => quote! { ::json_serde::Never },
            Type::Unit => quote! { () },
        }
    }

    pub(crate) fn render_struct_property(
        &self,
        StructProperty {
            rust_name,
            json_name,
            state,
            description,
            type_id,
        }: &StructProperty<Id>,
        serde_derives: SerdeDerives,
        vis_pub: bool,
        context: &str,
        out: &mut Outputspace,
    ) -> RenderedStructProperty {
        let description = description.as_ref().map(|text| {
            quote! {
                #[doc = #text]
            }
        });

        let mut serde_options = serde_derives.attrs();

        match json_name {
            StructPropertySerde::None => {}
            StructPropertySerde::Rename(s) => {
                serde_options.push(quote! {
                    rename = #s
                });
            }
            StructPropertySerde::Flatten => {
                serde_options.push(quote! {
                    flatten
                });
            }
        };

        // A property with a default value calls a function in the
        // `defaults` module to produce it. The serde attribute and the
        // struct builder name the same function, so the path is worked
        // out once, here, ahead of the match below: the attribute then
        // follows a rename or flatten and precedes whatever that match
        // adds.
        let default = match state {
            StructPropertyState::Required => DefaultConstructor::None,
            StructPropertyState::Optional | StructPropertyState::Default => {
                DefaultConstructor::Default
            }
            StructPropertyState::DefaultValue(JsonValue(value)) => {
                let fn_path = self.default_fn(context, rust_name, type_id, value, out);
                serde_options.push(quote! { default = #fn_path });
                let call = format!("{fn_path}()")
                    .parse::<TokenStream>()
                    .expect("a function path followed by () lexes as tokens");
                DefaultConstructor::Generated(call)
            }
        };

        let ty = self.types.get(type_id).unwrap();

        enum TypeOfInterest<Id> {
            // If the type is itself an Option (i.e. may be null), let's save
            // the inner type, which we may use i.e. if the field may be
            // absent and the consumer has specified a custom type for that
            // situation. In other cases, we need to know if the type is an
            // Option to add the appropriate serde annotations.
            Option(Id),
            // A Never property that's non-required turns into the
            // ::json_serde::Absent type.
            Never,
            // Other types don't require special handling.
            Other,
        }

        let type_of_interest = match ty {
            Type::Option(id) => TypeOfInterest::Option(id),
            Type::Never => TypeOfInterest::Never,
            _ => TypeOfInterest::Other,
        };

        let ty_ident = self.render_ident(type_id);
        let ty_ident_scoped = self.render_ident_with_scope(type_id, Some("super"));

        let std_opt_type = match &self.settings.std {
            Std::FullyQualified => quote! { ::std::option::Option },
            Std::Unqualified => quote! { Option },
        };
        let std_opt_type_str = std_opt_type.clone().token_print();
        let std_opt_is_none = format!("{std_opt_type_str}::is_none");

        let (prop_ty_ident, prop_ty_ident_scoped) = match (state, type_of_interest) {
            // A required field needs no serde annotations.
            (StructPropertyState::Required, TypeOfInterest::Other) => (ty_ident, ty_ident_scoped),

            // A required field that is an Option<T> needs a custom
            // deserializer so that the field is mandatory, but may be null;
            // without this attribute, the default handling is to permit
            // either.
            (StructPropertyState::Required, TypeOfInterest::Option(_)) => {
                let opt_deserialize = format!("{std_opt_type_str}::deserialize");
                // TODO schemars schema_with?
                serde_options.push(quote! { deserialize_with = #opt_deserialize });
                (ty_ident, ty_ident_scoped)
            }

            // An optional field that is not an Option<T> may not be null; we
            // use the json::serde::deserialize_some function to enforce this.
            (StructPropertyState::Optional, TypeOfInterest::Other) => {
                serde_options.push(quote! { default });
                serde_options.push(quote! {
                    deserialize_with = "::json_serde::deserialize_some"
                });
                serde_options.push(quote! { skip_serializing_if = #std_opt_is_none });
                // TODO schemars schema_with

                (
                    quote! { #std_opt_type<#ty_ident> },
                    quote! {#std_opt_type<#ty_ident_scoped>},
                )
            }

            // An optional field that is also an Option<T> may be the type
            // value, null, or absent. Customizable settings determine the
            // handling of this.
            (StructPropertyState::Optional, TypeOfInterest::Option(inner_id)) => {
                match &self.settings.optional_nullable {
                    OptionalNullable::ConflateAsAbsent => {
                        serde_options.push(quote! {
                            skip_serializing_if = #std_opt_is_none
                        });
                        (ty_ident, ty_ident_scoped)
                    }
                    OptionalNullable::ConflateAsNull => {
                        // We always serialize--including `None` as `null`--so
                        // no serde options are necessary.
                        (ty_ident, ty_ident_scoped)
                    }
                    OptionalNullable::DoubleOption => {
                        serde_options.push(quote! { default });
                        serde_options.push(quote! {
                            deserialize_with = "::json_serde::deserialize_some"
                        });
                        serde_options.push(quote! {
                            skip_serializing_if = #std_opt_is_none
                        });

                        (
                            quote! { #std_opt_type<#ty_ident> },
                            quote! { #std_opt_type<#ty_ident_scoped> },
                        )
                    }
                    // Trait resolution's edge classifier mirrors this
                    // condition.
                    OptionalNullable::CustomType(container) => {
                        let custom_type_path = container.rendered_path(&self.settings.std);
                        serde_options.push(quote! { default });
                        let is_absent = "::json_serde::OptionalNullable::is_absent";
                        serde_options.push(quote! {
                            skip_serializing_if = #is_absent
                        });

                        let inner_ident = self.render_ident(inner_id);
                        let inner_ident_scoped =
                            self.render_ident_with_scope(inner_id, Some("super"));

                        (
                            quote! { #custom_type_path<#inner_ident> },
                            quote! { #custom_type_path<#inner_ident_scoped> },
                        )
                    }
                }
            }
            (StructPropertyState::Default, TypeOfInterest::Option(_) | TypeOfInterest::Other) => {
                serde_options.push(quote! { default });
                self.render_struct_property_add_skip(
                    &mut serde_options,
                    type_id,
                    ty,
                    std_opt_is_none,
                );

                (ty_ident, ty_ident_scoped)
            }
            (
                StructPropertyState::DefaultValue(_),
                TypeOfInterest::Option(_) | TypeOfInterest::Other,
            ) => {
                // The default function and its serde attribute are
                // settled above; a default value leaves the property's
                // type alone.
                (ty_ident, ty_ident_scoped)
            }

            (StructPropertyState::Optional, TypeOfInterest::Never) => {
                // Convert to the ::json_serde::Absent type. It must have
                // `default` since it cannot be deserialized, and
                // `skip_serializing_if = "::json_serde::always"` because it
                // cannot be serialized (and to work around schemars bugs in
                // all versions).
                serde_options.push(quote! { default });
                serde_options.push(quote! {
                    skip_serializing_if = "::json_serde::always"
                });

                (
                    quote! { ::json_serde::Absent },
                    quote! { ::json_serde::Absent },
                )
            }
            (
                StructPropertyState::Required
                | StructPropertyState::Default
                | StructPropertyState::DefaultValue(_),
                TypeOfInterest::Never,
            ) => unreachable!("finalization rejects a Never property that requires a value"),
        };

        let rust_name_ident = format_ident!("{rust_name}");

        RenderedStructProperty {
            description,
            serde: serde_options,
            vis_pub,
            rust_name_ident,
            prop_ty_ident,
            prop_ty_ident_scoped,
            default,
        }
    }

    /// Name the `defaults` function that produces a property's default
    /// value, adding whatever definition that takes.
    ///
    /// A value that one of the shared functions produces records that
    /// function, which [`Outputspace::into_codespace`] defines once for
    /// the whole codespace, and yields the path that instantiates it.
    /// Any other value takes a function of its own, named for the
    /// property and added to the module here.
    fn default_fn(
        &self,
        context: &str,
        rust_name: &str,
        type_id: &Id,
        value: &serde_json::Value,
        out: &mut Outputspace,
    ) -> String {
        match shared_default_fn(self.types, type_id, value) {
            Some(SharedDefaultFn { helper, path }) => {
                out.add_default_helper(helper);
                path
            }
            None => {
                // TODO 9/3/2026
                // I don't love that the door is open to name collisions here,
                // but this is what typify 1 does so we'll hold the line for
                // now.
                //
                // The context is the containing type's path, which for an
                // enum's struct variant is the enum name followed by the
                // variant name and so is CamelCase. Snake-casing the joined
                // name gives the function a name `non_snake_case` accepts and
                // folds any run of separators down to one underscore.
                let fn_name_str = heck::AsSnakeCase(format!("{context}_{rust_name}")).to_string();
                let fn_name_ident = format_ident!("{}", fn_name_str);

                let ty_for_fn = self.render_ident_with_scope(type_id, Some("super"));
                let body = self.generate_default(value, type_id);
                // Key the item by the CONTAINING TYPE, not by the
                // function, which is what typify does
                // (typify-impl/src/structs.rs, `add_item(Defaults,
                // type_name, ..)`). A mod's items sort by key, so keying
                // by the function would order the module alphabetically
                // by function name; keying by the type groups each
                // type's functions together, in property order, and
                // orders the groups by type name. `context` is the
                // containing type's path in CamelCase, the same string
                // typify passes.
                out.cs().get_root_mod().get_mod("defaults").add_item(
                    context,
                    quote! {
                        pub(super) fn #fn_name_ident() -> #ty_for_fn {
                            #body
                        }
                    },
                );

                format!("defaults::{fn_name_str}")
            }
        }
    }

    fn render_struct_property_add_skip(
        &self,
        serde_options: &mut SerdeAttrs,
        ty_id: &Id,
        ty: &Type<Id>,
        std_opt_is_none: String,
    ) {
        match ty {
            // Here we assume that the generated type for the field has an
            // implementation of Default. There isn't a simple "is_default()"
            // that we can presume... so we'll just leave it.
            all_named_types!(_) => {}

            // The same applies to external types.
            Type::Native(_) => {}

            Type::Option(_) => {
                // We have a property whose type is an Option meaning that it
                // may have a value of null. The "Default" state means that it
                // takes on its "intrinsic" default value if the field is
                // absent. This means we can ignore any of the
                // optional/nullable settings as they don't particularly apply
                // here.
                //
                // Note that #[serde(default)] is a no-op for Option<T>.
                serde_options.push(quote! { skip_serializing_if = #std_opt_is_none });
            }
            Type::Box(boxed_id) => {
                let boxed_ty = self.types.get(boxed_id).unwrap();
                self.render_struct_property_add_skip(
                    serde_options,
                    boxed_id,
                    boxed_ty,
                    std_opt_is_none,
                );
            }

            // TYPIFY COMPAT. typify never skips serialization of a
            // default-state String, so imitation withholds the skip;
            // the attribute below returns when the flag goes.
            Type::String if self.settings.typify_compat => {}

            Type::Vec(_) | Type::Map(_, _) | Type::Set(_) | Type::String => {
                let ty_raw_ident = self.render_raw_type(ty_id);
                let is_empty = format!("{}::is_empty", ty_raw_ident.token_print());
                serde_options.push(quote! { skip_serializing_if = #is_empty });
            }

            // As above, sure--there might be a Default impl--but we don't have
            // a way to check if the value matches that value, so... whatever.
            Type::Array(_, _) | Type::Tuple(_) => {}

            Type::Unit => {
                // TODO 9.7.2026
                // It's possible that we could add skip here, but typify
                // doesn't do it, and it could also screw up JsonSchema
                // generation.
            }

            Type::Boolean => {
                // Congratulation! You found an external expression of my
                // insanity. I am genuinely curious if anyone will ever
                // encounter this via a generated type. Note that this may
                // cause invalid code to be generated e.g. if the type is
                // Box<bool>, and I'm fine with that.

                // I've had second thoughts and am leaving this out of the
                // code, but in as a reminder of crazier times...

                // serde_options.push(quote! {
                //     skip_serializing_if = "std::ops::Not::not"
                // });
            }

            // There isn't an "is_zero()" so... we'll just leave it be.
            Type::Integer(_) | Type::Float(_) => {}

            // This isn't a runtime error that could be handled; it's a
            // programming error.
            Type::JsonValue => panic!("Default value for JsonValue is not supported"),

            // A Never property reaches this function in no state:
            // finalization rejects every state that would, and the
            // Optional state renders without a skip of this kind.
            Type::Never => unreachable!("Never properties add no skip attribute"),
        }
    }

    fn array_bounds<'b>(&'b self, id: &'b Id) -> Option<(usize, Option<usize>)> {
        array_bounds(self.types, id)
    }
}

/// How many array elements a type serializes to: an inclusive minimum
/// and an optional maximum.
///
/// `None` means the count is unknown, which leaves a caller's schema
/// unconstrained rather than wrong.
pub(crate) fn array_bounds<'a, Id: Ord>(
    types: &'a BTreeMap<Id, Type<Id>>,
    id: &'a Id,
) -> Option<(usize, Option<usize>)> {
    array_bounds_seen(types, id, &mut BTreeSet::new())
}

/// array_bounds with the walk's visited ids threaded through, so a
/// tuple struct's remainder shares one set with the walk that reached
/// it.
fn array_bounds_seen<'a, Id: Ord>(
    types: &'a BTreeMap<Id, Type<Id>>,
    id: &'a Id,
    seen: &mut BTreeSet<&'a Id>,
) -> Option<(usize, Option<usize>)> {
    // A newtype, alias, or Box can reach one this walk already passed. That
    // graph is legal: `break_cycles` puts a `Box` in every cycle, and a named
    // type in the loop keeps it clear of `check_anonymous_cycles`. Revisiting
    // an id answers "unknown" instead of walking it again.
    let mut id = id;
    loop {
        if !seen.insert(id) {
            return None;
        }
        let ty = types.get(id)?;
        match ty {
            // We could pick these types apart... but not now.
            Type::Enum(_) | Type::UnitStruct(_) => {
                return None;
            }

            // A struct serializes as an object, not an array.
            Type::Struct(_) => {
                return None;
            }

            // A tuple struct is its fixed fields plus whatever its own
            // remainder contributes.
            Type::TupleStruct(tuple_struct) => {
                let fixed = tuple_struct.fields.len();
                return match tuple_struct.rest.as_ref() {
                    None => Some((fixed, Some(fixed))),
                    Some(rest_id) => {
                        let (rest_min, rest_max) = array_bounds_seen(types, rest_id, seen)?;
                        Some((fixed + rest_min, rest_max.map(|max| fixed + max)))
                    }
                };
            }

            Type::NewtypeStruct(NewtypeStruct {
                inner: inner_id, ..
            })
            | Type::TypeAlias(TypeAlias {
                target: inner_id, ..
            })
            | Type::Box(inner_id) => {
                id = inner_id;
            }

            // If we see a native type in this position, we just hope for
            // the best in terms of the bounds.
            //
            // We could do something cute here, like export its schema and
            // then--for tuples with flattened remainders--modify the
            // schema at runtime... but that's pretty fragile since we have
            // no idea of the structure of the output schema.
            Type::Native(_) => {
                return Some((0, None));
            }

            // Unbounded array
            Type::Vec(_) | Type::Set(_) => {
                return Some((0, None));
            }

            // Fixed-length array
            Type::Array(_, size) => {
                return Some((*size, Some(*size)));
            }

            // TODO 9/10/2026
            // unsure; null can't be serialized so we should probably
            // disallow?
            Type::Option(_) => {
                return None;
            }

            // A tuple serializes as an array of exactly its elements.
            Type::Tuple(items) => {
                return Some((items.len(), Some(items.len())));
            }

            // Not serialized as an array:
            Type::Map(_, _)
            | Type::Unit
            | Type::Boolean
            | Type::Integer(_)
            | Type::Float(_)
            | Type::String
            | Type::JsonValue
            | Type::Never => {
                return None;
            }
        }
    }
}

pub(crate) enum DefaultConstructor {
    None,
    Default,
    Generated(TokenStream),
}

pub(crate) struct RenderedStructProperty {
    pub description: Option<TokenStream>,
    pub serde: SerdeAttrs,
    pub vis_pub: bool,
    pub rust_name_ident: syn::Ident,
    pub prop_ty_ident: TokenStream,
    pub prop_ty_ident_scoped: TokenStream,
    pub default: DefaultConstructor,
}

impl ToTokens for RenderedStructProperty {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            description,
            serde,
            vis_pub,
            rust_name_ident,
            prop_ty_ident,
            prop_ty_ident_scoped: _,
            default: _,
        } = self;
        let vis_pub = vis_pub.then(|| quote! { pub });
        tokens.extend(quote! {
            #description
            #serde
            #vis_pub #rust_name_ident: #prop_ty_ident
        });
    }
}

/// Initialize `TypeCommonBuilt` for every named type before trait propagation.
fn build_commons<Id: Clone>(types: &mut BTreeMap<Id, Type<Id>>) {
    for typ in types.values_mut() {
        if let Some(common) = typ.common_mut() {
            common.built = Some(TypeCommonBuilt {
                traits: TypespaceTraitSet::empty(),
                // The real answer needs the post-break_cycles graph, so
                // resolve_from_string_irrefutable computes it later;
                // this pass only creates the slot.
                from_string_irrefutable: false,
            });
        }
    }
}

trait TokenPrint {
    fn token_print(self) -> String;
}

impl TokenPrint for proc_macro2::TokenStream {
    fn token_print(self) -> String {
        self.into_iter()
            .map(|tt| tt.to_string())
            .collect::<String>()
    }
}

/// Whether the type with `id` implements `trait_`.
///
/// A named type answers from the trait set resolution gave it.
/// Everything else answers structurally, descending into children
/// through [`trait_resolution::unnamed_provides`], so a container's
/// answer follows its elements and a native's follows its declaration.
/// A type alias has no impl site of its own and forwards to its target.
///
/// `seen` holds the ids on the walk's current path; a revisit answers
/// `false`, which keeps a cyclic graph terminating and is the
/// pessimistic answer a cycle deserves.
///
/// Both callers need this and neither can use the other's form:
/// [`view::Type::has_impl`] asks it of a finalized typespace, and the
/// desired phase asks it of a map mid-resolution, before any
/// [`Typespace`] exists.
pub(crate) fn has_trait<Id>(
    types: &BTreeMap<Id, Type<Id>>,
    settings: &Settings,
    id: &Id,
    trait_: TypespaceTrait,
    seen: &mut BTreeSet<Id>,
) -> bool
where
    Id: Clone + Ord,
{
    if !seen.insert(id.clone()) {
        return false;
    }

    let typ = types.get(id).unwrap();
    let answer = match typ {
        build::Type::Enum(e) => e
            .common
            .built
            .as_ref()
            .is_some_and(|b| b.traits.contains(&trait_)),
        build::Type::Struct(s) => s
            .common
            .built
            .as_ref()
            .is_some_and(|b| b.traits.contains(&trait_)),
        build::Type::NewtypeStruct(n) => n
            .common
            .built
            .as_ref()
            .is_some_and(|b| b.traits.contains(&trait_)),
        build::Type::UnitStruct(u) => u
            .common
            .built
            .as_ref()
            .is_some_and(|b| b.traits.contains(&trait_)),
        build::Type::TupleStruct(t) => t
            .common
            .built
            .as_ref()
            .is_some_and(|b| b.traits.contains(&trait_)),
        // A type alias has no impl site of its own; its answer is
        // entirely its target's, exactly as required resolution
        // treats it (see `Feasibility::IfAllChildren`).
        build::Type::TypeAlias(a) => has_trait(types, settings, &a.target, trait_, seen),
        typ => crate::trait_resolution::unnamed_provides(typ, trait_, settings, &mut |child_id| {
            has_trait(types, settings, child_id, trait_, seen)
        }),
    };
    seen.remove(id);
    answer
}