vespera_macro 0.1.38

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
use crate::{args::RouteArgs, http::is_http_method};

/// Extract doc comments from attributes
/// Returns concatenated doc comment string or None if no doc comments
pub fn extract_doc_comment(attrs: &[syn::Attribute]) -> Option<String> {
    let mut doc_lines = Vec::new();

    for attr in attrs {
        if attr.path().is_ident("doc")
            && let syn::Meta::NameValue(meta_nv) = &attr.meta
            && let syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Str(lit_str),
                ..
            }) = &meta_nv.value
        {
            let line = lit_str.value();
            // Trim leading space that rustdoc adds
            let trimmed = line.strip_prefix(' ').unwrap_or(&line);
            doc_lines.push(trimmed.to_string());
        }
    }

    if doc_lines.is_empty() {
        None
    } else {
        Some(doc_lines.join("\n"))
    }
}

#[derive(Debug)]
pub struct RouteInfo {
    pub method: String,
    pub path: Option<String>,
    pub error_status: Option<Vec<u16>>,
    pub tags: Option<Vec<String>>,
    pub description: Option<String>,
}

pub fn check_route_by_meta(meta: &syn::Meta) -> bool {
    match meta {
        syn::Meta::List(meta_list) => {
            (meta_list.path.segments.len() == 2
                && meta_list.path.segments[0].ident == "vespera"
                && meta_list.path.segments[1].ident == "route")
                || (meta_list.path.segments.len() == 1
                    && meta_list.path.segments[0].ident == "route")
        }
        syn::Meta::Path(path) => {
            (path.segments.len() == 2
                && path.segments[0].ident == "vespera"
                && path.segments[1].ident == "route")
                || (path.segments.len() == 1 && path.segments[0].ident == "route")
        }
        syn::Meta::NameValue(meta_nv) => {
            (meta_nv.path.segments.len() == 2
                && meta_nv.path.segments[0].ident == "vespera"
                && meta_nv.path.segments[1].ident == "route")
                || (meta_nv.path.segments.len() == 1 && meta_nv.path.segments[0].ident == "route")
        }
    }
}

pub fn extract_route_info(attrs: &[syn::Attribute]) -> Option<RouteInfo> {
    for attr in attrs {
        // Check if attribute path is "vespera" or "route"
        if check_route_by_meta(&attr.meta) {
            match &attr.meta {
                syn::Meta::List(meta_list) => {
                    // Try to parse as RouteArgs
                    if let Ok(route_args) = meta_list.parse_args::<RouteArgs>() {
                        let method = route_args
                            .method
                            .as_ref()
                            .map_or_else(|| "get".to_string(), syn::Ident::to_string);
                        let path = route_args.path.as_ref().map(syn::LitStr::value);

                        // Parse error_status array if present
                        let error_status = route_args.error_status.as_ref().and_then(|array| {
                            let mut status_codes = Vec::new();
                            for elem in &array.elems {
                                if let syn::Expr::Lit(syn::ExprLit {
                                    lit: syn::Lit::Int(lit_int),
                                    ..
                                }) = elem
                                    && let Ok(code) = lit_int.base10_parse::<u16>()
                                {
                                    status_codes.push(code);
                                }
                            }
                            if status_codes.is_empty() {
                                None
                            } else {
                                Some(status_codes)
                            }
                        });

                        // Parse tags array if present
                        let tags = route_args.tags.as_ref().and_then(|array| {
                            let mut tag_list = Vec::new();
                            for elem in &array.elems {
                                if let syn::Expr::Lit(syn::ExprLit {
                                    lit: syn::Lit::Str(lit_str),
                                    ..
                                }) = elem
                                {
                                    tag_list.push(lit_str.value());
                                }
                            }
                            if tag_list.is_empty() {
                                None
                            } else {
                                Some(tag_list)
                            }
                        });

                        // Parse description if present
                        let description = route_args.description.as_ref().map(syn::LitStr::value);

                        return Some(RouteInfo {
                            method,
                            path,
                            error_status,
                            tags,
                            description,
                        });
                    }
                }
                // Try to parse as Meta::NameValue (e.g., #[route = "patch"])
                syn::Meta::NameValue(meta_nv) => {
                    if let syn::Expr::Lit(syn::ExprLit {
                        lit: syn::Lit::Str(lit_str),
                        ..
                    }) = &meta_nv.value
                    {
                        let method_str = lit_str.value().to_lowercase();
                        if is_http_method(&method_str) {
                            return Some(RouteInfo {
                                method: method_str,
                                path: None,
                                error_status: None,
                                tags: None,
                                description: None,
                            });
                        }
                    }
                }
                // Try to parse as Meta::Path (e.g., #[route])
                syn::Meta::Path(_) => {
                    return Some(RouteInfo {
                        method: "get".to_string(),
                        path: None,
                        error_status: None,
                        tags: None,
                        description: None,
                    });
                }
            }
        }
    }
    None
}

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

    use super::*;

    fn parse_meta_from_attr(attr_str: &str) -> syn::Meta {
        // Parse attribute from string like "#[route()]" or "#[vespera::route(get)]"
        let full_code = format!("{attr_str} fn test() {{}}");
        let file: syn::File = syn::parse_str(&full_code).expect("Failed to parse with attribute");

        // Extract the first attribute from the function
        if let Some(syn::Item::Fn(fn_item)) = file.items.first()
            && let Some(attr) = fn_item.attrs.first()
        {
            return attr.meta.clone();
        }

        panic!("Failed to extract meta from attribute: {attr_str}");
    }

    #[rstest]
    // Valid route attributes (List meta)
    #[case("#[route()]", true)]
    #[case("#[vespera::route()]", true)]
    #[case("#[route(get)]", true)]
    #[case("#[vespera::route(get)]", true)]
    #[case("#[route(post)]", true)]
    #[case("#[vespera::route(post)]", true)]
    #[case("#[route(get, path = \"/api\")]", true)]
    #[case("#[vespera::route(get, path = \"/api\")]", true)]
    // Path meta (without parentheses) should return true
    #[case("#[route]", true)]
    #[case("#[vespera::route]", true)]
    // NameValue meta should return true
    #[case("#[route = \"get\"]", true)]
    #[case("#[vespera::route = \"get\"]", true)]
    // Invalid route attributes
    #[case("#[other()]", false)]
    #[case("#[vespera::other()]", false)]
    #[case("#[other(get)]", false)]
    #[case("#[vespera::other(get)]", false)]
    #[case("#[derive(Schema)]", false)]
    #[case("#[serde(rename_all = \"camelCase\")]", false)]
    #[case("#[test]", false)]
    // Nested paths with more than 2 segments should return false
    #[case("#[vespera::route::something]", false)]
    #[case("#[vespera::route::something()]", false)]
    fn test_check_route_by_meta(#[case] attr_str: &str, #[case] expected: bool) {
        let meta = parse_meta_from_attr(attr_str);
        let result = check_route_by_meta(&meta);
        assert_eq!(
            result, expected,
            "Failed for attribute: {attr_str}, expected: {expected}"
        );
    }

    fn parse_attrs_from_code(code: &str) -> Vec<syn::Attribute> {
        let file: syn::File = syn::parse_str(code).expect("Failed to parse code");
        if let Some(syn::Item::Fn(fn_item)) = file.items.first() {
            return fn_item.attrs.clone();
        }
        vec![]
    }

    #[rstest]
    // Route with method only
    #[case("#[route(get)] fn test() {}", Some(("get".to_string(), None, None)))]
    #[case("#[route(post)] fn test() {}", Some(("post".to_string(), None, None)))]
    #[case("#[route(put)] fn test() {}", Some(("put".to_string(), None, None)))]
    #[case("#[route(patch)] fn test() {}", Some(("patch".to_string(), None, None)))]
    #[case("#[route(delete)] fn test() {}", Some(("delete".to_string(), None, None)))]
    #[case("#[route(head)] fn test() {}", Some(("head".to_string(), None, None)))]
    #[case("#[route(options)] fn test() {}", Some(("options".to_string(), None, None)))]
    #[case("#[vespera::route(get)] fn test() {}", Some(("get".to_string(), None, None)))]
    // Route with method and path
    #[case("#[route(get, path = \"/api\")] fn test() {}", Some(("get".to_string(), Some("/api".to_string()), None)))]
    #[case("#[route(post, path = \"/users\")] fn test() {}", Some(("post".to_string(), Some("/users".to_string()), None)))]
    #[case("#[route(get, path = \"/api/v1\")] fn test() {}", Some(("get".to_string(), Some("/api/v1".to_string()), None)))]
    // Route with method and error_status
    #[case("#[route(get, error_status = [400])] fn test() {}", Some(("get".to_string(), None, Some(vec![400]))))]
    #[case("#[route(get, error_status = [400, 404])] fn test() {}", Some(("get".to_string(), None, Some(vec![400, 404]))))]
    #[case("#[route(get, error_status = [400, 404, 500])] fn test() {}", Some(("get".to_string(), None, Some(vec![400, 404, 500]))))]
    // Route with method, path, and error_status
    #[case("#[route(get, path = \"/api\", error_status = [400])] fn test() {}", Some(("get".to_string(), Some("/api".to_string()), Some(vec![400]))))]
    #[case("#[route(post, path = \"/users\", error_status = [400, 404])] fn test() {}", Some(("post".to_string(), Some("/users".to_string()), Some(vec![400, 404]))))]
    // Route without method (defaults to "get")
    #[case("#[route()] fn test() {}", Some(("get".to_string(), None, None)))]
    #[case("#[route(path = \"/api\")] fn test() {}", Some(("get".to_string(), Some("/api".to_string()), None)))]
    // Route with Path meta (e.g., #[route])
    #[case("#[route] fn test() {}", Some(("get".to_string(), None, None)))]
    #[case("#[vespera::route] fn test() {}", Some(("get".to_string(), None, None)))]
    // Route with empty error_status array (should return None for error_status)
    #[case("#[route(get, error_status = [])] fn test() {}", Some(("get".to_string(), None, None)))]
    // NameValue format (should work now)
    #[case("#[route = \"get\"] fn test() {}", Some(("get".to_string(), None, None)))]
    #[case("#[route = \"post\"] fn test() {}", Some(("post".to_string(), None, None)))]
    #[case("#[route = \"put\"] fn test() {}", Some(("put".to_string(), None, None)))]
    #[case("#[route = \"patch\"] fn test() {}", Some(("patch".to_string(), None, None)))]
    #[case("#[route = \"delete\"] fn test() {}", Some(("delete".to_string(), None, None)))]
    #[case("#[route = \"head\"] fn test() {}", Some(("head".to_string(), None, None)))]
    #[case("#[route = \"options\"] fn test() {}", Some(("options".to_string(), None, None)))]
    #[case("#[vespera::route = \"get\"] fn test() {}", Some(("get".to_string(), None, None)))]
    // Invalid cases (should return None)
    #[case("#[other(get)] fn test() {}", None)]
    #[case("#[derive(Schema)] fn test() {}", None)]
    #[case("#[test] fn test() {}", None)]
    #[case("fn test() {}", None)]
    // Invalid method in NameValue format
    #[case("#[route = \"invalid\"] fn test() {}", None)]
    #[case("#[route = \"GET\"] fn test() {}", Some(("get".to_string(), None, None)))] // lowercase conversion
    // Multiple attributes - should find route attribute
    #[case("#[derive(Debug)] #[route(get, path = \"/api\")] #[test] fn test() {}", Some(("get".to_string(), Some("/api".to_string()), None)))]
    // Multiple route attributes - first one wins
    #[case("#[route(get, path = \"/first\")] #[route(post, path = \"/second\")] fn test() {}", Some(("get".to_string(), Some("/first".to_string()), None)))]
    // Explicit tests for method.as_ref() and path.as_ref().map() coverage
    #[case("#[route(path = \"/test\")] fn test() {}", Some(("get".to_string(), Some("/test".to_string()), None)))] // method None, path Some
    #[case("#[route()] fn test() {}", Some(("get".to_string(), None, None)))] // method None, path None
    #[case("#[route(post)] fn test() {}", Some(("post".to_string(), None, None)))] // method Some, path None
    #[case("#[route(put, path = \"/test\")] fn test() {}", Some(("put".to_string(), Some("/test".to_string()), None)))] // method Some, path Some
    fn test_extract_route_info(
        #[case] code: &str,
        #[case] expected: Option<(String, Option<String>, Option<Vec<u16>>)>,
    ) {
        let attrs = parse_attrs_from_code(code);
        let result = extract_route_info(&attrs);

        match expected {
            Some((exp_method, exp_path, exp_error_status)) => {
                assert!(
                    result.is_some(),
                    "Expected Some but got None for code: {code}"
                );
                let route_info = result.unwrap();
                assert_eq!(
                    route_info.method, exp_method,
                    "Method mismatch for code: {code}"
                );
                assert_eq!(route_info.path, exp_path, "Path mismatch for code: {code}");
                assert_eq!(
                    route_info.error_status, exp_error_status,
                    "Error status mismatch for code: {code}"
                );
            }
            None => {
                assert!(
                    result.is_none(),
                    "Expected None but got Some({result:?}) for code: {code}"
                );
            }
        }
    }

    // Tests for extract_doc_comment function
    #[test]
    fn test_extract_doc_comment_single_line() {
        let code = r"
            /// This is a doc comment
            fn test() {}
        ";
        let file: syn::File = syn::parse_str(code).unwrap();
        if let Some(syn::Item::Fn(fn_item)) = file.items.first() {
            let doc = extract_doc_comment(&fn_item.attrs);
            assert_eq!(doc, Some("This is a doc comment".to_string()));
        }
    }

    #[test]
    fn test_extract_doc_comment_multi_line() {
        let code = r"
            /// First line
            /// Second line
            /// Third line
            fn test() {}
        ";
        let file: syn::File = syn::parse_str(code).unwrap();
        if let Some(syn::Item::Fn(fn_item)) = file.items.first() {
            let doc = extract_doc_comment(&fn_item.attrs);
            assert_eq!(doc, Some("First line\nSecond line\nThird line".to_string()));
        }
    }

    #[test]
    fn test_extract_doc_comment_empty() {
        let code = "fn test() {}";
        let file: syn::File = syn::parse_str(code).unwrap();
        if let Some(syn::Item::Fn(fn_item)) = file.items.first() {
            let doc = extract_doc_comment(&fn_item.attrs);
            assert_eq!(doc, None);
        }
    }

    #[test]
    fn test_extract_doc_comment_with_other_attrs() {
        let code = r"
            #[inline]
            /// Doc comment
            #[test]
            fn test() {}
        ";
        let file: syn::File = syn::parse_str(code).unwrap();
        if let Some(syn::Item::Fn(fn_item)) = file.items.first() {
            let doc = extract_doc_comment(&fn_item.attrs);
            assert_eq!(doc, Some("Doc comment".to_string()));
        }
    }

    #[test]
    fn test_extract_doc_comment_no_leading_space() {
        let code = r"
            ///No leading space
            fn test() {}
        ";
        let file: syn::File = syn::parse_str(code).unwrap();
        if let Some(syn::Item::Fn(fn_item)) = file.items.first() {
            let doc = extract_doc_comment(&fn_item.attrs);
            assert_eq!(doc, Some("No leading space".to_string()));
        }
    }

    // Tests for tags and description in extract_route_info
    #[test]
    fn test_extract_route_info_with_tags() {
        let code = r#"#[route(get, tags = ["users", "admin"])] fn test() {}"#;
        let attrs = parse_attrs_from_code(code);
        let result = extract_route_info(&attrs);
        assert!(result.is_some());
        let route_info = result.unwrap();
        assert_eq!(
            route_info.tags,
            Some(vec!["users".to_string(), "admin".to_string()])
        );
    }

    #[test]
    fn test_extract_route_info_with_single_tag() {
        let code = r#"#[route(get, tags = ["users"])] fn test() {}"#;
        let attrs = parse_attrs_from_code(code);
        let result = extract_route_info(&attrs);
        assert!(result.is_some());
        let route_info = result.unwrap();
        assert_eq!(route_info.tags, Some(vec!["users".to_string()]));
    }

    #[test]
    fn test_extract_route_info_with_empty_tags() {
        let code = r"#[route(get, tags = [])] fn test() {}";
        let attrs = parse_attrs_from_code(code);
        let result = extract_route_info(&attrs);
        assert!(result.is_some());
        let route_info = result.unwrap();
        assert_eq!(route_info.tags, None); // Empty array should return None
    }

    #[test]
    fn test_extract_route_info_with_description() {
        let code = r#"#[route(get, description = "Get all users")] fn test() {}"#;
        let attrs = parse_attrs_from_code(code);
        let result = extract_route_info(&attrs);
        assert!(result.is_some());
        let route_info = result.unwrap();
        assert_eq!(route_info.description, Some("Get all users".to_string()));
    }

    #[test]
    fn test_extract_route_info_with_tags_and_description() {
        let code = r#"#[route(get, tags = ["users"], description = "Get users")] fn test() {}"#;
        let attrs = parse_attrs_from_code(code);
        let result = extract_route_info(&attrs);
        assert!(result.is_some());
        let route_info = result.unwrap();
        assert_eq!(route_info.tags, Some(vec!["users".to_string()]));
        assert_eq!(route_info.description, Some("Get users".to_string()));
    }

    #[test]
    fn test_extract_route_info_all_options() {
        let code = r#"#[route(post, path = "/api/users", error_status = [400, 404], tags = ["users", "api"], description = "Create a new user")] fn test() {}"#;
        let attrs = parse_attrs_from_code(code);
        let result = extract_route_info(&attrs);
        assert!(result.is_some());
        let route_info = result.unwrap();
        assert_eq!(route_info.method, "post");
        assert_eq!(route_info.path, Some("/api/users".to_string()));
        assert_eq!(route_info.error_status, Some(vec![400, 404]));
        assert_eq!(
            route_info.tags,
            Some(vec!["users".to_string(), "api".to_string()])
        );
        assert_eq!(
            route_info.description,
            Some("Create a new user".to_string())
        );
    }
}