rsbinder-macros 0.12.0

Procedural macros for rsbinder — define Binder interfaces as Rust traits, without .aidl.
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
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
// Copyright 2026 Jeff Kim <hiking90@gmail.com>
// SPDX-License-Identifier: Apache-2.0

//! Define a Binder interface as a Rust trait — no `.aidl`, no `build.rs`.
//!
//! ```ignore
//! use rsbinder::{interface, BinderResult, Strong, Uri};
//!
//! #[interface(descriptor = "com.example.IHello")]
//! pub trait IHello {
//!     fn echo(&self, msg: &str) -> BinderResult<String>;
//!     fn fill(&self, out: &mut Vec<i32>) -> BinderResult<()>;   // `&mut` = out
//!     #[oneway] fn ping(&self) -> BinderResult<()>;
//! }
//!
//! rsbinder::serve(Uri::kernel())?.add("hello", BnHello::new_binder(Impl))?.run()?;
//! let h: Strong<dyn IHello> = rsbinder::connect(Uri::kernel().with_service("hello"))?;
//! ```
//!
//! # Relationship to `.aidl`
//!
//! `.aidl` stays the canonical path (plan 2-17 D3): it is what Android tooling
//! reads, what other languages generate from, and the only path that carries
//! AIDL-only semantics. This macro is for **rsbinder ↔ rsbinder** interfaces,
//! where the wire is private to both ends.
//!
//! It is not a re-implementation. The macro fills the very same
//! [`rsbinder_aidl::render`] structs the AIDL front-end fills and runs the same
//! templates, so a trait here and the equivalent `.aidl` produce **identical**
//! generated code — moving from one to the other never touches a call site.
//! What it cannot express (unions, constants, `@VintfStability`,
//! `@EnforcePermission`, `ParcelableHolder`, generics, nested types) is what
//! needs AIDL semantics; write those in `.aidl`.
//!
//! # What the signature means
//!
//! | Signature | Meaning |
//! |---|---|
//! | `x: i32` — an AIDL scalar, or a bare name that may be an enum (asserted `Copy`) | in argument, by value |
//! | `x: &Cfg`, `x: &str`, `x: &[T]` — every other `in` type borrows | in argument |
//! | `x: &mut T` | **out** argument |
//! | `#[inout] x: &mut T` | written **and** read back |
//! | `#[deprecated]` / `#[deprecated = "…"]` | AIDL's `@deprecated`, on a trait or a method |
//! | `Option<T>` | nullable |
//! | `#[oneway]` on a method | no reply; must return `BinderResult<()>` |
//!
//! `Option<T>` is AIDL's `@nullable`, which AIDL allows only on the types that
//! have a null representation on the wire. A `#[derive(BinderEnum)]` enum is
//! carried as its `repr` scalar and is not one of them: `Option<Mode>` fails to
//! compile inside the generated code, because the enum has no `SerializeOption`
//! — the same shape `.aidl` rejects at the AIDL level. A primitive has no null
//! either, so `Option<i32>` is refused outright, wherever it sits.
//!
//! **AIDL's scalars are a fixed set.** `bool`, `i8` (`byte`), `i32` (`int`),
//! `i64` (`long`), `f32` (`float`), `f64` (`double`) and `u16` (`char`) are the
//! only scalar spellings `.aidl` renders, joined by `u8` as the element of a
//! `byte[]` (`&[u8]`). `byte` is the one type whose spelling moves with the
//! place — `i8` as a scalar, `u8` as an array element — and neither is
//! accepted in the other's place. Any other Rust scalar — `u32`, `u64`, `i16`,
//! `usize`, `u128`, Rust's own `char`, or a `u8` outside an array — is refused
//! wherever it sits, argument, return or `#[derive(Parcelable)]` field: the
//! nearest `.aidl` renders a *different* Rust type, so moving the interface to
//! `.aidl` would break every call site, which is the one thing this macro
//! promises it will not do. `u128` is worse than a mismatch — it writes
//! sixteen bytes no conforming AIDL peer can decode.
//!
//! **Not everything can be an out parameter.** AIDL passes a primitive, a
//! `String`, an enum, an `IBinder` and an interface `in` only, and a
//! `ParcelFileDescriptor` `in` or `inout` (AOSP `GetArgumentAspect`). Each
//! `&mut` in a direction AIDL does not permit is refused — `&mut String` even
//! as `&mut Option<String>`, because `@nullable` does not widen the direction,
//! and a `&mut ParcelFileDescriptor` unless it is `#[inout]` — except for the
//! enum: the macro sees only its name and cannot tell
//! `&mut Mode` from a parcelable's `&mut Config`, which is a legal out
//! parameter. Never take an enum by `&mut`; no `.aidl` can express it. An
//! array of any of these takes every direction.
//!
//! A binder object (`Strong<dyn IFoo>`, `SIBinder`) and a
//! `ParcelFileDescriptor` have no `Default` for the callee to start from, so
//! `.aidl` wraps them in `Option<_>` wherever there is nothing to start from —
//! a `#[derive(Parcelable)]` field and the slots of an array the callee must
//! default. The table below has the exact spelling for every one of those;
//! what matters here is that the `Option` is `.aidl`'s own and not a
//! `@nullable` you wrote, and that an `out` fd array left `None` fails the
//! call with `UNEXPECTED_NULL`, a null having no valid fd encoding. A
//! `ParcelableHolder` is a parcelable field type only and cannot appear in a
//! signature at all.
//!
//! **An out vector is an array, never a `List`.** An out `&mut Vec<T>` is
//! `.aidl`'s `out T[]`, and `&mut Option<Vec<T>>` its `out @nullable T[]`: the
//! proxy sends the caller's current length (null for `None`) and the service
//! starts from a vector pre-sized to it. `.aidl`'s `out List<T>` renders the
//! very same signature but sends no length and starts the service from an
//! empty vector (`None` when `@nullable`), so the two are not wire-compatible.
//! `out List<T>` has no spelling here; it needs `.aidl`.
//!
//! **A `@nullable` array wraps its elements** unless the element is a
//! primitive or an enum, in every direction and at every arity. A
//! non-`@nullable` array wraps them only where the slot starts empty: an `out`
//! array, or a fixed-size parcelable field, of a binder, an interface or a fd.
//! Every cell of the rule is in the table below, which is generated from the
//! rules and checked against them.
//!
//! One cell no table can decide for you. A `#[derive(BinderEnum)]` element
//! counts as a primitive and stays bare; a parcelable element takes an
//! `Option<_>`. The macro sees a name and not which of the two it is, so it
//! accepts either and cannot tell you which is right — spell an enum element
//! bare and a parcelable element `Option<_>`, as `.aidl` renders them.
//!
//! **A `Box` appears in one place only.** `.aidl` boxes a parcelable field
//! that is `@nullable(heap=true)`, or a bare `@nullable` one that closes a
//! reference cycle — `Option<Box<T>>` — and nothing else, so a `Box` anywhere
//! else is refused, including every argument and return: a cycle is judged
//! against the declaration being generated, and an interface is never part of
//! one. Which `.aidl` field that spelling stands for depends on annotations and
//! declarations the macro cannot see, so it accepts it on any parcelable field.
//!
//! **Paths resolve inside the generated module.** The body lands in a
//! `{Trait}_binder` module one level below where the macro was written, and it
//! reaches the surrounding scope through a `use super::*;`. A bare name is
//! therefore the user's own — but `super::X` names the module the macro was
//! written in, not its parent, so a signature that means the parent has to say
//! `crate::X`. `self::` is rejected outright for the same reason; `super::` is
//! left legal because it is the only way to name a type the generated module
//! shadows (`BnFoo`, `BpFoo`, `transactions`, the trait's own name). Use the
//! macro at module scope: inside a function body `super::*` skips the block,
//! so items declared in that block are not visible to the signature.
//!
//! The generated body names prelude items by absolute path, so a parent item
//! called `Ok`, `Option` or `Default` reaches only the signatures that name
//! it. Two names still resolve in the module: `Box`, which `async-trait`'s
//! expansion uses bare under the `async` feature, and the owned `String` /
//! `Vec<T>` the stub declares for a `&str` / `&[T]` argument. The `async` half
//! declares its own type parameters and helper struct next to the signatures,
//! all named with the `__Rsb` prefix, so the macro refuses a trait name that
//! starts with it and a signature path whose first segment does (`crate::…`
//! still reaches such an item). A parent item named `rsbinder` takes over the
//! generated code's `rsbinder::` paths; the last paragraph of
//! [What it emits](#what-it-emits) says why.
//!
//! **Spell types directly.** A proc macro cannot see through a type alias or
//! a `use … as` rename, and every check above reads the spelling. `&mut Ids`
//! for `type Ids = Vec<i32>` reads as an opaque named type: it loses the
//! length word `.aidl` writes for an out array (`T[]`), and an aliased
//! `ParcelFileDescriptor` element loses the null guard that keeps a null fd
//! off the wire. Likewise a renamed `ParcelableHolder` or an alias of
//! `Option<i32>` slips past the check that refuses it and generates the code
//! that check exists to prevent, and a renamed `Strong` or
//! `ParcelFileDescriptor` escapes the out-parameter rule above. Path
//! qualification is fine — `std::vec::Vec<i32>` is matched structurally — but
//! an alias or a rename is not.
//!
//! A doc comment on the trait or a method is accepted but not carried: the
//! render layer has no doc field, so the emitted `IFoo`, its methods and
//! `BnFoo`/`BpFoo` carry no rustdoc from here.
//!
//! # What it emits
//!
//! The generated items — the trait, `BnFoo`, `BpFoo`, `IFooDefault`, and with
//! the `async` feature the `IFooAsync` halves — land in the module where the
//! macro was written, so they are usable without a path. They physically live
//! in a `#[doc(hidden)] mod {Trait}_binder` that is glob re-exported: the
//! generated body reuses `.aidl`'s fixed internal names (`transactions`,
//! `on_transact`, `DEFAULT_IMPL`), which would collide if two interfaces were
//! emitted side by side. That module is an implementation detail — never name
//! it. `IFoo` and `Foo` both name their halves `BnFoo`/`BpFoo` (AOSP
//! `ClassName`), so one module holds at most one of them: a second fails with
//! E0428 on `__rsbinder_one_interface_per_stem_Foo`. Put them in separate
//! modules.
//!
//! Transaction codes are assigned by declaration order
//! (`FIRST_CALL_TRANSACTION + i`), exactly as `.aidl` does without explicit
//! codes — so **reordering methods is a wire break**. The descriptor defaults
//! to the bare trait name; pass `descriptor = "…"` for anything shared across
//! crates.
//!
//! The generated code names `rsbinder::` directly, so the dependency has to
//! keep that name — a `package = "rsbinder"` rename will not resolve. The
//! path is relative, not `::rsbinder::`: the generated module glob-imports the
//! module the macro was written in, so a `mod rsbinder` or `use … as rsbinder`
//! there is what every generated `rsbinder::` path resolves to.

// Generated; `type_matrix::the_reference_table_matches_the_rules` fails when it falls behind.
#![doc = include_str!("../TYPES.md")]
// Library code returns errors; tests may unwrap (plan 13).
#![cfg_attr(not(test), deny(clippy::unwrap_used))]
// Every allow outside tests says why (plan 13-1).
#![cfg_attr(not(test), deny(clippy::allow_attributes_without_reason))]

use proc_macro::TokenStream;
use quote::quote;
use rsbinder_aidl::render::{render_interface, FnMembers, InterfaceRender, TransactionWrite};
use syn::{
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    FnArg, ItemTrait, Pat, PathArguments, ReturnType, Token, TraitItem, TraitItemFn, Type,
};

mod aidl_shape;
mod binder_enum;
mod parcelable;
mod service_error;
#[cfg(test)]
mod type_matrix;
mod type_str;

/// Argument direction, read off the Rust signature.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Dir {
    In,
    Out,
    Inout,
}

/// `#[interface(descriptor = "…")]`.
struct Args {
    descriptor: Option<String>,
}

impl Parse for Args {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut descriptor = None;
        if input.is_empty() {
            return Ok(Self { descriptor });
        }
        let metas = Punctuated::<syn::MetaNameValue, Token![,]>::parse_terminated(input)?;
        for meta in metas {
            if meta.path.is_ident("descriptor") {
                if descriptor.is_some() {
                    return Err(syn::Error::new_spanned(
                        &meta.path,
                        "`descriptor` is given more than once",
                    ));
                }
                let syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Str(s),
                    ..
                }) = &meta.value
                else {
                    return Err(syn::Error::new_spanned(
                        &meta.value,
                        "descriptor must be a string literal",
                    ));
                };
                // Spliced unescaped into a generated literal; `.aidl`'s grammar never admits these.
                let value = s.value();
                if let Some(bad) = value.chars().find(|c| "\\\"\n\r".contains(*c)) {
                    return Err(syn::Error::new_spanned(
                        s,
                        format!(
                            "a descriptor cannot contain {bad:?} — it is written verbatim \
                             into the generated source and onto the wire"
                        ),
                    ));
                }
                // Shared by `#[interface]` and `#[parcelable]`: the name a peer compares.
                if value.is_empty() {
                    return Err(syn::Error::new_spanned(
                        s,
                        "a descriptor cannot be empty — it is the wire name a peer compares, \
                         and `.aidl` always has a name to put there",
                    ));
                }
                descriptor = Some(value);
            } else {
                return Err(syn::Error::new_spanned(
                    &meta.path,
                    "unknown argument; only `descriptor = \"…\"` is supported",
                ));
            }
        }
        Ok(Self { descriptor })
    }
}

/// `#[<name>(descriptor = "…")]` on a derive input.
fn attr_descriptor(attrs: &[syn::Attribute], name: &str) -> syn::Result<Option<String>> {
    let mut found = None;
    for attr in attrs {
        if !attr.path().is_ident(name) {
            continue;
        }
        let args: Args = attr.parse_args()?;
        if args.descriptor.is_some() {
            if found.is_some() {
                return Err(syn::Error::new_spanned(
                    attr,
                    format!("`descriptor` is given more than once; #[{name}(..)] appears twice"),
                ));
            }
            found = args.descriptor;
        }
    }
    Ok(found)
}

/// Parcel codec for a plain Rust struct — the `.aidl`-free `parcelable`.
///
/// Fields are the wire, in declaration order, so **reordering or inserting a
/// field is a wire break**. The emitted `write_to_parcel` / `read_from_parcel`
/// are the same ones `rsbinder-aidl` emits for the equivalent `parcelable`,
/// including the size-prefixed header and the truncated-read handling that
/// lets an older reader accept a newer writer's extra fields.
///
/// Only the codec is generated, so `Debug`, `Clone` and friends stay yours to
/// derive — but **`Default` is required**: reading a parcelable that arrives
/// as `null` builds one from it. `#[derive(Parcelable, Default, Debug)]` is
/// the normal shape. The descriptor defaults to the type name and is
/// overridden with `#[parcelable(descriptor = "…")]`. `#[deprecated]` and
/// `#[deprecated = "…"]` carry through as AIDL's `@deprecated`, on the struct
/// and on a field alike; the richer Rust forms carry fields `.aidl` has
/// nowhere to put and are refused.
///
/// Fields must be named and owned — owned all the way down, so `Option<&str>`
/// and `Vec<&str>` are out too. A field passes the very same type gates a
/// signature does, reached through one entry point rather than a second copy,
/// so the crate-level docs' scalar set (`u128` and friends refused, `byte`
/// spelled `i8` as a scalar and `u8` as an array element), the array-element
/// rules and the refusal of `()` all apply here — answered for a field, which
/// has no direction of its own. A nullable primitive (`Option<i32>`) is
/// refused for the same reason the interface path refuses it: `.aidl` has no
/// `@nullable int`. A `ParcelableHolder` field is an `.aidl`-only shape. A
/// binder or fd field (`Strong<dyn IFoo>`, `SIBinder`,
/// `ParcelFileDescriptor`) has to be spelled `Option<_>`: the field has no
/// value to start from, so `.aidl` renders it that way whether or not it is
/// `@nullable`, and the bare spelling is refused. Here that `Option<_>` is
/// AIDL's `@nullable`, even though `.aidl` spells the non-nullable field the
/// same way.
///
/// These checks read the field's spelling — a proc macro cannot see through a
/// type alias or a `use … as` rename. A `ParcelableHolder` imported under
/// another name, or a `type MaybeInt = Option<i32>`, is not caught and
/// compiles into the very codec the check exists to refuse; spell them
/// directly.
#[proc_macro_derive(Parcelable, attributes(parcelable))]
pub fn derive_parcelable(item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::DeriveInput);
    match parcelable::expand(&input) {
        Ok(ts) => ts.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// Parcel codec for a plain Rust enum, carried as its `#[repr(..)]` scalar.
///
/// `#[repr(i8)]`, `#[repr(i32)]` or `#[repr(i64)]` is required — it is the
/// wire format (AIDL `byte`, `int`, `long`) — and every variant needs an
/// explicit value, so what goes on the wire is visible at the declaration
/// instead of implied by declaration order.
///
/// ```ignore
/// #[derive(BinderEnum, Clone, Copy, PartialEq, Eq, Debug)]
/// #[repr(i32)]
/// pub enum Mode { Fast = 0, Safe = 1 }
/// ```
///
/// Nothing beyond the `repr` is required of the type — the codec matches on
/// the variant rather than casting through a shared reference.
///
/// The enum is not nullable: `Option<Mode>` has no wire form here, matching
/// `.aidl`, where `@nullable` on an enum is rejected outright.
///
/// **This enum is closed.** A value no variant declares deserializes to
/// `rsbinder::StatusCode::BadValue`. An `.aidl` enum is open: its generated
/// newtype keeps whatever a newer peer sent, so a reader can pass an unknown
/// value along untouched. Use `.aidl` — or `rsbinder::declare_binder_enum!`,
/// which emits exactly that newtype — when the two ends may be different
/// versions. Within one build of both ends, a real Rust enum is the better
/// type: it matches exhaustively and cannot hold a value you never defined.
#[proc_macro_derive(BinderEnum)]
pub fn derive_binder_enum(item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::DeriveInput);
    match binder_enum::expand(&input) {
        Ok(ts) => ts.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// Binder service-specific error codes for a plain Rust enum.
///
/// Implements `rsbinder::ServiceSpecificError`, so the type can be passed to
/// `Status::service_specific` and read back with
/// `Status::service_error::<T>()` instead of a bare `i32`.
///
/// ```ignore
/// #[derive(ServiceSpecificError, Clone, Copy, PartialEq, Eq, Debug)]
/// #[repr(i32)]
/// pub enum LookupError { NotFound = 1, Busy = 2 }
///
/// Err(Status::service_specific(LookupError::Busy, Some("try again")))
/// ```
///
/// `#[repr(i8)]`, `#[repr(i16)]` or `#[repr(i32)]` is required, and every
/// variant needs an explicit value — it is the number a peer matches on, so
/// it belongs at the declaration rather than in declaration order. A wider
/// repr is refused here rather than truncated on the wire, where a binder
/// status carries the code as an `i32`.
///
/// This derive does not touch the parcel: an error code travels in the
/// status header, not as a value in the payload. Combine it with
/// `#[derive(BinderEnum)]` when the same enum is also a method argument or
/// return value.
///
/// For an `.aidl` enum, use `rsbinder::impl_service_specific_error!` instead
/// — the generated type is an open newtype, not a Rust enum, so a derive
/// cannot be attached to it. Never both on one type: two impls of one trait
/// do not compile.
#[proc_macro_derive(ServiceSpecificError)]
pub fn derive_service_specific_error(item: TokenStream) -> TokenStream {
    let input = syn::parse_macro_input!(item as syn::DeriveInput);
    match service_error::expand(&input) {
        Ok(ts) => ts.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

/// A binder interface from a plain Rust trait — the `.aidl`-free `interface`.
///
/// Emits what `rsbinder-aidl` emits for the equivalent `.aidl` interface: the
/// trait, `BnFoo`, `BpFoo` and `IFooDefault` (and the async halves with the
/// `async` feature). Transaction codes follow declaration order, so
/// **reordering methods is a wire break**. The descriptor defaults to the
/// trait name; pass `#[interface(descriptor = "…")]` for anything shared
/// across crates.
///
/// ```ignore
/// #[rsbinder::interface(descriptor = "my.pkg.IHello")]
/// pub trait IHello {
///     fn echo(&self, msg: &str) -> rsbinder::BinderResult<String>;
/// }
/// ```
///
/// Each signature must be the spelling `.aidl` renders for its type and
/// direction, and anything else is refused with that spelling named. The
/// full contract — directions, `#[oneway]`, `#[inout]`, the
/// type table and what the macro cannot express — is the
/// [crate documentation](https://docs.rs/rsbinder-macros).
#[proc_macro_attribute]
pub fn interface(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = syn::parse_macro_input!(attr as Args);
    let item_trait = syn::parse_macro_input!(item as ItemTrait);
    match expand(&args, &item_trait) {
        Ok(ts) => ts.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

fn expand(args: &Args, item: &ItemTrait) -> syn::Result<proc_macro2::TokenStream> {
    let rendered = render_source(args, item)?;

    let file = syn::parse_file(&rendered).map_err(|e| {
        syn::Error::new_spanned(
            &item.ident,
            format!("generated code did not parse ({e}); generated source follows:\n{rendered}"),
        )
    })?;
    let mut items = file.items.into_iter();
    let (Some(syn::Item::Mod(mut module)), None) = (items.next(), items.next()) else {
        return Err(syn::Error::new_spanned(
            &item.ident,
            "generated code was not a single module (generator contract changed)",
        ));
    };

    // Renamed: a module named like the trait would shadow the trait's glob re-export.
    let raw_name = item.ident.to_string();
    let mod_ident = syn::Ident::new(
        &format!("{}_binder", strip_raw(&raw_name)),
        item.ident.span(),
    );
    module.ident = mod_ident.clone();
    // A `pub` module would make a private trait nameable from outside.
    module.vis = item.vis.clone();

    // The proxy passes a by-value argument twice, so assert `Copy` where the body resolves it.
    let copied = by_value_types(item)?;
    if let Some((_, items)) = module.content.as_mut() {
        items.insert(
            0,
            syn::parse_quote!(
                use super::*;
            ),
        );
        for ty in &copied {
            items.push(syn::parse_quote!(
                const _: fn() = || {
                    fn __rsbinder_assert_copy<T: ::core::marker::Copy>() {}
                    __rsbinder_assert_copy::<#ty>();
                };
            ));
        }
    }

    // `IFoo` and `Foo` both glob-export `BnFoo`; this turns the later E0659 into E0428 here.
    let marker = syn::Ident::new(
        &format!(
            "__rsbinder_one_interface_per_stem_{}",
            rsbinder_aidl::render::interface_stem(strip_raw(&raw_name))
        ),
        item.ident.span(),
    );

    let vis = &item.vis;
    Ok(quote! {
        #[doc(hidden)]
        #module
        #vis use #mod_ident::*;
        #[doc(hidden)]
        #[allow(dead_code, non_upper_case_globals)]
        const #marker: () = ();
    })
}

/// `Ident`'s `Display` keeps the `r#`, and the templates add their own.
pub(crate) fn strip_raw(ident: &str) -> &str {
    ident.strip_prefix("r#").unwrap_or(ident)
}

/// The generated module source, split out for the golden test (plan 2-19 D1).
fn render_source(args: &Args, item: &ItemTrait) -> syn::Result<String> {
    render_source_with(args, item, cfg!(feature = "async"))
}

fn render_source_with(args: &Args, item: &ItemTrait, enabled_async: bool) -> syn::Result<String> {
    // A trait-level `#[cfg]` or `#[oneway]` would vanish in the re-render.
    check_attrs(&item.attrs, &["deprecated"])?;
    // The render layer carries no trait modifier, so an accepted one would vanish.
    if let Some(unsafety) = &item.unsafety {
        return Err(syn::Error::new_spanned(
            unsafety,
            "an `unsafe` binder interface is not supported — the generated trait is safe, \
             so the obligation would be silently dropped",
        ));
    }
    if let Some(auto_token) = &item.modifiers.auto_token {
        return Err(syn::Error::new_spanned(
            auto_token,
            "an `auto` trait carries no methods and cannot be a binder interface",
        ));
    }
    // `#[non_exhaustive]`: a modifier a later `syn` adds is refused instead of dropped.
    item.modifiers.require_empty()?;
    if let Some(where_clause) = &item.generics.where_clause {
        return Err(syn::Error::new_spanned(
            where_clause,
            "a where clause has no meaning on a binder interface — the generated trait \
             requires only `rsbinder::Interface + Send`",
        ));
    }
    if !item.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &item.generics,
            "a binder interface cannot be generic — the wire has no way to carry the parameter",
        ));
    }
    if !item.supertraits.is_empty() {
        return Err(syn::Error::new_spanned(
            &item.supertraits,
            "supertraits are not supported; the generated trait already requires \
             `rsbinder::Interface + Send`",
        ));
    }

    type_str::reject_reserved_ident(&item.ident)?;

    let raw = item.ident.to_string();
    let name = strip_raw(&raw).to_string();
    let mut fn_members = Vec::new();
    // `r#type` and `type` are one name.
    let mut seen = std::collections::HashSet::new();
    for (i, trait_item) in item.items.iter().enumerate() {
        let TraitItem::Fn(f) = trait_item else {
            return Err(syn::Error::new_spanned(
                trait_item,
                "only methods are supported; constants and associated types need `.aidl`",
            ));
        };
        let ident = f.sig.ident.to_string();
        if !seen.insert(strip_raw(&ident).to_string()) {
            return Err(syn::Error::new_spanned(
                &f.sig.ident,
                format!("duplicate method name `{}`", strip_raw(&ident)),
            ));
        }
        // The `.aidl` path refuses the same names (`rsbinder-aidl` `Generator::decl_interface`).
        let bare = strip_raw(&ident);
        if matches!(
            bare,
            "descriptor" | "getDefaultImpl" | "setDefaultImpl" | "dump" | "as_binder"
        ) {
            return Err(syn::Error::new_spanned(
                &f.sig.ident,
                format!("method `{bare}` collides with an item of the generated Rust trait"),
            ));
        }
        // AOSP `AidlInterface::CheckValid` `reserved_methods`, matched by signature.
        let args: Vec<&Type> = f
            .sig
            .inputs
            .iter()
            .filter_map(|a| match a {
                FnArg::Typed(t) => Some(&*t.ty),
                FnArg::Receiver(_) => None,
            })
            .collect();
        let reserved = match (bare, args.as_slice()) {
            ("asBinder" | "getInterfaceHash" | "getInterfaceVersion", []) => true,
            ("getTransactionName", [ty]) => matches!(
                type_str::unwrap_group(ty),
                Type::Path(p) if p.qself.is_none()
                    && p.path.segments.last().is_some_and(|s| s.ident == "i32" && s.arguments.is_none())
            ),
            _ => false,
        };
        if reserved {
            return Err(syn::Error::new_spanned(
                &f.sig.ident,
                format!("method `{bare}` is reserved for internal use"),
            ));
        }
        fn_members.push(make_fn_member(f, i as u32)?);
    }

    let descriptor = args.descriptor.clone().unwrap_or_else(|| name.clone());
    let mut render = InterfaceRender::new(name, descriptor);
    render.fn_members = fn_members;
    render.enabled_async = enabled_async;
    render.deprecated = deprecated_of(&item.attrs)?;

    render_interface(&render)
        .map(|s| s.trim().to_string())
        .map_err(|e| syn::Error::new_spanned(&item.ident, format!("codegen failed: {e}")))
}

fn make_fn_member(f: &TraitItemFn, index: u32) -> syn::Result<FnMembers> {
    // `#[non_exhaustive]`, like the trait's: the re-render carries none of them.
    f.modifiers.require_empty()?;
    if f.default.is_some() {
        return Err(syn::Error::new_spanned(
            &f.sig.ident,
            "a default body has no meaning on a binder interface — the server `impl` provides it",
        ));
    }
    if !f.sig.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &f.sig.generics,
            "generic methods are not supported",
        ));
    }
    if let Some(where_clause) = &f.sig.generics.where_clause {
        return Err(syn::Error::new_spanned(
            where_clause,
            "a where clause on a binder method is not supported",
        ));
    }
    // The re-render drops these, so the user's `impl` would miss its own signature.
    if let Some(tok) = &f.sig.asyncness {
        return Err(syn::Error::new_spanned(
            tok,
            "declare the method as sync; the `async` feature emits the `IFooAsync` halves \
             alongside it",
        ));
    }
    // `Safety::Safe` parses only inside an `extern` block.
    if !matches!(f.sig.safety, syn::Safety::Default) {
        return Err(syn::Error::new_spanned(
            &f.sig.safety,
            "an `unsafe` binder method is not supported",
        ));
    }
    if let Some(tok) = &f.sig.constness {
        return Err(syn::Error::new_spanned(
            tok,
            "a `const` binder method is not supported",
        ));
    }
    if let Some(abi) = &f.sig.abi {
        return Err(syn::Error::new_spanned(
            abi,
            "an explicit ABI has no meaning on a binder method",
        ));
    }
    // `syn` parses `...` even outside an `extern` block; the render layer would drop it.
    if let Some(variadic) = &f.sig.variadic {
        return Err(syn::Error::new_spanned(
            variadic,
            "a variadic binder method is not supported — the wire carries a fixed \
             argument list",
        ));
    }
    let oneway = has_attr(&f.attrs, "oneway");
    check_attrs(&f.attrs, &["oneway", "deprecated"])?;

    const SHARED_RECEIVER: &str = "the first parameter must be `&self` — a binder object is \
                                   shared, never owned or uniquely borrowed by a call";

    let mut inputs = f.sig.inputs.iter();
    let Some(FnArg::Receiver(receiver)) = inputs.next() else {
        return Err(syn::Error::new_spanned(&f.sig, SHARED_RECEIVER));
    };
    let syn::ReceiverKind::Reference(_, lifetime, None) = &receiver.kind else {
        return Err(syn::Error::new_spanned(&f.sig, SHARED_RECEIVER));
    };
    // `&'_ self` is `&self`; a named one would be dropped by the re-render.
    if let Some(lifetime) = lifetime.as_ref().filter(|lt| lt.ident != "_") {
        return Err(syn::Error::new_spanned(
            lifetime,
            "an explicit lifetime on `self` is not supported — the generated trait takes a \
             plain `&self`",
        ));
    }
    check_attrs(&receiver.attrs, &[])?;

    let mut args = "&self".to_string();
    let mut args_async = "&'a self".to_string();
    let mut func_call_params = String::new();
    let mut write_funcs = Vec::new();
    let mut transaction_decls = Vec::new();
    let mut transaction_write = Vec::new();
    let mut transaction_params = String::new();
    let mut read_onto_params = Vec::new();
    let mut arg_names = std::collections::HashSet::new();

    for input in inputs {
        let FnArg::Typed(pat_ty) = input else {
            return Err(syn::Error::new_spanned(input, "unexpected receiver"));
        };
        let Pat::Ident(pat_ident) = &*pat_ty.pat else {
            return Err(syn::Error::new_spanned(
                &pat_ty.pat,
                "parameter patterns are not supported; use a plain name",
            ));
        };
        // `rsbinder-aidl`'s `_arg_` prefix; trait parameter names do not bind the `impl`.
        check_attrs(&pat_ty.attrs, &["inout"])?;
        let raw_arg = pat_ident.ident.to_string();
        let ident = format!("_arg_{}", strip_raw(&raw_arg));
        // AOSP `AidlMethod::CheckValid`; else E0415 lands on generated tokens.
        if !arg_names.insert(ident.clone()) {
            return Err(syn::Error::new_spanned(
                &pat_ident.ident,
                format!("duplicate argument name `{}`", strip_raw(&raw_arg)),
            ));
        }
        let dir = direction(&pat_ty.attrs, &pat_ty.ty)?;
        if oneway && dir != Dir::In {
            return Err(syn::Error::new_spanned(
                &pat_ty.ty,
                "a #[oneway] method cannot have an out/inout parameter — there is no reply to \
                 write it back into",
            ));
        }
        type_str::check_type_at(
            &pat_ty.ty,
            match dir {
                Dir::In => type_str::Place::In,
                Dir::Out => type_str::Place::Out,
                Dir::Inout => type_str::Place::Inout,
            },
        )?;
        type_str::reject_reserved_names(&pat_ty.ty)?;
        let as_written = type_str::as_written(&pat_ty.ty)?;
        let owned = type_str::owned(&pat_ty.ty)?;

        let arg_str = format!(", {ident}: {as_written}");
        args += &arg_str;
        args_async += &arg_str.replace('&', "&'a ");
        func_call_params += &format!("{ident}, ");

        // Structural, not string: `std::vec::Vec<T>` carries the same length word as `Vec<T>`.
        let is_option_vec = type_str::option_vec_elem(&pat_ty.ty).is_some();
        let is_var_array = type_str::is_variable_array(&pat_ty.ty);
        if dir != Dir::Out {
            let param = if as_written.starts_with('&') {
                ident.clone()
            } else {
                format!("&{ident}")
            };
            write_funcs.push(format!("data.write({param})?;"));
        } else if is_option_vec {
            write_funcs.push(format!("data.write_slice_size({ident}.as_deref())?;"));
        } else if is_var_array {
            // Only the length is sent; the server sizes from it (AOSP `resizeOutVector`).
            write_funcs.push(format!(
                "data.write_slice_size(::core::option::Option::Some({ident}))?;"
            ));
        }

        let (mutable, init) = match dir {
            Dir::Out => (
                "mut ",
                type_str::out_default(&pat_ty.ty)?
                    .unwrap_or_else(|| "::core::default::Default::default()".into()),
            ),
            Dir::Inout => ("mut ", "_reader.read()?".to_string()),
            Dir::In => ("", "_reader.read()?".to_string()),
        };
        transaction_decls.push(format!("let {mutable}{ident}: {owned} = {init};"));
        if dir == Dir::Out {
            if is_option_vec {
                transaction_decls.push(format!("_reader.resize_nullable_out_vec(&mut {ident})?;"));
            } else if is_var_array {
                transaction_decls.push(format!("_reader.resize_out_vec(&mut {ident})?;"));
            }
        }

        if dir != Dir::In {
            let mut write = TransactionWrite::new(ident.clone());
            // A `None` fd element would go out as a null fd; `.aidl` raises `UNEXPECTED_NULL`.
            if dir == Dir::Out {
                if let Some(flatten) = type_str::out_pfd_null_guard(&pat_ty.ty) {
                    write.needs_null_guard = true;
                    write.null_guard_flatten = flatten;
                }
            }
            transaction_write.push(write);
            read_onto_params.push(ident.clone());
        }
        transaction_params += &format!(
            "{}, ",
            func_call_param(&ident, &pat_ty.ty, &as_written, &owned, dir)
        );
    }

    let return_type = return_type(f)?;
    if oneway && return_type != "()" {
        return Err(syn::Error::new_spanned(
            &f.sig.output,
            "a #[oneway] method cannot return a value — there is no reply to read it from",
        ));
    }

    let raw_ident = f.sig.ident.to_string();
    let mut member = FnMembers::new(strip_raw(&raw_ident), index);
    member.args = args;
    member.args_async = args_async;
    member.transaction_has_return = return_type != "()";
    member.return_type = return_type;
    member.write_funcs = write_funcs;
    member.func_call_params = trim_comma(func_call_params);
    member.transaction_decls = transaction_decls;
    member.transaction_write = transaction_write;
    member.transaction_params = trim_comma(transaction_params);
    member.oneway = oneway;
    member.read_onto_params = read_onto_params;
    member.deprecated = deprecated_of(&f.attrs)?;
    Ok(member)
}

/// Bridge `owned` to `as_written` off the signature alone, so no type list is needed.
fn func_call_param(ident: &str, ty: &Type, as_written: &str, owned: &str, dir: Dir) -> String {
    if dir != Dir::In {
        return format!("&mut {ident}");
    }
    if as_written == owned {
        return ident.to_string();
    }
    if as_written == "&str" {
        return format!("{ident}.as_str()");
    }
    if as_written.starts_with('&') {
        return format!("&{ident}");
    }
    // Structural, so `std::option::Option<&str>` borrows through like `Option<&str>`.
    let borrowed = type_str::option_inner(ty).map(type_str::unwrap_group);
    match borrowed {
        Some(Type::Reference(r)) => match type_str::unwrap_group(&r.elem) {
            Type::Path(p) if p.path.is_ident("str") => format!("{ident}.as_deref()"),
            Type::Slice(_) => format!("{ident}.as_deref()"),
            _ => format!("{ident}.as_ref()"),
        },
        _ => format!("&{ident}"),
    }
}

fn direction(attrs: &[syn::Attribute], ty: &Type) -> syn::Result<Dir> {
    let is_mut_ref =
        matches!(type_str::unwrap_group(ty), Type::Reference(r) if r.mutability.is_some());
    if has_attr(attrs, "inout") {
        if !is_mut_ref {
            return Err(syn::Error::new_spanned(
                ty,
                "#[inout] needs `&mut T` — the callee has to be able to write it back",
            ));
        }
        return Ok(Dir::Inout);
    }
    Ok(if is_mut_ref { Dir::Out } else { Dir::In })
}

fn return_type(f: &TraitItemFn) -> syn::Result<String> {
    let ReturnType::Type(_, ty) = &f.sig.output else {
        return Err(syn::Error::new_spanned(
            &f.sig,
            "a binder method must return `BinderResult<T>` — every call can fail on the wire",
        ));
    };
    let Type::Path(p) = type_str::unwrap_group(ty) else {
        return Err(syn::Error::new_spanned(ty, "expected `BinderResult<T>`"));
    };
    let last = p.path.segments.last().expect("non-empty path");
    if last.ident != "BinderResult" {
        return Err(syn::Error::new_spanned(
            ty,
            "expected `BinderResult<T>` (aliased as `rsbinder::BinderResult`)",
        ));
    }
    let PathArguments::AngleBracketed(args) = &last.arguments else {
        return Err(syn::Error::new_spanned(
            ty,
            "`BinderResult` needs its success type: `BinderResult<()>` for no return",
        ));
    };
    if args.args.len() != 1 {
        return Err(syn::Error::new_spanned(
            ty,
            "`BinderResult` takes exactly one type argument",
        ));
    }
    let Some(syn::GenericArgument::Type(inner)) = args.args.first() else {
        return Err(syn::Error::new_spanned(ty, "expected `BinderResult<T>`"));
    };
    type_str::check_type_at(inner, type_str::Place::Return)?;
    type_str::reject_reserved_names(inner)?;
    type_str::owned(inner)
}

/// Argument types the signature takes by value.
fn by_value_types(item: &ItemTrait) -> syn::Result<Vec<Type>> {
    let mut out = Vec::new();
    for trait_item in &item.items {
        let TraitItem::Fn(f) = trait_item else {
            continue;
        };
        for input in &f.sig.inputs {
            let FnArg::Typed(pat_ty) = input else {
                continue;
            };
            if !type_str::as_written(&pat_ty.ty)?.starts_with('&') {
                out.push((*pat_ty.ty).clone());
            }
        }
    }
    Ok(out)
}

/// `#[deprecated]` / `#[deprecated = "…"]` as `.aidl` renders `@deprecated`.
pub(crate) fn deprecated_of(attrs: &[syn::Attribute]) -> syn::Result<String> {
    let mut found = attrs.iter().filter(|a| a.path().is_ident("deprecated"));
    let Some(attr) = found.next() else {
        return Ok(String::new());
    };
    // The input item is not re-emitted, so rustc's own E0550 never sees the second one.
    if let Some(second) = found.next() {
        return Err(syn::Error::new_spanned(
            second,
            "#[deprecated] is given more than once",
        ));
    }
    match &attr.meta {
        syn::Meta::Path(_) => Ok(rsbinder_aidl::render::deprecated_attr(Some(&String::new()))),
        syn::Meta::NameValue(nv) => {
            let syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Str(s),
                ..
            }) = &nv.value
            else {
                return Err(syn::Error::new_spanned(
                    &nv.value,
                    "a deprecation note must be a string literal",
                ));
            };
            let note = s.value();
            Ok(rsbinder_aidl::render::deprecated_attr(Some(&note)))
        }
        syn::Meta::List(list) => Err(syn::Error::new_spanned(
            list,
            "`.aidl` carries only `#[deprecated]` and `#[deprecated = \"…\"]`; the other fields \
             of the Rust attribute have no AIDL form and would be dropped",
        )),
    }
}

fn has_attr(attrs: &[syn::Attribute], name: &str) -> bool {
    attrs.iter().any(|a| a.path().is_ident(name))
}

/// The re-render drops an unrecognised attribute, e.g. a mistyped `#[oneway]` or a `#[cfg]`.
fn check_attrs(attrs: &[syn::Attribute], allowed: &[&str]) -> syn::Result<()> {
    for attr in attrs {
        // Only `#[doc = "…"]`: a `#[doc(hidden)]` has no field to survive the re-render in.
        if attr.path().is_ident("doc") && matches!(attr.meta, syn::Meta::NameValue(_)) {
            continue;
        }
        if let Some(name) = allowed.iter().find(|a| attr.path().is_ident(a)) {
            // `#[deprecated]` carries its note; `deprecated_of` checks its shape.
            if *name != "deprecated" && !matches!(attr.meta, syn::Meta::Path(_)) {
                return Err(syn::Error::new_spanned(
                    attr,
                    format!("#[{name}] takes no arguments"),
                ));
            }
            continue;
        }
        let expected = if allowed.is_empty() {
            "no attribute is supported here".to_string()
        } else {
            format!(
                "#[rsbinder::interface] understands only {} here",
                allowed
                    .iter()
                    .map(|a| format!("#[{a}]"))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };
        return Err(syn::Error::new_spanned(
            attr,
            format!("unsupported attribute; {expected}"),
        ));
    }
    Ok(())
}

fn trim_comma(mut s: String) -> String {
    if s.ends_with(", ") {
        s.truncate(s.len() - 2);
    }
    s
}

#[cfg(test)]
mod golden {
    //! A trait here and the equivalent `.aidl` must render the same module source (plan 2-19 D1).

    use super::*;
    use std::path::{Path, PathBuf};
    use std::sync::atomic::{AtomicU32, Ordering};

    /// A temp directory that removes itself on drop.
    struct TempDir(PathBuf);

    impl TempDir {
        fn new(tag: &str) -> Self {
            static COUNTER: AtomicU32 = AtomicU32::new(0);
            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
            let dir = std::env::temp_dir().join(format!(
                "rsbinder_macros_golden_{tag}_{}_{n}",
                std::process::id()
            ));
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).expect("temp dir");
            Self(dir)
        }

        fn path(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    /// The interface module `rsbinder-aidl` generates from `aidl`, without the file header.
    fn from_aidl(aidl: &str, module: &str, enabled_async: bool) -> String {
        let dir = TempDir::new(module);
        let src = dir.path().join(format!("{module}.aidl"));
        std::fs::write(&src, aidl).expect("write aidl");

        rsbinder_aidl::Builder::new()
            .source(src)
            .include_dir(dir.path())
            .dest_dir(dir.path())
            .output(PathBuf::from("golden.rs"))
            .set_async_support(enabled_async)
            .generate()
            .expect("aidl generate");

        let text = std::fs::read_to_string(dir.path().join("golden.rs")).expect("read generated");
        extract_module(&text, module)
    }

    /// `pub mod {module} { … }`, dedented: a packaged `.aidl` nests it, the macro does not.
    fn extract_module(text: &str, module: &str) -> String {
        let needle = format!("pub mod {module} {{");
        let start_line = text
            .lines()
            .position(|l| l.trim_start().starts_with(&needle))
            .unwrap_or_else(|| panic!("no `pub mod {module}` in:\n{text}"));
        let lines: Vec<&str> = text.lines().collect();
        let indent = lines[start_line].len() - lines[start_line].trim_start().len();

        let mut depth = 0usize;
        let mut end_line = start_line;
        for (i, line) in lines.iter().enumerate().skip(start_line) {
            depth += line.matches('{').count();
            depth -= line.matches('}').count();
            if depth == 0 {
                end_line = i;
                break;
            }
        }

        lines[start_line..=end_line]
            .iter()
            .map(|l| {
                if l.len() >= indent {
                    &l[indent..]
                } else {
                    l.trim_start()
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
            .trim_end()
            .to_string()
    }

    fn from_macro(tokens: proc_macro2::TokenStream, enabled_async: bool) -> String {
        let item: ItemTrait = syn::parse2(tokens).expect("parse trait");
        render_source_with(&Args { descriptor: None }, &item, enabled_async).expect("render")
    }

    /// Both `enabled_async` settings: a `cfg!` would leave one half unchecked.
    #[track_caller]
    fn assert_same(aidl: &str, module: &str, tokens: proc_macro2::TokenStream) {
        for enabled_async in [false, true] {
            assert_same_for(aidl, module, tokens.clone(), enabled_async);
        }
    }

    #[track_caller]
    fn assert_same_for(
        aidl: &str,
        module: &str,
        tokens: proc_macro2::TokenStream,
        enabled_async: bool,
    ) {
        let expected = from_aidl(aidl, module, enabled_async);
        let actual = from_macro(tokens, enabled_async);
        if expected != actual {
            let mut report = String::new();
            for diff in expected
                .lines()
                .zip(actual.lines())
                .enumerate()
                .filter(|(_, (a, b))| a != b)
            {
                let (i, (a, b)) = diff;
                report.push_str(&format!("line {i}:\n  aidl : {a}\n  macro: {b}\n"));
            }
            if expected.lines().count() != actual.lines().count() {
                report.push_str(&format!(
                    "line count: aidl {} vs macro {}\n",
                    expected.lines().count(),
                    actual.lines().count()
                ));
            }
            panic!("generated code differs (enabled_async = {enabled_async})\n{report}\n--- aidl ---\n{expected}\n--- macro ---\n{actual}");
        }
    }

    /// [`assert_same`] for a multi-file fixture carrying an explicit descriptor.
    #[track_caller]
    fn assert_same_files(
        files: &[(&str, &str)],
        main: &str,
        module: &str,
        descriptor: &str,
        tokens: proc_macro2::TokenStream,
    ) {
        for enabled_async in [false, true] {
            let expected = from_aidl_files(files, main, module, enabled_async);
            let item: ItemTrait = syn::parse2(tokens.clone()).expect("parse trait");
            let actual = render_source_with(
                &Args {
                    descriptor: Some(descriptor.to_string()),
                },
                &item,
                enabled_async,
            )
            .expect("render");
            assert_eq!(
                expected, actual,
                "generated code differs (enabled_async = {enabled_async})"
            );
        }
    }

    /// [`from_aidl`] with sibling files, so a fixture can reference another interface.
    pub(crate) fn from_aidl_files(
        files: &[(&str, &str)],
        main: &str,
        module: &str,
        enabled_async: bool,
    ) -> String {
        let dir = TempDir::new(&format!("multi_{module}"));
        for (rel, body) in files {
            let path = dir.path().join(rel);
            std::fs::create_dir_all(path.parent().expect("relative path")).expect("mkdir");
            std::fs::write(&path, body).expect("write aidl");
        }
        rsbinder_aidl::Builder::new()
            .source(dir.path().join(main))
            .include_dir(dir.path())
            .dest_dir(dir.path())
            .output(PathBuf::from("golden_multi.rs"))
            .set_async_support(enabled_async)
            .generate()
            .expect("aidl generate");
        let text =
            std::fs::read_to_string(dir.path().join("golden_multi.rs")).expect("read generated");
        extract_module(&text, module)
    }

    #[test]
    fn scalars_and_strings() {
        assert_same(
            r#"
interface IGolden1 {
    String echo(in String msg);
    int add(in int a, in int b);
    boolean flag(in boolean b);
}
"#,
            "IGolden1",
            quote! {
                pub trait IGolden1 {
                    fn echo(&self, msg: &str) -> BinderResult<String>;
                    fn add(&self, a: i32, b: i32) -> BinderResult<i32>;
                    fn flag(&self, b: bool) -> BinderResult<bool>;
                }
            },
        );
    }

    #[test]
    fn oneway_and_void() {
        assert_same(
            r#"
interface IGolden2 {
    oneway void ping();
    void nudge(in long n);
}
"#,
            "IGolden2",
            quote! {
                pub trait IGolden2 {
                    #[oneway]
                    fn ping(&self) -> BinderResult<()>;
                    fn nudge(&self, n: i64) -> BinderResult<()>;
                }
            },
        );
    }

    #[test]
    fn out_and_inout_vectors() {
        assert_same(
            r#"
interface IGolden3 {
    void fill(out int[] values);
    void bump(inout int[] values);
    void take(in int[] values);
}
"#,
            "IGolden3",
            quote! {
                pub trait IGolden3 {
                    fn fill(&self, values: &mut Vec<i32>) -> BinderResult<()>;
                    fn bump(&self, #[inout] values: &mut Vec<i32>) -> BinderResult<()>;
                    fn take(&self, values: &[i32]) -> BinderResult<()>;
                }
            },
        );
    }

    /// `out List<T>` renders the same signature without the length word, so pin the array side.
    #[test]
    fn an_out_vec_is_the_array_form_not_the_list_form() {
        assert_same(
            r#"
interface IGolden12 {
    void fill(out String[] values);
    void maybe(out @nullable String[] values);
}
"#,
            "IGolden12",
            quote! {
                pub trait IGolden12 {
                    fn fill(&self, values: &mut Vec<String>) -> BinderResult<()>;
                    fn maybe(&self, values: &mut Option<Vec<Option<String>>>) -> BinderResult<()>;
                }
            },
        );
    }

    #[test]
    fn nullable_arguments_and_returns() {
        assert_same(
            r#"
interface IGolden4 {
    @nullable String maybe(in @nullable String msg, in @nullable byte[] blob);
    @nullable String[] some();
    String[] every();
}
"#,
            "IGolden4",
            quote! {
                pub trait IGolden4 {
                    fn maybe(
                        &self,
                        msg: Option<&str>,
                        blob: Option<&[u8]>,
                    ) -> BinderResult<Option<String>>;
                    fn some(&self) -> BinderResult<Option<Vec<Option<String>>>>;
                    fn every(&self) -> BinderResult<Vec<String>>;
                }
            },
        );
    }

    #[test]
    fn binder_objects() {
        // Cross-file, to pin the `super::Mod::Type` path a packaged import produces.
        assert_same_files(
            &[
                (
                    "com/example/IGolden5.aidl",
                    "package com.example;\nimport com.example.IGolden5Cb;\n\
                     interface IGolden5 {\n    void register(in IGolden5Cb cb);\n\
                         IGolden5Cb fetch();\n}\n",
                ),
                (
                    "com/example/IGolden5Cb.aidl",
                    "package com.example;\ninterface IGolden5Cb {\n    void hit();\n}\n",
                ),
            ],
            "com/example/IGolden5.aidl",
            "IGolden5",
            "com.example.IGolden5",
            quote! {
                pub trait IGolden5 {
                    fn register(
                        &self,
                        cb: &rsbinder::Strong<dyn super::IGolden5Cb::IGolden5Cb>,
                    ) -> BinderResult<()>;
                    fn fetch(
                        &self,
                    ) -> BinderResult<rsbinder::Strong<dyn super::IGolden5Cb::IGolden5Cb>>;
                }
            },
        );
    }

    /// A fixed-size out fd array keeps the guard, one `.flatten()` per extra dimension.
    #[test]
    fn out_fd_arrays_keep_the_null_guard_at_every_arity() {
        assert_same(
            r#"
interface IGolden8 {
    void variable(out ParcelFileDescriptor[] fds);
    void fixed(out ParcelFileDescriptor[3] fds);
    void nested(out ParcelFileDescriptor[2][3] fds);
}
"#,
            "IGolden8",
            quote! {
                pub trait IGolden8 {
                    fn variable(
                        &self,
                        fds: &mut Vec<Option<rsbinder::ParcelFileDescriptor>>,
                    ) -> BinderResult<()>;
                    fn fixed(
                        &self,
                        fds: &mut [Option<rsbinder::ParcelFileDescriptor>; 3],
                    ) -> BinderResult<()>;
                    fn nested(
                        &self,
                        fds: &mut [[Option<rsbinder::ParcelFileDescriptor>; 3]; 2],
                    ) -> BinderResult<()>;
                }
            },
        );
    }

    /// Every out/inout shape `.aidl` renders, in one interface.
    #[test]
    fn every_out_and_inout_shape_matches_aidl() {
        assert_same_files(
            &[
                (
                    "p/IGolden10.aidl",
                    "package p;\nimport p.IGolden10Cb;\nimport p.Golden10Cfg;\n\
                     interface IGolden10 {\n\
                     \x20   void d(out Golden10Cfg v);\n\
                     \x20   void e(out int[] v);\n\
                     \x20   void f(out String[] v);\n\
                     \x20   void g(out ParcelFileDescriptor[] v);\n\
                     \x20   void h(out IGolden10Cb[] v);\n\
                     \x20   void i(out Golden10Cfg[] v);\n\
                     \x20   void j(out int[3] v);\n\
                     \x20   void k(out ParcelFileDescriptor[3] v);\n\
                     \x20   void l(out ParcelFileDescriptor[2][3] v);\n\
                     \x20   void m(out Golden10Cfg[3] v);\n\
                     \x20   void n(out @nullable Golden10Cfg v);\n\
                     \x20   void o(out @nullable int[] v);\n\
                     \x20   void p(out @nullable String[] v);\n\
                     \x20   void q(out @nullable ParcelFileDescriptor[] v);\n\
                     \x20   void r(out @nullable int[3] v);\n\
                     \x20   void s(out @nullable Golden10Cfg[3] v);\n\
                     \x20   void t(inout ParcelFileDescriptor v);\n\
                     \x20   void u(inout @nullable ParcelFileDescriptor v);\n\
                     \x20   void w(inout ParcelFileDescriptor[] v);\n\
                     \x20   void x(inout IGolden10Cb[] v);\n\
                     \x20   void y(inout @nullable Golden10Cfg v);\n\
                     \x20   void z(inout @nullable ParcelFileDescriptor[] v);\n\
                     \x20   void aa(inout ParcelFileDescriptor[3] v);\n\
                     \x20   void ab(inout Golden10Cfg[3] v);\n\
                     \x20   void ac(inout IGolden10Cb[3] v);\n\
                     \x20   void ad(inout @nullable ParcelFileDescriptor[3] v);\n}\n",
                ),
                (
                    "p/IGolden10Cb.aidl",
                    "package p;\ninterface IGolden10Cb {\n    void hit();\n}\n",
                ),
                (
                    "p/Golden10Cfg.aidl",
                    "package p;\nparcelable Golden10Cfg {\n    int a;\n}\n",
                ),
            ],
            "p/IGolden10.aidl",
            "IGolden10",
            "p.IGolden10",
            quote! {
                pub trait IGolden10 {
                    fn d(&self, v: &mut super::Golden10Cfg::Golden10Cfg) -> BinderResult<()>;
                    fn e(&self, v: &mut Vec<i32>) -> BinderResult<()>;
                    fn f(&self, v: &mut Vec<String>) -> BinderResult<()>;
                    fn g(
                        &self,
                        v: &mut Vec<Option<rsbinder::ParcelFileDescriptor>>,
                    ) -> BinderResult<()>;
                    fn h(
                        &self,
                        v: &mut Vec<Option<rsbinder::Strong<dyn super::IGolden10Cb::IGolden10Cb>>>,
                    ) -> BinderResult<()>;
                    fn i(&self, v: &mut Vec<super::Golden10Cfg::Golden10Cfg>) -> BinderResult<()>;
                    fn j(&self, v: &mut [i32; 3]) -> BinderResult<()>;
                    fn k(
                        &self,
                        v: &mut [Option<rsbinder::ParcelFileDescriptor>; 3],
                    ) -> BinderResult<()>;
                    fn l(
                        &self,
                        v: &mut [[Option<rsbinder::ParcelFileDescriptor>; 3]; 2],
                    ) -> BinderResult<()>;
                    fn m(&self, v: &mut [super::Golden10Cfg::Golden10Cfg; 3]) -> BinderResult<()>;
                    fn n(
                        &self,
                        v: &mut Option<super::Golden10Cfg::Golden10Cfg>,
                    ) -> BinderResult<()>;
                    fn o(&self, v: &mut Option<Vec<i32>>) -> BinderResult<()>;
                    fn p(&self, v: &mut Option<Vec<Option<String>>>) -> BinderResult<()>;
                    fn q(
                        &self,
                        v: &mut Option<Vec<Option<rsbinder::ParcelFileDescriptor>>>,
                    ) -> BinderResult<()>;
                    fn r(&self, v: &mut Option<[i32; 3]>) -> BinderResult<()>;
                    fn s(
                        &self,
                        v: &mut Option<[Option<super::Golden10Cfg::Golden10Cfg>; 3]>,
                    ) -> BinderResult<()>;
                    fn t(
                        &self,
                        #[inout] v: &mut rsbinder::ParcelFileDescriptor,
                    ) -> BinderResult<()>;
                    fn u(
                        &self,
                        #[inout] v: &mut Option<rsbinder::ParcelFileDescriptor>,
                    ) -> BinderResult<()>;
                    fn w(
                        &self,
                        #[inout] v: &mut Vec<rsbinder::ParcelFileDescriptor>,
                    ) -> BinderResult<()>;
                    fn x(
                        &self,
                        #[inout] v: &mut Vec<rsbinder::Strong<dyn super::IGolden10Cb::IGolden10Cb>>,
                    ) -> BinderResult<()>;
                    fn y(
                        &self,
                        #[inout] v: &mut Option<super::Golden10Cfg::Golden10Cfg>,
                    ) -> BinderResult<()>;
                    fn z(
                        &self,
                        #[inout] v: &mut Option<Vec<Option<rsbinder::ParcelFileDescriptor>>>,
                    ) -> BinderResult<()>;
                    fn aa(
                        &self,
                        #[inout] v: &mut [rsbinder::ParcelFileDescriptor; 3],
                    ) -> BinderResult<()>;
                    fn ab(
                        &self,
                        #[inout] v: &mut [super::Golden10Cfg::Golden10Cfg; 3],
                    ) -> BinderResult<()>;
                    fn ac(
                        &self,
                        #[inout] v: &mut [rsbinder::Strong<dyn super::IGolden10Cb::IGolden10Cb>; 3],
                    ) -> BinderResult<()>;
                    fn ad(
                        &self,
                        #[inout] v: &mut Option<[Option<rsbinder::ParcelFileDescriptor>; 3]>,
                    ) -> BinderResult<()>;
                }
            },
        );
    }

    /// `@deprecated` on the trait and the method renders what `.aidl` renders.
    #[test]
    fn deprecation_matches_aidl() {
        assert_same(
            r#"
/**
 * @deprecated use IGolden12Next
 */
interface IGolden12 {
    /**
     * @deprecated use b
     */
    void a();
    void b();
}
"#,
            "IGolden12",
            quote! {
                #[deprecated = "use IGolden12Next"]
                pub trait IGolden12 {
                    #[deprecated = "use b"]
                    fn a(&self) -> BinderResult<()>;
                    fn b(&self) -> BinderResult<()>;
                }
            },
        );
    }

    /// The richer Rust forms carry fields `.aidl` has nowhere to put.
    #[test]
    fn rejects_a_deprecation_the_wire_cannot_carry() {
        let err = reject(quote! {
            #[deprecated(since = "1.0", note = "use b")]
            pub trait IBad {
                fn go(&self) -> BinderResult<()>;
            }
        });
        assert!(err.contains("no AIDL form"), "{err}");
    }

    /// Only the first would render; the rest would vanish without a word.
    #[test]
    fn rejects_a_repeated_deprecation() {
        let err = reject(quote! {
            pub trait IBad {
                #[deprecated = "a"]
                #[deprecated = "b"]
                fn go(&self) -> BinderResult<()>;
            }
        });
        assert!(err.contains("more than once"), "{err}");
    }

    /// `#[doc(hidden)]` has nowhere to go in the render, so it would be dropped.
    #[test]
    fn rejects_a_doc_attribute_the_re_render_would_drop() {
        for attr in [quote!(#[doc(hidden)]), quote!(#[doc(alias = "x")])] {
            let err = reject(quote! {
                #attr
                pub trait IBad {
                    fn go(&self) -> BinderResult<()>;
                }
            });
            assert!(err.contains("unsupported attribute"), "{attr}: {err}");
        }
        // A doc comment is `#[doc = "…"]`, and stays legal.
        render(quote! {
            /// Documented.
            pub trait IOk {
                /// Documented too.
                fn go(&self) -> BinderResult<()>;
            }
        });
    }

    /// Advice for a nullable bare path must keep the `Option`: `@nullable Mode` has no form.
    #[test]
    fn a_nullable_by_value_path_is_pointed_at_the_borrowed_form() {
        let err = reject(quote! {
            pub trait IBad {
                fn go(&self, c: Option<Cfg>) -> BinderResult<()>;
            }
        });
        assert!(err.contains("`Option<&Cfg>`"), "{err}");
        assert!(!err.contains("`Cfg` or"), "{err}");
    }

    /// Every `in` array shape `.aidl` renders; the element `Option` rule differs from `out`.
    #[test]
    fn every_in_array_shape_matches_aidl() {
        assert_same_files(
            &[
                (
                    "p/IGolden14.aidl",
                    "package p;\nimport p.IGolden14Cb;\nimport p.Golden14Cfg;\n\
                     interface IGolden14 {\n\
                     \x20   void a(in int[] v);\n\
                     \x20   void b(in @nullable int[] v);\n\
                     \x20   void c(in String[] v);\n\
                     \x20   void d(in @nullable String[] v);\n\
                     \x20   void e(in Golden14Cfg[] v);\n\
                     \x20   void f(in @nullable Golden14Cfg[] v);\n\
                     \x20   void g(in ParcelFileDescriptor[] v);\n\
                     \x20   void h(in @nullable ParcelFileDescriptor[] v);\n\
                     \x20   void i(in IGolden14Cb[] v);\n\
                     \x20   void j(in @nullable IGolden14Cb[] v);\n\
                     \x20   void k(in IBinder[] v);\n\
                     \x20   void l(in @nullable IBinder[] v);\n\
                     \x20   void m(in Golden14Cfg[3] v);\n\
                     \x20   void n(in @nullable Golden14Cfg[3] v);\n\
                     \x20   void o(in ParcelFileDescriptor[3] v);\n\
                     \x20   void p(in @nullable ParcelFileDescriptor[3] v);\n}\n",
                ),
                (
                    "p/IGolden14Cb.aidl",
                    "package p;\ninterface IGolden14Cb {\n    void hit();\n}\n",
                ),
                (
                    "p/Golden14Cfg.aidl",
                    "package p;\nparcelable Golden14Cfg {\n    int a;\n}\n",
                ),
            ],
            "p/IGolden14.aidl",
            "IGolden14",
            "p.IGolden14",
            quote! {
                pub trait IGolden14 {
                    fn a(&self, v: &[i32]) -> BinderResult<()>;
                    fn b(&self, v: Option<&[i32]>) -> BinderResult<()>;
                    fn c(&self, v: &[String]) -> BinderResult<()>;
                    fn d(&self, v: Option<&[Option<String>]>) -> BinderResult<()>;
                    fn e(&self, v: &[super::Golden14Cfg::Golden14Cfg]) -> BinderResult<()>;
                    fn f(
                        &self,
                        v: Option<&[Option<super::Golden14Cfg::Golden14Cfg>]>,
                    ) -> BinderResult<()>;
                    fn g(&self, v: &[rsbinder::ParcelFileDescriptor]) -> BinderResult<()>;
                    fn h(
                        &self,
                        v: Option<&[Option<rsbinder::ParcelFileDescriptor>]>,
                    ) -> BinderResult<()>;
                    fn i(
                        &self,
                        v: &[rsbinder::Strong<dyn super::IGolden14Cb::IGolden14Cb>],
                    ) -> BinderResult<()>;
                    fn j(
                        &self,
                        v: Option<&[Option<rsbinder::Strong<dyn super::IGolden14Cb::IGolden14Cb>>]>,
                    ) -> BinderResult<()>;
                    fn k(&self, v: &[rsbinder::SIBinder]) -> BinderResult<()>;
                    fn l(&self, v: Option<&[Option<rsbinder::SIBinder>]>) -> BinderResult<()>;
                    fn m(&self, v: &[super::Golden14Cfg::Golden14Cfg; 3]) -> BinderResult<()>;
                    fn n(
                        &self,
                        v: Option<&[Option<super::Golden14Cfg::Golden14Cfg>; 3]>,
                    ) -> BinderResult<()>;
                    fn o(&self, v: &[rsbinder::ParcelFileDescriptor; 3]) -> BinderResult<()>;
                    fn p(
                        &self,
                        v: Option<&[Option<rsbinder::ParcelFileDescriptor>; 3]>,
                    ) -> BinderResult<()>;
                }
            },
        );
    }

    /// An element `Option` `.aidl` spells bare lets a null go out that a peer cannot decode.
    #[test]
    fn rejects_an_array_of_options_aidl_would_spell_bare() {
        for decl in [
            // `in` never gives an element its own `Option`.
            quote!(
                fn go(&self, v: &[Option<rsbinder::ParcelFileDescriptor>]) -> BinderResult<()>;
            ),
            // `out` gives one only to a binder or a fd.
            quote!(
                fn go(&self, v: &mut Vec<Option<String>>) -> BinderResult<()>;
            ),
            // A variable `inout` array is read in fully populated.
            quote!(
                fn go(
                    &self,
                    #[inout] v: &mut Vec<Option<rsbinder::ParcelFileDescriptor>>,
                ) -> BinderResult<()>;
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains("`Option<_>` elements"), "{err}");
        }
    }

    /// Only `out` starts a slot empty, fixed `#[inout]` included; `@nullable` wraps everywhere.
    #[test]
    fn rejects_array_elements_aidl_spells_the_other_way() {
        for (decl, needle) in [
            (
                quote!(
                    fn go(
                        &self,
                        #[inout] v: &mut [Option<rsbinder::ParcelFileDescriptor>; 3],
                    ) -> BinderResult<()>;
                ),
                "an `inout` array cannot have `Option<_>` elements",
            ),
            (
                quote!(
                    fn go(
                        &self,
                        #[inout] v: &mut [Option<rsbinder::Strong<dyn IOther>>; 3],
                    ) -> BinderResult<()>;
                ),
                "an `inout` array cannot have `Option<_>` elements",
            ),
            (
                quote!(
                    fn go(&self, v: Option<&[String]>) -> BinderResult<()>;
                ),
                "a nullable `in` array",
            ),
            (
                quote!(
                    fn go(&self, v: Option<&[rsbinder::ParcelFileDescriptor]>) -> BinderResult<()>;
                ),
                "a nullable `in` array",
            ),
            (
                quote!(
                    fn go(&self, v: &mut Option<Vec<String>>) -> BinderResult<()>;
                ),
                "a nullable `out` array",
            ),
            (
                quote!(
                    fn go(
                        &self,
                        v: &mut Option<[rsbinder::ParcelFileDescriptor; 3]>,
                    ) -> BinderResult<()>;
                ),
                "a nullable `out` array",
            ),
            // A fixed-size `in` array wraps them like a variable one.
            (
                quote!(
                    fn go(
                        &self,
                        v: Option<&[rsbinder::ParcelFileDescriptor; 3]>,
                    ) -> BinderResult<()>;
                ),
                "a nullable `in` array",
            ),
            // A return renders down the same arm as `in`, both ways round.
            (
                quote!(
                    fn go(&self) -> BinderResult<Option<Vec<String>>>;
                ),
                "a nullable returned array",
            ),
            (
                quote!(
                    fn go(&self) -> BinderResult<Option<Vec<rsbinder::Strong<dyn IOther>>>>;
                ),
                "a nullable returned array",
            ),
            (
                quote!(
                    fn go(&self) -> BinderResult<Vec<Option<String>>>;
                ),
                "a returned array cannot have",
            ),
            (
                quote!(
                    fn go(&self) -> BinderResult<Option<[String; 3]>>;
                ),
                "a nullable returned array",
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains(needle), "{needle}: {err}");
        }
        // The spellings `.aidl` renders for those same shapes.
        render(quote! {
            pub trait IOk {
                fn a(
                    &self,
                    #[inout] v: &mut [rsbinder::ParcelFileDescriptor; 3],
                ) -> BinderResult<()>;
                fn a2(&self, #[inout] v: &mut [rsbinder::Strong<dyn IOther>; 3]) -> BinderResult<()>;
                fn b(&self, v: Option<&[Option<String>]>) -> BinderResult<()>;
                fn c(
                    &self,
                    v: Option<&[Option<rsbinder::ParcelFileDescriptor>; 3]>,
                ) -> BinderResult<()>;
                fn d(&self) -> BinderResult<Option<Vec<Option<String>>>>;
                fn e(&self) -> BinderResult<Vec<String>>;
                fn f(&self) -> BinderResult<Option<[Option<String>; 3]>>;
            }
        });
    }

    /// `.aidl` has no variable-length dimension beside another, nor an `Option` around one.
    #[test]
    fn rejects_arrays_nested_the_way_aidl_cannot_render() {
        for (decl, needle) in [
            (
                quote!(
                    fn go(&self) -> BinderResult<Vec<[i32; 3]>>;
                ),
                "fixed-size in every dimension",
            ),
            (
                quote!(
                    fn go(&self, v: &[[i32; 3]]) -> BinderResult<()>;
                ),
                "fixed-size in every dimension",
            ),
            (
                quote!(
                    fn go(
                        &self,
                        v: &mut Vec<[rsbinder::ParcelFileDescriptor; 3]>,
                    ) -> BinderResult<()>;
                ),
                "fixed-size in every dimension",
            ),
            (
                quote!(
                    fn go(&self) -> BinderResult<Vec<Vec<i32>>>;
                ),
                "fixed-size in every dimension",
            ),
            (
                quote!(
                    fn go(&self) -> BinderResult<Option<Vec<Option<[String; 3]>>>>;
                ),
                "`Option` of another array",
            ),
            (
                quote!(
                    fn go(&self) -> BinderResult<[Option<[String; 3]>; 2]>;
                ),
                "`Option` of another array",
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains(needle), "{needle}: {err}");
        }
    }

    /// The spellings `.aidl` never renders for an `in` argument.
    #[test]
    fn rejects_a_borrowed_owned_container() {
        for (ty, needle) in [
            (quote!(&String), "&str"),
            (quote!(&Vec<i32>), "&[T]"),
            (quote!(Option<&String>), "&str"),
            (quote!(Option<&Vec<i32>>), "&[T]"),
            (quote!(&Option<String>), "Option<&T>"),
            (quote!(Option<&Option<String>>), "Option<&T>"),
            (quote!(&i32), "drop the `&`"),
            (quote!(&bool), "drop the `&`"),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    fn go(&self, v: #ty) -> BinderResult<()>;
                }
            });
            assert!(err.contains(needle), "{ty}: {err}");
        }
        // `&mut Vec<T>` is the out spelling, and stays legal.
        render(quote! {
            pub trait IOk {
                fn go(&self, v: &mut Vec<i32>) -> BinderResult<()>;
            }
        });
    }

    /// The return type takes the argument guards too, minus the `()` it may be.
    #[test]
    fn rejects_return_types_with_no_wire_form() {
        for (ty, needle) in [
            (quote!(dyn std::fmt::Debug), "trait object"),
            (quote!(<Vec<i32> as IntoIterator>::Item), "qualified path"),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    fn go(&self) -> BinderResult<#ty>;
                }
            });
            assert!(err.contains(needle), "{ty}: {err}");
        }
    }

    /// A scalar `.aidl` cannot render makes the `.aidl` port a different type.
    #[test]
    fn rejects_scalars_aidl_never_renders() {
        for (decl, needle) in [
            (
                quote!(
                    fn go(&self, n: u32) -> BinderResult<()>;
                ),
                "`u32`",
            ),
            (
                quote!(
                    fn go(&self, n: i16) -> BinderResult<()>;
                ),
                "`i16`",
            ),
            (
                quote!(
                    fn go(&self, n: u8) -> BinderResult<()>;
                ),
                "`u8`",
            ),
            (
                quote!(
                    fn go(&self, n: char) -> BinderResult<()>;
                ),
                "`char`",
            ),
            (
                quote!(
                    fn go(&self, v: &[u32]) -> BinderResult<()>;
                ),
                "`u32`",
            ),
            // `byte` is `u8` in an array element, so `i8` is wrong exactly there.
            (
                quote!(
                    fn go(&self, v: &[i8]) -> BinderResult<()>;
                ),
                "element spelling",
            ),
            (
                quote!(
                    fn go(&self) -> BinderResult<u64>;
                ),
                "`u64`",
            ),
            (
                quote!(
                    fn go(&self) -> BinderResult<u128>;
                ),
                "`u128`",
            ),
            // Below a generic other than `Vec`/`Option` the argument is still a scalar.
            (
                quote!(
                    fn go(&self) -> BinderResult<Box<u128>>;
                ),
                "`u128`",
            ),
            (
                quote!(
                    fn go(&self, p: &Pair<u32>) -> BinderResult<()>;
                ),
                "`u32`",
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains(needle), "{needle}: {err}");
        }
        // Every scalar `.aidl` does render, plus `u8` as a `byte[]` element.
        render(quote! {
            pub trait IOk {
                fn a(&self, v: bool, w: i8, x: i32, y: i64) -> BinderResult<()>;
                fn b(&self, v: f32, w: f64, x: u16) -> BinderResult<()>;
                fn c(&self, v: &[u8]) -> BinderResult<()>;
                fn d(&self, v: Option<&[u8]>) -> BinderResult<()>;
                fn e(&self) -> BinderResult<i64>;
            }
        });
    }

    /// `.aidl` boxes only the cycle-closing `@nullable` parcelable field, at its outer `Option`.
    #[test]
    fn rejects_a_box_aidl_never_renders() {
        for decl in [
            quote!(
                fn go(&self) -> BinderResult<Box<Cfg>>;
            ),
            quote!(
                fn go(&self, c: &Box<Cfg>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, c: &mut Box<Cfg>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self) -> BinderResult<Vec<Option<Box<Cfg>>>>;
            ),
            quote!(
                fn go(&self) -> BinderResult<Option<Box<i32>>>;
            ),
            quote!(
                fn go(&self, c: Option<Box<Cfg>>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self) -> BinderResult<std::boxed::Box<Cfg>>;
            ),
            quote!(
                fn go(&self) -> BinderResult<Option<Box<Cfg>>>;
            ),
            quote!(
                fn go(&self, c: Option<&Box<Cfg>>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, c: &mut Option<Box<Cfg>>) -> BinderResult<()>;
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains("never renders this `Box`"), "{decl}: {err}");
        }
        render(quote! {
            pub trait IOk {
                fn d(&self) -> BinderResult<crate::p::Box<Cfg>>;
            }
        });
        let input: syn::DeriveInput = syn::parse2(quote! {
            pub struct Node {
                pub next: Option<Box<Node>>,
            }
        })
        .unwrap();
        parcelable::render_source(&input).expect("a field's `Option<Box<T>>` is accepted");
    }

    /// `.aidl` refuses an array, `List` or `@nullable` as a user generic's type argument.
    #[test]
    fn rejects_a_generic_argument_aidl_never_renders() {
        for decl in [
            quote!(
                fn go(&self) -> BinderResult<Pair<Vec<i32>>>;
            ),
            quote!(
                fn go(&self, p: &Pair<[i32; 3]>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self) -> BinderResult<Vec<Pair<Vec<i32>>>>;
            ),
            quote!(
                fn go(&self) -> BinderResult<crate::p::Box<Option<Cfg>>>;
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains("names a type argument bare"), "{decl}: {err}");
        }
        let input: syn::DeriveInput = syn::parse2(quote! {
            pub struct Holder {
                pub p: Pair<Option<Cfg>>,
            }
        })
        .unwrap();
        let err = parcelable::render_source(&input)
            .expect_err("a field's `Pair<Option<Cfg>>` is refused")
            .to_string();
        assert!(err.contains("names a type argument bare"), "{err}");
        render(quote! {
            pub trait IOk {
                fn a(&self, p: &Pair<Cfg>) -> BinderResult<Option<Pair<Pair<String>>>>;
                fn b(&self) -> BinderResult<Vec<Pair<i32>>>;
            }
        });
    }

    /// An empty descriptor would let two interfaces cast to each other's proxy.
    #[test]
    fn rejects_an_empty_descriptor() {
        let err = match syn::parse2::<Args>(quote!(descriptor = "")) {
            Ok(_) => panic!("an empty `descriptor` must be refused"),
            Err(e) => e.to_string(),
        };
        assert!(err.contains("cannot be empty"), "{err}");
    }

    /// The one shape where the two paths could disagree on how an interface names itself.
    #[test]
    fn self_referencing_interface() {
        assert_same(
            r#"
interface IGolden6 {
    void register(in IGolden6 cb);
    IGolden6 fetch();
}
"#,
            "IGolden6",
            quote! {
                pub trait IGolden6 {
                    fn register(
                        &self,
                        cb: &rsbinder::Strong<dyn IGolden6>,
                    ) -> BinderResult<()>;
                    fn fetch(&self) -> BinderResult<rsbinder::Strong<dyn IGolden6>>;
                }
            },
        );
    }

    /// Compared before the derive drops the struct and `Default`, so the whole module is pinned.
    #[test]
    fn parcelable_codec_matches_aidl() {
        let input: syn::DeriveInput = syn::parse2(quote! {
            pub struct GoldenConfig {
                pub name: String,
                pub retries: i32,
                pub verbose: bool,
                pub timeoutNanos: i64,
                pub ratio: f64,
                pub extra: Option<Vec<u8>>,
                pub tags: Vec<String>,
                pub labels: Option<Vec<Option<String>>>,
                pub slots: [String; 3],
                pub fds: [Option<rsbinder::ParcelFileDescriptor>; 3],
                pub ibinder: Option<rsbinder::SIBinder>,
            }
        })
        .unwrap();
        let actual = parcelable::render_source(&input).expect("render");
        for enabled_async in [false, true] {
            let expected = from_aidl(
                r#"
parcelable GoldenConfig {
    String name;
    int retries;
    boolean verbose;
    long timeoutNanos;
    double ratio;
    @nullable byte[] extra;
    String[] tags;
    @nullable String[] labels;
    String[3] slots;
    ParcelFileDescriptor[3] fds;
    @nullable IBinder ibinder;
}
"#,
                "GoldenConfig",
                enabled_async,
            );
            assert_eq!(expected, actual, "generated parcelable differs");
        }
    }

    /// An enum is a scalar in `.aidl`, so it is passed by value.
    #[test]
    fn parcelable_and_enum_arguments() {
        let files = [
            (
                "com/example/IGolden7.aidl",
                "package com.example;\nimport com.example.GoldenCfg;\n\
                 import com.example.GoldenMode;\n\
                 interface IGolden7 {\n\
                 \x20   GoldenCfg apply(in GoldenCfg cfg, in GoldenMode mode);\n}\n",
            ),
            (
                "com/example/GoldenCfg.aidl",
                "package com.example;\nparcelable GoldenCfg {\n    String name;\n\
                 \x20   int retries;\n}\n",
            ),
            (
                "com/example/GoldenMode.aidl",
                "package com.example;\n@Backing(type=\"int\")\n\
                 enum GoldenMode {\n    FAST = 0,\n    SAFE = 1,\n}\n",
            ),
        ];
        assert_same_files(
            &files,
            "com/example/IGolden7.aidl",
            "IGolden7",
            "com.example.IGolden7",
            quote! {
                pub trait IGolden7 {
                    fn apply(
                        &self,
                        cfg: &super::GoldenCfg::GoldenCfg,
                        mode: super::GoldenMode::GoldenMode,
                    ) -> BinderResult<super::GoldenCfg::GoldenCfg>;
                }
            },
        );
    }

    #[test]
    fn rejects_generic_trait() {
        let item: ItemTrait = syn::parse2(quote! {
            pub trait IBad<T> {
                fn go(&self) -> BinderResult<()>;
            }
        })
        .unwrap();
        let err = render_source(&Args { descriptor: None }, &item).unwrap_err();
        assert!(err.to_string().contains("cannot be generic"), "{err}");
    }

    #[test]
    fn rejects_oneway_with_return() {
        let item: ItemTrait = syn::parse2(quote! {
            pub trait IBad {
                #[oneway]
                fn go(&self) -> BinderResult<i32>;
            }
        })
        .unwrap();
        let err = render_source(&Args { descriptor: None }, &item).unwrap_err();
        assert!(err.to_string().contains("cannot return a value"), "{err}");
    }

    #[test]
    fn rejects_missing_receiver() {
        let item: ItemTrait = syn::parse2(quote! {
            pub trait IBad {
                fn go() -> BinderResult<()>;
            }
        })
        .unwrap();
        let err = render_source(&Args { descriptor: None }, &item).unwrap_err();
        assert!(err.to_string().contains("&self"), "{err}");
    }

    #[test]
    fn descriptor_defaults_to_trait_name_and_can_be_overridden() {
        let item: ItemTrait = syn::parse2(quote! {
            pub trait IHello {
                fn go(&self) -> BinderResult<()>;
            }
        })
        .unwrap();
        let bare = render_source(&Args { descriptor: None }, &item).unwrap();
        assert!(bare.contains(r#""IHello""#), "{bare}");
        let named = render_source(
            &Args {
                descriptor: Some("com.example.IHello".into()),
            },
            &item,
        )
        .unwrap();
        assert!(named.contains(r#""com.example.IHello""#), "{named}");
    }

    fn render(tokens: proc_macro2::TokenStream) -> String {
        let item: ItemTrait = syn::parse2(tokens).expect("parse trait");
        render_source(&Args { descriptor: None }, &item).expect("render")
    }

    fn reject(tokens: proc_macro2::TokenStream) -> String {
        let item: ItemTrait = syn::parse2(tokens).expect("parse trait");
        render_source(&Args { descriptor: None }, &item)
            .unwrap_err()
            .to_string()
    }

    /// The `_arg_` prefix and the templates' `r#` must not stack into `_arg_r#` / `r#r#`.
    #[test]
    fn raw_identifiers_are_not_double_escaped() {
        let s = render(quote! {
            pub trait IRaw {
                fn r#type(&self, r#match: i32) -> BinderResult<()>;
            }
        });
        assert!(!s.contains("r#r#"), "{s}");
        assert!(!s.contains("_arg_r#"), "{s}");
        assert!(s.contains("fn r#type("), "{s}");
        assert!(s.contains("_arg_match"), "{s}");
        syn::parse_file(&s).unwrap_or_else(|e| panic!("does not parse: {e}\n{s}"));
    }

    /// A raw trait name has to survive into `Bn`/`Bp` and the module name.
    #[test]
    fn raw_trait_name_renders() {
        let item: ItemTrait = syn::parse2(quote! {
            pub trait r#type {
                fn go(&self) -> BinderResult<()>;
            }
        })
        .unwrap();
        let s = render_source(&Args { descriptor: None }, &item).expect("render");
        assert!(s.contains("pub trait r#type"), "{s}");
        assert!(s.contains("Bntype"), "{s}");
        assert!(!s.contains("r#r#"), "{s}");
        syn::parse_file(&s).unwrap_or_else(|e| panic!("does not parse: {e}\n{s}"));
    }

    /// The re-render would drop these: a `#[cfg]` ignored, a `#[oneway]` turned twoway.
    #[test]
    fn rejects_trait_level_attributes() {
        let err = reject(quote! {
            #[cfg(feature = "x")]
            pub trait IBad {
                fn go(&self) -> BinderResult<()>;
            }
        });
        assert!(err.contains("unsupported attribute"), "{err}");

        let err = reject(quote! {
            #[oneway]
            pub trait IBad {
                fn go(&self) -> BinderResult<()>;
            }
        });
        assert!(err.contains("unsupported attribute"), "{err}");
    }

    #[test]
    fn rejects_where_clauses() {
        let err = reject(quote! {
            pub trait IBad where Self: Sized {
                fn go(&self) -> BinderResult<()>;
            }
        });
        assert!(err.contains("where clause"), "{err}");

        let err = reject(quote! {
            pub trait IBad {
                fn go(&self) -> BinderResult<()> where Self: Sized;
            }
        });
        assert!(err.contains("where clause"), "{err}");
    }

    /// The re-render drops modifiers, so the user's `impl` would miss its own signature.
    #[test]
    fn rejects_signature_modifiers() {
        let err = reject(quote! {
            pub trait IBad {
                async fn go(&self) -> BinderResult<()>;
            }
        });
        assert!(err.contains("sync"), "{err}");

        let err = reject(quote! {
            pub trait IBad {
                unsafe fn go(&self) -> BinderResult<()>;
            }
        });
        assert!(err.contains("unsafe"), "{err}");
    }

    /// `syn` keeps `&mut self`'s `mut` inside the receiver kind, so the check names the kind.
    #[test]
    fn rejects_non_shared_receivers() {
        for recv in [
            quote!(self),
            quote!(mut self),
            quote!(&mut self),
            quote!(&'static self),
            quote!(self: Box<Self>),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    fn go(#recv) -> BinderResult<()>;
                }
            });
            assert!(err.contains("`&self`"), "{recv}: {err}");
        }
        // Already a shared borrow, so the reason has to be the lifetime.
        let err = reject(quote! {
            pub trait IBad {
                fn go(&'static self) -> BinderResult<()>;
            }
        });
        assert!(err.contains("explicit lifetime on `self`"), "{err}");
        // `&'_ self` is the same type as `&self`, so nothing is lost.
        render(quote! {
            pub trait IOk {
                fn go(&'_ self) -> BinderResult<()>;
            }
        });
    }

    /// A receiver's attribute is dropped by the re-render like any other.
    #[test]
    fn rejects_an_attribute_on_the_receiver() {
        for recv in [
            quote!(
                #[oneway]
                &self
            ),
            quote!(
                #[cfg(feature = "never")]
                &self
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    fn go(#recv) -> BinderResult<()>;
                }
            });
            assert!(err.contains("unsupported attribute"), "{recv}: {err}");
        }
    }

    /// As a return type, `Option<&str>` would silently become `Option<String>`.
    #[test]
    fn rejects_borrowed_return_inside_option() {
        let err = reject(quote! {
            pub trait IBad {
                fn go(&self) -> BinderResult<Option<&str>>;
            }
        });
        assert!(err.contains("borrow"), "{err}");
    }

    /// `@nullable` does not widen a `String`'s direction.
    #[test]
    fn rejects_out_nullable_string() {
        for decl in [
            quote!(
                fn go(&self, s: &mut Option<String>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, #[inout] s: &mut Option<String>) -> BinderResult<()>;
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains("`String` cannot be an"), "{err}");
        }
    }

    /// AOSP `GetArgumentAspect`: `IBinder` and an interface `in` only, a fd `in` or `inout`.
    #[test]
    fn rejects_the_directions_aidl_refuses_for_a_binder_or_fd() {
        for decl in [
            quote!(
                fn go(&self, v: &mut rsbinder::Strong<dyn IOther>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, v: &mut Option<rsbinder::Strong<dyn IOther>>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, #[inout] v: &mut rsbinder::Strong<dyn IOther>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, #[inout] v: &mut Option<rsbinder::SIBinder>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, v: &mut rsbinder::SIBinder) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, v: &mut Option<rsbinder::SIBinder>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, v: &mut rsbinder::ParcelFileDescriptor) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, v: &mut Option<rsbinder::ParcelFileDescriptor>) -> BinderResult<()>;
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(
                err.contains("parameter — `.aidl` passes it"),
                "{decl}: {err}"
            );
        }
        // The attribute that marked a non-`@nullable` `out` binder or fd has nothing left to mark.
        let err = reject(quote! {
            pub trait IBad {
                fn go(&self, #[nonnull] v: &mut Vec<rsbinder::SIBinder>) -> BinderResult<()>;
            }
        });
        assert!(err.contains("unsupported attribute"), "{err}");
        // A fd `inout`, and an array of either in any direction, are `.aidl` forms.
        render(quote! {
            pub trait IOk {
                fn a(&self, #[inout] v: &mut rsbinder::ParcelFileDescriptor) -> BinderResult<()>;
                fn b(&self, #[inout] v: &mut Option<rsbinder::ParcelFileDescriptor>)
                    -> BinderResult<()>;
                fn c(&self, v: &mut Vec<Option<rsbinder::Strong<dyn IOther>>>) -> BinderResult<()>;
                fn d(&self, #[inout] v: &mut Vec<rsbinder::SIBinder>) -> BinderResult<()>;
            }
        });
    }

    /// Each element of an out array needs a `Default` to be sized or started from.
    #[test]
    fn rejects_an_out_array_of_bare_binder_objects_or_fds() {
        for ty in [
            quote!(&mut Vec<rsbinder::ParcelFileDescriptor>),
            quote!(&mut Option<Vec<rsbinder::ParcelFileDescriptor>>),
            quote!(&mut Vec<rsbinder::Strong<dyn IOther>>),
            quote!(&mut [rsbinder::SIBinder; 3]),
            quote!(&mut [[rsbinder::ParcelFileDescriptor; 3]; 2]),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    fn go(&self, v: #ty) -> BinderResult<()>;
                }
            });
            assert!(err.contains("`Option<_>` elements"), "{ty}: {err}");
        }
        // `.aidl`'s non-nullable `inout` array is the bare form.
        render(quote! {
            pub trait IOk {
                fn a(&self, #[inout] v: &mut Vec<rsbinder::ParcelFileDescriptor>)
                    -> BinderResult<()>;
            }
        });
    }

    /// `macro_rules!` hands a `$t:ty` over wrapped in an invisible group.
    #[test]
    fn a_macro_interpolated_type_renders_like_the_bare_one() {
        let str_ty = proc_macro2::Group::new(proc_macro2::Delimiter::None, quote!(str));
        let ref_str = proc_macro2::Group::new(proc_macro2::Delimiter::None, quote!(&str));
        assert_same(
            r#"
interface IGolden10 {
    void take(in String s, in @nullable String t);
}
"#,
            "IGolden10",
            quote! {
                pub trait IGolden10 {
                    fn take(&self, s: &#str_ty, t: Option<#ref_str>) -> BinderResult<()>;
                }
            },
        );
    }

    /// A whole interpolated parameter or return type keeps its direction and shape.
    #[test]
    fn a_macro_interpolated_parameter_keeps_its_direction() {
        let vec_ty = proc_macro2::Group::new(proc_macro2::Delimiter::None, quote!(&mut Vec<i32>));
        let ret_ty =
            proc_macro2::Group::new(proc_macro2::Delimiter::None, quote!(BinderResult<()>));
        assert_same(
            r#"
interface IGolden11 {
    void fill(out int[] v);
    void bump(inout int[] v);
}
"#,
            "IGolden11",
            quote! {
                pub trait IGolden11 {
                    fn fill(&self, v: #vec_ty) -> #ret_ty;
                    fn bump(&self, #[inout] v: #vec_ty) -> #ret_ty;
                }
            },
        );
    }

    /// No wire form; rustc would otherwise blame generated tokens.
    #[test]
    fn rejects_argument_shapes_with_no_wire_form() {
        for (ty, needle) in [
            (quote!(()), "`()` has no wire form"),
            (quote!(dyn IOther), "trait object"),
            (quote!(&dyn IOther), "trait object"),
            (quote!(Option<&dyn IOther>), "trait object"),
            (quote!(&[()]), "`()` has no wire form"),
            (quote!(Vec<()>), "`()` has no wire form"),
            (quote!(&[dyn IOther]), "trait object"),
            (quote!(&mut [i32]), "`&mut [T]`"),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    fn go(&self, v: #ty) -> BinderResult<()>;
                }
            });
            assert!(err.contains(needle), "{ty}: {err}");
        }
    }

    /// `&[Option<i32>]` is the `Vec<Option<i32>>` shape, and as inexpressible.
    #[test]
    fn rejects_a_nullable_primitive_behind_a_slice_or_array() {
        for ty in [
            quote!(&[Option<i32>]),
            quote!([Option<i32>; 4]),
            // By value: `&Vec<T>` is refused ahead of this for its own reason.
            quote!(Vec<Option<i32>>),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    fn go(&self, v: #ty) -> BinderResult<()>;
                }
            });
            assert!(err.contains("cannot be nullable"), "{ty}: {err}");
        }
    }

    /// `rsbinder-aidl` refuses a holder in a signature, however wrapped.
    #[test]
    fn rejects_a_parcelable_holder_in_a_signature() {
        for decl in [
            quote!(
                fn go(&self, h: &rsbinder::ParcelableHolder) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, h: &[rsbinder::ParcelableHolder]) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self) -> BinderResult<rsbinder::ParcelableHolder>;
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains("`ParcelableHolder` cannot appear"), "{err}");
        }
    }

    /// A duplicate would collide in generated tokens, away from the user's span.
    #[test]
    fn rejects_duplicate_names() {
        let err = reject(quote! {
            pub trait IBad {
                fn go(&self, a: i32, a: i32) -> BinderResult<()>;
            }
        });
        assert!(err.contains("duplicate argument name `a`"), "{err}");

        // The `r#` is not part of the name: the templates add their own.
        let err = reject(quote! {
            pub trait IBad {
                fn go(&self, r#type: i32, r#type: i32) -> BinderResult<()>;
            }
        });
        assert!(err.contains("duplicate argument name `type`"), "{err}");

        let err = reject(quote! {
            pub trait IBad {
                fn go(&self) -> BinderResult<()>;
                fn go(&self, a: i32) -> BinderResult<()>;
            }
        });
        assert!(err.contains("duplicate method name `go`"), "{err}");
    }

    /// A generated trait item's name is taken for every signature, as on the `.aidl` path.
    #[test]
    fn rejects_a_method_named_like_a_generated_trait_item() {
        for name in [
            "descriptor",
            "getDefaultImpl",
            "setDefaultImpl",
            "dump",
            "as_binder",
        ] {
            let ident = syn::Ident::new(name, proc_macro2::Span::call_site());
            let err = reject(quote! {
                pub trait IBad {
                    fn #ident(&self, a: i32) -> BinderResult<()>;
                }
            });
            assert!(
                err.contains(&format!(
                    "method `{name}` collides with an item of the generated Rust trait"
                )),
                "{err}"
            );
        }
        // Raw spelling is the same name.
        let err = reject(quote! {
            pub trait IBad {
                fn r#dump(&self) -> BinderResult<()>;
            }
        });
        assert!(err.contains("method `dump` collides"), "{err}");
    }

    /// AOSP reserves these by signature, so a `.aidl` port would have to rename them.
    #[test]
    fn rejects_the_aidl_reserved_method_signatures() {
        for tokens in [
            quote! { pub trait IBad { fn asBinder(&self) -> BinderResult<()>; } },
            quote! { pub trait IBad { fn getInterfaceHash(&self) -> BinderResult<String>; } },
            quote! { pub trait IBad { fn getInterfaceVersion(&self) -> BinderResult<i32>; } },
            quote! { pub trait IBad { fn getTransactionName(&self, c: i32) -> BinderResult<String>; } },
        ] {
            let err = reject(tokens);
            assert!(err.contains("is reserved for internal use"), "{err}");
        }
        // Another signature is another method to AOSP.
        render(quote! {
            pub trait IOk {
                fn getInterfaceVersion(&self, a: i32) -> BinderResult<i32>;
                fn getTransactionName(&self) -> BinderResult<String>;
            }
        });
    }

    /// The receiver allows nothing; an empty allow-list must not render `understands only`.
    #[test]
    fn an_empty_allow_list_names_no_attribute() {
        let err = reject(quote! {
            pub trait IBad {
                fn go(#[allow(dead_code)] &self) -> BinderResult<()>;
            }
        });
        assert_eq!(
            err, "unsupported attribute; no attribute is supported here",
            "{err}"
        );
    }

    /// The descriptor is the wire name, so a second one is refused, not picked.
    #[test]
    fn rejects_a_repeated_descriptor() {
        let err = match syn::parse2::<Args>(quote!(descriptor = "a", descriptor = "b")) {
            Ok(_) => panic!("a repeated `descriptor` must be refused"),
            Err(e) => e.to_string(),
        };
        assert!(err.contains("more than once"), "{err}");
    }

    /// The re-render reads no attribute argument and no second type argument.
    #[test]
    fn rejects_what_the_re_render_would_drop() {
        let err = reject(quote! {
            pub trait IBad {
                fn go(&self) -> BinderResult<i32, String>;
            }
        });
        assert!(err.contains("exactly one type argument"), "{err}");

        for decl in [
            quote!(
                #[oneway(false)]
                fn go(&self) -> BinderResult<()>;
            ),
            quote!(
                #[oneway = "no"]
                fn go(&self) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, #[inout(no)] v: &mut Vec<i32>) -> BinderResult<()>;
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains("takes no arguments"), "{err}");
        }
    }

    /// `self::` would resolve inside the generated module, not the user's.
    #[test]
    fn rejects_self_paths() {
        // The non-canonical ones must not first be told a `self::` spelling to use.
        for decl in [
            quote!(
                fn go(&self, cfg: &self::Config) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, v: Vec<self::Cfg>) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self) -> BinderResult<Option<Vec<self::pair::Pair<Cfg>>>>;
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains("`self::`"), "{err}");
        }
    }

    /// `__Rsb*` names are the template's own; `crate::`-anchored paths stay legal.
    #[test]
    fn rejects_the_reserved_name_prefix() {
        for tokens in [
            quote! {
                pub trait __RsbPool {
                    fn go(&self) -> BinderResult<()>;
                }
            },
            quote! {
                pub trait IBad {
                    fn go(&self, v: &__RsbService) -> BinderResult<()>;
                }
            },
            quote! {
                pub trait IBad {
                    fn go(&self) -> BinderResult<Vec<__RsbRuntime>>;
                }
            },
            quote! {
                pub trait IBad {
                    fn go(&self, v: &rsbinder::Strong<dyn __RsbAsyncWrapper>) -> BinderResult<()>;
                }
            },
            quote! {
                pub trait IBad {
                    fn go(&self, #[inout] v: &mut [__RsbPool; 3]) -> BinderResult<()>;
                }
            },
        ] {
            let err = reject(tokens);
            assert!(err.contains("reserved"), "{err}");
        }
        render(quote! {
            pub trait IOk {
                fn go(&self, v: &crate::m::__RsbService) -> BinderResult<()>;
            }
        });
    }

    /// A `Self` outside the receiver makes the generated trait unusable as `dyn IFoo`.
    #[test]
    fn rejects_self_in_a_signature() {
        for decl in [
            quote!(
                fn go(&self, other: &Self) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self, v: &[Self]) -> BinderResult<()>;
            ),
            quote!(
                fn go(&self) -> BinderResult<Option<Self>>;
            ),
            quote!(
                fn go(&self, v: Vec<Self>) -> BinderResult<()>;
            ),
        ] {
            let err = reject(quote! {
                pub trait IBad {
                    #decl
                }
            });
            assert!(err.contains("cannot name `Self`"), "{err}");
        }
    }

    /// Matched structurally, so a qualified `Vec` carries the same length word.
    #[test]
    fn qualified_vec_is_still_a_length_carrying_out_vector() {
        let bare = render(quote! {
            pub trait IOut {
                fn fill(&self, values: &mut Vec<i32>) -> BinderResult<()>;
            }
        });
        let qualified = render(quote! {
            pub trait IOut {
                fn fill(&self, values: &mut std::vec::Vec<i32>) -> BinderResult<()>;
            }
        });
        assert!(bare.contains("write_slice_size"), "{bare}");
        assert!(
            qualified.contains("write_slice_size"),
            "a qualified `Vec` must still write the length word:\n{qualified}"
        );
        assert!(qualified.contains("resize_out_vec"), "{qualified}");
    }

    /// Same for `Option<Vec<T>>`, and for the guard that keeps a null fd off the wire.
    #[test]
    fn qualified_paths_keep_the_nullable_and_fd_guards() {
        let s = render(quote! {
            pub trait IOut {
                fn fill(&self, v: &mut core::option::Option<std::vec::Vec<i32>>)
                    -> BinderResult<()>;
            }
        });
        assert!(s.contains("resize_nullable_out_vec"), "{s}");

        let s = render(quote! {
            pub trait IOut {
                fn fds(
                    &self,
                    v: &mut std::vec::Vec<Option<rsbinder::ParcelFileDescriptor>>,
                ) -> BinderResult<()>;
            }
        });
        assert!(
            s.contains("iter().any(::core::option::Option::is_none)"),
            "{s}"
        );
    }

    /// A qualified nullable `in` borrows through as the bare `Option<&T>` does.
    #[test]
    fn qualified_nullable_in_arguments_borrow_through() {
        let s = render(quote! {
            pub trait IIn {
                fn a(&self, x: std::option::Option<&str>) -> BinderResult<()>;
                fn b(&self, x: std::option::Option<&Cfg>) -> BinderResult<()>;
                fn c(&self, x: core::option::Option<&[u8]>) -> BinderResult<()>;
            }
        });
        for (method, call) in [
            ("a", "_arg_x.as_deref()"),
            ("b", "_arg_x.as_ref()"),
            ("c", "_arg_x.as_deref()"),
        ] {
            assert!(
                s.contains(&format!("_service.r#{method}({call})")),
                "{method}: {s}"
            );
        }
    }

    /// The `Copy` assertion refuses a by-value parcelable; pinned here as rustc's wording moves.
    #[test]
    fn by_value_argument_is_asserted_copy() {
        let item: ItemTrait = syn::parse2(quote! {
            pub trait IBad {
                fn go(&self, mode: super::Mode::Mode) -> BinderResult<()>;
            }
        })
        .unwrap();
        let expanded = expand(&Args { descriptor: None }, &item)
            .expect("expand")
            .to_string();
        // Both the `Copy` bound and the asserted type, so neither can be weakened unnoticed.
        assert!(
            expanded.contains("T : :: core :: marker :: Copy"),
            "{expanded}"
        );
        assert!(
            expanded.contains("__rsbinder_assert_copy :: < super :: Mode :: Mode > ()"),
            "{expanded}"
        );
    }

    /// The assertion names signature types, so it must resolve them where the body does.
    #[test]
    fn copy_assertion_shares_the_generated_module_scope() {
        let item: ItemTrait = syn::parse2(quote! {
            pub trait IScoped {
                fn go(&self, mode: super::Mode::Mode) -> BinderResult<()>;
            }
        })
        .unwrap();
        let expanded = expand(&Args { descriptor: None }, &item).expect("expand");
        let file: syn::File = syn::parse2(expanded).expect("expansion parses");
        let module = file
            .items
            .iter()
            .find_map(|i| match i {
                syn::Item::Mod(m) => Some(m),
                _ => None,
            })
            .expect("generated module");
        let body = quote!(#module).to_string();
        assert!(body.contains("__rsbinder_assert_copy"), "{body}");
    }

    /// `#[doc(hidden)]` hides the module from docs, not from paths.
    #[test]
    fn generated_module_follows_the_trait_visibility() {
        let item: ItemTrait = syn::parse2(quote! {
            trait IPrivate {
                fn go(&self) -> BinderResult<()>;
            }
        })
        .unwrap();
        let expanded = expand(&Args { descriptor: None }, &item).expect("expand");
        let file: syn::File = syn::parse2(expanded).expect("expansion parses");
        let module = file
            .items
            .iter()
            .find_map(|i| match i {
                syn::Item::Mod(m) => Some(m),
                _ => None,
            })
            .expect("generated module");
        assert!(
            matches!(module.vis, syn::Visibility::Inherited),
            "a private trait must not get a `pub` module"
        );
    }

    /// `IFoo` and `Foo` share `BnFoo`; both declare the same marker, so the clash is E0428.
    #[test]
    fn interfaces_sharing_a_stem_declare_the_same_marker() {
        let marker = |tokens| {
            let item: ItemTrait = syn::parse2(tokens).unwrap();
            let expanded = expand(&Args { descriptor: None }, &item).expect("expand");
            let file: syn::File = syn::parse2(expanded).expect("expansion parses");
            file.items
                .iter()
                .find_map(|i| match i {
                    syn::Item::Const(c) => Some(c.ident.to_string()),
                    _ => None,
                })
                .expect("marker const")
        };
        let prefixed = marker(quote!(
            pub trait IFoo {
                fn go(&self) -> BinderResult<()>;
            }
        ));
        let bare = marker(quote!(
            pub trait Foo {
                fn go(&self) -> BinderResult<()>;
            }
        ));
        assert_eq!(prefixed, "__rsbinder_one_interface_per_stem_Foo");
        assert_eq!(prefixed, bare);
        // `Ifoo` keeps its `I` (AOSP `ClassName`), so it does not clash with `foo`.
        let kept = marker(quote!(
            pub trait Ifoo {
                fn go(&self) -> BinderResult<()>;
            }
        ));
        assert_eq!(kept, "__rsbinder_one_interface_per_stem_Ifoo");
    }
}