roas-codegen 0.1.0

Generate Rust and Go types from OpenAPI 2.0 / 3.0 / 3.1 / 3.2 descriptions
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
//! The view model for Go: every type spelled, every name final, every
//! literal quoted. A template lays this out and nothing more.
//!
//! The decisions are the Rust backend's, carried over: the four
//! nullability cases, integers read from their tokens, tagged unions
//! decoded by reading the tag and then the whole value, and open holders
//! keeping the raw JSON. What differs is only how Go spells them — and
//! that Go's decoder stores a zero value for a JSON null where Rust's
//! refuses it, which the generated code turns back into an error.

use crate::config::{Config, FieldConfig, Layout, TypeConfig};
use crate::diagnostic::{Diagnostic, SchemaId};
use crate::front::{FloatWidth, IntWidth};
use crate::generate::GenerateError;
use crate::go::naming::{
    comment_text, exported, is_exported_ident, is_tag_key, quote, tag_name_ok,
};
use crate::ir::{Additional, Ir, TypeDef, TypeKind, TypeRef};
use crate::rust::naming::Allocator;
use crate::rust::view::{constraint_notes, select_check};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};

/// The packages every generated file imports, by import path and the
/// name they are used under.
const BUILTIN_IMPORTS: &[(&str, &str)] = &[
    ("encoding/json/jsontext", "jsontext"),
    ("encoding/json/v2", "json"),
    ("errors", "errors"),
    ("fmt", "fmt"),
];

/// Lowercase names the templates declare, at package level or locally; an
/// import used under one of them would not compile.
/// The names generated validation adds, reserved only when it is on.
const VALIDATION_NAMES: &[&str] = &[
    "certain",
    "uncertain",
    "branch",
    "repeated",
    "childPointer",
    "wideNumber",
    "members",
    "seen",
    "item",
    "p",
    "x",
    "f",
    "zero",
];

/// Locals, receivers and parameters of the decoders and accessors that
/// spell a substituted type, which a type of the package's own spelled
/// the same would be shadowed by.
const SPELLING_LOCALS: &[&str] = &[
    "d", "e", "u", "v", "err", "name", "token", "value", "present",
    // A tagged union's decoder, which spells a substituted variant.
    "raw", "tag", "members", "member", "ok",
];

/// The package-level names the generated code declares besides its types.
const HELPER_NAMES: &[&str] = &[
    "decodeOptions",
    "noUnmarshalers",
    "isolatedNone",
    "refuseNull",
    "readTag",
    "integerToken",
    "matchPattern",
    "patterns",
    "memberMatches",
    "decimalToken",
    "decimalDigits",
    "childPointer",
    "wideNumber",
];

/// The names the generated code may import a package under.
const BUILTIN_NAMES: &[&str] = &[
    "jsontext", "json", "errors", "fmt", "maps", "slices", "math", "big", "strconv", "utf8",
    "regexp", "sync",
];

/// Validation's loop variables, one per nesting depth: `i0`, `item0`,
/// `k0`. A file under `layout = "file_per_type"` reads `item0.` as a use
/// of a package of that name.
fn depth_local(name: &str) -> bool {
    ["item", "i", "k"].iter().any(|prefix| {
        name.strip_prefix(prefix)
            .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
    })
}

/// The package-level names the pattern support declares, reserved only
/// when it is generated.
const PATTERN_NAMES: &[&str] = &["matchPattern", "patterns"];

/// The names the `Decimal` support declares, at package level or locally,
/// reserved only when it is generated.
const DECIMAL_NAMES: &[&str] = &[
    "decimalToken",
    "decimalDigits",
    "power",
    "all",
    "start",
    "end",
    "count",
    "leading",
    "sx",
    "sy",
    "lx",
    "ly",
    "dx",
    "dy",
    "c",
    "b",
    "shift",
    "quotient",
    "remainder",
    "prime",
    "taken",
    "m",
    "y",
    "divisor",
];

const TEMPLATE_NAMES: &[&str] = &[
    "decodeOptions",
    "noUnmarshalers",
    "isolatedNone",
    "refuseNull",
    "readTag",
    "integerToken",
    "v",
    "u",
    "d",
    "e",
    "n",
    "raw",
    "err",
    "ok",
    "zero",
    "tag",
    "typ",
    "value",
    "s",
    "token",
    "name",
    "present",
    "members",
    "member",
    "limit",
    "text",
    "negative",
    "mantissa",
    "exponent",
    "digits",
    "negativeExponent",
    "whole",
    "fraction",
    "scale",
    "ceiling",
    "magnitude",
    "digit",
    "i",
    "j",
];

#[derive(Debug, Clone, Serialize, Default)]
pub(crate) struct SupportView {
    pub nullable: bool,
    pub int64: bool,
    pub int32: bool,
    /// A `number` held exactly, under `exact_numbers`: `Decimal`.
    pub decimal: bool,
    /// `exact_numbers` is on: the support reads numbers as decimals may.
    pub exact_numbers: bool,
    pub null: bool,
    pub tagged: bool,
    /// A self-writing struct has a catch-all, written in key order.
    pub sorted_keys: bool,
    /// Types a JSON null would silently set to their zero value, which
    /// the generated decoders refuse.
    pub refuse_null: Vec<String>,
    /// Substituted types likewise, whose own decoding then runs without
    /// the generated rules, as the substitution decides the rest itself.
    pub refuse_null_isolated: Vec<String>,
    /// Substituted types that hold null themselves: decoded without the
    /// generated rules, null included.
    pub isolated: Vec<String>,
    /// Generated validation is on: the report types and `Validator`.
    pub validation: bool,
    /// A pattern is matched, by validation or at decode: `matchPattern`.
    pub patterns: bool,
    /// A struct lets in only members matching a pattern: `memberMatches`.
    pub member_patterns: bool,
}

/// `type {name} = {ty}`.
#[derive(Debug, Clone, Serialize)]
pub(crate) struct AliasView {
    pub name: String,
    pub ty: String,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct FieldView {
    pub name: String,
    pub raw_name: String,
    pub ty: String,
    /// The whole struct tag, as a Go string literal.
    pub tag: String,
    pub doc: Vec<String>,
    /// `raw_name` as a Go string literal.
    pub literal: String,
    /// The decoder refuses a `null` for this member.
    pub non_null: bool,
    /// The member's slot among the required ones, if it is required.
    pub required_index: Option<usize>,
    /// The embedded map collecting members no field names.
    pub catch_all: bool,
    /// For a member left out when absent, the Go condition under which
    /// it is written; empty when it always is.
    pub present: String,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct VariantView {
    /// The constant, for a string enum; the variant's own name, for a
    /// tagged union.
    pub name: String,
    pub value: String,
    /// `value` as a Go string literal.
    pub literal: String,
    /// The payload type, for a tagged union; empty for a string enum.
    pub ty: String,
    pub accessor: String,
    pub constructor: String,
    /// The value is made up: no tag selects the variant.
    pub synthetic: bool,
    /// Every wire value selecting the variant, as a `case` list.
    pub cases: String,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct BranchView {
    pub accessor: String,
    pub constructor: String,
    pub ty: String,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct TypeView {
    /// `struct`, `enum`, `union_tagged`, `union_open`, `composed_open`,
    /// `newtype`, `alias`.
    pub kind: &'static str,
    pub name: String,
    /// `name` as a Go string literal, for error messages.
    pub name_literal: String,
    pub raw_name: String,
    pub doc: Vec<String>,
    pub fields: Vec<FieldView>,
    pub variants: Vec<VariantView>,
    pub branches: Vec<BranchView>,
    /// Inner type of a newtype or alias.
    pub inner: String,
    /// Discriminator property of a tagged union, and as a literal.
    pub tag: String,
    /// For a tagged union, the index of the variant an unknown or missing
    /// tag is read as; `None` refuses such a value.
    pub fallback: Option<usize>,
    pub tag_literal: String,
    /// `oneOf` rather than `anyOf`, for an open union's documentation.
    pub exclusive: bool,
    /// How many of a struct's members are required.
    pub required_count: usize,
    /// The value type of a struct's catch-all map; empty when members it
    /// does not name are refused.
    pub extra_ty: String,
    /// The catch-all field's name.
    pub extra_name: String,
    /// Beside `additionalProperties: false`, the quoted patterns a member
    /// no field reads must match.
    pub member_patterns: Vec<String>,
    /// The Go spelling of each `patternProperties` schema, in order.
    #[serde(skip)]
    pub pattern_tys: Vec<Option<String>>,
    /// The Go spelling of the `additionalProperties` schema beside them.
    #[serde(skip)]
    pub others_ty: Option<String>,
    /// Package-level aliases of the member types validation decodes into
    /// that name a substitution's package or a lower-case type of the
    /// package's own: inside `validateInto` a local, such as the report
    /// `r`, may shadow either.
    pub validate_aliases: Vec<AliasView>,
    /// A member name no struct tag can carry: the struct writes itself.
    pub marshal: bool,
    /// The raw constructor of a composed holder.
    pub from_raw: String,
    /// The statements of `validateInto`, with validation on; `None` for
    /// no methods of its own (an alias).
    pub validate: Option<Vec<String>>,
    /// The statements of `validateNull`; empty for none.
    pub validate_null: Vec<String>,
    /// Under `layout = "file_per_type"`, the stem of the file the type is
    /// written to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub(crate) struct FileView {
    /// The contract version this context follows.
    pub template_api: u32,
    pub source: String,
    pub header: String,
    pub package: String,
    /// Import specs, each a quoted path.
    pub imports: Vec<String>,
    pub extra_imports: Vec<String>,
    pub support: SupportView,
    pub types: Vec<TypeView>,
}

/// A Go module the generated code imports from, beyond the standard
/// library.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub struct GoDependency {
    /// The import path, as the substitution gives it.
    pub import: String,
}

impl GoDependency {
    pub fn new(import: impl Into<String>) -> Self {
        GoDependency {
            import: import.into(),
        }
    }
}

pub(crate) struct Built {
    pub file: FileView,
    /// For each of `file.imports`, the names a file using it qualifies
    /// with: what decides, under `layout = "file_per_type"`, which files
    /// import it.
    pub import_names: Vec<BTreeSet<String>>,
    pub dependencies: Vec<GoDependency>,
    pub diagnostics: Vec<Diagnostic>,
}

struct Builder<'a> {
    /// Imports the validation checks need.
    needs: super::validation::Needs,
    ir: &'a Ir,
    config: &'a Config,
    names: BTreeMap<SchemaId, String>,
    /// Package scope: types, constants and constructor functions.
    package_names: Allocator,
    suppressed: BTreeSet<SchemaId>,
    support: SupportView,
    refuse_null: BTreeSet<String>,
    refuse_null_isolated: BTreeSet<String>,
    isolated: BTreeSet<String>,
    externs: BTreeSet<String>,
    /// The substitution spellings the schema uses.
    spellings: BTreeSet<String>,
    /// For each substitution import, the qualifiers its spellings use.
    extern_names: BTreeMap<String, BTreeSet<String>>,
    diagnostics: Vec<Diagnostic>,
}

/// The package name an import path is used under, as far as the path
/// says: its last element, skipping a `/vN` major-version suffix.
pub(crate) fn package_of(import: &str) -> &str {
    let mut elements = import.rsplit('/');
    let last = elements.next().unwrap_or(import);
    let major =
        last.len() > 1 && last.starts_with('v') && last[1..].bytes().all(|b| b.is_ascii_digit());
    match elements.next() {
        Some(previous) if major => previous,
        _ => last,
    }
}

pub(crate) fn build(ir: &Ir, config: &Config, source: &str) -> Result<Built, GenerateError> {
    let mut builder = Builder {
        needs: Default::default(),
        ir,
        config,
        names: BTreeMap::new(),
        package_names: Allocator::default(),
        suppressed: ir.suppressed.clone(),
        support: SupportView {
            exact_numbers: config.exact_numbers,
            ..SupportView::default()
        },
        refuse_null: BTreeSet::new(),
        refuse_null_isolated: BTreeSet::new(),
        isolated: BTreeSet::new(),
        externs: BTreeSet::new(),
        spellings: BTreeSet::new(),
        extern_names: BTreeMap::new(),
        diagnostics: Vec::new(),
    };
    select_check(ir, config)?;
    builder.allocate_type_names()?;
    let mut types = Vec::new();
    for id in &ir.order {
        if builder.suppressed.contains(id) {
            continue;
        }
        if let Some(view) = builder.type_view(&ir.types[id])? {
            types.push(view);
        }
    }
    builder.support.refuse_null = builder.refuse_null.iter().cloned().collect();
    // A substitution spelled like a generated type (`string`, say) is
    // refused like that type; the first registered function would win.
    builder.support.refuse_null_isolated = builder
        .refuse_null_isolated
        .difference(&builder.refuse_null)
        .cloned()
        .collect();
    builder.support.isolated = builder.isolated.iter().cloned().collect();
    if config.layout == Layout::FilePerType {
        assign_files(&mut types, config);
    }
    let mut imports = Vec::new();
    let mut import_names = Vec::new();
    let mut dependencies = Vec::new();
    if !types.is_empty() {
        let mut builtin = BUILTIN_IMPORTS.to_vec();
        if builder.support.sorted_keys || builder.needs.sorted {
            builtin.extend([("maps", "maps"), ("slices", "slices")]);
        } else if builder.needs.slices {
            builtin.push(("slices", "slices"));
        }
        if builder.needs.math {
            builtin.push(("math", "math"));
        }
        if builder.support.decimal {
            builtin.extend([("math/big", "big"), ("strconv", "strconv")]);
        }
        if builder.needs.utf8 {
            builtin.push(("unicode/utf8", "utf8"));
        }
        if builder.needs.pattern {
            builtin.extend([("regexp", "regexp"), ("sync", "sync")]);
            builder.support.patterns = true;
        }
        imports.extend(builtin.iter().map(|(path, _)| quote(path)));
        import_names.extend(
            builtin
                .iter()
                .map(|(_, name)| BTreeSet::from([(*name).to_owned()])),
        );
        // Under `file_per_type` each substitution import goes to the files
        // using it, so its name must be certain: the one package its
        // spellings name that no builtin or extra import is used under.
        // One an extra import already brings in needs no import here.
        let file_per_type = config.layout == Layout::FilePerType;
        let extra_names: BTreeSet<String> = config
            .extra_imports
            .iter()
            .filter_map(|spec| match super::imports::spec_name(spec) {
                super::imports::SpecName::Named(name) => Some(name),
                _ => None,
            })
            .collect();
        // A substitution import an extra import brings in under the name
        // its spellings use: the extra import serves.
        let extra_paths: BTreeMap<&str, String> = config
            .extra_imports
            .iter()
            .filter_map(|spec| match super::imports::spec_name(spec) {
                super::imports::SpecName::Named(name) => {
                    Some((super::imports::spec_path(spec), name))
                }
                _ => None,
            })
            .collect();
        let served = |import: &String| {
            extra_paths.get(import.as_str()).is_some_and(|name| {
                builder
                    .extern_names
                    .get(import)
                    .is_some_and(|names| names.contains(name))
            })
        };
        let mut certain: BTreeMap<&String, String> = BTreeMap::new();
        if file_per_type {
            for import in &builder.externs {
                if builtin.iter().any(|(path, _)| path == import) || served(import) {
                    continue;
                }
                let candidates: Vec<&String> = builder
                    .extern_names
                    .get(import)
                    .into_iter()
                    .flatten()
                    .filter(|q| !builtin.iter().any(|(_, b)| b == q) && !extra_names.contains(*q))
                    .collect();
                let [name] = candidates.as_slice() else {
                    return Err(GenerateError::Config(format!(
                        "substitution import {import:?} is not the one package its spellings name beside the builtin and extra imports (they name {candidates:?}); under `layout = \"file_per_type\"` import the others through `extra_imports` with their names"
                    )));
                };
                certain.insert(import, (*name).clone());
            }
        }
        let mut used: BTreeMap<&str, &str> =
            builtin.iter().map(|(path, name)| (*name, *path)).collect();
        // A package named like a name the generated code declares would be
        // shadowed by it, or clash with it.
        for local in TEMPLATE_NAMES {
            used.insert(local, "a name the generated code declares");
        }
        if builder.needs.pattern {
            for local in PATTERN_NAMES {
                used.insert(local, "a name the generated code declares");
            }
            // Locals of `matchPattern`, in the package file.
            if config.layout == Layout::FilePerType {
                for local in ["re", "c"] {
                    used.insert(local, "a name the generated code declares");
                }
            }
        }
        if builder.support.member_patterns {
            used.insert("memberMatches", "a name the generated code declares");
        }
        if builder.support.decimal {
            for local in DECIMAL_NAMES {
                used.insert(local, "a name the generated code declares");
            }
        }
        if config.validation {
            for local in VALIDATION_NAMES {
                used.insert(local, "a name the generated validation declares");
            }
        }
        let aliases: BTreeSet<&str> = types
            .iter()
            .flat_map(|t| &t.validate_aliases)
            .map(|alias| alias.name.as_str())
            .collect();
        // A substitution spelled like an alias would name the alias, or
        // the alias be declared as itself.
        let spellings = config
            .substitutions
            .values()
            .filter_map(|s| s.go.as_ref())
            .map(|go| go.name.as_str());
        for spelling in spellings {
            // Unqualified, or a package qualifier: an import path need
            // not say the package's name.
            let qualifiers = super::imports::qualifiers(spelling);
            let unqualified = unqualified_names(spelling);
            if let Some(name) = unqualified
                .iter()
                .chain(&qualifiers)
                .find(|name| aliases.contains(name.as_str()))
            {
                return Err(GenerateError::Config(format!(
                    "substitution spelling {spelling:?} names `{name}`, which the generated validation declares"
                )));
            }
        }
        for alias in &aliases {
            used.insert(alias, "a name the generated validation declares");
        }
        // The `Decimal` methods' receiver, in the package file.
        if builder.support.decimal && config.layout == Layout::FilePerType {
            used.insert("x", "a name the generated code declares");
        }
        // A file whose only `r.` is validation's report would import a
        // package named `r`, which goes by its uses under `file_per_type`.
        if config.validation && config.layout == Layout::FilePerType {
            used.insert("r", "a name the generated validation declares");
        }
        for import in &builder.externs {
            if builtin.iter().any(|(path, _)| path == import) {
                continue;
            }
            // The standard library is no dependency to declare; a module
            // path has a dot in its first element.
            if import
                .split('/')
                .next()
                .is_some_and(|first| first.contains('.'))
            {
                dependencies.push(GoDependency::new(import.clone()));
            }
            if file_per_type && served(import) {
                continue;
            }
            let name = match certain.get(import) {
                Some(name) => name.as_str(),
                None => package_of(import),
            };
            // Under `file_per_type` the import goes to the files using its
            // name, so it may not be a local the generated code declares.
            let local = (file_per_type
                && ((config.validation && depth_local(name))
                    || used
                        .get(name)
                        .is_some_and(|what| what.starts_with("a name "))))
            .then_some(name);
            if let Some(q) = local {
                return Err(GenerateError::Config(format!(
                    "substitution import {import:?} is used as `{q}`, a name the generated code declares, which `layout = \"file_per_type\"` would read as its use; import it under another name"
                )));
            }
            if let Some(path) = used.insert(name, import) {
                return Err(GenerateError::Config(format!(
                    "substitution import {import:?} is used as `{name}`, which the generated code already imports as {path:?}"
                )));
            }
            imports.push(quote(import));
            let names = BTreeSet::from([name.to_owned()]);
            import_names.push(names);
        }
        // A type of the package's own spelled like a local of the code
        // spelling it is shadowed by that local, and one spelled like a
        // package-level name or an import clashes with it. Helpers and
        // builtin imports are refused even where this run has none, so a
        // config keeps working as the description grows.
        for spelling in &builder.spellings {
            let taken = type_names(spelling).into_iter().find_map(|name| {
                let what = if SPELLING_LOCALS.contains(&name.as_str()) {
                    "a local of the generated decoders, which would shadow it".to_owned()
                } else if HELPER_NAMES.contains(&name.as_str()) {
                    "a name the generated code may declare".to_owned()
                } else if BUILTIN_NAMES.contains(&name.as_str()) {
                    "the name the generated code may import a package under".to_owned()
                } else {
                    let path = used
                        .get(name.as_str())
                        .filter(|what| !what.starts_with("a name "))?;
                    format!("the name the generated code imports {path:?} under")
                };
                Some((name, what))
            });
            if let Some((name, what)) = taken {
                return Err(GenerateError::Config(format!(
                    "substitution spelling {spelling:?} names `{name}`, {what}; rename the type, or spell it through a package"
                )));
            }
        }
        // Under `file_per_type` an extra import goes to the files naming it,
        // and a name the generated code also declares, or imports, would
        // send it to files that only use that.
        if config.layout == Layout::FilePerType {
            for spec in &config.extra_imports {
                let name = match super::imports::spec_name(spec) {
                    super::imports::SpecName::Named(name) => name,
                    super::imports::SpecName::Unnamed => continue,
                    super::imports::SpecName::Uncertain => {
                        return Err(GenerateError::Config(format!(
                            "`extra_imports` entry {spec:?} does not say the name its package is used under, which `layout = \"file_per_type\"` places it by; give it one, such as `name \"path\"`"
                        )));
                    }
                };
                let what = if config.validation && depth_local(&name) {
                    Some("validation's loop variables")
                } else {
                    used.get(name.as_str()).copied()
                };
                if let Some(what) = what {
                    return Err(GenerateError::Config(format!(
                        "`extra_imports` entry {spec:?} is used as `{name}`, which is taken by {what}; under `layout = \"file_per_type\"` give it another name"
                    )));
                }
            }
        }
    }
    Ok(Built {
        file: FileView {
            template_api: crate::templates::TEMPLATE_API,
            source: comment_text(source),
            header: config.header.clone().unwrap_or_default(),
            package: config.go.package.clone(),
            imports,
            extra_imports: config.extra_imports.clone(),
            support: builder.support,
            types,
        },
        import_names,
        dependencies,
        diagnostics: builder.diagnostics,
    })
}

/// Names the file of every type under `layout = "file_per_type"`: its
/// name in snake case, never the package file's, one `go build` would
/// constrain, or one a file system resolves elsewhere.
fn assign_files(types: &mut [TypeView], config: &Config) {
    let mut taken = BTreeSet::from([config.go.file.clone()]);
    for t in types {
        let base = crate::write::capped_stem(super::naming::go_file_name(
            &crate::rust::naming::snake(std::slice::from_ref(&t.name)),
        ));
        let file = (1u32..)
            .map(|i| {
                if i == 1 {
                    base.clone()
                } else {
                    format!("{base}{i}")
                }
            })
            .find(|candidate| !taken.contains(candidate) && super::naming::is_file_stem(candidate))
            .expect("a free file name");
        taken.insert(file.clone());
        t.file = Some(file);
    }
}

/// The names a Go type spelling uses unqualified: neither a package
/// qualifier nor a selector after one, nor inside a literal (a tag).
fn unqualified_names(ty: &str) -> Vec<String> {
    scan_names(ty, false)
}

/// The unqualified names a Go type spelling uses as types: also not a
/// field, parameter or method name.
fn type_names(ty: &str) -> Vec<String> {
    scan_names(ty, true)
}

/// A token of a Go type spelling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Token<'a> {
    Ident(&'a str),
    /// A string, rune or number.
    Literal,
    /// An explicit `;`, or one Go reads into a line break.
    Semicolon,
    Punct(&'a str),
}

/// The tokens of a Go type spelling, with the semicolons Go inserts at
/// line breaks; comments are blanks, or line breaks when they hold one.
fn tokens(ty: &str) -> Vec<Token<'_>> {
    fn ends_line(last: Option<&Token<'_>>) -> bool {
        match last {
            Some(Token::Ident(word)) => {
                !super::naming::is_keyword(word)
                    || matches!(*word, "break" | "continue" | "fallthrough" | "return")
            }
            Some(Token::Literal) => true,
            Some(Token::Punct(p)) => matches!(*p, ")" | "]" | "}"),
            _ => false,
        }
    }
    let ident = |c: char| c.is_alphanumeric() || c == '_';
    let mut out = Vec::new();
    let mut rest = ty;
    while let Some(c) = rest.chars().next() {
        let len = if c == '\n' {
            if ends_line(out.last()) {
                out.push(Token::Semicolon);
            }
            1
        } else if c.is_whitespace() {
            c.len_utf8()
        } else if rest.starts_with("//") {
            rest.find('\n').unwrap_or(rest.len())
        } else if let Some(body) = rest.strip_prefix("/*") {
            let len = body.find("*/").map_or(rest.len(), |end| end + 4);
            if rest[..len].contains('\n') && ends_line(out.last()) {
                out.push(Token::Semicolon);
            }
            len
        } else if c.is_alphabetic() || c == '_' {
            let len = rest.find(|c: char| !ident(c)).unwrap_or(rest.len());
            out.push(Token::Ident(&rest[..len]));
            len
        } else if c.is_ascii_digit()
            || (c == '.' && rest[1..].starts_with(|c: char| c.is_ascii_digit()))
        {
            // `e` is a hex digit: only `p` gives a hex literal's exponent.
            let hex = rest.starts_with("0x") || rest.starts_with("0X");
            let mut len = 0;
            let mut prev = ' ';
            for c in rest.chars() {
                let exponent = if hex {
                    matches!(prev, 'p' | 'P')
                } else {
                    matches!(prev, 'e' | 'E')
                };
                let exponent_sign = matches!(c, '+' | '-') && exponent;
                if !(ident(c) || c == '.' || exponent_sign) {
                    break;
                }
                len += c.len_utf8();
                prev = c;
            }
            out.push(Token::Literal);
            len
        } else if matches!(c, '"' | '\'' | '`') {
            let mut escaped = false;
            let close = rest[1..].char_indices().find(|&(_, inner)| {
                let closes = inner == c && !escaped;
                escaped = c != '`' && inner == '\\' && !escaped;
                closes
            });
            out.push(Token::Literal);
            close.map_or(rest.len(), |(at, _)| at + 2)
        } else if rest.starts_with("...") || rest.starts_with("<-") {
            let len = if rest.starts_with("...") { 3 } else { 2 };
            out.push(Token::Punct(&rest[..len]));
            len
        } else if c == ';' {
            out.push(Token::Semicolon);
            1
        } else {
            out.push(Token::Punct(&rest[..c.len_utf8()]));
            c.len_utf8()
        };
        rest = &rest[len..];
    }
    out
}

fn scan_names(ty: &str, types_only: bool) -> Vec<String> {
    let tokens = tokens(ty);
    let at = |k: usize| tokens.get(k).copied();
    // Where a type can begin, after a name: `x T`, `x *T`, `x []T`,
    // `x ...T`, `x <-chan T`, `x (T)`.
    let type_starts = |k: usize| {
        matches!(
            at(k),
            Some(Token::Ident(_) | Token::Punct("*" | "[" | "(" | "..." | "<-"))
        )
    };
    // The token after a bracketed `[…]` opening at `k`.
    let after_brackets = |k: usize| {
        let mut depth = 0usize;
        for (j, token) in tokens.iter().enumerate().skip(k) {
            match token {
                Token::Punct("[") => depth += 1,
                Token::Punct("]") => {
                    depth -= 1;
                    if depth == 0 {
                        return j + 1;
                    }
                }
                _ => {}
            }
        }
        tokens.len()
    };
    // A type follows at `k`; `List[T]` instantiates, `x [N]T` declares.
    let type_follows = |k: usize| match at(k) {
        Some(Token::Punct("[")) => type_starts(after_brackets(k)),
        _ => type_starts(k),
    };
    // A field, parameter or method name at `k`: `x T`, `x, y T`, `x()`.
    let named = |k: usize| {
        let entry = k > 0
            && matches!(
                at(k - 1),
                Some(Token::Punct("(" | "," | "{") | Token::Semicolon)
            );
        if !entry {
            return false;
        }
        let mut j = k + 1;
        if at(j) == Some(Token::Punct("(")) {
            return true;
        }
        // `a, b, c T`; `a, chan T` lists types, `chan` being no name.
        while at(j) == Some(Token::Punct(",")) {
            match at(j + 1) {
                Some(Token::Ident(word)) if !super::naming::is_keyword(word) => j += 2,
                _ => return false,
            }
        }
        type_follows(j)
    };
    let mut out = Vec::new();
    for (k, token) in tokens.iter().enumerate() {
        let Token::Ident(word) = *token else {
            continue;
        };
        let selector = k > 0 && at(k - 1) == Some(Token::Punct("."));
        let qualifier = at(k + 1) == Some(Token::Punct("."));
        if selector || qualifier {
            continue;
        }
        if types_only && !super::naming::is_keyword(word) && named(k) {
            continue;
        }
        out.push(word.to_owned());
    }
    out
}

/// Whether a Go type spelling names an unqualified, unexported type that
/// Go does not predeclare: one a local may shadow.
fn names_unexported_type(ty: &str) -> bool {
    const PREDECLARED: &[&str] = &[
        "any",
        "bool",
        "byte",
        "comparable",
        "complex64",
        "complex128",
        "error",
        "float32",
        "float64",
        "int",
        "int8",
        "int16",
        "int32",
        "int64",
        "rune",
        "string",
        "uint",
        "uint8",
        "uint16",
        "uint32",
        "uint64",
        "uintptr",
    ];
    unqualified_names(ty).iter().any(|word| {
        !word.starts_with(|c: char| c.is_uppercase())
            && !PREDECLARED.contains(&word.as_str())
            && !super::naming::is_keyword(word)
    })
}

impl Builder<'_> {
    /// The spelling validation decodes a member of `view` into: `ty`
    /// itself, or, when it names a substitution's package or a type of
    /// the package's own spelled in lower case, an alias
    /// `{prefix}{view.name}` declared at package level, where no local of
    /// `validateInto` shadows that name.
    fn member_ty(&self, view: &mut TypeView, prefix: String, ty: String) -> String {
        let substituted = super::imports::qualifiers(&ty)
            .iter()
            .any(|q| !BUILTIN_IMPORTS.iter().any(|(_, name)| name == q))
            || names_unexported_type(&ty);
        if !self.config.validation || !substituted {
            return ty;
        }
        let name = format!("{prefix}{}", view.name);
        view.validate_aliases.push(AliasView {
            name: name.clone(),
            ty,
        });
        name
    }

    fn allocate_type_names(&mut self) -> Result<(), GenerateError> {
        // The helpers every file may declare.
        for reserved in ["Nullable", "Int64", "Int32", "Null"] {
            self.package_names.reserve(reserved);
        }
        if self.config.exact_numbers {
            for reserved in ["Decimal", "DecimalMaxDigits", "ParseDecimal"] {
                self.package_names.reserve(reserved);
            }
        }
        if self.config.validation {
            for reserved in [
                "ValidationReport",
                "Finding",
                "FindingKind",
                "Violation",
                "Unevaluated",
                "Validator",
            ] {
                self.package_names.reserve(reserved);
            }
        }
        // Components first: a component keeps its name whatever an inline
        // schema is titled or positioned to be called.
        let ir = self.ir;
        let order = ir
            .order
            .iter()
            .filter(|id| ir.types[*id].component.is_some());
        let rest = ir
            .order
            .iter()
            .filter(|id| ir.types[*id].component.is_none());
        for id in order.chain(rest) {
            let def = &self.ir.types[id];
            if matches!(def.kind, TypeKind::Extern) || self.suppressed.contains(id) {
                continue;
            }
            let base = match self.type_config(def).and_then(|t| t.rename.clone()) {
                Some(rename) => {
                    if !is_exported_ident(&rename) {
                        return Err(GenerateError::Config(format!(
                            "`types.{}.rename = {rename:?}` must be an exported Go identifier: an ASCII capital, then letters, digits or `_`",
                            def.component.as_deref().unwrap_or_default()
                        )));
                    }
                    rename
                }
                None => exported(&def.suggested_name),
            };
            let name = self.package_names.allocate(base);
            self.names.insert(id.clone(), name);
        }
        Ok(())
    }

    fn type_config(&self, def: &TypeDef) -> Option<&TypeConfig> {
        def.component
            .as_ref()
            .and_then(|c| self.config.types.get(c))
    }

    fn field_config<'c>(&'c self, def: &TypeDef, raw_name: &str) -> Option<&'c FieldConfig> {
        self.type_config(def).and_then(|t| t.fields.get(raw_name))
    }

    /// Spell a type for Go.
    fn spell(&mut self, ty: &TypeRef) -> Result<String, GenerateError> {
        let spelled = match ty {
            TypeRef::Named(id) => {
                let def = &self.ir.types[id];
                if let TypeKind::Extern = def.kind {
                    let component = def.component.clone().unwrap_or_default();
                    let spelled = self.extern_spelling(&component)?;
                    self.refused_extern(&spelled)
                } else {
                    self.names[id].clone()
                }
            }
            // Go needs a pointer where a value would contain itself.
            TypeRef::Boxed(inner) => format!("*{}", self.spell(inner)?),
            TypeRef::Nullable(inner) => format!("*{}", self.spell(unboxed(inner))?),
            TypeRef::String => self.refused("string"),
            TypeRef::Integer(IntWidth::Int64) => {
                self.support.int64 = true;
                "Int64".into()
            }
            TypeRef::Integer(IntWidth::Int32) => {
                self.support.int32 = true;
                "Int32".into()
            }
            TypeRef::Number(FloatWidth::Double) => self.refused("float64"),
            TypeRef::Number(FloatWidth::Float) => self.refused("float32"),
            // Its own decoder refuses null.
            TypeRef::Decimal => {
                self.support.decimal = true;
                "Decimal".into()
            }
            TypeRef::Boolean => self.refused("bool"),
            TypeRef::Null => {
                self.support.null = true;
                "Null".into()
            }
            TypeRef::Any => "jsontext.Value".into(),
            TypeRef::Array(inner) => {
                let spelled = format!("[]{}", self.spell(unboxed(inner))?);
                self.refused(&spelled)
            }
            TypeRef::Map(inner) => {
                let spelled = format!("map[string]{}", self.spell(unboxed(inner))?);
                self.refused(&spelled)
            }
            TypeRef::Extern(key) => {
                let spelled = self.extern_spelling(key)?;
                self.refused_extern(&spelled)
            }
        };
        Ok(spelled)
    }

    /// A type that stores its zero value for a JSON null, so the
    /// generated decoders refuse null for it explicitly.
    /// A substituted type, refused null like any other — unless it is
    /// spelled like a type the generator itself holds null in: a pointer,
    /// `jsontext.Value`, or an interface. The refusal is per Go type, so it
    /// would reach those positions too; such a substitution decides about
    /// null itself, as its Rust spelling does.
    fn refused_extern(&mut self, spelled: &str) -> String {
        if !null_holding_spelling(spelled) {
            self.refuse_null_isolated.insert(spelled.to_owned());
        } else if spelled != "jsontext.Value" {
            // Raw JSON has nothing inside to reach.
            self.isolated.insert(spelled.to_owned());
        }
        spelled.to_owned()
    }

    fn refused(&mut self, spelled: &str) -> String {
        self.refuse_null.insert(spelled.to_owned());
        spelled.to_owned()
    }

    fn extern_spelling(&mut self, key: &str) -> Result<String, GenerateError> {
        let spelling = self
            .config
            .substitutions
            .get(key)
            .and_then(|s| s.go.as_ref())
            .ok_or_else(|| {
                GenerateError::Config(format!("substitution `{key}` has no `go` spelling"))
            })?;
        if let Some(import) = &spelling.import {
            self.externs.insert(import.clone());
            self.extern_names
                .entry(import.clone())
                .or_default()
                .extend(super::imports::qualifiers(&spelling.name));
        }
        self.spellings.insert(spelling.name.clone());
        Ok(spelling.name.clone())
    }

    fn doc(
        description: Option<&str>,
        default: Option<&serde_json::Value>,
        read_only: bool,
        write_only: bool,
        constraints: &crate::front::Constraints,
        deprecated: bool,
    ) -> Vec<String> {
        let mut lines: Vec<String> = description
            .map(|d| d.lines().map(|l| l.trim_end().to_owned()).collect())
            .unwrap_or_default();
        let mut notes = Vec::new();
        if let Some(default) = default {
            notes.push(format!("Default: `{default}`."));
        }
        if read_only {
            notes.push("Read only.".to_owned());
        }
        if write_only {
            notes.push("Write only.".to_owned());
        }
        notes.extend(constraint_notes(constraints));
        for paragraph in [notes, deprecation(deprecated)] {
            if !paragraph.is_empty() {
                if !lines.is_empty() {
                    lines.push(String::new());
                }
                lines.extend(paragraph);
            }
        }
        lines
            .into_iter()
            .flat_map(|l| l.split(['\n', '\r']).map(comment_text).collect::<Vec<_>>())
            .collect()
    }

    fn type_view(&mut self, def: &TypeDef) -> Result<Option<TypeView>, GenerateError> {
        let Some(name) = self.names.get(&def.id).cloned() else {
            return Ok(None);
        };
        let raw_name = def
            .component
            .clone()
            .unwrap_or_else(|| def.id.pointer.clone());
        let mut doc = Vec::new();
        if let Some(title) = def
            .title
            .as_deref()
            .filter(|t| !t.trim().is_empty() && def.component.as_deref() != Some(t))
        {
            doc.extend(title.trim().lines().map(|l| comment_text(l.trim_end())));
            doc.push(String::new());
        }
        doc.extend(Self::doc(
            def.description.as_deref(),
            None,
            false,
            false,
            &def.constraints,
            false,
        ));
        if def.nullable {
            doc.push(
                "`null` is a valid instance; a position holding this type is a pointer or a `Nullable`."
                    .to_owned(),
            );
        }
        while doc.last().is_some_and(String::is_empty) {
            doc.pop();
        }
        let deprecated = deprecation(def.deprecated);
        if !deprecated.is_empty() {
            if !doc.is_empty() {
                doc.push(String::new());
            }
            doc.extend(deprecated);
        }
        let mut view = TypeView {
            kind: "struct",
            name_literal: quote(&name),
            name,
            raw_name,
            doc,
            fields: Vec::new(),
            variants: Vec::new(),
            branches: Vec::new(),
            inner: String::new(),
            tag: String::new(),
            fallback: None,
            tag_literal: String::new(),
            exclusive: false,
            required_count: 0,
            extra_ty: String::new(),
            extra_name: String::new(),
            member_patterns: Vec::new(),
            pattern_tys: Vec::new(),
            others_ty: None,
            validate_aliases: Vec::new(),
            marshal: false,
            from_raw: String::new(),
            validate: None,
            validate_null: Vec::new(),
            file: None,
        };
        if !self.fill_kind(def, &mut view)? {
            return Ok(None);
        }
        if self.config.validation {
            self.support.validation = true;
            // The validation support's number scan uses `math`.
            self.needs.math = true;
            let opted_out = self.type_config(def).and_then(|t| t.validation) == Some(false);
            let validates = |ty: &TypeRef| self.validates(ty);
            let nil_able = |ty: &TypeRef| match ty {
                TypeRef::Named(id) => matches!(
                    self.alias_target(id),
                    Some(TypeRef::Boxed(_) | TypeRef::Nullable(_))
                ),
                _ => false,
            };
            let names = &self.names;
            let ir = self.ir;
            // Through aliases, as `holds_null` sees them.
            let raw_holder = |ty: &TypeRef| {
                let mut id = ty.direct_named()?;
                for _ in 0..=ir.types.len() {
                    match &ir.types.get(id)?.kind {
                        // A JSON-value wrapper holds `null` itself.
                        TypeKind::Newtype(TypeRef::Any) => {
                            let name = names.get(id)?;
                            return Some(format!("{name}(jsontext.Value(\"null\"))"));
                        }
                        TypeKind::UnionOpen(_) | TypeKind::ComposedOpen(_) => {
                            let name = names.get(id)?;
                            return Some(format!("{name}{{raw: jsontext.Value(\"null\")}}"));
                        }
                        TypeKind::Alias(inner) | TypeKind::Newtype(inner) => {
                            id = inner.direct_named()?
                        }
                        _ => return None,
                    }
                }
                None
            };
            let holder_id = def.id.clone();
            let loops = |ty: &TypeRef| crate::checks::loops_back(ir, &holder_id, ty);
            // Through aliases, which share their target's methods.
            let null_name = |ty: &TypeRef| {
                let mut id = ty.direct_named()?;
                for _ in 0..=ir.types.len() {
                    let def = ir.types.get(id)?;
                    match &def.kind {
                        TypeKind::Alias(inner) => id = inner.direct_named()?,
                        // An opted-out type has no `validateNull`.
                        _ if !crate::checks::has_null_hook(def)
                            || self.type_config(def).and_then(|t| t.validation) == Some(false) =>
                        {
                            return None;
                        }
                        _ => return names.get(&def.id).cloned(),
                    }
                }
                None
            };
            let mut cx = super::validation::Context {
                validates: &validates,
                nil_able: &nil_able,
                raw_holder: &raw_holder,
                loops: &loops,
                null_name: &null_name,
                // A newtype over a substitution is an alias in Go, with no
                // validator of its own.
                extern_checks: &|ty: &TypeRef| {
                    crate::checks::extern_checks(ir, ty, !self.validates(ty))
                },
                ir,
                needs: self.needs,
            };
            view.validate = super::validation::body(def, &view, opted_out, &mut cx);
            if view.validate.is_some() && !opted_out {
                view.validate_null = super::validation::null_body(def, &view.name, &mut cx);
            }
            if opted_out && view.validate.is_none() {
                return Err(opt_out_on_alias(def));
            }
            self.needs = cx.needs;
        }
        Ok(Some(view))
    }

    /// Fill the kind-specific parts of a view; `false` when the type is
    /// not emitted at all.
    fn fill_kind(&mut self, def: &TypeDef, view: &mut TypeView) -> Result<bool, GenerateError> {
        match &def.kind {
            TypeKind::Extern => return Ok(false),
            TypeKind::Struct(s) => {
                view.kind = "struct";
                let mut fields = Allocator::default();
                // The methods a generated struct has.
                fields.reserve("UnmarshalJSONFrom");
                if self.config.validation {
                    fields.reserve("Validate");
                }
                fields.reserve("MarshalJSONTo");
                let mut required_count = 0;
                for field in &s.fields {
                    let config = self.field_config(def, &field.raw_name);
                    let rename = config.and_then(|f| f.rename.clone());
                    let go_tags = config.map(|f| f.go_tags.clone()).unwrap_or_default();
                    let at = format!("types.{}.fields.{}", view.raw_name, field.raw_name);
                    let base = match rename {
                        Some(rename) if !is_exported_ident(&rename) => {
                            return Err(GenerateError::Config(format!(
                                "`{at}.rename = {rename:?}` must be an exported Go identifier: an ASCII capital, then letters, digits or `_`"
                            )));
                        }
                        Some(rename) => rename,
                        None => exported(std::slice::from_ref(&field.raw_name)),
                    };
                    let name = fields.allocate(base);
                    // A type that holds `null` as a value — `{}`, `type: null`,
                    // an open holder, or a reference to one — reads it as
                    // that value, as in Rust; an optional one keeps it apart
                    // from absence, so its member is nullable in Go's terms.
                    let holds_null = self.holds_null(&field.ty);
                    let (ty, omitzero) = match (field.required, field.nullable || holds_null) {
                        (true, false) => (self.spell(&field.ty)?, false),
                        (true, true) => {
                            self.support.nullable = true;
                            (
                                format!("Nullable[{}]", self.spell(unboxed(&field.ty))?),
                                false,
                            )
                        }
                        // `omitzero` asks a pointer's pointee `IsZero` when it
                        // has one — `time.Time` does — so a present zero value
                        // would be dropped; `Nullable` asks only for absence.
                        (false, false) if self.substituted(&field.ty) => {
                            self.support.nullable = true;
                            (
                                format!("Nullable[{}]", self.spell(unboxed(&field.ty))?),
                                true,
                            )
                        }
                        (false, false) => {
                            let inner = self.spell(&field.ty)?;
                            if inner.starts_with('*') {
                                (inner, true)
                            } else {
                                (format!("*{inner}"), true)
                            }
                        }
                        (false, true) => {
                            self.support.nullable = true;
                            (
                                format!("Nullable[{}]", self.spell(unboxed(&field.ty))?),
                                true,
                            )
                        }
                    };
                    let required_index = field.required.then(|| {
                        required_count += 1;
                        required_count - 1
                    });
                    let tag = struct_tag(&field.raw_name, omitzero, &go_tags, &at)?;
                    if !tag_name_ok(&field.raw_name) {
                        view.marshal = true;
                        self.support.sorted_keys |= matches!(s.additional, Additional::CatchAll(_));
                    }
                    let present = match (omitzero, ty.starts_with("Nullable[")) {
                        (false, _) => String::new(),
                        (true, true) => format!("v.{name}.Set"),
                        (true, false) => format!("v.{name} != nil"),
                    };
                    view.fields.push(FieldView {
                        present,
                        name,
                        raw_name: field.raw_name.clone(),
                        ty,
                        tag,
                        literal: quote(&field.raw_name),
                        non_null: !field.nullable && !holds_null,
                        required_index,
                        catch_all: false,
                        doc: Self::doc(
                            field.description.as_deref(),
                            field.default.as_ref(),
                            field.read_only,
                            field.write_only,
                            &field.constraints,
                            field.deprecated,
                        ),
                    });
                }
                view.required_count = required_count;
                if let Some(patterns) = &s.only_patterns {
                    self.needs.pattern = true;
                    self.support.member_patterns = true;
                    view.member_patterns = patterns.iter().map(|p| quote(p)).collect();
                }
                for (i, pattern) in s.patterns.iter().enumerate() {
                    let spelled = match pattern.branch() {
                        Some(b) => {
                            let ty = self.spell(unboxed(&b.ty))?;
                            Some(self.member_ty(view, format!("pattern{i}Of"), ty))
                        }
                        None => None,
                    };
                    view.pattern_tys.push(spelled);
                }
                if let crate::ir::Others::Schema(b) = &s.others {
                    let ty = self.spell(unboxed(&b.ty))?;
                    view.others_ty = Some(self.member_ty(view, "othersOf".to_owned(), ty));
                }
                if let Additional::CatchAll(ty) = &s.additional {
                    let inner = self.spell(unboxed(ty))?;
                    let name = fields.allocate("AdditionalProperties".to_owned());
                    view.extra_name = name.clone();
                    view.extra_ty = inner.clone();
                    view.fields.push(FieldView {
                        name,
                        raw_name: "additionalProperties".to_owned(),
                        ty: format!("map[string]{inner}"),
                        tag: "`json:\",embed\"`".to_owned(),
                        doc: vec!["Members not named above.".to_owned()],
                        literal: String::new(),
                        non_null: false,
                        required_index: None,
                        catch_all: true,
                        present: String::new(),
                    });
                }
            }
            TypeKind::StringEnum(values) => {
                view.kind = "enum";
                let mut seen = BTreeSet::new();
                // A repeated value is one member: a second constant would make
                // a duplicate `case`, which Go refuses.
                for value in values.iter().filter(|v| seen.insert(v.as_str())) {
                    let base = if value.trim().is_empty() {
                        "Empty".to_owned()
                    } else {
                        exported(std::slice::from_ref(value))
                    };
                    let name = self.package_names.allocate(format!("{}{base}", view.name));
                    view.variants.push(VariantView {
                        name,
                        literal: quote(value),
                        value: value.clone(),
                        ty: String::new(),
                        accessor: String::new(),
                        constructor: String::new(),
                        synthetic: false,
                        cases: String::new(),
                    });
                }
            }
            TypeKind::UnionTagged(u) => {
                view.kind = "union_tagged";
                self.support.tagged = true;
                view.tag = u.tag.clone();
                view.tag_literal = quote(&u.tag);
                view.fallback = u.fallback;
                let mut methods = Allocator::default();
                for reserved in ["Tag", "Value", "MarshalJSONTo", "UnmarshalJSONFrom"] {
                    methods.reserve(reserved);
                }
                if self.config.validation {
                    methods.reserve("Validate");
                }
                for variant in &u.variants {
                    let base = exported(&variant.suggested_name);
                    let accessor = methods.allocate(format!("As{base}"));
                    let constructor = self
                        .package_names
                        .allocate(format!("{}From{base}", view.name));
                    view.variants.push(VariantView {
                        name: base,
                        literal: quote(&variant.value),
                        value: variant.value.clone(),
                        ty: self.spell(&variant.ty)?,
                        accessor,
                        constructor,
                        synthetic: variant.synthetic,
                        cases: std::iter::once(&variant.value)
                            .chain(&variant.aliases)
                            .map(|tag| quote(tag))
                            .collect::<Vec<_>>()
                            .join(", "),
                    });
                }
            }
            TypeKind::UnionOpen(u) => {
                view.kind = "union_open";
                view.exclusive = u.exclusive;
                view.branches = self.branches(&view.name, &u.branches)?;
            }
            TypeKind::ComposedOpen(branches) => {
                view.kind = "composed_open";
                view.from_raw = self.package_names.allocate(format!("{}FromRaw", view.name));
                view.branches = self.branches(&view.name, branches)?;
            }
            TypeKind::Newtype(inner) | TypeKind::Alias(inner) => {
                view.inner = self.spell(inner)?;
                // Methods cannot be declared on a pointer type, nor on an
                // interface, which a substituted type may be: the generator
                // cannot tell. An alias keeps the methods of the type it
                // names, so a substitution keeps its own JSON behaviour.
                let substituted = match unboxed(inner) {
                    TypeRef::Extern(_) => true,
                    TypeRef::Named(id) => matches!(self.ir.types[id].kind, TypeKind::Extern),
                    _ => false,
                };
                view.kind = if matches!(def.kind, TypeKind::Alias(_))
                    || view.inner.starts_with('*')
                    || substituted
                {
                    "alias"
                } else {
                    "newtype"
                };
            }
        }
        Ok(true)
    }

    /// Whether the type's own decoder takes `null` as one of its values:
    /// any JSON, `null` itself, or a holder of raw JSON.
    fn holds_null(&self, ty: &TypeRef) -> bool {
        let mut ty = ty;
        // A chain of aliases is at most every type long; one closing a cycle
        // generates nothing to hold anything.
        for _ in 0..=self.ir.types.len() {
            ty = match ty {
                TypeRef::Any | TypeRef::Null => return true,
                TypeRef::Boxed(inner) => inner,
                TypeRef::Extern(key) => return self.extern_holds_null(key),
                TypeRef::Named(id) => match &self.ir.types[id].kind {
                    TypeKind::Extern => {
                        let component = self.ir.types[id].component.as_deref();
                        return self.extern_holds_null(component.unwrap_or_default());
                    }
                    TypeKind::UnionOpen(_) | TypeKind::ComposedOpen(_) => return true,
                    TypeKind::Newtype(inner) | TypeKind::Alias(inner) => inner,
                    _ => return false,
                },
                _ => return false,
            };
        }
        false
    }

    /// Whether the type is a substitution, directly or through aliases and
    /// newtypes over one (emitted as aliases).
    /// The type a named type is a Go alias of, if it is emitted as one:
    /// it then has no methods of its own.
    fn alias_target(&self, id: &SchemaId) -> Option<&TypeRef> {
        match &self.ir.types.get(id)?.kind {
            TypeKind::Alias(inner) => Some(inner),
            TypeKind::Newtype(inner)
                if matches!(inner, TypeRef::Boxed(_) | TypeRef::Nullable(_))
                    || self.substituted(inner) =>
            {
                Some(inner)
            }
            _ => None,
        }
    }

    /// Whether `ty` holds a generated type with a `validateInto` of its own,
    /// seen through the aliases Go emits.
    fn validates(&self, ty: &TypeRef) -> bool {
        let mut ids = Vec::new();
        ty.named(&mut ids);
        ids.iter().any(|id| self.validates_named(id, 0))
    }

    fn validates_named(&self, id: &SchemaId, depth: usize) -> bool {
        if depth > self.ir.types.len()
            || !self.names.contains_key(id)
            || matches!(self.ir.types[id].kind, TypeKind::Extern)
        {
            return false;
        }
        match self.alias_target(id) {
            Some(inner) => inner
                .direct_named()
                .is_some_and(|target| self.validates_named(target, depth + 1)),
            None => true,
        }
    }

    fn substituted(&self, ty: &TypeRef) -> bool {
        let mut ty = ty;
        for _ in 0..=self.ir.types.len() {
            ty = match ty {
                TypeRef::Extern(_) => return true,
                TypeRef::Boxed(inner) => inner,
                TypeRef::Named(id) => match &self.ir.types[id].kind {
                    TypeKind::Extern => return true,
                    TypeKind::Newtype(inner) | TypeKind::Alias(inner) => inner,
                    _ => return false,
                },
                _ => return false,
            };
        }
        false
    }

    /// A substituted type takes null as a value when it is spelled like
    /// one that does.
    fn extern_holds_null(&self, key: &str) -> bool {
        self.config
            .substitutions
            .get(key)
            .and_then(|s| s.go.as_ref())
            .is_some_and(|go| null_holding_spelling(&go.name))
    }

    fn branches(
        &mut self,
        owner: &str,
        branches: &[crate::ir::Branch],
    ) -> Result<Vec<BranchView>, GenerateError> {
        let mut methods = Allocator::default();
        for reserved in ["Raw", "MarshalJSONTo", "UnmarshalJSONFrom"] {
            methods.reserve(reserved);
        }
        if self.config.validation {
            methods.reserve("Validate");
        }
        let mut out = Vec::new();
        for branch in branches {
            let base = exported(&branch.suggested_name);
            out.push(BranchView {
                accessor: methods.allocate(format!("As{base}")),
                constructor: self.package_names.allocate(format!("{owner}From{base}")),
                ty: self.spell(&branch.ty)?,
            });
        }
        Ok(out)
    }
}

/// A Go spelling the generator itself holds null in — a pointer,
/// `jsontext.Value` — or an interface, which takes null as nil.
fn null_holding_spelling(spelled: &str) -> bool {
    spelled.starts_with('*')
        || spelled == "jsontext.Value"
        || spelled == "any"
        || spelled.starts_with("interface")
}

/// A type that is an alias shares its target's validation, so a per-type
/// opt-out on it cannot be honoured: said rather than ignored.
pub(crate) fn opt_out_on_alias(def: &TypeDef) -> GenerateError {
    let name = def.component.as_deref().unwrap_or_default();
    GenerateError::Config(format!(
        "`types.{name}.validation = false` cannot apply: `{name}` is an alias, which validates as the type it names; opt that type out instead"
    ))
}

/// The value type a pointer or a container already gives indirection to.
fn unboxed(ty: &TypeRef) -> &TypeRef {
    match ty {
        TypeRef::Boxed(inner) => inner,
        other => other,
    }
}

fn deprecation(deprecated: bool) -> Vec<String> {
    if deprecated {
        vec!["Deprecated: the description marks this deprecated.".to_owned()]
    } else {
        Vec::new()
    }
}

/// The struct tag for one member: the backend's `json` key, then the
/// configured keys, as one Go string literal.
fn struct_tag(
    raw_name: &str,
    omitzero: bool,
    extra: &BTreeMap<String, String>,
    at: &str,
) -> Result<String, GenerateError> {
    let mut json = raw_name.to_owned();
    if !tag_name_ok(raw_name) {
        // The struct's own MarshalJSONTo writes it; decoding goes by name.
        json = "-".to_owned();
    } else if omitzero {
        json.push_str(",omitzero");
    } else if raw_name == "-" {
        // `json:"-"` alone skips the field, and a trailing comma is
        // malformed, so `-` takes an option that changes nothing: strict
        // matching is the default.
        json.push_str(",case:strict");
    }
    let mut parts = vec![format!("json:{}", quote(&json))];
    for (key, value) in extra {
        if key == "json" {
            return Err(GenerateError::Config(format!(
                "`{at}.go_tags` sets `json`, which the generator owns: it carries the member name and the absent-versus-null contract"
            )));
        }
        if !is_tag_key(key) {
            return Err(GenerateError::Config(format!(
                "`{at}.go_tags` key {key:?} is not a struct-tag key: it must be printable ASCII without space, quote or colon"
            )));
        }
        parts.push(format!("{key}:{}", quote(value)));
    }
    let tag = parts.join(" ");
    Ok(if tag.contains('`') {
        quote(&tag)
    } else {
        format!("`{tag}`")
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn struct_tags() {
        let none = BTreeMap::new();
        assert_eq!(
            struct_tag("name", false, &none, "x").unwrap(),
            "`json:\"name\"`"
        );
        assert_eq!(
            struct_tag("-", false, &none, "x").unwrap(),
            "`json:\"-,case:strict\"`"
        );
        assert_eq!(
            struct_tag("a b", true, &none, "x").unwrap(),
            "`json:\"a b,omitzero\"`"
        );
        let extra = BTreeMap::from([("db".to_owned(), "x`y".to_owned())]);
        assert_eq!(
            struct_tag("n", false, &extra, "x").unwrap(),
            "\"json:\\\"n\\\" db:\\\"x`y\\\"\""
        );
        let json = BTreeMap::from([("json".to_owned(), "x".to_owned())]);
        assert!(struct_tag("n", false, &json, "x").is_err());
        let bad = BTreeMap::from([("a b".to_owned(), "x".to_owned())]);
        assert!(struct_tag("n", false, &bad, "x").is_err());
    }

    #[test]
    fn import_package_names() {
        assert_eq!(package_of("example.com/x/uuid"), "uuid");
        assert_eq!(package_of("encoding/json/v2"), "json");
        assert_eq!(package_of("time"), "time");
        assert_eq!(package_of("example.com/v"), "v");
    }
}