server-less-parse 0.6.0

Shared parsing utilities for server-less proc macros
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
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
//! Shared parsing utilities for server-less proc macros.
//!
//! This crate provides common types and functions for extracting
//! method information from impl blocks.
//!
//! **Internal API.** This crate exists to support the `server-less` proc macros
//! and is published only because path dependencies are disallowed. Its surface is
//! typed in terms of `syn` / `proc-macro2` and carries **no stability guarantees**;
//! depend on the `server-less` facade instead.

use syn::{
    FnArg, GenericArgument, Ident, ImplItem, ImplItemFn, ItemImpl, Lit, Meta, Pat, PathArguments,
    ReturnType, Type, TypeReference,
};

/// Parsed method information with full `syn` AST types.
///
/// This is the rich, compile-time representation used by all proc macros
/// during code generation. It retains full `syn::Type` and `syn::Ident`
/// nodes for accurate token generation.
///
/// **Not to be confused with [`server_less_core::MethodInfo`]**, which is
/// a simplified, string-based representation for runtime introspection.
#[derive(Debug, Clone)]
pub struct MethodInfo {
    /// The original method
    pub method: ImplItemFn,
    /// Method name
    pub name: Ident,
    /// Documentation string
    pub docs: Option<String>,
    /// Parameters (excluding self)
    pub params: Vec<ParamInfo>,
    /// Return type info
    pub return_info: ReturnInfo,
    /// Whether the method is async
    pub is_async: bool,
    /// Group assignment from `#[server(group = "...")]`
    pub group: Option<String>,
    /// Explicit wire name override from `#[server(name = "...")]` or protocol-specific
    /// `#[cli(name = "...")]`, `#[mcp(name = "...")]`, etc.
    pub wire_name: Option<String>,
    /// `#[cfg(...)]` attributes on this method, to be propagated to generated dispatch items.
    pub cfg_attrs: Vec<syn::Attribute>,
}

/// Registry of declared method groups from `#[server(groups(...))]`.
///
/// When present on an impl block, method `group` values are resolved as IDs
/// against this registry. When absent, `group` values are literal display names.
#[derive(Debug, Clone)]
pub struct GroupRegistry {
    /// Ordered list of (id, display_name) pairs.
    /// Ordering determines display order in help output and documentation.
    pub groups: Vec<(String, String)>,
}

/// Parsed parameter information
#[derive(Debug, Clone)]
pub struct ParamInfo {
    /// Parameter name
    pub name: Ident,
    /// Parameter type
    pub ty: Type,
    /// Whether this is `Option<T>`
    pub is_optional: bool,
    /// Whether this is `bool`
    pub is_bool: bool,
    /// Whether this is `Vec<T>`
    pub is_vec: bool,
    /// Inner type if `Vec<T>`
    pub vec_inner: Option<Type>,
    /// Whether this looks like an ID (ends with _id or is named id)
    pub is_id: bool,
    /// Custom wire name (from #[param(name = "...")])
    pub wire_name: Option<String>,
    /// Parameter location override (from #[param(query/path/body/header)])
    pub location: Option<ParamLocation>,
    /// Default value as a string (from #[param(default = ...)])
    pub default_value: Option<String>,
    /// Short flag character (from #[param(short = 'x')])
    pub short_flag: Option<char>,
    /// Custom help text (from #[param(help = "...")])
    pub help_text: Option<String>,
    /// Whether this is a positional argument (from #[param(positional)] or is_id heuristic)
    pub is_positional: bool,
}

impl MethodInfo {
    /// Rust method name with `r#` prefix stripped.
    ///
    /// Returns the raw identifier name, ignoring any `wire_name` override.
    /// Use this for code generation (`self.method_name()`) and as the base for
    /// protocol-specific transforms (`.to_kebab_case()`, `.to_snake_case()`, etc.).
    pub fn name_str(&self) -> String {
        ident_str(&self.name)
    }

    /// Protocol-facing name, applying a transform to the raw name unless overridden.
    ///
    /// If `wire_name` is set (from `#[server(name = "...")]` or protocol-specific
    /// attributes), returns it as-is. Otherwise applies `transform` to the raw name.
    ///
    /// ```ignore
    /// // CLI: kebab-case
    /// method.wire_name_or(|n| n.to_kebab_case())
    /// // JSON-RPC: raw name
    /// method.wire_name_or(|n| n)
    /// // gRPC: snake_case
    /// method.wire_name_or(|n| n.to_snake_case())
    /// ```
    pub fn wire_name_or(&self, transform: impl FnOnce(String) -> String) -> String {
        if let Some(ref wn) = self.wire_name {
            wn.clone()
        } else {
            transform(self.name_str())
        }
    }
}

impl ParamInfo {
    /// Parameter name as a protocol string, stripping the `r#` prefix from raw identifiers.
    ///
    /// Use this instead of `.name.to_string()` whenever generating protocol-level names
    /// (CLI flags, HTTP query params, JSON schema properties, etc.).
    pub fn name_str(&self) -> String {
        ident_str(&self.name)
    }
}

/// Convert an identifier to a string, stripping the `r#` prefix for raw identifiers.
///
/// `proc_macro2::Ident::to_string()` preserves the `r#` prefix (e.g. `r#type` → `"r#type"`),
/// which produces incorrect protocol names. Use this function whenever an `Ident` is converted
/// to a string for protocol-level output (CLI flags, HTTP routes, JSON-RPC method names, etc.).
pub fn ident_str(ident: &Ident) -> String {
    let s = ident.to_string();
    s.strip_prefix("r#").map(str::to_string).unwrap_or(s)
}

/// Compile-time HTTP method enum used by proc macros during code generation.
///
/// See also [`server_less_core::HttpMethod`] for the runtime equivalent used
/// in generated introspection code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HttpMethod {
    Get,
    Post,
    Put,
    Patch,
    Delete,
}

impl HttpMethod {
    /// Returns the HTTP method as an uppercase string slice (e.g. `"GET"`, `"POST"`).
    pub fn as_str(&self) -> &'static str {
        match self {
            HttpMethod::Get => "GET",
            HttpMethod::Post => "POST",
            HttpMethod::Put => "PUT",
            HttpMethod::Patch => "PATCH",
            HttpMethod::Delete => "DELETE",
        }
    }

    /// Parse from string (case-insensitive)
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_uppercase().as_str() {
            "GET" => Some(HttpMethod::Get),
            "POST" => Some(HttpMethod::Post),
            "PUT" => Some(HttpMethod::Put),
            "PATCH" => Some(HttpMethod::Patch),
            "DELETE" => Some(HttpMethod::Delete),
            _ => None,
        }
    }
}

/// Parameter location for HTTP requests
#[derive(Debug, Clone, PartialEq)]
pub enum ParamLocation {
    Query,
    Path,
    Body,
    Header,
}

/// Parsed return type information
#[derive(Debug, Clone)]
pub struct ReturnInfo {
    /// The full return type
    pub ty: Option<Type>,
    /// Inner type if `Result<T, E>`
    pub ok_type: Option<Type>,
    /// Error type if `Result<T, E>`
    pub err_type: Option<Type>,
    /// Inner type if `Option<T>`
    pub some_type: Option<Type>,
    /// Whether it's a Result
    pub is_result: bool,
    /// Whether it's an Option (and not Result)
    pub is_option: bool,
    /// Whether it returns ()
    pub is_unit: bool,
    /// Whether it's impl Stream<Item=T>
    pub is_stream: bool,
    /// The stream item type if is_stream
    pub stream_item: Option<Type>,
    /// Whether it's impl Iterator<Item=T>
    pub is_iterator: bool,
    /// The iterator item type if is_iterator
    pub iterator_item: Option<Type>,
    /// Whether the return type is a reference (&T)
    pub is_reference: bool,
    /// The inner type T if returning &T
    pub reference_inner: Option<Type>,
}

/// Walks a method body looking for a real `.await` in a sync context.
///
/// Soundness rules (avoid false positives):
/// - Macro token streams are not parsed (the default `visit_macro` does not
///   descend into `Macro.tokens`), so `.await` text inside `println!`/`format!`
///   or any macro is invisible.
/// - Nested `async { ... }` blocks are skipped: a `.await` inside one is legal
///   in a sync fn.
/// - `async` closures are skipped; sync closures are walked normally.
struct AwaitFinder {
    /// Span of the first offending `.await`, if any.
    found: Option<proc_macro2::Span>,
}

impl<'ast> syn::visit::Visit<'ast> for AwaitFinder {
    fn visit_expr_await(&mut self, node: &'ast syn::ExprAwait) {
        if self.found.is_none() {
            self.found = Some(node.await_token.span);
        }
        // Continue walking the awaited base in case it contains another await,
        // though the first found span is what we report.
        syn::visit::visit_expr(self, &node.base);
    }

    fn visit_expr_async(&mut self, _node: &'ast syn::ExprAsync) {
        // `.await` inside a nested `async { ... }` block is legal in a sync fn.
        // Do not recurse.
    }

    fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
        // An `async` closure introduces its own async context; do not recurse.
        // A sync closure is walked normally.
        if node.asyncness.is_none() {
            syn::visit::visit_expr_closure(self, node);
        }
    }
}

impl MethodInfo {
    /// Parse a method from an ImplItemFn
    ///
    /// Returns None for associated functions without `&self` (constructors, etc.)
    pub fn parse(method: &ImplItemFn) -> syn::Result<Option<Self>> {
        let name = method.sig.ident.clone();
        let is_async = method.sig.asyncness.is_some();

        // Skip associated functions without self receiver (constructors, etc.)
        let has_receiver = method
            .sig
            .inputs
            .iter()
            .any(|arg| matches!(arg, FnArg::Receiver(_)));
        if !has_receiver {
            return Ok(None);
        }

        // Await-without-async: a sync method whose body really awaits cannot be
        // projected onto a protocol surface. Pre-empt rustc's generic E0728 with
        // projection framing. Only the OUTER method's asyncness matters.
        if method.sig.asyncness.is_none() {
            let mut finder = AwaitFinder { found: None };
            syn::visit::Visit::visit_block(&mut finder, &method.block);
            if let Some(span) = finder.found {
                return Err(syn::Error::new(
                    span,
                    "this method uses `.await` but is not declared `async`\n\n\
                     server-less projects each method onto a protocol surface; an \
                     awaiting method must be `async` so the projection can drive it.\n\n\
                     Hint: add `async` to the signature, e.g. `async fn NAME(&self, ...) -> ...`",
                ));
            }
        }

        // Extract doc comments
        let docs = extract_docs(&method.attrs);

        // Parse parameters
        let params = parse_params(&method.sig.inputs)?;

        // Parse return type
        let return_info = parse_return_type(&method.sig.output);

        // Extract group from #[server(group = "...")]
        let group = extract_server_group(&method.attrs);

        // Extract wire name from #[server(name = "...")] or protocol-specific attrs
        let wire_name = extract_wire_name(&method.attrs);

        // Collect #[cfg(...)] attributes for propagation to generated dispatch items
        let cfg_attrs: Vec<syn::Attribute> = method
            .attrs
            .iter()
            .filter(|a| a.path().is_ident("cfg"))
            .cloned()
            .collect();

        Ok(Some(Self {
            method: method.clone(),
            name,
            docs,
            params,
            return_info,
            is_async,
            group,
            wire_name,
            cfg_attrs,
        }))
    }
}

/// Extract doc comments from attributes
pub fn extract_docs(attrs: &[syn::Attribute]) -> Option<String> {
    let docs: Vec<String> = attrs
        .iter()
        .filter_map(|attr| {
            if attr.path().is_ident("doc")
                && let Meta::NameValue(meta) = &attr.meta
                && let syn::Expr::Lit(syn::ExprLit {
                    lit: Lit::Str(s), ..
                }) = &meta.value
            {
                return Some(s.value().trim().to_string());
            }
            None
        })
        .collect();

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

/// Known protocol attribute identifiers used by server-less macros.
const PROTOCOL_ATTRS: &[&str] = &[
    "server", "cli", "http", "mcp", "jsonrpc", "grpc", "ws", "graphql", "tool",
];

/// Extract `name = "..."` from any protocol attribute on a method.
///
/// Checks `#[server(name = "...")]`, `#[cli(name = "...")]`, `#[mcp(name = "...")]`, etc.
/// If multiple protocol attrs specify `name`, the first one found wins.
fn extract_wire_name(attrs: &[syn::Attribute]) -> Option<String> {
    for attr in attrs {
        let is_protocol = attr
            .path()
            .get_ident()
            .is_some_and(|id| PROTOCOL_ATTRS.iter().any(|p| id == p));
        if !is_protocol {
            continue;
        }
        let mut found = None;
        let _ = attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("name") {
                let value = meta.value()?;
                let s: syn::LitStr = value.parse()?;
                found = Some(s.value());
            } else if meta.input.peek(syn::Token![=]) {
                let _: proc_macro2::TokenStream = meta.value()?.parse()?;
            }
            Ok(())
        });
        if found.is_some() {
            return found;
        }
    }
    None
}

/// Extract the `group` value from `#[server(group = "...")]` on a method.
fn extract_server_group(attrs: &[syn::Attribute]) -> Option<String> {
    for attr in attrs {
        if attr.path().is_ident("server") {
            let mut group = None;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("group") {
                    let value = meta.value()?;
                    let s: syn::LitStr = value.parse()?;
                    group = Some(s.value());
                } else if meta.input.peek(syn::Token![=]) {
                    // Consume other `key = value` pairs without error.
                    let _: proc_macro2::TokenStream = meta.value()?.parse()?;
                }
                Ok(())
            });
            if group.is_some() {
                return group;
            }
        }
    }
    None
}

/// Extract the group registry from `#[server(groups(...))]` on an impl block.
///
/// Returns `None` if no `groups(...)` attribute is present.
/// Returns ordered `(id, display_name)` pairs matching declaration order.
pub fn extract_groups(impl_block: &ItemImpl) -> syn::Result<Option<GroupRegistry>> {
    for attr in &impl_block.attrs {
        if attr.path().is_ident("server") {
            let mut groups = Vec::new();
            let mut found_groups = false;
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("groups") {
                    found_groups = true;
                    meta.parse_nested_meta(|inner| {
                        let id = inner
                            .path
                            .get_ident()
                            .ok_or_else(|| inner.error("expected group identifier"))?
                            .to_string();
                        let value = inner.value()?;
                        let display: syn::LitStr = value.parse()?;
                        groups.push((id, display.value()));
                        Ok(())
                    })?;
                } else if meta.input.peek(syn::Token![=]) {
                    let _: proc_macro2::TokenStream = meta.value()?.parse()?;
                } else if meta.input.peek(syn::token::Paren) {
                    let _content;
                    syn::parenthesized!(_content in meta.input);
                }
                Ok(())
            })?;
            if found_groups {
                return Ok(Some(GroupRegistry { groups }));
            }
        }
    }
    Ok(None)
}

/// Resolve a method's group against the registry.
///
/// When the method has `group = "id"`, the registry must be present and must
/// contain a matching ID — otherwise a compile error is emitted. The returned
/// string is the display name from the registry.
///
/// When the method has no `group` attribute, returns `None`.
pub fn resolve_method_group(
    method: &MethodInfo,
    registry: &Option<GroupRegistry>,
) -> syn::Result<Option<String>> {
    let group_value = match &method.group {
        Some(v) => v,
        None => return Ok(None),
    };

    let span = method.method.sig.ident.span();

    match registry {
        Some(reg) => {
            for (id, display) in &reg.groups {
                if id == group_value {
                    return Ok(Some(display.clone()));
                }
            }
            Err(syn::Error::new(
                span,
                format!(
                    "unknown group `{group_value}`; declared groups are: {}",
                    reg.groups
                        .iter()
                        .map(|(id, _)| format!("`{id}`"))
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            ))
        }
        None => Err(syn::Error::new(
            span,
            format!(
                "method has `group = \"{group_value}\"` but no `groups(...)` registry is declared on the impl block\n\
                 \n\
                 help: add `#[server(groups({group_value} = \"Display Name\"))]` to the impl block"
            ),
        )),
    }
}

/// Parsed result of `#[param(...)]` attributes.
#[derive(Debug, Clone, Default)]
pub struct ParsedParamAttrs {
    /// Override for the parameter's name on the wire (from `#[param(name = "...")]`).
    /// When set, the API/CLI uses this name instead of the Rust identifier.
    pub wire_name: Option<String>,
    /// Force a specific extraction location (from `#[param(query)]`, `#[param(path)]`, etc.).
    /// When `None`, location is inferred from the HTTP method and parameter name.
    pub location: Option<ParamLocation>,
    /// Literal default value (from `#[param(default = ...)]`).
    /// Makes the parameter optional on the wire; the value is used when absent.
    pub default_value: Option<String>,
    /// Single-character CLI short flag (from `#[param(short = 'x')]`).
    /// When set, adds `-x` as an alias for the long flag in clap.
    pub short_flag: Option<char>,
    /// Human-readable help text (from `#[param(help = "...")]`).
    /// Shown in CLI `--help` output and OpenAPI parameter descriptions.
    pub help_text: Option<String>,
    /// Marks the parameter as a CLI positional argument (from `#[param(positional)]`).
    /// Positional parameters are ordered by declaration order and have no `--flag` form.
    pub positional: bool,
    /// Environment variable name (from `#[param(env = "VAR")]`). Used by `#[derive(Config)]`.
    pub env_var: Option<String>,
    /// Config file key override (from `#[param(file_key = "a.b.c")]`). Used by `#[derive(Config)]`.
    pub file_key: Option<String>,
    /// Marks a field as a nested `Config` sub-struct (from `#[param(nested)]`).
    ///
    /// The field's type must also `#[derive(Config)]`.  TOML loading delegates to
    /// the child's `Config::load`, using the field name (or `file_key`) as the
    /// sub-table name.  Env var loading narrows the prefix with the field name.
    pub nested: bool,
    /// Env-var prefix override for a nested field (from `#[param(env_prefix = "SEARCH")]`).
    ///
    /// When set, env vars for the child struct use `{env_prefix}_{CHILD_FIELD}` instead
    /// of `{parent_prefix}_{field_name}_{CHILD_FIELD}`.  Only meaningful with `nested`.
    pub env_prefix: Option<String>,
    /// Serde-passthrough flag for nested fields (from `#[param(nested, serde)]`).
    ///
    /// When `true` (implies `nested = true`), the TOML sub-table for this field is
    /// deserialized via `serde::Deserialize` instead of `Config::load`.  Env-var
    /// overrides are silently skipped for the serde-nested subtree; use
    /// `#[serde(default)]` in the child type for defaults.  Only meaningful with
    /// `nested`.
    pub nested_serde: bool,
}

/// Compute Levenshtein edit distance between two strings.
#[allow(clippy::needless_range_loop)]
pub fn levenshtein(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let m = a.len();
    let n = b.len();
    let mut dp = vec![vec![0usize; n + 1]; m + 1];
    for i in 0..=m {
        dp[i][0] = i;
    }
    for j in 0..=n {
        dp[0][j] = j;
    }
    for i in 1..=m {
        for j in 1..=n {
            dp[i][j] = if a[i - 1] == b[j - 1] {
                dp[i - 1][j - 1]
            } else {
                1 + dp[i - 1][j - 1].min(dp[i - 1][j]).min(dp[i][j - 1])
            };
        }
    }
    dp[m][n]
}

/// Return the closest candidate to `input` within edit distance ≤ 2, or `None`.
pub fn did_you_mean<'a>(input: &str, candidates: &[&'a str]) -> Option<&'a str> {
    candidates
        .iter()
        .filter_map(|&c| {
            let d = levenshtein(input, c);
            if d <= 2 { Some((d, c)) } else { None }
        })
        .min_by_key(|&(d, _)| d)
        .map(|(_, c)| c)
}

/// Parse #[param(...)] attributes from a parameter
pub fn parse_param_attrs(attrs: &[syn::Attribute]) -> syn::Result<ParsedParamAttrs> {
    let mut wire_name = None;
    let mut location = None;
    let mut default_value = None;
    let mut short_flag = None;
    let mut help_text = None;
    let mut positional = false;
    let mut env_var = None;
    let mut file_key = None;
    let mut nested = false;
    let mut env_prefix = None;
    let mut nested_serde = false;

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

        attr.parse_nested_meta(|meta| {
            // #[param(name = "...")]
            if meta.path.is_ident("name") {
                let value: syn::LitStr = meta.value()?.parse()?;
                wire_name = Some(value.value());
                Ok(())
            }
            // #[param(default = ...)]
            else if meta.path.is_ident("default") {
                // Accept various literal types
                let value = meta.value()?;
                let lookahead = value.lookahead1();
                if lookahead.peek(syn::LitStr) {
                    let lit: syn::LitStr = value.parse()?;
                    default_value = Some(format!("\"{}\"", lit.value()));
                } else if lookahead.peek(syn::LitInt) {
                    let lit: syn::LitInt = value.parse()?;
                    default_value = Some(lit.to_string());
                } else if lookahead.peek(syn::LitBool) {
                    let lit: syn::LitBool = value.parse()?;
                    default_value = Some(lit.value.to_string());
                } else {
                    return Err(lookahead.error());
                }
                Ok(())
            }
            // #[param(query)] or #[param(path)] etc.
            else if meta.path.is_ident("query") {
                location = Some(ParamLocation::Query);
                Ok(())
            } else if meta.path.is_ident("path") {
                location = Some(ParamLocation::Path);
                Ok(())
            } else if meta.path.is_ident("body") {
                location = Some(ParamLocation::Body);
                Ok(())
            } else if meta.path.is_ident("header") {
                location = Some(ParamLocation::Header);
                Ok(())
            }
            // #[param(short = 'v')]
            else if meta.path.is_ident("short") {
                let value: syn::LitChar = meta.value()?.parse()?;
                short_flag = Some(value.value());
                Ok(())
            }
            // #[param(help = "description")]
            else if meta.path.is_ident("help") {
                let value: syn::LitStr = meta.value()?.parse()?;
                help_text = Some(value.value());
                Ok(())
            }
            // #[param(positional)]
            else if meta.path.is_ident("positional") {
                positional = true;
                Ok(())
            }
            // #[param(env = "VAR_NAME")]
            else if meta.path.is_ident("env") {
                let value: syn::LitStr = meta.value()?.parse()?;
                env_var = Some(value.value());
                Ok(())
            }
            // #[param(file_key = "a.b.c")]
            else if meta.path.is_ident("file_key") {
                let value: syn::LitStr = meta.value()?.parse()?;
                file_key = Some(value.value());
                Ok(())
            }
            // #[param(nested)]
            else if meta.path.is_ident("nested") {
                nested = true;
                Ok(())
            }
            // #[param(serde)] — only meaningful alongside `nested`; sets nested_serde = true
            else if meta.path.is_ident("serde") {
                nested_serde = true;
                Ok(())
            }
            // #[param(env_prefix = "SEARCH")]
            else if meta.path.is_ident("env_prefix") {
                let value: syn::LitStr = meta.value()?.parse()?;
                env_prefix = Some(value.value());
                Ok(())
            } else {
                const VALID: &[&str] = &[
                    "name", "default", "query", "path", "body", "header", "short", "help",
                    "positional", "env", "file_key", "nested", "serde", "env_prefix",
                ];
                let unknown = meta
                    .path
                    .get_ident()
                    .map(|i| i.to_string())
                    .unwrap_or_default();
                let suggestion = did_you_mean(&unknown, VALID)
                    .map(|s| format!(" — did you mean `{s}`?"))
                    .unwrap_or_default();
                Err(meta.error(format!(
                    "unknown attribute `{unknown}`{suggestion}\n\
                     \n\
                     Valid attributes: name, default, query, path, body, header, short, help, positional, env, file_key, nested, serde, env_prefix\n\
                     \n\
                     Examples:\n\
                     - #[param(name = \"q\")]\n\
                     - #[param(default = 10)]\n\
                     - #[param(query)]\n\
                     - #[param(header, name = \"X-API-Key\")]\n\
                     - #[param(short = 'v')]\n\
                     - #[param(help = \"Enable verbose output\")]\n\
                     - #[param(positional)]\n\
                     - #[param(env = \"MY_VAR\")]\n\
                     - #[param(file_key = \"database.host\")]\n\
                     - #[param(nested)]\n\
                     - #[param(nested, serde)]\n\
                     - #[param(nested, env_prefix = \"SEARCH\")]"
                )))
            }
        })?;
    }

    // `#[param(serde)]` implies `nested = true` — serde-deserialization only
    // applies to nested sub-structs, so treat `serde` alone as `nested, serde`.
    if nested_serde {
        nested = true;
    }

    Ok(ParsedParamAttrs {
        wire_name,
        location,
        default_value,
        short_flag,
        help_text,
        positional,
        env_var,
        file_key,
        nested,
        env_prefix,
        nested_serde,
    })
}

/// Parse function parameters (excluding self)
pub fn parse_params(
    inputs: &syn::punctuated::Punctuated<FnArg, syn::Token![,]>,
) -> syn::Result<Vec<ParamInfo>> {
    let mut params = Vec::new();

    for arg in inputs {
        match arg {
            FnArg::Receiver(_) => continue, // skip self
            FnArg::Typed(pat_type) => {
                let name = match pat_type.pat.as_ref() {
                    Pat::Ident(pat_ident) => pat_ident.ident.clone(),
                    other => {
                        return Err(syn::Error::new_spanned(
                            other,
                            "unsupported parameter pattern\n\
                             \n\
                             Server-less macros require simple parameter names.\n\
                             Use: name: String\n\
                             Not: (name, _): (String, i32) or &name: &String",
                        ));
                    }
                };

                let ty = (*pat_type.ty).clone();
                let is_optional = is_option_type(&ty);
                let is_bool = is_bool_type(&ty);
                let vec_inner = extract_vec_type(&ty);
                let is_vec = vec_inner.is_some();
                let is_id = is_id_param(&name);

                // Parse #[param(...)] attributes
                let parsed = parse_param_attrs(&pat_type.attrs)?;

                // is_positional: explicit attribute takes priority, is_id heuristic as fallback
                let is_positional = parsed.positional || is_id;

                params.push(ParamInfo {
                    name,
                    ty,
                    is_optional,
                    is_bool,
                    is_vec,
                    vec_inner,
                    is_id,
                    is_positional,
                    wire_name: parsed.wire_name,
                    location: parsed.location,
                    default_value: parsed.default_value,
                    short_flag: parsed.short_flag,
                    help_text: parsed.help_text,
                });
            }
        }
    }

    Ok(params)
}

/// Parse return type information
pub fn parse_return_type(output: &ReturnType) -> ReturnInfo {
    match output {
        ReturnType::Default => ReturnInfo {
            ty: None,
            ok_type: None,
            err_type: None,
            some_type: None,
            is_result: false,
            is_option: false,
            is_unit: true,
            is_stream: false,
            stream_item: None,
            is_iterator: false,
            iterator_item: None,
            is_reference: false,
            reference_inner: None,
        },
        ReturnType::Type(_, ty) => {
            let ty = ty.as_ref().clone();

            // Check for Result<T, E>
            if let Some((ok, err)) = extract_result_types(&ty) {
                return ReturnInfo {
                    ty: Some(ty),
                    ok_type: Some(ok),
                    err_type: Some(err),
                    some_type: None,
                    is_result: true,
                    is_option: false,
                    is_unit: false,
                    is_stream: false,
                    stream_item: None,
                    is_iterator: false,
                    iterator_item: None,
                    is_reference: false,
                    reference_inner: None,
                };
            }

            // Check for Option<T>
            if let Some(inner) = extract_option_type(&ty) {
                return ReturnInfo {
                    ty: Some(ty),
                    ok_type: None,
                    err_type: None,
                    some_type: Some(inner),
                    is_result: false,
                    is_option: true,
                    is_unit: false,
                    is_stream: false,
                    stream_item: None,
                    is_iterator: false,
                    iterator_item: None,
                    is_reference: false,
                    reference_inner: None,
                };
            }

            // Check for impl Stream<Item=T>
            if let Some(item) = extract_stream_item(&ty) {
                return ReturnInfo {
                    ty: Some(ty),
                    ok_type: None,
                    err_type: None,
                    some_type: None,
                    is_result: false,
                    is_option: false,
                    is_unit: false,
                    is_stream: true,
                    stream_item: Some(item),
                    is_iterator: false,
                    iterator_item: None,
                    is_reference: false,
                    reference_inner: None,
                };
            }

            // Check for impl Iterator<Item=T>
            if let Some(item) = extract_iterator_item(&ty) {
                return ReturnInfo {
                    ty: Some(ty),
                    ok_type: None,
                    err_type: None,
                    some_type: None,
                    is_result: false,
                    is_option: false,
                    is_unit: false,
                    is_stream: false,
                    stream_item: None,
                    is_iterator: true,
                    iterator_item: Some(item),
                    is_reference: false,
                    reference_inner: None,
                };
            }

            // Check for ()
            if is_unit_type(&ty) {
                return ReturnInfo {
                    ty: Some(ty),
                    ok_type: None,
                    err_type: None,
                    some_type: None,
                    is_result: false,
                    is_option: false,
                    is_unit: true,
                    is_stream: false,
                    stream_item: None,
                    is_iterator: false,
                    iterator_item: None,
                    is_reference: false,
                    reference_inner: None,
                };
            }

            // Check for &T (reference return — mount point)
            if let Type::Reference(TypeReference { elem, .. }) = &ty {
                let inner = elem.as_ref().clone();
                return ReturnInfo {
                    ty: Some(ty),
                    ok_type: None,
                    err_type: None,
                    some_type: None,
                    is_result: false,
                    is_option: false,
                    is_unit: false,
                    is_stream: false,
                    stream_item: None,
                    is_iterator: false,
                    iterator_item: None,
                    is_reference: true,
                    reference_inner: Some(inner),
                };
            }

            // Regular type
            ReturnInfo {
                ty: Some(ty),
                ok_type: None,
                err_type: None,
                some_type: None,
                is_result: false,
                is_option: false,
                is_unit: false,
                is_stream: false,
                stream_item: None,
                is_iterator: false,
                iterator_item: None,
                is_reference: false,
                reference_inner: None,
            }
        }
    }
}

/// Check if a type is `bool`
pub fn is_bool_type(ty: &Type) -> bool {
    if let Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
        && type_path.path.segments.len() == 1
    {
        return segment.ident == "bool";
    }
    false
}

/// Check if a type is `Vec<T>` and extract T
pub fn extract_vec_type(ty: &Type) -> Option<Type> {
    if let Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
        && segment.ident == "Vec"
        && let PathArguments::AngleBracketed(args) = &segment.arguments
        && let Some(GenericArgument::Type(inner)) = args.args.first()
    {
        return Some(inner.clone());
    }
    None
}

/// Check if a type is `HashMap<K, V>` or `BTreeMap<K, V>` and extract K and V
pub fn extract_map_type(ty: &Type) -> Option<(Type, Type)> {
    if let Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
        && (segment.ident == "HashMap" || segment.ident == "BTreeMap")
        && let PathArguments::AngleBracketed(args) = &segment.arguments
    {
        let mut iter = args.args.iter();
        if let (Some(GenericArgument::Type(key)), Some(GenericArgument::Type(val))) =
            (iter.next(), iter.next())
        {
            return Some((key.clone(), val.clone()));
        }
    }
    None
}

/// Check if a type is `Option<T>` and extract T
pub fn extract_option_type(ty: &Type) -> Option<Type> {
    if let Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
        && segment.ident == "Option"
        && let PathArguments::AngleBracketed(args) = &segment.arguments
        && let Some(GenericArgument::Type(inner)) = args.args.first()
    {
        return Some(inner.clone());
    }
    None
}

/// Check if a type is `Option<T>`
pub fn is_option_type(ty: &Type) -> bool {
    extract_option_type(ty).is_some()
}

/// If `ty` is `Option<T>`, returns `Some(&T)`. Otherwise returns `None`.
pub fn unwrap_option_type(ty: &Type) -> Option<&Type> {
    if let Type::Path(type_path) = ty {
        let seg = type_path.path.segments.last()?;
        if seg.ident != "Option" { return None; }
        if let PathArguments::AngleBracketed(args) = &seg.arguments
            && let Some(GenericArgument::Type(inner)) = args.args.first() {
                return Some(inner);
            }
    }
    None
}

/// If `ty` is `Vec<T>`, returns `Some(&T)`. Otherwise returns `None`.
pub fn unwrap_vec_type(ty: &Type) -> Option<&Type> {
    if let Type::Path(type_path) = ty {
        let seg = type_path.path.segments.last()?;
        if seg.ident != "Vec" { return None; }
        if let PathArguments::AngleBracketed(args) = &seg.arguments
            && let Some(GenericArgument::Type(inner)) = args.args.first() {
                return Some(inner);
            }
    }
    None
}

/// If `ty` is `Result<T, E>`, returns `Some(&T)`. Otherwise returns `None`.
pub fn unwrap_result_ok_type(ty: &Type) -> Option<&Type> {
    if let Type::Path(type_path) = ty {
        let seg = type_path.path.segments.last()?;
        if seg.ident != "Result" { return None; }
        if let PathArguments::AngleBracketed(args) = &seg.arguments
            && let Some(GenericArgument::Type(inner)) = args.args.first() {
                return Some(inner);
            }
    }
    None
}

/// Check if a type is Result<T, E> and extract T and E
pub fn extract_result_types(ty: &Type) -> Option<(Type, Type)> {
    if let Type::Path(type_path) = ty
        && let Some(segment) = type_path.path.segments.last()
        && segment.ident == "Result"
        && let PathArguments::AngleBracketed(args) = &segment.arguments
    {
        let mut iter = args.args.iter();
        if let (Some(GenericArgument::Type(ok)), Some(GenericArgument::Type(err))) =
            (iter.next(), iter.next())
        {
            return Some((ok.clone(), err.clone()));
        }
    }
    None
}

/// Check if a type is impl Stream<Item=T> and extract T
pub fn extract_stream_item(ty: &Type) -> Option<Type> {
    if let Type::ImplTrait(impl_trait) = ty {
        for bound in &impl_trait.bounds {
            if let syn::TypeParamBound::Trait(trait_bound) = bound
                && let Some(segment) = trait_bound.path.segments.last()
                && segment.ident == "Stream"
                && let PathArguments::AngleBracketed(args) = &segment.arguments
            {
                for arg in &args.args {
                    if let GenericArgument::AssocType(assoc) = arg
                        && assoc.ident == "Item"
                    {
                        return Some(assoc.ty.clone());
                    }
                }
            }
        }
    }
    None
}

/// Check if a type is impl Iterator<Item=T> and extract T
pub fn extract_iterator_item(ty: &Type) -> Option<Type> {
    if let Type::ImplTrait(impl_trait) = ty {
        for bound in &impl_trait.bounds {
            if let syn::TypeParamBound::Trait(trait_bound) = bound
                && let Some(segment) = trait_bound.path.segments.last()
                && segment.ident == "Iterator"
                && let PathArguments::AngleBracketed(args) = &segment.arguments
            {
                for arg in &args.args {
                    if let GenericArgument::AssocType(assoc) = arg
                        && assoc.ident == "Item"
                    {
                        return Some(assoc.ty.clone());
                    }
                }
            }
        }
    }
    None
}

/// Check if a type is ()
pub fn is_unit_type(ty: &Type) -> bool {
    if let Type::Tuple(tuple) = ty {
        return tuple.elems.is_empty();
    }
    false
}

/// Check if a parameter name looks like an ID
pub fn is_id_param(name: &Ident) -> bool {
    let name_str = ident_str(name);
    name_str == "id" || name_str.ends_with("_id")
}

/// Extract all methods from an impl block
///
/// Skips:
/// - Private methods (starting with `_`)
/// - Associated functions without `&self` receiver (constructors, etc.)
pub fn extract_methods(impl_block: &ItemImpl) -> syn::Result<Vec<MethodInfo>> {
    let mut methods = Vec::new();

    for item in &impl_block.items {
        if let ImplItem::Fn(method) = item {
            // Skip private methods (those starting with _)
            if method.sig.ident.to_string().starts_with('_') {
                continue;
            }
            // Parse method - returns None for associated functions without self
            if let Some(info) = MethodInfo::parse(method)? {
                methods.push(info);
            }
        }
    }

    Ok(methods)
}

/// Categorized methods for code generation.
///
/// Methods returning `&T` (non-async) are mount points; everything else is a leaf.
/// Mount points are further split by whether they take parameters (slug) or not (static).
pub struct PartitionedMethods<'a> {
    /// Regular leaf methods (no reference return).
    pub leaf: Vec<&'a MethodInfo>,
    /// Static mounts: `fn foo(&self) -> &T` (no params).
    pub static_mounts: Vec<&'a MethodInfo>,
    /// Slug mounts: `fn foo(&self, id: Id) -> &T` (has params).
    pub slug_mounts: Vec<&'a MethodInfo>,
}

/// Partition methods into leaf commands, static mounts, and slug mounts.
///
/// The `skip` predicate allows each protocol to apply its own skip logic
/// (e.g., `#[cli(skip)]`, `#[mcp(skip)]`).
pub fn partition_methods<'a>(
    methods: &'a [MethodInfo],
    skip: impl Fn(&MethodInfo) -> bool,
) -> PartitionedMethods<'a> {
    let mut result = PartitionedMethods {
        leaf: Vec::new(),
        static_mounts: Vec::new(),
        slug_mounts: Vec::new(),
    };

    for method in methods {
        if skip(method) {
            continue;
        }

        if method.return_info.is_reference && !method.is_async {
            if method.params.is_empty() {
                result.static_mounts.push(method);
            } else {
                result.slug_mounts.push(method);
            }
        } else {
            result.leaf.push(method);
        }
    }

    result
}

/// Get the struct name from an impl block
pub fn get_impl_name(impl_block: &ItemImpl) -> syn::Result<Ident> {
    if let Type::Path(type_path) = impl_block.self_ty.as_ref()
        && let Some(segment) = type_path.path.segments.last()
    {
        return Ok(segment.ident.clone());
    }
    Err(syn::Error::new_spanned(
        &impl_block.self_ty,
        "Expected a simple type name",
    ))
}

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

    // ── extract_docs ────────────────────────────────────────────────

    #[test]
    fn extract_docs_returns_none_when_no_doc_attrs() {
        let method: ImplItemFn = syn::parse_quote! {
            fn hello(&self) {}
        };
        assert!(extract_docs(&method.attrs).is_none());
    }

    #[test]
    fn extract_docs_extracts_single_line() {
        let method: ImplItemFn = syn::parse_quote! {
            /// Hello world
            fn hello(&self) {}
        };
        assert_eq!(extract_docs(&method.attrs).unwrap(), "Hello world");
    }

    #[test]
    fn extract_docs_joins_multiple_lines() {
        let method: ImplItemFn = syn::parse_quote! {
            /// Line one
            /// Line two
            fn hello(&self) {}
        };
        assert_eq!(extract_docs(&method.attrs).unwrap(), "Line one\nLine two");
    }

    #[test]
    fn extract_docs_ignores_non_doc_attrs() {
        let method: ImplItemFn = syn::parse_quote! {
            #[inline]
            /// Documented
            fn hello(&self) {}
        };
        assert_eq!(extract_docs(&method.attrs).unwrap(), "Documented");
    }

    // ── parse_return_type ───────────────────────────────────────────

    #[test]
    fn parse_return_type_default_is_unit() {
        let ret: ReturnType = syn::parse_quote! {};
        let info = parse_return_type(&ret);
        assert!(info.is_unit);
        assert!(info.ty.is_none());
        assert!(!info.is_result);
        assert!(!info.is_option);
        assert!(!info.is_reference);
    }

    #[test]
    fn parse_return_type_regular_type() {
        let ret: ReturnType = syn::parse_quote! { -> String };
        let info = parse_return_type(&ret);
        assert!(!info.is_unit);
        assert!(!info.is_result);
        assert!(!info.is_option);
        assert!(!info.is_reference);
        assert!(info.ty.is_some());
    }

    #[test]
    fn parse_return_type_result() {
        let ret: ReturnType = syn::parse_quote! { -> Result<String, MyError> };
        let info = parse_return_type(&ret);
        assert!(info.is_result);
        assert!(!info.is_option);
        assert!(!info.is_unit);

        let ok = info.ok_type.unwrap();
        assert_eq!(quote!(#ok).to_string(), "String");

        let err = info.err_type.unwrap();
        assert_eq!(quote!(#err).to_string(), "MyError");
    }

    #[test]
    fn parse_return_type_option() {
        let ret: ReturnType = syn::parse_quote! { -> Option<i32> };
        let info = parse_return_type(&ret);
        assert!(info.is_option);
        assert!(!info.is_result);
        assert!(!info.is_unit);

        let some = info.some_type.unwrap();
        assert_eq!(quote!(#some).to_string(), "i32");
    }

    #[test]
    fn parse_return_type_unit_tuple() {
        let ret: ReturnType = syn::parse_quote! { -> () };
        let info = parse_return_type(&ret);
        assert!(info.is_unit);
        assert!(info.ty.is_some());
    }

    #[test]
    fn parse_return_type_reference() {
        let ret: ReturnType = syn::parse_quote! { -> &SubRouter };
        let info = parse_return_type(&ret);
        assert!(info.is_reference);
        assert!(!info.is_unit);

        let inner = info.reference_inner.unwrap();
        assert_eq!(quote!(#inner).to_string(), "SubRouter");
    }

    #[test]
    fn parse_return_type_stream() {
        let ret: ReturnType = syn::parse_quote! { -> impl Stream<Item = u64> };
        let info = parse_return_type(&ret);
        assert!(info.is_stream);
        assert!(!info.is_result);

        let item = info.stream_item.unwrap();
        assert_eq!(quote!(#item).to_string(), "u64");
    }

    // ── is_option_type / extract_option_type ────────────────────────

    #[test]
    fn is_option_type_true() {
        let ty: Type = syn::parse_quote! { Option<String> };
        assert!(is_option_type(&ty));
        let inner = extract_option_type(&ty).unwrap();
        assert_eq!(quote!(#inner).to_string(), "String");
    }

    #[test]
    fn is_option_type_false_for_non_option() {
        let ty: Type = syn::parse_quote! { String };
        assert!(!is_option_type(&ty));
        assert!(extract_option_type(&ty).is_none());
    }

    // ── extract_result_types ────────────────────────────────────────

    #[test]
    fn extract_result_types_works() {
        let ty: Type = syn::parse_quote! { Result<Vec<u8>, std::io::Error> };
        let (ok, err) = extract_result_types(&ty).unwrap();
        assert_eq!(quote!(#ok).to_string(), "Vec < u8 >");
        assert_eq!(quote!(#err).to_string(), "std :: io :: Error");
    }

    #[test]
    fn extract_result_types_none_for_non_result() {
        let ty: Type = syn::parse_quote! { Option<i32> };
        assert!(extract_result_types(&ty).is_none());
    }

    // ── is_unit_type ────────────────────────────────────────────────

    #[test]
    fn is_unit_type_true() {
        let ty: Type = syn::parse_quote! { () };
        assert!(is_unit_type(&ty));
    }

    #[test]
    fn is_unit_type_false_for_non_tuple() {
        let ty: Type = syn::parse_quote! { String };
        assert!(!is_unit_type(&ty));
    }

    #[test]
    fn is_unit_type_false_for_nonempty_tuple() {
        let ty: Type = syn::parse_quote! { (i32, i32) };
        assert!(!is_unit_type(&ty));
    }

    // ── is_id_param ─────────────────────────────────────────────────

    #[test]
    fn is_id_param_exact_id() {
        let ident: Ident = syn::parse_quote! { id };
        assert!(is_id_param(&ident));
    }

    #[test]
    fn is_id_param_suffix_id() {
        let ident: Ident = syn::parse_quote! { user_id };
        assert!(is_id_param(&ident));
    }

    #[test]
    fn is_id_param_false_for_other_names() {
        let ident: Ident = syn::parse_quote! { name };
        assert!(!is_id_param(&ident));
    }

    #[test]
    fn is_id_param_false_for_identity() {
        // "identity" ends with "id" but not "_id"
        let ident: Ident = syn::parse_quote! { identity };
        assert!(!is_id_param(&ident));
    }

    // ── MethodInfo::parse ───────────────────────────────────────────

    #[test]
    fn method_info_parse_basic() {
        let method: ImplItemFn = syn::parse_quote! {
            /// Does a thing
            fn greet(&self, name: String) -> String {
                format!("Hello {name}")
            }
        };
        let info = MethodInfo::parse(&method).unwrap().unwrap();
        assert_eq!(info.name.to_string(), "greet");
        assert!(!info.is_async);
        assert_eq!(info.docs.as_deref(), Some("Does a thing"));
        assert_eq!(info.params.len(), 1);
        assert_eq!(info.params[0].name.to_string(), "name");
        assert!(!info.params[0].is_optional);
        assert!(!info.params[0].is_id);
    }

    #[test]
    fn method_info_parse_async_method() {
        let method: ImplItemFn = syn::parse_quote! {
            async fn fetch(&self) -> Vec<u8> {
                vec![]
            }
        };
        let info = MethodInfo::parse(&method).unwrap().unwrap();
        assert!(info.is_async);
    }

    #[test]
    fn method_info_parse_skips_associated_function() {
        let method: ImplItemFn = syn::parse_quote! {
            fn new() -> Self {
                Self
            }
        };
        assert!(MethodInfo::parse(&method).unwrap().is_none());
    }

    #[test]
    fn method_info_parse_optional_param() {
        let method: ImplItemFn = syn::parse_quote! {
            fn search(&self, query: Option<String>) {}
        };
        let info = MethodInfo::parse(&method).unwrap().unwrap();
        assert!(info.params[0].is_optional);
    }

    #[test]
    fn method_info_parse_id_param() {
        let method: ImplItemFn = syn::parse_quote! {
            fn get_user(&self, user_id: u64) -> String {
                String::new()
            }
        };
        let info = MethodInfo::parse(&method).unwrap().unwrap();
        assert!(info.params[0].is_id);
    }

    #[test]
    fn method_info_parse_no_docs() {
        let method: ImplItemFn = syn::parse_quote! {
            fn bare(&self) {}
        };
        let info = MethodInfo::parse(&method).unwrap().unwrap();
        assert!(info.docs.is_none());
    }

    // ── extract_methods ─────────────────────────────────────────────

    #[test]
    fn extract_methods_basic() {
        let impl_block: ItemImpl = syn::parse_quote! {
            impl MyApi {
                fn hello(&self) -> String { String::new() }
                fn world(&self) -> String { String::new() }
            }
        };
        let methods = extract_methods(&impl_block).unwrap();
        assert_eq!(methods.len(), 2);
        assert_eq!(methods[0].name.to_string(), "hello");
        assert_eq!(methods[1].name.to_string(), "world");
    }

    #[test]
    fn extract_methods_skips_underscore_prefix() {
        let impl_block: ItemImpl = syn::parse_quote! {
            impl MyApi {
                fn public(&self) {}
                fn _private(&self) {}
                fn __also_private(&self) {}
            }
        };
        let methods = extract_methods(&impl_block).unwrap();
        assert_eq!(methods.len(), 1);
        assert_eq!(methods[0].name.to_string(), "public");
    }

    #[test]
    fn extract_methods_skips_associated_functions() {
        let impl_block: ItemImpl = syn::parse_quote! {
            impl MyApi {
                fn new() -> Self { Self }
                fn from_config(cfg: Config) -> Self { Self }
                fn greet(&self) -> String { String::new() }
            }
        };
        let methods = extract_methods(&impl_block).unwrap();
        assert_eq!(methods.len(), 1);
        assert_eq!(methods[0].name.to_string(), "greet");
    }

    // ── partition_methods ───────────────────────────────────────────

    #[test]
    fn partition_methods_splits_correctly() {
        let impl_block: ItemImpl = syn::parse_quote! {
            impl Router {
                fn leaf_action(&self) -> String { String::new() }
                fn static_mount(&self) -> &SubRouter { &self.sub }
                fn slug_mount(&self, id: u64) -> &SubRouter { &self.sub }
                async fn async_ref(&self) -> &SubRouter { &self.sub }
            }
        };
        let methods = extract_methods(&impl_block).unwrap();
        let partitioned = partition_methods(&methods, |_| false);

        // leaf_action and async_ref (async reference returns are leaf, not mounts)
        assert_eq!(partitioned.leaf.len(), 2);
        assert_eq!(partitioned.leaf[0].name.to_string(), "leaf_action");
        assert_eq!(partitioned.leaf[1].name.to_string(), "async_ref");

        assert_eq!(partitioned.static_mounts.len(), 1);
        assert_eq!(
            partitioned.static_mounts[0].name.to_string(),
            "static_mount"
        );

        assert_eq!(partitioned.slug_mounts.len(), 1);
        assert_eq!(partitioned.slug_mounts[0].name.to_string(), "slug_mount");
    }

    #[test]
    fn partition_methods_respects_skip() {
        let impl_block: ItemImpl = syn::parse_quote! {
            impl Router {
                fn keep(&self) -> String { String::new() }
                fn skip_me(&self) -> String { String::new() }
            }
        };
        let methods = extract_methods(&impl_block).unwrap();
        let partitioned = partition_methods(&methods, |m| m.name == "skip_me");

        assert_eq!(partitioned.leaf.len(), 1);
        assert_eq!(partitioned.leaf[0].name.to_string(), "keep");
    }

    // ── get_impl_name ───────────────────────────────────────────────

    #[test]
    fn get_impl_name_extracts_struct_name() {
        let impl_block: ItemImpl = syn::parse_quote! {
            impl MyService {
                fn hello(&self) {}
            }
        };
        let name = get_impl_name(&impl_block).unwrap();
        assert_eq!(name.to_string(), "MyService");
    }

    #[test]
    fn get_impl_name_with_generics() {
        let impl_block: ItemImpl = syn::parse_quote! {
            impl MyService<T> {
                fn hello(&self) {}
            }
        };
        let name = get_impl_name(&impl_block).unwrap();
        assert_eq!(name.to_string(), "MyService");
    }

    // ── ident_str ────────────────────────────────────────────────────

    #[test]
    fn ident_str_strips_raw_prefix() {
        let ident: Ident = syn::parse_quote!(r#type);
        assert_eq!(ident_str(&ident), "type");
    }

    #[test]
    fn ident_str_leaves_normal_ident_unchanged() {
        let ident: Ident = syn::parse_quote!(name);
        assert_eq!(ident_str(&ident), "name");
    }

    #[test]
    fn name_str_strips_raw_prefix_on_param() {
        let method: ImplItemFn = syn::parse_quote! {
            fn get(&self, r#type: String) -> String { r#type }
        };
        let info = MethodInfo::parse(&method).unwrap().unwrap();
        assert_eq!(info.params[0].name_str(), "type");
        // The Ident itself still has the raw prefix for code generation
        assert_eq!(info.params[0].name.to_string(), "r#type");
    }

    // ── await-without-async diagnostic ──────────────────────────────

    #[test]
    fn sync_fn_with_top_level_await_is_err() {
        let method: ImplItemFn = syn::parse_quote! {
            fn f(&self) {
                something().await;
            }
        };
        assert!(MethodInfo::parse(&method).is_err());
    }

    #[test]
    fn sync_fn_with_nested_async_block_await_is_ok() {
        let method: ImplItemFn = syn::parse_quote! {
            fn f(&self, x: Thing) {
                let _fut = async { x.await };
            }
        };
        assert!(MethodInfo::parse(&method).is_ok());
    }
}