kynos-macros 0.2.0

Procedural macros for the Kynos REST API framework.
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
use crate::route::{args::RouteArgs, attrs::split_doc, uri::endpoint_uri_impl};

fn lines(input: &[&str]) -> Vec<String> {
    input.iter().map(|line| (*line).to_owned()).collect()
}

/// Splitting a doc comment into its summary and its description.
///
/// The sweep below proves the split is total over every arrangement of blank
/// lines; the cases after it pin the characters the two halves are joined with.
/// Neither restates the other: the sweep reads words and never looks at the
/// separators, and the cases fix separators the sweep cannot see.
mod doc_comments {
    use super::{lines, split_doc};

    /// The whitespace-separated words of a half, absent or not.
    ///
    /// Blind to the join character on purpose, so that this and the cases below
    /// divide the work rather than share it.
    fn words(text: Option<&str>) -> Vec<String> {
        text.map(|text| text.split_whitespace().map(str::to_owned).collect())
            .unwrap_or_default()
    }

    /// Every arrangement of blank and non-blank lines, up to five lines.
    ///
    /// The expectation is built from the pattern rather than from `split_doc`:
    /// each non-blank line carries a word naming its own index, so where a word
    /// comes out says which half claimed it. Five lines is enough to hold a
    /// leading blank, a trailing blank, and a doubled blank between two
    /// paragraphs at the same time, which are the arrangements that differ.
    ///
    /// A sweep rather than a sampled property: the space is 2^5 patterns, and
    /// enumerating it is total where drawing from it would not be.
    #[test]
    fn every_arrangement_of_blank_lines_splits_without_losing_a_word() {
        for width in 0..=5usize {
            for pattern in 0..(1usize << width) {
                let blank: Vec<bool> = (0..width).map(|bit| pattern & (1 << bit) != 0).collect();
                let rendered: Vec<String> = blank
                    .iter()
                    .enumerate()
                    .map(|(index, &is_blank)| {
                        // Whitespace rather than "", so that a line that only
                        // looks blank is swept too.
                        if is_blank {
                            "  ".to_owned()
                        } else {
                            format!(" w{index}")
                        }
                    })
                    .collect();

                let (summary, description) = split_doc(&rendered);

                // The first paragraph is whatever precedes the first blank line,
                // so every line before it is non-blank by construction.
                let boundary = blank.iter().position(|&is_blank| is_blank).unwrap_or(width);
                let expected_summary: Vec<String> =
                    (0..boundary).map(|index| format!("w{index}")).collect();
                let expected_description: Vec<String> = ((boundary + 1)..width)
                    .filter(|index| !blank[*index])
                    .map(|index| format!("w{index}"))
                    .collect();

                assert_eq!(
                    words(summary.as_deref()),
                    expected_summary,
                    "summary for {blank:?}"
                );
                assert_eq!(
                    words(description.as_deref()),
                    expected_description,
                    "description for {blank:?}"
                );

                // An empty half is absent, never present and blank: `Some("")`
                // would reach the description as a field that renders as an
                // empty string rather than one that is omitted.
                assert_ne!(summary.as_deref(), Some(""), "summary for {blank:?}");
                assert_ne!(
                    description.as_deref(),
                    Some(""),
                    "description for {blank:?}"
                );
            }
        }
    }

    #[test]
    fn a_single_line_doc_comment_is_all_summary() {
        let (summary, description) = split_doc(&lines(&[" Fetch a single user."]));
        assert_eq!(summary.as_deref(), Some("Fetch a single user."));
        assert_eq!(description, None);
    }

    #[test]
    fn the_first_paragraph_is_the_summary_and_the_rest_the_description() {
        let (summary, description) = split_doc(&lines(&[
            " Fetch a single user.",
            "",
            " Includes soft-deleted accounts.",
            " Requires the `users:read` scope.",
        ]));
        assert_eq!(summary.as_deref(), Some("Fetch a single user."));
        assert_eq!(
            description.as_deref(),
            Some("Includes soft-deleted accounts.\nRequires the `users:read` scope.")
        );
    }

    #[test]
    fn a_wrapped_first_paragraph_joins_into_one_summary() {
        let (summary, description) = split_doc(&lines(&[
            " Fetch a single user by",
            " its identifier.",
            "",
            " More detail.",
        ]));
        assert_eq!(
            summary.as_deref(),
            Some("Fetch a single user by its identifier.")
        );
        assert_eq!(description.as_deref(), Some("More detail."));
    }

    /// A blank line inside the description is kept, because it separates
    /// paragraphs the specification renders as written.
    #[test]
    fn a_paragraph_break_survives_into_the_description() {
        let (_, description) = split_doc(&lines(&[" Summary.", "", " First.", "", " Second."]));
        assert_eq!(description.as_deref(), Some("First.\n\nSecond."));
    }

    #[test]
    fn an_absent_doc_comment_yields_neither() {
        let (summary, description) = split_doc(&[]);
        assert_eq!(summary, None);
        assert_eq!(description, None);
    }

    #[test]
    fn trailing_blank_lines_do_not_become_an_empty_description() {
        let (summary, description) = split_doc(&lines(&[" Fetch a user.", "", "  "]));
        assert_eq!(summary.as_deref(), Some("Fetch a user."));
        assert_eq!(description, None);
    }
}

/// The typed `relative_uri` constructor emitted beside each handler.
///
/// Which parameters it takes and which builder it calls are decided by whether
/// the handler extracts `Path<T>`, `Query<T>`, both or neither. Four arms, so
/// four cases: the arms differ from one another and nothing else covers them.
mod typed_uri {
    use quote::ToTokens;
    use syn::ItemFn;

    use super::endpoint_uri_impl;

    /// What the emitter decided, read back out of the expansion.
    #[derive(Debug, PartialEq, Eq)]
    struct Emission {
        /// Each parameter as `name: Type`.
        parameters: Vec<String>,
        /// The `__private::uri` builder the body calls.
        builder: String,
        /// Whether a `const` assertion pinning the parameter names came with it.
        checks_names: bool,
    }

    /// The expansion, and the constructor inside it.
    ///
    /// Shared by the two things read out of one emission: the signature the
    /// emitter wrote, and the documentation it attached.
    fn expansion(
        function: &ItemFn,
        path: &str,
        variables: &[&str],
    ) -> (syn::File, syn::ImplItemFn) {
        let variables: Vec<String> = variables.iter().map(|name| (*name).to_owned()).collect();
        let tokens = endpoint_uri_impl(function, path, &variables).expect("a valid endpoint");
        let file: syn::File = syn::parse2(tokens).expect("the expansion parses as items");

        let block = file
            .items
            .iter()
            .find_map(|item| match item {
                syn::Item::Impl(block) => Some(block),
                _ => None,
            })
            .expect("an inherent impl");
        let constructor = block
            .items
            .iter()
            .find_map(|item| match item {
                syn::ImplItem::Fn(function) => Some(function),
                _ => None,
            })
            .expect("a `relative_uri` constructor")
            .clone();

        assert_eq!(constructor.sig.ident, "relative_uri");

        (file, constructor)
    }

    /// The documentation rustdoc will read off the emitted constructor.
    ///
    /// Fragments joined the way rustdoc joins them, so a line here is a line of
    /// the rendered Markdown rather than a fragment of one.
    fn emitted_doc(function: &ItemFn, path: &str, variables: &[&str]) -> String {
        let (_, constructor) = expansion(function, path, variables);

        constructor
            .attrs
            .iter()
            .filter_map(|attribute| match &attribute.meta {
                syn::Meta::NameValue(pair) if pair.path.is_ident("doc") => match &pair.value {
                    syn::Expr::Lit(syn::ExprLit {
                        lit: syn::Lit::Str(text),
                        ..
                    }) => Some(text.value()),
                    _ => None,
                },
                _ => None,
            })
            .collect::<Vec<String>>()
            .join("\n")
    }

    /// Parses the expansion rather than matching its text.
    ///
    /// `quote` decides the spacing, so a `contains` over the stringified tokens
    /// breaks whenever the emitter is reformatted and passes whenever a wrong
    /// expansion happens to contain the fragment. Reading the parsed signature
    /// asks what the emitter actually decided.
    fn emitted(function: &ItemFn, path: &str, variables: &[&str]) -> Emission {
        let (file, constructor) = expansion(function, path, variables);

        let parameters = constructor
            .sig
            .inputs
            .iter()
            .map(|input| {
                let syn::FnArg::Typed(argument) = input else {
                    panic!("`relative_uri` is an associated function, not a method")
                };
                format!(
                    "{}: {}",
                    argument.pat.to_token_stream(),
                    argument.ty.to_token_stream()
                )
            })
            .collect();

        let [syn::Stmt::Expr(syn::Expr::Call(call), None)] = &constructor.block.stmts[..] else {
            panic!("`relative_uri` is one call")
        };
        let syn::Expr::Path(callee) = call.func.as_ref() else {
            panic!("the call names a path")
        };

        Emission {
            parameters,
            builder: callee
                .path
                .segments
                .last()
                .expect("a builder name")
                .ident
                .to_string(),
            checks_names: file
                .items
                .iter()
                .any(|item| matches!(item, syn::Item::Const(_))),
        }
    }

    #[test]
    fn a_route_without_parameters_takes_none() {
        let function: ItemFn = syn::parse_quote! {
            async fn report() {}
        };

        assert_eq!(
            emitted(&function, "/reports", &[]),
            Emission {
                parameters: vec![],
                builder: "endpoint_uri".to_owned(),
                // Nothing to check: no `Path<T>` means no names to line up.
                checks_names: false,
            }
        );
    }

    #[test]
    fn a_route_with_path_variables_takes_the_extracted_path_type() {
        let function: ItemFn = syn::parse_quote! {
            async fn report(Path(path): Path<ReportPath>) {}
        };

        assert_eq!(
            emitted(&function, "/reports/{name}", &["name"]),
            Emission {
                parameters: vec!["path: ReportPath".to_owned()],
                builder: "endpoint_uri_with_path".to_owned(),
                checks_names: true,
            }
        );
    }

    #[test]
    fn a_route_with_a_query_extractor_takes_the_extracted_query_type() {
        let function: ItemFn = syn::parse_quote! {
            async fn report(Query(query): Query<ReportQuery>) {}
        };

        assert_eq!(
            emitted(&function, "/reports", &[]),
            Emission {
                parameters: vec!["query: ReportQuery".to_owned()],
                builder: "endpoint_uri_with_query".to_owned(),
                checks_names: false,
            }
        );
    }

    #[test]
    fn a_route_extracting_both_takes_both_in_that_order() {
        let function: ItemFn = syn::parse_quote! {
            async fn report(Path(path): Path<ReportPath>, Query(query): Query<ReportQuery>) {}
        };

        assert_eq!(
            emitted(&function, "/reports/{name}", &["name"]),
            Emission {
                parameters: vec![
                    "path: ReportPath".to_owned(),
                    "query: ReportQuery".to_owned(),
                ],
                builder: "endpoint_uri_with_path_and_query".to_owned(),
                checks_names: true,
            }
        );
    }

    /// The four shapes the emitter matches on, as `(description, handler, path,
    /// variables)`.
    fn arms() -> Vec<(&'static str, ItemFn, &'static str, &'static [&'static str])> {
        vec![
            (
                "a route with no extractors",
                syn::parse_quote!(
                    async fn report() {}
                ),
                "/reports",
                &[],
            ),
            (
                "a route extracting Path<T> only",
                syn::parse_quote!(
                    async fn report(Path(path): Path<ReportPath>) {}
                ),
                "/reports/{name}",
                &["name"],
            ),
            (
                "a route extracting Query<T> only",
                syn::parse_quote!(
                    async fn report(Query(query): Query<ReportQuery>) {}
                ),
                "/reports",
                &[],
            ),
            (
                "a route extracting both",
                syn::parse_quote!(
                    async fn report(
                        Path(path): Path<ReportPath>,
                        Query(query): Query<ReportQuery>,
                    ) {
                    }
                ),
                "/reports/{name}",
                &["name"],
            ),
        ]
    }

    /// How far a line's leading whitespace carries it, in columns.
    ///
    /// Counted in columns rather than in characters because a tab is not worth
    /// one: CommonMark advances it to the next four-column stop, so a single
    /// leading tab opens the same indented code block that eight spaces did and
    /// a character count would read it as an indent of one. A sugared `///`
    /// fragment contributes one leading space of its own, which is why the
    /// threshold is four columns rather than none.
    fn indent_columns(line: &str) -> usize {
        let mut columns = 0;
        for character in line.chars() {
            match character {
                ' ' => columns += 1,
                '\t' => columns += 4 - columns % 4,
                _ => break,
            }
        }
        columns
    }

    /// Whether two whitespace characters stand next to each other.
    ///
    /// Any two, not two spaces: a literal re-wrapped without its line breaks
    /// leaves whatever whitespace the source indentation was made of.
    fn has_doubled_whitespace(line: &str) -> bool {
        line.chars()
            .zip(line.chars().skip(1))
            .any(|(left, right)| left.is_whitespace() && right.is_whitespace())
    }

    /// Every arm's documentation renders as prose, not as a code block.
    ///
    /// Markdown reads four or more leading spaces as an indented code block, and
    /// rustdoc compiles an unannotated code block as Rust -- so an indented
    /// paragraph here is one failing doctest per route attribute in every crate
    /// that writes one, and nothing in this workspace renders this documentation
    /// to notice. Swept rather than sampled: the emitter matches on
    /// `(Option<Path<T>>, Option<Query<T>>)`, so these four rows are the set.
    ///
    /// No counter stands beside this one, unlike the diagnostics above: that set
    /// is open and a rule can be added without a case, while this one is closed
    /// by the type system -- `(Option<_>, Option<_>)` has four inhabitants and
    /// the `match` is exhaustive or it does not compile. What the type system
    /// does *not* close is this table's mapping onto those inhabitants, which is
    /// transcribed; the distinct-builder assertion at the end is what holds it,
    /// so the exhaustiveness here is asserted rather than intended.
    #[test]
    fn every_emitted_doc_line_renders_as_prose() {
        let mut builders = Vec::new();

        for (description, function, path, variables) in arms() {
            // Read the signature beside the documentation, so that the four
            // rows are held to being four *different* arms. The mapping from
            // this table onto the emitter's `match` is transcribed rather than
            // checked by the compiler: an edit to a handler here, or a change
            // to the extractor spelling `extractor_type` recognises, would
            // collapse a row onto one already swept and retire an arm from the
            // sweep silently -- `relative_doc` is shared, so the emptiness
            // assertion below would still pass.
            builders.push(emitted(&function, path, variables).builder);

            let doc = emitted_doc(&function, path, variables);
            assert!(
                !doc.is_empty(),
                "{description}: the constructor carries no documentation"
            );
            for line in doc.lines() {
                assert!(
                    indent_columns(line) < 4,
                    "{description}: `{line}` is indented four columns, which Markdown reads as a \
                     Rust code block and rustdoc then tries to compile"
                );
                assert!(
                    !has_doubled_whitespace(line.trim_start()),
                    "{description}: `{line}` carries a run of whitespace, which is what a literal \
                     re-wrapped without its line breaks looks like"
                );
            }
        }

        let mut distinct = builders.clone();
        distinct.sort();
        distinct.dedup();
        assert_eq!(
            distinct.len(),
            builders.len(),
            "the rows must be four different arms, but they emit {builders:?}"
        );
    }

    /// One row per `syn::Error::new` site in `uri.rs`, counted below.
    fn cases() -> Vec<(
        &'static str,
        ItemFn,
        &'static str,
        &'static [&'static str],
        &'static str,
    )> {
        vec![
            (
                "a Path<T> extractor on a route with no variables",
                syn::parse_quote!(
                    async fn report(Path(path): Path<ReportPath>) {}
                ),
                "/reports",
                &[],
                "no path variables",
            ),
            (
                "path variables with no Path<T> extractor",
                syn::parse_quote!(
                    async fn report() {}
                ),
                "/reports/{name}",
                &["name"],
                "no Path<T> extractor",
            ),
            (
                "a Path extractor with no type argument",
                syn::parse_quote!(
                    async fn report(Path(path): Path) {}
                ),
                "/reports/{name}",
                &["name"],
                "Path needs one type argument",
            ),
            (
                "a Path extractor whose argument is not a type",
                syn::parse_quote!(
                    async fn report(Path(path): Path<'a>) {}
                ),
                "/reports/{name}",
                &["name"],
                "Path needs one type argument",
            ),
            (
                "two Path<T> extractors on one handler",
                syn::parse_quote!(
                    async fn report(Path(one): Path<A>, Path(two): Path<B>) {}
                ),
                "/reports/{name}",
                &["name"],
                "only once",
            ),
        ]
    }

    #[test]
    fn each_case_raises_the_diagnostic_it_names() {
        for (description, function, path, variables, expected) in cases() {
            let variables: Vec<String> = variables.iter().map(|name| (*name).to_owned()).collect();
            let Err(error) = endpoint_uri_impl(&function, path, &variables) else {
                panic!("{description} must be rejected");
            };
            let reported = error.to_string();
            assert!(
                reported.contains(expected),
                "{description}: expected a diagnostic containing {expected:?}, got {reported:?}"
            );
        }
    }

    #[test]
    fn every_typed_uri_diagnostic_has_a_case() {
        const SOURCE: &str = include_str!("uri.rs");

        let sites = SOURCE.matches("syn::Error::new(").count();
        assert_eq!(
            cases().len(),
            sites,
            "`uri.rs` raises {sites} diagnostic(s) and {} have a case",
            cases().len()
        );
    }
}

/// The arguments a route attribute accepts, and what it says when they are
/// wrong.
///
/// A closed key set rather than an open input space: four keys, each read once.
/// So the obligation here is one case per diagnostic, counted against the
/// source, and a sweep of the orders they may arrive in -- not a generator,
/// which would re-derive the match arms it was meant to check.
mod arguments {
    use proc_macro2::TokenStream as TokenStream2;
    use quote::quote;

    use super::RouteArgs;

    /// One row per `syn::Error::new` site in `args.rs`.
    ///
    /// Each row is the input that reaches its site and a fragment of what it
    /// says. The fragment identifies *which* diagnostic fired, not its wording:
    /// the exact text is `trybuild`'s to hold, in
    /// `crates/kynos/tests/ui/macros/`, where a reader sees it rendered.
    fn cases() -> Vec<(&'static str, TokenStream2, &'static str)> {
        vec![
            (
                "a bare word that is not `catch_panics`",
                quote!(path = "/health", nonsense),
                "expected a path string literal",
            ),
            (
                "a second tag, which would silently discard the first",
                quote!(path = "/health", tag = Users, tag = Admin),
                "already names a tag",
            ),
            (
                "an argument no attribute reads",
                quote!(path = "/health", nonsense = "x"),
                "unknown route argument",
            ),
            (
                "a list where a value belongs",
                quote!(path = "/health", tag(Users)),
                "expected `name = value`, not a list",
            ),
            (
                "no path at all",
                quote!(operation_id = "getHealth"),
                "needs a path",
            ),
            (
                "a path that is not a string",
                quote!(path = 7),
                "expected a string literal",
            ),
            (
                "a tag that is not a path expression",
                quote!(path = "/health", tag = "Users"),
                "expected the name of a type deriving `Tag`",
            ),
            (
                "a tag naming more than one segment",
                quote!(path = "/health", tag = tags::Users),
                "expected the name of a type deriving `Tag`",
            ),
        ]
    }

    #[test]
    fn each_case_raises_the_diagnostic_it_names() {
        for (description, tokens, expected) in cases() {
            let Err(error) = RouteArgs::parse(tokens) else {
                panic!("{description} must be rejected");
            };
            let reported = error.to_string();
            assert!(
                reported.contains(expected),
                "{description}: expected a diagnostic containing {expected:?}, got {reported:?}"
            );
        }
    }

    /// A count, not a mapping.
    ///
    /// It catches the drift that happens -- a rule added without a case -- and
    /// not a case rewritten to reach a site another already covers. Two sites
    /// share a message (`expect_ident` refuses a non-path and a multi-segment
    /// path in the same words), so the rows are what distinguish them.
    #[test]
    fn every_route_argument_diagnostic_has_a_case() {
        const SOURCE: &str = include_str!("args.rs");

        let sites = SOURCE.matches("syn::Error::new(").count();
        assert_eq!(
            cases().len(),
            sites,
            "`args.rs` raises {sites} diagnostic(s) and {} have a case; an argument rule added \
             without one is a rule that can stop firing silently",
            cases().len()
        );
    }

    /// `method` belongs to `#[kynos::operation]` alone. The shared parser must
    /// keep rejecting it, so that `#[kynos::get("/x", method = "POST")]` cannot
    /// serve one method while the description names another.
    #[test]
    fn a_per_method_attribute_rejects_a_method_argument() {
        let Err(error) = RouteArgs::parse(quote!(path = "/health", method = "POST")) else {
            panic!("a per-method attribute must not accept `method`")
        };

        assert!(error.to_string().contains("unknown route argument"));
    }

    #[test]
    fn catch_panics_is_a_bare_route_option() {
        let args = RouteArgs::parse(quote!(path = "/health", catch_panics))
            .expect("valid route arguments");

        assert!(args.catch_panics);
    }

    /// The arguments are read in a loop, so the order they arrive in must not
    /// change what is read. Swept over every permutation of the four rather
    /// than shown in one, because an order-dependent read is exactly the defect
    /// a single example cannot see.
    #[test]
    fn the_arguments_parse_alike_in_every_order() {
        let pieces: [TokenStream2; 4] = [
            quote!(path = "/health"),
            quote!(operation_id = "getHealth"),
            quote!(tag = Users),
            quote!(catch_panics),
        ];

        for order in permutations(&[0, 1, 2, 3]) {
            let tokens = order
                .iter()
                .map(|index| pieces[*index].clone())
                .reduce(|left, right| quote!(#left, #right))
                .expect("four pieces");

            let args = RouteArgs::parse(tokens).unwrap_or_else(|error| {
                panic!("order {order:?} must parse, got {error}");
            });

            assert_eq!(args.path.value(), "/health", "order {order:?}");
            assert_eq!(
                args.operation_id.map(|id| id.value()).as_deref(),
                Some("getHealth"),
                "order {order:?}"
            );
            assert_eq!(
                args.tag.map(|tag| tag.to_string()).as_deref(),
                Some("Users"),
                "order {order:?}"
            );
            assert!(args.catch_panics, "order {order:?}");
        }
    }

    /// Every ordering of `items`, by repeated removal.
    fn permutations(items: &[usize]) -> Vec<Vec<usize>> {
        if items.len() <= 1 {
            return vec![items.to_vec()];
        }
        let mut orders = Vec::new();
        for (index, item) in items.iter().enumerate() {
            let mut rest = items.to_vec();
            rest.remove(index);
            for mut tail in permutations(&rest) {
                tail.insert(0, *item);
                orders.push(tail);
            }
        }
        orders
    }
}