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
// Copyright 2026 Oxide Computer Company

use std::collections::BTreeSet;

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

use crate::build::{JsonValue, Type, TypeCommon, TypeCommonBuilt, validate_ident};
use crate::error::{Error, NameAxis};
use crate::output::Outputspace;
use crate::serde_attrs::SerdeDerives;
use crate::{
    DefaultConstructor, RenderedStructProperty, TypespaceBuilder, TypespaceRenderer, TypespaceTrait,
};

/// A struct with named fields.
///
/// A `Struct` is its own builder: [`Struct::new`] starts one under
/// construction, the fluent methods fill it in ([`Struct::name`] may
/// come at any point), and [`Struct::build`] validates it and produces
/// the finished [`Type::Struct`] value.
#[derive(Debug, Clone)]
pub struct Struct<Id> {
    pub(crate) common: TypeCommon,
    pub(crate) properties: Vec<StructProperty<Id>>,
    pub(crate) deny_unknown_fields: bool,
}

impl<Id> Default for Struct<Id> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Id> Struct<Id> {
    /// Start a struct under construction.
    pub fn new() -> Self {
        Self {
            common: Default::default(),
            properties: Vec::new(),
            deny_unknown_fields: false,
        }
    }

    /// Set the struct's name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.common.name = Some(name.into());
        self
    }

    /// Set the description (doc comment source).
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.common.description = Some(description.into());
        self
    }

    /// Set the default value.
    pub fn default(mut self, default: impl Into<JsonValue>) -> Self {
        self.common.default = Some(default.into());
        self
    }

    /// Add opaque derive paths applied to this type alone.
    ///
    /// These are additional to the crate-wide paths from
    /// [`Settings::with_derive`](crate::settings::Settings::with_derive);
    /// a type's derive attribute names both sets. Each path is emitted
    /// verbatim, with the same caveats `with_derive` documents.
    pub fn extra_derives(mut self, derives: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.common
            .extra_derives
            .extend(derives.into_iter().map(Into::into));
        self
    }

    /// Add opaque attributes applied to this type alone.
    ///
    /// These are additional to the crate-wide attributes from
    /// [`Settings::with_attr`](crate::settings::Settings::with_attr).
    pub fn extra_attrs(mut self, attrs: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.common
            .extra_attrs
            .extend(attrs.into_iter().map(Into::into));
        self
    }

    /// Append properties.
    pub fn properties(mut self, properties: impl IntoIterator<Item = StructProperty<Id>>) -> Self {
        self.properties.extend(properties);
        self
    }

    /// Make deserialization reject unknown fields.
    pub fn deny_unknown_fields(mut self) -> Self {
        self.deny_unknown_fields = true;
        self
    }

    /// Validate the struct and produce it as a [`Type`] value.
    ///
    /// Fails if the name is missing or not a valid identifier, if any
    /// property name is not a valid identifier, or if two properties
    /// collide on either name axis (see
    /// [`Error::DuplicateItemName`]).
    pub fn build(self) -> Result<Type<Id>, Error<Id>>
    where
        Id: std::fmt::Debug + std::fmt::Display,
    {
        self.validate()?;
        Ok(Type::Struct(self))
    }

    /// The checks `build()` applies; also run at insertion as
    /// defense-in-depth.
    pub(crate) fn validate(&self) -> Result<(), Error<Id>>
    where
        Id: std::fmt::Debug + std::fmt::Display,
    {
        self.common.validate_name("struct")?;
        check_properties(self.common.built_name(), &self.properties)
    }

    pub(crate) fn check_field_defaults(
        &self,
        typespace: &TypespaceBuilder<Id>,
    ) -> Result<BTreeSet<Id>, Error<Id>>
    where
        Id: Clone + Ord + std::fmt::Debug + std::fmt::Display,
    {
        self.properties
            .iter()
            .try_fold(BTreeSet::new(), |mut natives, prop| {
                natives.extend(prop.check_defaults(typespace)?);
                Ok(natives)
            })
    }

    /// The struct's name, if one has been set.
    pub fn get_name(&self) -> Option<&str> {
        self.common.name()
    }

    /// The description (doc comment source), if any.
    pub fn get_description(&self) -> Option<&str> {
        self.common.description()
    }

    /// The default value, if any.
    pub fn get_default(&self) -> Option<&serde_json::Value> {
        self.common.default()
    }

    /// The opaque derive paths applied to this type alone, additional
    /// to the crate-wide paths from
    /// [`Settings::with_derive`](crate::settings::Settings::with_derive).
    pub fn get_extra_derives(&self) -> &[String] {
        self.common.extra_derives()
    }

    /// The opaque attributes applied to this type alone, additional to
    /// the crate-wide attributes from
    /// [`Settings::with_attr`](crate::settings::Settings::with_attr).
    pub fn get_extra_attrs(&self) -> &[String] {
        self.common.extra_attrs()
    }

    /// The struct's properties, in declaration order.
    pub fn get_properties(&self) -> &[StructProperty<Id>] {
        &self.properties
    }

    /// Whether deserialization rejects unknown fields.
    pub fn get_deny_unknown_fields(&self) -> bool {
        self.deny_unknown_fields
    }
}

/// Check property names for validity and uniqueness.
///
/// Every Rust name must be a valid identifier, and names must be unique
/// on both axes: the Rust name and the wire name (the serialized name
/// after any rename). Flattened properties have no wire name of their
/// own and are exempt from the wire axis.
pub(crate) fn check_properties<Id>(
    type_name: &str,
    properties: &[StructProperty<Id>],
) -> Result<(), Error<Id>>
where
    Id: std::fmt::Debug + std::fmt::Display,
{
    let mut rust_names = BTreeSet::new();
    let mut wire_names = BTreeSet::new();
    for property in properties {
        let rust_name = property.rust_name.clone();
        validate_ident("property", &rust_name)?;
        let wire_name = property.wire_name().map(str::to_string);
        if !rust_names.insert(rust_name.clone()) {
            return Err(Error::DuplicateItemName {
                kind: "property",
                type_name: type_name.to_string(),
                name: rust_name,
                axis: NameAxis::Rust,
            });
        }
        if let Some(wire_name) = wire_name
            && !wire_names.insert(wire_name.clone())
        {
            return Err(Error::DuplicateItemName {
                kind: "property",
                type_name: type_name.to_string(),
                name: wire_name,
                axis: NameAxis::Wire,
            });
        }
    }
    Ok(())
}

impl<Id: Clone + Ord + std::fmt::Debug + std::fmt::Display> Struct<Id> {
    pub(crate) fn render(
        &self,
        id: &Id,
        typespace: &TypespaceRenderer<'_, Id>,
        out: &mut Outputspace,
    ) -> proc_macro2::TokenStream {
        let Self {
            common:
                TypeCommon {
                    name,
                    description,
                    default,
                    built:
                        Some(TypeCommonBuilt {
                            traits,
                            from_string_irrefutable: _,
                        }),
                    extra_derives,
                    extra_attrs,
                },
            properties,
            deny_unknown_fields,
        } = self
        else {
            unreachable!()
        };
        let name = name.as_deref().expect("validated type has a name");
        let description = description.as_ref().map(|desc| quote! { #[doc = #desc] });
        let name_ident = format_ident!("{name}");

        let mut traits = traits.clone();
        let serde_derives = SerdeDerives::new(&traits);

        let rendered_properties = properties
            .iter()
            .map(|prop| typespace.render_struct_property(prop, serde_derives, true, name, out))
            .collect::<Vec<_>>();

        if typespace.has_builder(id) {
            // TODO 9/1/2026
            // for compat: some of these are unqualified and some are fully
            // qualified; resolve.

            let prop_ident = rendered_properties
                .iter()
                .map(
                    |RenderedStructProperty {
                         rust_name_ident, ..
                     }| rust_name_ident,
                )
                .collect::<Vec<_>>();
            let prop_error = rendered_properties.iter().map(
                |RenderedStructProperty {
                     rust_name_ident, ..
                 }| {
                    format!(
                        "error converting supplied value for {}: {{e}}",
                        rust_name_ident
                    )
                },
            );
            let prop_ty_ident_scoped = rendered_properties
                .iter()
                .map(
                    |RenderedStructProperty {
                         prop_ty_ident_scoped,
                         ..
                     }| prop_ty_ident_scoped,
                )
                .collect::<Vec<_>>();
            let prop_default_value = rendered_properties.iter().map(
                |RenderedStructProperty {
                     rust_name_ident,
                     default,
                     ..
                 }| match default {
                    DefaultConstructor::None => {
                        let msg = format!("no value supplied for {}", rust_name_ident);
                        quote! {
                            Err(#msg.to_string())
                        }
                    }
                    DefaultConstructor::Default => quote! { Ok(Default::default()) },
                    DefaultConstructor::Generated(default_expr) => {
                        quote! { Ok(super::#default_expr) }
                    }
                },
            );

            // The builder mod is a separate application of the canonical
            // item order under its own item key: decl, Default, setters,
            // TryFrom<Builder> for Type, From<Type> for Builder. It is
            // BUILDER_ORDER in tests/item_order.rs.
            let value_ident = if prop_ident.is_empty() {
                quote! { _value }
            } else {
                quote! { value }
            };

            let builder = quote! {
                #[derive(Clone, Debug)]
                pub struct #name_ident {
                    #(
                        #prop_ident: ::std::result::Result<
                            #prop_ty_ident_scoped,
                            ::std::string::String,
                        >,
                    )*
                }

                impl ::std::default::Default for #name_ident {
                    fn default() -> Self {
                        Self {
                            #(
                                #prop_ident: #prop_default_value,
                            )*
                        }
                    }
                }

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

                impl ::std::convert::TryFrom<#name_ident>
                    for super::#name_ident
                {
                    type Error = super::error::ConversionError;

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

                impl ::std::convert::From<super::#name_ident> for #name_ident {
                    fn from(#value_ident: super::#name_ident) -> Self {
                        Self {
                            #(
                                #prop_ident: Ok(value.#prop_ident),
                            )*
                        }
                    }
                }
            };

            out.cs()
                .get_root_mod()
                .get_mod("builder")
                .add_item(name, builder);
            typespace.add_error_mod(out);
        }

        let builder_impl = typespace
            .render_builder_ident(id, None)
            .map(|builder_ident| {
                quote! {
                    impl #name_ident {
                        pub fn builder() -> #builder_ident {
                            // TODO 9/1/2026
                            // TYPIFY COMPAT: Add std scope
                            Default::default()
                        }
                    }
                }
            });

        let default_impl = traits.contains(&TypespaceTrait::Default).then(|| {
            // If there's no whole-type default value and every property's
            // default is the intrinsic `Default::default()`, the hand-written
            // `impl Default` would be exactly what `#[derive(Default)]`
            // produces (and would trip clippy's `derivable_impls` lint
            // downstream). In that case we derive `Default` rather than
            // emitting the manual impl below.
            //
            // TODO 9/4/2026
            // Default... or if it's optional? Not sure how typify handles
            // this.
            if default.is_none()
                && rendered_properties
                    .iter()
                    .all(|prop| matches!(&prop.default, DefaultConstructor::Default))
            {
                return Default::default();
            }

            traits.remove(TypespaceTrait::Default);

            if let Some(JsonValue(default_value)) = default {
                let body = typespace.generate_default_value_for_impl(default_value, id);
                quote! {
                    impl ::std::default::Default for #name_ident {
                        fn default() -> Self {
                            #body
                        }
                    }
                }
            } else {
                let default_props = rendered_properties.iter().map(
                    |RenderedStructProperty {
                         rust_name_ident,
                         default,
                         ..
                     }| {
                        let default_value = match default {
                            DefaultConstructor::None => unreachable!(),
                            DefaultConstructor::Default => quote! { Default::default() },
                            DefaultConstructor::Generated(default_fn) => default_fn.clone(),
                        };
                        quote! {
                            #rust_name_ident: #default_value
                        }
                    },
                );

                quote! {
                    impl ::std::default::Default for #name_ident {
                        fn default() -> Self {
                            Self {
                                #( #default_props, )*
                            }
                        }
                    }
                }
            }
        });

        // An ordinary struct is neither of typify's comparison-derive
        // exceptions, so it is never exempt.
        let derive_attr = typespace.render_derives(&traits, extra_derives, false);
        let attrs = typespace.render_attrs(extra_attrs);

        let mut serde = serde_derives.attrs();
        // An unknown field is a deserialization concern, so this one is
        // held back from a Serialize-only type rather than left inert.
        if serde_derives.deserialize() && *deny_unknown_fields {
            serde.push(quote! { deny_unknown_fields });
        }

        // Canonical item order: see tests/item_order.rs.
        quote! {
            #description
            #( #attrs )*
            #derive_attr
            #serde
            pub struct #name_ident {
                #( #rendered_properties, )*
            }

            #default_impl

            #builder_impl
        }
    }

    pub(crate) fn children(&self) -> Vec<Id> {
        self.properties
            .iter()
            .map(|StructProperty { type_id, .. }| type_id.clone())
            .collect()
    }
}

/// One named field of a [`Struct`] (or of a struct-shaped enum
/// variant).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub struct StructProperty<Id> {
    pub(crate) rust_name: String,
    pub(crate) json_name: StructPropertySerde,
    pub(crate) state: StructPropertyState,
    pub(crate) description: Option<String>,
    pub(crate) type_id: Id,
}

impl<Id> StructProperty<Id> {
    /// Create a property named `rust_name` whose type is `type_id`.
    ///
    /// The property starts [`StructPropertyState::Required`], with no
    /// serde renaming and no description; adjust with the `with_`
    /// methods. The name is validated--as a plain, non-keyword, non-raw
    /// Rust identifier--when the containing shape is built.
    pub fn new(rust_name: impl Into<String>, type_id: Id) -> Self {
        Self {
            rust_name: rust_name.into(),
            json_name: StructPropertySerde::None,
            state: StructPropertyState::Required,
            description: None,
            type_id,
        }
    }

    /// Set the property's volitionality.
    pub fn with_state(mut self, state: StructPropertyState) -> Self {
        self.state = state;
        self
    }

    /// Set the serde treatment of the property's name.
    pub fn with_json_name(mut self, json_name: StructPropertySerde) -> Self {
        self.json_name = json_name;
        self
    }

    /// Set the description (doc comment source).
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// The Rust field name.
    pub fn rust_name(&self) -> &str {
        &self.rust_name
    }

    /// The serde treatment of the property's name.
    pub fn json_name(&self) -> &StructPropertySerde {
        &self.json_name
    }

    /// The name the property serializes under.
    ///
    /// The serde rename when there is one and the Rust name otherwise.
    /// A flattened property has no wire name of its own: its fields are
    /// spliced into the containing type's wire form.
    pub(crate) fn wire_name(&self) -> Option<&str> {
        match &self.json_name {
            StructPropertySerde::None => Some(self.rust_name.as_str()),
            StructPropertySerde::Rename(rename) => Some(rename.as_str()),
            StructPropertySerde::Flatten => None,
        }
    }

    /// The property's volitionality.
    pub fn state(&self) -> &StructPropertyState {
        &self.state
    }

    /// The description (doc comment source), if any.
    pub fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }

    /// The ID of the property's type.
    pub fn type_id(&self) -> &Id {
        &self.type_id
    }

    pub(crate) fn check_defaults(
        &self,
        typespace: &TypespaceBuilder<Id>,
    ) -> Result<BTreeSet<Id>, Error<Id>>
    where
        Id: Clone + Ord + std::fmt::Debug + std::fmt::Display,
    {
        let StructPropertyState::DefaultValue(JsonValue(value)) = &self.state else {
            return Ok(BTreeSet::new());
        };

        // A property's own default value renders as a generated function in
        // the defaults `mod` that only a deserialize path calls. Any native
        // types initialized by that default value must implement `Deserialize`.
        //
        // The walk raises a second kind of obligation, which this filter must
        // remove. Wherever it reaches a struct with a Default-state property
        // that the value leaves out, the generated function writes `prop:
        // Default::default()`, so that property's type needs Default. The set
        // returned here names only ids, and everything in it is seeded as a
        // Deserialize requirement, so letting one through would charge the
        // wrong trait rather than merely charge one twice.
        //
        // Omitting them instead of widening this channel to carry a trait is
        // safe only because required_resolution separately charges Default to
        // the type of every Default-state property of every type, which
        // already covers every pair the walk can find. If that seed ever
        // narrows to the types that actually deserialize, these have to come
        // back.
        Ok(typespace
            .check_default(value, &self.type_id)?
            .into_iter()
            .filter_map(
                |crate::Obligation {
                     required, target, ..
                 }| {
                    (required == crate::TypespaceTrait::Deserialize).then_some(target)
                },
            )
            .collect())
    }
}

/// The serde treatment of a struct property's name.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum StructPropertySerde {
    /// The property serializes under its Rust name.
    None,
    /// The property serializes under the given name instead.
    Rename(String),
    /// The property's own fields are flattened into the containing type's
    /// serialized form; see [the serde
    /// docs](https://serde.rs/attr-flatten.html).
    Flatten,
}

/// The volitionality of a struct property.
///
/// Only `Optional` translates into an `Option<T>` type; the others are
/// required in Rust. Conversely, only `Required` must be present during
/// deserialization; the others may be omitted. Note that the rendering of an
/// `Optional` property whose type is [`Type::Option`] is dictated by the
/// value of
/// [`Settings::optional_nullable`](crate::settings::Settings::optional_nullable).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum StructPropertyState {
    /// The field must be present.
    Required,
    /// The field may be omitted.
    Optional,
    /// The field may be omitted; if it is, its value comes from the type's
    /// intrinsic default. For built-in types, serialization of the default
    /// will be omitted.
    Default,
    /// The field may be omitted; if it is, its value comes from the provided
    /// JSON value. This applies only to deserialization; serialization
    /// will always emit the field.
    DefaultValue(JsonValue),
}

impl StructPropertyState {
    /// Whether the property is in the optional state.
    pub(crate) fn is_optional(&self) -> bool {
        matches!(self, StructPropertyState::Optional)
    }
}

/// A fieldless struct with a fixed JSON representation.
///
/// A `UnitStruct` is its own builder: [`UnitStruct::new`] starts one
/// under construction around its required representation, the fluent
/// methods fill it in, and [`UnitStruct::build`] validates it and
/// produces the finished [`Type::UnitStruct`] value.
#[derive(Debug, Clone)]
pub struct UnitStruct {
    pub(crate) common: TypeCommon,

    pub(crate) repr: serde_json::Value,
}
impl UnitStruct {
    /// Start a unit struct that serializes as `repr`.
    pub fn new(repr: serde_json::Value) -> Self {
        Self {
            common: Default::default(),
            repr,
        }
    }

    /// Set the unit struct's name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.common.name = Some(name.into());
        self
    }

    /// Set the description (doc comment source).
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.common.description = Some(description.into());
        self
    }

    /// Add opaque derive paths applied to this type alone.
    ///
    /// These are additional to the crate-wide paths from
    /// [`Settings::with_derive`](crate::settings::Settings::with_derive);
    /// a type's derive attribute names both sets. Each path is emitted
    /// verbatim, with the same caveats `with_derive` documents.
    pub fn extra_derives(mut self, derives: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.common
            .extra_derives
            .extend(derives.into_iter().map(Into::into));
        self
    }

    /// Add opaque attributes applied to this type alone.
    ///
    /// These are additional to the crate-wide attributes from
    /// [`Settings::with_attr`](crate::settings::Settings::with_attr).
    pub fn extra_attrs(mut self, attrs: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.common
            .extra_attrs
            .extend(attrs.into_iter().map(Into::into));
        self
    }

    /// Validate the unit struct and produce it as a [`Type`] value.
    ///
    /// Fails if the name is missing or not a valid identifier.
    pub fn build<Id>(self) -> Result<Type<Id>, Error<Id>>
    where
        Id: std::fmt::Debug + std::fmt::Display,
    {
        self.validate()?;
        Ok(Type::UnitStruct(self))
    }

    /// The checks `build()` applies; also run at insertion as
    /// defense-in-depth.
    pub(crate) fn validate<Id>(&self) -> Result<(), Error<Id>>
    where
        Id: std::fmt::Debug + std::fmt::Display,
    {
        self.common.validate_name("unit struct")
    }

    /// The unit struct's name, if one has been set.
    pub fn get_name(&self) -> Option<&str> {
        self.common.name()
    }

    /// The description (doc comment source), if any.
    pub fn get_description(&self) -> Option<&str> {
        self.common.description()
    }

    /// The opaque derive paths applied to this type alone, additional
    /// to the crate-wide paths from
    /// [`Settings::with_derive`](crate::settings::Settings::with_derive).
    pub fn get_extra_derives(&self) -> &[String] {
        self.common.extra_derives()
    }

    /// The opaque attributes applied to this type alone, additional to
    /// the crate-wide attributes from
    /// [`Settings::with_attr`](crate::settings::Settings::with_attr).
    pub fn get_extra_attrs(&self) -> &[String] {
        self.common.extra_attrs()
    }

    /// The fixed JSON value the unit struct serializes to and
    /// deserializes from.
    pub fn get_repr(&self) -> &serde_json::Value {
        &self.repr
    }

    pub(crate) fn render<Id: Clone + Ord + std::fmt::Debug + std::fmt::Display>(
        &self,
        typespace: &TypespaceRenderer<'_, Id>,
    ) -> proc_macro2::TokenStream {
        let Self {
            common:
                TypeCommon {
                    name,
                    description,
                    built:
                        Some(TypeCommonBuilt {
                            traits,
                            from_string_irrefutable: _,
                        }),
                    default: _,
                    extra_derives,
                    extra_attrs,
                },
            repr,
        } = self
        else {
            unreachable!()
        };
        let name = name.as_deref().expect("validated type has a name");
        let description = description.as_ref().map(|desc| quote! { #[doc = #desc ]});
        let name_ident = format_ident!("{name}");

        let repr_tokens = crate::value_tokens::value_tokens(repr);
        let repr_string = serde_json::to_string(repr).unwrap();

        let mut traits = traits.clone();
        let serialize_impl = traits.remove(TypespaceTrait::Serialize).then(|| {
            quote! {
                impl ::serde::Serialize for #name_ident {
                    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
                    where
                        S: ::serde::Serializer,
                    {
                        #repr_tokens.serialize(serializer)
                    }
                }
            }
        });

        let deserialize_impl = traits.remove(TypespaceTrait::Deserialize).then(|| {
            quote! {
                impl<'de> ::serde::Deserialize<'de> for #name_ident {
                    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                    where
                        D: ::serde::Deserializer<'de>,
                    {
                        let expected = #repr_tokens;
                        let value: ::serde_json::Value =
                            ::serde::Deserialize::deserialize(deserializer)?;
                        if value != expected {
                            return Err(::serde::de::Error::custom(format!(
                                "expected unit struct value {}, found {}",
                                #repr_string,
                                ::serde_json::to_string(&value).unwrap())));
                        }
                        Ok(#name_ident)
                    }
                }
            }
        });

        // A unit struct is neither of typify's comparison-derive
        // exceptions, so it is never exempt.
        let derive_attr = typespace.render_derives(&traits, extra_derives, false);
        let attrs = typespace.render_attrs(extra_attrs);

        // Canonical item order: see tests/item_order.rs.
        quote! {
            #description
            #( #attrs )*
            #derive_attr
            pub struct #name_ident;

            #serialize_impl
            #deserialize_impl
        }
    }
}

/// A struct with unnamed, positional fields.
///
/// A `TupleStruct` is its own builder: [`TupleStruct::new`] starts one
/// under construction, the fluent methods fill it in, and
/// [`TupleStruct::build`] validates it and produces the finished
/// [`Type::TupleStruct`] value.
#[derive(Debug, Clone)]
pub struct TupleStruct<Id> {
    pub(crate) common: TypeCommon,
    /// Fields of the tuple.
    pub(crate) fields: Vec<Id>,

    /// Optional type, which must be represented as an array, that stores
    /// items beyond those in `fields`.
    pub(crate) rest: Option<Id>,
}

impl<Id> Default for TupleStruct<Id> {
    fn default() -> Self {
        Self::new()
    }
}

impl<Id> TupleStruct<Id> {
    /// Start a tuple struct under construction.
    pub fn new() -> Self {
        Self {
            common: Default::default(),
            fields: Vec::new(),
            rest: None,
        }
    }

    /// Set the tuple struct's name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.common.name = Some(name.into());
        self
    }

    /// Set the description (doc comment source).
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.common.description = Some(description.into());
        self
    }

    /// Set the default value.
    pub fn default(mut self, default: impl Into<JsonValue>) -> Self {
        self.common.default = Some(default.into());
        self
    }

    /// Add opaque derive paths applied to this type alone.
    ///
    /// These are additional to the crate-wide paths from
    /// [`Settings::with_derive`](crate::settings::Settings::with_derive);
    /// a type's derive attribute names both sets. Each path is emitted
    /// verbatim, with the same caveats `with_derive` documents.
    pub fn extra_derives(mut self, derives: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.common
            .extra_derives
            .extend(derives.into_iter().map(Into::into));
        self
    }

    /// Add opaque attributes applied to this type alone.
    ///
    /// These are additional to the crate-wide attributes from
    /// [`Settings::with_attr`](crate::settings::Settings::with_attr).
    pub fn extra_attrs(mut self, attrs: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.common
            .extra_attrs
            .extend(attrs.into_iter().map(Into::into));
        self
    }

    /// Append positional fields.
    pub fn fields(mut self, fields: impl IntoIterator<Item = Id>) -> Self {
        self.fields.extend(fields);
        self
    }

    /// Set the type, necessarily array-shaped, that stores items beyond
    /// the positional fields.
    pub fn rest(mut self, rest: Id) -> Self {
        self.rest = Some(rest);
        self
    }

    /// Validate the tuple struct and produce it as a [`Type`] value.
    ///
    /// Fails if the name is missing or not a valid identifier, or if no
    /// fields were added (see [`Error::FieldlessTupleStruct`]).
    pub fn build(self) -> Result<Type<Id>, Error<Id>>
    where
        Id: std::fmt::Debug + std::fmt::Display,
    {
        self.validate()?;
        Ok(Type::TupleStruct(self))
    }

    /// The checks `build()` applies; also run at insertion as
    /// defense-in-depth.
    pub(crate) fn validate(&self) -> Result<(), Error<Id>>
    where
        Id: std::fmt::Debug + std::fmt::Display,
    {
        self.common.validate_name("tuple struct")?;
        if self.fields.is_empty() {
            let alternative = match self.rest {
                Some(_) => "`NewtypeStruct` over the sequence type",
                None => "`UnitStruct`",
            };
            return Err(Error::FieldlessTupleStruct {
                name: self.common.built_name().to_string(),
                alternative,
            });
        }
        Ok(())
    }

    /// The tuple struct's name, if one has been set.
    pub fn get_name(&self) -> Option<&str> {
        self.common.name()
    }

    /// The description (doc comment source), if any.
    pub fn get_description(&self) -> Option<&str> {
        self.common.description()
    }

    /// The default value, if any.
    pub fn get_default(&self) -> Option<&serde_json::Value> {
        self.common.default()
    }

    /// The opaque derive paths applied to this type alone, additional
    /// to the crate-wide paths from
    /// [`Settings::with_derive`](crate::settings::Settings::with_derive).
    pub fn get_extra_derives(&self) -> &[String] {
        self.common.extra_derives()
    }

    /// The opaque attributes applied to this type alone, additional to
    /// the crate-wide attributes from
    /// [`Settings::with_attr`](crate::settings::Settings::with_attr).
    pub fn get_extra_attrs(&self) -> &[String] {
        self.common.extra_attrs()
    }

    /// The fields of the tuple, in order.
    pub fn get_fields(&self) -> &[Id] {
        &self.fields
    }

    /// The type, necessarily array-shaped, holding items beyond the
    /// positional fields, if any.
    pub fn get_rest(&self) -> Option<&Id> {
        self.rest.as_ref()
    }
}

impl<Id: Clone + Ord + std::fmt::Debug + std::fmt::Display> TupleStruct<Id> {
    pub(crate) fn render(
        &self,
        id: &Id,
        typespace: &TypespaceRenderer<'_, Id>,
    ) -> proc_macro2::TokenStream {
        let Self {
            common:
                TypeCommon {
                    name,
                    description,
                    default,
                    built:
                        Some(TypeCommonBuilt {
                            traits,
                            from_string_irrefutable: _,
                        }),
                    extra_derives,
                    extra_attrs,
                },
            fields,
            rest,
        } = self
        else {
            unreachable!()
        };
        let name = name.as_deref().expect("validated type has a name");
        let description = description.as_ref().map(|desc| quote! { #[doc = #desc] });

        let name_ident = format_ident!("{name}");

        let field_ident = fields
            .iter()
            .map(|field_id| typespace.render_ident(field_id))
            .collect::<Vec<_>>();
        let rest_ident = rest.as_ref().map(|rest_id| typespace.render_ident(rest_id));

        let field_index = (0..fields.len()).map(syn::Index::from);
        let rest_index = rest
            .as_ref()
            .map(|_| syn::Index::from(fields.len()))
            .into_iter();

        let field_var = (0..fields.len())
            .map(|ii| format_ident!("field_{ii}"))
            .collect::<Vec<_>>();
        let field_int = (0..fields.len()).collect::<Vec<_>>();
        let rest_var = rest
            .as_ref()
            .map(|_| format_ident!("rest"))
            .into_iter()
            .collect::<Vec<_>>();
        let expected = format!("a tuple of size {} or more", fields.len());

        let mut traits = traits.clone();
        let serialize_impl = traits.remove(TypespaceTrait::Serialize).then(|| {
            quote! {
                impl ::serde::Serialize for #name_ident {
                    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
                    where
                        S: ::serde::Serializer,
                    {
                        use ::serde::ser::SerializeSeq;
                        let mut seq = serializer.serialize_seq(None)?;
                        #(
                            seq.serialize_element(&self.#field_index)?;
                        )*
                        #(
                            self.#rest_index.serialize(
                                ::json_serde::FlattenedSequenceSerializer::new(&mut seq)
                            )?;
                        )*
                        seq.end()
                    }
                }
            }
        });
        let deserialize_impl = traits.remove(TypespaceTrait::Deserialize).then(|| {
            quote! {
                impl<'de> ::serde::Deserialize<'de> for #name_ident {
                    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                    where
                        D: ::serde::Deserializer<'de>,
                    {
                        struct Visitor;

                        impl<'de> ::serde::de::Visitor<'de> for Visitor {
                            type Value = #name_ident;

                            fn expecting(&self, formatter: &mut ::std::fmt::Formatter)
                                -> ::std::fmt::Result
                            {
                                formatter.write_str("a sequence")
                            }

                            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
                            where
                                A: ::serde::de::SeqAccess<'de>,
                            {
                                // Strictly speaking, we don't need to store
                                // each tuple element in a variable, but as a
                                // practical matter, it makes the generated
                                // code much easier to follow and less deeply
                                // indented.
                                #(
                                    let #field_var = seq
                                        .next_element()?
                                        .ok_or_else(|| ::serde::de::Error::invalid_length(
                                            #field_int,
                                            &#expected
                                        ))?;
                                )*
                                #(
                                    let #rest_var = ::serde::Deserialize::deserialize(
                                        ::json_serde::FlattenedSequenceDeserializer::new(&mut seq)
                                    )?;
                                )*
                                Ok(#name_ident(
                                    #( #field_var, )*
                                    #( #rest_var, )*
                                ))
                            }
                        }

                        deserializer.deserialize_seq(Visitor)
                    }
                }
            }
        });

        // TODO 9/10/2026
        // Do we only want to do this if `rest` is Some? Or do we want to err
        // on the side of more generated and less derive impls?
        let json_schema_impl = traits.remove(TypespaceTrait::JsonSchema).then(|| {
            let (additional_items, min_items, max_items) = if let Some(rest_id) = rest.as_ref() {
                assert!(rest_ident.is_some());
                let additional_items = quote! {
                    additional_items: Some(::std::boxed::Box::new(
                        g.subschema_for::<#rest_ident>()
                    )),
                };

                let array_bounds = typespace.array_bounds(rest_id);
                let len = fields.len();

                let min = match array_bounds {
                    Some((min, _)) => len + min,
                    _ => len,
                } as u32;
                let max = match array_bounds {
                    Some((_, Some(max))) => Some((len + max) as u32),
                    _ => None,
                };

                let max_items = if let Some(max) = max {
                    quote! { max_items: Some(#max), }
                } else {
                    TokenStream::new()
                };

                (
                    additional_items,
                    quote! { min_items: Some(#min), },
                    max_items,
                )
            } else {
                let len = fields.len() as u32;
                (
                    TokenStream::new(),
                    quote! { min_items: Some(#len), },
                    quote! { max_items: Some(#len), },
                )
            };

            let description = description.as_ref().map(|d| {
                quote! {
                    description: Some(#d.to_string()),
                }
            });

            let default = default.as_ref().map(|JsonValue(value)| {
                let as_str = value.to_string();
                quote! { default: Some(::serde_json::from_str(#as_str).unwrap()), }
            });

            quote! {
                impl ::schemars::JsonSchema for #name_ident {
                    fn schema_name() -> ::std::string::String {
                        #name.to_string()
                    }

                    fn json_schema(
                        g: &mut ::schemars::r#gen::SchemaGenerator,
                    ) -> ::schemars::schema::Schema {
                        let fields = [
                            #(
                                g.subschema_for::<#field_ident>(),
                            )*
                        ]
                            .into_iter()
                            .collect();
                        ::schemars::schema::SchemaObject {
                            metadata: Some(::std::boxed::Box::new(
                                ::schemars::schema::Metadata {
                                    title: Some(#name.to_string()),
                                    #description
                                    #default
                                    ..::std::default::Default::default()
                                }
                            )),
                            instance_type: Some(
                                ::schemars::schema::SingleOrVec::Single(
                                    ::std::boxed::Box::new(
                                        ::schemars::schema::InstanceType::Array,
                                    )
                                )
                            ),
                            array: Some(::std::boxed::Box::new(
                                ::schemars::schema::ArrayValidation {
                                    items: Some(
                                        ::schemars::schema::SingleOrVec::Vec(fields)
                                    ),
                                    #additional_items
                                    #max_items
                                    #min_items
                                    ..::std::default::Default::default()
                                }
                            )),
                            ..::std::default::Default::default()
                        }
                        .into()
                    }
                }
            }
        });

        let default_impl = if let Some(JsonValue(value)) = default
            && traits.remove(TypespaceTrait::Default)
        {
            let default_value = typespace.generate_default_value_for_impl(value, id);
            quote! {
                impl ::std::default::Default for #name_ident {
                    fn default() -> Self {
                        #default_value
                    }
                }
            }
        } else {
            TokenStream::new()
        };

        // A tuple struct is neither of typify's comparison-derive
        // exceptions, so it is never exempt.
        let derive_attr = typespace.render_derives(&traits, extra_derives, false);
        let attrs = typespace.render_attrs(extra_attrs);

        let rest_ident_iter = rest_ident.into_iter();

        // Canonical item order: see tests/item_order.rs.
        quote! {
            #description
            #( #attrs )*
            #derive_attr
            pub struct #name_ident(
                #( pub #field_ident, )*
                #( pub #rest_ident_iter, )*
            );

            #default_impl
            #serialize_impl
            #deserialize_impl
            #json_schema_impl
        }
    }

    pub(crate) fn children(&self) -> Vec<Id> {
        let mut children = self.fields.clone();
        if let Some(rest) = &self.rest {
            children.push(rest.clone());
        }

        children
    }

    pub(crate) fn contained_children_mut(&mut self) -> Vec<&mut Id> {
        let mut children = self.fields.iter_mut().collect::<Vec<&mut Id>>();

        if let Some(rest) = &mut self.rest {
            children.push(rest);
        }

        children
    }
}

/// A single-field wrapper struct.
///
/// A `NewtypeStruct` is its own builder: [`NewtypeStruct::new`] starts
/// one under construction around its required inner type, the fluent
/// methods fill it in, and [`NewtypeStruct::build`] validates it and
/// produces the finished [`Type::NewtypeStruct`] value.
#[derive(Debug, Clone)]
pub struct NewtypeStruct<Id> {
    pub(crate) common: TypeCommon,
    pub(crate) inner: Id,
    pub(crate) constraints: NewtypeConstraints,
}

impl<Id> NewtypeStruct<Id> {
    /// Start a newtype struct wrapping the type `inner`.
    pub fn new(inner: Id) -> Self {
        Self {
            common: Default::default(),
            inner,
            constraints: NewtypeConstraints::None,
        }
    }

    /// Set the newtype's name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.common.name = Some(name.into());
        self
    }

    /// Set the description (doc comment source).
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.common.description = Some(description.into());
        self
    }

    /// Set the default value.
    pub fn default(mut self, default: impl Into<JsonValue>) -> Self {
        self.common.default = Some(default.into());
        self
    }

    /// Add opaque derive paths applied to this type alone.
    ///
    /// These are additional to the crate-wide paths from
    /// [`Settings::with_derive`](crate::settings::Settings::with_derive);
    /// a type's derive attribute names both sets. Each path is emitted
    /// verbatim, with the same caveats `with_derive` documents.
    pub fn extra_derives(mut self, derives: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.common
            .extra_derives
            .extend(derives.into_iter().map(Into::into));
        self
    }

    /// Add opaque attributes applied to this type alone.
    ///
    /// These are additional to the crate-wide attributes from
    /// [`Settings::with_attr`](crate::settings::Settings::with_attr).
    pub fn extra_attrs(mut self, attrs: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.common
            .extra_attrs
            .extend(attrs.into_iter().map(Into::into));
        self
    }

    /// Set the constraints on the wrapped value; see
    /// [`NewtypeConstraints`].
    pub fn constraints(mut self, constraints: NewtypeConstraints) -> Self {
        self.constraints = constraints;
        self
    }

    /// Validate the newtype struct and produce it as a [`Type`] value.
    ///
    /// Fails if the name is missing or not a valid identifier.
    pub fn build(self) -> Result<Type<Id>, Error<Id>>
    where
        Id: std::fmt::Debug + std::fmt::Display,
    {
        self.validate()?;
        Ok(Type::NewtypeStruct(self))
    }

    /// The checks `build()` applies; also run at insertion as
    /// defense-in-depth.
    pub(crate) fn validate(&self) -> Result<(), Error<Id>>
    where
        Id: std::fmt::Debug + std::fmt::Display,
    {
        self.common.validate_name("newtype struct")?;

        // Constraints with nothing in them say nothing
        // NewtypeConstraints::None does not already say, and an
        // unconstrained newtype is the one written the short way.
        // Rejecting them is also what keeps "syntactically constrained"
        // and "stores its input verbatim" from disagreeing.
        let vacuous = match &self.constraints {
            NewtypeConstraints::String {
                min: None,
                max: None,
                patterns,
            } if patterns.is_empty() => Some("string"),
            NewtypeConstraints::AllowList(values) if values.is_empty() => Some("allow list"),
            NewtypeConstraints::DenyList(values) if values.is_empty() => Some("deny list"),
            _ => None,
        };

        match vacuous {
            Some(kind) => Err(Error::VacuousConstraints {
                name: self.common.built_name().to_string(),
                kind,
            }),
            None => Ok(()),
        }
    }

    /// The newtype's name, if one has been set.
    pub fn get_name(&self) -> Option<&str> {
        self.common.name()
    }

    /// The description (doc comment source), if any.
    pub fn get_description(&self) -> Option<&str> {
        self.common.description()
    }

    /// The default value, if any.
    pub fn get_default(&self) -> Option<&serde_json::Value> {
        self.common.default()
    }

    /// The opaque derive paths applied to this type alone, additional
    /// to the crate-wide paths from
    /// [`Settings::with_derive`](crate::settings::Settings::with_derive).
    pub fn get_extra_derives(&self) -> &[String] {
        self.common.extra_derives()
    }

    /// The opaque attributes applied to this type alone, additional to
    /// the crate-wide attributes from
    /// [`Settings::with_attr`](crate::settings::Settings::with_attr).
    pub fn get_extra_attrs(&self) -> &[String] {
        self.common.extra_attrs()
    }

    /// The ID of the wrapped type.
    pub fn get_inner(&self) -> &Id {
        &self.inner
    }

    /// The constraints on the wrapped value.
    pub fn get_constraints(&self) -> &NewtypeConstraints {
        &self.constraints
    }
}

// TODO 3/7/2026
// I'm ambivalent as to whether the constrained form of a newtype should be
// its own, fundamentally distinct entity. However for now I'm going to just
// shove it into the existing newtype representation.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum NewtypeConstraints {
    None,
    AllowList(Vec<JsonValue>),
    DenyList(Vec<JsonValue>),
    String {
        min: Option<usize>,
        max: Option<usize>,
        patterns: Vec<String>,
    },
    Array {
        min: Option<usize>,
        max: Option<usize>,
        // TODO 3/7/2026
        // I'm quite unsure of how to model the contains keyword. It also
        // occurs to me that the constraints below don't suffice--we need
        // an array of structures.
        // As a side-note, as I recall the interaction between `contains` and
        // `unevaluatedItems` is quite baroque i.e satisfying a `contains`
        // constraint counts as evaluation. I suppose this also means that
        // there's an important distinction between `items` being absent vs.
        // having the value of `true`.
        // min_contains: Option<usize>,
        // max_contains: Option<usize>,
        // contains: (),
    },

    /// Fallback constraint
    ///
    /// Verify data against the given JSON schema (using the crate
    /// `jsonschema` for runtime validation).
    JsonSchema(JsonValue),
}

impl<Id: Clone + Ord + std::fmt::Debug + std::fmt::Display> NewtypeStruct<Id> {
    pub(crate) fn children(&self) -> Vec<Id> {
        vec![self.inner.clone()]
    }

    pub(crate) fn contained_children_mut(&mut self) -> Vec<&mut Id> {
        vec![&mut self.inner]
    }

    pub(crate) fn render(
        &self,
        id: &Id,
        typespace: &TypespaceRenderer<'_, Id>,
        out: &mut Outputspace,
    ) -> proc_macro2::TokenStream {
        let Self {
            common:
                TypeCommon {
                    name,
                    description,
                    default,
                    built:
                        Some(TypeCommonBuilt {
                            traits,
                            from_string_irrefutable: _,
                        }),
                    extra_derives,
                    extra_attrs,
                },
            inner,
            constraints,
        } = self
        else {
            unreachable!()
        };

        let mut traits = traits.clone();

        let name = name.as_deref().expect("validated type has a name");
        let description = description.as_ref().map(|desc| quote! { #[doc = #desc ]});
        let name_ident = format_ident!("{name}");

        let inner_ident = typespace.render_ident(inner);

        // A newtype wrapping `String` directly is typify's other
        // comparison-derive exception.
        // TYPIFY COMPAT: read by render_derives' exemption and by the
        // unconstrained newtype's FromStr just below.
        let wraps_string = matches!(typespace.types.get(inner), Some(Type::String));

        let vis = matches!(constraints, NewtypeConstraints::None).then(|| quote! { pub });

        let constraint_impl = self.render_constraint_impl(typespace, out, &mut traits);

        let default_impl = traits.contains(&TypespaceTrait::Default).then(|| {
            if let Some(JsonValue(default_value)) = default {
                traits.remove(TypespaceTrait::Default);
                let body = typespace.generate_default_value_for_impl(default_value, id);
                quote! {
                    impl ::std::default::Default for #name_ident {
                        fn default() -> Self {
                            #body
                        }
                    }
                }
            } else {
                Default::default()
            }
        });

        let derive_attr = typespace.render_derives(&traits, extra_derives, wraps_string);
        let attrs = typespace.render_attrs(extra_attrs);

        // A newtype struct is its inner value on the wire.
        let mut serde_attr = SerdeDerives::new(&traits).attrs();
        serde_attr.push(quote! { transparent });

        // Canonical item order: see tests/item_order.rs.
        quote! {
            #description
            #( #attrs )*
            #derive_attr
            #serde_attr
            pub struct #name_ident(#vis #inner_ident);

            impl ::std::ops::Deref for #name_ident {
                type Target = #inner_ident;
                // TODO: typespace compat
                // fn deref(&self) -> &Self::Target {
                fn deref(&self) -> & #inner_ident {
                    &self.0
                }
            }

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

            #constraint_impl
            #default_impl
        }
    }

    fn render_constraint_impl(
        &self,
        typespace: &TypespaceRenderer<'_, Id>,
        out: &mut Outputspace,
        traits: &mut crate::TypespaceTraitSet,
    ) -> TokenStream
    where
        Id: Clone + Ord + std::fmt::Debug + std::fmt::Display,
    {
        let Self {
            common: TypeCommon {
                name: Some(name), ..
            },
            inner,
            constraints,
        } = self
        else {
            unreachable!();
        };

        let name_ident = format_ident!("{name}");
        let inner_ident = typespace.render_ident(inner);

        match constraints {
            NewtypeConstraints::None => {
                // An unconstrained newtype parses and prints according to its
                // inner value.
                let from_str_impl = traits.remove(TypespaceTrait::FromStr).then(|| {
                    // TYPIFY COMPAT: a newtype directly over `String` takes
                    // the value verbatim, so its FromStr cannot fail and it
                    // gets no TryFrom impls. Every other inner type parses, so
                    // FromStr forwards to the inner type's and the two TryFrom
                    // impls forward to that.
                    let wraps_string = matches!(typespace.types.get(inner), Some(Type::String));
                    if wraps_string {
                        quote! {
                            impl ::std::str::FromStr for #name_ident {
                                type Err = ::std::convert::Infallible;
                                fn from_str(value: &str) -> ::std::result::Result<Self, Self::Err> {
                                    Ok(Self(value.to_string()))
                                }
                            }
                        }
                    } else {
                        quote! {
                            impl ::std::str::FromStr for #name_ident {
                                type Err = <#inner_ident as ::std::str::FromStr>::Err;
                                fn from_str(value: &str) -> ::std::result::Result<Self, Self::Err> {
                                    Ok(Self(value.parse()?))
                                }
                            }

                        }
                    }
                });
                let display_impl = traits.remove(TypespaceTrait::Display).then(|| {
                    quote! {
                        impl ::std::fmt::Display for #name_ident {
                            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                                self.0.fmt(f)
                            }
                        }
                    }
                });

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

                    #display_impl
                    #from_str_impl
                }
            }

            NewtypeConstraints::AllowList(values) | NewtypeConstraints::DenyList(values) => {
                let value_output = values
                    .iter()
                    .map(|value| typespace.generate_default(&value.0, inner));

                let value_string = values
                    .iter()
                    .map(|value| serde_json::to_string(&value.0).unwrap());

                let deserialize_impl = traits.remove(TypespaceTrait::Deserialize).then(|| {
                    quote! {
                        impl<'de> ::serde::Deserialize<'de> for #name_ident {
                            fn deserialize<D>(
                                deserializer: D,
                            ) -> ::std::result::Result<Self, D::Error>
                            where
                                D: ::serde::Deserializer<'de>,
                            {
                                Self::try_from(
                                    <#inner_ident>::deserialize(deserializer)?,
                                )
                                .map_err(|e| {
                                    <D::Error as ::serde::de::Error>::custom(
                                        e.to_string(),
                                    )
                                })
                            }
                        }
                    }
                });

                // As with Deserialize, serde::JsonSchema requires a custom
                // impl. If it's present in the set of derives, remove it and
                // generate something that accurately models the type.
                let json_schema_impl = traits.remove(TypespaceTrait::JsonSchema).then(|| {
                    // TODO 9/7/2026
                    // I'm really not sure why typify 1 did this `from_str` stuff
                    // when we--I think--already have serde_json::Value tokens
                    // ready to go... but we can look into that later.
                    let enum_values = quote! {
                        ::std::option::Option::Some([
                            #( ::serde_json::from_str(#value_string).unwrap(), )*
                        ].into_iter().collect())
                    };

                    let body = match constraints {
                        NewtypeConstraints::AllowList(_) => quote! {
                            schema.enum_values = #enum_values;
                        },
                        NewtypeConstraints::DenyList(_) => quote! {
                            let not = ::schemars::schema::SchemaObject {
                                enum_values: #enum_values,
                                ..::std::default::Default::default()
                            };
                            schema.subschemas().not = Some(
                                ::std::boxed::Box::new(not.into())
                            );
                        },
                        _ => unreachable!(),
                    };
                    quote! {
                        impl ::schemars::JsonSchema for #name_ident {
                            fn schema_name() -> ::std::string::String {
                                #name.to_string()
                            }

                            fn json_schema(
                                g: &mut ::schemars::r#gen::SchemaGenerator
                            ) -> ::schemars::schema::Schema {
                                let mut schema =
                                    <#inner_ident as ::schemars::JsonSchema>
                                        ::json_schema(g)
                                        .into_object();
                                #body
                                schema.into()
                            }
                        }
                    }
                });

                // TODO if the sub_type is a string we could probably impl
                // TryFrom<&str> as well and FromStr. But we don't want to for
                // non-strings where the vibe of FromStr is more "parse me".

                let from_str_impl = traits.remove(TypespaceTrait::FromStr).then(|| quote! {});
                let display_impl = traits.remove(TypespaceTrait::Display).then(|| quote! {});

                let not =
                    matches!(constraints, NewtypeConstraints::AllowList(_)).then(|| quote! { ! });
                typespace.add_error_mod(out);

                quote! {
                        // This is effectively the constructor for this type.
                        impl ::std::convert::TryFrom<#inner_ident> for #name_ident {
                            type Error = self::error::ConversionError;

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


                        #display_impl
                        #from_str_impl
                        #deserialize_impl
                        #json_schema_impl

                }
            }

            NewtypeConstraints::String { min, max, patterns } => {
                typespace.add_error_mod(out);
                let max = max.map(|v| {
                    let err = format!("longer than {} characters", v);
                    quote! {
                        if value.chars().count() > #v {
                            return Err(#err.into());
                        }
                    }
                });
                let min = min.map(|v| {
                    let err = format!("shorter than {} characters", v);
                    quote! {
                        if value.chars().count() < #v {
                            return Err(#err.into());
                        }
                    }
                });

                let pat = patterns.iter().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());
                    }
                }
            }).collect::<Vec<_>>();

                // TYPIFY 1 COMPAT: pull out a lone pat
                let pat = match &pat[..] {
                    [] => TokenStream::new(),
                    [solo] => solo.clone(),
                    many => quote! {
                        #(
                            {
                                #many
                            }
                        )*
                    },
                };

                let deserialize_impl = traits.remove(TypespaceTrait::Deserialize).then(|| {
                    quote! {
                        impl<'de> ::serde::Deserialize<'de> for #name_ident {
                            fn deserialize<D>(
                                deserializer: D,
                            ) -> ::std::result::Result<Self, D::Error>
                            where
                                D: ::serde::Deserializer<'de>,
                            {
                                ::std::convert::TryFrom::try_from(
                                    ::std::string::String::deserialize(
                                        deserializer
                                    )?
                                )
                                .map_err(|e: self::error::ConversionError| {
                                    <D::Error as ::serde::de::Error>::custom(
                                        e.to_string(),
                                    )
                                })
                            }
                        }
                    }
                });

                let from_str_impl = traits.remove(TypespaceTrait::FromStr).then(|| {
                quote! {
                    impl ::std::str::FromStr for #name_ident {
                        type Err = self::error::ConversionError;

                        fn from_str(value: &str) -> ::std::result::Result<Self, self::error::ConversionError> {
                            ::std::convert::TryFrom::try_from(value)
                        }
                    }

                }
            });
                // TYPIFY COMPAT: typify 1 writes no Display for a
                // constrained string newtype.
                let display_impl = (traits.remove(TypespaceTrait::Display)
                && !typespace.settings.typify_compat)
                .then(|| {
                    quote! {
                        impl ::std::fmt::Display for #name_ident {
                            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                                self.0.fmt(f)
                            }
                        }
                    }
                });

                quote! {
                    #display_impl
                    #from_str_impl

                    impl ::std::convert::TryFrom<&str> for #name_ident {
                        type Error = self::error::ConversionError;

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

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

                    #deserialize_impl
                }
            }
            NewtypeConstraints::Array { .. } => todo!(),
            NewtypeConstraints::JsonSchema(_json_value) => todo!(),
        }
    }
}