vespera_macro 0.1.33

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
//! Parsing utilities for proc-macro input.
//!
//! Provides reusable helpers for parsing common patterns in proc-macro inputs,
//! including lookahead-based parsing, key-value pairs, and bracket-delimited lists.
//!
//! These utilities are available for future refactoring of existing parsing code in `args.rs`
//! and `router_codegen.rs`. They extract the most common lookahead-based patterns.

#![allow(dead_code)]

use proc_macro2::Delimiter;
use syn::parse::discouraged::AnyDelimiter;
use syn::{Ident, LitStr, Token, parse::ParseStream};

/// Parse a comma-separated list with optional trailing comma.
///
/// Automatically handles the lookahead and comma parsing loop.
/// The provided parser function is called for each item.
///
/// # Example
/// ```ignore
/// let items: Vec<String> = parse_comma_list(input, |input| {
///     input.parse::<LitStr>().map(|lit| lit.value())
/// })?;
/// ```
pub fn parse_comma_list<T, F>(input: ParseStream, mut parser: F) -> syn::Result<Vec<T>>
where
    F: FnMut(ParseStream) -> syn::Result<T>,
{
    let mut items = Vec::new();

    while !input.is_empty() {
        items.push(parser(input)?);

        if input.peek(Token![,]) {
            input.parse::<Token![,]>()?;
        } else {
            break;
        }
    }

    Ok(items)
}

/// Parse a bracket-delimited comma-separated list.
///
/// # Example
/// ```ignore
/// let items: Vec<String> = parse_bracketed_list(input, |input| {
///     input.parse::<LitStr>().map(|lit| lit.value())
/// })?;
/// ```
pub fn parse_bracketed_list<T, F>(input: ParseStream, parser: F) -> syn::Result<Vec<T>>
where
    F: Fn(ParseStream) -> syn::Result<T>,
{
    let (delim, _span, content) = input.parse_any_delimiter()?;
    if delim != Delimiter::Bracket {
        return Err(content.error("expected brackets"));
    }
    parse_comma_list(&content, parser)
}

/// Parse identifier-based key-value pairs.
///
/// Looks for patterns like `key = value`, where the key is an identifier.
/// Returns the key as a string and leaves the `=` token consumed.
///
/// # Returns
/// - `Some((key, true))` if we found an identifier that could be a key
/// - `None` if end of input or unexpected token type
///
/// # Example
/// ```ignore
/// if let Some((key, _)) = try_parse_key(input)? {
///     match key.as_str() {
///         "title" => { input.parse::<Token![=]>()?; title = Some(input.parse()?); }
///         "version" => { input.parse::<Token![=]>()?; version = Some(input.parse()?); }
///         _ => return Err(syn::Error::new(...))
///     }
/// }
/// ```
pub fn try_parse_key(input: ParseStream) -> syn::Result<Option<String>> {
    let lookahead = input.lookahead1();

    if lookahead.peek(Ident) {
        let ident: Ident = input.parse()?;
        Ok(Some(ident.to_string()))
    } else if lookahead.peek(LitStr) {
        Ok(None)
    } else {
        Err(lookahead.error())
    }
}

/// Parse a list of identifier-keyed key-value pairs.
///
/// Expects comma-separated key=value pairs where keys are identifiers.
/// Each iteration calls the handler with the key, and the handler is responsible
/// for consuming the `=` token and parsing the value.
///
/// # Example
/// ```ignore
/// let mut title = None;
/// let mut version = None;
///
/// parse_key_value_list(input, |key, input| {
///     match key.as_str() {
///         "title" => {
///             input.parse::<Token![=]>()?;
///             title = Some(input.parse()?);
///         }
///         "version" => {
///             input.parse::<Token![=]>()?;
///             version = Some(input.parse()?);
///         }
///         _ => return Err(syn::Error::new(...))
///     }
///     Ok(())
/// })?;
/// ```
pub fn parse_key_value_list<F>(input: ParseStream, mut handler: F) -> syn::Result<()>
where
    F: FnMut(String, ParseStream) -> syn::Result<()>,
{
    while !input.is_empty() {
        let lookahead = input.lookahead1();

        if lookahead.peek(Ident) {
            let ident: Ident = input.parse()?;
            let key = ident.to_string();
            handler(key, input)?;

            // Check if there's a comma
            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            } else {
                break;
            }
        } else if lookahead.peek(LitStr) {
            // Allow string as a special case (e.g., for backward compatibility)
            break;
        } else {
            return Err(lookahead.error());
        }
    }

    Ok(())
}

/// Check if next token is a comma and consume it if present.
///
/// Returns `true` if comma was found and consumed, `false` otherwise.
pub fn try_consume_comma(input: ParseStream) -> bool {
    if input.peek(Token![,]) {
        let _ = input.parse::<Token![,]>();
        true
    } else {
        false
    }
}

#[cfg(test)]
mod tests {
    use syn::parse::Parser;

    use super::*;

    #[test]
    fn test_parse_comma_list_single() {
        // Test basic parsing capability - parse a list of 3 strings
        let parser = |input: ParseStream| {
            parse_comma_list(input, |input| {
                input.parse::<LitStr>().map(|lit| lit.value())
            })
        };

        let tokens = quote::quote!("a", "b", "c");
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        let items: Vec<String> = result.unwrap();
        assert_eq!(items, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_parse_comma_list_with_trailing_comma() {
        let parser = |input: ParseStream| {
            parse_comma_list(input, |input| {
                input.parse::<LitStr>().map(|lit| lit.value())
            })
        };

        let tokens = quote::quote!("x", "y",);
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        let items: Vec<String> = result.unwrap();
        assert_eq!(items, vec!["x", "y"]);
    }

    #[test]
    fn test_parse_bracketed_list_strings() {
        let parser = |input: ParseStream| {
            parse_bracketed_list(input, |input| {
                input.parse::<LitStr>().map(|lit| lit.value())
            })
        };

        let tokens = quote::quote!(["a", "b", "c"]);
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        let items: Vec<String> = result.unwrap();
        assert_eq!(items, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_try_parse_key_ident() {
        let parser = |input: ParseStream| try_parse_key(input);

        let tokens = quote::quote!(title);
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        let key = result.unwrap();
        assert_eq!(key, Some("title".to_string()));
    }

    #[test]
    fn test_try_consume_comma_logic() {
        // Test the comma consumption logic by parsing and manually checking
        let parser = |input: ParseStream| {
            let has_comma = try_consume_comma(input);
            Ok(has_comma)
        };

        let tokens = quote::quote!(,);
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_try_parse_key_litstr() {
        // When input is a LitStr, try_parse_key returns Ok(None) without consuming
        let parser = |input: ParseStream| {
            let result = try_parse_key(input)?;
            // LitStr remains unconsumed, parse it to clear the buffer
            let _: LitStr = input.parse()?;
            Ok(result)
        };

        let tokens = quote::quote!("some_string");
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), None);
    }

    #[test]
    fn test_try_parse_key_invalid_token() {
        // When input is neither Ident nor LitStr, try_parse_key returns error
        let parser = |input: ParseStream| try_parse_key(input);

        // Use a number literal which is neither Ident nor LitStr
        let tokens = quote::quote!(42);
        let result = parser.parse2(tokens);
        assert!(result.is_err());
    }

    #[test]
    fn test_try_consume_comma_no_comma() {
        // When there's no comma, try_consume_comma returns false without consuming
        let parser = |input: ParseStream| {
            let has_comma = try_consume_comma(input);
            // Token remains unconsumed, parse it to clear the buffer
            let _: Ident = input.parse()?;
            Ok(has_comma)
        };

        // Some token that's not a comma
        let tokens = quote::quote!(foo);
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        assert!(!result.unwrap());
    }

    #[test]
    fn test_parse_key_value_handler() {
        let parser = |input: ParseStream| {
            let mut title = None;
            let mut version = None;

            parse_key_value_list(input, |key, input| {
                match key.as_str() {
                    "title" => {
                        input.parse::<Token![=]>()?;
                        title = Some(input.parse::<LitStr>()?.value());
                    }
                    "version" => {
                        input.parse::<Token![=]>()?;
                        version = Some(input.parse::<LitStr>()?.value());
                    }
                    _ => {
                        return Err(syn::Error::new(
                            proc_macro2::Span::call_site(),
                            "unknown key",
                        ));
                    }
                }
                Ok(())
            })?;

            Ok((title, version))
        };

        let tokens = quote::quote!(title = "Test", version = "1.0");
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        let (title, version) = result.unwrap();
        assert_eq!(title, Some("Test".to_string()));
        assert_eq!(version, Some("1.0".to_string()));
    }

    #[test]
    fn test_parse_key_value_list_litstr_breaks() {
        // When a LitStr is encountered in parse_key_value_list, it breaks (doesn't error)
        let parser = |input: ParseStream| {
            let mut keys = Vec::new();
            parse_key_value_list(input, |key, input| {
                input.parse::<Token![=]>()?;
                let _: LitStr = input.parse()?;
                keys.push(key);
                Ok(())
            })?;
            // The remaining LitStr is left unconsumed, parse it to clear the buffer
            let _: LitStr = input.parse()?;
            Ok(keys)
        };

        // "remaining" is a LitStr at the end, should break without error
        let tokens = quote::quote!(title = "Test", "remaining");
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), vec!["title"]);
    }

    #[test]
    fn test_parse_key_value_list_invalid_token() {
        // When an invalid token (not Ident or LitStr) is encountered, returns error
        let parser = |input: ParseStream| {
            parse_key_value_list(input, |_key, input| {
                input.parse::<Token![=]>()?;
                let _: LitStr = input.parse()?;
                Ok(())
            })
        };

        // 42 is neither Ident nor LitStr, should error
        let tokens = quote::quote!(42);
        let result = parser.parse2(tokens);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_bracketed_list_empty() {
        // Test parse_bracketed_list with empty brackets
        let parser = |input: ParseStream| {
            parse_bracketed_list(input, |input| {
                input.parse::<LitStr>().map(|lit| lit.value())
            })
        };

        let tokens = quote::quote!([]);
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        let items: Vec<String> = result.unwrap();
        assert!(items.is_empty());
    }

    #[test]
    fn test_parse_bracketed_list_single_item() {
        // Test parse_bracketed_list with single item
        let parser = |input: ParseStream| {
            parse_bracketed_list(input, |input| {
                input.parse::<LitStr>().map(|lit| lit.value())
            })
        };

        let tokens = quote::quote!(["single"]);
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        let items: Vec<String> = result.unwrap();
        assert_eq!(items, vec!["single"]);
    }

    #[test]
    fn test_parse_bracketed_list_with_trailing_comma() {
        // Test parse_bracketed_list with trailing comma
        let parser = |input: ParseStream| {
            parse_bracketed_list(input, |input| {
                input.parse::<LitStr>().map(|lit| lit.value())
            })
        };

        let tokens = quote::quote!(["a", "b",]);
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        let items: Vec<String> = result.unwrap();
        assert_eq!(items, vec!["a", "b"]);
    }

    #[test]
    fn test_parse_bracketed_list_integers() {
        // Test parse_bracketed_list with integer literals
        use syn::LitInt;
        let parser = |input: ParseStream| {
            parse_bracketed_list(input, |input| {
                input
                    .parse::<LitInt>()
                    .and_then(|lit| lit.base10_parse::<i32>())
            })
        };

        let tokens = quote::quote!([1, 2, 3]);
        let result = parser.parse2(tokens);
        assert!(result.is_ok());
        let items: Vec<i32> = result.unwrap();
        assert_eq!(items, vec![1, 2, 3]);
    }

    #[test]
    fn test_parse_bracketed_list_wrong_delimiter_parens() {
        // Test parse_bracketed_list with parentheses instead of brackets - should error
        let parser = |input: ParseStream| {
            parse_bracketed_list(input, |input| {
                input.parse::<LitStr>().map(|lit| lit.value())
            })
        };

        let tokens = quote::quote!(("a", "b"));
        let result = parser.parse2(tokens);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("expected brackets"));
    }

    #[test]
    fn test_parse_bracketed_list_wrong_delimiter_braces() {
        // Test parse_bracketed_list with braces instead of brackets - should error
        let parser = |input: ParseStream| {
            parse_bracketed_list(input, |input| {
                input.parse::<LitStr>().map(|lit| lit.value())
            })
        };

        let tokens = quote::quote!({"a", "b"});
        let result = parser.parse2(tokens);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("expected brackets"));
    }

    #[test]
    fn test_parse_bracketed_list_no_delimiter() {
        // Test parse_bracketed_list with no delimiter at all - should error
        let parser = |input: ParseStream| {
            parse_bracketed_list(input, |input| {
                input.parse::<LitStr>().map(|lit| lit.value())
            })
        };

        let tokens = quote::quote!("just_a_string");
        let result = parser.parse2(tokens);
        assert!(result.is_err());
    }
}