roas-codegen 0.2.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
//! The normalized front-end representation: what a schema *says*,
//! with the OpenAPI model's shape translated away.
//!
//! Lowering works from this rather than from `roas::v3_2::Schema`
//! directly, so a second description language — AsyncAPI — needs a
//! second translation into it, not a second lowering.

use crate::diagnostic::{SchemaId, push_token, source_of, synthetic};
use roas::common::bool_or::BoolOr;
use roas::common::formats::{IntegerFormat, NumberFormat, SchemaType, StringFormat};
use roas::common::reference::RefOr;
use roas::v3_0::schema::{Schema as V30Schema, SingleSchema as V30Single};
use roas::v3_2::discriminator::Discriminator;
use roas::v3_2::schema::{
    AllOfSchema, AnyOfSchema, ArraySchema, BooleanSchema, IntegerSchema, MultiSchema, NullSchema,
    NumberSchema, ObjectSchema, OneOfSchema, Schema, SchemaRef, SingleSchema, StringSchema,
};
use serde::Deserialize;
use serde_json::Value;
use std::collections::BTreeMap;
use url::Url;

/// Where a `$ref` points.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RefTarget {
    /// `#/components/schemas/<name>`: the one kind of reference the
    /// first release follows.
    Component(String),
    /// Anything else. Reported at lowering; the slot lowers to nothing.
    Unsupported(String),
}

/// One schema position: either a reference or an inline schema.
#[derive(Debug, Clone)]
pub(crate) enum Slot {
    Ref {
        id: SchemaId,
        target: RefTarget,
        /// The reference's sibling keywords, as a schema of their own,
        /// when they assert anything beyond annotations. `$ref` with
        /// siblings is the intersection of both.
        siblings: Option<Box<FrontSchema>>,
        /// Annotation-only siblings: a description or summary override.
        description: Option<String>,
    },
    Inline(Box<FrontSchema>),
}

impl Slot {
    pub(crate) fn id(&self) -> &SchemaId {
        match self {
            Slot::Ref { id, .. } => id,
            Slot::Inline(schema) => &schema.id,
        }
    }
}

/// How an object treats members its `properties` do not name.
#[derive(Debug, Clone)]
pub(crate) enum Additional {
    /// Omitted, or `true`: any JSON value.
    Any,
    /// `false`: unknown members are rejected.
    Denied,
    /// A schema every unknown member must match.
    Schema(Slot),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IntWidth {
    Int32,
    Int64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FloatWidth {
    Float,
    Double,
}

/// The constraints a schema declares that the type cannot express.
/// First-class so validation, when it lands, is a rendering decision.
#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct Constraints {
    pub min_length: Option<u64>,
    pub max_length: Option<u64>,
    pub pattern: Option<String>,
    pub minimum: Option<serde_json::Number>,
    pub maximum: Option<serde_json::Number>,
    pub exclusive_minimum: Option<serde_json::Number>,
    pub exclusive_maximum: Option<serde_json::Number>,
    pub multiple_of: Option<serde_json::Number>,
    pub min_items: Option<u64>,
    pub max_items: Option<u64>,
    pub unique_items: bool,
    pub min_properties: Option<u64>,
    pub max_properties: Option<u64>,
    /// `propertyNames` is declared.
    pub property_names: bool,
    /// What `propertyNames` says, when it says only what a string check
    /// covers (`minLength`, `maxLength`, `pattern`); `None` when it says
    /// more, and is then not checked.
    pub names: Option<Box<Constraints>>,
    /// `patternProperties` patterns, in declaration order.
    pub pattern_properties: Vec<String>,
    /// A numeric `enum`: the values a number may be.
    pub enum_numbers: Option<Vec<serde_json::Number>>,
    /// A numeric `const` on a number.
    pub const_number: Option<serde_json::Number>,
    /// Keywords neither the type nor a generated check enforces: a `const`
    /// the type does not pin.
    pub unenforced: Vec<&'static str>,
    /// The constraints of an inline `items` or `additionalProperties`
    /// schema, checked on each item or member value its type holds unless
    /// that type is generated (and checks itself).
    pub items: Option<Items>,
    /// The schema's keywords the generator does not handle at all.
    pub unsupported: Vec<String>,
}

/// What an inline item or member-value schema constrains.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Items {
    /// `items` or `additionalProperties`.
    pub keyword: &'static str,
    pub constraints: Box<Constraints>,
}

#[derive(Debug, Clone)]
pub(crate) enum Kind {
    /// `{}` or `true`: any JSON value.
    Any,
    /// `false`: no value is valid.
    Never,
    /// `not`: ungeneratable.
    Not,
    String {
        format: Option<String>,
        enum_values: Option<Vec<String>>,
    },
    Integer {
        width: Option<IntWidth>,
        enum_values: Option<Vec<i64>>,
    },
    Number {
        width: Option<FloatWidth>,
        enum_values: Option<Vec<serde_json::Number>>,
    },
    Boolean,
    Null,
    Array {
        /// `None` when `items` is omitted or `true`: any value.
        items: Option<Slot>,
    },
    Object {
        properties: BTreeMap<String, Slot>,
        required: Vec<String>,
        additional: Additional,
        /// No `type` was written. `properties` only constrains objects,
        /// so a typeless schema still permits every other instance.
        typeless: bool,
    },
    AllOf {
        branches: Vec<Slot>,
    },
    AnyOf {
        branches: Vec<Slot>,
    },
    OneOf {
        branches: Vec<Slot>,
        discriminator: Option<Discriminator>,
    },
    /// `type: [a, b, …]` with several non-null members: a union with no
    /// discriminator and no branch schemas of its own. Each branch is
    /// the same schema read under one type.
    TypeUnion {
        branches: Vec<Slot>,
    },
}

/// One schema, translated.
#[derive(Debug, Clone)]
pub(crate) struct FrontSchema {
    pub id: SchemaId,
    pub kind: Kind,
    /// `null` is among the permitted types.
    pub nullable: bool,
    pub title: Option<String>,
    pub description: Option<String>,
    pub default: Option<Value>,
    pub deprecated: bool,
    pub read_only: bool,
    pub write_only: bool,
    pub constraints: Constraints,
    /// Keywords that reached the model's catch-all and are not `x-`
    /// extensions. Every one is reported by lowering.
    pub unsupported: Vec<String>,
    /// `x-` extensions, verbatim.
    pub extensions: BTreeMap<String, Value>,
    /// `$schema`, when the schema declares its own dialect.
    pub dialect: Option<String>,
    /// `const`, which the model keeps only in its catch-all. Consumed
    /// by the discriminator proof; reported as unsupported otherwise.
    pub const_value: Option<Value>,
    /// `patternProperties`: each pattern, as written, with its schema.
    pub patterns: Vec<(String, Slot)>,
    /// A `discriminator` on an object schema: a parent the schemas building
    /// on it with `allOf` are selected from.
    pub discriminator: Option<roas::v3_2::discriminator::Discriminator>,
}

/// The translation of one document's components.
pub(crate) struct Front {
    pub components: BTreeMap<String, Slot>,
}

/// Keywords the catch-all may hold that mean something at every type
/// and need no report: annotations, and the reference machinery the
/// restriction report already covers.
const SILENT_KEYWORDS: &[&str] = &[
    "$comment",
    "$id",
    "$anchor",
    "$schema",
    "$defs",
    "definitions",
    "discriminator",
    "nullable",
    "const",
];

/// Keywords that make sense only under a given type. Used to read a
/// `type: [a, b]` schema once per member type without reporting `b`'s
/// keywords as unsupported under `a`.
fn keywords_for(schema_type: &SchemaType) -> &'static [&'static str] {
    match schema_type {
        SchemaType::String => &[
            "maxLength",
            "minLength",
            "pattern",
            "format",
            "enum",
            "default",
            "contentEncoding",
            "contentMediaType",
            "contentSchema",
        ],
        SchemaType::Integer | SchemaType::Number => &[
            "minimum",
            "maximum",
            "exclusiveMinimum",
            "exclusiveMaximum",
            "multipleOf",
            "format",
            "enum",
            "default",
        ],
        SchemaType::Array => &[
            "items",
            "prefixItems",
            "minItems",
            "maxItems",
            "uniqueItems",
            "contains",
            "minContains",
            "maxContains",
            "unevaluatedItems",
            "default",
        ],
        SchemaType::Object => &[
            "properties",
            "patternProperties",
            "additionalProperties",
            "required",
            "minProperties",
            "maxProperties",
            "propertyNames",
            "unevaluatedProperties",
            "dependentRequired",
            "dependentSchemas",
            "default",
        ],
        SchemaType::Boolean | SchemaType::Null | SchemaType::Custom(_) => &["default", "enum"],
    }
}

const COMMON_KEYWORDS: &[&str] = &[
    "title",
    "description",
    "deprecated",
    "readOnly",
    "writeOnly",
    "examples",
    "example",
    "xml",
    "externalDocs",
    "type",
    "$comment",
    "$schema",
    "$id",
    "$anchor",
    "not",
    "allOf",
    "anyOf",
    "oneOf",
    "if",
    "then",
    "else",
    "const",
];

pub(crate) struct Translator<'a> {
    pub uri: &'a Url,
    /// The source as given, for the one thing the model cannot say:
    /// whether `type` was written.
    pub raw: &'a Value,
    /// Maps a 3.2 pointer to the source document's pointer.
    pub source_pointer: fn(&str) -> String,
    /// The source is OpenAPI 2 or 3.0, whose `nullable` admits null even
    /// past an `enum`: those models cannot list null in one.
    pub legacy_nullable: bool,
    /// Validation is on: keywords the 2.0 / 3.0 model dropped are reported,
    /// so the values it checks are not passed for what it never read.
    /// Without validation they go unmentioned, as they always did.
    pub report_lost: bool,
    /// The source is OpenAPI 3.0. Its model keeps the schema keywords it
    /// does not claim, and conversion carries them forward; they are
    /// set aside here so they are read under the same lenient rules as
    /// the keywords the 2.0 model drops.
    pub v3_0_source: bool,
}

impl Translator<'_> {
    pub(crate) fn translate(&self, spec: &roas::v3_2::spec::Spec) -> Front {
        let mut components = BTreeMap::new();
        if let Some(schemas) = spec.components.as_ref().and_then(|c| c.schemas.as_ref()) {
            for (name, slot) in schemas {
                let mut pointer = String::from("/components/schemas");
                push_token(&mut pointer, name);
                components.insert(name.clone(), self.slot(slot, pointer));
            }
        }
        Front { components }
    }

    fn id(&self, pointer: &str) -> SchemaId {
        SchemaId::new(self.uri.clone(), pointer)
    }

    fn slot(&self, slot: &RefOr<Schema, SchemaRef>, pointer: String) -> Slot {
        match slot {
            RefOr::Item(schema) => Slot::Inline(Box::new(self.schema(schema, pointer))),
            RefOr::Ref(reference) => self.reference(reference, pointer),
        }
    }

    fn reference(&self, reference: &SchemaRef, pointer: String) -> Slot {
        let target = match reference.reference.strip_prefix("#/components/schemas/") {
            Some(name) if !name.is_empty() && !name.contains('/') => {
                RefTarget::Component(unescape(name))
            }
            _ => RefTarget::Unsupported(reference.reference.clone()),
        };
        let asserting = reference.siblings.keys().any(|k| {
            !k.starts_with("x-")
                && !matches!(
                    k.as_str(),
                    "title"
                        | "description"
                        | "deprecated"
                        | "readOnly"
                        | "writeOnly"
                        | "example"
                        | "examples"
                        | "externalDocs"
                        | "xml"
                        | "$comment"
                )
        });
        let siblings = if asserting {
            // Read the siblings as a schema on their own. The plain parse
            // reads a typeless set as an object; whether `type` was
            // written is checked against the source, as everywhere.
            reference
                .siblings_schema()
                .ok()
                .flatten()
                .map(|schema| Box::new(self.schema(&schema, pointer.clone())))
        } else {
            None
        };
        Slot::Ref {
            id: self.id(&pointer),
            target,
            siblings,
            description: reference
                .description
                .clone()
                .or_else(|| reference.summary.clone()),
        }
    }

    /// The keywords written beside a composition. A 3.1 or 3.2 model keeps
    /// them in its catch-all; a 2.0 or 3.0 one keeps only `x-` keys, so
    /// they are read from the source as written.
    fn composition_keywords(
        &self,
        extensions: &Option<BTreeMap<String, Value>>,
        pointer: &str,
    ) -> serde_json::Map<String, Value> {
        let mut out: serde_json::Map<String, Value> = extensions
            .iter()
            .flatten()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        if self.legacy_nullable {
            let source = (self.source_pointer)(&source_of(pointer));
            if let Some(raw) = self.raw.pointer(&source).and_then(Value::as_object) {
                for (k, v) in raw {
                    out.entry(k.clone()).or_insert_with(|| v.clone());
                }
            }
        }
        out
    }

    /// The keywords an OpenAPI 2.0 or 3.0 source wrote on this schema that
    /// its model dropped on the way to 3.2: unread, they are reported as
    /// unsupported rather than lost without a word.
    fn lost_in_conversion(&self, schema: &Schema, pointer: &str) -> Vec<String> {
        if !self.legacy_nullable || !self.report_lost {
            return Vec::new();
        }
        let source = (self.source_pointer)(&source_of(pointer));
        let Some(raw) = self.raw.pointer(&source).and_then(Value::as_object) else {
            return Vec::new();
        };
        let converted = serde_json::to_value(schema).unwrap_or(Value::Null);
        let kept = converted.as_object();
        let has = |key: &str| kept.is_some_and(|k| k.contains_key(key));
        raw.keys()
            .filter(|key| {
                let key = key.as_str();
                // Rewritten rather than lost: `nullable` into the type
                // list, `example` into `examples`, a boolean exclusive
                // bound into a numeric one. A 2.0 `discriminator` name is
                // dropped but asserts nothing; a `type` beside a
                // composition is dropped, and lost unless the branches
                // already say it.
                let rewritten = match key {
                    "nullable" | "x-nullable" | "example" | "discriminator" => true,
                    "type" => self.type_implied(raw),
                    "minimum" => has("exclusiveMinimum"),
                    "maximum" => has("exclusiveMaximum"),
                    // A boolean flag: `false` says what the inclusive bound
                    // already does, and `true` without a bound nothing.
                    "exclusiveMinimum" | "exclusiveMaximum" => raw[key].is_boolean(),
                    // The model reads `default: null` as no default.
                    "default" => raw[key].is_null(),
                    _ => false,
                };
                // An annotation asserts nothing: dropped, it changes no
                // instance's validity.
                let annotation = key.starts_with("x-")
                    || matches!(
                        key,
                        "title"
                            | "description"
                            | "deprecated"
                            | "readOnly"
                            | "writeOnly"
                            | "default"
                            | "examples"
                            | "xml"
                            | "externalDocs"
                            | "$comment"
                            | "$schema"
                            | "$id"
                            | "$anchor"
                            | "$defs"
                            | "definitions"
                    );
                !rewritten && !annotation && !has(key)
            })
            .cloned()
            .collect()
    }

    /// Whether a legacy composition's `type` is already said by its
    /// branches: by one of an `allOf`, by every one of an `anyOf` or a
    /// `oneOf`, directly or through a local `$ref`.
    fn type_implied(&self, raw: &serde_json::Map<String, Value>) -> bool {
        let Some(want) = raw.get("type") else {
            return true;
        };
        // A branch says the type only when it also leaves null out as the
        // schema does.
        // `nullable` in 3.0, `x-nullable` in 2.0.
        let nullable = |v: &Value| {
            ["nullable", "x-nullable"]
                .iter()
                .any(|k| v.get(k) == Some(&Value::Bool(true)))
        };
        let outer_nullable = ["nullable", "x-nullable"]
            .iter()
            .any(|k| raw.get(*k) == Some(&Value::Bool(true)));
        let typed = |branch: &Value| {
            let mut current = branch;
            for _ in 0..16 {
                if let Some(t) = current.get("type") {
                    return t == want && (outer_nullable || !nullable(current));
                }
                match current
                    .get("$ref")
                    .and_then(Value::as_str)
                    .and_then(|r| r.strip_prefix('#'))
                    .and_then(|p| self.raw.pointer(p))
                {
                    Some(next) => current = next,
                    None => return false,
                }
            }
            false
        };
        let branches = |key: &str| raw.get(key).and_then(Value::as_array);
        branches("allOf").is_some_and(|b| b.iter().any(typed))
            || branches("anyOf").is_some_and(|b| b.iter().all(typed))
            || branches("oneOf").is_some_and(|b| b.iter().all(typed))
    }

    fn type_written(&self, pointer: &str) -> bool {
        let source = (self.source_pointer)(&source_of(pointer));
        self.raw
            .pointer(&source)
            .and_then(Value::as_object)
            .is_some_and(|object| object.contains_key("type"))
    }

    /// A `propertyNames` schema at `pointer`, read as written, when all it
    /// asserts is what a string check covers. A member name is a string, so
    /// `type: string` asserts nothing.
    fn names(&self, pointer: &str) -> Option<Box<Constraints>> {
        let source = (self.source_pointer)(&source_of(pointer));
        let object = match self.raw.pointer(&source)? {
            Value::Bool(true) => return Some(Box::default()),
            Value::Object(object) => object,
            _ => return None,
        };
        let mut names = Constraints::default();
        for (key, value) in object {
            match key.as_str() {
                "type" if value == "string" => {}
                "minLength" => names.min_length = Some(value.as_u64()?),
                "maxLength" => names.max_length = Some(value.as_u64()?),
                "pattern" => names.pattern = Some(value.as_str()?.to_owned()),
                "title" | "description" | "$comment" | "examples" | "example" | "deprecated"
                | "readOnly" | "writeOnly" => {}
                key if key.starts_with("x-") => {}
                _ => return None,
            }
        }
        Some(Box::new(names))
    }

    /// The keywords the 3.0 source wrote on this schema that its model
    /// does not claim: kept in the model's catch-all and carried through
    /// conversion, unlike the 2.0 model, which drops them.
    fn kept_by_v3_0(&self, pointer: &str) -> Vec<String> {
        if !self.v3_0_source {
            return Vec::new();
        }
        let source = (self.source_pointer)(&source_of(pointer));
        let Some(raw) = self.raw.pointer(&source) else {
            return Vec::new();
        };
        if raw.get("$ref").is_some() {
            return Vec::new();
        }
        let Ok(schema) = roas::v3_0::schema::Schema::deserialize(raw) else {
            return Vec::new();
        };
        let catch_all = match &schema {
            V30Schema::AllOf(s) => &s.extensions,
            V30Schema::AnyOf(s) => &s.extensions,
            V30Schema::OneOf(s) => &s.extensions,
            V30Schema::Not(s) => &s.extensions,
            V30Schema::Single(single) => match single.as_ref() {
                V30Single::String(s) => &s.extensions,
                V30Single::Integer(s) => &s.extensions,
                V30Single::Number(s) => &s.extensions,
                V30Single::Boolean(s) => &s.extensions,
                V30Single::Array(s) => &s.extensions,
                V30Single::Null(s) => &s.extensions,
                V30Single::Object(s) => &s.extensions,
            },
        };
        catch_all
            .iter()
            .flatten()
            .map(|(key, _)| key)
            .filter(|key| !key.starts_with("x-"))
            .cloned()
            .collect()
    }

    fn schema(&self, schema: &Schema, pointer: String) -> FrontSchema {
        // A 3.0 source's kept keywords are set aside, so the schema reads
        // as the 3.0 model once had it and `lost_in_conversion` reports
        // them under the legacy rules: only with validation, a `type` its
        // branches imply exempt.
        let kept = self.kept_by_v3_0(&pointer);
        let without_kept;
        let schema = if kept.is_empty() {
            schema
        } else {
            without_kept = without_keywords(schema, &kept);
            &without_kept
        };
        let lost = self.lost_in_conversion(schema, &pointer);
        let mut front = self.schema_kind(schema, pointer);
        for keyword in lost {
            if !front.unsupported.contains(&keyword) {
                front.unsupported.push(keyword);
            }
        }
        // A number's `enum` and `const` are checked by generated validation.
        match &front.kind {
            Kind::Integer {
                enum_values: Some(values),
                ..
            } => front.constraints.enum_numbers = Some(values.iter().map(|&n| n.into()).collect()),
            Kind::Number {
                enum_values: Some(values),
                ..
            } => front.constraints.enum_numbers = Some(values.clone()),
            _ => {}
        }
        if let (Some(Value::Number(n)), Kind::Integer { .. } | Kind::Number { .. }) =
            (&front.const_value, &front.kind)
        {
            front.constraints.const_number = Some(n.clone());
        }
        // A required member with no property of its own lands in the
        // catch-all, where decoding does not ask for it.
        let undeclared = matches!(
            &front.kind,
            Kind::Object { properties, required, .. }
                if required.iter().any(|r| !properties.contains_key(r))
        );
        for (present, keyword) in [
            (
                front.const_value.is_some() && front.constraints.const_number.is_none(),
                "const",
            ),
            (undeclared, "required"),
        ] {
            if present && !front.constraints.unenforced.contains(&keyword) {
                front.constraints.unenforced.push(keyword);
            }
        }
        front.constraints.items = items(&front);
        front.constraints.unsupported = front.unsupported.clone();
        front
    }

    fn schema_kind(&self, schema: &Schema, pointer: String) -> FrontSchema {
        match schema {
            Schema::Bool(true) | Schema::Empty(_) => self.leaf(pointer, Kind::Any),
            Schema::Bool(false) => self.leaf(pointer, Kind::Never),
            Schema::Not(not) => {
                let mut front = self.leaf(pointer, Kind::Not);
                front.unsupported = catch_all_keywords(&not.extensions, &mut front.extensions);
                front.const_value = const_of(&not.extensions);
                front
            }
            Schema::AllOf(all) => self.all_of(all, pointer),
            Schema::AnyOf(any) => self.any_of(any, pointer),
            Schema::OneOf(one) => self.one_of(one, pointer),
            Schema::Multi(multi) => self.multi(multi, pointer),
            Schema::Single(single) => self.single(single, pointer),
        }
    }

    fn leaf(&self, pointer: String, kind: Kind) -> FrontSchema {
        FrontSchema {
            id: self.id(&pointer),
            kind,
            nullable: false,
            title: None,
            description: None,
            default: None,
            deprecated: false,
            read_only: false,
            write_only: false,
            constraints: Constraints::default(),
            unsupported: Vec::new(),
            extensions: BTreeMap::new(),
            dialect: None,
            const_value: None,
            patterns: Vec::new(),
            discriminator: None,
        }
    }

    fn branches(
        &self,
        slots: &[RefOr<Schema, SchemaRef>],
        pointer: &str,
        keyword: &str,
    ) -> Vec<Slot> {
        slots
            .iter()
            .enumerate()
            .map(|(i, slot)| {
                let mut child = pointer.to_owned();
                push_token(&mut child, keyword);
                push_token(&mut child, &i.to_string());
                self.slot(slot, child)
            })
            .collect()
    }

    fn all_of(&self, all: &AllOfSchema, pointer: String) -> FrontSchema {
        let branches = self.branches(&all.all_of, &pointer, "allOf");
        let mut front = self.leaf(pointer, Kind::AllOf { branches });
        front.unsupported = catch_all_keywords(&all.extensions, &mut front.extensions);
        let keywords = self.composition_keywords(&all.extensions, &front.id.pointer);
        composition_annotations(&mut front, &keywords);
        front.dialect = dialect_of(&all.extensions);
        front.const_value = const_of(&all.extensions);
        front
    }

    fn any_of(&self, any: &AnyOfSchema, pointer: String) -> FrontSchema {
        let branches = self.branches(&any.any_of, &pointer, "anyOf");
        let mut front = self.leaf(pointer, Kind::AnyOf { branches });
        front.unsupported = catch_all_keywords(&any.extensions, &mut front.extensions);
        let keywords = self.composition_keywords(&any.extensions, &front.id.pointer);
        composition_annotations(&mut front, &keywords);
        front.dialect = dialect_of(&any.extensions);
        front.const_value = const_of(&any.extensions);
        front
    }

    fn one_of(&self, one: &OneOfSchema, pointer: String) -> FrontSchema {
        let branches = self.branches(&one.one_of, &pointer, "oneOf");
        let mut front = self.leaf(
            pointer,
            Kind::OneOf {
                branches,
                discriminator: one.discriminator.clone(),
            },
        );
        front.unsupported = catch_all_keywords(&one.extensions, &mut front.extensions);
        let keywords = self.composition_keywords(&one.extensions, &front.id.pointer);
        composition_annotations(&mut front, &keywords);
        front.dialect = dialect_of(&one.extensions);
        front.const_value = const_of(&one.extensions);
        front
    }

    /// `type: [...]`. The model keeps nothing but the type list and the
    /// annotations; every other keyword sits in its catch-all. So the
    /// schema is re-read once per non-null member type, with the
    /// keywords that apply to that type, and `null` becomes the
    /// nullable flag.
    fn multi(&self, multi: &MultiSchema, pointer: String) -> FrontSchema {
        let nullable = multi
            .schema_types
            .iter()
            .any(|t| matches!(t, SchemaType::Null));
        let members: Vec<&SchemaType> = multi
            .schema_types
            .iter()
            .filter(|t| !matches!(t, SchemaType::Null))
            .collect();
        let raw = serde_json::to_value(multi).unwrap_or(Value::Null);
        let object = raw.as_object().cloned().unwrap_or_default();
        let read_as = |schema_type: &SchemaType,
                       restrict: bool,
                       object: &serde_json::Map<String, Value>|
         -> Member {
            let mut map = serde_json::Map::new();
            let applicable = keywords_for(schema_type);
            for (key, value) in object {
                if key == "type" {
                    continue;
                }
                // `enum` and `const` assert on every member, whether its
                // type's schema models them or not.
                if restrict
                    && !applicable.contains(&key.as_str())
                    && !COMMON_KEYWORDS.contains(&key.as_str())
                    && !matches!(key.as_str(), "enum" | "const")
                    && !key.starts_with("x-")
                {
                    continue;
                }
                // The values the list shares among its members: each
                // member keeps those of its own type. An `enum` or `const`
                // with none admits no value of this type.
                let value = match (key.as_str(), value) {
                    ("enum", Value::Array(values)) => {
                        let own: Vec<Value> = values
                            .iter()
                            .filter(|v| fits(schema_type, v))
                            .cloned()
                            .collect();
                        if own.is_empty() {
                            return Member::Nothing;
                        }
                        Value::Array(own)
                    }
                    ("const", v) if !fits(schema_type, v) => return Member::Nothing,
                    ("default", v) if !fits(schema_type, v) => continue,
                    _ => value.clone(),
                };
                map.insert(key.clone(), value);
            }
            map.insert("type".to_owned(), Value::String(schema_type.to_string()));
            let Ok(schema) = serde_json::from_value::<Schema>(Value::Object(map)) else {
                return Member::Unread;
            };
            // Several members are several schemas, each with an identity of
            // its own; a lone member is the schema itself.
            let at = if restrict {
                synthetic(&pointer, &schema_type.to_string())
            } else {
                pointer.clone()
            };
            let mut member = self.schema(&schema, at);
            // The member's `type` was written, as part of the list.
            if let Kind::Object { typeless, .. } = &mut member.kind {
                *typeless = false;
            }
            Member::Read(Box::new(member))
        };
        let read = |schema_type: &SchemaType, restrict: bool| -> Member {
            match read_as(schema_type, restrict, &object) {
                // A `format` another member type gives is an annotation
                // for this one.
                Member::Unread if object.contains_key("format") => {
                    let mut without = object.clone();
                    without.remove("format");
                    read_as(schema_type, restrict, &without)
                }
                other => other,
            }
        };
        // Only the list's null is left: read as `type: null`, so what else
        // the list says still stands.
        let null_admitted = nullable && (self.legacy_nullable || shared_admits_null(&object));
        let null_only = || -> FrontSchema {
            // The `enum` and `const` were found to admit null;
            // what applies to other types does not apply here.
            let null_keywords = keywords_for(&SchemaType::Null);
            let only: serde_json::Map<String, Value> = object
                .iter()
                .filter(|(key, _)| {
                    let key = key.as_str();
                    let other_type = [
                        SchemaType::String,
                        SchemaType::Number,
                        SchemaType::Integer,
                        SchemaType::Object,
                        SchemaType::Array,
                        SchemaType::Boolean,
                    ]
                    .iter()
                    .any(|t| keywords_for(t).contains(&key));
                    !matches!(key, "enum" | "const")
                        && (null_keywords.contains(&key) || !other_type)
                })
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect();
            match read_as(&SchemaType::Null, false, &only) {
                Member::Read(member) => *member,
                _ => self.leaf(pointer.clone(), Kind::Null),
            }
        };
        let mut front = match members.as_slice() {
            [] if null_admitted => null_only(),
            [] => self.leaf(pointer.clone(), Kind::Never),
            [one] => match read(one, false) {
                Member::Read(member) => *member,
                Member::Nothing if null_admitted => null_only(),
                Member::Nothing => self.leaf(pointer.clone(), Kind::Never),
                // Not lost without a word: the schema is reported as
                // one the generator does not handle.
                Member::Unread => {
                    let mut front = self.leaf(pointer.clone(), Kind::Any);
                    front.unsupported.push("type".to_owned());
                    front
                }
            },
            many => {
                let branches: Vec<Slot> = many
                    .iter()
                    .filter_map(|t| match read(t, true) {
                        Member::Read(member) => Some(member),
                        Member::Nothing => None,
                        // Kept as a branch that proves nothing, so a value
                        // of its type is never taken to match no member.
                        Member::Unread => {
                            let mut member =
                                self.leaf(synthetic(&pointer, &t.to_string()), Kind::Any);
                            member.unsupported.push("type".to_owned());
                            member.constraints.unsupported = member.unsupported.clone();
                            Some(Box::new(member))
                        }
                    })
                    .map(Slot::Inline)
                    .collect();
                if branches.is_empty() && null_admitted {
                    let mut front = null_only();
                    front.nullable = true;
                    return front;
                }
                let mut front = self.leaf(pointer.clone(), Kind::TypeUnion { branches });
                // A keyword that applies to none of the member types is read
                // by no branch; report it on the union rather than lose it.
                front.unsupported = object
                    .keys()
                    .filter(|key| {
                        key.as_str() != "type"
                            && !key.starts_with("x-")
                            && !COMMON_KEYWORDS.contains(&key.as_str())
                            && !SILENT_KEYWORDS.contains(&key.as_str())
                            && !many.iter().any(|t| keywords_for(t).contains(&key.as_str()))
                    })
                    .cloned()
                    .collect();
                front.title = multi.title.clone();
                front.description = multi.description.clone();
                front.deprecated = multi.deprecated.unwrap_or(false);
                front.read_only = multi.read_only.unwrap_or(false);
                front.write_only = multi.write_only.unwrap_or(false);
                front
            }
        };
        // A member read on its own reports its own `type` as written.
        if let Kind::Object { typeless, .. } = &mut front.kind {
            *typeless = false;
        }
        front.nullable = nullable && (self.legacy_nullable || shared_admits_null(&object));
        front
    }

    fn single(&self, single: &SingleSchema, pointer: String) -> FrontSchema {
        match single {
            SingleSchema::String(s) => self.string(s, pointer),
            SingleSchema::Integer(s) => self.integer(s, pointer),
            SingleSchema::Number(s) => self.number(s, pointer),
            SingleSchema::Boolean(s) => self.boolean(s, pointer),
            SingleSchema::Null(s) => self.null(s, pointer),
            SingleSchema::Array(s) => self.array(s, pointer),
            SingleSchema::Object(s) => self.object(s, pointer),
        }
    }

    fn string(&self, s: &StringSchema, pointer: String) -> FrontSchema {
        let format = s.format.as_ref().map(|f| match f {
            StringFormat::Custom(custom) => custom.clone(),
            other => other.to_string(),
        });
        let mut front = self.leaf(
            pointer,
            Kind::String {
                format,
                enum_values: s.enum_values.clone(),
            },
        );
        front.title = s.title.clone();
        front.description = s.description.clone();
        front.default = s.default.clone().map(Value::String);
        front.deprecated = s.deprecated.unwrap_or(false);
        front.read_only = s.read_only.unwrap_or(false);
        front.write_only = s.write_only.unwrap_or(false);
        front.constraints.min_length = s.min_length;
        front.constraints.max_length = s.max_length;
        front.constraints.pattern = s.pattern.clone();
        front.unsupported = catch_all_keywords(&s.extensions, &mut front.extensions);
        front.dialect = dialect_of(&s.extensions);
        front.const_value = const_of(&s.extensions);
        // A string `const` is a one-value enum: representing it that way
        // makes the generated type enforce it, which also keeps the pin
        // of a discriminated branch in the branch's own type.
        if let Some(Value::String(only)) = &front.const_value
            && let Kind::String { enum_values, .. } = &mut front.kind
            && enum_values.as_ref().is_none_or(|v| v.contains(only))
        {
            *enum_values = Some(vec![only.clone()]);
            front.const_value = None;
        }
        front
    }

    fn integer(&self, s: &IntegerSchema, pointer: String) -> FrontSchema {
        let width = s.format.as_ref().and_then(|f| match f {
            IntegerFormat::Int32 => Some(IntWidth::Int32),
            IntegerFormat::Int64 => Some(IntWidth::Int64),
            IntegerFormat::Custom(_) => None,
        });
        let mut front = self.leaf(
            pointer,
            Kind::Integer {
                width,
                enum_values: s.enum_values.clone(),
            },
        );
        front.title = s.title.clone();
        front.description = s.description.clone();
        front.default = s.default.map(Value::from);
        front.deprecated = s.deprecated.unwrap_or(false);
        front.read_only = s.read_only.unwrap_or(false);
        front.write_only = s.write_only.unwrap_or(false);
        front.constraints.minimum = s.minimum.clone();
        front.constraints.maximum = s.maximum.clone();
        front.constraints.exclusive_minimum = s.exclusive_minimum.clone();
        front.constraints.exclusive_maximum = s.exclusive_maximum.clone();
        front.constraints.multiple_of = s.multiple_of.clone();
        front.unsupported = catch_all_keywords(&s.extensions, &mut front.extensions);
        front.dialect = dialect_of(&s.extensions);
        front.const_value = const_of(&s.extensions);
        front
    }

    fn number(&self, s: &NumberSchema, pointer: String) -> FrontSchema {
        let width = s.format.as_ref().and_then(|f| match f {
            NumberFormat::Float => Some(FloatWidth::Float),
            NumberFormat::Double => Some(FloatWidth::Double),
            NumberFormat::Custom(_) => None,
        });
        let mut front = self.leaf(
            pointer,
            Kind::Number {
                width,
                enum_values: s.enum_values.clone(),
            },
        );
        front.title = s.title.clone();
        front.description = s.description.clone();
        front.default = s.default.clone().map(Value::Number);
        front.deprecated = s.deprecated.unwrap_or(false);
        front.read_only = s.read_only.unwrap_or(false);
        front.write_only = s.write_only.unwrap_or(false);
        front.constraints.minimum = s.minimum.clone();
        front.constraints.maximum = s.maximum.clone();
        front.constraints.exclusive_minimum = s.exclusive_minimum.clone();
        front.constraints.exclusive_maximum = s.exclusive_maximum.clone();
        front.constraints.multiple_of = s.multiple_of.clone();
        front.unsupported = catch_all_keywords(&s.extensions, &mut front.extensions);
        front.dialect = dialect_of(&s.extensions);
        front.const_value = const_of(&s.extensions);
        front
    }

    fn boolean(&self, s: &BooleanSchema, pointer: String) -> FrontSchema {
        let mut front = self.leaf(pointer, Kind::Boolean);
        front.title = s.title.clone();
        front.description = s.description.clone();
        front.default = s.default.map(Value::Bool);
        front.deprecated = s.deprecated.unwrap_or(false);
        front.read_only = s.read_only.unwrap_or(false);
        front.write_only = s.write_only.unwrap_or(false);
        front.unsupported = catch_all_keywords(&s.extensions, &mut front.extensions);
        front.dialect = dialect_of(&s.extensions);
        front.const_value = const_of(&s.extensions);
        front
    }

    fn null(&self, s: &NullSchema, pointer: String) -> FrontSchema {
        let mut front = self.leaf(pointer, Kind::Null);
        front.title = s.title.clone();
        front.description = s.description.clone();
        front.deprecated = s.deprecated.unwrap_or(false);
        front.read_only = s.read_only.unwrap_or(false);
        front.write_only = s.write_only.unwrap_or(false);
        front.unsupported = catch_all_keywords(&s.extensions, &mut front.extensions);
        front.dialect = dialect_of(&s.extensions);
        front.const_value = const_of(&s.extensions);
        front
    }

    fn array(&self, s: &ArraySchema, pointer: String) -> FrontSchema {
        // Beside `prefixItems`, `items` speaks only of the items after the
        // prefix, and the prefix items have schemas of their own: no one
        // item type holds both, so the items are kept as raw JSON and
        // `items` is reported unchecked rather than applied to every item.
        let prefixed = s
            .extensions
            .as_ref()
            .is_some_and(|e| e.contains_key("prefixItems"));
        let items = match &s.items {
            None | Some(BoolOr::Bool(true)) => None,
            Some(_) if prefixed => None,
            Some(BoolOr::Bool(false)) => {
                let mut child = pointer.clone();
                push_token(&mut child, "items");
                Some(Slot::Inline(Box::new(self.leaf(child, Kind::Never))))
            }
            Some(BoolOr::Item(slot)) => {
                let mut child = pointer.clone();
                push_token(&mut child, "items");
                Some(self.slot(slot, child))
            }
        };
        let mut front = self.leaf(pointer, Kind::Array { items });
        front.title = s.title.clone();
        front.description = s.description.clone();
        front.default = s.default.clone().map(Value::Array);
        front.deprecated = s.deprecated.unwrap_or(false);
        front.read_only = s.read_only.unwrap_or(false);
        front.write_only = s.write_only.unwrap_or(false);
        front.constraints.min_items = s.min_items;
        front.constraints.max_items = s.max_items;
        front.constraints.unique_items = s.unique_items.unwrap_or(false);
        front.unsupported = catch_all_keywords(&s.extensions, &mut front.extensions);
        if prefixed && !matches!(s.items, None | Some(BoolOr::Bool(true))) {
            front.unsupported.push("items".to_owned());
        }
        front.dialect = dialect_of(&s.extensions);
        front.const_value = const_of(&s.extensions);
        front
    }

    fn object(&self, s: &ObjectSchema, pointer: String) -> FrontSchema {
        let pointer_text = pointer.clone();
        let mut properties = BTreeMap::new();
        if let Some(props) = &s.properties {
            for (name, slot) in props {
                let mut child = pointer.clone();
                push_token(&mut child, "properties");
                push_token(&mut child, name);
                properties.insert(name.clone(), self.slot(slot, child));
            }
        }
        let additional = match &s.additional_properties {
            None | Some(BoolOr::Bool(true)) => Additional::Any,
            Some(BoolOr::Bool(false)) => Additional::Denied,
            Some(BoolOr::Item(slot)) => {
                let mut child = pointer.clone();
                push_token(&mut child, "additionalProperties");
                Additional::Schema(self.slot(slot, child))
            }
        };
        let typeless = !self.type_written(&pointer);
        let mut front = self.leaf(
            pointer,
            Kind::Object {
                properties,
                required: s.required.clone().unwrap_or_default(),
                additional,
                typeless,
            },
        );
        front.title = s.title.clone();
        front.description = s.description.clone();
        front.default = s
            .default
            .clone()
            .map(|m| Value::Object(m.into_iter().collect()));
        front.deprecated = s.deprecated.unwrap_or(false);
        front.read_only = s.read_only.unwrap_or(false);
        front.write_only = s.write_only.unwrap_or(false);
        front.constraints.min_properties = s.min_properties;
        front.constraints.max_properties = s.max_properties;
        front.constraints.property_names = s.property_names.is_some();
        if s.property_names.is_some() {
            front.constraints.names = self.names(&format!("{pointer_text}/propertyNames"));
        }
        front.constraints.pattern_properties = s
            .pattern_properties
            .as_ref()
            .map(|p| p.keys().cloned().collect())
            .unwrap_or_default();
        front.discriminator = s.discriminator.clone();
        for (source, slot) in s.pattern_properties.iter().flatten() {
            let mut child = pointer_text.clone();
            push_token(&mut child, "patternProperties");
            push_token(&mut child, source);
            front
                .patterns
                .push((source.clone(), self.slot(slot, child)));
        }
        front.unsupported = catch_all_keywords(&s.extensions, &mut front.extensions);
        if s.unevaluated_properties.is_some() {
            front.unsupported.push("unevaluatedProperties".to_owned());
        }
        front.dialect = dialect_of(&s.extensions);
        front.const_value = const_of(&s.extensions);
        front
    }
}

/// Split the model's catch-all into `x-` extensions, kept, and every
/// other keyword, returned for reporting.
/// The inline item or member-value schema's constraints. Not beside
/// `patternProperties`: `additionalProperties` then speaks only of the
/// members no pattern matches, which the generated map does not separate.
/// (Beside `prefixItems`, an array has no item schema to read.)
fn items(schema: &FrontSchema) -> Option<Items> {
    let (keyword, inner) = match &schema.kind {
        Kind::Array {
            items: Some(Slot::Inline(inner)),
        } => ("items", inner),
        Kind::Object {
            additional: Additional::Schema(Slot::Inline(inner)),
            ..
        } if schema.constraints.pattern_properties.is_empty() => ("additionalProperties", inner),
        _ => return None,
    };
    let mut constraints = inner.constraints.clone();
    constraints.unsupported = inner.unsupported.clone();
    (constraints != Constraints::default()).then(|| Items {
        keyword,
        constraints: Box::new(constraints),
    })
}

/// Whether a type list's shared `enum` and `const` allow null: without
/// it, they leave it out whatever the list says.
fn shared_admits_null(object: &serde_json::Map<String, Value>) -> bool {
    let admits = |key: &str| match object.get(key) {
        Some(Value::Array(values)) if key == "enum" => values.iter().any(Value::is_null),
        Some(value) if key == "const" => value.is_null(),
        _ => true,
    };
    admits("enum") && admits("const")
}

/// A member of a type list, read as a schema of its own.
enum Member {
    Read(Box<FrontSchema>),
    /// Its `enum` or `const` admits no value of its type.
    Nothing,
    /// Its keywords do not make a schema of its type.
    Unread,
}

/// Whether `value` is an instance of `schema_type`.
fn fits(schema_type: &SchemaType, value: &Value) -> bool {
    match schema_type {
        SchemaType::String => value.is_string(),
        SchemaType::Number => value.is_number(),
        SchemaType::Integer => {
            value.is_i64() || value.is_u64() || value.as_f64().is_some_and(|f| f.fract() == 0.0)
        }
        SchemaType::Object => value.is_object(),
        SchemaType::Array => value.is_array(),
        SchemaType::Boolean => value.is_boolean(),
        SchemaType::Null => value.is_null(),
        SchemaType::Custom(_) => true,
    }
}

/// `schema` with `keywords` taken out of its catch-all.
fn without_keywords(schema: &Schema, keywords: &[String]) -> Schema {
    let mut schema = schema.clone();
    let catch_all = match &mut schema {
        Schema::Bool(_) | Schema::Empty(_) => return schema,
        Schema::AllOf(s) => &mut s.extensions,
        Schema::AnyOf(s) => &mut s.extensions,
        Schema::OneOf(s) => &mut s.extensions,
        Schema::Not(s) => &mut s.extensions,
        Schema::Multi(s) => &mut s.extensions,
        Schema::Single(single) => match single.as_mut() {
            SingleSchema::String(s) => &mut s.extensions,
            SingleSchema::Integer(s) => &mut s.extensions,
            SingleSchema::Number(s) => &mut s.extensions,
            SingleSchema::Boolean(s) => &mut s.extensions,
            SingleSchema::Array(s) => &mut s.extensions,
            SingleSchema::Null(s) => &mut s.extensions,
            SingleSchema::Object(s) => &mut s.extensions,
        },
    };
    if let Some(map) = catch_all {
        map.retain(|key, _| !keywords.contains(key));
        if map.is_empty() {
            *catch_all = None;
        }
    }
    schema
}

fn catch_all_keywords(
    extensions: &Option<BTreeMap<String, Value>>,
    keep: &mut BTreeMap<String, Value>,
) -> Vec<String> {
    let mut unsupported = Vec::new();
    if let Some(extensions) = extensions {
        for (key, value) in extensions {
            if key.starts_with("x-") {
                keep.insert(key.clone(), value.clone());
            } else if !SILENT_KEYWORDS.contains(&key.as_str()) {
                unsupported.push(key.clone());
            }
        }
    }
    unsupported
}

/// A composition's annotations: the model keeps them in its catch-all,
/// but they assert nothing, so they are read rather than reported.
fn composition_annotations(front: &mut FrontSchema, keywords: &serde_json::Map<String, Value>) {
    for key in [
        "title",
        "description",
        "deprecated",
        "readOnly",
        "writeOnly",
        "default",
        "xml",
    ] {
        let Some(value) = keywords.get(key) else {
            continue;
        };
        // A value of the wrong type is not read, and stays reported.
        match (key, value) {
            ("title", Value::String(text)) => front.title = Some(text.clone()),
            ("description", Value::String(text)) => front.description = Some(text.clone()),
            ("deprecated", Value::Bool(flag)) => front.deprecated = *flag,
            ("readOnly", Value::Bool(flag)) => front.read_only = *flag,
            ("writeOnly", Value::Bool(flag)) => front.write_only = *flag,
            ("default", value) => front.default = Some(value.clone()),
            // Serialization hints for XML, which the generated code is not.
            ("xml", _) => {}
            // A 2.0 or 3.0 model holds no such key, so it is not listed yet.
            _ => {
                if !front.unsupported.iter().any(|k| k == key) {
                    front.unsupported.push(key.to_owned());
                }
                continue;
            }
        }
        front.unsupported.retain(|k| k != key);
    }
}

fn const_of(extensions: &Option<BTreeMap<String, Value>>) -> Option<Value> {
    extensions.as_ref().and_then(|e| e.get("const")).cloned()
}

fn dialect_of(extensions: &Option<BTreeMap<String, Value>>) -> Option<String> {
    extensions
        .as_ref()
        .and_then(|e| e.get("$schema"))
        .and_then(Value::as_str)
        .map(str::to_owned)
}

/// Undo RFC 6901 escaping in one reference token.
fn unescape(token: &str) -> String {
    token.replace("~1", "/").replace("~0", "~")
}

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

    fn translate(components: Value) -> Front {
        let raw = serde_json::json!({
            "openapi": "3.2.0",
            "info": {"title": "t", "version": "1"},
            "paths": {},
            "components": {"schemas": components}
        });
        let spec: roas::v3_2::spec::Spec = serde_json::from_value(raw.clone()).unwrap();
        let uri = Url::parse("file:///t.json").unwrap();
        let translator = Translator {
            uri: &uri,
            raw: &raw,
            source_pointer: |p| p.to_owned(),
            legacy_nullable: false,
            report_lost: false,
            v3_0_source: false,
        };
        translator.translate(&spec)
    }

    fn inline(slot: &Slot) -> &FrontSchema {
        match slot {
            Slot::Inline(schema) => schema,
            Slot::Ref { .. } => panic!("expected inline"),
        }
    }

    #[test]
    fn nullable_multi_is_read_as_its_single_type() {
        let front = translate(serde_json::json!({
            "Tag": {"type": ["string", "null"], "maxLength": 5, "description": "d"}
        }));
        let tag = inline(&front.components["Tag"]);
        assert!(tag.nullable);
        assert!(matches!(tag.kind, Kind::String { .. }));
        assert_eq!(tag.constraints.max_length, Some(5));
        assert_eq!(tag.description.as_deref(), Some("d"));
        assert!(tag.unsupported.is_empty(), "{:?}", tag.unsupported);
    }

    #[test]
    fn multi_with_several_types_is_a_type_union_with_per_type_keywords() {
        let front = translate(serde_json::json!({
            "V": {"type": ["string", "integer"], "maxLength": 5, "minimum": 1}
        }));
        let v = inline(&front.components["V"]);
        let Kind::TypeUnion { branches } = &v.kind else {
            panic!("{:?}", v.kind)
        };
        assert_eq!(branches.len(), 2);
        let s = inline(&branches[0]);
        assert!(matches!(s.kind, Kind::String { .. }));
        assert_eq!(s.constraints.max_length, Some(5));
        assert!(s.unsupported.is_empty(), "{:?}", s.unsupported);
        let i = inline(&branches[1]);
        assert!(matches!(i.kind, Kind::Integer { .. }));
        assert_eq!(i.constraints.minimum, Some(serde_json::Number::from(1)));
        assert!(i.unsupported.is_empty(), "{:?}", i.unsupported);
    }

    #[test]
    fn typeless_is_detected_from_the_source() {
        let front = translate(serde_json::json!({
            "Loose": {"properties": {"a": {"type": "string"}}},
            "Tight": {"type": "object", "properties": {"a": {"type": "string"}}},
            "Anything": {"description": "no keywords"}
        }));
        let Kind::Object { typeless, .. } = inline(&front.components["Loose"]).kind else {
            panic!()
        };
        assert!(typeless);
        let Kind::Object { typeless, .. } = inline(&front.components["Tight"]).kind else {
            panic!()
        };
        assert!(!typeless);
        let Kind::Object {
            typeless,
            properties,
            ..
        } = &inline(&front.components["Anything"]).kind
        else {
            panic!()
        };
        assert!(*typeless && properties.is_empty());
    }

    #[test]
    fn unsupported_keywords_are_collected_and_extensions_kept() {
        let front = translate(serde_json::json!({
            "A": {"type": "array", "contains": {"type": "string"}, "minContains": 1, "x-mine": 1, "$comment": "c"}
        }));
        let a = inline(&front.components["A"]);
        assert_eq!(
            a.unsupported,
            vec!["contains".to_owned(), "minContains".to_owned()]
        );
        assert_eq!(a.extensions.get("x-mine"), Some(&Value::from(1)));
    }

    #[test]
    fn references_are_classified_and_siblings_kept() {
        let front = translate(serde_json::json!({
            "Pet": {"type": "object"},
            "Plain": {"$ref": "#/components/schemas/Pet", "description": "d"},
            "Narrow": {"$ref": "#/components/schemas/Pet", "maxLength": 3},
            "Elsewhere": {"$ref": "#/components/responses/X"}
        }));
        let Slot::Ref {
            target,
            siblings,
            description,
            ..
        } = &front.components["Plain"]
        else {
            panic!()
        };
        assert_eq!(*target, RefTarget::Component("Pet".into()));
        assert!(siblings.is_none());
        assert_eq!(description.as_deref(), Some("d"));
        let Slot::Ref { siblings, .. } = &front.components["Narrow"] else {
            panic!()
        };
        assert!(siblings.is_some());
        let Slot::Ref { target, .. } = &front.components["Elsewhere"] else {
            panic!()
        };
        assert!(matches!(target, RefTarget::Unsupported(_)));
    }

    #[test]
    fn additional_properties_forms() {
        let front = translate(serde_json::json!({
            "Open": {"type": "object"},
            "Closed": {"type": "object", "additionalProperties": false},
            "Typed": {"type": "object", "additionalProperties": {"type": "integer"}}
        }));
        let Kind::Object { additional, .. } = &inline(&front.components["Open"]).kind else {
            panic!()
        };
        assert!(matches!(additional, Additional::Any));
        let Kind::Object { additional, .. } = &inline(&front.components["Closed"]).kind else {
            panic!()
        };
        assert!(matches!(additional, Additional::Denied));
        let Kind::Object { additional, .. } = &inline(&front.components["Typed"]).kind else {
            panic!()
        };
        assert!(matches!(additional, Additional::Schema(_)));
    }

    #[test]
    fn custom_integer_and_number_formats_lower_to_unconstrained_width() {
        let front = translate(serde_json::json!({
            "U32": {"type": "integer", "format": "uint32"},
            "Dec": {"type": "number", "format": "decimal"}
        }));
        let Kind::Integer { width, .. } = &inline(&front.components["U32"]).kind else {
            panic!()
        };
        assert_eq!(*width, None);
        let Kind::Number { width, .. } = &inline(&front.components["Dec"]).kind else {
            panic!()
        };
        assert_eq!(*width, None);
    }
}