typify-impl 0.6.1

typify backend implementation
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
// Copyright 2025 Oxide Computer Company

use std::collections::{BTreeMap, BTreeSet, HashMap};

use proc_macro2::{Punct, Spacing, TokenStream, TokenTree};
use quote::{format_ident, quote, ToTokens};
use schemars::schema::{Metadata, Schema};
use syn::Path;
use unicode_ident::is_xid_continue;

use crate::{
    enums::output_variant,
    output::{OutputSpace, OutputSpaceMod},
    sanitize,
    structs::{generate_serde_attr, DefaultFunction},
    util::{get_type_name, metadata_description, unique, TypePatch},
    Case, DefaultImpl, Name, Result, TypeId, TypeSpace, TypeSpaceImpl,
};

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct SchemaWrapper(Schema);

impl Eq for SchemaWrapper {}

impl Ord for SchemaWrapper {
    fn cmp(&self, _other: &Self) -> std::cmp::Ordering {
        std::cmp::Ordering::Equal
    }
}
impl PartialOrd for SchemaWrapper {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct TypeEntryEnum {
    pub name: String,
    pub rename: Option<String>,
    pub description: Option<String>,
    pub default: Option<WrappedValue>,
    pub tag_type: EnumTagType,
    pub variants: Vec<Variant>,
    pub deny_unknown_fields: bool,
    pub bespoke_impls: BTreeSet<TypeEntryEnumImpl>,
    pub schema: SchemaWrapper,
}

/// Cached attributes that (mostly) result in customized impl generation.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum TypeEntryEnumImpl {
    AllSimpleVariants,
    UntaggedFromStr,
    UntaggedDisplay,
    /// This is a cached marker to let us know that at least one of the
    /// variants is irrefutably a string. There is currently no associated
    /// implementation that we generate.
    UntaggedFromStringIrrefutable,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct TypeEntryStruct {
    pub name: String,
    pub rename: Option<String>,
    pub description: Option<String>,
    pub default: Option<WrappedValue>,
    pub properties: Vec<StructProperty>,
    pub deny_unknown_fields: bool,
    pub schema: SchemaWrapper,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct TypeEntryNewtype {
    pub name: String,
    pub rename: Option<String>,
    pub description: Option<String>,
    pub default: Option<WrappedValue>,
    pub type_id: TypeId,
    pub constraints: TypeEntryNewtypeConstraints,
    pub schema: SchemaWrapper,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum TypeEntryNewtypeConstraints {
    None,
    EnumValue(Vec<WrappedValue>),
    DenyValue(Vec<WrappedValue>),
    String {
        max_length: Option<u32>,
        min_length: Option<u32>,
        pattern: Option<String>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct TypeEntryNative {
    pub type_name: String,
    impls: Vec<TypeSpaceImpl>,
    // TODO to support const generics, this can be some sort of TypeOrValue,
    // but note that we may some day need to disambiguate char and &'static str
    // since schemars represents a char as a string of length 1.
    pub parameters: Vec<TypeId>,
}
impl TypeEntryNative {
    pub(crate) fn name_match(&self, type_name: &Name) -> bool {
        let native_name = self.type_name.rsplit("::").next().unwrap();
        !self.parameters.is_empty()
            || matches!(type_name, Name::Required(req) if req == native_name)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct WrappedValue(pub serde_json::Value);
impl WrappedValue {
    pub(crate) fn new(value: serde_json::Value) -> Self {
        Self(value)
    }
}

impl Ord for WrappedValue {
    fn cmp(&self, _: &Self) -> std::cmp::Ordering {
        std::cmp::Ordering::Equal
    }
}
impl PartialOrd for WrappedValue {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

// TODO This struct needs to go away (again). The derives should go into the
// generated struct/enum/newtype structs. Same for the impls. Native types will
// also have impls. Builtin generic types such as Box or Vec will delegate to
// their subtypes (while recursive, it is necessarily terminating... though I
// suppose we could memoize it). Builtin simple types such as u64 or String
// have a static list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TypeEntry {
    pub details: TypeEntryDetails,
    pub extra_derives: BTreeSet<String>,
    pub extra_attrs: BTreeSet<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum TypeEntryDetails {
    Enum(TypeEntryEnum),
    Struct(TypeEntryStruct),
    Newtype(TypeEntryNewtype),

    /// Native types exported from a well-known crate.
    Native(TypeEntryNative),

    // Types from core and std.
    Option(TypeId),
    Box(TypeId),
    Vec(TypeId),
    Map(TypeId, TypeId),
    Set(TypeId),
    Array(TypeId, usize),
    Tuple(Vec<TypeId>),
    Unit,
    Boolean,
    /// Integers
    Integer(String),
    /// Floating point numbers; not Eq, Ord, or Hash
    Float(String),
    /// Strings... which we handle a little specially.
    String,
    /// serde_json::Value which we also handle specially.
    JsonValue,

    /// While these types won't very make their way out to the user, we need
    /// reference types in particular to represent simple type aliases between
    /// types named as reference targets.
    Reference(TypeId),
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum EnumTagType {
    External,
    Internal { tag: String },
    Adjacent { tag: String, content: String },
    Untagged,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Variant {
    pub raw_name: String,
    pub ident_name: Option<String>,
    pub description: Option<String>,
    pub details: VariantDetails,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum VariantDetails {
    Simple,
    Item(TypeId),
    Tuple(Vec<TypeId>),
    Struct(Vec<StructProperty>),
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct StructProperty {
    pub name: String,
    pub rename: StructPropertyRename,
    pub state: StructPropertyState,
    pub description: Option<String>,
    pub type_id: TypeId,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum StructPropertyRename {
    None,
    Rename(String),
    Flatten,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum StructPropertyState {
    Required,
    Optional,
    Default(WrappedValue),
}

#[derive(Debug)]
pub(crate) enum DefaultKind {
    Intrinsic,
    Specific,
    Generic(DefaultImpl),
}

fn variants_unique(variants: &[Variant]) -> bool {
    unique(
        variants
            .iter()
            .map(|variant| variant.ident_name.as_ref().unwrap()),
    )
}

impl TypeEntryEnum {
    pub(crate) fn from_metadata(
        type_space: &TypeSpace,
        type_name: Name,
        metadata: &Option<Box<Metadata>>,
        tag_type: EnumTagType,
        mut variants: Vec<Variant>,
        deny_unknown_fields: bool,
        schema: Schema,
    ) -> TypeEntry {
        // Let's find some decent names for variants. We first try the simple
        // sanitization.
        variants.iter_mut().for_each(|variant| {
            let ident_name = sanitize(&variant.raw_name, Case::Pascal);
            variant.ident_name = Some(ident_name);
        });

        // If variants aren't unique, we're turn the elided characters into
        // 'x's.
        if !variants_unique(&variants) {
            variants.iter_mut().for_each(|variant| {
                let ident_name = sanitize(
                    &variant
                        .raw_name
                        .replace(|c| c == '_' || !is_xid_continue(c), "X"),
                    Case::Pascal,
                );
                variant.ident_name = Some(ident_name);
            });
        }

        // If variants still aren't unique, we fail: we'd rather not emit code
        // that can't compile
        if !variants_unique(&variants) {
            let mut counts = HashMap::new();
            variants.iter().for_each(|variant| {
                counts
                    .entry(variant.ident_name.as_ref().unwrap())
                    .and_modify(|xxx| *xxx += 1)
                    .or_insert(0);
            });
            let dups = variants
                .iter()
                .filter(|variant| *counts.get(variant.ident_name.as_ref().unwrap()).unwrap() > 0)
                .map(|variant| variant.raw_name.as_str())
                .collect::<Vec<_>>()
                .join(",");
            panic!("Failed to make unique variant names for [{}]", dups);
        }

        let name = get_type_name(&type_name, metadata).unwrap();
        let rename = None;
        let description = metadata_description(metadata);

        let type_patch = TypePatch::new(type_space, name);

        let details = TypeEntryDetails::Enum(Self {
            name: type_patch.name,
            rename,
            description,
            default: None,
            tag_type,
            variants,
            deny_unknown_fields,
            bespoke_impls: Default::default(),
            schema: SchemaWrapper(schema),
        });

        TypeEntry {
            details,
            extra_derives: type_patch.derives,
            extra_attrs: type_patch.attrs,
        }
    }

    pub(crate) fn finalize(&mut self, type_space: &TypeSpace) {
        self.bespoke_impls = [
            // Not untagged with all simple variants.
            (self.tag_type != EnumTagType::Untagged
                && !self.variants.is_empty()
                && self
                    .variants
                    .iter()
                    .all(|variant| matches!(variant.details, VariantDetails::Simple)))
            .then_some(TypeEntryEnumImpl::AllSimpleVariants),
            // Untagged and all variants impl FromStr, but none **is** a
            // String (i.e. irrefutably).
            untagged_newtype_variants(
                type_space,
                &self.tag_type,
                &self.variants,
                TypeSpaceImpl::FromStr,
                Some(TypeSpaceImpl::FromStringIrrefutable),
            )
            .then_some(TypeEntryEnumImpl::UntaggedFromStr),
            // Untagged and all variants impl Display.
            untagged_newtype_variants(
                type_space,
                &self.tag_type,
                &self.variants,
                TypeSpaceImpl::Display,
                None,
            )
            .then_some(TypeEntryEnumImpl::UntaggedDisplay),
            untagged_newtype_string(type_space, &self.tag_type, &self.variants)
                .then_some(TypeEntryEnumImpl::UntaggedFromStringIrrefutable),
        ]
        .into_iter()
        .flatten()
        .collect();
    }
}

impl Variant {
    pub(crate) fn new(
        raw_name: String,
        description: Option<String>,
        details: VariantDetails,
    ) -> Self {
        Self {
            raw_name,
            ident_name: None,
            description,
            details,
        }
    }
}

impl TypeEntryStruct {
    pub(crate) fn from_metadata(
        type_space: &TypeSpace,
        type_name: Name,
        metadata: &Option<Box<Metadata>>,
        properties: Vec<StructProperty>,
        deny_unknown_fields: bool,
        schema: Schema,
    ) -> TypeEntry {
        let name = get_type_name(&type_name, metadata).unwrap();
        let rename = None;
        let description = metadata_description(metadata);
        let default = metadata
            .as_ref()
            .and_then(|m| m.default.as_ref())
            .cloned()
            .map(WrappedValue::new);

        let type_patch = TypePatch::new(type_space, name);

        let details = TypeEntryDetails::Struct(Self {
            name: type_patch.name,
            rename,
            description,
            default,
            properties,
            deny_unknown_fields,
            schema: SchemaWrapper(schema),
        });

        TypeEntry {
            details,
            extra_derives: type_patch.derives,
            extra_attrs: type_patch.attrs,
        }
    }
}

impl TypeEntryNewtype {
    pub(crate) fn from_metadata(
        type_space: &TypeSpace,
        type_name: Name,
        metadata: &Option<Box<Metadata>>,
        type_id: TypeId,
        schema: Schema,
    ) -> TypeEntry {
        let name = get_type_name(&type_name, metadata).unwrap();
        let rename = None;
        let description = metadata_description(metadata);

        let type_patch = TypePatch::new(type_space, name);

        let details = TypeEntryDetails::Newtype(Self {
            name: type_patch.name,
            rename,
            description,
            default: None,
            type_id,
            constraints: TypeEntryNewtypeConstraints::None,
            schema: SchemaWrapper(schema),
        });

        TypeEntry {
            details,
            extra_derives: type_patch.derives,
            extra_attrs: type_patch.attrs,
        }
    }

    pub(crate) fn from_metadata_with_enum_values(
        type_space: &TypeSpace,
        type_name: Name,
        metadata: &Option<Box<Metadata>>,
        type_id: TypeId,
        enum_values: &[serde_json::Value],
        schema: Schema,
    ) -> TypeEntry {
        let name = get_type_name(&type_name, metadata).unwrap();
        let rename = None;
        let description = metadata_description(metadata);

        let type_patch = TypePatch::new(type_space, name);

        let details = TypeEntryDetails::Newtype(Self {
            name: type_patch.name,
            rename,
            description,
            default: None,
            type_id,
            constraints: TypeEntryNewtypeConstraints::EnumValue(
                enum_values.iter().cloned().map(WrappedValue::new).collect(),
            ),
            schema: SchemaWrapper(schema),
        });

        TypeEntry {
            details,
            extra_derives: type_patch.derives,
            extra_attrs: type_patch.attrs,
        }
    }

    pub(crate) fn from_metadata_with_deny_values(
        type_space: &TypeSpace,
        type_name: Name,
        metadata: &Option<Box<Metadata>>,
        type_id: TypeId,
        enum_values: &[serde_json::Value],
        schema: Schema,
    ) -> TypeEntry {
        let name = get_type_name(&type_name, metadata).unwrap();
        let rename = None;
        let description = metadata_description(metadata);

        let type_patch = TypePatch::new(type_space, name);

        let details = TypeEntryDetails::Newtype(Self {
            name: type_patch.name,
            rename,
            description,
            default: None,
            type_id,
            constraints: TypeEntryNewtypeConstraints::DenyValue(
                enum_values.iter().cloned().map(WrappedValue::new).collect(),
            ),
            schema: SchemaWrapper(schema),
        });

        TypeEntry {
            details,
            extra_derives: type_patch.derives,
            extra_attrs: type_patch.attrs,
        }
    }

    pub(crate) fn from_metadata_with_string_validation(
        type_space: &TypeSpace,
        type_name: Name,
        metadata: &Option<Box<Metadata>>,
        type_id: TypeId,
        validation: &schemars::schema::StringValidation,
        schema: Schema,
    ) -> TypeEntry {
        let name = get_type_name(&type_name, metadata).unwrap();
        let rename = None;
        let description = metadata_description(metadata);

        let schemars::schema::StringValidation {
            max_length,
            min_length,
            pattern,
        } = validation.clone();

        let type_patch = TypePatch::new(type_space, name);

        let details = TypeEntryDetails::Newtype(Self {
            name: type_patch.name,
            rename,
            description,
            default: None,
            type_id,
            constraints: TypeEntryNewtypeConstraints::String {
                max_length,
                min_length,
                pattern,
            },
            schema: SchemaWrapper(schema),
        });

        TypeEntry {
            details,
            extra_derives: type_patch.derives,
            extra_attrs: type_patch.attrs,
        }
    }
}

impl From<TypeEntryDetails> for TypeEntry {
    fn from(details: TypeEntryDetails) -> Self {
        Self {
            details,
            extra_derives: Default::default(),
            extra_attrs: Default::default(),
        }
    }
}

impl TypeEntry {
    pub(crate) fn new_native<S: ToString>(type_name: S, impls: &[TypeSpaceImpl]) -> Self {
        TypeEntry {
            details: TypeEntryDetails::Native(TypeEntryNative {
                type_name: type_name.to_string(),
                impls: impls.to_vec(),
                parameters: Default::default(),
            }),
            extra_derives: Default::default(),
            extra_attrs: Default::default(),
        }
    }
    pub(crate) fn new_native_params<S: ToString>(type_name: S, params: &[TypeId]) -> Self {
        TypeEntry {
            details: TypeEntryDetails::Native(TypeEntryNative {
                type_name: type_name.to_string(),
                impls: Default::default(),
                parameters: params.to_vec(),
            }),
            extra_derives: Default::default(),
            extra_attrs: Default::default(),
        }
    }
    pub(crate) fn new_boolean() -> Self {
        TypeEntry {
            details: TypeEntryDetails::Boolean,
            extra_derives: Default::default(),
            extra_attrs: Default::default(),
        }
    }
    pub(crate) fn new_integer<S: ToString>(type_name: S) -> Self {
        TypeEntryDetails::Integer(type_name.to_string()).into()
    }
    pub(crate) fn new_float<S: ToString>(type_name: S) -> Self {
        TypeEntry {
            details: TypeEntryDetails::Float(type_name.to_string()),
            extra_derives: Default::default(),
            extra_attrs: Default::default(),
        }
    }

    pub(crate) fn finalize(&mut self, type_space: &mut TypeSpace) -> Result<()> {
        if let TypeEntryDetails::Enum(enum_details) = &mut self.details {
            enum_details.finalize(type_space);
        }

        self.check_defaults(type_space)
    }

    pub(crate) fn name(&self) -> Option<&String> {
        match &self.details {
            TypeEntryDetails::Enum(TypeEntryEnum { name, .. })
            | TypeEntryDetails::Struct(TypeEntryStruct { name, .. })
            | TypeEntryDetails::Newtype(TypeEntryNewtype { name, .. }) => Some(name),

            _ => None,
        }
    }

    pub(crate) fn has_impl<'a>(
        &'a self,
        type_space: &'a TypeSpace,
        impl_name: TypeSpaceImpl,
    ) -> bool {
        match &self.details {
            TypeEntryDetails::Enum(details) => match impl_name {
                TypeSpaceImpl::Default => details.default.is_some(),
                TypeSpaceImpl::FromStr => {
                    details
                        .bespoke_impls
                        .contains(&TypeEntryEnumImpl::AllSimpleVariants)
                        || details
                            .bespoke_impls
                            .contains(&TypeEntryEnumImpl::UntaggedFromStr)
                }
                TypeSpaceImpl::Display => {
                    details
                        .bespoke_impls
                        .contains(&TypeEntryEnumImpl::AllSimpleVariants)
                        || details
                            .bespoke_impls
                            .contains(&TypeEntryEnumImpl::UntaggedDisplay)
                }
                TypeSpaceImpl::FromStringIrrefutable => details
                    .bespoke_impls
                    .contains(&TypeEntryEnumImpl::UntaggedFromStringIrrefutable),
            },

            TypeEntryDetails::Struct(details) => match impl_name {
                TypeSpaceImpl::Default => details.default.is_some(),
                _ => false,
            },
            TypeEntryDetails::Newtype(details) => match (&details.constraints, impl_name) {
                (_, TypeSpaceImpl::Default) => details.default.is_some(),
                (TypeEntryNewtypeConstraints::String { .. }, TypeSpaceImpl::FromStr) => true,
                (TypeEntryNewtypeConstraints::String { .. }, TypeSpaceImpl::Display) => true,
                (TypeEntryNewtypeConstraints::None, _) => {
                    // TODO this is a lucky kludge that will need to be removed
                    // once we have proper handling of reference cycles (i.e.
                    // as opposed to containment cycles... which we **do**
                    // handle correctly). In particular output_newtype calls
                    // this to determine if it should produce a FromStr impl.
                    // This implementation could be infinitely recursive for a
                    // type such as this:
                    //     struct A(Box<A>);
                    // While this type is useless and unusable, we do--
                    // basically--support and test this. On such a type, if one
                    // were to ask `ty.has_impl(TypeSpaceImpl::Default)` it
                    // would be infinitely recursive. Fortunately the type
                    // doesn't occur in the wild (we hope) and generation
                    // doesn't rely on that particular query.

                    let type_entry = type_space.id_to_entry.get(&details.type_id).unwrap();
                    type_entry.has_impl(type_space, impl_name)
                }
                _ => false,
            },
            TypeEntryDetails::Native(details) => details.impls.contains(&impl_name),
            TypeEntryDetails::Box(type_id) => {
                if impl_name == TypeSpaceImpl::Default {
                    let type_entry = type_space.id_to_entry.get(type_id).unwrap();
                    type_entry.has_impl(type_space, impl_name)
                } else {
                    false
                }
            }

            TypeEntryDetails::JsonValue => false,

            TypeEntryDetails::Unit
            | TypeEntryDetails::Option(_)
            | TypeEntryDetails::Vec(_)
            | TypeEntryDetails::Map(_, _)
            | TypeEntryDetails::Set(_) => {
                matches!(impl_name, TypeSpaceImpl::Default)
            }

            TypeEntryDetails::Tuple(type_ids) => {
                // Default is implemented for tuples of up to 12 items long.
                matches!(impl_name, TypeSpaceImpl::Default)
                    && type_ids.len() <= 12
                    && type_ids.iter().all(|type_id| {
                        let type_entry = type_space.id_to_entry.get(type_id).unwrap();
                        type_entry.has_impl(type_space, TypeSpaceImpl::Default)
                    })
            }

            TypeEntryDetails::Array(item_id, length) => {
                // Default is implemented for arrays of up to length 32.
                if *length <= 32 && impl_name == TypeSpaceImpl::Default {
                    let type_entry = type_space.id_to_entry.get(item_id).unwrap();
                    type_entry.has_impl(type_space, impl_name)
                } else {
                    false
                }
            }

            TypeEntryDetails::Boolean => match impl_name {
                TypeSpaceImpl::Default | TypeSpaceImpl::FromStr | TypeSpaceImpl::Display => true,
                TypeSpaceImpl::FromStringIrrefutable => false,
            },
            TypeEntryDetails::Integer(_) => match impl_name {
                TypeSpaceImpl::Default | TypeSpaceImpl::FromStr | TypeSpaceImpl::Display => true,
                TypeSpaceImpl::FromStringIrrefutable => false,
            },

            TypeEntryDetails::Float(_) => match impl_name {
                TypeSpaceImpl::Default | TypeSpaceImpl::FromStr | TypeSpaceImpl::Display => true,
                TypeSpaceImpl::FromStringIrrefutable => false,
            },
            TypeEntryDetails::String => match impl_name {
                TypeSpaceImpl::Default
                | TypeSpaceImpl::FromStr
                | TypeSpaceImpl::Display
                | TypeSpaceImpl::FromStringIrrefutable => true,
            },

            TypeEntryDetails::Reference(_) => unreachable!(),
        }
    }

    pub(crate) fn output(&self, type_space: &TypeSpace, output: &mut OutputSpace) {
        let derive_set = [
            "::serde::Serialize",
            "::serde::Deserialize",
            "Debug",
            "Clone",
        ]
        .into_iter()
        .collect::<BTreeSet<_>>();

        match &self.details {
            TypeEntryDetails::Enum(enum_details) => {
                self.output_enum(type_space, output, enum_details, derive_set)
            }
            TypeEntryDetails::Struct(struct_details) => {
                self.output_struct(type_space, output, struct_details, derive_set)
            }
            TypeEntryDetails::Newtype(newtype_details) => {
                self.output_newtype(type_space, output, newtype_details, derive_set)
            }

            // We should never get here as reference types should only be used
            // in-flight, but never recorded into the type space.
            TypeEntryDetails::Reference(_) => unreachable!(),

            // Unnamed types require no definition as they're already defined.
            _ => (),
        }
    }

    fn output_enum(
        &self,
        type_space: &TypeSpace,
        output: &mut OutputSpace,
        enum_details: &TypeEntryEnum,
        mut derive_set: BTreeSet<&str>,
    ) {
        let TypeEntryEnum {
            name,
            rename,
            description,
            default,
            tag_type,
            variants,
            deny_unknown_fields,
            bespoke_impls,
            schema: SchemaWrapper(schema),
        } = enum_details;

        let doc = make_doc(name, description.as_ref(), schema);

        // TODO this is a one-off for some useful traits; this should move into
        // the creation of the enum type.
        if variants
            .iter()
            .all(|variant| matches!(variant.details, VariantDetails::Simple))
        {
            derive_set.extend(["Copy", "PartialOrd", "Ord", "PartialEq", "Eq", "Hash"]);
        }

        let mut serde_options = Vec::new();
        if let Some(old_name) = rename {
            serde_options.push(quote! { rename = #old_name });
        }
        match tag_type {
            EnumTagType::External => {}
            EnumTagType::Internal { tag } => {
                serde_options.push(quote! { tag = #tag });
            }
            EnumTagType::Adjacent { tag, content } => {
                serde_options.push(quote! { tag = #tag });
                serde_options.push(quote! { content = #content });
            }
            EnumTagType::Untagged => {
                serde_options.push(quote! { untagged });
            }
        }
        if *deny_unknown_fields {
            serde_options.push(quote! { deny_unknown_fields });
        }

        let serde = (!serde_options.is_empty()).then(|| {
            quote! { #[serde( #( #serde_options ),* )] }
        });

        let type_name = format_ident!("{}", name);

        let variants_decl = variants
            .iter()
            .map(|variant| output_variant(variant, type_space, output, name))
            .collect::<Vec<_>>();

        // It should not be possible to construct an untagged enum
        // with more than one simple variant--it would not be usable.
        if tag_type == &EnumTagType::Untagged {
            assert!(
                variants
                    .iter()
                    .filter(|variant| matches!(variant.details, VariantDetails::Simple))
                    .count()
                    <= 1
            )
        }

        // Display and FromStr impls for enums that are made exclusively of
        // simple variants (and are not untagged).
        let simple_enum_impl = bespoke_impls
            .contains(&TypeEntryEnumImpl::AllSimpleVariants)
            .then(|| {
                let (match_variants, match_strs): (Vec<_>, Vec<_>) = variants
                    .iter()
                    .map(|variant| {
                        let ident_name = variant.ident_name.as_ref().unwrap();
                        let variant_name = format_ident!("{}", ident_name);
                        (variant_name, &variant.raw_name)
                    })
                    .unzip();

                quote! {
                    impl ::std::fmt::Display for #type_name {
                        fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                            match *self {
                                #(Self::#match_variants => f.write_str(#match_strs),)*
                            }
                        }
                    }
                    impl ::std::str::FromStr for #type_name {
                        type Err = self::error::ConversionError;

                        fn from_str(value: &str) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            match value {
                                #(#match_strs => Ok(Self::#match_variants),)*
                                _ => Err("invalid value".into()),
                            }
                        }
                    }
                    impl ::std::convert::TryFrom<&str> for #type_name {
                        type Error = self::error::ConversionError;

                        fn try_from(value: &str) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            value.parse()
                        }
                    }
                    impl ::std::convert::TryFrom<&::std::string::String> for #type_name {
                        type Error = self::error::ConversionError;

                        fn try_from(value: &::std::string::String) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            value.parse()
                        }
                    }
                    impl ::std::convert::TryFrom<::std::string::String> for #type_name {
                        type Error = self::error::ConversionError;

                        fn try_from(value: ::std::string::String) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            value.parse()
                        }
                    }
                }
            });

        let default_impl = default.as_ref().map(|value| {
            let default_stream = self.output_value(type_space, &value.0, &quote! {}).unwrap();
            quote! {
                impl ::std::default::Default for #type_name {
                    fn default() -> Self {
                        #default_stream
                    }
                }
            }
        });

        let untagged_newtype_from_string_impl = bespoke_impls
            .contains(&TypeEntryEnumImpl::UntaggedFromStr)
            .then(|| {
                let variant_name = variants
                    .iter()
                    .map(|variant| format_ident!("{}", variant.ident_name.as_ref().unwrap()));

                quote! {
                    impl ::std::str::FromStr for #type_name {
                        type Err = self::error::ConversionError;

                        fn from_str(value: &str) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            #(
                                // Try to parse() into each variant.
                                if let Ok(v) = value.parse() {
                                    Ok(Self::#variant_name(v))
                                } else
                            )*
                            {
                                Err("string conversion failed for all variants".into())
                            }
                        }
                    }
                    impl ::std::convert::TryFrom<&str> for #type_name {
                        type Error = self::error::ConversionError;

                        fn try_from(value: &str) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            value.parse()
                        }
                    }
                    impl ::std::convert::TryFrom<&::std::string::String> for #type_name {
                        type Error = self::error::ConversionError;

                        fn try_from(value: &::std::string::String) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            value.parse()
                        }
                    }
                    impl ::std::convert::TryFrom<::std::string::String> for #type_name {
                        type Error = self::error::ConversionError;

                        fn try_from(value: ::std::string::String) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            value.parse()
                        }
                    }
                }
            });

        let untagged_newtype_to_string_impl = bespoke_impls
            .contains(&TypeEntryEnumImpl::UntaggedDisplay)
            .then(|| {
                let variant_name = variants
                    .iter()
                    .map(|variant| format_ident!("{}", variant.ident_name.as_ref().unwrap()));

                quote! {
                    impl ::std::fmt::Display for #type_name {
                        fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                            match self {
                                #(Self::#variant_name(x) => x.fmt(f),)*
                            }
                        }
                    }
                }
            });

        let convenience_from = {
            // Build a map whose key is the type ID or type IDs of the Item and
            // Tuple variants, and whose value is a tuple of the original index
            // and the variant itself. Any key that is seen multiple times has
            // a value of None.
            // TODO this requires more consideration to handle single-item
            // tuples.
            let unique_variants =
                variants
                    .iter()
                    .enumerate()
                    .fold(BTreeMap::new(), |mut map, (index, variant)| {
                        let key = match &variant.details {
                            VariantDetails::Item(type_id) => vec![type_id],
                            VariantDetails::Tuple(type_ids) => type_ids.iter().collect(),
                            _ => return map,
                        };

                        map.entry(key)
                            .and_modify(|v| *v = None)
                            .or_insert(Some((index, variant)));
                        map
                    });

            // Remove any variants that are duplicates (i.e. the value is None)
            // with the flatten(). Then order a new map according to the
            // original order of variants. The allows for the order to be
            // stable and for impl blocks to appear in the same order as their
            // corresponding variants.
            let ordered_variants = unique_variants
                .into_values()
                .flatten()
                .collect::<BTreeMap<_, _>>();

            // Generate a `From<VariantType>` impl block that converts the type
            // into the appropriate variant of the enum.
            let variant_from = ordered_variants.into_values().map(|variant| {
                match &variant.details {
                    VariantDetails::Item(type_id) => {
                        let variant_type = type_space.id_to_entry.get(type_id).unwrap();

                        // TODO Strings might conflict with the way we're
                        // dealing with TryFrom<String> right now.
                        (variant_type.details != TypeEntryDetails::String).then(|| {
                            let variant_type_ident = variant_type.type_ident(type_space, &None);
                            let variant_name =
                                format_ident!("{}", variant.ident_name.as_ref().unwrap());
                            quote! {
                                impl ::std::convert::From<#variant_type_ident> for #type_name {
                                    fn from(value: #variant_type_ident)
                                        -> Self
                                    {
                                        Self::#variant_name(value)
                                    }
                                }
                            }
                        })
                    }
                    VariantDetails::Tuple(type_ids) => {
                        let variant_type_idents = type_ids.iter().map(|type_id| {
                            type_space
                                .id_to_entry
                                .get(type_id)
                                .unwrap()
                                .type_ident(type_space, &None)
                        });
                        let variant_type_ident = if type_ids.len() != 1 {
                            quote! { ( #(#variant_type_idents),* ) }
                        } else {
                            // A single-item tuple requires a trailing
                            // comma.
                            quote! { ( #(#variant_type_idents,)* ) }
                        };
                        let variant_name =
                            format_ident!("{}", variant.ident_name.as_ref().unwrap());
                        let ii = (0..type_ids.len()).map(syn::Index::from);
                        Some(quote! {
                            impl ::std::convert::From<#variant_type_ident> for #type_name {
                                fn from(value: #variant_type_ident) -> Self {
                                    Self::#variant_name(
                                        #( value.#ii, )*
                                    )
                                }
                            }
                        })
                    }
                    _ => None,
                }
            });

            quote! {
                #( #variant_from )*
            }
        };

        let derives = strings_to_derives(
            derive_set,
            &self.extra_derives,
            &type_space.settings.extra_derives,
        );

        let attrs = strings_to_attrs(&self.extra_attrs, &type_space.settings.extra_attrs);

        let item = quote! {
            #doc
            #(#attrs)*
            #[derive(#(#derives),*)]
            #serde
            pub enum #type_name {
                #(#variants_decl)*
            }

            #simple_enum_impl
            #default_impl
            #untagged_newtype_from_string_impl
            #untagged_newtype_to_string_impl
            #convenience_from
        };
        output.add_item(OutputSpaceMod::Crate, name, item);
    }

    fn output_struct(
        &self,
        type_space: &TypeSpace,
        output: &mut OutputSpace,
        struct_details: &TypeEntryStruct,
        derive_set: BTreeSet<&str>,
    ) {
        enum PropDefault {
            None(String),
            Default(TokenStream),
            Custom(TokenStream),
        }

        let TypeEntryStruct {
            name,
            rename,
            description,
            default,
            properties,
            deny_unknown_fields,
            schema: SchemaWrapper(schema),
        } = struct_details;
        let doc = make_doc(name, description.as_ref(), schema);

        // Generate the serde directives as needed.
        let mut serde_options = Vec::new();
        if let Some(old_name) = rename {
            serde_options.push(quote! { rename = #old_name });
        }
        if *deny_unknown_fields {
            serde_options.push(quote! { deny_unknown_fields });
        }
        let serde =
            (!serde_options.is_empty()).then(|| quote! { #[serde( #( #serde_options ),* )] });

        let type_name = format_ident!("{}", name);

        // Gather the various components for all properties.
        let mut prop_doc = Vec::new();
        let mut prop_serde = Vec::new();
        let mut prop_default = Vec::new();
        let mut prop_name = Vec::new();
        let mut prop_error = Vec::new();
        let mut prop_type = Vec::new();
        let mut prop_type_scoped = Vec::new();

        properties.iter().for_each(|prop| {
            prop_doc.push(prop.description.as_ref().map(|d| quote! { #[doc = #d] }));
            prop_name.push(format_ident!("{}", prop.name));
            prop_error.push(format!(
                "error converting supplied value for {}: {{e}}",
                prop.name,
            ));

            let prop_type_entry = type_space.id_to_entry.get(&prop.type_id).unwrap();
            prop_type.push(prop_type_entry.type_ident(type_space, &None));
            prop_type_scoped
                .push(prop_type_entry.type_ident(type_space, &Some("super".to_string())));

            let (serde, default_fn) = generate_serde_attr(
                name,
                &prop.name,
                &prop.rename,
                &prop.state,
                prop_type_entry,
                type_space,
                output,
            );

            prop_serde.push(serde);
            prop_default.push(match default_fn {
                DefaultFunction::Default => PropDefault::Default(quote! {
                    Default::default()
                }),
                DefaultFunction::Custom(fn_name) => {
                    let default_fn = syn::parse_str::<Path>(&fn_name).unwrap();
                    PropDefault::Custom(quote! {
                        #default_fn()
                    })
                }
                DefaultFunction::None => {
                    let err_msg = format!("no value supplied for {}", prop.name);
                    PropDefault::None(err_msg)
                }
            });
        });

        let derives = strings_to_derives(
            derive_set,
            &self.extra_derives,
            &type_space.settings.extra_derives,
        );

        let attrs = strings_to_attrs(&self.extra_attrs, &type_space.settings.extra_attrs);

        output.add_item(
            OutputSpaceMod::Crate,
            name,
            quote! {
                #doc
                #(#attrs)*
                #[derive(#(#derives),*)]
                #serde
                pub struct #type_name {
                    #(
                        #prop_doc
                        #prop_serde
                        pub #prop_name: #prop_type,
                    )*
                }
            },
        );

        // If there's a default value, generate an impl Default
        if let Some(value) = default {
            let default_stream = self.output_value(type_space, &value.0, &quote! {}).unwrap();
            output.add_item(
                OutputSpaceMod::Crate,
                name,
                quote! {
                    impl ::std::default::Default for #type_name {
                        fn default() -> Self {
                            #default_stream
                        }
                    }
                },
            );
        } else if let Some(prop_default) = prop_default
            .iter()
            .map(|pd| match pd {
                PropDefault::None(_) => None,
                PropDefault::Default(token_stream) | PropDefault::Custom(token_stream) => {
                    Some(token_stream)
                }
            })
            .collect::<Option<Vec<_>>>()
        {
            // If all properties have a default, we can generate a Default impl
            output.add_item(
                OutputSpaceMod::Crate,
                name,
                quote! {
                    impl ::std::default::Default for #type_name {
                        fn default() -> Self {
                            Self {
                                #(
                                    #prop_name: #prop_default,
                                )*
                            }
                        }
                    }
                },
            )
        }

        if type_space.settings.struct_builder {
            output.add_item(
                OutputSpaceMod::Crate,
                name,
                quote! {
                    impl #type_name {
                        pub fn builder() -> builder::#type_name {
                            Default::default()
                        }
                    }
                },
            );

            // If there are no properties, all of this is kind of pointless,
            // but at least this lets us avoid the lint warning.
            let value_ident = if prop_name.is_empty() {
                quote! { _value }
            } else {
                quote! { value }
            };

            let prop_default = prop_default.iter().map(|pd| match pd {
                PropDefault::None(err_msg) => quote! { Err(#err_msg.to_string()) },
                PropDefault::Default(default_fn) => quote! { Ok(#default_fn) },
                PropDefault::Custom(custom_fn) => quote! { Ok(super::#custom_fn) },
            });

            output.add_item(
                OutputSpaceMod::Builder,
                name,
                quote! {
                    #[derive(Clone, Debug)]
                    pub struct #type_name {
                        #(
                            #prop_name: ::std::result::Result<#prop_type_scoped, ::std::string::String>,
                        )*
                    }

                    impl ::std::default::Default for #type_name {
                        fn default() -> Self {
                            Self {
                                #(
                                    #prop_name: #prop_default,
                                )*
                            }
                        }
                    }

                    impl #type_name {
                        #(
                            pub fn #prop_name<T>(mut self, value: T) -> Self
                                where
                                    T: ::std::convert::TryInto<#prop_type_scoped>,
                                    T::Error: ::std::fmt::Display,
                            {
                                self.#prop_name = value.try_into()
                                    .map_err(|e| format!(#prop_error));
                                self
                            }
                        )*
                    }

                    // This is how the item is built.
                    impl ::std::convert::TryFrom<#type_name>
                        for super::#type_name
                    {
                        type Error = super::error::ConversionError;

                        fn try_from(#value_ident: #type_name)
                            -> ::std::result::Result<Self, super::error::ConversionError>
                        {
                            Ok(Self {
                                #(
                                    #prop_name: value.#prop_name?,
                                )*
                            })
                        }
                    }

                    // Construct a builder from the item.
                    impl ::std::convert::From<super::#type_name> for #type_name {
                        fn from(#value_ident: super::#type_name) -> Self {
                            Self {
                                #(
                                    #prop_name: Ok(value.#prop_name),
                                )*
                            }
                        }
                    }
                },
            );
        }
    }

    fn output_newtype(
        &self,
        type_space: &TypeSpace,
        output: &mut OutputSpace,
        newtype_details: &TypeEntryNewtype,
        mut derive_set: BTreeSet<&str>,
    ) {
        let TypeEntryNewtype {
            name,
            rename: _,
            description,
            default,
            type_id,
            constraints,
            schema: SchemaWrapper(schema),
        } = newtype_details;
        let doc = make_doc(name, description.as_ref(), schema);

        let type_name = format_ident!("{}", name);
        let inner_type = type_space.id_to_entry.get(type_id).unwrap();
        let inner_type_name = inner_type.type_ident(type_space, &None);

        let is_str = matches!(inner_type.details, TypeEntryDetails::String);

        // If this is just a wrapper around a string, we can derive some more
        // useful traits.
        if is_str {
            derive_set.extend(["PartialOrd", "Ord", "PartialEq", "Eq", "Hash"]);
        }

        let constraint_impl = match constraints {
            // In the unconstrained case we proxy impls through the inner type.
            TypeEntryNewtypeConstraints::None => {
                let str_impl = is_str.then(|| {
                    quote! {
                        impl ::std::str::FromStr for #type_name {
                            type Err = ::std::convert::Infallible;

                            fn from_str(value: &str) ->
                                ::std::result::Result<Self, Self::Err>
                            {
                                Ok(Self(value.to_string()))
                            }
                        }
                    }
                });

                // TODO see the comment in has_impl related to this case.
                let from_str_impl = (inner_type.has_impl(type_space, TypeSpaceImpl::FromStr)
                    && !is_str)
                    .then(|| {
                        quote! {
                            impl ::std::str::FromStr for #type_name {
                                type Err = <#inner_type_name as
                                    ::std::str::FromStr>::Err;

                                fn from_str(value: &str) ->
                                    ::std::result::Result<Self, Self::Err>
                                {
                                    Ok(Self(value.parse()?))
                                }
                            }
                            impl ::std::convert::TryFrom<&str> for #type_name {
                                type Error = <#inner_type_name as
                                    ::std::str::FromStr>::Err;

                                fn try_from(value: &str) ->
                                    ::std::result::Result<Self, Self::Error>
                                {
                                    value.parse()
                                }
                            }
                            impl ::std::convert::TryFrom<String> for #type_name {
                                type Error = <#inner_type_name as
                                    ::std::str::FromStr>::Err;

                                fn try_from(value: String) ->
                                    ::std::result::Result<Self, Self::Error>
                                {
                                    value.parse()
                                }
                            }
                        }
                    });

                let display_impl = inner_type
                    .has_impl(type_space, TypeSpaceImpl::Display)
                    .then(|| {
                        quote! {
                            impl ::std::fmt::Display for #type_name {
                                fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                                    self.0.fmt(f)
                                }
                            }
                        }
                    });

                quote! {
                    impl ::std::convert::From<#inner_type_name> for #type_name {
                        fn from(value: #inner_type_name) -> Self {
                            Self(value)
                        }
                    }

                    #str_impl
                    #from_str_impl
                    #display_impl
                }
            }

            TypeEntryNewtypeConstraints::DenyValue(enum_values)
            | TypeEntryNewtypeConstraints::EnumValue(enum_values) => {
                let not = matches!(constraints, TypeEntryNewtypeConstraints::EnumValue(_))
                    .then(|| quote! { ! });
                // Note that string types with enumerated values are converted
                // into simple enums rather than newtypes so we would not
                // expect to see a string as the inner type here.
                assert!(
                    matches!(constraints, TypeEntryNewtypeConstraints::DenyValue(_))
                        || !matches!(&inner_type.details, TypeEntryDetails::String)
                );

                // We're going to impl Deserialize so we can remove it
                // from the set of derived impls.
                derive_set.remove("::serde::Deserialize");

                // TODO: if a user were to derive schemars::JsonSchema, it
                // wouldn't be accurate.

                let value_output = enum_values
                    .iter()
                    .map(|value| inner_type.output_value(type_space, &value.0, &quote! {}));
                // TODO if the sub_type is a string we could probably impl
                // TryFrom<&str> as well and FromStr.
                // TODO maybe we want to handle JsonSchema here
                quote! {
                    // This is effectively the constructor for this type.
                    impl ::std::convert::TryFrom<#inner_type_name> for #type_name {
                        type Error = self::error::ConversionError;

                        fn try_from(
                            value: #inner_type_name
                        ) -> ::std::result::Result<Self, self::error::ConversionError>
                        {
                            if #not [
                                #(#value_output,)*
                            ].contains(&value) {
                                Err("invalid value".into())
                            } else {
                                Ok(Self(value))
                            }
                        }
                    }

                    impl<'de> ::serde::Deserialize<'de> for #type_name {
                        fn deserialize<D>(
                            deserializer: D,
                        ) -> ::std::result::Result<Self, D::Error>
                        where
                            D: ::serde::Deserializer<'de>,
                        {
                            Self::try_from(
                                <#inner_type_name>::deserialize(deserializer)?,
                            )
                            .map_err(|e| {
                                <D::Error as ::serde::de::Error>::custom(
                                    e.to_string(),
                                )
                            })
                        }
                    }
                }
            }

            TypeEntryNewtypeConstraints::String {
                max_length,
                min_length,
                pattern,
            } => {
                let max = max_length.map(|v| {
                    let v = v as usize;
                    let err = format!("longer than {} characters", v);
                    quote! {
                        if value.chars().count() > #v {
                            return Err(#err.into());
                        }
                    }
                });
                let min = min_length.map(|v| {
                    let v = v as usize;
                    let err = format!("shorter than {} characters", v);
                    quote! {
                        if value.chars().count() < #v {
                            return Err(#err.into());
                        }
                    }
                });

                let pat = pattern.as_ref().map(|p| {
                    let err = format!("doesn't match pattern \"{}\"", p);
                    quote! {
                        static PATTERN: ::std::sync::LazyLock<::regress::Regex> = ::std::sync::LazyLock::new(|| {
                            ::regress::Regex::new(#p).unwrap()
                        });
                        if PATTERN.find(value).is_none() {
                            return Err(#err.into());
                        }
                    }
                });

                // We're going to impl Deserialize so we can remove it
                // from the set of derived impls.
                derive_set.remove("::serde::Deserialize");

                // TODO: if a user were to derive schemars::JsonSchema, it
                // wouldn't be accurate.
                quote! {
                    impl ::std::str::FromStr for #type_name {
                        type Err = self::error::ConversionError;

                        fn from_str(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
                            #max
                            #min
                            #pat

                            Ok(Self(value.to_string()))
                        }
                    }
                    impl ::std::convert::TryFrom<&str> for #type_name {
                        type Error = self::error::ConversionError;

                        fn try_from(value: &str) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            value.parse()
                        }
                    }
                    impl ::std::convert::TryFrom<&::std::string::String> for #type_name {
                        type Error = self::error::ConversionError;

                        fn try_from(value: &::std::string::String) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            value.parse()
                        }
                    }
                    impl ::std::convert::TryFrom<::std::string::String> for #type_name {
                        type Error = self::error::ConversionError;

                        fn try_from(value: ::std::string::String) ->
                            ::std::result::Result<Self, self::error::ConversionError>
                        {
                            value.parse()
                        }
                    }

                    impl<'de> ::serde::Deserialize<'de> for #type_name {
                        fn deserialize<D>(
                            deserializer: D,
                        ) -> ::std::result::Result<Self, D::Error>
                        where
                            D: ::serde::Deserializer<'de>,
                        {
                            ::std::string::String::deserialize(deserializer)?
                            .parse()
                            .map_err(|e: self::error::ConversionError| {
                                <D::Error as ::serde::de::Error>::custom(
                                    e.to_string(),
                                )
                            })
                        }
                    }
                }
            }
        };

        // If there are no constraints, let consumers directly access the value.
        let vis = match constraints {
            TypeEntryNewtypeConstraints::None => Some(quote! {pub}),
            _ => None,
        };

        let default_impl = default.as_ref().map(|value| {
            let default_stream = self.output_value(type_space, &value.0, &quote! {}).unwrap();
            quote! {
                impl ::std::default::Default for #type_name {
                    fn default() -> Self {
                        #default_stream
                    }
                }
            }
        });

        let derives = strings_to_derives(
            derive_set,
            &self.extra_derives,
            &type_space.settings.extra_derives,
        );

        let attrs = strings_to_attrs(&self.extra_attrs, &type_space.settings.extra_attrs);

        let item = quote! {
            #doc
            #(#attrs)*
            #[derive(#(#derives),*)]
            #[serde(transparent)]
            pub struct #type_name(#vis #inner_type_name);

            impl ::std::ops::Deref for #type_name {
                type Target = #inner_type_name;
                fn deref(&self) -> &#inner_type_name {
                    &self.0
                }
            }

            impl ::std::convert::From<#type_name> for #inner_type_name {
                fn from(value: #type_name) -> Self {
                    value.0
                }
            }

            #default_impl
            #constraint_impl
        };
        output.add_item(OutputSpaceMod::Crate, name, item);
    }

    pub(crate) fn type_name(&self, type_space: &TypeSpace) -> String {
        self.type_ident(type_space, &None).to_string()
    }

    pub(crate) fn type_ident(
        &self,
        type_space: &TypeSpace,
        type_mod: &Option<String>,
    ) -> TokenStream {
        match &self.details {
            // Named types.
            TypeEntryDetails::Enum(TypeEntryEnum { name, .. })
            | TypeEntryDetails::Struct(TypeEntryStruct { name, .. })
            | TypeEntryDetails::Newtype(TypeEntryNewtype { name, .. }) => match &type_mod {
                Some(type_mod) => {
                    let type_mod = format_ident!("{}", type_mod);
                    let type_name = format_ident!("{}", name);
                    quote! { #type_mod :: #type_name }
                }
                None => {
                    let type_name = format_ident!("{}", name);
                    quote! { #type_name }
                }
            },

            TypeEntryDetails::Option(id) => {
                let inner_ty = type_space
                    .id_to_entry
                    .get(id)
                    .expect("unresolved type id for option");
                let inner_ident = inner_ty.type_ident(type_space, type_mod);

                // Flatten nested Option types. This would only happen if the
                // schema encoded it; it's an odd construction.
                match &inner_ty.details {
                    TypeEntryDetails::Option(_) => inner_ident,
                    _ => quote! { ::std::option::Option<#inner_ident> },
                }
            }

            TypeEntryDetails::Box(id) => {
                let inner_ty = type_space
                    .id_to_entry
                    .get(id)
                    .expect("unresolved type id for box");

                let item = inner_ty.type_ident(type_space, type_mod);

                quote! { ::std::boxed::Box<#item> }
            }

            TypeEntryDetails::Vec(id) => {
                let inner_ty = type_space
                    .id_to_entry
                    .get(id)
                    .expect("unresolved type id for array");
                let item = inner_ty.type_ident(type_space, type_mod);

                quote! { ::std::vec::Vec<#item> }
            }

            TypeEntryDetails::Map(key_id, value_id) => {
                let map_to_use = &type_space.settings.map_type;
                let key_ty = type_space
                    .id_to_entry
                    .get(key_id)
                    .expect("unresolved type id for map key");
                let value_ty = type_space
                    .id_to_entry
                    .get(value_id)
                    .expect("unresolved type id for map value");

                if key_ty.details == TypeEntryDetails::String
                    && value_ty.details == TypeEntryDetails::JsonValue
                {
                    quote! { ::serde_json::Map<::std::string::String, ::serde_json::Value> }
                } else {
                    let key_ident = key_ty.type_ident(type_space, type_mod);
                    let value_ident = value_ty.type_ident(type_space, type_mod);
                    let map_to_use = &map_to_use.0;

                    quote! { #map_to_use<#key_ident, #value_ident> }
                }
            }

            TypeEntryDetails::Set(id) => {
                let inner_ty = type_space
                    .id_to_entry
                    .get(id)
                    .expect("unresolved type id for set");
                let item = inner_ty.type_ident(type_space, type_mod);
                // TODO we'll want this to be a Set of some kind, but we need
                // to get the derives right first.
                quote! { Vec<#item> }
            }

            TypeEntryDetails::Tuple(items) => {
                let type_idents = items.iter().map(|item| {
                    type_space
                        .id_to_entry
                        .get(item)
                        .expect("unresolved type id for tuple")
                        .type_ident(type_space, type_mod)
                });

                if items.len() != 1 {
                    quote! { ( #(#type_idents),* ) }
                } else {
                    // A single-item tuple requires a trailing comma.
                    quote! { ( #(#type_idents,)* ) }
                }
            }

            TypeEntryDetails::Array(item_id, length) => {
                let item_ty = type_space
                    .id_to_entry
                    .get(item_id)
                    .expect("unresolved type id for array");
                let item_ident = item_ty.type_ident(type_space, type_mod);

                quote! { [#item_ident; #length]}
            }

            TypeEntryDetails::Native(TypeEntryNative {
                type_name,
                impls: _,
                parameters,
            }) => {
                let path =
                    syn::parse_str::<syn::TypePath>(type_name).expect("type path wasn't valid");

                let type_idents = (!parameters.is_empty()).then(|| {
                    let type_idents = parameters.iter().map(|type_id| {
                        type_space
                            .id_to_entry
                            .get(type_id)
                            .expect("unresolved type id for tuple")
                            .type_ident(type_space, type_mod)
                    });
                    quote! { < #(#type_idents,)* > }
                });

                quote! {
                    #path
                    #type_idents
                }
            }

            TypeEntryDetails::Unit => quote! { () },
            TypeEntryDetails::String => quote! { ::std::string::String },
            TypeEntryDetails::Boolean => quote! { bool },
            TypeEntryDetails::JsonValue => quote! { ::serde_json::Value },
            TypeEntryDetails::Integer(name) | TypeEntryDetails::Float(name) => {
                syn::parse_str::<syn::TypePath>(name)
                    .unwrap()
                    .to_token_stream()
            }

            TypeEntryDetails::Reference(_) => panic!("references should be resolved by now"),
        }
    }

    pub(crate) fn type_parameter_ident(
        &self,
        type_space: &TypeSpace,
        lifetime_name: Option<&str>,
    ) -> TokenStream {
        let lifetime = lifetime_name.map(|s| {
            vec![
                TokenTree::from(Punct::new('\'', Spacing::Joint)),
                TokenTree::from(format_ident!("{}", s)),
            ]
            .into_iter()
            .collect::<TokenStream>()
        });
        match &self.details {
            // We special-case enums for which all variants are simple to let
            // them be passed as values rather than as references.
            // TODO we should probably cache "simpleness" of all variants
            // rather than iterating every time. We'll know it when the enum is
            // constructed.
            TypeEntryDetails::Enum(TypeEntryEnum { variants, .. })
                if variants
                    .iter()
                    .all(|variant| matches!(&variant.details, VariantDetails::Simple)) =>
            {
                self.type_ident(type_space, &type_space.settings.type_mod)
            }
            TypeEntryDetails::Enum(_)
            | TypeEntryDetails::Struct(_)
            | TypeEntryDetails::Newtype(_)
            | TypeEntryDetails::Vec(_)
            | TypeEntryDetails::Map(..)
            | TypeEntryDetails::Set(_)
            | TypeEntryDetails::Box(_)
            | TypeEntryDetails::Native(_)
            | TypeEntryDetails::Array(..)
            | TypeEntryDetails::JsonValue => {
                let ident = self.type_ident(type_space, &type_space.settings.type_mod);
                quote! {
                    & #lifetime #ident
                }
            }

            TypeEntryDetails::Option(id) => {
                let inner_ty = type_space
                    .id_to_entry
                    .get(id)
                    .expect("unresolved type id for option");
                let inner_ident = inner_ty.type_parameter_ident(type_space, lifetime_name);

                // Flatten nested Option types. This would only happen if the
                // schema encoded it; it's an odd construction.
                match &inner_ty.details {
                    TypeEntryDetails::Option(_) => inner_ident,
                    _ => quote! { Option<#inner_ident> },
                }
            }

            TypeEntryDetails::Tuple(items) => {
                let type_streams = items.iter().map(|item| {
                    type_space
                        .id_to_entry
                        .get(item)
                        .expect("unresolved type id for tuple")
                        .type_parameter_ident(type_space, lifetime_name)
                });

                if items.len() != 1 {
                    quote! { ( #(#type_streams),* ) }
                } else {
                    // Single-element tuples require special handling. In
                    // particular, they must have a trailing comma or else are
                    // treated as extraneously parenthesized types.
                    quote! { ( #(#type_streams,)* ) }
                }
            }

            TypeEntryDetails::Unit
            | TypeEntryDetails::Boolean
            | TypeEntryDetails::Integer(_)
            | TypeEntryDetails::Float(_) => {
                self.type_ident(type_space, &type_space.settings.type_mod)
            }
            TypeEntryDetails::String => quote! { & #lifetime str },

            TypeEntryDetails::Reference(_) => panic!("references should be resolved by now"),
        }
    }

    pub(crate) fn describe(&self) -> String {
        match &self.details {
            TypeEntryDetails::Enum(TypeEntryEnum { name, .. }) => format!("enum {}", name),
            TypeEntryDetails::Struct(TypeEntryStruct { name, .. }) => format!("struct {}", name),
            TypeEntryDetails::Newtype(TypeEntryNewtype { name, type_id, .. }) => {
                format!("newtype {} {}", name, type_id.0)
            }

            TypeEntryDetails::Unit => "()".to_string(),
            TypeEntryDetails::Option(type_id) => format!("option {}", type_id.0),
            TypeEntryDetails::Vec(type_id) => format!("vec {}", type_id.0),
            TypeEntryDetails::Map(key_id, value_id) => {
                format!("map {} {}", key_id.0, value_id.0)
            }
            TypeEntryDetails::Set(type_id) => format!("set {}", type_id.0),
            TypeEntryDetails::Box(type_id) => format!("box {}", type_id.0),
            TypeEntryDetails::Tuple(type_ids) => {
                format!(
                    "tuple ({})",
                    type_ids
                        .iter()
                        .map(|type_id| type_id.0.to_string())
                        .collect::<Vec<String>>()
                        .join(", ")
                )
            }
            TypeEntryDetails::Array(type_id, length) => {
                format!("array {}; {}", type_id.0, length)
            }
            TypeEntryDetails::Boolean => "bool".to_string(),
            TypeEntryDetails::Native(TypeEntryNative {
                type_name: name, ..
            })
            | TypeEntryDetails::Integer(name)
            | TypeEntryDetails::Float(name) => name.clone(),
            TypeEntryDetails::String => "string".to_string(),

            TypeEntryDetails::JsonValue => "json value".to_string(),

            TypeEntryDetails::Reference(_) => unreachable!(),
        }
    }
}

fn make_doc(name: &str, description: Option<&String>, schema: &Schema) -> TokenStream {
    let desc = match description {
        Some(desc) => desc,
        None => &format!("`{}`", name),
    };
    let schema_json = serde_json::to_string_pretty(schema).unwrap();
    let schema_lines = schema_json.lines();
    quote! {
        #[doc = #desc]
        ///
        /// <details><summary>JSON schema</summary>
        ///
        /// ```json
        #(
            #[doc = #schema_lines]
        )*
        /// ```
        /// </details>
    }
}

fn strings_to_derives<'a>(
    derive_set: BTreeSet<&'a str>,
    type_derives: &'a BTreeSet<String>,
    extra_derives: &'a [String],
) -> impl Iterator<Item = TokenStream> + 'a {
    let mut combined_derives = derive_set.clone();
    combined_derives.extend(extra_derives.iter().map(String::as_str));
    combined_derives.extend(type_derives.iter().map(String::as_str));
    combined_derives.into_iter().map(|derive| {
        syn::parse_str::<syn::Path>(derive)
            .unwrap()
            .into_token_stream()
    })
}

fn strings_to_attrs<'a>(
    type_attrs: &'a BTreeSet<String>,
    extra_attrs: &'a [String],
) -> impl Iterator<Item = TokenStream> + 'a {
    let mut combined_attrs = BTreeSet::new();
    combined_attrs.extend(extra_attrs.iter().map(String::as_str));
    combined_attrs.extend(type_attrs.iter().map(String::as_str));
    combined_attrs
        .into_iter()
        .map(|attr| attr.parse::<TokenStream>().unwrap())
}

/// Returns true iff...
/// - the enum is untagged
/// - all variants are single items (aka newtype variants)
/// - the type of the newtype variant implements the required trait
fn untagged_newtype_variants(
    type_space: &TypeSpace,
    tag_type: &EnumTagType,
    variants: &[Variant],
    req_impl: TypeSpaceImpl,
    neg_impl: Option<TypeSpaceImpl>,
) -> bool {
    tag_type == &EnumTagType::Untagged
        && variants.iter().all(|variant| {
            // If the variant is a single item...
            match &variant.details {
                VariantDetails::Item(type_id) => Some(type_id),
                _ => None,
            }
            .map_or_else(
                || false,
                |type_id| {
                    let type_entry = type_space.id_to_entry.get(type_id).unwrap();
                    // ... and its type has the required impl
                    type_entry.has_impl(type_space, req_impl)
                        && neg_impl
                            .is_none_or(|neg_impl| !type_entry.has_impl(type_space, neg_impl))
                },
            )
        })
}

/// Returns true iff...
/// - the enum is untagged
/// - **any** variant is a single items **and** it is irrefutably a string
fn untagged_newtype_string(
    type_space: &TypeSpace,
    tag_type: &EnumTagType,
    variants: &[Variant],
) -> bool {
    tag_type == &EnumTagType::Untagged
        && variants.iter().any(|variant| {
            // If the variant is a single item...
            match &variant.details {
                VariantDetails::Item(type_id) => Some(type_id),
                _ => None,
            }
            .map_or_else(
                || false,
                |type_id| {
                    let type_entry = type_space.id_to_entry.get(type_id).unwrap();
                    // ... and it is irrefutably a string
                    type_entry.has_impl(type_space, TypeSpaceImpl::FromStringIrrefutable)
                },
            )
        })
}

#[cfg(test)]
mod tests {
    use crate::{
        type_entry::{SchemaWrapper, TypeEntry, TypeEntryStruct},
        TypeEntryDetails, TypeSpace,
    };

    #[test]
    fn test_ident() {
        let ts = TypeSpace::default();

        let type_mod = Some("the_mod".to_string());

        let t = TypeEntry::new_integer("u32");
        let ident = t.type_ident(&ts, &type_mod);
        assert_eq!(ident.to_string(), "u32");
        let parameter = t.type_parameter_ident(&ts, None);
        assert_eq!(parameter.to_string(), "u32");

        let t = TypeEntry::from(TypeEntryDetails::String);
        let ident = t.type_ident(&ts, &type_mod);
        assert_eq!(ident.to_string(), ":: std :: string :: String");
        let parameter = t.type_parameter_ident(&ts, None);
        assert_eq!(parameter.to_string(), "& str");
        let parameter = t.type_parameter_ident(&ts, Some("static"));
        assert_eq!(parameter.to_string(), "& 'static str");

        let t = TypeEntry::from(TypeEntryDetails::Unit);
        let ident = t.type_ident(&ts, &type_mod);
        assert_eq!(ident.to_string(), "()");
        let parameter = t.type_parameter_ident(&ts, None);
        assert_eq!(parameter.to_string(), "()");

        let t = TypeEntry::from(TypeEntryDetails::Struct(TypeEntryStruct {
            name: "SomeType".to_string(),
            rename: None,
            description: None,
            default: None,
            properties: vec![],
            deny_unknown_fields: false,
            schema: SchemaWrapper(schemars::schema::Schema::Bool(false)),
        }));

        let ident = t.type_ident(&ts, &type_mod);
        assert_eq!(ident.to_string(), "the_mod :: SomeType");
        let parameter = t.type_parameter_ident(&ts, None);
        assert_eq!(parameter.to_string(), "& SomeType");
        let parameter = t.type_parameter_ident(&ts, Some("a"));
        assert_eq!(parameter.to_string(), "& 'a SomeType");
    }
}