zlink-macros 0.5.0

Macros providing the high-level zlink API
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
//! Code generation for the service macro.

use std::collections::{HashMap, HashSet};

use proc_macro2::{Ident, TokenStream};
use quote::{ToTokens, format_ident, quote};
use syn::{Error, GenericParam, ItemImpl, Type};

use super::{attrs::ServiceAttrs, method::MethodInfo};
use crate::utils::convert_type_lifetimes;

/// Context for generating the `handle` method body.
struct HandleBodyContext<'a> {
    crate_path: &'a TokenStream,
    method_call_name: &'a Ident,
    user_methods_name: &'a Ident,
    reply_params_name: &'a Ident,
    reply_error_name: &'a Ident,
    reply_stream_params_name: &'a Ident,
    /// The token stream for the resolved `ReplyStreamError` type (either the generated enum or
    /// the [`Infallible`](crate::service::Infallible) sentinel).
    reply_stream_error_ty: &'a TokenStream,
    reply_stream_name: &'a Ident,
    error_type_map: &'a HashMap<String, usize>,
    stream_item_type_map: &'a HashMap<String, Ident>,
    interfaces: &'a [String],
    type_name: &'a str,
    /// Whether streaming methods require boxing (any uses `impl Trait`).
    needs_stream_boxing: bool,
}

/// Extract a simple type name from a Type for generating auxiliary type names.
fn extract_type_name(ty: &Type) -> Option<String> {
    match ty {
        Type::Path(type_path) => type_path
            .path
            .segments
            .last()
            .map(|seg| seg.ident.to_string()),
        _ => None,
    }
}

/// Collect all unique interfaces from methods.
fn collect_interfaces(methods_info: &[MethodInfo]) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut interfaces = Vec::new();
    for method in methods_info {
        if let Some(ref iface) = method.interface {
            if seen.insert(iface.clone()) {
                interfaces.push(iface.clone());
            }
        }
    }
    interfaces
}

/// Generate the Service trait implementation.
pub(super) fn generate_service_impl(
    item_impl: &ItemImpl,
    methods_info: &[MethodInfo],
    service_attrs: &ServiceAttrs,
) -> Result<TokenStream, Error> {
    let crate_path = &service_attrs.crate_path;
    let self_ty = &item_impl.self_ty;

    // Extract the type name for generating auxiliary type names.
    // All generated types use `__` prefix to indicate they are internal implementation details.
    let type_name = extract_type_name(self_ty).unwrap_or_else(|| "Service".to_string());
    let method_call_name = format_ident!("__{}MethodCall", type_name);
    let user_methods_name = format_ident!("__{}UserMethods", type_name);
    let reply_params_name = format_ident!("__{}ReplyParams", type_name);
    let reply_error_name = format_ident!("__{}ReplyError", type_name);
    let reply_stream_params_name = format_ident!("__{}ReplyStreamParams", type_name);
    let reply_stream_error_name = format_ident!("__{}ReplyStreamError", type_name);
    let reply_stream_name = format_ident!("__{}ReplyStream", type_name);

    // Collect interfaces for introspection.
    let interfaces = collect_interfaces(methods_info);

    // Generate the MethodCall enum (outer untagged wrapper + inner user methods).
    let method_call_enum = generate_method_call_enum(
        methods_info,
        &method_call_name,
        &user_methods_name,
        crate_path,
    )?;

    // Generate the Reply enum for parameters.
    let reply_params_enum = generate_reply_params_enum(
        methods_info,
        &method_call_name,
        &reply_params_name,
        crate_path,
    )?;

    // Generate the combo ReplyError enum (always include varlink_service::Error).
    let (reply_error_enum, error_type_map) =
        generate_reply_error_enum(methods_info, &reply_error_name, crate_path);

    // Error type is always the reply error enum (includes varlink_service::Error).
    // The lifetime 'ser is used in the Service trait definition.
    let error_type: syn::Type = syn::parse_quote!(#reply_error_name<'ser>);

    // Generate interface description constants.
    let interface_descriptions = generate_interface_descriptions(
        methods_info,
        service_attrs,
        &interfaces,
        crate_path,
        &type_name,
    )?;

    // Generate the ReplyStreamParams enum for streaming methods.
    let (reply_stream_params_enum, stream_item_type_map) =
        generate_reply_stream_params_enum(methods_info, &reply_stream_params_name);

    // Generate the ReplyStreamError enum (only when at least one streaming method emits errors).
    let (reply_stream_error_enum, stream_error_type_map) =
        generate_reply_stream_error_enum(methods_info, &reply_stream_error_name);
    let reply_stream_error_ty = if stream_error_type_map.is_empty() {
        quote! { #crate_path::service::Infallible }
    } else {
        quote! { #reply_stream_error_name }
    };

    // Check if any streaming method uses `impl Trait` (requires boxing).
    let needs_stream_boxing = methods_info
        .iter()
        .any(|m| m.is_streaming && m.stream_uses_impl_trait);

    // Generate the `handle` method body.
    let handle_body_ctx = HandleBodyContext {
        crate_path,
        method_call_name: &method_call_name,
        user_methods_name: &user_methods_name,
        reply_params_name: &reply_params_name,
        reply_error_name: &reply_error_name,
        reply_stream_params_name: &reply_stream_params_name,
        reply_stream_error_ty: &reply_stream_error_ty,
        reply_stream_name: &reply_stream_name,
        error_type_map: &error_type_map,
        stream_item_type_map: &stream_item_type_map,
        interfaces: &interfaces,
        type_name: &type_name,
        needs_stream_boxing,
    };
    let handle_body = generate_handle_body(methods_info, service_attrs, &handle_body_ctx)?;

    // Extract socket type parameter: use user-provided first type param, or default to __ZlinkSock.
    let (socket_ty, generics, user_where_clause) = item_impl
        .generics
        .params
        .iter()
        .find_map(|p| match p {
            GenericParam::Type(ty) => Some((
                ty.ident.clone(),
                item_impl.generics.clone(),
                item_impl.generics.where_clause.clone(),
            )),
            _ => None,
        })
        .unwrap_or_else(|| {
            let default_ident: Ident = format_ident!("__ZlinkSock");
            let mut generics = syn::Generics::default();
            generics
                .params
                .push(GenericParam::Type(syn::TypeParam::from(
                    default_ident.clone(),
                )));
            (default_ident, generics, None)
        });

    // Build the where clause: always add Socket bound, then user's additional predicates.
    let user_predicates = user_where_clause.map(|w| w.predicates).unwrap_or_default();
    let where_clause = quote! {
        where
            #socket_ty: #crate_path::connection::Socket,
            #user_predicates
    };

    // Check for streaming methods and determine stream types.
    let has_streaming_methods = methods_info.iter().any(|m| m.is_streaming);

    // Generate the ReplyStream type and enum (if using concrete types).
    let (reply_stream_type, reply_stream_params_type, reply_stream_enum) = if has_streaming_methods
    {
        if needs_stream_boxing {
            // Use boxing when any streaming method uses `impl Trait`.
            (
                quote! {
                    ::std::boxed::Box<
                        dyn #crate_path::futures_util::Stream<
                                Item = #crate_path::service::ReplyStreamItem<
                                    #reply_stream_params_name,
                                    #reply_stream_error_ty,
                                >
                            > + ::core::marker::Unpin
                    >
                },
                quote! { #reply_stream_params_name },
                quote! {},
            )
        } else {
            // Generate an enum stream type when all methods return concrete types.
            let reply_stream_enum = generate_reply_stream_enum(
                methods_info,
                &reply_stream_name,
                &reply_stream_params_name,
                &reply_stream_error_ty,
                &stream_item_type_map,
                crate_path,
            );
            (
                quote! { #reply_stream_name },
                quote! { #reply_stream_params_name },
                reply_stream_enum,
            )
        }
    } else {
        // No streaming methods - use empty stream. The error type is `Infallible` (uninhabited)
        // so the `Err` arm of the stream item is statically unreachable.
        (
            quote! {
                #crate_path::futures_util::stream::Empty<
                    #crate_path::service::ReplyStreamItem<
                        (),
                        #crate_path::service::Infallible,
                    >
                >
            },
            quote! { () },
            quote! {},
        )
    };

    // Generate the FDs parameter for the handle method (std only).
    #[cfg(feature = "std")]
    let handle_fds_param = quote! { __zlink_fds: ::std::vec::Vec<::std::os::fd::OwnedFd>, };
    #[cfg(not(feature = "std"))]
    let handle_fds_param = quote! {};

    // Generate the impl block.
    let service_impl = quote! {
        impl #generics #crate_path::Service<#socket_ty> for #self_ty
        #where_clause
        {
            type MethodCall<'de> = #method_call_name<'de>;
            type ReplyParams<'ser> = #reply_params_name<'ser> where Self: 'ser;
            type ReplyStream = #reply_stream_type;
            type ReplyStreamParams = #reply_stream_params_type;
            type ReplyStreamError = #reply_stream_error_ty;
            type ReplyError<'ser> = #error_type where Self: 'ser;

            async fn handle<'__zlink_ser>(
                &'__zlink_ser mut self,
                __zlink_call: &'__zlink_ser #crate_path::Call<Self::MethodCall<'_>>,
                __zlink_conn: &mut #crate_path::Connection<#socket_ty>,
                #handle_fds_param
            ) -> #crate_path::service::HandleResult<
                Self::ReplyParams<'__zlink_ser>,
                Self::ReplyStream,
                Self::ReplyError<'__zlink_ser>,
            > {
                #handle_body
            }
        }
    };

    Ok(quote! {
        #interface_descriptions

        #method_call_enum

        #reply_params_enum

        #reply_stream_params_enum

        #reply_stream_error_enum

        #reply_stream_enum

        #reply_error_enum

        #service_impl
    })
}

/// Generate the MethodCall enum for deserializing incoming calls.
/// This uses an untagged wrapper to combine varlink service methods with user methods.
fn generate_method_call_enum(
    methods_info: &[MethodInfo],
    enum_name: &Ident,
    user_methods_name: &Ident,
    crate_path: &TokenStream,
) -> Result<TokenStream, Error> {
    let variants: Vec<TokenStream> = methods_info
        .iter()
        .filter_map(|method| {
            let full_path = method.full_method_path()?;
            let variant_name = format_ident!("{}", method.varlink_name);

            // Only include serialized params (exclude connection params).
            let serialized_params: Vec<_> = method.serialized_params().collect();

            let fields = if serialized_params.is_empty() {
                quote! {}
            } else {
                let field_defs: Vec<TokenStream> = serialized_params
                    .iter()
                    .map(|param| {
                        let name = &param.name;
                        let converted_ty = convert_type_lifetimes(&param.ty, "'__de");

                        let serde_attr = if let Some(ref renamed) = param.serialized_name {
                            quote! { #[serde(rename = #renamed)] }
                        } else {
                            quote! {}
                        };

                        quote! {
                            #serde_attr
                            #name: #converted_ty
                        }
                    })
                    .collect();

                quote! {
                    { #(#field_defs),* }
                }
            };

            Some(quote! {
                #[serde(rename = #full_path)]
                #variant_name #fields
            })
        })
        .collect();

    let unused_variant = format_ident!("__{}Unused", user_methods_name);
    let unknown_variant = format_ident!("__{}Unknown", user_methods_name);

    // Generate the inner user methods enum.
    let user_methods_enum = if variants.is_empty() {
        quote! {
            #[allow(private_interfaces)]
            #[derive(::core::fmt::Debug, ::serde::Deserialize)]
            #[serde(tag = "method", content = "parameters")]
            pub enum #user_methods_name<'__de> {
                #unused_variant(::core::marker::PhantomData<&'__de ()>),
            }
        }
    } else {
        // Note: #[serde(other)] must be on the last variant.
        quote! {
            #[allow(private_interfaces)]
            #[derive(::core::fmt::Debug, ::serde::Deserialize)]
            #[serde(tag = "method", content = "parameters")]
            pub enum #user_methods_name<'__de> {
                #unused_variant(::core::marker::PhantomData<&'__de ()>),
                #(#variants,)*
                #[serde(other)]
                #unknown_variant,
            }
        }
    };

    // Generate the outer untagged wrapper enum.
    // VarlinkService is tried first (specific matches only), then UserMethods.
    let outer_enum = quote! {
        #[allow(private_interfaces)]
        #[derive(::core::fmt::Debug, ::serde::Deserialize)]
        #[serde(untagged)]
        pub enum #enum_name<'__de> {
            #[serde(borrow)]
            __VarlinkService(#crate_path::varlink_service::Method<'__de>),
            __UserMethods(#user_methods_name<'__de>),
        }
    };

    Ok(quote! {
        #user_methods_enum

        #outer_enum
    })
}

/// Build a mapping from return type string representation to variant index.
/// This ensures consistent variant naming between reply enum generation and handle body.
fn build_return_type_variant_map(methods_info: &[MethodInfo]) -> HashMap<String, usize> {
    let mut type_to_variant: HashMap<String, usize> = HashMap::new();
    let mut variant_idx = 0;

    for method in methods_info {
        let Some(ref return_type) = method.return_type else {
            continue;
        };

        // Use a simple string representation to check for duplicates.
        let type_str = return_type.to_token_stream().to_string();
        if let std::collections::hash_map::Entry::Vacant(e) = type_to_variant.entry(type_str) {
            e.insert(variant_idx);
            variant_idx += 1;
        }
    }

    type_to_variant
}

/// Build a mapping from error type string representation to variant index.
/// This ensures consistent variant naming for the combo error enum.
fn build_error_type_variant_map(methods_info: &[MethodInfo]) -> HashMap<String, usize> {
    let mut type_to_variant: HashMap<String, usize> = HashMap::new();
    let mut variant_idx = 0;

    for method in methods_info {
        let Some(ref error_type) = method.error_type else {
            continue;
        };

        // Use a simple string representation to check for duplicates.
        let type_str = error_type.to_token_stream().to_string();
        if let std::collections::hash_map::Entry::Vacant(e) = type_to_variant.entry(type_str) {
            e.insert(variant_idx);
            variant_idx += 1;
        }
    }

    type_to_variant
}

/// Build a mapping from stream error type string representation to variant index.
/// This ensures consistent variant naming for the stream error enum.
fn build_stream_error_type_variant_map(methods_info: &[MethodInfo]) -> HashMap<String, usize> {
    let mut type_to_variant: HashMap<String, usize> = HashMap::new();
    let mut variant_idx = 0;

    for method in methods_info {
        if !method.is_streaming {
            continue;
        }

        let Some(ref err_type) = method.stream_error_type else {
            continue;
        };

        let type_str = err_type.to_token_stream().to_string();
        if let std::collections::hash_map::Entry::Vacant(e) = type_to_variant.entry(type_str) {
            e.insert(variant_idx);
            variant_idx += 1;
        }
    }

    type_to_variant
}

/// Build a mapping from stream item type string representation to variant name.
/// This ensures consistent variant naming for the stream params enum.
fn build_stream_item_type_variant_map(methods_info: &[MethodInfo]) -> HashMap<String, Ident> {
    let mut type_to_variant: HashMap<String, Ident> = HashMap::new();

    for method in methods_info {
        if !method.is_streaming {
            continue;
        }

        let Some(ref stream_item_type) = method.stream_item_type else {
            continue;
        };

        // Use a simple string representation to check for duplicates.
        let type_str = stream_item_type.to_token_stream().to_string();
        if let std::collections::hash_map::Entry::Vacant(e) = type_to_variant.entry(type_str) {
            // Use the type name as the variant name.
            let variant_name = extract_type_name(stream_item_type)
                .map(|name| format_ident!("{}", name))
                .unwrap_or_else(|| format_ident!("__Unknown"));
            e.insert(variant_name);
        }
    }

    type_to_variant
}

/// Generate the combo ReplyError enum and From impls for each error type.
/// Always includes varlink_service::Error for introspection support.
/// Returns the enum definition, From impls, and the error type map.
fn generate_reply_error_enum(
    methods_info: &[MethodInfo],
    enum_name: &Ident,
    crate_path: &TokenStream,
) -> (TokenStream, HashMap<String, usize>) {
    let error_type_map = build_error_type_variant_map(methods_info);

    // Build variants in order of their indices.
    let mut type_variant_pairs: Vec<_> = error_type_map.iter().collect();
    type_variant_pairs.sort_by_key(|(_, idx)| *idx);

    let mut variants: Vec<TokenStream> = Vec::new();
    let mut from_impls: Vec<TokenStream> = Vec::new();

    for (type_str, idx) in type_variant_pairs {
        // Find the actual error type from methods.
        for method in methods_info {
            let Some(ref error_type) = method.error_type else {
                continue;
            };
            if &error_type.to_token_stream().to_string() == type_str {
                let variant_name = format_ident!("__{}Variant{}", enum_name, idx);
                let converted = convert_type_lifetimes(error_type, "'__ser");
                variants.push(quote! {
                    #variant_name(#converted)
                });

                from_impls.push(quote! {
                    impl<'__ser> ::core::convert::From<#converted> for #enum_name<'__ser> {
                        fn from(e: #converted) -> Self {
                            #enum_name::#variant_name(e)
                        }
                    }
                });
                break;
            }
        }
    }

    // Always add varlink_service::Error variant for introspection.
    let varlink_error_variant = format_ident!("__{}VarlinkService", enum_name);

    let enum_def = quote! {
        #[allow(private_interfaces)]
        #[derive(::core::fmt::Debug, ::serde::Serialize)]
        #[serde(untagged)]
        pub enum #enum_name<'__ser> {
            #varlink_error_variant(#crate_path::varlink_service::Error<'__ser>),
            #(#variants,)*
        }

        impl<'__ser> ::core::convert::From<#crate_path::varlink_service::Error<'__ser>>
            for #enum_name<'__ser>
        {
            fn from(e: #crate_path::varlink_service::Error<'__ser>) -> Self {
                #enum_name::#varlink_error_variant(e)
            }
        }

        #(#from_impls)*
    };

    (enum_def, error_type_map)
}

/// Generate the ReplyStreamError enum for errors emitted as streaming method items.
///
/// Returns the (optional) enum definition and the type map. When no streaming method emits
/// errors, the enum is omitted and `Infallible` is used as the associated type.
fn generate_reply_stream_error_enum(
    methods_info: &[MethodInfo],
    enum_name: &Ident,
) -> (TokenStream, HashMap<String, usize>) {
    let type_map = build_stream_error_type_variant_map(methods_info);

    if type_map.is_empty() {
        return (quote! {}, type_map);
    }

    let mut type_variant_pairs: Vec<_> = type_map.iter().collect();
    type_variant_pairs.sort_by_key(|(_, idx)| *idx);

    let mut variants: Vec<TokenStream> = Vec::new();
    let mut from_impls: Vec<TokenStream> = Vec::new();

    for (type_str, idx) in type_variant_pairs {
        for method in methods_info {
            if !method.is_streaming {
                continue;
            }
            let Some(ref err_type) = method.stream_error_type else {
                continue;
            };
            if &err_type.to_token_stream().to_string() == type_str {
                let variant_name = format_ident!("__{}Variant{}", enum_name, idx);
                variants.push(quote! {
                    #variant_name(#err_type)
                });

                from_impls.push(quote! {
                    impl ::core::convert::From<#err_type> for #enum_name {
                        fn from(e: #err_type) -> Self {
                            #enum_name::#variant_name(e)
                        }
                    }
                });
                break;
            }
        }
    }

    let enum_def = quote! {
        #[allow(private_interfaces)]
        #[derive(::core::fmt::Debug, ::serde::Serialize)]
        #[serde(untagged)]
        pub enum #enum_name {
            #(#variants,)*
        }

        #(#from_impls)*
    };

    (enum_def, type_map)
}

/// Generate the ReplyStreamParams enum for streaming method replies.
/// Returns the enum definition, From impls, and the type map.
fn generate_reply_stream_params_enum(
    methods_info: &[MethodInfo],
    enum_name: &Ident,
) -> (TokenStream, HashMap<String, Ident>) {
    let type_map = build_stream_item_type_variant_map(methods_info);

    let mut variants: Vec<TokenStream> = Vec::new();
    let mut from_impls: Vec<TokenStream> = Vec::new();

    for (type_str, variant_name) in &type_map {
        // Find the actual stream item type from methods.
        for method in methods_info {
            if !method.is_streaming {
                continue;
            }
            let Some(ref item_type) = method.stream_item_type else {
                continue;
            };
            if &item_type.to_token_stream().to_string() == type_str {
                variants.push(quote! {
                    #variant_name(#item_type)
                });

                from_impls.push(quote! {
                    impl ::core::convert::From<#item_type> for #enum_name {
                        fn from(v: #item_type) -> Self {
                            #enum_name::#variant_name(v)
                        }
                    }
                });
                break;
            }
        }
    }

    // If no streaming methods, generate an empty enum with a unit variant.
    if variants.is_empty() {
        let enum_def = quote! {
            #[allow(private_interfaces)]
            #[derive(::core::fmt::Debug, ::serde::Serialize)]
            #[serde(untagged)]
            pub enum #enum_name {
                __Unused(()),
            }
        };
        return (enum_def, type_map);
    }

    let enum_def = quote! {
        #[allow(private_interfaces)]
        #[derive(::core::fmt::Debug, ::serde::Serialize)]
        #[serde(untagged)]
        pub enum #enum_name {
            #(#variants,)*
        }

        #(#from_impls)*
    };

    (enum_def, type_map)
}

/// Generate the ReplyStream enum for concrete stream types (using pin-project-lite).
/// Build the body that maps `__r` (the user stream's item) into the trait's required
/// `Result<Reply<ReplyStreamParams>, ReplyStreamError>` shape.
///
/// Used by both the boxed (`impl Trait`) and concrete-type stream wrappers.
fn build_stream_map_body(
    has_err: bool,
    params_variant: &Ident,
    reply_stream_params_name: &Ident,
    reply_stream_error_ty: &TokenStream,
    crate_path: &TokenStream,
) -> TokenStream {
    let result_ty = quote! {
        ::core::result::Result::<
            #crate_path::Reply<#reply_stream_params_name>,
            #reply_stream_error_ty,
        >
    };
    let wrap_ok = quote! {
        #result_ty::Ok(__rep.map(|__p| #reply_stream_params_name::#params_variant(__p)))
    };
    if has_err {
        quote! {
            match __r {
                ::core::result::Result::Ok(__rep) => { #wrap_ok }
                ::core::result::Result::Err(__err) => {
                    #result_ty::Err(::core::convert::Into::into(__err))
                }
            }
        }
    } else {
        // Alias `__rep` so the `wrap_ok` template above is identical in both arms.
        quote! { { let __rep = __r; #wrap_ok } }
    }
}

/// Build the closure that adapts a stream item from the user's stream into the trait's stream
/// item shape (`ReplyStreamItem<P, E>`).
///
/// On `std`:
///   * `return_fds` → `|(__r, __fds)| (#map_body, __fds)`
///   * otherwise    → `|__r| (#map_body, Vec::new())`
///
/// On `no_std`: `|__r| #map_body` (no FDs).
fn build_stream_item_map_closure(map_body: &TokenStream, return_fds: bool) -> TokenStream {
    #[cfg(feature = "std")]
    {
        let fds_expr = if return_fds {
            quote! { __fds }
        } else {
            quote! { ::std::vec::Vec::new() }
        };
        let arg_pat = if return_fds {
            quote! { (__r, __fds) }
        } else {
            quote! { __r }
        };
        quote! {
            |#arg_pat| {
                let __mapped = #map_body;
                (__mapped, #fds_expr)
            }
        }
    }
    #[cfg(not(feature = "std"))]
    {
        let _ = return_fds;
        quote! { |__r| { #map_body } }
    }
}

/// This avoids boxing when all streaming methods return concrete types.
fn generate_reply_stream_enum(
    methods_info: &[MethodInfo],
    enum_name: &Ident,
    reply_stream_params_name: &Ident,
    reply_stream_error_ty: &TokenStream,
    stream_item_type_map: &HashMap<String, Ident>,
    crate_path: &TokenStream,
) -> TokenStream {
    let projection_name = format_ident!("{}Proj", enum_name);

    // Collect streaming methods with their return types and variant names.
    let streaming_methods: Vec<_> = methods_info
        .iter()
        .filter(|m| m.is_streaming && m.stream_return_type.is_some())
        .collect();

    if streaming_methods.is_empty() {
        return quote! {};
    }

    // Generate enum variants (one per streaming method, using method's varlink name).
    let variants: Vec<TokenStream> = streaming_methods
        .iter()
        .map(|method| {
            let variant_name = format_ident!("{}", method.varlink_name);
            let stream_type = method.stream_return_type.as_ref().unwrap();
            quote! {
                #variant_name { #[pin] stream: #stream_type }
            }
        })
        .collect();

    // Generate poll_next match arms. The user method's stream might yield:
    //   * `Reply<T>`                                       — wrap in `Ok(...)`
    //   * `Result<Reply<T>, E>`                             — convert error via `Into`
    //   * `(Reply<T>, Vec<OwnedFd>)`        (return_fds)    — wrap in `Ok(...)` (with FDs)
    //   * `(Result<Reply<T>, E>, Vec<OwnedFd>)` (return_fds + error)
    //
    // The trait's stream item shape is built by `build_stream_map_body` /
    // `build_stream_item_map_closure`.
    let poll_arms: Vec<TokenStream> = streaming_methods
        .iter()
        .map(|method| {
            let variant_name = format_ident!("{}", method.varlink_name);
            let item_type = method.stream_item_type.as_ref().unwrap();
            let type_str = item_type.to_token_stream().to_string();
            let params_variant = stream_item_type_map
                .get(&type_str)
                .cloned()
                .unwrap_or_else(|| format_ident!("__Unknown"));
            let map_body = build_stream_map_body(
                method.stream_error_type.is_some(),
                &params_variant,
                reply_stream_params_name,
                reply_stream_error_ty,
                crate_path,
            );
            let item_map = build_stream_item_map_closure(&map_body, method.return_fds);
            quote! {
                #projection_name::#variant_name { stream } => {
                    stream.poll_next(cx).map(|__opt| __opt.map(#item_map))
                }
            }
        })
        .collect();

    quote! {
        #crate_path::pin_project_lite::pin_project! {
            #[allow(private_interfaces)]
            #[project = #projection_name]
            pub enum #enum_name {
                #(#variants,)*
            }
        }

        impl #crate_path::futures_util::Stream for #enum_name {
            type Item = #crate_path::service::ReplyStreamItem<
                #reply_stream_params_name,
                #reply_stream_error_ty,
            >;

            fn poll_next(
                self: ::core::pin::Pin<&mut Self>,
                cx: &mut ::core::task::Context<'_>,
            ) -> ::core::task::Poll<::core::option::Option<Self::Item>> {
                match self.project() {
                    #(#poll_arms)*
                }
            }
        }
    }
}

/// Generate the ReplyParams enum for serializing outgoing replies.
fn generate_reply_params_enum(
    methods_info: &[MethodInfo],
    method_call_name: &Ident,
    enum_name: &Ident,
    crate_path: &TokenStream,
) -> Result<TokenStream, Error> {
    // Collect unique return types from methods.
    let mut variants: Vec<TokenStream> = Vec::new();
    let type_to_variant = build_return_type_variant_map(methods_info);

    // Build variants in order of their indices.
    let mut type_variant_pairs: Vec<_> = type_to_variant.iter().collect();
    type_variant_pairs.sort_by_key(|(_, idx)| *idx);

    for (type_str, idx) in type_variant_pairs {
        // Find the actual return type from methods.
        for method in methods_info {
            let Some(ref return_type) = method.return_type else {
                continue;
            };
            if &return_type.to_token_stream().to_string() == type_str {
                let variant_name = format_ident!("__{}Variant{}", method_call_name, idx);
                let converted = convert_type_lifetimes(return_type, "'__ser");
                variants.push(quote! {
                    #variant_name(#converted)
                });
                break;
            }
        }
    }

    let unused_variant = format_ident!("__{}Unused", enum_name);

    // Always add varlink service reply variant for introspection.
    let varlink_reply_variant = format_ident!("__{}VarlinkService", enum_name);

    if variants.is_empty() {
        return Ok(quote! {
            #[allow(private_interfaces)]
            #[derive(::core::fmt::Debug, ::serde::Serialize)]
            #[serde(untagged)]
            pub enum #enum_name<'__ser> {
                #varlink_reply_variant(#crate_path::varlink_service::Reply<'__ser>),
                #unused_variant(::core::marker::PhantomData<&'__ser ()>),
            }
        });
    }

    Ok(quote! {
        #[allow(private_interfaces)]
        #[derive(::core::fmt::Debug, ::serde::Serialize)]
        #[serde(untagged)]
        pub enum #enum_name<'__ser> {
            #varlink_reply_variant(#crate_path::varlink_service::Reply<'__ser>),
            #(#variants,)*
            #unused_variant(::core::marker::PhantomData<&'__ser ()>),
        }
    })
}

/// Generate interface description constants for each interface.
fn generate_interface_descriptions(
    methods_info: &[MethodInfo],
    service_attrs: &ServiceAttrs,
    interfaces: &[String],
    crate_path: &TokenStream,
    type_name: &str,
) -> Result<TokenStream, Error> {
    let mut descriptions: Vec<TokenStream> = Vec::new();

    for interface in interfaces {
        let const_name = format_ident!(
            "__{}_INTERFACE_{}",
            type_name.to_uppercase(),
            interface.replace('.', "_").to_uppercase()
        );

        // Collect methods for this interface.
        let interface_methods: Vec<&MethodInfo> = methods_info
            .iter()
            .filter(|m| m.interface.as_ref() == Some(interface))
            .collect();

        // Generate inner const method definitions.
        // Each method needs its own const to avoid destructor issues.
        let method_consts: Vec<TokenStream> = interface_methods
            .iter()
            .enumerate()
            .map(|(idx, method)| {
                let method_const_name = format_ident!("__METHOD_{}", idx);
                let method_name = &method.varlink_name;

                // Input parameters (excluding connection params).
                let in_params: Vec<TokenStream> = method
                    .serialized_params()
                    .map(|p| {
                        // Strip leading underscores from parameter names for IDL (Rust convention
                        // uses `_name` for unused params, but Varlink IDL doesn't allow that).
                        let default_name = p.name.to_string().trim_start_matches('_').to_string();
                        let param_name = p.serialized_name.as_ref().unwrap_or(&default_name);
                        let ty = convert_type_lifetimes(&p.ty, "'static");
                        quote! {
                            &#crate_path::idl::Parameter::new(
                                #param_name,
                                <#ty as #crate_path::introspect::Type>::TYPE,
                                &[],
                            )
                        }
                    })
                    .collect();

                // Generate a const for this method's in params slice.
                let in_params_const = if in_params.is_empty() {
                    quote! {
                        const __IN_PARAMS: &[&#crate_path::idl::Parameter<'static>] = &[];
                    }
                } else {
                    quote! {
                        const __IN_PARAMS: &[&#crate_path::idl::Parameter<'static>] =
                            &[#(#in_params),*];
                    }
                };

                let out_params_const = if method.is_streaming {
                    method.stream_item_type.clone()
                } else {
                    method.return_type.clone()
                }
                .map(|ty| {
                    if service_attrs.custom_types.contains(&ty) {
                        quote! {
                            const __OUT_PARAMS: &[&#crate_path::idl::Parameter<'static>] =
                                <#ty as #crate_path::introspect::CustomType>::CUSTOM_TYPE
                                    .as_object()
                                    .expect("Return type has to be an object")
                                    .fields_as_slice()
                                    .unwrap();
                        }
                    } else {
                        quote! {
                            const __OUT_PARAMS: &[&#crate_path::idl::Parameter<'static>] =
                                <#ty as #crate_path::introspect::Type>::TYPE
                                    .as_object()
                                    .expect("Return type has to be an object")
                                    .as_borrowed()
                                    .unwrap();
                        }
                    }
                })
                .unwrap_or_else(|| {
                    quote! {
                        const __OUT_PARAMS: &[&#crate_path::idl::Parameter<'static>] = &[];
                    }
                });

                Ok(quote! {
                    const #method_const_name: &#crate_path::idl::Method<'static> = &{
                        #in_params_const
                        #out_params_const
                        #crate_path::idl::Method::new(
                            #method_name,
                            __IN_PARAMS,
                            __OUT_PARAMS,
                            &[],
                        )
                    };
                })
            })
            .collect::<Result<_, Error>>()?;

        // Generate the list of method references.
        let method_refs: Vec<TokenStream> = (0..interface_methods.len())
            .map(|idx| {
                let method_const_name = format_ident!("__METHOD_{}", idx);
                quote! { #method_const_name }
            })
            .collect();

        // Collect custom types for this interface.
        let custom_types: Vec<TokenStream> = service_attrs
            .custom_types
            .iter()
            .map(|ty| {
                quote! {
                    <#ty as #crate_path::introspect::CustomType>::CUSTOM_TYPE
                }
            })
            .collect();

        // Collect error types for this interface, including those raised by streaming method
        // items. Deduplicate using string representation.
        let mut seen_error_types = HashSet::new();
        let error_types: Vec<TokenStream> = methods_info
            .iter()
            .filter(|m| m.interface.as_ref() == Some(interface))
            .flat_map(|m| {
                m.error_type
                    .as_ref()
                    .into_iter()
                    .chain(m.stream_error_type.as_ref())
            })
            .filter(|err_ty| {
                let type_str = err_ty.to_token_stream().to_string();
                seen_error_types.insert(type_str)
            })
            .map(|err_ty| {
                let err_ty = convert_type_lifetimes(err_ty, "'static");
                quote! {
                    <#err_ty as #crate_path::introspect::ReplyError>::VARIANTS
                }
            })
            .collect();

        // Flatten error variants into a single slice.
        let error_variants_expr = if error_types.is_empty() {
            quote! { &[] }
        } else {
            // For simplicity, we collect the first error type's variants.
            // In practice, a service usually has one error type per interface.
            let first_err = &error_types[0];
            quote! { #first_err }
        };

        descriptions.push(quote! {
            #[doc(hidden)]
            const #const_name: &#crate_path::idl::Interface<'static> = &{
                #(#method_consts)*
                #crate_path::idl::Interface::new(
                    #interface,
                    &[#(#method_refs),*],
                    &[#(#custom_types),*],
                    #error_variants_expr,
                    &[],
                )
            };
        });
    }

    Ok(quote! { #(#descriptions)* })
}

/// Wrap a `MethodReply` expression into a `HandleResult` with no file descriptors.
///
/// On std: `(method_reply, Vec::new())`
/// On no_std: `method_reply`
fn wrap_handle_result_no_fds(inner: TokenStream) -> TokenStream {
    #[cfg(feature = "std")]
    {
        quote! {
            {
                let __method_reply = { #inner };
                (__method_reply, ::std::vec::Vec::new())
            }
        }
    }
    #[cfg(not(feature = "std"))]
    {
        inner
    }
}

/// Wrap a `MethodReply` expression into a `HandleResult` with the given file descriptors.
///
/// On std: `(method_reply, fds_expr)`
/// On no_std: `method_reply`
#[cfg(feature = "std")]
fn wrap_handle_result_with_fds(inner: TokenStream, fds_expr: TokenStream) -> TokenStream {
    quote! {
        {
            let __method_reply = { #inner };
            (__method_reply, #fds_expr)
        }
    }
}

/// On no_std, FDs are ignored.
#[cfg(not(feature = "std"))]
fn wrap_handle_result_with_fds(inner: TokenStream, _fds_expr: TokenStream) -> TokenStream {
    inner
}

/// Generate the `handle` method body with match arms.
fn generate_handle_body(
    methods_info: &[MethodInfo],
    service_attrs: &ServiceAttrs,
    ctx: &HandleBodyContext<'_>,
) -> Result<TokenStream, Error> {
    let HandleBodyContext {
        crate_path,
        method_call_name,
        user_methods_name,
        reply_params_name,
        reply_error_name,
        reply_stream_params_name,
        reply_stream_error_ty,
        reply_stream_name,
        error_type_map,
        stream_item_type_map,
        interfaces,
        type_name,
        needs_stream_boxing,
    } = ctx;

    let mut user_match_arms: Vec<TokenStream> = Vec::new();
    let type_to_variant = build_return_type_variant_map(methods_info);

    for method in methods_info {
        let Some(_full_path) = method.full_method_path() else {
            continue;
        };

        let enum_variant_name = format_ident!("{}", method.varlink_name);
        let method_name = &method.name;

        // Only include serialized params in the pattern (exclude connection params).
        let serialized_params: Vec<_> = method.serialized_params().collect();

        // Build the pattern for the match arm.
        let pattern = if serialized_params.is_empty() {
            quote! { #user_methods_name::#enum_variant_name }
        } else {
            let param_names: Vec<_> = serialized_params.iter().map(|p| &p.name).collect();
            quote! { #user_methods_name::#enum_variant_name { #(#param_names),* } }
        };

        // Build the method call expression.
        // For methods with connection params, inline the body (the method isn't in the output
        // impl). For other methods, call the method normally.
        let method_call = if method.has_connection_param() {
            // Inline the method body with variable bindings.
            let body = &method.body;

            // Set up bindings for connection params.
            let conn_bindings: Vec<TokenStream> = method
                .params
                .iter()
                .filter(|p| p.is_connection)
                .map(|p| {
                    let name = &p.name;
                    quote! { let #name = __zlink_conn; }
                })
                .collect();

            // Set up bindings for the `more` param (from call request).
            let more_bindings: Vec<TokenStream> = method
                .params
                .iter()
                .filter(|p| p.is_more)
                .map(|p| {
                    let name = &p.name;
                    quote! { let #name = __zlink_call.more(); }
                })
                .collect();

            // Set up bindings for FD params.
            let fds_bindings: Vec<TokenStream> = method
                .params
                .iter()
                .filter(|p| p.is_fds)
                .map(|p| {
                    let name = &p.name;
                    quote! { let #name = __zlink_fds; }
                })
                .collect();

            // Set up bindings for regular params (clone from pattern match).
            let param_bindings: Vec<TokenStream> = method
                .params
                .iter()
                .filter(|p| !p.is_connection && !p.is_more && !p.is_fds)
                .map(|p| {
                    let name = &p.name;
                    quote! { let #name = ::core::clone::Clone::clone(#name); }
                })
                .collect();

            quote! {
                {
                    #(#conn_bindings)*
                    #(#more_bindings)*
                    #(#fds_bindings)*
                    #(#param_bindings)*
                    async move #body
                }.await
            }
        } else {
            // Build the method call arguments.
            let call_args: Vec<TokenStream> = method
                .params
                .iter()
                .map(|p| {
                    if p.is_more {
                        // `more` param comes from the call request.
                        quote! { __zlink_call.more() }
                    } else if p.is_fds {
                        // FD param gets the incoming FDs.
                        quote! { __zlink_fds }
                    } else {
                        // Clone from the pattern match.
                        let name = &p.name;
                        quote! { ::core::clone::Clone::clone(#name) }
                    }
                })
                .collect();

            quote! { self.#method_name(#(#call_args),*).await }
        };

        // Build the return expression based on method type.
        // Each branch must produce a `HandleResult`, not a raw `MethodReply`.
        let return_expr = if method.is_streaming {
            // Streaming method - wrap the stream to convert items to the enum type.
            // The stream produces Reply<T> items, we map to Reply<ReplyStreamParams>.
            let item_type = method
                .stream_item_type
                .as_ref()
                .expect("streaming method must have stream_item_type");

            // Get the variant name for this stream item type.
            let type_str = item_type.to_token_stream().to_string();
            let stream_variant_name = stream_item_type_map
                .get(&type_str)
                .cloned()
                .unwrap_or_else(|| format_ident!("__Unknown"));

            // Use the method's varlink name for the enum variant.
            let method_variant_name = format_ident!("{}", method.varlink_name);

            let streaming_reply = if *needs_stream_boxing {
                // Use boxing when any streaming method uses `impl Trait`.
                let map_body = build_stream_map_body(
                    method.stream_error_type.is_some(),
                    &stream_variant_name,
                    reply_stream_params_name,
                    reply_stream_error_ty,
                    crate_path,
                );
                let item_map = build_stream_item_map_closure(&map_body, method.return_fds);

                quote! {
                    let __stream = #method_call;
                    let __mapped =
                        #crate_path::futures_util::StreamExt::map(__stream, #item_map);
                    let __boxed: ::std::boxed::Box<
                        dyn #crate_path::futures_util::Stream<
                                Item = #crate_path::service::ReplyStreamItem<
                                    #reply_stream_params_name,
                                    #reply_stream_error_ty,
                                >
                            > + ::core::marker::Unpin
                    > = ::std::boxed::Box::new(__mapped);
                    #crate_path::service::MethodReply::Multi(__boxed)
                }
            } else {
                // Use enum variant when all streaming methods return concrete types.
                quote! {
                    let __stream = #method_call;
                    #crate_path::service::MethodReply::Multi(
                        #reply_stream_name::#method_variant_name { stream: __stream }
                    )
                }
            };
            wrap_handle_result_no_fds(streaming_reply)
        } else if method.return_fds && method.returns_result {
            // return_fds + (Result<T, E>, Vec<OwnedFd>).
            // FDs are available on both Ok and Err arms.
            let error_variant = method.error_type.as_ref().map(|err_ty| {
                let type_str = err_ty.to_token_stream().to_string();
                let variant_idx = error_type_map.get(&type_str).copied().unwrap_or(0);
                format_ident!("__{}Variant{}", reply_error_name, variant_idx)
            });
            let error_convert = if let Some(ref err_variant) = error_variant {
                quote! { #reply_error_name::#err_variant(__err) }
            } else {
                quote! { ::core::convert::From::from(__err) }
            };
            let err_reply = quote! {
                #crate_path::service::MethodReply::Error(#error_convert)
            };
            let err_arm = wrap_handle_result_with_fds(err_reply, quote! { __out_fds });

            if let Some(ref return_type) = method.return_type {
                let type_str = return_type.to_token_stream().to_string();
                let variant_idx = type_to_variant.get(&type_str).copied().unwrap_or(0);
                let reply_variant_name =
                    format_ident!("__{}Variant{}", method_call_name, variant_idx);
                let ok_reply = quote! {
                    #crate_path::service::MethodReply::Single(Some(
                        #reply_params_name::#reply_variant_name(__ok)
                    ))
                };
                let ok_arm = wrap_handle_result_with_fds(ok_reply, quote! { __out_fds });
                quote! {
                    let (__result, __out_fds) = #method_call;
                    match __result {
                        ::core::result::Result::Ok(__ok) => {
                            #ok_arm
                        }
                        ::core::result::Result::Err(__err) => {
                            #err_arm
                        }
                    }
                }
            } else {
                // (Result<(), E>, Vec<OwnedFd>).
                let ok_reply = quote! {
                    #crate_path::service::MethodReply::Single(None)
                };
                let ok_arm = wrap_handle_result_with_fds(ok_reply, quote! { __out_fds });
                quote! {
                    let (__result, __out_fds) = #method_call;
                    match __result {
                        ::core::result::Result::Ok(()) => {
                            #ok_arm
                        }
                        ::core::result::Result::Err(__err) => {
                            #err_arm
                        }
                    }
                }
            }
        } else if method.return_fds {
            // return_fds without Result: (T, Vec<OwnedFd>).
            if let Some(ref return_type) = method.return_type {
                let type_str = return_type.to_token_stream().to_string();
                let variant_idx = type_to_variant.get(&type_str).copied().unwrap_or(0);
                let reply_variant_name =
                    format_ident!("__{}Variant{}", method_call_name, variant_idx);
                let ok_reply = quote! {
                    #crate_path::service::MethodReply::Single(Some(
                        #reply_params_name::#reply_variant_name(__ok)
                    ))
                };
                let ok_arm = wrap_handle_result_with_fds(ok_reply, quote! { __out_fds });
                quote! {
                    let (__ok, __out_fds) = #method_call;
                    #ok_arm
                }
            } else {
                // ((), Vec<OwnedFd>).
                let ok_reply = quote! {
                    #crate_path::service::MethodReply::Single(None)
                };
                let ok_arm = wrap_handle_result_with_fds(ok_reply, quote! { __out_fds });
                quote! {
                    let ((), __out_fds) = #method_call;
                    #ok_arm
                }
            }
        } else if method.returns_result {
            // Method returns Result<T, E>. Get the error variant for this method's error type.
            let error_variant = method.error_type.as_ref().map(|err_ty| {
                let type_str = err_ty.to_token_stream().to_string();
                let variant_idx = error_type_map.get(&type_str).copied().unwrap_or(0);
                format_ident!("__{}Variant{}", reply_error_name, variant_idx)
            });

            if let Some(ref return_type) = method.return_type {
                // Result<T, E> where T is not ().
                let type_str = return_type.to_token_stream().to_string();
                let variant_idx = type_to_variant.get(&type_str).copied().unwrap_or(0);
                let reply_variant_name =
                    format_ident!("__{}Variant{}", method_call_name, variant_idx);
                let error_convert = if let Some(err_variant) = error_variant {
                    quote! { #reply_error_name::#err_variant(__err) }
                } else {
                    quote! { ::core::convert::From::from(__err) }
                };
                wrap_handle_result_no_fds(quote! {
                    match #method_call {
                        ::core::result::Result::Ok(__ok) => {
                            #crate_path::service::MethodReply::Single(Some(
                                #reply_params_name::#reply_variant_name(__ok)
                            ))
                        }
                        ::core::result::Result::Err(__err) => {
                            #crate_path::service::MethodReply::Error(#error_convert)
                        }
                    }
                })
            } else {
                // Result<(), E>.
                let error_convert = if let Some(err_variant) = error_variant {
                    quote! { #reply_error_name::#err_variant(__err) }
                } else {
                    quote! { ::core::convert::From::from(__err) }
                };
                wrap_handle_result_no_fds(quote! {
                    match #method_call {
                        ::core::result::Result::Ok(()) => {
                            #crate_path::service::MethodReply::Single(None)
                        }
                        ::core::result::Result::Err(__err) => {
                            #crate_path::service::MethodReply::Error(#error_convert)
                        }
                    }
                })
            }
        } else if let Some(ref return_type) = method.return_type {
            // Method returns T directly (not a Result).
            let type_str = return_type.to_token_stream().to_string();
            let variant_idx = type_to_variant.get(&type_str).copied().unwrap_or(0);
            let reply_variant_name = format_ident!("__{}Variant{}", method_call_name, variant_idx);
            wrap_handle_result_no_fds(quote! {
                let __result = #method_call;
                #crate_path::service::MethodReply::Single(Some(
                    #reply_params_name::#reply_variant_name(__result)
                ))
            })
        } else {
            // Method has no return type.
            wrap_handle_result_no_fds(quote! {
                let _ = #method_call;
                #crate_path::service::MethodReply::Single(None)
            })
        };

        user_match_arms.push(quote! {
            #pattern => {
                #return_expr
            }
        });
    }

    let unused_variant = format_ident!("__{}Unused", user_methods_name);
    let unknown_variant = format_ident!("__{}Unknown", user_methods_name);
    let varlink_error_variant = format_ident!("__{}VarlinkService", reply_error_name);
    let varlink_reply_variant = format_ident!("__{}VarlinkService", reply_params_name);

    // Add the unused variant arm first (to match enum order).
    user_match_arms.insert(
        0,
        quote! {
            #user_methods_name::#unused_variant(_) => {
                unreachable!("unused variant should never be matched")
            }
        },
    );

    // Add a catch-all arm for unknown methods (returns MethodNotFound error).
    let unknown_method_reply = wrap_handle_result_no_fds(quote! {
        #crate_path::service::MethodReply::Error(
            #reply_error_name::#varlink_error_variant(
                #crate_path::varlink_service::Error::MethodNotFound {
                    method: ::std::borrow::Cow::Borrowed("unknown"),
                }
            )
        )
    });
    user_match_arms.push(quote! {
        #user_methods_name::#unknown_variant => {
            #unknown_method_reply
        }
    });

    // Generate the user methods match.
    let user_methods_match = quote! {
        #method_call_name::__UserMethods(__user_method) => {
            match __user_method {
                #(#user_match_arms)*
            }
        }
    };

    // Generate interface description match arms for GetInterfaceDescription.
    let interface_match_arms: Vec<TokenStream> = interfaces
        .iter()
        .map(|interface| {
            let const_name = format_ident!(
                "__{}_INTERFACE_{}",
                type_name.to_uppercase(),
                interface.replace('.', "_").to_uppercase()
            );
            let desc_reply = wrap_handle_result_no_fds(quote! {
                #crate_path::service::MethodReply::Single(Some(
                    #reply_params_name::#varlink_reply_variant(
                        #crate_path::varlink_service::Reply::InterfaceDescription(desc)
                    )
                ))
            });
            quote! {
                #interface => {
                    let desc =
                        #crate_path::varlink_service::InterfaceDescription::from(#const_name);
                    #desc_reply
                }
            }
        })
        .collect();

    // Build the interfaces list for GetInfo.
    let interfaces_list: Vec<TokenStream> =
        interfaces.iter().map(|iface| quote! { #iface }).collect();

    // Service metadata.
    let vendor = service_attrs
        .vendor
        .as_ref()
        .map(|v| quote! { #v })
        .unwrap_or_else(|| quote! { "" });
    let product = service_attrs
        .product
        .as_ref()
        .map(|v| quote! { #v })
        .unwrap_or_else(|| quote! { "" });
    let version = service_attrs
        .version
        .as_ref()
        .map(|v| quote! { #v })
        .unwrap_or_else(|| quote! { "" });
    let url = service_attrs
        .url
        .as_ref()
        .map(|v| quote! { #v })
        .unwrap_or_else(|| quote! { "" });

    // Generate the varlink service methods match.
    let get_info_reply = wrap_handle_result_no_fds(quote! {
        #crate_path::service::MethodReply::Single(Some(
            #reply_params_name::#varlink_reply_variant(
                #crate_path::varlink_service::Reply::Info(info)
            )
        ))
    });
    let varlink_desc_reply = wrap_handle_result_no_fds(quote! {
        #crate_path::service::MethodReply::Single(Some(
            #reply_params_name::#varlink_reply_variant(
                #crate_path::varlink_service::Reply::InterfaceDescription(desc)
            )
        ))
    });
    let interface_not_found_reply = wrap_handle_result_no_fds(quote! {
        #crate_path::service::MethodReply::Error(
            #reply_error_name::#varlink_error_variant(
                #crate_path::varlink_service::Error::InterfaceNotFound {
                    interface: ::std::borrow::Cow::Borrowed(interface),
                }
            )
        )
    });
    let varlink_service_match = quote! {
        #method_call_name::__VarlinkService(__varlink_method) => {
            match __varlink_method {
                #crate_path::varlink_service::Method::GetInfo => {
                    let info = #crate_path::varlink_service::Info::new(
                        #vendor,
                        #product,
                        #version,
                        #url,
                        ::std::vec![
                            #(#interfaces_list,)*
                            #crate_path::varlink_service::INTERFACE_NAME,
                        ],
                    );
                    #get_info_reply
                }
                #crate_path::varlink_service::Method::GetInterfaceDescription { interface } => {
                    match *interface {
                        #(#interface_match_arms)*
                        #crate_path::varlink_service::INTERFACE_NAME => {
                            let desc =
                                #crate_path::varlink_service::InterfaceDescription::from(
                                    #crate_path::varlink_service::DESCRIPTION
                                );
                            #varlink_desc_reply
                        }
                        _ => {
                            #interface_not_found_reply
                        }
                    }
                }
            }
        }
    };

    // Check if any method uses the connection parameter.
    let uses_connection = methods_info.iter().any(|m| m.has_connection_param());

    let conn_suppression = if uses_connection {
        // Connection is used, no suppression needed.
        quote! {}
    } else {
        // Suppress unused warning when no methods use the connection.
        quote! { let _ = __zlink_conn; }
    };

    Ok(quote! {
        #conn_suppression
        match __zlink_call.method() {
            #varlink_service_match
            #user_methods_match
        }
    })
}