typed-openapi 0.0.2

Typed Rust calls and a clap command tree from one OpenAPI document, with every write behind a dry-run gate.
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
//! `OperationId`, one typed method per operation, and the inventory a
//! hand-written operation asserts against.
//!
//! A wrapper is four lines and holds no path template, no query rule and no
//! encoder: it names an `OperationId` variant, names the arguments under the
//! document's own names, and hands the result to the one request builder a CLI
//! also uses. That is why nothing here restates what `types.rs` already says.
//!
//! `OperationId` is the reason the wrappers cannot name an operation the
//! document lacks: it is generated from the document, in the document's own
//! order, so it is a closed set that `Api::new` pairs with the embedded
//! document once. It also carries the one fact the runtime crate cannot know —
//! which Rust type each operation's body is — as `check_body`, so a
//! `--json-body` file is held to the same schema a Rust caller is.

use heck::{ToPascalCase, ToSnakeCase};
use openapiv3::{OpenAPI, ReferenceOr, Schema, SchemaKind, StatusCode, Type};
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};
use syn::visit_mut::VisitMut as _;

use super::GenerateError;
use super::names::Names;
use crate::model::{Body, Shape};
use crate::{Document, Operation};

/// What one operation contributes to the generated file.
struct Emitted {
    /// `(operationId, method, path)` — one row of the generated `OPERATIONS`.
    row: TokenStream,
    /// The `OperationId` variant.
    variant: Ident,
    /// The `operationId`, as the document spells it.
    id: String,
    /// The group a CLI mounts it under.
    group: String,
    /// The subcommand name under that group.
    command: String,
    /// The Rust type of its JSON request body, when it has one.
    body: Option<TokenStream>,
    /// The typed wrapper, `impl Api`.
    method: TokenStream,
    /// The same call with its arguments named, in the `builder` block beside
    /// it. It delegates rather than repeating the body, so the two cannot
    /// describe different requests.
    builder_method: TokenStream,
}

/// A document element this generator has no Rust spelling for.
fn unsupported(reason: impl Into<String>) -> GenerateError {
    GenerateError::Unsupported(reason.into())
}

pub(super) fn emit(
    api: &OpenAPI,
    model: &Document,
    header: &str,
    names: &Names,
) -> Result<String, GenerateError> {
    let ops = gather(api, model, names)?;
    let operation_id = operation_id(&ops);
    let inventory = inventory(&ops);
    let methods = ops.iter().map(|op| &op.method);
    let builder_methods = ops.iter().map(|op| &op.builder_method);
    let mut file: syn::File = syn::parse2(quote! {
        use typed_openapi::{Part, Values};

        use crate::{Api, Call, Error, NoContent};

        #operation_id
        #inventory

        impl Api {
            #(#methods)*
        }

        #[cfg(feature = "builder")]
        #[::typed_openapi::bon::bon(crate = ::typed_openapi::bon)]
        impl Api {
            #(#builder_methods)*
        }
    })
    .map_err(|source| GenerateError::NotRust {
        file: "ops.rs",
        source,
    })?;
    // A summary and a description are the vendor's prose, and a wrapper's doc
    // is where they land.
    super::Prose.visit_file_mut(&mut file);
    Ok(format!("{header}{}", prettyplease::unparse(&file)))
}

/// One pass over the document, in its order — which is the order every
/// generated list below is in, and the order `Api::new` checks.
fn gather(api: &OpenAPI, model: &Document, names: &Names) -> Result<Vec<Emitted>, GenerateError> {
    model
        .iter()
        .map(|op| {
            let (path_item, operation) = find(api, op).ok_or_else(|| {
                unsupported(format!("`{}` is not in the overlaid document", op.id()))
            })?;
            let (id, method, path) = (op.id(), op.method().as_str(), op.path());
            // Every failure below is about this one operation, and a generated
            // file is far too large to bisect by hand — so the operation is
            // named here, once, rather than at each of the places that can
            // fail.
            let emitted = || {
                Ok(Emitted {
                    row: quote! { (#id, #method, #path) },
                    variant: variant_of(op)?,
                    id: id.to_owned(),
                    group: op.group().as_str().to_owned(),
                    command: op.command().as_str().to_owned(),
                    body: json_body_type(op, operation, names)?,
                    method: wrapper(op, path_item, operation, names)?,
                    builder_method: builder_wrapper(op, path_item, operation, names)?,
                })
            };
            emitted().map_err(|source| GenerateError::Operation {
                op: id.to_owned(),
                source: Box::new(source),
            })
        })
        .collect()
}

/// The closed set of operations, and the two things only generated code knows
/// about each one: what it is called on a command line, and what type its body
/// is.
fn operation_id(ops: &[Emitted]) -> TokenStream {
    let variants = ops.iter().map(|op| {
        let (variant, id) = (&op.variant, &op.id);
        quote! { #[doc = #id] #variant }
    });
    let idents = ops.iter().map(|op| &op.variant);
    let from_command = ops.iter().map(|op| {
        let (group, command, variant) = (&op.group, &op.command, &op.variant);
        quote! { (#group, #command) => Some(Self::#variant) }
    });
    let check_body = check_body(ops);

    quote! {
        #[doc = "Every operation the overlaid document declares, in its order."]
        #[doc = ""]
        #[doc = "A wrapper names one of these rather than a string, so the"]
        #[doc = "wrappers cannot ask for an operation the document lacks; and"]
        #[doc = "`Api::new` pairs the whole set with the embedded document"]
        #[doc = "once, so a stale artefact is a named error at startup rather"]
        #[doc = "than a subcommand that cannot run."]
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        pub enum OperationId {
            #(#variants),*
        }

        impl OperationId {
            #[doc = "Every variant, in the document's order — which is also"]
            #[doc = "`OPERATIONS`' order and this enum's discriminant order."]
            pub const ALL: &'static [OperationId] = &[#(OperationId::#idents),*];

            #[doc = "The `<group> <command>` pair the CLI mounts this"]
            #[doc = "operation under."]
            #[doc = ""]
            #[doc = "This is the one place a name off the command line becomes"]
            #[doc = "a typed operation; everything past it is exhaustive."]
            #[must_use]
            pub fn from_command(group: &str, command: &str) -> Option<Self> {
                match (group, command) {
                    #(#from_command,)*
                    _ => None,
                }
            }

            #check_body
        }
    }
}

/// The one fact about an operation that only the generated types can supply:
/// which Rust type its request body is.
///
/// A body assembled on a command line goes through this before a request is
/// built, so the CLI path is held to the same schema as the typed path.
fn check_body(ops: &[Emitted]) -> TokenStream {
    let typed = ops.iter().filter_map(|op| {
        let (variant, id, ty) = (&op.variant, &op.id, op.body.as_ref()?);
        Some(quote! { Self::#variant => typed_openapi::client::fits::<#ty>(#id, body) })
    });
    let untyped: Vec<&Ident> = ops
        .iter()
        .filter(|op| op.body.is_none())
        .map(|op| &op.variant)
        .collect();
    let untyped = (!untyped.is_empty()).then(|| quote! { #(Self::#untyped)|* => Ok(()) });
    quote! {
        #[doc = "Does `body` fit the type this operation's wrapper takes?"]
        #[doc = ""]
        #[doc = "An operation whose body this crate has no type for accepts"]
        #[doc = "anything, which is the document's own position on it."]
        pub fn check_body(
            self,
            body: &serde_json::Value,
        ) -> Result<(), typed_openapi::client::BodyError> {
            match self {
                #(#typed,)*
                #untyped
            }
        }
    }
}

/// The inventory a hand-written operation asserts against, and `Api::new`
/// pairs the embedded document with.
fn inventory(ops: &[Emitted]) -> TokenStream {
    let rows = ops.iter().map(|op| &op.row);
    let count = ops.len();
    quote! {
        #[doc = "Every `(operationId, method, path)` the overlaid document declares."]
        #[doc = ""]
        #[doc = "Row `n` describes `OperationId::ALL[n]`. `Api::new` checks that"]
        #[doc = "against the document it embeds before handing out an `Api`."]
        pub const OPERATIONS: &[(&str, &str, &str)] = &[#(#rows),*];

        #[doc = "How many operations the document declares. An operation *added*"]
        #[doc = "upstream moves this number and nothing else would have noticed."]
        pub const OPERATION_COUNT: usize = #count;

        const fn str_eq(a: &str, b: &str) -> bool {
            let (a, b) = (a.as_bytes(), b.as_bytes());
            if a.len() != b.len() {
                return false;
            }
            let mut i = 0;
            while i < a.len() {
                if a[i] != b[i] {
                    return false;
                }
                i += 1;
            }
            true
        }

        #[doc = "`const _: () = assert!(documented(..));` beside a hand-written"]
        #[doc = "operation, or beside code that depends on one, turns that"]
        #[doc = "operation's disappearance from the document into a compile error."]
        #[must_use]
        pub const fn documented(id: &str, method: &str, path: &str) -> bool {
            let mut i = 0;
            while i < OPERATIONS.len() {
                let (oid, m, p) = OPERATIONS[i];
                if str_eq(oid, id) && str_eq(m, method) && str_eq(p, path) {
                    return true;
                }
                i += 1;
            }
            false
        }
    }
}

/// The `OperationId` variant for an operation: the `operationId`, PascalCased.
fn variant_of(op: &Operation) -> Result<Ident, GenerateError> {
    operation_ident(&op.id().to_pascal_case())
}

/// An identifier built from an operationId. [`gather`] names the operation, so
/// this says only what about it could not be spelled.
fn operation_ident(word: &str) -> Result<Ident, GenerateError> {
    ident(word).ok_or_else(|| unsupported("the operationId has no spelling as a Rust identifier"))
}

/// `word` as an identifier the generated source can carry.
///
/// A document is free to name a parameter `type` or an operation `match`, and a
/// keyword is not an identifier. A raw identifier is what keeps the document's
/// own word: `r#type` reads as what the document said, where a mangled `type_`
/// reads as something this generator invented. Four words cannot be written raw
/// at all — `crate`, `self`, `Self` and `super` — and those take the underscore
/// instead, which is the one place a name is changed rather than quoted.
///
/// Nothing about a request depends on which of the two a name gets. The wire
/// name travels beside the argument, as the literal the request builder is
/// given, so an argument is free to be spelled however Rust requires.
///
/// A word with no spelling at all — one that starts with a digit, or that
/// case-conversion emptied — is an error rather than a panic, because
/// `format_ident!` panics and a bless step is a library call.
fn ident(word: &str) -> Option<Ident> {
    if typify::accept_as_ident(word) {
        return syn::parse_str(word).ok();
    }
    match word {
        "crate" | "self" | "Self" | "super" => Some(format_ident!("{word}_")),
        _ => syn::parse_str(&format!("r#{word}")).ok(),
    }
}

/// The Rust type of an operation's JSON request body, when it has one.
///
/// `None` covers an operation with no body and one whose body a CLI sends
/// verbatim — neither has a type to hold a `--json-body` file to.
fn json_body_type(
    op: &Operation,
    operation: &openapiv3::Operation,
    names: &Names,
) -> Result<Option<TokenStream>, GenerateError> {
    match op.body() {
        Body::JsonFields(_) | Body::JsonWhole { .. } => body_type(operation, names).map(Some),
        Body::None | Body::Opaque { .. } | Body::Multipart { .. } => Ok(None),
    }
}

/// The document's own entry for an operation the model already accepted.
fn find<'a>(
    api: &'a OpenAPI,
    op: &Operation,
) -> Option<(&'a openapiv3::PathItem, &'a openapiv3::Operation)> {
    let item = api.paths.paths.get(op.path())?.as_item()?;
    let operation = item.iter().find_map(|(_, candidate)| {
        (candidate.operation_id.as_deref() == Some(op.id())).then_some(candidate)
    })?;
    Some((item, operation))
}

fn wrapper(
    op: &Operation,
    item: &openapiv3::PathItem,
    operation: &openapiv3::Operation,
    names: &Names,
) -> Result<TokenStream, GenerateError> {
    let name = operation_ident(&op.id().to_snake_case())?;
    let summary = op.summary().unwrap_or(op.id());
    let signature = format!("{} {}", op.method(), op.path());
    let gate = gate_note(op);

    let Signature {
        args,
        builder,
        notes,
        // The delegate beside this one forwards the argument names; a
        // positional call has no use for them.
        names: _,
    } = signature_of(op, item, operation, names)?;
    let response = response_type(operation, names)?;
    let variant = variant_of(op)?;
    let doc = paragraphs(
        [summary, &signature, &gate]
            .into_iter()
            .map(str::to_owned)
            .chain(notes),
    );
    parses(quote! {
        #[doc = #doc]
        pub fn #name(&self, #(#args),*) -> Result<Call<'_, #response>, Error> {
            self.call(OperationId::#variant, Values::new() #(#builder)*)
        }
    })
}

/// One doc comment out of the paragraphs it is made of.
///
/// One rather than several, and this is the reason: rustc rebuilds a doc
/// comment's text by stripping the indentation *all* of an item's doc
/// fragments share, and a `/* */` fragment carries the indentation the item
/// sits at while a `///` fragment carries none. Mixing them leaves nothing to
/// strip, and a vendor's summary arrives four spaces in — a code block, which
/// rustdoc then compiles. A single fragment cannot be mixed with anything.
///
/// A summary that is itself several paragraphs is what makes this reachable,
/// and one attribute per paragraph is what would reach it: the multi-line
/// summary becomes the `/* */` fragment and the generated paragraphs beside it
/// the `///` ones. `PROSE` carries such a summary, so the doctest runner is
/// what holds this rather than the argument above it.
fn paragraphs(parts: impl IntoIterator<Item = String>) -> String {
    parts
        .into_iter()
        .map(|part| part.trim().to_owned())
        .collect::<Vec<_>>()
        .join("\n\n")
}

/// A wrapper, checked to be Rust before it joins six thousand lines of its
/// kind.
///
/// The whole file is parsed once at the end anyway, and a failure there names a
/// position in a token stream nobody can open. Parsing each wrapper as it is
/// built costs one small parse per operation and puts the failure inside the
/// operation that caused it, where [`gather`] names it.
fn parses(wrapper: TokenStream) -> Result<TokenStream, GenerateError> {
    syn::parse2::<syn::ImplItemFn>(wrapper.clone()).map_err(|source| GenerateError::NotRust {
        file: "ops.rs",
        source,
    })?;
    Ok(wrapper)
}

/// What a wrapper's doc says about the gate a command line holds the operation
/// behind.
///
/// A Rust caller is trusted and is stopped by nothing here, so this is the one
/// place the hazard is written down for them: the doc names every word the CLI
/// demands, because a caller reading the wrapper is deciding whether to make
/// the call at all.
fn gate_note(op: &Operation) -> String {
    let named: Vec<String> = op
        .gates()
        .iter()
        .map(|gate| format!("`--{gate}`"))
        .collect();
    match (op.effect(), named.is_empty()) {
        (crate::Effect::Read, _) => "A read.".to_owned(),
        (crate::Effect::Write, true) => {
            "This operation writes. A Rust caller is trusted; the CLI holds it behind `--commit`."
                .to_owned()
        }
        (crate::Effect::Write, false) => format!(
            "This operation writes. A Rust caller is trusted; the CLI holds it behind \
             `--commit` and {}.",
            named.join(" and ")
        ),
    }
}

/// The same operation with its arguments named at the call site.
///
/// The name carries a `_builder` suffix because this is an *addition*: the
/// `builder` feature must not change what an existing call site means, and a
/// feature that replaced `update_voucher` would break every crate that shares
/// the generated code, since cargo resolves features once for a whole build.
///
/// It delegates to the plain wrapper rather than repeating its body, so the two
/// cannot come to describe different requests.
fn builder_wrapper(
    op: &Operation,
    item: &openapiv3::PathItem,
    operation: &openapiv3::Operation,
    names: &Names,
) -> Result<TokenStream, GenerateError> {
    let plain = operation_ident(&op.id().to_snake_case())?;
    let name = format_ident!("{plain}_builder");
    let Signature {
        args,
        names: arguments,
        ..
    } = signature_of(op, item, operation, names)?;
    let response = response_type(operation, names)?;
    let doc = format!(
        "The same call as [`Api::{plain}`], with its arguments named. A missing \
         required argument is a compile error."
    );
    parses(quote! {
        #[doc = #doc]
        #[builder]
        pub fn #name(&self, #(#args),*) -> Result<Call<'_, #response>, Error> {
            self.#plain(#(#arguments),*)
        }
    })
}

/// One wrapper's arguments, the `Values` builder chain they feed, and whatever
/// about them the document can explain but the types cannot.
struct Signature {
    args: Vec<TokenStream>,
    names: Vec<Ident>,
    builder: Vec<TokenStream>,
    notes: Vec<String>,
}

fn signature_of(
    op: &Operation,
    item: &openapiv3::PathItem,
    operation: &openapiv3::Operation,
    names: &Names,
) -> Result<Signature, GenerateError> {
    let mut out = Signature {
        args: Vec::new(),
        names: Vec::new(),
        builder: Vec::new(),
        notes: Vec::new(),
    };
    for param in op.params() {
        add_param(&mut out, param, item, operation, names)?;
    }
    match op.body() {
        Body::None => {}
        Body::JsonFields(_) | Body::JsonWhole { .. } => {
            let ty = body_type(operation, names)?;
            out.args.push(quote! { body: &#ty });
            out.names.push(format_ident!("body"));
            out.builder.push(quote! { .json(crate::to_json(body)?) });
        }
        Body::Opaque { media_type, .. } => {
            out.notes.push(format!(
                "`body` is sent verbatim under the document's own `{media_type}`, \
                 which this crate does not assemble."
            ));
            out.args.push(quote! { body: Vec<u8> });
            out.names.push(format_ident!("body"));
            out.builder.push(quote! { .raw(body) });
        }
        Body::Multipart { names, .. } => {
            out.notes.push(multipart_note(names));
            out.args.push(quote! { parts: Vec<Part> });
            out.names.push(format_ident!("parts"));
            out.builder.push(quote! { .multipart(parts) });
        }
    }
    Ok(out)
}

/// What one parameter adds to a wrapper: an argument and the `Values` call that
/// fills it — or, for a parameter with no command-line spelling, a note saying
/// the wrapper does not carry it either. A Rust caller and a command line reach
/// one request builder, so what neither can supply is missing from both.
fn add_param(
    out: &mut Signature,
    param: &crate::Param,
    item: &openapiv3::PathItem,
    operation: &openapiv3::Operation,
    names: &Names,
) -> Result<(), GenerateError> {
    let join = match param.shape() {
        Shape::Flag { join, .. } => join,
        Shape::Unreachable(why) => {
            out.notes.push(format!(
                "The document's `{}` parameter is not an argument: it is {why}. \
                 A request built here does not carry it.",
                param.name()
            ));
            return Ok(());
        }
    };
    let ident = ident(&param.name().to_snake_case()).ok_or_else(|| {
        unsupported(format!(
            "parameter `{}` has no spelling as a Rust identifier",
            param.name()
        ))
    })?;
    let schema = param_schema(item, operation, param.name())?;
    let wire = param.name();
    out.names.push(ident.clone());
    if join.is_some() {
        // A list parameter is the wire name given once per value, which is the
        // repetition a repeated flag reaches the request builder with.
        let ty = list_type(param.name(), schema, names)?;
        out.args.push(quote! { #ident: Vec<#ty> });
        out.builder.push(quote! { .each(#wire, #ident) });
    } else if param.required() {
        let ty = scalar_type(schema, names)?;
        out.args.push(quote! { #ident: #ty });
        out.builder.push(quote! { .param(#wire, #ident) });
    } else {
        let ty = scalar_type(schema, names)?;
        out.args.push(quote! { #ident: Option<#ty> });
        out.builder.push(quote! { .maybe(#wire, #ident) });
    }
    Ok(())
}

fn multipart_note(names: &[String]) -> String {
    let assembled = "`parts` are assembled into a `multipart/form-data` body.";
    if names.is_empty() {
        assembled.to_owned()
    } else {
        format!("{assembled} The document declares: {}.", names.join(", "))
    }
}

/// The schema one parameter declares, keyed on the document's own name.
fn param_schema<'d>(
    item: &'d openapiv3::PathItem,
    operation: &'d openapiv3::Operation,
    name: &str,
) -> Result<&'d ReferenceOr<Schema>, GenerateError> {
    let declared = item
        .parameters
        .iter()
        .chain(&operation.parameters)
        .find_map(|p| {
            let ReferenceOr::Item(p) = p else { return None };
            (p.parameter_data_ref().name == name).then_some(p)
        })
        .ok_or_else(|| unsupported(format!("`{name}` is not declared on this operation")))?;
    let openapiv3::ParameterSchemaOrContent::Schema(schema) = &declared.parameter_data_ref().format
    else {
        return Err(unsupported(format!(
            "`{name}` is declared with `content`, not `schema`"
        )));
    };
    Ok(schema)
}

/// The Rust spelling of a list parameter's items.
///
/// Only an inline `type: array` has one here. Following a `$ref` to an array
/// schema would mean resolving against `components`, which this generator does
/// not carry, so the parameter names itself rather than being guessed at.
fn list_type(
    name: &str,
    schema: &ReferenceOr<Schema>,
    names: &Names,
) -> Result<TokenStream, GenerateError> {
    let ReferenceOr::Item(schema) = schema else {
        return Err(unsupported(format!(
            "`{name}` is a list, and a list parameter must declare `items` inline"
        )));
    };
    let SchemaKind::Type(Type::Array(array)) = &schema.schema_kind else {
        return Err(unsupported(format!(
            "`{name}` is a list that is not an array"
        )));
    };
    let Some(items) = &array.items else {
        return Err(unsupported(format!(
            "`{name}` is an array declaring no `items`"
        )));
    };
    scalar_type(&items.clone().unbox(), names)
}

/// A scalar schema's Rust spelling. A `$ref` to a named schema keeps its name,
/// so an enumerated parameter is the generated enum rather than a string.
fn scalar_type(schema: &ReferenceOr<Schema>, names: &Names) -> Result<TokenStream, GenerateError> {
    if let Some(name) = ref_name(schema) {
        return names.get(name).cloned();
    }
    let ReferenceOr::Item(schema) = schema else {
        return Err(unsupported(
            "only `#/components/schemas/` references are followed",
        ));
    };
    let SchemaKind::Type(kind) = &schema.schema_kind else {
        return Err(unsupported("only `type:` schemas have a scalar spelling"));
    };
    Ok(match kind {
        Type::String(_) => quote!(&str),
        Type::Integer(_) => quote!(i64),
        Type::Number(_) => quote!(f64),
        Type::Boolean(_) => quote!(bool),
        Type::Object(_) | Type::Array(_) => return Err(unsupported("not a scalar")),
    })
}

/// The type of a JSON request body. A `$ref` keeps its name; anything else is
/// a `serde_json::Value`, because the document did not name a shape to generate.
fn body_type(
    operation: &openapiv3::Operation,
    names: &Names,
) -> Result<TokenStream, GenerateError> {
    let Some(ReferenceOr::Item(body)) = &operation.request_body else {
        return Err(unsupported("requestBody $refs are not followed"));
    };
    let Some(media) = body
        .content
        .iter()
        .find_map(|(name, media)| crate::schema::is_json(name).then_some(media))
    else {
        return Err(unsupported("no JSON request body"));
    };
    let Some(schema) = &media.schema else {
        return Ok(quote!(serde_json::Value));
    };
    named_or_value(schema, names)
}

/// The type a successful response deserialises into.
fn response_type(
    operation: &openapiv3::Operation,
    names: &Names,
) -> Result<TokenStream, GenerateError> {
    let success =
        operation.responses.responses.iter().find(
            |(status, _)| matches!(status, StatusCode::Code(code) if (200..300).contains(code)),
        );
    let Some((_, ReferenceOr::Item(success))) = success else {
        return Ok(quote!(NoContent));
    };
    let Some(media) = success
        .content
        .iter()
        .find_map(|(name, media)| crate::schema::is_json(name).then_some(media))
    else {
        return Ok(quote!(NoContent));
    };
    let Some(schema) = &media.schema else {
        return Ok(quote!(NoContent));
    };
    if let Some(name) = ref_name(schema) {
        return names.get(name).cloned();
    }
    let ReferenceOr::Item(schema) = schema else {
        return Ok(quote!(serde_json::Value));
    };
    let SchemaKind::Type(Type::Array(array)) = &schema.schema_kind else {
        return Ok(quote!(serde_json::Value));
    };
    let Some(items) = &array.items else {
        return Ok(quote!(serde_json::Value));
    };
    let items = items.clone().unbox();
    let inner = named_or_value(&items, names)?;
    Ok(quote!(Vec<#inner>))
}

fn named_or_value(
    schema: &ReferenceOr<Schema>,
    names: &Names,
) -> Result<TokenStream, GenerateError> {
    if let Some(name) = ref_name(schema) {
        return names.get(name).cloned();
    }
    Ok(quote!(serde_json::Value))
}

fn ref_name(schema: &ReferenceOr<Schema>) -> Option<&str> {
    match schema {
        ReferenceOr::Reference { reference } => reference.strip_prefix("#/components/schemas/"),
        ReferenceOr::Item(_) => None,
    }
}