File: cpp.py

package info (click to toggle)
mupdf 1.27.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 29,224 kB
  • sloc: ansic: 335,320; python: 20,906; java: 7,520; javascript: 2,213; makefile: 1,152; xml: 675; cpp: 639; sh: 513; cs: 307; awk: 10; sed: 7; lisp: 3
file content (5965 lines) | stat: -rw-r--r-- 235,238 bytes parent folder | download
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
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
'''
Functions for generating source code for the C++ bindings.
'''

import io
import os
import pickle
import re
import textwrap

import jlib

from . import classes
from . import csharp
from . import parse
from . import python
from . import rename
from . import state
from . import util


def _make_top_level( text, top_level='::'):
    if text == 'string':
        # This is a hack; for some reason we often end up with `string` when it
        # it should be `std::string`.
        text = 'std::string'
    initial_prefix = ['']
    def handle_prefix( text, prefix):
        if text.startswith( prefix):
            initial_prefix[0] += prefix
            return text[ len(prefix):]
        return text
    text = handle_prefix( text, 'const ')
    text = handle_prefix( text, 'struct ')
    if text.startswith( ('fz_', 'pdf_')):
        text = f'{top_level}{text}'
    text = f'{initial_prefix[0]}{text}'
    return text


def declaration_text(
        type_,
        name,
        nest=0,
        name_is_simple=True,
        verbose=False,
        expand_typedef=True,
        top_level='::',
        ):
    '''
    Returns text for C++ declaration of <type_> called <name>.

    type:
        a clang.cindex.Type.
    name:
        name of type; can be empty.
    nest:
        for internal diagnostics.
    name_is_simple:
        true iff <name> is an identifier.
    verbose:
        .
    expand_typedef:
        .
    top_level:
        Prefix used for top-level names. When generating C# code, use `mupdf.`.

    If name_is_simple is false, we surround <name> with (...) if type is a
    function.
    '''
    # clang can give unhelpful spelling for anonymous structs.
    assert 'struct (unnamed at ' not in type_.spelling, f'type_.spelling={type_.spelling}'
    if verbose:
        jlib.log( '{nest=} {name=} {type_.spelling=} {type_.get_declaration().get_usr()=}')
        jlib.log( '{type_.kind=} {type_.get_array_size()=} {expand_typedef=}')

    array_n = type_.get_array_size()
    if verbose:
        jlib.log( '{array_n=}')
    if array_n >= 0 or type_.kind == state.clang.cindex.TypeKind.INCOMPLETEARRAY:
        if verbose: jlib.log( '{array_n=}')
        if array_n < 0:
            array_n = ''
        ret = declaration_text(
                type_.get_array_element_type(),
                f'{name}[{array_n}]',
                nest+1,
                name_is_simple,
                verbose=verbose,
                expand_typedef=expand_typedef,
                top_level=top_level,
                )
        if verbose:
            jlib.log( 'returning {ret=}')
        return ret

    pointee = type_.get_pointee()
    if pointee and pointee.spelling:
        if type_.kind == state.clang.cindex.TypeKind.LVALUEREFERENCE:
            pointee_type = '&'
        elif type_.kind == state.clang.cindex.TypeKind.POINTER:
            pointee_type = '*'
        else:
            assert 0, f'Unrecognised pointer kind {type_.kind=}.'
        if verbose: jlib.log( '{type_=} {type_.kind=} {pointee.spelling=}')
        ret = declaration_text(
                pointee,
                f'{pointee_type}{name}',
                nest+1,
                name_is_simple=False,
                verbose=verbose,
                expand_typedef=expand_typedef,
                top_level=top_level,
                )
        if verbose:
            jlib.log( 'returning {ret=}')
        return ret

    if expand_typedef and type_.get_typedef_name():
        if verbose: jlib.log( '{type_.get_typedef_name()=}')
        const = 'const ' if type_.is_const_qualified() else ''
        ret = f'{const}{_make_top_level(type_.get_typedef_name(), top_level)} {name}'
        if verbose:
            jlib.log( 'returning {ret=}')
        return ret

    # On MacOS type `size_t` returns true from get_result() and is
    # state.clang.cindex.TypeKind.ELABORATED.
    #
    if ( type_.get_result().spelling
            and type_.kind not in
                (
                    state.clang.cindex.TypeKind.FUNCTIONNOPROTO,
                    state.clang.cindex.TypeKind.ELABORATED,
                )
            ):
        # <type> is a function. We call ourselves with type=type_.get_result()
        # and name=<name>(<args>).
        #
        assert type_.kind == state.clang.cindex.TypeKind.FUNCTIONPROTO, \
                f'{type_.spelling=} {type_.kind=}'
        ret = ''
        sep = ''
        for arg in type_.argument_types():
            ret += sep
            ret += declaration_text(
                    arg,
                    '',
                    nest+1,
                    top_level=top_level,
                    verbose=verbose,
                    expand_typedef=expand_typedef,
                    )
            sep = ', '
        if verbose: jlib.log( '{ret!r=}')
        if not name_is_simple:
            # If name isn't a simple identifier, put it inside braces, e.g.
            # this crudely allows function pointers to work.
            name = f'({name})'
        ret = f'{name}({ret})'
        if verbose: jlib.log( '{type_.get_result()=}')
        ret = declaration_text(
                type_.get_result(),
                ret,
                nest+1,
                name_is_simple=False,
                verbose=verbose,
                expand_typedef=expand_typedef,
                top_level=top_level,
                )
        if verbose:
            jlib.log( 'returning {ret=}')
        return ret

    ret = f'{_make_top_level(type_.spelling, top_level)} {name}'
    assert not 'struct (unnamed at ' in ret, f'Bad clang name for anonymous struct: {ret}'
    if verbose: jlib.log( 'returning {ret=}')
    return ret


def write_call_arg(
        tu,
        arg,
        classname,
        have_used_this,
        out_cpp,
        verbose=False,
        python=False,
        ):
    '''
    Write an arg of a function call, translating between raw and wrapping
    classes as appropriate.

    If the required type is a fz_ struct that we wrap, we assume that arg.name
    is a reference to an instance of the wrapper class. If the wrapper class
    is the same as <classname>, we use 'this->' instead of <name>. We also
    generate slightly different code depending on whether the wrapper class is
    pod or inline pod.

    arg:
        Arg from get_args().
    classname:
        Name of wrapper class available as 'this'.
    have_used_this:
        If true, we never use 'this->...'.
    out_cpp:
        .
    python:
        If true, we write python code, not C.

    Returns True if we have used 'this->...', else return <have_used_this>.
    '''
    assert isinstance( arg, parse.Arg)
    assert isinstance( arg.cursor, state.clang.cindex.Cursor)
    if not arg.alt:
        # Arg is a normal type; no conversion necessary.
        if python:
            out_cpp.write( arg.name_python)
        else:
            out_cpp.write( arg.name)
        return have_used_this

    if verbose:
        jlib.log( '{=arg.name arg.alt.spelling classname}')
    type_ = state.get_name_canonical( arg.cursor.type)
    ptr = '*'
    #log( '{=arg.name arg.alt.spelling classname type_.spelling}')
    if type_.kind == state.clang.cindex.TypeKind.POINTER:
        type_ = state.get_name_canonical( type_.get_pointee())
        ptr = ''
    #log( '{=arg.name arg.alt.spelling classname type_.spelling}')
    extras = parse.get_fz_extras( tu, type_.spelling)
    assert extras, f'No extras for type_.spelling={type_.spelling}'
    if verbose:
        jlib.log( 'param is fz: {type_.spelling=} {extras2.pod=}')
    assert extras.pod != 'none' \
            'Cannot pass wrapper for {type_.spelling} as arg because pod is "none" so we cannot recover struct.'
    if python:
        if extras.pod == 'inline':
            out_cpp.write( f'{arg.name_python}.internal()')
        elif extras.pod:
            out_cpp.write( f'{arg.name_python}.m_internal')
        else:
            out_cpp.write( f'{arg.name_python}.m_internal')

    elif extras.pod == 'inline':
        # We use the address of the first class member, casting it to a pointer
        # to the wrapped type. Not sure this is guaranteed safe, but should
        # work in practise.
        name_ = f'{arg.name}.'
        if not have_used_this and rename.class_(arg.alt.type.spelling) == classname:
            have_used_this = True
            name_ = 'this->'
        field0 = parse.get_field0(type_).spelling
        out_cpp.write( f'{ptr} {name_}internal()')
    else:
        if verbose:
            jlib.log( '{=arg state.get_name_canonical(arg.cursor.type).kind classname extras}')
        if extras.pod and state.get_name_canonical( arg.cursor.type).kind == state.clang.cindex.TypeKind.POINTER:
            out_cpp.write( '&')
        elif not extras.pod and state.get_name_canonical( arg.cursor.type).kind != state.clang.cindex.TypeKind.POINTER:
            out_cpp.write( '*')
        elif arg.out_param:
            out_cpp.write( '&')
        if not have_used_this and rename.class_(arg.alt.type.spelling) == classname:
            have_used_this = True
            out_cpp.write( 'this->')
        else:
            out_cpp.write( f'{arg.name}.')
        out_cpp.write( 'm_internal')

    return have_used_this


def make_fncall( tu, cursor, return_type, fncall, out, refcheck_if, trace_if):
    '''
    Writes a low-level function call to <out>, using fz_context_s from
    internal_context_get() and with fz_try...fz_catch that converts to C++
    exceptions by calling throw_exception().

    return_type:
        Text return type of function, e.g. 'void' or 'double'.
    fncall:
        Text containing function call, e.g. 'function(a, b, 34)'.
    out:
        Stream to which we write generated code.
    '''
    uses_fz_context = False;

    # Setting this to False is a hack to elide all fz_try/fz_catch code. This
    # has a very small effect on mupdfpy test suite performance - e.g. reduce
    # time from 548.1s to 543.2s.
    #
    use_fz_try = True

    if cursor.spelling in (
            'pdf_specifics',
            ):
        # This fn takes a fz_context* but never throws, so we can omit
        # `fz_try()...fz_catch()`, which might give a small performance
        # improvement.
        use_fz_try = False
        uses_fz_context = True
    else:
        for arg in parse.get_args( tu, cursor, include_fz_context=True):
            if parse.is_pointer_to( arg.cursor.type, 'fz_context'):
                uses_fz_context = True
                break
    if uses_fz_context:
        context_get = rename.internal( 'context_get')
        throw_exception = rename.internal( 'throw_exception')
        out.write( f'    fz_context* auto_ctx = {context_get}();\n')

    # Output code that writes diagnostics to std::cerr if $MUPDF_trace is set.
    #
    def varname_enable():
        for t in 'fz_keep_', 'fz_drop_', 'pdf_keep_', 'pdf_drop_':
            if cursor.spelling.startswith( t):
                return 's_trace_keepdrop'
        return 's_trace > 1'

    out.write( f'    {trace_if}\n')
    out.write( f'    if ({varname_enable()}) {{\n')
    out.write( f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): calling {cursor.spelling}():";\n')
    for arg in parse.get_args( tu, cursor, include_fz_context=True):
        if parse.is_pointer_to( arg.cursor.type, 'fz_context'):
            out.write( f'        if ({varname_enable()}) std::cerr << " auto_ctx=" << auto_ctx;\n')
        elif arg.out_param:
            out.write( f'        if ({varname_enable()}) std::cerr << " {arg.name}=" << (void*) {arg.name};\n')
        elif arg.alt:
            # If not a pod, there will not be an operator<<, so just show
            # the address of this arg.
            #
            extras = parse.get_fz_extras( tu, arg.alt.type.spelling)
            assert extras.pod != 'none' \
                    'Cannot pass wrapper for {type_.spelling} as arg because pod is "none" so we cannot recover struct.'
            if extras.pod:
                out.write( f'        std::cerr << " {arg.name}=" << {arg.name};\n')
            elif arg.cursor.type.kind == state.clang.cindex.TypeKind.POINTER:
                out.write( f'        if ({varname_enable()}) std::cerr << " {arg.name}=" << {arg.name};\n')
            elif arg.cursor.type.kind == state.clang.cindex.TypeKind.LVALUEREFERENCE:
                out.write( f'        if ({varname_enable()}) std::cerr << " &{arg.name}=" << &{arg.name};\n')
            else:
                out.write( f'        std::cerr << " &{arg.name}=" << &{arg.name};\n')
        elif parse.is_pointer_to(arg.cursor.type, 'char') and state.get_name_canonical( arg.cursor.type.get_pointee()).is_const_qualified():
            # 'const char*' is assumed to be zero-terminated string. But we
            # need to protect against trying to write nullptr because this
            # appears to kill std::cerr on Linux.
            out.write( f'        if ({arg.name}) std::cerr << " {arg.name}=\'" << {arg.name} << "\'";\n')
            out.write( f'        else std::cerr << " {arg.name}:null";\n')
        elif parse.is_( arg.cursor.type, 'va_list'):
            out.write( f'        std::cerr << " {arg.name}:va_list";\n')
        elif (0
                or parse.is_( arg.cursor.type, 'signed char')
                or parse.is_( arg.cursor.type, 'unsigned char')
                ):
            # Typically used for raw data, so not safe to treat as text.
            out.write( f'        std::cerr << " {arg.name}=" << ((int) {arg.name});\n')
        elif (0
                or parse.is_pointer_to(arg.cursor.type, 'signed char')
                or parse.is_pointer_to(arg.cursor.type, 'unsigned char')
                ):
            # Typically used for raw data, so not safe to treat as text.
            out.write( f'        std::cerr << " {arg.name}=" << ((void*) {arg.name});\n')
        elif arg.cursor.type.kind == state.clang.cindex.TypeKind.POINTER:
            # Don't assume non-const 'char*' is a zero-terminated string.
            out.write( f'        if ({varname_enable()}) std::cerr << " {arg.name}=" << (void*) {arg.name};\n')
        elif arg.cursor.type.kind == state.clang.cindex.TypeKind.LVALUEREFERENCE:
            out.write( f'        if ({varname_enable()}) std::cerr << " &{arg.name}=" << &{arg.name};\n')
        else:
            out.write( f'        std::cerr << " {arg.name}=" << {arg.name};\n')
    out.write( f'        std::cerr << "\\n";\n')
    out.write( f'    }}\n')
    out.write( f'    #endif\n')

    if uses_fz_context:
        out.write( f'    {refcheck_if}\n')
        out.write( f'        long stack0;\n')
        out.write( f'        if (s_check_error_stack)\n')
        out.write( f'        {{\n')
        out.write( f'            stack0 = auto_ctx->error.top - auto_ctx->error.stack_base;\n')
        out.write( f'        }}\n')
        out.write( f'    #endif\n')

    # Now output the function call.
    #
    if return_type != 'void':
        out.write(  f'    {return_type} ret;\n')

    if cursor.spelling == 'fz_warn':
        out.write( '    va_list ap;\n')
        out.write( '    fz_var(ap);\n')

    indent = ''
    if uses_fz_context and use_fz_try:
        out.write(      f'    fz_try(auto_ctx) {{\n')
        indent = '    '

    if cursor.spelling == 'fz_warn':
        out.write( f'    {indent}va_start(ap, fmt);\n')
        out.write( f'    {indent}fz_vwarn(auto_ctx, fmt, ap);\n')
    else:
        if not uses_fz_context:
            out.write( f'    /* No fz_context* arg, so no need for fz_try()/fz_catch() to convert MuPDF exceptions into C++ exceptions. */\n')
        out.write(  f'    {indent}')
        if return_type != 'void':
            out.write(  f'ret = ')
        out.write(  f'{fncall};\n')

    if uses_fz_context and use_fz_try:
        out.write(      f'    }}\n')

    if cursor.spelling == 'fz_warn':
        if use_fz_try:
            out.write(      f'    fz_always(auto_ctx) {{\n')
            out.write(      f'        va_end(ap);\n')
            out.write(      f'    }}\n')
        else:
            out.write(      f'    va_end(ap);\n')

    if uses_fz_context and use_fz_try:
        out.write(      f'    fz_catch(auto_ctx) {{\n')
        out.write(      f'        {trace_if}\n')
        out.write(      f'        if (s_trace_exceptions) {{\n')
        out.write(      f'            std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): fz_catch() has caught exception.\\n";\n')
        out.write(      f'        }}\n')
        out.write(      f'        #endif\n')
        out.write(      f'        {throw_exception}(auto_ctx);\n')
        out.write(      f'    }}\n')

    if uses_fz_context:
        out.write( f'    {refcheck_if}\n')
        out.write( f'        if (s_check_error_stack)\n')
        out.write( f'        {{\n')
        out.write( f'            long stack1 = auto_ctx->error.top - auto_ctx->error.stack_base;\n')
        out.write( f'            if (stack1 != stack0)\n')
        out.write( f'                std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): MuPDF error stack size changed by {cursor.spelling}(): " << stack0 << " -> " << stack1 << "\\n";\n')
        out.write( f'        }}\n')
        out.write( f'    #endif\n')

    if return_type != 'void':
        out.write(  f'    return ret;\n')


def to_pickle( obj, path):
    '''
    Pickles <obj> to file <path>.
    '''
    with open( path, 'wb') as f:
        pickle.dump( obj, f)

def from_pickle( path):
    '''
    Returns contents of file <path> unpickled.
    '''
    with open( path, 'rb') as f:
        return pickle.load( f)

class Generated:
    '''
    Stores information generated when we parse headers using clang.
    '''
    def __init__( self):
        self.h_files = []
        self.cpp_files = []
        self.fn_usage_filename = None
        self.container_classnames = []
        self.to_string_structnames = []
        self.fn_usage = dict()
        self.output_param_fns = []
        self.c_functions = []
        self.c_globals = []
        self.c_enums = []
        self.c_structs = []
        self.swig_cpp = io.StringIO()
        self.swig_cpp_python = io.StringIO()
        self.swig_python = io.StringIO()
        self.swig_python_exceptions = io.StringIO()
        self.swig_python_set_error_classes = io.StringIO()
        self.swig_csharp = io.StringIO()
        self.swig_csharp_exceptions = io.StringIO()
        self.virtual_fnptrs = []    # List of extra wrapper class names with virtual fnptrs.
        self.cppyy_extra = ''

    def save( self, dirpath):
        '''
        Saves state to .pickle file, to be loaded later via pickle.load().
        '''
        to_pickle( self, f'{dirpath}/generated.pickle')


def make_outparam_helper(
        tu,
        cursor,
        fnname,
        fnname_wrapper,
        generated,
        ):
    '''
    Create extra C++, Python and C# code to make tuple-returning wrapper of
    specified function.

    We write Python code to generated.swig_python and C++ code to
    generated.swig_cpp.
    '''
    verbose = False
    main_name = rename.ll_fn(cursor.spelling)
    generated.swig_cpp.write( '\n')

    # Write struct.
    generated.swig_cpp.write( 'namespace mupdf\n')
    generated.swig_cpp.write('{\n')
    generated.swig_cpp.write(f'    /* Out-params helper class for {cursor.spelling}(). */\n')
    generated.swig_cpp.write(f'    struct {main_name}_outparams\n')
    generated.swig_cpp.write(f'    {{\n')
    for arg in parse.get_args( tu, cursor):
        if not arg.out_param:
            continue
        decl = declaration_text( arg.cursor.type, arg.name, verbose=verbose)
        if verbose:
            jlib.log( '{decl=}')
        assert arg.cursor.type.kind == state.clang.cindex.TypeKind.POINTER

        # We use state.get_name_canonical() here because, for example, it
        # converts int64_t to 'long long', which seems to be handled better by
        # swig - swig maps int64_t to mupdf.SWIGTYPE_p_int64_t which can't be
        # treated or converted to an integer.
        #
        # We also value-initialise in case the underlying mupdf function also
        # reads the supplied value - i.e. treats it as an in-parm as well as an
        # out-param; this is particularly important for pointer out-params.
        #
        pointee = state.get_name_canonical( arg.cursor.type.get_pointee())
        generated.swig_cpp.write(f'        {declaration_text( pointee, arg.name)} = {{}};\n')
    generated.swig_cpp.write(f'    }};\n')
    generated.swig_cpp.write('\n')

    # Write function definition.
    name_args = f'{main_name}_outparams_fn('
    sep = ''
    for arg in parse.get_args( tu, cursor):
        if arg.out_param:
            continue
        name_args += sep
        name_args += declaration_text( arg.cursor.type, arg.name, verbose=verbose)
        sep = ', '
    name_args += f'{sep}{main_name}_outparams* outparams'
    name_args += ')'
    generated.swig_cpp.write(f'    /* Out-params function for {cursor.spelling}(). */\n')
    generated.swig_cpp.write(f'    {declaration_text( cursor.result_type, name_args)}\n')
    generated.swig_cpp.write( '    {\n')
    return_void = (cursor.result_type.spelling == 'void')
    generated.swig_cpp.write(f'        ')
    if not return_void:
        generated.swig_cpp.write(f'{declaration_text(cursor.result_type, "ret")} = ')
    generated.swig_cpp.write(f'{rename.ll_fn(cursor.spelling)}(')
    sep = ''
    for arg in parse.get_args( tu, cursor):
        generated.swig_cpp.write(sep)
        if arg.out_param:
            generated.swig_cpp.write(f'&outparams->{arg.name}')
        else:
            generated.swig_cpp.write(f'{arg.name}')
        sep = ', '
    generated.swig_cpp.write(');\n')
    if not return_void:
        generated.swig_cpp.write('        return ret;\n')
    generated.swig_cpp.write('    }\n')
    generated.swig_cpp.write('}\n')

    # Write Python wrapper.
    python.make_outparam_helper_python(tu, cursor, fnname, fnname_wrapper, generated, main_name)

    # Write C# wrapper.
    csharp.make_outparam_helper_csharp(tu, cursor, fnname, fnname_wrapper, generated, main_name)


def make_python_class_method_outparam_override(
        tu,
        cursor,
        fnname,
        generated,
        structname,
        classname,
        return_type,
        ):
    '''
    Writes Python code to `generated.swig_python` that monkey-patches Python
    function or method to make it call the underlying MuPDF function's Python
    wrapper, which will return out-params in a tuple.

    This is necessary because C++ doesn't support out-params so the C++ API
    supports wrapper class out-params by taking references to a dummy wrapper
    class instances, whose m_internal is then changed to point to the out-param
    struct (with suitable calls to keep/drop to manage the destruction of the
    dummy instance).

    In Python, we could create dummy wrapper class instances (e.g. passing
    nullptr to constructor) and return them, but instead we make our own call
    to the underlying MuPDF function and wrap the out-params into wrapper
    classes.
    '''
    out = generated.swig_python
    # Underlying fn.
    main_name = rename.ll_fn(cursor.spelling)

    if structname:
        name_new = f'{classname}_{rename.method(structname, cursor.spelling)}_outparams_fn'
    else:
        name_new = f'{rename.fn(cursor.spelling)}_outparams_fn'

    # Define an internal Python function that will become the class method.
    #
    out.write( f'def {name_new}(')
    if structname:
        out.write( ' self')
        comma = ', '
    else:
        comma = ''
    for arg in parse.get_args( tu, cursor):
        if arg.out_param:
            continue
        if structname and parse.is_pointer_to( arg.cursor.type, structname):
            continue
        out.write(f'{comma}{arg.name_python}')
        comma = ', '
    out.write('):\n')
    out.write( '    """\n')
    if structname:
        out.write(f'    Helper for out-params of class method {structname}::{main_name}() [{cursor.spelling}()].\n')
    else:
        out.write(f'    Class-aware helper for out-params of {fnname}() [{cursor.spelling}()].\n')
    out.write( '    """\n')

    # ret, a, b, ... = foo::bar(self.m_internal, p, q, r, ...)
    out.write(f'    ')
    sep = ''
    if cursor.result_type.spelling != 'void':
        out.write( 'ret')
        sep = ', '
    for arg in parse.get_args( tu, cursor):
        if not arg.out_param:
            continue
        out.write( f'{sep}{arg.name_python}')
        sep = ', '
    out.write( f' = {main_name}(')
    sep = ''
    if structname:
        out.write( f' self.m_internal')
        sep = ', '
    for arg in parse.get_args( tu, cursor):
        if arg.out_param:
            continue
        if structname and parse.is_pointer_to( arg.cursor.type, structname):
            continue
        out.write( sep)
        write_call_arg( tu, arg, classname, have_used_this=False, out_cpp=out, python=True)
        sep = ', '
    out.write( ')\n')

    # return ret, a, b.
    #
    # We convert returned items to wrapper classes if they are MuPDF types.
    #
    out.write( '    return ')
    sep = ''
    if cursor.result_type.spelling != 'void':
        if return_type:
            #out.write( f'{return_type}(ret)')
            # Return type is a class wrapper.
            return_ll_type = cursor.result_type
            do_keep = False
            if cursor.result_type.kind == state.clang.cindex.TypeKind.POINTER:
                return_ll_type = return_ll_type.get_pointee()
                if parse.has_refs( tu, return_ll_type):
                    return_ll_type = return_ll_type.spelling
                    return_ll_type = util.clip( return_ll_type, ('struct ', 'const '))
                    assert return_ll_type.startswith( ( 'fz_', 'pdf_'))
                    for prefix in ( 'fz_', 'pdf_'):
                        if return_ll_type.startswith( prefix):
                            break
                    else:
                        assert 0, f'Unexpected arg type: {return_ll_type}'
                    return_extra = classes.classextras.get( tu, return_ll_type)
                    if not function_name_implies_kept_references( fnname):
                        do_keep = True
                else:
                    if 'char' in return_ll_type.spelling:
                        jlib.log('### Function returns {cursor.result_type.spelling=} -> {return_ll_type.spelling=}: {fnname}. {function_name_implies_kept_references(fnname)=}')
            if do_keep:
                keepfn = f'{prefix}keep_{return_ll_type[ len(prefix):]}'
                keepfn = rename.ll_fn( keepfn)
                out.write( f'{return_type}( {keepfn}( ret))')
            else:
                out.write( f'{return_type}(ret)')
        else:
            out.write( 'ret')
        sep = ', '
    for arg in parse.get_args( tu, cursor):
        if not arg.out_param:
            continue
        if arg.alt:
            name = util.clip( arg.alt.type.spelling, ('struct ', 'const '))
            for prefix in ( 'fz_', 'pdf_'):
                if name.startswith( prefix):
                    break
            else:
                assert 0, f'Unexpected arg type: {name}'
            if function_name_implies_kept_references( fnname):
                out.write( f'{sep}{rename.class_(name)}( {arg.name_python})')
            else:
                keepfn = f'{prefix}keep_{name[ len(prefix):]}'
                keepfn = rename.ll_fn( keepfn)
                out.write( f'{sep}{rename.class_(name)}({keepfn}( {arg.name_python}))')
        else:
            out.write( f'{sep}{arg.name_python}')
        sep = ', '
    out.write('\n')
    out.write('\n')

    # foo.bar = foo_bar_outparams_fn
    if structname:
        out.write(f'{classname}.{rename.method(structname, cursor.spelling)} = {name_new}\n')
    else:
        out.write(f'{rename.fn( cursor.spelling)} = {name_new}\n')
    out.write('\n')
    out.write('\n')


def make_wrapper_comment(
        tu,
        cursor,
        fnname,
        fnname_wrapper,
        indent,
        is_method,
        is_low_level,
        ):
    ret = io.StringIO()
    def write(text):
        text = text.replace('\n', f'\n{indent}')
        ret.write( text)

    num_out_params = 0
    for arg in parse.get_args(
            tu,
            cursor,
            include_fz_context=False,
            skip_first_alt=is_method,
            ):
        if arg.out_param:
            num_out_params += 1

    if is_low_level:
        write( f'Low-level wrapper for `{rename.c_fn(cursor.spelling)}()`.')
    else:
        write( f'Class-aware wrapper for `{rename.c_fn(cursor.spelling)}()`.')
    if num_out_params:
        tuple_size = num_out_params
        if cursor.result_type.spelling != 'void':
            tuple_size += 1
        write( f'\n')
        write( f'\n')
        write( f'This {"method" if is_method else "function"} has out-params. Python/C# wrappers look like:\n')
        write( f'    `{fnname_wrapper}(')
        sep = ''
        for arg in parse.get_args( tu, cursor, include_fz_context=False, skip_first_alt=is_method):
            if arg.alt or not arg.out_param:
                write( f'{sep}{declaration_text( arg.cursor.type, arg.name)}')
                sep = ', '
        write(')` => ')
        if tuple_size > 1:
            write( '`(')
        sep = ''
        if cursor.result_type.spelling != 'void':
            write( f'{cursor.result_type.spelling}')
            sep = ', '
        for arg in parse.get_args( tu, cursor, include_fz_context=False, skip_first_alt=is_method):
            if not arg.alt and arg.out_param:
                write( f'{sep}{declaration_text( arg.cursor.type.get_pointee(), arg.name)}')
                sep = ', '
        if tuple_size > 1:
            write( ')`')
        write( f'\n')
    else:
        write( ' ')

    return ret.getvalue()


def function_wrapper(
        tu,
        cursor,
        fnname,
        fnname_wrapper,
        out_h,
        out_cpp,
        generated,
        refcheck_if,
        trace_if,
        ):
    '''
    Writes low-level C++ wrapper fn, converting any fz_try..fz_catch exception
    into a C++ exception.

    cursor:
        Clang cursor for function to wrap.
    fnname:
        Name of wrapped function.
    fnname_wrapper:
        Name of function to create.
    out_h:
        Stream to which we write header output.
    out_cpp:
        Stream to which we write cpp output.
    generated:
        A Generated instance.
    refcheck_if:
        A '#if*' statement that determines whether extra checks are compiled
        in.
    trace_if:
        A '#if*' statement that determines whether runtime diagnostics are
        compiled in.

    Example generated function:

        fz_band_writer * mupdf_new_band_writer_of_size(fz_context *ctx, size_t size, fz_output *out)
        {
            fz_band_writer * ret;
            fz_try(ctx) {
                ret = fz_new_band_writer_of_size(ctx, size, out);
            }
            fz_catch(ctx) {
                mupdf_throw_exception(ctx);
            }
            return ret;
        }
    '''
    assert cursor.kind == state.clang.cindex.CursorKind.FUNCTION_DECL
    if cursor.type.is_function_variadic() and fnname != 'fz_warn':
        jlib.log( 'Not writing low-level wrapper because variadic: {fnname=}', 1)
        return

    verbose = state.state_.show_details( fnname)
    if verbose:
        jlib.log( 'Wrapping {fnname}')
    num_out_params = 0
    for arg in parse.get_args( tu, cursor, include_fz_context=True):
        if parse.is_pointer_to(arg.cursor.type, 'fz_context'):
            continue
        if arg.out_param:
            num_out_params += 1

    # Write first line: <result_type> <fnname_wrapper> (<args>...)
    #
    comment = make_wrapper_comment( tu, cursor, fnname, fnname_wrapper, indent='', is_method=False, is_low_level=True)
    comment = f'/** {comment}*/\n'
    for out in out_h, out_cpp:
        out.write( comment)

    # Copy any comment into .h file before declaration.
    if cursor.raw_comment:
        # On Windows, carriage returns can appear in cursor.raw_comment on
        # due to line ending inconsistencies in our generated extra.cpp and
        # extra.h, and can cause spurious differences in our generated C++
        # code, which in turn causes unnecessary rebuilds.
        #
        # It would probably better to fix line endings in our generation of
        # extra.*.
        raw_comment = cursor.raw_comment.replace('\r', '')
        out_h.write(raw_comment)
        if not raw_comment.endswith( '\n'):
            out_h.write( '\n')

    # Write declaration and definition.
    name_args_h = f'{fnname_wrapper}('
    name_args_cpp = f'{fnname_wrapper}('
    comma = ''
    for arg in parse.get_args( tu, cursor, include_fz_context=True):
        if verbose:
            jlib.log( '{arg.cursor=} {arg.name=} {arg.separator=} {arg.alt=} {arg.out_param=}')
        if parse.is_pointer_to(arg.cursor.type, 'fz_context'):
            continue
        decl = declaration_text( arg.cursor.type, arg.name, verbose=verbose)
        if verbose:
            jlib.log( '{decl=}')
        name_args_h += f'{comma}{decl}'
        decl = declaration_text( arg.cursor.type, arg.name)
        name_args_cpp += f'{comma}{decl}'
        comma = ', '

    if cursor.type.is_function_variadic():
        name_args_h += f'{comma}...'
        name_args_cpp += f'{comma}...'

    name_args_h += ')'
    name_args_cpp += ')'
    declaration_h = declaration_text( cursor.result_type, name_args_h, verbose=verbose)
    declaration_cpp = declaration_text( cursor.result_type, name_args_cpp, verbose=verbose)
    out_h.write( f'FZ_FUNCTION {declaration_h};\n')
    out_h.write( '\n')

    # Write function definition.
    #
    out_cpp.write( f'FZ_FUNCTION {declaration_cpp}\n')
    out_cpp.write( '{\n')
    return_type = cursor.result_type.spelling
    fncall = ''
    fncall += f'{rename.c_fn(cursor.spelling)}('
    for arg in parse.get_args( tu, cursor, include_fz_context=True):
        if parse.is_pointer_to( arg.cursor.type, 'fz_context'):
            fncall += f'{arg.separator}auto_ctx'
        else:
            fncall += f'{arg.separator}{arg.name}'
    fncall += ')'
    make_fncall( tu, cursor, return_type, fncall, out_cpp, refcheck_if, trace_if)
    out_cpp.write( '}\n')
    out_cpp.write( '\n')

    if num_out_params:
        make_outparam_helper(
                tu,
                cursor,
                fnname,
                fnname_wrapper,
                generated,
                )


def make_namespace_open( namespace, out):
    if namespace:
        out.write( '\n')
        out.write( f'namespace {namespace}\n')
        out.write( '{\n')


def make_namespace_close( namespace, out):
    if namespace:
        out.write( '\n')
        out.write( f'}} /* End of namespace {namespace}. */\n')


# libclang can't always find headers so we define our own `std::string`
# and `std::vector<>` that work well enough for the generation of the
# C++ API.
#
# We also define extra raw functions to aid SWIG-generated code. These
# are implemented in C++, and should be excluded from the generated
# windows_def file later on, otherwise we get link errors on Windows.
#
g_extra_declarations = textwrap.dedent(f'''

        #ifdef MUPDF_WRAP_LIBCLANG

            namespace std
            {{
                template<typename T>
                struct vector
                {{
                }};

                struct string
                {{
                }};
            }}

        #else

            #include <string>
            #include <vector>

        #endif

        #include "mupdf/fitz.h"
        #include "mupdf/pdf.h"

        /**
        C++ alternative to `fz_lookup_metadata()` that returns a `std::string`
        or calls `fz_throw()` if not found.
        */
        FZ_FUNCTION std::string fz_lookup_metadata2(fz_context* ctx, fz_document* doc, const char* key);

        /**
        C++ alternative to `pdf_lookup_metadata()` that returns a `std::string`
        or calls `fz_throw()` if not found.
        */
        FZ_FUNCTION std::string pdf_lookup_metadata2(fz_context* ctx, pdf_document* doc, const char* key);

        /**
        C++ alternative to `fz_md5_pixmap()` that returns the digest by value.
        */
        FZ_FUNCTION std::vector<unsigned char> fz_md5_pixmap2(fz_context* ctx, fz_pixmap* pixmap);

        /**
        C++ alternative to fz_md5_final() that returns the digest by value.
        */
        FZ_FUNCTION std::vector<unsigned char> fz_md5_final2(fz_md5* md5);

        /** */
        FZ_FUNCTION long long fz_pixmap_samples_int(fz_context* ctx, fz_pixmap* pixmap);

        /**
        Provides simple (but slow) access to pixmap data from Python and C#.
        */
        FZ_FUNCTION int fz_samples_get(fz_pixmap* pixmap, int offset);

        /**
        Provides simple (but slow) write access to pixmap data from Python and
        C#.
        */
        FZ_FUNCTION void fz_samples_set(fz_pixmap* pixmap, int offset, int value);

        /**
        C++ alternative to fz_highlight_selection() that returns quads in a
        std::vector.
        */
        FZ_FUNCTION std::vector<fz_quad> fz_highlight_selection2(fz_context* ctx, fz_stext_page* page, fz_point a, fz_point b, int max_quads);

        struct fz_search_page2_hit
        {{
            fz_quad quad;
            int mark;
        }};

        /**
        C++ alternative to fz_search_page() that returns information in a std::vector.
        */
        FZ_FUNCTION std::vector<fz_search_page2_hit> fz_search_page2(fz_context* ctx, fz_document* doc, int number, const char* needle, int hit_max);

        /**
        C++ alternative to fz_string_from_text_language() that returns information in a std::string.
        */
        FZ_FUNCTION std::string fz_string_from_text_language2(fz_text_language lang);

        /**
        C++ alternative to fz_get_glyph_name() that returns information in a std::string.
        */
        FZ_FUNCTION std::string fz_get_glyph_name2(fz_context* ctx, fz_font* font, int glyph);

        /**
        Extra struct containing fz_install_load_system_font_funcs()'s args,
        which we wrap with virtual_fnptrs set to allow use from Python/C# via
        Swig Directors.
        */
        typedef struct fz_install_load_system_font_funcs_args
        {{
            fz_load_system_font_fn* f;
            fz_load_system_cjk_font_fn* f_cjk;
            fz_load_system_fallback_font_fn* f_fallback;
        }} fz_install_load_system_font_funcs_args;

        /**
        Alternative to fz_install_load_system_font_funcs() that takes args in a
        struct, to allow use from Python/C# via Swig Directors.
        */
        FZ_FUNCTION void fz_install_load_system_font_funcs2(fz_context* ctx, fz_install_load_system_font_funcs_args* args);

        /** Internal singleton state to allow Swig Director class to find
        fz_install_load_system_font_funcs_args class wrapper instance. */
        FZ_DATA extern void* fz_install_load_system_font_funcs2_state;

        /** Helper for calling `fz_document_handler::open` function pointer via
        Swig from Python/C#. */
        FZ_FUNCTION fz_document* fz_document_handler_open(fz_context* ctx, const fz_document_handler *handler, fz_stream* stream, fz_stream* accel, fz_archive* dir, void* recognize_state);

        /** Helper for calling a `fz_document_handler::recognize` function
        pointer via Swig from Python/C#. */
        FZ_FUNCTION int fz_document_handler_recognize(fz_context* ctx, const fz_document_handler *handler, const char *magic);

        /** Swig-friendly wrapper for pdf_choice_widget_options(), returns the
        options directly in a vector. */
        FZ_FUNCTION std::vector<std::string> pdf_choice_widget_options2(fz_context* ctx, pdf_annot* tw, int exportval);

        /** Swig-friendly wrapper for fz_new_image_from_compressed_buffer(),
        uses specified `decode` and `colorkey` if they are not null (in which
        case we assert that they have size `2*fz_colorspace_n(colorspace)`). */
        FZ_FUNCTION fz_image* fz_new_image_from_compressed_buffer2(
                fz_context* ctx,
                int w,
                int h,
                int bpc,
                fz_colorspace* colorspace,
                int xres,
                int yres,
                int interpolate,
                int imagemask,
                const std::vector<float>& decode,
                const std::vector<int>& colorkey,
                fz_compressed_buffer* buffer,
                fz_image* mask
                );

        /** Swig-friendly wrapper for pdf_rearrange_pages(). */
        void pdf_rearrange_pages2(
                fz_context* ctx,
                pdf_document* doc,
                const std::vector<int>& pages,
                pdf_clean_options_structure structure
                );

        /** Swig-friendly wrapper for pdf_subset_fonts(). */
        void pdf_subset_fonts2(fz_context *ctx, pdf_document *doc, const std::vector<int>& pages);

        /** Swig-friendly and typesafe way to do fz_snprintf(fmt, value). `fmt`
        must end with one of 'efg' otherwise we throw an exception. */
        std::string fz_format_double(fz_context* ctx, const char* fmt, double value);

        struct fz_font_ucs_gid
        {{
            unsigned long ucs;
            unsigned int gid;
        }};

        /** SWIG-friendly wrapper for fz_enumerate_font_cmap(). */
        std::vector<fz_font_ucs_gid> fz_enumerate_font_cmap2(fz_context* ctx, fz_font* font);

        /** SWIG-friendly wrapper for pdf_set_annot_callout_line(). */
        void pdf_set_annot_callout_line2(fz_context *ctx, pdf_annot *annot, std::vector<fz_point>& callout);

        /** SWIG-friendly wrapper for fz_decode_barcode_from_display_list(),
        avoiding leak of the returned string. */
        std::string fz_decode_barcode_from_display_list2(fz_context *ctx, fz_barcode_type *type, fz_display_list *list, fz_rect subarea, int rotate);

        /** SWIG-friendly wrapper for fz_decode_barcode_from_pixmap(), avoiding
        leak of the returned string. */
        std::string fz_decode_barcode_from_pixmap2(fz_context *ctx, fz_barcode_type *type, fz_pixmap *pix, int rotate);

        /** SWIG-friendly wrapper for fz_decode_barcode_from_page(), avoiding
        leak of the returned string. */
        std::string fz_decode_barcode_from_page2(fz_context *ctx, fz_barcode_type *type, fz_page *page, fz_rect subarea, int rotate);
        ''')

g_extra_definitions = textwrap.dedent(f'''

        FZ_FUNCTION std::string fz_lookup_metadata2( fz_context* ctx, fz_document* doc, const char* key)
        {{
            /* Find length first. */
            int e = fz_lookup_metadata(ctx, doc, key, NULL /*buf*/, 0 /*size*/);
            if (e < 0)
            {{
                fz_throw(ctx, FZ_ERROR_GENERIC, "key not found: %s", key);
            }}
            assert(e != 0);
            char* buf = (char*) fz_malloc(ctx, e);
            int e2 = fz_lookup_metadata(ctx, doc, key, buf, e);
            assert(e2 == e);
            std::string ret = buf;
            free(buf);
            return ret;
        }}

        FZ_FUNCTION std::string pdf_lookup_metadata2( fz_context* ctx, pdf_document* doc, const char* key)
        {{
            /* Find length first. */
            int e = pdf_lookup_metadata(ctx, doc, key, NULL /*buf*/, 0 /*size*/);
            if (e < 0)
            {{
                fz_throw(ctx, FZ_ERROR_GENERIC, "key not found: %s", key);
            }}
            assert(e != 0);
            char* buf = (char*) fz_malloc(ctx, e);
            int e2 = pdf_lookup_metadata(ctx, doc, key, buf, e);
            assert(e2 == e);
            std::string ret = buf;
            free(buf);
            return ret;
        }}

        FZ_FUNCTION std::vector<unsigned char> fz_md5_pixmap2(fz_context* ctx, fz_pixmap* pixmap)
        {{
            std::vector<unsigned char>  ret(16);
            fz_md5_pixmap( ctx, pixmap, &ret[0]);
            return ret;
        }}

        FZ_FUNCTION long long fz_pixmap_samples_int(fz_context* ctx, fz_pixmap* pixmap)
        {{
            long long ret = (intptr_t) pixmap->samples;
            return ret;
        }}

        FZ_FUNCTION int fz_samples_get(fz_pixmap* pixmap, int offset)
        {{
            return pixmap->samples[offset];
        }}

        FZ_FUNCTION void fz_samples_set(fz_pixmap* pixmap, int offset, int value)
        {{
            pixmap->samples[offset] = value;
        }}

        FZ_FUNCTION std::vector<unsigned char> fz_md5_final2(fz_md5* md5)
        {{
            std::vector<unsigned char>  ret(16);
            fz_md5_final( md5, &ret[0]);
            return ret;
        }}

        FZ_FUNCTION std::vector<fz_quad> fz_highlight_selection2(fz_context* ctx, fz_stext_page* page, fz_point a, fz_point b, int max_quads)
        {{
            {{
                std::vector<fz_quad>    ret(max_quads);
                int n;
                fz_try(ctx)
                {{
                    n = fz_highlight_selection(ctx, page, a, b, &ret[0], max_quads);
                }}
                fz_catch(ctx)
                {{
                    n = -1;
                }}
                if (n >= 0)
                {{
                    ret.resize(n);
                    return ret;
                }}
            }}
            /* We are careful to only call `fz_throw()` after `ret`'s
            destructor has been called. */
            fz_throw(ctx, FZ_ERROR_GENERIC, "fz_highlight_selection() failed");
        }}

        FZ_FUNCTION std::vector<fz_search_page2_hit> fz_search_page2(fz_context* ctx, fz_document* doc, int number, const char* needle, int hit_max)
        {{
            std::vector<fz_quad>    quads(hit_max);
            std::vector<int>        marks(hit_max);
            int n = fz_search_page_number(ctx, doc, number, needle, &marks[0], &quads[0], hit_max);
            std::vector<fz_search_page2_hit>    ret(n);
            for (int i=0; i<n; ++i)
            {{
                ret[i].quad = quads[i];
                ret[i].mark = marks[i];
            }}
            return ret;
        }}

        FZ_FUNCTION std::string fz_string_from_text_language2(fz_text_language lang)
        {{
            char    str[8];
            fz_string_from_text_language(str, lang);
            return std::string(str);
        }}

        FZ_FUNCTION std::string fz_get_glyph_name2(fz_context* ctx, fz_font* font, int glyph)
        {{
            char name[32];
            fz_get_glyph_name(ctx, font, glyph, name, sizeof(name));
            return std::string(name);
        }}

        void fz_install_load_system_font_funcs2(fz_context* ctx, fz_install_load_system_font_funcs_args* args)
        {{
            fz_install_load_system_font_funcs(ctx, args->f, args->f_cjk, args->f_fallback);
        }}

        void* fz_install_load_system_font_funcs2_state = nullptr;

        FZ_FUNCTION fz_document* fz_document_handler_open(fz_context* ctx, const fz_document_handler *handler, fz_stream* stream, fz_stream* accel, fz_archive* dir, void* recognize_state)
        {{
            return handler->open(ctx, handler, stream, accel, dir, recognize_state);
        }}

        FZ_FUNCTION int fz_document_handler_recognize(fz_context* ctx, const fz_document_handler *handler, const char *magic)
        {{
            return handler->recognize(ctx, handler, magic);
        }}

        FZ_FUNCTION std::vector<std::string> pdf_choice_widget_options2(fz_context* ctx, pdf_annot* tw, int exportval)
        {{
            int n = pdf_choice_widget_options(ctx, tw, exportval, nullptr);
            std::vector<const char*> opts(n);
            int n2 = pdf_choice_widget_options(ctx, tw, exportval, &opts[0]);
            assert(n2 == n);
            std::vector<std::string> ret(n);
            for (int i=0; i<n; ++i)
            {{
                ret[i] = opts[i];
            }}
            return ret;
        }}

        FZ_FUNCTION fz_image* fz_new_image_from_compressed_buffer2(
                fz_context* ctx,
                int w,
                int h,
                int bpc,
                fz_colorspace* colorspace,
                int xres,
                int yres,
                int interpolate,
                int imagemask,
                const std::vector<float>& decode,
                const std::vector<int>& colorkey,
                fz_compressed_buffer* buffer,
                fz_image* mask
                )
        {{
            int n = fz_colorspace_n(ctx, colorspace);
            assert(decode.empty() || decode.size() == 2 * n);
            assert(colorkey.empty() || colorkey.size() == 2 * n);
            const float* decode2 = decode.empty() ? nullptr : &decode[0];
            const int* colorkey2 = colorkey.empty() ? nullptr : &colorkey[0];
            fz_image* ret = fz_new_image_from_compressed_buffer(
                    ctx,
                    w,
                    h,
                    bpc,
                    colorspace,
                    xres,
                    yres,
                    interpolate,
                    imagemask,
                    decode2,
                    colorkey2,
                    fz_keep_compressed_buffer(ctx, buffer),
                    mask
                    );
            return ret;
        }}

        void pdf_rearrange_pages2(
                fz_context* ctx,
                pdf_document* doc,
                const std::vector<int>& pages,
                pdf_clean_options_structure structure
                )
        {{
            return pdf_rearrange_pages(ctx, doc, pages.size(), &pages[0], structure);
        }}

        void pdf_subset_fonts2(fz_context *ctx, pdf_document *doc, const std::vector<int>& pages)
        {{
            return pdf_subset_fonts(ctx, doc, pages.size(), &pages[0]);
        }}

        static void s_format_check(fz_context* ctx, const char* fmt, const char* specifiers)
        {{
            int length = strlen(fmt);
            if (!length || !strchr(specifiers, fmt[length-1]))
            {{
                fz_throw(ctx, FZ_ERROR_ARGUMENT, "Incorrect fmt '%s' should end with one of '%s'.", fmt, specifiers);
            }}
        }}

        std::string fz_format_double(fz_context* ctx, const char* fmt, double value)
        {{
            char buffer[256];
            s_format_check(ctx, fmt, "efg");
            fz_snprintf(buffer, sizeof(buffer), fmt, value);
            return buffer;
        }}

        static void fz_enumerate_font_cmap2_cb(fz_context* ctx, void* opaque, unsigned long ucs, unsigned int gid)
        {{
            std::vector<fz_font_ucs_gid>& ret = *(std::vector<fz_font_ucs_gid>*) opaque;
            fz_font_ucs_gid item = {{ucs, gid}};
            ret.push_back(item);
        }}

        std::vector<fz_font_ucs_gid> fz_enumerate_font_cmap2(fz_context* ctx, fz_font* font)
        {{
            std::vector<fz_font_ucs_gid> ret;
            fz_enumerate_font_cmap(ctx, font, fz_enumerate_font_cmap2_cb, &ret);
            return ret;
        }}

        void pdf_set_annot_callout_line2(fz_context *ctx, pdf_annot *annot, std::vector<fz_point>& callout)
        {{
            pdf_set_annot_callout_line(ctx, annot, &callout[0], callout.size());
        }}

        std::string fz_decode_barcode_from_display_list2(fz_context *ctx, fz_barcode_type *type, fz_display_list *list, fz_rect subarea, int rotate)
        {{
            char* ret = fz_decode_barcode_from_display_list(ctx, type, list, subarea, rotate);
            std::string ret2 = ret;
            fz_free(ctx, ret);
            return ret2;
        }}

        std::string fz_decode_barcode_from_pixmap2(fz_context *ctx, fz_barcode_type *type, fz_pixmap *pix, int rotate)
        {{
            char* ret = fz_decode_barcode_from_pixmap(ctx, type, pix, rotate);
            std::string ret2 = ret;
            fz_free(ctx, ret);
            return ret2;
        }}

        std::string fz_decode_barcode_from_page2(fz_context *ctx, fz_barcode_type *type, fz_page *page, fz_rect subarea, int rotate)
        {{
            char* ret = fz_decode_barcode_from_page(ctx, type, page, subarea, rotate);
            std::string ret2 = ret;
            fz_free(ctx, ret);
            return ret2;
        }}
        ''')

def make_extra( out_extra_h, out_extra_cpp):
    '''
    We write extra abstractions here.

    These are written in C++ but are at the same level of abstraction as MuPDF
    C functions, for example they take `fz_context` args. This is done so that
    we automatically generate wrappers as class methods as well as global
    functions.
    '''
    out_extra_h.write( g_extra_declarations)

    out_extra_cpp.write( textwrap.dedent('''
            #include "mupdf/extra.h"

            '''))
    out_extra_cpp.write( g_extra_definitions)


def make_internal_functions( namespace, out_h, out_cpp, refcheck_if, trace_if):
    '''
    Writes internal support functions.

    out_h:
        Stream to which we write C++ header text.
    out_cpp:
        Stream to which we write C++ text.
    '''
    out_h.write(
            textwrap.dedent(
            f'''
            #define internal_assert(expression) (expression) ? (void) 0 : internal_assert_fail(__FILE__, __LINE__, __FUNCTION__, #expression)
            FZ_FUNCTION void internal_assert_fail(const char* file, int line, const char* fn, const char* expression);

            /** Internal use only. Looks at environmental variable <name>; returns 0 if unset else int value. */
            FZ_FUNCTION int {rename.internal('env_flag')}(const char* name);

            /** Internal use only. Looks at environmental variable <name>; returns 0 if unset else int value. */
            FZ_FUNCTION int {rename.internal('env_flag_check_unset')}( const char* if_, const char* name);

            /** Internal use only. Returns `fz_context*` for use by current thread. */
            FZ_FUNCTION fz_context* {rename.internal('context_get')}();

            /* Internal, do not call directly. */
            FZ_FUNCTION void {rename.internal('check_ndebug0')}(bool caller_ndebug_defined);

            /** Checks current NDEBUG is same as NDEBUG used when C++ bindings
            were built. If not, shows message on cerr and calls abort().

            Mixing NDEBUG and non-NDEBUG code is not supported by the C++
            bindings.
            */
            static inline void {rename.internal('check_ndebug')}()
            {{
                #ifdef NDEBUG
                    {rename.internal('check_ndebug0')}(true);
                #else
                    {rename.internal('check_ndebug0')}(false);
                #endif
            }}
            '''
            ))

    out_cpp.write(
            textwrap.dedent(
            '''
            #include "mupdf/exceptions.h"
            #include "mupdf/internal.h"

            #include <iostream>
            #include <thread>
            #include <mutex>

            #include <string.h>

            '''))

    make_namespace_open( namespace, out_cpp)

    state_t = rename.internal( 'state')
    thread_state_t = rename.internal( 'thread_state')

    cpp_text = textwrap.dedent(
            f'''
            FZ_FUNCTION void {rename.internal('check_ndebug0')}(bool caller_ndebug_defined)
            {{
                #ifdef NDEBUG
                    bool library_ndebug_defined = true;
                #else
                    bool library_ndebug_defined = false;
                #endif
                if (caller_ndebug_defined != library_ndebug_defined)
                {{
                    std::cerr << "*** MuPDF C++ build/configuration failure.\\n";
                    if (library_ndebug_defined)
                    {{
                        std::cerr << "*** Library built with NDEBUG but caller built without NDEBUG.\\n";
                    }}
                    else
                    {{
                        std::cerr << "*** Library built without NDEBUG but caller built with NDEBUG.\\n";
                    }}
                    std::cerr << "*** This is not supported.\\n";
                    std::cerr << "*** Calling abort().\\n";
                    std::cerr << std::flush;
                    abort();
                }}
            }}

            FZ_FUNCTION void internal_assert_fail(const char* file, int line, const char* fn, const char* expression)
            {{
                std::cerr << file << ":" << line << ":" << fn << "(): "
                        << "MuPDF C++ internal assert failure: " << expression
                        << "\\n" << std::flush;
                abort();
            }}

            FZ_FUNCTION int {rename.internal('env_flag')}(const char* name)
            {{
                const char* s = getenv( name);
                if (!s) return 0;
                return atoi( s);
            }}

            FZ_FUNCTION int {rename.internal('env_flag_check_unset')}(const char* if_, const char* name)
            {{
                const char* s = getenv( name);
                if (s) std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "():"
                        << " Warning: ignoring environmental variable because"
                        << " '" << if_ << "' is false: " << name << "\\n";
                return false;
            }}

            {trace_if}
                static const int    s_trace = mupdf::internal_env_flag("MUPDF_trace");
            #else
                static const int    s_trace = mupdf::internal_env_flag_check_unset("{trace_if}", "MUPDF_trace");
            #endif

            static bool s_state_valid = false;

            struct {rename.internal("state")}
            {{
                /* Constructor. */
                {rename.internal("state")}()
                {{
                    m_locks.user = this;
                    m_locks.lock = lock;
                    m_locks.unlock = unlock;
                    m_ctx = nullptr;
                    bool multithreaded = true;
                    const char* s = getenv( "MUPDF_mt_ctx");
                    if ( s && !strcmp( s, "0")) multithreaded = false;
                    reinit( multithreaded);
                    s_state_valid = true;
                }}

                void reinit( bool multithreaded)
                {{
                    if (s_trace)
                    {{
                        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): "
                                << " calling fz_drop_context()\\n";
                    }}
                    fz_drop_context( m_ctx);
                    m_multithreaded = multithreaded;
                    if (s_trace)
                    {{
                        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): "
                                << " calling fz_new_context()\\n";
                    }}
                    m_ctx = fz_new_context(NULL /*alloc*/, (multithreaded) ? &m_locks : nullptr, FZ_STORE_DEFAULT);
                    if (s_trace)
                    {{
                        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): "
                                << "fz_new_context() => " << m_ctx << "\\n";
                    }}
                    if (s_trace)
                    {{
                        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): "
                                << " calling fz_register_document_handlers()\\n";
                    }}
                    internal_assert("m_ctx = fz_new_context()" && m_ctx);
                    fz_register_document_handlers(m_ctx);
                }}
                static void lock(void *user, int lock)
                {{
                    {rename.internal("state")}*    self = ({rename.internal("state")}*) user;
                    internal_assert( self->m_multithreaded);
                    self->m_mutexes[lock].lock();
                }}
                static void unlock(void *user, int lock)
                {{
                    {rename.internal("state")}*    self = ({rename.internal("state")}*) user;
                    internal_assert( self->m_multithreaded);
                    self->m_mutexes[lock].unlock();
                }}
                ~{rename.internal("state")}()
                {{
                    if (s_trace)
                    {{
                        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): "
                                << " calling fz_drop_context()\\n";
                    }}
                    fz_drop_context(m_ctx);
                    m_ctx = nullptr;
                    s_state_valid = false;
                }}

                bool                m_multithreaded;
                fz_context*         m_ctx;
                std::mutex          m_mutex;    /* Serialise access to m_ctx. fixme: not actually necessary. */

                /* Provide thread support to mupdf. */
                std::mutex          m_mutexes[FZ_LOCK_MAX];
                fz_locks_context    m_locks;
            }};

            static {rename.internal("state")}  s_state;

            struct {rename.internal("thread_state")}
            {{
                {rename.internal("thread_state")}()
                :
                m_ctx( nullptr),
                m_constructed( true)
                {{}}
                fz_context* get_context()
                {{
                    internal_assert( s_state.m_multithreaded);

                    /* The following code checks that we are not being called after
                    we have been destructed. This can happen if global mupdf
                    wrapper class instances are defined - thread-local objects
                    are destructed /before/ globals. */
                    if (!m_constructed)
                    {{
                        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << ":\\n"
                                << "*** Error - undefined behaviour.\\n"
                                << "***\\n"
                                << "*** Attempt to get thread-local fz_context after destruction\\n"
                                << "*** of thread-local fz_context support instance.\\n"
                                << "***\\n"
                                << "*** This is undefined behaviour.\\n"
                                << "***\\n"
                                << "*** This can happen if mupdf wrapper class instances are\\n"
                                << "*** created as globals, because in C++ global object\\n"
                                << "*** destructors are run after thread_local destructors.\\n"
                                << "***\\n"
                                ;
                    }}
                    internal_assert( m_constructed);
                    if (!m_ctx)
                    {{
                        /* Make a context for this thread by cloning the global
                        context. */
                        /* fixme: we don't actually need to take a lock here. */
                        std::lock_guard<std::mutex> lock( s_state.m_mutex);
                        if (s_trace)
                        {{
                            std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): "
                                    << " calling fz_clone_context()\\n";
                        }}
                        internal_assert(s_state_valid);
                        m_ctx = fz_clone_context(s_state.m_ctx);
                        if (s_trace)
                        {{
                            std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): "
                                    << "fz_clone_context(" << s_state.m_ctx << ") => " << m_ctx << "\\n";
                        }}
                        internal_assert("m_ctx = fz_clone_context()" && m_ctx);
                    }}
                    return m_ctx;
                }}
                ~{rename.internal("thread_state")}()
                {{
                    if (m_ctx)
                    {{
                        internal_assert( s_state.m_multithreaded);
                        if (s_trace)
                        {{
                            std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): "
                                    << " calling fz_drop_context()\\n";
                        }}
                        fz_drop_context( m_ctx);
                    }}

                    /* These two statements are an attempt to get useful
                    diagnostics in cases of undefined behaviour caused by the
                    use of global wrapper class instances, whose destructors
                    will be called /after/ destruction of this thread-local
                    internal_thread_state instance. See check of m_constructed in
                    get_context().

                    This probably only works in non-optimised builds -
                    optimisation will simply elide both these statements. */
                    m_ctx = nullptr;
                    m_constructed = false;
                }}
                fz_context* m_ctx;
                bool m_constructed;
            }};

            static thread_local {rename.internal("thread_state")}  s_thread_state;

            FZ_FUNCTION fz_context* {rename.internal("context_get")}()
            {{
                if (s_state.m_multithreaded)
                {{
                    return s_thread_state.get_context();
                }}
                else
                {{
                    /* This gives a small improvement in performance for
                    single-threaded use, e.g. from 552.4s to 548.1s. */
                    internal_assert(s_state_valid);
                    fz_context* ret = s_state.m_ctx;
                    internal_assert(ret);
                    return ret;
                }}
            }}

            FZ_FUNCTION void reinit_singlethreaded()
            {{
                if (0)
                {{
                    std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): Reinitialising as single-threaded.\\n";
                }}
                s_state.reinit( false /*multithreaded*/);
            }}
            ''')
    out_cpp.write( cpp_text)

    make_namespace_close( namespace, out_cpp)

    # Generate code that exposes C++ operator new/delete to Memento.
    #
    # Disabled because our generated code makes very few direct calls
    # to operator new, and Memento ends up catching lots of (presumably
    # false-positive) leaks in the Python interpreter, so isn't very useful.
    #
    if 0:
        out_cpp.write( textwrap.dedent(
                '''
                #ifdef MEMENTO

                void* operator new( size_t size)
                {
                    return Memento_cpp_new( size);
                }

                void  operator delete( void* pointer)
                {
                    Memento_cpp_delete( pointer);
                }

                void* operator new[]( size_t size)
                {
                    return Memento_cpp_new_array( size);
                }

                void  operator delete[]( void* pointer)
                {
                    Memento_cpp_delete_array( pointer);
                }

                #endif
                '''
                ))


def make_function_wrappers(
        tu,
        namespace,
        out_exceptions_h,
        out_exceptions_cpp,
        out_functions_h,
        out_functions_cpp,
        out_internal_h,
        out_internal_cpp,
        out_functions_h2,
        out_functions_cpp2,
        generated,
        refcheck_if,
        trace_if,
        ):
    '''
    Generates C++ source code containing wrappers for all fz_*() functions.

    We also create a function throw_exception(fz_context* ctx) that throws a
    C++ exception appropriate for the error in ctx.

    If a function has first arg fz_context*, extra code is generated that
    converts fz_try..fz_catch exceptions into C++ exceptions by calling
    throw_exception().

    We remove any fz_context* argument and the implementation calls
    internal_get_context() to get a suitable thread-specific fz_context* to
    use.

    We generate a class for each exception type.

    Returned source is just the raw functions text, e.g. it does not contain
    required #include's.

    Args:
        tu:
            Clang translation unit.
        out_exceptions_h:
            Stream to which we write exception class definitions.
        out_exceptions_cpp:
            Stream to which we write exception class implementation.
        out_functions_h:
            Stream to which we write function declarations.
        out_functions_cpp:
            Stream to which we write function definitions.
        generated:
            A Generated instance.
    '''
    # Look for FZ_ERROR_* enums. We generate an exception class for each of
    # these.
    #
    error_name_prefix = 'FZ_ERROR_'
    fz_error_names = []
    fz_error_names_maxlen = 0   # Used for padding so generated code aligns.

    for cursor in parse.get_children(tu.cursor):
        if cursor.kind == state.clang.cindex.CursorKind.ENUM_DECL:
            #log( 'enum: {cursor.spelling=})
            for child in parse.get_members( cursor):
                #log( 'child:{ child.spelling=})
                if child.spelling.startswith( error_name_prefix):
                    name = child.spelling[ len(error_name_prefix):]
                    fz_error_names.append( name)
                    if len( name) > fz_error_names_maxlen:
                        fz_error_names_maxlen = len( name)

    def errors(include_error_base=False):
        '''
        Yields (enum, typename, padding) for each error.
        E.g.:
            enum=FZ_ERROR_SYSTEM
            typename=mupdf_error_memory
            padding='  '
        '''
        names = fz_error_names
        if include_error_base:
            names = ['BASE'] + names
        for name in names:
            enum = f'{error_name_prefix}{name}'
            typename = rename.error_class( enum)
            padding = (fz_error_names_maxlen - len(name)) * ' '
            yield enum, typename, padding

    # Declare base exception class and define its methods.
    #
    base_name = rename.error_class('FZ_ERROR_BASE')

    out_exceptions_h.write( textwrap.dedent(
            f'''
            /** Base class for exceptions. */
            struct {base_name} : std::exception
            {{
                int         m_code;
                std::string m_text;
                mutable std::string m_what;
                FZ_FUNCTION const char* what() const throw();
                FZ_FUNCTION {base_name}(int code, const char* text);
            }};
            '''))

    out_exceptions_cpp.write( textwrap.dedent(
            f'''
            FZ_FUNCTION {base_name}::{base_name}(int code, const char* text)
            :
            m_code(code),
            m_text(text)
            {{
                {trace_if}
                if (s_trace_exceptions)
                {{
                    std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): {base_name}: " << m_text << "\\n";
                }}
                #endif
            }};

            FZ_FUNCTION const char* {base_name}::what() const throw()
            {{
                m_what = "code=" + std::to_string(m_code) + ": " + m_text;
                return m_what.c_str();
            }};

            '''))

    # Generate SWIG Python code to allow conversion of our error class
    # exceptions into equivalent Python exceptions.
    error_classes_n = 0
    for enum, typename, padding in errors():
        error_classes_n += 1

    error_classes_n += 1    # Extra space for FzErrorBase.
    generated.swig_python_exceptions.write( textwrap.dedent( f'''

            void internal_set_error_classes(PyObject* classes);

            %{{
            /* A Python list of Error classes, [FzErrorNone, FzErrorMemory, FzErrorGeneric, ...]. */
            static PyObject* s_error_classes[{error_classes_n}] = {{}};

            /* Called on startup by mupdf.py, with a list of error classes
            to be copied into s_error_classes. This will allow us to create
            instances of these error classes in SWIG's `%exception ...`, so
            Python code will see exceptions as instances of Python error
            classes. */
            void internal_set_error_classes(PyObject* classes)
            {{
                assert(PyList_Check(classes));
                int n = PyList_Size(classes);
                assert(n == {error_classes_n});
                for (int i=0; i<n; ++i)
                {{
                    PyObject* class_ = PyList_GetItem(classes, i);
                    s_error_classes[i] = class_;
                }}
            }}

            /* Sets Python exception to a new mupdf.<name> object constructed
            with `text`. */
            void set_exception(PyObject* class_, int code, const std::string& text)
            {{
                PyObject* args = Py_BuildValue("(s)", text.c_str());
                PyObject* instance = PyObject_CallObject(class_, args);
                PyErr_SetObject(class_, instance);
                Py_XDECREF(instance);
                Py_XDECREF(args);
            }}

            /* Exception handler for swig-generated code. Uses internal
            `throw;` to recover the current C++ exception then uses
            `set_exception()` to set the current Python exception. Caller
            should do `SWIG_fail;` after we return. */
            void handle_exception()
            {{
                try
                {{
                    throw;
                }}
            '''
            ))

    generated.swig_csharp_exceptions.write(textwrap.dedent(f'''
            /*
            On Windows, exceptions are automatically converted into
            System.Runtime.InteropServices.SEHException instances but the exception
            message is not used.

            On Mono this doesn't seem to happen and std::terminate() is called.

            So we use swig's `%exception {...}` to convert exceptions here.

            Unlike in the Python bindings, we do not (yet) attempt to convert
            the different MuPDF C++ exception types into the equivalent C#
            types. Instead we always create a SWIG_CSharpApplicationException
            with the C++ exception's `.what()` string.
            */
            %exception
            {{
                try
                {{
                    $action
                }}
                catch (std::exception& e)
                {{
                    //std::cout << "%exception: Received exception: " << e.what() << "\\n" << std::flush;
                    SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
                    //std::cout << "%exception: after SWIG_CSharpSetPendingException.\\n" << std::flush;
                }}
            }}
            '''))

    # Declare exception class for each FZ_ERROR_*. Also append catch blocks for
    # each of these exception classes to `handle_exception()`.
    #
    for i, (enum, typename, padding) in enumerate(errors()):
        out_exceptions_h.write( textwrap.dedent(
                f'''
                /** For `{enum}`. */
                struct {typename} : {base_name}
                {{
                    FZ_FUNCTION {typename}(const char* message);
                }};

                '''))

        generated.swig_python_exceptions.write( textwrap.dedent( f'''
                /**/
                    catch (mupdf::{typename}& e)
                    {{
                        if (g_mupdf_trace_exceptions)
                        {{
                            std::cerr
                                    << __FILE__ << ':' << __LINE__ << ':'
                                    #ifndef _WIN32
                                    << __PRETTY_FUNCTION__ << ':'
                                    #endif
                                    << " Converting C++ std::exception mupdf::{typename} ({i=}) into Python exception:\\n"
                                    << "    e.m_code: " << e.m_code << "\\n"
                                    << "    e.m_text: " << e.m_text << "\\n"
                                    << "    e.what(): " << e.what() << "\\n"
                                    << "    typeid(e).name(): " << typeid(e).name() << "\\n"
                                    << "\\n";
                        }}
                        set_exception(s_error_classes[{i}], e.m_code, e.m_text);

                    }}'''))

    # Append less specific exception handling.
    generated.swig_python_exceptions.write( textwrap.dedent( f'''
                catch (mupdf::FzErrorBase& e)
                {{
                    if (g_mupdf_trace_exceptions)
                    {{
                        std::cerr
                                << __FILE__ << ':' << __LINE__ << ':'
                                #ifndef _WIN32
                                << __PRETTY_FUNCTION__ << ':'
                                #endif
                                << " Converting C++ std::exception mupdf::FzErrorBase ({error_classes_n-1=}) into Python exception:\\n"
                                << "    e.m_code: " << e.m_code << "\\n"
                                << "    e.m_text: " << e.m_text << "\\n"
                                << "    e.what(): " << e.what() << "\\n"
                                << "    typeid(e).name(): " << typeid(e).name() << "\\n"
                                << "\\n";
                    }}
                    PyObject* class_ = s_error_classes[{error_classes_n-1}];
                    PyObject* args = Py_BuildValue("is", e.m_code, e.m_text.c_str());
                    PyObject* instance = PyObject_CallObject(class_, args);
                    PyErr_SetObject(class_, instance);
                    Py_XDECREF(instance);
                    Py_XDECREF(args);
                }}
                catch (std::exception& e)
                {{
                    if (g_mupdf_trace_exceptions)
                    {{
                        std::cerr
                                << __FILE__ << ':' << __LINE__ << ':'
                                #ifndef _WIN32
                                << __PRETTY_FUNCTION__ << ':'
                                #endif
                                << " Converting C++ std::exception into Python exception: "
                                << e.what()
                                << "    typeid(e).name(): " << typeid(e).name() << "\\n"
                                << "\\n";
                    }}
                    SWIG_Error(SWIG_RuntimeError, e.what());

                }}
                catch (...)
                {{
                    if (g_mupdf_trace_exceptions)
                    {{
                        std::cerr
                                << __FILE__ << ':' << __LINE__ << ':'
                                #ifndef _WIN32
                                << __PRETTY_FUNCTION__ << ':'
                                #endif
                                << " Converting unknown C++ exception into Python exception."
                                << "\\n";
                    }}
                    SWIG_Error(SWIG_RuntimeError, "Unknown exception");
                }}
            }}

            %}}

            %exception
            {{
                try
                {{
                    $action
                }}
                catch (...)
                {{
                    handle_exception();
                    SWIG_fail;
                }}
            }}
            '''))

    generated.swig_python_set_error_classes.write( f'# Define __str()__ for each error/exception class, to use self.what().\n')
    for enum, typename, padding in errors(include_error_base=1):
        generated.swig_python_set_error_classes.write( f'{typename}.__str__ = lambda self: self.what()\n')

    generated.swig_python_set_error_classes.write( textwrap.dedent( f'''
            # This must be after the declaration of mupdf::FzError*
            # classes in mupdf/exceptions.h and declaration of
            # `internal_set_error_classes()`, otherwise generated code is
            # before the declaration of the Python class or similar. */
            internal_set_error_classes([
            '''))
    for enum, typename, padding in errors():
        generated.swig_python_set_error_classes.write(f'        {typename},\n')
    generated.swig_python_set_error_classes.write( textwrap.dedent( f'''
                    FzErrorBase,
                    ])
            '''))

    # Define constructor for each exception class.
    #
    for enum, typename, padding in errors():
        out_exceptions_cpp.write( textwrap.dedent(
                f'''
                FZ_FUNCTION {typename}::{typename}(const char* text)
                : {base_name}({enum}, text)
                {{
                    {trace_if}
                    if (s_trace_exceptions)
                    {{
                        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): {typename} constructor, text: " << m_text << "\\n";
                    }}
                    #endif
                }}

                '''))

    # Generate function that throws an appropriate exception from a fz_context.
    #
    throw_exception = rename.internal( 'throw_exception')
    out_exceptions_h.write( textwrap.dedent(
            f'''
            /** Throw exception appropriate for error in `ctx`. */
            FZ_FUNCTION void {throw_exception}(fz_context* ctx);

            '''))
    out_exceptions_cpp.write( textwrap.dedent(
            f'''
            FZ_FUNCTION void {throw_exception}(fz_context* ctx)
            {{
                int code;
                const char* text = fz_convert_error(ctx, &code);
                {trace_if}
                if (s_trace_exceptions)
                {{
                    std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): code=" << code << "\\n";
                    std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "(): text=" << text << "\\n";
                }}
                #endif
            '''))
    for enum, typename, padding in errors():
        out_exceptions_cpp.write( f'    if (code == {enum}) {padding}throw {typename}{padding}(text);\n')
    out_exceptions_cpp.write( f'    throw {base_name}(code, text);\n')
    out_exceptions_cpp.write( f'}}\n')
    out_exceptions_cpp.write( '\n')

    make_internal_functions( namespace, out_internal_h, out_internal_cpp, refcheck_if, trace_if)

    # Generate wrappers for each function that we find.
    #
    functions = []
    for fnname, cursor in state.state_.find_functions_starting_with( tu, ('fz_', 'pdf_'), method=False):
        assert fnname not in state.omit_fns
        #jlib.log( '{fnname=} {cursor.spelling=} {cursor.type.spelling=}')
        if ( cursor.type == state.clang.cindex.TypeKind.FUNCTIONPROTO
                and cursor.type.is_function_variadic()
                ):
            # We don't attempt to wrap variadic functions - would need to find
            # the equivalent function that takes a va_list.
            if 0:
                jlib.log( 'Variadic fn: {cursor.type.spelling=}')
            if fnname != 'fz_warn':
                continue
        if fnname == 'fz_push_try':
            # This is partof implementation of fz_try/catch so doesn't make
            # sense to provide a wrapper. Also it is OS-dependent so including
            # it makes our generated code OS-specific.
            continue

        functions.append( (fnname, cursor))

    jlib.log1( '{len(functions)=}')

    # Sort by function-name to make output easier to read.
    functions.sort()
    for fnname, cursor in functions:
        if state.state_.show_details( fnname):
            jlib.log( 'Looking at {fnname}')
        fnname_wrapper = rename.ll_fn( fnname)
        function_wrapper(
                tu,
                cursor,
                fnname,
                fnname_wrapper,
                out_functions_h,
                out_functions_cpp,
                generated,
                refcheck_if,
                trace_if,
                )
        if not fnname.startswith( ( 'fz_keep_', 'fz_drop_', 'pdf_keep_', 'pdf_drop_')):
            function_wrapper_class_aware(
                    tu,
                    register_fn_use=None,
                    struct_name=None,
                    class_name=None,
                    fn_cursor=cursor,
                    refcheck_if=refcheck_if,
                    trace_if=trace_if,
                    fnname=fnname,
                    out_h=out_functions_h2,
                    out_cpp=out_functions_cpp2,
                    generated=generated,
                    )

        python.cppyy_add_outparams_wrapper( tu, fnname, cursor, state.state_, generated)

        if fnname == "pdf_load_field_name":  #(fz_context *ctx, pdf_obj *field);
            # Output wrapper that returns std::string instead of buffer that
            # caller needs to free.
            out_functions_h.write(
                    textwrap.dedent(
                    f'''
                    /** Alternative to `{rename.ll_fn('pdf_load_field_name')}()` that returns a std::string. */
                    FZ_FUNCTION std::string {rename.ll_fn('pdf_load_field_name2')}(pdf_obj* field);

                    '''))
            out_functions_cpp.write(
                    textwrap.dedent(
                    f'''
                    FZ_FUNCTION std::string {rename.ll_fn('pdf_load_field_name2')}(pdf_obj* field)
                    {{
                        char* buffer = {rename.ll_fn('pdf_load_field_name')}( field);
                        std::string ret( buffer);
                        {rename.ll_fn('fz_free')}( buffer);
                        return ret;
                    }}
                    '''))
            out_functions_h2.write(
                    textwrap.indent(
                        textwrap.dedent(
                        f'''
                        /** Alternative to `{rename.fn('pdf_load_field_name')}()` that returns a std::string. */
                        FZ_FUNCTION std::string {rename.fn('pdf_load_field_name2')}({rename.class_('pdf_obj')}& field);
                        '''),
                        '    ',
                        )
                    )
            out_functions_cpp2.write(
                    textwrap.dedent(
                    f'''
                    FZ_FUNCTION std::string {rename.fn('pdf_load_field_name2')}({rename.class_('pdf_obj')}& field)
                    {{
                        return {rename.ll_fn('pdf_load_field_name2')}( field.m_internal);
                    }}
                    '''))

    # Output custom wrappers for variadic pdf_dict_getl().
    #

    decl = f'''FZ_FUNCTION pdf_obj* {rename.ll_fn('pdf_dict_getlv')}( pdf_obj* dict, va_list keys)'''
    out_functions_h.write( textwrap.dedent( f'''
            /* Low-level wrapper for `pdf_dict_getl()`. `keys` must be null-terminated list of `pdf_obj*`'s. */
            {decl};
            '''))
    out_functions_cpp.write( textwrap.dedent( f'''
            {decl}
            {{
                pdf_obj *key;
                while (dict != NULL && (key = va_arg(keys, pdf_obj *)) != NULL)
                {{
                    dict = {rename.ll_fn('pdf_dict_get')}( dict, key);
                }}
                return dict;
            }}
            '''))

    decl = f'''FZ_FUNCTION pdf_obj* {rename.ll_fn('pdf_dict_getl')}( pdf_obj* dict, ...)'''
    out_functions_h.write( textwrap.dedent( f'''
            /* Low-level wrapper for `pdf_dict_getl()`. `...` must be null-terminated list of `pdf_obj*`'s. */
            {decl};
            '''))
    out_functions_cpp.write( textwrap.dedent( f'''
            {decl}
            {{
                va_list keys;
                va_start(keys, dict);
                try
                {{
                    dict = {rename.ll_fn('pdf_dict_getlv')}( dict, keys);
                }}
                catch( std::exception&)
                {{
                    va_end(keys);
                    throw;
                }}
                va_end(keys);
                return dict;
            }}
            '''))

    decl = f'''FZ_FUNCTION {rename.class_('pdf_obj')} {rename.fn('pdf_dict_getlv')}( {rename.class_('pdf_obj')}& dict, va_list keys)'''
    out_functions_h2.write(
            textwrap.indent(
                textwrap.dedent( f'''
                    /* Class-aware wrapper for `pdf_dict_getl()`. `keys` must be null-terminated list of
                    `pdf_obj*`'s, not `{rename.class_('pdf_obj')}*`'s, so that conventional
                    use with `PDF_NAME()` works. */
                    {decl};
                    '''),
                '    ',
                )
            )
    out_functions_cpp2.write( textwrap.dedent( f'''
            {decl}
            {{
                pdf_obj* ret = {rename.ll_fn('pdf_dict_getlv')}( dict.m_internal, keys);
                return {rename.class_('pdf_obj')}( {rename.ll_fn('pdf_keep_obj')}( ret));
            }}
            '''))

    decl = f'''FZ_FUNCTION {rename.class_('pdf_obj')} {rename.fn('pdf_dict_getl')}( {rename.class_('pdf_obj')}* dict, ...)'''
    out_functions_h2.write(
            textwrap.indent(
                textwrap.dedent( f'''
                    /* Class-aware wrapper for `pdf_dict_getl()`. `...` must be null-terminated list of
                    `pdf_obj*`'s, not `{rename.class_('pdf_obj')}*`'s, so that conventional
                    use with `PDF_NAME()` works. [We use pointer `dict` arg because variadic
                    args do not with with reference args.] */
                    {decl};
                    '''),
                '    ',
                ),
            )
    out_functions_cpp2.write( textwrap.dedent( f'''
            {decl}
            {{
                va_list keys;
                va_start(keys, dict);
                try
                {{
                    {rename.class_('pdf_obj')} ret = {rename.fn('pdf_dict_getlv')}( *dict, keys);
                    va_end( keys);
                    return ret;
                }}
                catch (std::exception&)
                {{
                    va_end( keys);
                    throw;
                }}
            }}
            '''))


def class_add_iterator( tu, struct_cursor, struct_name, classname, extras, refcheck_if, trace_if):
    '''
    Add begin() and end() methods so that this generated class is iterable
    from C++ with:

        for (auto i: foo) {...}

    We modify <extras> to create an iterator class and add begin() and end()
    methods that each return an instance of the iterator class.
    '''
    it_begin, it_end = extras.iterator_next

    # Figure out type of what the iterator returns by looking at type of
    # <it_begin>.
    if it_begin:
        c = parse.find_name( struct_cursor, it_begin)
        assert c.type.kind == state.clang.cindex.TypeKind.POINTER
        it_internal_type = state.get_name_canonical( c.type.get_pointee()).spelling
        it_internal_type = util.clip( it_internal_type, 'struct ')
        it_type = rename.class_( it_internal_type)
    else:
        # The container is also the first item in the linked list.
        it_internal_type = struct_name
        it_type = classname

    # We add to extras.methods_extra().
    #
    check_refs = 1 if parse.has_refs( tu, struct_cursor.type) else 0
    extras.methods_extra.append(
            classes.ExtraMethod( f'{classname}Iterator', 'begin()',
                    f'''
                    {{
                        auto ret = {classname}Iterator({'m_internal->'+it_begin if it_begin else '*this'});
                        {refcheck_if}
                        #if {check_refs}
                        if (s_check_refs)
                        {{
                            s_{classname}_refs_check.check( this, __FILE__, __LINE__, __FUNCTION__);
                        }}
                        #endif
                        #endif
                        return ret;
                    }}
                    ''',
                    f'/* Used for iteration over linked list of {it_type} items starting at {it_internal_type}::{it_begin}. */',
                    ),
            )
    extras.methods_extra.append(
            classes.ExtraMethod( f'{classname}Iterator', 'end()',
                    f'''
                    {{
                        auto ret = {classname}Iterator({it_type}());
                        {refcheck_if}
                        #if {check_refs}
                        if (s_check_refs)
                        {{
                            s_{classname}_refs_check.check( this, __FILE__, __LINE__, __FUNCTION__);
                        }}
                        #endif
                        #endif
                        return ret;
                    }}
                    ''',
                    f'/* Used for iteration over linked list of {it_type} items starting at {it_internal_type}::{it_begin}. */',
                    ),
            )

    extras.class_bottom += f'\n    typedef {classname}Iterator iterator;\n'

    extras.class_pre += f'\nstruct {classname}Iterator;\n'

    extras.class_post += f'''
            struct {classname}Iterator
            {{
                FZ_FUNCTION {classname}Iterator(const {it_type}& item);
                FZ_FUNCTION {classname}Iterator& operator++();
                FZ_FUNCTION bool operator==( const {classname}Iterator& rhs);
                FZ_FUNCTION bool operator!=( const {classname}Iterator& rhs);
                FZ_FUNCTION {it_type} operator*();
                FZ_FUNCTION {it_type}* operator->();
                private:
                {it_type} m_item;
            }};
            '''
    keep_text = ''
    if extras.copyable and extras.copyable != 'default':
        # Our operator++ needs to create it_type from m_item.m_internal->next,
        # so we need to call fz_keep_<it_type>().
        #
        # [Perhaps life would be simpler if our generated constructors always
        # called fz_keep_*() as necessary? In some circumstances this would
        # require us to call fz_drop_*() when constructing an instance, but
        # that might be simpler?]
        #
        base_name = util.clip( struct_name, ('fz_', 'pdf_'))
        if struct_name.startswith( 'fz_'):
            keep_name = f'fz_keep_{base_name}'
        elif struct_name.startswith( 'pdf_'):
            keep_name = f'pdf_keep_{base_name}'
        keep_name = rename.ll_fn(keep_name)
        keep_text = f'{keep_name}(m_item.m_internal->next);'

    extras.extra_cpp += f'''
            FZ_FUNCTION {classname}Iterator::{classname}Iterator(const {it_type}& item)
            : m_item( item)
            {{
            }}
            FZ_FUNCTION {classname}Iterator& {classname}Iterator::operator++()
            {{
                {keep_text}
                m_item = {it_type}(m_item.m_internal->next);
                return *this;
            }}
            FZ_FUNCTION bool {classname}Iterator::operator==( const {classname}Iterator& rhs)
            {{
                return m_item.m_internal == rhs.m_item.m_internal;
            }}
            FZ_FUNCTION bool {classname}Iterator::operator!=( const {classname}Iterator& rhs)
            {{
                return m_item.m_internal != rhs.m_item.m_internal;
            }}
            FZ_FUNCTION {it_type} {classname}Iterator::operator*()
            {{
                return m_item;
            }}
            FZ_FUNCTION {it_type}* {classname}Iterator::operator->()
            {{
                return &m_item;
            }}

            '''


def class_find_constructor_fns( tu, classname, struct_name, base_name, extras):
    '''
    Returns list of functions that could be used as constructors of the
    specified wrapper class.

    For example we look for functions that return a pointer to <struct_name> or
    return a POD <struct_name> by value.

    tu:
        .
    classname:
        Name of our wrapper class.
    struct_name:
        Name of underlying mupdf struct.
    base_name:
        Name of struct without 'fz_' prefix.
    extras:
        .
    '''
    assert struct_name == f'fz_{base_name}' or struct_name == f'pdf_{base_name}'
    verbose = state.state_.show_details( struct_name)
    constructor_fns = []
    if '-' not in extras.constructor_prefixes:
        # Add default constructor fn prefix.
        if struct_name.startswith( 'fz_'):
            extras.constructor_prefixes.insert( 0, f'fz_new_')
            extras.constructor_prefixes.insert( 0, f'pdf_new_')
        elif struct_name.startswith( 'pdf_'):
            extras.constructor_prefixes.insert( 0, f'pdf_new_')
    for fnprefix in extras.constructor_prefixes:
        if verbose:
            jlib.log('{struct_name=} {fnprefix=}')
        for fnname, cursor in state.state_.find_functions_starting_with( tu, fnprefix, method=True):
            # Check whether this has identical signature to any fn we've
            # already found.
            if verbose:
                jlib.log( '{struct_name=} {fnname=}')
            duplicate_type = None
            duplicate_name = False
            for f, c, is_duplicate in constructor_fns:
                if verbose:
                    jlib.log( '{struct_name=} {cursor.spelling=} {c.type.spelling=}')
                if f == fnname:
                    if verbose:
                        jlib.log('setting duplicate_name to true')
                    duplicate_name = True
                    break
                if c.type == cursor.type:
                    if verbose:
                        jlib.log( '{struct_name} wrapper: ignoring candidate constructor {fnname}() because prototype is indistinguishable from {f=}()')
                    duplicate_type = f
                    break
            if duplicate_name:
                continue
            ok = False

            arg, n = parse.get_first_arg( tu, cursor)
            if arg and n == 1 and parse.is_pointer_to( arg.cursor.type, struct_name):
                # This avoids generation of bogus copy constructor wrapping
                # function fz_new_pixmap_from_alpha_channel() introduced
                # 2021-05-07.
                #
                if verbose:
                    jlib.log('ignoring possible constructor because looks like copy constructor: {fnname}')
            elif fnname in extras.constructor_excludes:
                if verbose:
                    jlib.log('{fnname=} is in {extras.constructor_excludes=}')
            elif extras.pod and extras.pod != 'none' and state.get_name_canonical( cursor.result_type).spelling == f'{struct_name}':
                # Returns POD struct by value.
                ok = True
            elif not extras.pod and parse.is_pointer_to( cursor.result_type, f'{struct_name}'):
                # Returns pointer to struct.
                ok = True

            if ok:
                if duplicate_type and extras.copyable:
                    if verbose:
                        jlib.log1( 'adding static method wrapper for {fnname}')
                    extras.method_wrappers_static.append( fnname)
                else:
                    if duplicate_type:
                        if verbose:
                            jlib.log( 'not able to provide static factory fn {struct_name}::{fnname} because wrapper class is not copyable.')
                    if verbose:
                        jlib.log( 'adding constructor wrapper for {fnname}')
                    constructor_fns.append( (fnname, cursor, duplicate_type))
            else:
                if verbose:
                    jlib.log( 'ignoring possible constructor for {classname=} because does not return required type: {fnname=} -> {cursor.result_type.spelling=}')

    constructor_fns.sort()
    return constructor_fns


def class_find_destructor_fns( tu, struct_name, base_name):
    '''
    Returns list of functions that could be used by destructor - must be called
    'fz_drop_<typename>', must take a <struct>* arg, may take a fz_context*
    arg.
    '''
    if struct_name.startswith( 'fz_'):
        destructor_prefix = f'fz_drop_{base_name}'
    elif struct_name.startswith( 'pdf_'):
        destructor_prefix = f'pdf_drop_{base_name}'
    destructor_fns = []
    for fnname, cursor in state.state_.find_functions_starting_with( tu, destructor_prefix, method=True):
        arg_struct = False
        arg_context = False
        args_num = 0
        for arg in parse.get_args( tu, cursor):
            if not arg_struct and parse.is_pointer_to( arg.cursor.type, struct_name):
                arg_struct = True
            elif not arg_context and parse.is_pointer_to( arg.cursor.type, 'fz_context'):
                arg_context = True
            args_num += 1
        if arg_struct:
            if args_num == 1 or (args_num == 2 and arg_context):
                # No params other than <struct>* and fz_context* so this is
                # candidate destructor.
                #log( 'adding candidate destructor: {fnname}')
                destructor_fns.append( (fnname, cursor))

    destructor_fns.sort()
    return destructor_fns


def num_instances(refcheck_if, delta, name):
    '''
    Returns C++ code to embed in a wrapper class constructor/destructor function
    to update the class static `s_num_instances` variable.
    '''
    ret = ''
    ret += f'    {refcheck_if}\n'
    if delta == +1:
        ret += '    ++s_num_instances;\n'
    elif delta == -1:
        ret += '    --s_num_instances;\n'
    else:
        assert 0
    ret += '    #endif\n'
    return ret


def class_constructor_default(
        tu,
        struct_cursor,
        classname,
        extras,
        out_h,
        out_cpp,
        refcheck_if,
        trace_if,
        ):
    '''
    Generates constructor that sets each member to default value.
    '''
    if extras.pod:
        comment = f'Default constructor, sets each member to default value.'
    else:
        comment = f'Default constructor, sets `m_internal` to null.'
    out_h.write( '\n')
    out_h.write( f'    /** {comment} */\n')
    out_h.write( f'    FZ_FUNCTION {classname}();\n')

    out_cpp.write( f'/** {comment} */\n')
    out_cpp.write( f'FZ_FUNCTION {classname}::{classname}()\n')
    if not extras.pod:
        out_cpp.write( f': m_internal(nullptr)\n')
    out_cpp.write( f'{{\n')
    if extras.pod == 'none':
        pass
    elif extras.pod:
        for c in parse.get_members(struct_cursor):
            if extras.pod == 'inline':
                c_name = f'this->{c.spelling}'
            else:
                c_name = f'this->m_internal.{c.spelling}'
            if c.type.kind == state.clang.cindex.TypeKind.CONSTANTARRAY:
                out_cpp.write( f'    memset(&{c_name}, 0, sizeof({c_name}));\n')
            else:
                out_cpp.write( f'    {c_name} = {{}};\n')
    else:
        if parse.has_refs( tu, struct_cursor.type):
            out_cpp.write(f'    {refcheck_if}\n')
            out_cpp.write( '    if (s_check_refs)\n')
            out_cpp.write( '    {\n')
            out_cpp.write(f'        s_{classname}_refs_check.add( this, __FILE__, __LINE__, __FUNCTION__);\n')
            out_cpp.write( '    }\n')
            out_cpp.write( '    #endif\n')

    out_cpp.write(num_instances(refcheck_if, +1, classname))

    out_cpp.write( f'}};\n')


def class_copy_constructor(
        tu,
        functions,
        struct_name,
        struct_cursor,
        base_name,
        classname,
        constructor_fns,
        out_h,
        out_cpp,
        refcheck_if,
        trace_if,
        ):
    '''
    Generate a copy constructor and operator= by finding a suitable fz_keep_*()
    function.

    We raise an exception if we can't find one.
    '''
    if struct_name.startswith( 'fz_'):
        keep_name = f'fz_keep_{base_name}'
        drop_name = f'fz_drop_{base_name}'
    elif struct_name.startswith( 'pdf_'):
        keep_name = f'pdf_keep_{base_name}'
        drop_name = f'pdf_drop_{base_name}'
    for name in keep_name, drop_name:
        cursor = state.state_.find_function( tu, name, method=True)
        if not cursor:
            classextra = classes.classextras.get( tu, struct_name)
            if classextra.copyable:
                if 1 or state.state_.show_details( struct_name):
                    jlib.log( 'changing to non-copyable because no function {name}(): {struct_name}')
                classextra.copyable = False
            return
        if name == keep_name:
            pvoid = parse.is_pointer_to( cursor.result_type, 'void')
            assert ( pvoid
                    or parse.is_pointer_to( cursor.result_type, struct_name)
                    ), (
                    f'Function {name}(): result_type not void* or pointer to {struct_name}: {cursor.result_type.spelling}'
                    )
        arg, n = parse.get_first_arg( tu, cursor)
        assert n == 1, f'should take exactly one arg: {cursor.spelling}()'
        assert parse.is_pointer_to( arg.cursor.type, struct_name), (
                f'arg0 is not pointer to {struct_name}: {cursor.spelling}(): {arg.cursor.spelling} {arg.name}')

    for fnname, cursor, duplicate_type in constructor_fns:
        fnname2 = rename.ll_fn(fnname)
        if fnname2 == keep_name:
            jlib.log( 'not generating copy constructor with {keep_name=} because already used by a constructor.')
            break
    else:
        functions( keep_name)
        comment = f'Copy constructor using `{keep_name}()`.'
        out_h.write( '\n')
        out_h.write( f'    /** {comment} */\n')
        out_h.write( f'    FZ_FUNCTION {classname}(const {classname}& rhs);\n')
        out_h.write( '\n')

        cast = ''
        if pvoid:
            # Need to cast the void* to the correct type.
            cast = f'(::{struct_name}*) '

        out_cpp.write( f'/** {comment} */\n')
        out_cpp.write( f'FZ_FUNCTION {classname}::{classname}(const {classname}& rhs)\n')
        out_cpp.write( f': m_internal({cast}{rename.ll_fn(keep_name)}(rhs.m_internal))\n')
        out_cpp.write( '{\n')

        # Write trace code.
        out_cpp.write( f'    {trace_if}\n')
        out_cpp.write( f'    if (s_trace_keepdrop) {{\n')
        out_cpp.write( f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "():"\n')
        out_cpp.write( f'                << " have called {rename.ll_fn(keep_name)}(rhs.m_internal)\\n"\n')
        out_cpp.write( f'                ;\n')
        out_cpp.write( f'    }}\n')
        out_cpp.write( f'    #endif\n')

        if parse.has_refs( tu, struct_cursor.type):
            out_cpp.write(f'    {refcheck_if}\n')
            out_cpp.write( '    if (s_check_refs)\n')
            out_cpp.write( '    {\n')
            out_cpp.write(f'        s_{classname}_refs_check.add( this, __FILE__, __LINE__, __FUNCTION__);\n')
            out_cpp.write( '    }\n')
            out_cpp.write( '    #endif\n')
        out_cpp.write(num_instances(refcheck_if, +1, classname))
        out_cpp.write( '}\n')
        out_cpp.write( '\n')

    # Make operator=().
    #
    comment = f'operator= using `{keep_name}()` and `{drop_name}()`.'
    out_h.write( f'    /** {comment} */\n')
    out_h.write( f'    FZ_FUNCTION {classname}& operator=(const {classname}& rhs);\n')

    out_cpp.write( f'/* {comment} */\n')
    out_cpp.write( f'FZ_FUNCTION {classname}& {classname}::operator=(const {classname}& rhs)\n')
    out_cpp.write(  '{\n')
    out_cpp.write( f'    {trace_if}\n')
    out_cpp.write( f'    if (s_trace_keepdrop) {{\n')
    out_cpp.write( f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "():"\n')
    out_cpp.write( f'                << " calling {rename.ll_fn(drop_name)}(this->m_internal)"\n')
    out_cpp.write( f'                << " and {rename.ll_fn(keep_name)}(rhs.m_internal)\\n"\n')
    out_cpp.write( f'                ;\n')
    out_cpp.write( f'    }}\n')
    out_cpp.write( f'    #endif\n')
    out_cpp.write( f'    {rename.ll_fn(drop_name)}(this->m_internal);\n')
    out_cpp.write( f'    {rename.ll_fn(keep_name)}(rhs.m_internal);\n')
    if parse.has_refs( tu, struct_cursor.type):
        out_cpp.write(f'    {refcheck_if}\n')
        out_cpp.write( '    if (s_check_refs)\n')
        out_cpp.write( '    {\n')
        out_cpp.write(f'        s_{classname}_refs_check.remove( this, __FILE__, __LINE__, __FUNCTION__);\n')
        out_cpp.write( '    }\n')
        out_cpp.write( '    #endif\n')
    out_cpp.write( f'    this->m_internal = {cast}rhs.m_internal;\n')
    if parse.has_refs( tu, struct_cursor.type):
        out_cpp.write(f'    {refcheck_if}\n')
        out_cpp.write( '    if (s_check_refs)\n')
        out_cpp.write( '    {\n')
        out_cpp.write(f'        s_{classname}_refs_check.add( this, __FILE__, __LINE__, __FUNCTION__);\n')
        out_cpp.write( '    }\n')
        out_cpp.write( '    #endif\n')
    out_cpp.write( f'    return *this;\n')
    out_cpp.write(  '}\n')
    out_cpp.write(  '\n')

def function_name_implies_kept_references( fnname):
    '''
    Returns true if <fnname> implies the function would return kept
    reference(s).
    '''
    if fnname in (
            'pdf_page_write',
            'fz_decomp_image_from_stream',
            'fz_get_pixmap_from_image',
            ):
        return True
    for i in (
            'add',
            'convert',
            'copy',
            'create',
            'deep_copy',
            'find',
            'graft',
            'keep',
            'load',
            'new',
            'open',
            'parse',
            'read',
            ):
        if fnname.startswith(f'fz_{i}_') or fnname.startswith(f'pdf_{i}_'):
            if state.state_.show_details(fnname):
                jlib.log('Assuming that {fnname=} returns a kept reference.')
            return True
    return False


def function_wrapper_class_aware_body(
        tu,
        fnname,
        out_cpp,
        struct_name,
        class_name,
        class_static,
        class_constructor,
        extras,
        struct_cursor,
        fn_cursor,
        return_cursor,
        wrap_return,
        refcheck_if,
        trace_if,
        ):
    '''
    Writes function or method body to <out_cpp> that calls a generated C++ wrapper
    function.

    fnname:
        .
    out_cpp:
        .
    struct_name:
        If false, we write a class-aware wrapping function body. Otherwise name
        of struct such as 'fz_rect' and we write method body for the struct's
        wrapper class.
    class_name:
    class_static:
        If true, this is a static class method.
    class_constructor:
        If true, this is a constructor.
    extras:
        .
    struct_cursor:
        .
    fn_cursor:
        Cursor for the underlying MuPDF function.
    return_cursor:
        If not None, the cursor for definition of returned type.
    wrap_return:
        If 'pointer', the underlying function returns a pointer to a struct
        that we wrap.

        If 'value' the underlying function returns, by value, a
        struct that we wrap, so we need to construct our wrapper from the
        address of this value.

        Otherwise we don't wrap the returned value.
    '''
    verbose = state.state_.show_details( fnname)
    out_cpp.write( f'{{\n')
    return_void = (fn_cursor.result_type.spelling == 'void')

    # Write trace code.
    out_cpp.write( f'    {trace_if}\n')
    out_cpp.write( f'    if (s_trace) {{\n')
    out_cpp.write( f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << "():"\n')
    out_cpp.write( f'                << " calling mupdf::{rename.ll_fn(fnname)}()\\n";\n')
    out_cpp.write( f'    }}\n')
    out_cpp.write( f'    #endif\n')

    if fn_cursor.type.is_function_variadic():
        assert fnname == 'fz_warn', f'{fnname=}'
        out_cpp.write( f'    va_list ap;\n')
        out_cpp.write( f'    va_start( ap, fmt);\n')
        out_cpp.write( f'    {rename.ll_fn("fz_vwarn")}( fmt, ap);\n')
        out_cpp.write( f'    va_end( ap);\n')

    elif class_constructor or not struct_name:
        # This code can generate a class method, but we choose to not use this,
        # instead method body simply calls the class-aware function (see below).
        def get_keep_drop(arg):
            name = util.clip( arg.alt.type.spelling, 'struct ')
            if name.startswith('fz_'):
                prefix = 'fz'
                name = name[3:]
            elif name.startswith('pdf_'):
                prefix = 'pdf'
                name = name[4:]
            else:
                assert 0
            return rename.ll_fn(f'{prefix}_keep_{name}'), rename.ll_fn(f'{prefix}_drop_{name}')

        # Handle wrapper-class out-params - need to drop .m_internal and set to
        # null.
        #
        # fixme: maybe instead simply call <arg.name>'s destructor directly?
        #
        for arg in parse.get_args( tu, fn_cursor):
            if arg.alt and arg.out_param:
                if parse.has_refs(tu, arg.alt.type):
                    keep_fn, drop_fn = get_keep_drop(arg)
                    out_cpp.write( f'    /* Out-param {arg.name}.m_internal will be overwritten. */\n')
                    out_cpp.write( f'    {drop_fn}({arg.name}.m_internal);\n')
                    out_cpp.write( f'    {arg.name}.m_internal = nullptr;\n')

        # Write function call.
        if class_constructor:
            if extras.pod:
                if extras.pod == 'inline':
                    out_cpp.write( f'    *(::{struct_name}*) &this->{parse.get_field0(struct_cursor.type).spelling} = ')
                else:
                    out_cpp.write( f'    this->m_internal = ')
                if fn_cursor.result_type.kind == state.clang.cindex.TypeKind.POINTER:
                    out_cpp.write( f'*')
            else:
                out_cpp.write( f'    this->m_internal = ')
                if fn_cursor.result_type.kind == state.clang.cindex.TypeKind.POINTER:
                    pass
                else:
                    assert 0, 'cannot handle underlying fn returning by value when not pod.'
            out_cpp.write( f'{rename.ll_fn(fnname)}(')
        elif wrap_return == 'value':
            out_cpp.write( f'    {_make_top_level(return_cursor.spelling)} temp = mupdf::{rename.ll_fn(fnname)}(')
        elif wrap_return == 'pointer':
            out_cpp.write( f'    {_make_top_level(return_cursor.spelling)}* temp = mupdf::{rename.ll_fn(fnname)}(')
        elif wrap_return == 'const pointer':
            out_cpp.write( f'    const {_make_top_level(return_cursor.spelling)}* temp = mupdf::{rename.ll_fn(fnname)}(')
        elif return_void:
            out_cpp.write( f'    mupdf::{rename.ll_fn(fnname)}(')
        else:
            out_cpp.write( f'    auto ret = mupdf::{rename.ll_fn(fnname)}(')

        have_used_this = False
        sep = ''
        for arg in parse.get_args( tu, fn_cursor):
            arg_classname = class_name
            if class_static or class_constructor:
                arg_classname = None
            out_cpp.write( sep)
            have_used_this = write_call_arg(
                    tu,
                    arg,
                    arg_classname,
                    have_used_this,
                    out_cpp,
                    state.state_.show_details(fnname),
                    )
            sep = ', '
        out_cpp.write( f');\n')

        if state.state_.show_details(fnname):
            jlib.log('{=wrap_return}')
        refcounted_return = False
        if wrap_return in ('pointer', 'const pointer') and parse.has_refs( tu, return_cursor.type):
            refcounted_return = True
            refcounted_return_struct_cursor = return_cursor
        elif class_constructor and parse.has_refs( tu, struct_cursor.type):
            refcounted_return = True
            refcounted_return_struct_cursor = struct_cursor

        if refcounted_return:
            # This MuPDF function returns pointer to a struct which uses reference
            # counting. If the function returns a borrowed reference, we need
            # to increment its reference count before passing it to our wrapper
            # class's constructor.
            #
            #jlib.log('Function returns pointer to {return_cursor=}')
            return_struct_name = util.clip( refcounted_return_struct_cursor.spelling, 'struct ')
            if return_struct_name.startswith('fz_'):
                prefix = 'fz_'
            elif return_struct_name.startswith('pdf_'):
                prefix = 'pdf_'
            else:
                prefix = None
            if state.state_.show_details(fnname):
                jlib.log('{=prefix}')
            if prefix:
                if function_name_implies_kept_references( fnname):
                    pass
                    #out_cpp.write( f'    /* We assume that {fnname} returns a kept reference. */\n')
                else:
                    if state.state_.show_details(fnname):
                        jlib.log('{=classname fnname constructor} Assuming that {fnname=} returns a borrowed reference.')
                    # This function returns a borrowed reference.
                    suffix = return_struct_name[ len(prefix):]
                    keep_fn = f'{prefix}keep_{suffix}'
                    #jlib.log('Function assumed to return borrowed reference: {fnname=} => {return_struct_name=} {keep_fn=}')
                    #out_cpp.write( f'    /* We assume that {fnname} returns a borrowed reference. */\n')
                    if class_constructor:
                        out_cpp.write( f'    {rename.ll_fn(keep_fn)}(this->m_internal);\n')
                    else:
                        out_cpp.write( f'    {rename.ll_fn(keep_fn)}(temp);\n')

        if wrap_return == 'value':
            out_cpp.write( f'    auto ret = {rename.class_(return_cursor.spelling)}(&temp);\n')
        elif wrap_return in ('pointer', 'const pointer'):
            out_cpp.write( f'    auto ret = {rename.class_(return_cursor.spelling)}(temp);\n')

        # Handle wrapper-class out-params - need to keep arg.m_internal if
        # fnname implies it will be a borrowed reference.
        for arg in parse.get_args( tu, fn_cursor):
            if arg.alt and arg.out_param:
                if parse.has_refs(tu, arg.alt.type):
                    if function_name_implies_kept_references( fnname):
                        out_cpp.write( f'    /* We assume that out-param {arg.name}.m_internal is a kept reference. */\n')
                    else:
                        keep_fn, drop_fn = get_keep_drop(arg)
                        out_cpp.write( f'    /* We assume that out-param {arg.name}.m_internal is a borrowed reference. */\n')
                        out_cpp.write( f'    {keep_fn}({arg.name}.m_internal);\n')
    else:
        # Class method simply calls the class-aware function, which will have
        # been generated elsewhere.
        out_cpp.write( '    ')
        if not return_void:
            out_cpp.write( 'auto ret = ')

        out_cpp.write( f'mupdf::{rename.fn(fnname)}(')
        sep = ''
        for i, arg in enumerate( parse.get_args( tu, fn_cursor)):
            out_cpp.write( sep)
            if i==0 and not class_static:
                out_cpp.write( '*this')
            else:
                out_cpp.write( f'{arg.name}')
            sep = ', '

        out_cpp.write( ');\n')

    if struct_name and not class_static:
        if parse.has_refs( tu, struct_cursor.type):
            # Write code that does runtime checking of reference counts.
            out_cpp.write( f'    {refcheck_if}\n')
            out_cpp.write( f'    if (s_check_refs)\n')
            out_cpp.write( f'    {{\n')
            if class_constructor:
                out_cpp.write( f'        s_{class_name}_refs_check.add( this, __FILE__, __LINE__, __FUNCTION__);\n')
            else:
                out_cpp.write( f'        s_{class_name}_refs_check.check( this, __FILE__, __LINE__, __FUNCTION__);\n')
            out_cpp.write( f'    }}\n')
            out_cpp.write( f'    #endif\n')

    if class_constructor:
        out_cpp.write(num_instances(refcheck_if, +1, class_name))

    if not return_void and not class_constructor:
        out_cpp.write( f'    return ret;\n')

    out_cpp.write( f'}}\n')
    out_cpp.write( f'\n')


def function_wrapper_class_aware(
        tu,
        register_fn_use,
        fnname,
        out_h,
        out_cpp,
        struct_name,
        class_name,
        fn_cursor,
        refcheck_if,
        trace_if,
        class_static=False,
        class_constructor=False,
        extras=None,
        struct_cursor=None,
        duplicate_type=None,
        generated=None,
        debug=None,
        ):
    '''
    Writes a function or class method that calls <fnname>.

    Also appends python and C# code to generated.swig_python and
    generated.swig_csharp if <generated> is not None.

        tu
            .
        register_fn_use
            Callback to keep track of what fz_*() fns have been used.
        fnname
            Name of fz_*() fn to wrap, e.g. fz_concat.
        out_h
        out_cpp
            Where to write generated code.
        struct_name
            If false, we generate class-aware wrapping function. Otherwise name
            of struct such as 'fz_rect' and we create a method in the struct's
            wrapper class.
        class_name
            Ignored if struct_name is false.

            Name of wrapper class, e.g. 'Rect'.
        class_static
            Ignored if struct_name is false.

            If true, we generate a static method.

            Otherwise we generate a normal class method, where first arg that
            is type <struct_name> is omitted from the generated method's
            prototype; in the implementation we use <this>.
        class_constructor
            If true, we write a constructor.
        extras
            None or ClassExtras instance.
            Only used if <constructor> is true.
        struct_cursor
            None or cursor for the struct definition.
            Only used if <constructor> is true.
        duplicate_type:
            If true, we have already generated a method with the same args, so
            this generated method will be commented-out.
        generated:
            If not None and there are one or more out-params, we write
            python code to generated.swig_python that overrides the default
            SWIG-generated method to call our *_outparams_fn() alternative.
        debug
            Show extra diagnostics.
    '''
    verbose = state.state_.show_details( fnname)
    if fn_cursor and fn_cursor.type.is_function_variadic() and fnname != 'fz_warn':
        jlib.log( 'Not writing class-aware wrapper because variadic: {fnname=}', 1)
        return
    if verbose:
        jlib.log( 'Writing class-aware wrapper for {fnname=}')
    if struct_name:
        assert fnname not in state.omit_methods, jlib.log_text( '{=fnname}')
    if debug:
        jlib.log( '{class_name=} {fnname=}')
    assert fnname.startswith( ('fz_', 'pdf_'))
    if not fn_cursor:
        fn_cursor = state.state_.find_function( tu, fnname, method=True)
    if not fn_cursor:
        jlib.log( '*** ignoring {fnname=}')
        return

    if fnname.endswith('_drop'):
        # E.g. fz_concat_push_drop() is not safe (or necessary) for us because
        # we need to manage reference counts ourselves.
        #jlib.log('Ignoring because ends with "_drop": {fnname}')
        return

    if struct_name:
        methodname = rename.method( struct_name, fnname)
    else:
        methodname = rename.fn( fnname)

    if verbose:
        jlib.log( 'Writing class-aware wrapper for {fnname=}')
    # Construct prototype fnname(args).
    #
    if class_constructor:
        assert struct_name
        decl_h = f'{class_name}('
        decl_cpp = f'{class_name}('
    else:
        decl_h = f'{methodname}('
        decl_cpp = f'{methodname}('
    have_used_this = False
    num_out_params = 0
    num_class_wrapper_params = 0
    comma = ''
    this_is_const = False
    debug = state.state_.show_details( fnname)

    for arg in parse.get_args( tu, fn_cursor):
        if debug:
            jlib.log( 'Looking at {struct_name=} {fnname=} {fnname_wrapper} {arg=}', 1)
        decl_h += comma
        decl_cpp += comma
        if arg.out_param:
            num_out_params += 1
        if arg.alt:
            # This parameter is a pointer to a struct that we wrap.
            num_class_wrapper_params += 1
            arg_extras = classes.classextras.get( tu, arg.alt.type.spelling)
            assert arg_extras, jlib.log_text( '{=structname fnname arg.alt.type.spelling}')
            const = ''
            if not arg.out_param and (not arg_extras.pod or arg.cursor.type.kind != state.clang.cindex.TypeKind.POINTER):
                const = 'const '

            if (1
                    and struct_name
                    and not class_static
                    and not class_constructor
                    and rename.class_(util.clip( arg.alt.type.spelling, 'struct ')) == class_name
                    and not have_used_this
                    ):
                assert not arg.out_param
                # Omit this arg from the method's prototype - we'll use <this>
                # when calling the underlying fz_ function.
                have_used_this = True
                if not arg_extras.pod:
                    this_is_const = const
                continue

            if arg_extras.pod == 'none':
                jlib.log( 'Not wrapping because {arg=} wrapper has {extras.pod=}', 1)
                return
            text = f'{const}{rename.class_(arg.alt.type.spelling)}& {arg.name}'
            decl_h += text
            decl_cpp += text
        else:
            jlib.logx( '{arg.spelling=}')
            decl_text = declaration_text( arg.cursor.type, arg.name)
            decl_h += decl_text
            decl_cpp += decl_text
        comma = ', '

    if fn_cursor.type.is_function_variadic():
        decl_h += f'{comma}...'
        decl_cpp += f'{comma}...'

    decl_h += ')'
    decl_cpp += ')'
    if this_is_const:
        decl_h += ' const'
        decl_cpp += ' const'

    if verbose:
        jlib.log( '{=struct_name class_constructor}')
    if class_constructor:
        comment = f'Constructor using `{fnname}()`.'
    else:
        comment = make_wrapper_comment(
                tu,
                fn_cursor,
                fnname,
                methodname,
                indent='    ',
                is_method=bool(struct_name),
                is_low_level=False,
                )

    if struct_name and not class_static and not class_constructor:
        assert have_used_this, f'error: wrapper for {struct_name}: {fnname}() is not useful - does not have a {struct_name} arg.'

    if struct_name and not duplicate_type:
        register_fn_use( fnname)

    # If this is true, we explicitly construct a temporary from what the
    # wrapped function returns.
    #
    wrap_return = None

    warning_not_copyable = False
    warning_no_raw_constructor = False

    # Figure out return type for our generated function/method.
    #
    if verbose:
        jlib.log( 'Looking at return type...')
    return_cursor = None
    return_type = None
    return_extras = None
    if class_constructor:
        assert struct_name
        fn_h = f'{decl_h}'
        fn_cpp = f'{class_name}::{decl_cpp}'
    else:
        fn_h = declaration_text( fn_cursor.result_type, decl_h)
        if verbose:
            jlib.log( '{fn_cursor.result_type=}')
        if struct_name:
            fn_cpp = declaration_text( fn_cursor.result_type, f'{class_name}::{decl_cpp}')
        else:
            fn_cpp = declaration_text( fn_cursor.result_type, f'{decl_cpp}')

        # See whether we can convert return type to an instance of a wrapper
        # class.
        #
        if verbose:
            jlib.log( '{fn_cursor.result_type.kind=}')
        if fn_cursor.result_type.kind == state.clang.cindex.TypeKind.POINTER:
            # Function returns a pointer.
            t = state.get_name_canonical( fn_cursor.result_type.get_pointee())
            if verbose:
                jlib.log( '{t.spelling=}')
            return_cursor = parse.find_struct( tu, t.spelling, require_definition=False)
            if verbose:
                jlib.log( '{=t.spelling return_cursor}')
            if return_cursor:
                # Function returns a pointer to a struct.
                return_extras = classes.classextras.get( tu, return_cursor.spelling)
                if return_extras:
                    # Function returns a pointer to a struct for which we
                    # generate a class wrapper, so change return type to be an
                    # instance of the class wrapper.
                    return_type = rename.class_(return_cursor.spelling)
                    if verbose:
                        jlib.log( '{=return_type}')
                    if 0 and (state.state_.show_details(return_cursor.type.spelling) or state.state_.show_details(struct_name)):
                        jlib.log('{return_cursor.type.spelling=}'
                                ' {return_cursor.spelling=}'
                                ' {struct_name=} {return_extras.copyable=}'
                                ' {return_extras.constructor_raw=}'
                                )
                    fn_h = f'{return_type} {decl_h}'
                    if struct_name:
                        fn_cpp = f'{return_type} {class_name}::{decl_cpp}'
                    else:
                        fn_cpp = f'{return_type} {decl_cpp}'
                    if t.is_const_qualified():
                        wrap_return = 'const pointer'
                    else:
                        wrap_return = 'pointer'
            else:
                return_pointee = fn_cursor.result_type.get_pointee()
                if 'char' in return_pointee.spelling:
                    if function_name_implies_kept_references(fnname):
                        # For now we just output a diagnostic, but eventually
                        # we might make C++ wrappers return a std::string here,
                        # free()-ing the char* before returning.
                        jlib.log1( 'Function name implies kept reference and returns char*:'
                                ' {fnname}(): {fn_cursor.result_type.spelling=}'
                                ' -> {return_pointee.spelling=}.'
                                )

            if verbose:
                jlib.log( '{=warning_not_copyable warning_no_raw_constructor}')
        else:
            # The fz_*() function returns by value. See whether we can convert
            # its return type to an instance of a wrapper class.
            #
            # If so, we will use constructor that takes pointer to the fz_
            # struct. C++ doesn't allow us to use address of temporary, so we
            # generate code like this:
            #
            #   fz_quad_s ret = mupdf_snap_selection(...);
            #   return Quad(&ret);
            #
            t = state.get_name_canonical( fn_cursor.result_type)

            # 2023-02-09: parse.find_struct() will actually find any definition,
            # and we now prefix Fitz headers with a typedef of size_t on Linux,
            # so we need to avoid calling parse.find_struct() unless `t` is for
            # a MuPDF type.
            #
            if t.spelling.startswith( ('fz_', 'pdf_')):
                return_cursor = parse.find_struct( tu, t.spelling)
                if return_cursor:
                    tt = state.get_name_canonical( return_cursor.type)
                    if tt.kind == state.clang.cindex.TypeKind.ENUM:
                        # For now, we return this type directly with no wrapping.
                        pass
                    else:
                        return_extras = classes.classextras.get( tu, return_cursor.spelling)
                        return_type = rename.class_(return_cursor.type.spelling)
                        fn_h = f'{return_type} {decl_h}'
                        if struct_name:
                            fn_cpp = f'{return_type} {class_name}::{decl_cpp}'
                        else:
                            fn_cpp = f'{return_type} {decl_cpp}'
                        wrap_return = 'value'

    if return_extras:
        if not return_extras.copyable:
            out_h.write(
                    textwrap.indent(
                        textwrap.dedent( f'''
                            /* Class-aware wrapper for `{fnname}()`
                            is not available because returned wrapper class for `{return_cursor.spelling}`
                            is non-copyable. */
                            '''
                            ),
                        '    ',
                        )
                    )
            if verbose:
                jlib.log( 'Not creating class-aware wrapper because returned wrapper class is non-copyable: {fnname=}.')
            return
        if not return_extras.constructor_raw:
            out_h.write(
                    textwrap.indent(
                        textwrap.dedent( f'''
                            /* Class-aware wrapper for `{fnname}()`
                            is not available because returned wrapper class for `{return_cursor.spelling}`
                            does not have raw constructor. */
                            '''
                            ),
                        '    ',
                        )
                    )
            if verbose:
                jlib.log( 'Not creating class-aware wrapper because returned wrapper class does not have raw constructor: {fnname=}.')
            return

    out_h.write( '\n')
    out_h.write( f'    /** {comment} */\n')

    # Copy any comment (indented) into class definition above method
    # declaration.
    if fn_cursor.raw_comment:
        raw_comment = fn_cursor.raw_comment.replace('\r', '')
        for line in raw_comment.split( '\n'):
            out_h.write( f'    {line}\n')

    if duplicate_type:
        out_h.write( f'    /* Disabled because same args as {duplicate_type}.\n')

    out_h.write( f'    FZ_FUNCTION {"static " if class_static else ""}{fn_h};\n')

    if duplicate_type:
        out_h.write( f'    */\n')

    if not struct_name:
        # Use extra spacing between non-class functions. Class methods are
        # grouped together.
        out_cpp.write( f'\n')

    out_cpp.write( f'/* {comment} */\n')
    if duplicate_type:
        out_cpp.write( f'/* Disabled because same args as {duplicate_type}.\n')

    out_cpp.write( f'FZ_FUNCTION {fn_cpp}\n')

    function_wrapper_class_aware_body(
            tu,
            fnname,
            out_cpp,
            struct_name,
            class_name,
            class_static,
            class_constructor,
            extras,
            struct_cursor,
            fn_cursor,
            return_cursor,
            wrap_return,
            refcheck_if,
            trace_if,
            )

    if struct_name:
        if duplicate_type:
            out_cpp.write( f'*/\n')

    # fixme: the test of `struct_name` means that we don't generate outparam override for
    # class-aware fns which don't have any struct/class args, e.g. fz_lookup_cjk_font().
    #

    if generated and num_out_params:
        make_python_class_method_outparam_override(
                tu,
                fn_cursor,
                fnname,
                generated,
                struct_name,
                class_name,
                return_type,
                )


def class_custom_method(
        tu,
        register_fn_use,
        struct_cursor,
        classname,
        extramethod,
        out_h,
        out_cpp,
        refcheck_if,
        trace_if,
        ):
    '''
    Writes custom method as specified by <extramethod>.

        tu
            .
        register_fn_use
            Callable taking single <fnname> arg.
        struct_cursor
            Cursor for definition of MuPDF struct.
        classname
            Name of wrapper class for <struct_cursor>.
        extramethod
            An ExtraMethod or ExtraConstructor instance.
        out_h
        out_cpp
            Where to write generated code.
    '''
    assert isinstance( extramethod, ( classes.ExtraMethod, classes.ExtraConstructor)), f'{type(extramethod)}'
    is_constructor = False
    is_destructor = False
    is_begin_end = False

    if extramethod.return_:
        name_args = extramethod.name_args
        return_space = f'{extramethod.return_} '
        comment = 'Custom method.'
        if name_args.startswith( 'begin(') or name_args.startswith( 'end('):
            is_begin_end = True
    elif extramethod.name_args == '~()':
        # Destructor.
        name_args = f'~{classname}{extramethod.name_args[1:]}'
        return_space = ''
        comment = 'Custom destructor.'
        is_destructor = True
    elif extramethod.name_args.startswith('operator '):
        name_args = extramethod.name_args
        comment = 'Custom operator.'
        return_space = ''
    else:
        # Constructor.
        assert extramethod.name_args.startswith( '('), f'bad constructor/destructor in {classname=}: {extramethod.name_args=}'
        name_args = f'{classname}{extramethod.name_args}'
        return_space = ''
        comment = 'Custom constructor.'
        is_constructor = True

    out_h.write( f'\n')
    if extramethod.comment:
        for i, line in enumerate( extramethod.comment.strip().split('\n')):
            line = line.replace( '/* ', '/** ')
            out_h.write( f'    {line}\n')
    else:
        out_h.write( f'    /** {comment} */\n')
    out_h.write( f'    FZ_FUNCTION {return_space}{name_args};\n')

    out_cpp.write( f'/** {comment} */\n')
    # Remove any default arg values from <name_args>.
    name_args_no_defaults = re.sub('= *[^(][^),]*', '', name_args)
    if name_args_no_defaults != name_args:
        jlib.log('have changed {name_args=} to {name_args_no_defaults=}', 1)
    out_cpp.write( f'FZ_FUNCTION {return_space}{classname}::{name_args_no_defaults}')

    body = textwrap.dedent(extramethod.body)

    end = body.rfind('}')
    assert end >= 0
    out_cpp.write( body[:end])

    if is_constructor and parse.has_refs( tu, struct_cursor.type):
        # Insert ref checking code into end of custom constructor body.
        out_cpp.write( f'    {refcheck_if}\n')
        out_cpp.write( f'    if (s_check_refs)\n')
        out_cpp.write( f'    {{\n')
        out_cpp.write( f'        s_{classname}_refs_check.add( this, __FILE__, __LINE__, __FUNCTION__);\n')
        out_cpp.write( f'    }}\n')
        out_cpp.write( f'    #endif\n')
    if is_constructor:
        out_cpp.write( num_instances(refcheck_if, +1, classname))
    if is_destructor:
        out_cpp.write( num_instances(refcheck_if, -1, classname))

    out_cpp.write( body[end:])

    out_cpp.write( f'\n')

    if 1:   # lgtm [py/constant-conditional-expression]
        # Register calls of all fz_* functions. Not necessarily helpful - we
        # might only be interested in calls of fz_* functions that are directly
        # available to uses of class.
        #
        for fnname in re.findall( '(mupdf::[a-zA-Z0-9_]+) *[(]', extramethod.body):
            fnname = util.clip( fnname, 'mupdf::')
            if not fnname.startswith( 'pdf_'):
                fnname = 'fz_' + fnname
            #log( 'registering use of {fnname} in extramethod {classname}::{name_args}')
            register_fn_use( fnname)

    return is_constructor, is_destructor, is_begin_end


def class_raw_constructor(
        tu,
        register_fn_use,
        classname,
        struct_cursor,
        struct_name,
        base_name,
        extras,
        constructor_fns,
        out_h,
        out_cpp,
        refcheck_if,
        trace_if,
        ):
    '''
    Create a raw constructor - a constructor taking a pointer to underlying
    struct. This raw constructor assumes that it already owns the pointer so it
    does not call fz_keep_*(); the class's destructor will call fz_drop_*().
    '''
    #jlib.log( 'Creating raw constructor {classname=} {struct_name=} {extras.pod=} {extras.constructor_raw=} {fnname=}')
    comment = f'/** Constructor using raw copy of pre-existing `::{struct_name}`. */'
    if extras.pod:
        constructor_decl = f'{classname}(const ::{struct_name}* internal)'
    else:
        constructor_decl = f'{classname}(::{struct_name}* internal)'
    out_h.write( '\n')
    out_h.write( f'    {comment}\n')
    explicit = ''
    if parse.has_refs( tu, struct_cursor.type):
        # Don't allow implicit construction from low-level struct, because our
        # destructor will drop it without a prior balancing keep.
        explicit = f'explicit '
        out_h.write(
                f'    /* This constructor is marked as `explicit` because wrapper classes do not\n'
                f'    call `keep`in constructors, but do call `drop` in destructors. So\n'
                f'    automatic construction from a {struct_name}* will generally cause an\n'
                f'    unbalanced `drop` resulting in errors such as SEGV. */\n'
                )
    if extras.constructor_raw == 'default':
        out_h.write( f'    FZ_FUNCTION {explicit}{classname}(::{struct_name}* internal=NULL);\n')
    else:
        out_h.write( f'    FZ_FUNCTION {explicit}{constructor_decl};\n')

    if extras.constructor_raw != 'declaration_only':
        out_cpp.write( f'FZ_FUNCTION {classname}::{constructor_decl}\n')
        if extras.pod == 'inline':
            pass
        elif extras.pod:
            out_cpp.write( ': m_internal(*internal)\n')
        else:
            out_cpp.write( ': m_internal(internal)\n')
        out_cpp.write( '{\n')
        if extras.pod == 'inline':
            assert struct_cursor, f'cannot form raw constructor for inline pod {classname} without cursor for underlying {struct_name}'
            out_cpp.write( f'    assert( internal);\n')
            for c in parse.get_members(struct_cursor):
                if c.type.kind == state.clang.cindex.TypeKind.CONSTANTARRAY:
                    out_cpp.write( f'    memcpy(this->{c.spelling}, internal->{c.spelling}, sizeof(this->{c.spelling}));\n')
                else:
                    out_cpp.write( f'    this->{c.spelling} = internal->{c.spelling};\n')
        if parse.has_refs( tu, struct_cursor.type):
            out_cpp.write( f'    {refcheck_if}\n')
            out_cpp.write( f'    if (s_check_refs)\n')
            out_cpp.write( f'    {{\n')
            out_cpp.write( f'        s_{classname}_refs_check.add( this, __FILE__, __LINE__, __FUNCTION__);\n')
            out_cpp.write( f'    }}\n')
            out_cpp.write( f'    #endif\n')

        out_cpp.write(num_instances(refcheck_if, +1, classname))

        out_cpp.write( '}\n')
        out_cpp.write( '\n')

    if extras.pod == 'inline':
        # Write second constructor that takes underlying struct by value.
        #
        assert not parse.has_refs( tu, struct_cursor.type)
        constructor_decl = f'{classname}(const ::{struct_name} internal)'
        out_h.write( '\n')
        out_h.write( f'    {comment}\n')
        out_h.write( f'    FZ_FUNCTION {constructor_decl};\n')

        if extras.constructor_raw != 'declaration_only':
            out_cpp.write( f'FZ_FUNCTION {classname}::{constructor_decl}\n')
            out_cpp.write( '{\n')
            for c in parse.get_members(struct_cursor):
                if c.type.kind == state.clang.cindex.TypeKind.CONSTANTARRAY:
                    out_cpp.write( f'    memcpy(this->{c.spelling}, &internal.{c.spelling}, sizeof(this->{c.spelling}));\n')
                else:
                    out_cpp.write( f'    this->{c.spelling} = internal.{c.spelling};\n')

            out_cpp.write(num_instances(refcheck_if, +1, classname))
            out_cpp.write( '}\n')
            out_cpp.write( '\n')

            # Write accessor for inline state.state_.
            #
            for const in False, True:
                space_const = ' const' if const else ''
                const_space = 'const ' if const else ''
                out_h.write( '\n')
                out_h.write( f'    /** Access as underlying struct. */\n')
                out_h.write( f'    FZ_FUNCTION {const_space}::{struct_name}* internal(){space_const};\n')
                out_cpp.write( f'{comment}\n')
                out_cpp.write( f'FZ_FUNCTION {const_space}::{struct_name}* {classname}::internal(){space_const}\n')
                out_cpp.write( '{\n')
                field0 = parse.get_field0(struct_cursor.canonical).spelling
                out_cpp.write( f'    auto ret = ({const_space}::{struct_name}*) &this->{field0};\n')
                if parse.has_refs( tu, struct_cursor.type):
                    out_cpp.write( f'    {refcheck_if}\n')
                    out_cpp.write( f'    if (s_check_refs)\n')
                    out_cpp.write( f'    {{\n')
                    out_cpp.write( f'        s_{classname}_refs_check.add( this, __FILE__, __LINE__, __FUNCTION__);\n')
                    out_cpp.write( f'    }}\n')
                    out_cpp.write( f'    #endif\n')

                out_cpp.write( '    return ret;\n')
                out_cpp.write( '}\n')
                out_cpp.write( '\n')



def class_accessors(
        tu,
        register_fn_use,
        classname,
        struct_cursor,
        struct_name,
        extras,
        out_h,
        out_cpp,
        ):
    '''
    Writes accessor functions for member data.
    '''
    if not extras.pod:
        jlib.logx( 'creating accessor for non-pod class {classname=} wrapping {struct_name}')

    n = 0

    for cursor in parse.get_members(struct_cursor):
        n += 1
        #jlib.log( 'accessors: {cursor.spelling=} {cursor.type.spelling=}')

        # We set this to fz_keep_<type>() function to call, if we return a
        # wrapper class constructed from raw pointer to underlying fz_* struct.
        keep_function = None

        # Set <decl> to be prototype with %s where the name is, e.g. 'int
        # %s()'; later on we use python's % operator to replace the '%s'
        # with the name we want.
        #
        if cursor.type.kind == state.clang.cindex.TypeKind.POINTER:
            decl = 'const ' + declaration_text( cursor.type, '%s()')
            pointee_type = state.get_name_canonical( cursor.type.get_pointee()).spelling
            pointee_type = util.clip( pointee_type, 'const ')
            pointee_type = util.clip( pointee_type, 'struct ')
            #if 'fz_' in pointee_type:
            #    jlib.log( '{pointee_type=}')
            # We don't attempt to make accessors to function pointers.
            if state.get_name_canonical( cursor.type.get_pointee()).kind == state.clang.cindex.TypeKind.FUNCTIONPROTO:
                jlib.logx( 'ignoring {cursor.spelling=} because pointer to FUNCTIONPROTO')
                continue
            elif pointee_type.startswith( ('fz_', 'pdf_')):
                extras2 = parse.get_fz_extras( tu, pointee_type)
                if extras2:
                    # Make this accessor return an instance of the wrapping
                    # class by value.
                    #
                    classname2 = rename.class_( pointee_type)
                    decl = f'{classname2} %s()'

                    # If there's a fz_keep_() function, we must call it on the
                    # internal data before returning the wrapper class.
                    pointee_type_base = util.clip( pointee_type, ('fz_', 'pdf_'))
                    keep_function = f'{parse.prefix(pointee_type)}keep_{pointee_type_base}'
                    if state.state_.find_function( tu, keep_function, method=False):
                        jlib.logx( 'using {keep_function=}')
                    else:
                        jlib.log( 'cannot find {keep_function=}')
                        keep_function = None
        elif cursor.type.kind == state.clang.cindex.TypeKind.FUNCTIONPROTO:
            jlib.log( 'ignoring {cursor.spelling=} because FUNCTIONPROTO')
            continue
        else:
            if 0 and extras.pod:    # lgtm [py/unreachable-statement]
                # Return reference so caller can modify. Unfortunately SWIG
                # converts non-const references to pointers, so generated
                # python isn't useful.
                fn_args = '& %s()'
            else:
                fn_args = '%s()'
            if cursor.type.get_array_size() >= 0:
                if 0:   # lgtm [py/unreachable-statement]
                    # Return reference to the array; we need to put fn name
                    # and args inside (...) to allow the declaration syntax
                    # to work - we end up with things like:
                    #
                    #   char (& media_class())[64];
                    #
                    # Unfortunately SWIG doesn't seem to be able to cope
                    # with this.
                    decl = declaration_text( cursor.type, '(%s)' % fn_args)
                else:
                    # Return pointer to the first element of the array, so
                    # that SWIG can cope.
                    fn_args = '* %s()'
                    type_ = cursor.type.get_array_element_type()
                    decl = declaration_text( type_, fn_args)
            else:
                if ( cursor.type.kind == state.clang.cindex.TypeKind.TYPEDEF
                        and cursor.type.get_typedef_name() in ('uint8_t', 'int8_t')
                        ):
                    # Don't let accessor return uint8_t because SWIG thinks it
                    # is a char*, leading to memory errors. Instead return int.
                    #
                    jlib.logx('Changing from {cursor.type.get_typedef_name()=} {cursor.type=} to int')
                    decl = f'int {fn_args}'
                else:
                    decl = declaration_text( cursor.type, fn_args)

        # todo: if return type is uint8_t or int8_t, maybe return as <int>
        # so SWIG doesn't think it is a string? This would fix errors with
        # fz_image::n and fz_image::bpc.
        out_h.write( f'    FZ_FUNCTION {decl % cursor.spelling};\n')
        out_cpp.write( 'FZ_FUNCTION %s\n' % (decl % ( f'{classname}::{cursor.spelling}')))
        out_cpp.write( '{\n')
        if keep_function:
            out_cpp.write( f'    {rename.ll_fn(keep_function)}(m_internal->{cursor.spelling});\n')
            out_cpp.write( f'    return ({classname2}) m_internal->{cursor.spelling};\n')
        else:
            if extras.pod:
                out_cpp.write( f'    return m_internal.{cursor.spelling};\n')
            else:
                out_cpp.write( f'    return m_internal->{cursor.spelling};\n')
        out_cpp.write( '}\n')
        out_cpp.write( '\n')
    assert n, f'No fields found for {struct_cursor.spelling}.'



def class_destructor(
        tu,
        register_fn_use,
        classname,
        extras,
        struct_cursor,
        destructor_fns,
        out_h,
        out_cpp,
        refcheck_if,
        trace_if,
        ):
    if len(destructor_fns) > 1:
        # Use function with shortest name.
        if 0:   # lgtm [py/unreachable-statement]
            jlib.log( 'Multiple possible destructor fns for {classname=}')
            for fnname, cursor in destructor_fns:
                jlib.log( '    {fnname=} {cursor.spelling=}')
        shortest = None
        for i in destructor_fns:
            if shortest is None or len(i[0]) < len(shortest[0]):
                shortest = i
        #jlib.log( 'Using: {shortest[0]=}')
        destructor_fns = [shortest]
    if len(destructor_fns):
        fnname, cursor = destructor_fns[0]
        register_fn_use( cursor.spelling)
        out_h.write( f'    /** Destructor using {cursor.spelling}(). */\n')
        out_h.write( f'    FZ_FUNCTION ~{classname}();\n')

        out_cpp.write( f'FZ_FUNCTION {classname}::~{classname}()\n')
        out_cpp.write(  '{\n')
        out_cpp.write( f'    {rename.ll_fn(fnname)}(m_internal);\n')
        if parse.has_refs( tu, struct_cursor.type):
            out_cpp.write( f'    {refcheck_if}\n')
            out_cpp.write( f'    if (s_check_refs)\n')
            out_cpp.write(  '    {\n')
            out_cpp.write( f'        s_{classname}_refs_check.remove( this, __FILE__, __LINE__, __FUNCTION__);\n')
            out_cpp.write(  '    }\n')
            out_cpp.write( f'    #endif\n')

        out_cpp.write(num_instances(refcheck_if, -1, classname))

        out_cpp.write(  '}\n')
        out_cpp.write( '\n')
    else:
        out_h.write(f'    {refcheck_if}\n')
        out_h.write(f'    /** Destructor only decrements s_num_instances. */\n')
        out_h.write(f'    FZ_FUNCTION ~{classname}();\n')
        out_h.write( '    #else\n')
        out_h.write( '    /** We use default destructor. */\n')
        out_h.write( '    #endif\n')

        out_cpp.write( f'{refcheck_if}\n')
        out_cpp.write( f'FZ_FUNCTION {classname}::~{classname}()\n')
        out_cpp.write(  '{\n')
        out_cpp.write(num_instances(refcheck_if, -1, classname))
        out_cpp.write(  '}\n')
        out_cpp.write( '#endif\n')
        out_cpp.write( '\n')



def pod_class_members(
        tu,
        classname,
        struct_cursor,
        struct_name,
        extras,
        out_h,
        out_cpp,
        ):
    '''
    Writes code for wrapper class's to_string() member function.
    '''
    out_h.write( f'\n')
    out_h.write( f'    /** Returns string containing our members, labelled and inside (...), using operator<<. */\n')
    out_h.write( f'    FZ_FUNCTION std::string to_string();\n')

    out_h.write( f'\n')
    out_h.write( f'    /** Comparison method. */\n')
    out_h.write( f'    FZ_FUNCTION bool operator==(const {classname}& rhs);\n')

    out_h.write( f'\n')
    out_h.write( f'    /** Comparison method. */\n')
    out_h.write( f'    FZ_FUNCTION bool operator!=(const {classname}& rhs);\n')

    out_cpp.write( f'FZ_FUNCTION std::string {classname}::to_string()\n')
    out_cpp.write( f'{{\n')
    out_cpp.write( f'    std::ostringstream buffer;\n')
    out_cpp.write( f'    buffer << *this;\n')
    out_cpp.write( f'    return buffer.str();\n')
    out_cpp.write( f'}}\n')
    out_cpp.write( f'\n')

    out_cpp.write( f'FZ_FUNCTION bool {classname}::operator==(const {classname}& rhs)\n')
    out_cpp.write( f'{{\n')
    out_cpp.write( f'    return ::operator==( *this, rhs);\n')
    out_cpp.write( f'}}\n')
    out_cpp.write( f'\n')

    out_cpp.write( f'FZ_FUNCTION bool {classname}::operator!=(const {classname}& rhs)\n')
    out_cpp.write( f'{{\n')
    out_cpp.write( f'    return ::operator!=( *this, rhs);\n')
    out_cpp.write( f'}}\n')
    out_cpp.write( f'\n')


def struct_to_string_fns(
        tu,
        struct_cursor,
        struct_name,
        extras,
        out_h,
        out_cpp,
        ):
    '''
    Writes functions for text representation of struct/wrapper-class members.
    '''
    out_h.write( f'\n')
    out_h.write( f'/** Returns string containing a {struct_name}\'s members, labelled and inside (...), using operator<<. */\n')
    out_h.write( f'FZ_FUNCTION std::string to_string_{struct_name}(const ::{struct_name}& s);\n')

    out_h.write( f'\n')
    out_h.write( f'/** Returns string containing a {struct_name}\'s members, labelled and inside (...), using operator<<.\n')
    out_h.write( f'(Convenience overload). */\n')
    out_h.write( f'FZ_FUNCTION std::string to_string(const ::{struct_name}& s);\n')

    out_cpp.write( f'\n')
    out_cpp.write( f'FZ_FUNCTION std::string to_string_{struct_name}(const ::{struct_name}& s)\n')
    out_cpp.write( f'{{\n')
    out_cpp.write( f'    std::ostringstream buffer;\n')
    out_cpp.write( f'    buffer << s;\n')
    out_cpp.write( f'    return buffer.str();\n')
    out_cpp.write( f'}}\n')

    out_cpp.write( f'\n')
    out_cpp.write( f'FZ_FUNCTION std::string to_string(const ::{struct_name}& s)\n')
    out_cpp.write( f'{{\n')
    out_cpp.write( f'    return to_string_{struct_name}(s);\n')
    out_cpp.write( f'}}\n')


def pod_struct_fns(
        tu,
        namespace,
        struct_cursor,
        struct_name,
        extras,
        out_h,
        out_cpp,
        ):
    '''
    Writes extra fns for POD structs - operator<<(), operator==(), operator!=().
    '''
    # Write operator<< functions for streaming text representation of C struct
    # members. We should be at top-level in out_h and out_cpp, i.e. not inside
    # 'namespace mupdf {...}'.
    out_h.write( f'\n')
    out_h.write( f'/** {struct_name}: writes members, labelled and inside (...), to a stream. */\n')
    out_h.write( f'FZ_FUNCTION std::ostream& operator<< (std::ostream& out, const ::{struct_name}& rhs);\n')

    out_cpp.write( f'\n')
    out_cpp.write( f'FZ_FUNCTION std::ostream& operator<< (std::ostream& out, const ::{struct_name}& rhs)\n')
    out_cpp.write( f'{{\n')
    i = 0
    out_cpp.write( f'    out\n')
    out_cpp.write( f'            << "("\n');
    for cursor in parse.get_members(struct_cursor):
        out_cpp.write( f'            << ');
        if i:
            out_cpp.write( f'" {cursor.spelling}="')
        else:
            out_cpp.write( f' "{cursor.spelling}="')
        out_cpp.write( f' << rhs.{cursor.spelling}\n')
        i += 1
    out_cpp.write( f'            << ")"\n');
    out_cpp.write( f'            ;\n')
    out_cpp.write( f'    return out;\n')
    out_cpp.write( f'}}\n')

    # Write comparison fns.
    out_h.write( f'\n')
    out_h.write( f'/** {struct_name}: comparison function. */\n')
    out_h.write( f'FZ_FUNCTION bool operator==( const ::{struct_name}& lhs, const ::{struct_name}& rhs);\n')
    out_h.write( f'\n')
    out_h.write( f'/** {struct_name}: comparison function. */\n')
    out_h.write( f'FZ_FUNCTION bool operator!=( const ::{struct_name}& lhs, const ::{struct_name}& rhs);\n')

    out_cpp.write( f'\n')
    out_cpp.write( f'FZ_FUNCTION bool operator==( const ::{struct_name}& lhs, const ::{struct_name}& rhs)\n')
    out_cpp.write( f'{{\n')
    for cursor in parse.get_members(struct_cursor):
        out_cpp.write( f'    if (lhs.{cursor.spelling} != rhs.{cursor.spelling}) return false;\n')
    out_cpp.write( f'    return true;\n')
    out_cpp.write( f'}}\n')
    out_cpp.write( f'FZ_FUNCTION bool operator!=( const ::{struct_name}& lhs, const ::{struct_name}& rhs)\n')
    out_cpp.write( f'{{\n')
    out_cpp.write( f'    return !(lhs == rhs);\n')
    out_cpp.write( f'}}\n')


def pod_class_fns(
        tu,
        classname,
        struct_cursor,
        struct_name,
        extras,
        out_h,
        out_cpp,
        ):
    '''
    Writes extra fns for wrappers for POD structs - operator<<(), operator==(),
    operator!=().
    '''
    # Write functions for text representation of wrapper-class members. These
    # functions make use of the corresponding struct functions created by
    # struct_to_string_fns().
    #
    assert extras.pod != 'none'
    classname = f'mupdf::{classname}'
    out_h.write( f'\n')
    out_h.write( f'/** {classname}: writes underlying {struct_name}\'s members, labelled and inside (...), to a stream. */\n')
    out_h.write( f'FZ_FUNCTION std::ostream& operator<< (std::ostream& out, const {classname}& rhs);\n')

    out_cpp.write( f'\n')
    out_cpp.write( f'FZ_FUNCTION std::ostream& operator<< (std::ostream& out, const {classname}& rhs)\n')
    out_cpp.write( f'{{\n')
    if extras.pod == 'inline':
        out_cpp.write( f'    return out << *rhs.internal();\n')
    elif extras.pod:
        out_cpp.write( f'    return out << rhs.m_internal;\n')
    else:
        out_cpp.write( f'    return out << " " << *rhs.m_internal;\n')
    out_cpp.write( f'}}\n')

    # Write comparison fns, using comparison of underlying MuPDF struct.
    out_h.write( f'\n')
    out_h.write( f'/** {classname}: comparison function. */\n')
    out_h.write( f'FZ_FUNCTION bool operator==( const {classname}& lhs, const {classname}& rhs);\n')
    out_h.write( f'\n')
    out_h.write( f'/** {classname}: comparison function. */\n')
    out_h.write( f'FZ_FUNCTION bool operator!=( const {classname}& lhs, const {classname}& rhs);\n')

    out_cpp.write( f'\n')
    out_cpp.write( f'FZ_FUNCTION bool operator==( const {classname}& lhs, const {classname}& rhs)\n')
    out_cpp.write( f'{{\n')
    if extras.pod == 'inline':
        out_cpp.write( f'    return *lhs.internal() == *rhs.internal();\n')
    else:
        out_cpp.write( f'    return lhs.m_internal == rhs.m_internal;\n')
    out_cpp.write( f'}}\n')

    out_cpp.write( f'\n')
    out_cpp.write( f'FZ_FUNCTION bool operator!=( const {classname}& lhs, const {classname}& rhs)\n')
    out_cpp.write( f'{{\n')
    if extras.pod == 'inline':
        out_cpp.write( f'    return *lhs.internal() != *rhs.internal();\n')
    else:
        out_cpp.write( f'    return lhs.m_internal != rhs.m_internal;\n')
    out_cpp.write( f'}}\n')


def get_struct_fnptrs( cursor_struct, shallow_typedef_expansion=False, verbose=False):
    '''
    Yields (cursor, fnptr_type) for function-pointer members of struct defined
    at cusor, where <cursor> is the cursor of the member and <fntr_type> is the
    type.

    cursor_struct:
        Cursor for definition of struct; this can be a typedef.
    shallow_typedef_expansion:
        If true, the returned <fnptr_type> has any top-level typedefs resolved
        so will be a clang.cindex.TypeKind.FUNCTIONPROTO, but typedefs within
        the function args are not resolved, e.g. they can be size_t. This can
        be useful when generating code that will be compiled on different
        platforms with differing definitions of size_t.
    '''
    if verbose:
        jlib.log('Looking for fnptrs in {cursor_struct.spelling=}')
    for cursor in parse.get_members(cursor_struct):
        t = cursor.type
        if verbose:
            jlib.log('{t.kind=} {cursor.spelling=}')
        if t.kind == state.clang.cindex.TypeKind.POINTER:
            t = cursor.type.get_pointee()
            if t.kind in (state.clang.cindex.TypeKind.TYPEDEF, state.clang.cindex.TypeKind.ELABORATED):
                t_cursor = t.get_declaration()
                t = t_cursor.underlying_typedef_type
            if t.kind == state.clang.cindex.TypeKind.FUNCTIONPROTO:
                if shallow_typedef_expansion:
                    if verbose:
                        jlib.log('Not calling state.get_name_canonical() for {t.spelling=}. {cursor.spelling=}.')
                else:
                    tt = state.get_name_canonical( t)
                    if verbose:
                        jlib.log('{tt.spelling=}')
                    if (0
                            or 'struct (unnamed at ' in tt.spelling
                            or 'unnamed struct at ' in tt.spelling
                            ):

                        # This is clang giving an unhelpful name to an
                        # anonymous struct.
                        if verbose:
                            jlib.log( 'Avoiding clang anonymous struct placeholder: {tt.spelling=}')
                    else:
                        t = tt
                if verbose:
                    jlib.log('Yielding: {cursor.spelling=} {t.spelling=}')
                yield cursor, t


def class_wrapper_virtual_fnptrs(
        tu,
        struct_cursor,
        struct_name,
        classname,
        extras,
        out_h,
        out_cpp,
        out_h_end,
        generated,
        refcheck_if,
        trace_if,
        ):
    '''
    Generate extra wrapper class if struct contains function pointers, for
    use as a SWIG Director class so that the function pointers can be made to
    effectively point to Python or C# code.
    '''
    if not extras.virtual_fnptrs:
        return
    verbose = state.state_.show_details( struct_name)
    generated.virtual_fnptrs.append( f'{classname}2')

    self_ = extras.virtual_fnptrs.pop( 'self_')
    self_n = extras.virtual_fnptrs.pop( 'self_n', 1)
    alloc = extras.virtual_fnptrs.pop( 'alloc')
    free = extras.virtual_fnptrs.pop( 'free', None)
    comment = extras.virtual_fnptrs.pop( 'comment', None)
    assert not extras.virtual_fnptrs, f'Unused items in virtual_fnptrs: {extras.virtual_fnptrs}'

    # Class definition beginning.
    #
    out_h.write( '\n')
    out_h.write( f'/** Wrapper class for struct {struct_name} with virtual fns for each fnptr; this is for use as a SWIG Director class. */\n')
    if comment:
        out_h.write(comment)
    out_h.write( f'struct {classname}2 : {classname}\n')
    out_h.write(  '{\n')

    out_cpp.write( f'/* Implementation of methods for `{classname}2`, virtual_fnptrs wrapper for `{struct_name}`). */\n')
    out_cpp.write( '\n')

    def get_fnptrs( shallow_typedef_expansion=False):
        for i in get_struct_fnptrs( struct_cursor, shallow_typedef_expansion, verbose=verbose):
            yield i

    # Constructor
    #
    out_h.write( '\n')
    out_h.write( '    /** == Constructor. */\n')
    out_h.write(f'    FZ_FUNCTION {classname}2();\n')
    out_cpp.write('\n')
    out_cpp.write(f'FZ_FUNCTION {classname}2::{classname}2()\n')
    out_cpp.write( '{\n')
    alloc = [''] + alloc.split('\n')
    alloc = '\n    '.join(alloc)
    out_cpp.write(f'{alloc}\n')
    out_cpp.write(f'    {trace_if}\n')
    out_cpp.write(f'    if (s_trace_director)\n')
    out_cpp.write( '    {\n')
    out_cpp.write(f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << ": {classname}2::{classname}2(): this=" << this << "\\n";\n')
    if not extras.pod:
        out_cpp.write(f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << ": {classname}2::{classname}2(): m_internal=" << m_internal << "\\n";\n')
        out_cpp.write(f'        {classname}2* self = {self_("m_internal")};\n')
        out_cpp.write(f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << ": {classname}2::{classname}2(): self=" << self << "\\n";\n')
    out_cpp.write('    }\n')
    out_cpp.write('    #endif\n')
    out_cpp.write( '}\n')

    # Destructor. This needs to be virtual with an empty implementation,
    # because instances will generally be derived classes.
    out_h.write( '\n')
    out_h.write( '    /** == Destructor. */\n')
    out_h.write(f'    FZ_FUNCTION virtual ~{classname}2();\n')
    out_cpp.write('\n')
    out_cpp.write(f'FZ_FUNCTION {classname}2::~{classname}2()\n')
    out_cpp.write( '{\n')
    out_cpp.write(f'    {trace_if}\n')
    out_cpp.write(f'    if (s_trace_director)\n')
    out_cpp.write( '    {\n')
    out_cpp.write(f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << ": ~{classname}2(): this=" << this << "\\n";\n')
    if not extras.pod:
        out_cpp.write( f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << ": ~{classname}2(): m_internal=" << m_internal << "\\n";\n')
    out_cpp.write( '    }\n')
    out_cpp.write(f'    #endif\n')
    if free:
        out_cpp.write(f'    {free}\n')
    out_cpp.write( '}\n')

    def write(text):
        out_h.write(text)
        out_cpp.write(text)

    # Define static callback for each fnptr. It's important that these
    # functions do not resolve function parameter typedefs such as size_t to
    # the underlying types such as long int, because:
    #
    #   * Our generated code can be compiled on different machines where types
    #   such as size_t can be typedef-ed differently.
    #
    #   * Elsewhere, code that we generate will assign our static callback
    #   functions to MuPDF's function pointers (which use things like size_t).
    #
    #   * These assignments will fail if the types don't match exactly.
    #
    # For example fz_output has a member:
    #   fz_output_write_fn *write;
    #
    # This typedef is:
    #   void (fz_output_write_fn)(fz_context *ctx, void *state, const void *data, size_t n);
    #
    # We generate a static function called Output2_s_write() and we will be
    # setting a fz_output's write member to point to Output2_s_write(), which
    # only works if the types match exactly.
    #
    # So we need to resolve the outer 'typedef fz_output_write_fn', but not
    # the inner 'size_t' typedef for the <n> arg. This is slightly tricky with
    # clang-python - it provide a Type.get_canonical() method that resolves all
    # typedefs, but to resolve just one level of typedefs requires a bit more
    # work. See get_struct_fnptrs() for details.
    #
    # [Usually our generated code deliberately resolves typedefs such as size_t
    # to long int etc, because SWIG-generated code for size_t etc does not
    # always work properly due to SWIG having its own definitions of things
    # like size_t in Python/C#. But in this case the generated static function
    # is not seen by SWIG so it's ok to make it use size_t etc.]
    #
    for cursor, fnptr_type in get_fnptrs( shallow_typedef_expansion=True):

        # Write static callback.
        return_type = _make_top_level(fnptr_type.get_result().spelling)
        out_cpp.write(f'/* Static callback, calls self->{cursor.spelling}(). */\n')
        out_cpp.write(f'static {return_type} {classname}2_s_{cursor.spelling}')
        out_cpp.write('(')
        sep = ''
        for i, arg_type in enumerate( fnptr_type.argument_types()):
            name = f'arg_{i}'
            out_cpp.write(sep)
            out_cpp.write( declaration_text( arg_type, name, expand_typedef=False))
            sep = ', '
        out_cpp.write(')')
        out_cpp.write('\n')
        out_cpp.write('{\n')
        self_expression = self_() if self_n is None else self_( f'arg_{self_n}')
        out_cpp.write(f'    {classname}2* self = {self_expression};\n')
        out_cpp.write(f'    {trace_if}\n')
        out_cpp.write(f'    if (s_trace_director)\n')
        out_cpp.write( '    {\n')
        out_cpp.write(f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << ": {classname}2_s_{cursor.spelling}(): arg_0=" << arg_0 << " arg_1=" << arg_1 << " self=" << self << "\\n";\n')
        out_cpp.write( '    }\n')
        out_cpp.write( '    #endif\n')
        out_cpp.write( '    {\n')
        out_cpp.write( '        char error_message[256] = "";\n')
        out_cpp.write( '        try\n')
        out_cpp.write( '        {\n')
        out_cpp.write(f'            return self->{cursor.spelling}(')
        sep = ''
        for i, arg_type in enumerate( fnptr_type.argument_types()):
            if i == self_n:
                # This is the void* from which we found `self` so ignore
                # here. Note that we still pass the fz_context to the virtual
                # fn.
                continue
            name = f'arg_{i}'
            out_cpp.write( f'{sep}{name}')
            sep = ', '
        out_cpp.write(');\n')
        out_cpp.write('        }\n')

        # todo: catch our different exception types and map to FZ_ERROR_*.
        out_cpp.write( '        catch (std::exception& e)\n')
        out_cpp.write( '        {\n')
        out_cpp.write(f'            {trace_if}\n')
        out_cpp.write( '            if (s_trace_director)\n')
        out_cpp.write( '            {\n')
        out_cpp.write(f'                std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << ": {classname}2_s_{cursor.spelling}(): converting std::exception to fz_throw(): " << e.what() << "\\n";\n')
        out_cpp.write( '            }\n')
        out_cpp.write( '            #endif\n')
        out_cpp.write( '            fz_strlcpy(error_message, e.what(), sizeof(error_message));\n')
        out_cpp.write( '        }\n')
        out_cpp.write( '        /* We defer fz_throw() to here, to ensure that `std::exception& e` has been destructed. */\n')
        out_cpp.write( '        fz_throw(arg_0, FZ_ERROR_GENERIC, "%s", error_message);\n')
        if return_type != 'void':
            out_cpp.write(f'        /* Keep compiler happy. */\n')
            out_cpp.write(f'        {return_type} ret;\n')
            out_cpp.write(f'        return ret;\n')
        out_cpp.write( '    }\n')
        out_cpp.write('}\n')

    # Define use_virtual_<name>( bool use) method for each fnptr.
    #
    out_h.write(f'\n')
    # Using a Doxygen-style `/**` comment prefix here can break swig with
    # `Error: Syntax error in input(3).` if there are no following method
    # declarations.
    out_h.write(f'    /** These methods set the function pointers in *m_internal\n')
    out_h.write(f'    to point to internal callbacks that call our virtual methods. */\n')
    for cursor, fnptr_type in get_fnptrs():
        out_h.write(f'    FZ_FUNCTION void use_virtual_{cursor.spelling}( bool use=true);\n')
        out_cpp.write(f'FZ_FUNCTION void {classname}2::use_virtual_{cursor.spelling}( bool use)\n')
        out_cpp.write( '{\n')

        out_cpp.write(f'    {trace_if}\n')
        out_cpp.write(f'    if (s_trace_director)\n')
        out_cpp.write( '    {\n')
        out_cpp.write(f'        std::cerr << __FILE__ << ":" << __LINE__ << ":" << __FUNCTION__ << ": {classname}2::use_virtual_{cursor.spelling}(): this=" << this << " use=" << use << "\\n";\n')
        out_cpp.write( '    }\n')
        out_cpp.write( '    #endif\n')

        if extras.pod == 'inline':
            # Fnptr (in {classname}2) and virtual function (in {classname})
            # have same name, so we need qualify the fnptr with {classname} to
            # ensure we distinguish between the two.
            out_cpp.write(f'    {classname}::{cursor.spelling} = (use) ? {classname}2_s_{cursor.spelling} : nullptr;\n')
        elif extras.pod:
            out_cpp.write(f'    m_internal.{cursor.spelling} = (use) ? {classname}2_s_{cursor.spelling} : nullptr;\n')
        else:
            out_cpp.write(f'    m_internal->{cursor.spelling} = (use) ? {classname}2_s_{cursor.spelling} : nullptr;\n')
        out_cpp.write( '}\n')

    # Write virtual fn default implementations.
    #
    out_h.write(f'\n')

    # Using a Doxygen-style `/**` comment prefix here can break swig with
    # `Error: Syntax error in input(3).` if there are no following method
    # declarations.
    out_h.write(f'    /** Default virtual method implementations; these all throw an exception. */\n')
    for cursor, fnptr_type in get_fnptrs():

        out_h.write(f'    FZ_FUNCTION virtual {_make_top_level(fnptr_type.get_result().spelling)} {cursor.spelling}(')
        out_cpp.write(f'/* Default implementation of virtual method. */\n')
        out_cpp.write(f'FZ_FUNCTION {_make_top_level(fnptr_type.get_result().spelling)} {classname}2::{cursor.spelling}(')
        sep = ''
        for i, arg_type in enumerate( fnptr_type.argument_types()):
            if i == self_n:
                # This is the void* from which we found `self` so ignore
                # here. Note that we still pass the fz_context to the virtual
                # fn.
                continue
            name = f'arg_{i}'
            write(f'{sep}')
            decl_text = declaration_text(arg_type, name, verbose=0)
            write(decl_text)
            sep = ', '
        out_h.write( ');\n')
        out_cpp.write( ')\n')
        out_cpp.write( '{\n')
        out_cpp.write(f'    std::cerr << "Unexpected call of unimplemented virtual_fnptrs fn {classname}2::{cursor.spelling}(): this=" << this << ".\\n";\n')
        out_cpp.write(f'    throw std::runtime_error( "Unexpected call of unimplemented virtual_fnptrs fn {classname}2::{cursor.spelling}()");\n')
        out_cpp.write( '}\n')

    out_h.write(  '};\n')


def class_wrapper(
        tu,
        register_fn_use,
        struct_cursor,
        struct_name,
        classname,
        extras,
        out_h,
        out_cpp,
        out_h_end,
        out_cpp2,
        out_h2,
        generated,
        refcheck_if,
        trace_if,
        ):
    '''
    Creates source for a class called <classname> that wraps <struct_name>,
    with methods that call selected fz_*() functions. Writes to out_h and
    out_cpp.

    Created source is just the per-class code, e.g. it does not contain
    #include's.

    Args:
        tu:
            Clang translation unit.
        struct_cursor:
            Cursor for struct to wrap.
        struct_name:
            Name of struct to wrap.
        classname:
            Name of wrapper class to create.
        out_h:
            Stream to which we write class definition.
        out_cpp:
            Stream to which we write method implementations.
        out_h_end:
            Stream for text that should be put at the end of the generated
            header text.
        generated:
            We write extra python and C# code to generated.out_swig_python and
            generated.out_swig_csharp for use in the swig .i file.

    Returns (is_container, has_to_string). <is_container> is true if generated
    class has custom begin() and end() methods; <has_to_string> is true if we
    have created a to_string() method.
    '''
    assert extras, f'extras is None for {struct_name}'
    if extras.iterator_next:
        class_add_iterator( tu, struct_cursor, struct_name, classname, extras, refcheck_if, trace_if)

    if extras.class_pre:
        out_h.write( textwrap.dedent( extras.class_pre))

    base_name = util.clip( struct_name, ('fz_', 'pdf_'))

    constructor_fns = class_find_constructor_fns( tu, classname, struct_name, base_name, extras)
    for fnname in extras.constructors_wrappers:
        cursor = state.state_.find_function( tu, fnname, method=True)
        assert cursor, f'No cursor for constructor wrapper fnname={fnname}'
        constructor_fns.append( (fnname, cursor, None))

    destructor_fns = class_find_destructor_fns( tu, struct_name, base_name)

    # Class definition beginning.
    #
    out_h.write( '\n')
    if extras.copyable:
        out_h.write( f'/** Wrapper class for struct `{struct_name}`. */\n')
    else:
        out_h.write( f'/** Wrapper class for struct `{struct_name}`. Not copyable or assignable. */\n')
    if struct_cursor.raw_comment:
        raw_comment = struct_cursor.raw_comment.replace('\r', '')
        out_h.write(raw_comment)
        if not raw_comment.endswith( '\n'):
            out_h.write( '\n')
    out_h.write( f'struct {classname}\n{{')

    out_cpp.write( '\n')
    out_cpp.write( f'/* Implementation of methods for {classname} (wrapper for {struct_name}). */\n')
    out_cpp.write( '\n')
    refs = parse.has_refs( tu, struct_cursor.type)
    if refs:
        refs_name, refs_size = refs
        out_cpp.write( f'{refcheck_if}\n')
        if isinstance(refs_name, int):
            # <refs_name> is offset of .refs in the struct.
            allow_int_this = ', true /*allow_int_this*/' if struct_name == 'pdf_obj' else ''
            out_cpp.write( f'static RefsCheck<::{struct_name}, {classname}{allow_int_this}> s_{classname}_refs_check({refs_name}, {refs_size});\n')
        else:
            # <refs_name> is name of .refs in the struct.
            out_cpp.write( f'static RefsCheck<::{struct_name}, {classname}> s_{classname}_refs_check(offsetof(::{struct_name}, {refs_name}), {refs_size});\n')
        out_cpp.write( f'#endif\n')
        out_cpp.write( '\n')

    # Trailing text in header, e.g. typedef for iterator.
    #
    if extras.class_top:
        # Strip leading blank line to avoid slightly odd-looking layout.
        text = util.clip( extras.class_top, '\n')
        text = textwrap.dedent( text)
        text = textwrap.indent( text, '    ')
        out_h.write( '\n')
        out_h.write( text)

    # Constructors
    #
    num_constructors = 0
    have_created_default_constructor = False

    if constructor_fns:
        out_h.write( '\n')
        out_h.write( '    /** == Constructors. */\n')
    num_constructors += len(constructor_fns)
    for fnname, cursor, duplicate_type in constructor_fns:
        # clang-6 appears not to be able to handle fn args that are themselves
        # function pointers, so for now we allow function_wrapper() to fail,
        # so we need to use temporary buffers, otherwise out_functions_h and
        # out_functions_cpp can get partial text written.
        #
        assert cursor, f'No cursor for constructor function. fnname={fnname} duplicate_type={duplicate_type}'
        temp_out_h = io.StringIO()
        temp_out_cpp = io.StringIO()
        if state.state_.show_details(fnname):
            jlib.log('Creating constructor for {=classname fnname}')
        if parse.get_first_arg( tu, cursor) == (None, 0):
            have_created_default_constructor = True
        try:
            function_wrapper_class_aware(
                    tu,
                    register_fn_use,
                    fnname,
                    temp_out_h,
                    temp_out_cpp,
                    struct_name,
                    classname,
                    cursor,
                    refcheck_if,
                    trace_if,
                    class_static=False,
                    class_constructor=True,
                    extras=extras,
                    struct_cursor=struct_cursor,
                    duplicate_type=duplicate_type,
                    )
        except Clang6FnArgsBug as e:
            jlib.log( 'Unable to wrap function {fnname} because: {e}')
        else:
            out_h.write( temp_out_h.getvalue())
            out_cpp.write( temp_out_cpp.getvalue())

    # Custom constructors.
    #
    for extra_constructor in extras.constructors_extra:
        if extra_constructor.name_args == '()':
            have_created_default_constructor = True
        class_custom_method(
                tu,
                register_fn_use,
                struct_cursor,
                classname,
                extra_constructor,
                out_h,
                out_cpp,
                refcheck_if,
                trace_if,
                )
        num_constructors += 1

    # Look for function that can be used by copy constructor and operator=.
    #
    if refs:
        assert extras.copyable != 'default', f'Non-POD class for {struct_name=} has refs, so must not use copyable="default"'

    if not extras.pod and extras.copyable and extras.copyable != 'default':
        class_copy_constructor(
                tu,
                register_fn_use,
                struct_name,
                struct_cursor,
                base_name,
                classname,
                constructor_fns,
                out_h,
                out_cpp,
                refcheck_if,
                trace_if,
                )
    elif extras.copyable:
        out_h.write( '\n')
        out_h.write( '    /** We use default copy constructor and operator=. */\n')

    if extras.constructor_default:
        if have_created_default_constructor:
            if 0:
                jlib.log( 'Not creating default constructor because default custom constructor. {struct_name=}')
        elif extras.constructor_raw == 'default':
            if 0:
                jlib.log( 'Not creating default constructor because default raw constructor. {struct_name=}')
        else:
            class_constructor_default(
                    tu,
                    struct_cursor,
                    classname,
                    extras,
                    out_h,
                    out_cpp,
                    refcheck_if,
                    trace_if,
                    )
            num_constructors += 1

    # Auto-add all methods that take <struct_name> as first param, but
    # skip methods that are already wrapped in extras.method_wrappers or
    # extras.methods_extra etc.
    #
    for fnname in parse.find_wrappable_function_with_arg0_type( tu, struct_name):
        if state.state_.show_details(fnname):
            jlib.log('{struct_name=}: looking at potential method wrapping {fnname=}')
        if fnname in extras.method_wrappers:
            #log( 'auto-detected fn already in {struct_name} method_wrappers: {fnname}')
            # Omit this function, because there is an extra method with the
            # same name. (We could probably include both as they will generally
            # have different args so overloading will distinguish them, but
            # extra methods are usually defined to be used in preference.)
            pass
        elif fnname.startswith( 'fz_new_draw_device'):
            # fz_new_draw_device*() functions take first arg fz_matrix, but
            # aren't really appropriate for the fz_matrix wrapper class.
            #
            pass
        elif isinstance( fnname, list):
            assert 0
        else:
            for extramethod in extras.methods_extra:
                if not extramethod.overload:
                    if extramethod.name_args.startswith( f'{rename.method( struct_name, fnname)}('):
                        jlib.log1( 'Omitting default method because same name as extramethod: {extramethod.name_args}')
                        break
            else:
                #log( 'adding to extras.method_wrappers: {fnname}')
                extras.method_wrappers.append( fnname)

    # Extra static methods.
    #
    if extras.method_wrappers_static:
        out_h.write( '\n')
        out_h.write( '    /* == Static methods. */\n')
    for fnname in extras.method_wrappers_static:
        function_wrapper_class_aware(
                tu,
                register_fn_use,
                fnname,
                out_h,
                out_cpp,
                struct_name,
                classname,
                fn_cursor=None,
                refcheck_if=refcheck_if,
                trace_if=trace_if,
                class_static=True,
                struct_cursor=struct_cursor,
                generated=generated,
                )

    # Extra methods that wrap fz_*() fns.
    #
    if extras.method_wrappers or extras.methods_extra:
        out_h.write( '\n')
        out_h.write( '    /* == Methods. */')
        out_h.write( '\n')
    extras.method_wrappers.sort()
    for fnname in extras.method_wrappers:
        function_wrapper_class_aware(
                tu,
                register_fn_use,
                fnname,
                out_h,
                out_cpp,
                struct_name,
                classname,
                None, #fn_cursor
                refcheck_if,
                trace_if,
                struct_cursor=struct_cursor,
                generated=generated,
                debug=state.state_.show_details(fnname),
                )

    # Custom methods.
    #
    is_container = 0
    custom_destructor = False
    for extramethod in extras.methods_extra:
        is_constructor, is_destructor, is_begin_end = class_custom_method(
                tu,
                register_fn_use,
                struct_cursor,
                classname,
                extramethod,
                out_h,
                out_cpp,
                refcheck_if,
                trace_if,
                )
        if is_constructor:
            num_constructors += 1
        if is_destructor:
            custom_destructor = True
        if is_begin_end:
            is_container += 1

    assert is_container==0 or is_container==2, f'struct_name={struct_name} is_container={is_container}'   # Should be begin()+end() or neither.
    if is_container:
        pass
        #jlib.log( 'Generated class has begin() and end(): {classname=}')

    if num_constructors == 0 or extras.constructor_raw:
        if state.state_.show_details(struct_name):
            jlib.log('calling class_raw_constructor(). {struct_name=}')
        class_raw_constructor(
                tu,
                register_fn_use,
                classname,
                struct_cursor,
                struct_name,
                base_name,
                extras,
                constructor_fns,
                out_h,
                out_cpp,
                refcheck_if,
                trace_if,
                )

    # Accessor methods to POD data.
    #
    if extras.accessors and extras.pod == 'inline':
        jlib.log( 'ignoring {extras.accessors=} for {struct_name=} because {extras.pod=}.')
    elif extras.accessors:
        out_h.write( f'\n')
        out_h.write( f'    /* == Accessors to members of ::{struct_name} m_internal. */\n')
        out_h.write( '\n')
        class_accessors(
                tu,
                register_fn_use,
                classname,
                struct_cursor,
                struct_name,
                extras,
                out_h,
                out_cpp,
                )

    # Destructor.
    #
    if not custom_destructor:
        out_h.write( f'\n')
        class_destructor(
                tu,
                register_fn_use,
                classname,
                extras,
                struct_cursor,
                destructor_fns,
                out_h,
                out_cpp,
                refcheck_if,
                trace_if,
                )

    # If class has '{structname}* m_internal;', provide access to m_iternal as
    # an integer, for use by python etc, and provide `operator bool()`.
    if not extras.pod:
        class_custom_method(
                tu,
                register_fn_use,
                struct_cursor,
                classname,
                classes.ExtraMethod(
                    'long long',
                    'm_internal_value()',
                    '''
                    {
                        return (uintptr_t) m_internal;
                    }
                    ''',
                    '/** Return numerical value of .m_internal; helps with Python debugging. */',
                    ),
                out_h,
                out_cpp,
                refcheck_if,
                trace_if,
                )
        class_custom_method(
                tu,
                register_fn_use,
                struct_cursor,
                classname,
                classes.ExtraMethod(
                    '',
                    'operator bool()',
                    f'''
                    {{
                        {trace_if}
                        if (s_trace)
                        {{
                            std::cerr << __FILE__ << ":" << __LINE__ << ":"
                                    << " {classname}::operator bool() called,"
                                    << " m_internal=" << m_internal << "."
                                    << "\\n";
                        }}
                        #endif
                        return m_internal ? true : false;
                    }}
                    ''',
                    '/** Return true iff `m_internal` is not null. */',
                    ),
                out_h,
                out_cpp,
                refcheck_if,
                trace_if,
                )

    # Class members.
    #
    out_h.write( '\n')
    out_h.write( '    /* == Member data. */\n')
    out_h.write( '\n')
    if extras.pod == 'none':
        pass
    elif extras.pod == 'inline':
        out_h.write( f'    /* These members are the same as the members of ::{struct_name}. */\n')
        for c in parse.get_members(struct_cursor):
            out_h.write( f'    {declaration_text(c.type, c.spelling)};\n')
    elif extras.pod:
        out_h.write( f'    ::{struct_cursor.spelling}  m_internal; /** Wrapped data is held by value. */\n')
    else:
        # Putting this double-asterix comment on same line as m_internal breaks
        # swig-4.02 with "Error: Syntax error in input(3).".
        out_h.write( f'    /** Pointer to wrapped data. */\n')
        out_h.write( f'    ::{struct_name}* m_internal;\n')

    # Declare static `num_instances` variable.
    out_h.write(  '\n')
    out_h.write(f'    /* Ideally this would be in `{refcheck_if}...#endif`, but Swig will\n')
    out_h.write(f'    generate code regardless so we always need to have this available. */\n')
    out_h.write(f'    FZ_DATA static int s_num_instances;\n')

    out_cpp.write(f'/* Ideally this would be in `{refcheck_if}...#endif`, but Swig will\n')
    out_cpp.write(f'generate code regardless so we always need to have this available. */\n')
    out_cpp.write(f'int {classname}::s_num_instances = 0;\n')
    out_cpp.write(f'\n')

    # Make operator<< (std::ostream&, ...) for POD classes.
    #
    has_to_string = False
    if extras.pod and extras.pod != 'none':
        has_to_string = True
        pod_class_members(
                tu,
                classname,
                struct_cursor,
                struct_name,
                extras,
                out_h,
                out_cpp,
                )

    # Trailing text in header, e.g. typedef for iterator.
    #
    if extras.class_bottom:
        out_h.write( textwrap.indent( textwrap.dedent( extras.class_bottom), '    '))

    # Private copy constructor if not copyable.
    #
    if not extras.copyable:
        out_h.write(  '\n')
        out_h.write(  '    private:\n')
        out_h.write(  '\n')
        out_h.write(  '    /** This class is not copyable or assignable. */\n')
        out_h.write( f'    {classname}(const {classname}& rhs);\n')
        out_h.write( f'    {classname}& operator=(const {classname}& rhs);\n')

    # Class definition end.
    #
    out_h.write( '};\n')

    if extras.class_post:
        out_h_end.write( textwrap.dedent( extras.class_post))

    if extras.extra_cpp:
        out_cpp.write( f'/* .extra_cpp for {struct_name}. */\n')
        out_cpp.write( textwrap.dedent( extras.extra_cpp))

    class_wrapper_virtual_fnptrs(
            tu,
            struct_cursor,
            struct_name,
            classname,
            extras,
            out_h,
            out_cpp,
            out_h_end,
            generated,
            refcheck_if,
            trace_if,
            )

    return is_container, has_to_string


def header_guard( name, out):
    '''
    Writes header guard for <name> to stream <out>.
    '''
    m = ''
    for c in name:
        m += c.upper() if c.isalnum() else '_'
    out.write( f'#ifndef {m}\n')
    out.write( f'#define {m}\n')
    out.write( '\n')


def tabify( filename, text):
    '''
    Returns <text> with leading multiples of 4 spaces converted to tab
    characters.
    '''
    ret = ''
    linenum = 0
    for line in text.split( '\n'):
        linenum += 1
        i = 0
        while 1:
            if i == len(line):
                break
            if line[i] != ' ':
                break
            i += 1
        if i % 4:
            if line[ int(i/4)*4:].startswith( ' *'):
                # This can happen in comments.
                pass
            else:
                jlib.log( '*** {filename}:{linenum}: {i=} {line!r=} indentation is not a multiple of 4')
        num_tabs = int(i / 4)
        ret += num_tabs * '\t' + line[ num_tabs*4:] + '\n'

    # We use [:-1] here because split() always returns extra last item '', so
    # we will have appended an extra '\n'.
    #
    return ret[:-1]


def refcount_check_code( out, refcheck_if):
    '''
    Writes reference count checking code to <out>.
    '''
    out.write( textwrap.dedent(
            f'''
            /* Support for checking that reference counts of underlying
            MuPDF structs are not smaller than the number of wrapper class
            instances. Enable at runtime by setting environmental variable
            MUPDF_check_refs to "1". */

            static const bool   s_check_refs = internal_env_flag("MUPDF_check_refs");

            /* For each MuPDF struct that has an 'int refs' member, we create
            a static instance of this class template with T set to our wrapper
            class, for example:

                static RefsCheck<fz_document, FzDocument> s_FzDocument_refs_check;

            Then if s_check_refs is true, constructor functions call .add(),
            the destructor calls .remove() and other class functions call
            .check(). This ensures that we check reference counting after each
            class operation.

            If <allow_int_this> is true, we allow _this->m_internal to be
            an invalid pointer less than 4096, in which case we don't try
            to check refs. This is used for pdf_obj because in Python the
            enums PDF_ENUM_NAME_* are converted to mupdf.PdfObj's contain
            .m_internal's which are the enum values cast to (for_pdf_obj*), so
            that they can be used directly.

            If m_size is -1, we don't attempt any checking; this is for fz_xml
            which is reference counted but does not have a simple .refs member.
            */
            {refcheck_if}
            template<typename Struct, typename ClassWrapper, bool allow_int_this=false>
            struct RefsCheck
            {{
                std::mutex              m_mutex;
                int                     m_offset;
                int                     m_size;
                std::map<Struct*, int>  m_this_to_num;

                RefsCheck(int offset, int size)
                : m_offset(offset), m_size(size)
                {{
                    assert(offset >= 0 && offset < 1000);
                    assert(m_size == 32 || m_size == 16 || m_size == 8 || m_size == -1);
                }}

                /* Called before keep/drop.

                Check that refs+delta and
                m_this_to_num[this_->m_internal]+delta are consistent. */
                void change( const ClassWrapper* this_, const char* file, int line, const char* fn, int delta)
                {{
                    assert( s_check_refs);
                    if (m_size == -1)
                    {{
                        /* No well-defined .refs member for us to check, e.g. fz_xml. */
                        return;
                    }}
                    if (!this_->m_internal) return;
                    if (allow_int_this)
                    {{
                        #if 0   // Historic diagnostics, might still be useful.
                        std::cerr << __FILE__ << ":" << __LINE__
                                << " " << file << ":" << line << ":" << fn << ":"
                                << " this_->m_internal=" << this_->m_internal
                                << "\\n";
                        #endif
                        if ((intptr_t) this_->m_internal < 4096)
                        {{
                            #if 0   // Historic diagnostics, might still be useful.
                            std::cerr << __FILE__ << ":" << __LINE__
                                    << " " << file << ":" << line << ":" << fn << ":"
                                    << " Ignoring this_->m_internal=" << this_->m_internal
                                    << "\\n";
                            #endif
                            return;
                        }}
                    }}
                    std::lock_guard< std::mutex> lock( m_mutex);
                    /* Our lock doesn't make our access to
                    this_->m_internal->refs thead-safe - other threads
                    could be modifying it via fz_keep_<Struct>() or
                    fz_drop_<Struct>(). But hopefully our read will be atomic
                    in practise anyway? */
                    void* refs_ptr = (char*) this_->m_internal + m_offset;
                    int refs;
                    if (m_size == 32)   refs = *(int32_t*) refs_ptr;
                    if (m_size == 16)   refs = *(int16_t*) refs_ptr;
                    if (m_size ==  8)   refs = *(int8_t* ) refs_ptr;
                    refs += delta;

                    int& n = m_this_to_num[ this_->m_internal];
                    int n_prev = n;
                    assert( n >= 0);
                    n += delta;
                    #if 0   // Historic diagnostics, might still be useful.
                    std::cerr << file << ":" << line << ":" << fn << "():"
                            // << " " << typeid(ClassWrapper).name() << ":"
                            << " this_=" << this_
                            << " this_->m_internal=" << this_->m_internal
                            << " refs=" << refs
                            << " n: " << n_prev << " => " << n
                            << "\\n";
                    #endif
                    if ( n < 0)
                    {{
                        #if 0   // Historic diagnostics, might still be useful.
                        std::cerr << file << ":" << line << ":" << fn << "():"
                                // << " " << typeid(ClassWrapper).name() << ":"
                                << " this_=" << this_
                                << " this_->m_internal=" << this_->m_internal
                                << " bad n: " << n_prev << " => " << n
                                << "\\n";
                        #endif
                        abort();
                    }}
                    if ( n && refs < n)
                    {{
                        #if 0   // Historic diagnostics, might still be useful.
                        std::cerr << file << ":" << line << ":" << fn << "():"
                                // << " " << typeid(ClassWrapper).name() << ":"
                                << " this_=" << this_
                                << " this_->m_internal=" << this_->m_internal
                                << " refs=" << refs
                                << " n: " << n_prev << " => " << n
                                << " refs mismatch (refs<n):"
                                << "\\n";
                        #endif
                        abort();
                    }}
                    if (n && ::abs( refs - n) > 1000)
                    {{
                        /* This traps case where n > 0 but underlying struct is
                        freed and .ref is set to bogus value by fz_free() or
                        similar. */
                        #if 0   // Historic diagnostics, might still be useful.
                        std::cerr << file << ":" << line << ":" << fn << "(): " << ": " << typeid(ClassWrapper).name()
                                << " bad change to refs."
                                << " this_=" << this_
                                << " refs=" << refs
                                << " n: " << n_prev << " => " << n
                                << "\\n";
                        #endif
                        abort();
                    }}
                    if (n == 0) m_this_to_num.erase( this_->m_internal);
                }}
                void add( const ClassWrapper* this_, const char* file, int line, const char* fn)
                {{
                    change( this_, file, line, fn, +1);
                }}
                void remove( const ClassWrapper* this_, const char* file, int line, const char* fn)
                {{
                    change( this_, file, line, fn, -1);
                }}
                void check( const ClassWrapper* this_, const char* file, int line, const char* fn)
                {{
                    change( this_, file, line, fn, 0);
                }}
            }};
            #endif

            '''
            ))

def cpp_source(
        dir_mupdf,
        namespace,
        base,
        header_git,
        generated,
        check_regress,
        clang_info_version,
        refcheck_if,
        trace_if,
        debug,
        ):
    '''
    Generates all .h and .cpp files.

    Args:

        dir_mupdf:
            Location of mupdf checkout.
        namespace:
            C++ namespace to use.
        base:
            Directory in which all generated files are placed.
        header_git:
            If true we include git info in the file comment that is written
            into all generated files.
        generated:
            A Generated instance.
        check_regress:
            If true, we raise exception if generated content differs from what
            is in existing files.
        refcheck_if:
            `#if ... ' text for enabling reference-checking code. For example
            `#if 1` to always enable, `#ifndef NDEBUG` to only enable in debug
            builds, `#if 0` to always disable.
        refcheck_if:
            `#if ... ' text for enabling optional runtime diagnostic, for
            example by setting `MuPDF_trace=1` runtime. For example `#if 1` to
            always enable, `#ifndef NDEBUG` to only enable in debug builds,
            `#if 0` to always disable.
        debug:
            True if debug build.

    Updates <generated> and returns <tu> from clang..
    '''
    assert isinstance(generated, Generated)
    assert not dir_mupdf.endswith( '/')
    assert not base.endswith( '/')

    # Do initial setting up of generated files before parse, because we include extra.h in our parse input.

    doit = True
    if doit:
        class File:
            def __init__( self, filename, tabify=True):
                self.filename = filename
                self.tabify = tabify
                self.file = io.StringIO()
                self.line_begin = True
                self.regressions = True
                self.closed = False
            def write( self, text, fileline=False):
                # Do not allow writes after .close().
                assert not self.closed, f'File.write() called after .close(). {self.filename=}'
                if fileline:
                    # Generate #line <line> "<filename>" for our caller's
                    # location. This makes any compiler warnings refer to their
                    # python code rather than the generated C++ code.
                    tb = traceback.extract_stack( None)
                    filename, line, function, source = tb[0]
                    if self.line_begin:
                        self.file.write( f'#line {line} "{filename}"\n')
                self.file.write( text)
                self.line_begin = text.endswith( '\n')
            def close( self):
                if self.closed:
                    # Allow multiple calls to .close().
                    return
                self.closed = True
                if self.filename:
                    # Overwrite if contents differ.
                    text = self.get()
                    if self.tabify:
                        text = tabify( self.filename, text)
                    cr = check_regress
                    jlib.log('calling util.update_file_regress() check_regress={cr}: {self.filename=}', 1)
                    e = util.update_file_regress( text, self.filename, check_regression=cr)
                    jlib.log('util.update_file_regress() returned => {e}', 1)
                    if e:
                        jlib.log('util.update_file_regress() => {e=}', 1)
                        self.regressions = True
                        jlib.log(f'File updated: {os.path.relpath(self.filename)}')
                    else:
                        jlib.log(f'File unchanged: {os.path.relpath(self.filename)}')
            def get( self):
                return self.file.getvalue()
    else:
        class File:
            def __init__( self, filename):
                pass
            def write( self, text, fileline=False):
                pass
            def close( self):
                pass

    class Outputs:
        '''
        A set of output files.

        For convenience, after outputs.add( 'foo', 'foo.c'), outputs.foo is a
        python stream that writes to 'foo.c'.
        '''
        def __init__( self):
            self.items = []

        def add( self, name, filename):
            '''
            Sets self.<name> to file opened for writing on <filename>.
            '''
            file = File( filename)
            self.items.append( (name, filename, file))
            setattr( self, name, file)

        def get( self):
            '''
            Returns list of (name, filename, file) tuples.
            '''
            return self.items

        def close( self):
            for name, filename, file in self.items:
                file.close()

    out_cpps = Outputs()
    out_hs = Outputs()
    for name in (
            'classes',
            'classes2',
            'exceptions',
            'functions',
            'internal',
            'extra',
            ):
        out_hs.add( name, f'{base}/include/mupdf/{name}.h')
        out_cpps.add( name, f'{base}/implementation/{name}.cpp')

    # Make text of header comment for all generated file.
    #
    header_text = textwrap.dedent(
            f'''
            /**
            This file was auto-generated by mupdfwrap.py.
            ''')

    if header_git:
        git_id = jlib.get_git_id( dir_mupdf, allow_none=True)
        if git_id:
            git_id = git_id.split('\n', 1)
            header_text += textwrap.dedent(
                    f'''
                    mupdf checkout:
                        {git_id[0]}'
                    ''')

    header_text += '*/\n'
    header_text += '\n'
    header_text = header_text[1:]   # Strip leading \n.
    for _, _, file in out_cpps.get() + out_hs.get():
        file.write( header_text)

    os.makedirs( f'{base}/include/mupdf', exist_ok=True)
    os.makedirs( f'{base}/implementation', exist_ok=True)

    num_regressions = 0
    # Create extra File that writes to internal buffer rather than an actual
    # file, which we will append to out_h.
    #
    out_h_classes_end = File( None)

    # Write multiple-inclusion guards into headers:
    #
    for name, filename, file in out_hs.get():
        prefix = f'{base}/include/'
        assert filename.startswith( prefix)
        name = filename[ len(prefix):]
        header_guard( name, file)

    # We need to write to out_hs.extra here before we do the parse
    # because out_hs.extra will be part of the input text passed to the
    # clang parser.
    #
    make_extra(out_hs.extra, out_cpps.extra)
    out_hs.extra.write( textwrap.dedent('''
            #endif
            '''))
    out_hs.extra.close()
    out_cpps.extra.close()

    # Now parse.
    #
    try:
        index = state.clang.cindex.Index.create()
    except Exception as e:
        raise Exception(f'libclang does not appear to be installed') from e

    header = f'{dir_mupdf}/include/mupdf/fitz.h'
    assert os.path.isfile( header), f'header={header}'

    # Get clang to parse mupdf/fitz.h and mupdf/pdf.h and mupdf/extra.h.
    #
    # It might be possible to use index.parse()'s <unsaved_files> arg to
    # specify these multiple files, but i couldn't get that to work.
    #
    # So instead we write some #include's to a temporary file and ask clang to
    # parse it.
    #
    temp_h = f'_mupdfwrap_temp.cpp'
    try:
        with open( temp_h, 'w') as f:
            if state.state_.linux or state.state_.macos:
                jlib.log1('Prefixing Fitz headers with `typedef unsigned long size_t;`'
                        ' because size_t not available to clang on Linux/MacOS.')
                # On Linux, size_t is defined internally in gcc (e.g. not even
                # in /usr/include/stdint.h) and so not visible to clang.
                #
                # If we don't define it, clang complains about C99 not
                # supporting implicit int and appears to variously expand
                # size_t as different function pointers, e.g. `int (int *)` and
                # `int (*)(int *)`.
                #
                f.write( textwrap.dedent('''
                    /*
                    Workaround on Linux/MacOS. size_t is defined internally in
                    gcc (e.g. not even in /usr/include/stdint.h) and so not visible to clang.
                    */
                    typedef unsigned long size_t;
                    '''))
            if state.state_.macos:
                f.write( textwrap.dedent('''
                    /*
                    Workaround on MacOS: we need to define fixed-size int types
                    and FILE and va_list, similarly as with size_t above.
                    */
                    typedef signed char         int8_t;
                    typedef short               int16_t;
                    typedef int                 int32_t;
                    typedef long long           int64_t;
                    typedef unsigned char       uint8_t;
                    typedef unsigned short      uint16_t;
                    typedef unsigned int        uint32_t;
                    typedef unsigned long long  uint64_t;
                    typedef struct FILE FILE;
                    typedef struct va_list va_list;
                    '''))
            f.write( textwrap.dedent('''
                    #include "mupdf/extra.h"

                    #include "mupdf/fitz.h"
                    #include "mupdf/pdf.h"
                    '''))

        # libclang often doesn't have access to system headers so we define
        # MUPDF_WRAP_LIBCLANG so that extra.h can use dummy definition of
        # std::vector.
        #
        args = [
                '-I', f'{dir_mupdf}/include',
                '-I', f'{dir_mupdf}/platform/c++/include',
                '-D', 'MUPDF_WRAP_LIBCLANG',
                '-D', 'FZ_FUNCTION=',
                ]
        tu = index.parse(
                temp_h,
                args = args,
                options = 0
                        | state.clang.cindex.TranslationUnit.PARSE_INCOMPLETE
                        | state.clang.cindex.TranslationUnit.PARSE_SKIP_FUNCTION_BODIES
                        ,
                )

        # Show warnings/errors from the parse. Failure to include stddef.h
        # appears to be harmless on Linux, but other failures seem to cause
        # more problems.
        #
        def show_clang_diagnostic( diagnostic, depth=0):
            for diagnostic2 in diagnostic.children:
                show_clang_diagnostic( diagnostic2, depth + 1)
            jlib.log1( '{" "*4*depth}{diagnostic}')
        if tu.diagnostics:
            jlib.log1( 'tu.diagnostics():')
            for diagnostic in tu.diagnostics:
                show_clang_diagnostic(diagnostic, 1)

    finally:
        if os.path.isfile( temp_h):
            os.remove( temp_h)

    # Write required #includes into .h files:
    #
    out_hs.exceptions.write( textwrap.dedent(
            '''
            #include <stdexcept>
            #include <string>

            #include "mupdf/fitz.h"

            '''))

    out_hs.internal.write( textwrap.dedent(
            '''
            #include <iostream>

            '''))

    out_hs.functions.write( textwrap.dedent(
            '''
            #include "mupdf/extra.h"

            #include "mupdf/fitz.h"
            #include "mupdf/pdf.h"

            #include <iostream>
            #include <string>
            #include <vector>

            '''))

    out_hs.classes.write( textwrap.dedent(
            '''
            #include "mupdf/fitz.h"
            #include "mupdf/functions.h"
            #include "mupdf/pdf.h"

            #include <map>
            #include <string>
            #include <vector>

            '''))

    out_hs.classes2.write( textwrap.dedent(
            '''
            #include "classes.h"

            '''))

    # Write required #includes into .cpp files:
    #
    out_cpps.exceptions.write( textwrap.dedent(
            f'''
            #include "mupdf/exceptions.h"
            #include "mupdf/fitz.h"
            #include "mupdf/internal.h"

            #include <iostream>

            #include <string.h>

            {trace_if}
                static const bool   s_trace_exceptions = mupdf::internal_env_flag("MUPDF_trace_exceptions");
            #else
                static const bool   s_trace_exceptions_dummy = mupdf::internal_env_flag_check_unset("{trace_if}", "MUPDF_trace_exceptions");
            #endif
            '''))

    out_cpps.functions.write( textwrap.dedent(
            '''
            #include "mupdf/exceptions.h"
            #include "mupdf/functions.h"
            #include "mupdf/internal.h"
            #include "mupdf/extra.h"

            #include <assert.h>
            #include <sstream>

            #include <string.h>

            '''))

    out_cpps.classes.write(
            textwrap.dedent(
            f'''
            #include "mupdf/classes.h"
            #include "mupdf/classes2.h"
            #include "mupdf/exceptions.h"
            #include "mupdf/internal.h"

            #include "mupdf/fitz/geometry.h"

            #include <algorithm>
            #include <map>
            #include <mutex>
            #include <sstream>
            #include <string.h>
            #include <thread>

            #include <string.h>

            {trace_if}
                static const int    s_trace = mupdf::internal_env_flag("MUPDF_trace");
                static const bool   s_trace_keepdrop = mupdf::internal_env_flag("MUPDF_trace_keepdrop");
                static const bool   s_trace_director = mupdf::internal_env_flag("MUPDF_trace_director");
            #else
                static const int    s_trace = mupdf::internal_env_flag_check_unset("{trace_if}", "MUPDF_trace");
                static const bool   s_trace_keepdrop = mupdf::internal_env_flag_check_unset("{trace_if}", "MUPDF_trace_keepdrop");
                static const bool   s_trace_director = mupdf::internal_env_flag_check_unset("{trace_if}", "MUPDF_trace_director");
            #endif
            '''))

    out_cpps.classes2.write(
            textwrap.dedent(
            f'''
            #include "mupdf/classes2.h"
            #include "mupdf/exceptions.h"
            #include "mupdf/internal.h"

            #include "mupdf/fitz/geometry.h"

            #include <map>
            #include <mutex>
            #include <sstream>
            #include <string.h>
            #include <thread>

            #include <string.h>

            {trace_if}
                static const int    s_trace = mupdf::internal_env_flag("MUPDF_trace");
            #else
                static const int    s_trace = mupdf::internal_env_flag_check_unset("{trace_if}", "MUPDF_trace");
            #endif
            '''))

    namespace = 'mupdf'
    for _, _, file in out_cpps.get() + out_hs.get():
        if file in (out_cpps.internal, out_cpps.extra, out_hs.extra):
            continue
        make_namespace_open( namespace, file)

    # Write reference counting check code to out_cpps.classes.
    refcount_check_code( out_cpps.classes, refcheck_if)

    # Write declaration and definition for metadata_keys global.
    #
    out_hs.functions.write(
            textwrap.dedent(
            '''
            /*
            The keys that are defined for fz_lookup_metadata().
            */
            FZ_DATA extern const std::vector<std::string> metadata_keys;

            '''))
    out_cpps.functions.write(
            textwrap.dedent(
            f'''
            FZ_FUNCTION const std::vector<std::string> metadata_keys = {{
                    "format",
                    "encryption",
                    "info:Title",
                    "info:Author",
                    "info:Subject",
                    "info:Keywords",
                    "info:Creator",
                    "info:Producer",
                    "info:CreationDate",
                    "info:ModDate",
            }};

            {trace_if}
                static const int    s_trace = internal_env_flag("MUPDF_trace");
                static const bool   s_trace_keepdrop = internal_env_flag("MUPDF_trace_keepdrop");
                static const bool   s_trace_exceptions = internal_env_flag("MUPDF_trace_exceptions");
                static const bool   s_check_error_stack = internal_env_flag("MUPDF_check_error_stack");
            #else
                static const int    s_trace = internal_env_flag_check_unset("{trace_if}", "MUPDF_trace");
                static const bool   s_trace_keepdrop = internal_env_flag_check_unset("{trace_if}", "MUPDF_trace_keepdrop");
                static const bool   s_trace_exceptions = internal_env_flag_check_unset("{trace_if}", "MUPDF_trace_exceptions");
                static const bool   s_check_error_stack = internal_env_flag_check_unset("{trace_if}", "MUPDF_check_error_stack");
            #endif

            '''))

    # Write source code for exceptions and wrapper functions.
    #
    jlib.log( 'Creating wrapper functions...')
    make_function_wrappers(
            tu,
            namespace,
            out_hs.exceptions,
            out_cpps.exceptions,
            out_hs.functions,
            out_cpps.functions,
            out_hs.internal,
            out_cpps.internal,
            out_hs.classes2,
            out_cpps.classes2,
            generated,
            refcheck_if,
            trace_if,
            )

    fn_usage = dict()
    functions_unrecognised = set()

    for fnname, cursor in state.state_.find_functions_starting_with( tu, '', method=True):
        fn_usage[ fnname] = [0, cursor]
        generated.c_functions.append(fnname)

    for structname, cursor in state.state_.structs[ tu].items():
        generated.c_structs.append( structname)

    # Create windows_mupdf.def, containing explicit exports for all MuPDF
    # global data and functions. We do this instead of explicitly prefixing
    # everything with FZ_FUNCTION or FZ_DATA in the MuPDF header files.
    #
    windows_def_path = os.path.relpath(f'{base}/windows_mupdf.def')
    windows_def = ''
    windows_def += 'EXPORTS\n'

    for name, cursor in state.state_.find_global_data_starting_with( tu, ('fz_', 'pdf_')):
        if state.state_.show_details(name):
            jlib.log('global: {name=}')
        generated.c_globals.append(name)
        windows_def += f'    {name} DATA\n'
    for fnname, cursor in state.state_.find_functions_starting_with( tu, ('fz_', 'pdf_', 'FT_'), method=False):
        if cursor.storage_class == state.clang.cindex.StorageClass.STATIC:
            # These fns do not work in windows.def, probably because they are
            # usually inline?
            #
            jlib.log('Not adding to windows_def because static: {fnname}()', 1)
        elif os.path.abspath(cursor.extent.start.file.name) == os.path.abspath(out_hs.extra.filename):
            # Items defined in out_hs.extra are C++ so we would need to use the
            # mangled name if we added them to windows_def. Instead they are
            # explicitly prefixed with `FZ_FUNCTION`.
            #
            # (We use os.path.abspath() to avoid problems with back and forward
            # slashes in cursor.extent.start.file.name on Windows.)
            #
            jlib.log1('Not adding to {windows_def_path} because defined in {os.path.relpath(out_hs.extra.filename)}: {cursor.spelling}')
        else:
            windows_def += f'    {fnname}\n'
    # Add some internal fns that PyMuPDF requires.
    for fnname in (
            'FT_Get_First_Char',
            'FT_Get_Next_Char',
            ):
        windows_def += f'    {fnname}\n'

    if debug:
        # In debug builds these are real fns, not macros, and we need to
        # make them exported.
        windows_def += f'    fz_lock_debug_lock\n'
        windows_def += f'    fz_lock_debug_unlock\n'

    jlib.fs_update( windows_def, windows_def_path)

    def register_fn_use( name):
        assert name.startswith( ('fz_', 'pdf_'))
        if name in fn_usage:
            fn_usage[ name][0] += 1
        else:
            functions_unrecognised.add( name)

    # Write source code for wrapper classes.
    #
    jlib.log( 'Creating wrapper classes...')

    # Find all classes that we can create.
    #
    classes_ = []
    for cursor in parse.get_children(tu.cursor):
        if not cursor.spelling.startswith( ('fz_', 'pdf_')):
            continue
        if cursor.kind != state.clang.cindex.CursorKind.TYPEDEF_DECL:
            continue;
        type_ = state.get_name_canonical( cursor.underlying_typedef_type)
        if type_.kind not in (state.clang.cindex.TypeKind.RECORD, state.clang.cindex.TypeKind.ELABORATED):
            continue
        if type_.kind == state.clang.cindex.TypeKind.ELABORATED:
            jlib.log( 'state.clang.cindex.TypeKind.ELABORATED: {type_.spelling=}')

        if not cursor.is_definition():
            # Handle abstract type only if we have an ClassExtra for it.
            extras = classes.classextras.get( tu, cursor.spelling)
            if extras and extras.opaque:
                pass
                #log( 'Creating wrapper for opaque struct: {cursor.spelling=}')
            else:
                continue

        #struct_name = type_.spelling
        struct_name = cursor.spelling
        struct_name = util.clip( struct_name, 'struct ')
        if cursor.spelling != struct_name:
            jlib.log('{type_.spelling=} {struct_name=} {cursor.spelling=}')
        classname = rename.class_( struct_name)

        # For some reason after updating mupdf 2020-04-13, clang-python is
        # returning two locations for struct fz_buffer_s, both STRUCT_DECL. One
        # is 'typedef struct fz_buffer_s fz_buffer;', the other is the full
        # struct definition.
        #
        # No idea why this is happening. Using .canonical doesn't seem to
        # affect things.
        #
        for cl, cu, s in classes_:
            if cl == classname:
                jlib.logx( 'ignoring duplicate STRUCT_DECL for {struct_name=}')
                break
        else:
            classes_.append( (classname, cursor, struct_name))

    classes_.sort()

    # Write forward declarations - this is required because some class
    # methods take pointers to other classes.
    #
    out_hs.classes.write( '\n')
    out_hs.classes.write( '/* Forward declarations of all classes that we define. */\n')
    for classname, struct_cursor, struct_name in classes_:
        out_hs.classes.write( f'struct {classname};\n')
    out_hs.classes.write( '\n')

    # Create each class.
    #
    for classname, struct_cursor, struct_name in classes_:
        #jlib.log( 'creating wrapper {classname} for {cursor.spelling}')
        extras = classes.classextras.get( tu, struct_name)
        assert extras, f'struct_name={struct_name}'
        if extras.pod:
            struct_to_string_fns(
                    tu,
                    struct_cursor,
                    struct_name,
                    extras,
                    out_hs.functions,
                    out_cpps.functions,
                    )

        with jlib.LogPrefixScope( f'{struct_name}: '):
            is_container, has_to_string = class_wrapper(
                    tu,
                    register_fn_use,
                    struct_cursor,
                    struct_name,
                    classname,
                    extras,
                    out_hs.classes,
                    out_cpps.classes,
                    out_h_classes_end,
                    out_cpps.classes2,
                    out_hs.classes2,
                    generated,
                    refcheck_if,
                    trace_if,
                    )
        if is_container:
            generated.container_classnames.append( classname)
        if has_to_string:
            generated.to_string_structnames.append( struct_name)

    out_hs.functions.write( textwrap.dedent( '''
            /** Reinitializes the MuPDF context for single-threaded use, which
            is slightly faster when calling code is single threaded.

            This should be called before any other use of MuPDF.
            */
            FZ_FUNCTION void reinit_singlethreaded();

            '''))

    # Generate num_instances diagnostic fn.
    out_hs.classes.write('\n')
    out_hs.classes.write('/** Returns map from class name (for example FzDocument) to s_num_instances. */\n')
    out_hs.classes.write('FZ_FUNCTION std::map<std::string, int> num_instances();\n')
    out_cpps.classes.write('FZ_FUNCTION std::map<std::string, int> num_instances()\n')
    out_cpps.classes.write('{\n')
    out_cpps.classes.write('    std::map<std::string, int> ret;\n')
    for classname, struct_cursor, struct_name in classes_:
        out_cpps.classes.write(f'    ret["{classname}"] = {classname}::s_num_instances;\n')
    out_cpps.classes.write('    \n')
    out_cpps.classes.write('    return ret;\n')
    out_cpps.classes.write('}\n')

    # Write close of namespace.
    out_hs.classes.write( out_h_classes_end.get())
    for _, _, file in out_cpps.get() + out_hs.get():
        if file in (out_cpps.internal, out_cpps.extra, out_hs.extra):
            continue
        make_namespace_close( namespace, file)

    # Write pod struct fns such as operator<<(), operator==() - these need to
    # be outside the namespace.
    #
    for classname, struct_cursor, struct_name in classes_:
        extras = classes.classextras.get( tu, struct_name)
        if extras.pod:
            # Make operator<<(), operator==(), operator!=() for POD struct.
            #
            pod_struct_fns(
                    tu,
                    namespace,
                    struct_cursor,
                    struct_name,
                    extras,
                    out_hs.functions,
                    out_cpps.functions,
                    )
            if extras.pod != 'none':
                # Make operator<<(), operator==(), operator!=() for POD class
                # wrappers.
                #
                pod_class_fns(
                        tu,
                        classname,
                        struct_cursor,
                        struct_name,
                        extras,
                        out_hs.classes,
                        out_cpps.classes,
                        )


    # Terminate multiple-inclusion guards in headers:
    #
    for name, _, file in out_hs.get():
        if name != 'extra':
            file.write( '\n#endif\n')

    out_hs.close()
    out_cpps.close()

    generated.h_files = [filename for _, filename, _ in out_hs.get()]
    generated.cpp_files = [filename for _, filename, _ in out_cpps.get()]
    if 0:   # lgtm [py/unreachable-statement]
        jlib.log( 'Have created:')
        for filename in filenames_h + filenames_cpp:
            jlib.log( '    {filename}')


    # Output usage information.
    #

    fn_usage_filename = f'{base}/fn_usage.txt'
    out_fn_usage = File( fn_usage_filename, tabify=False)
    functions_unused = 0
    functions_used = 0

    for fnname in sorted( fn_usage.keys()):
        n, cursor = fn_usage[ fnname]
        exclude_reasons = parse.find_wrappable_function_with_arg0_type_excluded_cache.get( fnname, [])
        if n:
            functions_used += 1
        else:
            functions_unused += 1
        if n and not exclude_reasons:
            continue

    out_fn_usage.write( f'Functions not wrapped by class methods:\n')
    out_fn_usage.write( '\n')

    for fnname in sorted( fn_usage.keys()):
        n, cursor = fn_usage[ fnname]
        exclude_reasons = parse.find_wrappable_function_with_arg0_type_excluded_cache.get( fnname, [])
        if not exclude_reasons:
            continue
        if n:
            continue
        num_interesting_reasons = 0
        for t, description in exclude_reasons:
            if t == parse.MethodExcludeReason_FIRST_ARG_NOT_STRUCT:
                continue
            if t == parse.MethodExcludeReason_VARIADIC:
                continue
            num_interesting_reasons += 1
        if num_interesting_reasons:
            try:
                out_fn_usage.write( f'    {declaration_text( cursor.type, cursor.spelling)}\n')
            except Clang6FnArgsBug as e:
                out_fn_usage.write( f'    {cursor.spelling} [full prototype not available due to known clang-6 issue]\n')
            for t, description in exclude_reasons:
                if t == parse.MethodExcludeReason_FIRST_ARG_NOT_STRUCT:
                    continue
                out_fn_usage.write( f'        {description}\n')
            out_fn_usage.write( '\n')

    out_fn_usage.write( f'\n')
    out_fn_usage.write( f'Functions used more than once:\n')
    for fnname in sorted( fn_usage.keys()):
        n, cursor = fn_usage[ fnname]
        if n > 1:
            out_fn_usage.write( f'    n={n}: {declaration_text( cursor.type, cursor.spelling)}\n')

    out_fn_usage.write( f'\n')
    out_fn_usage.write( f'Number of wrapped functions: {len(fn_usage)}\n')
    out_fn_usage.write( f'Number of wrapped functions used by wrapper classes: {functions_used}\n')
    out_fn_usage.write( f'Number of wrapped functions not used by wrapper classes: {functions_unused}\n')

    out_fn_usage.close()

    generated.c_enums = state.state_.enums[ tu]

    if num_regressions:
        raise Exception( f'There were {num_regressions} regressions')
    return tu


def test():
    '''
    Place to experiment with clang-python.
    '''
    text = ''
    if state.state_.linux:
        text += textwrap.dedent('''
            /*
            Workaround on Linux. size_t is defined internally in gcc. It isn't
            even in stdint.h.
            */
            typedef unsigned long size_t;
            ''')

    text += textwrap.dedent('''
            #include "mupdf/fitz.h"
            #include "mupdf/pdf.h"
            ''')
    path = 'wrap-test.c'
    jlib.fs_update( text, path)
    index = state.clang.cindex.Index.create()
    tu = index.parse( path, '-I /usr/include -I include'.split(' '))
    path2 = 'wrap-test.c.c'
    tu.save(path2)
    jlib.log( 'Have saved to: {path2}')
    parse.dump_ast( tu.cursor, 'ast')
    for diagnostic in tu.diagnostics:
        jlib.log('{diagnostic=}')
    for cursor in parse.get_members( tu.cursor):
        if 'cpp_test_' in cursor.spelling:
            parse.dump_ast(cursor, out=jlib.log)