vespera_macro 0.3.1

Procedural macros for Vespera - automatic route discovery and OpenAPI generation
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
//! Route attribute macro implementation.
//!
//! This module implements the `#[vespera::route]` attribute macro that validates
//! and processes handler functions for route registration.
//!
//! # Overview
//!
//! The `#[route]` attribute is applied to handler functions to:
//! - Validate that the function is `pub async fn`
//! - Parse route configuration (HTTP method, path, tags, etc.)
//! - Mark the function for route discovery by the `vespera!` macro
//!
//! # Route Requirements
//!
//! All handler functions must:
//! - Be public (`pub`)
//! - Be async (`async fn`)
//! - Accept standard Axum extractors (Path, Query, Json, etc.)
//! - Return a response type (Json, String, `StatusCode`, etc.)
//!
//! # Key Functions
//!
//! - [`validate_route_fn`] - Validate route function signature
//! - [`process_route_attribute`] - Parse and process the route attribute
//!
//! # Example
//!
//! ```ignore
//! #[vespera::route(get, path = "/{id}", tags = ["users"])]
//! pub async fn get_user(Path(id): Path<u32>) -> Json<User> {
//!     Json(User { id, name: "Alice".into() })
//! }
//! ```

use std::collections::HashMap;
use std::sync::{Arc, LazyLock, Mutex};

use crate::macro_storage::{CrateStorage, SourceIdentified};
use crate::{args, metadata::HeaderParam};
/// Metadata stored by `#[route]` for later consumption by `vespera!()`.
///
/// Each invocation of `#[route]` pushes one entry into [`ROUTE_STORAGE`].
/// The `vespera!()` macro reads this storage to supplement file-based
/// route discovery — when `file_path` is populated, the collector can
/// build route metadata directly from this struct without re-parsing
/// the source file with `syn::parse_file()`.
#[derive(Debug, Clone)]
pub struct StoredRouteInfo {
    /// Function name (e.g., `"get_user"`).
    pub fn_name: String,
    /// HTTP method (e.g., `"get"`, `"post"`).  Used by the collector's
    /// fast path ([`crate::collector`]) to populate `RouteMetadata.method`
    /// without re-parsing the source file.
    pub method: Option<String>,
    /// Custom path from `path = "/{id}"`.  Used by the collector to
    /// derive the full route URL when present.
    pub custom_path: Option<String>,
    /// Declared non-200 success status from `status = <u16>` (validated 2xx).
    pub success_status: Option<u16>,
    /// Additional error status codes from `error_status = [400, 404]`.
    pub error_status: Option<Vec<u16>>,
    /// Typed error responses from `responses = [(404, NotFoundError)]`.
    pub typed_responses: Option<Vec<(u16, String)>>,
    /// Tags for `OpenAPI` grouping from `tags = ["users"]`.
    pub tags: Option<Vec<String>>,
    /// Per-route security requirements from `security = ["bearerAuth"]`.
    pub security: Option<Vec<String>>,
    /// Header parameters from `headers = [{ name = "Authorization" }]`.
    pub headers: Vec<HeaderParam>,
    /// Explicit OpenAPI operationId from `operation_id = "getUser"`.
    pub operation_id: Option<String>,
    /// OpenAPI operation summary from `summary = "Get user"`.
    pub summary: Option<String>,
    /// Operation-level request example.
    pub request_example: Option<serde_json::Value>,
    /// Operation-level response example.
    pub response_example: Option<serde_json::Value>,
    /// Whether the operation is deprecated via bare `deprecated`.
    pub deprecated: bool,
    /// Description from `description = "Get user by ID"`.
    pub description: Option<String>,
    /// Source file path from `Span::call_site().local_file()` (requires Rust 1.88+).
    /// `None` on older Rust — collector falls back to full file parsing.
    pub file_path: Option<String>,
    /// Function signature as a string. Re-parsed via `syn::parse_str()` by
    /// [`crate::openapi_generator`] when the source file AST is unavailable.
    /// Stores only `syn::Signature` tokens, not the handler body.
    pub fn_sig_str: String,
}

/// Per-crate storage for route metadata collected by `#[route]` attribute
/// macros, read by `vespera!()` / `export_app!()` to supplement file-based
/// route discovery.
///
/// Keyed by [`crate::schema_impl::current_crate_key`] so a long-lived
/// rust-analyzer proc-macro server (one process, many crates) never feeds
/// crate A's routes into crate B's generated router/spec. See
/// [`SCHEMA_STORAGE`](crate::schema_impl::SCHEMA_STORAGE) for the rationale.
pub static ROUTE_STORAGE: CrateStorage<StoredRouteInfo> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

impl SourceIdentified for StoredRouteInfo {
    fn fn_name(&self) -> &str {
        &self.fn_name
    }
    fn file_path(&self) -> Option<&str> {
        self.file_path.as_deref()
    }
}

/// Replace-insert a `#[route]` metadata entry in the current crate's bucket.
pub fn register_route(info: StoredRouteInfo) {
    crate::macro_storage::register(&ROUTE_STORAGE, info);
}

/// Snapshot of the current crate's registered routes — a cheap `Arc` clone, so
/// consumers never deep-clone every stored function signature string.
#[must_use]
pub fn current_crate_routes() -> Arc<Vec<StoredRouteInfo>> {
    crate::macro_storage::current_crate_items(&ROUTE_STORAGE)
}

/// Extract `u16` error status codes from a `syn::ExprArray`.
fn extract_error_status_codes(arr: &syn::ExprArray) -> Option<Vec<u16>> {
    let codes: Vec<u16> = arr
        .elems
        .iter()
        .filter_map(|elem| {
            if let syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Int(lit_int),
                ..
            }) = elem
            {
                lit_int.base10_parse::<u16>().ok()
            } else {
                None
            }
        })
        .collect();
    if codes.is_empty() { None } else { Some(codes) }
}

/// Reject any non-string-literal element of a `[...]` attribute array with a
/// spanned compile error instead of silently dropping it.  A typo such as
/// `security = [bearerAuth]` (missing quotes) or `tags = [users]` would
/// otherwise vanish — and for `security` that silently documents a PROTECTED
/// route as unauthenticated, so this guard is security-relevant.
fn require_string_literal_elems(arr: &syn::ExprArray, attr_name: &str) -> syn::Result<()> {
    for elem in &arr.elems {
        if !matches!(
            elem,
            syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Str(_),
                ..
            })
        ) {
            return Err(syn::Error::new_spanned(
                elem,
                format!(
                    "#[route] `{attr_name}` entries must be string literals, e.g. `{attr_name} = [\"name\"]`"
                ),
            ));
        }
    }
    Ok(())
}

/// Collect every `syn::Lit::Str` value from a validated array.  Call only after
/// [`require_string_literal_elems`] so non-string elements cannot slip through.
fn collect_string_literal_values(arr: &syn::ExprArray) -> Vec<String> {
    arr.elems
        .iter()
        .filter_map(|elem| {
            if let syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Str(lit_str),
                ..
            }) = elem
            {
                Some(lit_str.value())
            } else {
                None
            }
        })
        .collect()
}

/// Extract `String` tags from a `syn::ExprArray`, erroring on any non-string
/// entry.  An all-empty / no-string array yields `None`.
fn extract_tag_strings(arr: &syn::ExprArray) -> syn::Result<Option<Vec<String>>> {
    require_string_literal_elems(arr, "tags")?;
    let tags = collect_string_literal_values(arr);
    Ok(if tags.is_empty() { None } else { Some(tags) })
}

/// Extract security scheme names from a `syn::ExprArray`, erroring on any
/// non-string entry.
///
/// Unlike tags, an empty array is meaningful: `security = []` disables
/// inherited/global security for that operation in OpenAPI.
fn extract_security_strings(arr: &syn::ExprArray) -> syn::Result<Vec<String>> {
    require_string_literal_elems(arr, "security")?;
    Ok(collect_string_literal_values(arr))
}

fn parse_example_string(lit: &syn::LitStr) -> serde_json::Value {
    let value = lit.value();
    serde_json::from_str(&value).unwrap_or(serde_json::Value::String(value))
}

/// Extract typed response status/schema pairs from `responses = [(404, NotFoundError)]`.
fn extract_typed_responses(arr: &syn::ExprArray) -> Option<Vec<(u16, String)>> {
    let responses: Vec<(u16, String)> = arr
        .elems
        .iter()
        .filter_map(|elem| {
            let syn::Expr::Tuple(tuple) = elem else {
                return None;
            };
            let status = tuple.elems.first().and_then(|status| {
                if let syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Int(lit_int),
                    ..
                }) = status
                {
                    lit_int.base10_parse::<u16>().ok()
                } else {
                    None
                }
            })?;
            let schema_name = tuple.elems.get(1).and_then(|schema| {
                if let syn::Expr::Path(path) = schema {
                    path.path.segments.last().map(|seg| seg.ident.to_string())
                } else {
                    None
                }
            })?;
            Some((status, schema_name))
        })
        .collect();

    if responses.is_empty() {
        None
    } else {
        Some(responses)
    }
}

/// Validate route function - must be pub and async
pub fn validate_route_fn(item_fn: &syn::ItemFn) -> Result<(), syn::Error> {
    if !matches!(item_fn.vis, syn::Visibility::Public(_)) {
        return Err(syn::Error::new_spanned(
            item_fn.sig.fn_token,
            "#[route] attribute: function must be public. Add `pub` before `fn`.",
        ));
    }
    if item_fn.sig.asyncness.is_none() {
        return Err(syn::Error::new_spanned(
            item_fn.sig.fn_token,
            "#[route] attribute: function must be async. Add `async` before `fn`.",
        ));
    }
    Ok(())
}

/// Process route attribute - extracted for testability
pub fn process_route_attribute(
    attr: proc_macro2::TokenStream,
    item: proc_macro2::TokenStream,
) -> syn::Result<proc_macro2::TokenStream> {
    let route_args = syn::parse2::<args::RouteArgs>(attr)?;
    let item_fn: syn::ItemFn = syn::parse2(item.clone()).map_err(|e| syn::Error::new(e.span(), "#[route] attribute: can only be applied to functions, not other items. Move or remove the attribute."))?;
    validate_route_fn(&item_fn)?;
    let fn_sig = &item_fn.sig;

    // Store route metadata for later consumption by vespera!() macro
    let stored = StoredRouteInfo {
        fn_name: item_fn.sig.ident.to_string(),
        method: route_args.method.as_ref().map(syn::Ident::to_string),
        custom_path: route_args.path.as_ref().map(syn::LitStr::value),
        success_status: route_args.success_status,
        error_status: route_args
            .error_status
            .as_ref()
            .and_then(extract_error_status_codes),
        typed_responses: route_args
            .responses
            .as_ref()
            .and_then(extract_typed_responses),
        tags: match route_args.tags.as_ref() {
            Some(arr) => extract_tag_strings(arr)?,
            None => None,
        },
        security: match route_args.security.as_ref() {
            Some(arr) => Some(extract_security_strings(arr)?),
            None => None,
        },
        headers: route_args.headers.unwrap_or_default(),
        operation_id: route_args.operation_id.as_ref().map(syn::LitStr::value),
        summary: route_args.summary.as_ref().map(syn::LitStr::value),
        request_example: route_args
            .request_example
            .as_ref()
            .map(parse_example_string),
        response_example: route_args
            .response_example
            .as_ref()
            .map(parse_example_string),
        deprecated: route_args.deprecated,
        description: route_args
            .description
            .as_ref()
            .map(syn::LitStr::value)
            .or_else(|| crate::route::extract_doc_comment(&item_fn.attrs)),
        fn_sig_str: quote::quote!(#fn_sig).to_string(),
        file_path: proc_macro2::Span::call_site()
            .local_file()
            .map(|p| p.display().to_string()),
    };
    register_route(stored);

    Ok(item)
}

#[cfg(test)]
mod tests {
    use quote::quote;
    use rstest::rstest;

    use super::*;

    // ========== Tests for validate_route_fn ==========

    #[test]
    fn test_validate_route_fn_not_public() {
        let item: syn::ItemFn = syn::parse_quote! {
            async fn private_handler() -> String {
                "test".to_string()
            }
        };
        let result = validate_route_fn(&item);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("function must be public")
        );
    }

    #[test]
    fn test_validate_route_fn_not_async() {
        let item: syn::ItemFn = syn::parse_quote! {
            pub fn sync_handler() -> String {
                "test".to_string()
            }
        };
        let result = validate_route_fn(&item);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("function must be async")
        );
    }

    #[test]
    fn test_validate_route_fn_valid() {
        let item: syn::ItemFn = syn::parse_quote! {
            pub async fn valid_handler() -> String {
                "test".to_string()
            }
        };
        let result = validate_route_fn(&item);
        assert!(result.is_ok());
    }

    // ========== Tests for process_route_attribute ==========

    #[test]
    fn test_process_route_attribute_valid() {
        let attr = quote!(get);
        let item = quote!(
            pub async fn handler() -> String {
                "ok".to_string()
            }
        );
        let result = process_route_attribute(attr, item.clone());
        assert!(result.is_ok());
        // Should return the original item unchanged
        assert_eq!(result.unwrap().to_string(), item.to_string());
    }

    #[test]
    fn test_process_route_attribute_invalid_attr() {
        let attr = quote!(invalid_method);
        let item = quote!(
            pub async fn handler() -> String {
                "ok".to_string()
            }
        );
        let result = process_route_attribute(attr, item);
        assert!(result.is_err());
    }

    #[test]
    fn test_process_route_attribute_not_function() {
        let attr = quote!(get);
        let item = quote!(
            struct NotAFunction;
        );
        let result = process_route_attribute(attr, item);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("can only be applied to functions"));
    }

    #[test]
    fn test_process_route_attribute_not_public() {
        let attr = quote!(get);
        let item = quote!(
            async fn private_handler() -> String {
                "ok".to_string()
            }
        );
        let result = process_route_attribute(attr, item);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("function must be public"));
    }

    #[test]
    fn test_process_route_attribute_not_async() {
        let attr = quote!(get);
        let item = quote!(
            pub fn sync_handler() -> String {
                "ok".to_string()
            }
        );
        let result = process_route_attribute(attr, item);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("function must be async"));
    }

    #[test]
    fn test_process_route_attribute_with_path() {
        let attr = quote!(get, path = "/users/{id}");
        let item = quote!(
            pub async fn get_user() -> String {
                "user".to_string()
            }
        );
        let result = process_route_attribute(attr, item);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_route_attribute_with_tags() {
        let attr = quote!(post, tags = ["users", "admin"]);
        let item = quote!(
            pub async fn create_user() -> String {
                "created".to_string()
            }
        );
        let result = process_route_attribute(attr, item);
        assert!(result.is_ok());
    }

    #[test]
    fn test_process_route_attribute_all_methods() {
        let methods = ["get", "post", "put", "patch", "delete", "head", "options"];
        for method in methods {
            let attr: proc_macro2::TokenStream = method.parse().unwrap();
            let item = quote!(
                pub async fn handler() -> String {
                    "ok".to_string()
                }
            );
            let result = process_route_attribute(attr, item);
            assert!(result.is_ok(), "Method {method} should be valid");
        }
    }

    // ========== Tests for ROUTE_STORAGE population ==========

    #[test]
    fn test_route_storage_populated_by_process_route_attribute() {
        let attr = quote!(
            get,
            path = "/{id}",
            tags = ["users"],
            description = "Get user by ID",
            error_status = [404]
        );
        let item = quote!(
            pub async fn get_user_test_storage() -> String {
                "test".to_string()
            }
        );
        let result = process_route_attribute(attr, item);
        assert!(result.is_ok());

        // Find our entry by unique fn_name (the current crate's routes are
        // shared across parallel tests in this crate).
        let storage = current_crate_routes();

        // Find our entry and verify fields
        let stored = storage
            .iter()
            .find(|s| s.fn_name == "get_user_test_storage");
        assert!(
            stored.is_some(),
            "StoredRouteInfo should be in ROUTE_STORAGE"
        );
        let stored = stored.unwrap();
        assert_eq!(stored.method, Some("get".to_string()));
        assert_eq!(stored.custom_path, Some("/{id}".to_string()));
        assert_eq!(stored.tags, Some(vec!["users".to_string()]));
        assert_eq!(stored.description, Some("Get user by ID".to_string()));
        assert_eq!(stored.error_status, Some(vec![404]));
        assert!(stored.headers.is_empty());
        assert!(stored.fn_sig_str.contains("get_user_test_storage"));
    }

    #[test]
    fn test_route_storage_no_optional_fields() {
        let attr = quote!();
        let item = quote!(
            pub async fn minimal_handler_test() -> String {
                "test".to_string()
            }
        );
        let result = process_route_attribute(attr, item);
        assert!(result.is_ok());

        let storage = current_crate_routes();

        let stored = storage.iter().find(|s| s.fn_name == "minimal_handler_test");
        assert!(stored.is_some());
        let stored = stored.unwrap();
        assert_eq!(stored.method, None);
        assert_eq!(stored.custom_path, None);
        assert_eq!(stored.tags, None);
        assert_eq!(stored.description, None);
        assert_eq!(stored.error_status, None);
        assert!(stored.headers.is_empty());
    }

    #[test]
    fn test_register_route_replaces_same_file_and_function() {
        let file_path = Some("/tmp/vespera/routes/replaced.rs".to_string());
        let fn_name = "__test_replace_route".to_string();
        let base = StoredRouteInfo {
            fn_name: fn_name.clone(),
            method: Some("get".to_string()),
            custom_path: Some("/before".to_string()),
            success_status: None,
            error_status: None,
            typed_responses: None,
            tags: None,
            security: None,
            headers: Vec::new(),
            operation_id: None,
            summary: None,
            request_example: None,
            response_example: None,
            deprecated: false,
            description: None,
            file_path: file_path.clone(),
            fn_sig_str: "pub async fn __test_replace_route ()".to_string(),
        };
        register_route(base);
        register_route(StoredRouteInfo {
            method: Some("post".to_string()),
            custom_path: Some("/after".to_string()),
            file_path,
            fn_sig_str: "pub async fn __test_replace_route ()".to_string(),
            ..current_crate_routes()
                .iter()
                .find(|entry| entry.fn_name == fn_name)
                .cloned()
                .expect("first route registration should exist")
        });

        let matches: Vec<_> = current_crate_routes()
            .iter()
            .filter(|entry| entry.fn_name == fn_name)
            .cloned()
            .collect();
        assert_eq!(matches.len(), 1, "same source route should replace");
        assert_eq!(matches[0].method, Some("post".to_string()));
        assert_eq!(matches[0].custom_path, Some("/after".to_string()));
    }

    #[test]
    fn test_extract_error_status_codes_empty() {
        let arr: syn::ExprArray = syn::parse_quote!([]);
        assert_eq!(extract_error_status_codes(&arr), None);
    }

    #[test]
    fn test_extract_error_status_codes_values() {
        let arr: syn::ExprArray = syn::parse_quote!([400, 404, 500]);
        assert_eq!(extract_error_status_codes(&arr), Some(vec![400, 404, 500]));
    }

    #[test]
    fn test_extract_tag_strings_empty() {
        let arr: syn::ExprArray = syn::parse_quote!([]);
        assert_eq!(extract_tag_strings(&arr).unwrap(), None);
    }

    #[test]
    fn test_extract_tag_strings_values() {
        let arr: syn::ExprArray = syn::parse_quote!(["users", "admin", "api"]);
        assert_eq!(
            extract_tag_strings(&arr).unwrap(),
            Some(vec![
                "users".to_string(),
                "admin".to_string(),
                "api".to_string()
            ])
        );
    }

    #[test]
    fn test_extract_tag_strings_rejects_non_string() {
        // `tags = [users]` (bare ident, missing quotes) must be a compile
        // error, not silently dropped.
        let arr: syn::ExprArray = syn::parse_quote!([users]);
        let err = extract_tag_strings(&arr).expect_err("non-string tag must error");
        assert!(err.to_string().contains("string literals"), "{err}");
    }

    #[test]
    fn test_extract_security_strings_values() {
        let arr: syn::ExprArray = syn::parse_quote!(["bearerAuth", "apiKey"]);
        assert_eq!(
            extract_security_strings(&arr).unwrap(),
            vec!["bearerAuth".to_string(), "apiKey".to_string()]
        );
    }

    #[test]
    fn test_extract_security_strings_empty_is_ok() {
        // `security = []` is meaningful (explicit no-auth) and must NOT error.
        let arr: syn::ExprArray = syn::parse_quote!([]);
        assert_eq!(
            extract_security_strings(&arr).unwrap(),
            Vec::<String>::new()
        );
    }

    #[test]
    fn test_extract_security_strings_rejects_non_string() {
        // `security = [bearerAuth]` (missing quotes) must error rather than
        // silently documenting a protected route as unauthenticated.
        let arr: syn::ExprArray = syn::parse_quote!([bearerAuth]);
        let err = extract_security_strings(&arr).expect_err("non-string security must error");
        assert!(err.to_string().contains("string literals"), "{err}");
    }

    #[test]
    fn low_level_collectors_ignore_non_literal_entries() {
        let statuses: syn::ExprArray = syn::parse_quote!([400, BAD_REQUEST, "404", 70_000]);
        let strings: syn::ExprArray = syn::parse_quote!(["users", admin, 7]);

        assert_eq!(extract_error_status_codes(&statuses), Some(vec![400]));
        assert_eq!(
            collect_string_literal_values(&strings),
            vec!["users".to_string()]
        );
    }

    #[rstest]
    #[case::json_array("[1,2]", serde_json::json!([1, 2]))]
    #[case::plain_text("not json", serde_json::Value::String("not json".to_string()))]
    fn example_parser_preserves_json_or_falls_back_to_text(
        #[case] source: &str,
        #[case] expected: serde_json::Value,
    ) {
        let literal = syn::LitStr::new(source, proc_macro2::Span::call_site());

        assert_eq!(parse_example_string(&literal), expected);
    }

    #[rstest]
    #[case::empty(quote!([]), None)]
    #[case::not_a_tuple(quote!([NotFound]), None)]
    #[case::missing_status(quote!([()]), None)]
    #[case::non_integer_status(quote!([(NOT_FOUND, ErrorBody)]), None)]
    #[case::out_of_range_status(quote!([(70_000, ErrorBody)]), None)]
    #[case::missing_schema(quote!([(404,)]), None)]
    #[case::non_path_schema(quote!([(404, "ErrorBody")]), None)]
    #[case::qualified_schema(
        quote!([(404, crate::errors::NotFound)]),
        Some(vec![(404, "NotFound".to_string())])
    )]
    fn typed_response_extractor_accepts_only_status_path_tuples(
        #[case] source: proc_macro2::TokenStream,
        #[case] expected: Option<Vec<(u16, String)>>,
    ) {
        let array = syn::parse2::<syn::ExprArray>(source).expect("valid response array fixture");

        assert_eq!(extract_typed_responses(&array), expected);
    }
}