vespera_macro 0.3.0

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
/// Serde enum representation types
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SerdeEnumRepr {
    /// Default externally tagged: `{"VariantName": {...}}`
    ExternallyTagged,
    /// Internally tagged: `{"type": "VariantName", ...fields...}`
    /// Only valid for struct and unit variants
    InternallyTagged { tag: String },
    /// Adjacently tagged: `{"type": "VariantName", "data": {...}}`
    AdjacentlyTagged { tag: String, content: String },
    /// Untagged: `{...fields...}` (no tag, first matching variant wins)
    Untagged,
}

/// Extract serde enum representation from attributes.
///
/// Detects the enum tagging strategy from serde attributes:
/// - `#[serde(tag = "type")]` → `InternallyTagged`
/// - `#[serde(tag = "type", content = "data")]` → `AdjacentlyTagged`
/// - `#[serde(untagged)]` → Untagged
/// - No relevant attributes → `ExternallyTagged` (default)
pub fn extract_enum_repr(attrs: &[syn::Attribute]) -> SerdeEnumRepr {
    let tag = extract_tag(attrs);
    let content = extract_content(attrs);
    let untagged = extract_untagged(attrs);

    if untagged {
        SerdeEnumRepr::Untagged
    } else if let Some(tag_name) = tag {
        if let Some(content_name) = content {
            SerdeEnumRepr::AdjacentlyTagged {
                tag: tag_name,
                content: content_name,
            }
        } else {
            SerdeEnumRepr::InternallyTagged { tag: tag_name }
        }
    } else {
        SerdeEnumRepr::ExternallyTagged
    }
}

/// Extract tag attribute from serde container attributes
/// Returns the tag name if `#[serde(tag = "...")]` is present
pub fn extract_tag(attrs: &[syn::Attribute]) -> Option<String> {
    for attr in attrs {
        if attr.path().is_ident("serde") {
            let mut found_tag = None;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("tag")
                    && let Ok(value) = meta.value()
                    && let Ok(syn::Expr::Lit(syn::ExprLit {
                        lit: syn::Lit::Str(s),
                        ..
                    })) = value.parse::<syn::Expr>()
                {
                    found_tag = Some(s.value());
                }
                Ok(())
            });
            if found_tag.is_some() {
                return found_tag;
            }

            // Fallback: manual token parsing
            let Ok(tokens) = attr.meta.require_list() else {
                continue;
            };
            let token_str = tokens.tokens.to_string();

            if let Some(start) = token_str.find("tag") {
                // Ensure it's "tag" not "untagged"
                let before = if start > 0 { &token_str[..start] } else { "" };
                let before_char = before.chars().last().unwrap_or(' ');
                if before_char != 'n' {
                    // Not "untagged"
                    let remaining = &token_str[start + "tag".len()..];
                    if let Some(equals_pos) = remaining.find('=') {
                        let value_part = remaining[equals_pos + 1..].trim();
                        if let Some(quote_start) = value_part.find('"') {
                            let after_quote = &value_part[quote_start + 1..];
                            if let Some(quote_end) = after_quote.find('"') {
                                let value = &after_quote[..quote_end];
                                return Some(value.to_string());
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

/// Extract content attribute from serde container attributes
/// Returns the content name if `#[serde(content = "...")]` is present
pub fn extract_content(attrs: &[syn::Attribute]) -> Option<String> {
    for attr in attrs {
        if attr.path().is_ident("serde") {
            let mut found_content = None;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("content")
                    && let Ok(value) = meta.value()
                    && let Ok(syn::Expr::Lit(syn::ExprLit {
                        lit: syn::Lit::Str(s),
                        ..
                    })) = value.parse::<syn::Expr>()
                {
                    found_content = Some(s.value());
                }
                Ok(())
            });
            if found_content.is_some() {
                return found_content;
            }

            // Fallback: manual token parsing
            let Ok(tokens) = attr.meta.require_list() else {
                continue;
            };
            let token_str = tokens.tokens.to_string();

            if let Some(start) = token_str.find("content") {
                let remaining = &token_str[start + "content".len()..];
                if let Some(equals_pos) = remaining.find('=') {
                    let value_part = remaining[equals_pos + 1..].trim();
                    if let Some(quote_start) = value_part.find('"') {
                        let after_quote = &value_part[quote_start + 1..];
                        if let Some(quote_end) = after_quote.find('"') {
                            let value = &after_quote[..quote_end];
                            return Some(value.to_string());
                        }
                    }
                }
            }
        }
    }
    None
}

/// Extract untagged attribute from serde container attributes
/// Returns true if `#[serde(untagged)]` is present
pub fn extract_untagged(attrs: &[syn::Attribute]) -> bool {
    for attr in attrs {
        if attr.path().is_ident("serde") {
            let mut found = false;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("untagged") {
                    found = true;
                }
                Ok(())
            });
            if found {
                return true;
            }

            // Fallback: manual token parsing
            if let syn::Meta::List(meta_list) = &attr.meta {
                let tokens = meta_list.tokens.to_string();
                if let Some(pos) = tokens.find("untagged") {
                    let before = if pos > 0 { &tokens[..pos] } else { "" };
                    let after = &tokens[pos + "untagged".len()..];
                    let before_char = before.chars().last().unwrap_or(' ');
                    let after_char = after.chars().next().unwrap_or(' ');
                    if (before_char == ' ' || before_char == ',' || before_char == '(')
                        && (after_char == ' ' || after_char == ',' || after_char == ')')
                    {
                        return true;
                    }
                }
            }
        }
    }
    false
}

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

    fn get_enum_attrs(serde_content: &str) -> Vec<syn::Attribute> {
        let src = format!(r"#[serde({serde_content})] enum Foo {{ A, B }}");
        let item: syn::ItemEnum = syn::parse_str(&src).unwrap();
        item.attrs
    }

    // extract_tag tests
    #[rstest]
    #[case(r#"tag = "type""#, Some("type"))]
    #[case(r#"tag = "kind""#, Some("kind"))]
    #[case(r#"tag = "variant""#, Some("variant"))]
    #[case(r#"tag = "type", content = "data""#, Some("type"))]
    #[case(r#"rename_all = "camelCase""#, None)]
    #[case(r"untagged", None)]
    #[case(r"default", None)]
    fn test_extract_tag(#[case] serde_content: &str, #[case] expected: Option<&str>) {
        let attrs = get_enum_attrs(serde_content);
        let result = extract_tag(&attrs);
        assert_eq!(result.as_deref(), expected, "Failed for: {serde_content}");
    }

    // extract_content tests
    #[rstest]
    #[case(r#"content = "data""#, Some("data"))]
    #[case(r#"content = "payload""#, Some("payload"))]
    #[case(r#"tag = "type", content = "data""#, Some("data"))]
    #[case(r#"tag = "type""#, None)]
    #[case(r"untagged", None)]
    #[case(r#"rename_all = "camelCase""#, None)]
    fn test_extract_content(#[case] serde_content: &str, #[case] expected: Option<&str>) {
        let attrs = get_enum_attrs(serde_content);
        let result = extract_content(&attrs);
        assert_eq!(result.as_deref(), expected, "Failed for: {serde_content}");
    }

    // extract_untagged tests
    #[rstest]
    #[case(r"untagged", true)]
    #[case(r#"untagged, rename_all = "camelCase""#, true)]
    #[case(r#"rename_all = "camelCase", untagged"#, true)]
    #[case(r#"tag = "type""#, false)]
    #[case(r#"rename_all = "camelCase""#, false)]
    #[case(r"default", false)]
    fn test_extract_untagged(#[case] serde_content: &str, #[case] expected: bool) {
        let attrs = get_enum_attrs(serde_content);
        let result = extract_untagged(&attrs);
        assert_eq!(result, expected, "Failed for: {serde_content}");
    }

    // extract_enum_repr comprehensive tests
    #[test]
    fn test_extract_enum_repr_externally_tagged() {
        // No serde tag attributes - default is externally tagged
        let attrs = get_enum_attrs(r#"rename_all = "camelCase""#);
        let repr = extract_enum_repr(&attrs);
        assert_eq!(repr, SerdeEnumRepr::ExternallyTagged);
    }

    #[test]
    fn test_extract_enum_repr_internally_tagged() {
        let attrs = get_enum_attrs(r#"tag = "type""#);
        let repr = extract_enum_repr(&attrs);
        assert_eq!(
            repr,
            SerdeEnumRepr::InternallyTagged {
                tag: "type".to_string()
            }
        );
    }

    #[test]
    fn test_extract_enum_repr_internally_tagged_custom_name() {
        let attrs = get_enum_attrs(r#"tag = "kind""#);
        let repr = extract_enum_repr(&attrs);
        assert_eq!(
            repr,
            SerdeEnumRepr::InternallyTagged {
                tag: "kind".to_string()
            }
        );
    }

    #[test]
    fn test_extract_enum_repr_adjacently_tagged() {
        let attrs = get_enum_attrs(r#"tag = "type", content = "data""#);
        let repr = extract_enum_repr(&attrs);
        assert_eq!(
            repr,
            SerdeEnumRepr::AdjacentlyTagged {
                tag: "type".to_string(),
                content: "data".to_string()
            }
        );
    }

    #[test]
    fn test_extract_enum_repr_adjacently_tagged_custom_names() {
        let attrs = get_enum_attrs(r#"tag = "kind", content = "payload""#);
        let repr = extract_enum_repr(&attrs);
        assert_eq!(
            repr,
            SerdeEnumRepr::AdjacentlyTagged {
                tag: "kind".to_string(),
                content: "payload".to_string()
            }
        );
    }

    #[test]
    fn test_extract_enum_repr_untagged() {
        let attrs = get_enum_attrs(r"untagged");
        let repr = extract_enum_repr(&attrs);
        assert_eq!(repr, SerdeEnumRepr::Untagged);
    }

    #[test]
    fn test_extract_enum_repr_untagged_with_other_attrs() {
        let attrs = get_enum_attrs(r#"untagged, rename_all = "camelCase""#);
        let repr = extract_enum_repr(&attrs);
        assert_eq!(repr, SerdeEnumRepr::Untagged);
    }

    #[test]
    fn test_extract_enum_repr_no_serde_attrs() {
        let item: syn::ItemEnum = syn::parse_str("enum Foo { A, B }").unwrap();
        let repr = extract_enum_repr(&item.attrs);
        assert_eq!(repr, SerdeEnumRepr::ExternallyTagged);
    }

    // Test that content without tag is still externally tagged (content alone is meaningless)
    #[test]
    fn test_extract_enum_repr_content_without_tag() {
        let attrs = get_enum_attrs(r#"content = "data""#);
        let repr = extract_enum_repr(&attrs);
        // Content without tag should be externally tagged (content is ignored)
        assert_eq!(repr, SerdeEnumRepr::ExternallyTagged);
    }

    // =================================================================
    // FALLBACK PATH TESTS FOR TAG/CONTENT (Lines 573, 583-590, 626)
    // =================================================================

    use proc_macro2::{Span, TokenStream};

    /// Helper to create a serde attribute with raw tokens
    fn create_enum_attr_with_raw_tokens(tokens: TokenStream) -> syn::Attribute {
        syn::Attribute {
            pound_token: syn::token::Pound::default(),
            style: syn::AttrStyle::Outer,
            bracket_token: syn::token::Bracket::default(),
            meta: syn::Meta::List(syn::MetaList {
                path: syn::Path::from(syn::Ident::new("serde", Span::call_site())),
                delimiter: syn::MacroDelimiter::Paren(syn::token::Paren::default()),
                tokens,
            }),
        }
    }

    /// Test extract_tag fallback path - Lines 573, 583-590
    /// Forces manual token parsing by using qualified path
    #[test]
    fn test_extract_tag_fallback_path() {
        let tokens: TokenStream = "my_module::tag = \"type\"".parse().unwrap();
        let attr = create_enum_attr_with_raw_tokens(tokens);
        let result = extract_tag(&[attr]);
        assert_eq!(
            result.as_deref(),
            Some("type"),
            "Fallback should extract tag value"
        );
    }

    /// Test extract_tag fallback with complex attributes
    /// Lines 583-590: Tests the value extraction in fallback
    #[test]
    fn test_extract_tag_fallback_complex() {
        let tokens: TokenStream = "crate::tag = \"kind\", rename_all = \"camelCase\""
            .parse()
            .unwrap();
        let attr = create_enum_attr_with_raw_tokens(tokens);
        let result = extract_tag(&[attr]);
        assert_eq!(result.as_deref(), Some("kind"));
    }

    /// Test extract_tag fallback doesn't match "untagged"
    /// Line 581: before_char != 'n' check
    #[test]
    fn test_extract_tag_fallback_avoids_untagged() {
        // "untagged" contains "tag" but should not be matched as tag = "..."
        let tokens: TokenStream = "untagged".parse().unwrap();
        let attr = create_enum_attr_with_raw_tokens(tokens);
        let result = extract_tag(&[attr]);
        assert_eq!(result, None, "Should not extract tag from 'untagged'");
    }

    /// Test extract_tag fallback with tag after other attributes
    #[test]
    fn test_extract_tag_fallback_at_end() {
        let tokens: TokenStream = "default, some_module::tag = \"variant\"".parse().unwrap();
        let attr = create_enum_attr_with_raw_tokens(tokens);
        let result = extract_tag(&[attr]);
        assert_eq!(result.as_deref(), Some("variant"));
    }

    /// Test extract_content fallback path - Line 626
    /// Forces manual token parsing by using qualified path
    #[test]
    fn test_extract_content_fallback_path() {
        let tokens: TokenStream = "my_module::content = \"data\"".parse().unwrap();
        let attr = create_enum_attr_with_raw_tokens(tokens);
        let result = extract_content(&[attr]);
        assert_eq!(
            result.as_deref(),
            Some("data"),
            "Fallback should extract content value"
        );
    }

    /// Test extract_content fallback with complex attributes
    /// Line 626+: Tests the fallback token parsing branch
    #[test]
    fn test_extract_content_fallback_complex() {
        let tokens: TokenStream = "crate::tag = \"type\", other::content = \"payload\""
            .parse()
            .unwrap();
        let attr = create_enum_attr_with_raw_tokens(tokens);
        let result = extract_content(&[attr]);
        assert_eq!(result.as_deref(), Some("payload"));
    }

    /// Test extract_content fallback with content at different position
    #[test]
    fn test_extract_content_fallback_at_start() {
        let tokens: TokenStream = "some::content = \"body\", tag = \"kind\"".parse().unwrap();
        let attr = create_enum_attr_with_raw_tokens(tokens);
        let result = extract_content(&[attr]);
        assert_eq!(result.as_deref(), Some("body"));
    }

    /// Test adjacently tagged using fallback paths for both tag and content
    #[test]
    fn test_extract_enum_repr_adjacently_tagged_fallback() {
        let tokens: TokenStream = "mod1::tag = \"type\", mod2::content = \"data\""
            .parse()
            .unwrap();
        let attr = create_enum_attr_with_raw_tokens(tokens);
        let repr = extract_enum_repr(&[attr]);
        assert_eq!(
            repr,
            SerdeEnumRepr::AdjacentlyTagged {
                tag: "type".to_string(),
                content: "data".to_string()
            }
        );
    }

    /// Test internally tagged using fallback path
    #[test]
    fn test_extract_enum_repr_internally_tagged_fallback() {
        let tokens: TokenStream = "qualified::tag = \"discriminator\"".parse().unwrap();
        let attr = create_enum_attr_with_raw_tokens(tokens);
        let repr = extract_enum_repr(&[attr]);
        assert_eq!(
            repr,
            SerdeEnumRepr::InternallyTagged {
                tag: "discriminator".to_string()
            }
        );
    }

    /// Helper to create a path-only serde attribute (#[serde] without parentheses)
    /// This format causes require_list() to fail (returns Err)
    fn create_path_only_serde_attr() -> syn::Attribute {
        syn::Attribute {
            pound_token: syn::token::Pound::default(),
            style: syn::AttrStyle::Outer,
            bracket_token: syn::token::Bracket::default(),
            meta: syn::Meta::Path(syn::Path::from(syn::Ident::new("serde", Span::call_site()))),
        }
    }

    /// Test extract_tag with non-list serde attribute
    /// When require_list() fails, extract_tag should continue to next attribute
    #[test]
    fn test_extract_tag_non_list_attr_continues() {
        // First attr is path-only (#[serde]), second has the actual tag
        let path_attr = create_path_only_serde_attr();
        let list_attr = {
            let src = r#"#[serde(tag = "type")] enum Foo { A }"#;
            let item: syn::ItemEnum = syn::parse_str(src).unwrap();
            item.attrs.into_iter().next().unwrap()
        };

        // extract_tag should skip the path-only attr and find tag in second attr
        let result = extract_tag(&[path_attr, list_attr]);
        assert_eq!(result.as_deref(), Some("type"));
    }

    /// Test extract_tag with only non-list serde attribute returns None
    #[test]
    fn test_extract_tag_only_non_list_attr_returns_none() {
        let path_attr = create_path_only_serde_attr();
        let result = extract_tag(&[path_attr]);
        assert_eq!(result, None);
    }

    /// Test extract_content with non-list serde attribute
    /// When require_list() fails, extract_content should continue to next attribute
    #[test]
    fn test_extract_content_non_list_attr_continues() {
        // First attr is path-only (#[serde]), second has the actual content
        let path_attr = create_path_only_serde_attr();
        let list_attr = {
            let src = r#"#[serde(content = "data")] enum Foo { A }"#;
            let item: syn::ItemEnum = syn::parse_str(src).unwrap();
            item.attrs.into_iter().next().unwrap()
        };

        // extract_content should skip the path-only attr and find content in second attr
        let result = extract_content(&[path_attr, list_attr]);
        assert_eq!(result.as_deref(), Some("data"));
    }

    /// Test extract_content with only non-list serde attribute returns None
    #[test]
    fn test_extract_content_only_non_list_attr_returns_none() {
        let path_attr = create_path_only_serde_attr();
        let result = extract_content(&[path_attr]);
        assert_eq!(result, None);
    }

    #[test]
    fn untagged_takes_precedence_over_tag_and_content() {
        let attrs = get_enum_attrs(r#"untagged, tag = "type", content = "data""#);
        assert_eq!(extract_enum_repr(&attrs), SerdeEnumRepr::Untagged);
    }

    #[rstest]
    #[case("tag = 42")]
    #[case("tag = true")]
    #[case("tag = value")]
    fn non_string_tag_is_ignored(#[case] tokens: &str) {
        let attr = create_enum_attr_with_raw_tokens(tokens.parse().unwrap());
        assert_eq!(extract_tag(&[attr]), None);
    }

    #[rstest]
    #[case(r#"tag = "type", content = 42"#)]
    #[case(r#"tag = "type", content = true"#)]
    #[case(r#"tag = "type", content = value"#)]
    fn non_string_content_is_ignored(#[case] tokens: &str) {
        let attr = create_enum_attr_with_raw_tokens(tokens.parse().unwrap());
        assert_eq!(extract_content(&[attr]), None);
    }

    #[rstest]
    #[case(r#"qualified::tag = "type""#, Some("type"))]
    #[case("qualified::tag = value", None)]
    #[case("qualified::tag", None)]
    fn malformed_tag_fallback_is_exact(#[case] tokens: &str, #[case] expected: Option<&str>) {
        let attr = create_enum_attr_with_raw_tokens(tokens.parse().unwrap());
        assert_eq!(extract_tag(&[attr]).as_deref(), expected);
    }

    #[rstest]
    #[case(r#"qualified::content = "data""#, Some("data"))]
    #[case("qualified::content = value", None)]
    #[case("qualified::content", None)]
    fn malformed_content_fallback_is_exact(#[case] tokens: &str, #[case] expected: Option<&str>) {
        let attr = create_enum_attr_with_raw_tokens(tokens.parse().unwrap());
        assert_eq!(extract_content(&[attr]).as_deref(), expected);
    }
}