kynos-openapi 0.1.0

OpenAPI 3.1 and 3.2 document model, serialization and validation.
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
use crate::{
    emit::downgrade,
    model::{
        document::{Document, SpecVersion},
        info::Info,
    },
};

fn document() -> Document {
    Document::new(SpecVersion::V3_1, Info::new("Orders", "1.0.0"))
}

/// A document with nothing in it still declares `paths`.
///
/// Not a stylistic choice: every version requires at least one of `paths`,
/// `components` or `webhooks`, so a document that skipped all three violated a
/// MUST. An empty Paths Object is the honest one of the three to write -- the
/// specification's "Security Filtering" section gives it the meaning "you are
/// in the right place and there is nothing here to show you".
#[test]
fn a_bare_document_declares_paths_and_nothing_else() {
    let json = document().to_json().expect("serializable");
    assert!(json.contains(r#""openapi": "3.1.2""#));
    assert!(json.contains(r#""title": "Orders""#));
    assert!(json.contains(r#""paths": {}"#));
    assert!(!json.contains("components"));
}

#[test]
fn emitting_the_declared_version_is_a_no_op() {
    let emitted = document()
        .emit(SpecVersion::V3_1)
        .expect("no 3.2 constructs");
    assert_eq!(emitted.openapi, "3.1.2");
}

#[test]
fn a_document_using_no_three_two_construct_has_no_blockers() {
    assert!(downgrade::three_two_only_constructs(&document()).is_empty());
}

/// One case per 3.2-only construct, and the exact location it is reported at.
///
/// `properties.rs` checks emission against `three_two_only_constructs` itself:
/// `emit(V3_1)` succeeds exactly when that function returns nothing, and the
/// error carries whatever it returned. So the property agrees with the function
/// by construction, including where the function is wrong. A construct it
/// forgets to look for is a document that silently emits as 3.1 while using a
/// keyword 3.1 has no way to read — and every test in the crate passes.
///
/// These cases are what the property cannot be: each builds a document using
/// exactly one 3.2 construct and states, independently, where that construct
/// lives. The location strings are the product here, since they are what a
/// caller is shown.
#[cfg(feature = "openapi32")]
mod blockers {
    use std::{collections::BTreeSet, fs, path::Path};

    use super::document;
    use crate::{
        emit::downgrade::three_two_only_constructs,
        model::{
            body::{encoding::Encoding, media_type::MediaType},
            components::ComponentName,
            document::{Document, SpecVersion},
            example::Example,
            parameter::{Parameter, ParameterIn, style::Style},
            paths::{item::PathItem, method::Method, operation::Operation, template::PathTemplate},
            reference::RefOr,
            response::{Response, Responses},
            schema::{Schema, discriminator::Discriminator, object::SchemaObject, xml::Xml},
            security::{
                SecurityScheme,
                oauth::{OAuthFlow, OAuthFlows},
            },
            server::Server,
            tag::Tag,
        },
        validate::violation::SpecError,
    };

    /// A document holding one operation, with `build` applied to it.
    fn with_operation(build: impl FnOnce(Operation) -> Operation) -> Document {
        let mut document = document();
        let template = PathTemplate::parse("/orders").expect("a valid template");
        document.paths.insert(
            &template,
            PathItem::new().with_operation(Method::Get, build(Operation::default())),
        );
        document
    }

    /// A document whose one operation sends `content` as its request body.
    fn with_request_content(content: MediaType) -> Document {
        with_operation(|operation| {
            operation.with_request_body(crate::model::body::RequestBody::new(
                "application/json",
                content,
            ))
        })
    }

    /// The location a media-type construct is reported at.
    fn in_request_body(field: &str) -> String {
        format!("#/paths/~1orders/get/requestBody/content/application~1json/{field}")
    }

    /// A document defining one security scheme under `Guard`.
    fn with_security_scheme(scheme: SecurityScheme) -> Document {
        let mut document = document();
        document.components.insert_security_scheme(
            &ComponentName::new("Guard").expect("a legal component key"),
            scheme,
        );
        document
    }

    /// The location a security-scheme construct is reported at.
    fn in_security_scheme(field: &str) -> String {
        format!("#/components/securitySchemes/Guard/{field}")
    }

    /// An OAuth 2.0 scheme carrying exactly `flows`.
    fn oauth2(flows: OAuthFlows) -> SecurityScheme {
        SecurityScheme::OAuth2 {
            flows: Box::new(flows),
            oauth2_metadata_url: None,
            description: None,
            deprecated: None,
            extensions: crate::model::extensions::Extensions::new(),
        }
    }

    /// One group per `blockers.push` site in `downgrade.rs`, each holding a row
    /// per construct that site reports.
    ///
    /// Grouped rather than flat so the count below means something: two sites
    /// report three fields apiece from a loop, and a flat list could not be
    /// compared against the sites.
    // Long because it is a table, not a procedure: one row per construct the
    // downgrade reports, and the count below is only meaningful if every one is
    // written out here.
    #[expect(clippy::too_many_lines)]
    fn ledger() -> Vec<Vec<(Document, String)>> {
        vec![
            vec![(
                Document {
                    self_uri: Some("https://example.com/orders".to_owned()),
                    ..document()
                },
                "#/$self".to_owned(),
            )],
            vec![(
                Document {
                    servers: vec![Server {
                        name: Some("eu".to_owned()),
                        ..Server::new("https://example.com")
                    }],
                    ..document()
                },
                "#/servers/0/name".to_owned(),
            )],
            vec![
                (
                    Document {
                        tags: vec![Tag {
                            summary: Some("Orders".to_owned()),
                            ..Tag::new("orders")
                        }],
                        ..document()
                    },
                    "#/tags/0/summary".to_owned(),
                ),
                (
                    Document {
                        tags: vec![Tag::new("orders").with_parent("root")],
                        ..document()
                    },
                    "#/tags/0/parent".to_owned(),
                ),
                (
                    Document {
                        tags: vec![Tag::new("orders").with_kind("nav")],
                        ..document()
                    },
                    "#/tags/0/kind".to_owned(),
                ),
            ],
            vec![(
                {
                    let mut document = document();
                    document.components.media_types.insert(
                        "application/json".to_owned(),
                        RefOr::Item(MediaType::new(Schema::any())),
                    );
                    document
                },
                "#/components/mediaTypes".to_owned(),
            )],
            vec![(
                {
                    let mut document = document();
                    let template = PathTemplate::parse("/orders").expect("a valid template");
                    document.paths.insert(
                        &template,
                        PathItem {
                            query: Some(Box::new(Operation::default())),
                            ..PathItem::new()
                        },
                    );
                    document
                },
                "#/paths/~1orders/query".to_owned(),
            )],
            vec![(
                {
                    let mut document = document();
                    let template = PathTemplate::parse("/orders").expect("a valid template");
                    let mut item = PathItem::new();
                    item.additional_operations
                        .insert("PURGE".to_owned(), Box::new(Operation::default()));
                    document.paths.insert(&template, item);
                    document
                },
                "#/paths/~1orders/additionalOperations".to_owned(),
            )],
            vec![(
                with_operation(|operation| {
                    operation.with_parameter(Parameter::new(
                        "filter",
                        ParameterIn::Querystring,
                        Schema::any(),
                    ))
                }),
                "#/paths/~1orders/get/parameters/filter".to_owned(),
            )],
            vec![(
                with_operation(|operation| {
                    operation.with_parameter(
                        Parameter::header("session", Schema::any())
                            .with_style(Style::Cookie, false),
                    )
                }),
                "#/paths/~1orders/get/parameters/session/style".to_owned(),
            )],
            vec![(
                with_operation(|operation| {
                    operation.with_responses(Responses::new().with(
                        200,
                        Response {
                            summary: Some("Created".to_owned()),
                            ..Response::new("ok")
                        },
                    ))
                }),
                "#/paths/~1orders/get/responses/200/summary".to_owned(),
            )],
            vec![
                (
                    with_request_content(MediaType::sequential(Schema::any())),
                    in_request_body("itemSchema"),
                ),
                (
                    with_request_content({
                        let mut content = MediaType::new(Schema::any());
                        content.prefix_encoding = Some(vec![Encoding::new("text/plain")]);
                        content
                    }),
                    in_request_body("prefixEncoding"),
                ),
                (
                    with_request_content({
                        let mut content = MediaType::new(Schema::any());
                        content.item_encoding = Some(Box::new(Encoding::new("text/plain")));
                        content
                    }),
                    in_request_body("itemEncoding"),
                ),
            ],
            // A security scheme's own 3.2 fields. `deprecated` is on all five
            // variants, so one row apiece: a walk that visited only the variant
            // it was written against would pass a single row and still let the
            // other four through.
            vec![
                (
                    with_security_scheme(SecurityScheme::ApiKey {
                        name: "X-Api-Key".to_owned(),
                        location: ParameterIn::Header,
                        description: None,
                        deprecated: Some(true),
                        extensions: crate::model::extensions::Extensions::new(),
                    }),
                    in_security_scheme("deprecated"),
                ),
                (
                    with_security_scheme(SecurityScheme::Http {
                        scheme: "bearer".to_owned(),
                        bearer_format: None,
                        description: None,
                        deprecated: Some(true),
                        extensions: crate::model::extensions::Extensions::new(),
                    }),
                    in_security_scheme("deprecated"),
                ),
                (
                    with_security_scheme(SecurityScheme::MutualTls {
                        description: None,
                        deprecated: Some(true),
                        extensions: crate::model::extensions::Extensions::new(),
                    }),
                    in_security_scheme("deprecated"),
                ),
                (
                    with_security_scheme(SecurityScheme::OpenIdConnect {
                        open_id_connect_url: "https://auth.example.com/.well-known".to_owned(),
                        description: None,
                        deprecated: Some(true),
                        extensions: crate::model::extensions::Extensions::new(),
                    }),
                    in_security_scheme("deprecated"),
                ),
                (
                    with_security_scheme(SecurityScheme::OAuth2 {
                        flows: Box::new(OAuthFlows::default()),
                        oauth2_metadata_url: None,
                        description: None,
                        deprecated: Some(true),
                        extensions: crate::model::extensions::Extensions::new(),
                    }),
                    in_security_scheme("deprecated"),
                ),
            ],
            vec![(
                with_security_scheme(SecurityScheme::OAuth2 {
                    flows: Box::new(OAuthFlows::default()),
                    oauth2_metadata_url: Some(
                        "https://auth.example.com/.well-known/oauth-authorization-server"
                            .to_owned(),
                    ),
                    description: None,
                    deprecated: None,
                    extensions: crate::model::extensions::Extensions::new(),
                }),
                in_security_scheme("oauth2MetadataUrl"),
            )],
            vec![(
                with_security_scheme(oauth2(OAuthFlows {
                    device_authorization: Some(OAuthFlow::new([(
                        "orders:read".to_owned(),
                        "Read orders".to_owned(),
                    )])),
                    ..OAuthFlows::default()
                })),
                in_security_scheme("flows/deviceAuthorization"),
            )],
            // The URL on a flow 3.1 *can* express, so the flow is not the
            // blocker and the field is. Without this row a walk could report
            // the whole `deviceAuthorization` flow and miss the field wherever
            // it rides on one of the four older flows.
            vec![(
                with_security_scheme(oauth2(OAuthFlows {
                    authorization_code: Some(OAuthFlow {
                        device_authorization_url: Some(
                            "https://auth.example.com/device".to_owned(),
                        ),
                        ..OAuthFlow::new([("orders:read".to_owned(), "Read orders".to_owned())])
                    }),
                    ..OAuthFlows::default()
                })),
                in_security_scheme("flows/authorizationCode/deviceAuthorizationUrl"),
            )],
            // The Encoding Object's own three fields, which share their names
            // with the three the Media Type Object carries. A walk that stops
            // at the media type sees neither the nested `encoding` map nor the
            // two positional fields beneath it.
            vec![
                (
                    with_request_content(
                        MediaType::new(Schema::any()).with_encoding(
                            "part",
                            Encoding {
                                encoding: [("inner".to_owned(), Encoding::new("text/plain"))]
                                    .into_iter()
                                    .collect(),
                                ..Encoding::new("multipart/mixed")
                            },
                        ),
                    ),
                    in_request_body("encoding/part/encoding"),
                ),
                (
                    with_request_content(MediaType::new(Schema::any()).with_encoding(
                        "part",
                        Encoding {
                            prefix_encoding: Some(vec![Encoding::new("text/plain")]),
                            ..Encoding::new("multipart/mixed")
                        },
                    )),
                    in_request_body("encoding/part/prefixEncoding"),
                ),
                (
                    with_request_content(MediaType::new(Schema::any()).with_encoding(
                        "part",
                        Encoding {
                            item_encoding: Some(Box::new(Encoding::new("text/plain"))),
                            ..Encoding::new("multipart/mixed")
                        },
                    )),
                    in_request_body("encoding/part/itemEncoding"),
                ),
            ],
            // The two example fields 3.2 added beside `value`. `data_external`
            // is its own row because `externalValue` is a field 3.1 *can*
            // express, so the value is not the blocker and `dataValue` riding
            // on it is.
            vec![
                (
                    with_request_content(
                        MediaType::new(Schema::any())
                            .with_named_example("e", Example::data(serde_json::json!({"id": 1}))),
                    ),
                    in_request_body("examples/e/dataValue"),
                ),
                (
                    with_request_content(
                        MediaType::new(Schema::any())
                            .with_named_example("e", Example::serialized("id=1")),
                    ),
                    in_request_body("examples/e/serializedValue"),
                ),
                (
                    with_request_content(MediaType::new(Schema::any()).with_named_example(
                        "e",
                        Example::data_external(
                            serde_json::json!({"id": 1}),
                            "https://example.com/e.json",
                        ),
                    )),
                    in_request_body("examples/e/dataValue"),
                ),
            ],
            // Inside a Schema Object, which the walk did not enter at all.
            // Neither name is an `x-` extension, so 3.1 has no way to read
            // either -- even though 3.1 leaves the schema subtree open enough
            // that its own meta-schema does not object.
            vec![
                (
                    with_request_content(MediaType::new(Schema::Object(Box::new(SchemaObject {
                        xml: Some(Xml {
                            node_type: Some("element".to_owned()),
                            ..Xml::default()
                        }),
                        ..SchemaObject::default()
                    })))),
                    in_request_body("schema/xml/nodeType"),
                ),
                (
                    with_request_content(MediaType::new(Schema::Object(Box::new(SchemaObject {
                        discriminator: Some(Discriminator {
                            default_mapping: Some("#/components/schemas/Fallback".to_owned()),
                            ..Discriminator::new("kind")
                        }),
                        ..SchemaObject::default()
                    })))),
                    in_request_body("schema/discriminator/defaultMapping"),
                ),
            ],
        ]
    }

    #[test]
    fn each_construct_is_reported_at_the_location_it_lives_at() {
        for (document, expected) in ledger().into_iter().flatten() {
            assert_eq!(
                three_two_only_constructs(&document),
                vec![expected],
                "a document using only this construct must report only it"
            );
        }
    }

    /// The blockers reach the caller, rather than only the collector.
    #[test]
    fn a_document_using_one_refuses_to_emit_as_three_one() {
        for (document, expected) in ledger().into_iter().flatten() {
            let error = document
                .emit(SpecVersion::V3_1)
                .expect_err("a 3.2 construct cannot be emitted as 3.1");

            assert_eq!(
                error,
                SpecError::RequiresV3_2 {
                    blockers: vec![expected],
                }
            );
        }
    }

    /// Every wire name the model gates behind `openapi32`, read from `model/`.
    ///
    /// A field is a gate followed, past any attributes and documentation, by a
    /// field declaration; its wire name is its `rename` where it has one and
    /// its identifier otherwise. Gates introducing an enum variant, a match
    /// arm, an `impl` or a function are skipped -- they are not wire names.
    // Long because it is a scanner: each rule it applies is a nested helper
    // stated where it is used, which reads better here than four private
    // functions at module scope with nothing else calling them.
    #[expect(clippy::too_many_lines)]
    fn gated_wire_names() -> BTreeSet<String> {
        const GATE: &str = "#[cfg(feature = \"openapi32\")]";

        fn walk(directory: &Path, names: &mut BTreeSet<String>) {
            let entries = fs::read_dir(directory).expect("the model sources are beside this test");
            for entry in entries.map(|entry| entry.expect("a readable directory entry")) {
                let path = entry.path();
                if path.is_dir() {
                    walk(&path, names);
                } else if path.extension().is_some_and(|ext| ext == "rs") {
                    collect(
                        &fs::read_to_string(&path).expect("a readable source file"),
                        names,
                    );
                }
            }
        }

        fn collect(source: &str, names: &mut BTreeSet<String>) {
            let lines: Vec<&str> = source.lines().map(str::trim).collect();
            for (index, line) in lines.iter().enumerate() {
                if *line != GATE {
                    continue;
                }

                // Step past the attributes and documentation between the gate
                // and whatever it gates, tracking brackets so a `#[serde(..)]`
                // written over several lines is one step rather than several.
                let mut cursor = index + 1;
                let mut depth = 0i32;
                while let Some(current) = lines.get(cursor) {
                    let open = current.matches('[').count() + current.matches('(').count();
                    let close = current.matches(']').count() + current.matches(')').count();
                    let attribute = depth > 0 || current.starts_with("#[");
                    if !attribute && !current.starts_with("//") && !current.is_empty() {
                        break;
                    }
                    depth += i32::try_from(open).expect("a short line")
                        - i32::try_from(close).expect("a short line");
                    cursor += 1;
                }

                let Some(declaration) = lines.get(cursor) else {
                    continue;
                };
                let Some(identifier) = field_identifier(declaration) else {
                    continue;
                };

                // A field only carries its own identifier to the wire when
                // serde drives the type declaring it. `ExampleValue` is the
                // model's one exception: it is a domain enum with no serde
                // derive, converted through `RawExample`, so its `data` field
                // is written as `dataValue` and looking for `data` would ask
                // the downgrade for a name no document ever contains.
                if !declared_in_a_serde_item(&lines, index) {
                    continue;
                }

                let attributes = lines[index + 1..cursor].join(" ");
                names.insert(rename_in(&attributes).unwrap_or_else(|| camel_case(&identifier)));
            }
        }

        /// Whether the type enclosing the gate at `gate` is serde-derived.
        ///
        /// The enclosing type is the nearest `struct` or `enum` header above
        /// the gate, and its derives are the attribute run directly above that
        /// header.
        fn declared_in_a_serde_item(lines: &[&str], gate: usize) -> bool {
            let header = lines[..gate].iter().rposition(|line| {
                let declaration = line.strip_prefix("pub ").unwrap_or(line);
                declaration.starts_with("enum ") || declaration.starts_with("struct ")
            });
            let Some(header) = header else {
                return false;
            };

            lines[..header]
                .iter()
                .rev()
                .take_while(|line| line.starts_with("#[") || line.starts_with("//"))
                .any(|line| line.contains("Serialize"))
        }

        /// The identifier of `line` when it *declares* a field.
        ///
        /// Nothing for a variant, an arm, or any other item a gate may sit
        /// above -- and nothing for a field *initializer*, which shares the
        /// `name: rest` shape. The two are told apart by what follows the
        /// colon: a declaration names a type, an initializer gives a value.
        fn field_identifier(line: &str) -> Option<String> {
            let declaration = line.strip_prefix("pub ").unwrap_or(line);
            let (identifier, rest) = declaration.split_once(": ")?;
            let identifier = identifier.trim();

            let names_a_type = rest.starts_with(|c: char| c.is_ascii_uppercase())
                || ["bool", "u16", "u32", "u64", "f64", "usize", "String"]
                    .iter()
                    .any(|primitive| rest.starts_with(primitive));
            let names_a_field = !identifier.is_empty()
                && identifier.starts_with(|c: char| c.is_ascii_lowercase() || c == '_')
                && identifier
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '_');

            (names_a_type && names_a_field && line.ends_with(',')).then(|| identifier.to_owned())
        }

        /// A field identifier as the wire spells it when no `rename` says
        /// otherwise. Every renamed field in this model is renamed to the
        /// camelCase of its identifier, and a single-word identifier is its own
        /// camelCase -- so this is the same rule read from the other side, and
        /// it is what lets the domain struct and the wire struct that carries
        /// the `rename` agree on one name.
        fn camel_case(identifier: &str) -> String {
            let mut camel = String::with_capacity(identifier.len());
            let mut capitalize = false;
            for character in identifier.chars() {
                if character == '_' {
                    capitalize = true;
                } else if capitalize {
                    camel.extend(character.to_uppercase());
                    capitalize = false;
                } else {
                    camel.push(character);
                }
            }
            camel
        }

        /// The `rename = "..."` value within a run of attributes.
        fn rename_in(attributes: &str) -> Option<String> {
            let (_, rest) = attributes.split_once("rename = \"")?;
            let (value, _) = rest.split_once('"')?;
            Some(value.to_owned())
        }

        let mut names = BTreeSet::new();
        walk(
            &Path::new(env!("CARGO_MANIFEST_DIR")).join("src/model"),
            &mut names,
        );
        assert!(
            !names.is_empty(),
            "the scan found no gated field, so it is measuring nothing"
        );
        names
    }

    /// Every 3.2 field the model can hold is one the downgrade reports.
    ///
    /// The anchor here is the *model*, and that is the whole point. This test
    /// counted `blockers.push` sites in `downgrade.rs` against the ledger,
    /// which proves every blocker has a case -- the converse of what has to
    /// hold. A field added with no blocker is exactly the document that emits
    /// as 3.1 while carrying a keyword 3.1 cannot read, and a reporter counted
    /// against itself can never see one. Five fields had slipped through when
    /// this was written.
    ///
    /// Names are matched against the string literals `downgrade.rs` builds its
    /// locations from, rather than against its source text, so an identifier
    /// that merely happens to share a field's spelling does not satisfy it.
    ///
    /// A name has to be a whole *segment* of some literal, not a substring of
    /// one. Substring matching is how `Server.name` passed this test while
    /// three of the four positions a Server Object hangs in went unread: `name`
    /// is a substring of `#/servers/{index}/name`, so the shortest field names
    /// — `name`, `kind`, `query`, `encoding` — were satisfied by any literal
    /// that happened to contain them. Splitting on `/` costs nothing and makes
    /// the check say what it always meant.
    #[test]
    fn every_three_two_field_is_reported() {
        // Both halves: the entry point holds the document-level segments and
        // `walk.rs` holds every nested one, so reading only the first would
        // let this pass on a fraction of the locations it is counting.
        const REPORTER: &str = concat!(
            include_str!("downgrade.rs"),
            include_str!("downgrade/walk.rs")
        );

        let segments: BTreeSet<&str> = REPORTER
            .split('"')
            .skip(1)
            .step_by(2)
            .flat_map(|literal| literal.split('/'))
            .collect();

        let unreported: Vec<String> = gated_wire_names()
            .into_iter()
            .filter(|name| !segments.contains(name.as_str()))
            .collect();

        assert!(
            unreported.is_empty(),
            "the model gates {unreported:?} behind `openapi32` and the downgrade names \
             none of them as a location segment, so a document carrying one emits as 3.1 \
             with no complaint"
        );
    }

    /// Every construct the downgrade reports is exercised by a ledger row.
    ///
    /// The counterpart to the test above, and the weaker direction: it keeps a
    /// reporting site from losing the case that proves what it says.
    #[test]
    fn every_construct_has_a_case() {
        // Both halves, for the reason the test above gives: every reporting
        // site is in `walk.rs`, so counting only the entry point would count
        // almost none of them and pass by comparing zero against zero.
        const SOURCE: &str = concat!(
            include_str!("downgrade.rs"),
            include_str!("downgrade/walk.rs")
        );

        let sites = SOURCE.matches("blockers.push(").count();
        assert_eq!(
            ledger().len(),
            sites,
            "`downgrade.rs` reports from {sites} site(s) and {} are covered; a construct added \
             without a case is one that can stop being detected, which makes a 3.2 document emit \
             as 3.1 with no complaint",
            ledger().len()
        );
    }
}

/// Every container a 3.2 construct can sit in is one the downgrade walks.
///
/// The ledger beside this proves each construct is *recognised*; this proves
/// each is *reached*. They are different failures with the same consequence,
/// and the second is invisible to the first: a construct with a perfectly good
/// blocker still emits as 3.1 if the walk never arrives at the object holding
/// it. The walk reached `paths` and `components.securitySchemes` and nothing
/// else, so a webhook, a reusable component, a hoisted path-item parameter, a
/// callback and a `default` response were all exempt.
///
/// One planted construct per container, chosen for being unambiguous rather
/// than for being interesting -- what is under test is the route to it.
#[cfg(feature = "openapi32")]
mod reach {
    use super::document;
    use crate::model::{
        body::{RequestBody, media_type::MediaType},
        callback::Callback,
        components::ComponentName,
        document::{Document, SpecVersion},
        example::Example,
        parameter::{Parameter, ParameterIn, header::Header},
        paths::{item::PathItem, method::Method, operation::Operation, template::PathTemplate},
        reference::RefOr,
        response::{Response, Responses},
        schema::Schema,
    };

    /// A component key, which every case below needs and none varies.
    fn key() -> ComponentName {
        ComponentName::new("Reused").expect("a legal component key")
    }

    /// A response carrying the 3.2 `summary` field.
    fn summarised() -> Response {
        Response {
            summary: Some("The order".to_owned()),
            ..Response::new("ok")
        }
    }

    /// A path item whose one operation answers with [`summarised`].
    fn item_with_summarised_response() -> PathItem {
        PathItem::new().with_operation(
            Method::Get,
            Operation {
                responses: Responses::new().with(200, summarised()),
                ..Operation::default()
            },
        )
    }

    /// A media type describing a sequential body, which is 3.2-only.
    fn sequential() -> MediaType {
        MediaType::sequential(Schema::any())
    }

    // Long for the reason `ledger` above is: one row per container, written
    // out rather than generated, because the count of them is the coverage.
    #[expect(clippy::too_many_lines)]
    fn cases() -> Vec<(&'static str, Document, String)> {
        let mut cases = Vec::new();
        let orders = PathTemplate::parse("/orders").expect("a valid template");

        cases.push((
            "webhooks",
            {
                let mut document = document();
                document
                    .webhooks
                    .insert("orderPlaced".to_owned(), item_with_summarised_response());
                document
            },
            "#/webhooks/orderPlaced/get/responses/200/summary".to_owned(),
        ));

        cases.push((
            "components.pathItems",
            {
                let mut document = document();
                document
                    .components
                    .path_items
                    .insert("Shared".to_owned(), item_with_summarised_response());
                document
            },
            "#/components/pathItems/Shared/get/responses/200/summary".to_owned(),
        ));

        cases.push((
            "components.responses",
            {
                let mut document = document();
                document
                    .components
                    .responses
                    .insert(key().to_string(), RefOr::Item(summarised()));
                document
            },
            "#/components/responses/Reused/summary".to_owned(),
        ));

        cases.push((
            "components.parameters",
            {
                let mut document = document();
                document.components.parameters.insert(
                    key().to_string(),
                    RefOr::Item(Parameter::new("q", ParameterIn::Querystring, Schema::any())),
                );
                document
            },
            "#/components/parameters/Reused".to_owned(),
        ));

        cases.push((
            "components.requestBodies",
            {
                let mut document = document();
                document.components.request_bodies.insert(
                    key().to_string(),
                    RefOr::Item(RequestBody::new("application/json", sequential())),
                );
                document
            },
            "#/components/requestBodies/Reused/content/application~1json/itemSchema".to_owned(),
        ));

        cases.push((
            "components.headers",
            {
                let mut document = document();
                document.components.headers.insert(
                    key().to_string(),
                    RefOr::Item(Header::with_content("application/json", sequential())),
                );
                document
            },
            "#/components/headers/Reused/content/application~1json/itemSchema".to_owned(),
        ));

        cases.push((
            "components.examples",
            {
                let mut document = document();
                document
                    .components
                    .examples
                    .insert(key().to_string(), RefOr::Item(Example::serialized("id=1")));
                document
            },
            "#/components/examples/Reused/serializedValue".to_owned(),
        ));

        cases.push((
            "components.callbacks",
            {
                let mut document = document();
                let mut callback = Callback::new();
                callback.items.insert(
                    "{$request.body#/url}".to_owned(),
                    RefOr::Item(item_with_summarised_response()),
                );
                document
                    .components
                    .callbacks
                    .insert(key().to_string(), RefOr::Item(callback));
                document
            },
            "#/components/callbacks/Reused/{$request.body#~1url}/get/responses/200/summary"
                .to_owned(),
        ));

        cases.push((
            "pathItem.parameters",
            {
                let mut document = document();
                document.paths.insert(
                    &orders,
                    PathItem {
                        parameters: vec![RefOr::Item(Parameter::new(
                            "q",
                            ParameterIn::Querystring,
                            Schema::any(),
                        ))],
                        ..PathItem::new()
                    },
                );
                document
            },
            "#/paths/~1orders/parameters/q".to_owned(),
        ));

        cases.push((
            "operation.callbacks",
            {
                let mut document = document();
                let mut callback = Callback::new();
                callback.items.insert(
                    "{$request.body#/url}".to_owned(),
                    RefOr::Item(item_with_summarised_response()),
                );
                document.paths.insert(
                    &orders,
                    PathItem::new().with_operation(
                        Method::Get,
                        Operation {
                            callbacks: [("onData".to_owned(), RefOr::Item(callback))]
                                .into_iter()
                                .collect(),
                            ..Operation::default()
                        },
                    ),
                );
                document
            },
            "#/paths/~1orders/get/callbacks/onData/{$request.body#~1url}/get/responses/200/summary"
                .to_owned(),
        ));

        cases.push((
            "responses.default",
            {
                let mut document = document();
                document.paths.insert(
                    &orders,
                    PathItem::new().with_operation(
                        Method::Get,
                        Operation {
                            responses: Responses::new().with_default(summarised()),
                            ..Operation::default()
                        },
                    ),
                );
                document
            },
            "#/paths/~1orders/get/responses/default/summary".to_owned(),
        ));

        cases
    }

    #[test]
    fn every_container_is_walked() {
        for (container, document, expected) in cases() {
            assert_eq!(
                crate::emit::downgrade::three_two_only_constructs(&document),
                vec![expected],
                "a 3.2 construct in `{container}` must be found and reported there"
            );
        }
    }

    #[test]
    fn a_construct_in_any_container_refuses_to_emit_as_three_one() {
        for (container, document, _) in cases() {
            document.emit(SpecVersion::V3_1).expect_err(container);
        }
    }
}

/// Every position a 3.2 *field* can occupy is one the downgrade reads.
///
/// `reach` above plants one construct per container and proves the walk
/// arrives; this fixes the container and varies the *position within it*. The
/// two fail differently, and the second is invisible to the first: a walk can
/// reach an object and still never read the field, because reading it is a
/// separate line from arriving at it.
///
/// `Server.name` is the field that shows the difference. A Server Object hangs
/// in four places — the document root, a Path Item, an Operation and a Link —
/// and only the first was read, so a `name` written in any of the other three
/// emitted under `openapi: 3.1.2` carrying a field 3.1 does not define. The
/// 3.1 meta-schema sets `unevaluatedProperties: false` on `$defs/server`, so
/// what came out was not merely over-described; it was invalid.
///
/// `every_three_two_field_is_reported` could not see this. It asks whether a
/// gated wire name appears among `downgrade.rs`'s string literals, and `name`
/// is a substring of `#/servers/{index}/name` — so the field counted as
/// reported on the strength of the one position that did read it.
#[cfg(feature = "openapi32")]
mod positions {
    use super::document;
    use crate::model::{
        document::{Document, SpecVersion},
        link::Link,
        paths::{item::PathItem, method::Method, operation::Operation, template::PathTemplate},
        reference::RefOr,
        response::{Response, Responses},
        server::Server,
    };

    /// A server carrying the 3.2 `name`, and nothing else 3.2.
    fn named() -> Server {
        Server {
            name: Some("production".to_owned()),
            ..Server::new("https://api.example.com")
        }
    }

    /// One case per position, written out rather than generated: the count of
    /// them is the coverage, as it is in `reach`.
    fn cases() -> Vec<(&'static str, Document, String)> {
        let orders = PathTemplate::parse("/orders").expect("a valid template");
        let mut cases = Vec::new();

        cases.push((
            "the document root",
            {
                let mut document = document();
                document.servers.push(named());
                document
            },
            "#/servers/0/name".to_owned(),
        ));

        cases.push((
            "a path item",
            {
                let mut document = document();
                document.paths.insert(
                    &orders,
                    PathItem {
                        servers: vec![named()],
                        ..PathItem::new()
                    },
                );
                document
            },
            "#/paths/~1orders/servers/0/name".to_owned(),
        ));

        cases.push((
            "an operation",
            {
                let mut document = document();
                document.paths.insert(
                    &orders,
                    PathItem::new().with_operation(
                        Method::Get,
                        Operation {
                            servers: vec![named()],
                            ..Operation::default()
                        },
                    ),
                );
                document
            },
            "#/paths/~1orders/get/servers/0/name".to_owned(),
        ));

        cases.push((
            "a link on a response",
            {
                let mut document = document();
                // `Link::target` is private, so the update syntax the other
                // cases use is unavailable; `server` is a public field.
                let mut link = Link::to_operation("getOrder");
                link.server = Some(named());
                let response = Response {
                    links: [("next".to_owned(), RefOr::Item(link))]
                        .into_iter()
                        .collect(),
                    ..Response::new("ok")
                };
                document.paths.insert(
                    &orders,
                    PathItem::new().with_operation(
                        Method::Get,
                        Operation {
                            responses: Responses::new().with(200, response),
                            ..Operation::default()
                        },
                    ),
                );
                document
            },
            "#/paths/~1orders/get/responses/200/links/next/server/name".to_owned(),
        ));

        cases
    }

    #[test]
    fn every_position_a_server_hangs_in_is_read() {
        for (position, document, expected) in cases() {
            assert_eq!(
                crate::emit::downgrade::three_two_only_constructs(&document),
                vec![expected],
                "a 3.2 `Server.name` in {position} must be found and reported there"
            );
        }
    }

    #[test]
    fn a_named_server_in_any_position_refuses_to_emit_as_three_one() {
        for (position, document, _) in cases() {
            document.emit(SpecVersion::V3_1).expect_err(position);
        }
    }
}