camel-endpoint-macros 0.28.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
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
    Data, DeriveInput, Fields, Lit, Meta, Token, Type, TypePath, parse::Parse, parse::ParseStream,
};

// ---------------------------------------------------------------------------
// UriParamAttr — parsed `#[uri_param]` attribute
// ---------------------------------------------------------------------------

/// Parsed `#[uri_param]` attribute.
///
/// Supports both bare-ident flags (`required`, `secret`) and `key = value`
/// pairs. See the attribute table in `lib.rs` for the full key set.
#[derive(Clone, Debug, Default)]
struct UriParamAttr {
    /// Custom parameter name (`name = "..."`).
    name: Option<String>,
    /// Default value (`default = "..."`).
    default: Option<String>,
    /// Human-readable description (`desc = "..."`).
    desc: Option<String>,
    /// `required` flag (bare or `required = bool`).
    required: bool,
    /// `secret` flag (bare or `secret = bool`).
    secret: bool,
    /// Deprecation reason (`deprecated = "..."`).
    deprecated: Option<String>,
    /// Alias names (`aliases = ["a", "b"]`).
    aliases: Vec<String>,
    /// OptionKind override (`kind = "duration"` / `kind = "enum:A,B"`), with
    /// the literal's span preserved for spanned error reporting.
    kind_override: Option<syn::LitStr>,
    /// Open-namespace separator (`pattern = "param."`). When `Some`, the field
    /// is a namespace option matching URI query keys by prefix.
    pattern: Option<String>,
}

impl Parse for UriParamAttr {
    /// Parse a comma-separated list of EITHER bare-ident flags
    /// (`required`, `secret`) OR `key = value` pairs.
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut attr = UriParamAttr::default();

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;
            let key_str = ident.to_string();

            if input.peek(Token![=]) {
                input.parse::<Token![=]>()?;
                match key_str.as_str() {
                    "name" | "default" | "desc" | "deprecated" | "pattern" => {
                        let lit: Lit = input.parse()?;
                        if let Lit::Str(lit_str) = lit {
                            let val = lit_str.value();
                            match key_str.as_str() {
                                "name" => attr.name = Some(val),
                                "default" => attr.default = Some(val),
                                "desc" => attr.desc = Some(val),
                                "deprecated" => attr.deprecated = Some(val),
                                "pattern" => attr.pattern = Some(val),
                                _ => unreachable!(),
                            }
                        } else {
                            return Err(syn::Error::new_spanned(lit, "expected a string literal"));
                        }
                    }
                    "kind" => {
                        let lit: Lit = input.parse()?;
                        if let Lit::Str(lit_str) = lit {
                            attr.kind_override = Some(lit_str);
                        } else {
                            return Err(syn::Error::new_spanned(lit, "expected a string literal"));
                        }
                    }
                    "required" | "secret" => {
                        let lit: Lit = input.parse()?;
                        if let Lit::Bool(b) = lit {
                            let v = b.value;
                            if key_str == "required" {
                                attr.required = v;
                            } else {
                                attr.secret = v;
                            }
                        } else {
                            return Err(syn::Error::new_spanned(lit, "expected a bool literal"));
                        }
                    }
                    "aliases" => {
                        let arr: syn::ExprArray = input.parse()?;
                        let mut items = Vec::new();
                        for expr in arr.elems {
                            if let syn::Expr::Lit(syn::ExprLit {
                                lit: Lit::Str(s), ..
                            }) = expr
                            {
                                items.push(s.value());
                            } else {
                                return Err(syn::Error::new_spanned(
                                    expr,
                                    "expected a string literal in aliases array",
                                ));
                            }
                        }
                        attr.aliases = items;
                    }
                    _ => {
                        return Err(syn::Error::new_spanned(
                            &ident,
                            format!("unknown attribute key: {}", key_str),
                        ));
                    }
                }
            } else {
                // Bare-ident flag form.
                match key_str.as_str() {
                    "required" => attr.required = true,
                    "secret" => attr.secret = true,
                    _ => {
                        return Err(syn::Error::new_spanned(
                            &ident,
                            format!("unknown attribute key: {}", key_str),
                        ));
                    }
                }
            }

            // Optional comma separator.
            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(attr)
    }
}

/// Extract the URI scheme from struct attributes (`#[uri_scheme = "xxx"]`).
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.
///
/// Returns `Ok(Some(attr))` when `#[uri_param]` is present (bare or with
/// args), `Ok(None)` when absent.
fn parse_uri_param_attr(attrs: &[syn::Attribute]) -> syn::Result<Option<UriParamAttr>> {
    for attr in attrs {
        if attr.path().is_ident("uri_param") {
            match &attr.meta {
                Meta::Path(_) => {
                    // Bare `#[uri_param]` — all flags/options default.
                    return Ok(Some(UriParamAttr::default()));
                }
                Meta::List(list) => {
                    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)
}

// ---------------------------------------------------------------------------
// UriConfigAttr — parsed `#[uri_config(...)]` struct attribute
// ---------------------------------------------------------------------------

struct UriConfigAttr {
    skip_impl: bool,
    descriptor: bool,
    crate_path: syn::Path,
    has_metadata: bool,
    metadata_scheme: Option<String>,
    metadata_description: Option<String>,
    supports_producer: bool,
    supports_consumer: bool,
    supports_polling_consumer: bool,
    supports_streaming: bool,
}

fn parse_uri_config_attr(attrs: &[syn::Attribute]) -> syn::Result<UriConfigAttr> {
    let mut skip_impl = false;
    let mut descriptor = false;
    let mut crate_path: Option<syn::Path> = None;
    let mut has_metadata = false;
    let mut metadata_scheme = None;
    let mut metadata_description = None;
    let mut supports_producer = false;
    let mut supports_consumer = false;
    let mut supports_polling_consumer = false;
    let mut supports_streaming = false;

    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("descriptor") {
                        descriptor = 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(());
                    }

                    if meta.path.is_ident("metadata") {
                        // C-NEW-2: `metadata(..)` mixes bare flags (`producer`)
                        // with kv pairs (`scheme = ".."`). Parse the
                        // parenthesized group, then walk it manually so both
                        // forms are accepted.
                        has_metadata = true;
                        let content;
                        syn::parenthesized!(content in meta.input);
                        while !content.is_empty() {
                            let key: syn::Ident = content.parse()?;
                            match key.to_string().as_str() {
                                "scheme" => {
                                    content.parse::<Token![=]>()?;
                                    let lit: syn::LitStr = content.parse()?;
                                    metadata_scheme = Some(lit.value());
                                }
                                "description" => {
                                    content.parse::<Token![=]>()?;
                                    let lit: syn::LitStr = content.parse()?;
                                    metadata_description = Some(lit.value());
                                }
                                "producer" => supports_producer = true,
                                "consumer" => supports_consumer = true,
                                "polling_consumer" => supports_polling_consumer = true,
                                "streaming" => supports_streaming = true,
                                other => {
                                    return Err(syn::Error::new_spanned(
                                        &key,
                                        format!("unknown metadata key: {}", other),
                                    ));
                                }
                            }
                            if content.peek(Token![,]) {
                                content.parse::<Token![,]>()?;
                            }
                        }
                        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,
        descriptor,
        crate_path: crate_path.unwrap_or_else(|| syn::parse_quote!(camel_endpoint)),
        has_metadata,
        metadata_scheme,
        metadata_description,
        supports_producer,
        supports_consumer,
        supports_polling_consumer,
        supports_streaming,
    })
}

// ---------------------------------------------------------------------------
// Type inspection helpers
// ---------------------------------------------------------------------------

/// 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 {
        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 {
        let segments: Vec<_> = path.segments.iter().map(|s| s.ident.to_string()).collect();
        segments.last().is_some_and(|s| s == "Duration")
    } else {
        false
    }
}

/// Unwrap `Option<T>` to its inner type, if applicable.
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
}

/// Unwrap `Vec<T>` to its inner type, if applicable.
fn get_vec_inner(ty: &Type) -> Option<Type> {
    if let Type::Path(TypePath { path, .. }) = ty {
        let segment = path.segments.last()?;
        if segment.ident == "Vec"
            && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
            && let Some(syn::GenericArgument::Type(inner_ty)) = args.args.first()
        {
            return Some(inner_ty.clone());
        }
    }
    None
}

/// Check whether a type is exactly `Vec<(String, String)>` (the canonical
/// form, the only field type permitted for a `pattern` namespace option).
///
/// Rejects `Vec<String>`, `(String, String)`, type aliases, and any path other
/// than the literal `Vec` of a 2-tuple of `String`.
fn is_vec_string_pair(ty: &Type) -> bool {
    let Some(inner) = get_vec_inner(ty) else {
        return false;
    };
    let Type::Tuple(tuple) = inner else {
        return false;
    };
    if tuple.elems.len() != 2 {
        return false;
    }
    tuple
        .elems
        .iter()
        .all(|elem| get_type_name(elem).is_some_and(|name| name == "String"))
}

// ---------------------------------------------------------------------------
// OptionKind inference (task 1.2)
// ---------------------------------------------------------------------------

/// Resolve a `kind = "..."` override string to an `OptionKind` constructor
/// token stream. Returns a spanned `syn::Error` for unrecognized strings.
///
/// Valid: `duration`, `bool`, `int`, `float`, `string`, `enum:A,B,C`.
fn parse_kind_override(
    kind_str: &str,
    span: proc_macro2::Span,
    endpoint_crate: &syn::Path,
) -> syn::Result<TokenStream> {
    let path = quote! { #endpoint_crate::OptionKind };
    match kind_str {
        "duration" => Ok(quote! { #path::Duration }),
        "bool" => Ok(quote! { #path::Bool }),
        "int" => Ok(quote! { #path::Int }),
        "float" => Ok(quote! { #path::Float }),
        "string" => Ok(quote! { #path::String }),
        s if s.starts_with("enum:") => {
            let rest = &s[5..];
            let variants: Vec<String> = rest
                .split(',')
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty())
                .collect();
            if variants.is_empty() {
                return Err(syn::Error::new(
                    span,
                    format!(
                        "invalid kind override '{}': enum requires at least one variant \
                         (e.g. kind = \"enum:A,B\")",
                        kind_str
                    ),
                ));
            }
            Ok(quote! { #path::Enum(::std::vec![#(::std::string::String::from(#variants)),*]) })
        }
        other => Err(syn::Error::new(
            span,
            // allow-secret: error message names kind overrides; lint window reaches the unrelated "token stream" doc
            format!(
                "unknown kind override '{}'. Valid: duration, bool, int, float, string, \
                 enum:VariantA,VariantB",
                other
            ),
        )),
    }
}

/// Map a Rust type to an `OptionKind` constructor token stream.
///
/// `Option<T>` is unwrapped to `T` first. **Inference NEVER emits `Enum`** —
/// an enum-typed field maps to `String`. Use `kind = "enum:..."` to opt into
/// `Enum`.
fn infer_option_kind(ty: &Type, endpoint_crate: &syn::Path) -> TokenStream {
    let effective_ty = is_option_type(ty).unwrap_or_else(|| ty.clone());
    infer_option_kind_inner(&effective_ty, endpoint_crate)
}

fn infer_option_kind_inner(ty: &Type, endpoint_crate: &syn::Path) -> TokenStream {
    let path = quote! { #endpoint_crate::OptionKind };

    if is_duration_type(ty) {
        return quote! { #path::Duration };
    }

    let type_name = get_type_name(ty);
    match type_name.as_deref() {
        Some("bool") => quote! { #path::Bool },
        Some("u8") | Some("u16") | Some("u32") | Some("u64") | Some("usize") | Some("i8")
        | Some("i16") | Some("i32") | Some("i64") | Some("isize") => quote! { #path::Int },
        Some("f32") | Some("f64") => quote! { #path::Float },
        Some("String") | Some("str") => quote! { #path::String },
        Some("Vec") => {
            if let Some(inner) = get_vec_inner(ty) {
                let inner_kind = infer_option_kind_inner(&inner, endpoint_crate);
                quote! { #path::List(::std::boxed::Box::new(#inner_kind)) }
            } else {
                quote! { #path::String }
            }
        }
        // Anything else (enums, custom types) infers to String — never Enum.
        _ => quote! { #path::String },
    }
}

// ---------------------------------------------------------------------------
// URI param parsing codegen (unchanged from original)
// ---------------------------------------------------------------------------

/// Generate code to parse a value from params into a local variable.
///
/// EMAC-005: Error messages include the URI parameter name (`param_name`) for
/// traceability. When `#[uri_param(name = "...")]` is used, the custom name
/// appears in errors; otherwise the Rust field name is used as the param name.
fn generate_param_parsing(
    param_name: &str,
    field_name: &syn::Ident,
    ty: &Type,
    default: Option<&str>,
    endpoint_crate: &syn::Path,
) -> syn::Result<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 Ok(match inner_type_name.as_deref() {
            Some("String") => quote! {
                let #field_name = params.get(#param_name).cloned()
            },
            Some("bool") => quote! {
                let #field_name = if let Some(v) = params.get(#param_name) {
                    Some(#endpoint_crate::uri::parse_bool_param(v).map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                        format!("invalid value for {}: {}", #param_name, e)
                    ))?)
                } else {
                    None
                }
            },
            Some("u64") | Some("u32") | Some("usize") | Some("i64") | Some("i32")
            | Some("isize") => quote! {
                let #field_name = if let Some(v) = params.get(#param_name) {
                    Some(v.parse::<#inner_ty>().map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                        format!("invalid value for {}: {}", #param_name, e)
                    ))?)
                } else {
                    None
                }
            },
            _ => quote! {
                let #field_name = if let Some(v) = params.get(#param_name) {
                    Some(v.parse::<#inner_ty>().map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                        format!("invalid value for {}: {}", #param_name, e)
                    ))?)
                } else {
                    None
                }
            },
        });
    }

    // Handle non-Option types
    Ok(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 =
                    matches!(default_val.to_lowercase().as_str(), "true" | "1" | "yes");
                quote! {
                    let #field_name = match params.get(#param_name) {
                        Some(v) => #endpoint_crate::uri::parse_bool_param(v).map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for {}: {}", #param_name, e)
                        ))?,
                        None => #default_bool,
                    }
                }
            } else {
                // Require the param instead of silent false default
                quote! {
                    let #field_name = #endpoint_crate::uri::parse_bool_param(
                        &params.get(#param_name).ok_or_else(|| #endpoint_crate::CamelError::InvalidUri(
                            format!("missing required parameter: {}", #param_name)
                        ))?
                    ).map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                        format!("invalid value for {}: {}", #param_name, e)
                    ))?
                }
            }
        }
        Some("u64") => {
            if let Some(default_val) = default {
                let default_num: u64 = default_val.parse().map_err(|_| {
                    syn::Error::new(
                        proc_macro2::Span::call_site(),
                        format!(
                            "invalid default value for '{}': '{}' is not a valid u64",
                            param_name, default_val
                        ),
                    )
                })?;
                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().map_err(|_| {
                    syn::Error::new(
                        proc_macro2::Span::call_site(),
                        format!(
                            "invalid default value for '{}': '{}' is not a valid u32",
                            param_name, default_val
                        ),
                    )
                })?;
                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().map_err(|_| {
                    syn::Error::new(
                        proc_macro2::Span::call_site(),
                        format!(
                            "invalid default value for '{}': '{}' is not a valid usize",
                            param_name, default_val
                        ),
                    )
                })?;
                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().map_err(|_| {
                    syn::Error::new(
                        proc_macro2::Span::call_site(),
                        format!(
                            "invalid default value for '{}': '{}' is not a valid i64",
                            param_name, default_val
                        ),
                    )
                })?;
                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().map_err(|_| {
                    syn::Error::new(
                        proc_macro2::Span::call_site(),
                        format!(
                            "invalid default value for '{}': '{}' is not a valid i32",
                            param_name, default_val
                        ),
                    )
                })?;
                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 = match params.get(#param_name) {
                        Some(v) => v.parse::<#ty>().map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid value for parameter '{}': {}", #param_name, e)
                        ))?,
                        None => #default_val.parse::<#ty>().map_err(|e| #endpoint_crate::CamelError::InvalidUri(
                            format!("invalid default value for parameter '{}': {}", #param_name, e)
                        ))?,
                    };
                }
            } 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)
                        ))?
                }
            }
        }
    })
}

// ---------------------------------------------------------------------------
// uri_options() generation (task 1.3)
// ---------------------------------------------------------------------------

/// Build the `UriOption` constructor expression (a builder-method chain) for
/// a single `#[uri_param]` field.
fn build_uri_option_entry(
    field_ident: &syn::Ident,
    field_type: &Type,
    attr: &UriParamAttr,
    endpoint_crate: &syn::Path,
    is_descriptor: bool,
) -> syn::Result<TokenStream> {
    // Guardrail: secret + default is a compile error.
    if attr.secret && attr.default.is_some() {
        return Err(syn::Error::new_spanned(
            field_ident,
            "#[uri_param] cannot have both `secret` and `default`; a secret \
             must never carry a default value",
        ));
    }

    // Pattern (open-namespace) guardrails. All checks below fire only when
    // `pattern` is present; they are co-located with the secret+default check
    // above (same shape: spanned on the field ident, returned as syn::Error).
    if let Some(sep) = &attr.pattern {
        // Field-type check: must be exactly Vec<(String, String)>.
        if !is_vec_string_pair(field_type) {
            return Err(syn::Error::new_spanned(
                field_ident,
                "`pattern` is only valid on fields of type `Vec<(String, String)>`",
            ));
        }
        if attr.required {
            return Err(syn::Error::new_spanned(
                field_ident,
                "#[uri_param] cannot have both `pattern` and `required`; \
                 an open namespace cannot require a single key",
            ));
        }
        if attr.default.is_some() {
            return Err(syn::Error::new_spanned(
                field_ident,
                "#[uri_param] cannot have both `pattern` and `default`; \
                 an open namespace has no default value",
            ));
        }
        if attr.secret {
            return Err(syn::Error::new_spanned(
                field_ident,
                "#[uri_param] cannot have both `pattern` and `secret`; \
                 an open namespace has no single secret value",
            ));
        }
        if attr.name.is_some() {
            return Err(syn::Error::new_spanned(
                field_ident,
                "#[uri_param] cannot have both `pattern` and `name`; \
                 the name is derived from the separator",
            ));
        }
        if !attr.aliases.is_empty() {
            return Err(syn::Error::new_spanned(
                field_ident,
                "#[uri_param] cannot have both `pattern` and `aliases`; \
                 a namespace matches by prefix, not by exact alias",
            ));
        }
        if let Some(lit) = &attr.kind_override
            && lit.value() != "string"
        {
            return Err(syn::Error::new_spanned(
                field_ident,
                "#[uri_param] `kind` on a pattern field must be `string` or omitted",
            ));
        }
        if sep.is_empty() {
            return Err(syn::Error::new_spanned(
                field_ident,
                "#[uri_param] `pattern` separator must be non-empty",
            ));
        }
        if !sep.ends_with('.') {
            return Err(syn::Error::new_spanned(
                field_ident,
                "#[uri_param] `pattern` separator must end with `.` \
                 (the only permitted separator shape in this version)",
            ));
        }
    }

    let param_name = if let Some(sep) = &attr.pattern {
        // Guardrail guarantees the separator ends with '.'; strip that one trailing dot.
        sep[..sep.len() - 1].to_string()
    } else {
        attr.name.clone().unwrap_or_else(|| field_ident.to_string())
    };
    let description = attr.desc.clone().unwrap_or_default();

    // Resolve kind: a pattern field is always String (the guardrails rejected
    // any non-string `kind`); otherwise an explicit override wins; otherwise
    // infer (never Enum).
    let kind_ts = if attr.pattern.is_some() {
        let path = quote! { #endpoint_crate::OptionKind };
        quote! { #path::String }
    } else if let Some(lit) = &attr.kind_override {
        parse_kind_override(&lit.value(), lit.span(), endpoint_crate)?
    } else {
        infer_option_kind(field_type, endpoint_crate)
    };

    // Required inference: a pattern namespace is never required; explicit
    // flag wins; descriptor mode suppresses shape inference; else
    // non-Option with no default => required, Option or has-default => false.
    let is_option = is_option_type(field_type).is_some();
    let required = if attr.pattern.is_some() {
        false
    } else if attr.required {
        true
    } else if is_descriptor {
        false
    } else {
        !is_option && attr.default.is_none()
    };

    let mut chain = quote! {
        #endpoint_crate::UriOption::new(#param_name, #description, #kind_ts)
    };
    if required {
        chain = quote! { #chain.required() };
    }
    if let Some(default_val) = &attr.default {
        chain = quote! { #chain.with_default(#default_val) };
    }
    if attr.secret {
        chain = quote! { #chain.secret() };
    }
    if let Some(deprecated_reason) = &attr.deprecated {
        chain = quote! { #chain.deprecated(#deprecated_reason) };
    }
    for alias in &attr.aliases {
        chain = quote! { #chain.with_alias(#alias) };
    }
    if let Some(sep) = &attr.pattern {
        chain = quote! { #chain.pattern_prefix(#sep) };
    }

    Ok(chain)
}

// ---------------------------------------------------------------------------
// Main derive entrypoint
// ---------------------------------------------------------------------------

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

    let uri_config_attr = parse_uri_config_attr(&input.attrs)?;

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

    // Extract scheme from struct attributes
    let scheme = extract_scheme(&input.attrs)?;

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

    // First pass: collect field info
    #[derive(Clone)]
    enum FieldType {
        Path,
        Param { attr: UriParamAttr },
        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()) // allow-unwrap
        .collect();

    for field in fields {
        let field_name = field.ident.as_ref().unwrap().clone(); // allow-unwrap
        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);

            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)) => {
                field_info.push((field_name, field_type, FieldType::Param { attr }));
            }
            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 {
                    return Err(syn::Error::new_spanned(
                        field,
                        "only one field can be the path field (first field without #[uri_param])",
                    ));
                }
            }
            Err(e) => {
                return Err(e);
            }
        }
    }

    // Second pass: generate local variable bindings
    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()
                        });
                    }
                    _ => {
                        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 { attr } => {
                if let Some(sep) = &attr.pattern {
                    // Open-namespace field: collect (suffix, value) pairs whose
                    // query key starts with the separator and has a non-empty
                    // suffix (matches the lint resolver semantics — a bare
                    // `param.` key does not match). The field-type guardrail in
                    // `build_uri_option_entry` already constrained this field to
                    // `Vec<(String, String)>`.
                    bindings.push(quote! {
                        let #field_name = params.iter()
                            .filter_map(|(k, v)| {
                                if k.starts_with(#sep) && k.len() > #sep.len() {
                                    Some((k[#sep.len()..].to_string(), v.clone()))
                                } else {
                                    None
                                }
                            })
                            .collect::<::std::vec::Vec<(::std::string::String, ::std::string::String)>>()
                    });
                } else {
                    let param_name = attr.name.clone().unwrap_or_else(|| field_name.to_string());
                    let parsing_code = generate_param_parsing(
                        &param_name,
                        field_name,
                        field_type,
                        attr.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),*
        })
    };

    // ---- Build uri_options() entries (one per #[uri_param] Param field) ----
    let mut uri_option_entries: Vec<TokenStream> = Vec::new();
    for (field_name, field_type, ftype) in &field_info {
        if let FieldType::Param { attr } = ftype {
            uri_option_entries.push(build_uri_option_entry(
                field_name,
                field_type,
                attr,
                &endpoint_crate,
                uri_config_attr.descriptor,
            )?);
        }
    }

    let uri_options_fn = quote! {
        /// Generated URI option definitions, one per `#[uri_param]` field.
        /// The path field is excluded.
        pub fn uri_options() -> ::std::vec::Vec<#endpoint_crate::UriOption> {
            vec![ #(#uri_option_entries),* ]
        }
    };

    // ---- Conditionally generate metadata() (task 1.4) ----
    let metadata_fn = if uri_config_attr.has_metadata {
        let meta_scheme = uri_config_attr
            .metadata_scheme
            .unwrap_or_else(|| scheme_lit.clone());
        let meta_description = uri_config_attr.metadata_description.unwrap_or_default();
        let sp = uri_config_attr.supports_producer;
        let sc = uri_config_attr.supports_consumer;
        let spc = uri_config_attr.supports_polling_consumer;
        let ss = uri_config_attr.supports_streaming;
        Some(quote! {
            /// Generated `ComponentMetadata`, built from the
            /// `#[uri_config(metadata(..))]` attribute plus the derived
            /// `uri_options()`.
            pub fn metadata() -> #endpoint_crate::ComponentMetadata {
                #endpoint_crate::ComponentMetadata::minimal(#meta_scheme)
                    .with_description(#meta_description)
                    .with_capabilities(#endpoint_crate::ComponentCapabilities {
                        supports_producer: #sp,
                        supports_consumer: #sc,
                        supports_polling_consumer: #spc,
                        supports_streaming: #ss,
                    })
                    .with_uri_options(Self::uri_options())
            }
        })
    } else {
        None
    };

    if skip_impl {
        Ok(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
                }

                #uri_options_fn
                #metadata_fn
            }
        })
    } else {
        Ok(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
                }

                #uri_options_fn
                #metadata_fn
            }
        })
    }
}

// ---------------------------------------------------------------------------
// Tests — pure parse/infer unit tests (no macro invocation).
// ---------------------------------------------------------------------------

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

    fn parse_attr(src: &str) -> UriParamAttr {
        syn::parse_str::<UriParamAttr>(src).expect("failed to parse uri_param attr")
    }

    #[test]
    fn parse_secret_flag() {
        let attr = parse_attr("secret");
        assert!(attr.secret);
        assert!(!attr.required);
    }

    #[test]
    fn parse_secret_with_other_keys() {
        // Mixed flag + keyvalue form.
        let attr = parse_attr("secret, default = \"x\"");
        assert!(attr.secret);
        assert_eq!(attr.default.as_deref(), Some("x"));
    }

    #[test]
    fn parse_deprecated_key() {
        let attr = parse_attr("deprecated = \"old\"");
        assert_eq!(attr.deprecated.as_deref(), Some("old"));
    }

    #[test]
    fn parse_aliases_array() {
        let attr = parse_attr("aliases = [\"a\", \"b\"]");
        assert_eq!(attr.aliases, vec!["a".to_string(), "b".to_string()]);
    }

    #[test]
    fn parse_unknown_key_still_errors() {
        let res = syn::parse_str::<UriParamAttr>("bogus = 1");
        assert!(res.is_err());
        let msg = res.unwrap_err().to_string();
        assert!(msg.contains("unknown attribute key"), "msg was: {msg}");
    }

    #[test]
    fn parse_required_flag_and_kv() {
        let a = parse_attr("required");
        assert!(a.required);
        let b = parse_attr("required = false");
        assert!(!b.required);
    }

    #[test]
    fn parse_kind_override_captured() {
        let a = parse_attr("kind = \"enum:A,B\"");
        assert_eq!(a.kind_override.as_ref().unwrap().value(), "enum:A,B");
    }

    #[test]
    fn parse_desc_key() {
        let a = parse_attr("desc = \"the period\"");
        assert_eq!(a.desc.as_deref(), Some("the period"));
    }

    fn parse_type(src: &str) -> Type {
        syn::parse_str::<Type>(src).expect("failed to parse type")
    }

    // A dummy crate path for unit-testing inference token output.
    fn test_crate() -> syn::Path {
        syn::parse_quote!(__test_crate)
    }

    fn kind_str(ty: &Type) -> String {
        infer_option_kind(ty, &test_crate()).to_string()
    }

    #[test]
    fn infer_bool() {
        let s = kind_str(&parse_type("bool"));
        assert!(s.contains("Bool"), "{s}");
    }

    #[test]
    fn infer_duration() {
        let s = kind_str(&parse_type("std::time::Duration"));
        assert!(s.contains("Duration"), "{s}");
    }

    #[test]
    fn infer_string() {
        let s = kind_str(&parse_type("String"));
        assert!(s.contains("String"), "{s}");
    }

    #[test]
    fn infer_option_inner_kind() {
        // Option<u32> unwraps to Int.
        let s = kind_str(&parse_type("Option<u32>"));
        assert!(s.contains("Int"), "{s}");
    }

    #[test]
    fn infer_vec_string() {
        let s = kind_str(&parse_type("Vec<String>"));
        assert!(s.contains("List"), "{s}");
        assert!(s.contains("String"), "{s}");
    }

    #[test]
    fn infer_enum_is_string() {
        // An unknown/enum type infers to String — never Enum.
        let s = kind_str(&parse_type("MyMode"));
        assert!(s.contains("String"), "{s}");
    }

    #[test]
    fn infer_ints_and_floats() {
        assert!(kind_str(&parse_type("u64")).contains("Int"));
        assert!(kind_str(&parse_type("i32")).contains("Int"));
        assert!(kind_str(&parse_type("f64")).contains("Float"));
    }

    #[test]
    fn kind_override_enum() {
        let ts = parse_kind_override("enum:A,B", proc_macro2::Span::call_site(), &test_crate())
            .expect("valid override");
        let s = ts.to_string();
        assert!(s.contains("Enum"), "{s}");
        assert!(s.contains("A") && s.contains("B"), "{s}");
    }

    #[test]
    fn kind_override_known_strings() {
        let c = test_crate();
        assert!(
            parse_kind_override("duration", proc_macro2::Span::call_site(), &c)
                .unwrap()
                .to_string()
                .contains("Duration")
        );
        assert!(
            parse_kind_override("bool", proc_macro2::Span::call_site(), &c)
                .unwrap()
                .to_string()
                .contains("Bool")
        );
    }

    #[test]
    fn kind_typo_errors() {
        let res = parse_kind_override("duraton", proc_macro2::Span::call_site(), &test_crate());
        assert!(res.is_err());
    }

    // ── uri_config parser-level tests ──

    /// Parse a `#[uri_config(...)]` attribute string, returning the
    /// parsed `UriConfigAttr`.
    fn parse_uri_config_str(attr_str: &str) -> UriConfigAttr {
        let input: syn::DeriveInput =
            syn::parse_str(&format!("#[uri_config({attr_str})]\nstruct Dummy;"))
                .expect("failed to parse derive input");
        parse_uri_config_attr(&input.attrs).expect("failed to parse uri_config attr")
    }

    #[test]
    fn descriptor_flag_parses_as_bare_ident() {
        let attr = parse_uri_config_str("skip_impl, descriptor, metadata(scheme = \"x\")");
        assert!(attr.descriptor);
    }

    #[test]
    fn absent_descriptor_defaults_to_false() {
        let attr = parse_uri_config_str("skip_impl, metadata(scheme = \"x\")");
        assert!(!attr.descriptor);
    }
}