camel-endpoint-macros 0.6.0

Proc-macros for camel-endpoint
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
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
    Data, DeriveInput, Fields, Lit, Meta, Token, Type, TypePath, parse::Parse, parse::ParseStream,
    punctuated::Punctuated,
};

/// Parsed `#[uri_param]` attribute
struct UriParamAttr {
    /// Custom parameter name (if specified)
    name: Option<String>,
    /// Default value (if specified)
    default: Option<String>,
}

/// Parse a single key=value pair
struct KeyValue {
    key: syn::Ident,
    value: Lit,
}

impl Parse for KeyValue {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let key: syn::Ident = input.parse()?;
        input.parse::<Token![=]>()?;
        let value: Lit = input.parse()?;
        Ok(KeyValue { key, value })
    }
}

impl Parse for UriParamAttr {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut name = None;
        let mut default = None;

        if input.is_empty() {
            return Ok(UriParamAttr { name, default });
        }

        // Parse comma-separated key=value pairs
        let pairs: Punctuated<KeyValue, Token![,]> =
            input.parse_terminated(KeyValue::parse, Token![,])?;

        for pair in pairs {
            let key_str = pair.key.to_string();
            if let Lit::Str(lit_str) = pair.value {
                let str_val = lit_str.value();
                match key_str.as_str() {
                    "name" => name = Some(str_val),
                    "default" => default = Some(str_val),
                    _ => {
                        return Err(syn::Error::new_spanned(
                            pair.key,
                            format!("unknown attribute key: {}", key_str),
                        ));
                    }
                }
            } else {
                return Err(syn::Error::new_spanned(
                    pair.value,
                    "expected a string literal",
                ));
            }
        }

        Ok(UriParamAttr { name, default })
    }
}

/// Extract the URI scheme from struct attributes
fn extract_scheme(attrs: &[syn::Attribute]) -> syn::Result<String> {
    for attr in attrs {
        if let Meta::NameValue(nv) = &attr.meta
            && nv.path.is_ident("uri_scheme")
            && let syn::Expr::Lit(expr_lit) = &nv.value
            && let Lit::Str(lit_str) = &expr_lit.lit
        {
            return Ok(lit_str.value());
        }
    }
    Err(syn::Error::new(
        proc_macro2::Span::call_site(),
        "missing #[uri_scheme = \"xxx\"] attribute on struct",
    ))
}

/// Parse a `#[uri_param]` attribute from field attributes
fn parse_uri_param_attr(attrs: &[syn::Attribute]) -> syn::Result<Option<UriParamAttr>> {
    for attr in attrs {
        if attr.path().is_ident("uri_param") {
            // Check if there are any tokens (i.e., parentheses present)
            // If the attribute is just `#[uri_param]` with no parens, return empty UriParamAttr
            match &attr.meta {
                Meta::Path(_) => {
                    // No parentheses - just #[uri_param]
                    return Ok(Some(UriParamAttr {
                        name: None,
                        default: None,
                    }));
                }
                Meta::List(list) => {
                    // Has parentheses - parse the contents
                    let parsed: UriParamAttr = list.parse_args()?;
                    return Ok(Some(parsed));
                }
                _ => {
                    return Err(syn::Error::new_spanned(
                        attr,
                        "unexpected attribute format for #[uri_param]",
                    ));
                }
            }
        }
    }
    Ok(None)
}

struct UriConfigAttr {
    skip_impl: bool,
    crate_path: syn::Path,
}

fn parse_uri_config_attr(attrs: &[syn::Attribute]) -> syn::Result<UriConfigAttr> {
    let mut skip_impl = false;
    let mut crate_path: Option<syn::Path> = None;

    for attr in attrs {
        if !attr.path().is_ident("uri_config") {
            continue;
        }

        match &attr.meta {
            Meta::List(_) => {
                attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("skip_impl") {
                        skip_impl = true;
                        return Ok(());
                    }

                    if meta.path.is_ident("crate") {
                        let value = meta.value()?;
                        let lit: syn::LitStr = value.parse()?;
                        crate_path = Some(lit.parse()?);
                        return Ok(());
                    }

                    Err(meta.error("unknown uri_config option"))
                })?;
            }
            _ => {
                return Err(syn::Error::new_spanned(
                    attr,
                    "unexpected attribute format for #[uri_config]",
                ));
            }
        }
    }

    Ok(UriConfigAttr {
        skip_impl,
        crate_path: crate_path.unwrap_or_else(|| syn::parse_quote!(camel_endpoint)),
    })
}

/// Get the type name as a string (for simple type matching)
fn get_type_name(ty: &Type) -> Option<String> {
    if let Type::Path(TypePath { path, .. }) = ty {
        // Get the last segment (handles qualified paths)
        let segment = path.segments.last()?;
        Some(segment.ident.to_string())
    } else {
        None
    }
}

/// Check if a type is std::time::Duration
fn is_duration_type(ty: &Type) -> bool {
    if let Type::Path(TypePath { path, .. }) = ty {
        // Handle both `Duration` and `std::time::Duration`
        let segments: Vec<_> = path.segments.iter().map(|s| s.ident.to_string()).collect();

        // Direct "Duration" or qualified "std::time::Duration"
        segments.last().map(|s| s == "Duration").unwrap_or(false)
    } else {
        false
    }
}

/// Check if a type is Option<T>
fn is_option_type(ty: &Type) -> Option<Type> {
    if let Type::Path(TypePath { path, .. }) = ty {
        let segment = path.segments.last()?;
        if segment.ident == "Option"
            && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
            && let Some(syn::GenericArgument::Type(inner_ty)) = args.args.first()
        {
            return Some(inner_ty.clone());
        }
    }
    None
}

/// Generate code to parse a value from params into a local variable
/// Returns (variable_name, binding_code) where binding_code assigns to the variable
fn generate_param_parsing(
    param_name: &str,
    field_name: &syn::Ident,
    ty: &Type,
    default: Option<&str>,
    endpoint_crate: &syn::Path,
) -> TokenStream {
    let type_name = get_type_name(ty);
    let inner_type = is_option_type(ty);

    // Handle Option<T>
    if let Some(inner_ty) = &inner_type {
        let inner_type_name = get_type_name(inner_ty);

        return match inner_type_name.as_deref() {
            Some("String") => quote! {
                let #field_name = params.get(#param_name).cloned()
            },
            Some("bool") => quote! {
                let #field_name = params.get(#param_name)
                    .map(|v| v == "true")
            },
            Some("u64") | Some("u32") | Some("usize") | Some("i64") | Some("i32")
            | Some("isize") => quote! {
                let #field_name = params.get(#param_name)
                    .and_then(|v| v.parse().ok())
            },
            _ => quote! {
                let #field_name = params.get(#param_name)
                    .map(|v| v.parse().ok())
                    .flatten()
            },
        };
    }

    // Handle non-Option types
    match type_name.as_deref() {
        Some("String") => {
            if let Some(default_val) = default {
                quote! {
                    let #field_name = params.get(#param_name).cloned().unwrap_or_else(|| #default_val.to_string())
                }
            } else {
                quote! {
                    let #field_name = params.get(#param_name).cloned().ok_or_else(|| {
                        #endpoint_crate::CamelError::InvalidUri(
                            format!("missing required parameter: {}", #param_name)
                        )
                    })?
                }
            }
        }
        Some("bool") => {
            if let Some(default_val) = default {
                let default_bool = default_val == "true";
                quote! {
                    let #field_name = params.get(#param_name)
                        .map(|v| v == "true")
                        .unwrap_or(#default_bool)
                }
            } else {
                // Require the param instead of silent false default
                quote! {
                    let #field_name = params.get(#param_name)
                        .map(|v| v == "true")
                        .ok_or_else(|| #endpoint_crate::CamelError::InvalidUri(
                            format!("missing required parameter: {}", #param_name)
                        ))?
                }
            }
        }
        Some("u64") => {
            if let Some(default_val) = default {
                let default_num: u64 = default_val.parse().unwrap_or(0);
                quote! {
                    let #field_name = match params.get(#param_name) {
                        Some(v) => v.parse::<u64>().map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?,
                        None => #default_num,
                    }
                }
            } else {
                quote! {
                    let #field_name = params.get(#param_name)
                        .ok_or_else(|| #endpoint_crate::CamelError::InvalidUri(
                            format!("missing required parameter: {}", #param_name)
                        ))?
                        .parse::<u64>()
                        .map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?
                }
            }
        }
        Some("u32") => {
            if let Some(default_val) = default {
                let default_num: u32 = default_val.parse().unwrap_or(0);
                quote! {
                    let #field_name = match params.get(#param_name) {
                        Some(v) => v.parse::<u32>().map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?,
                        None => #default_num,
                    }
                }
            } else {
                quote! {
                    let #field_name = params.get(#param_name)
                        .ok_or_else(|| #endpoint_crate::CamelError::InvalidUri(
                            format!("missing required parameter: {}", #param_name)
                        ))?
                        .parse::<u32>()
                        .map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?
                }
            }
        }
        Some("usize") => {
            if let Some(default_val) = default {
                let default_num: usize = default_val.parse().unwrap_or(0);
                quote! {
                    let #field_name = match params.get(#param_name) {
                        Some(v) => v.parse::<usize>().map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?,
                        None => #default_num,
                    }
                }
            } else {
                quote! {
                    let #field_name = params.get(#param_name)
                        .ok_or_else(|| #endpoint_crate::CamelError::InvalidUri(
                            format!("missing required parameter: {}", #param_name)
                        ))?
                        .parse::<usize>()
                        .map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?
                }
            }
        }
        Some("i64") => {
            if let Some(default_val) = default {
                let default_num: i64 = default_val.parse().unwrap_or(0);
                quote! {
                    let #field_name = match params.get(#param_name) {
                        Some(v) => v.parse::<i64>().map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?,
                        None => #default_num,
                    }
                }
            } else {
                quote! {
                    let #field_name = params.get(#param_name)
                        .ok_or_else(|| #endpoint_crate::CamelError::InvalidUri(
                            format!("missing required parameter: {}", #param_name)
                        ))?
                        .parse::<i64>()
                        .map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?
                }
            }
        }
        Some("i32") => {
            if let Some(default_val) = default {
                let default_num: i32 = default_val.parse().unwrap_or(0);
                quote! {
                    let #field_name = match params.get(#param_name) {
                        Some(v) => v.parse::<i32>().map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?,
                        None => #default_num,
                    }
                }
            } else {
                quote! {
                    let #field_name = params.get(#param_name)
                        .ok_or_else(|| #endpoint_crate::CamelError::InvalidUri(
                            format!("missing required parameter: {}", #param_name)
                        ))?
                        .parse::<i32>()
                        .map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?
                }
            }
        }
        _ => {
            // Assume it's an enum or other type with FromStr
            if let Some(default_val) = default {
                quote! {
                    let #field_name = params.get(#param_name)
                        .map(|v| v.parse::<#ty>().unwrap_or_else(|_| #default_val.parse().unwrap()))
                        .unwrap_or_else(|| #default_val.parse().unwrap())
                }
            } else {
                quote! {
                    let #field_name = params.get(#param_name)
                        .ok_or_else(|| #endpoint_crate::CamelError::InvalidUri(
                            format!("missing required parameter: {}", #param_name)
                        ))?
                        .parse::<#ty>()
                        .map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for parameter '{}': {}", #param_name, e)
                        ))?
                }
            }
        }
    }
}

pub fn impl_uri_config(input: &DeriveInput) -> TokenStream {
    let struct_name = &input.ident;

    let uri_config_attr = match parse_uri_config_attr(&input.attrs) {
        Ok(a) => a,
        Err(e) => return e.to_compile_error(),
    };

    let skip_impl = uri_config_attr.skip_impl;
    let endpoint_crate = uri_config_attr.crate_path;

    // Extract scheme from struct attributes
    let scheme = match extract_scheme(&input.attrs) {
        Ok(s) => s,
        Err(e) => return e.to_compile_error(),
    };

    // Get struct fields
    let fields = match &input.data {
        Data::Struct(data) => match &data.fields {
            Fields::Named(fields) => &fields.named,
            _ => {
                return syn::Error::new(
                    proc_macro2::Span::call_site(),
                    "UriConfig only supports structs with named fields",
                )
                .to_compile_error();
            }
        },
        _ => {
            return syn::Error::new(
                proc_macro2::Span::call_site(),
                "UriConfig can only be derived for structs",
            )
            .to_compile_error();
        }
    };

    // First pass: collect field info
    #[derive(Clone)]
    enum FieldType {
        Path,
        Param {
            param_name: String,
            default: Option<String>,
        },
        DurationFromMs {
            companion_field: String,
        },
    }

    let mut field_info: Vec<(syn::Ident, Type, FieldType)> = Vec::new();
    let mut path_field_found = false;

    // Collect all field names for Duration companion lookup
    let all_field_names: Vec<String> = fields
        .iter()
        .map(|f| f.ident.as_ref().unwrap().to_string())
        .collect();

    for field in fields {
        let field_name = field.ident.as_ref().unwrap().clone();
        let field_type = field.ty.clone();

        // Check if this is a Duration type that should derive from a companion field
        if is_duration_type(&field.ty) {
            let field_name_str = field_name.to_string();
            let companion_name = format!("{}_ms", field_name_str);

            // Check if companion field exists
            if all_field_names.contains(&companion_name) {
                field_info.push((
                    field_name,
                    field_type,
                    FieldType::DurationFromMs {
                        companion_field: companion_name,
                    },
                ));
                continue;
            }
            // If no companion, fall through to regular handling (will use FromStr)
        }

        // Check for #[uri_param] attribute
        match parse_uri_param_attr(&field.attrs) {
            Ok(Some(attr)) => {
                // This is a parameter field
                let param_name = attr.name.clone().unwrap_or_else(|| field_name.to_string());
                field_info.push((
                    field_name,
                    field_type,
                    FieldType::Param {
                        param_name,
                        default: attr.default,
                    },
                ));
            }
            Ok(None) => {
                // No #[uri_param] - this is a path field (only the first one)
                if !path_field_found {
                    path_field_found = true;
                    field_info.push((field_name, field_type, FieldType::Path));
                } else {
                    // Additional path field without attribute - error
                    return syn::Error::new_spanned(
                        field,
                        "only one field can be the path field (first field without #[uri_param])",
                    )
                    .to_compile_error();
                }
            }
            Err(e) => {
                return e.to_compile_error();
            }
        }
    }

    // Second pass: generate local variable bindings
    // We need to ensure companion fields are processed before Duration fields
    let mut bindings = Vec::new();
    let field_names: Vec<_> = field_info.iter().map(|(name, _, _)| name.clone()).collect();

    // Process non-Duration fields first
    for (field_name, field_type, ftype) in &field_info {
        match ftype {
            FieldType::Path => {
                let type_name = get_type_name(field_type);
                match type_name.as_deref() {
                    Some("String") => {
                        bindings.push(quote! {
                            let #field_name = parts.path.clone()
                        });
                    }
                    _ => {
                        // Try to parse the path
                        let ty = field_type;
                        bindings.push(quote! {
                            let #field_name = parts.path.parse::<#ty>()
                                .map_err(|_| #endpoint_crate::CamelError::InvalidUri(
                                    format!("invalid path value for field: {}", stringify!(#field_name))
                                ))?
                        });
                    }
                }
            }
            FieldType::Param {
                param_name,
                default,
            } => {
                let parsing_code = generate_param_parsing(
                    param_name,
                    field_name,
                    field_type,
                    default.as_deref(),
                    &endpoint_crate,
                );
                bindings.push(parsing_code);
            }
            FieldType::DurationFromMs { .. } => {
                // Process these in the second pass
            }
        }
    }

    // Process Duration fields second (after their companions are bound)
    for (field_name, _field_type, ftype) in &field_info {
        if let FieldType::DurationFromMs { companion_field } = ftype {
            let companion_ident: syn::Ident =
                syn::Ident::new(companion_field, proc_macro2::Span::call_site());
            bindings.push(quote! {
                let #field_name = std::time::Duration::from_millis(#companion_ident)
            });
        }
    }

    let scheme_lit = scheme;

    // Generate the parsing logic (shared between both modes)
    let parsing_logic = quote! {
        // Validate scheme
        if parts.scheme != #scheme_lit {
            return Err(#endpoint_crate::CamelError::InvalidUri(
                format!("expected scheme '{}' but got '{}'", #scheme_lit, parts.scheme)
            ));
        }

        let params = &parts.params;

        #(#bindings);*;

        Ok(Self {
            #(#field_names),*
        })
    };

    if skip_impl {
        // Generate an inherent method for parsing, user implements UriConfig manually
        quote! {
            impl #struct_name {
                /// Parse URI components into this config.
                /// Call this from your custom `UriConfig::from_components` implementation.
                pub fn parse_uri_components(parts: #endpoint_crate::UriComponents) -> Result<Self, #endpoint_crate::CamelError> {
                    #parsing_logic
                }
            }
        }
    } else {
        // Generate full UriConfig trait implementation
        quote! {
            impl #endpoint_crate::UriConfig for #struct_name {
                fn scheme() -> &'static str {
                    #scheme_lit
                }

                fn from_uri(uri: &str) -> Result<Self, #endpoint_crate::CamelError> {
                    let parts = #endpoint_crate::parse_uri(uri)?;
                    Self::from_components(parts)
                }

                fn from_components(parts: #endpoint_crate::UriComponents) -> Result<Self, #endpoint_crate::CamelError> {
                    let config = Self::parse_uri_components(parts)?;
                    // Call validate to allow custom validation logic
                    config.validate()
                }
            }

            impl #struct_name {
                /// Parse URI components into this config.
                pub fn parse_uri_components(parts: #endpoint_crate::UriComponents) -> Result<Self, #endpoint_crate::CamelError> {
                    #parsing_logic
                }
            }
        }
    }
}