zerodds-lang-rules 1.0.0-rc.7.1

Maps the common AST onto the language CSTs through rules that are data, not code: seesaw v2 rule specifications, comparable and checkable.
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
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 ZeroDDS Contributors
//! An IDL `interface`, as a complete DDS-RPC 1.0 Rust binding: the
//! request and reply topic types of ยง7.5.1.1, a typed client and
//! service trait, and a dispatcher โ€” all runnable, not only declared.
//!
//! `adapter::interface` reads the interface; `emit::interface_cpp` and
//! `emit::interface_java` write declarations a peer's own runtime gives
//! a body to. This writes both halves: the topic types get a real
//! XCDR2 codec, hand-assembled with the same per-field writers
//! `crate::encode::rust_codec` uses for an ordinary `struct`, and the
//! client and the dispatcher are built over `zerodds_rpc::requester`
//! and `zerodds_rpc::replier` โ€” the crate this generated file has to
//! depend on, named in the preamble every generated interface carries.
//!
//! ## Why the topic types get a codec here and nowhere else
//!
//! C++, Java and TypeScript declare `Calculator_add_In` and stop: the
//! octets are a job for a type-support pass none of the three has
//! written (`emit::interface_cpp`'s own module doc says so). Rust's
//! generated client and service actually run โ€” `crates/rpc/tests/`
//! sends a request and reads a reply โ€” and a `Requester<TIn, TOut>`
//! needs `TIn: DdsType`. So this crosses the boundary `zerodds-rpc โ†’
//! zerodds-dcps โ†’ zerodds-lang-rules` warns about, deliberately: not by
//! making this *crate* depend on `zerodds-rpc` โ€” it still does not โ€”
//! but by writing Rust source that does, exactly as
//! `crates/zerodds-build/src/dds_type.rs` writes an `impl
//! zerodds_dcps::DdsType` for a type this crate declared.
//!
//! ## The wire layout
//!
//! DDS-RPC 1.0 ยง7.5.1.1's Basic Service Mapping: one request topic type
//! and one reply topic type per interface, each a `header` plus a
//! `data` union over every operation. `crates/rpc/src/codegen.rs` is
//! the data model this shape comes from; this crate cannot depend on
//! it (`zerodds-rpc` depends on `zerodds-dcps` depends on this crate),
//! so the shape is read off `adapter::interface::Service` directly, the
//! way `emit::interface_cpp` already does for C++.
//!
//! A union becomes a Rust `enum`, one variant per case plus a default
//! `UnknownOp(u8)` โ€” ยง7.5.1.1.6 rule 3 and ยง7.5.1.1.7 rule 3 โ€” and its
//! `encode`/`decode` write the `long` discriminator
//! [`interface::operation_hash`]/[`interface::exception_hash`] compute,
//! then delegate to the case payload's own codec. Every payload type โ€”
//! an `_In`, an `_Out`, a `_Result`, a raised exception โ€” gets exactly
//! that: an inherent `encode(&self, w: &mut Writer)` and `decode(r: &mut
//! Reader)`, member by member, through `crate::encode::write_value_to`
//! and `crate::encode::read_for` โ€” the same two functions
//! `crate::encode::rust_codec` calls for a declared `struct`.
//!
//! Every synthesized type is `@final`: no `DHEADER`, matching
//! `crates/rpc/src/common_types.rs`'s own choice for `RequestHeader`
//! and `ReplyHeader`, and matching the classic-CDR shape DDS-RPC 1.0
//! predates XTypes 1.3's extensibility kinds with. The encoding is
//! fixed to XCDR2 little-endian regardless of the file's own
//! `--encoding`/`--endian` โ€” [`rpc_layout_key`] โ€” because
//! `zerodds_rpc::requester::Requester::send_request_blocking` calls
//! `TIn::encode`, the `DdsType` bridge's un-suffixed method, which is
//! always that one cell.
//!
//! ## What this does not do
//!
//! It reads `@service(name = "โ€ฆ")`, `@DDSRequestTopic` and
//! `@DDSReplyTopic` (`annotated_topics_expr`) and hands the names to
//! `zerodds_rpc::requester::Requester::with_options` as
//! `AnnotatedTopics`; `crates/rpc/src/topic_naming.rs` composes the topic
//! names of ยง7.4.1 and ยง7.4.2 from them.

mod enhanced;
pub mod type_information;

use core::fmt;
use std::collections::BTreeSet;

use zerodds_ast::{
    Ast, ExceptionNode, ModuleNode, ParamDirection, PrimitiveKind, TypeKind, TypeNode,
};
use zerodds_ast_core::Id;
use zerodds_ast_layout::key::{Encoding, Endianness, LayoutKey};
use zerodds_lang_cst::common::{Doc, Ident, Literal, Path, Visibility};
use zerodds_lang_cst::rust;

use crate::adapter::cst::{MaterialiseError, data_derives, rust_type_of};
use crate::adapter::interface::{
    self, BindingError, InterfaceError, Operation, RETURN_MEMBER, Raise, Service,
};
use crate::encode::{EncodeError, MemberWrite, Position, read_for, write_of, write_value_to};

/// Why an interface did not become a Rust binding.
#[derive(Debug)]
pub enum RustInterfaceError {
    /// The interface itself did not reach the seam.
    Interface(InterfaceError),
    /// A referenced type has no Rust spelling.
    Materialise(MaterialiseError),
    /// A field's codec could not be built.
    Codec(EncodeError),
}

impl From<InterfaceError> for RustInterfaceError {
    fn from(error: InterfaceError) -> Self {
        Self::Interface(error)
    }
}
impl From<BindingError> for RustInterfaceError {
    fn from(error: BindingError) -> Self {
        match error {
            BindingError::Interface(error) => Self::Interface(error),
            BindingError::Materialise(error) => Self::Materialise(error),
            // Only the C++ column builds codecs through the seam; the
            // reason is kept.
            BindingError::Codec(reason) => Self::Materialise(MaterialiseError::UnknownType {
                type_name: format!("a codec: {reason}"),
            }),
        }
    }
}
impl From<MaterialiseError> for RustInterfaceError {
    fn from(error: MaterialiseError) -> Self {
        Self::Materialise(error)
    }
}
impl From<EncodeError> for RustInterfaceError {
    fn from(error: EncodeError) -> Self {
        Self::Codec(error)
    }
}

impl fmt::Display for RustInterfaceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Interface(error) => write!(f, "{error}"),
            Self::Materialise(error) => write!(f, "{error:?}"),
            Self::Codec(error) => write!(f, "{error}"),
        }
    }
}

/// The `LayoutKey` every synthesized topic type's codec is built under.
/// See the module doc.
#[must_use]
pub fn rpc_layout_key() -> LayoutKey {
    LayoutKey::data(Encoding::PlainCdr2, Endianness::Little)
}

/// The `LayoutKey` of the XCDR1 (classic CDR) codec of every synthesized
/// topic type, the second pair `CodecVariant::XCDR1` writes. DDS-RPC 1.0
/// ยง7.5.1.1: the Basic Service Mapping is for DDS 1.3.
#[must_use]
pub fn rpc_layout_key_xcdr1() -> LayoutKey {
    LayoutKey::data(Encoding::PlainCdr1, Endianness::Little)
}

/// Which of a topic type's two codec pairs a function writes or calls.
///
/// The XCDR2 pair has the bare names `encode`/`decode`; the XCDR1 pair
/// carries `crate::encode::SECONDARY_SUFFIX` (`encode_xcdr1`,
/// `decode_xcdr1`), as `crate::encode::rust_codec_pair` names the second
/// pair of a declared type, so a member that is a declared type calls the
/// pair of its own version.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CodecVariant {
    Xcdr2,
    Xcdr1,
}

impl CodecVariant {
    fn suffix(self) -> &'static str {
        match self {
            Self::Xcdr2 => "",
            Self::Xcdr1 => crate::encode::SECONDARY_SUFFIX,
        }
    }

    fn key(self) -> LayoutKey {
        match self {
            Self::Xcdr2 => rpc_layout_key(),
            Self::Xcdr1 => rpc_layout_key_xcdr1(),
        }
    }

    fn encode_name(self) -> String {
        format!("encode{}", self.suffix())
    }

    fn decode_name(self) -> String {
        format!("decode{}", self.suffix())
    }
}

/// The Rust declarations and runnable binding every interface of `ast`
/// produces, each paired with the module it belongs in so a caller can
/// fold it into the same tree `crate::adapter::cst::nest_by_module`
/// builds for everything else.
///
/// # Errors
/// [`RustInterfaceError`] โ€” the interface did not reach the seam, a
/// referenced type has no Rust spelling, or a field's codec could not
/// be built. Never a dropped operation, parameter, attribute or raised
/// exception.
pub fn rust_interface_pairs(
    ast: &Ast,
) -> Result<Vec<(Id<ModuleNode>, rust::Item)>, RustInterfaceError> {
    rust_interface_pairs_with(ast, interface::ServiceMapping::Basic)
}

/// [`rust_interface_pairs`] for the given service mapping.
///
/// [`interface::ServiceMapping::Enhanced`] writes the topic types of
/// DDS-RPC 1.0 ยง7.5.1.2 โ€” the `@Choice @Autoid` `Request` and `Reply`
/// and the `In`, `Out` and `Result` structures, with their PL_CDR2 codec
/// โ€” and a client and a dispatcher that use
/// `zerodds_rpc::endpoint_options::RpcMapping::Enhanced`.
///
/// # Errors
/// As [`rust_interface_pairs`].
pub fn rust_interface_pairs_with(
    ast: &Ast,
    mapping: interface::ServiceMapping,
) -> Result<Vec<(Id<ModuleNode>, rust::Item)>, RustInterfaceError> {
    let mut out = Vec::new();
    let capable = xcdr1_capable_types(ast);
    for service in interface::services(ast)? {
        if mapping.is_enhanced() {
            enhanced::declare(ast, &Service { mapping, ..service }, &mut out)?;
        } else {
            declare(ast, &service, &capable, &mut out)?;
        }
    }
    Ok(out)
}

/// The declared types that have an XCDR1 codec pair
/// (`crate::encode::rust_codec_pair` under [`rpc_layout_key_xcdr1`]).
/// `crate::generate` emits those pairs for a model with interfaces, and the
/// topic types' XCDR1 codec calls them.
#[must_use]
pub fn xcdr1_capable_types(ast: &Ast) -> BTreeSet<Id<TypeNode>> {
    ast.types()
        .filter(|(id, node)| {
            !node.name.is_empty()
                && crate::encode::has_codec(&node.kind)
                && crate::encode::rust_codec_pair(ast, *id, rpc_layout_key_xcdr1()).is_ok()
        })
        .map(|(id, _)| id)
        .collect()
}

/// The most distinct declared types one reachability walk visits. The
/// visited set bounds the recursion; past this many the walk answers
/// "not closed", which withholds the XCDR1 form and makes the Basic default
/// fail with an error rather than send wrong octets.
const MAX_REACHABLE_TYPES: usize = 4096;

/// Whether every declared type reachable from `target` has an XCDR1 pair.
///
/// zerodds-lint: recursion-depth 4096 (each type is entered once; the
/// visited set is capped at `MAX_REACHABLE_TYPES`)
pub(crate) fn type_closed(
    ast: &Ast,
    target: Id<TypeNode>,
    capable: &BTreeSet<Id<TypeNode>>,
    seen: &mut BTreeSet<Id<TypeNode>>,
) -> bool {
    if !seen.insert(target) {
        return true;
    }
    if seen.len() > MAX_REACHABLE_TYPES {
        return false;
    }
    let Ok(node) = ast.type_(target) else {
        return false;
    };
    if crate::encode::has_codec(&node.kind) && !capable.contains(&target) {
        return false;
    }
    let reaches = |reference: &zerodds_ast_core::Ref<TypeNode>,
                   seen: &mut BTreeSet<Id<TypeNode>>| {
        reference
            .resolved()
            .is_some_and(|id| type_closed(ast, id, capable, seen))
    };
    let member_closed = |member: Id<zerodds_ast::MemberNode>, seen: &mut BTreeSet<Id<TypeNode>>| {
        ast.member(member)
            .is_ok_and(|member| reaches(&member.type_, seen))
    };
    match &node.kind {
        TypeKind::Structure { base, members } => {
            base.as_ref().is_none_or(|base| reaches(base, seen))
                && members.iter().all(|m| member_closed(*m, seen))
        }
        TypeKind::Union {
            discriminator,
            cases,
            ..
        } => {
            reaches(discriminator, seen)
                && cases.iter().all(|case| {
                    ast.case(*case)
                        .is_ok_and(|case| member_closed(case.member, seen))
                })
        }
        TypeKind::Alias { aliased } => reaches(aliased, seen),
        TypeKind::Sequence { element, .. } | TypeKind::Array { element, .. } => {
            reaches(element, seen)
        }
        TypeKind::Map { key, value, .. } => reaches(key, seen) && reaches(value, seen),
        TypeKind::ValueBox { boxed } => reaches(boxed, seen),
        TypeKind::Valuetype { bases, state, .. } => {
            bases.iter().all(|b| reaches(b, seen)) && state.iter().all(|m| member_closed(*m, seen))
        }
        _ => true,
    }
}

fn fields_closed(ast: &Ast, fields: &[FieldSpec], capable: &BTreeSet<Id<TypeNode>>) -> bool {
    fields.iter().all(|field| match field {
        FieldSpec::Octet(_) => true,
        FieldSpec::Real(_, target) => type_closed(ast, *target, capable, &mut BTreeSet::new()),
    })
}

fn declare(
    ast: &Ast,
    service: &Service,
    capable: &BTreeSet<Id<TypeNode>>,
    out: &mut Vec<(Id<ModuleNode>, rust::Item)>,
) -> Result<(), RustInterfaceError> {
    let module = service.module;
    let ops = service.all_operations();

    // The exceptions this interface's operations raise, each declared
    // (as a plain struct, by `crate::adapter::cst`'s own walk of
    // `ast.exceptions()`) but with no codec of its own โ€” nothing before
    // this reads an exception outside a C++/Java header. One codec per
    // exception, deduplicated, in the exception's own module: two
    // operations that raise the same exception must not each get their
    // own `impl DivByZero`, which is `error[E0592]`.
    //
    // Each codec has a second pair for XCDR1 (classic CDR, the Basic
    // mapping's encoding, DDS-RPC 1.0 ยง7.5.1.1), written only where every
    // declared type it reaches has one: `xcdr1_ok` records which of them
    // does, and a topic type without an XCDR1 pair leaves the `DdsType`
    // XCDR1 methods at the trait's refusing defaults.
    let mut exception_ok: Vec<(Id<ExceptionNode>, bool)> = Vec::new();
    for raise in exceptions_of(&ops) {
        let exc_module = exception_module(ast, raise.id)?;
        out.push((exc_module, exception_codec_item(ast, raise.id)?));
        let ok = exception_fields_closed(ast, raise.id, capable)?;
        if ok {
            out.push((
                exc_module,
                exception_codec_item_with(ast, raise.id, CodecVariant::Xcdr1)?,
            ));
        }
        exception_ok.push((raise.id, ok));
    }

    let mut in_ok: Vec<bool> = Vec::new();
    let mut result_ok: Vec<bool> = Vec::new();
    for op in &ops {
        out.push((module, rust::Item::Struct(in_struct(ast, service, op)?)));
        let in_name = interface::in_struct_name(&service.name, &op.name);
        out.push((
            module,
            struct_codec_item(ast, module, &in_name, &in_fields(op))?,
        ));
        let ok = fields_closed(ast, &in_fields(op), capable);
        if ok {
            out.push((
                module,
                struct_codec_item_with(ast, module, &in_name, &in_fields(op), CodecVariant::Xcdr1)?,
            ));
        }
        in_ok.push(ok);
        out.push((module, rust::Item::Struct(out_struct(ast, service, op)?)));
        let out_name = interface::out_struct_name(&service.name, &op.name);
        out.push((
            module,
            struct_codec_item(ast, module, &out_name, &out_fields(op))?,
        ));
        let out_ok = fields_closed(ast, &out_fields(op), capable);
        if out_ok {
            out.push((
                module,
                struct_codec_item_with(
                    ast,
                    module,
                    &out_name,
                    &out_fields(op),
                    CodecVariant::Xcdr1,
                )?,
            ));
        }
        let raised_ok = op
            .raises
            .iter()
            .all(|raise| exception_ok.iter().any(|(id, ok)| *id == raise.id && *ok));
        result_ok.push(out_ok && raised_ok);
    }

    for (op, ok) in ops.iter().zip(&result_ok) {
        let (item, codec) = result_union(ast, module, service, op)?;
        out.push((module, item));
        out.push((module, codec));
        if *ok {
            out.push((
                module,
                union_codec_with(
                    &interface::result_union_name(&service.name, &op.name),
                    &result_union_cases(ast, module, service, op)?,
                    None,
                    CodecVariant::Xcdr1,
                )?,
            ));
        }
    }

    let (call_item, call_codec) = call_union(service, &ops)?;
    out.push((module, call_item));
    out.push((module, call_codec));
    let call_ok = in_ok.iter().all(|ok| *ok);
    if call_ok {
        out.push((
            module,
            union_codec_with(
                &interface::call_union_name(&service.name),
                &call_union_cases(service, &ops),
                Some(UNKNOWN_OP_VARIANT),
                CodecVariant::Xcdr1,
            )?,
        ));
    }

    let (return_item, return_codec) = return_union(service, &ops)?;
    out.push((module, return_item));
    out.push((module, return_codec));
    let return_ok = ops.iter().zip(&result_ok).all(|(_, ok)| *ok);
    if return_ok {
        out.push((
            module,
            union_codec_with(
                &interface::return_union_name(&service.name),
                &return_union_cases(service, &ops),
                Some(UNKNOWN_OP_VARIANT),
                CodecVariant::Xcdr1,
            )?,
        ));
    }

    out.push((module, rust::Item::Struct(request_struct(service))));
    out.push((module, rust::Item::Struct(reply_struct(service))));

    let exceptions = exceptions_of(&ops);
    out.push((
        module,
        rust::Item::Enum(error_enum(ast, module, service, &exceptions)?),
    ));

    // `zerodds_rpc::requester::Requester<TIn, TOut>` and
    // `zerodds_rpc::replier::Replier<TIn, TOut>` both require
    // `TIn/TOut: DdsType` โ€” the two types they are instantiated with
    // here are `{I}_Call` and `{I}_Return`, never the per-operation
    // payloads, which reach the wire only nested inside one of those
    // two.
    out.push((
        module,
        dds_type_impl(
            &interface::call_union_name(&service.name),
            &interface::call_union_name(&service.name),
            call_ok,
        ),
    ));
    out.push((
        module,
        dds_type_impl(
            &interface::return_union_name(&service.name),
            &interface::return_union_name(&service.name),
            return_ok,
        ),
    ));

    if service.is_remote() {
        out.push((module, rust::Item::Trait(service_trait(ast, service)?)));
        out.push((module, rust::Item::Struct(client_struct(ast, service)?)));
        out.push((module, client_impl(ast, service)?));
        out.push((module, rust::Item::Struct(dispatcher_struct(service))));
        for item in dispatcher_impl(ast, service)? {
            out.push((module, item));
        }
    }

    Ok(())
}

// == field description ===================================================

/// One field of a synthesized structure: either a real IDL type, or one
/// of the three placeholder octets ยง7.5.1.1.1 declares
/// (`UnusedMember`/`UnknownOperation`), which have no `Id<TypeNode>` to
/// read a writer off.
enum FieldSpec {
    Real(String, Id<TypeNode>),
    Octet(String),
}

fn in_fields(op: &Operation) -> Vec<FieldSpec> {
    in_fields_styled(op, interface::EmptyOperationStyle::DummyMember)
}

/// [`in_fields`] with the Enhanced mapping's choice for an operation that
/// has nothing to carry (ยง7.5.1.2.1.3): the `dummy` member, or no member.
fn in_fields_styled(op: &Operation, empty: interface::EmptyOperationStyle) -> Vec<FieldSpec> {
    let mut out: Vec<FieldSpec> = op
        .inputs()
        .map(|p| FieldSpec::Real(rust::escape_keyword(&p.name), p.type_))
        .collect();
    if out.is_empty() && empty == interface::EmptyOperationStyle::DummyMember {
        out.push(FieldSpec::Octet(interface::DUMMY_MEMBER.to_string()));
    }
    out
}

fn out_fields(op: &Operation) -> Vec<FieldSpec> {
    out_fields_styled(op, interface::EmptyOperationStyle::DummyMember)
}

/// [`out_fields`] with the Enhanced mapping's choice for an operation that
/// has nothing to carry.
fn out_fields_styled(op: &Operation, empty: interface::EmptyOperationStyle) -> Vec<FieldSpec> {
    let mut out: Vec<FieldSpec> = op
        .outputs()
        .map(|p| FieldSpec::Real(rust::escape_keyword(&p.name), p.type_))
        .collect();
    if let Some(returns) = op.returns {
        let taken: Vec<&str> = out
            .iter()
            .map(|f| match f {
                FieldSpec::Real(name, _) | FieldSpec::Octet(name) => name.as_str(),
            })
            .collect();
        out.push(FieldSpec::Real(return_member_name(&taken), returns));
    }
    if out.is_empty() && empty == interface::EmptyOperationStyle::DummyMember {
        out.push(FieldSpec::Octet(interface::DUMMY_MEMBER.to_string()));
    }
    out
}

/// DDS-RPC 1.0 ยง7.5.1.1.5 rule 3b's collision rule, restated for Rust:
/// an `out` parameter already named `return_` pushes the return value
/// to `return_1`, `return_2`, โ€ฆ.
fn return_member_name(taken: &[&str]) -> String {
    if !taken.contains(&RETURN_MEMBER) {
        return RETURN_MEMBER.to_string();
    }
    for n in 1..=i32::MAX {
        let candidate = format!("{RETURN_MEMBER}{n}");
        if !taken.contains(&candidate.as_str()) {
            return candidate;
        }
    }
    format!("{RETURN_MEMBER}_")
}

fn field(name: &str, type_: rust::Type, doc: &str) -> rust::Field {
    rust::Field {
        doc: Doc::line(doc),
        attrs: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new(name),
        type_,
    }
}

/// `#[allow(non_camel_case_types)]` โ€” every wire-named type this module
/// declares (`{I}_{op}_In`, `{I}_Call`, โ€ฆ) carries the spelling
/// DDS-RPC 1.0 ยง7.5.1.1.4-7 fixes, not Rust's naming convention; the
/// generated file answers the lint itself rather than asking a
/// consumer to.
fn allow_non_camel_case() -> rust::Attr {
    rust::Attr {
        path: Path::single("allow"),
        args: vec![rust::AttrArg::Word(Ident::new("non_camel_case_types"))],
    }
}

fn rust_field_type(
    ast: &Ast,
    from: Id<ModuleNode>,
    spec: &FieldSpec,
) -> Result<rust::Type, RustInterfaceError> {
    Ok(match spec {
        FieldSpec::Real(_, target) => rust_type_of(ast, from, Some(*target))?,
        FieldSpec::Octet(_) => rust::Type::Primitive(rust::Primitive::U8),
    })
}

fn struct_of(name: &str, fields: Vec<rust::Field>, doc: Doc) -> rust::Struct {
    rust::Struct {
        body_text: zerodds_lang_cst::common::BodyText::none(),
        doc,
        attrs: vec![allow_non_camel_case()],
        derives: data_derives(),
        visibility: Visibility::Public,
        name: Ident::new(name),
        generics: Vec::new(),
        body: rust::StructBody::Named(fields),
    }
}

fn in_struct(
    ast: &Ast,
    service: &Service,
    op: &Operation,
) -> Result<rust::Struct, RustInterfaceError> {
    let mut fields = Vec::new();
    for spec in in_fields_styled(op, service.mapping.empty_style()) {
        let type_ = rust_field_type(ast, service.module, &spec)?;
        let name = match &spec {
            FieldSpec::Real(name, _) | FieldSpec::Octet(name) => name.clone(),
        };
        let doc = field_doc(&spec);
        fields.push(field(&name, type_, &doc));
    }
    Ok(struct_of(
        &interface::in_struct_name(&service.name, &op.name),
        fields,
        Doc::line("The `in` and `inout` parameters of one call. DDS-RPC 1.0 ยง7.5.1.1.4."),
    ))
}

/// The doc one field of a synthesized structure carries โ€” the IDL
/// parameter it came from, or the placeholder rule that put it there.
fn field_doc(spec: &FieldSpec) -> String {
    match spec {
        FieldSpec::Real(name, _) => format!("The `{name}` parameter."),
        FieldSpec::Octet(name) => format!(
            "`{name}`: the operation carries nothing else here. DDS-RPC 1.0 ยง7.5.1.1.4 rule 3c / \
             ยง7.5.1.1.5 rule 3c."
        ),
    }
}

fn out_struct(
    ast: &Ast,
    service: &Service,
    op: &Operation,
) -> Result<rust::Struct, RustInterfaceError> {
    let mut fields = Vec::new();
    for spec in out_fields_styled(op, service.mapping.empty_style()) {
        let type_ = rust_field_type(ast, service.module, &spec)?;
        let name = match &spec {
            FieldSpec::Real(name, _) | FieldSpec::Octet(name) => name.clone(),
        };
        let doc = if name == RETURN_MEMBER || name.starts_with(RETURN_MEMBER) {
            "The operation's return value. DDS-RPC 1.0 ยง7.5.1.1.5 rule 3b.".to_string()
        } else {
            field_doc(&spec)
        };
        fields.push(field(&name, type_, &doc));
    }
    Ok(struct_of(
        &interface::out_struct_name(&service.name, &op.name),
        fields,
        Doc::line(
            "The return value and the `out`/`inout` parameters of one call. DDS-RPC 1.0 ยง7.5.1.1.5.",
        ),
    ))
}

fn request_struct(service: &Service) -> rust::Struct {
    struct_of(
        &interface::request_type_name(&service.name),
        vec![
            field(
                "header",
                rust::Type::named(Path::new(&["zerodds_rpc", "common_types", "RequestHeader"])),
                "The request header. DDS-RPC 1.0 ยง7.5.1.1.6 rule 2.",
            ),
            field(
                interface::DATA_MEMBER,
                rust::Type::named(Path::single(&interface::call_union_name(&service.name))),
                "The call, as a union over every operation. DDS-RPC 1.0 ยง7.5.1.1.6 rule 2.",
            ),
        ],
        Doc::lines(&[
            "The request topic type. DDS-RPC 1.0 ยง7.5.1.1.6.",
            "",
            "Declared for wire-shape parity with the C++ and Java bindings; \
             `zerodds_rpc::requester::Requester` frames the header itself \
             (`crates/rpc/src/wire_codec.rs`) and takes the `data` type โ€” \
             this interface's `_Call`/`_Return` โ€” as its own two type \
             parameters, so this type is never constructed by the \
             generated client or dispatcher.",
        ]),
    )
}

fn reply_struct(service: &Service) -> rust::Struct {
    struct_of(
        &interface::reply_type_name(&service.name),
        vec![
            field(
                "header",
                rust::Type::named(Path::new(&["zerodds_rpc", "common_types", "ReplyHeader"])),
                "The reply header. DDS-RPC 1.0 ยง7.5.1.1.7 rule 3.",
            ),
            field(
                interface::DATA_MEMBER,
                rust::Type::named(Path::single(&interface::return_union_name(&service.name))),
                "The outcome, as a union over every non-`oneway` operation. \
                 DDS-RPC 1.0 ยง7.5.1.1.7 rule 3.",
            ),
        ],
        Doc::line("The reply topic type. DDS-RPC 1.0 ยง7.5.1.1.7. See `Request`'s own doc."),
    )
}

// == codec ================================================================

fn position_for(ast: &Ast, target: Id<TypeNode>) -> Position {
    Position {
        behaviour: ast.effective_try_construct(None, Some(target)),
        written: None,
    }
}

fn member_write_with(
    ast: &Ast,
    from: Id<ModuleNode>,
    target: Id<TypeNode>,
    variant: CodecVariant,
) -> MemberWrite {
    write_of(
        ast,
        from,
        target,
        variant.key(),
        variant.suffix(),
        position_for(ast, target),
    )
}

/// The length code of the `EMHEADER` of a member of type `target`
/// (XTypes 1.3 ยง7.4.3.4.2) in the Enhanced Service Mapping's PL_CDR2 form.
///
/// The Rust codec decides it from the member's write form; the C++ and the
/// Java codec of the same structures ask here, so the three write the same
/// octets.
pub(crate) fn emheader_length_code(ast: &Ast, from: Id<ModuleNode>, target: Id<TypeNode>) -> u8 {
    enhanced::length_code(&member_write_with(ast, from, target, CodecVariant::Xcdr2))
}

fn self_field(name: &str) -> rust::Expr {
    rust::Expr::Field {
        receiver: Box::new(rust::Expr::Path(Path::single("self"))),
        name: Ident::new(name),
    }
}

/// One structure's `encode`/`decode`, member by member, through
/// [`write_value_to`] and [`read_for`] โ€” the same two functions
/// `crate::encode::rust_codec` calls for a declared `struct`. `@final`
/// throughout: no `DHEADER`, matching the module doc.
fn struct_codec_item(
    ast: &Ast,
    from: Id<ModuleNode>,
    type_name: &str,
    fields: &[FieldSpec],
) -> Result<rust::Item, RustInterfaceError> {
    struct_codec_item_with(ast, from, type_name, fields, CodecVariant::Xcdr2)
}

/// [`struct_codec_item`] for one of the two codec pairs.
fn struct_codec_item_with(
    ast: &Ast,
    from: Id<ModuleNode>,
    type_name: &str,
    fields: &[FieldSpec],
    variant: CodecVariant,
) -> Result<rust::Item, RustInterfaceError> {
    let mut encode_statements = Vec::new();
    let mut decode_statements = Vec::new();
    let mut struct_fields = Vec::new();
    for spec in fields {
        let (name, kind) = match spec {
            FieldSpec::Real(name, target) => {
                (name.clone(), member_write_with(ast, from, *target, variant))
            }
            FieldSpec::Octet(name) => (name.clone(), MemberWrite::Primitive(PrimitiveKind::Octet)),
        };
        encode_statements.push(write_value_to("w", &name, &kind, self_field(&name), false)?);
        decode_statements.push(rust::Statement::Let {
            name: Ident::new(&name),
            type_: None,
            value: Some(rust::Expr::Try(Box::new(read_for(&name, &kind)?))),
            mutable: false,
        });
        struct_fields.push((Ident::new(&name), rust::Expr::Path(Path::single(&name))));
    }
    if fields.is_empty() {
        // An `@Empty` structure (ยง7.5.1.2.1.3) writes and reads nothing; the
        // writer and the reader are still parameters.
        for (statements, name) in [(&mut encode_statements, "w"), (&mut decode_statements, "r")] {
            statements.push(rust::Statement::Let {
                name: Ident::new("_"),
                type_: None,
                value: Some(rust::Expr::Ref {
                    target: Box::new(rust::Expr::Path(Path::single(name))),
                    mutable: false,
                }),
                mutable: false,
            });
        }
    }
    encode_statements.push(rust::Statement::Tail(ok_unit()));
    decode_statements.push(rust::Statement::Tail(rust::Expr::Call {
        callee: Box::new(rust::Expr::Path(Path::single("Ok"))),
        args: vec![rust::Expr::StructLit {
            path: Path::single("Self"),
            fields: struct_fields,
            base: None,
        }],
    }));
    Ok(rust::Item::Impl(rust::Impl {
        doc: Doc::none(),
        attrs: Vec::new(),
        generics: Vec::new(),
        trait_: None,
        self_type: rust::Type::named(Path::single(type_name)),
        items: vec![
            encode_fn_item_named(&variant.encode_name(), type_name, encode_statements),
            decode_fn_item_named(&variant.decode_name(), type_name, decode_statements),
        ],
    }))
}

fn ok_unit() -> rust::Expr {
    rust::Expr::Call {
        callee: Box::new(rust::Expr::Path(Path::single("Ok"))),
        args: vec![rust::Expr::Tuple(Vec::new())],
    }
}

fn writer_ref_type() -> rust::Type {
    rust::Type::Ref {
        target: Box::new(rust::Type::named(Path::single("Writer"))),
        mutable: true,
        lifetime: None,
    }
}

fn reader_ref_type() -> rust::Type {
    rust::Type::Ref {
        target: Box::new(rust::Type::named(Path::single("Reader"))),
        mutable: true,
        lifetime: None,
    }
}

fn wire_error_result(ok: rust::Type) -> rust::Type {
    rust::Type::generic(
        Path::single("Result"),
        vec![ok, rust::Type::named(Path::single("WireError"))],
    )
}

fn encode_fn_item_named(
    name: &str,
    type_name: &str,
    statements: Vec<rust::Statement>,
) -> rust::Item {
    rust::Item::Function(rust::Function {
        doc: Doc::line(&format!(
            "Writes `{type_name}` to `w` with `crate::encode::rust_codec`'s CDR encoding."
        )),
        attrs: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new(name),
        generics: Vec::new(),
        params: vec![
            rust::Param {
                name: None,
                type_: rust::Type::unit(),
                receiver: Some(rust::Receiver::Ref),
            },
            rust::Param {
                name: Some(Ident::new("w")),
                type_: writer_ref_type(),
                receiver: None,
            },
        ],
        returns: Some(wire_error_result(rust::Type::unit())),
        body: Some(rust::Block { statements }),
    })
}

fn decode_fn_item_named(
    name: &str,
    type_name: &str,
    statements: Vec<rust::Statement>,
) -> rust::Item {
    rust::Item::Function(rust::Function {
        doc: Doc::line(&format!(
            "Reads a `{type_name}` from `r` with `crate::encode::rust_codec`'s CDR decoding."
        )),
        attrs: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new(name),
        generics: Vec::new(),
        params: vec![rust::Param {
            name: Some(Ident::new("r")),
            type_: reader_ref_type(),
            receiver: None,
        }],
        returns: Some(wire_error_result(rust::Type::named(Path::single("Self")))),
        body: Some(rust::Block { statements }),
    })
}

// -- exceptions -----------------------------------------------------------

fn exceptions_of(ops: &[Operation]) -> Vec<Raise> {
    let mut out: Vec<Raise> = Vec::new();
    for op in ops {
        for raise in &op.raises {
            if !out.iter().any(|seen| seen.id == raise.id) {
                out.push(raise.clone());
            }
        }
    }
    out
}

fn exception_module(
    ast: &Ast,
    id: Id<ExceptionNode>,
) -> Result<Id<ModuleNode>, RustInterfaceError> {
    let node = ast.exception(id).map_err(|_| InterfaceError::NoNode {
        kind: "exception",
        at: "the model".to_string(),
    })?;
    Ok(node.module)
}

/// The path to an exception's already-declared Rust struct, relative to
/// `from`. `crate::adapter::cst::relative_path` cannot be reused
/// directly โ€” it takes a `&TypeNode` and an exception is not one โ€” so
/// this walks the same shared-prefix logic over
/// `adapter::interface::module_chain`.
fn exception_path(
    ast: &Ast,
    from: Id<ModuleNode>,
    id: Id<ExceptionNode>,
) -> Result<Path, RustInterfaceError> {
    let node = ast.exception(id).map_err(|_| InterfaceError::NoNode {
        kind: "exception",
        at: "the model".to_string(),
    })?;
    relative_module_path(ast, from, node.module, &node.name)
}

/// A declared type's path as written from inside module `from`, given
/// only the module it sits in and its own name.
///
/// `crate::adapter::cst::relative_path` cannot be reused directly โ€” it
/// takes a `&TypeNode`, and neither an exception nor an interface (an
/// RPC trait's base) is one. Same logic, over
/// `adapter::interface::module_chain`.
fn relative_module_path(
    ast: &Ast,
    from: Id<ModuleNode>,
    target_module: Id<ModuleNode>,
    leaf: &str,
) -> Result<Path, RustInterfaceError> {
    let here = interface::module_chain(ast, from)?;
    let there = interface::module_chain(ast, target_module)?;
    let shared = here
        .iter()
        .zip(there.iter())
        .take_while(|(a, b)| a.0 == b.0)
        .count();
    let mut segments: Vec<String> = Vec::new();
    for _ in shared..here.len() {
        segments.push("super".to_string());
    }
    for (_, name) in there.iter().skip(shared) {
        segments.push(rust::escape_keyword(name));
    }
    segments.push(rust::escape_keyword(leaf));
    let borrowed: Vec<&str> = segments.iter().map(String::as_str).collect();
    Ok(Path::new(&borrowed))
}

fn exception_codec_item(
    ast: &Ast,
    id: Id<ExceptionNode>,
) -> Result<rust::Item, RustInterfaceError> {
    exception_codec_item_with(ast, id, CodecVariant::Xcdr2)
}

/// Whether every declared type an exception's members reach has an XCDR1
/// pair.
fn exception_fields_closed(
    ast: &Ast,
    id: Id<ExceptionNode>,
    capable: &BTreeSet<Id<TypeNode>>,
) -> Result<bool, RustInterfaceError> {
    let node = ast.exception(id).map_err(|_| InterfaceError::NoNode {
        kind: "exception",
        at: "the model".to_string(),
    })?;
    Ok(node.members.iter().all(|member| {
        ast.member(*member).is_ok_and(|member| {
            member
                .type_
                .resolved()
                .is_some_and(|target| type_closed(ast, target, capable, &mut BTreeSet::new()))
        })
    }))
}

fn exception_codec_item_with(
    ast: &Ast,
    id: Id<ExceptionNode>,
    variant: CodecVariant,
) -> Result<rust::Item, RustInterfaceError> {
    let node = ast.exception(id).map_err(|_| InterfaceError::NoNode {
        kind: "exception",
        at: "the model".to_string(),
    })?;
    let module = node.module;
    let mut fields = Vec::new();
    for member in &node.members {
        let member_node = ast.member(*member).map_err(|_| InterfaceError::NoNode {
            kind: "parameter",
            at: node.name.clone(),
        })?;
        let Some(target) = member_node.type_.resolved() else {
            return Err(InterfaceError::Unresolved {
                construct: "exception member type",
                at: format!("{}::{}", node.name, member_node.name),
            }
            .into());
        };
        fields.push(FieldSpec::Real(
            rust::escape_keyword(&member_node.name),
            target,
        ));
    }
    struct_codec_item_with(ast, module, &node.name, &fields, variant)
}

// == tagged unions =========================================================

/// One case of a tagged union: the enum variant name, the path to the
/// type its payload carries (already declared, with its own
/// `encode`/`decode`), the `long` discriminator DDS-RPC 1.0 assigns it,
/// and a doc line.
///
/// The payload is a [`Path`] and not a [`rust::Type`]: every case here
/// is a named struct or a named union, never a primitive or a
/// collection, and keeping the path lets [`decode_case_body`] build
/// `<Path>::decode(r)` without taking a named type apart again to find
/// out what it already is.
struct UnionCase {
    variant: String,
    payload: Path,
    discriminator: i32,
    doc: String,
}

/// `${I}_Call`, `${I}_Return` or `${I}_${op}_Result` as a Rust `enum`,
/// plus its `encode`/`decode`.
///
/// `default_variant` is `Some(name)` for the `unknownOp` case DDS-RPC
/// 1.0 ยง7.5.1.1.6 rule 3 and ยง7.5.1.1.7 rule 3 both require on the
/// `Call` and `Return` unions; `None` for the per-operation `Result`
/// union of ยง7.5.1.1.5, which has no such case โ€” an unrecognised
/// discriminator there is refused on decode rather than defaulted,
/// because there is no spec-given value to construct.
fn tagged_union(
    name: &str,
    doc: Doc,
    cases: Vec<UnionCase>,
    default_variant: Option<&str>,
) -> Result<(rust::Item, rust::Item), RustInterfaceError> {
    let mut variants = Vec::new();
    for case in &cases {
        variants.push(rust::Variant {
            doc: Doc::line(&case.doc),
            attrs: Vec::new(),
            name: Ident::new(&case.variant),
            body: rust::VariantBody::Tuple(vec![rust::Type::named(case.payload.clone())]),
            discriminant: None,
        });
    }
    if let Some(default_variant) = default_variant {
        variants.push(rust::Variant {
            doc: Doc::line(
                "The default case: a discriminator this binding does not recognise. \
                 DDS-RPC 1.0 ยง7.5.1.1.6 rule 3 / ยง7.5.1.1.7 rule 3.",
            ),
            attrs: Vec::new(),
            name: Ident::new(default_variant),
            body: rust::VariantBody::Tuple(vec![rust::Type::Primitive(rust::Primitive::U8)]),
            discriminant: None,
        });
    }
    let item = rust::Item::Enum(rust::Enum {
        doc,
        attrs: vec![allow_non_camel_case()],
        derives: data_derives(),
        visibility: Visibility::Public,
        name: Ident::new(name),
        generics: Vec::new(),
        variants,
    });

    let codec = union_codec_with(name, &cases, default_variant, CodecVariant::Xcdr2)?;
    Ok((item, codec))
}

/// The `encode`/`decode` pair of a tagged union for one of the two codec
/// pairs: the `long` discriminator, then the case payload's own pair of
/// the same version.
fn union_codec_with(
    name: &str,
    cases: &[UnionCase],
    default_variant: Option<&str>,
    variant: CodecVariant,
) -> Result<rust::Item, RustInterfaceError> {
    let mut encode_arms = Vec::new();
    let mut decode_arms = Vec::new();
    for case in cases {
        encode_arms.push(rust::MatchArm {
            pattern: rust::Pattern::TupleStruct {
                path: Path::new(&["Self", &case.variant]),
                elements: vec![rust::Pattern::Binding(Ident::new("value"))],
            },
            guard: None,
            body: encode_case_body(case.discriminator, "value", variant)?,
        });
        decode_arms.push(rust::MatchArm {
            pattern: rust::Pattern::Literal(Literal::int(i128::from(case.discriminator))),
            guard: None,
            body: decode_case_body(&case.variant, &case.payload, variant),
        });
    }
    if let Some(default_variant) = default_variant {
        encode_arms.push(rust::MatchArm {
            pattern: rust::Pattern::TupleStruct {
                path: Path::new(&["Self", default_variant]),
                elements: vec![rust::Pattern::Binding(Ident::new("value"))],
            },
            guard: None,
            body: encode_default_body("value")?,
        });
        decode_arms.push(rust::MatchArm {
            pattern: rust::Pattern::Wildcard,
            guard: None,
            body: decode_default_body(default_variant)?,
        });
    } else {
        decode_arms.push(rust::MatchArm {
            pattern: rust::Pattern::Wildcard,
            guard: None,
            body: refused_expr("an unrecognised DDS-RPC 1.0 ยง7.5.1.1.5 Result discriminator"),
        });
    }

    let encode_statements = vec![rust::Statement::Tail(rust::Expr::Match {
        scrutinee: Box::new(rust::Expr::Path(Path::single("self"))),
        arms: encode_arms,
    })];
    let decode_statements = vec![
        rust::Statement::Let {
            name: Ident::new("disc"),
            type_: Some(rust::Type::Primitive(rust::Primitive::I32)),
            value: Some(rust::Expr::Try(Box::new(read_discriminator()?))),
            mutable: false,
        },
        rust::Statement::Tail(rust::Expr::Match {
            scrutinee: Box::new(rust::Expr::Path(Path::single("disc"))),
            arms: decode_arms,
        }),
    ];
    let codec = rust::Item::Impl(rust::Impl {
        doc: Doc::none(),
        attrs: Vec::new(),
        generics: Vec::new(),
        trait_: None,
        self_type: rust::Type::named(Path::single(name)),
        items: vec![
            encode_fn_item_named(&variant.encode_name(), name, encode_statements),
            decode_fn_item_named(&variant.decode_name(), name, decode_statements),
        ],
    });
    Ok(codec)
}

/// `w.write_i32(&value)?` in shape but never fallible in practice: an
/// `Int32` write never refuses. [`write_value_to`] is still called
/// through โ€” not hand-assembled โ€” so a change to how the runtime writes
/// an `Int32` reaches the discriminator the same call reaches every
/// other `Int32` member through, and the `EncodeError` it could in
/// principle answer with is reported rather than assumed away.
fn discriminator_write(value: rust::Expr) -> Result<rust::Statement, RustInterfaceError> {
    Ok(write_value_to(
        "w",
        "_d",
        &MemberWrite::Primitive(PrimitiveKind::Int32),
        value,
        false,
    )?)
}

fn read_discriminator() -> Result<rust::Expr, RustInterfaceError> {
    Ok(read_for(
        "_d",
        &MemberWrite::Primitive(PrimitiveKind::Int32),
    )?)
}

fn encode_case_body(
    discriminator: i32,
    binding: &str,
    variant: CodecVariant,
) -> Result<rust::Expr, RustInterfaceError> {
    Ok(rust::Expr::Block(rust::Block {
        statements: vec![
            discriminator_write(rust::Expr::Literal(Literal::int(i128::from(discriminator))))?,
            rust::Statement::Tail(rust::Expr::MethodCall {
                receiver: Box::new(rust::Expr::Path(Path::single(binding))),
                method: Ident::new(&variant.encode_name()),
                args: vec![rust::Expr::Path(Path::single("w"))],
            }),
        ],
    }))
}

fn encode_default_body(binding: &str) -> Result<rust::Expr, RustInterfaceError> {
    Ok(rust::Expr::Block(rust::Block {
        statements: vec![
            discriminator_write(rust::Expr::Literal(Literal::int(0)))?,
            write_value_to(
                "w",
                "unknown_op",
                &MemberWrite::Primitive(PrimitiveKind::Octet),
                rust::Expr::Path(Path::single(binding)),
                true,
            )?,
            rust::Statement::Tail(ok_unit()),
        ],
    }))
}

fn decode_case_body(variant: &str, payload: &Path, codec: CodecVariant) -> rust::Expr {
    rust::Expr::Call {
        callee: Box::new(rust::Expr::Path(Path::single("Ok"))),
        args: vec![rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(Path::new(&["Self", variant]))),
            args: vec![rust::Expr::Try(Box::new(rust::Expr::Call {
                callee: Box::new(rust::Expr::Path(payload.join(&codec.decode_name()))),
                args: vec![rust::Expr::Path(Path::single("r"))],
            }))],
        }],
    }
}

fn decode_default_body(default_variant: &str) -> Result<rust::Expr, RustInterfaceError> {
    Ok(rust::Expr::Call {
        callee: Box::new(rust::Expr::Path(Path::single("Ok"))),
        args: vec![rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(Path::new(&["Self", default_variant]))),
            args: vec![rust::Expr::Try(Box::new(read_for(
                "unknown_op",
                &MemberWrite::Primitive(PrimitiveKind::Octet),
            )?))],
        }],
    })
}

fn refused_expr(why: &str) -> rust::Expr {
    rust::Expr::Call {
        callee: Box::new(rust::Expr::Path(Path::single("Err"))),
        args: vec![rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(Path::new(&["WireError", "refused"]))),
            args: vec![
                rust::Expr::MethodCall {
                    receiver: Box::new(rust::Expr::Path(Path::single("r"))),
                    method: Ident::new("position"),
                    args: Vec::new(),
                },
                rust::Expr::Literal(Literal::string(why)),
            ],
        }],
    }
}

// -- Result, Call, Return --------------------------------------------------

fn result_union(
    ast: &Ast,
    module: Id<ModuleNode>,
    service: &Service,
    op: &Operation,
) -> Result<(rust::Item, rust::Item), RustInterfaceError> {
    let cases = result_union_cases(ast, module, service, op)?;
    let name = interface::result_union_name(&service.name, &op.name);
    tagged_union(
        &name,
        Doc::line(&format!(
            "The outcome of `{}`. DDS-RPC 1.0 ยง7.5.1.1.5.",
            op.name
        )),
        cases,
        None,
    )
}

/// The cases of `${I}_${op}_Result`.
fn result_union_cases(
    ast: &Ast,
    module: Id<ModuleNode>,
    service: &Service,
    op: &Operation,
) -> Result<Vec<UnionCase>, RustInterfaceError> {
    let mut cases = vec![UnionCase {
        variant: "Ok".to_string(),
        payload: Path::single(&interface::out_struct_name(&service.name, &op.name)),
        discriminator: interface::RETCODE_OK,
        doc: "`dds::RETCODE_OK`. DDS-RPC 1.0 ยง7.5.1.1.5 rule 3a.".to_string(),
    }];
    for raise in &op.raises {
        cases.push(UnionCase {
            variant: rust::escape_keyword(&raise.name),
            payload: exception_path(ast, module, raise.id)?,
            discriminator: interface::exception_hash(&raise.scoped_name),
            doc: format!("The `{}` case. DDS-RPC 1.0 ยง7.5.1.1.5 rule 5.", raise.name),
        });
    }
    Ok(cases)
}

fn exception_type(
    ast: &Ast,
    from: Id<ModuleNode>,
    id: Id<ExceptionNode>,
) -> Result<rust::Type, RustInterfaceError> {
    Ok(rust::Type::named(exception_path(ast, from, id)?))
}

fn call_union(
    service: &Service,
    ops: &[Operation],
) -> Result<(rust::Item, rust::Item), RustInterfaceError> {
    let cases = call_union_cases(service, ops);
    tagged_union(
        &interface::call_union_name(&service.name),
        Doc::line("The request union over every operation. DDS-RPC 1.0 ยง7.5.1.1.6."),
        cases,
        Some(UNKNOWN_OP_VARIANT),
    )
}

/// The cases of `${I}_Call`.
fn call_union_cases(service: &Service, ops: &[Operation]) -> Vec<UnionCase> {
    ops.iter()
        .map(|op| UnionCase {
            variant: variant_name(&op.name),
            payload: Path::single(&interface::in_struct_name(&service.name, &op.name)),
            discriminator: interface::operation_hash(&op.name),
            doc: format!("`{}`. DDS-RPC 1.0 ยง7.5.1.1.6 rule 5.", op.name),
        })
        .collect()
}

fn return_union(
    service: &Service,
    ops: &[Operation],
) -> Result<(rust::Item, rust::Item), RustInterfaceError> {
    let cases = return_union_cases(service, ops);
    tagged_union(
        &interface::return_union_name(&service.name),
        Doc::line("The reply union. DDS-RPC 1.0 ยง7.5.1.1.7."),
        cases,
        Some(UNKNOWN_OP_VARIANT),
    )
}

/// The cases of `${I}_Return`.
fn return_union_cases(service: &Service, ops: &[Operation]) -> Vec<UnionCase> {
    ops.iter()
        .map(|op| UnionCase {
            variant: variant_name(&op.name),
            payload: Path::single(&interface::result_union_name(&service.name, &op.name)),
            discriminator: interface::operation_hash(&op.name),
            doc: format!("`{}`. DDS-RPC 1.0 ยง7.5.1.1.7 rule 5b.", op.name),
        })
        .collect()
}

/// The enum variant DDS-RPC 1.0's `unknownOp` default case takes in
/// this binding. `crate::adapter::interface::UNKNOWN_OP_MEMBER` is the
/// wire member name the C++ and Java bindings spell; this is its Rust
/// variant spelling, named once so the `Call` and `Return` unions agree
/// with each other and with `dispatcher_impl`.
const UNKNOWN_OP_VARIANT: &str = "UnknownOp";

/// The variant an Enhanced `Result` choice holds a member id it does not
/// know in: an exception member added by a newer version of the
/// interface (DDS-RPC 1.0 ยง7.7.2.5.6).
const UNKNOWN_EX_VARIANT: &str = "UnknownEx";

/// A PascalCase enum variant from an IDL name. `get_memory` becomes
/// `GetMemory`; a name that is already one word capitalises its first
/// letter and keeps the rest, so `add` becomes `Add`.
fn variant_name(name: &str) -> String {
    let mut out = String::new();
    for segment in name.split('_') {
        let mut chars = segment.chars();
        if let Some(first) = chars.next() {
            out.extend(first.to_uppercase());
            out.extend(chars);
        }
    }
    if out.is_empty() {
        out.push_str("Op");
    }
    out
}

fn field_expr(receiver: &str, field_name: &str) -> rust::Expr {
    rust::Expr::Field {
        receiver: Box::new(rust::Expr::Path(Path::single(receiver))),
        name: Ident::new(field_name),
    }
}

fn field_vis(name: &str, type_: rust::Type, visibility: Visibility, doc: &str) -> rust::Field {
    rust::Field {
        doc: Doc::line(doc),
        attrs: Vec::new(),
        visibility,
        name: Ident::new(name),
        type_,
    }
}

fn error_type_name(service: &Service) -> String {
    format!("{}Error", service.name)
}

// == DdsType bridge ========================================================

/// `impl zerodds_dcps::dds_type::DdsType for {type_name}`, over the
/// inherent `encode`/`decode` [`struct_codec_item`] and [`tagged_union`]
/// both already give every synthesized type โ€” the same bridge
/// `crates/zerodds-build/src/dds_type.rs` writes for a declared
/// `struct`, at the one XCDR2-little-endian cell
/// `zerodds_rpc::requester::Requester::send_request_blocking` reads
/// (`TIn::encode`, never `encode_be`), so only the trait's two required
/// methods are given โ€” every other one keeps the trait's own refusing
/// default.
/// A `DdsType` impl for a type declared as `type_name` and named in DDS
/// `dds_name`: a structure in an IDL module is declared by its simple name
/// and named in DDS by its scoped one.
pub(crate) fn dds_type_impl(type_name: &str, dds_name: &str, xcdr1: bool) -> rust::Item {
    let type_name_const = rust::Item::Const(rust::Const {
        doc: Doc::line(
            "Informational only: `zerodds_rpc::requester::Requester` never \
             registers this as a DDS topic type โ€” it frames the request/reply \
             header itself and writes the sample through `DdsType::encode` \
             directly. See `crates/rpc/src/wire_codec.rs`.",
        ),
        attrs: Vec::new(),
        visibility: Visibility::Private,
        name: Ident::new("TYPE_NAME"),
        type_: rust::Type::Ref {
            target: Box::new(rust::Type::Primitive(rust::Primitive::Str)),
            mutable: false,
            lifetime: Some(Ident::new("static")),
        },
        value: rust::Expr::Literal(Literal::string(dds_name)),
    });

    let encode_fn = rust::Item::Function(rust::Function {
        doc: Doc::none(),
        attrs: Vec::new(),
        visibility: Visibility::Private,
        name: Ident::new("encode"),
        generics: Vec::new(),
        params: vec![
            rust::Param {
                name: None,
                type_: rust::Type::unit(),
                receiver: Some(rust::Receiver::Ref),
            },
            rust::Param {
                name: Some(Ident::new("out")),
                type_: rust::Type::Ref {
                    target: Box::new(rust::Type::generic(
                        Path::single("Vec"),
                        vec![rust::Type::Primitive(rust::Primitive::U8)],
                    )),
                    mutable: true,
                    lifetime: None,
                },
                receiver: None,
            },
        ],
        returns: Some(rust::Type::generic(
            Path::single("Result"),
            vec![
                rust::Type::unit(),
                rust::Type::named(Path::new(&["zerodds_dcps", "dds_type", "EncodeError"])),
            ],
        )),
        body: Some(rust::Block {
            statements: vec![
                rust::Statement::Let {
                    name: Ident::new("w"),
                    type_: None,
                    value: Some(rust::Expr::Call {
                        callee: Box::new(rust::Expr::Path(Path::new(&[
                            "zerodds_wire",
                            "Writer",
                            "with_max_align",
                        ]))),
                        args: vec![
                            rust::Expr::Path(Path::new(&["zerodds_wire", "Endianness", "Little"])),
                            rust::Expr::Literal(Literal::int(4)),
                        ],
                    }),
                    mutable: true,
                },
                rust::Statement::Semi(rust::Expr::Try(Box::new(rust::Expr::Call {
                    callee: Box::new(rust::Expr::Path(Path::new(&["Self", "encode"]))),
                    args: vec![
                        rust::Expr::Path(Path::single("self")),
                        rust::Expr::Ref {
                            target: Box::new(rust::Expr::Path(Path::single("w"))),
                            mutable: true,
                        },
                    ],
                }))),
                rust::Statement::Semi(rust::Expr::MethodCall {
                    receiver: Box::new(rust::Expr::Path(Path::single("out"))),
                    method: Ident::new("extend_from_slice"),
                    args: vec![rust::Expr::Ref {
                        target: Box::new(rust::Expr::MethodCall {
                            receiver: Box::new(rust::Expr::Path(Path::single("w"))),
                            method: Ident::new("finish"),
                            args: Vec::new(),
                        }),
                        mutable: false,
                    }],
                }),
                rust::Statement::Tail(ok_unit()),
            ],
        }),
    });

    let decode_fn = rust::Item::Function(rust::Function {
        doc: Doc::none(),
        attrs: Vec::new(),
        visibility: Visibility::Private,
        name: Ident::new("decode"),
        generics: Vec::new(),
        params: vec![rust::Param {
            name: Some(Ident::new("bytes")),
            type_: rust::Type::Ref {
                target: Box::new(rust::Type::Slice(Box::new(rust::Type::Primitive(
                    rust::Primitive::U8,
                )))),
                mutable: false,
                lifetime: None,
            },
            receiver: None,
        }],
        returns: Some(rust::Type::generic(
            Path::single("Result"),
            vec![
                rust::Type::named(Path::single("Self")),
                rust::Type::named(Path::new(&["zerodds_dcps", "dds_type", "DecodeError"])),
            ],
        )),
        body: Some(rust::Block {
            statements: vec![
                rust::Statement::Let {
                    name: Ident::new("r"),
                    type_: None,
                    value: Some(rust::Expr::Call {
                        callee: Box::new(rust::Expr::Path(Path::new(&[
                            "zerodds_wire",
                            "Reader",
                            "with_max_align",
                        ]))),
                        args: vec![
                            rust::Expr::Path(Path::single("bytes")),
                            rust::Expr::Path(Path::new(&["zerodds_wire", "Endianness", "Little"])),
                            rust::Expr::Literal(Literal::int(4)),
                        ],
                    }),
                    mutable: true,
                },
                rust::Statement::Tail(rust::Expr::Call {
                    callee: Box::new(rust::Expr::Path(Path::single("Ok"))),
                    args: vec![rust::Expr::Try(Box::new(rust::Expr::Call {
                        callee: Box::new(rust::Expr::Path(Path::new(&["Self", "decode"]))),
                        args: vec![rust::Expr::Ref {
                            target: Box::new(rust::Expr::Path(Path::single("r"))),
                            mutable: true,
                        }],
                    }))],
                }),
            ],
        }),
    });

    rust::Item::Impl(rust::Impl {
        doc: Doc::none(),
        attrs: Vec::new(),
        generics: Vec::new(),
        trait_: Some(rust::Type::named(Path::new(&[
            "zerodds_dcps",
            "dds_type",
            "DdsType",
        ]))),
        self_type: rust::Type::named(Path::single(type_name)),
        items: {
            let mut items = vec![type_name_const, encode_fn, decode_fn];
            // The XCDR1 methods only for a type that has the XCDR1 pair:
            // otherwise they keep the trait's refusing defaults, so a
            // Basic endpoint on classic CDR says why it cannot send.
            if xcdr1 {
                items.extend(continuing_codec_fns());
            }
            items
        },
    })
}

/// `zerodds_dcps::dds_type::DdsType::{encode_xcdr1, decode_xcdr1,
/// encode_continuing, decode_continuing}` for a topic type.
///
/// DDS-RPC 1.0 ยง7.5.1.1: the Basic Service Mapping targets DDS 1.3, which
/// has classic CDR (XCDR1) only, where an 8-octet member aligns to 8 and
/// not to 4. The same inherent `encode`/`decode` write both โ€” the writer's
/// alignment cap is the whole difference for a `@final` type โ€” and the
/// `continuing` pair starts them at the offset the type has inside the
/// sample, behind the `RequestHeader` or `ReplyHeader`, so the alignment is
/// the sample's.
fn continuing_codec_fns() -> Vec<rust::Item> {
    fn path(parts: &[&str]) -> rust::Expr {
        rust::Expr::Path(Path::new(parts))
    }
    fn call(parts: &[&str], args: Vec<rust::Expr>) -> rust::Expr {
        rust::Expr::Call {
            callee: Box::new(path(parts)),
            args,
        }
    }
    fn local(name: &str) -> rust::Expr {
        rust::Expr::Path(Path::single(name))
    }
    fn mut_ref(name: &str) -> rust::Expr {
        rust::Expr::Ref {
            target: Box::new(local(name)),
            mutable: true,
        }
    }
    fn let_(name: &str, value: rust::Expr, mutable: bool) -> rust::Statement {
        rust::Statement::Let {
            name: Ident::new(name),
            type_: None,
            value: Some(value),
            mutable,
        }
    }
    fn method(receiver: rust::Expr, name: &str, args: Vec<rust::Expr>) -> rust::Expr {
        rust::Expr::MethodCall {
            receiver: Box::new(receiver),
            method: Ident::new(name),
            args,
        }
    }
    fn lit(n: i128) -> rust::Expr {
        rust::Expr::Literal(Literal::int(n))
    }
    let little = || path(&["zerodds_wire", "Endianness", "Little"]);
    let self_param = rust::Param {
        name: None,
        type_: rust::Type::unit(),
        receiver: Some(rust::Receiver::Ref),
    };
    let bytes_param = |name: &str| rust::Param {
        name: Some(Ident::new(name)),
        type_: rust::Type::Ref {
            target: Box::new(rust::Type::Slice(Box::new(rust::Type::Primitive(
                rust::Primitive::U8,
            )))),
            mutable: false,
            lifetime: None,
        },
        receiver: None,
    };
    let vec_u8_mut = rust::Type::Ref {
        target: Box::new(rust::Type::generic(
            Path::single("Vec"),
            vec![rust::Type::Primitive(rust::Primitive::U8)],
        )),
        mutable: true,
        lifetime: None,
    };
    let bool_param = |name: &str| rust::Param {
        name: Some(Ident::new(name)),
        type_: rust::Type::Primitive(rust::Primitive::Bool),
        receiver: None,
    };
    let encode_result = || {
        rust::Type::generic(
            Path::single("Result"),
            vec![
                rust::Type::unit(),
                rust::Type::named(Path::new(&["zerodds_dcps", "dds_type", "EncodeError"])),
            ],
        )
    };
    let decode_result = || {
        rust::Type::generic(
            Path::single("Result"),
            vec![
                rust::Type::named(Path::single("Self")),
                rust::Type::named(Path::new(&["zerodds_dcps", "dds_type", "DecodeError"])),
            ],
        )
    };
    let function = |name: &str,
                    params: Vec<rust::Param>,
                    returns: rust::Type,
                    statements: Vec<rust::Statement>| {
        rust::Item::Function(rust::Function {
            doc: Doc::none(),
            attrs: Vec::new(),
            visibility: Visibility::Private,
            name: Ident::new(name),
            generics: Vec::new(),
            params,
            returns: Some(returns),
            body: Some(rust::Block { statements }),
        })
    };
    // `if xcdr1 { 8 } else { 4 }`: the alignment cap of the stream.
    let cap = || rust::Expr::If {
        condition: Box::new(local("xcdr1")),
        then: rust::Block {
            statements: vec![rust::Statement::Tail(lit(8))],
        },
        otherwise: Some(rust::Block {
            statements: vec![rust::Statement::Tail(lit(4))],
        }),
    };

    // The inherent pair of the version: `encode_xcdr1` for classic CDR,
    // `encode` for XCDR2.
    let by_version = |xcdr1_fn: &str, xcdr2_fn: &str, args: Vec<rust::Expr>| rust::Expr::If {
        condition: Box::new(local("xcdr1")),
        then: rust::Block {
            statements: vec![rust::Statement::Tail(call(
                &["Self", xcdr1_fn],
                args.clone(),
            ))],
        },
        otherwise: Some(rust::Block {
            statements: vec![rust::Statement::Tail(call(&["Self", xcdr2_fn], args))],
        }),
    };

    // encode_xcdr1
    let encode_xcdr1 = function(
        "encode_xcdr1",
        vec![
            self_param.clone(),
            rust::Param {
                name: Some(Ident::new("out")),
                type_: vec_u8_mut.clone(),
                receiver: None,
            },
        ],
        encode_result(),
        vec![
            let_(
                "w",
                call(
                    &["zerodds_wire", "Writer", "with_max_align"],
                    vec![little(), lit(8)],
                ),
                true,
            ),
            rust::Statement::Semi(rust::Expr::Try(Box::new(call(
                &["Self", "encode_xcdr1"],
                vec![local("self"), mut_ref("w")],
            )))),
            rust::Statement::Semi(method(
                local("out"),
                "extend_from_slice",
                vec![rust::Expr::Ref {
                    target: Box::new(method(local("w"), "finish", Vec::new())),
                    mutable: false,
                }],
            )),
            rust::Statement::Tail(call(&["Ok"], vec![rust::Expr::Path(Path::single("()"))])),
        ],
    );

    // decode_xcdr1
    let decode_xcdr1 = function(
        "decode_xcdr1",
        vec![bytes_param("bytes")],
        decode_result(),
        vec![
            let_(
                "r",
                call(
                    &["zerodds_wire", "Reader", "with_max_align"],
                    vec![local("bytes"), little(), lit(8)],
                ),
                true,
            ),
            rust::Statement::Tail(call(
                &["Ok"],
                vec![rust::Expr::Try(Box::new(call(
                    &["Self", "decode_xcdr1"],
                    vec![mut_ref("r")],
                )))],
            )),
        ],
    );

    // encode_continuing
    let encode_continuing = function(
        "encode_continuing",
        vec![
            self_param,
            rust::Param {
                name: Some(Ident::new("prefix")),
                type_: vec_u8_mut,
                receiver: None,
            },
            bool_param("xcdr1"),
        ],
        encode_result(),
        vec![
            let_(
                "w",
                call(
                    &["zerodds_wire", "Writer", "continuing"],
                    vec![
                        little(),
                        cap(),
                        call(&["core", "mem", "take"], vec![local("prefix")]),
                    ],
                ),
                true,
            ),
            rust::Statement::Semi(rust::Expr::Try(Box::new(by_version(
                "encode_xcdr1",
                "encode",
                vec![local("self"), mut_ref("w")],
            )))),
            rust::Statement::Semi(rust::Expr::Assign {
                target: Box::new(rust::Expr::Deref(Box::new(local("prefix")))),
                value: Box::new(method(local("w"), "finish", Vec::new())),
            }),
            rust::Statement::Tail(call(&["Ok"], vec![rust::Expr::Path(Path::single("()"))])),
        ],
    );

    // decode_continuing
    let decode_continuing = function(
        "decode_continuing",
        vec![
            bytes_param("bytes"),
            rust::Param {
                name: Some(Ident::new("offset")),
                type_: rust::Type::named(Path::single("usize")),
                receiver: None,
            },
            bool_param("xcdr1"),
        ],
        decode_result(),
        vec![
            let_(
                "r",
                call(
                    &["zerodds_wire", "Reader", "with_max_align"],
                    vec![local("bytes"), little(), cap()],
                ),
                true,
            ),
            rust::Statement::Semi(rust::Expr::Try(Box::new(method(
                local("r"),
                "skip_to",
                vec![local("offset")],
            )))),
            rust::Statement::Tail(call(
                &["Ok"],
                vec![rust::Expr::Try(Box::new(by_version(
                    "decode_xcdr1",
                    "decode",
                    vec![mut_ref("r")],
                )))],
            )),
        ],
    );

    vec![
        encode_xcdr1,
        decode_xcdr1,
        encode_continuing,
        decode_continuing,
    ]
}

// == the error type ========================================================

fn error_enum(
    ast: &Ast,
    module: Id<ModuleNode>,
    service: &Service,
    exceptions: &[Raise],
) -> Result<rust::Enum, RustInterfaceError> {
    let mut variants = Vec::new();
    for raise in exceptions {
        variants.push(rust::Variant {
            doc: Doc::line(&format!(
                "The declared `{}` exception. DDS-RPC 1.0 ยง7.5.1.1.5.",
                raise.name
            )),
            attrs: Vec::new(),
            name: Ident::new(&rust::escape_keyword(&raise.name)),
            body: rust::VariantBody::Tuple(vec![exception_type(ast, module, raise.id)?]),
            discriminant: None,
        });
    }
    variants.push(rust::Variant {
        doc: Doc::lines(&[
            "A DDS-RPC 1.0 ยง7.11.1.3 remote/system exception, or a transport",
            "failure `zerodds_rpc::requester::Requester` reports โ€” a timeout,",
            "an encode/decode failure, or a DCPS error.",
        ]),
        attrs: Vec::new(),
        name: Ident::new("Remote"),
        body: rust::VariantBody::Tuple(vec![rust::Type::named(Path::new(&[
            "zerodds_rpc",
            "error",
            "RpcError",
        ]))]),
        discriminant: None,
    });
    Ok(rust::Enum {
        doc: Doc::line(&format!("Every way a call to `{}` can fail.", service.name)),
        attrs: Vec::new(),
        derives: data_derives(),
        visibility: Visibility::Public,
        name: Ident::new(&error_type_name(service)),
        generics: Vec::new(),
        variants,
    })
}

// == the operation surface: trait, client, dispatcher =====================

/// One of the three things a `Result<T, {svc}Error>` value a client
/// method or a service trait method carries besides its error: the
/// operation's own return value, or one pure `out` parameter (never
/// `inout`, which travels through a `&mut` argument instead and is
/// never part of the `Ok` value).
#[derive(Clone, PartialEq, Eq)]
enum OutFieldSource {
    Return,
    Out(String),
    InOut(String),
}

fn same_source(a: &OutFieldSource, b: &OutFieldSource) -> bool {
    matches!((a, b), (OutFieldSource::Return, OutFieldSource::Return))
        || matches!((a, b), (OutFieldSource::Out(x), OutFieldSource::Out(y)) if x == y)
}

/// The `${I}_${op}_Out` structure's own fields, each paired with what
/// it is. The same order [`out_fields`] declares the structure in.
fn out_field_map(op: &Operation) -> Vec<(String, OutFieldSource)> {
    let mut out = Vec::new();
    for p in op.outputs() {
        let field_name = rust::escape_keyword(&p.name);
        let source = match p.direction {
            ParamDirection::InOut => OutFieldSource::InOut(p.name.clone()),
            _ => OutFieldSource::Out(p.name.clone()),
        };
        out.push((field_name, source));
    }
    if op.returns.is_some() {
        let taken: Vec<&str> = out.iter().map(|(name, _)| name.as_str()).collect();
        out.push((return_member_name(&taken), OutFieldSource::Return));
    }
    out
}

/// The positions the method's own `Ok` value carries: the return first,
/// when the operation has one, then every pure `out` parameter in
/// declaration order. Index 0 is tuple index `.0`, and so on โ€” the same
/// order the client and the dispatcher both read, so the two sides
/// agree on which slot is which without a third reading of the
/// operation.
fn ok_positions(op: &Operation) -> Vec<OutFieldSource> {
    let mut out = Vec::new();
    if op.returns.is_some() {
        out.push(OutFieldSource::Return);
    }
    for p in op
        .params
        .iter()
        .filter(|p| matches!(p.direction, ParamDirection::Out))
    {
        out.push(OutFieldSource::Out(p.name.clone()));
    }
    out
}

/// Where `target` sits in the `Ok` value [`ok_positions`] lays out.
///
/// Both lists come from the same operation, so a miss is this module
/// contradicting itself โ€” and answering position 0 for it would bind a
/// generated field to another field's value without a word.
fn position_index(
    positions: &[OutFieldSource],
    target: &OutFieldSource,
    op: &Operation,
) -> Result<usize, RustInterfaceError> {
    positions
        .iter()
        .position(|p| same_source(p, target))
        .ok_or_else(|| {
            RustInterfaceError::Interface(InterfaceError::Unresolved {
                construct: "out value's position in the Ok value",
                at: op.name.clone(),
            })
        })
}

/// The expression that reads `source` out of `binding`, a value shaped
/// by [`ok_type`]/[`ok_positions`] for this operation.
fn ok_component_expr(
    positions: &[OutFieldSource],
    source: &OutFieldSource,
    binding: &str,
    op: &Operation,
) -> Result<rust::Expr, RustInterfaceError> {
    if positions.len() <= 1 {
        Ok(rust::Expr::Path(Path::single(binding)))
    } else {
        let index = position_index(positions, source, op)?;
        Ok(field_expr(binding, &index.to_string()))
    }
}

fn ok_type(
    ast: &Ast,
    module: Id<ModuleNode>,
    op: &Operation,
) -> Result<rust::Type, RustInterfaceError> {
    let mut parts = Vec::new();
    if let Some(target) = op.returns {
        parts.push(rust_type_of(ast, module, Some(target))?);
    }
    for p in op
        .params
        .iter()
        .filter(|p| matches!(p.direction, ParamDirection::Out))
    {
        parts.push(rust_type_of(ast, module, Some(p.type_))?);
    }
    Ok(match parts.len() {
        0 => rust::Type::unit(),
        1 => parts.remove(0),
        _ => rust::Type::Tuple(parts),
    })
}

fn op_return_type(
    ast: &Ast,
    module: Id<ModuleNode>,
    service: &Service,
    op: &Operation,
) -> Result<rust::Type, RustInterfaceError> {
    Ok(rust::Type::generic(
        Path::single("Result"),
        vec![
            ok_type(ast, module, op)?,
            rust::Type::named(Path::single(&error_type_name(service))),
        ],
    ))
}

/// The parameters a service trait method, and a client method, take.
///
/// `in` by value, `inout` as `&mut T` โ€” it has an initial value to
/// read โ€” and a pure `out` is not a parameter at all: it has none to
/// read, and travels back through the `Ok` value instead
/// ([`ok_type`]), which is what lets a Rust caller call the method
/// without first inventing one.
fn op_params(
    ast: &Ast,
    module: Id<ModuleNode>,
    op: &Operation,
) -> Result<Vec<rust::Param>, RustInterfaceError> {
    let mut params = vec![rust::Param {
        name: None,
        type_: rust::Type::unit(),
        receiver: Some(rust::Receiver::Ref),
    }];
    for p in &op.params {
        let base = rust_type_of(ast, module, Some(p.type_))?;
        match p.direction {
            ParamDirection::In => params.push(rust::Param {
                name: Some(Ident::new(&rust::escape_keyword(&p.name))),
                type_: base,
                receiver: None,
            }),
            ParamDirection::InOut => params.push(rust::Param {
                name: Some(Ident::new(&rust::escape_keyword(&p.name))),
                type_: rust::Type::Ref {
                    target: Box::new(base),
                    mutable: true,
                    lifetime: None,
                },
                receiver: None,
            }),
            ParamDirection::Out => {}
        }
    }
    Ok(params)
}

/// A one-line doc for a generated operation: its `raises` clause where it
/// has one (DDS-RPC 1.0 ยง7.11.1.1.2 rule 6.c keeps the clause out of the
/// signature itself, so the doc line is where a reader finds it), else a
/// plain statement of what the IDL declared โ€” every `pub` item this module
/// emits carries a doc, per the workspace's `missing_docs` lint.
fn method_doc(op: &Operation) -> String {
    op.raises_line().unwrap_or_else(|| {
        format!(
            "Generated from the IDL operation `{}`; raises nothing.",
            op.name
        )
    })
}

fn trait_method_signature(
    ast: &Ast,
    service: &Service,
    op: &Operation,
) -> Result<rust::Function, RustInterfaceError> {
    Ok(rust::Function {
        doc: Doc::line(&method_doc(op)),
        attrs: Vec::new(),
        visibility: Visibility::Private,
        name: Ident::new(&rust::escape_keyword(&op.name)),
        generics: Vec::new(),
        params: op_params(ast, service.module, op)?,
        returns: Some(op_return_type(ast, service.module, service, op)?),
        body: None,
    })
}

fn base_interface_path(
    ast: &Ast,
    from: Id<ModuleNode>,
    base: &interface::Base,
    suffix: &str,
) -> Result<Path, RustInterfaceError> {
    let node = ast.interface(base.id).map_err(|_| InterfaceError::NoNode {
        kind: "base interface",
        at: base.name.clone(),
    })?;
    relative_module_path(ast, from, node.module, &format!("{}{suffix}", node.name))
}

fn service_trait(ast: &Ast, service: &Service) -> Result<rust::Trait, RustInterfaceError> {
    let mut supertraits = Vec::new();
    for base in &service.bases {
        supertraits.push(rust::Type::named(base_interface_path(
            ast,
            service.module,
            base,
            "",
        )?));
    }
    let mut items = Vec::new();
    for op in service.all_operations() {
        items.push(rust::Item::Function(trait_method_signature(
            ast, service, &op,
        )?));
    }
    let mut doc = Doc::line(&format!(
        "The `{}` service. DDS-RPC 1.0 ยง7.5.1.1.3, ยง7.11.",
        service.name
    ));
    doc.push(
        "`out`/`inout` parameters are `&mut` arguments; a pure `out` parameter \
         besides the declared return travels back through the `Ok` value instead \
         โ€” `()` for none, the bare value for one, a tuple (return first, then \
         every `out` in declaration order) for more than one.",
    );
    Ok(rust::Trait {
        doc,
        attrs: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new(&rust::escape_keyword(&service.name)),
        generics: Vec::new(),
        supertraits,
        items,
    })
}

// -- the client -------------------------------------------------------------

fn client_type_name(service: &Service) -> String {
    format!("{}Client", service.name)
}

fn client_field_name(base: &interface::Base) -> String {
    format!("base_{}", base.name.to_lowercase())
}

fn client_struct(ast: &Ast, service: &Service) -> Result<rust::Struct, RustInterfaceError> {
    let mut fields = vec![field_vis(
        "requester",
        rust::Type::generic(
            Path::new(&["zerodds_rpc", "requester", "Requester"]),
            vec![
                rust::Type::named(Path::single(&interface::call_union_name(&service.name))),
                rust::Type::named(Path::single(&interface::return_union_name(&service.name))),
            ],
        ),
        Visibility::Private,
        "The `Requester` this interface's own operations send `${I}_Call`s \
         through and read `${I}_Return`s back from โ€” DDS-RPC 1.0 ยง7.9.",
    )];
    for base in &service.bases {
        let path = base_interface_path(ast, service.module, base, "Client")?;
        fields.push(field_vis(
            &client_field_name(base),
            rust::Type::named(path),
            Visibility::Public,
            &format!(
                "The `{}` client this interface's own base composes โ€” DDS-RPC 1.0 \
                 ยง7.5.1.1.8 keeps its topic separate from this one's.",
                base.name
            ),
        ));
    }
    let mut doc = Doc::line("A typed DDS-RPC client. DDS-RPC 1.0 ยง7.11.1.5.4/ยง7.9.");
    doc.push(
        "A base interface's operations are not repeated here โ€” DDS-RPC 1.0 keeps a \
         base's topic separate from a derived interface's own (ยง7.5.1.1.8) โ€” they \
         are reachable through the base client field this struct composes, one per \
         parent interface, so a call to an inherited operation is one field access \
         away rather than absent.",
    );
    Ok(rust::Struct {
        body_text: zerodds_lang_cst::common::BodyText::none(),
        doc,
        attrs: Vec::new(),
        derives: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new(&client_type_name(service)),
        generics: Vec::new(),
        body: rust::StructBody::Named(fields),
    })
}

fn dcps_participant_type() -> rust::Type {
    rust::Type::Ref {
        target: Box::new(rust::Type::named(Path::new(&[
            "zerodds_dcps",
            "participant",
            "DomainParticipant",
        ]))),
        mutable: false,
        lifetime: None,
    }
}

fn rpc_qos_type() -> rust::Type {
    rust::Type::Ref {
        target: Box::new(rust::Type::named(Path::new(&[
            "zerodds_rpc",
            "qos_profile",
            "RpcQos",
        ]))),
        mutable: false,
        lifetime: None,
    }
}

fn rpc_result_of(ok: rust::Type) -> rust::Type {
    rust::Type::generic(Path::new(&["zerodds_rpc", "error", "RpcResult"]), vec![ok])
}

fn try_call(callee: Path, args: Vec<rust::Expr>) -> rust::Expr {
    rust::Expr::Try(Box::new(rust::Expr::Call {
        callee: Box::new(rust::Expr::Path(callee)),
        args,
    }))
}

/// `"text".to_string()` โ€” an owned `String` from a literal, for a field
/// whose type is `String`/`Option<String>` rather than `&str`.
fn owned_string_literal(text: &str) -> rust::Expr {
    rust::Expr::MethodCall {
        receiver: Box::new(rust::Expr::Literal(Literal::string(text))),
        method: Ident::new("to_string"),
        args: Vec::new(),
    }
}

/// `Some("text".to_string())` / `None::<String>` for an `Option<String>`
/// field, from an `Option<String>` already read off the model.
fn optional_owned_string(value: Option<&str>) -> rust::Expr {
    match value {
        Some(text) => rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(Path::single("Some"))),
            args: vec![owned_string_literal(text)],
        },
        None => rust::Expr::Path(Path::new(&["None"])),
    }
}

/// `&zerodds_rpc::topic_naming::AnnotatedTopics { .. }` for `service` โ€”
/// its own `@service`/`@DDSRequestTopic`/`@DDSReplyTopic` values
/// (`adapter::interface::Service::service_name`/`request_topic`/
/// `reply_topic`, already read off the IDL's facets), no run-time
/// override (`TopicNameOverrides::default()` โ€” a caller with one does
/// not go through the generated `new`/`serve` at all). DDS-RPC 1.0
/// ยง7.9/ยง7.10 give the `Requester`/`Replier` exactly these three
/// service-declared inputs; this is the generated binding reading them
/// instead of leaving every service at the `Calculator_Service_Request`
/// default regardless of what its own IDL declared.
fn annotated_topics_expr(service: &Service) -> rust::Expr {
    rust::Expr::Ref {
        target: Box::new(rust::Expr::StructLit {
            path: Path::new(&["zerodds_rpc", "topic_naming", "AnnotatedTopics"]),
            fields: vec![
                (
                    Ident::new("service_name"),
                    optional_owned_string(Some(service.service_name.as_str())),
                ),
                (
                    Ident::new("request_topic"),
                    optional_owned_string(service.request_topic.as_deref()),
                ),
                (
                    Ident::new("reply_topic"),
                    optional_owned_string(service.reply_topic.as_deref()),
                ),
                (
                    Ident::new("overrides"),
                    rust::Expr::Call {
                        callee: Box::new(rust::Expr::Path(Path::new(&[
                            "zerodds_rpc",
                            "topic_naming",
                            "TopicNameOverrides",
                            "none",
                        ]))),
                        args: Vec::new(),
                    },
                ),
            ],
            base: None,
        }),
        mutable: false,
    }
}

/// `&zerodds_rpc::endpoint_options::RpcEndpointOptions::for_interface(scope,
/// name).with_parent(..)` for `service`: the DDS type names of its topics
/// โ€” `${interfaceName}_Request` and `_Reply` in the module the interface
/// is declared in (ยง7.5.1.1.6, ยง7.5.1.1.7) โ€” and the base interfaces whose
/// topics are its aliases (ยง7.4.3).
fn endpoint_options_expr(ast: &Ast, service: &Service) -> Result<rust::Expr, RustInterfaceError> {
    Ok(rust::Expr::Ref {
        target: Box::new(endpoint_options_value(ast, service)?),
        mutable: false,
    })
}

/// [`endpoint_options_expr`] without the reference: the options by value.
fn endpoint_options_value(ast: &Ast, service: &Service) -> Result<rust::Expr, RustInterfaceError> {
    let scope = interface::module_chain(ast, service.module)?
        .into_iter()
        .map(|(_, name)| name)
        .collect::<Vec<_>>()
        .join("::");
    let mut options = rust::Expr::Call {
        callee: Box::new(rust::Expr::Path(Path::new(&[
            "zerodds_rpc",
            "endpoint_options",
            "RpcEndpointOptions",
            "for_interface",
        ]))),
        args: vec![
            rust::Expr::Literal(Literal::string(&scope)),
            rust::Expr::Literal(Literal::string(&service.name)),
        ],
    };
    for base in &service.bases {
        options = rust::Expr::MethodCall {
            receiver: Box::new(options),
            method: Ident::new("with_parent"),
            args: vec![rust::Expr::Literal(Literal::string(&base.qualified_name))],
        };
    }
    if service.mapping.is_enhanced() {
        options = rust::Expr::MethodCall {
            receiver: Box::new(options),
            method: Ident::new("with_mapping"),
            args: vec![rust::Expr::Path(Path::new(&[
                "zerodds_rpc",
                "endpoint_options",
                "RpcMapping",
                "Enhanced",
            ]))],
        };
        // The XTypes description of the two topic types, when every type
        // they name has an object. A recursive type, or one XTypes 1.3 ยง7.3
        // has no identifier for, leaves the topics matched by type name.
        let model = interface::enhanced_service(ast, service, service.mapping.empty_style())?;
        if let Ok(objects) = type_information::service_type_objects(ast, service, &model) {
            options = rust::Expr::MethodCall {
                receiver: Box::new(options),
                method: Ident::new("with_type_information"),
                args: vec![type_information_expr(&objects)],
            };
        }
    }
    Ok(options)
}

/// `zerodds_rpc::endpoint_options::RpcTypeInformation { request, reply }`
/// over the bytes of `objects`.
fn type_information_expr(objects: &type_information::ServiceTypeObjects) -> rust::Expr {
    let topic = |topic: &type_information::TopicTypeObjects| rust::Expr::StructLit {
        path: Path::new(&["zerodds_rpc", "endpoint_options", "TopicTypeBytes"]),
        fields: vec![
            (
                Ident::new("object"),
                rust::Expr::Literal(Literal::Bytes(topic.object.clone())),
            ),
            (
                Ident::new("dependencies"),
                rust::Expr::Ref {
                    target: Box::new(rust::Expr::Array(
                        topic
                            .dependencies
                            .iter()
                            .map(|bytes| rust::Expr::Literal(Literal::Bytes(bytes.clone())))
                            .collect(),
                    )),
                    mutable: false,
                },
            ),
        ],
        base: None,
    };
    rust::Expr::StructLit {
        path: Path::new(&["zerodds_rpc", "endpoint_options", "RpcTypeInformation"]),
        fields: vec![
            (Ident::new("request"), topic(&objects.request)),
            (Ident::new("reply"), topic(&objects.reply)),
        ],
        base: None,
    }
}

fn binding_style_expr() -> rust::Expr {
    rust::Expr::Path(Path::new(&[
        "zerodds_rpc",
        "topic_naming",
        "BindingStyle",
        "FunctionCall",
    ]))
}

fn client_impl(ast: &Ast, service: &Service) -> Result<rust::Item, RustInterfaceError> {
    let mut new_fields = vec![(
        Ident::new("requester"),
        try_call(
            Path::new(&["zerodds_rpc", "requester", "Requester", "with_options"]),
            vec![
                rust::Expr::Path(Path::single("participant")),
                rust::Expr::Literal(Literal::string(&service.qualified_name)),
                rust::Expr::Literal(Literal::string("")),
                rust::Expr::Path(Path::single("qos")),
                binding_style_expr(),
                annotated_topics_expr(service),
                endpoint_options_expr(ast, service)?,
            ],
        ),
    )];
    for base in &service.bases {
        let path = base_interface_path(ast, service.module, base, "Client")?;
        new_fields.push((
            Ident::new(&client_field_name(base)),
            try_call(
                path.join("new"),
                vec![
                    rust::Expr::Path(Path::single("participant")),
                    rust::Expr::Path(Path::single("qos")),
                ],
            ),
        ));
    }
    let new_fn = rust::Item::Function(rust::Function {
        doc: Doc::line(
            "A client bound to a `DomainParticipant`, one `Requester` per interface level.",
        ),
        attrs: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new("new"),
        generics: Vec::new(),
        params: vec![
            rust::Param {
                name: Some(Ident::new("participant")),
                type_: dcps_participant_type(),
                receiver: None,
            },
            rust::Param {
                name: Some(Ident::new("qos")),
                type_: rpc_qos_type(),
                receiver: None,
            },
        ],
        returns: Some(rpc_result_of(rust::Type::named(Path::single("Self")))),
        body: Some(rust::Block {
            statements: vec![rust::Statement::Tail(rust::Expr::Call {
                callee: Box::new(rust::Expr::Path(Path::single("Ok"))),
                args: vec![rust::Expr::StructLit {
                    path: Path::single("Self"),
                    fields: new_fields,
                    base: None,
                }],
            })],
        }),
    });

    let options_fn = rust::Item::Function(rust::Function {
        doc: Doc::line(
            "The options this interface's endpoints are created with: the DDS type names of \
             the topics, the base interfaces, the service mapping and, under the Enhanced \
             mapping, the TypeObjects of the topic types. An endpoint written by hand for \
             the same topics, on a participant that also holds this binding, has to use \
             them: a topic name is reused only with the same type metadata.",
        ),
        attrs: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new("endpoint_options"),
        generics: Vec::new(),
        params: Vec::new(),
        returns: Some(rust::Type::named(Path::new(&[
            "zerodds_rpc",
            "endpoint_options",
            "RpcEndpointOptions",
        ]))),
        body: Some(rust::Block {
            statements: vec![rust::Statement::Tail(endpoint_options_value(ast, service)?)],
        }),
    });
    let mut items = vec![new_fn, options_fn];
    if let Some(request_profile) = service.qos_request_profile.as_deref() {
        items.push(declared_qos_fn(
            "new_with_declared_qos",
            "A client whose QoS is the one `@Qos` declares for this interface (DDS-RPC 1.0 ยง7.10.1).",
            request_profile,
            service.qos_reply_profile.as_deref(),
            None,
            rpc_result_of(rust::Type::named(Path::single("Self"))),
            &["Self", "new"],
        ));
    }
    for op in service.all_operations() {
        items.push(rust::Item::Function(client_method(ast, service, &op)?));
    }

    Ok(rust::Item::Impl(rust::Impl {
        doc: Doc::none(),
        attrs: Vec::new(),
        generics: Vec::new(),
        trait_: None,
        self_type: rust::Type::named(Path::single(&client_type_name(service))),
        items,
    }))
}

/// A constructor whose QoS is `@Qos(RequestProfile, ReplyProfile)`
/// (ยง7.10.1): reads the profiles from their URLs and calls `delegate`
/// with the result. `receiver` is the `self` the delegate also takes.
fn declared_qos_fn(
    name: &str,
    doc: &str,
    request_profile: &str,
    reply_profile: Option<&str>,
    receiver: Option<rust::Receiver>,
    returns: rust::Type,
    delegate: &[&str],
) -> rust::Item {
    let reply = match reply_profile {
        Some(url) => rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(Path::single("Some"))),
            args: vec![rust::Expr::Literal(Literal::string(url))],
        },
        None => rust::Expr::Path(Path::single("None")),
    };
    let load_qos = rust::Statement::Let {
        name: Ident::new("qos"),
        type_: None,
        value: Some(try_call(
            Path::new(&[
                "zerodds_rpc",
                "qos_profile",
                "RpcQos",
                "from_service_profiles",
            ]),
            vec![rust::Expr::Literal(Literal::string(request_profile)), reply],
        )),
        mutable: false,
    };
    let mut call_args = Vec::new();
    if receiver.is_some() {
        call_args.push(rust::Expr::Path(Path::single("self")));
    }
    call_args.push(rust::Expr::Path(Path::single("participant")));
    call_args.push(rust::Expr::Ref {
        target: Box::new(rust::Expr::Path(Path::single("qos"))),
        mutable: false,
    });
    let mut params = Vec::new();
    if let Some(receiver) = receiver {
        params.push(rust::Param {
            name: None,
            type_: rust::Type::unit(),
            receiver: Some(receiver),
        });
    }
    params.push(rust::Param {
        name: Some(Ident::new("participant")),
        type_: dcps_participant_type(),
        receiver: None,
    });
    rust::Item::Function(rust::Function {
        doc: Doc::line(doc),
        attrs: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new(name),
        generics: Vec::new(),
        params,
        returns: Some(returns),
        body: Some(rust::Block {
            statements: vec![
                load_qos,
                rust::Statement::Tail(rust::Expr::Call {
                    callee: Box::new(rust::Expr::Path(Path::new(delegate))),
                    args: call_args,
                }),
            ],
        }),
    })
}

fn requester_field() -> rust::Expr {
    field_expr("self", "requester")
}

fn map_err_remote(service: &Service, value: rust::Expr) -> rust::Expr {
    rust::Expr::MethodCall {
        receiver: Box::new(value),
        method: Ident::new("map_err"),
        args: vec![rust::Expr::Path(Path::new(&[
            &error_type_name(service),
            "Remote",
        ]))],
    }
}

/// Whether `rustc` derives `Copy` for a [`rust::Type`] this generator
/// materialises โ€” the scalar primitives DDS-RPC 1.0's own IDL primitive
/// mapping produces. Anything else (`String`, a generated `struct`, a
/// generated `enum`) is `Clone`-only.
fn is_copy_primitive(type_: &rust::Type) -> bool {
    matches!(
        type_,
        rust::Type::Primitive(
            rust::Primitive::Bool
                | rust::Primitive::Char
                | rust::Primitive::I8
                | rust::Primitive::I16
                | rust::Primitive::I32
                | rust::Primitive::I64
                | rust::Primitive::I128
                | rust::Primitive::U8
                | rust::Primitive::U16
                | rust::Primitive::U32
                | rust::Primitive::U64
                | rust::Primitive::U128
                | rust::Primitive::F32
                | rust::Primitive::F64
        )
    )
}

fn in_struct_literal(
    ast: &Ast,
    module: Id<ModuleNode>,
    op: &Operation,
    path: Path,
    empty: interface::EmptyOperationStyle,
) -> Result<rust::Expr, RustInterfaceError> {
    let mut fields = Vec::new();
    for p in op.inputs() {
        let name = rust::escape_keyword(&p.name);
        // An `in` parameter (`op_params`) is already owned by this method,
        // so it moves straight into the payload. An `inout` one is
        // `&mut T` (`rust::Type::Ref { mutable: true, .. }`): the payload
        // needs an owned `T` and the caller keeps the reference to assign
        // the reply back into (`client_reply_match`), so it is read
        // through the reference โ€” by value (`*x`) where `T` is one of
        // DDS-RPC 1.0's `Copy` primitives, else by `.clone()`, so neither
        // `clippy::clone_on_copy` nor a move out of a `&mut` reference.
        let value = if matches!(p.direction, ParamDirection::InOut) {
            let target = rust_type_of(ast, module, Some(p.type_))?;
            if is_copy_primitive(&target) {
                rust::Expr::Deref(Box::new(rust::Expr::Path(Path::single(&name))))
            } else {
                rust::Expr::MethodCall {
                    receiver: Box::new(rust::Expr::Path(Path::single(&name))),
                    method: Ident::new("clone"),
                    args: Vec::new(),
                }
            }
        } else {
            rust::Expr::Path(Path::single(&name))
        };
        fields.push((Ident::new(&name), value));
    }
    if fields.is_empty() && empty == interface::EmptyOperationStyle::DummyMember {
        fields.push((
            Ident::new(interface::DUMMY_MEMBER),
            rust::Expr::Literal(Literal::int(0)),
        ));
    }
    Ok(rust::Expr::StructLit {
        path,
        fields,
        base: None,
    })
}

/// A client method's body, for one operation of `service`.
///
/// Send, block for the reply, and take the reply union's own
/// case apart into the operation's `Ok`/`Err`. A reply whose case does
/// not match the operation called is a protocol error and not
/// constructed by this binding's own dispatcher; it is reported through
/// `{svc}Error::Remote` rather than panicked on.
fn client_method(
    ast: &Ast,
    service: &Service,
    op: &Operation,
) -> Result<rust::Function, RustInterfaceError> {
    let module = service.module;
    let params = op_params(ast, module, op)?;
    let returns = op_return_type(ast, module, service, op)?;
    let variant = variant_name(&op.name);
    let in_struct_path = Path::single(&interface::in_struct_name(&service.name, &op.name));
    let call_path = Path::new(&[&interface::call_union_name(&service.name), &variant]);

    let build_payload = rust::Statement::Let {
        name: Ident::new("request_payload"),
        type_: None,
        value: Some(in_struct_literal(
            ast,
            module,
            op,
            in_struct_path,
            service.mapping.empty_style(),
        )?),
        mutable: false,
    };
    let build_call = rust::Statement::Let {
        name: Ident::new("call"),
        type_: None,
        value: Some(rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(call_path)),
            args: vec![rust::Expr::Path(Path::single("request_payload"))],
        }),
        mutable: false,
    };

    let send = rust::Expr::MethodCall {
        receiver: Box::new(requester_field()),
        method: Ident::new("send_request_blocking"),
        args: vec![
            rust::Expr::Ref {
                target: Box::new(rust::Expr::Path(Path::single("call"))),
                mutable: false,
            },
            rust::Expr::Path(Path::single("None")),
        ],
    };
    let reply_let = rust::Statement::Let {
        name: Ident::new("reply"),
        type_: None,
        value: Some(rust::Expr::Try(Box::new(map_err_remote(service, send)))),
        mutable: false,
    };
    let statements = vec![
        build_payload,
        build_call,
        reply_let,
        client_reply_match(service, op, &variant)?,
    ];

    Ok(rust::Function {
        doc: Doc::line(&method_doc(op)),
        attrs: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new(&rust::escape_keyword(&op.name)),
        generics: Vec::new(),
        params,
        returns: Some(returns),
        body: Some(rust::Block { statements }),
    })
}

fn client_reply_match(
    service: &Service,
    op: &Operation,
    variant: &str,
) -> Result<rust::Statement, RustInterfaceError> {
    let map = out_field_map(op);
    let positions = ok_positions(op);
    let mut assigns = Vec::new();
    let mut ok_values = Vec::new();
    for (field_name, source) in &map {
        match source {
            OutFieldSource::InOut(param_name) => {
                assigns.push(rust::Statement::Semi(rust::Expr::Assign {
                    target: Box::new(rust::Expr::Deref(Box::new(rust::Expr::Path(Path::single(
                        &rust::escape_keyword(param_name),
                    ))))),
                    value: Box::new(field_expr("out_val", field_name)),
                }));
            }
            OutFieldSource::Return | OutFieldSource::Out(_) => {
                let index = position_index(&positions, source, op)?;
                ok_values.push((index, field_expr("out_val", field_name)));
            }
        }
    }
    ok_values.sort_by_key(|(index, _)| *index);
    let ok_expr = match ok_values.len() {
        0 => ok_unit(),
        1 => rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(Path::single("Ok"))),
            args: vec![ok_values.remove(0).1],
        },
        _ => rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(Path::single("Ok"))),
            args: vec![rust::Expr::Tuple(
                ok_values.into_iter().map(|(_, expr)| expr).collect(),
            )],
        },
    };
    let mut ok_arm_statements = assigns;
    ok_arm_statements.push(rust::Statement::Tail(ok_expr));

    let result_name = interface::result_union_name(&service.name, &op.name);
    // `out_val` is read by `assigns`/`ok_values` above only where the
    // reply carries an `out`, `inout`, or return value (DDS-RPC 1.0
    // ยง7.5.1.1.5); an operation whose `${I}_${op}_Out` is empty (no
    // outputs, `void` return) binds a wildcard instead so `rustc` does
    // not warn on the unread payload.
    let ok_binding = if map.is_empty() {
        rust::Pattern::Wildcard
    } else {
        rust::Pattern::Binding(Ident::new("out_val"))
    };
    let mut result_arms = vec![rust::MatchArm {
        pattern: rust::Pattern::TupleStruct {
            path: Path::new(&[&result_name, "Ok"]),
            elements: vec![ok_binding],
        },
        guard: None,
        body: rust::Expr::Block(rust::Block {
            statements: ok_arm_statements,
        }),
    }];
    for raise in &op.raises {
        let raise_variant = rust::escape_keyword(&raise.name);
        result_arms.push(rust::MatchArm {
            pattern: rust::Pattern::TupleStruct {
                path: Path::new(&[&result_name, &raise_variant]),
                elements: vec![rust::Pattern::Binding(Ident::new("exc"))],
            },
            guard: None,
            body: rust::Expr::Call {
                callee: Box::new(rust::Expr::Path(Path::single("Err"))),
                args: vec![rust::Expr::Call {
                    callee: Box::new(rust::Expr::Path(Path::new(&[
                        &error_type_name(service),
                        &raise_variant,
                    ]))),
                    args: vec![rust::Expr::Path(Path::single("exc"))],
                }],
            },
        });
    }

    // ยง7.7.2.5.6: an Enhanced `Result` that carries an exception member
    // this version of the interface does not declare is
    // `REMOTE_EX_UNKNOWN_EXCEPTION` for the client.
    if service.mapping.is_enhanced() {
        result_arms.push(rust::MatchArm {
            pattern: rust::Pattern::TupleStruct {
                path: Path::new(&[&result_name, UNKNOWN_EX_VARIANT]),
                elements: vec![rust::Pattern::Wildcard],
            },
            guard: None,
            body: rust::Expr::Call {
                callee: Box::new(rust::Expr::Path(Path::single("Err"))),
                args: vec![rust::Expr::Call {
                    callee: Box::new(rust::Expr::Path(Path::new(&[
                        &error_type_name(service),
                        "Remote",
                    ]))),
                    args: vec![rust::Expr::Call {
                        callee: Box::new(rust::Expr::Path(Path::new(&[
                            "zerodds_rpc",
                            "error",
                            "RpcError",
                            "RemoteException",
                        ]))),
                        args: vec![rust::Expr::MethodCall {
                            receiver: Box::new(rust::Expr::Path(remote_exception_code(
                                "UnknownException",
                            ))),
                            method: Ident::new("as_u32"),
                            args: Vec::new(),
                        }],
                    }],
                }],
            },
        });
    }

    let return_name = interface::return_union_name(&service.name);
    let outer_match = rust::Expr::Match {
        scrutinee: Box::new(rust::Expr::Path(Path::single("reply"))),
        arms: vec![
            rust::MatchArm {
                pattern: rust::Pattern::TupleStruct {
                    path: Path::new(&[&return_name, variant]),
                    elements: vec![rust::Pattern::Binding(Ident::new("result"))],
                },
                guard: None,
                body: rust::Expr::Match {
                    scrutinee: Box::new(rust::Expr::Path(Path::single("result"))),
                    arms: result_arms,
                },
            },
            rust::MatchArm {
                pattern: rust::Pattern::Wildcard,
                guard: None,
                body: rust::Expr::Call {
                    callee: Box::new(rust::Expr::Path(Path::single("Err"))),
                    args: vec![rust::Expr::Call {
                        callee: Box::new(rust::Expr::Path(Path::new(&[
                            &error_type_name(service),
                            "Remote",
                        ]))),
                        args: vec![rust::Expr::Call {
                            callee: Box::new(rust::Expr::Path(Path::new(&[
                                "zerodds_rpc",
                                "error",
                                "RpcError",
                                "Dcps",
                            ]))),
                            args: vec![rust::Expr::MethodCall {
                                receiver: Box::new(rust::Expr::Literal(Literal::string(&format!(
                                    "reply carried a case other than `{}`",
                                    op.name
                                )))),
                                method: Ident::new("to_string"),
                                args: Vec::new(),
                            }],
                        }],
                    }],
                },
            },
        ],
    };
    Ok(rust::Statement::Tail(outer_match))
}

// -- the dispatcher -----------------------------------------------------------

fn dispatcher_type_name(service: &Service) -> String {
    format!("{}Dispatcher", service.name)
}

fn remote_exception_code(variant: &str) -> Path {
    Path::new(&[
        "zerodds_rpc",
        "common_types",
        "RemoteExceptionCode",
        variant,
    ])
}

fn service_bound(service: &Service) -> Vec<rust::Type> {
    vec![
        rust::Type::named(Path::single(&rust::escape_keyword(&service.name))),
        rust::Type::named(Path::single("Send")),
        rust::Type::named(Path::single("Sync")),
        rust::Type::named(Path::single("'static")),
    ]
}

fn dispatcher_generic() -> rust::GenericParam {
    // Filled in per service by the caller โ€” see `dispatcher_struct`.
    rust::GenericParam {
        name: Ident::new("S"),
        bounds: Vec::new(),
        lifetime: false,
    }
}

fn dispatcher_struct(service: &Service) -> rust::Struct {
    let mut generic = dispatcher_generic();
    generic.bounds = service_bound(service);
    let mut doc =
        Doc::line("Serves one service implementation over a `zerodds_rpc::replier::Replier`.");
    doc.push(
        "A base interface's operations are dispatched by that base's own \
         `Dispatcher` and `Replier`, run alongside this one โ€” DDS-RPC 1.0 keeps \
         a base's topic separate from a derived interface's own (ยง7.5.1.1.8), \
         and so does this binding.",
    );
    rust::Struct {
        body_text: zerodds_lang_cst::common::BodyText::none(),
        doc,
        attrs: Vec::new(),
        derives: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new(&dispatcher_type_name(service)),
        generics: vec![generic],
        body: rust::StructBody::Named(vec![field_vis(
            "service",
            rust::Type::named(Path::single("S")),
            Visibility::Private,
            "The implementation this dispatcher hands each `${I}_Call` to โ€” \
             DDS-RPC 1.0 ยง7.10's Replier, over the `${I}` trait.",
        )]),
    }
}

fn dispatcher_out_literal(
    service: &Service,
    op: &Operation,
    qualify: &impl Fn(&str) -> Result<Path, RustInterfaceError>,
) -> Result<rust::Expr, RustInterfaceError> {
    let map = out_field_map(op);
    let out_path = qualify(&interface::out_struct_name(&service.name, &op.name))?;
    if map.is_empty() {
        let fields = if service.mapping.empty_style() == interface::EmptyOperationStyle::DummyMember
        {
            vec![(
                Ident::new(interface::DUMMY_MEMBER),
                rust::Expr::Literal(Literal::int(0)),
            )]
        } else {
            Vec::new()
        };
        return Ok(rust::Expr::StructLit {
            path: out_path,
            fields,
            base: None,
        });
    }
    let positions = ok_positions(op);
    let mut fields = Vec::new();
    for (field_name, source) in &map {
        let expr = match source {
            OutFieldSource::InOut(param_name) => {
                rust::Expr::Path(Path::single(&rust::escape_keyword(param_name)))
            }
            OutFieldSource::Return | OutFieldSource::Out(_) => {
                ok_component_expr(&positions, source, "value", op)?
            }
        };
        fields.push((Ident::new(field_name), expr));
    }
    Ok(rust::Expr::StructLit {
        path: out_path,
        fields,
        base: None,
    })
}

/// The dispatcher call arm's binding for the `${I}_${op}_In` payload: a
/// name where `dispatcher_call_args`/`dispatcher_inout_locals` read one of
/// its fields (any `in`/`inout` parameter), else a wildcard โ€” an operation
/// with none, such as a no-argument `reset()`, binds nothing so `rustc`
/// does not warn on the unread name.
fn in_binding_pattern(op: &Operation) -> rust::Pattern {
    let reads_in = op
        .params
        .iter()
        .any(|p| matches!(p.direction, ParamDirection::In | ParamDirection::InOut));
    if reads_in {
        rust::Pattern::Binding(Ident::new("in_"))
    } else {
        rust::Pattern::Wildcard
    }
}

fn dispatcher_call_args(op: &Operation) -> Vec<rust::Expr> {
    let mut args = Vec::new();
    for p in &op.params {
        let name = rust::escape_keyword(&p.name);
        match p.direction {
            ParamDirection::In => args.push(field_expr("in_", &name)),
            ParamDirection::InOut => args.push(rust::Expr::Ref {
                target: Box::new(rust::Expr::Path(Path::single(&name))),
                mutable: true,
            }),
            ParamDirection::Out => {}
        }
    }
    args
}

fn dispatcher_inout_locals(op: &Operation) -> Vec<rust::Statement> {
    op.params
        .iter()
        .filter(|p| matches!(p.direction, ParamDirection::InOut))
        .map(|p| {
            let name = rust::escape_keyword(&p.name);
            rust::Statement::Let {
                name: Ident::new(&name),
                type_: None,
                value: Some(field_expr("in_", &name)),
                mutable: true,
            }
        })
        .collect()
}

/// One `${I}_Call` variant's arm in the dispatcher's `handle`.
fn dispatcher_call_arm(
    service: &Service,
    op: &Operation,
) -> Result<rust::MatchArm, RustInterfaceError> {
    dispatcher_call_arm_via(service, service, op, &|name| Ok(Path::single(name)))
}

/// The arm of `dispatching`'s dispatcher for `op`, which `declaring`
/// declares: the same interface for an operation of its own, a base for an
/// inherited one (DDS-RPC 1.0 ยง7.5.1.2.6: the Enhanced mapping's request
/// choice holds every inherited operation, and the derived service
/// implements the base trait). The topic types are `dispatching`'s; the
/// `Result`, `Out` and error types are `declaring`'s, reached through
/// `qualify`.
fn dispatcher_call_arm_via(
    dispatching: &Service,
    declaring: &Service,
    op: &Operation,
    qualify: &impl Fn(&str) -> Result<Path, RustInterfaceError>,
) -> Result<rust::MatchArm, RustInterfaceError> {
    let service = dispatching;
    let variant = variant_name(&op.name);
    let call_name = interface::call_union_name(&service.name);
    let return_name = interface::return_union_name(&service.name);

    let mut statements = dispatcher_inout_locals(op);
    let call_expr = rust::Expr::MethodCall {
        receiver: Box::new(field_expr("self", "service")),
        method: Ident::new(&rust::escape_keyword(&op.name)),
        args: dispatcher_call_args(op),
    };

    let ok_pattern = if ok_positions(op).is_empty() {
        rust::Pattern::Wildcard
    } else {
        rust::Pattern::Binding(Ident::new("value"))
    };
    let result_name = interface::result_union_name(&declaring.name, &op.name);
    let ok_arm = rust::MatchArm {
        pattern: rust::Pattern::TupleStruct {
            path: Path::single("Ok"),
            elements: vec![ok_pattern],
        },
        guard: None,
        body: rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(Path::single("Ok"))),
            args: vec![rust::Expr::Call {
                callee: Box::new(rust::Expr::Path(Path::new(&[&return_name, &variant]))),
                args: vec![rust::Expr::Call {
                    callee: Box::new(rust::Expr::Path(qualify(&result_name)?.join("Ok"))),
                    args: vec![dispatcher_out_literal(declaring, op, qualify)?],
                }],
            }],
        },
    };
    let mut arms = vec![ok_arm];
    for raise in &op.raises {
        let raise_variant = rust::escape_keyword(&raise.name);
        arms.push(rust::MatchArm {
            pattern: rust::Pattern::TupleStruct {
                path: Path::single("Err"),
                elements: vec![rust::Pattern::TupleStruct {
                    path: qualify(&error_type_name(declaring))?.join(&raise_variant),
                    elements: vec![rust::Pattern::Binding(Ident::new("exc"))],
                }],
            },
            guard: None,
            body: rust::Expr::Call {
                callee: Box::new(rust::Expr::Path(Path::single("Ok"))),
                args: vec![rust::Expr::Call {
                    callee: Box::new(rust::Expr::Path(Path::new(&[&return_name, &variant]))),
                    args: vec![rust::Expr::Call {
                        callee: Box::new(rust::Expr::Path(
                            qualify(&result_name)?.join(&raise_variant),
                        )),
                        args: vec![rust::Expr::Path(Path::single("exc"))],
                    }],
                }],
            },
        });
    }
    // Exhaustive over `{svc}Error` whatever else it carries: a
    // `Remote(_)` this service should not have produced, or an
    // exception variant `op` does not declare because some *other*
    // operation of the same interface raises it โ€” `{svc}Error` is
    // shared. Either is an exception the caller's declared set does not
    // name; ยง7.5.2 makes that `REMOTE_EX_UNKNOWN_EXCEPTION`.
    arms.push(rust::MatchArm {
        pattern: rust::Pattern::Wildcard,
        guard: None,
        body: rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(Path::single("Err"))),
            args: vec![rust::Expr::Path(remote_exception_code("UnknownException"))],
        },
    });
    statements.push(rust::Statement::Tail(rust::Expr::Match {
        scrutinee: Box::new(call_expr),
        arms,
    }));

    Ok(rust::MatchArm {
        pattern: rust::Pattern::TupleStruct {
            path: Path::new(&[&call_name, &variant]),
            elements: vec![in_binding_pattern(op)],
        },
        guard: None,
        body: rust::Expr::Block(rust::Block { statements }),
    })
}

fn dispatcher_handle_fn(
    service: &Service,
    ops: &[Operation],
) -> Result<rust::Item, RustInterfaceError> {
    let call_name = interface::call_union_name(&service.name);
    let mut arms: Vec<rust::MatchArm> = ops
        .iter()
        .map(|op| dispatcher_call_arm(service, op))
        .collect::<Result<_, _>>()?;
    arms.push(rust::MatchArm {
        pattern: rust::Pattern::TupleStruct {
            path: Path::new(&[&call_name, UNKNOWN_OP_VARIANT]),
            elements: vec![rust::Pattern::Wildcard],
        },
        guard: None,
        body: rust::Expr::Call {
            callee: Box::new(rust::Expr::Path(Path::single("Err"))),
            args: vec![rust::Expr::Path(remote_exception_code("Unsupported"))],
        },
    });
    Ok(rust::Item::Function(rust::Function {
        doc: Doc::none(),
        attrs: Vec::new(),
        visibility: Visibility::Private,
        name: Ident::new("handle"),
        generics: Vec::new(),
        params: vec![
            rust::Param {
                name: None,
                type_: rust::Type::unit(),
                receiver: Some(rust::Receiver::Ref),
            },
            rust::Param {
                name: Some(Ident::new("request")),
                type_: rust::Type::named(Path::single(&call_name)),
                receiver: None,
            },
        ],
        returns: Some(rust::Type::generic(
            Path::single("Result"),
            vec![
                rust::Type::named(Path::single(&interface::return_union_name(&service.name))),
                rust::Type::named(Path::new(&[
                    "zerodds_rpc",
                    "common_types",
                    "RemoteExceptionCode",
                ])),
            ],
        )),
        body: Some(rust::Block {
            statements: vec![rust::Statement::Tail(rust::Expr::Match {
                scrutinee: Box::new(rust::Expr::Path(Path::single("request"))),
                arms,
            })],
        }),
    }))
}

fn dispatcher_impl(ast: &Ast, service: &Service) -> Result<Vec<rust::Item>, RustInterfaceError> {
    let _ = ast;
    let mut generic = dispatcher_generic();
    generic.bounds = service_bound(service);
    let self_type = rust::Type::generic(
        Path::single(&dispatcher_type_name(service)),
        vec![rust::Type::named(Path::single("S"))],
    );

    let new_fn = rust::Item::Function(rust::Function {
        doc: Doc::line("Wraps a service implementation, ready to serve."),
        attrs: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new("new"),
        generics: Vec::new(),
        params: vec![rust::Param {
            name: Some(Ident::new("service")),
            type_: rust::Type::named(Path::single("S")),
            receiver: None,
        }],
        returns: Some(rust::Type::named(Path::single("Self"))),
        body: Some(rust::Block {
            statements: vec![rust::Statement::Tail(rust::Expr::StructLit {
                path: Path::single("Self"),
                fields: vec![(
                    Ident::new("service"),
                    rust::Expr::Path(Path::single("service")),
                )],
                base: None,
            })],
        }),
    });

    let call_name = interface::call_union_name(&service.name);
    let return_name = interface::return_union_name(&service.name);
    let serve_fn = rust::Item::Function(rust::Function {
        doc: Doc::line(
            "Registers a `Replier` for this interface level and starts serving. \
             Ticking it โ€” reading requests, calling the service, writing replies \
             โ€” is the caller's own event loop, as `zerodds_rpc::replier::Replier` \
             always leaves it.",
        ),
        attrs: Vec::new(),
        visibility: Visibility::Public,
        name: Ident::new("serve"),
        generics: Vec::new(),
        params: vec![
            rust::Param {
                name: None,
                type_: rust::Type::unit(),
                receiver: Some(rust::Receiver::Value),
            },
            rust::Param {
                name: Some(Ident::new("participant")),
                type_: dcps_participant_type(),
                receiver: None,
            },
            rust::Param {
                name: Some(Ident::new("qos")),
                type_: rpc_qos_type(),
                receiver: None,
            },
        ],
        returns: Some(rpc_result_of(rust::Type::generic(
            Path::new(&["zerodds_rpc", "replier", "Replier"]),
            vec![
                rust::Type::named(Path::single(&call_name)),
                rust::Type::named(Path::single(&return_name)),
            ],
        ))),
        body: Some(rust::Block {
            statements: vec![rust::Statement::Tail(rust::Expr::Call {
                callee: Box::new(rust::Expr::Path(Path::new(&[
                    "zerodds_rpc",
                    "replier",
                    "Replier",
                    "with_options",
                ]))),
                args: vec![
                    rust::Expr::Path(Path::single("participant")),
                    rust::Expr::Literal(Literal::string(&service.qualified_name)),
                    rust::Expr::Literal(Literal::string("")),
                    rust::Expr::Path(Path::single("qos")),
                    binding_style_expr(),
                    annotated_topics_expr(service),
                    endpoint_options_expr(ast, service)?,
                    rust::Expr::Call {
                        callee: Box::new(rust::Expr::Path(Path::new(&[
                            "std", "sync", "Arc", "new",
                        ]))),
                        args: vec![rust::Expr::Path(Path::single("self"))],
                    },
                ],
            })],
        }),
    });

    let inherent = rust::Item::Impl(rust::Impl {
        doc: Doc::none(),
        attrs: Vec::new(),
        generics: vec![generic.clone()],
        trait_: None,
        self_type: self_type.clone(),
        items: {
            let mut items = vec![new_fn, serve_fn];
            if let Some(request_profile) = service.qos_request_profile.as_deref() {
                items.push(declared_qos_fn(
                    "serve_with_declared_qos",
                    "Like `serve`, with the QoS `@Qos` declares for this interface (DDS-RPC 1.0 ยง7.10.1).",
                    request_profile,
                    service.qos_reply_profile.as_deref(),
                    Some(rust::Receiver::Value),
                    rpc_result_of(rust::Type::generic(
                        Path::new(&["zerodds_rpc", "replier", "Replier"]),
                        vec![
                            rust::Type::named(Path::single(&call_name)),
                            rust::Type::named(Path::single(&return_name)),
                        ],
                    )),
                    &["Self", "serve"],
                ));
            }
            items
        },
    });

    let ops = service.all_operations();
    let handler = rust::Item::Impl(rust::Impl {
        doc: Doc::none(),
        attrs: Vec::new(),
        generics: vec![generic],
        trait_: Some(rust::Type::generic(
            Path::new(&["zerodds_rpc", "replier", "ReplierHandler"]),
            vec![
                rust::Type::named(Path::single(&call_name)),
                rust::Type::named(Path::single(&return_name)),
            ],
        )),
        self_type,
        items: vec![dispatcher_handle_fn(service, &ops)?],
    });

    Ok(vec![inherent, handler])
}