1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
|
// slang-test-main.cpp
#include "../../source/compiler-core/slang-artifact-desc-util.h"
#include "../../source/compiler-core/slang-artifact-helper.h"
#include "../../source/core/slang-byte-encode-util.h"
#include "../../source/core/slang-castable.h"
#include "../../source/core/slang-char-util.h"
#include "../../source/core/slang-hex-dump-util.h"
#include "../../source/core/slang-io.h"
#include "../../source/core/slang-memory-arena.h"
#include "../../source/core/slang-process-util.h"
#include "../../source/core/slang-render-api-util.h"
#include "../../source/core/slang-shared-library.h"
#include "../../source/core/slang-std-writers.h"
#include "../../source/core/slang-string-escape-util.h"
#include "../../source/core/slang-string-util.h"
#include "../../source/core/slang-token-reader.h"
#include "../../source/core/slang-type-text-util.h"
#include "slang-com-helper.h"
#include "unit-test/slang-unit-test.h"
#undef SLANG_UNIT_TEST
#include "../../source/compiler-core/slang-artifact-associated-impl.h"
#include "../../source/compiler-core/slang-downstream-compiler.h"
#include "../../source/compiler-core/slang-language-server-protocol.h"
#include "../../source/compiler-core/slang-nvrtc-compiler.h"
#include "../render-test/slang-support.h"
#include "directory-util.h"
#include "options.h"
#include "parse-diagnostic-util.h"
#include "slangc-tool.h"
#include "slangi-tool.h"
#include "test-context.h"
#include "test-reporter.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <math.h>
#include <random>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#define SLANG_PRELUDE_NAMESPACE CPPPrelude
#include "../../prelude/slang-cpp-types.h"
#include <atomic>
#include <thread>
#if defined(_WIN32)
#include <slang-rhi/agility-sdk.h>
SLANG_RHI_EXPORT_AGILITY_SDK
#endif
using namespace Slang;
// Constants for slang-test specific options
static const char* kPreserveEmbeddedSourceOption = "-preserve-embedded-source";
// Options for a particular test
struct TestOptions
{
enum Type
{
Normal, ///< A regular test
Diagnostic, ///< Diagnostic tests will always run (as form of failure is being tested)
};
void addCategory(TestCategory* category)
{
if (categories.indexOf(category) < 0)
{
categories.add(category);
}
}
void addCategories(TestCategory* const* inCategories, Index count)
{
for (Index i = 0; i < count; ++i)
{
addCategory(inCategories[i]);
}
}
// Small helper to help consistently interrogating for filecheck usage
bool getFileCheckPrefix(String& prefix) const
{
return commandOptions.tryGetValue("filecheck", prefix);
}
bool getFileCheckBufferPrefix(String& prefix) const
{
return commandOptions.tryGetValue("filecheck-buffer", prefix);
}
Type type = Type::Normal;
String command;
List<String> args;
Dictionary<String, String> commandOptions;
// The categories that this test was assigned to
List<TestCategory*> categories;
bool isEnabled = true;
bool isSynthesized = false;
};
struct FileTestInfoImpl : public FileTestInfo
{
String testName;
String filePath;
String outputStem;
TestOptions options;
};
struct TestDetails
{
TestDetails() {}
explicit TestDetails(const TestOptions& inOptions)
: options(inOptions)
{
}
TestOptions options; ///< The options for the test
TestRequirements requirements; ///< The requirements for the test to work
};
// Information on tests to run for a particular file
struct FileTestList
{
List<TestDetails> tests;
};
struct TestInput
{
// Path to the input file for the test
String filePath;
// Prefix for the path that test output should write to
// (usually the same as `filePath`, but will differ when
// we run multiple tests out of the same file)
String outputStem;
// Arguments for the test (usually to be interpreted
// as command line args)
TestOptions const* testOptions;
// Determines how the test will be spawned
SpawnType spawnType;
};
typedef TestResult (*TestCallback)(TestContext* context, TestInput& input);
// Globals
// Pre declare
static void _addRenderTestOptions(const Options& options, CommandLine& ioCmdLine);
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!! Functions !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
// Tries to read in order
// - The file specific to this test: input.outputStem + suffix
// - The general file for a set of tests: input.fileName + suffix;
static SlangResult _readTestFile(const TestInput& input, const String& suffix, String& out)
{
StringBuilder buf;
buf << input.outputStem << suffix;
if (auto r = Slang::File::readAllText(buf, out); SLANG_SUCCEEDED(r))
{
return r;
}
buf.clear();
buf << input.filePath << suffix;
return Slang::File::readAllText(buf, out);
}
bool match(char const** ioCursor, char const* expected)
{
char const* cursor = *ioCursor;
while (*expected && *cursor == *expected)
{
cursor++;
expected++;
}
if (*expected != 0)
return false;
*ioCursor = cursor;
return true;
}
void skipHorizontalSpace(char const** ioCursor)
{
char const* cursor = *ioCursor;
for (;;)
{
switch (*cursor)
{
case ' ':
case '\t':
cursor++;
continue;
default:
break;
}
break;
}
*ioCursor = cursor;
}
void skipToEndOfLine(char const** ioCursor)
{
char const* cursor = *ioCursor;
for (;;)
{
int c = *cursor;
switch (c)
{
default:
cursor++;
continue;
case '\r':
case '\n':
{
cursor++;
int d = *cursor;
if ((c ^ d) == ('\r' ^ '\n'))
{
cursor++;
}
}
[[fallthrough]];
case 0:
*ioCursor = cursor;
return;
}
}
}
String getString(char const* textBegin, char const* textEnd)
{
StringBuilder sb;
sb.append(textBegin, textEnd - textBegin);
return sb.produceString();
}
String collectRestOfLine(char const** ioCursor)
{
char const* cursor = *ioCursor;
char const* textBegin = cursor;
skipToEndOfLine(&cursor);
char const* textEnd = cursor;
*ioCursor = cursor;
return getString(textBegin, textEnd);
}
static bool _isEndOfLineOrParens(char c)
{
switch (c)
{
case '\n':
case '\r':
case 0:
case ')':
{
return true;
}
default:
return false;
}
}
static SlangResult _parseCategories(
TestCategorySet* categorySet,
char const** ioCursor,
TestOptions& out)
{
char const* cursor = *ioCursor;
// If don't have ( we don't have category list
if (*cursor == '(')
{
cursor++;
const char* const start = cursor;
// Find the end
for (; !_isEndOfLineOrParens(*cursor); ++cursor)
;
if (*cursor != ')')
{
*ioCursor = cursor;
return SLANG_FAIL;
}
cursor++;
List<UnownedStringSlice> slices;
StringUtil::split(UnownedStringSlice(start, cursor - 1), ',', slices);
for (auto& slice : slices)
{
// Trim any whitespace
auto categoryName = slice.trim();
TestCategory* category = categorySet->find(categoryName);
if (!category)
{
// Mark this test as disabled, as we don't have all of the categories
out.isEnabled = false;
break;
}
out.addCategory(category);
}
}
*ioCursor = cursor;
return SLANG_OK;
}
static SlangResult _parseCommandArguments(char const** ioCursor, TestOptions& out)
{
char const* cursor = *ioCursor;
// If don't have ( we don't have any additional options
if (*cursor == '(')
{
cursor++;
const char* const start = cursor;
// Find the end
for (; !_isEndOfLineOrParens(*cursor); ++cursor)
;
if (*cursor != ')')
{
*ioCursor = cursor;
return SLANG_FAIL;
}
cursor++;
List<UnownedStringSlice> options;
StringUtil::split(UnownedStringSlice(start, cursor - 1), ',', options);
for (auto& option : options)
{
auto i = option.indexOf('=');
if (i == -1)
{
out.commandOptions.add(option.trim(), "");
}
else
{
out.commandOptions.add(option.head(i).trim(), option.tail(i + 1).trim());
}
}
}
*ioCursor = cursor;
return SLANG_OK;
}
static SlangResult _parseArg(const char** ioCursor, UnownedStringSlice& outArg)
{
const char* cursor = *ioCursor;
const char* const argBegin = cursor;
// Let's try to read one option
for (;;)
{
switch (*cursor)
{
default:
{
++cursor;
break;
}
case '"':
{
// If we have quotes let's just parse them as is and make output
auto escapeHandler = StringEscapeUtil::getHandler(StringEscapeUtil::Style::Space);
SLANG_RETURN_ON_FAIL(escapeHandler->lexQuoted(cursor, &cursor));
break;
}
case 0:
case '\r':
case '\n':
case ' ':
case '\t':
{
char const* argEnd = cursor;
assert(argBegin != argEnd);
outArg = UnownedStringSlice(argBegin, argEnd);
*ioCursor = cursor;
return SLANG_OK;
}
}
}
}
static SlangResult _gatherTestOptions(
TestCategorySet* categorySet,
char const** ioCursor,
TestOptions& outOptions)
{
SLANG_RETURN_ON_FAIL(_parseCategories(categorySet, ioCursor, outOptions));
char const* cursor = *ioCursor;
if (*cursor != ':')
{
return SLANG_FAIL;
}
cursor++;
// Next scan for a sub-command name
char const* commandStart = cursor;
for (;;)
{
switch (*cursor)
{
default:
cursor++;
continue;
case '(':
case ':':
break;
case 0:
case '\r':
case '\n':
return SLANG_FAIL;
}
break;
}
char const* commandEnd = cursor;
outOptions.command = getString(commandStart, commandEnd);
// Allow parameterizing the test command separately from the arguments, this
// is because the arguments are often passed to the compiler verbatim, and
// it's messy to have the test runner rifling through and picking things
// out
// Format is: (foo=bar, baz = 2)
SLANG_RETURN_ON_FAIL(_parseCommandArguments(&cursor, outOptions));
if (*cursor == ':')
cursor++;
else
{
return SLANG_FAIL;
}
// Now scan for arguments. For now we just assume that
// any whitespace separation indicates a new argument
for (;;)
{
skipHorizontalSpace(&cursor);
// End of line? then no more options.
switch (*cursor)
{
case 0:
case '\r':
case '\n':
skipToEndOfLine(&cursor);
*ioCursor = cursor;
return SLANG_OK;
default:
break;
}
// Let's try to read one option
UnownedStringSlice arg;
SLANG_RETURN_ON_FAIL(_parseArg(&cursor, arg));
outOptions.args.add(arg);
}
}
static RenderApiFlags _getRequiredRenderApisByCommand(const UnownedStringSlice& name);
static void _combineOptions(
TestCategorySet* categorySet,
const TestOptions& fileOptions,
TestOptions& ioOptions)
{
// And the file categories
ioOptions.addCategories(fileOptions.categories.getBuffer(), fileOptions.categories.getCount());
// If no categories were specified, then add the default category
if (ioOptions.categories.getCount() == 0)
{
ioOptions.categories.add(categorySet->defaultCategory);
}
}
static SlangResult _extractCommand(const char** ioCursor, UnownedStringSlice& outCommand)
{
const char* cursor = *ioCursor;
const char* const start = cursor;
while (true)
{
const char c = *cursor;
if (CharUtil::isAlpha(c) || c == '_')
{
cursor++;
continue;
}
if (c == ':' || c == '(' || c == 0 || c == '\n' || c == '\r')
{
*ioCursor = cursor;
outCommand = UnownedStringSlice(start, cursor);
return SLANG_OK;
}
return SLANG_FAIL;
}
}
static void applyMacroSubstitution(String filePath, TestDetails& details)
{
for (auto& arg : details.options.args)
{
arg = StringUtil::replaceAll(
arg.getUnownedSlice(),
toSlice("$dirname"),
Path::getParentDirectory(filePath).getUnownedSlice());
}
}
// Try to read command-line options from the test file itself
static SlangResult _gatherTestsForFile(
TestCategorySet* categorySet,
String filePath,
FileTestList* outTestList,
TestContext* context = nullptr)
{
outTestList->tests.clear();
String fileContents;
SlangResult readResult = Slang::File::readAllText(filePath, fileContents);
if (SLANG_FAILED(readResult))
{
// Log file reading failure with details (thread-safe)
if (context && context->getTestReporter())
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"Failed to read test file '%s' (error: 0x%08X)",
filePath.getBuffer(),
(unsigned int)readResult);
}
else
{
// Fallback to stderr if no context available
fprintf(
stderr,
"Failed to read test file '%s' (error: 0x%08X)\n",
filePath.getBuffer(),
(unsigned int)readResult);
}
return readResult;
}
// Walk through the lines of the file, looking for test commands
char const* cursor = fileContents.begin();
// Options that are specified across all tests in the file.
TestOptions fileOptions;
while (*cursor)
{
// We are at the start of a line of input.
skipHorizontalSpace(&cursor);
if (!match(&cursor, "//"))
{
skipToEndOfLine(&cursor);
continue;
}
// Skip any extra slashes and spaces to handle malformed directives like ///TEST or // TEST
while (*cursor == '/')
{
cursor++;
}
skipHorizontalSpace(&cursor);
UnownedStringSlice command;
if (SLANG_FAILED(_extractCommand(&cursor, command)))
{
// Couldn't find a command so skip
skipToEndOfLine(&cursor);
continue;
}
// Look for a pattern that matches what we want
if (command == "TEST_IGNORE_FILE")
{
outTestList->tests.clear();
return SLANG_OK;
}
const UnownedStringSlice disablePrefix = UnownedStringSlice::fromLiteral("DISABLE_");
TestDetails testDetails;
{
if (command.startsWith(disablePrefix))
{
testDetails.options.isEnabled = false;
command = command.tail(disablePrefix.getLength());
}
}
if (command == "TEST_CATEGORY")
{
SlangResult res = _parseCategories(categorySet, &cursor, fileOptions);
// If it failed we are done, unless it was just 'not available'
if (SLANG_FAILED(res) && res != SLANG_E_NOT_AVAILABLE)
{
if (context && context->getTestReporter())
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"Failed to parse TEST_CATEGORY in file '%s' (error: 0x%08X)",
filePath.getBuffer(),
(unsigned int)res);
}
else
{
fprintf(
stderr,
"Failed to parse TEST_CATEGORY in file '%s' (error: 0x%08X)\n",
filePath.getBuffer(),
(unsigned int)res);
}
return res;
}
skipToEndOfLine(&cursor);
continue;
}
if (command == "TEST")
{
SlangResult testRes = _gatherTestOptions(categorySet, &cursor, testDetails.options);
if (SLANG_FAILED(testRes))
{
if (context && context->getTestReporter())
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"Failed to parse TEST directive in file '%s' (error: 0x%08X)",
filePath.getBuffer(),
(unsigned int)testRes);
}
else
{
fprintf(
stderr,
"Failed to parse TEST directive in file '%s' (error: 0x%08X)\n",
filePath.getBuffer(),
(unsigned int)testRes);
}
return testRes;
}
applyMacroSubstitution(filePath, testDetails);
// See if the type of test needs certain APIs available
const RenderApiFlags testRequiredApis =
_getRequiredRenderApisByCommand(testDetails.options.command.getUnownedSlice());
testDetails.requirements.addUsedRenderApis(testRequiredApis);
// Apply the file wide options
_combineOptions(categorySet, fileOptions, testDetails.options);
outTestList->tests.add(testDetails);
}
else if (command == "DIAGNOSTIC_TEST")
{
SlangResult diagRes = _gatherTestOptions(categorySet, &cursor, testDetails.options);
if (SLANG_FAILED(diagRes))
{
if (context && context->getTestReporter())
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"Failed to parse DIAGNOSTIC_TEST directive in file '%s' (error: 0x%08X)",
filePath.getBuffer(),
(unsigned int)diagRes);
}
else
{
fprintf(
stderr,
"Failed to parse DIAGNOSTIC_TEST directive in file '%s' (error: 0x%08X)\n",
filePath.getBuffer(),
(unsigned int)diagRes);
}
return diagRes;
}
applyMacroSubstitution(filePath, testDetails);
// Apply the file wide options
_combineOptions(categorySet, fileOptions, testDetails.options);
// Mark that it is a diagnostic test
testDetails.options.type = TestOptions::Type::Diagnostic;
outTestList->tests.add(testDetails);
}
else
{
// Hmm we don't know what kind of test this actually is.
// Assume that's ok and this *isn't* a test and ignore.
skipToEndOfLine(&cursor);
}
}
return SLANG_OK;
}
static void SLANG_STDCALL _fileCheckDiagnosticCallback(
void* data,
const TestMessageType messageType,
const char* message) noexcept
{
auto& testReporter = *reinterpret_cast<TestReporter*>(data);
testReporter.message(messageType, message);
}
struct bool2
{
bool x, y;
};
//
// Check some generated output with FileCheck
//
static TestResult _fileCheckTest(
TestContext& context,
const String& fileCheckRules,
const String& fileCheckPrefix,
const String& outputToCheck)
{
auto& testReporter = *context.getTestReporter();
IFileCheck* fc = context.getFileCheck();
if (!fc)
{
// Ignore if FileCheck is not available.
// We could report an error, but our ARM64 CI doesn't have FileCheck yet.
testReporter.message(TestMessageType::Info, "FileCheck is not available");
return TestResult::Ignored;
}
const bool coloredOutput = true;
testReporter.message(TestMessageType::Info, outputToCheck.getBuffer());
return fc->performTest(
"slang-test",
fileCheckRules.begin(),
fileCheckPrefix.begin(),
outputToCheck.begin(),
"actual-output",
_fileCheckDiagnosticCallback,
&testReporter,
coloredOutput);
}
template<typename Compare>
static TestResult _fileComparisonTest(
TestContext& context,
const TestInput& input,
const char* defaultExpectedContent,
const char* expectedFileSuffix,
const String& actualOutput,
Compare compare)
{
String expectedOutput;
if (SLANG_FAILED(_readTestFile(input, expectedFileSuffix, expectedOutput)))
{
if (defaultExpectedContent)
{
expectedOutput = defaultExpectedContent;
}
else
{
context.getTestReporter()->messageFormat(
TestMessageType::RunError,
"Unable to read %s output for '%s'\n",
expectedFileSuffix,
input.outputStem.getBuffer());
return TestResult::Fail;
}
}
// Otherwise we compare to the expected output
if (!compare(actualOutput, expectedOutput))
{
context.getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
return TestResult::Fail;
}
return TestResult::Pass;
}
static bool _areLinesEqual(const String& a, const String& e)
{
return StringUtil::areLinesEqual(a.getUnownedSlice(), e.getUnownedSlice());
}
// Either run FileCheck over the result, or read and compare with a .expected file
// On a comparison failure, dump the difference
// On any failure, write a .actual file.
template<typename Compare = decltype(_areLinesEqual)>
static TestResult _validateOutput(
TestContext* const context,
const TestInput& input,
const String& actualOutput,
const bool forceFailure = false,
const char* defaultExpectedContent = nullptr,
const Compare compare = _areLinesEqual)
{
String fileCheckPrefix;
const TestResult result =
input.testOptions->getFileCheckPrefix(fileCheckPrefix)
? _fileCheckTest(*context, input.filePath, fileCheckPrefix, actualOutput)
: _fileComparisonTest(
*context,
input,
defaultExpectedContent,
".expected",
actualOutput,
compare);
// If the test failed, then we write the actual output to a file
// so that we can easily diff it from the command line and
// diagnose the problem.
if (result == TestResult::Fail || forceFailure)
{
String actualOutputPath = input.outputStem + ".actual";
Slang::File::writeAllText(actualOutputPath, actualOutput);
return TestResult::Fail;
}
else
{
return result;
}
}
Result spawnAndWaitExe(
TestContext* context,
const String& testPath,
const CommandLine& cmdLine,
ExecuteResult& outRes)
{
std::lock_guard<std::mutex> lock(context->mutex);
const auto& options = context->options;
if (options.verbosity == VerbosityLevel::Verbose)
{
String commandLine = cmdLine.toString();
context->getTestReporter()->messageFormat(
TestMessageType::Info,
"%s\n",
commandLine.begin());
}
Result res = ProcessUtil::execute(cmdLine, outRes);
if (SLANG_FAILED(res))
{
// fprintf(stderr, "failed to run test '%S'\n", testPath.ToWString());
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"failed to run test '%S'",
testPath.toWString().begin());
}
return res;
}
Result spawnAndWaitSharedLibrary(
TestContext* context,
const String& testPath,
const CommandLine& cmdLine,
ExecuteResult& outRes)
{
std::lock_guard<std::mutex> lock(context->mutex);
const auto& options = context->options;
String exeName = Path::getFileNameWithoutExt(cmdLine.m_executableLocation.m_pathOrName);
if (options.verbosity == VerbosityLevel::Verbose)
{
CommandLine testCmdLine;
testCmdLine.setExecutableLocation(ExecutableLocation("slang-test"));
if (options.binDir.getLength())
{
testCmdLine.addArg("-bindir");
testCmdLine.addArg(options.binDir);
}
testCmdLine.addArg(exeName);
testCmdLine.m_args.addRange(cmdLine.m_args);
context->getTestReporter()->messageFormat(
TestMessageType::Info,
"%s\n",
testCmdLine.toString().getBuffer());
}
auto func = context->getInnerMainFunc(context->options.binDir, exeName);
if (func)
{
StringBuilder stdErrorString;
StringBuilder stdOutString;
renderer_test::CoreDebugCallback coreDebugCallback;
renderer_test::CoreToRHIDebugBridge rhiDebugBridge;
rhiDebugBridge.setCoreCallback(&coreDebugCallback);
// Say static so not released
StringWriter stdError(&stdErrorString, WriterFlag::IsConsole | WriterFlag::IsStatic);
StringWriter stdOut(&stdOutString, WriterFlag::IsConsole | WriterFlag::IsStatic);
StdWriters* prevStdWriters = StdWriters::getSingleton();
StdWriters stdWriters;
stdWriters.setWriter(SLANG_WRITER_CHANNEL_STD_ERROR, &stdError);
stdWriters.setWriter(SLANG_WRITER_CHANNEL_STD_OUTPUT, &stdOut);
stdWriters.setDebugCallback(&coreDebugCallback);
if (exeName == "slangc" || exeName == "slangi")
{
stdWriters.setWriter(SLANG_WRITER_CHANNEL_DIAGNOSTIC, &stdError);
}
String exePath = Path::combine(context->exeDirectoryPath, exeName);
List<const char*> args;
args.add(exePath.getBuffer());
for (const auto& cmdArg : cmdLine.m_args)
{
args.add(cmdArg.getBuffer());
}
SlangResult res =
func(&stdWriters, context->getSession(), int(args.getCount()), args.begin());
StdWriters::setSingleton(prevStdWriters);
outRes.standardError = stdErrorString;
outRes.standardOutput = stdOutString;
outRes.debugLayer = coreDebugCallback.getString();
outRes.resultCode = (int)TestToolUtil::getReturnCode(res);
return SLANG_OK;
}
return SLANG_FAIL;
}
Result spawnAndWaitProxy(
TestContext* context,
const String& testPath,
const CommandLine& inCmdLine,
ExecuteResult& outRes)
{
std::lock_guard<std::mutex> lock(context->mutex);
// Get the name of the thing to execute
String exeName = Path::getFileNameWithoutExt(inCmdLine.m_executableLocation.m_pathOrName);
if (exeName == "slangc" || exeName == "slangi")
{
// If the test is slangc there is a command line version we can just directly use
// return spawnAndWaitExe(context, testPath, inCmdLine, outRes);
return spawnAndWaitSharedLibrary(context, testPath, inCmdLine, outRes);
}
CommandLine cmdLine(inCmdLine);
// Make the first arg the name of the tool to invoke
cmdLine.m_args.insert(0, exeName);
cmdLine.setExecutableLocation(ExecutableLocation(context->exeDirectoryPath, "test-proxy"));
const auto& options = context->options;
if (options.verbosity == VerbosityLevel::Verbose)
{
String commandLine = cmdLine.toString();
context->getTestReporter()->messageFormat(
TestMessageType::Info,
"%s\n",
commandLine.begin());
}
// Execute
Result res = ProcessUtil::execute(cmdLine, outRes);
if (SLANG_FAILED(res))
{
// fprintf(stderr, "failed to run test '%S'\n", testPath.ToWString());
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"failed to run test '%S'",
testPath.toWString().begin());
}
return res;
}
static Result _executeRPC(
TestContext* context,
SpawnType spawnType,
const UnownedStringSlice& method,
const RttiInfo* rttiInfo,
const void* args,
ExecuteResult& outRes)
{
// If we are 'fully isolated', we cannot share a test server.
// So tear down the RPC connection if there is one currently.
if (spawnType == SpawnType::UseFullyIsolatedTestServer)
{
context->destroyRPCConnection();
}
JSONRPCConnection* rpcConnection = context->getOrCreateJSONRPCConnection();
if (!rpcConnection)
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"JSON RPC failure: getOrCreateJSONRPCConnection()");
return SLANG_FAIL;
}
// Execute
if (SLANG_FAILED(rpcConnection->sendCall(method, rttiInfo, args)))
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"JSON RPC failure: sendCall()");
context->destroyRPCConnection();
return SLANG_FAIL;
}
// Wait for the result
if (SLANG_FAILED(rpcConnection->waitForResult(context->connectionTimeOutInMs)))
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"JSON RPC failure: waitForResult()");
}
if (!rpcConnection->hasMessage())
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"JSON RPC failure: hasMessage()");
// We can assume somethings gone wrong. So lets kill the connection and fail.
context->destroyRPCConnection();
return SLANG_FAIL;
}
if (rpcConnection->getMessageType() != JSONRPCMessageType::Result)
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"JSON RPC failure: getMessageType() != JSONRPCMessageType::Result");
context->destroyRPCConnection();
return SLANG_FAIL;
}
// Get the result
TestServerProtocol::ExecutionResult exeRes;
if (SLANG_FAILED(rpcConnection->getMessage(&exeRes)))
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"JSON RPC failure: getMessage()");
context->destroyRPCConnection();
return SLANG_FAIL;
}
outRes.resultCode = exeRes.returnCode;
outRes.standardError = exeRes.stdError;
outRes.standardOutput = exeRes.stdOut;
outRes.debugLayer = exeRes.debugLayer;
return SLANG_OK;
}
template<typename T>
static Result _executeRPC(
TestContext* context,
SpawnType spawnType,
const UnownedStringSlice& method,
const T* msg,
ExecuteResult& outRes)
{
return _executeRPC(context, spawnType, method, GetRttiInfo<T>::get(), (const void*)msg, outRes);
}
Result spawnAndWaitTestServer(
TestContext* context,
SpawnType spawnType,
const String& testPath,
const CommandLine& inCmdLine,
ExecuteResult& outRes)
{
String exeName = Path::getFileNameWithoutExt(inCmdLine.m_executableLocation.m_pathOrName);
// This is a test tool execution
TestServerProtocol::ExecuteToolTestArgs args;
args.toolName = exeName;
args.args = inCmdLine.m_args;
return _executeRPC(
context,
spawnType,
TestServerProtocol::ExecuteToolTestArgs::g_methodName,
&args,
outRes);
}
static SlangResult _extractArg(const CommandLine& cmdLine, const String& argName, String& outValue)
{
SLANG_ASSERT(argName.getLength() > 0 && argName[0] == '-');
Index index = cmdLine.findArgIndex(argName.getUnownedSlice());
if (index >= 0 && index < cmdLine.getArgCount() - 1)
{
outValue = cmdLine.m_args[index + 1];
return SLANG_OK;
}
return SLANG_FAIL;
}
static bool _hasOption(const List<String>& args, const String& argName)
{
return args.indexOf(argName) != Index(-1);
}
static PassThroughFlags _getPassThroughFlagsForTarget(SlangCompileTarget target)
{
switch (target)
{
case SLANG_TARGET_UNKNOWN:
case SLANG_HLSL:
case SLANG_GLSL:
case SLANG_C_SOURCE:
case SLANG_CPP_SOURCE:
case SLANG_CPP_PYTORCH_BINDING:
case SLANG_HOST_CPP_SOURCE:
case SLANG_CUDA_SOURCE:
case SLANG_METAL:
case SLANG_WGSL:
case SLANG_HOST_VM:
{
return 0;
}
case SLANG_WGSL_SPIRV:
case SLANG_WGSL_SPIRV_ASM:
{
return PassThroughFlag::Tint;
}
case SLANG_DXBC:
case SLANG_DXBC_ASM:
{
return PassThroughFlag::Fxc;
}
case SLANG_SPIRV:
case SLANG_SPIRV_ASM:
{
return PassThroughFlag::Glslang;
}
case SLANG_DXIL:
case SLANG_DXIL_ASM:
{
return PassThroughFlag::Dxc;
}
case SLANG_METAL_LIB:
case SLANG_METAL_LIB_ASM:
{
return PassThroughFlag::Metal;
}
case SLANG_SHADER_HOST_CALLABLE:
case SLANG_HOST_HOST_CALLABLE:
case SLANG_HOST_EXECUTABLE:
case SLANG_SHADER_SHARED_LIBRARY:
case SLANG_HOST_SHARED_LIBRARY:
{
return PassThroughFlag::Generic_C_CPP;
}
case SLANG_PTX:
{
return PassThroughFlag::NVRTC;
}
default:
{
SLANG_ASSERT(!"Unknown type");
return 0;
}
}
}
static SlangResult _extractRenderTestRequirements(
const CommandLine& cmdLine,
TestRequirements* ioRequirements)
{
const auto& args = cmdLine.m_args;
// TODO(JS):
// This is rather convoluted in that it has to work out from the command line parameters passed
// to render-test what renderer will be used.
// That a similar logic has to be kept inside the implementation of render-test and both this
// and render-test will have to be kept in sync.
bool useDxbc = cmdLine.findArgIndex(UnownedStringSlice::fromLiteral("-use-dxbc")) >= 0;
bool usePassthru = false;
// Work out what kind of render will be used
RenderApiType renderApiType;
{
RenderApiType foundRenderApiType = RenderApiType::Unknown;
RenderApiType foundLanguageRenderType = RenderApiType::Unknown;
for (const auto& arg : args)
{
Slang::UnownedStringSlice argSlice = arg.getUnownedSlice();
if (argSlice.getLength() && argSlice[0] == '-')
{
// Look up the rendering API if set
UnownedStringSlice argName =
UnownedStringSlice(argSlice.begin() + 1, argSlice.end());
RenderApiType renderApiType = RenderApiUtil::findApiTypeByName(argName);
if (renderApiType != RenderApiType::Unknown)
{
foundRenderApiType = renderApiType;
// There should be only one explicit api
SLANG_ASSERT(
ioRequirements->explicitRenderApi == RenderApiType::Unknown ||
ioRequirements->explicitRenderApi == renderApiType);
// Set the explicitly set render api
ioRequirements->explicitRenderApi = renderApiType;
continue;
}
// Lookup the target language type
RenderApiType languageRenderType =
RenderApiUtil::findImplicitLanguageRenderApiType(argName);
if (languageRenderType != RenderApiType::Unknown)
{
foundLanguageRenderType = languageRenderType;
// Use the pass thru compiler if these are the sources
usePassthru |= (argName == "hlsl" || argName == "glsl");
continue;
}
}
}
// If a render option isn't set use defaultRenderType
renderApiType = (foundRenderApiType == RenderApiType::Unknown) ? foundLanguageRenderType
: foundRenderApiType;
}
// The native language for the API
SlangSourceLanguage nativeLanguage = SLANG_SOURCE_LANGUAGE_UNKNOWN;
SlangCompileTarget target = SLANG_TARGET_NONE;
SlangPassThrough passThru = SLANG_PASS_THROUGH_NONE;
switch (renderApiType)
{
case RenderApiType::D3D11:
target = SLANG_DXBC;
nativeLanguage = SLANG_SOURCE_LANGUAGE_HLSL;
passThru = SLANG_PASS_THROUGH_FXC;
break;
case RenderApiType::D3D12:
target = SLANG_DXIL;
nativeLanguage = SLANG_SOURCE_LANGUAGE_HLSL;
passThru = SLANG_PASS_THROUGH_DXC;
if (useDxbc)
{
target = SLANG_DXBC;
passThru = SLANG_PASS_THROUGH_FXC;
}
break;
case RenderApiType::Vulkan:
target = SLANG_SPIRV;
nativeLanguage = SLANG_SOURCE_LANGUAGE_GLSL;
passThru = SLANG_PASS_THROUGH_GLSLANG;
break;
case RenderApiType::Metal:
target = SLANG_METAL_LIB;
nativeLanguage = SLANG_SOURCE_LANGUAGE_METAL;
passThru = SLANG_PASS_THROUGH_METAL;
break;
case RenderApiType::CPU:
target = SLANG_SHADER_HOST_CALLABLE;
nativeLanguage = SLANG_SOURCE_LANGUAGE_CPP;
passThru = SLANG_PASS_THROUGH_GENERIC_C_CPP;
break;
case RenderApiType::CUDA:
target = SLANG_PTX;
nativeLanguage = SLANG_SOURCE_LANGUAGE_CUDA;
passThru = SLANG_PASS_THROUGH_NVRTC;
break;
case RenderApiType::WebGPU:
target = SLANG_WGSL;
nativeLanguage = SLANG_SOURCE_LANGUAGE_WGSL;
passThru = SLANG_PASS_THROUGH_TINT;
break;
}
SlangSourceLanguage sourceLanguage = nativeLanguage;
if (!usePassthru)
{
sourceLanguage = SLANG_SOURCE_LANGUAGE_SLANG;
passThru = SLANG_PASS_THROUGH_NONE;
}
if (passThru == SLANG_PASS_THROUGH_NONE)
{
// Work out backends needed based on the target
ioRequirements->addUsedBackends(_getPassThroughFlagsForTarget(target));
}
else
{
ioRequirements->addUsedBackEnd(passThru);
}
// Add the render api used
ioRequirements->addUsedRenderApi(renderApiType);
return SLANG_OK;
}
static SlangResult _extractSlangCTestRequirements(
const CommandLine& cmdLine,
TestRequirements* ioRequirements)
{
// This determines what the requirements are for a slangc like command line
// First check pass through
{
String passThrough;
if (SLANG_SUCCEEDED(_extractArg(cmdLine, "-pass-through", passThrough)))
{
ioRequirements->addUsedBackEnd(
TypeTextUtil::findPassThrough(passThrough.getUnownedSlice()));
}
}
// The target if set will also imply a backend
{
String targetName;
if (SLANG_SUCCEEDED(_extractArg(cmdLine, "-target", targetName)))
{
const SlangCompileTarget target =
TypeTextUtil::findCompileTargetFromName(targetName.getUnownedSlice());
ioRequirements->addUsedBackends(_getPassThroughFlagsForTarget(target));
}
}
return SLANG_OK;
}
static SlangResult _extractReflectionTestRequirements(
const CommandLine& cmdLine,
TestRequirements* ioRequirements)
{
// There are no specialized constraints for a reflection test
return SLANG_OK;
}
static SlangResult _extractTestRequirements(const CommandLine& cmdLine, TestRequirements* ioInfo)
{
String exeName = Path::getFileNameWithoutExt(cmdLine.m_executableLocation.m_pathOrName);
if (exeName == "render-test")
{
return _extractRenderTestRequirements(cmdLine, ioInfo);
}
else if (exeName == "slangc")
{
return _extractSlangCTestRequirements(cmdLine, ioInfo);
}
else if (exeName == "slangi")
{
return SLANG_OK;
}
else if (exeName == "slang-reflection-test")
{
return _extractReflectionTestRequirements(cmdLine, ioInfo);
}
SLANG_ASSERT(!"Unknown tool type");
return SLANG_FAIL;
}
static RenderApiFlags _getAvailableRenderApiFlags(TestContext* context)
{
static std::mutex mutex;
std::lock_guard<std::mutex> lock(mutex);
// Only evaluate if it hasn't already been evaluated (the actual evaluation is slow...)
if (!context->isAvailableRenderApiFlagsValid)
{
// Call the render-test tool asking it only to startup a specified render api
// (taking into account adapter options)
RenderApiFlags availableRenderApiFlags = 0;
for (int i = 0; i < int(RenderApiType::CountOf); ++i)
{
const RenderApiType apiType = RenderApiType(i);
if (apiType == RenderApiType::CPU)
{
if ((context->availableBackendFlags & PassThroughFlag::Generic_C_CPP) == 0)
{
continue;
}
// Check that the session has the generic C/CPP compiler availability - which is all
// we should need for CPU target
if (SLANG_SUCCEEDED(context->getSession()->checkPassThroughSupport(
SLANG_PASS_THROUGH_GENERIC_C_CPP)))
{
availableRenderApiFlags |= RenderApiFlags(1) << int(apiType);
}
continue;
}
// See if it's possible the api is available
if (RenderApiUtil::calcHasApi(apiType))
{
if (context->options.skipApiDetection)
{
availableRenderApiFlags |= RenderApiFlags(1) << int(apiType);
continue;
}
// Try starting up the device
CommandLine cmdLine;
cmdLine.setExecutableLocation(
ExecutableLocation(context->options.binDir, "render-test"));
_addRenderTestOptions(context->options, cmdLine);
// We just want to see if the device can be started up
cmdLine.addArg("-only-startup");
// Select what api to use
StringBuilder builder;
builder << "-" << RenderApiUtil::getApiName(apiType);
cmdLine.addArg(builder);
// Run the render-test tool and see if the device could startup
ExecuteResult exeRes;
if (SLANG_SUCCEEDED(
spawnAndWaitSharedLibrary(context, "device-startup", cmdLine, exeRes)) &&
TestToolUtil::getReturnCodeFromInt(exeRes.resultCode) ==
ToolReturnCode::Success)
{
availableRenderApiFlags |= RenderApiFlags(1) << int(apiType);
StdWriters::getOut().print(
"Check %s: Supported\n",
RenderApiUtil::getApiName(apiType).begin());
}
else
{
StdWriters::getOut().print(
"Check %s: Not Supported\n",
RenderApiUtil::getApiName(apiType).begin());
const auto out = exeRes.standardOutput;
const auto err = exeRes.standardError;
if (err.getLength())
StdWriters::getOut().print("%s\n", err.getBuffer());
if (out.getLength())
StdWriters::getOut().print("%s\n", out.getBuffer());
}
}
}
// After determining available APIs, print adapter info for each one
if (context->options.showAdapterInfo && availableRenderApiFlags)
{
StdWriters::getOut().print("\nAdapter Information for Available APIs:\n");
for (int i = 0; i < int(RenderApiType::CountOf); ++i)
{
const RenderApiType apiType = RenderApiType(i);
const RenderApiFlags apiFlag = RenderApiFlags(1) << int(apiType);
if (availableRenderApiFlags & apiFlag)
{
// Create command line to query adapter info
CommandLine cmdLine;
cmdLine.setExecutableLocation(
ExecutableLocation(context->options.binDir, "render-test"));
// Add the API type
StringBuilder builder;
builder << "-" << RenderApiUtil::getApiName(apiType);
cmdLine.addArg(builder);
// Add flags to show adapter info and only startup
cmdLine.addArg("-show-adapter-info");
cmdLine.addArg("-only-startup");
// Run render-test to get adapter info
ExecuteResult exeRes;
if (SLANG_SUCCEEDED(
spawnAndWaitSharedLibrary(context, "adapter-info", cmdLine, exeRes)))
{
// Output the adapter info
StdWriters::getOut().print(
"\n%s:\n%s",
RenderApiUtil::getApiName(apiType).begin(),
exeRes.standardOutput.getBuffer());
}
}
}
StdWriters::getOut().print("\n");
}
context->availableRenderApiFlags = availableRenderApiFlags;
context->isAvailableRenderApiFlagsValid = true;
}
return context->availableRenderApiFlags;
}
ToolReturnCode getReturnCode(const ExecuteResult& exeRes)
{
return TestToolUtil::getReturnCodeFromInt(exeRes.resultCode);
}
ToolReturnCode spawnAndWait(
TestContext* context,
const String& testPath,
SpawnType spawnType,
const CommandLine& cmdLine,
ExecuteResult& outExeRes)
{
if (context->isCollectingRequirements())
{
std::lock_guard<std::mutex> lock(context->mutex);
// If we just want info... don't bother running anything
const SlangResult res = _extractTestRequirements(cmdLine, context->getTestRequirements());
// Keep compiler happy on release
SLANG_UNUSED(res);
SLANG_ASSERT(SLANG_SUCCEEDED(res));
return ToolReturnCode::Success;
}
const auto& options = context->options;
const auto finalSpawnType = context->getFinalSpawnType(spawnType);
SlangResult spawnResult = SLANG_FAIL;
switch (finalSpawnType)
{
case SpawnType::UseExe:
{
spawnResult = spawnAndWaitExe(context, testPath, cmdLine, outExeRes);
break;
}
case SpawnType::Default:
case SpawnType::UseSharedLibrary:
{
spawnResult = spawnAndWaitSharedLibrary(context, testPath, cmdLine, outExeRes);
break;
}
case SpawnType::UseFullyIsolatedTestServer:
case SpawnType::UseTestServer:
{
spawnResult =
spawnAndWaitTestServer(context, finalSpawnType, testPath, cmdLine, outExeRes);
break;
}
default:
break;
}
if (SLANG_FAILED(spawnResult))
{
return ToolReturnCode::FailedToRun;
}
return getReturnCode(outExeRes);
}
// Remove embedded source code from SPIR-V assembly output to prevent filecheck from matching
// against embedded source instead of actual SPIR-V instructions
String removeEmbeddedSourceFromSPIRV(const String& spirvOutput)
{
StringBuilder filteredOutput;
List<UnownedStringSlice> lines;
StringUtil::calcLines(spirvOutput.getUnownedSlice(), lines);
if (spirvOutput.endsWith("\n"))
{
// The last empty line should be removed,
// because `StringUtil::calcLines()` turns "A\nB\n" into three lines; not two.
SLANG_ASSERT(lines[lines.getCount() - 1] == "");
lines.setCount(lines.getCount() - 1);
}
// First pass: Find OpString IDs that are referenced by DebugSource
List<String> sourceStringIds;
for (const auto& line : lines)
{
UnownedStringSlice trimmedLine = line.trim();
if (trimmedLine.indexOf(UnownedStringSlice(" DebugSource ")) == Index(-1))
continue;
// Extract the last parameter which is the source string ID
// Pattern: %4 = OpExtInst %void %2 DebugSource %5 %1
List<UnownedStringSlice> tokens;
StringUtil::split(trimmedLine, ' ', tokens);
// The last token should be the source string ID
UnownedStringSlice lastToken = tokens.getLast();
if (lastToken.startsWith(UnownedStringSlice("%")))
{
sourceStringIds.add(String(lastToken));
}
}
// Second pass: Process embedded source strings to replace content with informative message
bool insideSourceString = false;
for (const auto& line : lines)
{
UnownedStringSlice trimmedLine = line.trim();
if (!insideSourceString)
{
Index equalPos = trimmedLine.indexOf(UnownedStringSlice(" = OpString"));
if (equalPos != Index(-1) && trimmedLine.startsWith(UnownedStringSlice("%")))
{
String currentStringId = String(trimmedLine.head(equalPos));
if (sourceStringIds.contains(currentStringId))
{
insideSourceString = true;
Index quotePos = line.indexOf('\"');
if (quotePos != Index(-1))
{
filteredOutput.append(String(line.head(quotePos + 1)));
filteredOutput.append("// slang-test removed the embedded source\n");
filteredOutput.append("// Use `");
filteredOutput.append(kPreserveEmbeddedSourceOption);
filteredOutput.append("` to keep it explicitly\n\"\n");
}
continue;
}
}
}
if (insideSourceString)
{
if (trimmedLine.endsWith("\"") &&
(trimmedLine.getLength() < 2 || trimmedLine[trimmedLine.getLength() - 2] != '\\'))
{
insideSourceString = false;
}
// skip the embedded source lines
continue;
}
// Add this line to the filtered output
filteredOutput.append(line);
filteredOutput.append("\n");
}
return filteredOutput.produceString();
}
String getOutput(const ExecuteResult& exeRes, bool removeEmbeddedSource = false)
{
ExecuteResult::ResultCode resultCode = exeRes.resultCode;
String standardOuptut = exeRes.standardOutput;
String standardError = exeRes.standardError;
String debugLayer = exeRes.debugLayer;
// Apply embedded source removal to standard output if requested
if (removeEmbeddedSource && standardOuptut.getLength() > 0)
{
standardOuptut = removeEmbeddedSourceFromSPIRV(standardOuptut);
}
// We construct a single output string that captures the results
StringBuilder actualOutputBuilder;
actualOutputBuilder.append("result code = ");
actualOutputBuilder.append(resultCode);
actualOutputBuilder.append("\nstandard error = {\n");
actualOutputBuilder.append(standardError);
actualOutputBuilder.append("}\nstandard output = {\n");
actualOutputBuilder.append(standardOuptut);
actualOutputBuilder.append("}\n");
if (debugLayer.getLength() > 0)
{
actualOutputBuilder.append("debug layer = {\n");
actualOutputBuilder.append(debugLayer);
actualOutputBuilder.append("}\n");
}
return actualOutputBuilder.produceString();
}
// Finds the specialized or default path for expected data for a test.
// If neither are found, will return an empty string
String findExpectedPath(const TestInput& input, const char* postFix)
{
StringBuilder specializedBuf;
// Try the specialized name first
specializedBuf << input.outputStem;
if (postFix)
{
specializedBuf << postFix;
}
if (File::exists(specializedBuf))
{
return specializedBuf;
}
// Try the default name
StringBuilder defaultBuf;
defaultBuf.clear();
defaultBuf << input.filePath;
if (postFix)
{
defaultBuf << postFix;
}
if (File::exists(defaultBuf))
{
return defaultBuf;
}
// Couldn't find either
fprintf(
stderr,
"referenceOutput '%s' or '%s' not found.\n",
defaultBuf.getBuffer(),
specializedBuf.getBuffer());
return "";
}
static SlangResult _initSlangInterpreter(TestContext* context, CommandLine& ioCmdLine)
{
ioCmdLine.setExecutableLocation(ExecutableLocation(context->options.binDir, "slangi"));
return SLANG_OK;
}
static SlangResult _initSlangCompiler(TestContext* context, CommandLine& ioCmdLine)
{
ioCmdLine.setExecutableLocation(ExecutableLocation(context->options.binDir, "slangc"));
if (context->options.verbosePaths)
{
ioCmdLine.addArgIfNotFound("-verbose-paths");
}
for (auto& capability : context->options.capabilities)
{
ioCmdLine.addArg("-capability");
ioCmdLine.addArg(capability.getBuffer());
}
// Look for definition of a slot
{
const auto prefix = toSlice("-DNV_SHADER_EXTN_SLOT=");
bool usesNVAPI = false;
for (auto& arg : ioCmdLine.m_args)
{
if (arg.startsWith(prefix))
{
// Has NVAPI prefix, meaning
usesNVAPI = true;
break;
}
}
// This is necessary because the session can be shared, and the prelude overwritten by the
// renderer.
if (usesNVAPI)
{
// We want to set the path to NVAPI
String rootPath;
SLANG_RETURN_ON_FAIL(TestToolUtil::getRootPath(context->exePath.getBuffer(), rootPath));
String includePath;
SLANG_RETURN_ON_FAIL(
TestToolUtil::getIncludePath(rootPath, "external/nvapi/nvHLSLExtns.h", includePath))
StringBuilder buf;
// Include the NVAPI header
buf << "#include ";
StringEscapeUtil::appendQuoted(
StringEscapeUtil::getHandler(StringEscapeUtil::Style::Cpp),
includePath.getUnownedSlice(),
buf);
buf << "\n\n";
context->getSession()->setLanguagePrelude(SLANG_SOURCE_LANGUAGE_HLSL, buf.getBuffer());
}
}
return SLANG_OK;
}
TestResult asTestResult(ToolReturnCode code)
{
switch (code)
{
case ToolReturnCode::Success:
return TestResult::Pass;
case ToolReturnCode::Ignored:
return TestResult::Ignored;
default:
return TestResult::Fail;
}
}
#define TEST_RETURN_ON_DONE(x) \
{ \
const ToolReturnCode toolRet_ = x; \
if (TestToolUtil::isDone(toolRet_)) \
{ \
return asTestResult(toolRet_); \
} \
}
static SlangResult _createArtifactFromHexDump(
const UnownedStringSlice& hexDump,
const ArtifactDesc& desc,
ComPtr<IArtifact>& outArtifact)
{
// We need to extract the binary
List<uint8_t> data;
SLANG_RETURN_ON_FAIL(HexDumpUtil::parseWithMarkers(hexDump, data));
auto blob = ListBlob::moveCreate(data);
auto artifact = ArtifactUtil::createArtifact(desc);
artifact->addRepresentationUnknown(blob);
outArtifact.swap(artifact);
return SLANG_OK;
}
static SlangResult _executeBinary(const UnownedStringSlice& hexDump, ExecuteResult& outExeRes)
{
ComPtr<IArtifact> artifact;
SLANG_RETURN_ON_FAIL(_createArtifactFromHexDump(
hexDump,
ArtifactDesc::make(
ArtifactKind::Executable,
ArtifactPayload::HostCPU,
ArtifactStyle::Unknown),
artifact));
ComPtr<IOSFileArtifactRepresentation> fileRep;
SLANG_RETURN_ON_FAIL(artifact->requireFile(ArtifactKeep::Yes, fileRep.writeRef()));
const auto fileName = fileRep->getPath();
// Execute it
ExecutableLocation exe;
exe.setPath(fileName);
CommandLine cmdLine;
cmdLine.setExecutableLocation(exe);
return ProcessUtil::execute(cmdLine, outExeRes);
}
static bool _areDiagnosticsEqual(const UnownedStringSlice& a, const UnownedStringSlice& b)
{
ParseDiagnosticUtil::OutputInfo outA, outB;
// If we can't parse, we can't match, so fail.
if (SLANG_FAILED(ParseDiagnosticUtil::parseOutputInfo(a, outA)) ||
SLANG_FAILED(ParseDiagnosticUtil::parseOutputInfo(b, outB)))
{
return false;
}
// The result codes must match, and std out
if (outA.resultCode != outB.resultCode ||
!StringUtil::areLinesEqual(outA.stdOut.getUnownedSlice(), outB.stdOut.getUnownedSlice()))
{
return false;
}
// Parse the compiler diagnostics and make sure they are the same.
// Ignores line number differences
return ParseDiagnosticUtil::areEqual(
outA.stdError.getUnownedSlice(),
outB.stdError.getUnownedSlice(),
ParseDiagnosticUtil::EqualityFlag::IgnoreLineNos);
}
static bool _areResultsEqual(TestOptions::Type type, const String& a, const String& b)
{
switch (type)
{
case TestOptions::Type::Diagnostic:
return _areDiagnosticsEqual(a.getUnownedSlice(), b.getUnownedSlice());
case TestOptions::Type::Normal:
return a == b;
default:
{
SLANG_ASSERT(!"Unknown test type");
return false;
}
}
}
static String _calcModulePath(const TestInput& input)
{
// Make the module name the same as the source file
auto filePath = input.filePath;
String directory = Path::getParentDirectory(input.outputStem);
String moduleName = Path::getFileNameWithoutExt(filePath);
return Path::combine(directory, moduleName);
}
TestResult runDocTest(TestContext* context, TestInput& input)
{
// need to execute the stand-alone Slang compiler on the file, and compare its output to what we
// expect
auto outputStem = input.outputStem;
CommandLine cmdLine;
cmdLine.addArg(input.filePath);
for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
_initSlangCompiler(context, cmdLine);
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
String actualOutput = getOutput(exeRes);
String expectedOutputPath = outputStem + ".expected";
String expectedOutput;
// TODO(JS): Might want to check the result code..
Slang::File::readAllText(expectedOutputPath, expectedOutput);
// If no expected output file was found, then we
// expect everything to be empty
if (expectedOutput.getLength() == 0)
{
expectedOutput = "result code = 0\nstandard error = {\n}\nstandard output = {\n}\n";
}
TestResult result = TestResult::Pass;
// Otherwise we compare to the expected output
if (!_areResultsEqual(input.testOptions->type, expectedOutput, actualOutput))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
result = TestResult::Fail;
}
// If the test failed, then we write the actual output to a file
// so that we can easily diff it from the command line and
// diagnose the problem.
if (result == TestResult::Fail)
{
String actualOutputPath = outputStem + ".actual";
Slang::File::writeAllText(actualOutputPath, actualOutput);
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
}
return result;
}
TestResult runExecutableTest(TestContext* context, TestInput& input)
{
IDownstreamCompiler* compiler = context->getDefaultCompiler(SLANG_SOURCE_LANGUAGE_CPP);
if (!compiler)
{
return TestResult::Ignored;
}
// If we are just collecting requirements, say it passed
if (context->isCollectingRequirements())
{
std::lock_guard<std::mutex> lock(context->mutex);
context->getTestRequirements()->addUsedBackEnd(SLANG_PASS_THROUGH_GENERIC_C_CPP);
return TestResult::Pass;
}
auto filePath = input.filePath;
auto outputStem = input.outputStem;
String actualOutputPath = outputStem + ".actual";
File::remove(actualOutputPath);
// Make the module name the same as the current executable path, so it can discover
// the slang-rt library if needed.
String modulePath = Path::combine(
Path::getParentDirectory(Path::getExecutablePath()),
Path::getFileNameWithoutExt(filePath));
// String testRoot
// for(;;)
// {
// String testRoot = Path::getParentDirectory(filePath);
// if (testRoot == "")
// {
// break;
// }
// }
// printf("test folder = %s\n", testRoot.begin());
String moduleExePath;
{
StringBuilder buf;
buf << modulePath;
buf << Process::getExecutableSuffix();
moduleExePath = buf;
}
// Remove the exe if it exists
File::remove(moduleExePath);
CommandLine cmdLine;
_initSlangCompiler(context, cmdLine);
StringEscapeHandler* escapeHandler =
StringEscapeUtil::getHandler(StringEscapeUtil::Style::Space);
List<String> args;
args.add(filePath);
args.add("-o");
args.add(moduleExePath);
args.add("-target");
args.add("exe");
args.add("-Xgenericcpp");
args.add("-I./include");
args.add("-Xgenericcpp");
args.add("-I./external/unordered_dense/include");
for (auto arg : args)
{
// If unescaping is needed, do it
if (StringEscapeUtil::isUnescapeShellLikeNeeded(escapeHandler, arg.getUnownedSlice()))
{
StringBuilder buf;
StringEscapeUtil::unescapeShellLike(escapeHandler, arg.getUnownedSlice(), buf);
cmdLine.addArg(buf.produceString());
}
else
{
cmdLine.addArg(arg);
}
}
ExecuteResult exeRes;
// TODO(Yong) HACK:
// Just use shared library now, TestServer spawn mode seems to cause slangc to fail to find its
// own executable path, and thus failed to find the `gfx.slang` file sitting along side
// `slangc.exe`. We need to figure out what happened to `Path::getExecutablePath()` inside
// test-server.
SpawnType slangcSpawnType = input.spawnType;
if (slangcSpawnType == SpawnType::UseTestServer)
slangcSpawnType = SpawnType::UseExe;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, slangcSpawnType, cmdLine, exeRes));
String actualOutput;
// If the actual compilation failed, then the output will be the summary
if (exeRes.resultCode != 0)
{
actualOutput = getOutput(exeRes);
}
else
{
// Execute the binary and see what we get
CommandLine cmdLine;
ExecutableLocation exe;
exe.setPath(moduleExePath);
cmdLine.setExecutableLocation(exe);
ExecuteResult exeRes;
if (SLANG_FAILED(ProcessUtil::execute(cmdLine, exeRes)))
{
return TestResult::Fail;
}
// Write the output, and compare to expected
actualOutput = getOutput(exeRes);
}
// Write the output
Slang::File::writeAllText(actualOutputPath, actualOutput);
// Check that they are the same
{
// Read the expected
String expectedOutput;
String expectedOutputPath = outputStem + ".expected";
Slang::File::readAllText(expectedOutputPath, expectedOutput);
// Compare if they are the same
if (!StringUtil::areLinesEqual(
actualOutput.getUnownedSlice(),
expectedOutput.getUnownedSlice()))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
return TestResult::Fail;
}
}
return TestResult::Pass;
}
TestResult runLanguageServerTest(TestContext* context, TestInput& input)
{
// We don't support running language server tests in parallel yet.
std::lock_guard lock(context->mutex);
if (!context->m_languageServerConnection)
{
if (SLANG_FAILED(context->createLanguageServerJSONRPCConnection(
context->m_languageServerConnection)))
{
return TestResult::Fail;
}
}
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
auto connection = context->m_languageServerConnection.Ptr();
LanguageServerProtocol::InitializeParams initParams;
LanguageServerProtocol::WorkspaceFolder wsFolder;
wsFolder.name = "test";
String fullPath;
Path::getCanonical(input.filePath, fullPath);
wsFolder.uri = URI::fromLocalFilePath(Path::getParentDirectory(fullPath).getUnownedSlice()).uri;
initParams.workspaceFolders.add(wsFolder);
if (SLANG_FAILED(connection->sendCall(
LanguageServerProtocol::InitializeParams::methodName,
&initParams,
JSONValue::makeInt(0))))
{
return TestResult::Fail;
}
if (SLANG_FAILED(connection->waitForResult(-1)))
{
return TestResult::Fail;
}
LanguageServerProtocol::InitializeResult initResult;
if (SLANG_FAILED(connection->getMessage(&initResult)))
{
return TestResult::Fail;
}
// Send open document call.
String testFileContent;
if (SLANG_FAILED(File::readAllText(input.filePath, testFileContent)))
{
return TestResult::Fail;
}
LanguageServerProtocol::DidOpenTextDocumentParams openDocParams;
openDocParams.textDocument.version = 0;
openDocParams.textDocument.uri = URI::fromLocalFilePath(fullPath.getUnownedSlice()).uri;
openDocParams.textDocument.text = testFileContent;
connection->sendCall(
LanguageServerProtocol::DidOpenTextDocumentParams::methodName,
&openDocParams,
JSONValue::makeInt(1));
List<LanguageServerProtocol::PublishDiagnosticsParams> diagnostics;
bool diagnosticsReceived = false;
auto waitForNonDiagnosticResponse = [&]() -> SlangResult
{
repeat:
if (SLANG_FAILED(connection->waitForResult(-1)))
return SLANG_FAIL;
if (connection->getMessageType() == JSONRPCMessageType::Call)
{
JSONRPCCall call;
connection->getRPC(&call);
if (call.method == "textDocument/publishDiagnostics")
{
diagnosticsReceived = true;
LanguageServerProtocol::PublishDiagnosticsParams arg;
if (SLANG_FAILED(connection->getMessage(&arg)))
return SLANG_FAIL;
diagnostics.add(arg);
goto repeat;
}
}
return SLANG_OK;
};
List<UnownedStringSlice> lines;
StringUtil::calcLines(testFileContent.getUnownedSlice(), lines);
StringBuilder actualOutputSB;
auto parseLocation = [&](UnownedStringSlice text, Index startPos, Int& linePos, Int& colPos)
{
linePos = StringUtil::parseIntAndAdvancePos(text.trimStart(), startPos);
startPos++;
colPos = StringUtil::parseIntAndAdvancePos(text.trimStart(), startPos);
return startPos;
};
int callId = 2;
for (auto line : lines)
{
line = line.trimStart();
if (!line.startsWith("//"))
continue;
line = line.tail(2).trimStart();
if (line.startsWith("COMPLETE:"))
{
auto arg = line.tail(UnownedStringSlice("COMPLETE:").getLength());
Int linePos, colPos;
parseLocation(arg, 0, linePos, colPos);
LanguageServerProtocol::CompletionParams params;
params.position.line = int(linePos - 1);
params.position.character = int(colPos - 1);
params.textDocument.uri = openDocParams.textDocument.uri;
if (SLANG_FAILED(connection->sendCall(
LanguageServerProtocol::CompletionParams::methodName,
¶ms,
JSONValue::makeInt(callId++))))
{
return TestResult::Fail;
}
if (SLANG_FAILED(waitForNonDiagnosticResponse()))
return TestResult::Fail;
actualOutputSB << "--------\n";
LanguageServerProtocol::NullResponse nullResponse;
List<LanguageServerProtocol::CompletionItem> completionItems;
if (SLANG_SUCCEEDED(connection->getMessage(&nullResponse)))
{
actualOutputSB << "null\n";
}
else if (SLANG_SUCCEEDED(connection->getMessage(&completionItems)))
{
for (auto item : completionItems)
{
actualOutputSB << item.label << ": " << item.kind << " " << item.detail << " ";
for (auto ch : item.commitCharacters)
actualOutputSB << ch;
if (item.sortText.hasValue)
actualOutputSB << " sort(" << item.sortText.value << ")";
actualOutputSB << "\n";
}
}
}
else if (line.startsWith("SIGNATURE:"))
{
auto arg = line.tail(UnownedStringSlice("SIGNATURE:").getLength());
Int linePos, colPos;
parseLocation(arg, 0, linePos, colPos);
LanguageServerProtocol::SignatureHelpParams params;
params.position.line = int(linePos - 1);
params.position.character = int(colPos - 1);
params.textDocument.uri = openDocParams.textDocument.uri;
if (SLANG_FAILED(connection->sendCall(
LanguageServerProtocol::SignatureHelpParams::methodName,
¶ms,
JSONValue::makeInt(callId++))))
{
return TestResult::Fail;
}
if (SLANG_FAILED(waitForNonDiagnosticResponse()))
return TestResult::Fail;
actualOutputSB << "--------\n";
LanguageServerProtocol::NullResponse nullResponse;
LanguageServerProtocol::SignatureHelp sigInfo;
if (SLANG_SUCCEEDED(connection->getMessage(&nullResponse)))
{
actualOutputSB << "null\n";
}
else if (SLANG_SUCCEEDED(connection->getMessage(&sigInfo)))
{
actualOutputSB << "activeParameter: " << sigInfo.activeParameter << "\n";
actualOutputSB << "activeSignature: " << sigInfo.activeSignature << "\n";
for (Index i = 0; i < sigInfo.signatures.getCount(); ++i)
{
auto& item = sigInfo.signatures[i];
if (i == sigInfo.activeSignature)
{
actualOutputSB << "(selected) ";
}
actualOutputSB << item.label << ":";
for (auto param : item.parameters)
{
actualOutputSB << " (" << param.label[0] << "," << param.label[1] << ")";
}
actualOutputSB << "\n";
actualOutputSB << item.documentation.value << "\n";
}
}
}
else if (line.startsWith("HOVER:"))
{
auto arg = line.tail(UnownedStringSlice("HOVER:").getLength());
Int linePos, colPos;
parseLocation(arg, 0, linePos, colPos);
LanguageServerProtocol::HoverParams params;
params.position.line = int(linePos - 1);
params.position.character = int(colPos - 1);
params.textDocument.uri = openDocParams.textDocument.uri;
if (SLANG_FAILED(connection->sendCall(
LanguageServerProtocol::HoverParams::methodName,
¶ms,
JSONValue::makeInt(callId++))))
{
return TestResult::Fail;
}
if (SLANG_FAILED(waitForNonDiagnosticResponse()))
return TestResult::Fail;
actualOutputSB << "--------\n";
LanguageServerProtocol::NullResponse nullResponse;
LanguageServerProtocol::Hover hover;
if (SLANG_SUCCEEDED(connection->getMessage(&nullResponse)))
{
actualOutputSB << "null\n";
}
else if (SLANG_SUCCEEDED(connection->getMessage(&hover)))
{
actualOutputSB << "range: " << hover.range.start.line << ","
<< hover.range.start.character << " - " << hover.range.end.line
<< "," << hover.range.end.character;
actualOutputSB << "\ncontent:\n" << hover.contents.value << "\n";
}
}
else if (line.startsWith("DIAGNOSTICS"))
{
if (!diagnosticsReceived)
{
waitForNonDiagnosticResponse();
}
actualOutputSB << "--------\n";
for (auto item : diagnostics)
{
actualOutputSB << item.uri << "\n";
for (auto msg : item.diagnostics)
{
actualOutputSB << msg.range.start.line << "," << msg.range.start.character
<< "-" << msg.range.end.line << "," << msg.range.end.character
<< " " << msg.message;
}
}
}
}
LanguageServerProtocol::DidCloseTextDocumentParams closeDocParams;
closeDocParams.textDocument.uri = URI::fromLocalFilePath(fullPath.getUnownedSlice()).uri;
connection->sendCall(
LanguageServerProtocol::DidCloseTextDocumentParams::methodName,
&closeDocParams,
JSONValue::makeInt(1));
auto outputStem = input.outputStem;
String expectedOutputPath = outputStem + ".expected.txt";
String expectedOutput;
Slang::File::readAllText(expectedOutputPath, expectedOutput);
expectedOutput = expectedOutput.trim();
TestResult result = TestResult::Pass;
auto actualOutput = actualOutputSB.produceString();
// Redact absolute file names from actualOutput
List<UnownedStringSlice> outputLines;
StringUtil::calcLines(actualOutput.getUnownedSlice(), outputLines);
StringBuilder redactedSB;
for (auto line : outputLines)
{
Index extIdx = line.indexOf(UnownedStringSlice(".slang"));
if (extIdx == -1)
{
redactedSB << line << "\n";
continue;
}
redactedSB << "{REDACTED}" << line.tail(extIdx) << "\n";
}
actualOutput = redactedSB.produceString().trim();
String fileCheckPrefix;
const bool isFileCheckTest = input.testOptions->getFileCheckPrefix(fileCheckPrefix);
if (isFileCheckTest)
{
result = _fileCheckTest(*context, input.filePath, fileCheckPrefix, actualOutput);
}
else
{
if (!_areResultsEqual(input.testOptions->type, expectedOutput, actualOutput))
{
if (expectedOutput.startsWith("CONTAINS"))
{
List<UnownedStringSlice> words;
List<UnownedStringSlice> expectedLines;
StringUtil::calcLines(expectedOutput.getUnownedSlice(), expectedLines);
if (expectedLines.getCount() >= 1)
{
StringUtil::split(expectedLines[0], ' ', words);
if (words.getCount() >= 2)
{
if (actualOutput.contains(words[1].trim()))
{
return result;
}
}
}
}
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
result = TestResult::Fail;
}
}
// If the test failed, then we write the actual output to a file
// so that we can easily diff it from the command line and
// diagnose the problem.
if (result == TestResult::Fail)
{
String actualOutputPath = outputStem + ".actual";
Slang::File::writeAllText(actualOutputPath, actualOutput);
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
}
return result;
}
TestResult runSimpleTest(TestContext* context, TestInput& input)
{
// need to execute the stand-alone Slang compiler on the file, and compare its output to what we
// expect
auto outputStem = input.outputStem;
CommandLine cmdLine;
if (input.testOptions->command != "SIMPLE_EX")
{
cmdLine.addArg(input.filePath);
}
for (auto arg : input.testOptions->args)
{
// Filter out slang-test specific options that shouldn't be passed to slangc
if (arg == kPreserveEmbeddedSourceOption)
continue;
cmdLine.addArg(arg);
}
// If we can't set up for simple compilation, it's because some external resource isn't
// available such as NVAPI headers. In that case we just ignore the test.
if (SLANG_FAILED(_initSlangCompiler(context, cmdLine)))
{
return TestResult::Ignored;
}
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
// See what kind of target it is
SlangCompileTarget target = SLANG_TARGET_UNKNOWN;
{
const auto& args = input.testOptions->args;
const Index targetIndex = args.indexOf("-target");
if (targetIndex != Index(-1) && targetIndex + 1 < args.getCount())
{
target =
TypeTextUtil::findCompileTargetFromName(args[targetIndex + 1].getUnownedSlice());
}
}
// If it's executable we run it and use it's output
if (target == SLANG_HOST_EXECUTABLE)
{
ExecuteResult runExeRes;
if (SLANG_FAILED(_executeBinary(exeRes.standardOutput.getUnownedSlice(), runExeRes)))
{
return TestResult::Fail;
}
exeRes = runExeRes;
}
bool needToRemoveEmbeddedSource =
((target == SLANG_SPIRV || target == SLANG_SPIRV_ASM) &&
input.testOptions->args.indexOf(kPreserveEmbeddedSourceOption) == Index(-1));
String actualOutput = getOutput(exeRes, needToRemoveEmbeddedSource);
return _validateOutput(
context,
input,
actualOutput,
false,
"result code = 0\nstandard error = {\n}\nstandard output = {\n}\n",
[&input](auto e, auto a) { return _areResultsEqual(input.testOptions->type, e, a); });
}
TestResult runSimpleLineTest(TestContext* context, TestInput& input)
{
// need to execute the stand-alone Slang compiler on the file, and compare its output to what we
// expect
auto outputStem = input.outputStem;
CommandLine cmdLine;
_initSlangCompiler(context, cmdLine);
cmdLine.addArg(input.filePath);
for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
// Parse all the diagnostics so we can extract line numbers
auto diagnostics = ArtifactDiagnostics::create();
if (SLANG_FAILED(ParseDiagnosticUtil::parseDiagnostics(
exeRes.standardError.getUnownedSlice(),
diagnostics)) ||
diagnostics->getCount() <= 0)
{
// Write out the diagnostics which couldn't be parsed.
String actualOutputPath = outputStem + ".actual";
Slang::File::writeAllText(actualOutputPath, exeRes.standardError);
return TestResult::Fail;
}
StringBuilder actualOutput;
if (diagnostics->getCount() > 0)
{
actualOutput << diagnostics->getAt(0)->location.line << "\n";
}
else
{
actualOutput << "No output diagnostics\n";
}
return _validateOutput(context, input, actualOutput, false);
}
TestResult runInterpreterTest(TestContext* context, TestInput& input)
{
// need to execute the stand-alone Slang compiler on the file, and compare its output to what we
// expect
auto outputStem = input.outputStem;
CommandLine cmdLine;
List<String> args;
for (Index i = 0; i < input.testOptions->args.getCount(); i++)
{
auto& arg = input.testOptions->args[i];
if (arg == "-disasm")
cmdLine.addArg(arg);
else if (arg == "-entry")
{
cmdLine.addArg(arg);
i++;
if (i < input.testOptions->args.getCount())
{
cmdLine.addArg(input.testOptions->args[i]);
}
}
else
{
args.add(arg);
}
}
cmdLine.addArg(input.filePath);
for (auto arg : args)
{
cmdLine.addArg(arg);
}
if (SLANG_FAILED(_initSlangInterpreter(context, cmdLine)))
{
return TestResult::Ignored;
}
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
String actualOutput = getOutput(exeRes);
return _validateOutput(
context,
input,
actualOutput,
false,
"result code = 0\nstandard error = {\n}\nstandard output = {\n}\n",
[&input](auto e, auto a) { return _areResultsEqual(input.testOptions->type, e, a); });
}
TestResult runCompile(TestContext* context, TestInput& input)
{
auto outputStem = input.outputStem;
CommandLine cmdLine;
_initSlangCompiler(context, cmdLine);
StringEscapeHandler* escapeHandler =
StringEscapeUtil::getHandler(StringEscapeUtil::Style::Space);
for (auto arg : input.testOptions->args)
{
// If unescaping is needed, do it
if (StringEscapeUtil::isUnescapeShellLikeNeeded(escapeHandler, arg.getUnownedSlice()))
{
StringBuilder buf;
StringEscapeUtil::unescapeShellLike(escapeHandler, arg.getUnownedSlice(), buf);
cmdLine.addArg(buf.produceString());
}
else
{
cmdLine.addArg(arg);
}
}
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
if (exeRes.resultCode != 0)
{
auto reporter = context->getTestReporter();
if (reporter)
{
auto output = getOutput(exeRes);
reporter->message(TestMessageType::TestFailure, output);
}
return TestResult::Fail;
}
return TestResult::Pass;
}
TestResult runSimpleCompareCommandLineTest(TestContext* context, TestInput& input)
{
TestInput workInput(input);
// Use the original files input to compare with
workInput.outputStem = input.filePath;
// Force to using exes
workInput.spawnType = SpawnType::UseExe;
return runSimpleTest(context, workInput);
}
static SlangResult _parseJSON(
const UnownedStringSlice& slice,
DiagnosticSink* sink,
JSONContainer* container,
JSONValue& outValue)
{
SourceManager* sourceManager = sink->getSourceManager();
SourceFile* sourceFile =
sourceManager->createSourceFileWithString(PathInfo::makeUnknown(), slice);
SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr, SourceLoc());
JSONLexer lexer;
lexer.init(sourceView, sink);
JSONBuilder builder(container);
JSONParser parser;
SLANG_RETURN_ON_FAIL(parser.parse(&lexer, sourceView, &builder, sink));
outValue = builder.getRootValue();
return SLANG_OK;
}
TestResult runReflectionTest(TestContext* context, TestInput& input)
{
const auto& options = context->options;
const auto& filePath = input.filePath;
auto& outputStem = input.outputStem;
bool isCPUTest = input.testOptions->command.startsWith("CPU_");
CommandLine cmdLine;
cmdLine.setExecutableLocation(ExecutableLocation(options.binDir, "slang-reflection-test"));
cmdLine.addArg(filePath);
for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
String actualOutput = getOutput(exeRes);
if (isCPUTest)
{
#if SLANG_PTR_IS_32
outputStem.append(".32");
#else
outputStem.append(".64");
#endif
}
// Extrac the stand
ParseDiagnosticUtil::OutputInfo outputInfo;
if (SLANG_SUCCEEDED(
ParseDiagnosticUtil::parseOutputInfo(actualOutput.getUnownedSlice(), outputInfo)))
{
const auto toolReturnCode = ToolReturnCode(outputInfo.resultCode);
// The output should be JSON.
// Parse it to check that it is valid json
if (toolReturnCode == ToolReturnCode::Success)
{
SourceManager sourceManager;
sourceManager.initialize(nullptr, nullptr);
JSONContainer container(&sourceManager);
DiagnosticSink sink;
sink.init(&sourceManager, nullptr);
JSONValue value;
if (SLANG_FAILED(
_parseJSON(outputInfo.stdOut.getUnownedSlice(), &sink, &container, value)))
{
// Unable to parse as JSON
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"Unable to parse reflection JSON '%s'\n",
input.outputStem.getBuffer());
String actualOutputPath = input.outputStem + ".actual";
Slang::File::writeAllText(actualOutputPath, actualOutput);
return TestResult::Fail;
}
}
}
return _validateOutput(context, input, actualOutput);
}
static String _calcSummary(IArtifactDiagnostics* inDiagnostics)
{
auto diagnostics = cloneInterface(inDiagnostics);
// We only want to analyze errors for now
diagnostics->removeBySeverity(ArtifactDiagnostic::Severity::Info);
diagnostics->removeBySeverity(ArtifactDiagnostic::Severity::Warning);
ComPtr<ISlangBlob> summary;
diagnostics->calcSimplifiedSummary(summary.writeRef());
return StringUtil::getString(summary);
}
static TestResult runCPPCompilerCompile(TestContext* context, TestInput& input)
{
IDownstreamCompiler* compiler = context->getDefaultCompiler(SLANG_SOURCE_LANGUAGE_CPP);
if (!compiler)
{
return TestResult::Ignored;
}
// need to execute the stand-alone Slang compiler on the file, and compare its output to what we
// expect
auto outputStem = input.outputStem;
CommandLine cmdLine;
_initSlangCompiler(context, cmdLine);
cmdLine.addArg(input.filePath);
for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
// Dump out what happened
{
String actualOutputPath = outputStem + ".actual";
Slang::File::writeAllText(actualOutputPath, getOutput(exeRes));
}
if (exeRes.resultCode != 0)
{
return TestResult::Fail;
}
return TestResult::Pass;
}
static TestResult runCPPCompilerSharedLibrary(TestContext* context, TestInput& input)
{
IDownstreamCompiler* compiler = context->getDefaultCompiler(SLANG_SOURCE_LANGUAGE_CPP);
if (!compiler)
{
std::lock_guard<std::mutex> lock(context->mutex);
return TestResult::Ignored;
}
// If we are just collecting requirements, say it passed
if (context->isCollectingRequirements())
{
context->getTestRequirements()->addUsedBackEnd(SLANG_PASS_THROUGH_GENERIC_C_CPP);
return TestResult::Pass;
}
auto outputStem = input.outputStem;
auto filePath = input.filePath;
String actualOutputPath = outputStem + ".actual";
File::remove(actualOutputPath);
// Make the module name the same as the source file
String modulePath = _calcModulePath(input);
String ext = Path::getPathExt(filePath);
// Remove the binary..
String sharedLibraryPath = SharedLibrary::calcPlatformPath(modulePath.getUnownedSlice());
File::remove(sharedLibraryPath);
// Set up the compilation options
DownstreamCompileOptions options;
options.sourceLanguage = (ext == "c") ? SLANG_SOURCE_LANGUAGE_C : SLANG_SOURCE_LANGUAGE_CPP;
// Build a shared library
options.targetType = SLANG_SHADER_SHARED_LIBRARY;
auto helper = DefaultArtifactHelper::getSingleton();
// Compile this source
ComPtr<IArtifact> sourceArtifact;
// If set, we store the artifact in memory without a name.
bool checkMemory = false;
if (checkMemory)
{
helper->createArtifact(
ArtifactDescUtil::makeDescForSourceLanguage(options.sourceLanguage),
"",
sourceArtifact.writeRef());
ComPtr<IOSFileArtifactRepresentation> fileRep;
// Let's just add a blob with the contents
helper->createOSFileArtifactRepresentation(
IOSFileArtifactRepresentation::Kind::Reference,
asCharSlice(filePath.getUnownedSlice()),
nullptr,
fileRep.writeRef());
ComPtr<ICastable> castable;
fileRep->createRepresentation(ISlangBlob::getTypeGuid(), castable.writeRef());
sourceArtifact->addRepresentation(castable);
}
else
{
helper->createOSFileArtifact(
ArtifactDescUtil::makeDescForSourceLanguage(options.sourceLanguage),
asCharSlice(filePath.getUnownedSlice()),
sourceArtifact.writeRef());
}
TerminatedCharSlice includePaths[] = {TerminatedCharSlice(".")};
options.sourceArtifacts = makeSlice(sourceArtifact.readRef(), 1);
options.includePaths = makeSlice(includePaths, SLANG_COUNT_OF(includePaths));
options.modulePath = SliceUtil::asTerminatedCharSlice(modulePath);
ComPtr<IArtifact> artifact;
if (SLANG_FAILED(compiler->compile(options, artifact.writeRef())))
{
return TestResult::Fail;
}
auto diagnostics = findAssociatedRepresentation<IArtifactDiagnostics>(artifact);
if (diagnostics && SLANG_FAILED(diagnostics->getResult()))
{
// Compilation failed
String actualOutput = _calcSummary(diagnostics);
// Write the output
Slang::File::writeAllText(actualOutputPath, actualOutput);
// Check that they are the same
{
// Read the expected
String expectedOutput;
String expectedOutputPath = outputStem + ".expected";
Slang::File::readAllText(expectedOutputPath, expectedOutput);
// Compare if they are the same
if (!StringUtil::areLinesEqual(
actualOutput.getUnownedSlice(),
expectedOutput.getUnownedSlice()))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
return TestResult::Fail;
}
}
}
else
{
SharedLibrary::Handle handle;
if (SLANG_FAILED(
SharedLibrary::loadWithPlatformPath(sharedLibraryPath.getBuffer(), handle)))
{
return TestResult::Fail;
}
const int inValue = 10;
const char inBuffer[] = "Hello World!";
char buffer[128] = "";
int value = 0;
typedef int (*TestFunc)(int intValue, const char* textValue, char* outTextValue);
// We could capture output if we passed in a ISlangWriter - but for that to work we'd need a
TestFunc testFunc = (TestFunc)SharedLibrary::findSymbolAddressByName(handle, "test");
if (testFunc)
{
value = testFunc(inValue, inBuffer, buffer);
}
else
{
printf("Unable to access 'test' function\n");
}
SharedLibrary::unload(handle);
if (!(inValue == value && strcmp(inBuffer, buffer) == 0))
{
return TestResult::Fail;
}
}
return TestResult::Pass;
}
static TestResult runCPPCompilerExecute(TestContext* context, TestInput& input)
{
IDownstreamCompiler* compiler = context->getDefaultCompiler(SLANG_SOURCE_LANGUAGE_CPP);
if (!compiler)
{
return TestResult::Ignored;
}
// If we are just collecting requirements, say it passed
if (context->isCollectingRequirements())
{
std::lock_guard<std::mutex> lock(context->mutex);
context->getTestRequirements()->addUsedBackEnd(SLANG_PASS_THROUGH_GENERIC_C_CPP);
return TestResult::Pass;
}
auto filePath = input.filePath;
auto outputStem = input.outputStem;
String actualOutputPath = outputStem + ".actual";
File::remove(actualOutputPath);
// Make the module name the same as the source file
String ext = Path::getPathExt(filePath);
String modulePath = _calcModulePath(input);
// Remove the binary..
String moduleExePath;
{
StringBuilder buf;
buf << modulePath;
buf << Process::getExecutableSuffix();
moduleExePath = buf;
}
// Remove the exe if it exists
File::remove(moduleExePath);
// Set up the compilation options
DownstreamCompileOptions options;
options.sourceLanguage = (ext == "c") ? SLANG_SOURCE_LANGUAGE_C : SLANG_SOURCE_LANGUAGE_CPP;
TerminatedCharSlice filePaths[] = {SliceUtil::asTerminatedCharSlice(filePath)};
auto helper = DefaultArtifactHelper::getSingleton();
ComPtr<IArtifact> sourceArtifact;
helper->createOSFileArtifact(
ArtifactDescUtil::makeDescForSourceLanguage(options.sourceLanguage),
asCharSlice(filePath.getUnownedSlice()),
sourceArtifact.writeRef());
// Compile this source
options.sourceArtifacts = makeSlice(sourceArtifact.readRef(), 1);
options.modulePath = SliceUtil::asTerminatedCharSlice(modulePath);
ComPtr<IArtifact> artifact;
if (SLANG_FAILED(compiler->compile(options, artifact.writeRef())))
{
return TestResult::Fail;
}
String actualOutput;
auto diagnostics = findAssociatedRepresentation<IArtifactDiagnostics>(artifact);
// If the actual compilation failed, then the output will be the summary
if (diagnostics && SLANG_FAILED(diagnostics->getResult()))
{
actualOutput = _calcSummary(diagnostics);
}
else
{
// Execute the binary and see what we get
CommandLine cmdLine;
ExecutableLocation exe;
exe.setPath(moduleExePath);
cmdLine.setExecutableLocation(exe);
ExecuteResult exeRes;
if (SLANG_FAILED(ProcessUtil::execute(cmdLine, exeRes)))
{
return TestResult::Fail;
}
// Write the output, and compare to expected
actualOutput = getOutput(exeRes);
}
// Write the output
Slang::File::writeAllText(actualOutputPath, actualOutput);
// Check that they are the same
{
// Read the expected
String expectedOutput;
String expectedOutputPath = outputStem + ".expected";
Slang::File::readAllText(expectedOutputPath, expectedOutput);
// Compare if they are the same
if (!StringUtil::areLinesEqual(
actualOutput.getUnownedSlice(),
expectedOutput.getUnownedSlice()))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
return TestResult::Fail;
}
}
return TestResult::Pass;
}
// Returns TestResult::Ignored if we don't have the capability to run the passthrough compiler
// Returns TestResult::Fail if we can't write the expected output debug file
// Otherwise return TestResult::Pass and if we are not just collecting
// requirements, writes the output into the `expectedOutput` parameter
static TestResult generateExpectedOutput(
TestContext* const context,
const TestInput& input,
String& expectedOutput)
{
auto filePath = input.filePath;
auto outputStem = input.outputStem;
CommandLine expectedCmdLine;
_initSlangCompiler(context, expectedCmdLine);
const auto& args = input.testOptions->args;
const Index targetIndex = args.indexOf("-target");
if (targetIndex != Index(-1) && targetIndex + 1 < args.getCount())
{
const SlangCompileTarget target =
TypeTextUtil::findCompileTargetFromName(args[targetIndex + 1].getUnownedSlice());
// Check the session supports it. If not we ignore it
if (SLANG_FAILED(context->getSession()->checkCompileTargetSupport(target)))
{
return TestResult::Ignored;
}
switch (target)
{
case SLANG_DXIL:
case SLANG_DXIL_ASM:
{
expectedCmdLine.addArg(filePath + ".hlsl");
expectedCmdLine.addArg("-pass-through");
expectedCmdLine.addArg("dxc");
break;
}
case SLANG_DXBC:
case SLANG_DXBC_ASM:
{
expectedCmdLine.addArg(filePath + ".hlsl");
expectedCmdLine.addArg("-pass-through");
expectedCmdLine.addArg("fxc");
break;
}
default:
{
expectedCmdLine.addArg(filePath + ".glsl");
expectedCmdLine.addArg("-emit-spirv-via-glsl");
expectedCmdLine.addArg("-pass-through");
expectedCmdLine.addArg("glslang");
break;
}
}
}
for (auto arg : args)
{
expectedCmdLine.addArg(arg);
}
ExecuteResult expectedExeRes;
TEST_RETURN_ON_DONE(
spawnAndWait(context, outputStem, input.spawnType, expectedCmdLine, expectedExeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
expectedOutput = getOutput(expectedExeRes);
String expectedOutputPath = outputStem + ".expected";
if (SLANG_FAILED(Slang::File::writeAllText(expectedOutputPath, expectedOutput)))
{
context->getTestReporter()->messageFormat(
TestMessageType::TestFailure,
"Failed to write test expected output to %s",
expectedOutputPath.getBuffer());
return TestResult::Fail;
}
return TestResult::Pass;
}
// Returns TestResult::Fail if compilation fails
// Otherwise return TestResult::Pass and if we are not just collecting
// requirements, writes the output into the `expectedOutput` parameter
TestResult generateActualOutput(
TestContext* const context,
const TestInput& input,
String& actualOutput)
{
auto filePath = input.filePath;
CommandLine actualCmdLine;
_initSlangCompiler(context, actualCmdLine);
actualCmdLine.addArg(filePath);
actualCmdLine.addArg("-emit-spirv-via-glsl");
const auto& args = input.testOptions->args;
for (auto arg : input.testOptions->args)
{
actualCmdLine.addArg(arg);
}
ExecuteResult actualExeRes;
TEST_RETURN_ON_DONE(
spawnAndWait(context, input.outputStem, input.spawnType, actualCmdLine, actualExeRes));
// Early out if we're just collecting requirements
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
actualOutput = getOutput(actualExeRes);
// Always fail if the compilation produced a failure, just
// to catch situations where, e.g., command-line options parsing
// caused the same error in both the Slang and glslang cases.
//
if (actualExeRes.resultCode != 0)
{
return TestResult::Fail;
}
return TestResult::Pass;
}
TestResult runCrossCompilerTest(TestContext* context, TestInput& input)
{
// Need to execute the stand-alone Slang compiler on the file
// then on the same file + `.glsl` and compare output
//
// Or, in the case of a filecheck test, instead of comparing against the
// +".glsl" version, we run some filecheck rules on it
String fileCheckPrefix;
const bool isFileCheckTest = input.testOptions->getFileCheckPrefix(fileCheckPrefix);
String actualOutput;
if (TestResult r = generateActualOutput(context, input, actualOutput); r != TestResult::Pass)
{
return r;
}
// Only generate the expected output if this is a comparison against some
// known-good glsl/hlsl input
String expectedOutput;
if (!isFileCheckTest)
{
if (TestResult r = generateExpectedOutput(context, input, expectedOutput);
r != TestResult::Pass)
{
return r;
}
}
// Early out if we're just collecting requirements
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
TestResult result = TestResult::Pass;
if (isFileCheckTest)
{
result = _fileCheckTest(*context, input.filePath, fileCheckPrefix, actualOutput);
// TODO: It might be a good idea to sanity check any expected output
// source files against the filecheck rules if they're applicable.
//
// Something like:
// fileCheckTest(context, prefix="HLSL", input, filePath + ".hlsl");
}
else
{
if (!StringUtil::areLinesEqual(
actualOutput.getUnownedSlice(),
expectedOutput.getUnownedSlice()))
{
result = TestResult::Fail;
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
}
}
// If the test failed, then we write the actual output to a file
// so that we can easily inspect it from the command line and
// diagnose the problem.
if (result == TestResult::Fail)
{
String actualOutputPath = input.outputStem + ".actual";
Slang::File::writeAllText(actualOutputPath, actualOutput);
}
return result;
}
TestResult generateHLSLBaseline(
TestContext* context,
TestInput& input,
char const* targetFormat,
char const* passThroughName)
{
auto filePath999 = input.filePath;
auto outputStem = input.outputStem;
CommandLine cmdLine;
_initSlangCompiler(context, cmdLine);
cmdLine.addArg(filePath999);
for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
cmdLine.addArg("-target");
cmdLine.addArg(targetFormat);
cmdLine.addArg("-pass-through");
cmdLine.addArg(passThroughName);
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
String expectedOutput = getOutput(exeRes);
String expectedOutputPath = outputStem + ".expected";
if (SLANG_FAILED(Slang::File::writeAllText(expectedOutputPath, expectedOutput)))
{
return TestResult::Fail;
}
return TestResult::Pass;
}
TestResult generateHLSLBaseline(TestContext* context, TestInput& input)
{
return generateHLSLBaseline(context, input, "dxbc-assembly", "fxc");
}
static TestResult _runHLSLComparisonTest(
TestContext* context,
TestInput& input,
char const* targetFormat,
char const* passThroughName)
{
auto filePath999 = input.filePath;
auto outputStem = input.outputStem;
// We will use the Microsoft compiler to generate out expected output here
String expectedOutputPath = outputStem + ".expected";
// Generate the expected output using standard HLSL compiler
generateHLSLBaseline(context, input, targetFormat, passThroughName);
// need to execute the stand-alone Slang compiler on the file, and compare its output to what we
// expect
CommandLine cmdLine;
_initSlangCompiler(context, cmdLine);
cmdLine.addArg(filePath999);
for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
// TODO: The compiler should probably define this automatically...
cmdLine.addArg("-D");
cmdLine.addArg("__SLANG__");
cmdLine.addArg("-target");
cmdLine.addArg(targetFormat);
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
// We ignore output to stdout, and only worry about what the compiler
// wrote to stderr.
ExecuteResult::ResultCode resultCode = exeRes.resultCode;
String standardOutput = exeRes.standardOutput;
String standardError = exeRes.standardError;
String debugLayer = exeRes.debugLayer;
// We construct a single output string that captures the results
StringBuilder actualOutputBuilder;
actualOutputBuilder.append("result code = ");
actualOutputBuilder.append(resultCode);
actualOutputBuilder.append("\nstandard error = {\n");
actualOutputBuilder.append(standardError);
actualOutputBuilder.append("}\nstandard output = {\n");
actualOutputBuilder.append(standardOutput);
actualOutputBuilder.append("}\n");
if (debugLayer.getLength() > 0)
{
actualOutputBuilder.append("debug layer = {\n");
actualOutputBuilder.append(debugLayer);
actualOutputBuilder.append("}\n");
}
String actualOutput = actualOutputBuilder.produceString();
// Always fail if the compilation produced a failure, just
// to catch situations where, e.g., command-line options parsing
// caused the same error in both the Slang and fxc cases.
return _validateOutput(context, input, actualOutput, resultCode != 0);
}
static TestResult runDXBCComparisonTest(TestContext* context, TestInput& input)
{
return _runHLSLComparisonTest(context, input, "dxbc-assembly", "fxc");
}
static TestResult runDXILComparisonTest(TestContext* context, TestInput& input)
{
return _runHLSLComparisonTest(context, input, "dxil-assembly", "dxc");
}
TestResult doGLSLComparisonTestRun(
TestContext* context,
TestInput& input,
char const* langDefine,
char const* passThrough,
char const* outputKind,
String* outOutput)
{
auto filePath999 = input.filePath;
auto outputStem = input.outputStem;
CommandLine cmdLine;
_initSlangCompiler(context, cmdLine);
cmdLine.addArg(filePath999);
if (langDefine)
{
cmdLine.addArg("-D");
cmdLine.addArg(langDefine);
}
if (passThrough)
{
cmdLine.addArg("-pass-through");
cmdLine.addArg(passThrough);
}
cmdLine.addArg("-target");
cmdLine.addArg("spirv-assembly");
for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
ExecuteResult::ResultCode resultCode = exeRes.resultCode;
String standardOuptut = exeRes.standardOutput;
String standardError = exeRes.standardError;
String debugLayer = exeRes.debugLayer;
// We construct a single output string that captures the results
StringBuilder outputBuilder;
outputBuilder.append("result code = ");
outputBuilder.append(resultCode);
outputBuilder.append("\nstandard error = {\n");
outputBuilder.append(standardError);
outputBuilder.append("}\nstandard output = {\n");
outputBuilder.append(standardOuptut);
outputBuilder.append("}\n");
if (debugLayer.getLength() > 0)
{
outputBuilder.append("debug layer = {\n");
outputBuilder.append(debugLayer);
outputBuilder.append("}\n");
}
String outputPath = outputStem + outputKind;
String output = outputBuilder.produceString();
*outOutput = output;
return TestResult::Pass;
}
TestResult runGLSLComparisonTest(TestContext* context, TestInput& input)
{
auto filePath999 = input.filePath;
auto outputStem = input.outputStem;
String expectedOutput;
String actualOutput;
TestResult hlslResult = doGLSLComparisonTestRun(
context,
input,
"__GLSL__",
"glslang",
".expected",
&expectedOutput);
TestResult slangResult =
doGLSLComparisonTestRun(context, input, "__SLANG__", nullptr, ".actual", &actualOutput);
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
// If either is ignored, the whole test is
if (hlslResult == TestResult::Ignored || slangResult == TestResult::Ignored)
{
return TestResult::Ignored;
}
Slang::File::writeAllText(outputStem + ".expected", expectedOutput);
Slang::File::writeAllText(outputStem + ".actual", actualOutput);
if (hlslResult == TestResult::Fail)
return TestResult::Fail;
if (slangResult == TestResult::Fail)
return TestResult::Fail;
if (!StringUtil::areLinesEqual(
actualOutput.getUnownedSlice(),
expectedOutput.getUnownedSlice()))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
return TestResult::Fail;
}
return TestResult::Pass;
}
static void _addRenderTestOptions(const Options& options, CommandLine& ioCmdLine)
{
if (!options.emitSPIRVDirectly)
{
ioCmdLine.addArg("-emit-spirv-via-glsl");
}
for (auto capability : options.capabilities)
{
ioCmdLine.addArg("-capability");
ioCmdLine.addArg(capability);
}
if (options.enableDebugLayers)
{
ioCmdLine.addArg("-enable-debug-layers");
}
if (options.ignoreAbortMsg)
{
ioCmdLine.addArg("-ignore-abort-msg");
}
if (options.cacheRhiDevice)
{
ioCmdLine.addArg("-cache-rhi-device");
}
}
static SlangResult _extractProfileTime(const UnownedStringSlice& text, double& timeOut)
{
// Need to find the profile figure..
LineParser parser(text);
const auto lineStart = UnownedStringSlice::fromLiteral("profile-time=");
for (auto line : parser)
{
if (line.startsWith(lineStart))
{
UnownedStringSlice remaining(line.begin() + lineStart.getLength(), line.end());
remaining.trim();
timeOut = stringToDouble(String(remaining));
return SLANG_OK;
}
}
return SLANG_FAIL;
}
TestResult runPerformanceProfile(TestContext* context, TestInput& input)
{
auto outputStem = input.outputStem;
CommandLine cmdLine;
cmdLine.setExecutableLocation(ExecutableLocation(context->options.binDir, "render-test"));
cmdLine.addArg(input.filePath);
cmdLine.addArg("-performance-profile");
_addRenderTestOptions(context->options, cmdLine);
for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
auto actualOutput = getOutput(exeRes);
double time;
if (SLANG_FAILED(_extractProfileTime(actualOutput.getUnownedSlice(), time)))
{
return TestResult::Fail;
}
context->getTestReporter()->addExecutionTime(time);
return TestResult::Pass;
}
static double _textToDouble(const UnownedStringSlice& slice)
{
Index size = Index(slice.getLength());
// We have to zero terminate to be able to use atof
const Index maxSize = 80;
char buffer[maxSize + 1];
size = (size > maxSize) ? maxSize : size;
memcpy(buffer, slice.begin(), size);
buffer[size] = 0;
return atof(buffer);
}
static void _calcLines(const UnownedStringSlice& slice, List<UnownedStringSlice>& outLines)
{
StringUtil::calcLines(slice, outLines);
// Remove any trailing empty lines
while (outLines.getCount())
{
if (outLines.getLast().trim() == UnownedStringSlice())
{
outLines.removeLast();
}
else
{
break;
}
}
}
static SlangResult _compareWithType(
const UnownedStringSlice& actual,
const UnownedStringSlice& ref,
double differenceThreshold = 0.0001)
{
typedef slang::TypeReflection::ScalarType ScalarType;
ScalarType scalarType = ScalarType::None;
// We just do straight comparison if there is no type
List<UnownedStringSlice> linesActual, linesRef;
_calcLines(actual, linesActual);
_calcLines(ref, linesRef);
// If there are more lines in actual, we just ignore them, to keep same behavior as before
if (linesRef.getCount() < linesActual.getCount())
{
linesActual.setCount(linesRef.getCount());
}
if (linesActual.getCount() != linesRef.getCount())
{
return SLANG_FAIL;
}
for (Index i = 0; i < linesActual.getCount(); ++i)
{
const UnownedStringSlice lineActual = linesActual[i];
const UnownedStringSlice lineRef = linesRef[i];
if (lineActual.startsWith(UnownedStringSlice::fromLiteral("type:")))
{
if (lineActual != lineRef)
{
return SLANG_FAIL;
}
// Get the type
List<UnownedStringSlice> split;
StringUtil::split(lineActual, ':', split);
if (split.getCount() != 2)
{
return SLANG_FAIL;
}
scalarType = TypeTextUtil::findScalarType(split[1].trim());
continue;
}
switch (scalarType)
{
default:
{
if (lineActual.trim() != lineRef.trim())
{
return SLANG_FAIL;
}
break;
}
case ScalarType::Float16:
case ScalarType::Float32:
case ScalarType::Float64:
{
// Compare as double
double valueA = _textToDouble(lineActual);
double valueB = _textToDouble(lineRef);
if (!Math::AreNearlyEqual(valueA, valueB, differenceThreshold))
{
return SLANG_FAIL;
}
break;
}
}
}
return SLANG_OK;
}
TestResult runComputeComparisonImpl(
TestContext* context,
TestInput& input,
const char* const* langOpts,
size_t numLangOpts)
{
// TODO: delete any existing files at the output path(s) to avoid stale outputs leading to a
// false pass
auto filePath999 = input.filePath;
auto outputStem = input.outputStem;
CommandLine cmdLine;
cmdLine.setExecutableLocation(ExecutableLocation(context->options.binDir, "render-test"));
cmdLine.addArg(filePath999);
_addRenderTestOptions(context->options, cmdLine);
for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
for (int i = 0; i < int(numLangOpts); ++i)
{
cmdLine.addArg(langOpts[i]);
}
cmdLine.addArg("-o");
auto actualOutputFile = outputStem + ".actual.txt";
cmdLine.addArg(actualOutputFile);
if (context->isExecuting())
{
// clear the stale actual output file first. This will allow us to detect error if
// render-test fails and outputs nothing.
File::writeAllText(actualOutputFile, "");
}
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
// Check the stdout/stderr from the compiler process
auto actualOutput = getOutput(exeRes);
auto compileResult = _validateOutput(
context,
input,
actualOutput,
false,
"result code = 0\nstandard error = {\n}\nstandard output = {\n}\n");
// check against reference output
String actualOutputContent;
if (SLANG_FAILED(File::readAllText(actualOutputFile, actualOutputContent)))
{
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"Unable to read render-test output: %s\n",
actualOutput.getBuffer());
return TestResult::Fail;
}
String fileCheckPrefix;
auto bufferResult =
input.testOptions->getFileCheckBufferPrefix(fileCheckPrefix)
? _fileCheckTest(*context, input.filePath, fileCheckPrefix, actualOutputContent)
: _fileComparisonTest(
*context,
input,
nullptr,
".expected.txt",
actualOutputContent,
[](const auto& a, const auto& e) {
return SLANG_SUCCEEDED(
_compareWithType(a.getUnownedSlice(), e.getUnownedSlice()));
});
return std::max(compileResult, bufferResult);
}
TestResult runSlangComputeComparisonTest(TestContext* context, TestInput& input)
{
const char* langOpts[] = {"-slang", "-compute"};
return runComputeComparisonImpl(context, input, langOpts, SLANG_COUNT_OF(langOpts));
}
TestResult runSlangComputeComparisonTestEx(TestContext* context, TestInput& input)
{
return runComputeComparisonImpl(context, input, nullptr, 0);
}
TestResult runHLSLComputeTest(TestContext* context, TestInput& input)
{
const char* langOpts[] = {"--hlsl-rewrite", "-compute"};
return runComputeComparisonImpl(context, input, langOpts, SLANG_COUNT_OF(langOpts));
}
TestResult runSlangRenderComputeComparisonTest(TestContext* context, TestInput& input)
{
const char* langOpts[] = {"-slang", "-gcompute"};
return runComputeComparisonImpl(context, input, langOpts, SLANG_COUNT_OF(langOpts));
}
TestResult doRenderComparisonTestRun(
TestContext* context,
TestInput& input,
char const* langOption,
char const* outputKind,
String* outOutput)
{
// TODO: delete any existing files at the output path(s) to avoid stale outputs leading to a
// false pass
auto filePath = input.filePath;
auto outputStem = input.outputStem;
CommandLine cmdLine;
cmdLine.setExecutableLocation(ExecutableLocation(context->options.binDir, "render-test"));
cmdLine.addArg(filePath);
_addRenderTestOptions(context->options, cmdLine);
for (auto arg : input.testOptions->args)
{
cmdLine.addArg(arg);
}
cmdLine.addArg(langOption);
cmdLine.addArg("-o");
cmdLine.addArg(outputStem + outputKind + ".png");
ExecuteResult exeRes;
TEST_RETURN_ON_DONE(spawnAndWait(context, outputStem, input.spawnType, cmdLine, exeRes));
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
ExecuteResult::ResultCode resultCode = exeRes.resultCode;
String standardOutput = exeRes.standardOutput;
String standardError = exeRes.standardError;
String debugLayer = exeRes.debugLayer;
// We construct a single output string that captures the results
StringBuilder outputBuilder;
outputBuilder.append("result code = ");
outputBuilder.append(resultCode);
outputBuilder.append("\nstandard error = {\n");
outputBuilder.append(standardError);
outputBuilder.append("}\nstandard output = {\n");
outputBuilder.append(standardOutput);
outputBuilder.append("}\n");
if (debugLayer.getLength() > 0)
{
outputBuilder.append("debug layer = {\n");
outputBuilder.append(debugLayer);
outputBuilder.append("}\n");
}
String outputPath = outputStem + outputKind;
String output = outputBuilder.produceString();
*outOutput = output;
// Always fail if the compilation produced a failure.
if (exeRes.resultCode != 0)
{
return TestResult::Fail;
}
return TestResult::Pass;
}
class STBImage
{
public:
typedef STBImage ThisType;
/// Reset back to default initialized state (frees any image set)
void reset();
/// True if rhs has same size and amount of channels
bool isComparable(const ThisType& rhs) const;
/// The width in pixels
int getWidth() const { return m_width; }
/// The height in pixels
int getHeight() const { return m_height; }
/// The number of channels (typically held as bytes in order)
int getNumChannels() const { return m_numChannels; }
/// Get the contained pixels, nullptr if nothing loaded
const unsigned char* getPixels() const { return m_pixels; }
unsigned char* getPixels() { return m_pixels; }
/// Read an image with filename. SLANG_OK on success
SlangResult read(const char* filename);
~STBImage() { reset(); }
int m_width = 0;
int m_height = 0;
int m_numChannels = 0;
unsigned char* m_pixels = nullptr;
};
void STBImage::reset()
{
if (m_pixels)
{
stbi_image_free(m_pixels);
m_pixels = nullptr;
}
m_width = 0;
m_height = 0;
m_numChannels = 0;
}
SlangResult STBImage::read(const char* filename)
{
reset();
m_pixels = stbi_load(filename, &m_width, &m_height, &m_numChannels, 0);
if (!m_pixels)
{
return SLANG_FAIL;
}
return SLANG_OK;
}
bool STBImage::isComparable(const ThisType& rhs) const
{
return (this == &rhs) || (m_width == rhs.m_width && m_height == rhs.m_height &&
m_numChannels == rhs.m_numChannels);
}
TestResult doImageComparison(TestContext* context, String const& filePath)
{
auto reporter = context->getTestReporter();
// Allow a difference in the low bits of the 8-bit result, just to play it safe
static const int kAbsoluteDiffCutoff = 2;
// Allow a relative 1% difference
static const float kRelativeDiffCutoff = 0.01f;
String expectedPath = filePath + ".expected.png";
String actualPath = filePath + ".actual.png";
STBImage expectedImage;
if (SLANG_FAILED(expectedImage.read(expectedPath.getBuffer())))
{
reporter->messageFormat(
TestMessageType::RunError,
"Unable to load image ;%s'",
expectedPath.getBuffer());
return TestResult::Fail;
}
STBImage actualImage;
if (SLANG_FAILED(actualImage.read(actualPath.getBuffer())))
{
reporter->messageFormat(
TestMessageType::RunError,
"Unable to load image ;%s'",
actualPath.getBuffer());
return TestResult::Fail;
}
if (!expectedImage.isComparable(actualImage))
{
reporter->messageFormat(
TestMessageType::TestFailure,
"Images are different sizes '%s' '%s'",
actualPath.getBuffer(),
expectedPath.getBuffer());
return TestResult::Fail;
}
{
const unsigned char* expectedPixels = expectedImage.getPixels();
const unsigned char* actualPixels = actualImage.getPixels();
const int height = actualImage.getHeight();
const int width = actualImage.getWidth();
const int numChannels = actualImage.getNumChannels();
const int rowSize = width * numChannels;
for (int y = 0; y < height; ++y)
{
for (int i = 0; i < rowSize; ++i)
{
int expectedVal = expectedPixels[i];
int actualVal = actualPixels[i];
int absoluteDiff = actualVal - expectedVal;
if (absoluteDiff < 0)
absoluteDiff = -absoluteDiff;
if (absoluteDiff < kAbsoluteDiffCutoff)
{
// There might be a difference, but we'll consider it to be inside tolerance
continue;
}
float relativeDiff = 0.0f;
if (expectedVal != 0)
{
relativeDiff =
fabsf(float(actualVal) - float(expectedVal)) / float(expectedVal);
if (relativeDiff < kRelativeDiffCutoff)
{
// relative difference was small enough
continue;
}
}
// TODO: may need to do some local search sorts of things, to deal with
// cases where vertex shader results lead to rendering that is off
// by one pixel...
const int x = i / numChannels;
const int channelIndex = i % numChannels;
reporter->messageFormat(
TestMessageType::TestFailure,
"image compare failure at (%d,%d) channel %d. expected %d got %d (absolute "
"error: %d, relative error: %f)\n",
x,
y,
channelIndex,
expectedVal,
actualVal,
absoluteDiff,
relativeDiff);
// There was a difference we couldn't excuse!
return TestResult::Fail;
}
expectedPixels += rowSize;
actualPixels += rowSize;
}
}
return TestResult::Pass;
}
TestResult runHLSLRenderComparisonTestImpl(
TestContext* context,
TestInput& input,
char const* expectedArg,
char const* actualArg)
{
String _fileCheckPrefix;
if (input.testOptions->getFileCheckPrefix(_fileCheckPrefix))
{
context->getTestReporter()->message(
TestMessageType::RunError,
"FileCheck testing isn't supported for HLSL render tests");
return TestResult::Fail;
}
auto filePath = input.filePath;
auto outputStem = input.outputStem;
String expectedOutput;
String actualOutput;
// Run the expected test case only if we're not skipping reference image generation
TestResult hlslResult = TestResult::Pass;
if (!context->options.skipReferenceImageGeneration)
{
hlslResult =
doRenderComparisonTestRun(context, input, expectedArg, ".expected", &expectedOutput);
if (hlslResult != TestResult::Pass)
{
return hlslResult;
}
}
// Always run the actual test case
TestResult slangResult =
doRenderComparisonTestRun(context, input, actualArg, ".actual", &actualOutput);
if (slangResult != TestResult::Pass)
{
return slangResult;
}
if (context->isCollectingRequirements())
{
return TestResult::Pass;
}
// Save the expected output if we generated it
if (!context->options.skipReferenceImageGeneration)
{
Slang::File::writeAllText(outputStem + ".expected", expectedOutput);
}
Slang::File::writeAllText(outputStem + ".actual", actualOutput);
if (hlslResult == TestResult::Fail)
return TestResult::Fail;
if (slangResult == TestResult::Fail)
return TestResult::Fail;
// Compare text output only if we generated the expected output
if (!context->options.skipReferenceImageGeneration && !StringUtil::areLinesEqual(
actualOutput.getUnownedSlice(),
expectedOutput.getUnownedSlice()))
{
context->getTestReporter()->dumpOutputDifference(expectedOutput, actualOutput);
return TestResult::Fail;
}
// Next do an image comparison on the expected output images!
TestResult imageCompareResult = doImageComparison(context, outputStem);
if (imageCompareResult != TestResult::Pass)
return imageCompareResult;
return TestResult::Pass;
}
TestResult runHLSLRenderComparisonTest(TestContext* context, TestInput& input)
{
return runHLSLRenderComparisonTestImpl(context, input, "-hlsl", "-slang");
}
TestResult runHLSLCrossCompileRenderComparisonTest(TestContext* context, TestInput& input)
{
return runHLSLRenderComparisonTestImpl(context, input, "-slang", "-glsl-cross");
}
TestResult runHLSLAndGLSLRenderComparisonTest(TestContext* context, TestInput& input)
{
return runHLSLRenderComparisonTestImpl(context, input, "-hlsl-rewrite", "-glsl-rewrite");
}
TestResult skipTest(TestContext* /* context */, TestInput& /*input*/)
{
return TestResult::Ignored;
}
// based on command name, dispatch to an appropriate callback
struct TestCommandInfo
{
char const* name;
TestCallback callback;
RenderApiFlags requiredRenderApiFlags; ///< An RenderApi types that are needed to run the tests
};
static const TestCommandInfo s_testCommandInfos[] = {
{"SIMPLE", &runSimpleTest, 0},
{"SIMPLE_EX", &runSimpleTest, 0},
{"SIMPLE_LINE", &runSimpleLineTest, 0},
{"INTERPRET", &runInterpreterTest, 0},
{"REFLECTION", &runReflectionTest, 0},
{"CPU_REFLECTION", &runReflectionTest, 0},
{"COMMAND_LINE_SIMPLE", &runSimpleCompareCommandLineTest, 0},
{"COMPARE_HLSL", &runDXBCComparisonTest, 0},
{"COMPARE_DXIL", &runDXILComparisonTest, 0},
{"COMPARE_HLSL_RENDER", &runHLSLRenderComparisonTest, 0},
{"COMPARE_HLSL_CROSS_COMPILE_RENDER", &runHLSLCrossCompileRenderComparisonTest, 0},
{"COMPARE_HLSL_GLSL_RENDER", &runHLSLAndGLSLRenderComparisonTest, 0},
{"COMPARE_COMPUTE", &runSlangComputeComparisonTest, 0},
{"COMPARE_COMPUTE_EX", &runSlangComputeComparisonTestEx, 0},
{"HLSL_COMPUTE", &runHLSLComputeTest, 0},
{"COMPARE_RENDER_COMPUTE", &runSlangRenderComputeComparisonTest, 0},
{"COMPARE_GLSL", &runGLSLComparisonTest, 0},
{"CROSS_COMPILE", &runCrossCompilerTest, 0},
{"CPP_COMPILER_EXECUTE", &runCPPCompilerExecute, RenderApiFlag::CPU},
{"CPP_COMPILER_SHARED_LIBRARY", &runCPPCompilerSharedLibrary, RenderApiFlag::CPU},
{"CPP_COMPILER_COMPILE", &runCPPCompilerCompile, RenderApiFlag::CPU},
{"PERFORMANCE_PROFILE", &runPerformanceProfile, 0},
{"COMPILE", &runCompile, 0},
{"DOC", &runDocTest, 0},
{"LANG_SERVER", &runLanguageServerTest, 0},
{"EXECUTABLE", &runExecutableTest, RenderApiFlag::CPU}};
const TestCommandInfo* _findTestCommandInfoByCommand(const UnownedStringSlice& name)
{
for (const auto& command : s_testCommandInfos)
{
if (name == command.name)
{
return &command;
}
}
return nullptr;
}
static RenderApiFlags _getRequiredRenderApisByCommand(const UnownedStringSlice& name)
{
auto info = _findTestCommandInfoByCommand(name);
return info ? info->requiredRenderApiFlags : 0;
}
TestResult runTest(
TestContext* context,
String const& filePath,
String const& outputStem,
String const& testName,
TestOptions const& testOptions)
{
// If we are collecting requirements and it's diagnostic test, we always run
// (ie no requirements need to be captured - effectively it has 'no requirements')
if (context->isCollectingRequirements() && testOptions.type == TestOptions::Diagnostic)
{
return TestResult::Pass;
}
auto testInfo = _findTestCommandInfoByCommand(testOptions.command.getUnownedSlice());
if (testInfo)
{
TestInput testInput;
testInput.filePath = filePath;
testInput.outputStem = outputStem;
testInput.testOptions = &testOptions;
testInput.spawnType = context->options.defaultSpawnType;
return testInfo->callback(context, testInput);
}
// No actual test runner found!
return TestResult::Fail;
}
bool testCategoryMatches(TestCategory* sub, TestCategory* sup)
{
auto ss = sub;
while (ss)
{
if (ss == sup)
return true;
ss = ss->parent;
}
return false;
}
bool testCategoryMatches(
TestCategory* categoryToMatch,
const Dictionary<TestCategory*, TestCategory*>& categorySet)
{
for (const auto& [_, category] : categorySet)
{
if (testCategoryMatches(categoryToMatch, category))
return true;
}
return false;
}
bool testPassesCategoryMask(TestContext* context, TestOptions const& test)
{
// Don't include a test we should filter out
for (auto testCategory : test.categories)
{
if (testCategoryMatches(testCategory, context->options.excludeCategories))
return false;
}
// Otherwise include any test the user asked for
for (auto testCategory : test.categories)
{
if (testCategoryMatches(testCategory, context->options.includeCategories))
return true;
}
// skip by default
return false;
}
static void _calcSynthesizedTests(
TestContext* context,
RenderApiType synthRenderApiType,
const List<TestDetails>& srcTests,
List<TestDetails>& ioSynthTests)
{
// Add the explicit parameter
for (const auto& srcTest : srcTests)
{
const auto& requirements = srcTest.requirements;
// Render tests use renderApis...
// If it's an explicit test, we don't synth from it now
// In the case of CUDA, we can only synth from a CPU source
if (synthRenderApiType == RenderApiType::CUDA)
{
if (requirements.explicitRenderApi != RenderApiType::CPU)
{
continue;
}
// If the source language is defined, and it's
const Index index = srcTest.options.args.indexOf("-source-language");
if (index >= 0)
{
//
const auto& language = srcTest.options.args[index + 1];
SlangSourceLanguage sourceLanguage =
TypeTextUtil::findSourceLanguage(language.getUnownedSlice());
bool isCrossCompile = true;
switch (sourceLanguage)
{
case SLANG_SOURCE_LANGUAGE_GLSL:
case SLANG_SOURCE_LANGUAGE_C:
case SLANG_SOURCE_LANGUAGE_CPP:
{
isCrossCompile = false;
}
default:
break;
}
if (!isCrossCompile)
{
continue;
}
}
}
else
{
// TODO(JS): Arguably we should synthesize from explicit tests. In principal we can
// remove the explicit api apply another although that may not always work. If it
// doesn't use any render API or only uses CPU, we don't synthesize
if (requirements.usedRenderApiFlags == 0 ||
requirements.usedRenderApiFlags == RenderApiFlag::CPU ||
requirements.explicitRenderApi != RenderApiType::Unknown)
{
continue;
}
}
TestDetails synthTestDetails(srcTest.options);
TestOptions& synthOptions = synthTestDetails.options;
// If there's a category associated with this render api, add it to the synthesized test
if (auto c = context->categorySet.find(RenderApiUtil::getApiName(synthRenderApiType)))
{
synthOptions.categories.add(c);
}
// Mark as synthesized
synthOptions.isSynthesized = true;
StringBuilder builder;
builder << "-";
builder << RenderApiUtil::getApiName(synthRenderApiType);
synthOptions.args.add(builder);
// If the target is vulkan remove the -hlsl option
if (synthRenderApiType == RenderApiType::Vulkan)
{
const Index index = synthOptions.args.indexOf("-hlsl");
if (index >= 0)
{
synthOptions.args.removeAt(index);
}
}
else if (synthRenderApiType == RenderApiType::CUDA)
{
const Index index = synthOptions.args.indexOf("-cpu");
if (index >= 0)
{
synthOptions.args.removeAt(index);
}
}
// Work out the info about this tests
context->setTestRequirements(&synthTestDetails.requirements);
runTest(context, "", "", "", synthOptions);
context->setTestRequirements(nullptr);
// It does set the explicit render target
SLANG_ASSERT(synthTestDetails.requirements.explicitRenderApi == synthRenderApiType);
// Add to the tests
ioSynthTests.add(synthTestDetails);
}
}
static bool _canIgnore(TestContext* context, const TestDetails& details)
{
if (details.options.isEnabled == false)
{
return true;
}
const auto& requirements = details.requirements;
// Check if it's possible in principal to run this test with the render api flags used by this
// test
if (!context->canRunTestWithRenderApiFlags(requirements.usedRenderApiFlags))
{
return true;
}
// Are all the required backends available?
if (((requirements.usedBackendFlags & context->availableBackendFlags) !=
requirements.usedBackendFlags))
{
return true;
}
// If there are no render API requirements, then we don't need to ignore.
if (requirements.usedRenderApiFlags == 0)
{
return false;
}
// Work out what render api flags are actually available, lazily
const RenderApiFlags availableRenderApiFlags =
requirements.usedRenderApiFlags ? _getAvailableRenderApiFlags(context) : 0;
// Are all the required rendering apis available?
if ((requirements.usedRenderApiFlags & availableRenderApiFlags) !=
requirements.usedRenderApiFlags)
{
return true;
}
return false;
}
static SlangResult _runTestsOnFile(TestContext* context, String filePath)
{
// Gather a list of tests to run
FileTestList testList;
SLANG_RETURN_ON_FAIL(_gatherTestsForFile(&context->categorySet, filePath, &testList, context));
if (testList.tests.getCount() == 0)
{
// Test was explicitly ignored
return SLANG_OK;
}
// Note cases where a test file exists, but we found nothing to run
if (testList.tests.getCount() == 0)
{
context->getTestReporter()->addTest(filePath, TestResult::Ignored);
return SLANG_OK;
}
RenderApiFlags apiUsedFlags = 0;
RenderApiFlags explictUsedApiFlags = 0;
{
// We can get the test info for each of them
for (auto& testDetails : testList.tests)
{
auto& requirements = testDetails.requirements;
// Collect what the test needs (by setting restRequirements the test isn't actually run)
context->setTestRequirements(&requirements);
runTest(context, filePath, filePath, filePath, testDetails.options);
apiUsedFlags |= requirements.usedRenderApiFlags;
explictUsedApiFlags |= (requirements.explicitRenderApi != RenderApiType::Unknown)
? (RenderApiFlags(1) << int(requirements.explicitRenderApi))
: 0;
}
context->setTestRequirements(nullptr);
}
SLANG_ASSERT((apiUsedFlags & explictUsedApiFlags) == explictUsedApiFlags);
const RenderApiFlags availableRenderApiFlags =
apiUsedFlags ? _getAvailableRenderApiFlags(context) : 0;
// If synthesized tests are wanted look into adding them
if (context->options.synthesizedTestApis && availableRenderApiFlags)
{
List<TestDetails> synthesizedTests;
// What render options do we want to synthesize
RenderApiFlags missingApis =
(~apiUsedFlags) & (context->options.synthesizedTestApis & availableRenderApiFlags);
// const Index numInitialTests = testList.tests.getCount();
while (missingApis)
{
const int index = ByteEncodeUtil::calcMsb8(missingApis);
SLANG_ASSERT(index >= 0 && index <= int(RenderApiType::CountOf));
const RenderApiType synthRenderApiType = RenderApiType(index);
_calcSynthesizedTests(context, synthRenderApiType, testList.tests, synthesizedTests);
// Disable the bit
missingApis &= ~(RenderApiFlags(1) << index);
}
// Add all the synthesized tests
testList.tests.addRange(synthesizedTests);
}
// We have found a test to run!
int subTestCount = 0;
for (auto& testDetails : testList.tests)
{
int subTestIndex = subTestCount++;
// Check that the test passes our current category mask
if (!testPassesCategoryMask(context, testDetails.options))
{
continue;
}
// Work out the test stem
StringBuilder outputStem;
outputStem << filePath;
if (subTestIndex != 0)
{
outputStem << "." << subTestIndex;
}
// Work out the test name - taking into account render api / if synthesized
StringBuilder testName(outputStem);
if (testDetails.options.isSynthesized)
{
testName << " syn";
}
const auto& requirements = testDetails.requirements;
// Display list of used apis on render test
if (requirements.usedRenderApiFlags)
{
RenderApiFlags usedFlags = requirements.usedRenderApiFlags;
testName << " (";
bool isPrev = false;
while (usedFlags)
{
const int index = ByteEncodeUtil::calcMsb8(usedFlags);
const RenderApiType renderApiType = RenderApiType(index);
if (isPrev)
{
testName << ",";
}
testName << RenderApiUtil::getApiName(renderApiType);
// Disable bit
usedFlags &= ~(RenderApiFlags(1) << index);
isPrev = true;
}
testName << ")";
}
// Report the test and run/ignore
{
TestReporter::TestScope scope(context->getTestReporter(), testName);
TestResult testResult = TestResult::Fail;
// If this test can be ignored
if (_canIgnore(context, testDetails))
{
testResult = TestResult::Ignored;
context->getTestReporter()->addResult(testResult);
}
else
{
testResult = runTest(context, filePath, outputStem, testName, testDetails.options);
if (testResult == TestResult::Fail &&
!context->getTestReporter()->m_expectedFailureList.contains(testName))
{
RefPtr<FileTestInfoImpl> fileTestInfo = new FileTestInfoImpl();
fileTestInfo->filePath = filePath;
fileTestInfo->testName = testName;
fileTestInfo->outputStem = outputStem;
fileTestInfo->options = testDetails.options;
std::lock_guard lock(context->mutexFailedTests);
context->failedFileTests.add(fileTestInfo);
}
else
{
context->getTestReporter()->addResult(testResult);
}
}
// Could determine if to continue or not here... based on result
}
}
return SLANG_OK;
}
static bool endsWithAllowedExtension(TestContext* /*context*/, String filePath)
{
char const* allowedExtensions[] = {
".slang",
".hlsl",
".fx",
".glsl",
".vert",
".frag",
".geom",
".tesc",
".tese",
".comp",
".internal",
".ahit",
".chit",
".miss",
".rgen",
".c",
".cpp",
".cu",
};
for (auto allowedExtension : allowedExtensions)
{
if (filePath.endsWith(allowedExtension))
return true;
}
return false;
}
static bool shouldRunTest(TestContext* context, String filePath)
{
if (!endsWithAllowedExtension(context, filePath))
return false;
// Check exclude prefixes first - if any match, skip the test
for (auto& excludePrefix : context->options.excludePrefixes)
{
if (filePath.startsWith(excludePrefix))
{
if (context->options.verbosity == VerbosityLevel::Verbose)
{
context->getTestReporter()->messageFormat(
TestMessageType::Info,
"%s file is excluded from the test because it is found from the exclusion "
"list\n",
filePath.getBuffer());
}
return false;
}
}
if (!context->options.testPrefixes.getCount())
{
return true;
}
// If we have prefixes, it has to match one of them
for (auto& p : context->options.testPrefixes)
{
if (filePath.startsWith(p))
{
return true;
}
}
return false;
}
void getFilesInDirectory(String directoryPath, List<String>& files)
{
{
List<String> localFiles;
DirectoryUtil::findFiles(directoryPath, localFiles);
files.addRange(localFiles);
}
{
List<String> subDirs;
DirectoryUtil::findDirectories(directoryPath, subDirs);
for (auto subDir : subDirs)
{
getFilesInDirectory(subDir, files);
}
}
}
template<typename F>
void runTestsInParallel(TestContext* context, int count, const F& f)
{
auto originalReporter = context->getTestReporter();
std::atomic<int> consumePtr;
consumePtr = 0;
auto threadFunc = [&](int threadId)
{
TestReporter reporter;
reporter.init(context->options.outputMode, context->options.expectedFailureList, true);
TestReporter::SuiteScope suiteScope(&reporter, "tests");
context->setThreadIndex(threadId);
context->setTestReporter(&reporter);
do
{
int index = consumePtr.fetch_add(1);
if (index >= count)
break;
f(index);
} while (true);
{
std::lock_guard<std::mutex> lock(context->mutex);
originalReporter->consolidateWith(&reporter);
}
context->setTestReporter(nullptr);
};
List<std::thread> threads;
for (int threadId = 0; threadId < context->options.serverCount; threadId++)
{
threads.add(std::thread(threadFunc, threadId));
}
for (auto& t : threads)
t.join();
context->setTestReporter(originalReporter);
}
void runTestsInDirectory(TestContext* context)
{
List<String> files;
getFilesInDirectory(context->options.testDir, files);
// NTFS on Windows stores files in sorted order but not on Linux/Macos.
// Because of that, the testing on Linux/Macos were randomly failing, which
// is a good thing because it reveals problems. But it is useless
// if we cannot reproduce the failures deterministically.
// https://github.com/shader-slang/slang/issues/7388
files.sort();
// If asked, shuffle the list using seed for deterministic behavior.
if (context->options.shuffleTests)
{
std::mt19937 mt(context->options.shuffleSeed);
std::shuffle(files.begin(), files.end(), mt);
}
auto processFile = [&](String file)
{
if (shouldRunTest(context, file))
{
SlangResult result = _runTestsOnFile(context, file);
if (SLANG_FAILED(result))
{
{
TestReporter::TestScope scope(context->getTestReporter(), file);
context->getTestReporter()->messageFormat(
TestMessageType::RunError,
"slang-test: unable to parse test (error code: 0x%08X)",
(unsigned int)result);
context->getTestReporter()->addResult(TestResult::Fail);
}
// Output there was some kind of error trying to run the tests on this file
// fprintf(stderr, "slang-test: unable to parse test '%s'\n", file.getBuffer());
}
}
};
bool useMultiThread = false;
switch (context->options.defaultSpawnType)
{
case SpawnType::UseFullyIsolatedTestServer:
case SpawnType::UseTestServer:
useMultiThread = true;
break;
}
if (context->options.serverCount == 1)
{
useMultiThread = false;
}
if (!useMultiThread)
{
for (auto file : files)
{
processFile(file);
}
}
else
{
runTestsInParallel(
context,
(int)files.getCount(),
[&](int index) { processFile(files[index]); });
}
}
static void _disableCPPBackends(TestContext* context)
{
const SlangPassThrough cppPassThrus[] = {
SLANG_PASS_THROUGH_GENERIC_C_CPP,
SLANG_PASS_THROUGH_VISUAL_STUDIO,
SLANG_PASS_THROUGH_CLANG,
SLANG_PASS_THROUGH_GCC,
};
for (auto passThru : cppPassThrus)
{
context->availableBackendFlags &= ~(PassThroughFlags(1) << int(passThru));
context->availableRenderApiFlags &= ~(RenderApiFlag::CPU);
context->options.enabledApis &= ~(RenderApiFlag::CPU);
}
}
static void _disableD3D12Backend(TestContext* context)
{
context->options.enabledApis &= ~(RenderApiFlag::D3D12);
}
static TestResult _asTestResult(ToolReturnCode retCode)
{
switch (retCode)
{
default:
return TestResult::Fail;
case ToolReturnCode::Success:
return TestResult::Pass;
case ToolReturnCode::Ignored:
return TestResult::Ignored;
}
}
/// Loads a DLL containing unit test functions and run them one by one.
static SlangResult runUnitTestModule(
TestContext* context,
TestOptions& testOptions,
SpawnType spawnType,
const char* moduleName)
{
ISlangSharedLibraryLoader* loader = DefaultSharedLibraryLoader::getSingleton();
ComPtr<ISlangSharedLibrary> moduleLibrary;
SLANG_RETURN_ON_FAIL(loader->loadSharedLibrary(
Path::combine(context->dllDirectoryPath, moduleName).getBuffer(),
moduleLibrary.writeRef()));
UnitTestGetModuleFunc getModuleFunc =
(UnitTestGetModuleFunc)moduleLibrary->findFuncByName("slangUnitTestGetModule");
if (!getModuleFunc)
return SLANG_FAIL;
IUnitTestModule* testModule = getModuleFunc();
if (!testModule)
return SLANG_FAIL;
renderer_test::CoreDebugCallback coreDebugCallback;
renderer_test::CoreToRHIDebugBridge rhiDebugBridge;
rhiDebugBridge.setCoreCallback(&coreDebugCallback);
UnitTestContext unitTestContext;
unitTestContext.slangGlobalSession = context->getSession();
unitTestContext.workDirectory = "";
unitTestContext.enabledApis = context->options.enabledApis;
unitTestContext.enableDebugLayers = context->options.enableDebugLayers;
unitTestContext.executableDirectory = context->exeDirectoryPath.getBuffer();
unitTestContext.debugCallback = &rhiDebugBridge;
auto testCount = testModule->getTestCount();
struct TestItem
{
UnitTestFunc testFunc;
String testName;
String command;
};
List<TestItem> tests;
// Discover all tests first.
for (SlangInt i = 0; i < testCount; i++)
{
auto testFunc = testModule->getTestFunc(i);
auto testName = testModule->getTestName(i);
StringBuilder filePath;
filePath << moduleName << "/" << testName << ".internal";
auto command = filePath.produceString();
if (shouldRunTest(context, command))
{
if (testPassesCategoryMask(context, testOptions))
{
tests.add(TestItem{testFunc, testName, command});
}
}
}
auto runUnitTest = [&](TestItem test)
{
auto reporter = context->getTestReporter();
TestOptions options = testOptions;
options.command = test.command;
if (spawnType == SpawnType::UseTestServer ||
spawnType == SpawnType::UseFullyIsolatedTestServer)
{
TestServerProtocol::ExecuteUnitTestArgs args;
args.enabledApis = context->options.enabledApis;
args.enableDebugLayers = context->options.enableDebugLayers;
args.moduleName = moduleName;
args.testName = test.testName;
{
TestReporter::TestScope scopeTest(reporter, options.command);
ExecuteResult exeRes;
// Initialize the ExecuteResult, otherwise we can get bogus
// error results.
exeRes.init();
SlangResult rpcRes = _executeRPC(
context,
spawnType,
TestServerProtocol::ExecuteUnitTestArgs::g_methodName,
&args,
exeRes);
auto testResult = _asTestResult(ToolReturnCode(exeRes.resultCode));
bool isFailed = (SLANG_FAILED(rpcRes) || testResult == TestResult::Fail);
// If the rpc failed, output an error message
if (SLANG_FAILED(rpcRes))
{
reporter->message(TestMessageType::RunError, "rpc failed");
}
// Check for VVL errors in unit tests
if (exeRes.debugLayer.getLength() > 0)
{
testResult = TestResult::Fail;
reporter->message(TestMessageType::TestFailure, exeRes.debugLayer);
}
// If the test fails, output any output - which might give information about
// individual tests that have failed.
if (testResult == TestResult::Fail)
{
String output = getOutput(exeRes);
reporter->message(TestMessageType::TestFailure, output.getBuffer());
}
// If the test failed and it is not an expected failure, add it to the list of
// failed unit tests so that we can retry.
if (isFailed && !context->isRetry &&
!context->getTestReporter()->m_expectedFailureList.contains(test.testName))
{
std::lock_guard lock(context->mutexFailedTests);
context->failedUnitTests.add(test.command);
}
else
{
reporter->addResult(testResult);
}
}
}
else
{
TestReporter::TestScope scopeTest(reporter, options.command);
// TODO(JS): Problem here could be exception not handled properly across
// shared library boundary.
testModule->setTestReporter(reporter);
// Clear any previous debug messages
coreDebugCallback.clear();
try
{
test.testFunc(&unitTestContext);
// Check for VVL errors after test completion
String debugMessages = coreDebugCallback.getString();
if (debugMessages.getLength() > 0)
{
reporter->message(TestMessageType::TestFailure, debugMessages);
reporter->addResult(TestResult::Fail);
}
}
catch (...)
{
reporter->message(
TestMessageType::TestFailure,
"Exception was thrown during execution");
reporter->addResult(TestResult::Fail);
}
}
};
bool useMultiThread = false;
if (spawnType == SpawnType::UseTestServer || spawnType == SpawnType::UseFullyIsolatedTestServer)
{
if (context->options.serverCount > 1)
{
useMultiThread = true;
}
}
if (useMultiThread)
{
runTestsInParallel(
context,
(int)tests.getCount(),
[&](int index) { runUnitTest(tests[index]); });
}
else
{
auto reporter = TestReporter::get();
testModule->setTestReporter(reporter);
for (auto t : tests)
runUnitTest(t);
}
testModule->destroy();
return SLANG_OK;
}
static void cleanupRenderTestDeviceCache(TestContext& context)
{
auto cleanFunc = context.getCleanDeviceCacheFunc("render-test");
if (cleanFunc)
{
cleanFunc();
}
}
SlangResult innerMain(int argc, char** argv)
{
auto stdWriters = StdWriters::initDefaultSingleton();
// The context holds useful things used during testing
TestContext context;
SLANG_RETURN_ON_FAIL(SLANG_FAILED(context.init(argv[0])))
auto& categorySet = context.categorySet;
// Set up our test categories here
auto fullTestCategory = categorySet.add("full", nullptr);
auto quickTestCategory = categorySet.add("quick", fullTestCategory);
auto smokeTestCategory = categorySet.add("smoke", quickTestCategory);
auto renderTestCategory = categorySet.add("render", fullTestCategory);
/*auto computeTestCategory = */ categorySet.add("compute", fullTestCategory);
auto vulkanTestCategory = categorySet.add("vulkan", fullTestCategory);
auto unitTestCategory = categorySet.add("unit-test", fullTestCategory);
auto cudaTestCategory = categorySet.add("cuda", fullTestCategory);
auto optixTestCategory = categorySet.add("optix", cudaTestCategory);
auto waveTestCategory = categorySet.add("wave", fullTestCategory);
auto waveMaskCategory = categorySet.add("wave-mask", waveTestCategory);
auto waveActiveCategory = categorySet.add("wave-active", waveTestCategory);
auto compatibilityIssueCategory = categorySet.add("compatibility-issue", fullTestCategory);
auto sharedLibraryCategory = categorySet.add("shared-library", fullTestCategory);
#if SLANG_WINDOWS_FAMILY
auto windowsCategory = categorySet.add("windows", fullTestCategory);
#endif
#if SLANG_UNIX_FAMILY
auto unixCategory = categorySet.add("unix", fullTestCategory);
#endif
#if SLANG_PTR_IS_64
auto ptr64Category = categorySet.add("64-bit", fullTestCategory);
#else
auto ptr32Category = categorySet.add("32-bit", fullTestCategory);
#endif
// An un-categorized test will always belong to the `full` category
categorySet.defaultCategory = fullTestCategory;
// All following values are initialized to '0', so null.
TestCategory* passThroughCategories[SLANG_PASS_THROUGH_COUNT_OF] = {nullptr};
// Work out what backends/pass-thrus are available
{
SlangSession* session = context.getSession();
auto out = StdWriters::getOut();
out.print("Supported backends:");
for (int i = 0; i < SLANG_PASS_THROUGH_COUNT_OF; ++i)
{
const SlangPassThrough passThru = SlangPassThrough(i);
if (passThru == SLANG_PASS_THROUGH_NONE)
{
continue;
}
if (SLANG_SUCCEEDED(session->checkPassThroughSupport(passThru)))
{
context.availableBackendFlags |= PassThroughFlags(1) << int(i);
StringBuilder buf;
auto name = TypeTextUtil::getPassThroughName(passThru);
buf << " " << name;
SLANG_ASSERT(passThroughCategories[i] == nullptr);
passThroughCategories[i] = categorySet.add(buf.getBuffer() + 1, fullTestCategory);
out.write(buf.getBuffer(), buf.getLength());
}
}
out.print("\n");
}
{
SlangSession* session = context.getSession();
const bool hasLlvm =
SLANG_SUCCEEDED(session->checkPassThroughSupport(SLANG_PASS_THROUGH_LLVM));
const auto hostCallableCompiler = session->getDownstreamCompilerForTransition(
SLANG_CPP_SOURCE,
SLANG_SHADER_HOST_CALLABLE);
if (hasLlvm && hostCallableCompiler == SLANG_PASS_THROUGH_LLVM && SLANG_PROCESSOR_X86)
{
// TODO(JS)
// For some reason host-callable with llvm/double produces different results on x86
}
else
{
// Special category to mark a test only works for targets that work correctly with
// double (ie not x86/llvm)
categorySet.add("war-double-host-callable", fullTestCategory);
}
}
// Working out what renderApis is worked on on demand through
// _getAvailableRenderApiFlags()
{
// We can set the slangc command line tool, to just use the function defined here
context.setInnerMainFunc("slangc", &SlangCTool::innerMain);
}
{
// We can set the slangc command line tool, to just use the function defined here
context.setInnerMainFunc("slangi", &SlangITool::innerMain);
}
SLANG_RETURN_ON_FAIL(Options::parse(
argc,
argv,
&categorySet,
StdWriters::getOut(),
StdWriters::getError(),
&context.options));
Options& options = context.options;
context.setMaxTestRunnerThreadCount(options.serverCount);
// Set up the prelude/s
TestToolUtil::setSessionDefaultPreludeFromExePath(argv[0], context.getSession());
if (options.outputMode == TestOutputMode::TeamCity)
{
// On TeamCity CI there is an issue with unix/linux targets where test system may be
// different from the build system That we rely on having compilation tools present such
// that on x64 systems we can build x86 binaries, and that appears to not always be the
// case. For now we only allow CPP backends to run on x86_64 targets
#if SLANG_UNIX_FAMILY && !SLANG_PROCESSOR_X86_64
_disableCPPBackends(&context);
#endif
}
#if SLANG_PROCESSOR_X86
// Disable d3d12 tests on x86 right now since dxc for 32-bit windows doesn't seem to recognize
// sm_6_6.
_disableD3D12Backend(&context);
#endif
if (options.subCommand.getLength())
{
// Get the function from the tool
auto func = context.getInnerMainFunc(options.binDir, options.subCommand);
if (!func)
{
StdWriters::getError().print(
"error: Unable to launch tool '%s'\n",
options.subCommand.getBuffer());
return SLANG_FAIL;
}
// Copy args to a char* list
const auto& srcArgs = options.subCommandArgs;
List<const char*> args;
args.setCount(srcArgs.getCount());
for (Index i = 0; i < srcArgs.getCount(); ++i)
{
args[i] = srcArgs[i].getBuffer();
}
return func(
StdWriters::getSingleton(),
context.getSession(),
int(args.getCount()),
args.getBuffer());
}
if (options.includeCategories.getCount() == 0)
{
options.includeCategories.add(fullTestCategory, fullTestCategory);
}
// Exclude rendering tests when building under AppVeyor.
//
// TODO: this is very ad hoc, and we should do something cleaner.
if (options.outputMode == TestOutputMode::AppVeyor)
{
options.excludeCategories.add(renderTestCategory, renderTestCategory);
options.excludeCategories.add(vulkanTestCategory, vulkanTestCategory);
}
{
// Setup the reporter
TestReporter reporter;
SLANG_RETURN_ON_FAIL(reporter.init(options.outputMode, options.expectedFailureList));
context.setTestReporter(&reporter);
reporter.m_dumpOutputOnFailure = options.dumpOutputOnFailure;
reporter.m_verbosity = options.verbosity;
reporter.m_hideIgnored = options.hideIgnored;
{
TestReporter::SuiteScope suiteScope(&reporter, "tests");
// Enumerate test files according to policy
runTestsInDirectory(&context);
}
// Run the unit tests (these are internal C++ tests - not specified via files in a
// directory) They are registered with SLANG_UNIT_TEST macro
//
//
if (context.canRunUnitTests())
{
TestReporter::SuiteScope suiteScope(&reporter, "unit tests");
TestReporter::set(&reporter);
for (bool isRetry : {false, true})
{
auto spawnType = context.getFinalSpawnType();
context.isRetry = isRetry;
if (isRetry)
{
if (context.failedUnitTests.getCount() == 0)
break;
printf("Retrying unit tests...\n");
context.options.testPrefixes = context.failedUnitTests;
context.failedUnitTests.clear();
}
// Run the unit tests
{
TestOptions testOptions;
testOptions.categories.add(unitTestCategory);
testOptions.categories.add(smokeTestCategory);
runUnitTestModule(&context, testOptions, spawnType, "slang-unit-test-tool");
}
{
TestOptions testOptions;
testOptions.categories.add(unitTestCategory);
runUnitTestModule(&context, testOptions, spawnType, "gfx-unit-test-tool");
}
}
TestReporter::set(nullptr);
}
// If we have a couple failed tests, they maybe intermittent failures due to parallel
// excution or driver instability. We can try running them again. Debug build has more
// instability at this moment, so we allow more retries.
#if _DEBUG
static constexpr int kFailedTestLimitForRetry = 100;
#else
static constexpr int kFailedTestLimitForRetry = 16;
#endif
if (context.failedFileTests.getCount() <= kFailedTestLimitForRetry)
{
if (context.failedFileTests.getCount() > 0)
printf("Retrying %d failed tests...\n", (int)context.failedFileTests.getCount());
for (auto& test : context.failedFileTests)
{
context.isRetry = true;
FileTestInfoImpl* fileTestInfo = static_cast<FileTestInfoImpl*>(test.Ptr());
TestReporter::SuiteScope suiteScope(&reporter, "tests");
TestReporter::TestScope scope(&reporter, fileTestInfo->testName);
auto newResult = runTest(
&context,
fileTestInfo->filePath,
fileTestInfo->outputStem,
fileTestInfo->testName,
fileTestInfo->options);
reporter.addResult(newResult);
}
}
else
{
// If there are too many failed tests, don't bother retrying.
for (auto& test : context.failedFileTests)
{
FileTestInfoImpl* fileTestInfo = static_cast<FileTestInfoImpl*>(test.Ptr());
TestReporter::SuiteScope suiteScope(&reporter, "tests");
TestReporter::TestScope scope(&reporter, fileTestInfo->testName);
reporter.addResult(TestResult::Fail);
}
}
reporter.outputSummary();
cleanupRenderTestDeviceCache(context);
return reporter.didAllSucceed() ? SLANG_OK : SLANG_FAIL;
}
}
int main(int argc, char** argv)
{
// Fallback: run without cleanup if context initialization fails
SlangResult res = innerMain(argc, argv);
slang::shutdown();
Slang::RttiInfo::deallocateAll();
#ifdef _MSC_VER
_CrtDumpMemoryLeaks();
#endif
return SLANG_SUCCEEDED(res) ? 0 : 1;
}
|