summaryrefslogtreecommitdiffstats
path: root/source/slang/slang-reflection-api.cpp
blob: ae351aee9b7d751ccc8d51b848f19ebfc7b3491d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
// slang-reflection-api.cpp

#include "../core/slang-basic.h"
#include "slang-syntax.h"

#include "slang.h"

#include "slang-compiler.h"
#include "slang-type-layout.h"
#include "slang-syntax.h"
#include "slang-check.h"
#include <assert.h>

// Don't signal errors for stuff we don't implement here,
// and instead just try to return things defensively
//
// Slang developers can switch this when debugging.
#define SLANG_REFLECTION_UNEXPECTED() do {} while(0)

namespace Slang
{

// Conversion routines to help with strongly-typed reflection API

static inline UserDefinedAttribute* convert(SlangReflectionUserAttribute* attrib)
{
    return (UserDefinedAttribute*)attrib;
}
static inline SlangReflectionUserAttribute* convert(UserDefinedAttribute* attrib)
{
    return (SlangReflectionUserAttribute*)attrib;
}

static inline Type* convert(SlangReflectionType* type)
{
    return (Type*) type;
}

static inline SlangReflectionType* convert(Type* type)
{
    return (SlangReflectionType*) type;
}

static inline TypeLayout* convert(SlangReflectionTypeLayout* type)
{
    return (TypeLayout*) type;
}

static inline SlangReflectionTypeLayout* convert(TypeLayout* type)
{
    return (SlangReflectionTypeLayout*) type;
}

static inline SpecializationParamLayout* convert(SlangReflectionTypeParameter * typeParam)
{
    return (SpecializationParamLayout*) typeParam;
}

static inline DeclRef<Decl> convert(SlangReflectionVariable* var)
{
    return DeclRef<Decl>((DeclRefBase*) var);
}

static inline SlangReflectionVariable* convert(DeclRef<Decl> var)
{
    return (SlangReflectionVariable*) var.declRefBase;
}

static inline DeclRef<FunctionDeclBase> convertToFunc(SlangReflectionFunction* func)
{
    NodeBase* nodeBase = (NodeBase*)func;
    if (DeclRefBase* declRefBase = as<DeclRefBase>(nodeBase))
    {
        return DeclRef<FunctionDeclBase>(declRefBase);
    }

    return DeclRef<FunctionDeclBase>();
}

static inline OverloadedExpr* convertToOverloadedFunc(SlangReflectionFunction* func)
{
    NodeBase* nodeBase = (NodeBase*)func;
    return as<OverloadedExpr>(nodeBase);
}

static inline SlangReflectionFunction* convert(DeclRef<FunctionDeclBase> func)
{
    return (SlangReflectionFunction*)func.declRefBase;
}

static inline SlangReflectionFunction* convert(OverloadedExpr* overloadedFunc)
{
    return (SlangReflectionFunction*)overloadedFunc;
}

static inline DeclRef<Decl> convertGenericToDeclRef(SlangReflectionGeneric* func)
{
    DeclRefBase* declBase = (DeclRefBase*)func;
    return DeclRef<Decl>(declBase);
}

static inline SlangReflectionGeneric* convertDeclToGeneric(DeclRef<Decl> func)
{
    return (SlangReflectionGeneric*)func.declRefBase;
}

static inline VarLayout* convert(SlangReflectionVariableLayout* var)
{
    return (VarLayout*) var;
}

static inline SlangReflectionVariableLayout* convert(VarLayout* var)
{
    return (SlangReflectionVariableLayout*) var;
}

static inline EntryPointLayout* convert(SlangReflectionEntryPoint* entryPoint)
{
    return (EntryPointLayout*) entryPoint;
}

static inline SlangReflectionEntryPoint* convert(EntryPointLayout* entryPoint)
{
    return (SlangReflectionEntryPoint*) entryPoint;
}

static inline ProgramLayout* convert(SlangReflection* program)
{
    return (ProgramLayout*) program;
}

[[maybe_unused]]
static inline SlangReflection* convert(ProgramLayout* program)
{
    return (SlangReflection*) program;
}

// user attribute

static unsigned int getUserAttributeCount(Decl* decl)
{
    unsigned int count = 0;
    for (auto x : decl->getModifiersOfType<UserDefinedAttribute>())
    {
        SLANG_UNUSED(x);
        count++;
    }
    return count;
}

static SlangReflectionUserAttribute* findUserAttributeByName(Session* session, Decl* decl, const char* name)
{
    auto nameObj = session->tryGetNameObj(name);
    for (auto x : decl->getModifiersOfType<UserDefinedAttribute>())
    {
        if (x->keywordName == nameObj)
            return (SlangReflectionUserAttribute*)(x);
    }
    return nullptr;
}

static SlangReflectionUserAttribute* getUserAttributeByIndex(Decl* decl, unsigned int index)
{
    unsigned int id = 0;
    for (auto x : decl->getModifiersOfType<UserDefinedAttribute>())
    {
        if (id == index)
            return convert(x);
        id++;
    }
    return nullptr;
}


// Attempt "do what I mean" remapping from the parameter category the user asked about,
// over to a parameter category that they might have meant.
static SlangParameterCategory maybeRemapParameterCategory(
    TypeLayout*             typeLayout,
    SlangParameterCategory  category)
{
    // Do we have an entry for the category they asked about? Then use that.
    if (typeLayout->FindResourceInfo(LayoutResourceKind(category)))
        return category;

    // Do we have an entry for the `DescriptorTableSlot` category?
    if (typeLayout->FindResourceInfo(LayoutResourceKind::DescriptorTableSlot))
    {
        // Is the category they were asking about one that makes sense for the type
        // of this variable?
        Type* type = typeLayout->getType();
        while (auto arrayType = as<ArrayExpressionType>(type))
            type = arrayType->getElementType();
        switch (spReflectionType_GetKind(convert(type)))
        {
            case SLANG_TYPE_KIND_CONSTANT_BUFFER:
                if (category == SLANG_PARAMETER_CATEGORY_CONSTANT_BUFFER)
                    return SLANG_PARAMETER_CATEGORY_DESCRIPTOR_TABLE_SLOT;
                break;

            case SLANG_TYPE_KIND_RESOURCE:
                if (category == SLANG_PARAMETER_CATEGORY_SHADER_RESOURCE)
                    return SLANG_PARAMETER_CATEGORY_DESCRIPTOR_TABLE_SLOT;
                break;

            case SLANG_TYPE_KIND_SAMPLER_STATE:
                if (category == SLANG_PARAMETER_CATEGORY_SAMPLER_STATE)
                    return SLANG_PARAMETER_CATEGORY_DESCRIPTOR_TABLE_SLOT;
                break;

            case SLANG_TYPE_KIND_SHADER_STORAGE_BUFFER:
                if (category == SLANG_PARAMETER_CATEGORY_UNIFORM)
                    return SLANG_PARAMETER_CATEGORY_DESCRIPTOR_TABLE_SLOT;
                break;

                // TODO: implement more helpers here

            default:
                break;
        }
    }

    return category;
}

// Helpers for getting parameter count

static unsigned getParameterCount(RefPtr<TypeLayout> typeLayout)
{
    if (auto parameterGroupLayout = as<ParameterGroupTypeLayout>(typeLayout))
    {
        typeLayout = parameterGroupLayout->offsetElementTypeLayout;
    }

    if (auto structLayout = as<StructTypeLayout>(typeLayout))
    {
        return (unsigned)structLayout->fields.getCount();
    }

    return 0;
}

static VarLayout* getParameterByIndex(RefPtr<TypeLayout> typeLayout, unsigned index)
{
    if (auto parameterGroupLayout = as<ParameterGroupTypeLayout>(typeLayout))
    {
        typeLayout = parameterGroupLayout->offsetElementTypeLayout;
    }

    if (auto structLayout = as<StructTypeLayout>(typeLayout))
    {
        return structLayout->fields[index];
    }

    return 0;
}

static SlangParameterCategory getParameterCategory(
    LayoutResourceKind kind)
{
    return SlangParameterCategory(kind);
}

static SlangParameterCategory getParameterCategory(
    TypeLayout*  typeLayout)
{
    auto resourceInfoCount = typeLayout->resourceInfos.getCount();
    if (resourceInfoCount == 1)
    {
        return getParameterCategory(typeLayout->resourceInfos[0].kind);
    }
    else if (resourceInfoCount == 0)
    {
        // TODO: can this ever happen?
        return SLANG_PARAMETER_CATEGORY_NONE;
    }
    return SLANG_PARAMETER_CATEGORY_MIXED;
}

static bool hasDefaultConstantBuffer(ScopeLayout* layout)
{
    auto typeLayout = layout->parametersLayout->getTypeLayout();
    return as<ParameterGroupTypeLayout>(typeLayout) != nullptr;
}


} // namespace Slang

using namespace Slang;

// Implementation to back public-facing reflection API

SLANG_API char const* spReflectionUserAttribute_GetName(SlangReflectionUserAttribute* attrib)
{
    auto userAttr = convert(attrib);
    if (!userAttr) return nullptr;
    return userAttr->getKeywordName()->text.getBuffer();
}
SLANG_API unsigned int spReflectionUserAttribute_GetArgumentCount(SlangReflectionUserAttribute* attrib)
{
    auto userAttr = convert(attrib);
    if (!userAttr) return 0;
    return (unsigned int)userAttr->args.getCount();
}
SlangReflectionType* spReflectionUserAttribute_GetArgumentType(SlangReflectionUserAttribute* attrib, unsigned int index)
{
    auto userAttr = convert(attrib);
    if (!userAttr) return nullptr;
    return convert(userAttr->args[index]->type.type);
}
SLANG_API SlangResult spReflectionUserAttribute_GetArgumentValueInt(SlangReflectionUserAttribute* attrib, unsigned int index, int * rs)
{
    auto userAttr = convert(attrib);
    if (!userAttr) return SLANG_E_INVALID_ARG;
    if (index >= (unsigned int)userAttr->args.getCount()) return SLANG_E_INVALID_ARG;

    if (userAttr->intArgVals.getCount() > (Index)index)
    {
        auto intVal = as<ConstantIntVal>(userAttr->intArgVals[index]);
        if (intVal)
        {
            *rs = (int)intVal->getValue();
            return 0;
        }
    }
    return SLANG_E_INVALID_ARG;
}
SLANG_API SlangResult spReflectionUserAttribute_GetArgumentValueFloat(SlangReflectionUserAttribute* attrib, unsigned int index, float * rs)
{
    auto userAttr = convert(attrib);
    if (!userAttr) return SLANG_E_INVALID_ARG;
    if (index >= (unsigned int)userAttr->args.getCount()) return SLANG_E_INVALID_ARG;
    if (auto cexpr = as<FloatingPointLiteralExpr>(userAttr->args[index]))
    {
        *rs = (float)cexpr->value;
        return 0;
    }
    return SLANG_E_INVALID_ARG;
}
SLANG_API const char* spReflectionUserAttribute_GetArgumentValueString(SlangReflectionUserAttribute* attrib, unsigned int index, size_t* bufLen)
{
    auto userAttr = convert(attrib);
    if (!userAttr) return nullptr;
    if (index >= (unsigned int)userAttr->args.getCount()) return nullptr;
    if (auto cexpr = as<StringLiteralExpr>(userAttr->args[index]))
    {
        if (bufLen)
            *bufLen = cexpr->token.getContentLength();
        return cexpr->token.getContent().begin();
    }
    return nullptr;
}

// type Reflection

SLANG_API SlangTypeKind spReflectionType_GetKind(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return SLANG_TYPE_KIND_NONE;

    // TODO(tfoley): Don't emit the same type more than once...

    if (const auto basicType = as<BasicExpressionType>(type))
    {
        return SLANG_TYPE_KIND_SCALAR;
    }
    else if (const auto vectorType = as<VectorExpressionType>(type))
    {
        return SLANG_TYPE_KIND_VECTOR;
    }
    else if (const auto matrixType = as<MatrixExpressionType>(type))
    {
        return SLANG_TYPE_KIND_MATRIX;
    }
    else if (const auto parameterBlockType = as<ParameterBlockType>(type))
    {
        return SLANG_TYPE_KIND_PARAMETER_BLOCK;
    }
    else if (const auto constantBufferType = as<ConstantBufferType>(type))
    {
        return SLANG_TYPE_KIND_CONSTANT_BUFFER;
    }
    else if( const auto streamOutputType = as<HLSLStreamOutputType>(type) )
    {
        return SLANG_TYPE_KIND_OUTPUT_STREAM;
    }
    else if( as<MeshOutputType>(type) )
    {
        return SLANG_TYPE_KIND_MESH_OUTPUT;
    }
    else if (as<TextureBufferType>(type))
    {
        return SLANG_TYPE_KIND_TEXTURE_BUFFER;
    }
    else if (as<GLSLShaderStorageBufferType>(type))
    {
        return SLANG_TYPE_KIND_SHADER_STORAGE_BUFFER;
    }
    else if (const auto samplerStateType = as<SamplerStateType>(type))
    {
        return SLANG_TYPE_KIND_SAMPLER_STATE;
    }
    else if (const auto textureType = as<TextureTypeBase>(type))
    {
        return SLANG_TYPE_KIND_RESOURCE;
    }
    else if (const auto feedbackType = as<FeedbackType>(type))
    {
        return SLANG_TYPE_KIND_FEEDBACK;
    }
    else if (const auto ptrType = as<PtrType>(type))
    {
        return SLANG_TYPE_KIND_POINTER;
    }
    else if (const auto dynamicResourceType = as<DynamicResourceType>(type))
    {
        return SLANG_TYPE_KIND_DYNAMIC_RESOURCE;
    }
    // TODO: need a better way to handle this stuff...
#define CASE(TYPE)                          \
    else if(as<TYPE>(type)) do {          \
        return SLANG_TYPE_KIND_RESOURCE;    \
    } while(0)

    CASE(HLSLStructuredBufferType);
    CASE(HLSLRWStructuredBufferType);
    CASE(HLSLRasterizerOrderedStructuredBufferType);
    CASE(HLSLAppendStructuredBufferType);
    CASE(HLSLConsumeStructuredBufferType);
    CASE(HLSLByteAddressBufferType);
    CASE(HLSLRWByteAddressBufferType);
    CASE(HLSLRasterizerOrderedByteAddressBufferType);
    CASE(UntypedBufferResourceType);
    CASE(GLSLShaderStorageBufferType);
#undef CASE

    else if (const auto arrayType = as<ArrayExpressionType>(type))
    {
        return SLANG_TYPE_KIND_ARRAY;
    }
    else if( auto declRefType = as<DeclRefType>(type) )
    {
        const auto& declRef = declRefType->getDeclRef();
        if(declRef.is<StructDecl>() )
        {
            return SLANG_TYPE_KIND_STRUCT;
        }
        else if (declRef.is<GlobalGenericParamDecl>())
        {
            return SLANG_TYPE_KIND_GENERIC_TYPE_PARAMETER;
        }
        else if (declRef.is<InterfaceDecl>())
        {
            return SLANG_TYPE_KIND_INTERFACE;
        }
        else if (declRef.is<FuncDecl>())
        {
            // This is a reference to an entry point
            return SLANG_TYPE_KIND_STRUCT;
        }
    }
    else if( const auto specializedType = as<ExistentialSpecializedType>(type) )
    {
        return SLANG_TYPE_KIND_SPECIALIZED;
    }
    else if (const auto errorType = as<ErrorType>(type))
    {
        // This means we saw a type we didn't understand in the user's code
        return SLANG_TYPE_KIND_NONE;
    }

    SLANG_REFLECTION_UNEXPECTED();
    return SLANG_TYPE_KIND_NONE;
}

SLANG_API unsigned int spReflectionType_GetFieldCount(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return 0;

    // TODO: maybe filter based on kind

    if(auto declRefType = as<DeclRefType>(type))
    {
        auto declRef = declRefType->getDeclRef();
        if( auto structDeclRef = declRef.as<StructDecl>())
        {
            return (unsigned int)getFields(
                       getModule(declRef.getDecl())->getLinkage()->getASTBuilder(),
                       structDeclRef,
                       MemberFilterStyle::Instance)
                .getCount();
        }
    }

    return 0;
}

SLANG_API SlangReflectionVariable* spReflectionType_GetFieldByIndex(SlangReflectionType* inType, unsigned index)
{
    auto type = convert(inType);
    if(!type) return nullptr;

    // TODO: maybe filter based on kind

    if(auto declRefType = as<DeclRefType>(type))
    {
        auto declRef = declRefType->getDeclRef();
        if( auto structDeclRef = declRef.as<StructDecl>())
        {
            auto fields = getFields(
                getModule(declRef.getDecl())->getLinkage()->getASTBuilder(), structDeclRef, MemberFilterStyle::Instance);
            auto fieldDeclRef = fields[index];
            return convert(fieldDeclRef);
        }
    }

    return nullptr;
}

SLANG_API size_t spReflectionType_GetElementCount(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return 0;

    if(auto arrayType = as<ArrayExpressionType>(type))
    {
        return !arrayType->isUnsized() ? (size_t)getIntVal(arrayType->getElementCount()) : 0;
    }
    else if( auto vectorType = as<VectorExpressionType>(type))
    {
        return (size_t) getIntVal(vectorType->getElementCount());
    }

    return 0;
}

SLANG_API SlangReflectionType* spReflectionType_GetElementType(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return nullptr;

    if(auto arrayType = as<ArrayExpressionType>(type))
    {
        return (SlangReflectionType*) arrayType->getElementType();
    }
    else if( auto parameterGroupType = as<ParameterGroupType>(type))
    {
        return convert(parameterGroupType->getElementType());
    }
    else if (auto structuredBufferType = as<HLSLStructuredBufferTypeBase>(type))
    {
        return convert(structuredBufferType->getElementType());
    }
    else if( auto vectorType = as<VectorExpressionType>(type))
    {
        return convert(vectorType->getElementType());
    }
    else if( auto matrixType = as<MatrixExpressionType>(type))
    {
        return convert(matrixType->getElementType());
    }

    return nullptr;
}

SLANG_API unsigned int spReflectionType_GetRowCount(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return 0;

    if(auto matrixType = as<MatrixExpressionType>(type))
    {
        return (unsigned int) getIntVal(matrixType->getRowCount());
    }
    else if(const auto vectorType = as<VectorExpressionType>(type))
    {
        return 1;
    }
    else if( const auto basicType = as<BasicExpressionType>(type) )
    {
        return 1;
    }

    return 0;
}

SLANG_API unsigned int spReflectionType_GetColumnCount(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return 0;

    if(auto matrixType = as<MatrixExpressionType>(type))
    {
        return (unsigned int) getIntVal(matrixType->getColumnCount());
    }
    else if(auto vectorType = as<VectorExpressionType>(type))
    {
        return (unsigned int) getIntVal(vectorType->getElementCount());
    }
    else if( const auto basicType = as<BasicExpressionType>(type) )
    {
        return 1;
    }

    return 0;
}

SLANG_API SlangScalarType spReflectionType_GetScalarType(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return SLANG_SCALAR_TYPE_NONE;

    if(auto matrixType = as<MatrixExpressionType>(type))
    {
        type = matrixType->getElementType();
    }
    else if(auto vectorType = as<VectorExpressionType>(type))
    {
        type = vectorType->getElementType();
    }

    if(auto basicType = as<BasicExpressionType>(type))
    {
        switch (basicType->getBaseType())
        {
#define CASE(BASE, TAG) \
        case BaseType::BASE: return SLANG_SCALAR_TYPE_##TAG

            CASE(Void,      VOID);
            CASE(Bool,      BOOL);
            CASE(Int8,      INT8);
            CASE(Int16,     INT16);
            CASE(Int,       INT32);
            CASE(Int64,     INT64);
            CASE(UInt8,     UINT8);
            CASE(UInt16,    UINT16);
            CASE(UInt,      UINT32);
            CASE(UInt64,    UINT64);
            CASE(Half,      FLOAT16);
            CASE(Float,     FLOAT32);
            CASE(Double,    FLOAT64);

#undef CASE

        default:
            SLANG_REFLECTION_UNEXPECTED();
            return SLANG_SCALAR_TYPE_NONE;
            break;
        }
    }

    return SLANG_SCALAR_TYPE_NONE;
}

SLANG_API unsigned int spReflectionType_GetUserAttributeCount(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if (!type) return 0;
    if (auto declRefType = as<DeclRefType>(type))
    {
        return getUserAttributeCount(declRefType->getDeclRef().getDecl());
    }
    return 0;
}
SLANG_API SlangReflectionUserAttribute* spReflectionType_GetUserAttribute(SlangReflectionType* inType, unsigned int index)
{
    auto type = convert(inType);
    if (!type) return 0;
    if (auto declRefType = as<DeclRefType>(type))
    {
        return getUserAttributeByIndex(declRefType->getDeclRef().getDecl(), index);
    }
    return 0;
}
SLANG_API SlangReflectionUserAttribute* spReflectionType_FindUserAttributeByName(SlangReflectionType* inType, char const* name)
{
    auto type = convert(inType);
    if (!type) return 0;
    if (auto declRefType = as<DeclRefType>(type))
    {
        ASTBuilder* astBuilder = declRefType->getASTBuilderForReflection();
        auto globalSession = astBuilder->getGlobalSession();

        return findUserAttributeByName(globalSession, declRefType->getDeclRef().getDecl(), name);
    }
    return 0;
}

SLANG_API SlangReflectionType* spReflectionType_applySpecializations(SlangReflectionType* inType, SlangReflectionGeneric* generic)
{
    auto type = convert(inType);
    auto genericDeclRef = convertGenericToDeclRef(generic);
    
    if (!type || !genericDeclRef)
        return nullptr;
    
    return convert(substituteType(SubstitutionSet(genericDeclRef), type->getASTBuilderForReflection(), type));
}

SLANG_API SlangResourceShape spReflectionType_GetResourceShape(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return SLANG_RESOURCE_NONE;

    while(auto arrayType = as<ArrayExpressionType>(type))
    {
        type = arrayType->getElementType();
    }

    if(auto textureType = as<TextureTypeBase>(type))
    {
        return textureType->getShape();
    }

    // TODO: need a better way to handle this stuff...
#define CASE(TYPE, SHAPE, ACCESS)   \
    else if(as<TYPE>(type)) do {  \
        return SHAPE;               \
    } while(0)

    CASE(HLSLStructuredBufferType,                      SLANG_STRUCTURED_BUFFER,        SLANG_RESOURCE_ACCESS_READ);
    CASE(HLSLRWStructuredBufferType,                    SLANG_STRUCTURED_BUFFER,        SLANG_RESOURCE_ACCESS_READ_WRITE);
    CASE(HLSLRasterizerOrderedStructuredBufferType,     SLANG_STRUCTURED_BUFFER,        SLANG_RESOURCE_ACCESS_RASTER_ORDERED);
    CASE(HLSLAppendStructuredBufferType,                SLANG_STRUCTURED_BUFFER,        SLANG_RESOURCE_ACCESS_APPEND);
    CASE(HLSLConsumeStructuredBufferType,               SLANG_STRUCTURED_BUFFER,        SLANG_RESOURCE_ACCESS_CONSUME);
    CASE(HLSLByteAddressBufferType,                     SLANG_BYTE_ADDRESS_BUFFER,      SLANG_RESOURCE_ACCESS_READ);
    CASE(HLSLRWByteAddressBufferType,                   SLANG_BYTE_ADDRESS_BUFFER,      SLANG_RESOURCE_ACCESS_READ_WRITE);
    CASE(HLSLRasterizerOrderedByteAddressBufferType,    SLANG_BYTE_ADDRESS_BUFFER,      SLANG_RESOURCE_ACCESS_RASTER_ORDERED);
    CASE(RaytracingAccelerationStructureType,           SLANG_ACCELERATION_STRUCTURE,   SLANG_RESOURCE_ACCESS_READ);
    CASE(UntypedBufferResourceType,                     SLANG_BYTE_ADDRESS_BUFFER,      SLANG_RESOURCE_ACCESS_READ);
    CASE(GLSLShaderStorageBufferType,                   SLANG_BYTE_ADDRESS_BUFFER,      SLANG_RESOURCE_ACCESS_READ_WRITE);
#undef CASE

    return SLANG_RESOURCE_NONE;
}

SLANG_API SlangResourceAccess spReflectionType_GetResourceAccess(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return SLANG_RESOURCE_ACCESS_NONE;

    while(auto arrayType = as<ArrayExpressionType>(type))
    {
        type = arrayType->getElementType();
    }

    if(auto textureType = as<TextureTypeBase>(type))
    {
        return textureType->getAccess();
    }

    // TODO: need a better way to handle this stuff...
#define CASE(TYPE, SHAPE, ACCESS)   \
    else if(as<TYPE>(type)) do {  \
        return ACCESS;              \
    } while(0)

    CASE(HLSLStructuredBufferType,                      SLANG_STRUCTURED_BUFFER,    SLANG_RESOURCE_ACCESS_READ);
    CASE(HLSLRWStructuredBufferType,                    SLANG_STRUCTURED_BUFFER,    SLANG_RESOURCE_ACCESS_READ_WRITE);
    CASE(HLSLRasterizerOrderedStructuredBufferType,     SLANG_STRUCTURED_BUFFER,    SLANG_RESOURCE_ACCESS_RASTER_ORDERED);
    CASE(HLSLAppendStructuredBufferType,                SLANG_STRUCTURED_BUFFER,    SLANG_RESOURCE_ACCESS_APPEND);
    CASE(HLSLConsumeStructuredBufferType,               SLANG_STRUCTURED_BUFFER,    SLANG_RESOURCE_ACCESS_CONSUME);
    CASE(HLSLByteAddressBufferType,                     SLANG_BYTE_ADDRESS_BUFFER,  SLANG_RESOURCE_ACCESS_READ);
    CASE(HLSLRWByteAddressBufferType,                   SLANG_BYTE_ADDRESS_BUFFER,  SLANG_RESOURCE_ACCESS_READ_WRITE);
    CASE(HLSLRasterizerOrderedByteAddressBufferType,    SLANG_BYTE_ADDRESS_BUFFER,  SLANG_RESOURCE_ACCESS_RASTER_ORDERED);
    CASE(UntypedBufferResourceType,                     SLANG_BYTE_ADDRESS_BUFFER,  SLANG_RESOURCE_ACCESS_READ);
    CASE(GLSLShaderStorageBufferType,                   SLANG_BYTE_ADDRESS_BUFFER,  SLANG_RESOURCE_ACCESS_READ_WRITE);
#undef CASE

    return SLANG_RESOURCE_ACCESS_NONE;
}

SLANG_API char const* spReflectionType_GetName(SlangReflectionType* inType)
{
    auto type = convert(inType);

    if( auto declRefType = as<DeclRefType>(type) )
    {
        auto declRef = declRefType->getDeclRef();

        // Don't return a name for auto-generated anonymous types
        // that represent `cbuffer` members, etc.
        auto decl = declRef.getDecl();
        if(decl->hasModifier<ImplicitParameterGroupElementTypeModifier>())
            return nullptr;
        return getText(declRef.getName()).begin();
    }

    return nullptr;
}

SLANG_API SlangResult spReflectionType_GetFullName(SlangReflectionType* inType, ISlangBlob** outNameBlob)
{
    auto type = convert(inType);

    if (!type) return SLANG_FAIL;

    StringBuilder sb;
    type->toText(sb);
    *outNameBlob = StringUtil::createStringBlob(sb.produceString()).detach();
    return SLANG_OK;
}

SlangReflectionFunction* tryConvertExprToFunctionReflection(ASTBuilder* astBuilder, Expr* expr)
{
    if (auto declRefExpr = as<DeclRefExpr>(expr))
    {
        auto declRef = declRefExpr->declRef;
        if (auto genericDeclRef = declRef.as<GenericDecl>())
        {
            auto innerDeclRef = createDefaultSubstitutionsIfNeeded(astBuilder, nullptr, genericDeclRef.getDecl()->inner);
            declRef = substituteDeclRef(
                SubstitutionSet(genericDeclRef), astBuilder, innerDeclRef);
        }

        if (auto funcDeclRef = declRef.as<FunctionDeclBase>())
            return convert(funcDeclRef);
    }
    else if (auto overloadedExpr = as<OverloadedExpr>(expr))
        return convert(overloadedExpr);
    
    return nullptr;
}

SLANG_API SlangReflectionFunction* spReflection_FindFunctionByName(SlangReflection* reflection, char const* name)
{
    auto programLayout = convert(reflection);
    auto program = programLayout->getProgram();

    // TODO: We should extend this API to support getting error messages
    // when type lookup fails.
    //
    Slang::DiagnosticSink sink(
        programLayout->getTargetReq()->getLinkage()->getSourceManager(),
        Lexer::sourceLocationLexer);

    auto astBuilder = program->getLinkage()->getASTBuilder();
    try
    {
        return tryConvertExprToFunctionReflection(
            astBuilder,
            program->findDeclFromString(name, &sink));
    }
    catch (...)
    {
    }
    return nullptr;
}

SLANG_API SlangReflectionFunction* spReflection_FindFunctionByNameInType(SlangReflection* reflection, SlangReflectionType* reflType, char const* name)
{
    auto programLayout = convert(reflection);
    auto program = programLayout->getProgram();

    auto type = convert(reflType);

    Slang::DiagnosticSink sink(
        programLayout->getTargetReq()->getLinkage()->getSourceManager(),
        Lexer::sourceLocationLexer);

    auto astBuilder = program->getLinkage()->getASTBuilder();

    try
    {
        auto result = program->findDeclFromStringInType(type, name, LookupMask::Function, &sink);
        return tryConvertExprToFunctionReflection(astBuilder, result);
    }
    catch (...)
    {
    }
    return nullptr;
}

SLANG_API SlangReflectionVariable* spReflection_FindVarByNameInType(SlangReflection* reflection, SlangReflectionType* reflType, char const* name)
{
    auto programLayout = convert(reflection);
    auto program = programLayout->getProgram();

    auto type = convert(reflType);

    Slang::DiagnosticSink sink(
        programLayout->getTargetReq()->getLinkage()->getSourceManager(),
        Lexer::sourceLocationLexer);
    
    try
    {
        auto result = program->findDeclFromStringInType(type, name, LookupMask::Value, &sink);
        if (auto declRefExpr = as<DeclRefExpr>(result))
        {
            if (auto varDeclRef = declRefExpr->declRef.as<VarDeclBase>())
                return convert(varDeclRef.as<Decl>());
        }
    }
    catch (...)
    {
    }
    return nullptr;
}

SLANG_API SlangReflectionType * spReflection_FindTypeByName(SlangReflection * reflection, char const * name)
{
    auto programLayout = convert(reflection);
    auto program = programLayout->getProgram();

    // TODO: We should extend this API to support getting error messages
    // when type lookup fails.
    //
    Slang::DiagnosticSink sink(
        programLayout->getTargetReq()->getLinkage()->getSourceManager(),
        Lexer::sourceLocationLexer);

    try
    {
        Type* result = program->getTypeFromString(name, &sink);

        ASTBuilder* astBuilder = program->getLinkage()->getASTBuilder();

        if (auto genericType = as<GenericDeclRefType>(result))
        {
            auto genericDeclRef = genericType->getDeclRef();
            auto innerDeclRef = substituteDeclRef(
                SubstitutionSet(genericDeclRef), astBuilder, genericDeclRef.getDecl()->inner);
            return convert(
                DeclRefType::create(
                    astBuilder, 
                    createDefaultSubstitutionsIfNeeded(
                        astBuilder, nullptr, innerDeclRef)));
        }

        if (as<ErrorType>(result))
            return nullptr;
        return (SlangReflectionType*)result;
    }
    catch( ... )
    {
        return nullptr;
    }
}


SLANG_API bool spReflection_isSubType(
    SlangReflection * reflection,
    SlangReflectionType* subType,
    SlangReflectionType* superType)
{
    auto programLayout = convert(reflection);
    auto program = programLayout->getProgram();

    // TODO: We should extend this API to support getting error messages
    // when type lookup fails.
    //
    Slang::DiagnosticSink sink(
        programLayout->getTargetReq()->getLinkage()->getSourceManager(),
        Lexer::sourceLocationLexer);

    try
    {
        auto sub = convert(subType);
        auto super = convert(superType);

        return program->isSubType(sub, super);
    }
    catch( ... )
    {
        return false;
    }
}

DeclRef<Decl> getInnermostGenericParent(DeclRef<Decl> declRef)
{
    auto decl = declRef.getDecl();
    auto astBuilder = getModule(decl)->getLinkage()->getASTBuilder();
    auto parentDecl = decl;
    while(parentDecl)
    {
        if(parentDecl->parentDecl && as<GenericDecl>(parentDecl->parentDecl))
            return substituteDeclRef(
                    SubstitutionSet(declRef),
                    astBuilder,
                    createDefaultSubstitutionsIfNeeded(astBuilder, nullptr, DeclRef(parentDecl)));
        parentDecl = parentDecl->parentDecl;
    }

    return DeclRef<Decl>();
}

SLANG_API SlangReflectionGeneric* spReflectionType_GetGenericContainer(SlangReflectionType* type)
{
    auto slangType = convert(type);
    if (auto declRefType = as<DeclRefType>(slangType))
    {
        return convertDeclToGeneric(
            getInnermostGenericParent(declRefType->getDeclRef()));
    }
    else if (auto genericDeclRefType = as<GenericDeclRefType>(slangType))
    {
        return convertDeclToGeneric(
            getInnermostGenericParent(genericDeclRefType->getDeclRef()));
    }

    return nullptr;
}

SLANG_API SlangReflectionTypeLayout* spReflection_GetTypeLayout(
    SlangReflection* reflection,
    SlangReflectionType* inType,
    SlangLayoutRules rules)
{
    auto context = convert(reflection);
    auto type = convert(inType);
    auto targetReq = context->getTargetReq();

    auto typeLayout = targetReq->getTypeLayout(type, (slang::LayoutRules)rules);
    return convert(typeLayout);
}

SLANG_API SlangReflectionType* spReflectionType_GetResourceResultType(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return nullptr;

    while(auto arrayType = as<ArrayExpressionType>(type))
    {
        type = arrayType->getElementType();
    }

    if (auto textureType = as<TextureTypeBase>(type))
    {
        return convert(textureType->getElementType());
    }

    // TODO: need a better way to handle this stuff...
#define CASE(TYPE, SHAPE, ACCESS)                                                       \
    else if(as<TYPE>(type)) do {                                                      \
        return convert(as<TYPE>(type)->getElementType());                            \
    } while(0)

    // TODO: structured buffer needs to expose type layout!

    CASE(HLSLStructuredBufferType,                  SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_READ);
    CASE(HLSLRWStructuredBufferType,                SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_READ_WRITE);
    CASE(HLSLRasterizerOrderedStructuredBufferType, SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_RASTER_ORDERED);
    CASE(HLSLAppendStructuredBufferType,            SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_APPEND);
    CASE(HLSLConsumeStructuredBufferType,           SLANG_STRUCTURED_BUFFER, SLANG_RESOURCE_ACCESS_CONSUME);
#undef CASE

    return nullptr;
}

// type Layout Reflection

SLANG_API SlangReflectionType* spReflectionTypeLayout_GetType(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return nullptr;

    return (SlangReflectionType*) typeLayout->type;
}

SLANG_API SlangTypeKind spReflectionTypeLayout_getKind(SlangReflectionTypeLayout* inTypeLayout)
{
    if(!inTypeLayout) return SLANG_TYPE_KIND_NONE;

    if( auto type = spReflectionTypeLayout_GetType(inTypeLayout) )
    {
        return spReflectionType_GetKind(type);
    }

    auto typeLayout = convert(inTypeLayout);
    if( as<StructTypeLayout>(typeLayout) )
    {
        return SLANG_TYPE_KIND_STRUCT;
    }
    else if( as<ParameterGroupTypeLayout>(typeLayout) )
    {
        return SLANG_TYPE_KIND_CONSTANT_BUFFER;
    }

    return SLANG_TYPE_KIND_NONE;
}

namespace
{
    static size_t getReflectionSize(LayoutSize size)
    {
        if(size.isFinite())
            return size.getFiniteValue();

        return SLANG_UNBOUNDED_SIZE;
    }

    static int32_t getAlignment(TypeLayout* typeLayout, SlangParameterCategory category)
    {
        if( category == SLANG_PARAMETER_CATEGORY_UNIFORM )
        {
            return int32_t(typeLayout->uniformAlignment);
        }
        else
        {
            return 1;
        }
    }

    static size_t getStride(TypeLayout* typeLayout, SlangParameterCategory category)
    {
        auto info = typeLayout->FindResourceInfo(LayoutResourceKind(category));
        if(!info) return 0;

        auto size = info->count;
        if(size.isInfinite())
            return SLANG_UNBOUNDED_SIZE;

        size_t finiteSize = size.getFiniteValue();
        size_t alignment = getAlignment(typeLayout, category);
        SLANG_ASSERT(alignment >= 1);

        auto stride = (finiteSize + (alignment-1)) & ~(alignment-1);
        return stride;
    }
}

SLANG_API size_t spReflectionTypeLayout_GetSize(SlangReflectionTypeLayout* inTypeLayout, SlangParameterCategory category)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto info = typeLayout->FindResourceInfo(LayoutResourceKind(category));
    if(!info) return 0;

    return getReflectionSize(info->count);
}

SLANG_API size_t spReflectionTypeLayout_GetStride(SlangReflectionTypeLayout* inTypeLayout, SlangParameterCategory category)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    return getStride(typeLayout, category);
}

SLANG_API int32_t spReflectionTypeLayout_getAlignment(SlangReflectionTypeLayout* inTypeLayout, SlangParameterCategory category)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    return getAlignment(typeLayout, category);
}

SLANG_API SlangReflectionVariableLayout* spReflectionTypeLayout_GetFieldByIndex(SlangReflectionTypeLayout* inTypeLayout, unsigned index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return nullptr;

    if(auto structTypeLayout = as<StructTypeLayout>(typeLayout))
    {
        return (SlangReflectionVariableLayout*) structTypeLayout->fields[index].Ptr();
    }

    return nullptr;
}

SLANG_API SlangInt spReflectionTypeLayout_findFieldIndexByName(SlangReflectionTypeLayout* inTypeLayout, const char* nameBegin, const char* nameEnd)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return -1;

    UnownedStringSlice name = nameEnd != nullptr ? UnownedStringSlice(nameBegin, nameEnd) : UnownedTerminatedStringSlice(nameBegin);

    if(auto structTypeLayout = as<StructTypeLayout>(typeLayout))
    {
        Index fieldCount = structTypeLayout->fields.getCount();
        for(Index f = 0; f < fieldCount; ++f)
        {
            auto field = structTypeLayout->fields[f];
            if(getReflectionName(field->getVariable())->text.getUnownedSlice() == name)
                return f;
        }
    }

    return -1;
}

SLANG_API SlangReflectionVariableLayout* spReflectionTypeLayout_GetExplicitCounter(SlangReflectionTypeLayout* inTypeLayout)
{
    const auto typeLayout = convert(inTypeLayout);
    if(const auto structuredBufferTypeLayout = as<StructuredBufferTypeLayout>(typeLayout))
        return (SlangReflectionVariableLayout*) structuredBufferTypeLayout->counterVarLayout.Ptr();
    return nullptr;
}

SLANG_API size_t spReflectionTypeLayout_GetElementStride(SlangReflectionTypeLayout* inTypeLayout, SlangParameterCategory category)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    if( auto arrayTypeLayout = as<ArrayTypeLayout>(typeLayout))
    {
        switch (category)
        {
        // We store the stride explicitly for the uniform case
        case SLANG_PARAMETER_CATEGORY_UNIFORM:
            return arrayTypeLayout->uniformStride;

        // For most other cases (resource registers), the "stride"
        // of an array is simply the number of resources (if any)
        // consumed by its element type.
        default:
            {
                auto elementTypeLayout = arrayTypeLayout->elementTypeLayout;
                auto info = elementTypeLayout->FindResourceInfo(LayoutResourceKind(category));
                if(!info) return 0;
                return getReflectionSize(info->count);
            }

        // An important special case, though, is Vulkan descriptor-table slots,
        // where an entire array will use a single `binding`, so that the
        // effective stride is zero:
        case SLANG_PARAMETER_CATEGORY_DESCRIPTOR_TABLE_SLOT:
            return 0;
        }
    }
    else if (auto vectorTypeLayout = as<VectorTypeLayout>(typeLayout))
    {
        auto resInfo = vectorTypeLayout->elementTypeLayout->FindResourceInfo(LayoutResourceKind::Uniform);
        if (!resInfo) return 0;
        return resInfo->count.getFiniteValue();
    }

    return 0;
}

SLANG_API SlangReflectionTypeLayout* spReflectionTypeLayout_GetElementTypeLayout(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return nullptr;

    if( auto arrayTypeLayout = as<ArrayTypeLayout>(typeLayout))
    {
        return (SlangReflectionTypeLayout*) arrayTypeLayout->elementTypeLayout.Ptr();
    }
    else if( auto constantBufferTypeLayout = as<ParameterGroupTypeLayout>(typeLayout))
    {
        return convert(constantBufferTypeLayout->offsetElementTypeLayout.Ptr());
    }
    else if( auto structuredBufferTypeLayout = as<StructuredBufferTypeLayout>(typeLayout))
    {
        return convert(structuredBufferTypeLayout->elementTypeLayout.Ptr());
    }
    else if( auto specializedTypeLayout = as<ExistentialSpecializedTypeLayout>(typeLayout) )
    {
        return convert(specializedTypeLayout->baseTypeLayout.Ptr());
    }
    else if (auto vectorTypeLayout = as<VectorTypeLayout>(typeLayout))
    {
        return convert(vectorTypeLayout->elementTypeLayout);
    }
    else if (auto matrixTypeLayout = as<MatrixTypeLayout>(typeLayout))
    {
        return convert(matrixTypeLayout->elementTypeLayout);
    }
    else if (auto ptrTypeLayout = as<PointerTypeLayout>(typeLayout))
    {
        return convert(ptrTypeLayout->valueTypeLayout.Ptr());
    }
    return nullptr;
}

SLANG_API SlangReflectionVariableLayout* spReflectionTypeLayout_GetElementVarLayout(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return nullptr;

    if( auto parameterGroupTypeLayout = as<ParameterGroupTypeLayout>(typeLayout))
    {
        return convert(parameterGroupTypeLayout->elementVarLayout.Ptr());
    }

    return nullptr;
}

SLANG_API SlangReflectionVariableLayout* spReflectionTypeLayout_getContainerVarLayout(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return nullptr;

    if( auto parameterGroupTypeLayout = as<ParameterGroupTypeLayout>(typeLayout))
    {
        return convert(parameterGroupTypeLayout->containerVarLayout.Ptr());
    }

    return nullptr;
}

SLANG_API SlangParameterCategory spReflectionTypeLayout_GetParameterCategory(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return SLANG_PARAMETER_CATEGORY_NONE;

    return getParameterCategory(typeLayout);
}

SLANG_API uint32_t spReflectionTypeLayout_GetFieldCount(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if (!typeLayout) return 0;

    if (auto structTypeLayout = as<StructTypeLayout>(typeLayout))
    {
        return (uint32_t)structTypeLayout->fields.getCount();
    }
    return 0;
}

SLANG_API unsigned spReflectionTypeLayout_GetCategoryCount(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    return (unsigned) typeLayout->resourceInfos.getCount();
}

SLANG_API SlangParameterCategory spReflectionTypeLayout_GetCategoryByIndex(SlangReflectionTypeLayout* inTypeLayout, unsigned index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return SLANG_PARAMETER_CATEGORY_NONE;

    return SlangParameterCategory(typeLayout->resourceInfos[index].kind);
}

SLANG_API SlangMatrixLayoutMode spReflectionTypeLayout_GetMatrixLayoutMode(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return SLANG_MATRIX_LAYOUT_MODE_UNKNOWN;

    if( auto matrixLayout = as<MatrixTypeLayout>(typeLayout) )
    {
        return SlangMatrixLayoutMode(matrixLayout->mode);
    }
    else
    {
        return SLANG_MATRIX_LAYOUT_MODE_UNKNOWN;
    }

}

SLANG_API int spReflectionTypeLayout_getGenericParamIndex(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return -1;

    if(auto genericParamTypeLayout = as<GenericParamTypeLayout>(typeLayout))
    {
        return (int) genericParamTypeLayout->paramIndex;
    }
    else
    {
        return -1;
    }
}

SLANG_API SlangReflectionTypeLayout* spReflectionTypeLayout_getPendingDataTypeLayout(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return nullptr;

    auto pendingDataTypeLayout = typeLayout->pendingDataTypeLayout.Ptr();
    return convert(pendingDataTypeLayout);
}

SLANG_API SlangReflectionVariableLayout* spReflectionVariableLayout_getPendingDataLayout(SlangReflectionVariableLayout* inVarLayout)
{
    auto varLayout = convert(inVarLayout);
    if(!varLayout) return nullptr;

    auto pendingDataLayout = varLayout->pendingVarLayout.Ptr();
    return convert(pendingDataLayout);
}

SLANG_API SlangReflectionVariableLayout* spReflectionTypeLayout_getSpecializedTypePendingDataVarLayout(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return nullptr;

    if( auto specializedTypeLayout = as<ExistentialSpecializedTypeLayout>(typeLayout) )
    {
        auto pendingDataVarLayout = specializedTypeLayout->pendingDataVarLayout.Ptr();
        return convert(pendingDataVarLayout);
    }
    else
    {
        return nullptr;
    }
}

SLANG_API SlangInt spReflectionType_getSpecializedTypeArgCount(SlangReflectionType* inType)
{
    auto type = convert(inType);
    if(!type) return 0;

    auto specializedType = as<ExistentialSpecializedType>(type);
    if(!specializedType) return 0;

    return specializedType->getArgCount();
}

SLANG_API SlangReflectionType* spReflectionType_getSpecializedTypeArgType(SlangReflectionType* inType, SlangInt index)
{
    auto type = convert(inType);
    if(!type) return nullptr;

    auto specializedType = as<ExistentialSpecializedType>(type);
    if(!specializedType) return nullptr;

    if(index < 0) return nullptr;
    if(index >= specializedType->getArgCount()) return nullptr;

    auto argType = as<Type>(specializedType->getArg(index).val);
    return convert(argType);
}

namespace Slang
{
        /// A link in a chain of `VarLayout`s that can be used to compute offset information for a nested field
    struct BindingRangePathLink
    {
        BindingRangePathLink()
        {}

        BindingRangePathLink(
            BindingRangePathLink*   parent,
            VarLayout*              var)
            : var(var)
            , parent(parent)
        {}

            /// The inner-most variable that contributes to the offset along this path
        VarLayout*              var = nullptr;

            /// The next outer link along the path
        BindingRangePathLink*   parent = nullptr;
    };

        /// A path leading to some nested field, with both parimary and "pending" data offsets
    struct BindingRangePath
    {

            /// The chain of variables that defines the "primary" offset of a nested field
        BindingRangePathLink* primary = nullptr;

            /// The chain of variables that defines the offset for "pending" data of a nested field
        BindingRangePathLink* pending = nullptr;
    };

        /// A helper type to construct a `BindingRangePath` that extends an existing path
    struct ExtendedBindingRangePath : BindingRangePath
    {
            /// Construct a path that extends `parent` with offset information from `varLayout`
        ExtendedBindingRangePath(
            BindingRangePath const& parent,
            VarLayout*              varLayout)
        {
            SLANG_ASSERT(varLayout);

            // We always add another link to the primary chain.
            //
            primaryLink = BindingRangePathLink(parent.primary, varLayout);
            primary = &primaryLink;

            // If the `varLayout` provided has any offset information
            // for pending data, then we also add a link to the pending
            // chain, but otherwise we re-use the pending chain from
            // the parent path.
            //
            if(auto pendingLayout = varLayout->pendingVarLayout)
            {
                pendingLink = BindingRangePathLink(parent.pending, pendingLayout);
                pending = &pendingLink;
            }
            else
            {
                pending = parent.pending;
            }
        }

            /// Storage for a link in the primary chain, if needed
        BindingRangePathLink primaryLink;

            /// Storage for a link in the pending chain, if needed
        BindingRangePathLink pendingLink;
    };

        /// Calculate the offset for resources of the given `kind` in the `path`.
    Int _calcIndexOffset(BindingRangePathLink* path, LayoutResourceKind kind)
    {
        Int result = 0;
        for( auto link = path; link; link = link->parent )
        {
            if( auto resInfo = link->var->FindResourceInfo(kind) )
            {
                result += resInfo->index;
            }
        }
        return result;
    }

        /// Calculate the regsiter space / set for resources of the given `kind` in the `path`.
    Int _calcSpaceOffset(BindingRangePathLink* path, LayoutResourceKind kind)
    {
        Int result = 0;
        for( auto link = path; link; link = link->parent )
        {
            if( auto resInfo = link->var->FindResourceInfo(kind) )
            {
                result += resInfo->space;
            }
        }
        return result;
    }

    SlangBindingType _calcResourceBindingType(
        Type* type)
    {
        if( auto resourceType = as<ResourceType>(type) )
        {
            if (resourceType->isCombined())
                return SlangBindingType(SLANG_BINDING_TYPE_COMBINED_TEXTURE_SAMPLER);

            auto shape = resourceType->getBaseShape();

            auto access = resourceType->getAccess();
            auto mutableFlag = access != SLANG_RESOURCE_ACCESS_READ
                                   ? SLANG_BINDING_TYPE_MUTABLE_FLAG
                                   : SLANG_BINDING_TYPE_UNKNOWN;

            switch(SlangResourceShape(shape ))
            {
            default:
                return SlangBindingType(SLANG_BINDING_TYPE_TEXTURE | mutableFlag);

            case SLANG_TEXTURE_BUFFER:
                return SlangBindingType(SLANG_BINDING_TYPE_TYPED_BUFFER | mutableFlag);
            }
        }
        else if( const auto structuredBufferType = as<HLSLStructuredBufferTypeBase>(type) )
        {
            if( as<HLSLStructuredBufferType>(type) )
            {
                return SLANG_BINDING_TYPE_RAW_BUFFER;
            }
            else
            {
                return SLANG_BINDING_TYPE_MUTABLE_RAW_BUFFER;
            }
        }
        else if( as<RaytracingAccelerationStructureType>(type) )
        {
            return SLANG_BINDING_TYPE_RAY_TRACING_ACCELERATION_STRUCTURE;
        }
        else if( const auto untypedBufferType = as<UntypedBufferResourceType>(type) )
        {
            if( as<HLSLByteAddressBufferType>(type) )
            {
                return SLANG_BINDING_TYPE_RAW_BUFFER;
            }
            else
            {
                return SLANG_BINDING_TYPE_MUTABLE_RAW_BUFFER;
            }
        }
        else if (as<GLSLAtomicUintType>(type))
        {
            return SLANG_BINDING_TYPE_MUTABLE_RAW_BUFFER;
        }
        else if( as<GLSLShaderStorageBufferType>(type) )
        {
            // TODO Immutable buffers
            return SLANG_BINDING_TYPE_MUTABLE_RAW_BUFFER;
        }
        else if( as<ConstantBufferType>(type) )
        {
            return SLANG_BINDING_TYPE_CONSTANT_BUFFER;
        }
        else if( as<SamplerStateType>(type) )
        {
            return SLANG_BINDING_TYPE_SAMPLER;
        }
        else if (as<ParameterBlockType>(type))
        {
            return SLANG_BINDING_TYPE_PARAMETER_BLOCK;
        }
        else
        {
            return SLANG_BINDING_TYPE_UNKNOWN;
        }
    }

    SlangBindingType _calcResourceBindingType(
        TypeLayout* typeLayout)
    {
        if(auto type = typeLayout->getType())
        {
            return _calcResourceBindingType(type);
        }

        if(as<ParameterGroupTypeLayout>(typeLayout))
        {
            return SLANG_BINDING_TYPE_CONSTANT_BUFFER;
        }
        else
        {
            return SLANG_BINDING_TYPE_UNKNOWN;
        }
    }

    SlangBindingType _calcBindingType(
        LayoutResourceKind  kind)
    {
        switch( kind )
        {
        default:
            return SLANG_BINDING_TYPE_UNKNOWN;

        // Some cases of `LayoutResourceKind` can be mapped
        // directly to a `BindingType` because there is only
        // one case of types that have that resource kind.

    #define CASE(FROM, TO) \
        case LayoutResourceKind::FROM: return SLANG_BINDING_TYPE_##TO

        CASE(ConstantBuffer,            CONSTANT_BUFFER);
        CASE(SamplerState,              SAMPLER);
        CASE(VaryingInput,              VARYING_INPUT);
        CASE(VaryingOutput,             VARYING_OUTPUT);
        CASE(ExistentialObjectParam,    EXISTENTIAL_VALUE);
        CASE(PushConstantBuffer,        PUSH_CONSTANT);
        CASE(Uniform,                   INLINE_UNIFORM_DATA);
        // TODO: register space

    #undef CASE
        }
    }

    SlangBindingType _calcBindingType(
        Slang::TypeLayout*  typeLayout,
        LayoutResourceKind  kind)
    {
        // At the type level, a push-constant buffer and a regular constant
        // buffer are currently not distinct, so we need to detect push
        // constant buffers/ranges before we inspect the `typeLayout` to
        // avoid reflecting them all as ordinary constant buffers.
        //
        switch(kind)
        {
        default:
            break;

        case LayoutResourceKind::PushConstantBuffer:
            return SLANG_BINDING_TYPE_PUSH_CONSTANT;
        }

        // If the type or type layout implies a specific binding type
        // (e.g., a `Texture2D` implies a texture binding), then we
        // will always favor the binding type implied.
        //
        if( auto bindingType = _calcResourceBindingType(typeLayout) )
        {
            if(bindingType != SLANG_BINDING_TYPE_UNKNOWN)
                return bindingType;
        }

        // As a fallback, we may look at the kind of resources consumed
        // by a type layout, and use that to infer the type of binding
        // used. Note that, for example, a `float4` might represent
        // multiple different kinds of binding, depending on where/how
        // it is used (e.g., as a varying parameter, a root constant, etc.).
        //
        return _calcBindingType(kind);
    }

    static DeclRefType* asInterfaceType(Type* type)
    {
        if(auto declRefType = as<DeclRefType>(type))
        {
            if(declRefType->getDeclRef().as<InterfaceDecl>())
            {
                return declRefType;
            }
        }
        return nullptr;
    }

    struct ExtendedTypeLayoutContext
    {
        TypeLayout* m_typeLayout;
        TypeLayout::ExtendedInfo* m_extendedInfo;

        Dictionary<Int, Int> m_mapSpaceToDescriptorSetIndex;

        Int _findOrAddDescriptorSet(Int space)
        {
            Int index = 0;
            if(m_mapSpaceToDescriptorSetIndex.tryGetValue(space, index))
                return index;

            index = m_extendedInfo->m_descriptorSets.getCount();
            m_mapSpaceToDescriptorSetIndex.add(space, index);

            RefPtr<TypeLayout::ExtendedInfo::DescriptorSetInfo> descriptorSet = new TypeLayout::ExtendedInfo::DescriptorSetInfo();
            m_extendedInfo->m_descriptorSets.add(descriptorSet);

            return index;
        }

            /// Create a single `VarLayout` for `typeLayout` that summarizes all of the offset information in `path`.
            ///
            /// Note: This function does not handle "pending" layout information.
        RefPtr<VarLayout> _createSimpleOffsetVarLayout(TypeLayout* typeLayout, BindingRangePathLink* path)
        {
            SLANG_ASSERT(typeLayout);

            RefPtr<VarLayout> varLayout = new VarLayout();
            varLayout->typeLayout = typeLayout;
            varLayout->typeLayout.demoteToWeakReference();

            for(auto typeResInfo : typeLayout->resourceInfos)
            {
                auto kind = typeResInfo.kind;
                auto varResInfo = varLayout->findOrAddResourceInfo(kind);
                varResInfo->index = _calcIndexOffset(path, kind);
                varResInfo->space = _calcSpaceOffset(path, kind);
            }

            return varLayout;
        }

            /// Create a single `VarLayout` for `typeLayout` that summarizes all of the offset information in `path`.
        RefPtr<VarLayout> createOffsetVarLayout(TypeLayout* typeLayout, BindingRangePath const& path)
        {
            auto primaryVarLayout = _createSimpleOffsetVarLayout(typeLayout, path.primary);
            SLANG_ASSERT(primaryVarLayout);

            if(auto pendingDataTypeLayout = typeLayout->pendingDataTypeLayout)
            {
                primaryVarLayout->pendingVarLayout = _createSimpleOffsetVarLayout(pendingDataTypeLayout, path.pending);
            }

            return primaryVarLayout;
        }

        void addRangesRec(TypeLayout* typeLayout, BindingRangePath const& path, LayoutSize multiplier)
        {
            if( auto structTypeLayout = as<StructTypeLayout>(typeLayout) )
            {
                // For a structure type, we need to recursively
                // add the ranges for each field.
                //
                // Along the way we will make sure to properly update
                // the offset information on the fields so that
                // they properly show their binding-range offset
                // within the parent type.
                //
                Index structBindingRangeIndex = m_extendedInfo->m_bindingRanges.getCount();
                for( auto fieldVarLayout : structTypeLayout->fields )
                {
                    Index fieldBindingRangeIndex = m_extendedInfo->m_bindingRanges.getCount();
                    fieldVarLayout->bindingRangeOffset = fieldBindingRangeIndex - structBindingRangeIndex;

                    auto fieldTypeLayout = fieldVarLayout->getTypeLayout();

                    ExtendedBindingRangePath fieldPath(path, fieldVarLayout);
                    addRangesRec(fieldTypeLayout, fieldPath, multiplier);
                }
                return;
            }
            else if( auto arrayTypeLayout = as<ArrayTypeLayout>(typeLayout) )
            {
                // For an array, we need to recursively add the
                // element type of the array, but with an adjusted
                // `multiplier` to account for the element count.
                //
                auto elementTypeLayout = arrayTypeLayout->elementTypeLayout;
                LayoutSize elementCount = LayoutSize::infinite();
                if( auto arrayType = as<ArrayExpressionType>(arrayTypeLayout->type) )
                {
                    if( !arrayType->isUnsized())
                    {
                        elementCount = LayoutSize::RawValue(getIntVal(arrayType->getElementCount()));
                    }
                }
                addRangesRec(elementTypeLayout, path, multiplier * elementCount);
                return;
            }
            else if( auto parameterGroupTypeLayout = as<ParameterGroupTypeLayout>(typeLayout))
            {
                // A parameter group (whether a `ConstantBuffer<>` or `ParameterBlock<>`
                // introduces a separately-allocated "sub-object" in the application's
                // layout for shader objects.
                //
                // We will represent the parameter group with a single sub-object
                // binding range (and an associated sub-object range).
                //
                // We start out by looking at the resources consumed by the parameter group
                // itself, to determine what kind of binding range to report it as.
                //
                Index bindingRangeIndex = m_extendedInfo->m_bindingRanges.getCount();
                SlangBindingType bindingType = SLANG_BINDING_TYPE_CONSTANT_BUFFER;
                bool shouldAllocDescriptorSet = true;
                LayoutResourceKind kind = LayoutResourceKind::None;

                // If the parameter group container starts a new space,
                // we do not want to allocate a descriptor set from the current parent.
                if (parameterGroupTypeLayout->containerVarLayout->FindResourceInfo(LayoutResourceKind::RegisterSpace))
                {
                    kind = LayoutResourceKind::RegisterSpace;
                    bindingType = SLANG_BINDING_TYPE_PARAMETER_BLOCK;
                    shouldAllocDescriptorSet = false;
                }

                if (shouldAllocDescriptorSet)
                {
                    // If this is not a parameter block, derive the binding type
                    // from resource infos.
                    for(auto& resInfo : parameterGroupTypeLayout->resourceInfos)
                    {
                        kind = resInfo.kind;
                        switch(kind)
                        {
                        default:
                            continue;

                        case LayoutResourceKind::ConstantBuffer:
                        case LayoutResourceKind::PushConstantBuffer:
                        case LayoutResourceKind::DescriptorTableSlot:
                            break;

                            // Certain cases indicate a parameter block that
                            // actually involves indirection.
                            //
                            // Note: the only case where a parameter group should
                            // reflect as consuming `Uniform` storage is on CPU/CUDA,
                            // where that will be the only resource it contains.
                        case LayoutResourceKind::Uniform:
                            break;
                        }

                        bindingType = _calcBindingType(typeLayout, kind);
                        break;
                    }
                }
                
                TypeLayout::ExtendedInfo::BindingRangeInfo bindingRange;
                bindingRange.leafTypeLayout = typeLayout;
                bindingRange.leafVariable = path.primary ? path.primary->var->getVariable() : nullptr;
                bindingRange.bindingType = bindingType;
                bindingRange.count = multiplier;
                bindingRange.descriptorSetIndex = -1;
                bindingRange.firstDescriptorRangeIndex = 0;
                bindingRange.descriptorRangeCount = 0;

                // Every parameter group will introduce a sub-object range,
                // which will include bindings based on the type of data
                // inside the sub-object.
                //
                TypeLayout::ExtendedInfo::SubObjectRangeInfo subObjectRange;
                subObjectRange.bindingRangeIndex = bindingRangeIndex;
                subObjectRange.offsetVarLayout = createOffsetVarLayout(typeLayout, path);
                subObjectRange.spaceOffset = 0;
                if (kind == LayoutResourceKind::SubElementRegisterSpace && path.primary)
                {
                    if (auto resInfo = path.primary->var->FindResourceInfo(LayoutResourceKind::SubElementRegisterSpace))
                    {
                        subObjectRange.spaceOffset = resInfo->index;
                    }
                }
                // It is possible that the sub-object has descriptor ranges
                // that will need to be exposed upward, into the parent.
                //
                // Note: it is a subtle point, but we are only going to expose
                // *descriptor ranges* upward and not *binding ranges*. The
                // distinction here comes down to:
                //
                // * Descriptor ranges are used to describe the entries that
                //   must be allocated in one or more API descriptor sets to
                //   physically hold a value of a given type (layout).
                //
                // * Binding ranges are used to describe the entries that must
                //   be allocated in an application shader object to logically
                //   hold a value of a given type (layout).
                //
                // In practice, a binding range might logically belong to a
                // sub-object, but physically belong to a parent. Consider:
                //
                //    cbuffer C { Texture2D a; float b; }
                //
                // Independent of the API we compile for, we expect the global
                // scope to have a sub-object for `C`, and for that sub-object
                // to have a binding range for `a` (that is, we bind the texture
                // into the sub-object).
                //
                // When compiling for D3D12 or Vulkan, we expect that the global
                // scope must have two descriptor ranges for `C`: one for the
                // constant buffer itself, and another for the texture `a`.
                // The reason for this is that `a` needs to be bound as part
                // of a descriptor set, and `C` doesn't create/allocate its own
                // descriptor set(s).
                //
                // When compiling for CPU or CUDA, we expect that the global scope
                // will have a descriptor range for `C` but *not* one for `C.a`,
                // because the physical storage for `C.a` is provided by the
                // memory allocation for `C` itself.

                if (shouldAllocDescriptorSet)
                {
                    // The logic here assumes that when a parameter group consumes
                    // resources that must "leak" into the outer scope (including
                    // reosurces consumed by the group "container"), those resources
                    // will amount to descriptor ranges that are part of the same
                    // descriptor set.
                    //
                    // (If the contents of a group consume whole spaces/sets, then
                    // those resources will be accounted for separately).
                    //
                    Int descriptorSetIndex = _findOrAddDescriptorSet(0);
                    auto descriptorSet = m_extendedInfo->m_descriptorSets[descriptorSetIndex];
                    auto firstDescriptorRangeIndex = descriptorSet->descriptorRanges.getCount();

                    // First, we need to deal with any descriptor ranges that are
                    // introduced by the "container" type itself.
                    //
                    switch(kind)
                    {
                        // If the parameter group was allocated to consume one or
                        // more whole register spaces/sets, then nothing should
                        // leak through that is measured in descriptor sets.
                        //
                    case LayoutResourceKind::SubElementRegisterSpace:
                    case LayoutResourceKind::None:
                        break;

                    default:
                        {
                            // In a constant-buffer-like case, then all the (non-space/set) resource
                            // usage of the "container" should be reflected as descriptor
                            // ranges in the parent scope.
                            //
                            for(auto resInfo : parameterGroupTypeLayout->containerVarLayout->typeLayout->resourceInfos)
                            {
                                switch( resInfo.kind )
                                {
                                case LayoutResourceKind::SubElementRegisterSpace:
                                    continue;

                                default:
                                    break;
                                }

                                TypeLayout::ExtendedInfo::DescriptorRangeInfo descriptorRange;
                                descriptorRange.kind = resInfo.kind;
                                descriptorRange.bindingType = _calcBindingType(typeLayout, resInfo.kind);
                                descriptorRange.count = multiplier;
                                descriptorRange.indexOffset = _calcIndexOffset(path.primary, resInfo.kind);
                                descriptorSet->descriptorRanges.add(descriptorRange);
                            }
                        }

                    }

                    // Second, we need to consider resource usage from the "element"
                    // type that might leak through to the parent.
                    //
                    switch(kind)
                    {
                        // If the parameter group was allocated as a full register space/set,
                        // *or* if it was allocated as ordinary uniform storage (likely
                        // because it was compiled for CPU/CUDA), then there should
                        // be no "leakage" of descriptor ranges from the element type
                        // to the parent.
                        //
                    case LayoutResourceKind::SubElementRegisterSpace:
                    case LayoutResourceKind::Uniform:
                    case LayoutResourceKind::None:
                        break;

                    default:
                        {
                            // If we are in the constant-buffer-like case, on an API
                            // where constant bufers "leak" resource usage to the
                            // outer context, then we need to add the descriptor ranges
                            // implied by the element type.
                            //
                            // HACK: We enumerate these nested ranges by recurisvely
                            // calling `addRangesRec`, which adds all of descriptor ranges,
                            // binding ranges, and sub-object ranges, and then we trim
                            // the lists we don't actually care about as a post-process.
                            //
                            // TODO: We could try to consider a model where we first
                            // query the extended layout information of the element
                            // type (which might already be cached) and then enumerate
                            // the descriptor ranges and copy them over.
                            //
                            // TODO: It is possible that there could be cases where
                            // some, but not all, of the nested descriptor ranges ought
                            // to be enumerated here. In that case we might have to introduce
                            // a kind of "mask" parameter that is passed down into
                            // the recursive call so that only the appropriate ranges
                            // get added.

                            // We need to add a link to the "path" that is used when looking
                            // up binding information, to ensure that the descriptor ranges
                            // that get enumerated here have correct register/binding offsets.
                            //
                            ExtendedBindingRangePath elementPath(path, parameterGroupTypeLayout->elementVarLayout);

                            Index bindingRangeCountBefore = m_extendedInfo->m_bindingRanges.getCount();
                            Index subObjectRangeCountBefore = m_extendedInfo->m_subObjectRanges.getCount();

                            addRangesRec(parameterGroupTypeLayout->elementVarLayout->typeLayout, elementPath, multiplier);

                            m_extendedInfo->m_bindingRanges.setCount(bindingRangeCountBefore);
                            m_extendedInfo->m_subObjectRanges.setCount(subObjectRangeCountBefore);
                        }
                        break;
                    }

                    auto descriptorRangeCount = descriptorSet->descriptorRanges.getCount() - firstDescriptorRangeIndex;
                    bindingRange.descriptorSetIndex = descriptorSetIndex;
                    bindingRange.firstDescriptorRangeIndex = firstDescriptorRangeIndex;
                    bindingRange.descriptorRangeCount = descriptorRangeCount;
                }

                m_extendedInfo->m_bindingRanges.add(bindingRange);
                m_extendedInfo->m_subObjectRanges.add(subObjectRange);
                return;
            }
            else if(asInterfaceType(typeLayout->type))
            {
                // An `interface` type should introduce a binding range and a matching
                // sub-object range.
                //
                TypeLayout::ExtendedInfo::BindingRangeInfo bindingRange;
                bindingRange.leafTypeLayout = typeLayout;
                bindingRange.leafVariable = path.primary ? path.primary->var->getVariable() : nullptr;
                bindingRange.bindingType = SLANG_BINDING_TYPE_EXISTENTIAL_VALUE;
                bindingRange.count = multiplier;
                bindingRange.descriptorSetIndex = 0;
                bindingRange.descriptorRangeCount = 0;
                bindingRange.firstDescriptorRangeIndex = 0;

                TypeLayout::ExtendedInfo::SubObjectRangeInfo subObjectRange;
                subObjectRange.bindingRangeIndex = m_extendedInfo->m_bindingRanges.getCount();
                subObjectRange.offsetVarLayout = createOffsetVarLayout(typeLayout, path);

                m_extendedInfo->m_bindingRanges.add(bindingRange);
                m_extendedInfo->m_subObjectRanges.add(subObjectRange);
            }
            else if(const auto structuredBufferTypeLayout = as<StructuredBufferTypeLayout>(typeLayout))
            {
                // For structured buffers we expect them to consume a single
                // resource descriptor slot (not counting the possible counter
                // buffer)
                SLANG_ASSERT(typeLayout->resourceInfos.getCount() >= 1);
                TypeLayout::ResourceInfo resInfo;
                for (auto& info : typeLayout->resourceInfos)
                {
                    switch (info.kind)
                    {
                    case LayoutResourceKind::UnorderedAccess:
                    case LayoutResourceKind::ShaderResource:
                    case LayoutResourceKind::DescriptorTableSlot:
                    case LayoutResourceKind::Uniform:
                    case LayoutResourceKind::ConstantBuffer: // for metal
                    case LayoutResourceKind::MetalArgumentBufferElement:
                        resInfo = info;
                        break;
                    }
                }
                SLANG_ASSERT(resInfo.kind != LayoutResourceKind::None);

                const auto bindingType = as<HLSLStructuredBufferType>(typeLayout->getType())
                    ? SLANG_BINDING_TYPE_RAW_BUFFER
                    : SLANG_BINDING_TYPE_MUTABLE_RAW_BUFFER;

                // We now allocate a descriptor range for this buffer
                TypeLayout::ExtendedInfo::DescriptorRangeInfo descriptorRange;
                descriptorRange.kind = resInfo.kind;
                descriptorRange.bindingType = bindingType;
                // Note that we don't use resInfo.count here, as each
                // structuredBufferType is essentially a struct of 2 fields
                // (elements, counter) and not an array of length 2.
                SLANG_ASSERT(resInfo.count != 2 || structuredBufferTypeLayout->counterVarLayout);
                SLANG_ASSERT(resInfo.count != 1 || !structuredBufferTypeLayout->counterVarLayout);
                descriptorRange.count = multiplier;
                descriptorRange.indexOffset = _calcIndexOffset(path.primary, resInfo.kind);

                Int descriptorSetIndex = _findOrAddDescriptorSet(_calcSpaceOffset(path.primary, resInfo.kind));
                const RefPtr<TypeLayout::ExtendedInfo::DescriptorSetInfo> descriptorSet
                    = m_extendedInfo->m_descriptorSets[descriptorSetIndex];
                auto descriptorRangeIndex = descriptorSet->descriptorRanges.getCount();
                descriptorSet->descriptorRanges.add(descriptorRange);

                // We will map the elements buffer to a single binding range
                TypeLayout::ExtendedInfo::BindingRangeInfo bindingRange;
                bindingRange.leafTypeLayout = typeLayout;
                bindingRange.leafVariable = path.primary ? path.primary->var->getVariable() : nullptr;
                bindingRange.bindingType = bindingType;
                bindingRange.count = multiplier;
                bindingRange.descriptorSetIndex = descriptorSetIndex;
                bindingRange.firstDescriptorRangeIndex = descriptorRangeIndex;
                bindingRange.descriptorRangeCount = 1;

                auto bindingRangeIndex = m_extendedInfo->m_bindingRanges.getCount();
                m_extendedInfo->m_bindingRanges.add(bindingRange);

                // We also make sure to report it as a sub-object range.
                TypeLayout::ExtendedInfo::SubObjectRangeInfo subObjectRange;
                subObjectRange.bindingRangeIndex = bindingRangeIndex;
                subObjectRange.offsetVarLayout = createOffsetVarLayout(typeLayout, path);
                subObjectRange.spaceOffset = 0;
                m_extendedInfo->m_subObjectRanges.add(subObjectRange);

                // If we have an associated counter for this structured buffer,
                // add its ranges
                if(structuredBufferTypeLayout->counterVarLayout)
                {
                    ExtendedBindingRangePath counterPath(
                        path,
                        structuredBufferTypeLayout->counterVarLayout
                    );
                    // This should always be 1, because it comes after the
                    // single binding range we just added
                    structuredBufferTypeLayout->counterVarLayout->bindingRangeOffset =
                        m_extendedInfo->m_bindingRanges.getCount() - bindingRangeIndex;
                    addRangesRec(
                        structuredBufferTypeLayout->counterVarLayout->typeLayout,
                        counterPath,
                        multiplier
                    );
                }
            }
            else
            {
                // Here we have the catch-all case that handles "leaf" fields
                // that might need to introduce a binding range and descriptor
                // ranges.
                //
                // First, we want to determine what type of binding this
                // leaf field should map to, if any. We being by querying
                // the type itself, since there are many distinct descriptor
                // types for textures/buffers that can only be determined
                // by type, rather than by a `LayoutResourceKind`.
                //
                auto bindingType = _calcResourceBindingType(typeLayout);

                // It is possible that the type alone isn't enough to tell
                // us a specific binding type, at which point we need to
                // start looking at the actual resources the type layout
                // consumes.
                //
                if(bindingType == SLANG_BINDING_TYPE_UNKNOWN)
                {
                    // We will search through all the resource kinds that
                    // the type layout consumes, to see if we can find
                    // one that indicates a binding type we actually
                    // want to reflect.
                    //
                    for( auto resInfo : typeLayout->resourceInfos )
                    {
                        auto kind = resInfo.kind;
                        if(kind == LayoutResourceKind::Uniform)
                            continue;

                        auto kindBindingType = _calcBindingType(kind);
                        if(kindBindingType == SLANG_BINDING_TYPE_UNKNOWN)
                            continue;

                        // If we find a relevant binding type based on
                        // one of the resource kinds that are consumed,
                        // then we immediately stop the search and use
                        // the first one found (whether or not later
                        // entries might also provide something relevant).
                        //
                        bindingType = kindBindingType;
                        break;
                    }
                }

                // After we've tried to determine a binding type, if
                // we have nothing to go on then we don't want to add
                // a binding range.
                //
                if(bindingType == SLANG_BINDING_TYPE_UNKNOWN)
                    return;

                // We now know that the leaf field will map to a single binding range,
                // and zero or more descriptor ranges.
                //
                TypeLayout::ExtendedInfo::BindingRangeInfo bindingRange;
                bindingRange.leafTypeLayout = typeLayout;
                bindingRange.leafVariable = path.primary ? path.primary->var->getVariable() : nullptr;
                bindingRange.bindingType = bindingType;
                bindingRange.count = multiplier;
                bindingRange.descriptorSetIndex = 0;
                bindingRange.firstDescriptorRangeIndex = 0;
                bindingRange.descriptorRangeCount = 0;

                // We will associate the binding range with a specific descriptor
                // set on demand *if* we discover that it shold contain any
                // descriptor ranges.
                //
                RefPtr<TypeLayout::ExtendedInfo::DescriptorSetInfo> descriptorSet;


                // We will add a descriptor range for each relevant resource kind
                // that the type layout consumes.
                //
                for(auto resInfo : typeLayout->resourceInfos)
                {
                    auto kind = resInfo.kind;
                    switch( kind )
                    {
                    default:
                        break;


                        // There are many resource kinds that we do not want
                        // to expose as descriptor ranges simply because they
                        // do not actually allocate descriptors on our target
                        // APIs.
                        //
                        // Notably included here are uniform/ordinary data and
                        // varying input/output (including the ray-tracing cases).
                        //
                        // It is worth noting that we *do* allow root/push-constant
                        // ranges to be reflected as "descriptor" ranges here,
                        // despite the fact that they are not descriptor-bound
                        // under D3D12/Vulkan.
                        //
                        // In practice, even with us filtering out some cases here,
                        // an application/renderer layer will need to filter/translate
                        // or descriptor ranges into API-specific ones, and a one-to-one
                        // mapping should not be assumed.
                        //
                        // TODO: Make some clear decisions about what should and should
                        // not appear here.
                        //
                    case LayoutResourceKind::SubElementRegisterSpace:
                    case LayoutResourceKind::VaryingInput:
                    case LayoutResourceKind::VaryingOutput:
                    case LayoutResourceKind::HitAttributes:
                    case LayoutResourceKind::RayPayload:
                    case LayoutResourceKind::ExistentialTypeParam:
                    case LayoutResourceKind::ExistentialObjectParam:
                        continue;
                    }

                    // We will prefer to use a binding type derived from the specific
                    // resource kind, but will fall back to information from the
                    // type layout when that is not available.
                    //
                    // TODO: This logic probably needs a bit more work to handle
                    // the case of a combined texture-sampler field that is being
                    // compiled for an API with separate textures and samplers.
                    //
                    auto kindBindingType = _calcBindingType(kind);
                    if( kindBindingType == SLANG_BINDING_TYPE_UNKNOWN )
                    {
                        kindBindingType = bindingType;
                    }

                    // We now expect to allocate a descriptor range for this
                    // `resInfo` representing resouce usage.
                    //
                    auto count = resInfo.count * multiplier;
                    auto indexOffset = _calcIndexOffset(path.primary, kind);
                    auto spaceOffset = _calcSpaceOffset(path.primary, kind);

                    TypeLayout::ExtendedInfo::DescriptorRangeInfo descriptorRange;
                    descriptorRange.kind = kind;
                    descriptorRange.bindingType = kindBindingType;
                    descriptorRange.count = count;
                    descriptorRange.indexOffset = indexOffset;

                    if(!descriptorSet)
                    {
                        Int descriptorSetIndex = _findOrAddDescriptorSet(spaceOffset);
                        descriptorSet = m_extendedInfo->m_descriptorSets[descriptorSetIndex];

                        bindingRange.descriptorSetIndex = descriptorSetIndex;
                        bindingRange.firstDescriptorRangeIndex = descriptorSet->descriptorRanges.getCount();
                    }

                    descriptorSet->descriptorRanges.add(descriptorRange);
                    bindingRange.descriptorRangeCount++;
                }

                m_extendedInfo->m_bindingRanges.add(bindingRange);
            }
        }
    };

    TypeLayout::ExtendedInfo* getExtendedTypeLayout(TypeLayout* typeLayout)
    {
        if( !typeLayout->m_extendedInfo )
        {
            RefPtr<TypeLayout::ExtendedInfo> extendedInfo = new TypeLayout::ExtendedInfo;

            ExtendedTypeLayoutContext context;
            context.m_typeLayout = typeLayout;
            context.m_extendedInfo = extendedInfo;

            BindingRangePath rootPath;
            context.addRangesRec(typeLayout, rootPath, 1);

            typeLayout->m_extendedInfo = extendedInfo;
        }
        return typeLayout->m_extendedInfo;
    }
}

SLANG_API SlangInt spReflectionTypeLayout_getBindingRangeCount(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);
    return extTypeLayout->m_bindingRanges.getCount();
}

SLANG_API SlangBindingType spReflectionTypeLayout_getBindingRangeType(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return SLANG_BINDING_TYPE_UNKNOWN;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);
    if(index < 0) return SLANG_BINDING_TYPE_UNKNOWN;
    if(index >= extTypeLayout->m_bindingRanges.getCount()) return SLANG_BINDING_TYPE_UNKNOWN;
    auto& bindingRange = extTypeLayout->m_bindingRanges[index];

    return bindingRange.bindingType;
}

SLANG_API SlangInt spReflectionTypeLayout_isBindingRangeSpecializable(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if (!typeLayout) return SLANG_BINDING_TYPE_UNKNOWN;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);
    if (index < 0) return SLANG_BINDING_TYPE_UNKNOWN;
    if (index >= extTypeLayout->m_bindingRanges.getCount()) return SLANG_BINDING_TYPE_UNKNOWN;
    auto& bindingRange = extTypeLayout->m_bindingRanges[index];
    auto type = bindingRange.leafTypeLayout->getType();
    if (asInterfaceType(type))
        return 1;
    if (auto parameterGroupType = as<ParameterGroupType>(type))
    {
        if (asInterfaceType(parameterGroupType->getElementType()))
            return 1;
    }
    return 0;
}

SLANG_API SlangInt spReflectionTypeLayout_getBindingRangeBindingCount(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);
    if(index < 0) return 0;
    if(index >= extTypeLayout->m_bindingRanges.getCount()) return 0;
    auto& bindingRange = extTypeLayout->m_bindingRanges[index];

    auto count = bindingRange.count;
    return count.isFinite() ? SlangInt(count.getFiniteValue()) : -1;
}

#if 0
SLANG_API SlangInt spReflectionTypeLayout_getBindingRangeIndexOffset(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    return Slang::_findBindingRange(typeLayout, index).indexOffset;
}

SLANG_API SlangInt spReflectionTypeLayout_getBindingRangeSpaceOffset(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    return Slang::_findBindingRange(typeLayout, index).spaceOffset;
}
#endif

SLANG_API SlangReflectionTypeLayout* spReflectionTypeLayout_getBindingRangeLeafTypeLayout(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);
    if(index < 0) return 0;
    if(index >= extTypeLayout->m_bindingRanges.getCount()) return 0;
    auto& bindingRange = extTypeLayout->m_bindingRanges[index];

    return convert(bindingRange.leafTypeLayout);
}

SLANG_API SlangReflectionVariable* spReflectionTypeLayout_getBindingRangeLeafVariable(
    SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if (!typeLayout)
        return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);
    if (index < 0)
        return 0;
    if (index >= extTypeLayout->m_bindingRanges.getCount())
        return 0;
    auto& bindingRange = extTypeLayout->m_bindingRanges[index];

    return convert(DeclRef<Decl>(bindingRange.leafVariable));
}

SLANG_API SlangImageFormat spReflectionTypeLayout_getBindingRangeImageFormat(SlangReflectionTypeLayout* typeLayout, SlangInt index)
{
    auto typeLayout_ = convert(typeLayout);
    if (!typeLayout_) return SLANG_IMAGE_FORMAT_unknown;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout_);
    if (index < 0) return SLANG_IMAGE_FORMAT_unknown;
    if (index >= extTypeLayout->m_bindingRanges.getCount()) return SLANG_IMAGE_FORMAT_unknown;
    auto& bindingRange = extTypeLayout->m_bindingRanges[index];

    auto leafVar = bindingRange.leafVariable;
    if (auto formatAttrib = leafVar->findModifier<FormatAttribute>())
    {
        return (SlangImageFormat)formatAttrib->format;
    }
    return SLANG_IMAGE_FORMAT_unknown;
}


SLANG_API SlangInt spReflectionTypeLayout_getBindingRangeDescriptorSetIndex(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);
    if(index < 0) return 0;
    if(index >= extTypeLayout->m_bindingRanges.getCount()) return 0;
    auto& bindingRange = extTypeLayout->m_bindingRanges[index];

    return bindingRange.descriptorSetIndex;
}

SLANG_API SlangInt spReflectionTypeLayout_getBindingRangeFirstDescriptorRangeIndex(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);
    if(index < 0) return 0;
    if(index >= extTypeLayout->m_bindingRanges.getCount()) return 0;
    auto& bindingRange = extTypeLayout->m_bindingRanges[index];

    return bindingRange.firstDescriptorRangeIndex;
}

SLANG_API SlangInt spReflectionTypeLayout_getBindingRangeDescriptorRangeCount(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);
    if(index < 0) return 0;
    if(index >= extTypeLayout->m_bindingRanges.getCount()) return 0;
    auto& bindingRange = extTypeLayout->m_bindingRanges[index];

    return bindingRange.descriptorRangeCount;
}

SLANG_API SlangInt spReflectionTypeLayout_getDescriptorSetCount(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    return extTypeLayout->m_descriptorSets.getCount();
}

SLANG_API SlangInt spReflectionTypeLayout_getDescriptorSetSpaceOffset(SlangReflectionTypeLayout* inTypeLayout, SlangInt setIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    if(setIndex < 0) return 0;
    if(setIndex >= extTypeLayout->m_descriptorSets.getCount()) return 0;
    auto descriptorSet = extTypeLayout->m_descriptorSets[setIndex];

    return descriptorSet->spaceOffset;
}

SLANG_API SlangInt spReflectionTypeLayout_getDescriptorSetDescriptorRangeCount(SlangReflectionTypeLayout* inTypeLayout, SlangInt setIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    if(setIndex < 0) return 0;
    if(setIndex >= extTypeLayout->m_descriptorSets.getCount()) return 0;
    auto descriptorSet = extTypeLayout->m_descriptorSets[setIndex];

    return descriptorSet->descriptorRanges.getCount();
}

SLANG_API SlangInt spReflectionTypeLayout_getDescriptorSetDescriptorRangeIndexOffset(SlangReflectionTypeLayout* inTypeLayout, SlangInt setIndex, SlangInt rangeIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    if(setIndex < 0) return 0;
    if(setIndex >= extTypeLayout->m_descriptorSets.getCount()) return 0;
    auto descriptorSet = extTypeLayout->m_descriptorSets[setIndex];

    if(rangeIndex < 0) return 0;
    if(rangeIndex >= descriptorSet->descriptorRanges.getCount()) return 0;
    auto& range = descriptorSet->descriptorRanges[rangeIndex];

    return range.indexOffset;
}

SLANG_API SlangInt spReflectionTypeLayout_getDescriptorSetDescriptorRangeDescriptorCount(SlangReflectionTypeLayout* inTypeLayout, SlangInt setIndex, SlangInt rangeIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    if(setIndex < 0) return 0;
    if(setIndex >= extTypeLayout->m_descriptorSets.getCount()) return 0;
    auto descriptorSet = extTypeLayout->m_descriptorSets[setIndex];

    if(rangeIndex < 0) return 0;
    if(rangeIndex >= descriptorSet->descriptorRanges.getCount()) return 0;
    auto& range = descriptorSet->descriptorRanges[rangeIndex];

    auto count = range.count;
    return count.isFinite() ? count.getFiniteValue() : -1;
}

SLANG_API SlangBindingType spReflectionTypeLayout_getDescriptorSetDescriptorRangeType(SlangReflectionTypeLayout* inTypeLayout, SlangInt setIndex, SlangInt rangeIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return SLANG_BINDING_TYPE_UNKNOWN;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    if(setIndex < 0) return SLANG_BINDING_TYPE_UNKNOWN;
    if(setIndex >= extTypeLayout->m_descriptorSets.getCount()) return SLANG_BINDING_TYPE_UNKNOWN;
    auto descriptorSet = extTypeLayout->m_descriptorSets[setIndex];

    if(rangeIndex < 0) return SLANG_BINDING_TYPE_UNKNOWN;
    if(rangeIndex >= descriptorSet->descriptorRanges.getCount()) return SLANG_BINDING_TYPE_UNKNOWN;
    auto& range = descriptorSet->descriptorRanges[rangeIndex];

    return range.bindingType;
}

SLANG_API SlangParameterCategory spReflectionTypeLayout_getDescriptorSetDescriptorRangeCategory(SlangReflectionTypeLayout* inTypeLayout, SlangInt setIndex, SlangInt rangeIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return SLANG_PARAMETER_CATEGORY_NONE;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    if(setIndex < 0) return SLANG_PARAMETER_CATEGORY_NONE;
    if(setIndex >= extTypeLayout->m_descriptorSets.getCount()) return SLANG_PARAMETER_CATEGORY_NONE;
    auto descriptorSet = extTypeLayout->m_descriptorSets[setIndex];

    if(rangeIndex < 0) return SLANG_PARAMETER_CATEGORY_NONE;
    if(rangeIndex >= descriptorSet->descriptorRanges.getCount()) return SLANG_PARAMETER_CATEGORY_NONE;
    auto& range = descriptorSet->descriptorRanges[rangeIndex];

    return SlangParameterCategory(range.kind);
}

SLANG_API SlangInt spReflectionTypeLayout_getSubObjectRangeCount(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    return extTypeLayout->m_subObjectRanges.getCount();
}

SLANG_API SlangInt spReflectionTypeLayout_getSubObjectRangeBindingRangeIndex(SlangReflectionTypeLayout* inTypeLayout, SlangInt subObjectRangeIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    if(subObjectRangeIndex < 0) return 0;
    if(subObjectRangeIndex >= extTypeLayout->m_subObjectRanges.getCount()) return 0;

    return extTypeLayout->m_subObjectRanges[subObjectRangeIndex].bindingRangeIndex;
}

SLANG_API SlangInt spReflectionTypeLayout_getSubObjectRangeSpaceOffset(
    SlangReflectionTypeLayout* inTypeLayout,
    SlangInt subObjectRangeIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if (!typeLayout)
        return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    if (subObjectRangeIndex < 0)
        return 0;
    if (subObjectRangeIndex >= extTypeLayout->m_subObjectRanges.getCount())
        return 0;

    return extTypeLayout->m_subObjectRanges[subObjectRangeIndex].spaceOffset;
}

SLANG_API SlangReflectionVariableLayout* spReflectionTypeLayout_getSubObjectRangeOffset(
    SlangReflectionTypeLayout* inTypeLayout,
    SlangInt subObjectRangeIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if (!typeLayout)
        return 0;

    auto extTypeLayout = Slang::getExtendedTypeLayout(typeLayout);

    if (subObjectRangeIndex < 0)
        return 0;
    if (subObjectRangeIndex >= extTypeLayout->m_subObjectRanges.getCount())
        return 0;

    return convert(extTypeLayout->m_subObjectRanges[subObjectRangeIndex].offsetVarLayout);
}



#if 0
SLANG_API SlangInt spReflectionTypeLayout_getBindingRangeSubObjectRangeIndex(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    return Slang::_findBindingRange(typeLayout, index).subObjectRangeIndex;
}
#endif


SLANG_API SlangInt spReflectionTypeLayout_getFieldBindingRangeOffset(SlangReflectionTypeLayout* inTypeLayout, SlangInt fieldIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    if( auto structTypeLayout = as<StructTypeLayout>(typeLayout) )
    {
        getExtendedTypeLayout(structTypeLayout);

        return structTypeLayout->fields[fieldIndex]->bindingRangeOffset;
    }

    return 0;
}

SLANG_API SlangInt spReflectionTypeLayout_getExplicitCounterBindingRangeOffset(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    if(const auto structuredBufferTypeLayout = as<StructuredBufferTypeLayout>(typeLayout))
    {
        getExtendedTypeLayout(structuredBufferTypeLayout);
        return structuredBufferTypeLayout->counterVarLayout
            ? structuredBufferTypeLayout->counterVarLayout->bindingRangeOffset
            : 0;
    }

    return 0;
}

#if 0
SLANG_API SlangInt spReflectionTypeLayout_getSubObjectRangeCount(SlangReflectionTypeLayout* inTypeLayout)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    return Slang::_calcSubObjectRangeCount(typeLayout);
}

SLANG_API SlangInt spReflectionTypeLayout_getSubObjectRangeObjectCount(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto count = Slang::_findSubObjectRange(typeLayout, index).count;
    return count.isFinite() ? SlangInt(count.getFiniteValue()) : -1;
}

SLANG_API SlangInt spReflectionTypeLayout_getSubObjectRangeBindingRangeIndex(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    return Slang::_findSubObjectRange(typeLayout, index).bindingRangeIndex;
}


SLANG_API SlangReflectionTypeLayout* spReflectionTypeLayout_getSubObjectRangeTypeLayout(SlangReflectionTypeLayout* inTypeLayout, SlangInt index)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    return convert(Slang::_findSubObjectRange(typeLayout, index).leafTypeLayout);
}

SLANG_API SlangInt spReflectionTypeLayout_getSubObjectRangeDescriptorRangeCount(SlangReflectionTypeLayout* inTypeLayout, SlangInt subObjectRangeIndex)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto subObjectRange = Slang::_findSubObjectRange(typeLayout, subObjectRangeIndex);
    return Slang::_getSubObjectDescriptorRangeCount(subObjectRange);
}

SLANG_API SlangBindingType spReflectionTypeLayout_getSubObjectRangeDescriptorRangeBindingType(SlangReflectionTypeLayout* inTypeLayout, SlangInt subObjectRangeIndex, SlangInt bindingRangeIndexInSubObject)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto subObjectRange = Slang::_findSubObjectRange(typeLayout, subObjectRangeIndex);
    return Slang::_getSubObjectDescriptorRange(subObjectRange, bindingRangeIndexInSubObject).bindingType;
}

SLANG_API SlangInt spReflectionTypeLayout_getSubObjectRangeDescriptorRangeBindingCount(SlangReflectionTypeLayout* inTypeLayout, SlangInt subObjectRangeIndex, SlangInt bindingRangeIndexInSubObject)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto subObjectRange = Slang::_findSubObjectRange(typeLayout, subObjectRangeIndex);
    auto count = Slang::_getSubObjectDescriptorRange(subObjectRange, bindingRangeIndexInSubObject).count;
    return count.isFinite() ? count.getFiniteValue() : -1;
}

SLANG_API SlangInt spReflectionTypeLayout_getSubObjectRangeDescriptorRangeIndexOffset(SlangReflectionTypeLayout* inTypeLayout, SlangInt subObjectRangeIndex, SlangInt bindingRangeIndexInSubObject)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto subObjectRange = Slang::_findSubObjectRange(typeLayout, subObjectRangeIndex);
    return Slang::_getSubObjectDescriptorRange(subObjectRange, bindingRangeIndexInSubObject).indexOffset;
}

SLANG_API SlangInt spReflectionTypeLayout_getSubObjectRangeDescriptorRangeSpaceOffset(SlangReflectionTypeLayout* inTypeLayout, SlangInt subObjectRangeIndex, SlangInt bindingRangeIndexInSubObject)
{
    auto typeLayout = convert(inTypeLayout);
    if(!typeLayout) return 0;

    auto subObjectRange = Slang::_findSubObjectRange(typeLayout, subObjectRangeIndex);
    return Slang::_getSubObjectDescriptorRange(subObjectRange, bindingRangeIndexInSubObject).spaceOffset;
}
#endif

// Variable Reflection

SLANG_API char const* spReflectionVariable_GetName(SlangReflectionVariable* inVar)
{
    auto var = convert(inVar).getDecl();
    if (as<InheritanceDecl>(var))
        return "$base";

    if(!var) return nullptr;

    // If the variable is one that has an "external" name that is supposed
    // to be exposed for reflection, then report it here
    if(auto reflectionNameMod = var->findModifier<ParameterGroupReflectionName>())
        return getText(reflectionNameMod->nameAndLoc.name).getBuffer();

    return getText(var->getName()).getBuffer();
}

SLANG_API SlangReflectionType* spReflectionVariable_GetType(SlangReflectionVariable* inVar)
{
    auto var = convert(inVar);

    if(!var) return nullptr;

    auto astBuilder = getModule(var.getDecl())->getLinkage()->getASTBuilder();

    if (auto inheritanceDecl = as<InheritanceDecl>(var.getDecl()))
        return convert(inheritanceDecl->base.type);

    if (auto varDecl = as<VarDeclBase>(var.getDecl()))
        return convert(
            substituteType(
                SubstitutionSet(var),
                astBuilder,
                varDecl->getType()));
    
    return nullptr;
}

SLANG_API SlangReflectionModifier* spReflectionVariable_FindModifier(SlangReflectionVariable* inVar, SlangModifierID modifierID)
{
    auto var = convert(inVar).getDecl();

    if(!var) return nullptr;

    Modifier* modifier = nullptr;
    switch( modifierID )
    {
    case SLANG_MODIFIER_SHARED:
        modifier = var->findModifier<HLSLEffectSharedModifier>();
        break;
    case SLANG_MODIFIER_CONST:
        modifier = var->findModifier<ConstModifier>();
        break;
    case SLANG_MODIFIER_NO_DIFF:
        modifier = var->findModifier<NoDiffModifier>();
        break;
    case SLANG_MODIFIER_STATIC:
        modifier = var->findModifier<HLSLStaticModifier>();
        break;
    case SLANG_MODIFIER_EXPORT:
        modifier = var->findModifier<HLSLExportModifier>();
        break;
    case SLANG_MODIFIER_EXTERN:
        modifier = var->findModifier<ExternModifier>();
        break;
    case SLANG_MODIFIER_DIFFERENTIABLE:
        modifier = var->findModifier<DifferentiableAttribute>();
        break;
    case SLANG_MODIFIER_MUTATING:
        modifier = var->findModifier<MutatingAttribute>();
        break;
    case SLANG_MODIFIER_IN:
        modifier = var->findModifier<InModifier>();
        break;
    case SLANG_MODIFIER_OUT:
        modifier = var->findModifier<OutModifier>();
        break;
    case SLANG_MODIFIER_INOUT:
        modifier = var->findModifier<InOutModifier>();
        break;
    default:
        return nullptr;
    }

    return (SlangReflectionModifier*) modifier;
}

SLANG_API unsigned int spReflectionVariable_GetUserAttributeCount(SlangReflectionVariable* inVar)
{
    auto varDecl = convert(inVar).getDecl();
    if (!varDecl) return 0;
    return getUserAttributeCount(varDecl);
}
SLANG_API SlangReflectionUserAttribute* spReflectionVariable_GetUserAttribute(SlangReflectionVariable* inVar, unsigned int index)
{
    auto varDecl = convert(inVar).getDecl();
    if (!varDecl) return 0;
    return getUserAttributeByIndex(varDecl, index);
}
SLANG_API SlangReflectionUserAttribute* spReflectionVariable_FindUserAttributeByName(SlangReflectionVariable* inVar, SlangSession* session, char const* name)
{
    auto varDecl = convert(inVar).getDecl();
    if (!varDecl) return 0;
    return findUserAttributeByName(asInternal(session), varDecl, name);
}

SLANG_API bool spReflectionVariable_HasDefaultValue(SlangReflectionVariable* inVar)
{
    auto decl = convert(inVar).getDecl();
    if (auto varDecl = as<VarDeclBase>(decl))
    {
        return varDecl->initExpr != nullptr;
    }
    
    return false;
}

SLANG_API SlangReflectionGeneric* spReflectionVariable_GetGenericContainer(SlangReflectionVariable* var)
{
    auto declRef = convert(var);
    return convertDeclToGeneric(getInnermostGenericParent(declRef));
}

SLANG_API SlangReflectionVariable* spReflectionVariable_applySpecializations(SlangReflectionVariable* var, SlangReflectionGeneric* generic)
{
    auto declRef = convert(var);
    auto genericDeclRef = convertGenericToDeclRef(generic);
    if (!declRef || !genericDeclRef)
        return nullptr;
    
    auto astBuilder = getModule(declRef.getDecl())->getLinkage()->getASTBuilder();

    auto substDeclRef = substituteDeclRef(SubstitutionSet(genericDeclRef), astBuilder, declRef);
    return convert(substDeclRef);
}

// Variable Layout Reflection

SLANG_API SlangReflectionVariable* spReflectionVariableLayout_GetVariable(SlangReflectionVariableLayout* inVarLayout)
{
    auto varLayout = convert(inVarLayout);
    if(!varLayout) return nullptr;

    return convert(varLayout->varDecl);
}

SLANG_API SlangReflectionTypeLayout* spReflectionVariableLayout_GetTypeLayout(SlangReflectionVariableLayout* inVarLayout)
{
    auto varLayout = convert(inVarLayout);
    if(!varLayout) return nullptr;

    return convert(varLayout->getTypeLayout());
}

SLANG_API size_t spReflectionVariableLayout_GetOffset(SlangReflectionVariableLayout* inVarLayout, SlangParameterCategory category)
{
    auto varLayout = convert(inVarLayout);
    if(!varLayout) return 0;

    auto info = varLayout->FindResourceInfo(LayoutResourceKind(category));

    if (!info)
    {
        // No match with requested category? Try again with one they might have meant...
        category = maybeRemapParameterCategory(varLayout->getTypeLayout(), category);
        info = varLayout->FindResourceInfo(LayoutResourceKind(category));
    }

    if(!info) return 0;

    return info->index;
}

SLANG_API size_t spReflectionVariableLayout_GetSpace(SlangReflectionVariableLayout* inVarLayout, SlangParameterCategory category)
{
    auto varLayout = convert(inVarLayout);
    if(!varLayout) return 0;


    auto info = varLayout->FindResourceInfo(LayoutResourceKind(category));
    if (!info)
    {
        // No match with requested category? Try again with one they might have meant...
        category = maybeRemapParameterCategory(varLayout->getTypeLayout(), category);
        info = varLayout->FindResourceInfo(LayoutResourceKind(category));
    }

    UInt space = 0;

    // First, deal with any offset applied to the specific resource kind specified
    if (info)
    {
        space += info->space;
    }

    if (auto regSpaceInfo = varLayout->FindResourceInfo(LayoutResourceKind::RegisterSpace))
        space += regSpaceInfo->index;

    // Note: this code used to try and take a variable with
    // an offset for `LayoutResourceKind::RegisterSpace` and
    // add it to the space returned, but that isn't going
    // to be right in some cases.
    //
    // Imageine if we have:
    //
    //  struct X { Texture2D y; }
    //  struct S { Texture2D t; ParmaeterBlock<X> x; }
    //
    //  Texture2D gA;
    //  S gS;
    //
    // We expect `gS` to have an offset for `LayoutResourceKind::ShaderResourceView`
    // of one (since its texture must come after `gA`), and an offset for
    // `LayoutResourceKind::RegisterSpace` of one (since the default space will be
    // space zero). It would be incorrect for us to imply that `gS.t` should
    // be `t1, space1`, though, because the space offset of `gS` doesn't actually
    // apply to `t`.
    //
    // For now we are punting on this issue and leaving it in the hands of the
    // application to determine when a space offset from an "outer" variable should
    // apply to the locations of things in an "inner" variable.
    //
    // There is no policy we can apply locally in this function that
    // will Just Work, so the best we can do is try to not lie.

    return space;
}

SLANG_API char const* spReflectionVariableLayout_GetSemanticName(SlangReflectionVariableLayout* inVarLayout)
{
    auto varLayout = convert(inVarLayout);
    if(!varLayout) return 0;

    if (!(varLayout->flags & Slang::VarLayoutFlag::HasSemantic))
        return 0;

    return varLayout->semanticName.getBuffer();
}

SLANG_API size_t spReflectionVariableLayout_GetSemanticIndex(SlangReflectionVariableLayout* inVarLayout)
{
    auto varLayout = convert(inVarLayout);
    if(!varLayout) return 0;

    if (!(varLayout->flags & Slang::VarLayoutFlag::HasSemantic))
        return 0;

    return varLayout->semanticIndex;
}

SLANG_API SlangStage spReflectionVariableLayout_getStage(
    SlangReflectionVariableLayout* inVarLayout)
{
    auto varLayout = convert(inVarLayout);
    if(!varLayout) return SLANG_STAGE_NONE;

    // A parameter that is not a varying input or output is
    // not considered to belong to a single stage.
    //
    // TODO: We might need to reconsider this for, e.g., entry
    // point parameters, where they might be stage-specific even
    // if they are uniform.
    if (!varLayout->FindResourceInfo(Slang::LayoutResourceKind::VaryingInput)
        && !varLayout->FindResourceInfo(Slang::LayoutResourceKind::VaryingOutput))
    {
        return SLANG_STAGE_NONE;
    }

    // TODO: We should find the stage for a variable layout by
    // walking up the tree of layout information, until we find
    // something that has a definitive stage attached to it (e.g.,
    // either an entry point or a GLSL translation unit).
    //
    // We don't currently have parent links in the reflection layout
    // information, so doing that walk would be tricky right now, so
    // it is easier to just bloat the representation and store yet another
    // field on every variable layout.
    return (SlangStage) varLayout->stage;
}

// Function Reflection

SLANG_API SlangReflectionDecl* spReflectionFunction_asDecl(SlangReflectionFunction* inFunc)
{
    auto func = convertToFunc(inFunc);
    if (!func) return nullptr;

    return (SlangReflectionDecl*)func.getDecl();
}

SLANG_API char const* spReflectionFunction_GetName(SlangReflectionFunction* inFunc)
{
    auto func = convertToFunc(inFunc);
    if (!func) return nullptr;

    return getText(func.getDecl()->getName()).getBuffer();
}

SLANG_API SlangReflectionType* spReflectionFunction_GetResultType(SlangReflectionFunction* inFunc)
{
    auto func = convertToFunc(inFunc);
    if (!func) return nullptr;

    auto rawType = func.getDecl()->returnType.type;
    auto astBuilder = rawType->getASTBuilderForReflection();

    return convert((Type*)rawType->substitute(astBuilder, SubstitutionSet(func.declRefBase)));
}

SLANG_API SlangReflectionModifier* spReflectionFunction_FindModifier(SlangReflectionFunction* inFunc, SlangModifierID modifierID)
{
    auto funcDeclRef = convertToFunc(inFunc);
    if (!funcDeclRef) return nullptr;

    auto varRefl = convert(funcDeclRef.as<Decl>());
    if (!varRefl) return nullptr;

    return spReflectionVariable_FindModifier(varRefl, modifierID);
}

SLANG_API unsigned int spReflectionFunction_GetUserAttributeCount(SlangReflectionFunction* inFunc)
{
    auto func = convertToFunc(inFunc);
    if (!func) return 0;

    return getUserAttributeCount(func.getDecl());
}

SLANG_API SlangReflectionUserAttribute* spReflectionFunction_GetUserAttribute(SlangReflectionFunction* inFunc, unsigned int index)
{
    auto func = convertToFunc(inFunc);
    if (!func) return nullptr;
    return getUserAttributeByIndex(func.getDecl(), index);
}

SLANG_API SlangReflectionUserAttribute* spReflectionFunction_FindUserAttributeByName(SlangReflectionFunction* inFunc, SlangSession* session, char const* name)
{
    auto func = convertToFunc(inFunc);
    if (!func) return nullptr;

    return findUserAttributeByName(asInternal(session), func.getDecl(), name);
}

SLANG_API unsigned int spReflectionFunction_GetParameterCount(SlangReflectionFunction* inFunc)
{
    auto func = convertToFunc(inFunc);
    if (!func) return 0;

    return (unsigned int)func.getDecl()->getParameters().getCount();
}

SLANG_API SlangReflectionVariable* spReflectionFunction_GetParameter(SlangReflectionFunction* inFunc, unsigned int index)
{
    auto func = convertToFunc(inFunc);
    if (!func) return nullptr;

    auto astBuilder = getModule(func.getDecl())->getLinkage()->getASTBuilder();

    return convert(getParameters(astBuilder, func)[index]);
}

SLANG_API SlangReflectionGeneric* spReflectionFunction_GetGenericContainer(SlangReflectionFunction* func)
{
    auto declRef = convertToFunc(func);
    if (!declRef)
        return nullptr;

    return convertDeclToGeneric(getInnermostGenericParent(declRef));
}

SLANG_API SlangReflectionFunction* spReflectionFunction_applySpecializations(SlangReflectionFunction* func, SlangReflectionGeneric* generic)
{
    auto declRef = convertToFunc(func);
    auto genericDeclRef = convertGenericToDeclRef(generic);
    if (!declRef || !genericDeclRef)
        return nullptr;

    auto astBuilder = getModule(declRef.getDecl())->getLinkage()->getASTBuilder();

    auto substDeclRef = substituteDeclRef(SubstitutionSet(genericDeclRef), astBuilder, declRef);
    return convert(substDeclRef.as<FunctionDeclBase>());
}

SLANG_API SlangReflectionFunction* spReflectionFunction_specializeWithArgTypes(
    SlangReflectionFunction* func,
    SlangInt argTypeCount,
    SlangReflectionType* const* argTypes)
{
    Linkage* linkage = nullptr;
    Expr* funcExpr = nullptr;

    if (auto funcDeclRef = convertToFunc(func))
    {
        linkage = getModule(funcDeclRef.getDecl())->getLinkage();
        auto declRefExpr = linkage->getASTBuilder()->create<DeclRefExpr>();
        declRefExpr->declRef = funcDeclRef;
        funcExpr = declRefExpr;
    }
    else if (auto overloadedExpr = convertToOverloadedFunc(func))
    {
        linkage = getModule(overloadedExpr->lookupResult2.items[0].declRef.getDecl())->getLinkage();
        funcExpr = overloadedExpr;
    }
    else
    {
        return nullptr;
    }
    
    List<Type*> argTypeList;
    for (SlangInt ii = 0; ii < argTypeCount; ++ii)
    {
        auto argType = convert(argTypes[ii]);
        argTypeList.add(argType);
    }

    try 
    {
        DiagnosticSink sink(linkage->getSourceManager(), Lexer::sourceLocationLexer);
        auto resultFunc = linkage->specializeWithArgTypes(funcExpr, argTypeList, &sink).as<FunctionDeclBase>();

        if (sink.getErrorCount() != 0)
            return nullptr; // Failed coercion.

        return convert(resultFunc);
    }
    catch (...)
    {
        return nullptr;
    }
}

SLANG_API bool spReflectionFunction_isOverloaded(
    SlangReflectionFunction* func)
{
    return (convertToOverloadedFunc(func) != nullptr);
}

SLANG_API unsigned int spReflectionFunction_getOverloadCount(
    SlangReflectionFunction* func)
{
    auto overloadedFunc = convertToOverloadedFunc(func);
    if (!overloadedFunc) return 1;

    return (unsigned int) overloadedFunc->lookupResult2.items.getCount();
}

SLANG_API SlangReflectionFunction* spReflectionFunction_getOverload(
    SlangReflectionFunction* func,
    unsigned int index)
{
    auto overloadedFunc = convertToOverloadedFunc(func);
    if (!overloadedFunc) return nullptr;

    auto declRef = overloadedFunc->lookupResult2.items[index].declRef;
    if (auto funcDeclRef = declRef.as<FunctionDeclBase>())
    {
        return convert(declRef.as<FunctionDeclBase>());
    }
    else if (auto genericDeclRef = declRef.as<GenericDecl>())
    {
        auto astBuilder = getModule(genericDeclRef.getDecl())->getLinkage()->getASTBuilder();
        auto innerDeclRef = substituteDeclRef(
                SubstitutionSet(genericDeclRef), astBuilder, genericDeclRef.getDecl()->inner);
        return convert(
            createDefaultSubstitutionsIfNeeded(astBuilder, nullptr, innerDeclRef).as<FunctionDeclBase>());
    }

    return nullptr;
}    

// Abstract decl reflection

SLANG_API unsigned int spReflectionDecl_getChildrenCount(SlangReflectionDecl* parentDecl)
{
    Decl* decl = (Decl*)parentDecl;
    if (as<ContainerDecl>(decl))
    {
        return (unsigned int)as<ContainerDecl>(decl)->members.getCount();
    }
    
    return 0;
}

SLANG_API SlangReflectionDecl* spReflectionDecl_getChild(SlangReflectionDecl* parentDecl, unsigned int index)
{
    Decl* decl = (Decl*)parentDecl;
    if (auto containerDecl = as<ContainerDecl>(decl))
    {
        if (containerDecl->members.getCount() > index)
            return (SlangReflectionDecl*)containerDecl->members[index];
    }

    return nullptr;
}

SLANG_API char const* spReflectionDecl_getName(SlangReflectionDecl* decl)
{
    Decl* slangDecl = (Decl*)decl;
    
    if (auto name = slangDecl->getName())
        return getText(name).getBuffer();

    return nullptr;
}

SLANG_API SlangDeclKind spReflectionDecl_getKind(SlangReflectionDecl* decl)
{
    Decl* slangDecl = (Decl*)decl;
    if (as<StructDecl>(slangDecl))
    {
        return SLANG_DECL_KIND_STRUCT;
    }
    else if (as<VarDeclBase>(slangDecl))
    {
        return SLANG_DECL_KIND_VARIABLE;
    }
    else if (as<GenericDecl>(slangDecl))
    {
        return SLANG_DECL_KIND_GENERIC;
    }
    else if (as<FunctionDeclBase>(slangDecl))
    {
        return SLANG_DECL_KIND_FUNC;
    }
    else if (as<ModuleDecl>(slangDecl))
    {
        return SLANG_DECL_KIND_MODULE;
    }
    else if (as<NamespaceDecl>(slangDecl))
    {
        return SLANG_DECL_KIND_NAMESPACE;
    }
    else
        return SLANG_DECL_KIND_UNSUPPORTED_FOR_REFLECTION;
}

SLANG_API SlangReflectionFunction* spReflectionDecl_castToFunction(SlangReflectionDecl* decl)
{
    Decl* slangDecl = (Decl*) decl;
    if (auto funcDecl = as<FunctionDeclBase>(slangDecl))
    {
        return convert(DeclRef<FunctionDeclBase>(funcDecl->getDefaultDeclRef()));
    }

    // Improper cast
    return nullptr;
}

SLANG_API SlangReflectionVariable* spReflectionDecl_castToVariable(SlangReflectionDecl* decl)
{
    Decl* slangDecl = (Decl*) decl;
    if (auto varDecl = as<VarDeclBase>(slangDecl))
    {
        return convert(DeclRef(varDecl));
    }

    // Improper cast
    return nullptr;
}

SLANG_API SlangReflectionGeneric* spReflectionDecl_castToGeneric(SlangReflectionDecl* decl)
{
    Decl* slangDecl = (Decl*) decl;
    if (auto genericInnerDecl = as<GenericDecl>(slangDecl)->inner)
    {
        return convertDeclToGeneric(genericInnerDecl);
    }

    // Improper cast
    return nullptr;
}

SLANG_API SlangReflectionType* spReflection_getTypeFromDecl(SlangReflectionDecl* decl)
{
    Decl* slangDecl = (Decl*)decl;

    ASTBuilder* builder = getModule(slangDecl)->getLinkage()->getASTBuilder();
    // TODO: create default substitutions
    if (auto type = DeclRefType::create(builder, slangDecl->getDefaultDeclRef()))
    {
        return convert(type);
    }

    // Couldn't create a type from the decl
    return nullptr;
}

SLANG_API SlangReflectionDecl* spReflectionDecl_getParent(SlangReflectionDecl* decl)
{
    Decl* slangDecl = (Decl*)decl;
    if (auto parentDecl = slangDecl->parentDecl)
    {
        return (SlangReflectionDecl*)parentDecl;
    }

    return nullptr;
}

// Generic Reflection

SLANG_API SlangReflectionDecl* spReflectionGeneric_asDecl(SlangReflectionGeneric* generic)
{
    return (SlangReflectionDecl*) convertGenericToDeclRef(generic).getDecl()->parentDecl;
}

SLANG_API char const* spReflectionGeneric_GetName(SlangReflectionGeneric* generic)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return nullptr;
    return getText(slangGeneric.getDecl()->getName()).getBuffer();
}

SLANG_API unsigned int spReflectionGeneric_GetTypeParameterCount(SlangReflectionGeneric* generic)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return 0;
    auto astBuilder = getModule(slangGeneric.getDecl())->getLinkage()->getASTBuilder();

    return (unsigned int) getMembersOfType<GenericTypeParamDecl>(astBuilder, slangGeneric.getDecl()->parentDecl).getCount();
}

SLANG_API SlangReflectionVariable* spReflectionGeneric_GetTypeParameter(SlangReflectionGeneric* generic, unsigned index)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return nullptr;
    auto astBuilder = getModule(slangGeneric.getDecl())->getLinkage()->getASTBuilder();

    auto paramDeclRef = getMembersOfType<GenericTypeParamDecl>(astBuilder, slangGeneric.getDecl()->parentDecl)[index];

    return convert(substituteDeclRef(SubstitutionSet(slangGeneric), astBuilder, paramDeclRef));
}

SLANG_API unsigned int spReflectionGeneric_GetValueParameterCount(SlangReflectionGeneric* generic)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return 0;
    auto astBuilder = getModule(slangGeneric.getDecl())->getLinkage()->getASTBuilder();

    return (unsigned int) getMembersOfType<GenericValueParamDecl>(astBuilder, slangGeneric.getDecl()->parentDecl).getCount();
}

SLANG_API SlangReflectionVariable* spReflectionGeneric_GetValueParameter(SlangReflectionGeneric* generic, unsigned index)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return nullptr;
    auto astBuilder = getModule(slangGeneric.getDecl())->getLinkage()->getASTBuilder();

    auto paramDeclRef = getMembersOfType<GenericValueParamDecl>(astBuilder, slangGeneric.getDecl()->parentDecl)[index];

    return convert(substituteDeclRef(SubstitutionSet(slangGeneric), astBuilder, paramDeclRef));
}

SLANG_API unsigned int spReflectionGeneric_GetTypeParameterConstraintCount(SlangReflectionGeneric* generic, SlangReflectionVariable* typeParam)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return 0;
    auto astBuilder = getModule(slangGeneric.getDecl())->getLinkage()->getASTBuilder();

    if (auto typeParamDecl = as<GenericTypeParamDecl>(convert(typeParam).getDecl()))
    {
        auto constraints = getCanonicalGenericConstraints(
            astBuilder, 
            DeclRef<GenericDecl>(slangGeneric.getDecl()->parentDecl));
        return (unsigned int)(constraints[typeParamDecl]).getValue().getCount();
    }

    return 0;
}

SLANG_API SlangReflectionType* spReflectionGeneric_GetTypeParameterConstraintType(SlangReflectionGeneric* generic, SlangReflectionVariable* typeParam, unsigned index)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return nullptr;
    auto astBuilder = getModule(slangGeneric.getDecl())->getLinkage()->getASTBuilder();

    if (auto typeParamDecl = as<GenericTypeParamDecl>(convert(typeParam).getDecl()))
    {
        auto constraints = getCanonicalGenericConstraints(
            astBuilder,
            DeclRef<GenericDecl>(slangGeneric.getDecl()->parentDecl));
        if (auto constraint = (constraints[typeParamDecl]).getValue()[index])
        {
            return convert(substituteType(SubstitutionSet(slangGeneric), astBuilder, constraint));
        }
    }

    return nullptr;
}

SLANG_API SlangDeclKind spReflectionGeneric_GetInnerKind(SlangReflectionGeneric* generic)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return SLANG_DECL_KIND_UNSUPPORTED_FOR_REFLECTION;

    return spReflectionDecl_getKind((SlangReflectionDecl*)slangGeneric.getDecl());
}

SLANG_API SlangReflectionDecl* spReflectionGeneric_GetInnerDecl(SlangReflectionGeneric* generic)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return nullptr;

    return (SlangReflectionDecl*)slangGeneric.getDecl();
}

SLANG_API SlangReflectionGeneric* spReflectionGeneric_GetOuterGenericContainer(SlangReflectionGeneric* generic)
{
    auto declRef = convertGenericToDeclRef(generic);
    
    auto astBuilder = getModule(declRef.getDecl())->getLinkage()->getASTBuilder();

    return convertDeclToGeneric(
        getInnermostGenericParent(
            substituteDeclRef(
                SubstitutionSet(declRef),
                astBuilder,
                createDefaultSubstitutionsIfNeeded(astBuilder, nullptr, DeclRef(declRef.getDecl()->parentDecl)))));
}

SLANG_API SlangReflectionType* spReflectionGeneric_GetConcreteType(SlangReflectionGeneric* generic, SlangReflectionVariable* typeParam)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return nullptr;
    auto astBuilder = getModule(slangGeneric.getDecl())->getLinkage()->getASTBuilder();
    
    auto genericType = DeclRefType::create(astBuilder, convert(typeParam));

    auto substType = substituteType(SubstitutionSet(slangGeneric), astBuilder, genericType);

    if (genericType != substType)
    {
        return convert(substType);
    }

    return nullptr;
}

SLANG_API int64_t spReflectionGeneric_GetConcreteIntVal(SlangReflectionGeneric* generic, SlangReflectionVariable* valueParam)
{
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return 0;
    auto astBuilder = getModule(slangGeneric.getDecl())->getLinkage()->getASTBuilder();

    auto valueParamDeclRef = convert(valueParam);

    Val* valResult = astBuilder->getOrCreate<GenericParamIntVal>(
                    valueParamDeclRef.substitute(astBuilder, as<GenericValueParamDecl>(valueParamDeclRef.getDecl())->getType()),
                    valueParamDeclRef);
    valResult = valResult->substitute(astBuilder, SubstitutionSet(slangGeneric));

    auto intVal = as<ConstantIntVal>(valResult);
    if (intVal)
    {
        return intVal->getValue();
    }

    return 0;
}

SLANG_API SlangReflectionGeneric* spReflectionGeneric_applySpecializations(SlangReflectionGeneric* currGeneric, SlangReflectionGeneric* generic)
{
    auto declRef = convertGenericToDeclRef(currGeneric);
    auto genericDeclRef = convertGenericToDeclRef(generic);
    if (!declRef || !genericDeclRef)
        return nullptr;

    auto astBuilder = getModule(declRef.getDecl())->getLinkage()->getASTBuilder();

    auto substDeclRef = substituteDeclRef(SubstitutionSet(genericDeclRef), astBuilder, declRef);
    return convertDeclToGeneric(substDeclRef);
}


// Shader Parameter Reflection

SLANG_API unsigned spReflectionParameter_GetBindingIndex(SlangReflectionParameter* inVarLayout)
{
    SlangReflectionVariableLayout* varLayout = (SlangReflectionVariableLayout*)inVarLayout;
    return (unsigned) spReflectionVariableLayout_GetOffset(
        varLayout,
        spReflectionTypeLayout_GetParameterCategory(
            spReflectionVariableLayout_GetTypeLayout(varLayout)));
}

SLANG_API unsigned spReflectionParameter_GetBindingSpace(SlangReflectionParameter* inVarLayout)
{
    SlangReflectionVariableLayout* varLayout = (SlangReflectionVariableLayout*)inVarLayout;
    return (unsigned) spReflectionVariableLayout_GetSpace(
        varLayout,
        spReflectionTypeLayout_GetParameterCategory(
            spReflectionVariableLayout_GetTypeLayout(varLayout)));
}

SLANG_API SlangResult spIsParameterLocationUsed(
    SlangCompileRequest* request,
    SlangInt entryPointIndex,
    SlangInt targetIndex,
    SlangParameterCategory category,
    SlangUInt spaceIndex,
    SlangUInt registerIndex,
    bool& outUsed)
{    
    if (!request)
        return SLANG_E_INVALID_ARG;
        
    return request->isParameterLocationUsed(entryPointIndex, targetIndex, category, spaceIndex, registerIndex, outUsed);
}


// Entry Point Reflection

SLANG_API char const* spReflectionEntryPoint_getName(
    SlangReflectionEntryPoint* inEntryPoint)
{
    auto entryPointLayout = convert(inEntryPoint);
    return entryPointLayout ? getCstr(entryPointLayout->name) : nullptr;
}

SLANG_API char const* spReflectionEntryPoint_getNameOverride(SlangReflectionEntryPoint* inEntryPoint)
{
    auto entryPointLayout = convert(inEntryPoint);
    if (entryPointLayout)
    {
        if (entryPointLayout->nameOverride.getLength())
            return entryPointLayout->nameOverride.getBuffer();
        else
            return getCstr(entryPointLayout->name);
    }
    return nullptr;
}

SLANG_API SlangReflectionFunction* spReflectionEntryPoint_getFunction(SlangReflectionEntryPoint* inEntryPoint)
{
    auto entryPointLayout = convert(inEntryPoint);
    if (entryPointLayout)
    {
        return convert(entryPointLayout->entryPoint.as<FunctionDeclBase>());
    }
    return nullptr;
}

SLANG_API unsigned spReflectionEntryPoint_getParameterCount(
    SlangReflectionEntryPoint* inEntryPoint)
{
    auto entryPointLayout = convert(inEntryPoint);
    if(!entryPointLayout) return 0;

    return getParameterCount(entryPointLayout->parametersLayout->typeLayout);
}

SLANG_API SlangReflectionVariableLayout* spReflectionEntryPoint_getParameterByIndex(
    SlangReflectionEntryPoint*  inEntryPoint,
    unsigned                    index)
{
    auto entryPointLayout = convert(inEntryPoint);
    if(!entryPointLayout) return 0;

    return convert(getParameterByIndex(entryPointLayout->parametersLayout->typeLayout, index));
}

SLANG_API SlangStage spReflectionEntryPoint_getStage(SlangReflectionEntryPoint* inEntryPoint)
{
    auto entryPointLayout = convert(inEntryPoint);

    if(!entryPointLayout) return SLANG_STAGE_NONE;

    return SlangStage(entryPointLayout->profile.getStage());
}

SLANG_API void spReflectionEntryPoint_getComputeThreadGroupSize(
    SlangReflectionEntryPoint*  inEntryPoint,
    SlangUInt                   axisCount,
    SlangUInt*                  outSizeAlongAxis)
{
    auto entryPointLayout = convert(inEntryPoint);

    if(!entryPointLayout)   return;
    if(!axisCount)          return;
    if(!outSizeAlongAxis)   return;

    auto entryPointFunc = entryPointLayout->entryPoint;
    if(!entryPointFunc) return;

    SlangUInt sizeAlongAxis[3] = { 1, 1, 1 };

    // First look for the HLSL case, where we have an attribute attached to the entry point function
    auto numThreadsAttribute = entryPointFunc.getDecl()->findModifier<NumThreadsAttribute>();
    if (numThreadsAttribute)
    {
        if (auto cint = entryPointLayout->program->tryFoldIntVal(numThreadsAttribute->x))
            sizeAlongAxis[0] = (SlangUInt)cint->getValue();
        else if (numThreadsAttribute->x)
            sizeAlongAxis[0] = 0;
        if (auto cint = entryPointLayout->program->tryFoldIntVal(numThreadsAttribute->y))
            sizeAlongAxis[1] = (SlangUInt)cint->getValue();
        else if (numThreadsAttribute->y)
            sizeAlongAxis[1] = 0;
        if (auto cint = entryPointLayout->program->tryFoldIntVal(numThreadsAttribute->z))
            sizeAlongAxis[2] = (SlangUInt)cint->getValue();
        else if (numThreadsAttribute->z)
            sizeAlongAxis[2] = 0;
    }

    //

    if(axisCount > 0) outSizeAlongAxis[0] = sizeAlongAxis[0];
    if(axisCount > 1) outSizeAlongAxis[1] = sizeAlongAxis[1];
    if(axisCount > 2) outSizeAlongAxis[2] = sizeAlongAxis[2];
    for( SlangUInt aa = 3; aa < axisCount; ++aa )
    {
        outSizeAlongAxis[aa] = 1;
    }
}

SLANG_API void spReflectionEntryPoint_getComputeWaveSize(
    SlangReflectionEntryPoint* inEntryPoint,
    SlangUInt* outWaveSize)
{
    auto entryPointLayout = convert(inEntryPoint);

    if (!entryPointLayout)   return;
    if (!outWaveSize)   return;

    auto entryPointFunc = entryPointLayout->entryPoint;
    if (!entryPointFunc) return;

    // First look for the HLSL case, where we have an attribute attached to the entry point function
    if (auto waveSizeAttribute = entryPointFunc.getDecl()->findModifier<WaveSizeAttribute>())
    {
        if (auto cint = entryPointLayout->program->tryFoldIntVal(waveSizeAttribute->numLanes))
            *outWaveSize = (SlangUInt)cint->getValue();
        else if (waveSizeAttribute->numLanes)
            *outWaveSize = 0;
    }
}

SLANG_API int spReflectionEntryPoint_usesAnySampleRateInput(
    SlangReflectionEntryPoint* inEntryPoint)
{
    auto entryPointLayout = convert(inEntryPoint);
    if(!entryPointLayout)
        return 0;

    if (entryPointLayout->profile.getStage() != Stage::Fragment)
        return 0;

    return (entryPointLayout->flags & EntryPointLayout::Flag::usesAnySampleRateInput) != 0;
}

SLANG_API SlangReflectionVariableLayout* spReflectionEntryPoint_getVarLayout(
    SlangReflectionEntryPoint* inEntryPoint)
{
    auto entryPointLayout = convert(inEntryPoint);
    if(!entryPointLayout)
        return nullptr;

    return convert(entryPointLayout->parametersLayout);
}

SLANG_API SlangReflectionVariableLayout* spReflectionEntryPoint_getResultVarLayout(
    SlangReflectionEntryPoint* inEntryPoint)
{
    auto entryPointLayout = convert(inEntryPoint);
    if(!entryPointLayout)
        return nullptr;

    return convert(entryPointLayout->resultLayout);
}

SLANG_API int spReflectionEntryPoint_hasDefaultConstantBuffer(
    SlangReflectionEntryPoint* inEntryPoint)
{
    auto entryPointLayout = convert(inEntryPoint);
    if(!entryPointLayout)
        return 0;

    return hasDefaultConstantBuffer(entryPointLayout);
}


// SlangReflectionTypeParameter
SLANG_API char const* spReflectionTypeParameter_GetName(SlangReflectionTypeParameter * inTypeParam)
{
    auto specializationParam = convert(inTypeParam);
    if( auto genericParamLayout = as<GenericSpecializationParamLayout>(specializationParam) )
    {
        return genericParamLayout->decl->getName()->text.getBuffer();
    }
    // TODO: Add case for existential type parameter? They don't have as simple of a notion of "name" as the generic case...
    return nullptr;
}

SLANG_API unsigned spReflectionTypeParameter_GetIndex(SlangReflectionTypeParameter * inTypeParam)
{
    auto typeParam = convert(inTypeParam);
    return (unsigned)(typeParam->index);
}

SLANG_API unsigned int spReflectionTypeParameter_GetConstraintCount(SlangReflectionTypeParameter* inTypeParam)
{
    auto specializationParam = convert(inTypeParam);
    if(auto genericParamLayout = as<GenericSpecializationParamLayout>(specializationParam))
    {
        if( auto globalGenericParamDecl = as<GlobalGenericParamDecl>(genericParamLayout->decl) )
        {
            auto constraints = globalGenericParamDecl->getMembersOfType<GenericTypeConstraintDecl>();
            return (unsigned int)constraints.getCount();
        }
        // TODO: Add case for entry-point generic parameters.
    }
    // TODO: Add case for existential type parameters.
    return 0;
}

SLANG_API SlangReflectionType* spReflectionTypeParameter_GetConstraintByIndex(SlangReflectionTypeParameter * inTypeParam, unsigned index)
{
    auto specializationParam = convert(inTypeParam);
    if(auto genericParamLayout = as<GenericSpecializationParamLayout>(specializationParam))
    {
        if( auto globalGenericParamDecl = as<GlobalGenericParamDecl>(genericParamLayout->decl) )
        {
            auto constraints = globalGenericParamDecl->getMembersOfType<GenericTypeConstraintDecl>();
            return (SlangReflectionType*)constraints[index]->sup.Ptr();
        }
        // TODO: Add case for entry-point generic parameters.
    }
    // TODO: Add case for existential type parameters.
    return 0;
}

// Shader Reflection

SLANG_API unsigned spReflection_GetParameterCount(SlangReflection* inProgram)
{
    auto program = convert(inProgram);
    if(!program) return 0;

    auto globalStructLayout = getGlobalStructLayout(program);
    if (!globalStructLayout)
        return 0;

    return (unsigned) globalStructLayout->fields.getCount();
}

SLANG_API SlangReflectionParameter* spReflection_GetParameterByIndex(SlangReflection* inProgram, unsigned index)
{
    auto program = convert(inProgram);
    if(!program) return nullptr;

    auto globalStructLayout = getGlobalStructLayout(program);
    if (!globalStructLayout)
        return 0;

    return convert(globalStructLayout->fields[index].Ptr());
}

SLANG_API SlangReflectionVariableLayout* spReflection_getGlobalParamsVarLayout(SlangReflection* inProgram)
{
    auto program = convert(inProgram);
    if(!program) return nullptr;

    return convert(program->parametersLayout);
}

SLANG_API unsigned int spReflection_GetTypeParameterCount(SlangReflection * reflection)
{
    auto program = convert(reflection);
    return (unsigned int) program->specializationParams.getCount();
}

SLANG_API slang::ISession* spReflection_GetSession(SlangReflection* reflection)
{
    auto program = convert(reflection);
    return program->getTargetProgram()->getTargetReq()->getLinkage();
}

SLANG_API SlangReflectionTypeParameter* spReflection_GetTypeParameterByIndex(SlangReflection * reflection, unsigned int index)
{
    auto program = convert(reflection);
    return (SlangReflectionTypeParameter*) program->specializationParams[index].Ptr();
}

SLANG_API SlangReflectionTypeParameter * spReflection_FindTypeParameter(SlangReflection * inProgram, char const * name)
{
    auto program = convert(inProgram);
    if (!program) return nullptr;
    for( auto& param : program->specializationParams )
    {
        auto genericParamLayout = as<GenericSpecializationParamLayout>(param);
        if(!genericParamLayout)
            continue;

        if(getText(genericParamLayout->decl->getName()) != UnownedTerminatedStringSlice(name))
            continue;

        return (SlangReflectionTypeParameter*) genericParamLayout;
    }

    return 0;
}

SLANG_API SlangUInt spReflection_getEntryPointCount(SlangReflection* inProgram)
{
    auto program = convert(inProgram);
    if(!program) return 0;

    return SlangUInt(program->entryPoints.getCount());
}

SLANG_API SlangReflectionEntryPoint* spReflection_getEntryPointByIndex(SlangReflection* inProgram, SlangUInt index)
{
    auto program = convert(inProgram);
    if(!program) return 0;

    return convert(program->entryPoints[(int) index].Ptr());
}

SLANG_API SlangReflectionEntryPoint* spReflection_findEntryPointByName(SlangReflection* inProgram, char const* name)
{
    auto program = convert(inProgram);
    if(!program) return 0;

    // TODO: improve on naive linear search
    for(auto ep : program->entryPoints)
    {
        if(ep->entryPoint.getName()->text == name)
        {
            return convert(ep);
        }
    }

    return nullptr;
}

SLANG_API SlangUInt spReflection_getGlobalConstantBufferBinding(SlangReflection* inProgram)
{
    auto program = convert(inProgram);
    if (!program) return 0;
    auto cb = program->parametersLayout->FindResourceInfo(LayoutResourceKind::ConstantBuffer);
    if (!cb) return 0;
    return cb->index;
}

SLANG_API size_t spReflection_getGlobalConstantBufferSize(SlangReflection* inProgram)
{
    auto program = convert(inProgram);
    if (!program) return 0;
    auto structLayout = getGlobalStructLayout(program);
    auto uniform = structLayout->FindResourceInfo(LayoutResourceKind::Uniform);
    if (!uniform) return 0;
    return getReflectionSize(uniform->count);
}

SLANG_API  SlangReflectionType* spReflection_specializeType(
    SlangReflection*            inProgramLayout,
    SlangReflectionType*        inType,
    SlangInt                    specializationArgCount,
    SlangReflectionType* const* specializationArgs,
    ISlangBlob**                outDiagnostics)
{
    auto programLayout = convert(inProgramLayout);
    if(!programLayout) return nullptr;

    auto unspecializedType = convert(inType);
    if(!unspecializedType) return nullptr;

    auto linkage = programLayout->getProgram()->getLinkage();

    DiagnosticSink sink(linkage->getSourceManager(), Lexer::sourceLocationLexer);

    auto specializedType = linkage->specializeType(unspecializedType, specializationArgCount, (Type* const*) specializationArgs, &sink);

    sink.getBlobIfNeeded(outDiagnostics);

    return convert(specializedType);
}


SLANG_API SlangReflectionGeneric* spReflection_specializeGeneric(
                SlangReflection*                        inProgramLayout,
                SlangReflectionGeneric*                 generic,
                SlangInt                                argCount,
                SlangReflectionGenericArgType const*    argTypes,
                SlangReflectionGenericArg const*        args,
                ISlangBlob**                            outDiagnostics)
{
    auto programLayout = convert(inProgramLayout);
    auto slangGeneric = convertGenericToDeclRef(generic);
    if (!slangGeneric) return nullptr;
    auto astBuilder = getModule(slangGeneric.getDecl())->getLinkage()->getASTBuilder();

    auto linkage = programLayout->getProgram()->getLinkage();

    DiagnosticSink sink(linkage->getSourceManager(), Lexer::sourceLocationLexer);

    List<Expr*> argExprs;
    for (SlangInt i = 0; i < argCount; ++i)
    {
        auto argType = argTypes[i];
        auto arg = args[i];

        switch (argType)
        {
            case SLANG_GENERIC_ARG_TYPE:
            {
                auto type = convert(arg.typeVal);
                auto declRefType = as<DeclRefType>(type);
                auto declRefExpr = astBuilder->create<DeclRefExpr>();
                declRefExpr->declRef = declRefType->getDeclRef();
                declRefExpr->type.type = astBuilder->getOrCreate<TypeType>(type);
                argExprs.add(declRefExpr);
                break;
            }
            case SLANG_GENERIC_ARG_INT:
            {
                auto literalExpr = astBuilder->create<IntegerLiteralExpr>();
                literalExpr->value = args[i].intVal;
                literalExpr->type = astBuilder->getIntType();
                argExprs.add(literalExpr);
                break;
            }
            case SLANG_GENERIC_ARG_BOOL:
            {
                auto literalExpr = astBuilder->create<BoolLiteralExpr>();
                literalExpr->value = args[i].boolVal;
                literalExpr->type = astBuilder->getBoolType();
                argExprs.add(literalExpr);
                break;
            }
            default:
                // abort (TODO: throw a proper error)
                return nullptr;
        }
    }

    auto specialized = linkage->specializeGeneric(slangGeneric, argExprs, &sink);
    sink.getBlobIfNeeded(outDiagnostics);

    return convertDeclToGeneric(specialized);
}


SLANG_API SlangUInt spReflection_getHashedStringCount(
    SlangReflection*  reflection)
{
    auto programLayout = convert(reflection);
    auto slices = programLayout->hashedStringLiteralPool.getAdded();
    return slices.getCount();
}

SLANG_API const char* spReflection_getHashedString(
    SlangReflection*  reflection,
    SlangUInt index,
    size_t* outCount)
{
    auto programLayout = convert(reflection);

    auto slices = programLayout->hashedStringLiteralPool.getAdded();
    auto slice = slices[Index(index)];

    *outCount = slice.getLength();
    return slice.begin();
}

SLANG_API SlangUInt32 spComputeStringHash(const char* chars, size_t count)
{
    return SlangUInt32(getStableHashCode32(chars, count));
}

SLANG_API SlangReflectionTypeLayout* spReflection_getGlobalParamsTypeLayout(
    SlangReflection* reflection)
{
    auto programLayout = convert(reflection);
    if(!programLayout) return nullptr;

    return convert(programLayout->parametersLayout->typeLayout);
}