summaryrefslogtreecommitdiffstats
path: root/ipc/ipdl/ipdl/lower.py
blob: b8ef219b9bf26c2b8c54425437b8f260936f3672 (plain)
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
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import re
from copy import deepcopy
from collections import OrderedDict
import itertools

import ipdl.ast
import ipdl.builtin
from ipdl.cxx.ast import *
from ipdl.cxx.code import *
from ipdl.type import ActorType, UnionType, TypeVisitor, builtinHeaderIncludes
from ipdl.util import hash_str


# -----------------------------------------------------------------------------
# "Public" interface to lowering
##


class LowerToCxx:
    def lower(self, tu, segmentcapacitydict):
        """returns |[ header: File ], [ cpp : File ]| representing the
        lowered form of |tu|"""
        # annotate the AST with IPDL/C++ IR-type stuff used later
        tu.accept(_DecorateWithCxxStuff())

        # Any modifications to the filename scheme here need corresponding
        # modifications in the ipdl.py driver script.
        name = tu.name
        pheader, pcpp = File(name + ".h"), File(name + ".cpp")

        _GenerateProtocolCode().lower(tu, pheader, pcpp, segmentcapacitydict)
        headers = [pheader]
        cpps = [pcpp]

        if tu.protocol:
            pname = tu.protocol.name

            parentheader, parentcpp = (
                File(pname + "Parent.h"),
                File(pname + "Parent.cpp"),
            )
            _GenerateProtocolParentCode().lower(
                tu, pname + "Parent", parentheader, parentcpp
            )

            childheader, childcpp = File(pname + "Child.h"), File(pname + "Child.cpp")
            _GenerateProtocolChildCode().lower(
                tu, pname + "Child", childheader, childcpp
            )

            headers += [parentheader, childheader]
            cpps += [parentcpp, childcpp]

        return headers, cpps


# -----------------------------------------------------------------------------
# Helper code
##


def hashfunc(value):
    h = hash_str(value) % 2 ** 32
    if h < 0:
        h += 2 ** 32
    return h


_NULL_ACTOR_ID = ExprLiteral.ZERO
_FREED_ACTOR_ID = ExprLiteral.ONE

_DISCLAIMER = Whitespace(
    """//
// Automatically generated by ipdlc.
// Edit at your own risk
//

"""
)


class _struct:
    pass


def _namespacedHeaderName(name, namespaces):
    pfx = "/".join([ns.name for ns in namespaces])
    if pfx:
        return pfx + "/" + name
    else:
        return name


def _ipdlhHeaderName(tu):
    assert tu.filetype == "header"
    return _namespacedHeaderName(tu.name, tu.namespaces)


def _protocolHeaderName(p, side=""):
    if side:
        side = side.title()
    base = p.name + side
    return _namespacedHeaderName(base, p.namespaces)


def _includeGuardMacroName(headerfile):
    return re.sub(r"[./]", "_", headerfile.name)


def _includeGuardStart(headerfile):
    guard = _includeGuardMacroName(headerfile)
    return [CppDirective("ifndef", guard), CppDirective("define", guard)]


def _includeGuardEnd(headerfile):
    guard = _includeGuardMacroName(headerfile)
    return [CppDirective("endif", "// ifndef " + guard)]


def _messageStartName(ptype):
    return ptype.name() + "MsgStart"


def _protocolId(ptype):
    return ExprVar(_messageStartName(ptype))


def _protocolIdType():
    return Type.INT32


def _actorName(pname, side):
    """|pname| is the protocol name. |side| is 'Parent' or 'Child'."""
    tag = side
    if not tag[0].isupper():
        tag = side.title()
    return pname + tag


def _actorIdType():
    return Type.INT32


def _actorTypeTagType():
    return Type.INT32


def _actorId(actor=None):
    if actor is not None:
        return ExprCall(ExprSelect(actor, "->", "Id"))
    return ExprCall(ExprVar("Id"))


def _actorHId(actorhandle):
    return ExprSelect(actorhandle, ".", "mId")


def _backstagePass():
    return ExprCall(ExprVar("mozilla::ipc::PrivateIPDLInterface"))


def _deleteId():
    return ExprVar("Msg___delete____ID")


def _deleteReplyId():
    return ExprVar("Reply___delete____ID")


def _lookupListener(idexpr):
    return ExprCall(ExprVar("Lookup"), args=[idexpr])


def _makeForwardDeclForQClass(clsname, quals, cls=True, struct=False):
    fd = ForwardDecl(clsname, cls=cls, struct=struct)
    if 0 == len(quals):
        return fd

    outerns = Namespace(quals[0])
    innerns = outerns
    for ns in quals[1:]:
        tmpns = Namespace(ns)
        innerns.addstmt(tmpns)
        innerns = tmpns

    innerns.addstmt(fd)
    return outerns


def _makeForwardDeclForActor(ptype, side):
    return _makeForwardDeclForQClass(
        _actorName(ptype.qname.baseid, side), ptype.qname.quals
    )


def _makeForwardDecl(type):
    return _makeForwardDeclForQClass(type.name(), type.qname.quals)


def _putInNamespaces(cxxthing, namespaces):
    """|namespaces| is in order [ outer, ..., inner ]"""
    if 0 == len(namespaces):
        return cxxthing

    outerns = Namespace(namespaces[0].name)
    innerns = outerns
    for ns in namespaces[1:]:
        newns = Namespace(ns.name)
        innerns.addstmt(newns)
        innerns = newns
    innerns.addstmt(cxxthing)
    return outerns


def _sendPrefix(msgtype):
    """Prefix of the name of the C++ method that sends |msgtype|."""
    if msgtype.isInterrupt():
        return "Call"
    return "Send"


def _recvPrefix(msgtype):
    """Prefix of the name of the C++ method that handles |msgtype|."""
    if msgtype.isInterrupt():
        return "Answer"
    return "Recv"


def _flatTypeName(ipdltype):
    """Return a 'flattened' IPDL type name that can be used as an
    identifier.
    E.g., |Foo[]| --> |ArrayOfFoo|."""
    # NB: this logic depends heavily on what IPDL types are allowed to
    # be constructed; e.g., Foo[][] is disallowed.  needs to be kept in
    # sync with grammar.
    if ipdltype.isIPDL() and ipdltype.isArray():
        return "ArrayOf" + _flatTypeName(ipdltype.basetype)
    if ipdltype.isIPDL() and ipdltype.isMaybe():
        return "Maybe" + _flatTypeName(ipdltype.basetype)
    # NotNull types just assume the underlying variant name to avoid unnecessary
    # noise, as a NotNull<T> and T should never exist in the same union.
    if ipdltype.isIPDL() and ipdltype.isNotNull():
        return _flatTypeName(ipdltype.basetype)
    return ipdltype.name()


def _hasVisibleActor(ipdltype):
    """Return true iff a C++ decl of |ipdltype| would have an Actor* type.
    For example: |Actor[]| would turn into |Array<ActorParent*>|, so this
    function would return true for |Actor[]|."""
    return ipdltype.isIPDL() and (
        ipdltype.isActor()
        or (ipdltype.hasBaseType() and _hasVisibleActor(ipdltype.basetype))
    )


def _abortIfFalse(cond, msg):
    return StmtExpr(
        ExprCall(ExprVar("MOZ_RELEASE_ASSERT"), [cond, ExprLiteral.String(msg)])
    )


def _refptr(T):
    return Type("RefPtr", T=T)


def _alreadyaddrefed(T):
    return Type("already_AddRefed", T=T)


def _tuple(types, const=False, ref=False):
    return Type("std::tuple", T=types, const=const, ref=ref)


def _promise(resolvetype, rejecttype, tail, resolver=False):
    inner = Type("Private") if resolver else None
    return Type("MozPromise", T=[resolvetype, rejecttype, tail], inner=inner)


def _makePromise(returns, side, resolver=False):
    if len(returns) > 1:
        resolvetype = _tuple([d.bareType(side) for d in returns])
    else:
        resolvetype = returns[0].bareType(side)

    # MozPromise is purposefully made to be exclusive only. Really, we mean it.
    return _promise(
        resolvetype, _ResponseRejectReason.Type(), ExprLiteral.TRUE, resolver=resolver
    )


def _resolveType(returns, side):
    if len(returns) > 1:
        return _tuple([d.inType(side, "send") for d in returns])
    return returns[0].inType(side, "send")


def _makeResolver(returns, side):
    return TypeFunction([Decl(_resolveType(returns, side), "")])


def _cxxArrayType(basetype, const=False, ref=False):
    return Type("nsTArray", T=basetype, const=const, ref=ref, hasimplicitcopyctor=False)


def _cxxSpanType(basetype, const=False, ref=False):
    basetype = deepcopy(basetype)
    basetype.rightconst = True
    return Type(
        "mozilla::Span", T=basetype, const=const, ref=ref, hasimplicitcopyctor=True
    )


def _cxxMaybeType(basetype, const=False, ref=False):
    return Type(
        "mozilla::Maybe",
        T=basetype,
        const=const,
        ref=ref,
        hasimplicitcopyctor=basetype.hasimplicitcopyctor,
    )


def _cxxReadResultType(basetype, const=False, ref=False):
    return Type(
        "IPC::ReadResult",
        T=basetype,
        const=const,
        ref=ref,
        hasimplicitcopyctor=basetype.hasimplicitcopyctor,
    )


def _cxxNotNullType(basetype, const=False, ref=False):
    return Type(
        "mozilla::NotNull",
        T=basetype,
        const=const,
        ref=ref,
        hasimplicitcopyctor=basetype.hasimplicitcopyctor,
    )


def _cxxManagedContainerType(basetype, const=False, ref=False):
    return Type(
        "ManagedContainer", T=basetype, const=const, ref=ref, hasimplicitcopyctor=False
    )


def _cxxLifecycleProxyType(ptr=False):
    return Type("mozilla::ipc::ActorLifecycleProxy", ptr=ptr)


def _otherSide(side):
    if side == "child":
        return "parent"
    if side == "parent":
        return "child"
    assert 0


def _ifLogging(topLevelProtocol, stmts):
    return StmtCode(
        """
        if (mozilla::ipc::LoggingEnabledFor(${proto})) {
            $*{stmts}
        }
        """,
        proto=topLevelProtocol,
        stmts=stmts,
    )


# XXX we need to remove these and install proper error handling


def _printErrorMessage(msg):
    if isinstance(msg, str):
        msg = ExprLiteral.String(msg)
    return StmtExpr(ExprCall(ExprVar("NS_ERROR"), args=[msg]))


def _protocolErrorBreakpoint(msg):
    if isinstance(msg, str):
        msg = ExprLiteral.String(msg)
    return StmtExpr(
        ExprCall(ExprVar("mozilla::ipc::ProtocolErrorBreakpoint"), args=[msg])
    )


def _printWarningMessage(msg):
    if isinstance(msg, str):
        msg = ExprLiteral.String(msg)
    return StmtExpr(ExprCall(ExprVar("NS_WARNING"), args=[msg]))


def _fatalError(msg):
    return StmtExpr(ExprCall(ExprVar("FatalError"), args=[ExprLiteral.String(msg)]))


def _logicError(msg):
    return StmtExpr(
        ExprCall(ExprVar("mozilla::ipc::LogicError"), args=[ExprLiteral.String(msg)])
    )


def _sentinelReadError(classname):
    return StmtExpr(
        ExprCall(
            ExprVar("mozilla::ipc::SentinelReadError"),
            args=[ExprLiteral.String(classname)],
        )
    )


# Results that IPDL-generated code returns back to *Channel code.
# Users never see these


class _Result:
    @staticmethod
    def Type():
        return Type("Result")

    Processed = ExprVar("MsgProcessed")
    NotKnown = ExprVar("MsgNotKnown")
    NotAllowed = ExprVar("MsgNotAllowed")
    PayloadError = ExprVar("MsgPayloadError")
    ProcessingError = ExprVar("MsgProcessingError")
    RouteError = ExprVar("MsgRouteError")
    ValuError = ExprVar("MsgValueError")  # [sic]


# these |errfn*| are functions that generate code to be executed on an
# error, such as "bad actor ID".  each is given a Python string
# containing a description of the error

# used in user-facing Send*() methods


def errfnSend(msg, errcode=ExprLiteral.FALSE):
    return [_fatalError(msg), StmtReturn(errcode)]


def errfnSendCtor(msg):
    return errfnSend(msg, errcode=ExprLiteral.NULL)


# TODO should this error handling be strengthened for dtors?


def errfnSendDtor(msg):
    return [_printErrorMessage(msg), StmtReturn.FALSE]


# used in |OnMessage*()| handlers that hand in-messages off to Recv*()
# interface methods


def errfnRecv(msg, errcode=_Result.ValuError):
    return [_fatalError(msg), StmtReturn(errcode)]


def errfnSentinel(rvalue=ExprLiteral.FALSE):
    def inner(msg):
        return [_sentinelReadError(msg), StmtReturn(rvalue)]

    return inner


def _destroyMethod():
    return ExprVar("ActorDestroy")


def errfnUnreachable(msg):
    return [_logicError(msg)]


def readResultError():
    return ExprCode("{}")


class _DestroyReason:
    @staticmethod
    def Type():
        return Type("ActorDestroyReason")

    Deletion = ExprVar("Deletion")
    AncestorDeletion = ExprVar("AncestorDeletion")
    NormalShutdown = ExprVar("NormalShutdown")
    AbnormalShutdown = ExprVar("AbnormalShutdown")
    FailedConstructor = ExprVar("FailedConstructor")
    ManagedEndpointDropped = ExprVar("ManagedEndpointDropped")


class _ResponseRejectReason:
    @staticmethod
    def Type():
        return Type("ResponseRejectReason")

    SendError = ExprVar("ResponseRejectReason::SendError")
    ChannelClosed = ExprVar("ResponseRejectReason::ChannelClosed")
    HandlerRejected = ExprVar("ResponseRejectReason::HandlerRejected")
    ActorDestroyed = ExprVar("ResponseRejectReason::ActorDestroyed")


# -----------------------------------------------------------------------------
# Intermediate representation (IR) nodes used during lowering


class _ConvertToCxxType(TypeVisitor):
    def __init__(self, side, fq):
        self.side = side
        self.fq = fq

    def typename(self, thing):
        if self.fq:
            return thing.fullname()
        return thing.name()

    def visitImportedCxxType(self, t):
        cxxtype = Type(self.typename(t))
        if t.isRefcounted():
            cxxtype = _refptr(cxxtype)
        return cxxtype

    def visitBuiltinCType(self, b):
        return Type(self.typename(b))

    def visitActorType(self, a):
        if self.side is None:
            return Type(
                "::mozilla::ipc::SideVariant",
                T=[
                    _cxxBareType(a, "parent", self.fq),
                    _cxxBareType(a, "child", self.fq),
                ],
            )
        return Type(_actorName(self.typename(a.protocol), self.side), ptr=True)

    def visitStructType(self, s):
        return Type(self.typename(s))

    def visitUnionType(self, u):
        return Type(self.typename(u))

    def visitArrayType(self, a):
        basecxxtype = a.basetype.accept(self)
        return _cxxArrayType(basecxxtype)

    def visitMaybeType(self, m):
        basecxxtype = m.basetype.accept(self)
        return _cxxMaybeType(basecxxtype)

    def visitShmemType(self, s):
        return Type(self.typename(s))

    def visitByteBufType(self, s):
        return Type(self.typename(s))

    def visitFDType(self, s):
        return Type(self.typename(s))

    def visitEndpointType(self, s):
        return Type(self.typename(s))

    def visitManagedEndpointType(self, s):
        return Type(self.typename(s))

    def visitUniquePtrType(self, s):
        return Type(self.typename(s))

    def visitNotNullType(self, n):
        basecxxtype = n.basetype.accept(self)
        return _cxxNotNullType(basecxxtype)

    def visitProtocolType(self, p):
        assert 0

    def visitMessageType(self, m):
        assert 0

    def visitVoidType(self, v):
        assert 0


def _cxxBareType(ipdltype, side, fq=False):
    return ipdltype.accept(_ConvertToCxxType(side, fq))


def _cxxRefType(ipdltype, side):
    t = _cxxBareType(ipdltype, side)
    t.ref = True
    return t


def _cxxConstRefType(ipdltype, side):
    t = _cxxBareType(ipdltype, side)
    if ipdltype.isIPDL() and ipdltype.isActor():
        return t
    if ipdltype.isIPDL() and ipdltype.isShmem():
        t.ref = True
        return t
    if ipdltype.isIPDL() and ipdltype.isNotNull():
        # If the inner type chooses to use a raw pointer, wrap that instead.
        inner = _cxxConstRefType(ipdltype.basetype, side)
        if inner.ptr:
            t = _cxxNotNullType(inner)
            return t
    if ipdltype.isIPDL() and ipdltype.hasBaseType():
        # Keep same constness as inner type.
        inner = _cxxConstRefType(ipdltype.basetype, side)
        t.const = inner.const or not inner.ref
        t.ref = True
        return t
    if ipdltype.isCxx() and (ipdltype.isSendMoveOnly() or ipdltype.isDataMoveOnly()):
        t.const = True
        t.ref = True
        return t
    if ipdltype.isCxx() and ipdltype.isRefcounted():
        # Use T* instead of const RefPtr<T>&
        t = t.T
        t.ptr = True
        return t
    t.const = True
    t.ref = True
    return t


def _cxxTypeNeedsMoveForSend(ipdltype, context="root", visited=None):
    """Returns `True` if serializing ipdltype requires a mutable reference, e.g.
    because the underlying resource represented by the value is being
    transferred to another process. This is occasionally distinct from whether
    the C++ type exposes a copy constructor, such as for types which are not
    cheaply copiable, but are not mutated when serialized."""

    if visited is None:
        visited = set()

    visited.add(ipdltype)

    if ipdltype.isCxx():
        return ipdltype.isSendMoveOnly()

    if ipdltype.isIPDL():
        if ipdltype.hasBaseType():
            return _cxxTypeNeedsMoveForSend(ipdltype.basetype, "wrapper", visited)
        if ipdltype.isStruct() or ipdltype.isUnion():
            return any(
                _cxxTypeNeedsMoveForSend(t, "compound", visited)
                for t in ipdltype.itercomponents()
                if t not in visited
            )

        # For historical reasons, shmem is `const_cast` to a mutable reference
        # when being stored in a struct or union (see
        # `_StructField.constRefExpr` and `_UnionMember.getConstValue`), meaning
        # that they do not cause the containing struct to require move for
        # sending.
        if ipdltype.isShmem():
            return context != "compound"

        return (
            ipdltype.isByteBuf()
            or ipdltype.isEndpoint()
            or ipdltype.isManagedEndpoint()
        )

    return False


def _cxxTypeNeedsMoveForData(ipdltype, context="root", visited=None):
    """Returns `True` if the bare C++ type corresponding to ipdltype does not
    satisfy std::is_copy_constructible_v<T>. All C++ types supported by IPDL
    must support std::is_move_constructible_v<T>, so non-movable types must be
    passed behind a `UniquePtr`."""

    if visited is None:
        visited = set()

    visited.add(ipdltype)

    if ipdltype.isCxx():
        return ipdltype.isDataMoveOnly()

    if ipdltype.isIPDL():
        if ipdltype.isUniquePtr():
            return True

        # When nested within a maybe or array, arrays are no longer copyable.
        if context == "wrapper" and ipdltype.isArray():
            return True
        if ipdltype.hasBaseType():
            return _cxxTypeNeedsMoveForData(ipdltype.basetype, "wrapper", visited)
        if ipdltype.isStruct() or ipdltype.isUnion():
            return any(
                _cxxTypeNeedsMoveForData(t, "compound", visited)
                for t in ipdltype.itercomponents()
                if t not in visited
            )
        return (
            ipdltype.isByteBuf()
            or ipdltype.isEndpoint()
            or ipdltype.isManagedEndpoint()
        )

    return False


def _cxxTypeCanMove(ipdltype):
    return not (ipdltype.isIPDL() and ipdltype.isActor())


def _cxxForceMoveRefType(ipdltype, side):
    assert _cxxTypeCanMove(ipdltype)
    t = _cxxBareType(ipdltype, side)
    t.rvalref = True
    return t


def _cxxPtrToType(ipdltype, side):
    t = _cxxBareType(ipdltype, side)
    if ipdltype.isIPDL() and ipdltype.isActor() and side is not None:
        t.ptr = False
        t.ptrptr = True
        return t
    t.ptr = True
    return t


def _cxxConstPtrToType(ipdltype, side):
    t = _cxxBareType(ipdltype, side)
    if ipdltype.isIPDL() and ipdltype.isActor() and side is not None:
        t.ptr = False
        t.ptrconstptr = True
        return t
    t.const = True
    t.ptr = True
    return t


def _cxxInType(ipdltype, side, direction):
    t = _cxxBareType(ipdltype, side)
    if ipdltype.isIPDL() and ipdltype.isActor():
        return t
    if ipdltype.isIPDL() and ipdltype.isNotNull():
        # If the inner type chooses to use a raw pointer, wrap that instead.
        inner = _cxxInType(ipdltype.basetype, side, direction)
        if inner.ptr:
            t = _cxxNotNullType(inner)
            return t
    if _cxxTypeNeedsMoveForSend(ipdltype):
        t.rvalref = True
        return t
    if ipdltype.isCxx():
        if ipdltype.isRefcounted():
            # Use T* instead of const RefPtr<T>&
            t = t.T
            t.ptr = True
            return t
        if ipdltype.name() == "nsCString":
            t = Type("nsACString")
        if ipdltype.name() == "nsString":
            t = Type("nsAString")
    # Use Span<T const> rather than nsTArray<T> for array types which aren't
    # `_cxxTypeNeedsMoveForSend`. This is only done for the "send" side, and not
    # for recv signatures.
    if direction == "send" and ipdltype.isIPDL() and ipdltype.isArray():
        inner = _cxxBareType(ipdltype.basetype, side)
        return _cxxSpanType(inner)

    t.const = True
    t.ref = True
    return t


def _allocMethod(ptype, side):
    return "Alloc" + ptype.name() + side.title()


def _deallocMethod(ptype, side):
    return "Dealloc" + ptype.name() + side.title()


##
# A _HybridDecl straddles IPDL and C++ decls.  It knows which C++
# types correspond to which IPDL types, and it also knows how
# serialize and deserialize "special" IPDL C++ types.
##


class _HybridDecl:
    """A hybrid decl stores both an IPDL type and all the C++ type
    info needed by later passes, along with a basic name for the decl."""

    def __init__(self, ipdltype, name, attributes={}):
        self.ipdltype = ipdltype
        self.name = name
        self.attributes = attributes

    def var(self):
        return ExprVar(self.name)

    def bareType(self, side, fq=False):
        """Return this decl's unqualified C++ type."""
        return _cxxBareType(self.ipdltype, side, fq=fq)

    def refType(self, side):
        """Return this decl's C++ type as a 'reference' type, which is not
        necessarily a C++ reference."""
        return _cxxRefType(self.ipdltype, side)

    def constRefType(self, side):
        """Return this decl's C++ type as a const, 'reference' type."""
        return _cxxConstRefType(self.ipdltype, side)

    def ptrToType(self, side):
        return _cxxPtrToType(self.ipdltype, side)

    def constPtrToType(self, side):
        return _cxxConstPtrToType(self.ipdltype, side)

    def inType(self, side, direction):
        """Return this decl's C++ Type with sending inparam semantics."""
        return _cxxInType(self.ipdltype, side, direction)

    def outType(self, side):
        """Return this decl's C++ Type with outparam semantics."""
        t = self.bareType(side)
        if self.ipdltype.isIPDL() and self.ipdltype.isActor():
            t.ptr = False
            t.ptrptr = True
            return t
        t.ptr = True
        return t

    def forceMoveType(self, side):
        """Return this decl's C++ Type with forced move semantics."""
        assert _cxxTypeCanMove(self.ipdltype)
        return _cxxForceMoveRefType(self.ipdltype, side)


# --------------------------------------------------


class HasFQName:
    def fqClassName(self):
        return self.decl.type.fullname()


class _CompoundTypeComponent(_HybridDecl):
    # @override the following methods to make the side argument optional.
    def bareType(self, side=None, fq=False):
        return _HybridDecl.bareType(self, side, fq=fq)

    def refType(self, side=None):
        return _HybridDecl.refType(self, side)

    def constRefType(self, side=None):
        return _HybridDecl.constRefType(self, side)

    def ptrToType(self, side=None):
        return _HybridDecl.ptrToType(self, side)

    def constPtrToType(self, side=None):
        return _HybridDecl.constPtrToType(self, side)

    def forceMoveType(self, side=None):
        return _HybridDecl.forceMoveType(self, side)


class StructDecl(ipdl.ast.StructDecl, HasFQName):
    def fields_ipdl_order(self):
        for f in self.fields:
            yield f

    def fields_member_order(self):
        assert len(self.packed_field_order) == len(self.fields)

        for i in self.packed_field_order:
            yield self.fields[i]

    @staticmethod
    def upgrade(structDecl):
        assert isinstance(structDecl, ipdl.ast.StructDecl)
        structDecl.__class__ = StructDecl


class _StructField(_CompoundTypeComponent):
    def __init__(self, ipdltype, name, sd):
        self.basename = name

        _CompoundTypeComponent.__init__(self, ipdltype, name)

    def getMethod(self, thisexpr=None, sel="."):
        meth = self.var()
        if thisexpr is not None:
            return ExprSelect(thisexpr, sel, meth.name)
        return meth

    def refExpr(self, thisexpr=None):
        ref = self.memberVar()
        if thisexpr is not None:
            ref = ExprSelect(thisexpr, ".", ref.name)
        return ref

    def constRefExpr(self, thisexpr=None):
        # sigh, gross hack
        refexpr = self.refExpr(thisexpr)
        if "Shmem" == self.ipdltype.name():
            refexpr = ExprCast(refexpr, Type("Shmem", ref=True), const=True)
        return refexpr

    def argVar(self):
        return ExprVar("_" + self.name)

    def memberVar(self):
        return ExprVar(self.name + "_")


class UnionDecl(ipdl.ast.UnionDecl, HasFQName):
    def callType(self, var=None):
        func = ExprVar("type")
        if var is not None:
            func = ExprSelect(var, ".", func.name)
        return ExprCall(func)

    @staticmethod
    def upgrade(unionDecl):
        assert isinstance(unionDecl, ipdl.ast.UnionDecl)
        unionDecl.__class__ = UnionDecl


class _UnionMember(_CompoundTypeComponent):
    """Not in the AFL sense, but rather a member (e.g. |int;|) of an
    IPDL union type."""

    def __init__(self, ipdltype, ud):
        flatname = _flatTypeName(ipdltype)

        _CompoundTypeComponent.__init__(self, ipdltype, "V" + flatname)
        self.flattypename = flatname

        # To create a finite object with a mutually recursive type, a union must
        # be present somewhere in the recursive loop. Because of that we only
        # need to care about introducing indirections inside unions.
        self.recursive = ud.decl.type.mutuallyRecursiveWith(ipdltype)

    def enum(self):
        return "T" + self.flattypename

    def enumvar(self):
        return ExprVar(self.enum())

    def internalType(self):
        if self.recursive:
            return self.ptrToType()
        else:
            return self.bareType()

    def unionType(self):
        """Type used for storage in generated C union decl."""
        if self.recursive:
            return self.ptrToType()
        else:
            return Type("mozilla::AlignedStorage2", T=self.internalType())

    def unionValue(self):
        # NB: knows that Union's storage C union is named |mValue|
        return ExprSelect(ExprVar("mValue"), ".", self.name)

    def typedef(self):
        return self.flattypename + "__tdef"

    def callGetConstPtr(self):
        """Return an expression of type self.constptrToSelfType()"""
        return ExprCall(ExprVar(self.getConstPtrName()))

    def callGetPtr(self):
        """Return an expression of type self.ptrToSelfType()"""
        return ExprCall(ExprVar(self.getPtrName()))

    def callCtor(self, expr=None):
        assert not isinstance(expr, list)

        if expr is None:
            args = None
        elif (
            self.ipdltype.isIPDL()
            and self.ipdltype.isArray()
            and not isinstance(expr, ExprMove)
        ):
            args = [ExprCall(ExprSelect(expr, ".", "Clone"), args=[])]
        else:
            args = [expr]

        if self.recursive:
            return ExprAssn(self.callGetPtr(), ExprNew(self.bareType(), args=args))
        else:
            return ExprNew(
                self.bareType(),
                args=args,
                newargs=[ExprVar("mozilla::KnownNotNull"), self.callGetPtr()],
            )

    def callDtor(self):
        if self.recursive:
            return ExprDelete(self.callGetPtr())
        else:
            return ExprCall(ExprSelect(self.callGetPtr(), "->", "~" + self.typedef()))

    def getTypeName(self):
        return "get_" + self.flattypename

    def getConstTypeName(self):
        return "get_" + self.flattypename

    def getOtherTypeName(self):
        return "get_" + self.otherflattypename

    def getPtrName(self):
        return "ptr_" + self.flattypename

    def getConstPtrName(self):
        return "constptr_" + self.flattypename

    def ptrToSelfExpr(self):
        """|*ptrToSelfExpr()| has type |self.bareType()|"""
        v = self.unionValue()
        if self.recursive:
            return v
        else:
            return ExprCall(ExprSelect(v, ".", "addr"))

    def constptrToSelfExpr(self):
        """|*constptrToSelfExpr()| has type |self.constType()|"""
        v = self.unionValue()
        if self.recursive:
            return v
        return ExprCall(ExprSelect(v, ".", "addr"))

    def ptrToInternalType(self):
        t = self.ptrToType()
        if self.recursive:
            t.ref = True
        return t

    def defaultValue(self, fq=False):
        # Use the default constructor for any class that does not have an
        # implicit copy constructor.
        if not self.bareType().hasimplicitcopyctor:
            return None

        if self.ipdltype.isIPDL() and self.ipdltype.isActor():
            return ExprLiteral.NULL
        # XXX sneaky here, maybe need ExprCtor()?
        return ExprCall(self.bareType(fq=fq))

    def getConstValue(self):
        v = ExprDeref(self.callGetConstPtr())
        # sigh
        if "Shmem" == self.ipdltype.name():
            v = ExprCast(v, Type("Shmem", ref=True), const=True)
        return v


# --------------------------------------------------


class MessageDecl(ipdl.ast.MessageDecl):
    def baseName(self):
        return self.name

    def recvMethod(self):
        name = _recvPrefix(self.decl.type) + self.baseName()
        if self.decl.type.isCtor():
            name += "Constructor"
        return name

    def sendMethod(self):
        name = _sendPrefix(self.decl.type) + self.baseName()
        if self.decl.type.isCtor():
            name += "Constructor"
        return name

    def hasReply(self):
        return (
            self.decl.type.hasReply()
            or self.decl.type.isCtor()
            or self.decl.type.isDtor()
        )

    def hasAsyncReturns(self):
        return self.decl.type.isAsync() and self.returns

    def msgCtorFunc(self):
        return "Msg_%s" % (self.decl.progname)

    def prettyMsgName(self, pfx=""):
        return pfx + self.msgCtorFunc()

    def pqMsgCtorFunc(self):
        return "%s::%s" % (self.namespace, self.msgCtorFunc())

    def msgId(self):
        return self.msgCtorFunc() + "__ID"

    def pqMsgId(self):
        return "%s::%s" % (self.namespace, self.msgId())

    def replyCtorFunc(self):
        return "Reply_%s" % (self.decl.progname)

    def pqReplyCtorFunc(self):
        return "%s::%s" % (self.namespace, self.replyCtorFunc())

    def replyId(self):
        return self.replyCtorFunc() + "__ID"

    def pqReplyId(self):
        return "%s::%s" % (self.namespace, self.replyId())

    def prettyReplyName(self, pfx=""):
        return pfx + self.replyCtorFunc()

    def promiseName(self):
        name = self.baseName()
        if self.decl.type.isCtor():
            name += "Constructor"
        name += "Promise"
        return name

    def resolverName(self):
        return self.baseName() + "Resolver"

    def actorDecl(self):
        return self.params[0]

    def makeCxxParams(
        self, paramsems="in", returnsems="out", side=None, implicit=True, direction=None
    ):
        """Return a list of C++ decls per the spec'd configuration.
        |params| and |returns| is the C++ semantics of those: 'in', 'out', or None."""

        def makeDecl(d, sems):
            if (
                self.decl.type.tainted
                and "NoTaint" not in d.attributes
                and direction == "recv"
            ):
                # Tainted types are passed by-value, allowing the receiver to move them if desired.
                assert sems != "out"
                return Decl(Type("Tainted", T=d.bareType(side)), d.name)

            if sems == "in":
                t = d.inType(side, direction)
                # If this is the `recv` side, and we're not using "move"
                # semantics, that means we're an alloc method, and cannot accept
                # values by rvalue reference. Downgrade to an lvalue reference.
                if direction == "recv" and t.rvalref:
                    t.rvalref = False
                    t.ref = True
                return Decl(t, d.name)
            elif sems == "move":
                assert direction == "recv"
                # For legacy reasons, use an rvalue reference when generating
                # parameters for recv methods which accept arrays.
                if d.ipdltype.isIPDL() and d.ipdltype.isArray():
                    t = d.bareType(side)
                    t.rvalref = True
                    return Decl(t, d.name)
                return Decl(d.inType(side, direction), d.name)
            elif sems == "out":
                return Decl(d.outType(side), d.name)
            else:
                assert 0

        def makeResolverDecl(returns):
            return Decl(Type(self.resolverName(), rvalref=True), "aResolve")

        def makeCallbackResolveDecl(returns):
            if len(returns) > 1:
                resolvetype = _tuple([d.bareType(side) for d in returns])
            else:
                resolvetype = returns[0].bareType(side)

            return Decl(
                Type("mozilla::ipc::ResolveCallback", T=resolvetype, rvalref=True),
                "aResolve",
            )

        def makeCallbackRejectDecl(returns):
            return Decl(Type("mozilla::ipc::RejectCallback", rvalref=True), "aReject")

        cxxparams = []
        if paramsems is not None:
            cxxparams.extend([makeDecl(d, paramsems) for d in self.params])

        if returnsems == "promise" and self.returns:
            pass
        elif returnsems == "callback" and self.returns:
            cxxparams.extend(
                [
                    makeCallbackResolveDecl(self.returns),
                    makeCallbackRejectDecl(self.returns),
                ]
            )
        elif returnsems == "resolver" and self.returns:
            cxxparams.extend([makeResolverDecl(self.returns)])
        elif returnsems is not None:
            cxxparams.extend([makeDecl(r, returnsems) for r in self.returns])

        if not implicit and self.decl.type.hasImplicitActorParam():
            cxxparams = cxxparams[1:]

        return cxxparams

    def makeCxxArgs(
        self, paramsems="in", retsems="out", retcallsems="out", implicit=True
    ):
        assert not retcallsems or retsems  # retcallsems => returnsems
        cxxargs = []

        if paramsems == "move":
            # We don't std::move() RefPtr<T> types because current Recv*()
            # implementors take these parameters as T*, and
            # std::move(RefPtr<T>) doesn't coerce to T*.
            # We also don't move NotNull, as it has no move constructor.
            cxxargs.extend(
                [
                    p.var()
                    if p.ipdltype.isRefcounted()
                    or (p.ipdltype.isIPDL() and p.ipdltype.isNotNull())
                    else ExprMove(p.var())
                    for p in self.params
                ]
            )
        elif paramsems == "in":
            cxxargs.extend([p.var() for p in self.params])
        else:
            assert False

        for ret in self.returns:
            if retsems == "in":
                if retcallsems == "in":
                    cxxargs.append(ret.var())
                elif retcallsems == "out":
                    cxxargs.append(ExprAddrOf(ret.var()))
                else:
                    assert 0
            elif retsems == "out":
                if retcallsems == "in":
                    cxxargs.append(ExprDeref(ret.var()))
                elif retcallsems == "out":
                    cxxargs.append(ret.var())
                else:
                    assert 0
            elif retsems == "resolver":
                pass
        if retsems == "resolver":
            cxxargs.append(ExprMove(ExprVar("resolver")))

        if not implicit:
            assert self.decl.type.hasImplicitActorParam()
            cxxargs = cxxargs[1:]

        return cxxargs

    @staticmethod
    def upgrade(messageDecl):
        assert isinstance(messageDecl, ipdl.ast.MessageDecl)
        if messageDecl.decl.type.hasImplicitActorParam():
            messageDecl.params.insert(
                0,
                _HybridDecl(
                    ipdl.type.ActorType(messageDecl.decl.type.constructedType()),
                    "actor",
                ),
            )
        messageDecl.__class__ = MessageDecl


# --------------------------------------------------
def _usesShmem(p):
    for md in p.messageDecls:
        for param in md.inParams:
            if ipdl.type.hasshmem(param.type):
                return True
        for ret in md.outParams:
            if ipdl.type.hasshmem(ret.type):
                return True
    return False


def _subtreeUsesShmem(p):
    if _usesShmem(p):
        return True

    ptype = p.decl.type
    for mgd in ptype.manages:
        if ptype is not mgd:
            if _subtreeUsesShmem(mgd._ast):
                return True
    return False


class Protocol(ipdl.ast.Protocol):
    def managerInterfaceType(self, ptr=False):
        return Type("mozilla::ipc::IProtocol", ptr=ptr)

    def openedProtocolInterfaceType(self, ptr=False):
        return Type("mozilla::ipc::IToplevelProtocol", ptr=ptr)

    def _ipdlmgrtype(self):
        assert 1 == len(self.decl.type.managers)
        for mgr in self.decl.type.managers:
            return mgr

    def managerActorType(self, side, ptr=False):
        return Type(_actorName(self._ipdlmgrtype().name(), side), ptr=ptr)

    def unregisterMethod(self, actorThis=None):
        if actorThis is not None:
            return ExprSelect(actorThis, "->", "Unregister")
        return ExprVar("Unregister")

    def removeManageeMethod(self):
        return ExprVar("RemoveManagee")

    def deallocManageeMethod(self):
        return ExprVar("DeallocManagee")

    def getChannelMethod(self):
        return ExprVar("GetIPCChannel")

    def callGetChannel(self, actorThis=None):
        fn = self.getChannelMethod()
        if actorThis is not None:
            fn = ExprSelect(actorThis, "->", fn.name)
        return ExprCall(fn)

    def processingErrorVar(self):
        assert self.decl.type.isToplevel()
        return ExprVar("ProcessingError")

    def shouldContinueFromTimeoutVar(self):
        assert self.decl.type.isToplevel()
        return ExprVar("ShouldContinueFromReplyTimeout")

    def routingId(self, actorThis=None):
        if self.decl.type.isToplevel():
            return ExprVar("MSG_ROUTING_CONTROL")
        if actorThis is not None:
            return ExprCall(ExprSelect(actorThis, "->", "Id"))
        return ExprCall(ExprVar("Id"))

    def managerVar(self, thisexpr=None):
        assert thisexpr is not None or not self.decl.type.isToplevel()
        mvar = ExprCall(ExprVar("Manager"), args=[])
        if thisexpr is not None:
            mvar = ExprCall(ExprSelect(thisexpr, "->", "Manager"), args=[])
        return mvar

    def managedCxxType(self, actortype, side):
        assert self.decl.type.isManagerOf(actortype)
        return Type(_actorName(actortype.name(), side), ptr=True)

    def managedMethod(self, actortype, side):
        assert self.decl.type.isManagerOf(actortype)
        return ExprVar("Managed" + _actorName(actortype.name(), side))

    def managedVar(self, actortype, side):
        assert self.decl.type.isManagerOf(actortype)
        return ExprVar("mManaged" + _actorName(actortype.name(), side))

    def managedVarType(self, actortype, side, const=False, ref=False):
        assert self.decl.type.isManagerOf(actortype)
        return _cxxManagedContainerType(
            Type(_actorName(actortype.name(), side)), const=const, ref=ref
        )

    def subtreeUsesShmem(self):
        return _subtreeUsesShmem(self)

    @staticmethod
    def upgrade(protocol):
        assert isinstance(protocol, ipdl.ast.Protocol)
        protocol.__class__ = Protocol


class TranslationUnit(ipdl.ast.TranslationUnit):
    @staticmethod
    def upgrade(tu):
        assert isinstance(tu, ipdl.ast.TranslationUnit)
        tu.__class__ = TranslationUnit


# -----------------------------------------------------------------------------

pod_types = {
    "::int8_t": 1,
    "::uint8_t": 1,
    "::int16_t": 2,
    "::uint16_t": 2,
    "::int32_t": 4,
    "::uint32_t": 4,
    "::int64_t": 8,
    "::uint64_t": 8,
    "float": 4,
    "double": 8,
}
max_pod_size = max(pod_types.values())
# We claim that all types we don't recognize are automatically "bigger"
# than pod types for ease of sorting.
pod_size_sentinel = max_pod_size * 2


def pod_size(ipdltype):
    if not ipdltype.isCxx():
        return pod_size_sentinel

    return pod_types.get(ipdltype.fullname(), pod_size_sentinel)


class _DecorateWithCxxStuff(ipdl.ast.Visitor):
    """Phase 1 of lowering: decorate the IPDL AST with information
    relevant to C++ code generation.

    This pass results in an AST that is a poor man's "IR"; in reality, a
    "hybrid" AST mainly consisting of IPDL nodes with new C++ info along
    with some new IPDL/C++ nodes that are tuned for C++ codegen."""

    def __init__(self):
        self.visitedTus = set()
        self.protocolName = None

    def visitTranslationUnit(self, tu):
        if tu not in self.visitedTus:
            self.visitedTus.add(tu)
            ipdl.ast.Visitor.visitTranslationUnit(self, tu)
            if not isinstance(tu, TranslationUnit):
                TranslationUnit.upgrade(tu)

    def visitInclude(self, inc):
        if inc.tu.filetype == "header":
            inc.tu.accept(self)

    def visitProtocol(self, pro):
        self.protocolName = pro.name
        Protocol.upgrade(pro)
        return ipdl.ast.Visitor.visitProtocol(self, pro)

    def visitStructDecl(self, sd):
        if not isinstance(sd, StructDecl):
            newfields = [_StructField(f.decl.type, f.name, sd) for f in sd.fields]

            # Compute a permutation of the fields for in-memory storage such
            # that the memory layout of the structure will be well-packed.
            permutation = list(range(len(newfields)))

            # Note that the results of `pod_size` ensure that non-POD fields
            # sort before POD ones.
            def size(idx):
                return pod_size(newfields[idx].ipdltype)

            permutation.sort(key=size, reverse=True)

            sd.fields = newfields
            sd.packed_field_order = permutation
            StructDecl.upgrade(sd)

    def visitUnionDecl(self, ud):
        ud.components = [_UnionMember(ctype, ud) for ctype in ud.decl.type.components]
        UnionDecl.upgrade(ud)

    def visitDecl(self, decl):
        return _HybridDecl(decl.type, decl.progname, decl.attributes)

    def visitMessageDecl(self, md):
        md.namespace = self.protocolName
        md.params = [param.accept(self) for param in md.inParams]
        md.returns = [ret.accept(self) for ret in md.outParams]
        MessageDecl.upgrade(md)


# -----------------------------------------------------------------------------


def msgenums(protocol, pretty=False):
    msgenum = TypeEnum("MessageType")
    msgstart = _messageStartName(protocol.decl.type) + " << 16"
    msgenum.addId(protocol.name + "Start", msgstart)

    for md in protocol.messageDecls:
        msgenum.addId(md.prettyMsgName() if pretty else md.msgId())
        if md.hasReply():
            msgenum.addId(md.prettyReplyName() if pretty else md.replyId())

    msgenum.addId(protocol.name + "End")
    return msgenum


class _GenerateProtocolCode(ipdl.ast.Visitor):
    """Creates code common to both the parent and child actors."""

    def __init__(self):
        self.protocol = None  # protocol we're generating a class for
        self.hdrfile = None  # what will become Protocol.h
        self.cppfile = None  # what will become Protocol.cpp
        self.cppIncludeHeaders = []
        self.structUnionDefns = []
        self.funcDefns = []

    def lower(self, tu, cxxHeaderFile, cxxFile, segmentcapacitydict):
        self.protocol = tu.protocol
        self.hdrfile = cxxHeaderFile
        self.cppfile = cxxFile
        self.segmentcapacitydict = segmentcapacitydict
        tu.accept(self)

    def visitTranslationUnit(self, tu):
        hf = self.hdrfile

        hf.addthing(_DISCLAIMER)
        hf.addthings(_includeGuardStart(hf))
        hf.addthing(Whitespace.NL)

        for inc in builtinHeaderIncludes:
            self.visitBuiltinCxxInclude(inc)

        # Compute the set of includes we need for declared structure/union
        # classes for this protocol.
        typesToIncludes = {}
        for using in tu.using:
            typestr = str(using.type)
            if typestr not in typesToIncludes:
                typesToIncludes[typestr] = using.header
            else:
                assert typesToIncludes[typestr] == using.header

        aggregateTypeIncludes = set()
        for su in tu.structsAndUnions:
            typedeps = _ComputeTypeDeps(su.decl.type, typesToIncludes)
            if isinstance(su, ipdl.ast.StructDecl):
                aggregateTypeIncludes.add("mozilla/ipc/IPDLStructMember.h")
                for f in su.fields:
                    f.ipdltype.accept(typedeps)
            elif isinstance(su, ipdl.ast.UnionDecl):
                for c in su.components:
                    c.ipdltype.accept(typedeps)

            aggregateTypeIncludes.update(typedeps.includeHeaders)

        if len(aggregateTypeIncludes) != 0:
            hf.addthing(Whitespace.NL)
            hf.addthings([Whitespace("// Headers for typedefs"), Whitespace.NL])

            for headername in sorted(iter(aggregateTypeIncludes)):
                hf.addthing(CppDirective("include", '"' + headername + '"'))

        # Manually run Visitor.visitTranslationUnit. For dependency resolution
        # we need to handle structs and unions separately.
        for cxxInc in tu.cxxIncludes:
            cxxInc.accept(self)
        for inc in tu.includes:
            inc.accept(self)
        self.generateStructsAndUnions(tu)
        for using in tu.builtinUsing:
            using.accept(self)
        for using in tu.using:
            using.accept(self)
        if tu.protocol:
            tu.protocol.accept(self)

        if tu.filetype == "header":
            self.cppIncludeHeaders.append(_ipdlhHeaderName(tu) + ".h")

        hf.addthing(Whitespace.NL)
        hf.addthings(_includeGuardEnd(hf))

        cf = self.cppfile
        cf.addthings(
            (
                [_DISCLAIMER, Whitespace.NL]
                + [
                    CppDirective("include", '"' + h + '"')
                    for h in self.cppIncludeHeaders
                ]
                + [Whitespace.NL]
                + [
                    CppDirective("include", '"%s"' % filename)
                    for filename in ipdl.builtin.CppIncludes
                ]
                + [Whitespace.NL]
            )
        )

        if self.protocol:
            # construct the namespace into which we'll stick all our defns
            ns = Namespace(self.protocol.name)
            cf.addthing(_putInNamespaces(ns, self.protocol.namespaces))
            ns.addstmts(([Whitespace.NL] + self.funcDefns + [Whitespace.NL]))

        cf.addthings(self.structUnionDefns)

    def visitBuiltinCxxInclude(self, inc):
        self.hdrfile.addthing(CppDirective("include", '"' + inc.file + '"'))

    def visitCxxInclude(self, inc):
        self.cppIncludeHeaders.append(inc.file)

    def visitInclude(self, inc):
        if inc.tu.filetype == "header":
            self.hdrfile.addthing(
                CppDirective("include", '"' + _ipdlhHeaderName(inc.tu) + '.h"')
            )
            # Inherit cpp includes defined by imported header files, as they may
            # be required to serialize an imported `using` type.
            for cxxinc in inc.tu.cxxIncludes:
                cxxinc.accept(self)
        else:
            self.cppIncludeHeaders += [
                _protocolHeaderName(inc.tu.protocol, "parent") + ".h",
                _protocolHeaderName(inc.tu.protocol, "child") + ".h",
            ]

    def generateStructsAndUnions(self, tu):
        """Generate the definitions for all structs and unions. This will
        re-order the declarations if needed in the C++ code such that
        dependencies have already been defined."""
        decls = OrderedDict()
        for su in tu.structsAndUnions:
            if isinstance(su, StructDecl):
                which = "struct"
                forwarddecls, fulldecltypes, cls = _generateCxxStruct(su)
                traitsdecl, traitsdefns = _ParamTraits.structPickling(su.decl.type)
            else:
                assert isinstance(su, UnionDecl)
                which = "union"
                forwarddecls, fulldecltypes, cls = _generateCxxUnion(su)
                traitsdecl, traitsdefns = _ParamTraits.unionPickling(su.decl.type)

            clsdecl, methoddefns = _splitClassDeclDefn(cls)

            # Store the declarations in the decls map so we can emit in
            # dependency order.
            decls[su.decl.type] = (
                fulldecltypes,
                [Whitespace.NL]
                + forwarddecls
                + [
                    Whitespace(
                        """
//-----------------------------------------------------------------------------
// Declaration of the IPDL type |%s %s|
//
"""
                        % (which, su.name)
                    ),
                    _putInNamespaces(clsdecl, su.namespaces),
                ]
                + [Whitespace.NL, traitsdecl],
            )

            self.structUnionDefns.extend(
                [
                    Whitespace(
                        """
//-----------------------------------------------------------------------------
// Method definitions for the IPDL type |%s %s|
//
"""
                        % (which, su.name)
                    ),
                    _putInNamespaces(methoddefns, su.namespaces),
                    Whitespace.NL,
                    traitsdefns,
                ]
            )

        # Generate the declarations structs in dependency order.
        def gen_struct(deps, defn):
            for dep in deps:
                if dep in decls:
                    d, t = decls[dep]
                    del decls[dep]
                    gen_struct(d, t)
            self.hdrfile.addthings(defn)

        while len(decls) > 0:
            _, (d, t) = decls.popitem(False)
            gen_struct(d, t)

    def visitProtocol(self, p):
        self.cppIncludeHeaders.append(_protocolHeaderName(self.protocol, "") + ".h")
        self.cppIncludeHeaders.append(
            _protocolHeaderName(self.protocol, "Parent") + ".h"
        )
        self.cppIncludeHeaders.append(
            _protocolHeaderName(self.protocol, "Child") + ".h"
        )

        # Forward declare our own actors.
        self.hdrfile.addthings(
            [
                Whitespace.NL,
                _makeForwardDeclForActor(p.decl.type, "Parent"),
                _makeForwardDeclForActor(p.decl.type, "Child"),
            ]
        )

        self.hdrfile.addthing(
            Whitespace(
                """
//-----------------------------------------------------------------------------
// Code common to %sChild and %sParent
//
"""
                % (p.name, p.name)
            )
        )

        # construct the namespace into which we'll stick all our decls
        ns = Namespace(self.protocol.name)
        self.hdrfile.addthing(_putInNamespaces(ns, p.namespaces))
        ns.addstmt(Whitespace.NL)

        for func in self.genEndpointFuncs():
            edecl, edefn = _splitFuncDeclDefn(func)
            ns.addstmts([edecl, Whitespace.NL])
            self.funcDefns.append(edefn)

        # spit out message type enum and classes
        msgenum = msgenums(self.protocol)
        ns.addstmts([StmtDecl(Decl(msgenum, "")), Whitespace.NL])

        for md in p.messageDecls:
            decls = []

            # Look up the segment capacity used for serializing this
            # message. If the capacity is not specified, use '0' for
            # the default capacity (defined in ipc_message.cc)
            name = "%s::%s" % (md.namespace, md.decl.progname)
            segmentcapacity = self.segmentcapacitydict.get(name, 0)

            mfDecl, mfDefn = _splitFuncDeclDefn(
                _generateMessageConstructor(md, segmentcapacity, p, forReply=False)
            )
            decls.append(mfDecl)
            self.funcDefns.append(mfDefn)

            if md.hasReply():
                rfDecl, rfDefn = _splitFuncDeclDefn(
                    _generateMessageConstructor(md, 0, p, forReply=True)
                )
                decls.append(rfDecl)
                self.funcDefns.append(rfDefn)

            decls.append(Whitespace.NL)
            ns.addstmts(decls)

        ns.addstmts([Whitespace.NL, Whitespace.NL])

    # Generate code for PFoo::CreateEndpoints.
    def genEndpointFuncs(self):
        p = self.protocol.decl.type
        tparent = _cxxBareType(ActorType(p), "Parent", fq=True)
        tchild = _cxxBareType(ActorType(p), "Child", fq=True)

        def mkOverload(includepids):
            params = []
            if includepids:
                params = [
                    Decl(Type("base::ProcessId"), "aParentDestPid"),
                    Decl(Type("base::ProcessId"), "aChildDestPid"),
                ]
            params += [
                Decl(
                    Type("mozilla::ipc::Endpoint<" + tparent.name + ">", ptr=True),
                    "aParent",
                ),
                Decl(
                    Type("mozilla::ipc::Endpoint<" + tchild.name + ">", ptr=True),
                    "aChild",
                ),
            ]
            openfunc = MethodDefn(
                MethodDecl("CreateEndpoints", params=params, ret=Type.NSRESULT)
            )
            openfunc.addcode(
                """
                return mozilla::ipc::CreateEndpoints(
                    mozilla::ipc::PrivateIPDLInterface(),
                    $,{args});
                """,
                args=[ExprVar(d.name) for d in params],
            )
            return openfunc

        funcs = [mkOverload(True)]
        if not p.hasOtherPid():
            funcs.append(mkOverload(False))
        return funcs


# --------------------------------------------------

cppPriorityList = list(
    map(lambda src: src.upper() + "_PRIORITY", ipdl.ast.priorityList)
)


def _generateMessageConstructor(md, segmentSize, protocol, forReply=False):
    if forReply:
        clsname = md.replyCtorFunc()
        msgid = md.replyId()
        replyEnum = "REPLY"
        prioEnum = cppPriorityList[md.decl.type.replyPrio]
    else:
        clsname = md.msgCtorFunc()
        msgid = md.msgId()
        replyEnum = "NOT_REPLY"
        prioEnum = cppPriorityList[md.decl.type.prio]

    nested = md.decl.type.nested
    compress = md.decl.type.compress
    lazySend = md.decl.type.lazySend

    routingId = ExprVar("routingId")

    func = FunctionDefn(
        FunctionDecl(
            clsname,
            params=[Decl(Type("int32_t"), routingId.name)],
            ret=Type("mozilla::UniquePtr<IPC::Message>"),
        )
    )

    if not compress:
        compression = "COMPRESSION_NONE"
    elif compress.value == "all":
        compression = "COMPRESSION_ALL"
    else:
        assert compress.value is None
        compression = "COMPRESSION_ENABLED"

    if lazySend:
        lazySendEnum = "LAZY_SEND"
    else:
        lazySendEnum = "EAGER_SEND"

    if nested == ipdl.ast.NOT_NESTED:
        nestedEnum = "NOT_NESTED"
    elif nested == ipdl.ast.INSIDE_SYNC_NESTED:
        nestedEnum = "NESTED_INSIDE_SYNC"
    else:
        assert nested == ipdl.ast.INSIDE_CPOW_NESTED
        nestedEnum = "NESTED_INSIDE_CPOW"

    if md.decl.type.isSync():
        syncEnum = "SYNC"
    else:
        syncEnum = "ASYNC"

    # FIXME(bug ???) - remove support for interrupt messages from the IPDL compiler.
    if md.decl.type.isInterrupt():
        func.addcode(
            """
            static_assert(
                false,
                "runtime support for intr messages has been removed from IPDL");
            """
        )

    if md.decl.type.isCtor():
        ctorEnum = "CONSTRUCTOR"
    else:
        ctorEnum = "NOT_CONSTRUCTOR"

    def messageEnum(valname):
        return ExprVar("IPC::Message::" + valname)

    flags = ExprCall(
        ExprVar("IPC::Message::HeaderFlags"),
        args=[
            messageEnum(nestedEnum),
            messageEnum(prioEnum),
            messageEnum(compression),
            messageEnum(lazySendEnum),
            messageEnum(ctorEnum),
            messageEnum(syncEnum),
            messageEnum(replyEnum),
        ],
    )

    segmentSize = int(segmentSize)
    if not segmentSize:
        segmentSize = 0
    func.addstmt(
        StmtReturn(
            ExprCall(
                ExprVar("IPC::Message::IPDLMessage"),
                args=[
                    routingId,
                    ExprVar(msgid),
                    ExprLiteral.Int(int(segmentSize)),
                    flags,
                ],
            )
        )
    )

    return func


# --------------------------------------------------


class _ParamTraits:
    var = ExprVar("aVar")
    writervar = ExprVar("aWriter")
    readervar = ExprVar("aReader")

    @classmethod
    def ifsideis(cls, rdrwtr, side, then, els=None):
        cxxside = ExprVar("mozilla::ipc::ChildSide")
        if side == "parent":
            cxxside = ExprVar("mozilla::ipc::ParentSide")

        ifstmt = StmtIf(
            ExprBinary(
                cxxside,
                "==",
                ExprCode("${rdrwtr}->GetActor()->GetSide()", rdrwtr=rdrwtr),
            )
        )
        ifstmt.addifstmt(then)
        if els is not None:
            ifstmt.addelsestmt(els)
        return ifstmt

    @classmethod
    def fatalError(cls, rdrwtr, reason):
        return StmtCode(
            "${rdrwtr}->FatalError(${reason});",
            rdrwtr=rdrwtr,
            reason=ExprLiteral.String(reason),
        )

    @classmethod
    def writeSentinel(cls, writervar, sentinelKey):
        return [
            Whitespace("// Sentinel = " + repr(sentinelKey) + "\n", indent=True),
            StmtExpr(
                ExprCall(
                    ExprSelect(writervar, "->", "WriteSentinel"),
                    args=[ExprLiteral.Int(hashfunc(sentinelKey))],
                )
            ),
        ]

    @classmethod
    def readSentinel(cls, readervar, sentinelKey, sentinelFail):
        # Read the sentinel
        read = ExprCall(
            ExprSelect(readervar, "->", "ReadSentinel"),
            args=[ExprLiteral.Int(hashfunc(sentinelKey))],
        )
        ifsentinel = StmtIf(ExprNot(read))
        ifsentinel.addifstmts(sentinelFail)

        return [
            Whitespace("// Sentinel = " + repr(sentinelKey) + "\n", indent=True),
            ifsentinel,
        ]

    @classmethod
    def write(cls, var, writervar, ipdltype=None):
        if ipdltype and _cxxTypeNeedsMoveForSend(ipdltype):
            var = ExprMove(var)
        return ExprCall(ExprVar("IPC::WriteParam"), args=[writervar, var])

    @classmethod
    def checkedWrite(cls, ipdltype, var, writervar, sentinelKey):
        assert sentinelKey
        block = Block()

        block.addstmts(
            [
                StmtExpr(cls.write(var, writervar, ipdltype)),
            ]
        )
        block.addstmts(cls.writeSentinel(writervar, sentinelKey))
        return block

    @classmethod
    def bulkSentinelKey(cls, fields):
        return " | ".join(f.basename for f in fields)

    @classmethod
    def checkedBulkWrite(cls, var, size, fields):
        block = Block()
        first = fields[0]

        block.addstmts(
            [
                StmtExpr(
                    ExprCall(
                        ExprSelect(cls.writervar, "->", "WriteBytes"),
                        args=[
                            ExprAddrOf(
                                ExprCall(first.getMethod(thisexpr=var, sel="."))
                            ),
                            ExprLiteral.Int(size * len(fields)),
                        ],
                    )
                )
            ]
        )
        block.addstmts(cls.writeSentinel(cls.writervar, cls.bulkSentinelKey(fields)))

        return block

    @classmethod
    def checkedBulkRead(cls, var, size, fields):
        block = Block()
        first = fields[0]

        readbytes = ExprCall(
            ExprSelect(cls.readervar, "->", "ReadBytesInto"),
            args=[
                ExprAddrOf(ExprCall(first.getMethod(thisexpr=var, sel="->"))),
                ExprLiteral.Int(size * len(fields)),
            ],
        )
        ifbad = StmtIf(ExprNot(readbytes))
        errmsg = "Error bulk reading fields from %s" % first.ipdltype.name()
        ifbad.addifstmts(
            [cls.fatalError(cls.readervar, errmsg), StmtReturn(readResultError())]
        )
        block.addstmt(ifbad)
        block.addstmts(
            cls.readSentinel(
                cls.readervar,
                cls.bulkSentinelKey(fields),
                errfnSentinel(readResultError())(errmsg),
            )
        )

        return block

    @classmethod
    def checkedRead(
        cls,
        ipdltype,
        cxxtype,
        var,
        readervar,
        errfn,
        paramtype,
        sentinelKey,
        errfnSentinel,
    ):
        assert isinstance(var, ExprVar)

        if not isinstance(paramtype, list):
            paramtype = ["Error deserializing " + paramtype]

        block = Block()

        # Read the data
        block.addcode(
            """
            auto ${maybevar} = IPC::ReadParam<${ty}>(${reader});
            if (!${maybevar}) {
                $*{errfn}
            }
            auto& ${var} = *${maybevar};
            """,
            maybevar=ExprVar("maybe__" + var.name),
            ty=cxxtype,
            reader=readervar,
            errfn=errfn(*paramtype),
            var=var,
        )

        block.addstmts(
            cls.readSentinel(readervar, sentinelKey, errfnSentinel(*paramtype))
        )

        return block

    # Helper wrapper for checkedRead for use within _ParamTraits
    @classmethod
    def _checkedRead(cls, ipdltype, cxxtype, var, sentinelKey, what):
        def errfn(msg):
            return [cls.fatalError(cls.readervar, msg), StmtReturn(readResultError())]

        return cls.checkedRead(
            ipdltype,
            cxxtype,
            var,
            cls.readervar,
            errfn=errfn,
            paramtype=what,
            sentinelKey=sentinelKey,
            errfnSentinel=errfnSentinel(readResultError()),
        )

    @classmethod
    def generateDecl(cls, fortype, write, read, needsmove=False):
        # ParamTraits impls are selected ignoring constness, and references.
        pt = Class(
            "ParamTraits",
            specializes=Type(
                fortype.name, T=fortype.T, inner=fortype.inner, ptr=fortype.ptr
            ),
            struct=True,
        )

        # typedef T paramType;
        pt.addstmt(Typedef(fortype, "paramType"))

        # static void Write(Message*, const T&);
        if needsmove:
            intype = Type("paramType", rvalref=True)
        else:
            intype = Type("paramType", ref=True, const=True)
        writemthd = MethodDefn(
            MethodDecl(
                "Write",
                params=[
                    Decl(Type("IPC::MessageWriter", ptr=True), cls.writervar.name),
                    Decl(intype, cls.var.name),
                ],
                methodspec=MethodSpec.STATIC,
            )
        )
        writemthd.addstmts(write)
        pt.addstmt(writemthd)

        # static ReadResult<T> Read(MessageReader*);
        readmthd = MethodDefn(
            MethodDecl(
                "Read",
                params=[
                    Decl(Type("IPC::MessageReader", ptr=True), cls.readervar.name),
                ],
                ret=Type("IPC::ReadResult<paramType>"),
                methodspec=MethodSpec.STATIC,
            )
        )
        readmthd.addstmts(read)
        pt.addstmt(readmthd)

        # Split the class into declaration and definition
        clsdecl, methoddefns = _splitClassDeclDefn(pt)

        namespaces = [Namespace("IPC")]
        clsns = _putInNamespaces(clsdecl, namespaces)
        defns = _putInNamespaces(methoddefns, namespaces)
        return clsns, defns

    @classmethod
    def actorPickling(cls, actortype, side):
        """Generates pickling for IPDL actors. This is a |nullable| deserializer.
        Write and read callers will perform nullability validation."""

        cxxtype = _cxxBareType(actortype, side, fq=True)

        write = StmtCode(
            """
            MOZ_RELEASE_ASSERT(
                ${writervar}->GetActor(),
                "Cannot serialize managed actors without an actor");

            int32_t id;
            if (!${var}) {
                id = 0;  // kNullActorId
            } else {
                id = ${var}->Id();
                if (id == 1) {  // kFreedActorId
                    ${var}->FatalError("Actor has been |delete|d");
                }
                MOZ_RELEASE_ASSERT(
                    ${writervar}->GetActor()->GetIPCChannel() == ${var}->GetIPCChannel(),
                    "Actor must be from the same channel as the"
                    " actor it's being sent over");
                MOZ_RELEASE_ASSERT(
                    ${var}->CanSend(),
                    "Actor must still be open when sending");
            }

            ${write};
            """,
            var=cls.var,
            writervar=cls.writervar,
            write=cls.write(ExprVar("id"), cls.writervar),
        )

        # bool Read(..) impl
        read = StmtCode(
            """
            MOZ_RELEASE_ASSERT(
                ${readervar}->GetActor(),
                "Cannot deserialize managed actors without an actor");
            mozilla::Maybe<mozilla::ipc::IProtocol*> actor = ${readervar}->GetActor()
              ->ReadActor(${readervar}, true, ${actortype}, ${protocolid});
            if (actor.isSome()) {
                return static_cast<${cxxtype}>(actor.ref());
            }
            return {};
            """,
            readervar=cls.readervar,
            actortype=ExprLiteral.String(actortype.name()),
            protocolid=_protocolId(actortype),
            cxxtype=cxxtype,
        )

        return cls.generateDecl(cxxtype, [write], [read])

    @classmethod
    def structPickling(cls, structtype):
        sd = structtype._ast
        # NOTE: Not using _cxxBareType here as we don't have a side
        cxxtype = Type(structtype.fullname())

        write = []
        read = []

        # First serialize/deserialize all non-pod data in IPDL order. These need
        # to be read/written first because they'll be used to invoke the IPDL
        # struct's constructor.
        ctorargs = []
        for f in sd.fields_ipdl_order():
            if pod_size(f.ipdltype) == pod_size_sentinel:
                write.append(
                    cls.checkedWrite(
                        f.ipdltype,
                        ExprCall(f.getMethod(thisexpr=cls.var, sel=".")),
                        cls.writervar,
                        sentinelKey=f.basename,
                    )
                )
                read.append(
                    cls._checkedRead(
                        f.ipdltype,
                        f.bareType(fq=True),
                        f.argVar(),
                        f.basename,
                        "'"
                        + f.getMethod().name
                        + "' "
                        + "("
                        + f.ipdltype.name()
                        + ") member of "
                        + "'"
                        + structtype.name()
                        + "'",
                    )
                )
                if _cxxTypeCanMove(f.ipdltype):
                    ctorargs.append(ExprMove(f.argVar()))
                else:
                    ctorargs.append(f.argVar())
            else:
                # We're going to bulk-read in this value later, so we'll just
                # zero-initialize it for now.
                ctorargs.append(ExprCode("${type}{0}", type=f.bareType(fq=True)))

        resultvar = ExprVar("result__")
        read.append(
            StmtDecl(
                Decl(_cxxReadResultType(Type("paramType")), resultvar.name),
                initargs=[ExprVar("std::in_place")] + ctorargs,
            )
        )

        # After non-pod data, bulk read/write pod data in member order. This has
        # to be done after the result has been constructed, so that we have
        # somewhere to read into.
        for (size, fields) in itertools.groupby(
            sd.fields_member_order(), lambda f: pod_size(f.ipdltype)
        ):
            if size != pod_size_sentinel:
                fields = list(fields)
                write.append(cls.checkedBulkWrite(cls.var, size, fields))
                read.append(cls.checkedBulkRead(resultvar, size, fields))

        read.append(StmtReturn(resultvar))

        return cls.generateDecl(
            cxxtype, write, read, needsmove=_cxxTypeNeedsMoveForSend(structtype)
        )

    @classmethod
    def unionPickling(cls, uniontype):
        # NOTE: Not using _cxxBareType here as we don't have a side
        cxxtype = Type(uniontype.fullname())
        ud = uniontype._ast

        # Use typedef to set up an alias so it's easier to reference the struct type.
        alias = "union__"
        typevar = ExprVar("type")

        prelude = [
            Typedef(cxxtype, alias),
        ]

        writeswitch = StmtSwitch(typevar)
        write = prelude + [
            StmtDecl(Decl(Type.INT, typevar.name), init=ud.callType(cls.var)),
            cls.checkedWrite(
                None, typevar, cls.writervar, sentinelKey=uniontype.name()
            ),
            Whitespace.NL,
            writeswitch,
        ]

        readswitch = StmtSwitch(typevar)
        read = prelude + [
            cls._checkedRead(
                None,
                Type.INT,
                typevar,
                uniontype.name(),
                "type of union " + uniontype.name(),
            ),
            Whitespace.NL,
            readswitch,
        ]

        for c in ud.components:
            caselabel = CaseLabel(alias + "::" + c.enum())
            origenum = c.enum()

            writecase = StmtBlock()
            wstmt = cls.checkedWrite(
                c.ipdltype,
                ExprCall(ExprSelect(cls.var, ".", c.getTypeName())),
                cls.writervar,
                sentinelKey=c.enum(),
            )
            writecase.addstmts([wstmt, StmtReturn()])
            writeswitch.addcase(caselabel, writecase)

            readcase = StmtBlock()
            tmpvar = ExprVar("tmp")
            readcase.addstmts(
                [
                    cls._checkedRead(
                        c.ipdltype,
                        c.bareType(fq=True),
                        tmpvar,
                        origenum,
                        "variant " + origenum + " of union " + uniontype.name(),
                    ),
                    StmtReturn(ExprMove(tmpvar)),
                ]
            )
            readswitch.addcase(caselabel, readcase)

        # Add the error default case
        writeswitch.addcase(
            DefaultLabel(),
            StmtBlock(
                [
                    cls.fatalError(
                        cls.writervar, "unknown variant of union " + uniontype.name()
                    ),
                    StmtReturn(),
                ]
            ),
        )
        readswitch.addcase(
            DefaultLabel(),
            StmtBlock(
                [
                    cls.fatalError(
                        cls.readervar, "unknown variant of union " + uniontype.name()
                    ),
                    StmtReturn(readResultError()),
                ]
            ),
        )

        return cls.generateDecl(
            cxxtype, write, read, needsmove=_cxxTypeNeedsMoveForSend(uniontype)
        )


# --------------------------------------------------


class _ComputeTypeDeps(TypeVisitor):
    """Pass that gathers the C++ types that a particular IPDL type
    (recursively) depends on.  There are three kinds of dependencies: (i)
    types that need forward declaration; (ii) types that need a |using|
    stmt; (iii) IPDL structs or unions which must be fully declared
    before this struct.  Some types generate multiple kinds."""

    def __init__(self, fortype, typesToIncludes=None):
        ipdl.type.TypeVisitor.__init__(self)
        self.usingTypedefs = []
        self.forwardDeclStmts = []
        self.fullDeclTypes = []
        self.includeHeaders = set()
        self.fortype = fortype
        self.typesToIncludes = typesToIncludes

    def maybeTypedef(self, fqname, name, templateargs=[]):
        assert fqname.startswith("::")
        if fqname != name:
            self.usingTypedefs.append(Typedef(Type(fqname), name, templateargs))
        if self.typesToIncludes is not None and fqname in self.typesToIncludes:
            self.includeHeaders.add(self.typesToIncludes[fqname])

    def visitImportedCxxType(self, t):
        if t in self.visited:
            return
        self.visited.add(t)
        self.maybeTypedef(t.fullname(), t.name())

    def visitActorType(self, t):
        if t in self.visited:
            return
        self.visited.add(t)

        fqname, name = t.fullname(), t.name()

        self.includeHeaders.add("mozilla/ipc/SideVariant.h")
        self.maybeTypedef(_actorName(fqname, "Parent"), _actorName(name, "Parent"))
        self.maybeTypedef(_actorName(fqname, "Child"), _actorName(name, "Child"))

        self.forwardDeclStmts.extend(
            [
                _makeForwardDeclForActor(t.protocol, "parent"),
                Whitespace.NL,
                _makeForwardDeclForActor(t.protocol, "child"),
                Whitespace.NL,
            ]
        )

    def visitStructOrUnionType(self, su, defaultVisit):
        if su in self.visited or su == self.fortype:
            return
        self.visited.add(su)
        self.maybeTypedef(su.fullname(), su.name())

        # Mutually recursive fields in unions are behind indirection, so we only
        # need a forward decl, and don't need a full type declaration.
        if isinstance(self.fortype, UnionType) and self.fortype.mutuallyRecursiveWith(
            su
        ):
            self.forwardDeclStmts.append(_makeForwardDecl(su))
        else:
            self.fullDeclTypes.append(su)

        return defaultVisit(self, su)

    def visitStructType(self, t):
        return self.visitStructOrUnionType(t, TypeVisitor.visitStructType)

    def visitUnionType(self, t):
        return self.visitStructOrUnionType(t, TypeVisitor.visitUnionType)

    def visitArrayType(self, t):
        return TypeVisitor.visitArrayType(self, t)

    def visitMaybeType(self, m):
        return TypeVisitor.visitMaybeType(self, m)

    def visitShmemType(self, s):
        if s in self.visited:
            return
        self.visited.add(s)
        self.maybeTypedef("::mozilla::ipc::Shmem", "Shmem")

    def visitByteBufType(self, s):
        if s in self.visited:
            return
        self.visited.add(s)
        self.maybeTypedef("::mozilla::ipc::ByteBuf", "ByteBuf")

    def visitFDType(self, s):
        if s in self.visited:
            return
        self.visited.add(s)
        self.maybeTypedef("::mozilla::ipc::FileDescriptor", "FileDescriptor")

    def visitEndpointType(self, s):
        if s in self.visited:
            return
        self.visited.add(s)
        self.maybeTypedef("::mozilla::ipc::Endpoint", "Endpoint", ["FooSide"])
        self.visitActorType(s.actor)

    def visitManagedEndpointType(self, s):
        if s in self.visited:
            return
        self.visited.add(s)
        self.maybeTypedef(
            "::mozilla::ipc::ManagedEndpoint", "ManagedEndpoint", ["FooSide"]
        )
        self.visitActorType(s.actor)

    def visitUniquePtrType(self, s):
        if s in self.visited:
            return
        self.visited.add(s)

    def visitVoidType(self, v):
        assert 0

    def visitMessageType(self, v):
        assert 0

    def visitProtocolType(self, v):
        assert 0


def _fieldStaticAssertions(sd):
    staticasserts = []
    for (size, fields) in itertools.groupby(
        sd.fields_member_order(), lambda f: pod_size(f.ipdltype)
    ):
        if size == pod_size_sentinel:
            continue

        fields = list(fields)
        if len(fields) == 1:
            continue

        staticasserts.append(
            StmtCode(
                """
            static_assert(
                (offsetof(${struct}, ${last}) - offsetof(${struct}, ${first})) == ${expected},
                "Bad assumptions about field layout!");
            """,
                struct=sd.name,
                first=fields[0].memberVar(),
                last=fields[-1].memberVar(),
                expected=ExprLiteral.Int(size * (len(fields) - 1)),
            )
        )

    return staticasserts


def _generateCxxStruct(sd):
    """ """
    # compute all the typedefs and forward decls we need to make
    gettypedeps = _ComputeTypeDeps(sd.decl.type)
    for f in sd.fields:
        f.ipdltype.accept(gettypedeps)

    usingTypedefs = gettypedeps.usingTypedefs
    forwarddeclstmts = gettypedeps.forwardDeclStmts
    fulldecltypes = gettypedeps.fullDeclTypes

    struct = Class(sd.name, final=True)
    struct.addstmts([Label.PRIVATE] + usingTypedefs + [Whitespace.NL, Label.PUBLIC])

    constreftype = Type(sd.name, const=True, ref=True)

    # Struct()
    # We want the default constructor to be declared if it is available, but
    # some of our members may not be default-constructible. Silence the
    # warning which clang generates in that case.
    #
    # Members which need value initialization will be handled by wrapping
    # the member in a template type when declaring them.
    struct.addcode(
        """
        #ifdef __clang__
        #  pragma clang diagnostic push
        #  if __has_warning("-Wdefaulted-function-deleted")
        #    pragma clang diagnostic ignored "-Wdefaulted-function-deleted"
        #  endif
        #endif
        ${name}() = default;
        #ifdef __clang__
        #  pragma clang diagnostic pop
        #endif

        """,
        name=sd.name,
    )

    # If this is an empty struct (no fields), then the default ctor
    # and "create-with-fields" ctors are equivalent.
    if len(sd.fields):
        assert len(sd.fields) == len(sd.packed_field_order)

        # Struct(const field1& _f1, ...)
        valctor = ConstructorDefn(
            ConstructorDecl(
                sd.name,
                params=[
                    Decl(
                        f.forceMoveType()
                        if _cxxTypeNeedsMoveForData(f.ipdltype)
                        else f.constRefType(),
                        f.argVar().name,
                    )
                    for f in sd.fields_ipdl_order()
                ],
                force_inline=True,
            )
        )
        valctor.memberinits = []
        for f in sd.fields_member_order():
            arg = f.argVar()
            if _cxxTypeNeedsMoveForData(f.ipdltype):
                arg = ExprMove(arg)
            valctor.memberinits.append(ExprMemberInit(f.memberVar(), args=[arg]))

        struct.addstmts([valctor, Whitespace.NL])

        # If a constructor which moves each argument would be different from the
        # `const T&` version, also generate that constructor.
        if not all(
            _cxxTypeNeedsMoveForData(f.ipdltype) or not _cxxTypeCanMove(f.ipdltype)
            for f in sd.fields_ipdl_order()
        ):
            # Struct(field1&& _f1, ...)
            valmovector = ConstructorDefn(
                ConstructorDecl(
                    sd.name,
                    params=[
                        Decl(
                            f.forceMoveType()
                            if _cxxTypeCanMove(f.ipdltype)
                            else f.constRefType(),
                            f.argVar().name,
                        )
                        for f in sd.fields_ipdl_order()
                    ],
                    force_inline=True,
                )
            )

            valmovector.memberinits = []
            for f in sd.fields_member_order():
                arg = f.argVar()
                if _cxxTypeCanMove(f.ipdltype):
                    arg = ExprMove(arg)
                valmovector.memberinits.append(
                    ExprMemberInit(f.memberVar(), args=[arg])
                )

            struct.addstmts([valmovector, Whitespace.NL])

    # The default copy, move, and assignment constructors, and the default
    # destructor, will do the right thing.

    if "Comparable" in sd.attributes:
        # bool operator==(const Struct& _o)
        ovar = ExprVar("_o")
        opeqeq = MethodDefn(
            MethodDecl(
                "operator==",
                params=[Decl(constreftype, ovar.name)],
                ret=Type.BOOL,
                const=True,
            )
        )
        for f in sd.fields_ipdl_order():
            ifneq = StmtIf(
                ExprNot(
                    ExprBinary(
                        ExprCall(f.getMethod()), "==", ExprCall(f.getMethod(ovar))
                    )
                )
            )
            ifneq.addifstmt(StmtReturn.FALSE)
            opeqeq.addstmt(ifneq)
        opeqeq.addstmt(StmtReturn.TRUE)
        struct.addstmts([opeqeq, Whitespace.NL])

        # bool operator!=(const Struct& _o)
        opneq = MethodDefn(
            MethodDecl(
                "operator!=",
                params=[Decl(constreftype, ovar.name)],
                ret=Type.BOOL,
                const=True,
            )
        )
        opneq.addstmt(StmtReturn(ExprNot(ExprCall(ExprVar("operator=="), args=[ovar]))))
        struct.addstmts([opneq, Whitespace.NL])

    # field1& f1()
    # const field1& f1() const
    for f in sd.fields_ipdl_order():
        get = MethodDefn(
            MethodDecl(
                f.getMethod().name, params=[], ret=f.refType(), force_inline=True
            )
        )
        get.addstmt(StmtReturn(f.refExpr()))

        getconstdecl = deepcopy(get.decl)
        getconstdecl.ret = f.constRefType()
        getconstdecl.const = True
        getconst = MethodDefn(getconstdecl)
        getconst.addstmt(StmtReturn(f.constRefExpr()))

        struct.addstmts([get, getconst, Whitespace.NL])

    # private:
    struct.addstmt(Label.PRIVATE)

    # Static assertions to ensure our assumptions about field layout match
    # what the compiler is actually producing.  We define this as a member
    # function, rather than throwing the assertions in the constructor or
    # similar, because we don't want to evaluate the static assertions every
    # time the header file containing the structure is included.
    staticasserts = _fieldStaticAssertions(sd)
    if staticasserts:
        method = MethodDefn(
            MethodDecl("StaticAssertions", params=[], ret=Type.VOID, const=True)
        )
        method.addstmts(staticasserts)
        struct.addstmts([method])

    # members
    struct.addstmts(
        [
            StmtDecl(Decl(_effectiveMemberType(f), f.memberVar().name))
            for f in sd.fields_member_order()
        ]
    )

    return forwarddeclstmts, fulldecltypes, struct


def _effectiveMemberType(f):
    effective_type = f.bareType()
    # Structs must be copyable for backwards compatibility reasons, so we use
    # CopyableTArray<T> as their member type for arrays. This is not exposed
    # in the method signatures, these keep using nsTArray<T>, which is a base
    # class of CopyableTArray<T>.
    if effective_type.name == "nsTArray":
        effective_type.name = "CopyableTArray"
    return Type("::mozilla::ipc::IPDLStructMember", T=[effective_type])


# --------------------------------------------------


def _generateCxxUnion(ud):
    # This Union class basically consists of a type (enum) and a
    # union for storage.  The union can contain POD and non-POD
    # types.  Each type needs a copy/move ctor, assignment operators,
    # and dtor.
    #
    # Rather than templating this class and only providing
    # specializations for the types we support, which is slightly
    # "unsafe" in that C++ code can add additional specializations
    # without the IPDL compiler's knowledge, we instead explicitly
    # implement non-templated methods for each supported type.
    #
    # The one complication that arises is that C++, for arcane
    # reasons, does not allow the placement destructor of a
    # builtin type, like int, to be directly invoked.  So we need
    # to hack around this by internally typedef'ing all
    # constituent types.  Sigh.
    #
    # So, for each type, this "Union" class needs:
    # (private)
    #  - entry in the type enum
    #  - entry in the storage union
    #  - [type]ptr() method to get a type* from the underlying union
    #  - same as above to get a const type*
    #  - typedef to hack around placement delete limitations
    # (public)
    #  - placement delete case for dtor
    #  - copy ctor
    #  - move ctor
    #  - case in generic copy ctor
    #  - copy operator= impl
    #  - move operator= impl
    #  - case in generic operator=
    #  - operator [type&]
    #  - operator [const type&] const
    #  - [type&] get_[type]()
    #  - [const type&] get_[type]() const
    #
    cls = Class(ud.name, final=True)
    # const Union&, i.e., Union type with inparam semantics
    inClsType = Type(ud.name, const=True, ref=True)
    refClsType = Type(ud.name, ref=True)
    rvalueRefClsType = Type(ud.name, rvalref=True)
    typetype = Type("Type")
    valuetype = Type("Value")
    mtypevar = ExprVar("mType")
    mvaluevar = ExprVar("mValue")
    maybedtorvar = ExprVar("MaybeDestroy")
    assertsanityvar = ExprVar("AssertSanity")
    tnonevar = ExprVar("T__None")
    tlastvar = ExprVar("T__Last")

    def callAssertSanity(uvar=None, expectTypeVar=None):
        func = assertsanityvar
        args = []
        if uvar is not None:
            func = ExprSelect(uvar, ".", assertsanityvar.name)
        if expectTypeVar is not None:
            args.append(expectTypeVar)
        return ExprCall(func, args=args)

    def maybeDestroy():
        return StmtExpr(ExprCall(maybedtorvar))

    # compute all the typedefs and forward decls we need to make
    gettypedeps = _ComputeTypeDeps(ud.decl.type)
    for c in ud.components:
        c.ipdltype.accept(gettypedeps)

    usingTypedefs = gettypedeps.usingTypedefs
    forwarddeclstmts = gettypedeps.forwardDeclStmts
    fulldecltypes = gettypedeps.fullDeclTypes

    # the |Type| enum, used to switch on the discunion's real type
    cls.addstmt(Label.PUBLIC)
    typeenum = TypeEnum(typetype.name)
    typeenum.addId(tnonevar.name, 0)
    firstid = ud.components[0].enum()
    typeenum.addId(firstid, 1)
    for c in ud.components[1:]:
        typeenum.addId(c.enum())
    typeenum.addId(tlastvar.name, ud.components[-1].enum())
    cls.addstmts([StmtDecl(Decl(typeenum, "")), Whitespace.NL])

    cls.addstmt(Label.PRIVATE)
    cls.addstmts(
        usingTypedefs
        # hacky typedef's that allow placement dtors of builtins
        + [Typedef(c.internalType(), c.typedef()) for c in ud.components]
    )
    cls.addstmt(Whitespace.NL)

    # the C++ union the discunion use for storage
    valueunion = TypeUnion(valuetype.name)
    for c in ud.components:
        valueunion.addComponent(c.unionType(), c.name)
    cls.addstmts([StmtDecl(Decl(valueunion, "")), Whitespace.NL])

    # for each constituent type T, add private accessors that
    # return a pointer to the Value union storage casted to |T*|
    # and |const T*|
    for c in ud.components:
        getptr = MethodDefn(
            MethodDecl(
                c.getPtrName(), params=[], ret=c.ptrToInternalType(), force_inline=True
            )
        )
        getptr.addstmt(StmtReturn(c.ptrToSelfExpr()))

        getptrconst = MethodDefn(
            MethodDecl(
                c.getConstPtrName(),
                params=[],
                ret=c.constPtrToType(),
                const=True,
                force_inline=True,
            )
        )
        getptrconst.addstmt(StmtReturn(c.constptrToSelfExpr()))

        cls.addstmts([getptr, getptrconst])
    cls.addstmt(Whitespace.NL)

    # add a helper method that invokes the placement dtor on the
    # current underlying value, only if |aNewType| is different
    # than the current type, and returns true if the underlying
    # value needs to be re-constructed
    maybedtor = MethodDefn(MethodDecl(maybedtorvar.name, ret=Type.VOID))
    # wasn't /actually/ dtor'd, but it needs to be re-constructed
    ifnone = StmtIf(ExprBinary(mtypevar, "==", tnonevar))
    ifnone.addifstmt(StmtReturn())
    # need to destroy.  switch on underlying type
    dtorswitch = StmtSwitch(mtypevar)
    for c in ud.components:
        dtorswitch.addcase(
            CaseLabel(c.enum()), StmtBlock([StmtExpr(c.callDtor()), StmtBreak()])
        )
    dtorswitch.addcase(
        DefaultLabel(), StmtBlock([_logicError("not reached"), StmtBreak()])
    )
    maybedtor.addstmts([ifnone, dtorswitch])
    cls.addstmts([maybedtor, Whitespace.NL])

    # add helper methods that ensure the discunion has a
    # valid type
    sanity = MethodDefn(
        MethodDecl(assertsanityvar.name, ret=Type.VOID, const=True, force_inline=True)
    )
    sanity.addstmts(
        [
            _abortIfFalse(ExprBinary(tnonevar, "<=", mtypevar), "invalid type tag"),
            _abortIfFalse(ExprBinary(mtypevar, "<=", tlastvar), "invalid type tag"),
        ]
    )
    cls.addstmt(sanity)

    atypevar = ExprVar("aType")
    sanity2 = MethodDefn(
        MethodDecl(
            assertsanityvar.name,
            params=[Decl(typetype, atypevar.name)],
            ret=Type.VOID,
            const=True,
            force_inline=True,
        )
    )
    sanity2.addstmts(
        [
            StmtExpr(ExprCall(assertsanityvar)),
            _abortIfFalse(ExprBinary(mtypevar, "==", atypevar), "unexpected type tag"),
        ]
    )
    cls.addstmts([sanity2, Whitespace.NL])

    # ---- begin public methods -----

    # Union() default ctor
    cls.addstmts(
        [
            Label.PUBLIC,
            ConstructorDefn(
                ConstructorDecl(ud.name, force_inline=True),
                memberinits=[ExprMemberInit(mtypevar, [tnonevar])],
            ),
            Whitespace.NL,
        ]
    )

    # Union(const T&) copy & Union(T&&) move ctors
    othervar = ExprVar("aOther")
    for c in ud.components:
        if not _cxxTypeNeedsMoveForData(c.ipdltype):
            copyctor = ConstructorDefn(
                ConstructorDecl(ud.name, params=[Decl(c.constRefType(), othervar.name)])
            )
            copyctor.addstmts(
                [
                    StmtExpr(c.callCtor(othervar)),
                    StmtExpr(ExprAssn(mtypevar, c.enumvar())),
                ]
            )
            cls.addstmts([copyctor, Whitespace.NL])

        if not _cxxTypeCanMove(c.ipdltype):
            continue
        movector = ConstructorDefn(
            ConstructorDecl(ud.name, params=[Decl(c.forceMoveType(), othervar.name)])
        )
        movector.addstmts(
            [
                StmtExpr(c.callCtor(ExprMove(othervar))),
                StmtExpr(ExprAssn(mtypevar, c.enumvar())),
            ]
        )
        cls.addstmts([movector, Whitespace.NL])

    unionNeedsMove = any(_cxxTypeNeedsMoveForData(c.ipdltype) for c in ud.components)

    # Union(const Union&) copy ctor
    if not unionNeedsMove:
        copyctor = ConstructorDefn(
            ConstructorDecl(ud.name, params=[Decl(inClsType, othervar.name)])
        )
        othertype = ud.callType(othervar)
        copyswitch = StmtSwitch(othertype)
        for c in ud.components:
            copyswitch.addcase(
                CaseLabel(c.enum()),
                StmtBlock(
                    [
                        StmtExpr(
                            c.callCtor(
                                ExprCall(
                                    ExprSelect(othervar, ".", c.getConstTypeName())
                                )
                            )
                        ),
                        StmtBreak(),
                    ]
                ),
            )
        copyswitch.addcase(CaseLabel(tnonevar.name), StmtBlock([StmtBreak()]))
        copyswitch.addcase(
            DefaultLabel(), StmtBlock([_logicError("unreached"), StmtReturn()])
        )
        copyctor.addstmts(
            [
                StmtExpr(callAssertSanity(uvar=othervar)),
                copyswitch,
                StmtExpr(ExprAssn(mtypevar, othertype)),
            ]
        )
        cls.addstmts([copyctor, Whitespace.NL])

    # Union(Union&&) move ctor
    movector = ConstructorDefn(
        ConstructorDecl(ud.name, params=[Decl(rvalueRefClsType, othervar.name)])
    )
    othertypevar = ExprVar("t")
    moveswitch = StmtSwitch(othertypevar)
    for c in ud.components:
        case = StmtBlock()
        if c.recursive:
            # This is sound as we set othervar.mTypeVar to T__None after the
            # switch. The pointer in the union will be left dangling.
            case.addstmts(
                [
                    # ptr_C() = other.ptr_C()
                    StmtExpr(
                        ExprAssn(
                            c.callGetPtr(),
                            ExprCall(
                                ExprSelect(othervar, ".", ExprVar(c.getPtrName()))
                            ),
                        )
                    )
                ]
            )
        else:
            case.addstmts(
                [
                    # new ... (Move(other.get_C()))
                    StmtExpr(
                        c.callCtor(
                            ExprMove(
                                ExprCall(ExprSelect(othervar, ".", c.getTypeName()))
                            )
                        )
                    ),
                    # other.MaybeDestroy(T__None)
                    StmtExpr(ExprCall(ExprSelect(othervar, ".", maybedtorvar))),
                ]
            )
        case.addstmts([StmtBreak()])
        moveswitch.addcase(CaseLabel(c.enum()), case)
    moveswitch.addcase(CaseLabel(tnonevar.name), StmtBlock([StmtBreak()]))
    moveswitch.addcase(
        DefaultLabel(), StmtBlock([_logicError("unreached"), StmtReturn()])
    )
    movector.addstmts(
        [
            StmtExpr(callAssertSanity(uvar=othervar)),
            StmtDecl(Decl(typetype, othertypevar.name), init=ud.callType(othervar)),
            moveswitch,
            StmtExpr(ExprAssn(ExprSelect(othervar, ".", mtypevar), tnonevar)),
            StmtExpr(ExprAssn(mtypevar, othertypevar)),
        ]
    )
    cls.addstmts([movector, Whitespace.NL])

    # ~Union()
    dtor = DestructorDefn(DestructorDecl(ud.name))
    dtor.addstmt(maybeDestroy())
    cls.addstmts([dtor, Whitespace.NL])

    # type()
    typemeth = MethodDefn(
        MethodDecl("type", ret=typetype, const=True, force_inline=True)
    )
    typemeth.addstmt(StmtReturn(mtypevar))
    cls.addstmts([typemeth, Whitespace.NL])

    # Union& operator= methods
    rhsvar = ExprVar("aRhs")
    for c in ud.components:

        def opeqBody(rhs):
            return [
                # might need to placement-delete old value first
                maybeDestroy(),
                StmtExpr(c.callCtor(rhs)),
                StmtExpr(ExprAssn(mtypevar, c.enumvar())),
                StmtReturn(ExprDeref(ExprVar.THIS)),
            ]

        if not _cxxTypeNeedsMoveForData(c.ipdltype):
            # Union& operator=(const T&)
            opeq = MethodDefn(
                MethodDecl(
                    "operator=",
                    params=[Decl(c.constRefType(), rhsvar.name)],
                    ret=refClsType,
                )
            )
            opeq.addstmts(opeqBody(rhsvar))
            cls.addstmts([opeq, Whitespace.NL])

        # Union& operator=(T&&)
        if not _cxxTypeCanMove(c.ipdltype):
            continue

        opeq = MethodDefn(
            MethodDecl(
                "operator=",
                params=[Decl(c.forceMoveType(), rhsvar.name)],
                ret=refClsType,
            )
        )
        opeq.addstmts(opeqBody(ExprMove(rhsvar)))
        cls.addstmts([opeq, Whitespace.NL])

    # Union& operator=(const Union&)
    if not unionNeedsMove:
        opeq = MethodDefn(
            MethodDecl(
                "operator=", params=[Decl(inClsType, rhsvar.name)], ret=refClsType
            )
        )
        rhstypevar = ExprVar("t")
        opeqswitch = StmtSwitch(rhstypevar)
        for c in ud.components:
            case = StmtBlock()
            case.addstmts(
                [
                    maybeDestroy(),
                    StmtExpr(
                        c.callCtor(
                            ExprCall(ExprSelect(rhsvar, ".", c.getConstTypeName()))
                        )
                    ),
                    StmtBreak(),
                ]
            )
            opeqswitch.addcase(CaseLabel(c.enum()), case)
        opeqswitch.addcase(
            CaseLabel(tnonevar.name),
            StmtBlock([maybeDestroy(), StmtBreak()]),
        )
        opeqswitch.addcase(
            DefaultLabel(), StmtBlock([_logicError("unreached"), StmtBreak()])
        )
        opeq.addstmts(
            [
                StmtExpr(callAssertSanity(uvar=rhsvar)),
                StmtDecl(Decl(typetype, rhstypevar.name), init=ud.callType(rhsvar)),
                opeqswitch,
                StmtExpr(ExprAssn(mtypevar, rhstypevar)),
                StmtReturn(ExprDeref(ExprVar.THIS)),
            ]
        )
        cls.addstmts([opeq, Whitespace.NL])

    # Union& operator=(Union&&)
    opeq = MethodDefn(
        MethodDecl(
            "operator=", params=[Decl(rvalueRefClsType, rhsvar.name)], ret=refClsType
        )
    )
    rhstypevar = ExprVar("t")
    opeqswitch = StmtSwitch(rhstypevar)
    for c in ud.components:
        case = StmtBlock()
        if c.recursive:
            case.addstmts(
                [
                    maybeDestroy(),
                    StmtExpr(
                        ExprAssn(
                            c.callGetPtr(),
                            ExprCall(ExprSelect(rhsvar, ".", ExprVar(c.getPtrName()))),
                        )
                    ),
                ]
            )
        else:
            case.addstmts(
                [
                    maybeDestroy(),
                    StmtExpr(
                        c.callCtor(
                            ExprMove(ExprCall(ExprSelect(rhsvar, ".", c.getTypeName())))
                        )
                    ),
                    # other.MaybeDestroy()
                    StmtExpr(ExprCall(ExprSelect(rhsvar, ".", maybedtorvar))),
                ]
            )
        case.addstmts([StmtBreak()])
        opeqswitch.addcase(CaseLabel(c.enum()), case)
    opeqswitch.addcase(
        CaseLabel(tnonevar.name),
        StmtBlock([maybeDestroy(), StmtBreak()]),
    )
    opeqswitch.addcase(
        DefaultLabel(), StmtBlock([_logicError("unreached"), StmtBreak()])
    )
    opeq.addstmts(
        [
            StmtExpr(callAssertSanity(uvar=rhsvar)),
            StmtDecl(Decl(typetype, rhstypevar.name), init=ud.callType(rhsvar)),
            opeqswitch,
            StmtExpr(ExprAssn(ExprSelect(rhsvar, ".", mtypevar), tnonevar)),
            StmtExpr(ExprAssn(mtypevar, rhstypevar)),
            StmtReturn(ExprDeref(ExprVar.THIS)),
        ]
    )
    cls.addstmts([opeq, Whitespace.NL])

    if "Comparable" in ud.attributes:
        # bool operator==(const T&)
        for c in ud.components:
            opeqeq = MethodDefn(
                MethodDecl(
                    "operator==",
                    params=[Decl(c.constRefType(), rhsvar.name)],
                    ret=Type.BOOL,
                    const=True,
                )
            )
            opeqeq.addstmt(
                StmtReturn(ExprBinary(ExprCall(ExprVar(c.getTypeName())), "==", rhsvar))
            )
            cls.addstmts([opeqeq, Whitespace.NL])

        # bool operator==(const Union&)
        opeqeq = MethodDefn(
            MethodDecl(
                "operator==",
                params=[Decl(inClsType, rhsvar.name)],
                ret=Type.BOOL,
                const=True,
            )
        )
        iftypesmismatch = StmtIf(ExprBinary(ud.callType(), "!=", ud.callType(rhsvar)))
        iftypesmismatch.addifstmt(StmtReturn.FALSE)
        opeqeq.addstmts([iftypesmismatch, Whitespace.NL])

        opeqeqswitch = StmtSwitch(ud.callType())
        for c in ud.components:
            case = StmtBlock()
            case.addstmt(
                StmtReturn(
                    ExprBinary(
                        ExprCall(ExprVar(c.getTypeName())),
                        "==",
                        ExprCall(ExprSelect(rhsvar, ".", c.getTypeName())),
                    )
                )
            )
            opeqeqswitch.addcase(CaseLabel(c.enum()), case)
        opeqeqswitch.addcase(
            DefaultLabel(), StmtBlock([_logicError("unreached"), StmtReturn.FALSE])
        )
        opeqeq.addstmt(opeqeqswitch)

        cls.addstmts([opeqeq, Whitespace.NL])

    # accessors for each type: operator T&, operator const T&,
    # T& get(), const T& get()
    for c in ud.components:
        getValueVar = ExprVar(c.getTypeName())
        getConstValueVar = ExprVar(c.getConstTypeName())

        getvalue = MethodDefn(
            MethodDecl(getValueVar.name, ret=c.refType(), force_inline=True)
        )
        getvalue.addstmts(
            [
                StmtExpr(callAssertSanity(expectTypeVar=c.enumvar())),
                StmtReturn(ExprDeref(c.callGetPtr())),
            ]
        )

        getconstvalue = MethodDefn(
            MethodDecl(
                getConstValueVar.name,
                ret=c.constRefType(),
                const=True,
                force_inline=True,
            )
        )
        getconstvalue.addstmts(
            [
                StmtExpr(callAssertSanity(expectTypeVar=c.enumvar())),
                StmtReturn(c.getConstValue()),
            ]
        )

        cls.addstmts([getvalue, getconstvalue])

        optype = MethodDefn(MethodDecl("", typeop=c.refType(), force_inline=True))
        optype.addstmt(StmtReturn(ExprCall(getValueVar)))
        opconsttype = MethodDefn(
            MethodDecl("", const=True, typeop=c.constRefType(), force_inline=True)
        )
        opconsttype.addstmt(StmtReturn(ExprCall(getConstValueVar)))

        cls.addstmts([optype, opconsttype, Whitespace.NL])
    # private vars
    cls.addstmts(
        [
            Label.PRIVATE,
            StmtDecl(Decl(valuetype, mvaluevar.name)),
            StmtDecl(Decl(typetype, mtypevar.name)),
        ]
    )

    return forwarddeclstmts, fulldecltypes, cls


# -----------------------------------------------------------------------------


class _FindFriends(ipdl.ast.Visitor):
    def __init__(self):
        self.mytype = None  # ProtocolType
        self.vtype = None  # ProtocolType
        self.friends = set()  # set<ProtocolType>

    def findFriends(self, ptype):
        self.mytype = ptype
        for toplvl in ptype.toplevels():
            self.walkDownTheProtocolTree(toplvl)
        return self.friends

    # TODO could make this into a _iterProtocolTreeHelper ...
    def walkDownTheProtocolTree(self, ptype):
        if ptype != self.mytype:
            # don't want to |friend| ourself!
            self.visit(ptype)
        for mtype in ptype.manages:
            if mtype is not ptype:
                self.walkDownTheProtocolTree(mtype)

    def visit(self, ptype):
        # |vtype| is the type currently being visited
        savedptype = self.vtype
        self.vtype = ptype
        ptype._ast.accept(self)
        self.vtype = savedptype

    def visitMessageDecl(self, md):
        for it in self.iterActorParams(md):
            if it.protocol == self.mytype:
                self.friends.add(self.vtype)

    def iterActorParams(self, md):
        for param in md.inParams:
            for actor in ipdl.type.iteractortypes(param.type):
                yield actor
        for ret in md.outParams:
            for actor in ipdl.type.iteractortypes(ret.type):
                yield actor


class _GenerateProtocolActorCode(ipdl.ast.Visitor):
    def __init__(self, myside):
        self.side = myside  # "parent" or "child"
        self.prettyside = myside.title()
        self.clsname = None
        self.protocol = None
        self.hdrfile = None
        self.cppfile = None
        self.ns = None
        self.cls = None
        self.protocolCxxIncludes = []
        self.actorForwardDecls = []
        self.usingDecls = []
        self.externalIncludes = set()
        self.nonForwardDeclaredHeaders = set()
        self.typedefSet = set(
            [
                Typedef(Type("mozilla::ipc::ActorHandle"), "ActorHandle"),
                Typedef(Type("base::ProcessId"), "ProcessId"),
                Typedef(Type("mozilla::ipc::ProtocolId"), "ProtocolId"),
                Typedef(Type("mozilla::ipc::Endpoint"), "Endpoint", ["FooSide"]),
                Typedef(
                    Type("mozilla::ipc::ManagedEndpoint"),
                    "ManagedEndpoint",
                    ["FooSide"],
                ),
                Typedef(Type("mozilla::UniquePtr"), "UniquePtr", ["T"]),
                Typedef(
                    Type("mozilla::ipc::ResponseRejectReason"), "ResponseRejectReason"
                ),
            ]
        )

    def lower(self, tu, clsname, cxxHeaderFile, cxxFile):
        self.clsname = clsname
        self.hdrfile = cxxHeaderFile
        self.cppfile = cxxFile
        tu.accept(self)

    def standardTypedefs(self):
        return [
            Typedef(Type("mozilla::ipc::IProtocol"), "IProtocol"),
            Typedef(Type("IPC::Message"), "Message"),
            Typedef(Type("base::ProcessHandle"), "ProcessHandle"),
            Typedef(Type("mozilla::ipc::MessageChannel"), "MessageChannel"),
            Typedef(Type("mozilla::ipc::SharedMemory"), "SharedMemory"),
        ]

    def visitTranslationUnit(self, tu):
        self.protocol = tu.protocol

        hf = self.hdrfile
        cf = self.cppfile

        # make the C++ header
        hf.addthings(
            [_DISCLAIMER]
            + _includeGuardStart(hf)
            + [
                Whitespace.NL,
                CppDirective("include", '"' + _protocolHeaderName(tu.protocol) + '.h"'),
            ]
        )

        for inc in tu.includes:
            inc.accept(self)
        for inc in tu.cxxIncludes:
            inc.accept(self)

        for using in tu.builtinUsing:
            using.accept(self)
        for using in tu.using:
            using.accept(self)
        for su in tu.structsAndUnions:
            su.accept(self)

        # this generates the actor's full impl in self.cls
        tu.protocol.accept(self)

        clsdecl, clsdefn = _splitClassDeclDefn(self.cls)

        # XXX damn C++ ... return types in the method defn aren't in
        # class scope
        for stmt in clsdefn.stmts:
            if isinstance(stmt, MethodDefn):
                if stmt.decl.ret and stmt.decl.ret.name == "Result":
                    stmt.decl.ret.name = clsdecl.name + "::" + stmt.decl.ret.name

        def setToIncludes(s):
            return [CppDirective("include", '"%s"' % i) for i in sorted(iter(s))]

        def makeNamespace(p, file):
            if 0 == len(p.namespaces):
                return file
            ns = Namespace(p.namespaces[-1].name)
            outerns = _putInNamespaces(ns, p.namespaces[:-1])
            file.addthing(outerns)
            return ns

        if len(self.nonForwardDeclaredHeaders) != 0:
            self.hdrfile.addthings(
                [
                    Whitespace("// Headers for things that cannot be forward declared"),
                    Whitespace.NL,
                ]
                + setToIncludes(self.nonForwardDeclaredHeaders)
                + [Whitespace.NL]
            )
        self.hdrfile.addthings(self.actorForwardDecls)
        self.hdrfile.addthings(self.usingDecls)

        hdrns = makeNamespace(self.protocol, self.hdrfile)
        hdrns.addstmts(
            [Whitespace.NL, Whitespace.NL, clsdecl, Whitespace.NL, Whitespace.NL]
        )

        actortype = ActorType(tu.protocol.decl.type)
        traitsdecl, traitsdefn = _ParamTraits.actorPickling(actortype, self.side)

        self.hdrfile.addthings([traitsdecl, Whitespace.NL] + _includeGuardEnd(hf))

        # If the implementation type is not overridden, add an implicit import
        # for the default implementation header file. Explicit implementation
        # types will specify their headers manually with `include`.
        if self.protocol.implAttribute(self.side) is None:
            assert self.protocol.name.startswith("P")
            self.externalIncludes.add(
                "".join(n.name + "/" for n in self.protocol.namespaces)
                + self.protocol.name[1:]
                + self.side.capitalize()
                + ".h"
            )

        # make the .cpp file
        cf.addthings(
            [
                _DISCLAIMER,
                Whitespace.NL,
                CppDirective(
                    "include",
                    '"' + _protocolHeaderName(self.protocol, self.side) + '.h"',
                ),
            ]
            + setToIncludes(self.externalIncludes)
        )

        cf.addthings(
            (
                [Whitespace.NL]
                + [
                    CppDirective("include", '"%s.h"' % (inc))
                    for inc in self.protocolCxxIncludes
                ]
                + [Whitespace.NL]
                + [
                    CppDirective("include", '"%s"' % filename)
                    for filename in ipdl.builtin.CppIncludes
                ]
                + [Whitespace.NL]
            )
        )

        cppns = makeNamespace(self.protocol, cf)
        cppns.addstmts(
            [Whitespace.NL, Whitespace.NL, clsdefn, Whitespace.NL, Whitespace.NL]
        )

        cf.addthing(traitsdefn)

    def visitUsingStmt(self, using):
        if using.decl.fullname is not None:
            self.typedefSet.add(
                Typedef(Type(using.decl.fullname), using.decl.shortname)
            )

        if using.header is None:
            return

        if using.canBeForwardDeclared():
            spec = using.type

            self.usingDecls.extend(
                [
                    _makeForwardDeclForQClass(
                        spec.baseid,
                        spec.quals,
                        cls=using.isClass(),
                        struct=using.isStruct(),
                    ),
                    Whitespace.NL,
                ]
            )
            self.externalIncludes.add(using.header)
        else:
            self.nonForwardDeclaredHeaders.add(using.header)

    def visitCxxInclude(self, inc):
        self.externalIncludes.add(inc.file)

    def visitInclude(self, inc):
        if inc.tu.filetype == "header":
            # Including a header will declare any globals defined by "using"
            # statements into our scope. To serialize these, we also may need
            # cxx include statements, so visit them as well.
            for cxxinc in inc.tu.cxxIncludes:
                cxxinc.accept(self)
            for using in inc.tu.using:
                using.accept(self)
            for su in inc.tu.structsAndUnions:
                su.accept(self)
        else:
            # Includes for protocols only include types explicitly exported by
            # those protocols.
            ip = inc.tu.protocol
            if ip == self.protocol:
                return

            self.actorForwardDecls.extend(
                [
                    _makeForwardDeclForActor(ip.decl.type, self.side),
                    _makeForwardDeclForActor(ip.decl.type, _otherSide(self.side)),
                    Whitespace.NL,
                ]
            )
            self.protocolCxxIncludes.append(_protocolHeaderName(ip, self.side))

            if ip.decl.fullname is not None:
                self.typedefSet.add(
                    Typedef(
                        Type(_actorName(ip.decl.fullname, self.side.title())),
                        _actorName(ip.decl.shortname, self.side.title()),
                    )
                )

                self.typedefSet.add(
                    Typedef(
                        Type(
                            _actorName(ip.decl.fullname, _otherSide(self.side).title())
                        ),
                        _actorName(ip.decl.shortname, _otherSide(self.side).title()),
                    )
                )

    def visitStructDecl(self, sd):
        if sd.decl.fullname is not None:
            self.typedefSet.add(Typedef(Type(sd.fqClassName()), sd.name))

    def visitUnionDecl(self, ud):
        if ud.decl.fullname is not None:
            self.typedefSet.add(Typedef(Type(ud.fqClassName()), ud.name))

    def visitProtocol(self, p):
        self.hdrfile.addcode(
            """
            #ifdef DEBUG
            #include "prenv.h"
            #endif  // DEBUG

            #include "mozilla/Tainting.h"
            #include "mozilla/ipc/MessageChannel.h"
            #include "mozilla/ipc/ProtocolUtils.h"
            """
        )

        self.protocol = p
        ptype = p.decl.type
        toplevel = p.decl.type.toplevel()

        hasAsyncReturns = False
        for md in p.messageDecls:
            if md.hasAsyncReturns():
                hasAsyncReturns = True
                break

        inherits = []
        if ptype.isToplevel():
            inherits.append(Inherit(p.openedProtocolInterfaceType(), viz="public"))
        else:
            inherits.append(Inherit(p.managerInterfaceType(), viz="public"))

        if ptype.isToplevel() and self.side == "parent":
            self.hdrfile.addthings(
                [_makeForwardDeclForQClass("nsIFile", []), Whitespace.NL]
            )

        self.cls = Class(self.clsname, inherits=inherits, abstract=True)

        self.cls.addstmt(Label.PRIVATE)
        friends = _FindFriends().findFriends(ptype)
        if ptype.isManaged():
            friends.update(ptype.managers)

        # |friend| managed actors so that they can call our Dealloc*()
        friends.update(ptype.manages)

        # don't friend ourself if we're a self-managed protocol
        friends.discard(ptype)

        for friend in sorted(friends, key=lambda f: f.fullname()):
            self.actorForwardDecls.extend(
                [_makeForwardDeclForActor(friend, self.prettyside), Whitespace.NL]
            )
            self.cls.addstmt(
                FriendClassDecl(_actorName(friend.fullname(), self.prettyside))
            )

        self.cls.addstmt(Label.PROTECTED)
        for typedef in sorted(self.typedefSet):
            self.cls.addstmt(typedef)

        self.cls.addstmt(Whitespace.NL)

        if hasAsyncReturns:
            self.cls.addstmt(Label.PUBLIC)
            for md in p.messageDecls:
                if self.sendsMessage(md) and md.hasAsyncReturns():
                    self.cls.addstmt(
                        Typedef(_makePromise(md.returns, self.side), md.promiseName())
                    )
                if self.receivesMessage(md) and md.hasAsyncReturns():
                    self.cls.addstmt(
                        Typedef(_makeResolver(md.returns, self.side), md.resolverName())
                    )
            self.cls.addstmt(Whitespace.NL)

        self.cls.addstmt(Label.PROTECTED)
        # interface methods that the concrete subclass has to impl
        for md in p.messageDecls:
            isctor, isdtor = md.decl.type.isCtor(), md.decl.type.isDtor()

            if self.receivesMessage(md):
                # generate Recv/Answer* interface
                implicit = not isdtor
                returnsems = "resolver" if md.decl.type.isAsync() else "out"
                recvDecl = MethodDecl(
                    md.recvMethod(),
                    params=md.makeCxxParams(
                        paramsems="move",
                        returnsems=returnsems,
                        side=self.side,
                        implicit=implicit,
                        direction="recv",
                    ),
                    ret=Type("mozilla::ipc::IPCResult"),
                    methodspec=MethodSpec.VIRTUAL,
                )

                # These method implementations cause problems when trying to
                # override them with different types in a direct call class.
                #
                # For the `isdtor` case there's a simple solution: it doesn't
                # make much sense to specify arguments and then completely
                # ignore them, and the no-arg case isn't a problem for
                # overriding.
                if isctor or (isdtor and not md.inParams):
                    defaultRecv = MethodDefn(recvDecl)
                    defaultRecv.addcode("return IPC_OK();\n")
                    self.cls.addstmt(defaultRecv)
                elif self.protocol.implAttribute(self.side) == "virtual":
                    # If we're using virtual calls, we need the methods to be
                    # declared on the base class.
                    recvDecl.methodspec = MethodSpec.PURE
                    self.cls.addstmt(StmtDecl(recvDecl))

        # If we're using virtual calls, we need the methods to be declared on
        # the base class.
        if self.protocol.implAttribute(self.side) == "virtual":
            for md in p.messageDecls:
                managed = md.decl.type.constructedType()
                if not ptype.isManagerOf(managed) or md.decl.type.isDtor():
                    continue

                # add the Alloc interface for managed actors
                actortype = md.actorDecl().bareType(self.side)

                if managed.isRefcounted():
                    if not self.receivesMessage(md):
                        continue

                    actortype.ptr = False
                    actortype = _alreadyaddrefed(actortype)

                self.cls.addstmt(
                    StmtDecl(
                        MethodDecl(
                            _allocMethod(managed, self.side),
                            params=md.makeCxxParams(
                                side=self.side, implicit=False, direction="recv"
                            ),
                            ret=actortype,
                            methodspec=MethodSpec.PURE,
                        )
                    )
                )

            # add the Dealloc interface for all managed non-refcounted actors,
            # even without ctors. This is useful for protocols which use
            # ManagedEndpoint for construction.
            for managed in ptype.manages:
                if managed.isRefcounted():
                    continue

                self.cls.addstmt(
                    StmtDecl(
                        MethodDecl(
                            _deallocMethod(managed, self.side),
                            params=[
                                Decl(p.managedCxxType(managed, self.side), "aActor")
                            ],
                            ret=Type.BOOL,
                            methodspec=MethodSpec.PURE,
                        )
                    )
                )

        if ptype.isToplevel():
            # void ProcessingError(code); default to no-op
            processingerror = MethodDefn(
                MethodDecl(
                    p.processingErrorVar().name,
                    params=[
                        Param(_Result.Type(), "aCode"),
                        Param(Type("char", const=True, ptr=True), "aReason"),
                    ],
                    methodspec=MethodSpec.OVERRIDE,
                )
            )

            # bool ShouldContinueFromReplyTimeout(); default to |true|
            shouldcontinue = MethodDefn(
                MethodDecl(
                    p.shouldContinueFromTimeoutVar().name,
                    ret=Type.BOOL,
                    methodspec=MethodSpec.OVERRIDE,
                )
            )
            shouldcontinue.addcode("return true;\n")

            self.cls.addstmts(
                [
                    processingerror,
                    shouldcontinue,
                    Whitespace.NL,
                ]
            )

        self.cls.addstmts(([Label.PUBLIC] + self.standardTypedefs() + [Whitespace.NL]))

        self.cls.addstmt(Label.PUBLIC)
        # Actor()
        ctor = ConstructorDefn(ConstructorDecl(self.clsname))
        side = ExprVar("mozilla::ipc::" + self.side.title() + "Side")
        if ptype.isToplevel():
            name = ExprLiteral.String(_actorName(p.name, self.side))
            ctor.memberinits = [
                ExprMemberInit(
                    ExprVar("mozilla::ipc::IToplevelProtocol"),
                    [name, _protocolId(ptype), side],
                )
            ]
        else:
            ctor.memberinits = [
                ExprMemberInit(
                    ExprVar("mozilla::ipc::IProtocol"), [_protocolId(ptype), side]
                )
            ]

        ctor.addcode("MOZ_COUNT_CTOR(${clsname});\n", clsname=self.clsname)
        self.cls.addstmts([ctor, Whitespace.NL])

        # ~Actor()
        dtor = DestructorDefn(
            DestructorDecl(self.clsname, methodspec=MethodSpec.VIRTUAL)
        )
        dtor.addcode("MOZ_COUNT_DTOR(${clsname});\n", clsname=self.clsname)

        self.cls.addstmts([dtor, Whitespace.NL])

        if ptype.isRefcounted():
            if not ptype.isToplevel():
                self.cls.addcode(
                    """
                    NS_INLINE_DECL_PURE_VIRTUAL_REFCOUNTING
                    """
                )
            self.cls.addstmt(Label.PROTECTED)
            self.cls.addcode(
                """
                void ActorAlloc() final { AddRef(); }
                void ActorDealloc() final { Release(); }
                """
            )

        self.cls.addstmt(Label.PUBLIC)
        if ptype.hasOtherPid():
            otherpidmeth = MethodDefn(
                MethodDecl("OtherPid", ret=Type("::base::ProcessId"), const=True)
            )
            otherpidmeth.addcode(
                """
                ::base::ProcessId pid =
                    ::mozilla::ipc::IProtocol::ToplevelProtocol()->OtherPidMaybeInvalid();
                MOZ_RELEASE_ASSERT(pid != ::base::kInvalidProcessId);
                return pid;
                """
            )
            self.cls.addstmts([otherpidmeth, Whitespace.NL])

        if not ptype.isToplevel():
            if 1 == len(p.managers):
                # manager() const
                managertype = p.managerActorType(self.side, ptr=True)
                managermeth = MethodDefn(
                    MethodDecl("Manager", ret=managertype, const=True)
                )
                managermeth.addcode(
                    """
                    return static_cast<${type}>(IProtocol::Manager());
                    """,
                    type=managertype,
                )

                self.cls.addstmts([managermeth, Whitespace.NL])

        def actorFromIter(itervar):
            return ExprCode("${iter}.Get()->GetKey()", iter=itervar)

        def forLoopOverHashtable(hashtable, itervar, const=False):
            itermeth = "ConstIter" if const else "Iter"
            return StmtFor(
                init=ExprCode(
                    "auto ${itervar} = ${hashtable}.${itermeth}()",
                    itervar=itervar,
                    hashtable=hashtable,
                    itermeth=itermeth,
                ),
                cond=ExprCode("!${itervar}.Done()", itervar=itervar),
                update=ExprCode("${itervar}.Next()", itervar=itervar),
            )

        # Managed[T](Array& inout) const
        # const Array<T>& Managed() const
        for managed in ptype.manages:
            container = p.managedVar(managed, self.side)

            meth = MethodDefn(
                MethodDecl(
                    p.managedMethod(managed, self.side).name,
                    params=[
                        Decl(
                            _cxxArrayType(
                                p.managedCxxType(managed, self.side), ref=True
                            ),
                            "aArr",
                        )
                    ],
                    const=True,
                )
            )
            meth.addcode("${container}.ToArray(aArr);\n", container=container)

            refmeth = MethodDefn(
                MethodDecl(
                    p.managedMethod(managed, self.side).name,
                    params=[],
                    ret=p.managedVarType(managed, self.side, const=True, ref=True),
                    const=True,
                )
            )
            refmeth.addcode("return ${container};\n", container=container)

            self.cls.addstmts([meth, refmeth, Whitespace.NL])

        # AllManagedActors(Array& inout) const
        arrvar = ExprVar("arr__")
        managedmeth = MethodDefn(
            MethodDecl(
                "AllManagedActors",
                params=[
                    Decl(
                        _cxxArrayType(_refptr(_cxxLifecycleProxyType()), ref=True),
                        arrvar.name,
                    )
                ],
                methodspec=MethodSpec.OVERRIDE,
                const=True,
            )
        )

        # Count the number of managed actors, and allocate space in the output array.
        managedmeth.addcode(
            """
            uint32_t total = 0;
            """
        )
        for managed in ptype.manages:
            managedmeth.addcode(
                """
                total += ${container}.Count();
                """,
                container=p.managedVar(managed, self.side),
            )
        managedmeth.addcode(
            """
            arr__.SetCapacity(total);

            """
        )

        for managed in ptype.manages:
            managedmeth.addcode(
                """
                for (auto* key : ${container}) {
                    arr__.AppendElement(key->GetLifecycleProxy());
                }

                """,
                container=p.managedVar(managed, self.side),
            )

        self.cls.addstmts([managedmeth, Whitespace.NL])

        # OpenPEndpoint(...)/BindPEndpoint(...)
        for managed in ptype.manages:
            self.genManagedEndpoint(managed)

        # OnMessageReceived()/OnCallReceived()

        # save these away for use in message handler case stmts
        msgvar = ExprVar("msg__")
        self.msgvar = msgvar
        replyvar = ExprVar("reply__")
        self.replyvar = replyvar
        var = ExprVar("v__")
        self.var = var
        # for ctor recv cases, we can't read the actor ID into a PFoo*
        # because it doesn't exist on this side yet.  Use a "special"
        # actor handle instead
        handlevar = ExprVar("handle__")
        self.handlevar = handlevar

        msgtype = ExprCode("msg__.type()")
        self.asyncSwitch = StmtSwitch(msgtype)
        self.syncSwitch = None
        self.interruptSwitch = None
        if toplevel.isSync() or toplevel.isInterrupt():
            self.syncSwitch = StmtSwitch(msgtype)
            if toplevel.isInterrupt():
                self.interruptSwitch = StmtSwitch(msgtype)

        # Add a handler for the MANAGED_ENDPOINT_BOUND and
        # MANAGED_ENDPOINT_DROPPED message types for managed actors.
        if not ptype.isToplevel():
            clearawaitingmanagedendpointbind = """
                if (!mAwaitingManagedEndpointBind) {
                    NS_WARNING("Unexpected managed endpoint lifecycle message after actor bound!");
                    return MsgNotAllowed;
                }
                mAwaitingManagedEndpointBind = false;
                """
            self.asyncSwitch.addcase(
                CaseLabel("MANAGED_ENDPOINT_BOUND_MESSAGE_TYPE"),
                StmtBlock(
                    [
                        StmtCode(clearawaitingmanagedendpointbind),
                        StmtReturn(_Result.Processed),
                    ]
                ),
            )
            self.asyncSwitch.addcase(
                CaseLabel("MANAGED_ENDPOINT_DROPPED_MESSAGE_TYPE"),
                StmtBlock(
                    [
                        StmtCode(clearawaitingmanagedendpointbind),
                        *self.destroyActor(
                            None,
                            ExprVar.THIS,
                            why=_DestroyReason.ManagedEndpointDropped,
                        ),
                        StmtReturn(_Result.Processed),
                    ]
                ),
            )

        # implement Send*() methods and add dispatcher cases to
        # message switch()es
        for md in p.messageDecls:
            self.visitMessageDecl(md)

        # add default cases
        default = StmtCode(
            """
            return MsgNotKnown;
            """
        )
        self.asyncSwitch.addcase(DefaultLabel(), default)
        if toplevel.isSync() or toplevel.isInterrupt():
            self.syncSwitch.addcase(DefaultLabel(), default)
            if toplevel.isInterrupt():
                self.interruptSwitch.addcase(DefaultLabel(), default)

        self.cls.addstmts(self.implementManagerIface())

        def makeHandlerMethod(name, switch, hasReply, dispatches=False):
            params = [Decl(Type("Message", const=True, ref=True), msgvar.name)]
            if hasReply:
                params.append(Decl(Type("UniquePtr<Message>", ref=True), replyvar.name))

            method = MethodDefn(
                MethodDecl(
                    name,
                    methodspec=MethodSpec.OVERRIDE,
                    params=params,
                    ret=_Result.Type(),
                )
            )

            if not switch:
                method.addcode(
                    """
                    MOZ_ASSERT_UNREACHABLE("message protocol not supported");
                    return MsgNotKnown;
                    """
                )
                return method

            if dispatches:
                if hasReply:
                    ondeadactor = [StmtReturn(_Result.RouteError)]
                else:
                    ondeadactor = [
                        self.logMessage(
                            None, ExprAddrOf(msgvar), "Ignored message for dead actor"
                        ),
                        StmtReturn(_Result.Processed),
                    ]

                method.addcode(
                    """
                    int32_t route__ = ${msgvar}.routing_id();
                    if (MSG_ROUTING_CONTROL != route__) {
                        IProtocol* routed__ = Lookup(route__);
                        if (!routed__ || !routed__->GetLifecycleProxy()) {
                            $*{ondeadactor}
                        }

                        RefPtr<mozilla::ipc::ActorLifecycleProxy> proxy__ =
                            routed__->GetLifecycleProxy();
                        return proxy__->Get()->${name}($,{args});
                    }

                    """,
                    msgvar=msgvar,
                    ondeadactor=ondeadactor,
                    name=name,
                    args=[p.name for p in params],
                )

            # bug 509581: don't generate the switch stmt if there
            # is only the default case; MSVC doesn't like that
            if switch.nr_cases > 1:
                method.addstmt(switch)
            else:
                method.addstmt(StmtReturn(_Result.NotKnown))

            return method

        dispatches = ptype.isToplevel() and ptype.isManager()
        self.cls.addstmts(
            [
                makeHandlerMethod(
                    "OnMessageReceived",
                    self.asyncSwitch,
                    hasReply=False,
                    dispatches=dispatches,
                ),
                Whitespace.NL,
            ]
        )
        self.cls.addstmts(
            [
                makeHandlerMethod(
                    "OnMessageReceived",
                    self.syncSwitch,
                    hasReply=True,
                    dispatches=dispatches,
                ),
                Whitespace.NL,
            ]
        )
        self.cls.addstmts(
            [
                makeHandlerMethod(
                    "OnCallReceived",
                    self.interruptSwitch,
                    hasReply=True,
                    dispatches=dispatches,
                ),
                Whitespace.NL,
            ]
        )

        clearsubtreevar = ExprVar("ClearSubtree")

        if ptype.isToplevel():
            # OnChannelClose()
            onclose = MethodDefn(
                MethodDecl("OnChannelClose", methodspec=MethodSpec.OVERRIDE)
            )
            onclose.addcode(
                """
                DestroySubtree(NormalShutdown);
                ClearSubtree();
                DeallocShmems();
                if (GetLifecycleProxy()) {
                    GetLifecycleProxy()->Release();
                }
                """
            )
            self.cls.addstmts([onclose, Whitespace.NL])

            # OnChannelError()
            onerror = MethodDefn(
                MethodDecl("OnChannelError", methodspec=MethodSpec.OVERRIDE)
            )
            onerror.addcode(
                """
                DestroySubtree(AbnormalShutdown);
                ClearSubtree();
                DeallocShmems();
                if (GetLifecycleProxy()) {
                    GetLifecycleProxy()->Release();
                }
                """
            )
            self.cls.addstmts([onerror, Whitespace.NL])

        if ptype.isToplevel() and ptype.isInterrupt():
            processnative = MethodDefn(
                MethodDecl("ProcessNativeEventsInInterruptCall", ret=Type.VOID)
            )
            processnative.addcode(
                """
                #ifdef OS_WIN
                GetIPCChannel()->ProcessNativeEventsInInterruptCall();
                #else
                FatalError("This method is Windows-only");
                #endif
                """
            )

            self.cls.addstmts([processnative, Whitespace.NL])

        # private methods
        self.cls.addstmt(Label.PRIVATE)

        # ClearSubtree()
        clearsubtree = MethodDefn(MethodDecl(clearsubtreevar.name))
        for managed in ptype.manages:
            clearsubtree.addcode(
                """
                for (auto* key : ${container}) {
                    key->ClearSubtree();
                }
                for (auto* key : ${container}) {
                    // Recursively releasing ${container} kids.
                    auto* proxy = key->GetLifecycleProxy();
                    NS_IF_RELEASE(proxy);
                }
                ${container}.Clear();

                """,
                container=p.managedVar(managed, self.side),
            )

        # don't release our own IPC reference: either the manager will do it,
        # or we're toplevel
        self.cls.addstmts([clearsubtree, Whitespace.NL])

        if not ptype.isToplevel():
            self.cls.addstmts(
                [
                    StmtDecl(
                        Decl(Type.BOOL, "mAwaitingManagedEndpointBind"),
                        init=ExprLiteral.FALSE,
                    ),
                    Whitespace.NL,
                ]
            )

        for managed in ptype.manages:
            self.cls.addstmts(
                [
                    StmtDecl(
                        Decl(
                            p.managedVarType(managed, self.side),
                            p.managedVar(managed, self.side).name,
                        )
                    )
                ]
            )

    def genManagedEndpoint(self, managed):
        hereEp = "ManagedEndpoint<%s>" % _actorName(managed.name(), self.side)
        thereEp = "ManagedEndpoint<%s>" % _actorName(
            managed.name(), _otherSide(self.side)
        )

        actor = _HybridDecl(ipdl.type.ActorType(managed), "aActor")

        # ManagedEndpoint<PThere> OpenPEndpoint(PHere* aActor)
        openmeth = MethodDefn(
            MethodDecl(
                "Open%sEndpoint" % managed.name(),
                params=[
                    Decl(self.protocol.managedCxxType(managed, self.side), actor.name)
                ],
                ret=Type(thereEp),
            )
        )
        openmeth.addcode(
            """
            $*{bind}
            // Mark our actor as awaiting the other side to be bound. This will
            // be cleared when a `MANAGED_ENDPOINT_{DROPPED,BOUND}` message is
            // received.
            aActor->mAwaitingManagedEndpointBind = true;
            return ${thereEp}(mozilla::ipc::PrivateIPDLInterface(), aActor);
            """,
            bind=self.bindManagedActor(actor, errfn=ExprCall(ExprVar(thereEp))),
            thereEp=thereEp,
        )

        # void BindPEndpoint(ManagedEndpoint<PHere>&& aEndpoint, PHere* aActor)
        bindmeth = MethodDefn(
            MethodDecl(
                "Bind%sEndpoint" % managed.name(),
                params=[
                    Decl(Type(hereEp), "aEndpoint"),
                    Decl(self.protocol.managedCxxType(managed, self.side), actor.name),
                ],
                ret=Type.BOOL,
            )
        )
        bindmeth.addcode(
            """
            return aEndpoint.Bind(mozilla::ipc::PrivateIPDLInterface(), aActor, this, ${container});
            """,
            container=self.protocol.managedVar(managed, self.side),
        )

        self.cls.addstmts([openmeth, bindmeth, Whitespace.NL])

    def implementManagerIface(self):
        p = self.protocol
        protocolbase = Type("IProtocol", ptr=True)

        methods = []

        if p.decl.type.isToplevel():
            # FIXME: This used to be declared conditionally based on whether
            # shmem appeared somewhere in the protocol hierarchy, however that
            # caused issues due to Shmem instances hidden within custom C++
            # types.
            self.asyncSwitch.addcase(
                CaseLabel("SHMEM_CREATED_MESSAGE_TYPE"),
                self.genShmemCreatedHandler(),
            )
            self.asyncSwitch.addcase(
                CaseLabel("SHMEM_DESTROYED_MESSAGE_TYPE"),
                self.genShmemDestroyedHandler(),
            )

        # Keep track of types created with an INOUT ctor. We need to call
        # Register() or RegisterID() for them depending on the side the managee
        # is created.
        inoutCtorTypes = []
        for msg in p.messageDecls:
            msgtype = msg.decl.type
            if msgtype.isCtor() and msgtype.isInout():
                inoutCtorTypes.append(msgtype.constructedType())

        # all protocols share the "same" RemoveManagee() implementation
        pvar = ExprVar("aProtocolId")
        listenervar = ExprVar("aListener")
        removemanagee = MethodDefn(
            MethodDecl(
                p.removeManageeMethod().name,
                params=[
                    Decl(_protocolIdType(), pvar.name),
                    Decl(protocolbase, listenervar.name),
                ],
                methodspec=MethodSpec.OVERRIDE,
            )
        )

        if not len(p.managesStmts):
            removemanagee.addcode(
                """
                FatalError("unreached");
                return;
                """
            )
        else:
            switchontype = StmtSwitch(pvar)
            for managee in p.managesStmts:
                manageeipdltype = managee.decl.type
                manageecxxtype = _cxxBareType(
                    ipdl.type.ActorType(manageeipdltype), self.side
                )
                case = ExprCode(
                    """
                    {
                        ${manageecxxtype} actor = static_cast<${manageecxxtype}>(aListener);

                        const bool removed = ${container}.EnsureRemoved(actor);
                        MOZ_RELEASE_ASSERT(removed, "actor not managed by this!");

                        auto* proxy = actor->GetLifecycleProxy();
                        NS_IF_RELEASE(proxy);
                        return;
                    }
                    """,
                    manageecxxtype=manageecxxtype,
                    container=p.managedVar(manageeipdltype, self.side),
                )
                switchontype.addcase(CaseLabel(_protocolId(manageeipdltype).name), case)
            switchontype.addcase(
                DefaultLabel(),
                ExprCode(
                    """
                FatalError("unreached");
                return;
                """
                ),
            )
            removemanagee.addstmt(switchontype)

        # The `DeallocManagee` method is called for managed actors to trigger
        # deallocation when ActorLifecycleProxy is freed.
        deallocmanagee = MethodDefn(
            MethodDecl(
                p.deallocManageeMethod().name,
                params=[
                    Decl(_protocolIdType(), pvar.name),
                    Decl(protocolbase, listenervar.name),
                ],
                methodspec=MethodSpec.OVERRIDE,
            )
        )

        if not len(p.managesStmts):
            deallocmanagee.addcode(
                """
                FatalError("unreached");
                return;
                """
            )
        else:
            switchontype = StmtSwitch(pvar)
            for managee in p.managesStmts:
                manageeipdltype = managee.decl.type
                # Reference counted actor types don't have corresponding
                # `Dealloc` methods, as they are deallocated by releasing the
                # IPDL-held reference.
                if manageeipdltype.isRefcounted():
                    continue

                case = StmtCode(
                    """
                    ${concrete}->${dealloc}(static_cast<${type}>(aListener));
                    return;
                    """,
                    concrete=self.concreteThis(),
                    dealloc=_deallocMethod(manageeipdltype, self.side),
                    type=_cxxBareType(ipdl.type.ActorType(manageeipdltype), self.side),
                )
                switchontype.addcase(CaseLabel(_protocolId(manageeipdltype).name), case)
            switchontype.addcase(
                DefaultLabel(),
                StmtCode(
                    """
                FatalError("unreached");
                return;
                """
                ),
            )
            deallocmanagee.addstmt(switchontype)

        return methods + [removemanagee, deallocmanagee, Whitespace.NL]

    def genShmemCreatedHandler(self):
        assert self.protocol.decl.type.isToplevel()

        return StmtCode(
            """
            {
                if (!ShmemCreated(${msgvar})) {
                    return MsgPayloadError;
                }
                return MsgProcessed;
            }
            """,
            msgvar=self.msgvar,
        )

    def genShmemDestroyedHandler(self):
        assert self.protocol.decl.type.isToplevel()

        return StmtCode(
            """
            {
                if (!ShmemDestroyed(${msgvar})) {
                    return MsgPayloadError;
                }
                return MsgProcessed;
            }
            """,
            msgvar=self.msgvar,
        )

    # -------------------------------------------------------------------------
    # The next few functions are the crux of the IPDL code generator.
    # They generate code for all the nasty work of message
    # serialization/deserialization and dispatching handlers for
    # received messages.
    ##

    def concreteThis(self):
        implAttr = self.protocol.implAttribute(self.side)
        if implAttr == "virtual":
            return ExprVar.THIS

        if implAttr is None:
            assert self.protocol.name.startswith("P")
            className = self.protocol.name[1:] + self.side.capitalize()
        else:
            assert isinstance(implAttr, ipdl.ast.StringLiteral)
            className = implAttr.value

        return ExprCode("static_cast<${className}*>(this)", className=className)

    def thisCall(self, function, args):
        return ExprCall(ExprSelect(self.concreteThis(), "->", function), args=args)

    def visitMessageDecl(self, md):
        isctor = md.decl.type.isCtor()
        isdtor = md.decl.type.isDtor()
        decltype = md.decl.type
        sendmethod = None
        movesendmethod = None
        promisesendmethod = None
        recvlbl, recvcase = None, None

        def addRecvCase(lbl, case):
            if decltype.isAsync():
                self.asyncSwitch.addcase(lbl, case)
            elif decltype.isSync():
                self.syncSwitch.addcase(lbl, case)
            elif decltype.isInterrupt():
                self.interruptSwitch.addcase(lbl, case)
            else:
                assert 0

        if self.sendsMessage(md):
            isasync = decltype.isAsync()

            # NOTE: Don't generate helper ctors for refcounted types.
            #
            # Safety concerns around providing your own actor to a ctor (namely
            # that the return value won't be checked, and the argument will be
            # `delete`-ed) are less critical with refcounted actors, due to the
            # actor being held alive by the callsite.
            #
            # This allows refcounted actors to not implement crashing AllocPFoo
            # methods on the sending side.
            if isctor and not md.decl.type.constructedType().isRefcounted():
                self.cls.addstmts([self.genHelperCtor(md), Whitespace.NL])

            if isctor and isasync:
                sendmethod, (recvlbl, recvcase) = self.genAsyncCtor(md)
            elif isctor:
                sendmethod = self.genBlockingCtorMethod(md)
            elif isdtor and isasync:
                sendmethod, (recvlbl, recvcase) = self.genAsyncDtor(md)
            elif isdtor:
                sendmethod = self.genBlockingDtorMethod(md)
            elif isasync:
                (
                    sendmethod,
                    movesendmethod,
                    promisesendmethod,
                    (recvlbl, recvcase),
                ) = self.genAsyncSendMethod(md)
            else:
                sendmethod, movesendmethod = self.genBlockingSendMethod(md)

        # XXX figure out what to do here
        if isdtor and md.decl.type.constructedType().isToplevel():
            sendmethod = None

        if sendmethod is not None:
            self.cls.addstmts([sendmethod, Whitespace.NL])
        if movesendmethod is not None:
            self.cls.addstmts([movesendmethod, Whitespace.NL])
        if promisesendmethod is not None:
            self.cls.addstmts([promisesendmethod, Whitespace.NL])
        if recvcase is not None:
            addRecvCase(recvlbl, recvcase)
            recvlbl, recvcase = None, None

        if self.receivesMessage(md):
            if isctor:
                recvlbl, recvcase = self.genCtorRecvCase(md)
            elif isdtor:
                recvlbl, recvcase = self.genDtorRecvCase(md)
            else:
                recvlbl, recvcase = self.genRecvCase(md)

            # XXX figure out what to do here
            if isdtor and md.decl.type.constructedType().isToplevel():
                return

            addRecvCase(recvlbl, recvcase)

    def genAsyncCtor(self, md):
        actor = md.actorDecl()
        method = MethodDefn(self.makeSendMethodDecl(md))

        msgvar, stmts = self.makeMessage(md, errfnSendCtor)
        sendok, sendstmts = self.sendAsync(md, msgvar)

        method.addcode(
            """
            $*{bind}

            // Build our constructor message.
            $*{stmts}

            // Notify the other side about the newly created actor. This can
            // fail if our manager has already been destroyed.
            //
            // NOTE: If the send call fails due to toplevel channel teardown,
            // the `IProtocol::ChannelSend` wrapper absorbs the error for us,
            // so we don't tear down actors unexpectedly.
            $*{sendstmts}

            // Warn, destroy the actor, and return null if the message failed to
            // send. Otherwise, return the successfully created actor reference.
            if (!${sendok}) {
                NS_WARNING("Error sending ${actorname} constructor");
                $*{destroy}
                return nullptr;
            }
            return ${actor};
            """,
            bind=self.bindManagedActor(actor),
            stmts=stmts,
            sendstmts=sendstmts,
            sendok=sendok,
            destroy=self.destroyActor(
                md, actor.var(), why=_DestroyReason.FailedConstructor
            ),
            actor=actor.var(),
            actorname=actor.ipdltype.protocol.name() + self.side.capitalize(),
        )

        lbl = CaseLabel(md.pqReplyId())
        case = StmtBlock()
        case.addstmt(StmtReturn(_Result.Processed))
        # TODO not really sure what to do with async ctor "replies" yet.
        # destroy actor if there was an error?  tricky ...

        return method, (lbl, case)

    def genBlockingCtorMethod(self, md):
        actor = md.actorDecl()
        method = MethodDefn(self.makeSendMethodDecl(md))

        msgvar, stmts = self.makeMessage(md, errfnSendCtor)

        replyvar = self.replyvar
        sendok, sendstmts = self.sendBlocking(md, msgvar, replyvar)
        replystmts = self.deserializeReply(
            md,
            replyvar,
            self.side,
            errfnSendCtor,
            errfnSentinel(ExprLiteral.NULL),
        )

        method.addcode(
            """
            $*{bind}

            // Build our constructor message.
            $*{stmts}

            // Synchronously send the constructor message to the other side. If
            // the send fails, e.g. due to the remote side shutting down, the
            // actor will be destroyed and potentially freed.
            UniquePtr<Message> ${replyvar};
            $*{sendstmts}

            if (!(${sendok})) {
                // Warn, destroy the actor and return null if the message
                // failed to send.
                NS_WARNING("Error sending constructor");
                $*{destroy}
                return nullptr;
            }

            $*{replystmts}
            return ${actor};
            """,
            bind=self.bindManagedActor(actor),
            stmts=stmts,
            replyvar=replyvar,
            sendstmts=sendstmts,
            sendok=sendok,
            destroy=self.destroyActor(
                md, actor.var(), why=_DestroyReason.FailedConstructor
            ),
            replystmts=replystmts,
            actor=actor.var(),
            actorname=actor.ipdltype.protocol.name() + self.side.capitalize(),
        )

        return method

    def bindManagedActor(self, actordecl, errfn=ExprLiteral.NULL, idexpr=None):
        actorproto = actordecl.ipdltype.protocol

        if idexpr is None:
            setManagerArgs = [ExprVar.THIS]
        else:
            setManagerArgs = [ExprVar.THIS, idexpr]

        return [
            StmtCode(
                """
            if (!${actor}) {
                NS_WARNING("Cannot bind null ${actorname} actor");
                return ${errfn};
            }

            ${actor}->SetManagerAndRegister($,{setManagerArgs});
            ${container}.Insert(${actor});
            """,
                actor=actordecl.var(),
                actorname=actorproto.name() + self.side.capitalize(),
                errfn=errfn,
                setManagerArgs=setManagerArgs,
                container=self.protocol.managedVar(actorproto, self.side),
            )
        ]

    def genHelperCtor(self, md):
        helperdecl = self.makeSendMethodDecl(md)
        helperdecl.params = helperdecl.params[1:]
        helper = MethodDefn(helperdecl)

        helper.addstmts(
            [
                self.callAllocActor(md, retsems="out", side=self.side),
                StmtReturn(
                    ExprCall(
                        ExprVar(helperdecl.name), args=md.makeCxxArgs(paramsems="move")
                    )
                ),
            ]
        )
        return helper

    def genAsyncDtor(self, md):
        actorvar = ExprVar("actor")
        method = MethodDefn(self.makeDtorMethodDecl(md, actorvar))

        method.addstmt(self.dtorPrologue(actorvar))

        msgvar, stmts = self.makeMessage(md, errfnSendDtor, actorvar)
        sendok, sendstmts = self.sendAsync(md, msgvar, actorvar)
        method.addstmts(
            stmts
            + sendstmts
            + [Whitespace.NL]
            + self.dtorEpilogue(md, actorvar)
            + [StmtReturn(sendok)]
        )

        lbl = CaseLabel(md.pqReplyId())
        case = StmtBlock()
        case.addstmt(StmtReturn(_Result.Processed))
        # TODO if the dtor is "inherently racy", keep the actor alive
        # until the other side acks

        return method, (lbl, case)

    def genBlockingDtorMethod(self, md):
        actorvar = ExprVar("actor")
        method = MethodDefn(self.makeDtorMethodDecl(md, actorvar))

        method.addstmt(self.dtorPrologue(actorvar))

        msgvar, stmts = self.makeMessage(md, errfnSendDtor, actorvar)

        replyvar = self.replyvar
        sendok, sendstmts = self.sendBlocking(md, msgvar, replyvar, actorvar)
        method.addstmts(
            stmts
            + [Whitespace.NL, StmtDecl(Decl(Type("UniquePtr<Message>"), replyvar.name))]
            + sendstmts
        )

        destmts = self.deserializeReply(
            md, replyvar, self.side, errfnSend, errfnSentinel(), actorvar
        )
        ifsendok = StmtIf(ExprLiteral.FALSE)
        ifsendok.addifstmts(destmts)
        ifsendok.addifstmts(
            [Whitespace.NL, StmtExpr(ExprAssn(sendok, ExprLiteral.FALSE, "&="))]
        )

        method.addstmt(ifsendok)

        method.addstmts(
            self.dtorEpilogue(md, actorvar) + [Whitespace.NL, StmtReturn(sendok)]
        )

        return method

    def destroyActor(self, md, actorexpr, why=_DestroyReason.Deletion):
        if md and md.decl.type.isCtor():
            destroyedType = md.decl.type.constructedType()
        else:
            destroyedType = self.protocol.decl.type

        return [
            StmtCode(
                """
                IProtocol* mgr = ${actor}->Manager();
                ${actor}->DestroySubtree(${why});
                ${actor}->ClearSubtree();
                mgr->RemoveManagee(${protoId}, ${actor});
                """,
                actor=actorexpr,
                why=why,
                protoId=_protocolId(destroyedType),
            )
        ]

    def dtorPrologue(self, actorexpr):
        return StmtCode(
            """
            if (!${actor} || !${actor}->CanSend()) {
                NS_WARNING("Attempt to __delete__ missing or closed actor");
                return false;
            }
            """,
            actor=actorexpr,
        )

    def dtorEpilogue(self, md, actorexpr):
        return self.destroyActor(md, actorexpr)

    def genRecvAsyncReplyCase(self, md):
        lbl = CaseLabel(md.pqReplyId())
        case = StmtBlock()
        resolve, reason, prologue, desrej, desstmts = self.deserializeAsyncReply(
            md, self.side, errfnRecv, errfnSentinel(_Result.ValuError)
        )

        if len(md.returns) > 1:
            resolvetype = _tuple([d.bareType(self.side) for d in md.returns])
            resolvearg = ExprCall(
                ExprVar("std::make_tuple"), args=[ExprMove(p.var()) for p in md.returns]
            )
        else:
            resolvetype = md.returns[0].bareType(self.side)
            resolvearg = ExprMove(md.returns[0].var())

        case.addcode(
            """
            $*{prologue}

            UniquePtr<MessageChannel::UntypedCallbackHolder> untypedCallback =
                GetIPCChannel()->PopCallback(${msgvar}, Id());

            typedef MessageChannel::CallbackHolder<${resolvetype}> CallbackHolder;
            auto* callback = static_cast<CallbackHolder*>(untypedCallback.get());
            if (!callback) {
                FatalError("Error unknown callback");
                return MsgProcessingError;
            }

            if (${resolve}) {
                $*{desstmts}
                callback->Resolve(${resolvearg});
            } else {
                $*{desrej}
                callback->Reject(std::move(${reason}));
            }
            return MsgProcessed;
            """,
            prologue=prologue,
            msgvar=self.msgvar,
            resolve=resolve,
            resolvetype=resolvetype,
            desstmts=desstmts,
            resolvearg=resolvearg,
            desrej=desrej,
            reason=reason,
        )

        return (lbl, case)

    def genAsyncSendMethod(self, md):
        decl = self.makeSendMethodDecl(md)
        if "VirtualSendImpl" in md.attributes:
            decl.methodspec = MethodSpec.VIRTUAL
        method = MethodDefn(decl)
        msgvar, stmts = self.makeMessage(md, errfnSend)
        retvar, sendstmts = self.sendAsync(md, msgvar)

        method.addstmts(stmts + [Whitespace.NL] + sendstmts + [StmtReturn(retvar)])

        movemethod = None

        # Add the promise overload if we need one.
        if md.returns:
            decl = self.makeSendMethodDecl(md, promise=True)
            if "VirtualSendImpl" in md.attributes:
                decl.methodspec = MethodSpec.VIRTUAL
            promisemethod = MethodDefn(decl)
            stmts = self.sendAsyncWithPromise(md)
            promisemethod.addstmts(stmts)

            (lbl, case) = self.genRecvAsyncReplyCase(md)
        else:
            (promisemethod, lbl, case) = (None, None, None)

        return method, movemethod, promisemethod, (lbl, case)

    def genBlockingSendMethod(self, md):
        method = MethodDefn(self.makeSendMethodDecl(md))

        msgvar, serstmts = self.makeMessage(md, errfnSend)
        replyvar = self.replyvar

        sendok, sendstmts = self.sendBlocking(md, msgvar, replyvar)
        failif = StmtIf(ExprNot(sendok))
        failif.addifstmt(StmtReturn.FALSE)

        desstmts = self.deserializeReply(
            md, replyvar, self.side, errfnSend, errfnSentinel()
        )

        method.addstmts(
            serstmts
            + [Whitespace.NL, StmtDecl(Decl(Type("UniquePtr<Message>"), replyvar.name))]
            + sendstmts
            + [failif]
            + desstmts
            + [Whitespace.NL, StmtReturn.TRUE]
        )

        movemethod = None

        return method, movemethod

    def genCtorRecvCase(self, md):
        lbl = CaseLabel(md.pqMsgId())
        case = StmtBlock()
        actorhandle = self.handlevar

        stmts = self.deserializeMessage(
            md, self.side, errfnRecv, errfnSent=errfnSentinel(_Result.ValuError)
        )

        idvar, saveIdStmts = self.saveActorId(md)
        case.addstmts(
            stmts
            + [
                StmtDecl(Decl(r.bareType(self.side), r.var().name), initargs=[])
                for r in md.returns
            ]
            # alloc the actor, register it under the foreign ID
            + [self.callAllocActor(md, retsems="in", side=self.side)]
            + self.bindManagedActor(
                md.actorDecl(), errfn=_Result.ValuError, idexpr=_actorHId(actorhandle)
            )
            + [Whitespace.NL]
            + saveIdStmts
            + self.invokeRecvHandler(md)
            + self.makeReply(md, errfnRecv, idvar)
            + [Whitespace.NL, StmtReturn(_Result.Processed)]
        )

        return lbl, case

    def genDtorRecvCase(self, md):
        lbl = CaseLabel(md.pqMsgId())
        case = StmtBlock()

        stmts = self.deserializeMessage(
            md, self.side, errfnRecv, errfnSent=errfnSentinel(_Result.ValuError)
        )

        idvar, saveIdStmts = self.saveActorId(md)
        case.addstmts(
            stmts
            + [
                StmtDecl(Decl(r.bareType(self.side), r.var().name), initargs=[])
                for r in md.returns
            ]
            + self.invokeRecvHandler(md)
            + [Whitespace.NL]
            + saveIdStmts
            + self.makeReply(md, errfnRecv, routingId=idvar)
            + [Whitespace.NL]
            + self.dtorEpilogue(md, ExprVar.THIS)
            + [Whitespace.NL, StmtReturn(_Result.Processed)]
        )

        return lbl, case

    def genRecvCase(self, md):
        lbl = CaseLabel(md.pqMsgId())
        case = StmtBlock()

        stmts = self.deserializeMessage(
            md, self.side, errfn=errfnRecv, errfnSent=errfnSentinel(_Result.ValuError)
        )

        idvar, saveIdStmts = self.saveActorId(md)
        declstmts = [
            StmtDecl(Decl(r.bareType(self.side), r.var().name), initargs=[])
            for r in md.returns
        ]
        if md.decl.type.isAsync() and md.returns:
            declstmts = self.makeResolver(md, errfnRecv, routingId=idvar)
        case.addstmts(
            stmts
            + saveIdStmts
            + declstmts
            + self.invokeRecvHandler(md)
            + [Whitespace.NL]
            + self.makeReply(md, errfnRecv, routingId=idvar)
            + [StmtReturn(_Result.Processed)]
        )

        return lbl, case

    # helper methods

    def makeMessage(self, md, errfn, fromActor=None):
        msgvar = self.msgvar
        writervar = ExprVar("writer__")
        routingId = self.protocol.routingId(fromActor)
        this = fromActor or ExprVar.THIS

        stmts = (
            [
                StmtDecl(
                    Decl(Type("UniquePtr<IPC::Message>"), msgvar.name),
                    init=ExprCall(ExprVar(md.pqMsgCtorFunc()), args=[routingId]),
                ),
                StmtDecl(
                    Decl(Type("IPC::MessageWriter"), writervar.name),
                    initargs=[ExprDeref(msgvar), this],
                ),
            ]
            + [Whitespace.NL]
            + [
                _ParamTraits.checkedWrite(
                    p.ipdltype,
                    p.var(),
                    ExprAddrOf(writervar),
                    sentinelKey=p.name,
                )
                for p in md.params
            ]
            + [Whitespace.NL]
            + self.setMessageFlags(md, msgvar)
        )
        return msgvar, stmts

    def makeResolver(self, md, errfn, routingId):
        if routingId is None:
            routingId = self.protocol.routingId()
        if not md.decl.type.isAsync() or not md.hasReply():
            return []

        def paramValue(idx):
            assert idx < len(md.returns)
            if len(md.returns) > 1:
                return ExprCode("std::get<${idx}>(aParam)", idx=idx)
            return ExprVar("aParam")

        serializeParams = [
            _ParamTraits.checkedWrite(
                p.ipdltype,
                paramValue(idx),
                ExprAddrOf(ExprVar("writer__")),
                sentinelKey=p.name,
            )
            for idx, p in enumerate(md.returns)
        ]

        return [
            StmtCode(
                """
                UniquePtr<IPC::Message> ${replyvar}(${replyCtor}(${routingId}));
                ${replyvar}->set_seqno(${msgvar}.seqno());

                RefPtr<mozilla::ipc::IPDLResolverInner> resolver__ =
                    new mozilla::ipc::IPDLResolverInner(std::move(${replyvar}), this);

                ${resolvertype} resolver = [resolver__ = std::move(resolver__)](${resolveType} aParam) {
                    resolver__->Resolve([&] (IPC::Message* ${replyvar}, IProtocol* self__) {
                        IPC::MessageWriter writer__(*${replyvar}, self__);
                        $*{serializeParams}
                        ${logSendingReply}
                    });
                };
                """,
                msgvar=self.msgvar,
                resolvertype=Type(md.resolverName()),
                routingId=routingId,
                resolveType=_resolveType(md.returns, self.side),
                replyvar=self.replyvar,
                replyCtor=ExprVar(md.pqReplyCtorFunc()),
                serializeParams=serializeParams,
                logSendingReply=self.logMessage(
                    md,
                    self.replyvar,
                    "Sending reply ",
                    actor=ExprVar("self__"),
                ),
            )
        ]

    def makeReply(self, md, errfn, routingId):
        if routingId is None:
            routingId = self.protocol.routingId()
        # TODO special cases for async ctor/dtor replies
        if not md.decl.type.hasReply():
            return []
        if md.decl.type.isAsync() and md.decl.type.hasReply():
            return []

        replyvar = self.replyvar
        return (
            [
                StmtExpr(
                    ExprAssn(
                        replyvar,
                        ExprCall(ExprVar(md.pqReplyCtorFunc()), args=[routingId]),
                    )
                ),
                StmtDecl(
                    Decl(Type("IPC::MessageWriter"), "writer__"),
                    initargs=[ExprDeref(replyvar), ExprVar.THIS],
                ),
                Whitespace.NL,
            ]
            + [
                _ParamTraits.checkedWrite(
                    r.ipdltype,
                    r.var(),
                    ExprAddrOf(ExprVar("writer__")),
                    sentinelKey=r.name,
                )
                for r in md.returns
            ]
            + self.setMessageFlags(md, replyvar)
            + [self.logMessage(md, replyvar, "Sending reply ")]
        )

    def setMessageFlags(self, md, var, seqno=None):
        stmts = []

        if seqno:
            stmts.append(
                StmtExpr(ExprCall(ExprSelect(var, "->", "set_seqno"), args=[seqno]))
            )

        return stmts + [Whitespace.NL]

    def deserializeMessage(self, md, side, errfn, errfnSent):
        msgvar = self.msgvar
        msgexpr = ExprAddrOf(msgvar)
        readervar = ExprVar("reader__")
        isctor = md.decl.type.isCtor()
        stmts = [
            self.logMessage(md, msgexpr, "Received ", receiving=True),
            self.profilerLabel(md),
            Whitespace.NL,
        ]

        if 0 == len(md.params):
            return stmts

        start, reads = 0, []
        if isctor:
            # return the raw actor handle so that its ID can be used
            # to construct the "real" actor
            handlevar = self.handlevar
            handletype = Type("ActorHandle")
            reads = [
                _ParamTraits.checkedRead(
                    None,
                    handletype,
                    handlevar,
                    ExprAddrOf(readervar),
                    errfn,
                    "'%s'" % handletype.name,
                    sentinelKey="actor",
                    errfnSentinel=errfnSent,
                )
            ]
            start = 1

        def maybeTainted(p, side):
            if md.decl.type.tainted and "NoTaint" not in p.attributes:
                return Type("Tainted", T=p.bareType(side))
            return p.bareType(side)

        reads.extend(
            [
                _ParamTraits.checkedRead(
                    p.ipdltype,
                    maybeTainted(p, side),
                    p.var(),
                    ExprAddrOf(readervar),
                    errfn,
                    "'%s'" % p.ipdltype.name(),
                    sentinelKey=p.name,
                    errfnSentinel=errfnSent,
                )
                for p in md.params[start:]
            ]
        )

        stmts.extend(
            (
                [
                    StmtDecl(
                        Decl(Type("IPC::MessageReader"), readervar.name),
                        initargs=[msgvar, ExprVar.THIS],
                    )
                ]
                + [Whitespace.NL]
                + reads
                + [StmtCode("${reader}.EndRead();\n", reader=readervar)]
            )
        )

        return stmts

    def deserializeAsyncReply(self, md, side, errfn, errfnSent):
        msgvar = self.msgvar
        readervar = ExprVar("reader__")
        msgexpr = ExprAddrOf(msgvar)
        isctor = md.decl.type.isCtor()
        resolve = ExprVar("resolve__")
        reason = ExprVar("reason__")

        # NOTE: The `resolve__` and `reason__` parameters don't have sentinels,
        # as they are serialized by the IPDLResolverInner type in
        # ProtocolUtils.cpp rather than by generated code.
        desresolve = [
            StmtCode(
                """
                bool resolve__ = false;
                if (!IPC::ReadParam(&${readervar}, &resolve__)) {
                    FatalError("Error deserializing bool");
                    return MsgValueError;
                }
                """,
                readervar=readervar,
            ),
        ]
        desrej = [
            StmtCode(
                """
                ResponseRejectReason reason__{};
                if (!IPC::ReadParam(&${readervar}, &reason__)) {
                    FatalError("Error deserializing ResponseRejectReason");
                    return MsgValueError;
                }
                ${readervar}.EndRead();
                """,
                readervar=readervar,
            ),
        ]
        prologue = [
            self.logMessage(md, msgexpr, "Received ", receiving=True),
            self.profilerLabel(md),
            Whitespace.NL,
        ]

        if not md.returns:
            return prologue

        prologue.extend(
            [
                StmtDecl(
                    Decl(Type("IPC::MessageReader"), readervar.name),
                    initargs=[msgvar, ExprVar.THIS],
                )
            ]
            + desresolve
        )

        start, reads = 0, []
        if isctor:
            # return the raw actor handle so that its ID can be used
            # to construct the "real" actor
            handlevar = self.handlevar
            handletype = Type("ActorHandle")
            reads = [
                _ParamTraits.checkedRead(
                    None,
                    handletype,
                    handlevar,
                    ExprAddrOf(readervar),
                    errfn,
                    "'%s'" % handletype.name,
                    sentinelKey="actor",
                    errfnSentinel=errfnSent,
                )
            ]
            start = 1

        stmts = (
            reads
            + [
                _ParamTraits.checkedRead(
                    p.ipdltype,
                    p.bareType(side),
                    p.var(),
                    ExprAddrOf(readervar),
                    errfn,
                    "'%s'" % p.ipdltype.name(),
                    sentinelKey=p.name,
                    errfnSentinel=errfnSent,
                )
                for p in md.returns[start:]
            ]
            + [StmtCode("${reader}.EndRead();", reader=readervar)]
        )

        return resolve, reason, prologue, desrej, stmts

    def deserializeReply(self, md, replyexpr, side, errfn, errfnSentinel, actor=None):
        stmts = [
            Whitespace.NL,
            self.logMessage(md, replyexpr, "Received reply ", actor, receiving=True),
        ]
        if 0 == len(md.returns):
            return stmts

        def tempvar(r):
            return ExprVar(r.var().name + "__reply")

        readervar = ExprVar("reader__")
        stmts.extend(
            [
                Whitespace.NL,
                StmtDecl(
                    Decl(Type("IPC::MessageReader"), readervar.name),
                    initargs=[ExprDeref(self.replyvar), ExprVar.THIS],
                ),
            ]
            + [Whitespace.NL]
            + [
                _ParamTraits.checkedRead(
                    r.ipdltype,
                    r.bareType(side),
                    tempvar(r),
                    ExprAddrOf(readervar),
                    errfn,
                    "'%s'" % r.ipdltype.name(),
                    sentinelKey=r.name,
                    errfnSentinel=errfnSentinel,
                )
                for r in md.returns
            ]
            # Move-assign the values out of the variables created with
            # checkedRead into outparams.
            + [
                StmtExpr(ExprAssn(ExprDeref(r.var()), ExprMove(tempvar(r))))
                for r in md.returns
            ]
            + [StmtCode("${reader}.EndRead();", reader=readervar)]
        )

        return stmts

    def sendAsync(self, md, msgexpr, actor=None):
        sendok = ExprVar("sendok__")
        resolvefn = ExprVar("aResolve")
        rejectfn = ExprVar("aReject")

        stmts = [
            Whitespace.NL,
            self.logMessage(md, msgexpr, "Sending ", actor),
            self.profilerLabel(md),
        ]
        stmts.append(Whitespace.NL)

        # Generate the actual call expression.
        send = ExprVar("ChannelSend")
        if actor is not None:
            send = ExprSelect(actor, "->", send.name)
        if md.returns:
            stmts.append(
                StmtExpr(
                    ExprCall(
                        send,
                        args=[
                            ExprMove(msgexpr),
                            ExprVar(md.pqReplyId()),
                            ExprMove(resolvefn),
                            ExprMove(rejectfn),
                        ],
                    )
                )
            )
            retvar = None
        else:
            stmts.append(
                StmtDecl(
                    Decl(Type.BOOL, sendok.name),
                    init=ExprCall(send, args=[ExprMove(msgexpr)]),
                )
            )
            retvar = sendok

        return (retvar, stmts)

    def sendBlocking(self, md, msgexpr, replyexpr, actor=None):
        send = ExprVar("ChannelSend")
        if md.decl.type.isInterrupt():
            send = ExprVar("ChannelCall")
        if actor is not None:
            send = ExprSelect(actor, "->", send.name)

        sendok = ExprVar("sendok__")
        self.externalIncludes.add("mozilla/ProfilerMarkers.h")
        return (
            sendok,
            (
                [
                    Whitespace.NL,
                    self.logMessage(md, msgexpr, "Sending ", actor),
                    self.profilerLabel(md),
                ]
                + [
                    Whitespace.NL,
                    StmtDecl(Decl(Type.BOOL, sendok.name), init=ExprLiteral.FALSE),
                    StmtBlock(
                        [
                            StmtExpr(
                                ExprCall(
                                    ExprVar("AUTO_PROFILER_TRACING_MARKER"),
                                    [
                                        ExprLiteral.String("Sync IPC"),
                                        ExprLiteral.String(
                                            self.protocol.name
                                            + "::"
                                            + md.prettyMsgName()
                                        ),
                                        ExprVar("IPC"),
                                    ],
                                )
                            ),
                            StmtExpr(
                                ExprAssn(
                                    sendok,
                                    ExprCall(
                                        send,
                                        args=[ExprMove(msgexpr), ExprAddrOf(replyexpr)],
                                    ),
                                )
                            ),
                        ]
                    ),
                ]
            ),
        )

    def sendAsyncWithPromise(self, md):
        # Create a new promise, and forward to the callback send overload.
        promise = _makePromise(md.returns, self.side, resolver=True)

        if len(md.returns) > 1:
            resolvetype = _tuple([d.bareType(self.side) for d in md.returns])
        else:
            resolvetype = md.returns[0].bareType(self.side)

        resolve = ExprCode(
            """
            [promise__](${resolvetype}&& aValue) {
                promise__->Resolve(std::move(aValue), __func__);
            }
            """,
            resolvetype=resolvetype,
        )
        reject = ExprCode(
            """
            [promise__](ResponseRejectReason&& aReason) {
                promise__->Reject(std::move(aReason), __func__);
            }
            """,
            resolvetype=resolvetype,
        )

        args = [ExprMove(p.var()) for p in md.params] + [resolve, reject]
        stmt = StmtCode(
            """
            RefPtr<${promise}> promise__ = new ${promise}(__func__);
            promise__->UseDirectTaskDispatch(__func__);
            ${send}($,{args});
            return promise__;
            """,
            promise=promise,
            send=md.sendMethod(),
            args=args,
        )
        return [stmt]

    def callAllocActor(self, md, retsems, side):
        actortype = md.actorDecl().bareType(self.side)
        if md.decl.type.constructedType().isRefcounted():
            actortype.ptr = False
            actortype = _refptr(actortype)

        callalloc = self.thisCall(
            _allocMethod(md.decl.type.constructedType(), side),
            args=md.makeCxxArgs(retsems=retsems, retcallsems="out", implicit=False),
        )

        return StmtDecl(Decl(actortype, md.actorDecl().var().name), init=callalloc)

    def invokeRecvHandler(self, md):
        retsems = "in"
        if md.decl.type.isAsync() and md.returns:
            retsems = "resolver"
        okdecl = StmtDecl(
            Decl(Type("mozilla::ipc::IPCResult"), "__ok"),
            init=self.thisCall(
                md.recvMethod(),
                md.makeCxxArgs(
                    paramsems="move",
                    retsems=retsems,
                    retcallsems="out",
                ),
            ),
        )
        failif = StmtIf(ExprNot(ExprVar("__ok")))
        failif.addifstmts(
            [
                _protocolErrorBreakpoint("Handler returned error code!"),
                Whitespace(
                    "// Error handled in mozilla::ipc::IPCResult\n", indent=True
                ),
                StmtReturn(_Result.ProcessingError),
            ]
        )
        return [okdecl, failif]

    def makeDtorMethodDecl(self, md, actorvar):
        decl = self.makeSendMethodDecl(md)
        decl.params.insert(
            0,
            Decl(
                _cxxInType(
                    ipdl.type.ActorType(md.decl.type.constructedType()),
                    side=self.side,
                    direction="send",
                ),
                actorvar.name,
            ),
        )
        decl.methodspec = MethodSpec.STATIC
        return decl

    def makeSendMethodDecl(self, md, promise=False, paramsems="in"):
        implicit = md.decl.type.hasImplicitActorParam()
        if md.decl.type.isAsync() and md.returns:
            if promise:
                returnsems = "promise"
                rettype = _refptr(Type(md.promiseName()))
            else:
                returnsems = "callback"
                rettype = Type.VOID
        else:
            assert not promise
            returnsems = "out"
            rettype = Type.BOOL
        decl = MethodDecl(
            md.sendMethod(),
            params=md.makeCxxParams(
                paramsems,
                returnsems=returnsems,
                side=self.side,
                implicit=implicit,
                direction="send",
            ),
            warn_unused=(
                (self.side == "parent" and returnsems != "callback")
                or (md.decl.type.isCtor() and not md.decl.type.isAsync())
            ),
            ret=rettype,
        )
        if md.decl.type.isCtor():
            decl.ret = md.actorDecl().bareType(self.side)
        return decl

    def logMessage(self, md, msgptr, pfx, actor=None, receiving=False):
        actorname = _actorName(self.protocol.name, self.side)
        return StmtCode(
            """
            if (mozilla::ipc::LoggingEnabledFor(${actorname})) {
                mozilla::ipc::LogMessageForProtocol(
                    ${actorname},
                    ${actor}->ToplevelProtocol()->OtherPidMaybeInvalid(),
                    ${pfx},
                    ${msgptr}->type(),
                    mozilla::ipc::MessageDirection::${direction});
            }
            """,
            actorname=ExprLiteral.String(actorname),
            actor=actor or ExprVar.THIS,
            pfx=ExprLiteral.String(pfx),
            msgptr=msgptr,
            direction="eReceiving" if receiving else "eSending",
        )

    def profilerLabel(self, md):
        self.externalIncludes.add("mozilla/ProfilerLabels.h")
        return StmtCode(
            """
            AUTO_PROFILER_LABEL("${name}::${msgname}", OTHER);
            """,
            name=self.protocol.name,
            msgname=md.prettyMsgName(),
        )

    def saveActorId(self, md):
        idvar = ExprVar("id__")
        if md.decl.type.hasReply():
            # only save the ID if we're actually going to use it, to
            # avoid unused-variable warnings
            saveIdStmts = [
                StmtDecl(Decl(_actorIdType(), idvar.name), self.protocol.routingId())
            ]
        else:
            saveIdStmts = []
        return idvar, saveIdStmts


class _GenerateProtocolParentCode(_GenerateProtocolActorCode):
    def __init__(self):
        _GenerateProtocolActorCode.__init__(self, "parent")

    def sendsMessage(self, md):
        return not md.decl.type.isIn()

    def receivesMessage(self, md):
        return md.decl.type.isInout() or md.decl.type.isIn()


class _GenerateProtocolChildCode(_GenerateProtocolActorCode):
    def __init__(self):
        _GenerateProtocolActorCode.__init__(self, "child")

    def sendsMessage(self, md):
        return not md.decl.type.isOut()

    def receivesMessage(self, md):
        return md.decl.type.isInout() or md.decl.type.isOut()


# -----------------------------------------------------------------------------
# Utility passes
##


def _splitClassDeclDefn(cls):
    """Destructively split |cls| methods into declarations and
    definitions (if |not methodDecl.force_inline|).  Return classDecl,
    methodDefns."""
    defns = Block()

    for i, stmt in enumerate(cls.stmts):
        if isinstance(stmt, MethodDefn) and not stmt.decl.force_inline:
            decl, defn = _splitMethodDeclDefn(stmt, cls)
            cls.stmts[i] = StmtDecl(decl)
            if defn:
                defns.addstmts([defn, Whitespace.NL])

    return cls, defns


def _splitMethodDeclDefn(md, cls):
    # Pure methods have decls but no defns.
    if md.decl.methodspec == MethodSpec.PURE:
        return md.decl, None

    saveddecl = deepcopy(md.decl)
    md.decl.cls = cls
    # Don't emit method specifiers on method defns.
    md.decl.methodspec = MethodSpec.NONE
    md.decl.warn_unused = False
    md.decl.only_for_definition = True
    for param in md.decl.params:
        if isinstance(param, Param):
            param.default = None
    return saveddecl, md


def _splitFuncDeclDefn(fun):
    assert not fun.decl.force_inline
    return StmtDecl(fun.decl), fun