File: make_vulkan

package info (click to toggle)
wine 10.0~repack-6
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 325,920 kB
  • sloc: ansic: 4,156,003; perl: 23,800; yacc: 22,031; javascript: 15,872; makefile: 12,346; pascal: 9,519; objc: 6,923; lex: 5,273; xml: 3,219; python: 2,673; cpp: 1,741; sh: 893; java: 750; asm: 299; cs: 62
file content (3908 lines) | stat: -rwxr-xr-x 157,175 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
#!/usr/bin/env python3
# Wine Vulkan generator
#
# Copyright 2017-2018 Roderick Colenbrander
# Copyright 2022 Jacek Caban for CodeWeavers
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
#  License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#

import argparse
import logging
import os
import re
import urllib.request
import xml.etree.ElementTree as ET
from collections import OrderedDict
from collections.abc import Sequence
from enum import Enum

# This script generates code for a Wine Vulkan ICD driver from Vulkan's vk.xml.
# Generating the code is like 10x worse than OpenGL, which is mostly a calling
# convention passthrough.
#
# The script parses vk.xml and maps functions and types to helper objects. These
# helper objects simplify the xml parsing and map closely to the Vulkan types.
# The code generation utilizes the helper objects during code generation and
# most of the ugly work is carried out by these objects.
#
# Vulkan ICD challenges:
# - Vulkan ICD loader (vulkan-1.dll) relies on a section at the start of
#   'dispatchable handles' (e.g. VkDevice, VkInstance) for it to insert
#   its private data. It uses this area to stare its own dispatch tables
#   for loader internal use. This means any dispatchable objects need wrapping.
#
# - Vulkan structures have different alignment between win32 and 32-bit Linux.
#   This means structures with alignment differences need conversion logic.
#   Often structures are nested, so the parent structure may not need any
#   conversion, but some child may need some.
#
# vk.xml parsing challenges:
# - Contains type data for all platforms (generic Vulkan, Windows, Linux,..).
#   Parsing of extension information required to pull in types and functions
#   we really want to generate. Just tying all the data together is tricky.
#
# - Extensions can affect core types e.g. add new enum values, bitflags or
#   additional structure chaining through 'pNext' / 'sType'.
#
# - Arrays are used all over the place for parameters or for structure members.
#   Array length is often stored in a previous parameter or another structure
#   member and thus needs careful parsing.

LOGGER = logging.Logger("vulkan")
LOGGER.addHandler(logging.StreamHandler())

VK_XML_VERSION = "1.4.303"
WINE_VK_VERSION = (1, 4)

# Filenames to create.
WINE_VULKAN_H = "../../include/wine/vulkan.h"
WINE_VULKAN_DRIVER_H = "../../include/wine/vulkan_driver.h"
WINE_VULKAN_LOADER_SPEC = "../vulkan-1/vulkan-1.spec"
WINE_VULKAN_JSON = "winevulkan.json"
WINE_VULKAN_SPEC = "winevulkan.spec"
WINE_VULKAN_THUNKS_C = "vulkan_thunks.c"
WINE_VULKAN_THUNKS_H = "vulkan_thunks.h"
WINE_VULKAN_LOADER_THUNKS_C = "loader_thunks.c"
WINE_VULKAN_LOADER_THUNKS_H = "loader_thunks.h"

# Extension enum values start at a certain offset (EXT_BASE).
# Relative to the offset each extension has a block (EXT_BLOCK_SIZE)
# of values.
# Start for a given extension is:
# EXT_BASE + (extension_number-1) * EXT_BLOCK_SIZE
EXT_BASE = 1000000000
EXT_BLOCK_SIZE = 1000

UNSUPPORTED_EXTENSIONS = [
    # Instance extensions
    "VK_EXT_headless_surface", # Needs WSI work.
    "VK_KHR_display", # Needs WSI work.
    "VK_KHR_surface_protected_capabilities",
    "VK_LUNARG_direct_driver_loading", # Implemented in the Vulkan loader

    # Device extensions
    "VK_AMD_display_native_hdr",
    "VK_EXT_full_screen_exclusive",
    "VK_GOOGLE_display_timing",
    "VK_KHR_external_fence_win32",
    "VK_KHR_external_semaphore_win32",
    # Relates to external_semaphore and needs type conversions in bitflags.
    "VK_KHR_maintenance7", # Causes infinity recursion in struct convert code
    "VK_KHR_shared_presentable_image", # Needs WSI work.
    "VK_KHR_win32_keyed_mutex",
    "VK_NV_external_memory_rdma", # Needs shared resources work.

    # Extensions for other platforms
    "VK_EXT_external_memory_dma_buf",
    "VK_EXT_image_drm_format_modifier",
    "VK_EXT_metal_objects",
    "VK_EXT_physical_device_drm",
    "VK_GOOGLE_surfaceless_query",
    "VK_KHR_external_fence_fd",
    "VK_KHR_external_memory_fd",
    "VK_KHR_external_semaphore_fd",
    "VK_SEC_amigo_profiling", # Angle specific.

    # Extensions which require callback handling
    "VK_EXT_device_memory_report",

    # Deprecated extensions
    "VK_NV_external_memory_capabilities",
    "VK_NV_external_memory_win32",
]

# Either internal extensions which aren't present on the win32 platform which
# winevulkan may nonetheless use, or extensions we want to generate headers for
# but not expose to applications (useful for test commits)
UNEXPOSED_EXTENSIONS = {
    "VK_EXT_map_memory_placed",
    "VK_KHR_external_memory_win32",
}

# The Vulkan loader provides entry-points for core functionality and important
# extensions. Based on vulkan-1.def this amounts to WSI extensions on 1.0.51.
CORE_EXTENSIONS = [
    "VK_KHR_display",
    "VK_KHR_display_swapchain",
    "VK_KHR_get_surface_capabilities2",
    "VK_KHR_surface",
    "VK_KHR_swapchain",
    "VK_KHR_win32_surface",
]

# List of surface extensions that can be exposed directly to the PE side
WIN_SURFACE_EXTENSIONS = [
    "VK_KHR_win32_surface",
    "VK_EXT_headless_surface",
]

# Some experimental extensions are used by shipping applications so their API is extremely unlikely
# to change in a backwards-incompatible way. Allow translation of those extensions with WineVulkan.
ALLOWED_X_EXTENSIONS = [
    "VK_NVX_binary_import",
    "VK_NVX_image_view_handle",
]

# Some frequently called functions skip traces and checks for performance reasons.
PERF_CRITICAL_FUNCTIONS = [
    "vkUpdateDescriptorSets",
    "vkUpdateDescriptorSetWithTemplate",
    "vkGetDescriptorEXT",
]

# Table of functions for which we have a special implementation.
# These are regular device / instance functions for which we need
# to do more work compared to a regular thunk or because they are
# part of the driver interface.
# - dispatch (default: True):  set whether we need a function pointer in the device / instance dispatch table.
FUNCTION_OVERRIDES = {
    # Global functions
    "vkCreateInstance" : {"extra_param" : "client_ptr"},

    # Instance functions
    "vkCreateDevice" : {"extra_param" : "client_ptr"},
    "vkGetPhysicalDeviceExternalBufferProperties" : {"dispatch" : False},
    "vkGetPhysicalDeviceExternalFenceProperties" : {"dispatch" : False},
    "vkGetPhysicalDeviceExternalSemaphoreProperties" : {"dispatch" : False},

    # Device functions
    "vkCreateCommandPool" : {"extra_param" : "client_ptr"},
    "vkGetDeviceProcAddr" : {"dispatch" : False},

    # VK_KHR_external_fence_capabilities
    "vkGetPhysicalDeviceExternalFencePropertiesKHR" : {"dispatch" : False},

    # VK_KHR_external_memory_capabilities
    "vkGetPhysicalDeviceExternalBufferPropertiesKHR" : {"dispatch" : False},

    # VK_KHR_external_semaphore_capabilities
    "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR" : {"dispatch" : False},
}

# functions for which a user driver entry must be generated
USER_DRIVER_FUNCS = {
    "vkAcquireNextImage2KHR",
    "vkAcquireNextImageKHR",
    "vkCreateSwapchainKHR",
    "vkCreateWin32SurfaceKHR",
    "vkDestroySurfaceKHR",
    "vkDestroySwapchainKHR",
    "vkGetDeviceProcAddr",
    "vkGetInstanceProcAddr",
    "vkGetPhysicalDevicePresentRectanglesKHR",
    "vkGetPhysicalDeviceSurfaceCapabilities2KHR",
    "vkGetPhysicalDeviceSurfaceCapabilitiesKHR",
    "vkGetPhysicalDeviceSurfaceFormats2KHR",
    "vkGetPhysicalDeviceSurfaceFormatsKHR",
    "vkGetPhysicalDeviceWin32PresentationSupportKHR",
    "vkQueuePresentKHR",
}

# functions for which the unix thunk is manually implemented
MANUAL_UNIX_THUNKS = {
    "vkAllocateCommandBuffers",
    "vkAllocateMemory",
    "vkCreateBuffer",
    "vkCreateCommandPool",
    "vkCreateDebugReportCallbackEXT",
    "vkCreateDebugUtilsMessengerEXT",
    "vkCreateDeferredOperationKHR",
    "vkCreateDevice",
    "vkCreateImage",
    "vkCreateInstance",
    "vkDestroyCommandPool",
    "vkDestroyDebugReportCallbackEXT",
    "vkDestroyDebugUtilsMessengerEXT",
    "vkDestroyDeferredOperationKHR",
    "vkDestroyDevice",
    "vkDestroyInstance",
    "vkEnumerateDeviceExtensionProperties",
    "vkEnumerateDeviceLayerProperties",
    "vkEnumerateInstanceExtensionProperties",
    "vkEnumerateInstanceLayerProperties",
    "vkEnumerateInstanceVersion",
    "vkEnumeratePhysicalDeviceGroups",
    "vkEnumeratePhysicalDeviceGroupsKHR",
    "vkEnumeratePhysicalDevices",
    "vkFreeCommandBuffers",
    "vkFreeMemory",
    "vkGetCalibratedTimestampsEXT",
    "vkGetCalibratedTimestampsKHR",
    "vkGetDeviceProcAddr",
    "vkGetDeviceQueue",
    "vkGetDeviceQueue2",
    "vkGetInstanceProcAddr",
    "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT",
    "vkGetPhysicalDeviceCalibrateableTimeDomainsKHR",
    "vkGetPhysicalDeviceExternalBufferProperties",
    "vkGetPhysicalDeviceExternalBufferPropertiesKHR",
    "vkGetPhysicalDeviceExternalFenceProperties",
    "vkGetPhysicalDeviceExternalFencePropertiesKHR",
    "vkGetPhysicalDeviceExternalSemaphoreProperties",
    "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR",
    "vkGetPhysicalDeviceImageFormatProperties2",
    "vkGetPhysicalDeviceImageFormatProperties2KHR",
    "vkMapMemory",
    "vkMapMemory2KHR",
    "vkUnmapMemory",
    "vkUnmapMemory2KHR",
}

# loader functions which are entirely manually implemented
MANUAL_LOADER_FUNCTIONS = {
    "vkEnumerateInstanceLayerProperties",
    "vkGetDeviceProcAddr",
    "vkGetInstanceProcAddr",
}

# functions which loader thunks are manually implemented
MANUAL_LOADER_THUNKS = {
    "vkAllocateCommandBuffers",
    "vkCreateCommandPool",
    "vkCreateDevice",
    "vkCreateInstance",
    "vkDestroyCommandPool",
    "vkDestroyDevice",
    "vkDestroyInstance",
    "vkEnumerateInstanceExtensionProperties",
    "vkEnumerateInstanceVersion",
    "vkFreeCommandBuffers",
    "vkGetPhysicalDeviceProperties2",
    "vkGetPhysicalDeviceProperties2KHR",
}

STRUCT_CHAIN_CONVERSIONS = {
    # Ignore to not confuse host loader.
    "VkDeviceCreateInfo": ["VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO"],
    "VkInstanceCreateInfo": ["VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO"],
}

# Some struct members are conditionally ignored and callers are free to leave them uninitialized.
# We can't deduce that from XML, so we allow expressing it here.
MEMBER_LENGTH_EXPRESSIONS = {
    "VkWriteDescriptorSet": {
        "pImageInfo":
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || " +
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER || " +
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE || " +
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE || " +
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT || " +
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_SAMPLE_WEIGHT_IMAGE_QCOM || " +
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_BLOCK_MATCH_IMAGE_QCOM ? {len} : 0",
        "pBufferInfo":
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || " +
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER || " +
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC || " +
            "{struct}descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC ? {len} : 0",
    }
}

class Direction(Enum):
    """ Parameter direction: input, output, input_output. """
    INPUT = 1
    OUTPUT = 2


class Unwrap(Enum):
    NONE = 0
    HOST = 1
    DRIVER = 2


def api_is_vulkan(obj):
    return "vulkan" in obj.get("api", "vulkan").split(",")


def convert_suffix(direction, win_type, unwrap, is_wrapped):
    if direction == Direction.OUTPUT:
        if not is_wrapped:
            return "host_to_{0}".format(win_type)
        if unwrap == Unwrap.NONE:
            return "unwrapped_host_to_{0}".format(win_type)
        return "host_to_{0}".format(win_type)
    else:
        if not is_wrapped:
            return "{0}_to_host".format(win_type)
        if unwrap == Unwrap.NONE:
            return "{0}_to_unwrapped_host".format(win_type)
        return "{0}_to_host".format(win_type)


# Arrays come in multiple formats. Known formats are:
#
# <member><type>uint32_t</type> <name>foo</name>[<enum>VK_FOO_SIZE</enum>][<enum>VK_FOO_COUNT</enum>]</member>
# <member><type>uint32_t</type> <name>foo</name>[3][4]</member>
def parse_array_lens(element):
    text = ''

    for e in element:
        if e.tag == 'name':
            if e.tail:
                text += e.tail
        elif e.tag == 'enum':
            text += e.text + e.tail
        elif e.tag != 'comment' and e.tag != 'type':
            LOGGER.warning("Ignoring tag <{0}> while trying to parse array sizes".format(e.tag))
    return [i.strip('[]') for i in re.findall(r'\[\w+\]', text)]

class VkBaseType(object):
    def __init__(self, name, _type, alias=None, requires=None):
        """ Vulkan base type class.

        VkBaseType is mostly used by Vulkan to define its own
        base types like VkFlags through typedef out of e.g. uint32_t.

        Args:
            name (:obj:'str'): Name of the base type.
            _type (:obj:'str'): Underlying type
            alias (bool): type is an alias or not.
            requires (:obj:'str', optional): Other types required.
                Often bitmask values pull in a *FlagBits type.
        """
        self.name = name
        self.type = _type
        self.alias = alias
        self.requires = requires
        self.required = False

    def definition(self):
        # Definition is similar for alias or non-alias as type
        # is already set to alias.
        if not self.type is None:
            return "typedef {0} {1};\n".format(self.type, self.name)
        else:
            return "struct {0};\n".format(self.name)

    def is_alias(self):
        return bool(self.alias)


class VkConstant(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def definition(self):
        text = "#define {0} {1}\n".format(self.name, self.value)
        return text


class VkDefine(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

    @staticmethod
    def from_xml(define):
        if not api_is_vulkan(define):
            return None

        name_elem = define.find("name")

        if name_elem is None:
            # <type category="define" name="some_name">some_value</type>
            name = define.attrib.get("name")

            # We override behavior of VK_USE_64_BIT_PTR_DEFINES as the default non-dispatchable handle
            # definition various between 64-bit (uses pointers) and 32-bit (uses uint64_t).
            # This complicates TRACEs in the thunks, so just use uint64_t.
            if name == "VK_USE_64_BIT_PTR_DEFINES":
                value = "#define VK_USE_64_BIT_PTR_DEFINES 0"
            else:
                value = define.text
            return VkDefine(name, value)

        # With a name element the structure is like:
        # <type category="define"><name>some_name</name>some_value</type>
        name = name_elem.text

        # Perform minimal parsing for Vulkan constants, which we don't need, but are referenced
        # elsewhere in vk.xml.
        # - VK_API_VERSION is a messy, deprecated constant and we don't want generate code for it.
        # - AHardwareBuffer/ANativeWindow are forward declarations for Android types, which leaked
        #   into the define region.
        if name in ["VK_API_VERSION", "AHardwareBuffer", "ANativeWindow", "CAMetalLayer"]:
            return VkDefine(name, None)

        # The body of the define is basically unstructured C code. It is not meant for easy parsing.
        # Some lines contain deprecated values or comments, which we try to filter out.
        value = ""
        for line in define.text.splitlines():
            # Skip comments or deprecated values.
            if "//" in line:
                continue
            value += line

        for child in define:
            value += child.text
            if child.tail is not None:
                # Split comments for VK_API_VERSION_1_0 / VK_API_VERSION_1_1
                if "//" in child.tail:
                    value += child.tail.split("//")[0]
                else:
                    value += child.tail

        return VkDefine(name, value.rstrip(' '))

    def definition(self):
        if self.value is None:
            return ""

        # Nothing to do as the value was already put in the right form during parsing.
        return "{0}\n".format(self.value)


class VkEnum(object):
    def __init__(self, name, bitwidth, alias=None):
        if not bitwidth in [32, 64]:
            LOGGER.error("unknown bitwidth {0} for {1}".format(bitwidth, name))
        self.name = name
        self.bitwidth = bitwidth
        self.values = [] if alias == None else alias.values
        self.required = False
        self.alias = alias
        self.aliased_by = []

    @staticmethod
    def from_alias(enum, alias):
        name = enum.attrib.get("name")
        aliasee = VkEnum(name, alias.bitwidth, alias=alias)

        alias.add_aliased_by(aliasee)
        return aliasee

    @staticmethod
    def from_xml(enum):
        if not api_is_vulkan(enum):
            return None

        name = enum.attrib.get("name")
        bitwidth = int(enum.attrib.get("bitwidth", "32"))
        result = VkEnum(name, bitwidth)

        for v in enum.findall("enum"):
            value_name = v.attrib.get("name")
            # Value is either a value or a bitpos, only one can exist.
            value = v.attrib.get("value")
            alias_name = v.attrib.get("alias")
            if alias_name:
                result.create_alias(value_name, alias_name)
            elif value:
                result.create_value(value_name, value)
            else:
                # bitmask
                result.create_bitpos(value_name, int(v.attrib.get("bitpos")))

        if bitwidth == 32:
            # vulkan.h contains a *_MAX_ENUM value set to 32-bit at the time of writing,
            # which is to prepare for extensions as they can add values and hence affect
            # the size definition.
            max_name = re.sub(r'([0-9a-z_])([A-Z0-9])',r'\1_\2', name).upper() + "_MAX_ENUM"
            result.create_value(max_name, "0x7fffffff")

        return result

    def create_alias(self, name, alias_name):
        """ Create an aliased value for this enum """
        self.add(VkEnumValue(name, self.bitwidth, alias=alias_name))

    def create_value(self, name, value):
        """ Create a new value for this enum """
        # Some values are in hex form. We want to preserve the hex representation
        # at least when we convert back to a string. Internally we want to use int.
        hex = "0x" in value
        self.add(VkEnumValue(name, self.bitwidth, value=int(value, 0), hex=hex))

    def create_bitpos(self, name, pos):
        """ Create a new bitmask value for this enum """
        self.add(VkEnumValue(name, self.bitwidth, value=(1 << pos), hex=True))

    def add(self, value):
        """ Add a value to enum. """

        # Extensions can add new enum values. When an extension is promoted to Core
        # the registry defines the value twice once for old extension and once for
        # new Core features. Add the duplicate if it's explicitly marked as an
        # alias, otherwise ignore it.
        for v in self.values:
            if not value.is_alias() and v.value == value.value:
                LOGGER.debug("Adding duplicate enum value {0} to {1}".format(v, self.name))
                return
        # Avoid adding duplicate aliases multiple times
        if not any(x.name == value.name for x in self.values):
            self.values.append(value)

    def fixup_64bit_aliases(self):
        """ Replace 64bit aliases with literal values """
        # Older GCC versions need a literal to initialize a static const uint64_t
        # which is what we use for 64bit bitmasks.
        if self.bitwidth != 64:
            return
        for value in self.values:
            if not value.is_alias():
                continue
            alias = next(x for x in self.values if x.name == value.alias)
            value.hex = alias.hex
            value.value = alias.value

    def definition(self):
        if self.is_alias():
            return ""

        default_value = 0x7ffffffe if self.bitwidth == 32 else 0xfffffffffffffffe

        # Print values sorted, values can have been added in a random order.
        values = sorted(self.values, key=lambda value: value.value if value.value is not None else default_value)

        if self.bitwidth == 32:
            text = "typedef enum {0}\n{{\n".format(self.name)
            for value in values:
                text += "    {0},\n".format(value.definition())
            text += "}} {0};\n".format(self.name)
        elif self.bitwidth == 64:
            text = "typedef VkFlags64 {0};\n\n".format(self.name)
            for value in values:
                text += "static const {0} {1};\n".format(self.name, value.definition())

        for aliasee in self.aliased_by:
            text += "typedef {0} {1};\n".format(self.name, aliasee.name)

        text += "\n"
        return text

    def is_alias(self):
        return bool(self.alias)

    def add_aliased_by(self, aliasee):
        self.aliased_by.append(aliasee)


class VkEnumValue(object):
    def __init__(self, name, bitwidth, value=None, hex=False, alias=None):
        self.name = name
        self.bitwidth = bitwidth
        self.value = value
        self.hex = hex
        self.alias = alias

    def __repr__(self):
        postfix = "ull" if self.bitwidth == 64 else ""
        if self.is_alias() and self.value == None:
            return "{0}={1}".format(self.name, self.alias)
        return "{0}={1}{2}".format(self.name, self.value, postfix)

    def definition(self):
        """ Convert to text definition e.g. VK_FOO = 1 """
        postfix = "ull" if self.bitwidth == 64 else ""
        if self.is_alias() and self.value == None:
            return "{0} = {1}".format(self.name, self.alias)

        # Hex is commonly used for FlagBits and sometimes within
        # a non-FlagBits enum for a bitmask value as well.
        if self.hex:
            return "{0} = 0x{1:08x}{2}".format(self.name, self.value, postfix)
        else:
            return "{0} = {1}{2}".format(self.name, self.value, postfix)

    def is_alias(self):
        return self.alias is not None


class VkFunction(object):
    def __init__(self, _type=None, name=None, params=[], alias=None):
        self.extensions = set()
        self.name = name
        self.type = _type
        self.params = params
        self.alias = alias

        # For some functions we need some extra metadata from FUNCTION_OVERRIDES.
        func_info = FUNCTION_OVERRIDES.get(self.name, {})
        self.dispatch = func_info.get("dispatch", True)
        self.extra_param = func_info.get("extra_param", None)

        # Required is set while parsing which APIs and types are required
        # and is used by the code generation.
        self.required = True if func_info else False

        if self.name in MANUAL_UNIX_THUNKS | USER_DRIVER_FUNCS:
            self.unwrap = Unwrap.NONE
        else:
            self.unwrap = Unwrap.HOST

    @staticmethod
    def from_alias(command, alias):
        """ Create VkFunction from an alias command.

        Args:
            command: xml data for command
            alias (VkFunction): function to use as a base for types / parameters.

        Returns:
            VkFunction
        """
        if not api_is_vulkan(command):
            return None

        func_name = command.attrib.get("name")
        func_type = alias.type
        params = alias.params

        return VkFunction(_type=func_type, name=func_name, params=params, alias=alias)

    @staticmethod
    def from_xml(command, types):
        if not api_is_vulkan(command):
            return None

        proto = command.find("proto")
        func_name = proto.find("name").text
        func_type = proto.find("type").text

        params = []
        for param in command.findall("param"):
            vk_param = VkParam.from_xml(param, types, params)
            if vk_param:
                params.append(vk_param)

        return VkFunction(_type=func_type, name=func_name, params=params)

    def get_conversions(self):
        """ Get a list of conversion functions required for this function if any.
        Parameters which are structures may require conversion between win32
        and the host platform. This function returns a list of conversions
        required.
        """

        conversions = []
        for param in self.params:
            conversions.extend(param.get_conversions(self.unwrap))
        return conversions

    def is_alias(self):
        return bool(self.alias)

    def is_core_func(self):
        """ Returns whether the function is a Vulkan core function.
        Core functions are APIs defined by the Vulkan spec to be part of the
        Core API as well as several KHR WSI extensions.
        """

        if not self.extensions:
            return True

        return any(ext in self.extensions for ext in CORE_EXTENSIONS)

    def is_device_func(self):
        # If none of the other, it must be a device function
        return not self.is_global_func() and not self.is_instance_func() and not self.is_phys_dev_func()

    def is_driver_func(self):
        """ Returns if function is part of Wine driver interface. """
        return self.name in USER_DRIVER_FUNCS

    def is_global_func(self):
        # Treat vkGetInstanceProcAddr as a global function as it
        # can operate with NULL for vkInstance.
        if self.name == "vkGetInstanceProcAddr":
            return True
        # Global functions are not passed a dispatchable object.
        elif self.params[0].is_dispatchable():
            return False
        return True

    def is_instance_func(self):
        # Instance functions are passed VkInstance.
        if self.params[0].type == "VkInstance":
            return True
        return False

    def is_phys_dev_func(self):
        # Physical device functions are passed VkPhysicalDevice.
        if self.params[0].type == "VkPhysicalDevice":
            return True
        return False

    def is_required(self):
        return self.required

    def returns_longlong(self):
        return self.type in ["uint64_t", "VkDeviceAddress"]

    def needs_dispatch(self):
        return self.dispatch

    def needs_private_thunk(self):
        return self.needs_exposing() and self.name not in MANUAL_LOADER_FUNCTIONS and \
            self.name in MANUAL_UNIX_THUNKS

    def needs_exposing(self):
        # The function needs exposed if at-least one extension isn't both UNSUPPORTED and UNEXPOSED
        return self.is_required() and (not self.extensions or not self.extensions.issubset(UNEXPOSED_EXTENSIONS))

    def is_perf_critical(self):
        # vkCmd* functions are frequently called, do not trace for performance
        if self.name.startswith("vkCmd") and self.type == "void":
            return True
        return self.name in PERF_CRITICAL_FUNCTIONS

    def pfn(self, prefix="p", call_conv=None):
        """ Create function pointer. """

        if call_conv:
            pfn = "{0} ({1} *{2}_{3})(".format(self.type, call_conv, prefix, self.name)
        else:
            pfn = "{0} (*{1}_{2})(".format(self.type, prefix, self.name)

        for i, param in enumerate(self.params):
            if param.const:
                pfn += param.const + " "

            pfn += param.type

            if param.is_pointer():
                pfn += " " + param.pointer

            for l in param.array_lens:
                pfn += "[{0}]".format(l)

            if i < len(self.params) - 1:
                pfn += ", "
        pfn += ")"
        return pfn

    def prototype(self, call_conv=None, prefix=None, is_thunk=False):
        """ Generate prototype for given function.

        Args:
            call_conv (str, optional): calling convention e.g. WINAPI
            prefix (str, optional): prefix to append prior to function name e.g. vkFoo -> wine_vkFoo
        """

        proto = "{0}".format(self.type)

        if call_conv is not None:
            proto += " {0}".format(call_conv)

        if prefix is not None:
            proto += " {0}{1}(".format(prefix, self.name)
        else:
            proto += " {0}(".format(self.name)

        # Add all the parameters.
        proto += ", ".join([p.definition() for p in self.params])

        if is_thunk and self.extra_param:
            proto += ", void *" + self.extra_param

        proto += ")"
        return proto

    def loader_body(self):
        body = "    struct {0}_params params;\n".format(self.name)
        if not self.is_perf_critical():
            body += "    NTSTATUS status;\n"
        for p in self.params:
            body += "    params.{0} = {0};\n".format(p.name)

        # Call the Unix function.
        if self.is_perf_critical():
            body += "    UNIX_CALL({0}, &params);\n".format(self.name)
        else:
            body += "    status = UNIX_CALL({0}, &params);\n".format(self.name)
            body += "    assert(!status && \"{0}\");\n".format(self.name)

        if self.type != "void":
            body += "    return params.result;\n"
        return body

    def body(self, conv, params_prefix=""):
        body = ""
        needs_alloc = False
        deferred_op = None

        # Declare any tmp parameters for conversion.
        for p in self.params:
            if p.needs_variable(conv, self.unwrap):
                if p.is_dynamic_array():
                    body += "    {3}{0}{1} *{2}_host;\n".format(
                        p.type, p.pointer[:-1] if p.pointer else "",
                        p.name, "const " if p.is_const() else "")
                elif p.optional:
                    body += "    {0} *{1}_host = NULL;\n".format(p.type, p.name)
                    needs_alloc = True
                elif p.pointer:
                    body += "    {0} {1}{2}_host;\n".format(p.type, p.pointer[:-1], p.name)
                else:
                    body += "    {0} {1}_host;\n".format(p.type, p.name)
            if p.needs_alloc(conv, self.unwrap):
                needs_alloc = True
            if p.type == "VkDeferredOperationKHR" and not p.is_pointer():
                deferred_op = p.name

        if needs_alloc:
            body += "    struct conversion_context local_ctx;\n"
            body += "    struct conversion_context *ctx = &local_ctx;\n"
        body += "\n"

        if not self.is_perf_critical():
            body += "    {0}\n".format(self.trace(params_prefix=params_prefix, conv=conv))

        if self.params[0].optional and self.params[0].is_handle():
            if self.type != "void":
                LOGGER.warning("return type {0} with optional handle not supported".format(self.type))
            body += "    if (!{0}{1})\n".format(params_prefix, self.params[0].name)
            body += "        return STATUS_SUCCESS;\n\n"

        if needs_alloc:
            if deferred_op is not None:
                body += "    if (params->{} == VK_NULL_HANDLE)\n".format(deferred_op)
                body += "    "
            body += "    init_conversion_context(ctx);\n"
            if deferred_op is not None:
                body += "    else\n"
                body += "        ctx = &wine_deferred_operation_from_handle(params->{})->ctx;\n".format(deferred_op)

        # Call any win_to_host conversion calls.
        unwrap = self.name not in MANUAL_UNIX_THUNKS
        for p in self.params:
            if p.needs_conversion(conv, self.unwrap, Direction.INPUT):
                body += p.copy(Direction.INPUT, conv, self.unwrap, prefix=params_prefix)
            elif p.is_dynamic_array() and p.needs_conversion(conv, self.unwrap, Direction.OUTPUT):
                body += "    {0}_host = ({2}{0} && {1}) ? conversion_context_alloc(ctx, sizeof(*{0}_host) * {1}) : NULL;\n".format(
                    p.name, p.get_dyn_array_len(params_prefix, conv), params_prefix)

        # Build list of parameters containing converted and non-converted parameters.
        # The param itself knows if conversion is needed and applies it when we set conv=True.
        unwrap = Unwrap.NONE if self.name in MANUAL_UNIX_THUNKS else self.unwrap
        params = ", ".join([p.variable(conv, unwrap, params_prefix) for p in self.params])
        if self.extra_param:
            if conv:
                params += ", UlongToPtr({0}{1})".format(params_prefix, self.extra_param)
            else:
                params += ", {0}{1}".format(params_prefix, self.extra_param)

        if self.name in MANUAL_UNIX_THUNKS:
            func_prefix = "wine_"
        elif self.name in USER_DRIVER_FUNCS:
            func_prefix = "vk_funcs->p_"
        else:
            func_prefix = "{0}->p_".format(self.params[0].dispatch_table(params_prefix, conv))

        # Call the host Vulkan function.
        if self.type == "void":
            body += "    {0}{1}({2});\n".format(func_prefix, self.name, params)
        else:
            body += "    {0}result = {1}{2}({3});\n".format(params_prefix, func_prefix, self.name, params)

        # Call any host_to_win conversion calls.
        for p in self.params:
            if p.needs_conversion(conv, self.unwrap, Direction.OUTPUT):
                body += p.copy(Direction.OUTPUT, conv, self.unwrap, prefix=params_prefix)

        if needs_alloc:
            if deferred_op is not None:
                body += "    if (params->{} == VK_NULL_HANDLE)\n".format(deferred_op)
                body += "    "
            body += "    free_conversion_context(ctx);\n"

        # Finally return the result. Performance critical functions return void to allow tail calls.
        if not self.is_perf_critical():
            body += "    return STATUS_SUCCESS;\n"

        return body

    def spec(self, prefix=None, symbol=None):
        """ Generate spec file entry for this function.

        Args
            prefix (str, optional): prefix to prepend to entry point name.
            symbol (str, optional): allows overriding the name of the function implementing the entry point.
        """

        spec = ""
        params = " ".join([p.spec() for p in self.params])
        if prefix is not None:
            spec += "@ stdcall -private {0}{1}({2})".format(prefix, self.name, params)
        else:
            spec += "@ stdcall {0}({1})".format(self.name, params)

        if symbol is not None:
            spec += " " + symbol

        spec += "\n"
        return spec

    def stub(self, call_conv=None, prefix=None):
        stub = self.prototype(call_conv=call_conv, prefix=prefix)
        stub += "\n{\n"
        stub += "    {0}".format(self.trace(message="stub: ", trace_func="FIXME"))

        if self.type == "VkResult":
            stub += "    return VK_ERROR_OUT_OF_HOST_MEMORY;\n"
        elif self.type == "VkBool32":
            stub += "    return VK_FALSE;\n"
        elif self.type == "PFN_vkVoidFunction":
            stub += "    return NULL;\n"

        stub += "}\n\n"
        return stub

    def thunk(self, prefix=None, conv=False):
        thunk = ""
        if not conv:
            thunk += "#ifdef _WIN64\n"
        if self.is_perf_critical():
            thunk += "static void {0}{1}(void *args)\n".format(prefix, self.name)
        else:
            thunk += "static NTSTATUS {0}{1}(void *args)\n".format(prefix, self.name)
        thunk += "{\n"
        if conv:
            thunk += "    struct\n"
            thunk += "    {\n"
            for p in self.params:
                thunk += "        {0};\n".format(p.definition(conv=True, is_member=True))
            if self.extra_param:
                thunk += "        PTR32 {0};\n".format(self.extra_param)
            if self.type != "void":
                thunk += "        {0} result;\n".format(self.type)
            thunk += "    } *params = args;\n"
        else:
            thunk += "    struct {0}_params *params = args;\n".format(self.name)
        thunk += self.body(conv, params_prefix="params->")
        thunk += "}\n"
        if not conv:
            thunk += "#endif /* _WIN64 */\n"
        thunk += "\n"
        return thunk

    def loader_thunk(self, prefix=None):
        thunk = self.prototype(call_conv="WINAPI", prefix=prefix)
        thunk += "\n{\n"
        thunk += self.loader_body()
        thunk += "}\n\n"
        return thunk

    def trace(self, message=None, trace_func=None, params_prefix="", conv=False):
        """ Create a trace string including all parameters.

        Args:
            message (str, optional): text to print at start of trace message e.g. 'stub: '
            trace_func (str, optional): used to override trace function e.g. FIXME, printf, etcetera.
        """
        if trace_func is not None:
            trace = "{0}(\"".format(trace_func)
        else:
            trace = "TRACE(\""

        if message is not None:
            trace += message

        # First loop is for all the format strings.
        trace += ", ".join([p.format_string(conv) for p in self.params])
        trace += "\\n\""

        # Second loop for parameter names and optional conversions.
        for param in self.params:
            if param.format_conv is not None:
                trace += ", " + param.format_conv.format("{0}{1}".format(params_prefix, param.name))
            else:
                trace += ", {0}{1}".format(params_prefix, param.name)
        trace += ");\n"

        return trace


class VkFunctionPointer(object):
    def __init__(self, _type, name, members, forward_decls):
        self.name = name
        self.members = members
        self.type = _type
        self.required = False
        self.forward_decls = forward_decls

    @staticmethod
    def from_xml(funcpointer):
        if not api_is_vulkan(funcpointer):
            return None

        members = []
        begin = None

        for t in funcpointer.findall("type"):
            # General form:
            # <type>void</type>*       pUserData,
            # Parsing of the tail (anything past </type>) is tricky since there
            # can be other data on the next line like: const <type>int</type>..

            const = True if begin and "const" in begin else False
            _type = t.text
            lines = t.tail.split(",\n")
            if lines[0][0] == "*":
                pointer = "*"
                name = lines[0][1:].strip()
            else:
                pointer = None
                name = lines[0].strip()

            # Filter out ); if it is contained.
            name = name.partition(");")[0]

            # If tail encompasses multiple lines, assign the second line to begin
            # for the next line.
            try:
                begin = lines[1].strip()
            except IndexError:
                begin = None

            members.append(VkMember(const=const, _type=_type, pointer=pointer, name=name))

        _type = funcpointer.text
        name = funcpointer.find("name").text
        if "requires" in funcpointer.attrib:
            forward_decls = funcpointer.attrib.get("requires").split(",")
        else:
            forward_decls = []
        return VkFunctionPointer(_type, name, members, forward_decls)

    def definition(self):
        text = ""
        # forward declare required structs
        for decl in self.forward_decls:
            text += "typedef struct {0} {0};\n".format(decl)

        text += "{0} {1})(\n".format(self.type, self.name)

        first = True
        if len(self.members) > 0:
            for m in self.members:
                if first:
                    text += "    " + m.definition()
                    first = False
                else:
                    text += ",\n    " + m.definition()
        else:
            # Just make the compiler happy by adding a void parameter.
            text += "void"
        text += ");\n"
        return text

    def is_alias(self):
        return False

class VkHandle(object):
    def __init__(self, name, _type, parent, alias=None):
        self.name = name
        self.type = _type
        self.parent = parent
        self.alias = alias
        self.required = False
        self.object_type = None

    @staticmethod
    def from_alias(handle, alias):
        name = handle.attrib.get("name")
        return VkHandle(name, alias.type, alias.parent, alias=alias)

    @staticmethod
    def from_xml(handle):
        if not api_is_vulkan(handle):
            return None

        name = handle.find("name").text
        _type = handle.find("type").text
        parent = handle.attrib.get("parent") # Most objects have a parent e.g. VkQueue has VkDevice.
        return VkHandle(name, _type, parent)

    def dispatch_table(self, param):
        if not self.is_dispatchable():
            return None

        if self.parent is None:
            # Should only happen for VkInstance
            return "vulkan_instance_from_handle({0})".format(param)
        elif self.name == "VkCommandBuffer":
            return "wine_cmd_buffer_from_handle({0})->device".format(param)
        elif self.name == "VkDevice":
            return "vulkan_device_from_handle({0})".format(param)
        elif self.name == "VkPhysicalDevice":
            return "vulkan_physical_device_from_handle({0})->instance".format(param)
        elif self.name == "VkQueue":
            return "vulkan_queue_from_handle({0})->device".format(param)
        elif self.parent in ["VkInstance", "VkPhysicalDevice"]:
            return "{0}->instance".format(param)
        elif self.parent in ["VkDevice", "VkCommandPool"]:
            return "{0}->device".format(param)
        else:
            LOGGER.error("Unhandled dispatchable parent: {0}".format(self.parent))

    def definition(self):
        """ Generates handle definition e.g. VK_DEFINE_HANDLE(vkInstance) """

        # Legacy types are typedef'ed to the new type if they are aliases.
        if self.is_alias():
            return "typedef {0} {1};\n".format(self.alias.name, self.name)

        return "{0}({1})\n".format(self.type, self.name)

    def is_alias(self):
        return self.alias is not None

    def is_dispatchable(self):
        """ Some handles like VkInstance, VkDevice are dispatchable objects,
        which means they contain a dispatch table of function pointers.
        """
        return self.type == "VK_DEFINE_HANDLE"

    def is_required(self):
        return self.required

    def host_handle(self, name):
        """ Provide access to the host handle of a wrapped object. """

        if self.name == "VkCommandBuffer":
            return "wine_cmd_buffer_from_handle({0})->host.command_buffer".format(name)
        if self.name == "VkCommandPool":
            return "wine_cmd_pool_from_handle({0})->host.command_pool".format(name)
        if self.name == "VkDebugUtilsMessengerEXT":
            return "wine_debug_utils_messenger_from_handle({0})->host.debug_messenger".format(name)
        if self.name == "VkDebugReportCallbackEXT":
            return "wine_debug_report_callback_from_handle({0})->host.debug_callback".format(name)
        if self.name == "VkDeferredOperationKHR":
            return "wine_deferred_operation_from_handle({0})->host.deferred_operation".format(name)
        if self.name == "VkDevice":
            return "vulkan_device_from_handle({0})->host.device".format(name)
        if self.name == "VkInstance":
            return "vulkan_instance_from_handle({0})->host.instance".format(name)
        if self.name == "VkDeviceMemory":
            return "wine_device_memory_from_handle({0})->host.device_memory".format(name)
        if self.name == "VkPhysicalDevice":
            return "vulkan_physical_device_from_handle({0})->host.physical_device".format(name)
        if self.name == "VkQueue":
            return "vulkan_queue_from_handle({0})->host.queue".format(name)
        if self.name == "VkSurfaceKHR":
            return "vulkan_surface_from_handle({0})->host.surface".format(name)
        if self.name == "VkSwapchainKHR":
            return "vulkan_swapchain_from_handle({0})->host.swapchain".format(name)
        if self.is_dispatchable():
            LOGGER.error("Unhandled host handle for: {0}".format(self.name))
        return None

    def unwrap_handle(self, name, unwrap):
        if unwrap == Unwrap.HOST:
            return self.host_handle(name)
        assert unwrap != Unwrap.NONE
        return None

    def is_wrapped(self):
        return self.host_handle("test") is not None


class VkVariable(object):
    def __init__(self, const=False, type_info=None, type=None, name=None, pointer=None, array_lens=[],
                 dyn_array_len=None, object_type=None, optional=False, returnedonly=False, parent=None,
                 selection=None, selector=None):
        self.const = const
        self.type_info = type_info
        self.type = type
        self.name = name
        self.parent = parent
        self.object_type = object_type
        self.optional = optional
        self.returnedonly = returnedonly
        self.selection = selection
        self.selector = selector

        self.pointer = pointer
        self.array_lens = array_lens
        self.dyn_array_len = dyn_array_len
        self.pointer_array = False
        if isinstance(dyn_array_len, str):
            i = dyn_array_len.find(",")
            if i != -1:
                self.dyn_array_len = dyn_array_len[0:i]
                self.pointer_array = True

        if type_info:
            self.set_type_info(type_info)

    def __eq__(self, other):
        """ Compare member based on name against a string. """
        return self.name == other

    def set_type_info(self, type_info):
        """ Helper function to set type information from the type registry.
        This is needed, because not all type data is available at time of
        parsing.
        """
        self.type_info = type_info
        self.handle = type_info["data"] if type_info["category"] == "handle" else None
        self.struct = type_info["data"] if type_info["category"] == "struct" or type_info["category"] == "union" else None

    def get_dyn_array_len(self, prefix, conv):
        if isinstance(self.dyn_array_len, int):
            return self.dyn_array_len

        len_str = self.dyn_array_len
        parent = self.parent
        len = prefix

        # check if length is a member of another struct (for example pAllocateInfo->commandBufferCount)
        i = len_str.find("->")
        if i != -1:
            var = parent[parent.index(len_str[0:i])]
            len_str = len_str[i+2:]
            len = "({0})->".format(var.value(len, conv))
            parent = var.struct

        if len_str in parent:
            var = parent[parent.index(len_str)]
            len = var.value(len, conv);
            if var.is_pointer():
                len = "*" + len
        else:
            len += len_str

        if isinstance(self.parent, VkStruct) and self.parent.name in MEMBER_LENGTH_EXPRESSIONS:
            exprs = MEMBER_LENGTH_EXPRESSIONS[self.parent.name]
            if self.name in exprs:
                len = exprs[self.name].format(struct=prefix, len=len)

        return len

    def is_const(self):
        return self.const

    def is_pointer(self):
        return self.pointer is not None

    def is_pointer_pointer(self):
        return self.pointer and self.pointer.count('*') > 1

    def is_pointer_size(self):
        if self.type in ["size_t", "HWND", "HINSTANCE"] or self.type.startswith("PFN"):
            return True
        if self.is_handle() and self.handle.is_dispatchable():
            return True
        return self.is_pointer_pointer()

    def is_handle(self):
        return self.handle is not None

    def is_struct(self):
        return self.type_info["category"] == "struct"

    def is_union(self):
        return self.type_info["category"] == "union"

    def is_bitmask(self):
        return self.type_info["category"] == "bitmask"

    def is_enum(self):
        return self.type_info["category"] == "enum"

    def is_dynamic_array(self):
        """ Returns if the member is an array element.
        Vulkan uses this for dynamically sized arrays for which
        there is a 'count' parameter.
        """
        return self.dyn_array_len is not None and len(self.array_lens) == 0

    def is_static_array(self):
        """ Returns if the member is an array.
        Vulkan uses this often for fixed size arrays in which the
        length is part of the member.
        """
        return len(self.array_lens) > 0

    def is_generic_handle(self):
        """ Returns True if the member is a unit64_t containing
        a handle with a separate object type
        """
        return self.object_type != None and self.type == "uint64_t"

    def needs_alignment(self):
        """ Check if this member needs alignment for 64-bit data.
        Various structures need alignment on 64-bit variables due
        to compiler differences on 32-bit between Win32 and Linux.
        """

        if self.is_pointer():
            return False
        elif self.type == "size_t":
            return False
        elif self.type in ["uint64_t", "VkDeviceAddress", "VkDeviceSize"]:
            return True
        elif self.is_bitmask():
            return self.type_info["data"].type == "VkFlags64"
        elif self.is_enum():
            return self.type_info["data"].bitwidth == 64
        elif self.is_struct() or self.is_union():
            return self.type_info["data"].needs_alignment()
        elif self.is_handle():
            # Dispatchable handles are pointers to objects, while
            # non-dispatchable are uint64_t and hence need alignment.
            return not self.handle.is_dispatchable()
        return False

    def is_wrapped(self):
        """ Returns if variable needs unwrapping of handle. """

        if self.is_struct():
            return self.struct.is_wrapped()

        if self.is_handle():
            return self.handle.is_wrapped()

        if self.is_generic_handle():
            return True

        return False

    def needs_alloc(self, conv, unwrap):
        """ Returns True if conversion needs allocation """
        if self.is_dynamic_array():
            return self.needs_conversion(conv, unwrap, Direction.INPUT, False) \
                or self.needs_conversion(conv, unwrap, Direction.OUTPUT, False)

        return (self.is_struct() or (self.is_union() and self.selector)) and self.struct.needs_alloc(conv, unwrap)

    def needs_win32_type(self):
        return (self.is_struct() or (self.is_union() and self.selector)) and self.struct.needs_win32_type()

    def get_conversions(self, unwrap, parent_const=False):
        """ Get a list of conversions required for this parameter if any.
        Parameters which are structures may require conversion between win32
        and the host platform. This function returns a list of conversions
        required.
        """

        conversions = []

        # Collect any member conversions first, so we can guarantee
        # those functions will be defined prior to usage by the
        # 'parent' param requiring conversion.
        if self.is_struct() or (self.is_union() and self.selector):
            struct = self.struct
            is_const = self.is_const() if self.is_pointer() else parent_const

            conversions.extend(struct.get_conversions(unwrap, is_const))

            for conv in [False, True]:
                if struct.needs_conversion(conv, unwrap, Direction.INPUT, is_const):
                    conversions.append(StructConversionFunction(struct, Direction.INPUT, conv, unwrap, is_const))
                if struct.needs_conversion(conv, unwrap, Direction.OUTPUT, is_const):
                    conversions.append(StructConversionFunction(struct, Direction.OUTPUT, conv, unwrap, is_const))

        if self.is_static_array() or self.is_dynamic_array():
            for conv in [False, True]:
                if self.needs_conversion(conv, unwrap, Direction.INPUT, parent_const):
                    conversions.append(ArrayConversionFunction(self, Direction.INPUT, conv, unwrap))
                if self.needs_conversion(conv, unwrap, Direction.OUTPUT, parent_const):
                    conversions.append(ArrayConversionFunction(self, Direction.OUTPUT, conv, unwrap))

        return conversions

    def needs_ptr32_type(self):
        """ Check if variable needs to use PTR32 type. """

        return self.is_pointer() or self.is_pointer_size() or self.is_static_array()

    def value(self, prefix, conv):
        """ Returns code accessing member value, casting 32-bit pointers when needed. """

        if not conv or not self.needs_ptr32_type() or (not self.is_pointer() and self.type == "size_t"):
            return prefix + self.name

        cast_type = ""
        if self.const:
            cast_type += "const "

        if self.pointer_array or ((self.is_pointer() or self.is_static_array()) and self.is_pointer_size()):
            cast_type += "PTR32 *"
        else:
            cast_type += self.type
            if self.needs_win32_type():
                cast_type += "32"

            if self.is_pointer():
                cast_type += " {0}".format(self.pointer)
            elif self.is_static_array():
                cast_type += " *"

        return "({0})UlongToPtr({1}{2})".format(cast_type, prefix, self.name)


class VkMember(VkVariable):
    def __init__(self, const=False, struct_fwd_decl=False,_type=None, pointer=None, name=None, array_lens=[],
                 dyn_array_len=None, optional=False, values=None, object_type=None, bit_width=None,
                 returnedonly=False, parent=None, selection=None, selector=None):
        VkVariable.__init__(self, const=const, type=_type, name=name, pointer=pointer, array_lens=array_lens,
                            dyn_array_len=dyn_array_len, object_type=object_type, optional=optional,
                            returnedonly=returnedonly, parent=parent, selection=selection, selector=selector)
        self.struct_fwd_decl = struct_fwd_decl
        self.values = values
        self.bit_width = bit_width

    def __repr__(self):
        return "{0} {1} {2} {3} {4} {5} {6}".format(self.const, self.struct_fwd_decl, self.type, self.pointer,
                self.name, self.array_lens, self.dyn_array_len)

    @staticmethod
    def from_xml(member, returnedonly, parent):
        """ Helper function for parsing a member tag within a struct or union. """

        if not api_is_vulkan(member):
            return None

        name_elem = member.find("name")
        type_elem = member.find("type")

        const = False
        struct_fwd_decl = False
        member_type = None
        pointer = None
        bit_width = None

        values = member.get("values")

        if member.text:
            if "const" in member.text:
                const = True

            # Some members contain forward declarations:
            # - VkBaseInstructure has a member "const struct VkBaseInStructure *pNext"
            # - VkWaylandSurfaceCreateInfoKHR has a member "struct wl_display *display"
            if "struct" in member.text:
                struct_fwd_decl = True

        if type_elem is not None:
            member_type = type_elem.text
            if type_elem.tail is not None:
                pointer = type_elem.tail.strip() if type_elem.tail.strip() != "" else None

        name_tail = None
        if name_elem.tail and name_elem.tail.strip() != "":
            name_tail = name_elem.tail.strip()

        # Name of other member within, which stores the number of
        # elements pointed to be by this member.
        dyn_array_len = member.get("len")

        # Some members are optional, which is important for conversion code e.g. not dereference NULL pointer.
        optional = True if member.get("optional") else False

        # Usually we need to allocate memory for dynamic arrays. We need to do the same in a few other cases
        # like for VkCommandBufferBeginInfo.pInheritanceInfo. Just threat such cases as dynamic arrays of
        # size 1 to simplify code generation.
        if dyn_array_len is None and pointer is not None:
            dyn_array_len = 1

        array_lens = parse_array_lens(member)

        object_type = member.get("objecttype", None)

        # Some members are bit field values:
        # <member><type>uint32_t</type> <name>mask</name>:8</member>
        if name_tail and name_tail[0] == ':':
            LOGGER.debug("Found bit field")
            bit_width = int(name_tail[1:])

        selection = member.get("selection").split(',') if member.get("selection") else None
        selector = member.get("selector", None)

        return VkMember(const=const, struct_fwd_decl=struct_fwd_decl, _type=member_type, pointer=pointer,
                        name=name_elem.text, array_lens=array_lens, dyn_array_len=dyn_array_len, optional=optional,
                        values=values, object_type=object_type, bit_width=bit_width, returnedonly=returnedonly,
                        parent=parent, selection=selection, selector=selector)

    def copy(self, input, output, direction, conv, unwrap):
        """ Helper method for use by conversion logic to generate a C-code statement to copy this member.
            - `conv` indicates whether the statement is in a struct alignment conversion path. """

        win_type = "win32" if conv else "win64"
        suffix = convert_suffix(direction, win_type, unwrap, self.is_wrapped())

        if self.needs_conversion(conv, unwrap, direction, False):
            if self.is_dynamic_array():
                # Array length is either a variable name (string) or an int.
                count = self.get_dyn_array_len(input, conv)
                pointer_part = "pointer_" if self.pointer_array else ""
                if direction == Direction.OUTPUT:
                    return "convert_{2}_{6}array_{5}({3}{1}, {0}, {4});\n".format(self.value(output, conv),
                        self.name, self.type, input, count, suffix, pointer_part)
                else:
                    return "{0}{1} = convert_{2}_{6}array_{5}(ctx, {3}, {4});\n".format(output,
                        self.name, self.type, self.value(input, conv), count, suffix, pointer_part)
            elif self.is_static_array():
                count = self.array_lens[0]
                if len(self.array_lens) > 1:
                    LOGGER.warning("TODO: implement conversion of multidimensional static array for {0}.{1}".format(self.type, self.name))
                elif direction == Direction.OUTPUT:
                    # Needed by VkMemoryHeap.memoryHeaps
                    return "convert_{0}_array_{5}({2}{1}, {3}{1}, {4});\n".format(self.type,
                        self.name, input, output, count, suffix)
                else:
                    # Nothing needed this yet.
                    LOGGER.warning("TODO: implement copying of static array for {0}.{1}".format(self.type, self.name))
            elif self.is_handle() and self.is_wrapped():
                handle = self.type_info["data"]
                if direction == Direction.OUTPUT:
                    LOGGER.error("OUTPUT parameter {0}.{1} cannot be unwrapped".format(self.type, self.name))
                elif self.optional:
                    return "{0}{1} = {2} ? {3} : 0;\n".format(output, self.name, self.value(input, conv),
                        handle.unwrap_handle(self.value(input, conv), unwrap))
                else:
                    return "{0}{1} = {2};\n".format(output, self.name,
                        handle.unwrap_handle(self.value(input, conv), unwrap))
            elif self.is_generic_handle():
                if direction == Direction.OUTPUT:
                    LOGGER.error("OUTPUT parameter {0}.{1} cannot be unwrapped".format(self.type, self.name))
                return "{0}{1} = wine_vk_unwrap_handle({2}{3}, {2}{1});\n".format(output, self.name, input, self.object_type)
            else:
                selector_part = ", {0}{1}".format(input, self.selector) if self.selector else ""
                if direction == Direction.OUTPUT:
                    return "convert_{0}_{4}(&{2}{1}, &{3}{1}{5});\n".format(self.type,
                        self.name, input, output, suffix, selector_part)
                else:
                    ctx_param = "ctx, " if self.needs_alloc(conv, unwrap) else ""
                    return "convert_{0}_{4}({5}&{2}{1}, &{3}{1}{6});\n".format(self.type,
                        self.name, input, output, suffix, ctx_param, selector_part)
        elif self.is_static_array():
            bytes_count = "sizeof({0})".format(self.type)
            for l in self.array_lens:
                bytes_count = "{0} * ".format(l) + bytes_count
            return "memcpy({0}{1}, {2}{1}, {3});\n".format(output, self.name, input, bytes_count)
        elif conv and direction == Direction.OUTPUT and self.is_pointer():
            return "{0}{1} = PtrToUlong({2}{1});\n".format(output, self.name, input)
        elif conv and direction == Direction.INPUT and self.is_pointer():
            return "{0}{1} = UlongToPtr({2}{1});\n".format(output, self.name, input)
        elif direction == Direction.INPUT:
            return "{0}{1} = {2};\n".format(output, self.name, self.value(input, conv))
        else:
            return "{0}{1} = {2}{1};\n".format(output, self.name, input)

    def definition(self, align=False, conv=False):
        """ Generate prototype for given function.

        Args:
            align (bool, optional): Enable alignment if a type needs it. This adds WINE_VK_ALIGN(8) to a member.
            conv (bool, optional): Enable conversion if a type needs it. This appends '_host' to the name.
        """

        if conv and (self.is_pointer() or self.is_pointer_size()):
            text = "PTR32 " + self.name
            for l in self.array_lens:
                text += "[{0}]".format(l)
            return text

        text = ""
        if self.is_const():
            text += "const "

        if self.is_struct_forward_declaration():
            text += "struct "

        text += self.type
        if conv and self.needs_win32_type():
            text += "32"

        if self.is_pointer():
            text += " {0}{1}".format(self.pointer, self.name)
        else:
            if align and self.needs_alignment():
                if conv:
                    text += " DECLSPEC_ALIGN(8) " + self.name
                else:
                    text += " WINE_VK_ALIGN(8) " + self.name
            else:
                text += " " + self.name

        for l in self.array_lens:
            text += "[{0}]".format(l)

        if self.is_bit_field():
            text += ":{}".format(self.bit_width)

        return text

    def is_struct_forward_declaration(self):
        return self.struct_fwd_decl

    def is_bit_field(self):
        return self.bit_width is not None

    def needs_conversion(self, conv, unwrap, direction, struct_const):
        """ Check if member needs conversion. """

        # we can't convert unions if we don't have a selector
        if self.is_union() and not self.selector:
            return False

        is_const = self.is_const() if self.is_pointer() else struct_const

        # const members don't needs output conversion unless they are structs with non-const pointers
        if direction == Direction.OUTPUT and is_const and not self.is_struct():
            return False

        if direction == Direction.INPUT:
            # returnedonly members don't needs input conversions
            if not self.is_pointer() and self.returnedonly:
                return False
            # pointer arrays always need input conversion
            if conv and self.is_dynamic_array() and self.pointer_array:
                return True

        if self.is_handle():
            if unwrap != Unwrap.NONE and self.handle.is_wrapped():
                return True
            if conv and self.handle.is_dispatchable():
                return True
        elif self.is_generic_handle():
            if unwrap != Unwrap.NONE:
                return True
        elif self.is_struct() or self.is_union():
            if self.struct.needs_conversion(conv, unwrap, direction, is_const):
                return True

        # if pointer member needs output conversion, it also needs input conversion
        # to allocate the pointer
        if direction == Direction.INPUT and self.is_pointer() and \
           self.needs_conversion(conv, unwrap, Direction.OUTPUT, struct_const):
            return True

        return False

class VkParam(VkVariable):
    """ Helper class which describes a parameter to a function call. """

    def __init__(self, type_info, const=None, pointer=None, name=None, parent=None, array_lens=None,
                 dyn_array_len=None, object_type=None, optional=False):
        VkVariable.__init__(self, const=const, type_info=type_info, type=type_info["name"], name=name,
                            pointer=pointer, array_lens=array_lens, dyn_array_len=dyn_array_len,
                            object_type=object_type, optional=optional, parent=parent)

        self._set_format_string()

    def __repr__(self):
        return "{0} {1} {2} {3} {4} {5}".format(self.const, self.type, self.pointer, self.name, self.array_lens, self.dyn_array_len)

    @staticmethod
    def from_xml(param, types, parent):
        """ Helper function to create VkParam from xml. """

        if not api_is_vulkan(param):
            return None

        # Parameter parsing is slightly tricky. All the data is contained within
        # a param tag, but some data is within subtags while others are text
        # before or after the type tag.
        # Common structure:
        # <param>const <type>char</type>* <name>pLayerName</name></param>

        name_elem = param.find("name")
        name = name_elem.text
        # E.g. vkCmdSetBlendConstants().
        array_lens = parse_array_lens(param)

        # Name of other parameter in function prototype, which stores the number of
        # elements pointed to be by this parameter.
        dyn_array_len = param.get("len", None)

        const = param.text.strip() if param.text else None
        type_elem = param.find("type")
        pointer = type_elem.tail.strip() if type_elem.tail.strip() != "" else None
        assert not pointer or pointer.count('*') <= 2 # only pointers and pointer of pointers are supported

        attr = param.get("optional")
        optional = attr and attr.startswith("true")

        # Some uint64_t are actually handles with a separate type param
        object_type = param.get("objecttype", None)

        # Since we have parsed all types before hand, this should not happen.
        type_info = types.get(type_elem.text, None)
        if type_info is None:
            LOGGER.error("type info not found for: {0}".format(type_elem.text))

        return VkParam(type_info, const=const, pointer=pointer, name=name, array_lens=array_lens,
                       dyn_array_len=dyn_array_len, object_type=object_type, optional=optional,
                       parent=parent)

    def _set_format_string(self):
        """ Internal helper function to be used by constructor to set format string. """

        # Determine a format string used by code generation for traces.
        # 64-bit types need a conversion function.
        self.format_conv = None
        if self.is_static_array() or self.is_pointer():
            self.format_str = "%p"
        else:
            if self.type_info["category"] in ["bitmask"]:
                # Since 1.2.170 bitmasks can be 32 or 64-bit, check the basetype.
                if self.type_info["data"].type == "VkFlags64":
                    self.format_str = "0x%s"
                    self.format_conv = "wine_dbgstr_longlong({0})"
                else:
                    self.format_str = "%#x"
            elif self.type_info["category"] in ["enum"]:
                self.format_str = "%#x"
            elif self.is_handle():
                # We use uint64_t for non-dispatchable handles as opposed to pointers
                # for dispatchable handles.
                if self.handle.is_dispatchable():
                    self.format_str = "%p"
                else:
                    self.format_str = "0x%s"
                    self.format_conv = "wine_dbgstr_longlong({0})"
            elif self.type == "float":
                self.format_str = "%f"
            elif self.type == "int":
                self.format_str = "%d"
            elif self.type == "int32_t":
                self.format_str = "%d"
            elif self.type == "size_t":
                self.format_str = "0x%s"
                self.format_conv = "wine_dbgstr_longlong({0})"
            elif self.type in ["uint16_t", "uint32_t", "VkBool32"]:
                self.format_str = "%u"
            elif self.type in ["uint64_t", "VkDeviceAddress", "VkDeviceSize"]:
                self.format_str = "0x%s"
                self.format_conv = "wine_dbgstr_longlong({0})"
            elif self.type == "HANDLE":
                self.format_str = "%p"
            elif self.type in ["VisualID", "xcb_visualid_t", "RROutput", "zx_handle_t", "NvSciBufObj", "NvSciBufAttrList", "NvSciSyncAttrList"]:
                # Don't care about specific types for non-Windows platforms.
                self.format_str = ""
            else:
                LOGGER.warning("Unhandled type: {0}".format(self.type_info))

    def copy(self, direction, conv, unwrap, prefix=""):
        win_type = "win32" if conv else "win64"
        suffix = convert_suffix(direction, win_type, unwrap, self.is_wrapped())

        if direction == Direction.INPUT:
            ctx_param = "ctx, " if self.needs_alloc(conv, unwrap) else ""
            if self.is_dynamic_array():
                return "    {0}_host = convert_{2}_array_{4}({5}{1}, {3});\n".format(self.name, self.value(prefix, conv),
                    self.type, self.get_dyn_array_len(prefix, conv), suffix, ctx_param)
            elif self.optional:
                ret  = "    if ({0}{1})\n".format(prefix, self.name)
                ret += "    {\n"
                ret += "        {0}_host = conversion_context_alloc(ctx, sizeof(*{0}_host));\n".format(self.name)
                ret += "        convert_{0}_{3}({4}{1}, {2}_host);\n".format(self.type, self.value(prefix, conv),
                    self.name, suffix, ctx_param)
                ret += "    }\n"
                return ret
            elif self.is_struct():
                return "    convert_{0}_{3}({4}{1}, &{2}_host);\n".format(self.type, self.value(prefix, conv),
                    self.name, suffix, ctx_param)
            elif self.is_pointer_size() and self.type != "size_t":
                return "    {0}_host = UlongToPtr(*{1});\n".format(self.name, self.value(prefix, conv))
            else:
                return "    {0}_host = *{1};\n".format(self.name, self.value(prefix, conv))
        else:
            if self.is_dynamic_array():
                return "    convert_{0}_array_{1}({2}_host, {3}, {4});\n".format(
                    self.type, suffix, self.name, self.value(prefix, conv).replace('const ', ''),
                    self.get_dyn_array_len(prefix, conv))
            elif self.is_struct():
                ref_part = "" if self.optional else "&"
                return "    convert_{0}_host_to_{3}({4}{2}_host, {1});\n".format(
                    self.type, self.value(prefix, conv), self.name, win_type, ref_part)
            elif self.is_pointer_size() and self.type != "size_t":
                return "    *{0} = PtrToUlong({1}_host);\n".format(self.value(prefix, conv), self.name)
            else:
                return "    *{0} = {1}_host;\n".format(self.value(prefix, conv), self.name)

    def definition(self, postfix=None, is_member=False, conv=False):
        """ Return prototype for the parameter. E.g. 'const char *foo' """

        if is_member and conv and self.needs_ptr32_type():
            return "PTR32 {0}".format(self.name)

        proto = ""
        if self.const:
            proto += self.const + " "

        proto += self.type
        name = self.name
        if conv and self.needs_win32_type():
            proto += "32"

        if is_member and self.needs_alignment():
            proto += " DECLSPEC_ALIGN(8)"

        if self.is_pointer():
            proto += " {0}{1}".format(self.pointer, name)
        elif is_member and self.is_static_array():
            proto += " *" + name
        else:
            proto += " " + name

        # Allows appending something to the variable name useful for
        # win32 to host conversion.
        if postfix is not None:
            proto += postfix

        if not is_member:
            for l in self.array_lens:
                proto += "[{0}]".format(l)

        return proto

    def dispatch_table(self, params_prefix, conv):
        """ Return functions dispatch table pointer for dispatchable objects. """

        if not self.is_dispatchable():
            return None

        return self.handle.dispatch_table(self.value(params_prefix, conv))

    def format_string(self, conv):
        if conv and self.needs_ptr32_type() and (self.type != "size_t" or self.is_pointer()):
            return "%#x"
        return self.format_str

    def is_dispatchable(self):
        if not self.is_handle():
            return False

        return self.handle.is_dispatchable()

    def needs_conversion(self, conv, unwrap, direction, parent_const=False):
        """ Check if param needs conversion. """

        if self.is_pointer_pointer() and self.type != 'void':
            if direction == Direction.INPUT or not self.is_const():
                return conv

        if self.is_struct():
            return self.struct.needs_conversion(conv, unwrap, direction, self.is_const())

        if self.is_handle():
            # non-pointer handles are handled inline in thunks
            if not self.is_dynamic_array() and not self.is_static_array():
                return conv and self.is_pointer() and self.handle.is_dispatchable()

            # vkAllocateCommandBuffers is a special case, we use it in our private thunk as an input param
            param_direction = (Direction.INPUT if self.is_const() else Direction.OUTPUT)
            if self.name == "pCommandBuffers":
                param_direction = Direction.INPUT
            if direction != param_direction:
                return False

            if unwrap != Unwrap.NONE and self.handle.is_wrapped():
                return True
            if conv and self.handle.is_dispatchable():
                return True
        elif self.is_pointer() and self.is_pointer_size():
            return conv

        return False

    def needs_variable(self, conv, unwrap):
        if self.needs_conversion(conv, unwrap, Direction.INPUT):
            return True
        if self.needs_conversion(conv, unwrap, Direction.OUTPUT):
            return True
        return False

    def spec(self):
        """ Generate spec file entry for this parameter. """

        if self.is_pointer() and self.type == "char":
            return "str"
        if self.is_dispatchable() or self.is_pointer() or self.is_static_array():
            return "ptr"
        if self.type_info["category"] in ["bitmask"]:
            # Since 1.2.170 bitmasks can be 32 or 64-bit, check the basetype.
            if self.type_info["data"].type == "VkFlags64":
                return "int64"
            else:
                return "long"
        if self.type_info["category"] in ["enum"]:
            return "long"
        if self.is_handle() and not self.is_dispatchable():
            return "int64"
        if self.type == "float":
            return "float"
        if self.type in ["int", "int32_t", "size_t", "uint16_t", "uint32_t", "VkBool32"]:
            return "long"
        if self.type in ["uint64_t", "VkDeviceSize"]:
            return "int64"

        LOGGER.error("Unhandled spec conversion for type: {0}".format(self.type))

    def variable(self, conv, unwrap, params_prefix=""):
        """ Returns 'glue' code during generation of a function call on how to access the variable.
        This function handles various scenarios such as 'unwrapping' if dispatchable objects and
        renaming of parameters in case of win32 -> host conversion.

        Args:
            conv (bool, optional): Enable conversion if the param needs it. This appends '_host' to the name.
        """

        # Hack until we enable allocation callbacks from ICD to application. These are a joy
        # to enable one day, because of calling convention conversion.
        if unwrap != Unwrap.NONE and "VkAllocationCallbacks" in self.type:
            LOGGER.debug("TODO: setting NULL VkAllocationCallbacks for {0}".format(self.name))
            return "NULL"

        if self.needs_variable(conv, unwrap):
            if self.is_dynamic_array() or self.optional:
                return "{0}_host".format(self.name)
            else:
                return "&{0}_host".format(self.name)

        p = self.value(params_prefix, conv)

        if unwrap != Unwrap.NONE:
            unwrap_handle = None
            if self.object_type != None and self.type == "uint64_t":
                unwrap_handle = "wine_vk_unwrap_handle({0}{1}, {0}{2})".format(
                    params_prefix, self.object_type, self.name)

            elif self.is_handle():
                # We need to pass the host handle to the host Vulkan calls and
                # the wine driver's handle to calls which are wrapped by the driver.
                unwrap_handle = self.handle.unwrap_handle(p, unwrap)
            if unwrap_handle:
                if self.optional:
                    unwrap_handle = "{0}{1} ? {2} : 0".format(params_prefix, self.name, unwrap_handle)
                return unwrap_handle

        return p


class VkStruct(Sequence):
    """ Class which represents the type union and struct. """

    def __init__(self, name, members, returnedonly, structextends, alias=None, union=False):
        self.name = name
        self.members = members
        self.returnedonly = returnedonly
        self.structextends = structextends
        self.required = False
        self.alias = alias
        self.union = union
        self.type_info = None # To be set later.
        self.struct_extensions = []
        self.aliased_by = []

    def __getitem__(self, i):
        return self.members[i]

    def __len__(self):
        return len(self.members)

    @staticmethod
    def from_alias(struct, alias):
        name = struct.attrib.get("name")
        aliasee = VkStruct(name, alias.members, alias.returnedonly, alias.structextends, alias=alias)

        alias.add_aliased_by(aliasee)
        return aliasee

    @staticmethod
    def from_xml(struct):
        if not api_is_vulkan(struct):
            return None

        # Unions and structs are the same parsing wise, but we need to
        # know which one we are dealing with later on for code generation.
        union = True if struct.attrib["category"] == "union" else False

        name = struct.attrib.get("name")

        # 'Output' structures for which data is filled in by the API are
        # marked as 'returnedonly'.
        returnedonly = True if struct.attrib.get("returnedonly") else False

        # Those structs seem to be broken in spec, they are specified as
        # returned only, but documented as input structs.
        if name in ["VkPipelineShaderStageRequiredSubgroupSizeCreateInfo"]:
            returnedonly = False

        # Those structs don't have returnedonly in spec, but they could (should?).
        if name in ["VkSurfaceCapabilitiesPresentBarrierNV"]:
            returnedonly = True

        structextends = struct.attrib.get("structextends")
        structextends = structextends.split(",") if structextends else []

        s = VkStruct(name, [], returnedonly, structextends, union=union)
        for member in struct.findall("member"):
            vk_member = VkMember.from_xml(member, returnedonly, s)
            if vk_member:
                s.members.append(vk_member)

        return s

    @staticmethod
    def decouple_structs(structs):
        """ Helper function which decouples a list of structs.
        Structures often depend on other structures. To make the C compiler
        happy we need to define 'substructures' first. This function analyzes
        the list of structures and reorders them in such a way that they are
        decoupled.
        """

        tmp_structs = list(structs) # Don't modify the original structures.
        decoupled_structs = []

        while (len(tmp_structs) > 0):
            # Iterate over a copy because we want to modify the list inside the loop.
            for struct in list(tmp_structs):
                dependends = False

                if not struct.required:
                    tmp_structs.remove(struct)
                    continue

                for m in struct:
                    if not (m.is_struct() or m.is_union()):
                        continue

                    # VkBaseInstructure and VkBaseOutStructure reference themselves.
                    if m.type == struct.name:
                        break

                    found = False
                    # Check if a struct we depend on has already been defined.
                    for s in decoupled_structs:
                        if s.name == m.type:
                            found = True
                            break

                    if not found:
                        # Check if the struct we depend on is even in the list of structs.
                        # If found now, it means we haven't met all dependencies before we
                        # can operate on the current struct.
                        # When generating 'host' structs we may not be able to find a struct
                        # as the list would only contain the structs requiring conversion.
                        for s in tmp_structs:
                            if s.name == m.type:
                                dependends = True
                                break

                if dependends == False:
                    decoupled_structs.append(struct)
                    tmp_structs.remove(struct)

        return decoupled_structs

    def definition(self, align=False, conv=False):
        """ Convert structure to textual definition.

        Args:
            align (bool, optional): enable alignment to 64-bit for win32 struct compatibility.
            conv (bool, optional): enable struct conversion if the struct needs it.
            postfix (str, optional): text to append to end of struct name, useful for struct renaming.
        """

        if self.is_alias():
            return ""

        suffix = "32" if conv else ""
        if self.union:
            text = "typedef union {0}".format(self.name)
        else:
            text = "typedef struct {0}".format(self.name)
        text += suffix

        text += "\n{\n"

        for m in self:
            if align and m.needs_alignment():
                text += "    {0};\n".format(m.definition(align=align, conv=conv))
            else:
                text += "    {0};\n".format(m.definition(conv=conv))

        text += "}} {0}{1};\n".format(self.name, suffix)

        for aliasee in self.aliased_by:
            text += "typedef {0}{2} {1}{2};\n".format(self.name, aliasee.name, suffix)

        return text

    def is_alias(self):
        return bool(self.alias)

    def add_aliased_by(self, aliasee):
        self.aliased_by.append(aliasee)

    def needs_alignment(self):
        """ Check if structure needs alignment for 64-bit data.
        Various structures need alignment on 64-bit variables due
        to compiler differences on 32-bit between Win32 and Linux.
        """

        for m in self.members:
            if self.name == m.type:
                continue
            if m.needs_alignment():
                return True
        return False

    def is_wrapped(self):
        """ Returns if struct members need unwrapping of handle. """

        for m in self.members:
            if self.name == m.type:
                continue
            if m.is_wrapped():
                return True
        return False

    def needs_extensions_conversion(self, conv, direction):
        """ Check if struct contains extensions chain that needs to be converted """

        if direction == Direction.INPUT and self.name in STRUCT_CHAIN_CONVERSIONS:
            return True

        if not "pNext" in self:
            return False
        is_const = self.members[self.members.index("pNext")].is_const()
        # VkOpticalFlowSessionCreateInfoNV is missing const in its pNext pointer
        if self.name in ["VkOpticalFlowSessionCreateInfoNV",
                         "VkDescriptorBufferBindingInfoEXT"]:
            is_const = True

        for e in self.struct_extensions:
            if not e.required:
                continue
            if e.needs_conversion(conv, Unwrap.HOST, direction, is_const, check_extensions=False):
                return True
            if direction == Direction.INPUT:
                # we need input conversion of structs containing struct chain even if it's returnedonly,
                # so that we have a chance to allocate buffers
                if e.needs_conversion(conv, Unwrap.HOST, Direction.OUTPUT, is_const, check_extensions=False):
                    return True

        return False

    def needs_conversion(self, conv, unwrap, direction, is_const, check_extensions=True):
        """ Check if struct needs conversion. """

        # VkAllocationCallbacks never needs conversion
        if self.name == "VkAllocationCallbacks":
            return False

        # pFixedRateFlags field is missing const, but it doesn't need output conversion
        if direction == Direction.OUTPUT and self.name == "VkImageCompressionControlEXT":
            return False

        needs_output_copy = False

        for m in self.members:
            if self.name == m.type:
                continue

            if m.name == "pNext":
                # pNext is a pointer, so it always needs conversion
                if conv and direction == Direction.INPUT:
                    return True
                # we need input conversion of structs containing struct chain even if it's returnedonly
                if direction == Direction.INPUT and \
                   self.needs_conversion(conv, unwrap, Direction.OUTPUT, is_const):
                    return True
                continue

            # for non-pointer members, check for returnedonly and const attributes
            if not m.is_pointer() or m.type == "void":
                if direction == Direction.INPUT:
                    if self.returnedonly:
                        continue
                else:
                    if is_const or m.is_const():
                        continue

            # check alignment and pointer-sized members for 32-bit conversions
            if conv and (direction == Direction.INPUT or not is_const):
                if m.is_pointer() or m.is_pointer_size():
                    return True
                # we don't check structs here, they will will be traversed by needs_conversion chain anyway
                if not m.is_struct() and m.needs_alignment():
                    return True

            if m.needs_conversion(conv, unwrap, direction, is_const):
                return True

            # pointers will be handled by needs_conversion, but if we have any other non-const
            # member, we may need to copy output
            if direction == Direction.OUTPUT and not m.is_pointer() and not is_const and not m.is_const():
                needs_output_copy = True

        # if output needs any copy and we need input conversion, then we also need output conversion
        if needs_output_copy and self.needs_conversion(conv, unwrap, Direction.INPUT, check_extensions):
            return True

        return check_extensions and self.needs_extensions_conversion(conv, direction)

    def needs_alloc(self, conv, unwrap):
        """ Check if any struct member needs some memory allocation."""

        if self.needs_extensions_conversion(conv, Direction.INPUT):
            return True

        for m in self.members:
            if self.name == m.type:
                continue
            if m.needs_alloc(conv, unwrap):
                return True

        return False

    def needs_win32_type(self):
        # VkAllocationCallbacks never needs conversion
        if self.name == "VkAllocationCallbacks":
            return False

        for m in self.members:
            if self.name == m.type:
                continue
            if m.is_pointer() or m.is_pointer_size():
                return True
            if m.needs_alignment():
                return True
            if (m.is_struct() or m.is_union()) and m.struct.needs_win32_type():
                return True

    def set_type_info(self, types):
        """ Helper function to set type information from the type registry.
        This is needed, because not all type data is available at time of
        parsing.
        """
        for m in self.members:
            type_info = types[m.type]
            m.set_type_info(type_info)

    def get_conversions(self, unwrap, parent_const):
        conversions = []

        # Collect any conversion for any extension structs.
        for e in self.struct_extensions:
            if not e.required:
                continue
            conversions.extend(e.get_conversions(Unwrap.HOST, parent_const))

        # Collect any conversion for any member structs.
        for m in self:
            if m.type == self.name:
                continue
            conversions.extend(m.get_conversions(unwrap, parent_const))

        return conversions


class StructConversionFunction(object):
    def __init__(self, struct, direction, conv, unwrap, const):
        self.direction = direction
        self.operand = struct
        self.type = struct.name
        self.conv = conv
        self.unwrap = unwrap
        self.const = const

        name = "convert_{0}_".format(self.type)
        win_type = "win32" if self.conv else "win64"
        name += convert_suffix(direction, win_type, unwrap, struct.is_wrapped())
        self.name = name

    def __eq__(self, other):
        return self.name == other.name

    def member_needs_copy(self, struct, m):
        if self.direction == Direction.OUTPUT:
            if m.name in ["sType", "pNext"]:
                return False
            if self.const and not m.is_pointer():
                return False
            if m.is_const() and not m.needs_conversion(self.conv, self.unwrap, Direction.OUTPUT, self.const):
                return False
        else:
            if m.name == "pNext":
                return True
            if m.name != "sType" and struct.returnedonly and not m.needs_conversion(
                    self.conv, self.unwrap, Direction.INPUT, self.const):
                return False
        return True

    def definition(self):
        """ Helper function for generating a struct conversion function. """

        # It doesn't make sense to generate conversion functions for non-struct variables
        # which aren't in arrays, as this should be handled by the copy() function
        if not isinstance(self.operand, VkStruct):
            return ""

        body = ""

        if not self.conv:
            body += "#ifdef _WIN64\n"

        needs_alloc = self.direction != Direction.OUTPUT and self.operand.needs_alloc(self.conv, self.unwrap)
        win_type = self.type
        if self.conv and self.operand.needs_win32_type():
            win_type += "32"
        if self.direction == Direction.OUTPUT and self.const:
            win_type = "const " + win_type

        if self.conv:
            body += "static inline void {0}(".format(self.name)

            if self.direction == Direction.OUTPUT:
                params = ["const {0} *in".format(self.type), "{0} *out".format(win_type)]
            else:
                params = ["const {0} *in".format(win_type), "{0} *out".format(self.type)]

            if self.operand.union:
                params.append("VkFlags selector")

            # Generate parameter list
            if needs_alloc:
                body += "struct conversion_context *ctx, "
            body += ", ".join(p for p in params)
            body += ")\n"

        else:
            body += "static inline void {0}(".format(self.name)

            params = ["const {0} *in".format(self.type), "{0} *out".format(self.type)]

            # Generate parameter list
            if needs_alloc:
                body += "struct conversion_context *ctx, "
            body += ", ".join(p for p in params)
            body += ")\n"

        needs_extensions = self.operand.needs_extensions_conversion(self.conv, self.direction)

        if self.direction == Direction.OUTPUT and not any([any([self.member_needs_copy(ext, m) for m in ext]) for ext in self.operand.struct_extensions]):
            needs_extensions = False

        body += "{\n"
        if needs_extensions:
            if self.direction == Direction.INPUT:
                if self.conv:
                    body += "    const VkBaseInStructure32 *in_header;\n"
                else:
                    body += "    const VkBaseInStructure *in_header;\n"
                body += "    VkBaseOutStructure *out_header = (void *)out;\n\n"
            else:
                body += "    const VkBaseInStructure *in_header;\n"
                if self.conv:
                    body += "    VkBaseOutStructure32 *out_header = (void *)out;\n\n"
                else:
                    body += "    VkBaseOutStructure *out_header = (void *)out;\n\n"

        body += "    if (!in) return;\n\n"

        for m in self.operand:
            if not self.member_needs_copy(self.operand, m):
                continue
            if m.name == "pNext" and (needs_extensions or self.conv):
                body += "    out->pNext = NULL;\n"
                continue

            if m.selection:
                body += "    if ("
                body += " || ".join("selector == {}".format(s) for s in m.selection)
                body += ")\n    "

            body += "    " + m.copy("in->", "out->", self.direction, self.conv, self.unwrap)

        if needs_extensions:
            if self.conv and self.direction == Direction.INPUT:
                body += "\n    for (in_header = UlongToPtr(in->pNext); in_header; in_header = UlongToPtr(in_header->pNext))\n"
            else:
                body += "\n    for (in_header = (void *)in->pNext; in_header; in_header = (void *)in_header->pNext)\n"
            body += "    {\n"
            body += "        switch (in_header->sType)\n"
            body += "        {\n"

            ident = "            "

            if self.direction == Direction.INPUT and self.type in STRUCT_CHAIN_CONVERSIONS:
                for i in STRUCT_CHAIN_CONVERSIONS[self.type]:
                    body += "        case {0}:\n".format(i)
                body += ident + "break;\n"

            for ext in self.operand.struct_extensions:
                if not ext.required:
                    continue

                if self.direction == Direction.OUTPUT and not any([self.member_needs_copy(ext, m) for m in ext]):
                    continue

                stype = next(x for x in ext.members if x.name == "sType").values
                win_type = ext.name + "32" if self.conv and ext.needs_win32_type() else ext.name
                if self.direction == Direction.INPUT:
                    in_type = "const " + win_type
                    out_type = ext.name
                else:
                    in_type = "const " + ext.name
                    out_type = win_type

                body += "        case {0}:\n".format(stype)
                body += "        {\n"
                if self.direction == Direction.INPUT:
                    body += ident + "{0} *out_ext = conversion_context_alloc(ctx, sizeof(*out_ext));\n".format(out_type)
                elif self.conv:
                    body += ident + "{0} *out_ext = find_next_struct32(out_header, {1});\n".format(out_type, stype)
                else:
                    body += ident + "{0} *out_ext = find_next_struct(out_header, {1});\n".format(out_type, stype)

                copy_body = ""

                for m in ext:
                    if m.name == "sType":
                        copy_body += ident + "out_ext->sType = {0};\n".format(stype)
                        continue
                    if not self.member_needs_copy(ext, m):
                        continue
                    if m.name == "pNext":
                        copy_body += ident + "out_ext->pNext = NULL;\n"
                        continue
                    copy_body += ident + m.copy("in_ext->", "out_ext->", self.direction, self.conv, Unwrap.HOST)

                # Generate the definition of "in_ext" if we need it
                if "in_ext->" in copy_body:
                    body += ident + "{0} *in_ext = ({0} *)in_header;\n".format(in_type)
                body += copy_body

                if self.direction == Direction.INPUT:
                    body += ident + "out_header->pNext = (void *)out_ext;\n"
                body += ident + "out_header = (void *)out_ext;\n"
                body += ident + "break;\n"
                body += "        }\n"

            body += "        default:\n"
            if self.direction == Direction.INPUT:
                body += ident + "FIXME(\"Unhandled sType %u.\\n\", in_header->sType);\n"
            body += "            break;\n"
            body += "        }\n"
            body += "    }\n"
        elif self.conv and self.direction == Direction.INPUT and "pNext" in self.operand:
            body += "    if (in->pNext)\n"
            body += "        FIXME(\"Unexpected pNext\\n\");\n"

        body += "}\n"
        if not self.conv:
            body += "#endif /* _WIN64 */\n"
        body += "\n"

        return body


class ArrayConversionFunction(object):
    def __init__(self, array, direction, conv, unwrap):
        self.array = array
        self.direction = direction
        self.type = array.type
        self.conv = conv
        self.unwrap = unwrap

        if array.is_static_array() and direction == Direction.INPUT:
            LOGGER.error("Static array input conversion is not supported")

        name = "convert_{0}_".format(array.type)
        if array.pointer_array:
            name += "pointer_"
        name += "array_"
        win_type = "win32" if self.conv else "win64"
        name += convert_suffix(direction, win_type, unwrap, array.is_wrapped())
        self.name = name

    def __eq__(self, other):
        return self.name == other.name

    def definition(self):
        """ Helper function for generating a conversion function for array operands. """

        body = ""

        if not self.conv:
            body += "#ifdef _WIN64\n"

        needs_alloc = self.direction != Direction.OUTPUT and self.array.needs_alloc(self.conv, self.unwrap)
        pointer_array = self.array.pointer_array or self.array.is_pointer_pointer()

        win_type = self.type
        if self.conv:
            if self.array.needs_win32_type():
                win_type += "32"
            elif self.array.is_handle() and self.array.handle.is_dispatchable():
                win_type = "PTR32"
        if self.direction == Direction.OUTPUT and self.array.is_const():
            win_type = "const " + win_type
        pointer_part = self.array.pointer if self.array.pointer else "*"

        if self.direction == Direction.OUTPUT:
            if self.conv and pointer_array:
                out = "PTR32 *out"
            else:
                out = "{0} {1}out".format(win_type, pointer_part)
            params = ["const {0} {1}in".format(self.type, pointer_part), out, "uint32_t count"]
            return_type = None
        elif self.conv and pointer_array:
            params = ["const PTR32 *in", "uint32_t count"]
            return_type = self.type
        else:
            params = ["const {0} {1}in".format(win_type, pointer_part), "uint32_t count"]
            return_type = self.type

        needs_copy = not self.array.is_struct() or self.direction != Direction.INPUT or \
            not self.array.struct.returnedonly or "pNext" in self.array.struct

        # Generate function prototype.
        if return_type:
            body += "static inline {0}{1} {2}{3}(".format(
                "const " if self.array.is_const() else "", return_type, pointer_part, self.name)
        else:
            body += "static inline void {0}(".format(self.name)
        if needs_alloc:
            body += "struct conversion_context *ctx, "
        body += ", ".join(p for p in params)
        body += ")\n{\n"

        if return_type:
            pointer = self.array.pointer.replace('const*', '*').replace(' *', '*')
            body += "    {0} {1}out;\n".format(return_type, pointer)
        if needs_copy:
            body += "    unsigned int i;\n\n"

        if return_type:
            body += "    if (!in || !count) return NULL;\n\n"
        else:
            body += "    if (!in) return;\n\n"

        if self.direction == Direction.INPUT:
            body += "    out = conversion_context_alloc(ctx, count * sizeof(*out));\n"

        if needs_copy:
            body += "    for (i = 0; i < count; i++)\n"
            body += "    {\n"

            if self.array.is_struct():
                struct = self.array.struct
                win_part = "win32" if self.conv else "win64"
                suffix = convert_suffix(self.direction, win_part, self.unwrap, struct.is_wrapped())
                ctx_part = ""
                if self.direction == Direction.INPUT and struct.needs_alloc(self.conv, self.unwrap):
                    ctx_part = "ctx, "

                if not pointer_array:
                    body += "        convert_{0}_{1}({2}&in[i], &out[i]);\n".format(
                        struct.name, suffix, ctx_part)
                else:
                    if struct.needs_conversion(self.conv, self.unwrap, self.direction, False):
                        body += "        if (in[i])\n"
                        body += "        {\n"
                        body += "            out[i] = conversion_context_alloc(ctx, sizeof(*out[i]));\n"
                        if self.conv:
                            in_param = "({0} *)UlongToPtr(in[i])".format(win_type)
                        else:
                            in_param = "in[i]"
                        body += "            convert_{0}_{1}({2}{3}, out[i]);\n".format(
                            struct.name, suffix, ctx_part, in_param)
                        body += "        }\n"
                        body += "        else\n"
                        body += "            out[i] = NULL;\n"
                    else:
                        body += "        out[i] = UlongToPtr(in[i]);\n"
            elif self.array.is_handle():
                if pointer_array:
                    LOGGER.error("Unhandled handle pointer arrays")
                handle = self.array.handle
                if not self.conv or not handle.is_dispatchable():
                    input = "in[i]"
                elif self.direction == Direction.INPUT:
                    input = "UlongToPtr(in[i])"
                else:
                    input = "PtrToUlong(in[i])"

                if self.unwrap == Unwrap.NONE or not handle.is_wrapped():
                    body += "        out[i] = {0};\n".format(input)
                elif self.direction == Direction.INPUT:
                    body += "        out[i] = {0};\n".format(handle.unwrap_handle(input, self.unwrap))
                else:
                    LOGGER.warning("Unhandled handle output conversion")
            elif pointer_array:
                if self.direction == Direction.INPUT:
                    body += "        out[i] = UlongToPtr(in[i]);\n"
                else:
                    body += "        out[i] = PtrToUlong(in[i]);\n"
            else:
                body += "        out[i] = in[i];\n"

            body += "    }\n"

        if return_type:
            body += "\n    return {0}out;\n".format("(void *)" if pointer_array else "")
        body += "}\n"

        if not self.conv:
            body += "#endif /* _WIN64 */\n"

        body += "\n"

        return body


class VkGenerator(object):
    def __init__(self, registry):
        self.registry = registry

        # Build a list conversion functions for struct conversion.
        self.conversions = []
        self.win32_structs = []
        for func in self.registry.funcs.values():
            if not func.needs_exposing():
                continue

            conversions = func.get_conversions()
            for conv in conversions:
                # Append if we don't already have this conversion.
                if not any(c == conv for c in self.conversions):
                    self.conversions.append(conv)

                if not isinstance(conv, StructConversionFunction):
                    continue

                for e in conv.operand.struct_extensions:
                    if not e.required or not e.needs_win32_type():
                        continue
                    if not any(s.name == e.name for s in self.win32_structs):
                        self.win32_structs.append(e)

                if not conv.operand.needs_win32_type():
                    continue

                # Structs can be used in different ways by different conversions
                # e.g. array vs non-array. Just make sure we pull in each struct once.
                if not any(s.name == conv.operand.name for s in self.win32_structs):
                    self.win32_structs.append(conv.operand)

    def _generate_copyright(self, f, spec_file=False):
        f.write("# " if spec_file else "/* ")
        f.write("Automatically generated from ")
        f.write(self.registry._vk)
        f.write(" and ")
        f.write(self.registry._video)
        f.write("; DO NOT EDIT!\n")

        lines = ["", "This file is generated from Vulkan vk.xml file covered",
            "by the following copyright and permission notice:"]
        lines.extend([l.rstrip(" ") for l in self.registry.copyright.splitlines()])
        lines.extend(["and from Vulkan video.xml file covered",
            "by the following copyright and permission notice:"])
        lines.extend([l.rstrip(" ") for l in self.registry.video_copyright.splitlines()])
        for line in lines:
            f.write("{0}{1}".format("# " if spec_file else " * ", line).rstrip(" ") + "\n")
        f.write("\n" if spec_file else " */\n\n")

    def generate_thunks_c(self, f):
        self._generate_copyright(f)

        f.write("#if 0\n")
        f.write("#pragma makedep unix\n")
        f.write("#endif\n\n")

        f.write("#include \"config.h\"\n\n")

        f.write("#include <stdlib.h>\n\n")

        f.write("#include \"vulkan_private.h\"\n\n")

        f.write("WINE_DEFAULT_DEBUG_CHANNEL(vulkan);\n\n")

        for struct in self.win32_structs:
            f.write(struct.definition(conv=True, align=True))
            f.write("\n")

        f.write("static uint64_t wine_vk_unwrap_handle(uint32_t type, uint64_t handle)\n")
        f.write("{\n")
        f.write("    switch(type)\n")
        f.write("    {\n")
        for handle in self.registry.handles:
            if not handle.is_required() or not handle.is_wrapped() or handle.is_alias():
                continue
            f.write("    case {}:\n".format(handle.object_type))
            if handle.is_dispatchable():
                f.write("        return (uint64_t) (uintptr_t) ")
                f.write(handle.host_handle("(({}) (uintptr_t) handle)".format(handle.name)))
            else:
                f.write("        return (uint64_t) ")
                f.write(handle.host_handle("handle"))
            f.write(";\n");
        f.write("    default:\n")
        f.write("       return handle;\n")
        f.write("    }\n")
        f.write("}\n\n")

        # Generate any conversion helper functions.
        for conv in self.conversions:
            f.write(conv.definition())

        # Create thunks for instance and device functions.
        # Global functions don't go through the thunks.
        for vk_func in self.registry.funcs.values():
            if not vk_func.needs_exposing():
                continue
            if vk_func.name in MANUAL_LOADER_FUNCTIONS:
                continue

            f.write(vk_func.thunk(prefix="thunk64_"))
            f.write(vk_func.thunk(prefix="thunk32_", conv=True))

        # Create array of device extensions.
        f.write("static const char * const vk_device_extensions[] =\n{\n")
        for ext in self.registry.extensions:
            if ext["type"] != "device":
                continue
            if ext["name"] in UNEXPOSED_EXTENSIONS:
                continue

            f.write("    \"{0}\",\n".format(ext["name"]))
        f.write("};\n\n")

        # Create array of instance extensions.
        f.write("static const char * const vk_instance_extensions[] =\n{\n")
        for ext in self.registry.extensions:
            if ext["type"] != "instance":
                continue
            if ext["name"] in UNEXPOSED_EXTENSIONS:
                continue

            f.write("    \"{0}\",\n".format(ext["name"]))
        f.write("};\n\n")

        # Create array of surface extensions.
        f.write("static const char * const vk_host_surface_extensions[] =\n{\n")
        for ext in self.registry.surface_extensions:
            if ext["name"] not in WIN_SURFACE_EXTENSIONS:
                f.write("    \"{0}\",\n".format(ext["name"]))
        f.write("};\n\n")

        f.write("BOOL wine_vk_device_extension_supported(const char *name)\n")
        f.write("{\n")
        f.write("    unsigned int i;\n")
        f.write("    for (i = 0; i < ARRAY_SIZE(vk_device_extensions); i++)\n")
        f.write("    {\n")
        f.write("        if (strcmp(vk_device_extensions[i], name) == 0)\n")
        f.write("            return TRUE;\n")
        f.write("    }\n")
        f.write("    return FALSE;\n")
        f.write("}\n\n")

        f.write("BOOL wine_vk_instance_extension_supported(const char *name)\n")
        f.write("{\n")
        f.write("    unsigned int i;\n")
        f.write("    for (i = 0; i < ARRAY_SIZE(vk_instance_extensions); i++)\n")
        f.write("    {\n")
        f.write("        if (strcmp(vk_instance_extensions[i], name) == 0)\n")
        f.write("            return TRUE;\n")
        f.write("    }\n")
        f.write("    return FALSE;\n")
        f.write("}\n\n")

        f.write("BOOL wine_vk_is_host_surface_extension(const char *name)\n")
        f.write("{\n")
        f.write("    unsigned int i;\n")
        f.write("    for (i = 0; i < ARRAY_SIZE(vk_host_surface_extensions); i++)\n")
        f.write("    {\n")
        f.write("        if (strcmp(vk_host_surface_extensions[i], name) == 0)\n")
        f.write("            return TRUE;\n")
        f.write("    }\n")
        f.write("    return FALSE;\n")
        f.write("}\n\n")

        f.write("BOOL wine_vk_is_type_wrapped(VkObjectType type)\n")
        f.write("{\n")
        f.write("    return FALSE")
        for handle in self.registry.handles:
            if not handle.is_required() or not handle.is_wrapped() or handle.is_alias():
                continue
            f.write(" ||\n        type == {}".format(handle.object_type))
        f.write(";\n")
        f.write("}\n\n")


        f.write("#ifdef _WIN64\n\n")

        f.write("const unixlib_entry_t __wine_unix_call_funcs[] =\n")
        f.write("{\n")
        f.write("    init_vulkan,\n")
        f.write("    vk_is_available_instance_function,\n")
        f.write("    vk_is_available_device_function,\n")
        for vk_func in self.registry.funcs.values():
            if not vk_func.needs_exposing():
                continue
            if vk_func.name in MANUAL_LOADER_FUNCTIONS:
                continue

            if vk_func.is_perf_critical():
                f.write("    (void *){1}{0},\n".format(vk_func.name, "thunk64_"))
            else:
                f.write("    {1}{0},\n".format(vk_func.name, "thunk64_"))
        f.write("};\n")
        f.write("C_ASSERT(ARRAYSIZE(__wine_unix_call_funcs) == unix_count);\n\n")

        f.write("#endif /* _WIN64 */\n\n")

        f.write("#ifdef _WIN64\n")
        f.write("const unixlib_entry_t __wine_unix_call_wow64_funcs[] =\n")
        f.write("#else\n")
        f.write("const unixlib_entry_t __wine_unix_call_funcs[] =\n")
        f.write("#endif\n")
        f.write("{\n")
        f.write("    init_vulkan,\n")
        f.write("    vk_is_available_instance_function32,\n")
        f.write("    vk_is_available_device_function32,\n")
        for vk_func in self.registry.funcs.values():
            if not vk_func.needs_exposing():
                continue
            if vk_func.name in MANUAL_LOADER_FUNCTIONS:
                continue

            if vk_func.is_perf_critical():
                f.write("    (void *){1}{0},\n".format(vk_func.name, "thunk32_"))
            else:
                f.write("    {1}{0},\n".format(vk_func.name, "thunk32_"))
        f.write("};\n")
        f.write("C_ASSERT(ARRAYSIZE(__wine_unix_call_funcs) == unix_count);\n")

    def generate_thunks_h(self, f, prefix):
        self._generate_copyright(f)

        f.write("#ifndef __WINE_VULKAN_THUNKS_H\n")
        f.write("#define __WINE_VULKAN_THUNKS_H\n\n")

        f.write("#define WINE_VK_VERSION VK_API_VERSION_{0}_{1}\n\n".format(WINE_VK_VERSION[0], WINE_VK_VERSION[1]))

        # Generate prototypes for device and instance functions requiring a custom implementation.
        f.write("/* Functions for which we have custom implementations outside of the thunks. */\n")
        for vk_func in self.registry.funcs.values():
            if not vk_func.needs_private_thunk():
                continue

            f.write("{0};\n".format(vk_func.prototype(prefix=prefix, is_thunk=True)))
        f.write("\n")

        f.write("#endif /* __WINE_VULKAN_THUNKS_H */\n")

    def generate_loader_thunks_c(self, f):
        self._generate_copyright(f)

        f.write("#include \"vulkan_loader.h\"\n\n")

        f.write("WINE_DEFAULT_DEBUG_CHANNEL(vulkan);\n\n")

        for vk_func in self.registry.funcs.values():
            if not vk_func.needs_exposing():
                continue
            if vk_func.name in MANUAL_LOADER_THUNKS | MANUAL_LOADER_FUNCTIONS:
                continue

            f.write(vk_func.loader_thunk())

        f.write("static const struct vulkan_func vk_device_dispatch_table[] =\n{\n")
        for vk_func in self.registry.device_funcs:
            if not vk_func.needs_exposing():
                continue

            f.write("    {{\"{0}\", {0}}},\n".format(vk_func.name))
        f.write("};\n\n")

        f.write("static const struct vulkan_func vk_phys_dev_dispatch_table[] =\n{\n")
        for vk_func in self.registry.phys_dev_funcs:
            if not vk_func.needs_exposing():
                continue

            f.write("    {{\"{0}\", {0}}},\n".format(vk_func.name))
        f.write("};\n\n")

        f.write("static const struct vulkan_func vk_instance_dispatch_table[] =\n{\n")
        for vk_func in self.registry.instance_funcs:
            if not vk_func.needs_exposing():
                continue

            f.write("    {{\"{0}\", {0}}},\n".format(vk_func.name))
        f.write("};\n\n")

        f.write("void *wine_vk_get_device_proc_addr(const char *name)\n")
        f.write("{\n")
        f.write("    unsigned int i;\n")
        f.write("    for (i = 0; i < ARRAY_SIZE(vk_device_dispatch_table); i++)\n")
        f.write("    {\n")
        f.write("        if (strcmp(vk_device_dispatch_table[i].name, name) == 0)\n")
        f.write("        {\n")
        f.write("            TRACE(\"Found name=%s in device table\\n\", debugstr_a(name));\n")
        f.write("            return vk_device_dispatch_table[i].func;\n")
        f.write("        }\n")
        f.write("    }\n")
        f.write("    return NULL;\n")
        f.write("}\n\n")

        f.write("void *wine_vk_get_phys_dev_proc_addr(const char *name)\n")
        f.write("{\n")
        f.write("    unsigned int i;\n")
        f.write("    for (i = 0; i < ARRAY_SIZE(vk_phys_dev_dispatch_table); i++)\n")
        f.write("    {\n")
        f.write("        if (strcmp(vk_phys_dev_dispatch_table[i].name, name) == 0)\n")
        f.write("        {\n")
        f.write("            TRACE(\"Found name=%s in physical device table\\n\", debugstr_a(name));\n")
        f.write("            return vk_phys_dev_dispatch_table[i].func;\n")
        f.write("        }\n")
        f.write("    }\n")
        f.write("    return NULL;\n")
        f.write("}\n\n")

        f.write("void *wine_vk_get_instance_proc_addr(const char *name)\n")
        f.write("{\n")
        f.write("    unsigned int i;\n")
        f.write("    for (i = 0; i < ARRAY_SIZE(vk_instance_dispatch_table); i++)\n")
        f.write("    {\n")
        f.write("        if (strcmp(vk_instance_dispatch_table[i].name, name) == 0)\n")
        f.write("        {\n")
        f.write("            TRACE(\"Found name=%s in instance table\\n\", debugstr_a(name));\n")
        f.write("            return vk_instance_dispatch_table[i].func;\n")
        f.write("        }\n")
        f.write("    }\n")
        f.write("    return NULL;\n")
        f.write("}\n")

    def generate_loader_thunks_h(self, f):
        self._generate_copyright(f)

        f.write("#ifndef __WINE_VULKAN_LOADER_THUNKS_H\n")
        f.write("#define __WINE_VULKAN_LOADER_THUNKS_H\n\n")

        f.write("enum unix_call\n")
        f.write("{\n")
        f.write("    unix_init,\n")
        f.write("    unix_is_available_instance_function,\n")
        f.write("    unix_is_available_device_function,\n")
        for vk_func in self.registry.funcs.values():
            if not vk_func.needs_exposing():
                continue
            if vk_func.name in MANUAL_LOADER_FUNCTIONS:
                continue

            f.write("    unix_{0},\n".format(vk_func.name))
        f.write("    unix_count,\n")
        f.write("};\n\n")

        for vk_func in self.registry.funcs.values():
            if not vk_func.needs_exposing():
                continue
            if vk_func.name in MANUAL_LOADER_FUNCTIONS:
                continue

            f.write("struct {0}_params\n".format(vk_func.name))
            f.write("{\n");
            for p in vk_func.params:
                f.write("    {0};\n".format(p.definition(is_member=True)))
            if vk_func.extra_param:
                f.write("    void *{0};\n".format(vk_func.extra_param))
            if vk_func.type != "void":
                f.write("    {0} result;\n".format(vk_func.type))
            f.write("};\n\n");

        f.write("#endif /* __WINE_VULKAN_LOADER_THUNKS_H */\n")

    def generate_vulkan_h(self, f):
        self._generate_copyright(f)
        f.write("#ifndef __WINE_VULKAN_H\n")
        f.write("#define __WINE_VULKAN_H\n\n")

        f.write("#include <windef.h>\n")
        f.write("#include <stdint.h>\n\n")

        f.write("#ifdef WINE_UNIX_LIB\n")
        f.write("#define VK_NO_PROTOTYPES\n")
        f.write("#define VKAPI_CALL\n")
        f.write('#define WINE_VK_ALIGN(x)\n')
        f.write("#endif\n\n")

        f.write("#ifndef VKAPI_CALL\n")
        f.write("#define VKAPI_CALL __stdcall\n")
        f.write("#endif\n\n")

        f.write("#ifndef VKAPI_PTR\n")
        f.write("#define VKAPI_PTR VKAPI_CALL\n")
        f.write("#endif\n\n")

        f.write("#ifndef WINE_VK_ALIGN\n")
        f.write("#define WINE_VK_ALIGN DECLSPEC_ALIGN\n")
        f.write("#endif\n\n")

        # The overall strategy is to define independent constants and datatypes,
        # prior to complex structures and function calls to avoid forward declarations.
        for const in self.registry.consts:
            # For now just generate things we may not need. The amount of parsing needed
            # to get some of the info is tricky as you need to figure out which structure
            # references a certain constant.
            f.write(const.definition())
        f.write("\n")

        for define in self.registry.defines:
            f.write(define.definition())

        for handle in self.registry.handles:
            # For backward compatibility also create definitions for aliases.
            # These types normally don't get pulled in as we use the new types
            # even in legacy functions if they are aliases.
            if handle.is_required() or handle.is_alias():
                 f.write(handle.definition())
        f.write("\n")

        for base_type in self.registry.base_types:
            f.write(base_type.definition())
        f.write("\n")

        for bitmask in self.registry.bitmasks:
            f.write(bitmask.definition())
        f.write("\n")

        # Define enums, this includes values for some of the bitmask types as well.
        for enum in self.registry.enums.values():
            if enum.required:
                f.write(enum.definition())

        for fp in self.registry.funcpointers:
            if fp.required:
                f.write(fp.definition())
        f.write("\n")

        # This generates both structures and unions. Since structures
        # may depend on other structures/unions, we need a list of
        # decoupled structs.
        # Note: unions are stored in structs for dependency reasons,
        # see comment in parsing section.
        structs = VkStruct.decouple_structs(self.registry.structs)
        for struct in structs:
            LOGGER.debug("Generating struct: {0}".format(struct.name))
            f.write(struct.definition(align=True))
            f.write("\n")

        for func in self.registry.funcs.values():
            if not func.is_required():
                LOGGER.debug("Skipping PFN definition for: {0}".format(func.name))
                continue

            f.write("typedef {0};\n".format(func.pfn(prefix="PFN", call_conv="VKAPI_PTR")))
        f.write("\n")

        f.write("#ifndef VK_NO_PROTOTYPES\n")
        for func in self.registry.funcs.values():
            if not func.is_required():
                LOGGER.debug("Skipping API definition for: {0}".format(func.name))
                continue

            LOGGER.debug("Generating API definition for: {0}".format(func.name))
            f.write("{0};\n".format(func.prototype(call_conv="VKAPI_CALL")))
        f.write("#endif /* VK_NO_PROTOTYPES */\n\n")

        f.write("#define ALL_VK_DEVICE_FUNCS \\\n")
        first = True
        for vk_func in self.registry.device_funcs:
            if not vk_func.needs_exposing():
                continue

            if not vk_func.needs_dispatch():
                LOGGER.debug("skipping {0} in ALL_VK_DEVICE_FUNCS".format(vk_func.name))
                continue

            if first:
                f.write("    USE_VK_FUNC({0})".format(vk_func.name))
                first = False
            else:
                f.write(" \\\n    USE_VK_FUNC({0})".format(vk_func.name))
        f.write("\n\n")

        f.write("#define ALL_VK_INSTANCE_FUNCS \\\n")
        first = True
        for vk_func in self.registry.instance_funcs + self.registry.phys_dev_funcs:
            if not vk_func.needs_exposing():
                continue

            if not vk_func.needs_dispatch():
                LOGGER.debug("skipping {0} in ALL_VK_INSTANCE_FUNCS".format(vk_func.name))
                continue

            if first:
                f.write("    USE_VK_FUNC({0})".format(vk_func.name))
                first = False
            else:
                f.write(" \\\n    USE_VK_FUNC({0})".format(vk_func.name))
        f.write("\n\n")

        f.write("#endif /* __WINE_VULKAN_H */\n")

    def generate_vulkan_spec(self, f):
        self._generate_copyright(f, spec_file=True)
        f.write("@ stdcall -private vk_icdGetInstanceProcAddr(ptr str)\n")
        f.write("@ stdcall -private vk_icdGetPhysicalDeviceProcAddr(ptr str)\n")
        f.write("@ stdcall -private vk_icdNegotiateLoaderICDInterfaceVersion(ptr)\n")

        # Export symbols for all Vulkan Core functions.
        for func in self.registry.funcs.values():
            if not func.is_core_func():
                continue

            # We support all Core functions except for VK_KHR_display* APIs.
            # Create stubs for unsupported Core functions.
            if func.is_required():
                f.write(func.spec())
            else:
                f.write("@ stub {0}\n".format(func.name))

        f.write("@ stdcall -private DllRegisterServer()\n")
        f.write("@ stdcall -private DllUnregisterServer()\n")

    def generate_vulkan_loader_spec(self, f):
        self._generate_copyright(f, spec_file=True)

        # Export symbols for all Vulkan Core functions.
        for func in self.registry.funcs.values():
            if not func.is_core_func():
                continue

            # We support all Core functions except for VK_KHR_display* APIs.
            # Create stubs for unsupported Core functions.
            if func.is_required():
                f.write(func.spec(symbol="winevulkan." + func.name))
            else:
                f.write("@ stub {0}\n".format(func.name))


class VkRegistry(object):
    def __init__(self, vk_xml, video_xml):
        # Used for storage of type information.
        self.base_types = None
        self.bitmasks = None
        self.consts = None
        self.defines = None
        self.enums = None
        self.funcpointers = None
        self.handles = None
        self.structs = None
        self._vk = vk_xml
        self._video = video_xml

        # We aggregate all types in here for cross-referencing.
        self.funcs = {}
        self.types = {}
        self.surface_extensions = []

        self.version_regex = re.compile(
            r'^'
            r'VK_VERSION_'
            r'(?P<major>[0-9])'
            r'_'
            r'(?P<minor>[0-9])'
            r'$'
        )

        # Overall strategy for parsing the registry is to first
        # parse all type / function definitions. Then parse
        # features and extensions to decide which types / functions
        # to actually 'pull in' for code generation. For each type or
        # function call we want we set a member 'required' to True.
        tree = ET.parse(vk_xml)
        root = tree.getroot()
        # The video XML currently only has enums, types, and part of the
        # extension data in it.
        # All of the relevant extensions and commands are in vk.xml.
        video_tree = ET.parse(video_xml)
        video_root = video_tree.getroot()

        self.copyright = root.find('./comment').text
        self.video_copyright = video_root.find('./comment').text

        root.extend(video_root)

        self._parse_enums(root)
        self._parse_types(root)
        self._parse_commands(root)

        # Pull in any required types and functions.
        self._parse_features(root)
        self._parse_extensions(root)

        for enum in self.enums.values():
            enum.fixup_64bit_aliases()

        self._match_object_types()

    def _is_feature_supported(self, feature):
        version = self.version_regex.match(feature)
        if not version:
            return True

        version = tuple(map(int, version.group('major', 'minor')))
        return version <= WINE_VK_VERSION

    def _is_extension_supported(self, extension):
        # We disable some extensions as either we haven't implemented
        # support yet or because they are for platforms other than win32.
        return extension not in UNSUPPORTED_EXTENSIONS

    def _mark_command_required(self, command):
        """ Helper function to mark a certain command and the datatypes it needs as required."""
        def mark_bitmask_dependencies(bitmask, types):
            if bitmask.requires is not None:
                types[bitmask.requires]["data"].required = True

        def mark_funcpointer_dependencies(fp, types):
            for m in fp.members:
                type_info = types[m.type]

                # Complex types have a matching definition e.g. VkStruct.
                # Not needed for base types such as uint32_t.
                if "data" in type_info:
                    types[m.type]["data"].required = True

        def mark_struct_dependencies(struct, types):
             for m in struct:
                type_info = types[m.type]

                # Complex types have a matching definition e.g. VkStruct.
                # Not needed for base types such as uint32_t.
                if "data" in type_info:
                    types[m.type]["data"].required = True

                if type_info["category"] == "struct" and struct.name != m.type:
                    # Yay, recurse
                    mark_struct_dependencies(type_info["data"], types)
                elif type_info["category"] == "funcpointer":
                    mark_funcpointer_dependencies(type_info["data"], types)
                elif type_info["category"] == "bitmask":
                    mark_bitmask_dependencies(type_info["data"], types)

        func = self.funcs[command]
        func.required = True

        # Pull in return type
        if func.type != "void":
            self.types[func.type]["data"].required = True

        # Analyze parameter dependencies and pull in any type needed.
        for p in func.params:
            type_info = self.types[p.type]

            # Check if we are dealing with a complex type e.g. VkEnum, VkStruct and others.
            if "data" not in type_info:
                continue

            # Mark the complex type as required.
            type_info["data"].required = True
            if type_info["category"] == "struct":
                struct = type_info["data"]
                mark_struct_dependencies(struct, self.types)
            elif type_info["category"] == "bitmask":
                mark_bitmask_dependencies(type_info["data"], self.types)

    def _match_object_types(self):
        """ Matches each handle with the correct object type. """
        # Use upper case comparison for simplicity.
        object_types = {}
        for value in self.enums["VkObjectType"].values:
            object_name = "VK" + value.name[len("VK_OBJECT_TYPE"):].replace("_", "")
            object_types[object_name] = value.name

        for handle in self.handles:
            if not handle.is_required():
                continue
            handle.object_type = object_types.get(handle.name.upper())
            if not handle.object_type:
                LOGGER.warning("No object type found for {}".format(handle.name))

    def _parse_commands(self, root):
        """ Parse command section containing the Vulkan function calls. """
        funcs = {}
        commands = root.findall("./commands/")

        # As of Vulkan 1.1, various extensions got promoted to Core.
        # The old commands (e.g. KHR) are available for backwards compatibility
        # and are marked in vk.xml as 'alias' to the non-extension type.
        # The registry likes to avoid data duplication, so parameters and other
        # metadata need to be looked up from the Core command.
        # We parse the alias commands in a second pass.
        alias_commands = []
        for command in commands:
            alias_name = command.attrib.get("alias")
            if alias_name:
                alias_commands.append(command)
                continue

            func = VkFunction.from_xml(command, self.types)
            if func:
                funcs[func.name] = func

        for command in alias_commands:
            alias_name = command.attrib.get("alias")
            alias = funcs[alias_name]
            func = VkFunction.from_alias(command, alias)
            if func:
                funcs[func.name] = func

        # To make life easy for the code generation, separate all function
        # calls out in the 4 types of Vulkan functions:
        # device, global, physical device and instance.
        device_funcs = []
        global_funcs = []
        phys_dev_funcs = []
        instance_funcs = []
        for func in funcs.values():
            if func.is_device_func():
                device_funcs.append(func)
            elif func.is_global_func():
                global_funcs.append(func)
            elif func.is_phys_dev_func():
                phys_dev_funcs.append(func)
            else:
                instance_funcs.append(func)

        # Sort function lists by name and store them.
        self.device_funcs = sorted(device_funcs, key=lambda func: func.name)
        self.global_funcs = sorted(global_funcs, key=lambda func: func.name)
        self.phys_dev_funcs = sorted(phys_dev_funcs, key=lambda func: func.name)
        self.instance_funcs = sorted(instance_funcs, key=lambda func: func.name)

        # The funcs dictionary is used as a convenient way to lookup function
        # calls when needed e.g. to adjust member variables.
        self.funcs = OrderedDict(sorted(funcs.items()))

    def _parse_enums(self, root):
        """ Parse enums section or better described as constants section. """
        enums = {}
        self.consts = []
        for enum in root.findall("./enums"):
            name = enum.attrib.get("name")
            _type = enum.attrib.get("type")

            if _type in ("enum", "bitmask"):
                enum_obj = VkEnum.from_xml(enum)
                if enum_obj:
                    enums[name] = enum_obj
            else:
                # If no type is set, we are dealing with API constants.
                for value in enum.findall("enum"):
                    # If enum is an alias, set the value to the alias name.
                    # E.g. VK_LUID_SIZE_KHR is an alias to VK_LUID_SIZE.
                    alias = value.attrib.get("alias")
                    if alias:
                        self.consts.append(VkConstant(value.attrib.get("name"), alias))
                    else:
                        self.consts.append(VkConstant(value.attrib.get("name"), value.attrib.get("value")))

        self.enums = OrderedDict(sorted(enums.items()))

    def _process_require_enum(self, enum_elem, ext=None, only_aliased=False):
        if "extends" in enum_elem.keys():
            enum = self.types[enum_elem.attrib["extends"]]["data"]

            # Need to define VkEnumValues which were aliased to by another value. This is necessary
            # from VK spec version 1.2.135 where the provisional VK_KHR_ray_tracing extension was
            # added which altered VK_NV_ray_tracing's VkEnumValues to alias to the provisional
            # extension.
            aliased = False
            for _, t in self.types.items():
                if t["category"] != "enum":
                    continue
                if not t["data"]:
                    continue
                for value in t["data"].values:
                    if value.alias == enum_elem.attrib["name"]:
                        aliased = True

            if only_aliased and not aliased:
                return

            if "bitpos" in enum_elem.keys():
                # We need to add an extra value to an existing enum type.
                # E.g. VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG to VkFormatFeatureFlagBits.
                enum.create_bitpos(enum_elem.attrib["name"], int(enum_elem.attrib["bitpos"]))

            elif "offset" in enum_elem.keys():
                # Extensions promoted to Core, have the extension number as part
                # of the enum value. Else retrieve from the extension tag.
                if enum_elem.attrib.get("extnumber"):
                    ext_number = int(enum_elem.attrib.get("extnumber"))
                else:
                    ext_number = int(ext.attrib["number"])
                offset = int(enum_elem.attrib["offset"])
                value = EXT_BASE + (ext_number - 1) * EXT_BLOCK_SIZE + offset

                # Deal with negative values.
                direction = enum_elem.attrib.get("dir")
                if direction is not None:
                    value = -value

                enum.create_value(enum_elem.attrib["name"], str(value))

            elif "value" in enum_elem.keys():
                enum.create_value(enum_elem.attrib["name"], enum_elem.attrib["value"])
            elif "alias" in enum_elem.keys():
                enum.create_alias(enum_elem.attrib["name"], enum_elem.attrib["alias"])

        elif "value" in enum_elem.keys():
            # Constant with an explicit value
            if only_aliased:
                return

            self.consts.append(VkConstant(enum_elem.attrib["name"], enum_elem.attrib["value"]))
        elif "alias" in enum_elem.keys():
            # Aliased constant
            if not only_aliased:
                return

            self.consts.append(VkConstant(enum_elem.attrib["name"], enum_elem.attrib["alias"]))

    @staticmethod
    def _require_type(type_info):
        if type(type_info) != VkDefine and type_info.is_alias():
            type_info = type_info.alias
        type_info.required = True
        if type(type_info) == VkStruct:
            for member in type_info.members:
                if "data" in member.type_info:
                  VkRegistry._require_type(member.type_info["data"])

    def _parse_extensions(self, root):
        """ Parse extensions section and pull in any types and commands for this extension. """
        extensions = []
        exts = root.findall("./extensions/extension")
        deferred_exts = []
        skipped_exts = UNSUPPORTED_EXTENSIONS.copy()

        def process_ext(ext, deferred=False):
            ext_name = ext.attrib["name"]

            if ext_name.endswith('_surface') and ext.attrib.get('depends', None) == 'VK_KHR_surface':
                self.surface_extensions.append({"name" : ext_name})

            # Set extension name on any functions calls part of this extension as we
            # were not aware of the name during initial parsing.
            commands = ext.findall("require/command")
            for command in commands:
                cmd_name = command.attrib["name"]
                # Need to verify that the command is defined, and otherwise skip it.
                # vkCreateScreenSurfaceQNX is declared in <extensions> but not defined in
                # <commands>. A command without a definition cannot be enabled, so it's valid for
                # the XML file to handle this, but because of the manner in which we parse the XML
                # file we pre-populate from <commands> before we check if a command is enabled.
                if cmd_name in self.funcs:
                    self.funcs[cmd_name].extensions.add(ext_name)

            # Some extensions are not ready or have numbers reserved as a place holder
            # or are only supported for VulkanSC.
            if not "vulkan" in ext.attrib["supported"].split(","):
                LOGGER.debug("Skipping disabled extension: {0}".format(ext_name))
                skipped_exts.append(ext_name)
                return

            # Defer extensions with 'sortorder' as they are order-dependent for spec-parsing.
            if not deferred and "sortorder" in ext.attrib:
                deferred_exts.append(ext)
                return

            # Disable highly experimental extensions as the APIs are unstable and can
            # change between minor Vulkan revisions until API is final and becomes KHR
            # or NV.
            if ("KHX" in ext_name or "NVX" in ext_name) and ext_name not in ALLOWED_X_EXTENSIONS:
                LOGGER.debug("Skipping experimental extension: {0}".format(ext_name))
                skipped_exts.append(ext_name)
                return

            # Extensions can define VkEnumValues which alias to provisional extensions. Pre-process
            # extensions to define any required VkEnumValues before the platform check below.
            for require in ext.findall("require"):
                # Extensions can add enum values to Core / extension enums, so add these.
                for enum_elem in require.findall("enum"):
                    self._process_require_enum(enum_elem, ext, only_aliased=True)

            platform = ext.attrib.get("platform")
            if platform and platform != "win32":
                LOGGER.debug("Skipping extensions {0} for platform {1}".format(ext_name, platform))
                skipped_exts.append(ext_name)
                return

            if not self._is_extension_supported(ext_name):
                LOGGER.debug("Skipping unsupported extension: {0}".format(ext_name))
                skipped_exts.append(ext_name)
                return
            elif "requires" in ext.attrib:
                # Check if this extension builds on top of another unsupported extension.
                requires = ext.attrib["requires"].split(",")
                if len(set(requires).intersection(skipped_exts)) > 0:
                    skipped_exts.append(ext_name)
                    return
            elif "depends" in ext.attrib:
                # The syntax for this is more complex, but this is good enough for now.
                if any([sext in ext.attrib["depends"] for sext in skipped_exts]):
                    skipped_exts.append(ext_name)
                    return

            LOGGER.debug("Loading extension: {0}".format(ext_name))

            # Extensions can define one or more require sections each requiring
            # different features (e.g. Vulkan 1.1). Parse each require section
            # separately, so we can skip sections we don't want.
            for require in ext.findall("require"):
                # Extensions can add enum values to Core / extension enums, so add these.
                for enum_elem in require.findall("enum"):
                    self._process_require_enum(enum_elem, ext)

                for t in require.findall("type"):
                    # video.xml uses "type" to include various headers,
                    # including stdint.h (which we include manually) and
                    # specific vk_video/* headers (which we don't use).
                    # We don't even parse <type category="include"> tags.
                    # Therefore just skip any types that aren't found.
                    if t.attrib["name"] in self.types:
                        type_info = self.types[t.attrib["name"]]["data"]
                        self._require_type(type_info)
                feature = require.attrib.get("feature")
                if feature and not self._is_feature_supported(feature):
                    continue

                required_extension = require.attrib.get("extension")
                if required_extension and not self._is_extension_supported(required_extension):
                    continue

                # Pull in any commands we need. We infer types to pull in from the command
                # as well.
                for command in require.findall("command"):
                    cmd_name = command.attrib["name"]
                    self._mark_command_required(cmd_name)


            # Store a list with extensions.
            # Video extensions are for some reason split up across vk.xml and
            # video.xml.
            # vk.xml has the actual extension definition and most of the
            # dependent type and enum definitions.
            # video.xml has an <extension> whose "name" is the target header
            # file and whose <require> has the remaining type and enum
            # definitions. We parse those above for the <require> part, but we
            # don't want to add the extension as a real extension here.
            # Checking for the existence of "type" seems to achieve this.
            if "type" in ext.attrib:
                ext_info = {"name" : ext_name, "type" : ext.attrib["type"]}
                extensions.append(ext_info)


        # Process extensions, allowing for sortorder to defer extension processing
        for ext in exts:
            process_ext(ext)

        deferred_exts.sort(key=lambda ext: ext.attrib["sortorder"])

        # Respect sortorder
        for ext in deferred_exts:
            process_ext(ext, deferred=True)

        # Sort in alphabetical order.
        self.extensions = sorted(extensions, key=lambda ext: ext["name"])

    def _parse_features(self, root):
        """ Parse the feature section, which describes Core commands and types needed. """

        for feature in root.findall("./feature"):
            if not api_is_vulkan(feature):
                continue
            feature_name = feature.attrib["name"]
            for require in feature.findall("require"):
                LOGGER.info("Including features for {0}".format(require.attrib.get("comment")))
                for tag in require:
                    if tag.tag == "comment":
                        continue
                    elif tag.tag == "command":
                        if not self._is_feature_supported(feature_name):
                            continue
                        name = tag.attrib["name"]
                        self._mark_command_required(name)
                    elif tag.tag == "enum":
                        self._process_require_enum(tag)
                    elif tag.tag == "type":
                        name = tag.attrib["name"]

                        # Skip pull in for vk_platform.h for now.
                        if name == "vk_platform":
                            continue

                        type_info = self.types[name]
                        type_info["data"].required = True

    def _parse_types(self, root):
        """ Parse types section, which contains all data types e.g. structs, typedefs etcetera. """
        types = root.findall("./types/type")

        base_types = []
        bitmasks = []
        defines = []
        funcpointers = []
        handles = []
        structs = []

        alias_types = []
        for t in types:
            type_info = {}
            type_info["category"] = t.attrib.get("category", None)
            type_info["requires"] = t.attrib.get("requires", None)

            # We parse aliases in a second pass when we know more.
            alias = t.attrib.get("alias")
            if alias:
                LOGGER.debug("Alias found: {0}".format(alias))
                alias_types.append(t)
                continue

            if type_info["category"] in ["include"]:
                continue

            # video.xml redefines stdint types which we already parsed in vk.xml.
            # For some reason, it doesn't define them the same way.
            if type_info["requires"] == "stdint":
                continue

            if type_info["category"] == "basetype":
                name = t.find("name").text
                _type = None
                if not t.find("type") is None:
                    _type = t.find("type").text
                    tail = t.find("type").tail
                    if tail is not None:
                        _type += tail.strip()
                basetype = VkBaseType(name, _type)
                if basetype:
                    base_types.append(basetype)
                    type_info["data"] = basetype
                else:
                    continue

            # Basic C types don't need us to define them, but we do need data for them
            if type_info["requires"] == "vk_platform":
                requires = type_info["requires"]
                basic_c = VkBaseType(name, _type, requires=requires)
                type_info["data"] = basic_c

            if type_info["category"] == "bitmask":
                name = t.find("name").text
                _type = t.find("type").text

                # Most bitmasks have a requires attribute used to pull in
                # required '*FlagBits" enum.
                requires = type_info["requires"]
                bitmask = VkBaseType(name, _type, requires=requires)
                bitmasks.append(bitmask)
                type_info["data"] = bitmask

            if type_info["category"] == "define":
                define = VkDefine.from_xml(t)
                if define:
                    defines.append(define)
                    type_info["data"] = define
                else:
                    continue

            if type_info["category"] == "enum":
                name = t.attrib.get("name")
                # The type section only contains enum names, not the actual definition.
                # Since we already parsed the enum before, just link it in.
                try:
                    type_info["data"] = self.enums[name]
                except KeyError:
                    # Not all enums seem to be defined yet, typically that's for
                    # ones ending in 'FlagBits' where future extensions may add
                    # definitions.
                    type_info["data"] = None

            if type_info["category"] == "funcpointer":
                funcpointer = VkFunctionPointer.from_xml(t)
                if funcpointer:
                    funcpointers.append(funcpointer)
                    type_info["data"] = funcpointer
                else:
                    continue

            if type_info["category"] == "handle":
                handle = VkHandle.from_xml(t)
                if handle:
                    handles.append(handle)
                    type_info["data"] = handle
                else:
                    continue

            if type_info["category"] in ["struct", "union"]:
                # We store unions among structs as some structs depend
                # on unions. The types are very similar in parsing and
                # generation anyway. The official Vulkan scripts use
                # a similar kind of hack.
                struct = VkStruct.from_xml(t)
                if struct:
                    structs.append(struct)
                    type_info["data"] = struct
                else:
                    continue

            # Name is in general within a name tag else it is an optional
            # attribute on the type tag.
            name_elem = t.find("name")
            if name_elem is not None:
                type_info["name"] = name_elem.text
            else:
                type_info["name"] = t.attrib.get("name", None)

            # Store all type data in a shared dictionary, so we can easily
            # look up information for a given type. There are no duplicate
            # names.
            self.types[type_info["name"]] = type_info

        # Second pass for alias types, so we can retrieve all data from
        # the aliased object.
        for t in alias_types:
            type_info = {}
            type_info["category"] = t.attrib.get("category")
            type_info["name"] = t.attrib.get("name")

            alias = t.attrib.get("alias")

            if type_info["category"] == "bitmask":
                bitmask = VkBaseType(type_info["name"], alias, alias=self.types[alias]["data"])
                bitmasks.append(bitmask)
                type_info["data"] = bitmask

            if type_info["category"] == "enum":
                enum = VkEnum.from_alias(t, self.types[alias]["data"])
                type_info["data"] = enum
                self.enums[enum.name] = enum

            if type_info["category"] == "handle":
                handle = VkHandle.from_alias(t, self.types[alias]["data"])
                handles.append(handle)
                type_info["data"] = handle

            if type_info["category"] == "struct":
                struct = VkStruct.from_alias(t, self.types[alias]["data"])
                structs.append(struct)
                type_info["data"] = struct

            self.types[type_info["name"]] = type_info

        # We need detailed type information during code generation
        # on structs for alignment reasons. Unfortunately structs
        # are parsed among other types, so there is no guarantee
        # that any types needed have been parsed already, so set
        # the data now.
        for struct in structs:
            struct.set_type_info(self.types)

            # Alias structures have enum values equivalent to those of the
            # structure which they are aliased against. we need to ignore alias
            # structs when populating the struct extensions list, otherwise we
            # will create duplicate case entries.
            if struct.alias:
                continue

            for structextend in struct.structextends:
                s = self.types[structextend]["data"]
                s.struct_extensions.append(struct)

        # Guarantee everything is sorted, so code generation doesn't have
        # to deal with this.
        self.base_types = sorted(base_types, key=lambda base_type: base_type.name)
        self.bitmasks = sorted(bitmasks, key=lambda bitmask: bitmask.name)
        self.defines = defines
        self.enums = OrderedDict(sorted(self.enums.items()))
        self.funcpointers = sorted(funcpointers, key=lambda fp: fp.name)
        self.handles = sorted(handles, key=lambda handle: handle.name)
        self.structs = sorted(structs, key=lambda struct: struct.name)

def generate_vulkan_json(f):
    f.write("{\n")
    f.write("    \"file_format_version\": \"1.0.0\",\n")
    f.write("    \"ICD\": {\n")
    f.write("        \"library_path\": \".\\\\winevulkan.dll\",\n")
    f.write("        \"api_version\": \"{0}\"\n".format(VK_XML_VERSION))
    f.write("    }\n")
    f.write("}\n")

def set_working_directory():
    path = os.path.abspath(__file__)
    path = os.path.dirname(path)
    os.chdir(path)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose", action="count", default=0, help="increase output verbosity")
    parser.add_argument("-x", "--xml", default=None, type=str, help="path to specification XML file")
    parser.add_argument("-X", "--video-xml", default=None, type=str, help="path to specification video XML file")

    args = parser.parse_args()
    if args.verbose == 0:
        LOGGER.setLevel(logging.WARNING)
    elif args.verbose == 1:
        LOGGER.setLevel(logging.INFO)
    else: # > 1
        LOGGER.setLevel(logging.DEBUG)

    set_working_directory()

    if args.xml:
        vk_xml = args.xml
    else:
        vk_xml = os.path.join(cache, "vk-{0}.xml".format(VK_XML_VERSION))

    if args.video_xml:
        video_xml = args.video_xml
    else:
        video_xml = os.path.join(cache, "video-{0}.xml".format(VK_XML_VERSION))

    registry = VkRegistry(vk_xml, video_xml)
    generator = VkGenerator(registry)

    with open(WINE_VULKAN_H, "w") as f:
        generator.generate_vulkan_h(f)

    with open(WINE_VULKAN_THUNKS_H, "w") as f:
        generator.generate_thunks_h(f, "wine_")

    with open(WINE_VULKAN_THUNKS_C, "w") as f:
        generator.generate_thunks_c(f)

    with open(WINE_VULKAN_LOADER_THUNKS_H, "w") as f:
        generator.generate_loader_thunks_h(f)

    with open(WINE_VULKAN_LOADER_THUNKS_C, "w") as f:
        generator.generate_loader_thunks_c(f)

    with open(WINE_VULKAN_JSON, "w") as f:
        generate_vulkan_json(f)

    with open(WINE_VULKAN_SPEC, "w") as f:
        generator.generate_vulkan_spec(f)

    with open(WINE_VULKAN_LOADER_SPEC, "w") as f:
        generator.generate_vulkan_loader_spec(f)

if __name__ == "__main__":
    main()