kache 0.20.0

Zero-copy, content-addressed build cache for Rust, C/C++ and more, with S3 and shared-filesystem remotes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
//! C-family compiler (cc / gcc / g++ / clang / clang++ / c++).
//!
//! **C/C++ caching is live for the single-source `-c` compile.**
//! A `cc -c foo.c -o foo.o` invocation gets a content-addressed
//! cache entry; an identical re-invocation restores the `.o` and, when
//! requested, its `.d` dep-info sidecar without running the compiler.
//!
//! What's cached:
//! - **`-c` object compiles**, exactly one source per invocation.
//!   The cache key is the preprocessor expansion (`cc -E -P` with
//!   `SOURCE_DATE_EPOCH` pinned) plus compiler identity, target
//!   arch, and codegen flags. The preprocessor hash captures the
//!   source and every transitively-included header. The cold probe also writes
//!   a private complete dependency list; a later local invocation can reuse
//!   the expansion hash only while every source/header fingerprint matches,
//!   otherwise it preprocesses again. The key also digests **names** in
//!   user include dirs (`-I`, `-iquote`, and the source file's directory)
//!   so a header that appears in an earlier search dir cannot shadow a
//!   previously-read one without changing the key. `-E -P` strips line
//!   markers so header *paths* don't leak — the object key remains portable
//!   across machines and worktrees, while the optimization itself is
//!   deliberately local.
//!
//! What passes through (refused, see [`CcArgs::refuse_reasons`]):
//! - Link mode (whole-program caching is a separate, harder problem)
//! - Preprocess (`-E`) / assemble (`-S`) modes
//! - Multi-source compiles, multi-arch fat binaries
//! - Response files, coverage instrumentation, split DWARF,
//!   precompiled headers, modules, output-to-stdout
//! - Any flag not classified by [`CC_FLAGS`] (see [`classify_cc_flag`])
//!   — an unmodeled codegen flag, a cross-target, profiling, or simply
//!   a flag kache has not classified. Refused so an unknown flag is
//!   never silently cached. The table is declarative; see
//!   [`crate::compiler::flags`] for the matcher / classification
//!   vocabulary it uses.
//!
//! Future work (separate PRs):
//! - Link-mode / whole-executable caching
//! - `ar` archive caching
//! - Mach-O OSO record stripping for cross-machine sharing of *linked*
//!   artifacts (issue #78) — deferred until link-mode caching exists, since
//!   `-c` object compiles carry no linker-emitted `N_OSO` records. The
//!   SDKROOT half of #78 is handled: the Apple SDK path is mapped to the
//!   `/kache/sdkroot` prefix-map target ([`CC_SDKROOT_SENTINEL`]).

use anyhow::{Context, Result};
use regex::Regex;
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::ffi::OsStr;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;

use super::flags::{Dialect, FlagClass, FlagSpec, Matcher};
use super::{
    Artifact, ArtifactKind, ArtifactSet, CompileResult, Compiler, CompilerAdapter, CompilerId,
    KeyCtx, RefuseReason, classify_by_filename,
};

/// Compiler driver family of a cc-wrapper invocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolFamily {
    /// gcc / cc and compatible drivers.
    Gnu,
    /// clang / clang++ in the default (gcc-compatible) driver mode.
    Clang,
    /// clang in MSVC driver mode (`clang-cl` or `--driver-mode=cl`).
    ClangCl,
}

impl ToolFamily {
    /// The flag dialect this family speaks (Gnu and Clang share one).
    pub fn dialect(self) -> Dialect {
        match self {
            ToolFamily::Gnu | ToolFamily::Clang => Dialect::Gnu,
            ToolFamily::ClangCl => Dialect::Cl,
        }
    }

    /// Detect the family from argv0 and the argument list.
    ///
    /// `clang-cl` (including versioned/target-prefixed forms) or any argv
    /// carrying `--driver-mode=cl` is `ClangCl`. A
    /// `clang`/`clang++`/`clang-<n>` basename is `Clang`.
    /// `zigcc` wrappers (cargo-zigbuild) are also `Clang` — zig's cc is
    /// clang-based.
    /// Everything else (gcc, cc, g++, c++) is `Gnu`. Bare `cl` is NOT
    /// special-cased — real MSVC `cl.exe` stays out of scope.
    pub fn detect(program: &str, rest: &[String]) -> ToolFamily {
        let name = super::command_basename(program)
            .map(super::strip_windows_exe_suffix)
            .unwrap_or(program)
            .to_ascii_lowercase();
        if rest.iter().any(|a| a == "--driver-mode=cl") {
            return ToolFamily::ClangCl;
        }
        if name == "zigcc" || name.starts_with("zigcc-") {
            return ToolFamily::Clang;
        }
        named_tool_family(&name).unwrap_or(ToolFamily::Gnu)
    }
}

pub const CC_ID: CompilerId = CompilerId::new("cc");
pub const ADAPTER: CompilerAdapter =
    CompilerAdapter::new(CC_ID, "C-family compiler", CcCompiler::recognizes);

/// What stage the compiler is being asked to produce.
///
/// Cargo's `cc` crate (and most build systems) use `-c` for the
/// per-file compile step that produces a `.o`, then a separate
/// invocation that links them into the final executable / library.
/// Caching is most valuable for `Compile` mode (the per-file work
/// gets reused across invocations); `Link` mode caching is harder
/// (depends on every input `.o`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompileMode {
    /// `-c`: produce object file(s) from source. The default cache
    /// target for kache's cc support.
    Compile,
    /// (no `-c` flag): compile + link, producing an executable or
    /// dynamic library. Realistic to cache eventually but more
    /// failure-prone (linker version, link order, native lib search
    /// paths).
    Link,
    /// `-E`: preprocess only — emits the source after macro expansion.
    /// Used by build systems for header probing; rarely cached.
    /// Note: also matches the `cc` crate's family probe shape, which
    /// is handled BEFORE this parser via [`CcCompiler::recognizes_family_probe`].
    Preprocess,
    /// `-S`: produce assembly output. Niche; same caching profile
    /// as `Compile` in principle but rarely worth the engineering.
    Assemble,
}

/// `-O0` … `-O3`, plus the size and debug variants. Stored as the
/// raw character (`'0'`..`'3'`, `'s'`, `'z'`, `'g'`) so the cache
/// key can hash it directly without re-stringification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptLevel {
    O0,
    O1,
    O2,
    O3,
    /// `-Os` — optimize for size.
    Os,
    /// `-Oz` — optimize for size, more aggressive (clang-only).
    Oz,
    /// `-Og` — optimize while preserving debuggability.
    Og,
}

/// Dependency-info generation flags (`-MMD` / `-MD` / `-MF` / `-MT`).
///
/// Cargo uses these to figure out which headers a `.o` depends on
/// for incremental rebuild. kache caches the `.o` directly, so the
/// dep-info file is generated as a side effect — but its CONTENTS
/// (a Make-style dependency list) embed absolute paths that need
/// the same path-normalization treatment as rustc's dep-info.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct DepInfoSpec {
    /// True when the invocation actually asks the compiler to emit dep-info
    /// in compile mode (`-MD` / `-MMD`). Path/target modifiers alone do not
    /// create a depfile.
    pub emit: bool,
    /// `-MD` (true) or `-MMD` (false). True = include system headers
    /// in the dep-info output; false = user headers only.
    pub include_system: bool,
    /// `-MP`: add phony targets for each dependency.
    pub phony_targets: bool,
    /// `-MG`: treat missing headers as generated files in dependency output.
    pub missing_generated: bool,
    /// `-MF foo.d`: where to write the dep-info file. `None` means
    /// the compiler picks a default (typically next to the `.o`).
    pub output: Option<PathBuf>,
    /// `-MT target`: the make target name for dep-info entries.
    /// Defaults to the output object name.
    pub target: Option<String>,
}

/// Parsed C-family invocation.
///
/// Field order roughly matches the cache-key construction order
/// (compiler family + version, then flags affecting code gen, then
/// flags affecting layout, then sources). Keeping that consistency
/// makes the cache_key implementation (PR5-B) easier to read.
#[derive(Debug, Clone)]
pub struct CcArgs {
    /// argv[0] — the compiler binary path the wrapper was invoked as.
    pub program: String,
    /// argv[1..] verbatim — preserved for passthrough / re-execution.
    pub rest: Vec<String>,

    /// Source files (`.c`, `.cpp`, `.cc`, `.cxx`, `.m`, `.mm`).
    /// May be empty for link-only invocations or pure flag probes.
    pub sources: Vec<PathBuf>,
    /// Output path from `-o`. `None` = compiler default (varies by mode).
    pub output: Option<PathBuf>,
    /// What stage the compiler was asked to produce.
    pub mode: CompileMode,
    /// Include search paths from `-I dir` / `-Idir` (in declaration
    /// order — order matters for header search semantics).
    pub includes: Vec<PathBuf>,
    /// Defines from `-D NAME` / `-D NAME=VALUE` (declaration order).
    pub defines: Vec<(String, Option<String>)>,
    /// Optimization level.
    pub optimization: Option<OptLevel>,
    /// Debug-info level: `0` = none (`-g0`), through `3` = max
    /// (`-g3`). Bare `-g` is treated as `2` (compiler default).
    pub debug_level: Option<u8>,
    /// Language standard from `-std=c11` / `-std=c++17` etc.
    /// Stored without the `-std=` prefix.
    pub std: Option<String>,
    /// Position-independent code (`-fPIC` / `-fpic`).
    pub pic: bool,
    /// Dependency-info generation flags. `None` = no dep-info.
    pub depinfo: Option<DepInfoSpec>,
    /// Language override from `-x c` / `-x c++` / `-x objective-c`.
    /// Without this flag, the compiler infers from source extension.
    pub language_override: Option<String>,
    /// Detected compiler driver family (selects the flag dialect).
    pub family: ToolFamily,
}

/// Source file extensions the parser recognizes as C-family input.
/// Anything else gets ignored (left in `rest` for passthrough).
const SOURCE_EXTENSIONS: &[&str] = &[
    "c", "cc", "cpp", "cxx", "c++", "C", // C / C++
    "m", "mm", "M", // Objective-C / Objective-C++
    "i", "ii", // already-preprocessed
    "S", "s", "sx", // assembly
];

/// `-x` language overrides whose compilation is representable by one
/// preprocessor output and one code-generation pass. Anything outside
/// this list is refused: multi-pass languages (CUDA, HIP) compile the
/// same TU once per target with different predefined macros
/// (`__CUDA_ARCH__`), so a single `-E` output cannot soundly key them.
const LANGUAGE_OVERRIDE_ALLOWLIST: &[&str] = &[
    "c",
    "c++",
    "objective-c",
    "objective-c++",
    "assembler",
    "assembler-with-cpp",
    "cpp-output",
    "c++-cpp-output",
    "objective-c-cpp-output",
    "objective-c++-cpp-output",
];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CcArgValueForm {
    Flag,
    Separated,
    Concatenated { prefix: &'static str },
    CanBeSeparated { prefix: &'static str },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CcArgAction {
    SetMode(CompileMode),
    SetOutput,
    SetPic,
    SetDebugLevel(u8),
    SetOptimization(OptLevel),
    SetStd,
    DepIncludeSystem(bool),
    DepPhonyTargets,
    DepMissingGenerated,
    DepOutput,
    DepTarget,
    LanguageOverride,
    Include,
    Define,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CcArgBucket {
    Structural,
    ModeledInKey,
    ProbeKeyed,
    Preprocessor,
    RawKeyed,
    #[allow(dead_code)]
    ExtraHashFile,
    Artifact,
    NoObjectEffect,
    TooHard,
}

#[derive(Debug, Clone, Copy)]
struct CcArgSpec {
    matcher: Matcher,
    value_form: CcArgValueForm,
    action: CcArgAction,
    bucket: CcArgBucket,
    source: &'static str,
    /// Dialect this row applies to. `None` = any dialect.
    dialect: Option<Dialect>,
}

#[derive(Debug, Clone)]
struct ParsedCcArg {
    spec: &'static CcArgSpec,
    value: Option<String>,
    consumed: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct CcArgAnalysis<'a> {
    arg: &'a str,
    class: Option<FlagClass>,
    bucket: CcArgBucket,
    normalized: Vec<String>,
    refusal: Option<&'static str>,
    source: Option<&'static str>,
}

static CC_ARG_SPECS: &[CcArgSpec] = &[
    CcArgSpec {
        matcher: Matcher::Exact("-c"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetMode(CompileMode::Compile),
        bucket: CcArgBucket::Structural,
        source: "compile mode marker",
        dialect: None,
    },
    CcArgSpec {
        // MSVC `/c` slash spelling of the compile-only marker. clang-cl
        // accepts both `-c` and `/c`; without this kache misreads `/c`
        // builds as link mode and passes them through (box-confirmed).
        matcher: Matcher::Exact("/c"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetMode(CompileMode::Compile),
        bucket: CcArgBucket::Structural,
        source: "compile mode marker (cl)",
        dialect: Some(Dialect::Cl),
    },
    CcArgSpec {
        matcher: Matcher::Exact("-E"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetMode(CompileMode::Preprocess),
        bucket: CcArgBucket::Structural,
        source: "preprocess mode marker",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-S"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetMode(CompileMode::Assemble),
        bucket: CcArgBucket::Structural,
        source: "assembly mode marker",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-o"),
        value_form: CcArgValueForm::Separated,
        action: CcArgAction::SetOutput,
        bucket: CcArgBucket::Artifact,
        source: "primary output path",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-fPIC"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetPic,
        bucket: CcArgBucket::ModeledInKey,
        source: "position-independent code",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-fpic"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetPic,
        bucket: CcArgBucket::ModeledInKey,
        source: "position-independent code",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-g"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetDebugLevel(2),
        bucket: CcArgBucket::ModeledInKey,
        source: "debug-info level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-g0"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetDebugLevel(0),
        bucket: CcArgBucket::ModeledInKey,
        source: "debug-info level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-g1"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetDebugLevel(1),
        bucket: CcArgBucket::ModeledInKey,
        source: "debug-info level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-g2"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetDebugLevel(2),
        bucket: CcArgBucket::ModeledInKey,
        source: "debug-info level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-g3"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetDebugLevel(3),
        bucket: CcArgBucket::ModeledInKey,
        source: "debug-info level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-O"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetOptimization(OptLevel::O1),
        bucket: CcArgBucket::ModeledInKey,
        source: "optimization level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-O0"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetOptimization(OptLevel::O0),
        bucket: CcArgBucket::ModeledInKey,
        source: "optimization level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-O1"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetOptimization(OptLevel::O1),
        bucket: CcArgBucket::ModeledInKey,
        source: "optimization level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-O2"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetOptimization(OptLevel::O2),
        bucket: CcArgBucket::ModeledInKey,
        source: "optimization level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-O3"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetOptimization(OptLevel::O3),
        bucket: CcArgBucket::ModeledInKey,
        source: "optimization level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-Os"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetOptimization(OptLevel::Os),
        bucket: CcArgBucket::ModeledInKey,
        source: "optimization level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-Oz"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetOptimization(OptLevel::Oz),
        bucket: CcArgBucket::ModeledInKey,
        source: "optimization level",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Exact("-Og"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::SetOptimization(OptLevel::Og),
        bucket: CcArgBucket::ModeledInKey,
        source: "optimization level",
        dialect: None,
    },
    // ── GNU dep-info rows — gnu dialect only ─────────────────────
    // In clang-cl mode, `-MD`/`-MMD` are CRT-selection flags (matching
    // MSVC `/MD`/`/MDd`), `-MT`/`-MF`/`-MQ` are also CRT/output
    // spellings, and `-MP`/`-MG` are unrelated. Tagging these rows
    // `Dialect::Gnu` makes the parser skip them entirely under clang-cl
    // so they fall through to the flag classifier / unknown-flag path.
    CcArgSpec {
        matcher: Matcher::Exact("-MD"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::DepIncludeSystem(true),
        bucket: CcArgBucket::NoObjectEffect,
        source: "dependency sidecar",
        dialect: Some(Dialect::Gnu),
    },
    CcArgSpec {
        matcher: Matcher::Exact("-MMD"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::DepIncludeSystem(false),
        bucket: CcArgBucket::NoObjectEffect,
        source: "dependency sidecar",
        dialect: Some(Dialect::Gnu),
    },
    CcArgSpec {
        matcher: Matcher::Exact("-MP"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::DepPhonyTargets,
        bucket: CcArgBucket::NoObjectEffect,
        source: "dependency sidecar phony targets",
        dialect: Some(Dialect::Gnu),
    },
    CcArgSpec {
        matcher: Matcher::Exact("-MG"),
        value_form: CcArgValueForm::Flag,
        action: CcArgAction::DepMissingGenerated,
        bucket: CcArgBucket::NoObjectEffect,
        source: "dependency sidecar generated headers",
        dialect: Some(Dialect::Gnu),
    },
    CcArgSpec {
        matcher: Matcher::Exact("-MF"),
        value_form: CcArgValueForm::Separated,
        action: CcArgAction::DepOutput,
        bucket: CcArgBucket::Artifact,
        source: "dependency output path",
        dialect: Some(Dialect::Gnu),
    },
    CcArgSpec {
        matcher: Matcher::Exact("-MT"),
        value_form: CcArgValueForm::Separated,
        action: CcArgAction::DepTarget,
        bucket: CcArgBucket::NoObjectEffect,
        source: "dependency target",
        dialect: Some(Dialect::Gnu),
    },
    CcArgSpec {
        matcher: Matcher::Exact("-MQ"),
        value_form: CcArgValueForm::Separated,
        action: CcArgAction::DepTarget,
        bucket: CcArgBucket::NoObjectEffect,
        source: "dependency target",
        dialect: Some(Dialect::Gnu),
    },
    CcArgSpec {
        matcher: Matcher::Prefix("-x"),
        value_form: CcArgValueForm::CanBeSeparated { prefix: "-x" },
        action: CcArgAction::LanguageOverride,
        bucket: CcArgBucket::ProbeKeyed,
        source: "language override",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Prefix("-I"),
        value_form: CcArgValueForm::CanBeSeparated { prefix: "-I" },
        action: CcArgAction::Include,
        bucket: CcArgBucket::Preprocessor,
        source: "include search path",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Prefix("-D"),
        value_form: CcArgValueForm::CanBeSeparated { prefix: "-D" },
        action: CcArgAction::Define,
        bucket: CcArgBucket::Preprocessor,
        source: "preprocessor define",
        dialect: None,
    },
    CcArgSpec {
        matcher: Matcher::Prefix("-std="),
        value_form: CcArgValueForm::Concatenated { prefix: "-std=" },
        action: CcArgAction::SetStd,
        bucket: CcArgBucket::ModeledInKey,
        source: "language standard",
        dialect: None,
    },
    // ── clang-cl output and standard rows (#285) ─────────────────
    // clang-cl uses `-Fo<obj>` / `/Fo<obj>` (concatenated, no space)
    // for the object output path, analogous to gnu `-o <obj>`.
    CcArgSpec {
        matcher: Matcher::Prefix("-Fo"),
        value_form: CcArgValueForm::Concatenated { prefix: "-Fo" },
        action: CcArgAction::SetOutput,
        bucket: CcArgBucket::Artifact,
        source: "clang-cl object output (#285)",
        dialect: Some(Dialect::Cl),
    },
    CcArgSpec {
        matcher: Matcher::Prefix("/Fo"),
        value_form: CcArgValueForm::Concatenated { prefix: "/Fo" },
        action: CcArgAction::SetOutput,
        bucket: CcArgBucket::Artifact,
        source: "clang-cl object output (#285)",
        dialect: Some(Dialect::Cl),
    },
    // clang-cl language standard: `-std:c++20` / `/std:c++20`.
    // The value after the prefix (e.g. `c++20`) is stored in `parsed.std`.
    CcArgSpec {
        matcher: Matcher::Prefix("-std:"),
        value_form: CcArgValueForm::Concatenated { prefix: "-std:" },
        action: CcArgAction::SetStd,
        bucket: CcArgBucket::ModeledInKey,
        source: "clang-cl language standard (#285)",
        dialect: Some(Dialect::Cl),
    },
    CcArgSpec {
        matcher: Matcher::Prefix("/std:"),
        value_form: CcArgValueForm::Concatenated { prefix: "/std:" },
        action: CcArgAction::SetStd,
        bucket: CcArgBucket::ModeledInKey,
        source: "clang-cl language standard (#285)",
        dialect: Some(Dialect::Cl),
    },
];

impl CcArgs {
    pub fn parse(args: &[String]) -> Result<Self> {
        let (program, rest) = args
            .split_first()
            .context("cc invocation missing argv[0]")?;

        let family = ToolFamily::detect(program, rest);

        let mut parsed = CcArgs {
            program: program.clone(),
            rest: rest.to_vec(),
            sources: Vec::new(),
            output: None,
            mode: CompileMode::Link, // default: compile + link
            includes: Vec::new(),
            defines: Vec::new(),
            optimization: None,
            debug_level: None,
            std: None,
            pic: false,
            depinfo: None,
            language_override: None,
            family,
        };

        // Walk argv through a table-driven parser so spelling variants
        // like `-x c` / `-xc` and `-I dir` / `-Idir` share one rule.
        let mut depinfo: Option<DepInfoSpec> = None;
        let mut idx = 0;
        while idx < rest.len() {
            if let Some(arg) = parse_cc_arg_at(rest, idx, family.dialect()) {
                apply_cc_arg(&mut parsed, &mut depinfo, &arg);
                idx += arg.consumed;
                continue;
            }

            let arg = &rest[idx];
            if !arg.starts_with('-') && looks_like_source(arg) {
                parsed.sources.push(PathBuf::from(arg));
            }
            idx += 1;
        }
        parsed.depinfo = depinfo;

        Ok(parsed)
    }

    /// Enumerate refuse-to-cache reasons the parsed invocation
    /// triggers. Returns an empty vector for "looks safe to cache".
    ///
    /// Each detection is conservative — we'd rather refuse a
    /// cacheable invocation than miscache an unsafe one. Specific
    /// patterns covered:
    ///
    /// - **Response files** (`@file.rsp`): the actual flags live in
    ///   another file we'd need to read + hash separately.
    /// - **Multi-arch fat binaries** (`-arch x86_64 -arch arm64`):
    ///   output is a single file containing multiple object slices,
    ///   doesn't fit the per-source-per-output model.
    /// - **Coverage instrumentation** (`--coverage`,
    ///   `-fprofile-arcs`, `-ftest-coverage`): coverage tools need
    ///   the original source paths in profraw data; cache hits
    ///   would break coverage mapping.
    /// - **Split DWARF** (`-gsplit-dwarf`): produces a separate
    ///   `.dwo` file alongside the `.o`; output discovery would
    ///   need to know about the pair.
    /// - **Precompiled headers** (`-include-pch`, `-emit-pch`):
    ///   PCHs are non-portable across compiler versions and depend
    ///   on the entire include graph at PCH-build time.
    /// - **Modules** (`-fmodules`, `-fcxx-modules`): module
    ///   compilation has its own dependency model; doesn't fit the
    ///   per-TU cache model.
    /// - **Any flag not classified by [`CC_FLAGS`]**: the cache key
    ///   captures the preprocessor expansion plus the codegen flags
    ///   kache explicitly models (`FlagClass::ModeledInKey`) plus the
    ///   resolved `cc -###` tokens (`FlagClass::CapturedByProbe`). A
    ///   flag whose object-file effect is in none of those — an
    ///   unmodeled codegen flag (`-Ofast`, `-fsanitize=address`),
    ///   profiling (`-pg`), or a flag kache has
    ///   never seen — would miscache. The table is the source of truth;
    ///   anything it does not classify is refused with the offending
    ///   flags named in the reason.
    /// - **Output to stdout** (`-o -`): not a cacheable artifact.
    /// - **Preprocess / Assemble mode**: `-E` and `-S` produce
    ///   developer-facing output that's rarely worth caching and
    ///   tangles with the cc-crate probe pattern.
    pub fn refuse_reasons(&self, extra_allowlist_flags: &[String]) -> Vec<RefuseReason> {
        let mut reasons = Vec::new();

        // ── Non-`-c` mode refusals (short-circuit) ──
        //
        // First, check whether the invocation is the `-c` object
        // compile shape the flag classifier was designed for. If not,
        // the flag-classifier output below ("unsupported flag(s): -E")
        // is misleading — those flags aren't blocking caching of a
        // compile, they belong to a different invocation pattern.
        // Short-circuit to keep the reason list focused.
        //
        // All variants here are `Unsupported` — none of them are
        // conceptually uncacheable. `-E` / `-S` / link / output-to-
        // stdout are all deterministic input-to-output functions; the
        // reason kache doesn't cache them today is engineering
        // priority, not feasibility. Messages include "(not yet
        // supported)" so this is explicit in the bench output and
        // anyone reading `kache report`.
        match self.mode {
            CompileMode::Compile => {}
            CompileMode::Link => reasons.push(RefuseReason::Unsupported(
                "cc link mode (whole-program caching) — not yet",
            )),
            // `-E` writing to a named file is an ordinary single-output
            // compile: the expansion is the artifact, and the key already
            // covers everything that can change it. Writing to stdout would
            // need the entry to carry an output no file holds, so that shape
            // keeps its own refusal and stays countable.
            CompileMode::Preprocess if self.output.is_none() => reasons.push(
                RefuseReason::Unsupported("cc preprocessor mode -E to stdout — not yet"),
            ),
            CompileMode::Preprocess => {}
            CompileMode::Assemble => {
                reasons.push(RefuseReason::Unsupported("cc assembly mode -S — not yet"))
            }
        }

        // Output to stdout — `-o -` is unambiguous; an `-o` followed
        // by a literal `-` arg. Cacheable in principle (cache the
        // stdout bytes); not yet implemented.
        if let Some(output) = &self.output
            && output.as_os_str() == "-"
        {
            reasons.push(RefuseReason::Unsupported("cc output to stdout — not yet"));
        }

        // If a non-`-c` refusal accumulated, return early — running
        // the flag classifier or feature checks would add misleading
        // noise ("unsupported flag(s): -E" when the real cause is
        // "this is preprocessor mode"). The single-source check is NOT
        // short-circuited here: a feature like a response file
        // (`@foo.opts`) appears to the parser as zero sources, and the
        // feature explanation is more useful than the bare symptom.
        if !reasons.is_empty() {
            return reasons;
        }

        if self.requires_compiler_output_semantics() {
            reasons.push(RefuseReason::Unsupported(
                "existing output path requires compiler write semantics — caching not yet supported",
            ));
        }

        // ── Feature refusals ──
        //
        // The invocation IS a single-source object compile, but uses a
        // feature kache doesn't model yet. These are the actionable
        // refusals: adding support would convert future invocations
        // into hits.

        // Multi-pass languages. CUDA and HIP split compilation into
        // host and device passes over the same TU; `__CUDA_ARCH__`
        // differs between them, so one `-E` output cannot safely key
        // the invocation. Fail closed: only overrides known to be
        // single-pass stay cacheable.
        if let Some(language) = &self.language_override
            && !LANGUAGE_OVERRIDE_ALLOWLIST.contains(&language.as_str())
        {
            reasons.push(RefuseReason::Unsupported(
                "cc language override -x outside the single-pass C family — not yet",
            ));
        }

        // CUDA sources are not in SOURCE_EXTENSIONS, so they stay in
        // `rest`; recognizing them here avoids misreporting a
        // CUDA-shaped compile as having no source file.
        let cuda_input = self
            .rest
            .iter()
            .any(|arg| arg.ends_with(".cu") || arg.ends_with(".cuh"));
        if cuda_input {
            reasons.push(RefuseReason::Unsupported(
                "cc CUDA source input (.cu/.cuh) — not yet",
            ));
        }

        // Response files: any arg starting with `@` (typically a
        // path to a file containing additional flags). The flags
        // inside aren't visible to our parser without recursive
        // expansion + path normalization.
        if self.rest.iter().any(|a| a.starts_with('@')) {
            reasons.push(RefuseReason::Unsupported(
                "cc response file @file (expansion) — not yet",
            ));
        }

        // Multi-arch (`-arch X -arch Y` produces a fat binary).
        // Single `-arch` is fine — many cc invocations specify it.
        let arch_count = self.rest.windows(2).filter(|w| w[0] == "-arch").count();
        if arch_count > 1 {
            reasons.push(RefuseReason::Unsupported(
                "cc multi-arch -arch X -arch Y (fat-binary caching) — not yet",
            ));
        }

        // Coverage instrumentation.
        for flag in &["--coverage", "-fprofile-arcs", "-ftest-coverage"] {
            if self.rest.iter().any(|a| a == flag) {
                reasons.push(RefuseReason::Unsupported(
                    "cc coverage instrumentation — not yet",
                ));
                break;
            }
        }

        // Split DWARF (separate .dwo file alongside .o).
        if self.rest.iter().any(|a| a == "-gsplit-dwarf") {
            reasons.push(RefuseReason::Unsupported("cc -gsplit-dwarf — not yet"));
        }

        // Precompiled headers.
        for flag in &["-include-pch", "-emit-pch"] {
            if self.rest.iter().any(|a| a == flag) {
                reasons.push(RefuseReason::Unsupported(
                    "cc precompiled headers — not yet",
                ));
                break;
            }
        }
        // `*.pch` / `*.gch` as a forced-include argument also indicates PCH.
        // All three spellings of the same option have to be checked, or the
        // long forms (modeled `PreprocessorCaptured` for #580) would carry a
        // PCH past a refusal the short form catches.
        let is_pch = |p: &str| p.ends_with(".pch") || p.ends_with(".gch");
        let mut iter = self.rest.iter().peekable();
        while let Some(arg) = iter.next() {
            let pch = match arg.strip_prefix("--include=") {
                Some(value) => is_pch(value),
                None => {
                    (arg == "-include" || arg == "--include")
                        && iter.peek().is_some_and(|next| is_pch(next))
                }
            };
            if pch {
                reasons.push(RefuseReason::Unsupported(
                    "cc precompiled headers — not yet",
                ));
                break;
            }
        }

        // Modules (clang/gcc).
        for flag in &["-fmodules", "-fcxx-modules"] {
            if self.rest.iter().any(|a| a == flag) {
                reasons.push(RefuseReason::Unsupported("cc modules — not yet"));
                break;
            }
        }

        // Classifier gate — the structural safety net.
        //
        // kache's cc cache key captures the preprocessor expansion
        // plus the codegen flags it *explicitly* models (optimization,
        // debug level, `-std`, PIC, target arch) plus the resolved
        // `cc -###` token stream. A flag whose effect is captured by
        // none of those would change the object file WITHOUT changing
        // the key — a silent miscache.
        //
        // [`CC_FLAGS`] declares which flags fall into which category;
        // [`classify_cc_flag`] returns `None` for anything outside the
        // table. Unclassified flags include the genuinely unsafe
        // (`-Ofast`, `-march=native`), the cross-targets (`-target`,
        // `--target=`), profiling (`-pg`), and any flag kache has not
        // yet seen — all force a passthrough. The rejected flags are
        // named in the reason so it is visible which flags blocked
        // caching (and therefore which rows to add to `CC_FLAGS`).
        let rejected = classify_and_trace_cc_flags(self, extra_allowlist_flags);
        if !rejected.is_empty() {
            // Leak a per-invocation summary so it can ride in
            // `RefuseReason::Unsupported(&'static str)`. The wrapper
            // process handles one compile then exits, so the leak is
            // bounded and short-lived.
            let detail: &'static str = Box::leak(
                format!("cc unsupported flag(s): {} — not yet", rejected.join(" "))
                    .into_boxed_str(),
            );
            tracing::debug!("{detail} — passthrough");
            reasons.push(RefuseReason::Unsupported(detail));
        }

        // Single-source contract — last, so feature refusals
        // (response file, PCH-as-input, ...) get a chance to explain
        // *why* there's no parseable single source. Without that
        // ordering, `cc @foo.opts` would land here instead of getting
        // the more specific "response file (@file)" reason.
        //
        // Reported as `Unsupported` with "(not yet supported)" wording:
        // multi-source `cc -c a.c b.c` is conceptually N independent
        // single-source compiles bundled into one invocation —
        // per-source caching is on the roadmap, just unimplemented.
        // Zero-source falls under the same "kache doesn't yet handle
        // this invocation pattern" bucket; a future expansion of
        // response files or improved probe-vs-compile detection would
        // convert most of these.
        if self.sources.len() > 1 {
            reasons.push(RefuseReason::Unsupported(
                "cc multi-source compile (per-source split) — not yet",
            ));
        } else if self.sources.is_empty() && !cuda_input {
            // Suppressed for CUDA inputs: the dedicated refusal above
            // already names the real cause.
            reasons.push(RefuseReason::Unsupported("cc no source file — not yet"));
        }

        reasons
    }

    /// The object file a `-c` compile produces.
    ///
    /// `-o <path>` if explicit; otherwise the compiler default — the
    /// source file's stem with a `.o` (gnu dialect) or `.obj` (cl
    /// dialect) extension, in the current working directory. Returns
    /// `None` only for degenerate invocations with no source (which
    /// `refuse_reasons` already rejects, so callers on the cache path
    /// won't hit `None`).
    pub fn object_output_path(&self) -> Option<PathBuf> {
        if let Some(o) = &self.output {
            return Some(o.clone());
        }
        let stem = self.sources.first()?.file_stem()?;
        let ext = match self.family.dialect() {
            Dialect::Cl => "obj",
            Dialect::Gnu => "o",
        };
        Some(PathBuf::from(format!("{}.{ext}", stem.to_string_lossy())))
    }

    /// The dep-info file a compile produces when `-MD` / `-MMD` is active.
    ///
    /// `-MF <path>` wins. Otherwise gcc/clang derive the depfile from the
    /// object output by replacing its extension with `.d`.
    pub fn depinfo_output_path(&self) -> Option<PathBuf> {
        let depinfo = self.depinfo.as_ref()?;
        if !depinfo.emit {
            return None;
        }
        if let Some(output) = &depinfo.output {
            return Some(output.clone());
        }
        let mut object = self.object_output_path()?;
        object.set_extension("d");
        Some(object)
    }

    /// Every filesystem output selected by a compile-mode invocation.
    ///
    /// Cacheable invocations have one source, but refused multi-source
    /// invocations still need exact passthrough safety checks for each default
    /// object and dep-info path. Non-compile modes deliberately return no
    /// object-shaped paths: `-E foo.c` does not select `foo.o`.
    pub(crate) fn compiler_output_paths(&self) -> Vec<PathBuf> {
        if self.mode != CompileMode::Compile {
            return Vec::new();
        }

        let objects = if let Some(output) = &self.output {
            vec![output.clone()]
        } else {
            let ext = match self.family.dialect() {
                Dialect::Cl => "obj",
                Dialect::Gnu => "o",
            };
            self.sources
                .iter()
                .filter_map(|source| {
                    source
                        .file_stem()
                        .map(|stem| PathBuf::from(format!("{}.{ext}", stem.to_string_lossy())))
                })
                .collect()
        };

        let mut paths = objects.clone();
        if let Some(depinfo) = &self.depinfo
            && depinfo.emit
        {
            if let Some(output) = &depinfo.output {
                paths.push(output.clone());
            } else {
                paths.extend(objects.into_iter().map(|mut object| {
                    object.set_extension("d");
                    object
                }));
            }
        }
        paths
    }

    /// Whether an existing output needs the selected compiler's own path
    /// handling instead of cache materialization.
    ///
    /// Ordinary compiler-owned outputs are private, owner-writable regular
    /// files. Kache may replace those on a hit and let the compiler overwrite
    /// them on a miss. Symlinks, hardlinks, read-only files and non-regular
    /// paths still need the selected compiler's exact pathname semantics.
    pub(crate) fn requires_compiler_output_semantics(&self) -> bool {
        self.compiler_output_paths()
            .into_iter()
            .any(|path| output_path_requires_compiler_semantics(&path))
    }

    /// Anchor used to relativize/expand C/C++ dep-info target paths.
    pub fn depinfo_anchor(&self) -> Option<PathBuf> {
        self.depinfo_output_path()?;
        let object = self.object_output_path()?;
        Some(
            object
                .parent()
                .filter(|p| !p.as_os_str().is_empty())
                .map(Path::to_path_buf)
                .unwrap_or_else(|| PathBuf::from(".")),
        )
    }

    /// Target architecture for cache-key / metadata purposes:
    /// an explicit `-arch X` if present, else the host arch.
    pub fn cache_target_arch(&self) -> String {
        cc_target_arch(self)
    }

    /// True when this clang-cl compile requests debug info that CodeView
    /// records with un-remapped paths. Those objects stay in the local store.
    pub fn embeds_codeview_debug(&self) -> bool {
        cl_debug_present(self)
    }

    /// The subset of `rest` that identifies the *compile configuration*
    /// — per-translation-unit noise removed: source files, the `-o`
    /// output path, and (under the Gnu dialect only) dependency-file
    /// flags (`-MF`/`-MT`/`-MQ`) with their values. Under the Cl dialect
    /// those `-M*` spellings are CRT selection (codegen), so they are
    /// kept. The resolved-invocation probe (`cc -###`) is memoized on
    /// this, so every TU of a build that shares a flag set reuses one
    /// probe record instead of re-resolving per file.
    pub fn config_args(&self) -> Vec<String> {
        let mut out = Vec::new();
        let mut iter = self.rest.iter();
        // Per-TU noise to drop from the probe-memo key. GnuDialect drops
        // the dep-target flags (`-MT`/`-MF`/`-MQ`) and their values; the
        // cl dialect must NOT — there `-MT`/`-MD` are CRT-selection
        // codegen (CapturedByProbe) and stripping them from the memo key
        // would collapse distinct CRTs into one record (false hit, #285).
        let drops_value: &[&str] = match self.family.dialect() {
            Dialect::Gnu => &["-o", "-MF", "-MT", "-MQ"],
            Dialect::Cl => &["-o"],
        };
        while let Some(arg) = iter.next() {
            if drops_value.contains(&arg.as_str()) {
                iter.next(); // also drop the flag's value
            } else if self.family.dialect() == Dialect::Cl
                && (arg.starts_with("-Fo") || arg.starts_with("/Fo"))
            {
                // `-Fo<obj>` / `/Fo<obj>` — concatenated output token,
                // per-TU noise. Strip it from the probe-memo key so the
                // same config with different output paths reuses one probe
                // record. The value is embedded in the token (no next-arg
                // to consume).
            } else if self
                .sources
                .iter()
                .any(|s| s.to_str() == Some(arg.as_str()))
            {
                // source file — per-TU
            } else {
                out.push(arg.clone());
            }
        }
        out
    }
}

pub(crate) fn output_path_requires_compiler_semantics(path: &Path) -> bool {
    match std::fs::symlink_metadata(path) {
        Ok(meta) => !meta.file_type().is_file() || !regular_output_is_replaceable(path, &meta),
        Err(err) => err.kind() != std::io::ErrorKind::NotFound,
    }
}

fn regular_output_is_replaceable(path: &Path, meta: &std::fs::Metadata) -> bool {
    regular_output_is_independent(path, meta) && regular_output_is_owner_writable(meta)
}

fn regular_output_is_owner_writable(meta: &std::fs::Metadata) -> bool {
    if meta.permissions().readonly() {
        return false;
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};

        // SAFETY: geteuid has no arguments, pointers, or preconditions.
        let current_uid = unsafe { libc::geteuid() };
        meta.uid() == current_uid && meta.permissions().mode() & 0o200 != 0
    }

    #[cfg(not(unix))]
    {
        true
    }
}

#[cfg(unix)]
fn regular_output_is_independent(_path: &Path, meta: &std::fs::Metadata) -> bool {
    use std::os::unix::fs::MetadataExt;

    meta.nlink() == 1
}

#[cfg(windows)]
fn regular_output_is_independent_windows(path: &Path, _meta: &std::fs::Metadata) -> bool {
    use std::os::windows::io::AsRawHandle;
    use windows_sys::Win32::Storage::FileSystem::{
        BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
    };

    let Ok(file) = std::fs::File::open(path) else {
        return false;
    };
    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
    let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle() as _, &mut info) };
    ok != 0 && info.nNumberOfLinks == 1
}
#[cfg(windows)]
use self::regular_output_is_independent_windows as regular_output_is_independent;

#[cfg(not(any(unix, windows)))]
fn regular_output_is_independent_unsupported(_path: &Path, _meta: &std::fs::Metadata) -> bool {
    true
}
#[cfg(not(any(unix, windows)))]
use self::regular_output_is_independent_unsupported as regular_output_is_independent;

fn parse_cc_arg_at(args: &[String], idx: usize, dialect: Dialect) -> Option<ParsedCcArg> {
    let arg = args.get(idx)?;
    CC_ARG_SPECS
        .iter()
        .find_map(|spec| parse_cc_arg_with_spec(spec, args, idx, arg, dialect))
}

fn parse_cc_arg_with_spec(
    spec: &'static CcArgSpec,
    args: &[String],
    idx: usize,
    arg: &str,
    dialect: Dialect,
) -> Option<ParsedCcArg> {
    // Skip rows that are restricted to a different dialect (mirrors the
    // classifier's dialect filter in `flags::classify_against`).
    if let Some(d) = spec.dialect
        && d != dialect
    {
        return None;
    }
    match spec.value_form {
        CcArgValueForm::Flag => cc_arg_spec_matches(spec, arg).then_some(ParsedCcArg {
            spec,
            value: None,
            consumed: 1,
        }),
        CcArgValueForm::Separated => cc_arg_spec_matches(spec, arg).then(|| ParsedCcArg {
            spec,
            value: args.get(idx + 1).cloned(),
            consumed: if args.get(idx + 1).is_some() { 2 } else { 1 },
        }),
        CcArgValueForm::Concatenated { prefix } => {
            arg.strip_prefix(prefix).map(|value| ParsedCcArg {
                spec,
                value: Some(value.to_string()),
                consumed: 1,
            })
        }
        CcArgValueForm::CanBeSeparated { prefix } => {
            if arg == prefix {
                Some(ParsedCcArg {
                    spec,
                    value: args.get(idx + 1).cloned(),
                    consumed: if args.get(idx + 1).is_some() { 2 } else { 1 },
                })
            } else {
                arg.strip_prefix(prefix)
                    .filter(|value| !value.is_empty())
                    .map(|value| ParsedCcArg {
                        spec,
                        value: Some(value.to_string()),
                        consumed: 1,
                    })
            }
        }
    }
}

fn cc_arg_spec_matches(spec: &CcArgSpec, arg: &str) -> bool {
    match spec.matcher {
        Matcher::Exact(s) => arg == s,
        Matcher::Prefix(s) => arg.starts_with(s),
        Matcher::Regex(pat) => Regex::new(&format!("^(?:{pat})$"))
            .map(|re| re.is_match(arg))
            .unwrap_or(false),
    }
}

fn apply_cc_arg(parsed: &mut CcArgs, depinfo: &mut Option<DepInfoSpec>, arg: &ParsedCcArg) {
    match arg.spec.action {
        CcArgAction::SetMode(mode) => parsed.mode = mode,
        CcArgAction::SetOutput => {
            if let Some(value) = &arg.value {
                parsed.output = Some(PathBuf::from(value));
            }
        }
        CcArgAction::SetPic => parsed.pic = true,
        CcArgAction::SetDebugLevel(level) => parsed.debug_level = Some(level),
        CcArgAction::SetOptimization(level) => parsed.optimization = Some(level),
        CcArgAction::SetStd => {
            if let Some(value) = &arg.value {
                parsed.std = Some(value.clone());
            }
        }
        CcArgAction::DepIncludeSystem(include_system) => {
            let d = depinfo.get_or_insert_with(DepInfoSpec::default);
            d.emit = true;
            d.include_system = include_system;
        }
        CcArgAction::DepPhonyTargets => {
            let d = depinfo.get_or_insert_with(DepInfoSpec::default);
            d.phony_targets = true;
        }
        CcArgAction::DepMissingGenerated => {
            let d = depinfo.get_or_insert_with(DepInfoSpec::default);
            d.missing_generated = true;
        }
        CcArgAction::DepOutput => {
            if let Some(value) = &arg.value {
                let d = depinfo.get_or_insert_with(DepInfoSpec::default);
                d.output = Some(PathBuf::from(value));
            }
        }
        CcArgAction::DepTarget => {
            if let Some(value) = &arg.value {
                let d = depinfo.get_or_insert_with(DepInfoSpec::default);
                d.target = Some(value.clone());
            }
        }
        CcArgAction::LanguageOverride => {
            if let Some(value) = &arg.value {
                parsed.language_override = Some(value.clone());
            }
        }
        CcArgAction::Include => {
            if let Some(value) = &arg.value {
                parsed.includes.push(PathBuf::from(value));
            }
        }
        CcArgAction::Define => {
            if let Some(value) = &arg.value {
                parsed.defines.push(parse_define(value));
            }
        }
    }
}

/// Cache key schema version for C-family compiles. Bump when the key
/// composition or restored artifact semantics change in a way that
/// could collide with old entries.
///
/// v4: `.pp` dependency sidecars are restored as dep-info and C/C++
/// dep-info path rewriting uses the common source/object root. Older
/// entries may contain machine-local source paths in `.pp` blobs.
///
/// v5: dep-info blobs use an explicit kache sentinel instead of `./`
/// for stored project-root paths. The old marker collided with ordinary
/// make depfile parent paths such as `../foo.h` during restore.
///
/// v6: C/C++ object compiles now inject prefix maps for the common
/// source/build root, not just the compiler CWD, and the preprocessor
/// stdout is normalized with the same maps before hashing. Older
/// entries may embed clone-local paths in `__FILE__`, debug info, or
/// preprocessor-expanded string literals.
///
/// The cc recipe now shares [`crate::cache_key::CACHE_KEY_VERSION`] with
/// the rustc recipe (one number to bump). The `cc_key_version:` label
/// plus disjoint fields keep cc and rustc entries from ever colliding;
/// the shared number just means one bump invalidates both recipes.
// Prefix-map targets are ABSOLUTE, profiler-resolvable spellings rather than
// angle-bracket sentinels (kunobi-ninja/kache#485). Absolute targets stop a
// DWARF consumer composing a relative target onto `DW_AT_comp_dir`, and the
// `<CC_BUILD>` cwd target uses `/proc/self/cwd` on Linux so samply / gdb / perf
// launched from the build directory resolve C/C++ sources through the kernel
// with no configuration (the Bazel trick). The other roots are ancestors of —
// or unrelated to — the cwd, so they get distinct `/kache/*` roots (a debugger
// `source-map`s them, or a future `/proc/self/cwd/..` scheme resolves the
// common-root case; see #485). These strings are also folded into the cc cache
// key, so changing them is covered by the `CACHE_KEY_VERSION` bump.
const CC_ROOT_SENTINEL: &str = "/kache/cc-root";
#[cfg(target_os = "linux")]
const CC_BUILD_SENTINEL: &str = "/proc/self/cwd";
#[cfg(not(target_os = "linux"))]
const CC_BUILD_SENTINEL: &str = "/kache/cc-build";
const CC_SOURCE_SENTINEL: &str = "/kache/cc-source";
/// Stable store-side name for a C/C++ dependency artifact.
///
/// `-MF` accepts arbitrary filenames. Inferring the artifact kind from that
/// filename loses the parser's knowledge for compound or extensionless names
/// such as OpenSSL's `a_bitstr.d.tmp` (kunobi-ninja/kache#655). The restore
/// target always comes from the current parsed invocation, so the cache entry
/// can use one semantic name ending in `.d`. Besides making every future `-MF`
/// spelling restoreable, this keeps pre-fix `.d.tmp` entries untrusted: their
/// old raw name still fails the coverage gate once, is evicted, and is replaced
/// with a normalized entry without a store-wide cache-version bump.
pub(crate) const CC_DEPINFO_STORE_NAME: &str = "__kache_cc_depinfo.d";
/// Target for a user-declared `KACHE_BASE_DIR` (ccache `CCACHE_BASEDIR`
/// analog). Shares the spelling with the rustc `<BASE_DIR>` target (same
/// concept, compiler-independent) and stays distinct from the derived roots so
/// an explicit base dir can't collide with a `/kache/cc-root` subtree.
const CC_BASE_SENTINEL: &str = "/kache/base-dir";
/// Sentinel for the Apple SDK root (issue #78). The resolved `cc -###`
/// tokens embed the SDK path (`-isysroot /…/MacOSX14.2.sdk`,
/// `-internal-isystem /…/usr/include`), which differs across Xcode and
/// Command Line Tools installs and between machines. Stripping it to a
/// sentinel lets two builds with the same SDK *contents* at different
/// paths share a key — differing SDK *contents* still diverge via
/// `compiler_version` and the preprocessor expansion, so this only ever
/// merges keys that would otherwise miss, never miscaches. A distinct
/// sentinel so the SDK can't collide with a project root.
const CC_SDKROOT_SENTINEL: &str = "/kache/sdkroot";

#[derive(Debug, Clone, PartialEq, Eq)]
struct CcPrefixMap {
    from: String,
    to: String,
}

/// Resolve the target architecture for the cache key: an explicit
/// `-arch X` flag if present, else the host arch. (Multi-`-arch` is
/// refused upstream, so at most one value is found here.)
fn cc_target_arch(parsed: &CcArgs) -> String {
    parsed
        .rest
        .windows(2)
        .find(|w| w[0] == "-arch")
        .map(|w| w[1].clone())
        .unwrap_or_else(|| std::env::consts::ARCH.to_string())
}

/// Build the argv for a preprocess-only run, dialect-dependent.
///
/// **Gnu dialect** — the original args with mode/output/dep-info flags
/// stripped and `-E -P` forced:
/// - `-c` / `-S` removed — we force `-E` (preprocess only).
/// - `-o <arg>` removed — preprocessed output must go to stdout, not
///   a file (we capture and hash it).
/// - `-MMD` / `-MD` / `-MF` / `-MT` / `-MQ` / `-MP` / `-MG` removed —
///   dep-info generation is irrelevant to preprocessor *content* and
///   `-MF` would redirect output.
/// - `-E -P` prepended. `-P` suppresses line markers
///   (`# 1 "/abs/path/header.h"`), so the hash captures expanded
///   *content* without leaking machine-local header paths — that's
///   what makes the key portable across machines.
///
/// **Cl dialect** — `/EP` is the MSVC equivalent (preprocess to stdout,
/// no line markers; gnu `-E -P` writes nothing to stdout under clang-cl).
/// Only compile-mode (`-c`/`-S`) and output (`-o`, `-Fo`/`/Fo`) flags are
/// stripped; the `-M*` spellings are CRT-selection codegen in this dialect
/// (they affect `_MT`/`_DLL` defines), so they are KEPT in the expansion.
fn build_preprocess_args(parsed: &CcArgs) -> Vec<String> {
    match parsed.family.dialect() {
        Dialect::Gnu => {
            let mut out = vec!["-E".to_string(), "-P".to_string()];
            let mut iter = parsed.rest.iter();
            while let Some(arg) = iter.next() {
                match arg.as_str() {
                    "-c" | "-S" => {}
                    "-o" | "-MF" | "-MT" | "-MQ" => {
                        iter.next(); // also drop the flag's value
                    }
                    "-MMD" | "-MD" | "-MP" | "-MG" => {}
                    _ => out.push(arg.clone()),
                }
            }
            out
        }
        Dialect::Cl => {
            // `/EP` = preprocess to stdout, no line markers (MSVC
            // equivalent of gnu `-E -P`). Drop compile-mode + output
            // flags; keep preprocessor-affecting flags so the hash
            // reflects them.
            let mut out = vec!["/EP".to_string()];
            let mut iter = parsed.rest.iter();
            while let Some(arg) = iter.next() {
                match arg.as_str() {
                    "-c" | "-S" => {}
                    "-o" => {
                        iter.next();
                    }
                    // Attached output form (`-Fofoo.obj` / `/Fofoo.obj`).
                    // clang-cl build systems use the attached form
                    // exclusively; a space-separated `/Fo obj` would leave
                    // a stray token, but such an invocation refuses before
                    // this point (output flags are unmodeled until Layer 2).
                    _ if arg.starts_with("-Fo") || arg.starts_with("/Fo") => {}
                    _ => out.push(arg.clone()),
                }
            }
            out
        }
    }
}

/// Hash the preprocessor expansion of the translation unit.
///
/// Runs `<cc> -E -P …` (gnu) or `<cc> /EP …` (clang-cl) — see
/// [`build_preprocess_args`] — with `SOURCE_DATE_EPOCH` pinned so the
/// `__DATE__` / `__TIME__` macros expand deterministically (without
/// this the hash would change every second → ~0% hit rate; gcc, clang,
/// and clang-cl all honor it). The expansion includes every `#include`d
/// header transitively, so any header change invalidates the key
/// automatically — no separate dependency tracking needed. Bails (→
/// passthrough) if the preprocessor yields empty stdout.
const CC_PREPROCESS_MEMO_TARGET: &str = "__kache_preprocess_memo";

fn add_preprocess_dep_capture(
    parsed: &CcArgs,
    pp_args: Vec<String>,
    dep_path: &Path,
) -> Vec<String> {
    let path = dep_path
        .to_str()
        .expect("dependency capture is enabled only for UTF-8 temp paths")
        .to_string();
    let extra = match parsed.family.dialect() {
        Dialect::Gnu => vec![
            "-MD".to_string(),
            "-MF".to_string(),
            path,
            "-MT".to_string(),
            CC_PREPROCESS_MEMO_TARGET.to_string(),
        ],
        Dialect::Cl => vec![
            "-Xclang".to_string(),
            "-dependency-file".to_string(),
            "-Xclang".to_string(),
            path,
            "-Xclang".to_string(),
            "-MT".to_string(),
            "-Xclang".to_string(),
            CC_PREPROCESS_MEMO_TARGET.to_string(),
            // clang-cl excludes system headers from dependency output unless
            // this cc1 option is present. A partial header set is never safe
            // for direct-mode reuse.
            "-Xclang".to_string(),
            "-sys-header-deps".to_string(),
        ],
    };
    compose_cc_args(&pp_args, extra)
}

/// Parse the Make dependency rule emitted into the probe's private file.
/// Continuations, escaped spaces/hash/backslashes, and Make's `$$` spelling
/// are decoded. The target may remain user-selected under clang-cl when its
/// earlier forwarded `-MT` wins; only the private output path is authoritative.
/// Any unfamiliar/malformed shape disables memoization.
fn parse_preprocess_dependencies(raw: &str, cwd: &Path) -> Result<Vec<PathBuf>> {
    let bytes = raw.as_bytes();
    let mut logical = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] == b'\\' && bytes.get(index + 1) == Some(&b'\n') {
            logical.push(b' ');
            index = index.saturating_add(2);
        } else if bytes[index] == b'\\'
            && bytes.get(index + 1) == Some(&b'\r')
            && bytes.get(index + 2) == Some(&b'\n')
        {
            logical.push(b' ');
            index = index.saturating_add(3);
        } else {
            logical.push(bytes[index]);
            index = index.saturating_add(1);
        }
    }
    let logical = std::str::from_utf8(&logical).context("cc dependency file is not UTF-8")?;
    let (rule, separator) = logical
        .lines()
        .find_map(|line| {
            line.find(": ")
                .or_else(|| line.find(":\t"))
                .map(|separator| (line, separator))
        })
        .context("cc dependency file has no Make rule")?;
    let dependencies = &rule[separator + 1..];

    let mut paths = Vec::new();
    let mut word = String::new();
    let mut chars = dependencies.chars().peekable();
    while let Some(character) = chars.next() {
        match character {
            '\\' => match chars.peek().copied() {
                Some(next) if matches!(next, ' ' | '\t' | '#' | '\\' | ':') => {
                    word.push(next);
                    chars.next();
                }
                Some(_) => word.push('\\'),
                None => anyhow::bail!("cc dependency rule ends in an escape"),
            },
            '$' if chars.peek() == Some(&'$') => {
                word.push('$');
                chars.next();
            }
            '#' => break,
            whitespace if whitespace.is_whitespace() => {
                if !word.is_empty() {
                    paths.push(PathBuf::from(std::mem::take(&mut word)));
                }
            }
            other => word.push(other),
        }
    }
    if !word.is_empty() {
        paths.push(PathBuf::from(word));
    }
    if paths.is_empty() {
        anyhow::bail!("cc dependency rule contains no inputs");
    }
    for path in &mut paths {
        let text = path.to_string_lossy();
        let bytes = text.as_bytes();
        let windows_absolute = bytes.len() >= 3
            && bytes[0].is_ascii_alphabetic()
            && bytes[1] == b':'
            && matches!(bytes[2], b'/' | b'\\');
        if path.is_relative() && !windows_absolute && !text.starts_with("\\\\") {
            *path = cwd.join(&*path);
        }
    }
    paths.sort();
    paths.dedup();
    Ok(paths)
}

#[derive(Debug)]
struct PreprocessHash {
    hash: String,
    fingerprints: Option<Vec<crate::cache_key::CcPreprocessMemoInput>>,
    /// The expansion spells out a checkout root, so its object does too and
    /// the key is bound to this checkout (see [`hash_cc_expansion`]).
    path_bound: bool,
}

/// The `-E` key probe's argv: the preprocess args plus the same
/// `-ffile-prefix-map` rules the real compile gets.
///
/// With the maps applied, `__FILE__` expands to its sentinel exactly as it
/// will in the object. A checkout root still spelled out in the expansion is
/// then text the compiler copies into the object verbatim, such as a `-D`
/// value or a string in a generated header (kunobi-ninja/kache#1004).
fn key_preprocess_args(parsed: &CcArgs, prefix_maps: &[CcPrefixMap]) -> Vec<String> {
    compose_cc_args(
        &build_preprocess_args(parsed),
        file_prefix_map_args(prefix_maps),
    )
}

#[derive(Debug, PartialEq, Eq)]
struct CcExpansionHash {
    hash: String,
    path_bound: bool,
}

/// Hash a preprocessor expansion for the cc key.
///
/// The probe ran with the compile's prefix maps (see [`key_preprocess_args`]),
/// so any root left in the expansion is one `-ffile-prefix-map` does not
/// rewrite, and the object will carry it. Mapping it to a sentinel would give
/// every checkout the same key for objects that differ. Such an expansion is
/// hashed as it is instead: the key hits in this checkout and misses in every
/// other one. A portable expansion hashes its mapped form, as before.
///
/// A bound hash also folds every mapped root, not only the ones the expansion
/// spells out. `execute` skips the object scan for a bound key, so a root that
/// reaches the object some other way must still separate two checkouts even
/// when the expansion only names a root they share, such as a base dir.
fn hash_cc_expansion(raw: Vec<u8>, prefix_maps: &[CcPrefixMap]) -> CcExpansionHash {
    let mapped = apply_cc_prefix_maps_to_bytes(raw.clone(), prefix_maps);
    if mapped == raw {
        return CcExpansionHash {
            hash: blake3::hash(&mapped).to_hex().to_string(),
            path_bound: false,
        };
    }
    let mut roots: Vec<&str> = prefix_maps
        .iter()
        .map(|map| map.from.as_str())
        .filter(|from| !from.is_empty())
        .collect();
    roots.sort_unstable();
    roots.dedup();
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"kache.cc.path-bound-expansion.v1\0");
    for root in roots {
        hasher.update(root.as_bytes());
        hasher.update(b"\0");
    }
    hasher.update(b"\n");
    hasher.update(&raw);
    CcExpansionHash {
        hash: hasher.finalize().to_hex().to_string(),
        path_bound: true,
    }
}

/// Assembler directives that read another file at assembly time.
const CC_ASSEMBLER_FILE_DIRECTIVES: [&str; 2] = [".incbin", ".include"];

/// Assembler facilities that substitute into their bodies, and so can build a
/// file directive whose name never appears in the expansion (`.\op "\file"`
/// invoked as `emit incbin, payload.bin`, or `.inc\()bin` inside `.rept`).
const CC_ASSEMBLER_MACRO_DIRECTIVES: [&str; 4] = [".macro", ".irp", ".irpc", ".rept"];

/// Why the assembler may read a file the key cannot see, if it may.
///
/// `.incbin` and assembler `.include` run after preprocessing, so no depfile
/// lists what they read: a changed file would be served from the old object
/// (kunobi-ninja/kache#1015). They reach the expansion from `.S` and `.s`
/// sources and from inline `asm` strings in C, where the compiler joins
/// adjacent literals and decodes escapes only after preprocessing. So the
/// expansion is checked as written and as the compiler reads its strings, and
/// an `asm` whose text is computed rather than written is refused outright.
fn cc_assembler_hidden_input(expansion: &[u8]) -> Option<&'static str> {
    if let Some(found) = cc_assembler_text_hidden_input(expansion) {
        return Some(found);
    }
    let literals = cc_string_literals(expansion);
    if literals.computed_asm {
        return Some("asm((...))");
    }
    if literals.named_escape {
        return Some(r"\N{...}");
    }
    cc_assembler_text_hidden_input(&literals.text)
}

/// The first construct in assembler text that may read an unseen file.
///
/// Directives are matched ignoring case, as the assembler does, and must end
/// at a word boundary. A file directive counts when the next non-blank byte
/// opens its operand: a quote, or a backslash for an escaped quote in a C
/// string or a macro argument. That keeps C++ member access such as
/// `opts.include(` out. A macro facility counts when a blank follows it;
/// `.altmacro` and the `\()` separator count anywhere.
fn cc_assembler_text_hidden_input(text: &[u8]) -> Option<&'static str> {
    let file = CC_ASSEMBLER_FILE_DIRECTIVES.into_iter().find(|directive| {
        cc_directive_operands(text, directive.as_bytes()).any(|rest| {
            rest.iter()
                .find(|byte| !matches!(byte, b' ' | b'\t'))
                .is_some_and(|byte| matches!(byte, b'"' | b'\\'))
        })
    });
    file.or_else(|| {
        CC_ASSEMBLER_MACRO_DIRECTIVES.into_iter().find(|directive| {
            cc_directive_operands(text, directive.as_bytes()).any(|rest| {
                rest.first()
                    .is_some_and(|byte| matches!(byte, b' ' | b'\t'))
            })
        })
    })
    .or_else(|| {
        cc_directive_operands(text, b".altmacro")
            .next()
            .map(|_| ".altmacro")
    })
    .or_else(|| {
        text.windows(3)
            .any(|window| window == br"\()")
            .then_some(r"\()")
    })
}

/// String literals in a C or C++ expansion, read the way the compiler reads
/// them after preprocessing.
#[derive(Debug, Default, PartialEq, Eq)]
struct CcStringLiterals {
    /// Each run of adjacent literals joined, escapes decoded, one run per line.
    text: Vec<u8>,
    /// An `asm` whose text is an expression rather than a string literal.
    computed_asm: bool,
    /// A C++23 named escape (`\N{LATIN SMALL LETTER B}`). It can spell any
    /// character, and decoding it would need the Unicode name table.
    named_escape: bool,
}

/// Literal prefixes that open a raw string (`R"delim(...)delim"`).
const CC_RAW_STRING_PREFIXES: [&[u8]; 5] = [b"R", b"u8R", b"uR", b"UR", b"LR"];

/// Encoding prefixes of ordinary string and character literals.
const CC_LITERAL_PREFIXES: [&[u8]; 4] = [b"u8", b"u", b"U", b"L"];

/// Read the string literals in `src`, skipping character literals and numbers
/// so a quote inside them cannot throw the reading out of step. Raw strings
/// are taken as written. Assembly sources are not C; for them the plain text
/// check is the one that counts, and a misreading here can only refuse more.
fn cc_string_literals(src: &[u8]) -> CcStringLiterals {
    let mut literals = CcStringLiterals::default();
    let mut joining = false;
    let mut i = 0;
    while let Some(&byte) = src.get(i) {
        let next = if byte.is_ascii_whitespace() {
            i + 1
        } else if byte == b'/' && matches!(src.get(i + 1), Some(b'*' | b'/')) {
            // Comments only survive a `-C` probe. The compiler reads one as a
            // blank, so literals on either side still join.
            cc_skip_comment(src, i)
        } else {
            cc_read_token(src, i, &mut literals, &mut joining)
        };
        debug_assert!(next > i, "string literal reader must advance");
        i = next;
    }
    literals
}

/// Read the token starting at `i`, which is not a blank or a comment, and
/// return the index after it. String literals are decoded into `literals`;
/// `joining` tracks whether the previous token was one.
fn cc_read_token(
    src: &[u8],
    i: usize,
    literals: &mut CcStringLiterals,
    joining: &mut bool,
) -> usize {
    let word_end = cc_word_end(src, i);
    let word = &src[i..word_end];
    let quote = src.get(word_end).copied();
    let plain = word.is_empty() || CC_LITERAL_PREFIXES.contains(&word);
    let raw_paren = (quote == Some(b'"') && CC_RAW_STRING_PREFIXES.contains(&word))
        .then(|| cc_raw_delimiter(src, word_end))
        .flatten();
    if raw_paren.is_some() || (quote == Some(b'"') && plain) {
        if !*joining {
            literals.text.push(b'\n');
        }
        *joining = true;
        return match raw_paren {
            Some(paren) => cc_read_raw_string(src, word_end, paren, &mut literals.text),
            None => cc_read_string(src, word_end, literals),
        };
    }
    *joining = false;
    if quote == Some(b'\'') && plain {
        return cc_skip_char_literal(src, word_end);
    }
    if word.is_empty() {
        return i + 1;
    }
    if matches!(word, b"asm" | b"__asm" | b"__asm__") && !cc_asm_text_is_literal(src, word_end) {
        literals.computed_asm = true;
    }
    word_end
}

/// End of the identifier or number starting at `start`, or `start` if neither
/// starts there. A number takes C++14 digit separators, whose quote would
/// otherwise read as a character literal.
fn cc_word_end(src: &[u8], start: usize) -> usize {
    let is_word = |byte: &u8| byte.is_ascii_alphanumeric() || *byte == b'_';
    if !src.get(start).is_some_and(is_word) {
        return start;
    }
    let number = src[start].is_ascii_digit();
    let mut i = start;
    while let Some(byte) = src.get(i) {
        let separator = number && *byte == b'\'' && src.get(i + 1).is_some_and(is_word);
        if !is_word(byte) && !separator {
            break;
        }
        let next = i + 1;
        debug_assert!(next > i, "word reader must advance");
        i = next;
    }
    i
}

/// Decode the string literal whose opening quote is at `open` into
/// `literals.text`, and return the index after it. A literal cut off by a
/// newline ends there.
fn cc_read_string(src: &[u8], open: usize, literals: &mut CcStringLiterals) -> usize {
    let mut i = open + 1;
    while let Some(&byte) = src.get(i) {
        let next = match byte {
            b'"' | b'\n' => return i + 1,
            b'\\' => cc_decode_escape(src, i + 1, literals),
            _ => {
                literals.text.push(byte);
                i + 1
            }
        };
        debug_assert!(next > i, "string reader must advance");
        i = next;
    }
    i
}

/// Decode the escape whose letter is at `at` into `literals.text`, returning
/// the index after it. Control escapes other than newline and tab become a
/// blank: the directive check only needs to know that they separate words. A
/// named escape is flagged rather than decoded.
fn cc_decode_escape(src: &[u8], at: usize, literals: &mut CcStringLiterals) -> usize {
    let out = &mut literals.text;
    let digits = |from: usize, max: usize, radix: u32| {
        let len = src[from..]
            .iter()
            .take(max)
            .take_while(|byte| char::from(**byte).is_digit(radix))
            .count();
        let value = src[from..from + len].iter().fold(0u32, |value, byte| {
            value
                .wrapping_mul(radix)
                .wrapping_add(char::from(*byte).to_digit(radix).unwrap_or(0))
        });
        (value, from + len)
    };
    let push_code_point = |out: &mut Vec<u8>, value: u32| {
        let mut utf8 = [0; 4];
        let decoded = char::from_u32(value).unwrap_or(' ');
        out.extend_from_slice(decoded.encode_utf8(&mut utf8).as_bytes());
    };
    let Some(&kind) = src.get(at) else {
        return at;
    };
    // C23 and C++23 delimited escapes: `\x{2e}`, `\o{56}`, `\u{62}`. One
    // without its `}` does not compile, so its object is never stored.
    if matches!(kind, b'x' | b'o' | b'u') && src.get(at + 1) == Some(&b'{') {
        let (value, end) = digits(at + 2, usize::MAX, if kind == b'o' { 8 } else { 16 });
        if kind == b'u' {
            push_code_point(out, value);
        } else {
            out.push(value as u8);
        }
        return end + usize::from(src.get(end) == Some(&b'}'));
    }
    match kind {
        b'x' => {
            let (value, end) = digits(at + 1, usize::MAX, 16);
            out.push(value as u8);
            end
        }
        b'0'..=b'7' => {
            let (value, end) = digits(at, 3, 8);
            out.push(value as u8);
            end
        }
        b'u' | b'U' => {
            let (value, end) = digits(at + 1, if kind == b'u' { 4 } else { 8 }, 16);
            push_code_point(out, value);
            end
        }
        b'n' => {
            out.push(b'\n');
            at + 1
        }
        b't' => {
            out.push(b'\t');
            at + 1
        }
        b'r' | b'f' | b'v' | b'a' | b'b' => {
            out.push(b' ');
            at + 1
        }
        b'N' if src.get(at + 1) == Some(&b'{') => {
            literals.named_escape = true;
            let close = src[at..]
                .iter()
                .position(|byte| matches!(byte, b'}' | b'"' | b'\n'));
            close.map_or(src.len(), |offset| {
                at + offset + usize::from(src[at + offset] == b'}')
            })
        }
        other => {
            out.push(other);
            at + 1
        }
    }
}

/// The offset of the `(` that ends a raw string's delimiter, if the quote at
/// `open` starts a valid one: at most 16 characters, none of them a blank,
/// backslash, parenthesis or quote. Otherwise the prefix is an identifier and
/// the quote opens an ordinary string, as the compiler would read it.
fn cc_raw_delimiter(src: &[u8], open: usize) -> Option<usize> {
    let body = src.get(open + 1..)?;
    let paren = body.iter().take(17).position(|byte| *byte == b'(')?;
    body[..paren]
        .iter()
        .all(|byte| !byte.is_ascii_whitespace() && !matches!(byte, b'\\' | b')' | b'"'))
        .then_some(paren)
}

/// Copy the raw string whose opening quote is at `open` and whose delimiter
/// ends at `paren` into `out`, returning the index after it. Its text is
/// taken as written, escapes included.
fn cc_read_raw_string(src: &[u8], open: usize, paren: usize, out: &mut Vec<u8>) -> usize {
    let body = &src[open + 1..];
    let mut close = vec![b')'];
    close.extend_from_slice(&body[..paren]);
    close.push(b'"');
    let text = &body[paren + 1..];
    let len = text
        .windows(close.len())
        .position(|window| window == close.as_slice())
        .unwrap_or(text.len());
    out.extend_from_slice(&text[..len]);
    open + 1 + paren + 1 + len + close.len()
}

/// The index after the character literal whose opening quote is at `open`.
fn cc_skip_char_literal(src: &[u8], open: usize) -> usize {
    let mut i = open + 1;
    while let Some(&byte) = src.get(i) {
        let next = match byte {
            b'\\' => i + 2,
            b'\'' | b'\n' => return i + 1,
            _ => i + 1,
        };
        debug_assert!(next > i, "character literal reader must advance");
        i = next;
    }
    i
}

/// The index after the `/* */` or `//` comment starting at `start`.
fn cc_skip_comment(src: &[u8], start: usize) -> usize {
    let close: &[u8] = if src.get(start + 1) == Some(&b'*') {
        b"*/"
    } else {
        b"\n"
    };
    let rest = start + 2;
    src[rest.min(src.len())..]
        .windows(close.len())
        .position(|window| window == close)
        .map_or(src.len(), |offset| rest + offset + close.len())
}

/// Whether the `asm` keyword ending at `after` takes a written string. Clang
/// accepts a constant expression in its place, which can build any text, so
/// anything else counts as computed. A word not followed by `(` is not an
/// `asm` statement.
fn cc_asm_text_is_literal(src: &[u8], after: usize) -> bool {
    let skip_blanks = |mut i: usize| loop {
        let next = if src.get(i).is_some_and(u8::is_ascii_whitespace) {
            i + 1
        } else if src.get(i) == Some(&b'/') && matches!(src.get(i + 1), Some(b'*' | b'/')) {
            cc_skip_comment(src, i)
        } else {
            return i;
        };
        debug_assert!(next > i, "asm reader must advance");
        i = next;
    };
    let mut i = skip_blanks(after);
    loop {
        let end = cc_word_end(src, i);
        match &src[i..end] {
            b"volatile" | b"__volatile__" | b"__volatile" | b"inline" | b"__inline__" | b"goto" => {
                i = skip_blanks(end)
            }
            b"" if src.get(i) == Some(&b'(') => break,
            _ => return true,
        }
    }
    let start = skip_blanks(i + 1);
    let end = cc_word_end(src, start);
    let word = &src[start..end];
    src.get(end) == Some(&b'"')
        && (word.is_empty()
            || CC_LITERAL_PREFIXES.contains(&word)
            || CC_RAW_STRING_PREFIXES.contains(&word))
}

/// The text after each whole-word, case-insensitive occurrence of `name`.
fn cc_directive_operands<'a>(
    expansion: &'a [u8],
    name: &'a [u8],
) -> impl Iterator<Item = &'a [u8]> + 'a {
    expansion
        .iter()
        .enumerate()
        .filter(|(_, byte)| **byte == b'.')
        .filter_map(move |(start, _)| {
            let candidate = expansion.get(start..start + name.len())?;
            if !candidate.eq_ignore_ascii_case(name) {
                return None;
            }
            let rest = &expansion[start + name.len()..];
            let continues_word = rest
                .first()
                .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_');
            (!continues_word).then_some(rest)
        })
}

/// Whether `bytes` contain the raw spelling of any mapped root.
///
/// A plain substring search, unlike [`apply_cc_prefix_maps_to_bytes`]: object
/// files separate strings with NUL bytes, which the configured-root token rule
/// does not treat as a boundary, and a missed root here is a false hit.
fn bytes_embed_mapped_root(bytes: &[u8], prefix_maps: &[CcPrefixMap]) -> bool {
    prefix_maps
        .iter()
        .map(|map| map.from.as_bytes())
        .filter(|from| !from.is_empty())
        .any(|from| {
            bytes
                .iter()
                .enumerate()
                .filter(|(_, byte)| **byte == from[0])
                .any(|(start, _)| bytes[start..].starts_with(from))
        })
}

/// Whether the object at `path` embeds a raw mapped root.
fn cc_object_embeds_mapped_root(path: &Path, prefix_maps: &[CcPrefixMap]) -> std::io::Result<bool> {
    std::fs::read(path).map(|bytes| bytes_embed_mapped_root(&bytes, prefix_maps))
}

/// Why a successful compile's outputs must not be stored, if they must not.
///
/// Only a key bound to this checkout may hold an object that names it.
/// Anything the scan cannot vouch for is not stored either: an object that
/// cannot be read, or outputs with no object to read (`object_embeds_root`
/// returns `None`). With no artifacts there is nothing to store or scan.
fn cc_unsafe_to_store(
    no_artifacts: bool,
    key_path_bound: bool,
    object_embeds_root: impl FnOnce() -> Option<std::io::Result<bool>>,
) -> Option<String> {
    if no_artifacts || key_path_bound {
        return None;
    }
    match object_embeds_root() {
        None => Some("has no object to check for checkout roots".to_string()),
        Some(Ok(false)) => None,
        Some(Ok(true)) => {
            Some("embeds a checkout root the prefix maps did not rewrite".to_string())
        }
        Some(Err(error)) => Some(format!(
            "could not be read to check for checkout roots: {error}"
        )),
    }
}

/// The key cannot see a file the assembler would read (kunobi-ninja/kache#1015).
///
/// Its own type so the wrapper can tell it from other key failures: this TU
/// is unsafe for any cache keyed on the preprocessor output, so it must run
/// the compiler directly rather than through a configured fallback wrapper.
#[derive(Debug)]
pub(crate) struct CcHiddenInput {
    pub(crate) construct: &'static str,
}

impl std::fmt::Display for CcHiddenInput {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // The fixed text leads so one `known_passthrough` prefix in the bench
        // scenarios covers every construct.
        write!(
            f,
            "cc: the assembler may read a file the cache key cannot see (`{}`)",
            self.construct
        )
    }
}

impl std::error::Error for CcHiddenInput {}

fn preprocess_hash(
    parsed: &CcArgs,
    prefix_maps: &[CcPrefixMap],
    file_hasher: &crate::cache_key::FileHasher<'_>,
    capture_dependencies: bool,
) -> Result<PreprocessHash> {
    let pp_args = key_preprocess_args(parsed, prefix_maps);
    let dep_temp = if capture_dependencies {
        match tempfile::Builder::new()
            .prefix("kache-cc-preprocess-")
            .tempdir()
        {
            Ok(temp) => Some(temp),
            Err(error) => {
                tracing::debug!("cc preprocess dependency tempdir unavailable: {error}");
                None
            }
        }
    } else {
        None
    };
    let dep_path = dep_temp
        .as_ref()
        .map(|dir| dir.path().join("inputs.d"))
        .filter(|path| path.to_str().is_some());
    let pp_args = dep_path.as_deref().map_or(pp_args.clone(), |path| {
        add_preprocess_dep_capture(parsed, pp_args.clone(), path)
    });
    let run = |args: &[String]| {
        crate::opcounts::record_preprocessor_run();
        let mut command = Command::new(&parsed.program);
        command.args(args);
        // Pin the build timestamp so `__DATE__` / `__TIME__` expand
        // deterministically. The real compile uses the same value.
        if let Some(epoch) = effective_source_date_epoch() {
            command.env("SOURCE_DATE_EPOCH", epoch);
        }
        command
            .output()
            .with_context(|| format!("running preprocessor `{}`", parsed.program))
    };
    let mut output = run(&pp_args)?;
    if !output.status.success() && dep_path.is_some() {
        // An otherwise supported compiler may not implement the private
        // dependency flags. Preserve the existing cache-key behavior and just
        // leave this invocation unmemoized.
        tracing::debug!("cc preprocess dependency capture failed; retrying without memo capture");
        output = run(&key_preprocess_args(parsed, prefix_maps))?;
    }
    if !output.status.success() {
        // Preprocess failed — the real compile would also fail.
        // Bail so the wrapper falls back to passthrough, which runs
        // the real compiler and surfaces the real diagnostic. Worded as the
        // `uncacheable` passthrough detail, not a failure: often a configure
        // probe that is *meant* to fail.
        anyhow::bail!(
            "cc -E key probe exited {}",
            output
                .status
                .code()
                .map_or_else(|| "by signal".to_string(), |c| c.to_string())
        );
    }
    if output.stdout.is_empty() {
        // Zero preprocessor output: a mis-detected family ran the wrong
        // preprocess flags (gnu `-E -P` under clang-cl writes to a file),
        // or a degenerate empty TU. Either way refuse rather than hash
        // nothing → passthrough.
        anyhow::bail!("cc -E key probe produced no output");
    }
    if let Some(construct) = cc_assembler_hidden_input(&output.stdout) {
        // Refuse before the memo can record this TU: a memo hit skips the
        // probe, and the file the assembler reads is in no fingerprint.
        return Err(CcHiddenInput { construct }.into());
    }
    let CcExpansionHash { hash, path_bound } = hash_cc_expansion(output.stdout, prefix_maps);
    // A path-bound expansion is never memoized. The memo is read from other
    // checkouts through mapped names, and a hit skips the probe that would
    // have noticed the root.
    let fingerprints = dep_path
        .as_deref()
        .filter(|_| !path_bound)
        .and_then(|path| {
            let dependencies = std::fs::read_to_string(path)
                .context("reading cc preprocess dependency file")
                .and_then(|raw| {
                    let cwd = std::env::current_dir().context("reading cc compiler directory")?;
                    parse_preprocess_dependencies(&raw, &cwd)
                });
            match dependencies {
                Ok(paths) => {
                    // Record each input under its prefix-mapped spelling, the form
                    // the expansion above was hashed in. That is what lets another
                    // checkout read the memo: the path a second worktree resolves
                    // an input to differs, the mapped name does not.
                    let mapped: Vec<(String, PathBuf)> = paths
                        .into_iter()
                        .map(|path| (cc_mapped_path(&path, prefix_maps), path))
                        .collect();
                    file_hasher.cc_preprocess_fingerprints(&mapped, &|path| {
                        cc_mapped_content_hash(path, prefix_maps)
                    })
                }
                Err(error) => {
                    tracing::debug!("cc preprocess dependency capture unavailable: {error:#}");
                    None
                }
            }
        });
    Ok(PreprocessHash {
        hash,
        fingerprints,
        path_bound,
    })
}

/// Whether a positional argument looks like a C-family source file
/// (matches one of the recognized extensions in [`SOURCE_EXTENSIONS`]).
/// Conservative: extensionless files or unknown extensions are NOT
/// treated as sources, even if they happen to be C code in practice.
fn looks_like_source(arg: &str) -> bool {
    Path::new(arg)
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| SOURCE_EXTENSIONS.contains(&e))
        .unwrap_or(false)
}

/// Parse a `-D NAME` or `-D NAME=VALUE` argument value.
fn parse_define(s: &str) -> (String, Option<String>) {
    match s.split_once('=') {
        Some((name, value)) => (name.to_string(), Some(value.to_string())),
        None => (s.to_string(), None),
    }
}

/// Cc flag classification table — the declarative source of truth
/// for "how does kache treat this argument?".
///
/// Each row pairs a [`Matcher`] with a [`FlagClass`] and a `source`
/// reference. See [`crate::compiler::flags`] for the matcher /
/// classification vocabulary and for the audit / extensibility
/// guarantees this shape delivers.
///
/// **Adding a flag**: drop a row in the appropriate `class`
/// section, point `source` at the issue / PR that introduced it,
/// and write a test for the new pattern. Done.
///
/// **Reading the table**: `class` answers "why is this safe?".
/// `ModeledInKey` = the parser extracts it into a typed field.
/// `ParserHandled` = the parser routes it to a structural field used
/// for refusal / execution flow rather than object-content keying.
/// `CapturedByProbe` = `cc -###` resolves it into `-cc1` tokens
/// the cache key already hashes. `RawKeyed` = the argument is folded
/// directly into the cache key. `PreprocessorCaptured` = the
/// preprocessor expansion hash subsumes its effect.
/// `NoObjectEffect` = it doesn't change the resulting object.
///
/// **Anything not in the table** is refused with `cc: unsupported
/// flag(s): …` — see [`CcArgs::refuse_reasons`]. The omission is
/// the safety signal: a flag kache has never seen could miscache,
/// so the conservative default is to passthrough.
pub static CC_FLAGS: &[FlagSpec] = &[
    // ── ModeledInKey: parser extracts into a typed field ──
    FlagSpec {
        // `-O` family: bare, digit (`-O0`..`-O3`), `-Os`/`-Oz`, `-Og`.
        // The regex names the family in one row; an out-of-set value
        // (`-Ofast`) deliberately falls through to refusal because the
        // parser doesn't model it. See `CcArgs::parse`.
        matcher: Matcher::Regex(r"-O[0-3sz]?|-Og"),
        class: FlagClass::ModeledInKey,
        source: "PR #94 — opt level. Regex captures family; -Ofast/+others fall through to refuse.",
        dialect: None,
    },
    FlagSpec {
        // `-g` family: bare or with a level digit (`-g0`..`-g3`). The
        // parser extracts the level into `debug_level`. Variants like
        // `-gdwarf-5` / `-ggdb` / `-gline-tables-only` change debug
        // info but aren't modeled, so they're not on this row.
        matcher: Matcher::Regex(r"-g[0-3]?"),
        class: FlagClass::ModeledInKey,
        source: "PR #94 — debug level. Regex captures `-g`/`-g0..3`; -gdwarf-* etc. refuse.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fPIC"),
        class: FlagClass::ModeledInKey,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fpic"),
        class: FlagClass::ModeledInKey,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("-std="),
        class: FlagClass::ModeledInKey,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        // Single `-arch <value>`. The parser sets `cache_target_arch`
        // from the resolved arch; multi-`-arch X -arch Y` is refused
        // separately in the procedural pass of `refuse_reasons`.
        matcher: Matcher::Exact("-arch"),
        class: FlagClass::ModeledInKey,
        source: "PR #94",
        dialect: None,
    },
    // ── ParserHandled: parser routes to structural invocation state ──
    FlagSpec {
        matcher: Matcher::Exact("-c"),
        class: FlagClass::ParserHandled,
        source: "PR #94 — compile mode marker parsed into CompileMode.",
        dialect: None,
    },
    FlagSpec {
        // End-of-options marker. Does not change object bytes; Firefox's
        // Windows clang-cl nightly still refused it as an unclassified flag.
        matcher: Matcher::Exact("--"),
        class: FlagClass::NoObjectEffect,
        source: "Firefox Windows 0.20 nightly — end-of-options marker.",
        dialect: None,
    },
    FlagSpec {
        // MSVC `/c` slash spelling of the compile-mode marker (cl only).
        // The parser already routes `/c` to CompileMode::Compile via
        // CC_ARG_SPECS; this row tells the unsupported-flag classifier the
        // token is known (ParserHandled) so it isn't rejected. Without it,
        // a `/c` clang-cl compile is refused as `unsupported flag(s): /c`
        // (box-confirmed). Mirrors the `-c` row above. (#312)
        matcher: Matcher::Exact("/c"),
        class: FlagClass::ParserHandled,
        source: "Issue #312 — MSVC /c compile-mode marker, cl dialect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-E"),
        class: FlagClass::ParserHandled,
        source: "Flag audit — preprocessor mode marker parsed into CompileMode.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-S"),
        class: FlagClass::ParserHandled,
        source: "Flag audit — assembly mode marker parsed into CompileMode.",
        dialect: None,
    },
    FlagSpec {
        // `--driver-mode=<mode>` selects the driver dialect clang speaks —
        // `cl` turns a plain `clang` into clang-cl (a real cross-/Linux way
        // to get MSVC-driver behavior, and how kache's own Linux e2e drives
        // the clang-cl path). The token is consumed structurally by
        // `ToolFamily::detect`; it carries no object effect of its own, and
        // the dialect's actual codegen/preprocessor consequences are already
        // keyed (the `-E`/`/EP` preprocessor hash sees the MSVC predefined
        // macros, the `-###` probe sees the resolved cc1 line). Without this
        // row every `clang --driver-mode=cl` compile refused on the token
        // itself. Prefix-matched so `=gcc`/`=g++`/`=cpp` are covered too.
        matcher: Matcher::Prefix("--driver-mode="),
        class: FlagClass::ParserHandled,
        source: "Issue #411 — driver-mode selector; consumed by ToolFamily::detect, effects keyed via preprocessor + -### probe.",
        dialect: None,
    },
    // ── CapturedByProbe: `cc -###` resolved tokens differentiate ──
    //
    // Each row's effect on the resulting object is captured by the
    // resolved `cc -###` `-cc1` token stream that the cache key
    // already hashes (see `cache_key`'s `resolved:` tokens). Identical
    // user-facing flags → identical resolved tokens → same key;
    // different values → different tokens → different key. Safety holds
    // only when the probe resolves on the host compiler. If it does
    // not, `cache_key` refuses probe-keyed flags before preprocessing
    // so these rows cannot silently under-key.
    //
    // Initial population sourced from the Firefox/Gecko Darwin
    // baseline (kunobi-ninja/kache#114): ~4,476 single-source compiles
    // per Firefox build that previously passed through unnecessarily.
    FlagSpec {
        matcher: Matcher::Prefix("-mmacosx-version-min="),
        class: FlagClass::CapturedByProbe,
        source: "Issue #114 — Darwin deployment target.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("-fstrict-flex-arrays="),
        class: FlagClass::CapturedByProbe,
        source: "Issue #114 — strict-flex-arrays codegen knob.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("-ffp-contract="),
        class: FlagClass::CapturedByProbe,
        source: "Issue #114 — fp-contract codegen knob.",
        dialect: None,
    },
    FlagSpec {
        // Clang's automatic-variable hardening mode changes generated code and
        // is forwarded verbatim to `-cc1`, so the resolved-token hash safely
        // distinguishes it from the default mode. Keep the row exact on the
        // Firefox-reported spelling; adjacent modes remain fail-closed until
        // there is workload evidence for them.
        matcher: Matcher::Exact("-ftrivial-auto-var-init=pattern"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #849 — Firefox automatic-variable pattern initialization; Apple clang forwards the value to -cc1 verbatim (verified -###).",
        dialect: None,
    },
    // ── Codegen knobs: one sorted stem list, BOTH polarities ──
    //
    // `-f(?:no-)?<stem>` matches `-f<stem>` AND `-fno-<stem>` for every stem
    // below. Each is a codegen knob clang/gcc forward to `-cc1`, so the
    // resolved-token hash captures whichever polarity is passed — both are
    // equally safe (CapturedByProbe; the probe resolves the actual codegen).
    // Listing the STEM once instead of each `-f`/`-fno-` spelling structurally
    // prevents the "modeled one polarity, missed the other" passthrough class
    // that recurred across the nightly benches: `-ftrapping-math` (#422) and
    // `-fomit-frame-pointer` (#426) each slipped through because only the
    // opposite polarity was listed. Add a knob = add one sorted stem; both
    // polarities are then covered, and a stray knob on every TU can't silently
    // void the cache (the #411 class).
    //
    // The matcher is anchored `^(?:…)$` by `cc_arg_spec_matches`, so this never
    // partial-matches a longer flag. Math stems: `-ffast-math` defines
    // `__FAST_MATH__`/`__FINITE_MATH_ONLY__` (seen by the `-E` hash), but its
    // optimizer assumptions (reassociation, no-inf/no-nan, FP contraction) are
    // invisible to `-E` — only the `-cc1` stream captures them, so these are
    // `CapturedByProbe`, not `PreprocessorCaptured`. Verified against
    // `clang -###`. Stems are kept ALPHABETICAL for maintenance.
    FlagSpec {
        matcher: Matcher::Regex(concat!(
            r"-f(?:no-)?(?:",
            "associative-math|asynchronous-unwind-tables|data-sections|fast-math|",
            "finite-math-only|function-sections|math-errno|merge-all-constants|",
            "omit-frame-pointer|reciprocal-math|rounding-math|semantic-interposition|",
            "signaling-nans|signed-zeros|strict-aliasing|trapping-math|",
            "unsafe-math-optimizations|unroll-loops|unwind-tables|wrapv",
            ")",
        )),
        class: FlagClass::CapturedByProbe,
        source: "#114/#245/#418/#422/#426/#580/#856 + 0.20 nightly — codegen knobs, both polarities, resolved into -cc1 tokens. One sorted stem per knob covers -f<stem> AND -fno-<stem> (prevents the missed-polarity passthrough class). unroll-loops / asynchronous-unwind-tables from lance/Firefox passthroughs.",
        dialect: None,
    },
    FlagSpec {
        // `-mrecip=<value>` (x86 reciprocal-estimate codegen). Prefix-matched so
        // `=none`/`=all`/`=default,...` are all covered; the value rides through
        // to `-cc1` so different settings key differently.
        matcher: Matcher::Prefix("-mrecip="),
        class: FlagClass::CapturedByProbe,
        source: "Firefox nightly bench — reciprocal-estimate codegen selector; value forwarded to -cc1 (verified clang -###).",
        dialect: None,
    },
    FlagSpec {
        // `-mno-omit-leaf-frame-pointer` (clang): forces frame pointers for
        // leaf functions too. Current cc-rs emits it when Rust requests
        // forced frame pointers, and in debug-mode tool setup alongside
        // `-fno-omit-frame-pointer` — so it lands on every aws-lc-sys TU of
        // a macOS debug build (#839). Real codegen effect: clang's `-###`
        // resolves it to `-mframe-pointer=all` against the default
        // `-mframe-pointer=non-leaf`, which the resolved-token hash
        // separates. gcc spells the equivalent knob `-momit-leaf-frame-
        // pointer` (opposite default, same `-m` shape); a driver whose
        // `-###` doesn't resolve keeps refusing fail-closed.
        matcher: Matcher::Exact("-mno-omit-leaf-frame-pointer"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #839 — cc-rs forced-frame-pointer flag (aws-lc-sys debug builds); clang -### resolves to -mframe-pointer=all.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-pthread"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #114 — pthread feature switch (also visible via _REENTRANT in preprocessor).",
        dialect: None,
    },
    FlagSpec {
        // Firefox nightly still passed `-fno-stack-protector` through because
        // only `-fstack-protector-strong` was listed. Cover the family
        // (bare / -strong / -all, both polarities); clang forwards the
        // resulting -stack-protector* token to -cc1.
        matcher: Matcher::Regex(r"-f(?:no-)?stack-protector(?:-strong|-all)?"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #114 + Firefox 0.20 nightly — stack-protector family, both polarities.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fstack-clash-protection"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #245 — stack-clash-protection codegen hardening (Firefox).",
        dialect: None,
    },
    // `--param <name>=<value>` / `--param=<name>=<value>` — backend tuning
    // knobs (`ssp-buffer-size`, `max-inline-insns-auto`, …). Real codegen
    // effect under gcc, which forwards the pair verbatim to cc1, so the
    // resolved-token hash separates one value from another. Classifying the
    // flag `CapturedByProbe` also *forces* the probe
    // (`cc_flags_need_resolved_invocation`), and the key bails when it can't
    // resolve — the separated value token is inert on its own, so without
    // that forcing it would under-key. clang accepts the option and drops it
    // before cc1: no token, and no object difference either, so collapsing
    // those keys is correct rather than lossy.
    //
    // aws-lc-sys passes `--param ssp-buffer-size=4` on its 6 jitterentropy
    // TUs (#580). Those live in the same archive as the `--include=` TUs
    // above, so both rows are needed for the `.a` to converge cross-clone.
    FlagSpec {
        matcher: Matcher::Exact("--param"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #580 — aws-lc-sys jitterentropy `--param ssp-buffer-size=4`; gcc forwards the pair to cc1, clang drops it.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("--param="),
        class: FlagClass::CapturedByProbe,
        source: "Issue #580 — joined spelling of --param; value rides through to cc1.",
        dialect: None,
    },
    // `-fsanitize-undefined-strip-path-components=-1` (clang-only). aws-lc-sys
    // 0.44 adds it to the same jitterentropy TUs as the `--param` rows above
    // once a compile probe confirms support (`builder/cc_builder.rs`): Clang's
    // UBSan check metadata at -O0 can embed the full source path, and the
    // option strips leading path components from it. Path metadata rather
    // than codegen, but it still changes object bytes, so it must be keyed —
    // clang forwards the option, value included, verbatim into the resolved
    // `-cc1` line, and the resolved-token hash captures it. Exact-matched on
    // the one observed value: every integer value clang accepts rides through
    // to cc1 (verified `=0`/`=2` on Apple clang 21), so widening is safe when
    // a workload needs it, but `=-1` is the only spelling in evidence and the
    // exact row keeps unobserved values refusing — the `-gdwarf-4` precedent.
    FlagSpec {
        matcher: Matcher::Exact("-fsanitize-undefined-strip-path-components=-1"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #840 — aws-lc-sys 0.44 jitterentropy UBSan path-stripping; Apple clang forwards the value to -cc1 verbatim (verified -###).",
        dialect: None,
    },
    // (math-errno, strict-aliasing, omit-frame-pointer, unwind-tables —
    // #114/#426 — are now covered by the sorted codegen-knob stem list above,
    // both polarities.)
    // `-ffile-reproducible` / `-fno-file-reproducible` (clang). Firefox's
    // Windows build passes `-ffile-reproducible` (it also `-Werror`-probes
    // for it — see `clang_cl_invocation_injects_no_flags_issue_299`). The
    // flag controls how clang renders embedded paths (`__FILE__`, debug
    // info) for reproducibility; clang forwards it to `-cc1`, so its full
    // effect is captured by the resolved-token hash. `CapturedByProbe`,
    // not `NoObjectEffect`: it can change object bytes (the `__FILE__`
    // path separator), so it must be keyed. Dialect-agnostic — the flag is
    // gnu-spelled and accepted by both the default driver and clang-cl;
    // under a driver whose `-###` doesn't resolve, the probe contract
    // refuses rather than under-keys. (Issue #411 — Firefox/Windows.)
    FlagSpec {
        matcher: Matcher::Exact("-ffile-reproducible"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #411 — clang reproducible embedded paths; keyed via -### resolved tokens.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fno-file-reproducible"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #411 — clang reproducible embedded paths (negation); keyed via -### resolved tokens.",
        dialect: None,
    },
    // Firefox debug-info & clang argument-wrapper flags
    // (kunobi-ninja/kache#117). The debug-info flags affect DWARF
    // sections of the object; clang's `-###` expands them into
    // `-cc1 -dwarf-version=4` / `-dwarf-linkage-names=Abstract` / etc.,
    // so the resolved-tokens hash differentiates them per-value.
    //
    // The DWARF version digit is *not* wildcarded on purpose:
    // `-gdwarf-5` produces a different (larger, newer-toolchain-
    // dependent) object and isn't part of any observed evidence. Each
    // version is listed exactly as workloads surface it; the probe's
    // resolved `-dwarf-version=N` token keeps the keys distinct.
    FlagSpec {
        matcher: Matcher::Exact("-gdwarf-4"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #117 — DWARF v4 emission (Firefox baseline).",
        dialect: None,
    },
    // cc-rs selects `-gdwarf-2` for every Apple target when debug info is
    // enabled, so every Rust workspace with native deps hits this on macOS
    // debug/test profiles (aws-lc-sys was the sampled root).
    FlagSpec {
        matcher: Matcher::Exact("-gdwarf-2"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #838 — DWARF v2 emission; cc-rs default on Apple targets.",
        dialect: None,
    },
    // ring's Darwin build.rs requires full debug information so Apple's
    // dead strip can see which symbols are used. Apple clang's `-###`
    // resolves `-gfull` to `-debug-info-kind=standalone -dwarf-version=5`,
    // the same cc1 tokens as ordinary `-g` on that compiler; a no-debug
    // invocation has neither. Exact, not a `-g*` prefix: neighbouring
    // Apple spellings such as `-gused` stay refused until a workload
    // needs them. (Issue #857)
    FlagSpec {
        matcher: Matcher::Exact("-gfull"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #857 — Darwin full debug info; ring 0.17 dead-strip contract. Apple clang -### resolves it to standalone DWARF; keyed via those tokens.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-gsimple-template-names"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #117 — clang template-name compression in debug info.",
        dialect: None,
    },
    FlagSpec {
        // `-mllvm=` passes through to LLVM. Different `-mllvm`
        // values can do arbitrary codegen things, so a `Prefix("-mllvm=")`
        // wildcard would silently accept unmodeled codegen flags. List
        // specific values that workloads need; `-Mllvm=…` etc. still
        // refuse.
        matcher: Matcher::Exact("-mllvm=-dwarf-linkage-names=Abstract"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #117 — LLVM debug-info abstraction (Firefox baseline). Listed by exact value rather than `-mllvm=*` wildcard so unmodeled LLVM flags still refuse.",
        dialect: None,
    },
    // Compiler path-remapping flags: `-ffile-prefix-map` (= `-fdebug-prefix-map`
    // + `-fmacro-prefix-map`). Build systems pass these to make the OBJECT
    // path-portable — e.g. Firefox's `--enable-path-remapping` emits
    // `-fdebug-prefix-map=<objdir>=/topobjdir/`, a `<srcdir>` map, and an SDK
    // map. Each is `<flag>=<from>=<to>`. Clang's `-###` captures them in the
    // resolved invocation, and kache normalizes every resolved token through
    // its own cc prefix maps before hashing — so a per-checkout `<from>`
    // (the objdir/srcdir) collapses to a sentinel (two clones → one key),
    // while a genuinely different `<to>`, or an unrelated `<from>` like the
    // SDK path (identical across clones), still differentiates correctly.
    //
    // Without these rows the entire compile refused ("unsupported flag(s):
    // -fdebug-prefix-map=…"), so a build enabling its OWN path remapping
    // silently disabled all cc caching (kunobi-ninja/kache: Firefox bench saw
    // 4090+ TUs pass through uncached). `CapturedByProbe`, not
    // `CapturedByPreprocessor`: `-fdebug-prefix-map` only rewrites debug-info
    // paths in the object (not the preprocessed text), so the preprocessor
    // hash would under-key it — the resolved `-###` token stream is what
    // captures the flag's full effect.
    FlagSpec {
        matcher: Matcher::Prefix("-ffile-prefix-map="),
        class: FlagClass::CapturedByProbe,
        source: "Build-system path remapping (e.g. Firefox --enable-path-remapping). Resolved-token hash captures it; per-checkout `from` normalized via cc prefix maps.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("-fdebug-prefix-map="),
        class: FlagClass::CapturedByProbe,
        source: "Build-system debug-info path remapping. Resolved-token hash captures it; per-checkout `from` normalized via cc prefix maps.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("-fmacro-prefix-map="),
        class: FlagClass::CapturedByProbe,
        source: "Build-system __FILE__ path remapping. Resolved-token hash captures it; per-checkout `from` normalized via cc prefix maps.",
        dialect: None,
    },
    FlagSpec {
        // `aws-lc-sys` passes this spelling for assembler sources because
        // `-fdebug-prefix-map` does not reach GNU as. GCC's `-###` output puts
        // it only on the separate `as` subprocess, while kache's probe hashes
        // the `cc1`/`cc1plus` subprocess. Key it directly rather than claiming
        // it is probe-captured. The anchored regex admits exactly one `-Wa`
        // sub-option: GCC splits commas into additional assembler arguments,
        // which must remain unsupported until modeled separately.
        matcher: Matcher::Regex(r"-Wa,--debug-prefix-map=[^,=]+=[^,]*"),
        class: FlagClass::RawKeyed,
        source: "Issue #644 — GNU assembler debug path remapping; raw-keyed because the cc1 probe omits the separate assembler subprocess.",
        dialect: Some(Dialect::Gnu),
    },
    // C++ ABI, RTTI, and exception flags (kunobi-ninja/kache#116).
    // Each row affects the resulting object materially — `-fno-rtti`
    // omits RTTI tables, `-fno-exceptions` skips exception-handling
    // tables, `-stdlib=libc++` vs `libstdc++` selects a different C++
    // standard library with different ABI defaults. Clang's `-###`
    // captures all of them in the resolved `-cc1` invocation, so the
    // cache key differentiates per-value via the resolved-tokens hash.
    //
    // Both the positive and negative forms are listed (`-frtti` /
    // `-fno-rtti`, `-fexceptions` / `-fno-exceptions`) because a build
    // may explicitly request either mode — they're conflicting and the
    // cache must distinguish them, which is automatic via the probe.
    FlagSpec {
        // `-stdlib=libc++` (clang default on macOS), `-stdlib=libstdc++`
        // (typical on Linux). Values are a small fixed set; the probe
        // resolves each into a distinct `-cc1` form.
        matcher: Matcher::Prefix("-stdlib="),
        class: FlagClass::CapturedByProbe,
        source: "Issue #116 — C++ standard-library selector (libc++ / libstdc++).",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fno-exceptions"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #116 — C++ exception mode (off).",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fexceptions"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #116 — C++ exception mode (on).",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fno-rtti"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #116 — C++ RTTI mode (off).",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-frtti"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #116 — C++ RTTI mode (on).",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fno-sized-deallocation"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #116 — C++ sized-deallocation (disabled).",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fno-aligned-new"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #116 — C++ aligned new/delete (disabled).",
        dialect: None,
    },
    // ELF symbol-visibility defaults (Firefox bench evidence, post-#146).
    // `-fvisibility=hidden` and `-fvisibility-inlines-hidden` are pure-
    // codegen knobs that change the object's exported symbol table; same
    // source + same flag pair → same object bytes. Clang's `cc -###`
    // resolves each into a distinct `-cc1 -fvisibility hidden` /
    // `-fvisibility-inlines-hidden` token, so the resolved-tokens hash
    // differentiates them. Single highest-volume passthrough on a
    // Firefox warm build: 2987 of 3475 refused compiles came from this
    // pair (86% of the cc passthrough wall).
    //
    // Listed by `Exact` value (not `Prefix("-fvisibility=")`) so
    // unmodeled visibility modes (`default`, `protected`, `internal`)
    // still refuse — same conservative convention as the #116 cluster.
    FlagSpec {
        matcher: Matcher::Exact("-fvisibility=hidden"),
        class: FlagClass::CapturedByProbe,
        source: "Firefox bench evidence (post-#146) — symbol visibility default = hidden.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fvisibility-inlines-hidden"),
        class: FlagClass::CapturedByProbe,
        source: "Firefox bench evidence (post-#146) — inline-function visibility default = hidden.",
        dialect: None,
    },
    // (`-f[no-]semantic-interposition` — the SINGLE flag that degraded the first
    // LLVM CMake/Ninja bench to a 0% hit rate, on every Release TU — is now in
    // the sorted codegen-knob stem list above, both polarities.)
    // Target / arch / WASM / ObjC / section flags
    // (kunobi-ninja/kache#115). Each row affects the resulting object
    // materially — `--target=` changes the entire output architecture,
    // `-march=` picks a CPU baseline, `-msimd128` enables WASM SIMD,
    // section flags reshape the object layout. Clang's `cc -###`
    // resolves each into the `-cc1` token stream (target triple,
    // target-cpu, target-feature list, language mode, section options),
    // so the resolved-tokens hash differentiates per-value and a
    // cross-target hit can't serve a foreign object.
    //
    // These flags were previously in the refuse-list (catch-all "would
    // serve a foreign object" guard); the explicit classification
    // makes them safe via the probe, with the boundary tests pinning
    // adjacent / unmodeled cases.
    FlagSpec {
        // Sticky `--target=arm64-apple-macosx` / `--target=wasm32-wasi`
        // / `--target=aarch64-linux-gnu`. The probe resolves the
        // triple into a `-cc1 -triple <value>` token, so different
        // targets produce different keys.
        matcher: Matcher::Prefix("--target="),
        class: FlagClass::CapturedByProbe,
        source: "Issue #115 — cross-compilation target triple (sticky form).",
        dialect: None,
    },
    FlagSpec {
        // Separate-arg form: `-target <triple>`. The value classifies
        // as a positional (no leading `-`), so this row only needs to
        // accept the flag itself.
        matcher: Matcher::Exact("-target"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #115 — cross-compilation target triple (separate-arg form).",
        dialect: None,
    },
    FlagSpec {
        // `-march=` family: `native`, `armv8-a`, `armv8.2-a+dotprod`,
        // `armv8.2-a+i8mm`, etc. The probe captures the resolved
        // `-target-cpu` and `-target-feature` list, so `native` on
        // host A vs host B produces different keys (correct: they're
        // different objects).
        matcher: Matcher::Prefix("-march="),
        class: FlagClass::CapturedByProbe,
        source: "Issue #115 — architecture selection. `Prefix` is safe because the probe resolves the value into target-cpu/target-feature tokens.",
        dialect: None,
    },
    // ── Cross-target ABI / ISA-state selectors (issue #823) ──
    //
    // The Rust `cc` crate injects these on its own for cross targets:
    // `-mabi=` (riscv), `-mfloat-abi=` + `-mfpu=` (arm), `-mthumb` (thumbv*)
    // — so refusing any one of them makes every cross-compiled C TU on that
    // architecture uncacheable, not just hand-written invocations.
    //
    // Each is `RawKeyed`, deliberately NOT `CapturedByProbe` like their
    // `-march=` neighbour. Every value in these sets is a closed enumeration
    // with no host-relative member (there is no `-mabi=native` the way
    // `-mtune=`/`-mcpu=` have one), so the flag text alone determines the
    // object — the exact property a verbatim fold keys. Clang does lower
    // them into the resolved cc1 line (verified: `-### --target=
    // riscv64-unknown-linux-gnu -mabi=lp64d` yields `"-target-abi" "lp64d"`
    // against `"lp64"` for `-mabi=lp64`), so the probe would key them on
    // clang — but probe-captured soundness would rest on every supported
    // driver spelling the effect into that line, and a driver that omitted
    // it would serve one ABI's object to the other: a broken binary, not a
    // missed hit. The verbatim fold cannot do that.
    FlagSpec {
        // Target ABI: `lp64d`/`lp64`/`ilp32` on riscv, `ms`/`sysv` on
        // x86-64, `aapcs-linux` on arm.
        matcher: Matcher::Prefix("-mabi="),
        class: FlagClass::RawKeyed,
        source: "Issue #823 — target ABI selection; closed value set, keyed verbatim.",
        dialect: None,
    },
    FlagSpec {
        // Float ABI: `soft` / `softfp` / `hard`. cc-rs injects
        // `-mfloat-abi=hard` for every *eabihf target.
        matcher: Matcher::Prefix("-mfloat-abi="),
        class: FlagClass::RawKeyed,
        source: "Issue #823 — arm float ABI; closed value set (soft/softfp/hard), keyed verbatim.",
        dialect: None,
    },
    FlagSpec {
        // Code model: `tiny`/`small`/`kernel`/`medium`/`large` (x86,
        // aarch64), `medlow`/`medany` (riscv). Common in riscv firmware
        // and kernel builds.
        matcher: Matcher::Prefix("-mcmodel="),
        class: FlagClass::RawKeyed,
        source: "Issue #823 — code model; closed value set, keyed verbatim.",
        dialect: None,
    },
    FlagSpec {
        // Concrete arm FPU names — the standardized set gcc and clang
        // both document. cc-rs injects `vfpv3-d16` / `vfp` / `neon`.
        //
        // `-mfpu=auto` is DELIBERATELY not matched and keeps refusing: it
        // resolves from `-march`/`-mcpu` (and the toolchain's configured
        // default when those are absent) inside cc1, so its text does not
        // determine the object, and gcc's driver passes the literal `auto`
        // to cc1 — the probe cannot capture the resolution either.
        matcher: Matcher::Regex(
            r"-mfpu=(?:none|vfp|vfpv2|vfpv3(?:-fp16|-d16(?:-fp16)?|xd(?:-fp16)?)?|vfpv4(?:-d16)?|fpv4-sp-d16|fpv5-(?:sp-)?d16|fp-armv8(?:-fullfp16)?|neon(?:-fp16|-vfpv3|-vfpv4|-fp-armv8)?|crypto-neon-fp-armv8)",
        ),
        class: FlagClass::RawKeyed,
        source: "Issue #823 — concrete arm FPU selection; enumerated so `-mfpu=auto` (resolved inside cc1, not text-deterministic) still refuses.",
        dialect: None,
    },
    FlagSpec {
        // Instruction-set state: Thumb vs ARM encoding, both polarities —
        // conflicting occurrences are last-one-wins, which the raw fold
        // preserves because it hashes in argv order with duplicates kept.
        // Valueless and text-deterministic; cc-rs injects `-mthumb` for
        // thumbv* targets.
        matcher: Matcher::Regex(r"-m(?:(?:no-)?thumb|arm)"),
        class: FlagClass::RawKeyed,
        source: "Issue #823 — arm/thumb instruction-set state, keyed verbatim in argv order.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-msimd128"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #115 — WASM SIMD128 enable.",
        dialect: None,
    },
    FlagSpec {
        // x86 width / SIMD / ISA feature flags seen in Firefox passthroughs
        // (#375, extended). These materially change the object by selecting the
        // target width or enabled ISA features. The resolved `cc -###` stream
        // records the resulting target triple / `-target-feature` set, so the
        // cache key differentiates each value (and a `-mno-` form flips it).
        // The nightly Firefox bench passed media/codec TUs through on
        // `-mavx -mbmi2 -mf16c`; the set below covers the x86 codec ISA family
        // (libvpx/dav1d/aom). Enumerated explicitly (with optional `no-`)
        // rather than opening `-m*`, so the remaining value-taking knobs
        // (`-mtune=`, `-mcpu=`, `-mcmodel=`) and unmodeled `-m` flags still
        // refuse. `-mabi=` is modeled separately above.
        matcher: Matcher::Regex(
            r"^-m(?:no-)?(?:32|64|mmx|sse|sse2|sse3|ssse3|sse4|sse4\.1|sse4\.2|sse4a|avx|avx2|avxvnni|avx512[a-z0-9]+|fma|fma4|f16c|bmi|bmi2|abm|popcnt|lzcnt|aes|vaes|pclmul|vpclmulqdq|gfni|sha|movbe|rdrnd|rdseed|adx|fsgsbase|xsave|xsaveopt|xsavec|xsaves|prfchw|clflushopt|clwb|cldemote|fxsr)$",
        ),
        class: FlagClass::CapturedByProbe,
        source: "Issue #375 (extended, Firefox nightly bench) — x86 width + SIMD/ISA codec feature flags; resolved into target-cpu/target-feature tokens.",
        dialect: None,
    },
    // (`-f[no-]function-sections` / `-f[no-]data-sections` — #115 — are now in
    // the sorted codegen-knob stem list above, both polarities.)
    FlagSpec {
        // `-Wa,*` passes through to the assembler. Different `-Wa,*`
        // values do arbitrary assembler things — listed as `Exact` for
        // the specific Firefox value (per #115's evidence) so a wildcard
        // `Prefix("-Wa,")` doesn't silently accept unmodeled assembler
        // flags. `--noexecstack` sets a section flag on the object.
        matcher: Matcher::Exact("-Wa,--noexecstack"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #115 — assembler: non-executable stack section flag. Listed by exact value rather than `-Wa,*` wildcard so unmodeled assembler flags still refuse.",
        dialect: None,
    },
    FlagSpec {
        // Separate-arg form: `-x <lang>`. Value is positional. The
        // probe resolves the language mode into the `-cc1` invocation.
        matcher: Matcher::Exact("-x"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #115 — language override (separate-arg form).",
        dialect: None,
    },
    FlagSpec {
        // Sticky language override forms. The parser records the
        // language for invocation shape, and the probe resolves the
        // language mode into the `-cc1` invocation. One regex row
        // covers the sticky forms while `-x <lang>` stays an exact
        // row because its language value is a separate argv token.
        matcher: Matcher::Regex(r"-x(?:c|c\+\+|objective-c|objective-c\+\+)"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #115 / flag audit — sticky language override forms.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fobjc-exceptions"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #115 — Objective-C exception model.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fobjc-arc"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #115 — Objective-C ARC mode.",
        dialect: None,
    },
    // ── PreprocessorCaptured: cc -E -P expansion hash subsumes effect ──
    FlagSpec {
        matcher: Matcher::Prefix("-D"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("-U"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("-I"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("--sysroot"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-include"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    // `--include=<file>` / `--include <file>` — the long spellings of
    // `-include`. Same forced-include semantics, so the header's bytes land
    // in the `-E` expansion the key already hashes. `Prefix("--include=")`
    // (not a bare `--include` prefix) so the neighbouring `--include-*`
    // options (`--include-directory=`, `--include-with-prefix=`, …) keep
    // refusing until they are modeled on their own terms.
    //
    // aws-lc-sys drives its BoringSSL symbol-prefixing through the `=` form
    // (`builder/cc_builder.rs`: `--include=` for non-cl, `/FI` for cl), so
    // before this row 56 of its TUs passed through uncached, the `.a`
    // diverged per checkout, and the `extern:` content hash re-keyed the
    // whole rustls/TLS subtree above it (#580).
    FlagSpec {
        matcher: Matcher::Prefix("--include="),
        class: FlagClass::PreprocessorCaptured,
        source: "Issue #580 — aws-lc-sys boringssl_prefix_symbols forced include; `=` form of -include.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("--include"),
        class: FlagClass::PreprocessorCaptured,
        source: "Issue #580 — separated form of --include=<file>.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-imacros"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-isystem"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-iquote"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-idirafter"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-isysroot"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-nostdinc"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-nostdinc++"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-undef"),
        class: FlagClass::PreprocessorCaptured,
        source: "PR #94",
        dialect: None,
    },
    // ── NoObjectEffect: diagnostics / dep-info / build mechanics ──
    //
    // Outcome gates come FIRST: classification is first-match, so the
    // `-Werror` / `-pedantic-errors` rows below must precede the general
    // diagnostics rows they would otherwise be shadowed by.
    FlagSpec {
        // `-Werror[=spec]` and `-Wno-error[=spec]`: escalate (or de-escalate)
        // warnings into/out of hard errors. They cannot change the object
        // bytes of a *successful* compile, but they change whether the
        // compile succeeds at all — and a hit replays success. Two
        // invocations differing only here must not share a key: an entry
        // stored under `-Wno-error=foo` must not serve green to a `-Werror`
        // build that `foo` should have failed (review finding #2). Both
        // spellings are RawKeyed so any combination keys distinctly.
        //
        // The tail is deliberately open-ended: every spelling that starts
        // `-Werror` / `-Wno-error` is about turning diagnostics into errors,
        // including the dashed legacy aliases GCC and clang still accept
        // (`-Werror-implicit-function-declaration`). Keying one of these
        // unnecessarily would only cost a hit; missing one serves a green
        // hit to a build that should have failed, so the row errs wide.
        matcher: Matcher::Regex(r"-W(no-)?error.*"),
        class: FlagClass::RawKeyed,
        source: "review #2 — outcome gate: -Werror/-Wno-error change success vs failure; keyed verbatim.",
        dialect: None,
    },
    FlagSpec {
        // `-pedantic-errors` is the error-flavored member of the -pedantic
        // family: unlike plain `-pedantic` (diagnostics-only) it makes
        // non-conforming code fail to compile. Keyed for the same reason as
        // `-Werror` above; the plain `-pedantic` prefix row further down
        // keeps its NoObjectEffect treatment.
        matcher: Matcher::Exact("-pedantic-errors"),
        class: FlagClass::RawKeyed,
        source: "review #2 — outcome gate: -pedantic-errors changes success vs failure.",
        dialect: None,
    },
    FlagSpec {
        // `-W*` warnings — the remaining, genuinely diagnostics-only
        // warning flags (`-Werror`/`-Wno-error` are keyed above). The
        // regex EXCLUDES `-Wl,*` / `-Wa,*` / `-Wp,*` (linker /
        // assembler / preprocessor passthrough forms that change the
        // resulting object); they need separate handling and aren't
        // covered here.
        matcher: Matcher::Regex(r"-W[^,]*"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94 — warnings. Regex excludes `-Wl,*`/`-Wa,*`/`-Wp,*` passthrough forms.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-w"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("-pedantic"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Prefix("-fdiagnostics-"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fcolor-diagnostics"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-fno-color-diagnostics"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        // Forces ANSI color escapes in diagnostics regardless of TTY
        // detection — terminal coloring only, no object effect. A real
        // clang driver flag in both dialects (Firefox's Windows clang-cl
        // build passes it bare, not just `-Xclang` forwarded as #411
        // covered), with no clang-cl spelling collision. Same family as
        // `-fcolor-diagnostics` above. Re-added after #430's codegen-knob
        // refactor dropped it (issue #438; originally #425/#424).
        matcher: Matcher::Exact("-fansi-escape-codes"),
        class: FlagClass::NoObjectEffect,
        source: "Issue #424/#438 — Firefox/Windows bare diagnostics flag; ANSI color escapes only, no object effect.",
        dialect: None,
    },
    FlagSpec {
        // Dep-info generation: -MD, -MMD, -MF, -MT, -MQ, -MP, -MG.
        // All write the `.d` sidecar; none affect the object. Regex
        // captures the family; alternatives are equally tight in this
        // table layout but the row stays declarative this way.
        matcher: Matcher::Regex(r"-MM?D|-M[FTQPG]"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94 — gcc dep-info flags. Gnu-dialect ONLY: in cl mode -MD/-MT/-MTd/-MDd are CRT selection (codegen), -MP is multi-process; they must not classify as inert dep-info (issue #285).",
        dialect: Some(Dialect::Gnu),
    },
    FlagSpec {
        matcher: Matcher::Exact("-o"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-P"),
        class: FlagClass::NoObjectEffect,
        source: "Flag audit — preprocessor line-marker suppression has no compile-mode object effect.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-pipe"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        // `-fno-lto` on a `-c` compile is a no-op: LTO is off by default, so the
        // object is native code either way — `clang -###` resolves IDENTICAL
        // `-cc1` tokens with and without it (verified). Firefox passes it
        // defensively per-TU and the nightly bench passed those TUs through.
        // `NoObjectEffect` (drop from key) is correct and honest here. The
        // positive forms — `-flto` / `-flto=thin` / `-ffat-lto-objects` — DO
        // change the output (LLVM bitcode) and stay unmodeled/refused, so the
        // dangerous `-flto -fno-lto` combination still passes through (the
        // unmodeled `-flto` refuses) rather than silently sharing this key.
        matcher: Matcher::Exact("-fno-lto"),
        class: FlagClass::NoObjectEffect,
        source: "Firefox nightly bench — explicit non-LTO `-c` compile; identical -cc1 tokens vs absent (verified clang -###). -flto/-flto=* stay refused.",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("-v"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("--verbose"),
        class: FlagClass::NoObjectEffect,
        source: "PR #94",
        dialect: None,
    },
    // Clang argument-wrapper flags (kunobi-ninja/kache#117). These
    // bracket a section of the command line where clang suppresses
    // unused-argument warnings; they only affect diagnostics, never
    // the resulting object. Listed as `Exact` (not a paired/regional
    // matcher) because each flag classifies independently for caching
    // purposes — kache doesn't care whether they appear together.
    FlagSpec {
        matcher: Matcher::Exact("--start-no-unused-arguments"),
        class: FlagClass::NoObjectEffect,
        source: "Issue #117 — clang unused-argument warning region (open).",
        dialect: None,
    },
    FlagSpec {
        matcher: Matcher::Exact("--end-no-unused-arguments"),
        class: FlagClass::NoObjectEffect,
        source: "Issue #117 — clang unused-argument warning region (close).",
        dialect: None,
    },
    // ── clang-cl flag classification (#285) ──────────────────────
    //
    // All rows below carry `dialect: Some(Dialect::Cl)` — they apply
    // exclusively to clang-cl invocations. Gnu/clang dialect behaviour
    // is unchanged.

    // NoObjectEffect — output path and conformance flags that do not
    // affect the resulting object bytes.
    FlagSpec {
        // `-Fo<obj>` / `/Fo<obj>` — object output path. Classified here
        // so the classifier gate doesn't refuse it; the parser extracts
        // it into `CcArgs.output` (Artifact bucket).
        matcher: Matcher::Prefix("-Fo"),
        class: FlagClass::NoObjectEffect,
        source: "Issue #285 — clang-cl object output path, no object-content effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Prefix("/Fo"),
        class: FlagClass::NoObjectEffect,
        source: "Issue #285 — clang-cl object output path, no object-content effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        // `-Zc:inline` / `/Zc:inline` — clang-cl ignores this flag
        // entirely in cc1; confirmed via -### that it generates no cc1
        // token and produces no object-content difference.
        matcher: Matcher::Exact("-Zc:inline"),
        class: FlagClass::NoObjectEffect,
        source: "Issue #285 — clang-cl ignores -Zc:inline (no cc1 token, no object effect).",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/Zc:inline"),
        class: FlagClass::NoObjectEffect,
        source: "Issue #285 — clang-cl ignores /Zc:inline (no cc1 token, no object effect).",
        dialect: Some(Dialect::Cl),
    },
    // ModeledInKey — language standard is extracted by the parser into
    // `CcArgs.std` and folded directly into the cache key.
    FlagSpec {
        matcher: Matcher::Prefix("-std:"),
        class: FlagClass::ModeledInKey,
        source: "Issue #285 — clang-cl language standard (-std:c++NN); modeled in key via CcArgs.std.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Prefix("/std:"),
        class: FlagClass::ModeledInKey,
        source: "Issue #285 — clang-cl language standard (/std:c++NN); modeled in key via CcArgs.std.",
        dialect: Some(Dialect::Cl),
    },
    // PreprocessorCaptured — forced-include headers enter the /EP
    // preprocessor hash, so their content is already in the key.
    FlagSpec {
        matcher: Matcher::Prefix("-FI"),
        class: FlagClass::PreprocessorCaptured,
        source: "Issue #285 — clang-cl forced include; content captured by /EP preprocessor hash.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Prefix("/FI"),
        class: FlagClass::PreprocessorCaptured,
        source: "Issue #285 — clang-cl forced include; content captured by /EP preprocessor hash.",
        dialect: Some(Dialect::Cl),
    },
    // CapturedByProbe — keyed via the clang-cl -### resolved-token
    // stream. Different values produce different cc1 tokens → different
    // keys. Safe only when the probe resolves; `cc_flags_need_resolved_invocation`
    // ensures the key refuses if the probe is unavailable.
    FlagSpec {
        // `-guard:cf` / `-guard:cf,nochecks` / `/guard:cf` etc. The
        // `Prefix` wildcard is intentional and safe here BECAUSE this is
        // CapturedByProbe: clang-cl -### resolves each guard variant into
        // a distinct -cc1 token (e.g. `-cfguard`) so the key differentiates
        // per-value automatically. An unrecognized guard variant still
        // produces a distinct -### token → distinct key (no miscache risk).
        matcher: Matcher::Prefix("-guard:"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl Control Flow Guard. Prefix wildcard safe: -### resolves each variant to a distinct -cc1 token.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Prefix("/guard:"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl Control Flow Guard (/guard: spelling). Prefix wildcard safe: -### resolves each variant to a distinct -cc1 token.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        // `-fms-compatibility-version=<ver>` — MSVC version emulation.
        // `Prefix` wildcard is safe here BECAUSE this is CapturedByProbe:
        // clang-cl -### reflects the exact version number into a -cc1
        // token, so different versions produce different keys.
        matcher: Matcher::Prefix("-fms-compatibility-version="),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — MSVC compatibility version. Prefix wildcard safe: -### reflects the exact version into a -cc1 token.",
        dialect: Some(Dialect::Cl),
    },
    // Function/global inlining and frame-pointer optimizations.
    FlagSpec {
        matcher: Matcher::Exact("-Gy"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl function-level linking (COMDAT). Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/Gy"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl function-level linking (COMDAT). Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-Gw"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl global data optimization (COMDAT). Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/Gw"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl global data optimization (COMDAT). Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-Oy-"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl frame-pointer omission disabled. Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/Oy-"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl frame-pointer omission disabled. Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    // CRT (C Runtime) selection flags. Under Cl these are codegen flags
    // (they define `_MT`/`_DLL` macros and link the appropriate CRT),
    // not dep-info markers (cf. the Gnu-dialect row above which tags
    // the same spellings as NoObjectEffect).
    FlagSpec {
        matcher: Matcher::Exact("-MD"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl CRT: multithreaded DLL (dynamic). Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-MDd"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl CRT: multithreaded DLL debug. Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-MT"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl CRT: multithreaded static. Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-MTd"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl CRT: multithreaded static debug. Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/MD"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl CRT: multithreaded DLL (dynamic). Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/MDd"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl CRT: multithreaded DLL debug. Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/MT"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl CRT: multithreaded static. Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/MTd"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl CRT: multithreaded static debug. Keyed via -### resolved tokens.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        // clang-cl optimization levels, `-` and `/` spellings, keyed via
        // the cc1 level in `-###`. NOTE: the bare `-O1`/`-O2` spellings
        // are already matched by the earlier dialect-agnostic `-O[0-3sz]?`
        // ModeledInKey row (→ `parsed.optimization`), so this row only
        // fires for `/O1`/`/O2`/`-Od`/`/Od`/`-Ox`/`/Ox`. Both paths key
        // the level, just by different mechanisms. `-Os`/`-Oz`/`-Ofast`
        // are not in this set and still refuse.
        matcher: Matcher::Regex(r"[-/]O[12dx]"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #285 — clang-cl optimization levels. Bare -O1/-O2 are caught earlier as ModeledInKey; this row covers /Onn and -Od/-Ox. -### resolves each to a distinct cc1 level. -Ofast/-Os/-Oz not matched → still refuse.",
        dialect: Some(Dialect::Cl),
    },
    // ── clang-cl Layer 4: Firefox-corpus flag classification (#285) ──
    //
    // All rows carry `dialect: Some(Dialect::Cl)`. Gnu/clang dialect
    // behaviour is unchanged.

    // ── CapturedByProbe: exception / RTTI / stack-protector / misc codegen ──
    //
    // Each row's effect is reflected in the clang-cl -### token stream:
    //   -EHsc   → -fexceptions + -fcxx-exceptions
    //   -GR-    → -fno-rtti
    //   -GS-    → removes -stack-protector from cc1
    //   -Brepro → removes -mincremental-linker-compatible from cc1
    //   -utf-8  → clang-cl is UTF-8 by default; the flag is inert (no cc1 token)
    //             but remains CapturedByProbe — keyed if it ever produces a token,
    //             inert if not; the probe requirement is always met for clang-cl.
    //   -Zc:*   → various conformance knobs reflected into cc1 tokens per value.
    //             NOTE: `-Zc:inline` / `/Zc:inline` are listed BEFORE these Prefix
    //             rows (exact rows appear earlier in the table) so they continue to
    //             resolve as NoObjectEffect via first-match.
    // `Prefix` wildcards on CapturedByProbe are safe: the -### stream captures the
    // exact value (or the flag is inert), so an unknown suffix still produces a
    // distinct key (no miscache risk).
    // clang-cl source-language override: `-TP`/`/TP` force every input to
    // compile as C++, `-TC`/`/TC` force C (MSVC `/TP` / `/TC`). This
    // changes the language the front end uses (and thus the object), but
    // clang-cl resolves it into the `-cc1 -x c++` / `-x c` token, so the
    // resolved-token hash differentiates it — the same treatment as the
    // gnu `-x <lang>` override. (Issue #411 — Firefox/Windows compiles
    // `Unified_cpp_*.cpp` with `-TP`.)
    FlagSpec {
        matcher: Matcher::Exact("-TP"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #411 — clang-cl force-C++ source mode (-TP). -### resolves it into the -cc1 -x c++ token.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/TP"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #411 — clang-cl force-C++ source mode (/TP). -### resolves it into the -cc1 -x c++ token.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-TC"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #411 — clang-cl force-C source mode (-TC). -### resolves it into the -cc1 -x c token.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/TC"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #411 — clang-cl force-C source mode (/TC). -### resolves it into the -cc1 -x c token.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Prefix("-EH"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl exception model (-EHsc, -EHs-c-, …). Prefix safe: -### resolves each variant into distinct -fexceptions/-fcxx-exceptions tokens (or their negations).",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Prefix("/EH"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl exception model (/EH* spelling). Prefix safe: -### resolves each variant into distinct -fexceptions/-fcxx-exceptions tokens (or their negations).",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-GR"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl RTTI enabled (-GR). -### reflects -frtti.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-GR-"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl RTTI disabled (-GR-). -### reflects -fno-rtti.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/GR"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl RTTI enabled (/GR). -### reflects -frtti.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/GR-"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl RTTI disabled (/GR-). -### reflects -fno-rtti.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-GS"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl stack-buffer-security-check enabled (-GS). -### reflects -stack-protector.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-GS-"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl stack-buffer-security-check disabled (-GS-). -### removes -stack-protector.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/GS"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl stack-buffer-security-check enabled (/GS). -### reflects -stack-protector.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/GS-"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl stack-buffer-security-check disabled (/GS-). -### removes -stack-protector.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-Brepro"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl reproducible build (-Brepro). -### removes -mincremental-linker-compatible.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/Brepro"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl reproducible build (/Brepro). -### removes -mincremental-linker-compatible.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("-utf-8"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl UTF-8 source/execution charset (-utf-8). clang-cl is UTF-8 by default; the flag produces no cc1 token but is inert — CapturedByProbe is safe (keyed if token present, inert if not; probe always resolves for clang-cl).",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/utf-8"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl UTF-8 source/execution charset (/utf-8). Same rationale as -utf-8.",
        dialect: Some(Dialect::Cl),
    },
    // -Zc: conformance flags. The Exact rows for -Zc:inline / /Zc:inline
    // appear EARLIER in the table and resolve first (NoObjectEffect), so
    // only non-inline -Zc: values reach these Prefix rows.
    FlagSpec {
        matcher: Matcher::Prefix("-Zc:"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl conformance flags (-Zc:wchar_t, -Zc:forScope, …). Prefix safe: -### captures the exact value (or flag is inert); placed AFTER the -Zc:inline Exact row so that spelling resolves NoObjectEffect first.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Prefix("/Zc:"),
        class: FlagClass::CapturedByProbe,
        source: "#285 Layer 4 — clang-cl conformance flags (/Zc:* spelling). Prefix safe: -### captures the exact value (or flag is inert); placed AFTER the /Zc:inline Exact row so that spelling resolves NoObjectEffect first.",
        dialect: Some(Dialect::Cl),
    },
    // ── PreprocessorCaptured: -FC makes __FILE__ expand to the full path ──
    //
    // clang-cl's `/EP` preprocessor hash captures `__FILE__` expansions,
    // so `-FC`'s effect (full path in `__FILE__`) is already in the key.
    FlagSpec {
        matcher: Matcher::Exact("-FC"),
        class: FlagClass::PreprocessorCaptured,
        source: "#285 Layer 4 — clang-cl full-path __FILE__ (-FC). Makes __FILE__ expand to the absolute source path; that expansion is captured by the /EP preprocessor hash.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/FC"),
        class: FlagClass::PreprocessorCaptured,
        source: "#285 Layer 4 — clang-cl full-path __FILE__ (/FC). Makes __FILE__ expand to the absolute source path; that expansion is captured by the /EP preprocessor hash.",
        dialect: Some(Dialect::Cl),
    },
    // ── NoObjectEffect: diagnostics / build mechanics ──
    //
    // None of these flags change the resulting object bytes.
    FlagSpec {
        matcher: Matcher::Exact("-nologo"),
        class: FlagClass::NoObjectEffect,
        source: "#285 Layer 4 — clang-cl suppress banner (-nologo). Pure build-output mechanic; no object effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/nologo"),
        class: FlagClass::NoObjectEffect,
        source: "#285 Layer 4 — clang-cl suppress banner (/nologo). Pure build-output mechanic; no object effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        // `-wdNNNN` / `/wdNNNN` — disable a specific warning by number.
        // Warnings only affect diagnostics, never the object.
        matcher: Matcher::Prefix("-wd"),
        class: FlagClass::NoObjectEffect,
        source: "#285 Layer 4 — clang-cl disable warning (-wdNNNN). Diagnostics only; no object effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Prefix("/wd"),
        class: FlagClass::NoObjectEffect,
        source: "#285 Layer 4 — clang-cl disable warning (/wdNNNN). Diagnostics only; no object effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        // `-FS` / `/FS` — force synchronous PDB writes (serializes access
        // to the shared .pdb across parallel compilations). Pure build
        // mechanic; has no effect on the object file content.
        matcher: Matcher::Exact("-FS"),
        class: FlagClass::NoObjectEffect,
        source: "#285 Layer 4 — clang-cl force synchronous PDB writes (-FS). Build mechanic; no object effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/FS"),
        class: FlagClass::NoObjectEffect,
        source: "#285 Layer 4 — clang-cl force synchronous PDB writes (/FS). Build mechanic; no object effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        // `-Gm-` / `/Gm-` — disable minimal rebuild (deprecated MSVC flag).
        // Has no effect on the object content.
        matcher: Matcher::Exact("-Gm-"),
        class: FlagClass::NoObjectEffect,
        source: "#285 Layer 4 — clang-cl minimal rebuild disabled (-Gm-, deprecated). No object effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Exact("/Gm-"),
        class: FlagClass::NoObjectEffect,
        source: "#285 Layer 4 — clang-cl minimal rebuild disabled (/Gm-, deprecated). No object effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        // `-external:W<n>` / `/external:W<n>` and similar external-header
        // warning-level flags. These only affect diagnostics for headers
        // treated as "external" (system headers); no object effect.
        matcher: Matcher::Prefix("-external:"),
        class: FlagClass::NoObjectEffect,
        source: "#285 Layer 4 — clang-cl external-header warning level (-external:*). Diagnostics only; no object effect.",
        dialect: Some(Dialect::Cl),
    },
    FlagSpec {
        matcher: Matcher::Prefix("/external:"),
        class: FlagClass::NoObjectEffect,
        source: "#285 Layer 4 — clang-cl external-header warning level (/external:*). Diagnostics only; no object effect.",
        dialect: Some(Dialect::Cl),
    },
    // ── clang-cl debug-info flags (#312) ─────────────────────────
    //
    // MSVC `/Z7`/`/Zi`/`/ZI`/`/Zd` and their `-` spellings embed
    // CodeView debug info in the object. Their codegen effect is in the
    // `-cc1` line (`-gcodeview`, `-debug-info-kind`, edit-and-continue),
    // so the variant is keyed via the `cc -###` resolved tokens —
    // `CapturedByProbe`. This also enforces the safety contract: if the
    // probe is unavailable the compile bails rather than under-keying
    // (box-confirmed: `/Z7` and `/Zi` resolve identically and produce
    // identical objects, but `/ZI` differs). The PATH inputs the debug
    // object embeds (source/output/compilation-dir) are a separate
    // concern, folded into the key by `cl_debug_path_inputs`.
    FlagSpec {
        matcher: Matcher::Regex(r"[-/]Z[7iId]"),
        class: FlagClass::CapturedByProbe,
        source: "Issue #312 — clang-cl CodeView debug-info flags; variant captured via cc -### resolved tokens; embedded paths folded by cl_debug_path_inputs.",
        dialect: Some(Dialect::Cl),
    },
];

#[derive(Debug, Default)]
struct FlagClassificationSummary {
    modeled_in_key: usize,
    raw_keyed: usize,
    captured_by_probe: usize,
    preprocessor_captured: usize,
    no_object_effect: usize,
    parser_handled: usize,
    /// Unmodeled by the built-in table but opted into caching via the
    /// user's `[cc] extra_allowlist_flags` allow-list (issue #95).
    user_allowed: usize,
    unmodeled: usize,
}

impl FlagClassificationSummary {
    fn record(&mut self, class: Option<FlagClass>) {
        match class {
            Some(FlagClass::ModeledInKey) => self.modeled_in_key += 1,
            Some(FlagClass::RawKeyed) => self.raw_keyed += 1,
            Some(FlagClass::CapturedByProbe) => self.captured_by_probe += 1,
            Some(FlagClass::PreprocessorCaptured) => self.preprocessor_captured += 1,
            Some(FlagClass::NoObjectEffect) => self.no_object_effect += 1,
            Some(FlagClass::ParserHandled) => self.parser_handled += 1,
            None => self.unmodeled += 1,
        }
    }
}

/// Classify the parsed flags, emitting per-flag and per-compile traces,
/// and return the tokens that should *refuse* (force passthrough).
///
/// `extra_allowlist_flags` is the user's allow-list (issue #95): a flag the
/// built-in table doesn't model is normally rejected, but if it exactly
/// matches an allow-list entry it is accepted instead (logged as
/// `user-allowed (config)`) and folded verbatim into the cache key by
/// [`CcCompiler::cache_key`].
fn classify_and_trace_cc_flags<'a>(
    parsed: &'a CcArgs,
    extra_allowlist_flags: &[String],
) -> Vec<&'a str> {
    let subject = parsed
        .sources
        .first()
        .map(|source| source.display().to_string())
        .unwrap_or_else(|| parsed.program.clone());
    let mut summary = FlagClassificationSummary::default();
    let mut rejected = Vec::new();

    let dialect = parsed.family.dialect();
    let mut idx = 0;
    while idx < parsed.rest.len() {
        let arg = &parsed.rest[idx];

        // `-Xclang <tok>` forwards `<tok>` straight to the cc1 front end,
        // so the driver-level table can't classify it — `<tok>` means
        // whatever cc1 makes of it (cc1 `-MP` is dep-info phony targets,
        // not the clang-cl driver's `/MP`). Classify the forwarded token
        // against the cc1 allow-list and consume the pair, so its value
        // (itself a separate `-Xclang <value>`) isn't reprocessed.
        // Issue #411 (Firefox/Windows).
        if arg == "-Xclang" {
            // The marker only forwards; it has no object effect itself.
            summary.record(Some(FlagClass::NoObjectEffect));
            let Some(inner) = parsed.rest.get(idx + 1) else {
                // Trailing `-Xclang` with no operand: nothing to forward.
                tracing::trace!("[cc:{subject}] flag -Xclang (no operand) -> NoObjectEffect");
                idx += 1;
                continue;
            };
            let class = classify_xclang_forwarded(inner, dialect);
            summary.record(class);
            match class {
                Some(class) => tracing::trace!(
                    "[cc:{subject}] flag -Xclang {inner} -> {class:?} [forwarded cc1]"
                ),
                None if extra_allowlist_flags.iter().any(|f| f == inner) => {
                    summary.user_allowed += 1;
                    tracing::trace!("[cc:{subject}] flag -Xclang {inner} -> user-allowed (config)");
                }
                None => {
                    tracing::trace!(
                        "[cc:{subject}] flag -Xclang {inner} -> unmodeled [forwarded cc1]"
                    );
                    rejected.push(inner.as_str());
                }
            }
            idx += 2;
            continue;
        }

        let analysis = analyze_cc_arg(arg, dialect);
        summary.record(analysis.class);
        match analysis.class {
            Some(class) => tracing::trace!(
                "[cc:{subject}] flag {arg} -> {class:?} [{:?}]",
                analysis.bucket
            ),
            None if extra_allowlist_flags.iter().any(|f| f == arg) => {
                summary.user_allowed += 1;
                tracing::trace!(
                    "[cc:{subject}] flag {arg} -> user-allowed (config) [verbatim-keyed]"
                );
            }
            None => {
                tracing::trace!(
                    "[cc:{subject}] flag {arg} -> unmodeled [{:?}]",
                    analysis.bucket
                );
                rejected.push(arg.as_str());
            }
        }
        idx += 1;
    }

    if !parsed.rest.is_empty() {
        tracing::debug!(
            "[cc:{subject}] flag classify: {} modeled / {} raw-keyed / {} probe / {} preprocessor / {} no-effect / {} parser-handled / {} user-allowed / {} unmodeled",
            summary.modeled_in_key,
            summary.raw_keyed,
            summary.captured_by_probe,
            summary.preprocessor_captured,
            summary.no_object_effect,
            summary.parser_handled,
            summary.user_allowed,
            summary.unmodeled
        );
    }

    rejected
}

/// Select the user-declared flags (issue #95) to fold verbatim into the
/// cache key: the command-line tokens that (a) match an allow-list entry
/// exactly and (b) the built-in table does NOT model — i.e. exactly the
/// "user-allowed" set from [`classify_and_trace_cc_flags`]. Sorted +
/// deduped so argv order and repeated flags never perturb the key, and a
/// configured-but-absent flag is excluded (it has no codegen effect).
fn cc_extra_flags_for_key<'a>(
    parsed: &'a CcArgs,
    extra_allowlist_flags: &[String],
) -> Vec<&'a str> {
    if extra_allowlist_flags.is_empty() {
        return Vec::new();
    }
    let dialect = parsed.family.dialect();
    let mut matched: Vec<&str> = parsed
        .rest
        .iter()
        .map(String::as_str)
        .filter(|arg| {
            classify_cc_flag(arg, dialect).is_none()
                && extra_allowlist_flags.iter().any(|f| f == arg)
        })
        .collect();
    matched.sort_unstable();
    matched.dedup();
    matched
}

const WA_DEBUG_PREFIX_MAP_PREFIX: &str = "-Wa,--debug-prefix-map=";

/// Built-in flags whose object effect is not present in the resolved `cc1`
/// stream and therefore must be folded directly into the cache key.
///
/// Preserve argv order and duplicates: assembler option precedence may be
/// order-sensitive. For GNU as's `--debug-prefix-map=OLD=NEW`, normalize only
/// the location-dependent `OLD`; `NEW` is object material and stays verbatim.
fn cc_raw_flags_for_key(parsed: &CcArgs, prefix_maps: &[CcPrefixMap]) -> Vec<Vec<u8>> {
    let dialect = parsed.family.dialect();
    parsed
        .rest
        .iter()
        .filter(|arg| classify_cc_flag(arg, dialect) == Some(FlagClass::RawKeyed))
        .map(|arg| normalize_raw_keyed_cc_flag(arg, prefix_maps))
        .collect()
}

fn normalize_raw_keyed_cc_flag(arg: &str, prefix_maps: &[CcPrefixMap]) -> Vec<u8> {
    let Some(mapping) = arg.strip_prefix(WA_DEBUG_PREFIX_MAP_PREFIX) else {
        return arg.as_bytes().to_vec();
    };
    let Some((from, to)) = mapping.split_once('=') else {
        // The classifier rejects this malformed spelling, but keeping the
        // fallback lossless makes this helper safe if called independently.
        return arg.as_bytes().to_vec();
    };

    let from = apply_cc_prefix_maps_to_bytes(from.as_bytes().to_vec(), prefix_maps);
    let mut normalized = Vec::with_capacity(arg.len());
    normalized.extend_from_slice(WA_DEBUG_PREFIX_MAP_PREFIX.as_bytes());
    normalized.extend_from_slice(&from);
    normalized.push(b'=');
    normalized.extend_from_slice(to.as_bytes());
    normalized
}

fn analyze_cc_arg(arg: &str, dialect: Dialect) -> CcArgAnalysis<'_> {
    let class = classify_cc_flag(arg, dialect);
    let spec = cc_arg_spec_for_token(arg, dialect);
    CcArgAnalysis {
        arg,
        class,
        bucket: cc_arg_bucket(class, spec),
        normalized: normalize_cc_arg(arg, dialect),
        refusal: class.is_none().then_some("cc: unsupported flag"),
        source: spec.map(|spec| spec.source),
    }
}

fn cc_arg_bucket(class: Option<FlagClass>, spec: Option<&'static CcArgSpec>) -> CcArgBucket {
    if class.is_none() {
        return CcArgBucket::TooHard;
    }
    if let Some(spec) = spec {
        return spec.bucket;
    }
    match class {
        Some(FlagClass::ModeledInKey) => CcArgBucket::ModeledInKey,
        Some(FlagClass::RawKeyed) => CcArgBucket::RawKeyed,
        Some(FlagClass::ParserHandled) => CcArgBucket::Structural,
        Some(FlagClass::CapturedByProbe) => CcArgBucket::ProbeKeyed,
        Some(FlagClass::PreprocessorCaptured) => CcArgBucket::Preprocessor,
        Some(FlagClass::NoObjectEffect) => CcArgBucket::NoObjectEffect,
        None => CcArgBucket::TooHard,
    }
}

fn normalize_cc_arg(arg: &str, dialect: Dialect) -> Vec<String> {
    let Some(spec) = cc_arg_spec_for_token(arg, dialect) else {
        return vec![arg.to_string()];
    };
    match spec.value_form {
        CcArgValueForm::Flag | CcArgValueForm::Separated => vec![arg.to_string()],
        CcArgValueForm::Concatenated { prefix } => arg
            .strip_prefix(prefix)
            .map(|value| vec![prefix.to_string(), value.to_string()])
            .unwrap_or_else(|| vec![arg.to_string()]),
        CcArgValueForm::CanBeSeparated { prefix } => {
            if arg == prefix {
                vec![prefix.to_string()]
            } else {
                arg.strip_prefix(prefix)
                    .filter(|value| !value.is_empty())
                    .map(|value| vec![prefix.to_string(), value.to_string()])
                    .unwrap_or_else(|| vec![arg.to_string()])
            }
        }
    }
}

fn cc_arg_spec_for_token(arg: &str, dialect: Dialect) -> Option<&'static CcArgSpec> {
    CC_ARG_SPECS.iter().find(|spec| {
        // Skip rows restricted to a different dialect, so a token shared
        // across dialects (e.g. `-MT`) resolves to the row for the active
        // dialect — not whichever appears first in the table.
        if spec.dialect.is_some_and(|d| d != dialect) {
            return false;
        }
        match spec.value_form {
            CcArgValueForm::Flag | CcArgValueForm::Separated => cc_arg_spec_matches(spec, arg),
            CcArgValueForm::Concatenated { prefix } => arg.starts_with(prefix),
            CcArgValueForm::CanBeSeparated { prefix } => {
                arg == prefix
                    || arg
                        .strip_prefix(prefix)
                        .is_some_and(|value| !value.is_empty())
            }
        }
    })
}

/// Classify a cc argument. Wraps [`crate::compiler::flags::classify_against`]
/// over [`CC_FLAGS`] with a lazy regex cache. Returns `None` for any
/// argument no row matches — the caller treats that as "unsupported
/// flag, refuse to cache".
fn classify_cc_flag(arg: &str, dialect: Dialect) -> Option<FlagClass> {
    static CACHE: OnceLock<HashMap<&'static str, Regex>> = OnceLock::new();
    crate::compiler::flags::classify_against(
        arg,
        CC_FLAGS,
        CACHE.get_or_init(|| crate::compiler::flags::build_regex_cache(CC_FLAGS)),
        dialect,
    )
}

/// cc1 frontend flags that clang's driver forwards verbatim via
/// `-Xclang <flag>`. Each is inert for object-content caching — dep-info
/// sidecar emission or terminal diagnostics — so an `-Xclang`-wrapped one
/// is safe to cache past. A forwarded flag NOT on this list still refuses
/// (see [`classify_xclang_forwarded`]), so an `-Xclang`-wrapped *codegen*
/// flag can never slip through. Sourced from Firefox's Windows build
/// (issue #411).
///
/// These are deliberately classified only in forwarded (`-Xclang`)
/// position, NOT as bare driver flags: e.g. cc1 `-MP` means "emit phony
/// dep targets", whereas the clang-cl driver's `/MP` is multi-process
/// compilation — different flags that happen to share a spelling.
const XCLANG_INERT_CC1_FLAGS: &[&str] = &[
    // ── dep-info sidecar family ──────────────────────────────────────
    // Every one of these only shapes the `.d`/`.pp` dependency sidecar;
    // none changes a byte of the object. They are listed as a *family*,
    // not just the two flags issue #411 happened to surface, because they
    // co-occur: cc1 rejects `-dependency-file` unless a `-MT`/`-MQ` target
    // accompanies it, so a build that forwards one forwards several. (cc1
    // spellings — distinct from the clang-cl driver's `/MT` CRT-selection
    // flag, which is why these are recognized only in forwarded position.)
    "-dependency-file", // write the dep sidecar (path is a separate -Xclang value)
    "-MT",              // dependency target name
    "-MQ",              // dependency target name, quoted for make
    "-MP",              // emit a phony target per header
    "-MG",              // tolerate missing (generated) headers
    "-MV",              // NMake/Visual Studio style dependency output
    "-sys-header-deps", // include system headers in the dep output
    "-module-file-deps", // include module files in the dep output
    "-dependency-dot",  // write DOT-format header deps (path is a separate value)
    // ── terminal diagnostics ─────────────────────────────────────────
    "-fansi-escape-codes", // emit ANSI color escapes regardless of TTY detection
];

/// Classify a single cc1 token forwarded to the front end via `-Xclang`.
///
/// Returns `NoObjectEffect` for an allow-listed inert cc1 flag
/// ([`XCLANG_INERT_CC1_FLAGS`]) or for a bare value token — e.g. the
/// dependency-file path, itself forwarded as its own `-Xclang <value>`
/// pair.
///
/// A forwarded flag that matches a modeled `CapturedByProbe` codegen knob
/// (`-Xclang -ffp-contract=off`, the Firefox/Windows clang-cl shape of #428)
/// is allowed and keyed via the probe: `-Xclang` forwards it to cc1, where the
/// `cc -###` resolved cc1 line records it (verified: `-Xclang -ffp-contract=off`
/// appends `-ffp-contract=off` to the dump), so the cache key already
/// differentiates it from the default. This is safe, NOT "blind": the bare
/// operand token also classifies as `ProbeKeyed` at the driver level, so
/// `cc_flags_need_resolved_invocation` forces the probe and refuses to cache if
/// it cannot resolve — there is no under-keying path. An UNMODELED `-Xclang`
/// codegen flag (not in `CC_FLAGS`) still returns `None` and refuses.
fn classify_xclang_forwarded(inner: &str, dialect: Dialect) -> Option<FlagClass> {
    if !inner.starts_with('-') {
        // A value token (e.g. the dependency-file path). No object effect;
        // its content is irrelevant to the resulting `.obj`.
        return Some(FlagClass::NoObjectEffect);
    }
    // Inert cc1 flags FIRST: a forwarded `-MT`/`-MP`/… is the cc1 dep-info flag,
    // which must NOT be confused with the clang-cl driver flag of the same
    // spelling (`/MT` = CRT selection, a CapturedByProbe codegen knob). The
    // driver-level `classify_cc_flag` below would misread the cc1 spelling as
    // the driver flag, so the forwarded-position allow-list wins.
    if XCLANG_INERT_CC1_FLAGS.contains(&inner) {
        return Some(FlagClass::NoObjectEffect);
    }
    if classify_cc_flag(inner, dialect) == Some(FlagClass::CapturedByProbe) {
        return Some(FlagClass::CapturedByProbe);
    }
    None
}

fn cc_flags_need_resolved_invocation(parsed: &CcArgs) -> bool {
    let dialect = parsed.family.dialect();
    // Any driver-level probe-keyed flag forces the resolved `cc -###`
    // invocation so the key captures its codegen effect.
    if parsed
        .rest
        .iter()
        .any(|arg| analyze_cc_arg(arg, dialect).bucket == CcArgBucket::ProbeKeyed)
    {
        return true;
    }
    // A `-Xclang`-forwarded CapturedByProbe knob is keyed via the resolved cc1
    // line too (#428), so it must force the probe as well. The flat scan above
    // already catches self-contained shapes whose operand also matches a driver
    // row (e.g. `-ffp-contract=`), but a cc1-only forwarded knob would slip
    // past it — without the probe its codegen effect would not be keyed.
    parsed.rest.windows(2).any(|w| {
        w[0] == "-Xclang"
            && classify_xclang_forwarded(&w[1], dialect) == Some(FlagClass::CapturedByProbe)
    })
}

/// MSVC debug-info markers that embed absolute CodeView paths into the
/// object. clang-cl puts debug info in the `.obj` for all of these (no
/// compile-time PDB — box-confirmed), so each is a single cacheable
/// artifact once the embedded path inputs are keyed.
const CL_DEBUG_FLAGS: &[&str] = &["/Z7", "/Zi", "/ZI", "/Zd", "-Z7", "-Zi", "-ZI", "-Zd"];

/// Whether this clang-cl invocation requests debug info (native MSVC
/// spelling or a `-g` form parsed into `debug_level`). Only meaningful
/// for `Dialect::Cl`; the caller gates on dialect.
///
/// NOTE: `cl_debug_present` does NOT imply the `-###` probe is forced.
/// The native `/Z*` spellings are modeled `CapturedByProbe` (the
/// `/Z7`-vs-`/ZI` variant split is keyed via resolved tokens, bailing if
/// the probe is absent). The bare `-g` form has no such variant — it is
/// `ModeledInKey` via `debug_level` and its embedded paths are folded
/// here — so a `-g`-only clang-cl compile keys correctly without the
/// probe. Don't assume `cl_debug_present ⇒ probe required`.
fn cl_debug_present(parsed: &CcArgs) -> bool {
    parsed.family.dialect() == Dialect::Cl
        && (parsed.debug_level.is_some_and(|d| d > 0)
            || parsed
                .rest
                .iter()
                .any(|a| CL_DEBUG_FLAGS.contains(&a.as_str())))
}

/// The per-TU path inputs a clang-cl debug object embeds in CodeView that
/// the cache key would otherwise miss: the source file path(s) as spelled
/// on the command line, the output object name from `-Fo`/`-o`, and the
/// effective compilation directory (an explicit `-fdebug-compilation-dir`
/// or `-ffile-compilation-dir` value if present, otherwise the OS cwd).
/// These are exactly the tokens `config_args()` strips (source, output)
/// plus the compilation directory. `-I` dirs and flags are already in the
/// key via the resolved tokens. Capture, not remap — clang-cl stays
/// path-literal (#299/#312). `None` when this is not a clang-cl debug
/// compile (no fold; non-debug objects don't embed these, so
/// cross-CWD/name hits stay correct).
/// Per-TU path strings that can appear verbatim in the resolved `cc -###`
/// token stream and MUST be kept out of the cache key.
///
/// The resolved-invocation probe is memoized per *flag set* — `config_args`
/// strips the source, `-o`/`-Fo` output, and dep-file values so ONE probe
/// record serves every TU of a build. Absolute paths in the resolved tokens
/// are already blanked to a sentinel ([`crate::probe`]), and the trailing
/// source input token too — but a RELATIVE per-TU path that appears as a
/// flag *value* (`-main-file-name u00.c`, `-o build/u00.o`) survives,
/// leaving the shared record's tokens TU-specific. Serially the leak is
/// consistent (cold==warm → still hits); under `make -j` the TUs race over
/// whose paths the first-probing TU wrote into the shared record, leaking
/// one TU's source/output into another TU's key, so the key is
/// non-deterministic and the warm rebuild intermittently MISSES.
///
/// Blanking these tokens (to the path sentinel, inside the shared probe
/// record before it is stored) is safe in the never-miscache direction: the
/// source CONTENT is already captured by the preprocessor-expansion hash and
/// the output path has no object-content effect, so this only ever merges
/// keys that differ solely in a per-TU path. The set mirrors what
/// `config_args` removes from the probe-memo key, and is handed to the probe
/// so [`crate::probe`] sentinels these values out of the resolved tokens.
fn cc_resolved_per_tu_paths(parsed: &CcArgs) -> Vec<String> {
    let mut set = HashSet::new();
    // Insert a path both as written AND by basename: the cc1 line spells
    // the same file differently per token — `-o build/u00.o` keeps the
    // path, but `-main-file-name u00.c` uses only the basename. Blanking
    // must catch every spelling or a residual per-TU token still races.
    let mut add = |p: &Path| {
        set.insert(p.to_string_lossy().into_owned());
        if let Some(name) = p.file_name() {
            set.insert(name.to_string_lossy().into_owned());
        }
    };
    for src in &parsed.sources {
        add(src);
    }
    if let Some(o) = &parsed.output {
        add(o);
    }
    if let Some(o) = parsed.object_output_path() {
        add(&o);
    }
    if let Some(d) = parsed.depinfo_output_path() {
        add(&d);
    }
    if let Some(t) = parsed.depinfo.as_ref().and_then(|d| d.target.clone()) {
        set.insert(t);
    }
    // Never blank an empty token (a no-op path would blank real tokens).
    set.remove("");
    set.into_iter().collect()
}

fn cl_debug_path_inputs(parsed: &CcArgs) -> Option<Vec<String>> {
    if !cl_debug_present(parsed) {
        return None;
    }
    let mut out = Vec::new();
    // Paths are encoded lossily; on Windows (where clang-cl runs) paths
    // are always valid UTF-16 → UTF-8, so no two distinct paths collapse.
    for src in &parsed.sources {
        out.push(format!("src={}", src.to_string_lossy()));
    }
    if let Some(o) = &parsed.output {
        out.push(format!("out={}", o.to_string_lossy()));
    }
    // NOTE (#312 follow-up): the compilation-dir spellings below are
    // NOT yet modeled in CC_FLAGS, so a clang-cl debug compile that
    // passes one EXPLICITLY currently hits the unmodeled-flag refusal
    // (passthrough — safe, not a miscache) before reaching this fold.
    // The common case (clang auto-injects -fdebug-compilation-dir at
    // -cc1, not on the driver line) is unaffected. Modeling these flags
    // to also cache the explicit-dir case is a deferred follow-up.
    let dir = parsed
        .rest
        .iter()
        .find_map(|a| {
            [
                "-fdebug-compilation-dir=",
                "-ffile-compilation-dir=",
                "/fdebug-compilation-dir=",
                "/ffile-compilation-dir=",
            ]
            .iter()
            .find_map(|p| a.strip_prefix(p))
            .map(str::to_string)
        })
        .or_else(|| {
            std::env::current_dir()
                .ok()
                .map(|p| p.to_string_lossy().into_owned())
        });
    if let Some(d) = dir {
        out.push(format!("dir={d}"));
    }
    Some(out)
}

/// Prefix maps that make C/C++ objects path-stable across worktrees.
///
/// A `-g` compile bakes paths into DWARF (`DW_AT_comp_dir`) and
/// `__FILE__` expansions. Firefox also exposes this through headers
/// whose macros stringify absolute include paths after preprocessing.
/// Mapping only the compiler CWD misses sibling objdir/source paths
/// like `<checkout>/obj/dist/include`, so derive the common root of
/// the source and build directories and map that instead.
///
/// The fallback split roots handle out-of-tree builds where source and
/// object directories do not share a useful project root. Distinct
/// sentinels avoid collapsing unrelated paths to the same spelling.
fn cc_prefix_maps(parsed: &CcArgs, configured_base_dirs: &[String]) -> Vec<CcPrefixMap> {
    // `KACHE_CC_PATH_NORMALIZE=0` disables cc path normalization entirely:
    // no maps → the key hashes raw paths AND `execute` injects no
    // `-ffile-prefix-map`. The conservative escape hatch — cc keys become
    // path-literal (no cross-machine cc sharing, but zero normalization
    // miscache risk). Default on.
    if !cc_path_normalize_enabled() {
        return Vec::new();
    }
    let cwd = match std::env::current_dir() {
        Ok(cwd) => cwd,
        Err(_) => return Vec::new(),
    };
    let base = std::env::var_os("KACHE_BASE_DIR").filter(|v| !v.is_empty());
    // `SDKROOT` is the Apple-clang env that pins the SDK when no explicit
    // `-isysroot` is on the command line; read here (the only env access)
    // and threaded into the deterministic core for testability.
    let sdkroot = std::env::var_os("SDKROOT").filter(|v| !v.is_empty());
    cc_prefix_maps_cfg(
        parsed,
        &cwd,
        base.as_deref().map(Path::new),
        sdkroot.as_deref().map(Path::new),
        configured_base_dirs,
    )
}

/// The Apple SDK path this invocation pins, for the `<SDKROOT>` map.
///
/// Prefers an explicit `-isysroot <path>` (cargo's `cc` crate passes it on
/// Apple targets via `apple_sdk_root()`; mozbuild and CMake toolchains do
/// too), falling back to the `SDKROOT` env value the env-reading wrapper
/// threads in. Returns `None` when neither is present — a bare `cc -c`
/// that lets clang resolve the SDK via `xcrun` internally is not
/// normalized yet (issue #78).
fn cc_sdk_root(parsed: &CcArgs, sdkroot_env: Option<&Path>) -> Option<PathBuf> {
    let mut iter = parsed.rest.iter();
    while let Some(arg) = iter.next() {
        if arg == "-isysroot"
            && let Some(path) = iter.next()
            && !path.is_empty()
        {
            return Some(PathBuf::from(path));
        }
    }
    sdkroot_env.map(Path::to_path_buf)
}

/// Deterministic core of [`cc_prefix_maps`] (reads no env) — the derived
/// roots plus an optional user `base_dir` (`KACHE_BASE_DIR`) and the
/// Apple SDK root (explicit `-isysroot`, else `sdk_root` from `SDKROOT`).
fn cc_prefix_maps_cfg(
    parsed: &CcArgs,
    cwd: &Path,
    base_dir: Option<&Path>,
    sdk_root: Option<&Path>,
    configured_base_dirs: &[String],
) -> Vec<CcPrefixMap> {
    // clang-cl ignores `-ffile-prefix-map`, so prefix-mapping the key over
    // an object that still embeds raw paths would miscache. Until Layer 3
    // proves a cl path-remap, cl keys stay path-literal (unnormalised
    // `-###` abs paths make them per-machine — misses, never miscache) and
    // `execute` injects nothing. (The MSVC dialect doesn't use
    // `-isysroot`/`SDKROOT` anyway, on any host.)
    if parsed.family.dialect() == Dialect::Cl {
        return Vec::new();
    }
    let mut maps: Vec<CcPrefixMap> = Vec::new();

    // User-declared base dir (ccache `CCACHE_BASEDIR` analog). An explicit
    // root stripped to `<CC_BASE>` — covers paths the derived roots miss,
    // e.g. objdir-built TUs whose `__FILE__` points into the source tree
    // *above* the (narrow) derived root. A distinct sentinel so it can't
    // collide with a derived `<CC_ROOT>` subtree.
    if let Some(base) = base_dir {
        let base_abs = absolutize_path(cwd, base);
        for root in [base_abs.clone(), canonicalize_or_self(&base_abs)] {
            let from = root.to_string_lossy().to_string();
            if !from.is_empty() && !maps.iter().any(|m| m.from == from) {
                maps.push(CcPrefixMap {
                    from,
                    to: CC_BASE_SENTINEL.to_string(),
                });
            }
        }
    }

    // File-configured extra roots. Share PathNormalizer's lexical-first alias
    // reservation and Windows path variants so Rust and C/C++ assign the same
    // stable target on every host.
    for (from, to) in crate::path_normalizer::configured_base_dir_prefix_maps(configured_base_dirs)
    {
        if !from.is_empty() && !maps.iter().any(|m| m.from == from) {
            maps.push(CcPrefixMap { from, to });
        }
    }

    // Explicit roots win exact-prefix ties; derived roots cover everything
    // else. Longest-prefix sorting below handles overlapping configured roots.
    for map in cc_prefix_maps_for(parsed, cwd) {
        if !maps.iter().any(|existing| existing.from == map.from) {
            maps.push(map);
        }
    }

    // Apple SDK root (issue #78). The SDK path leaks into the key via the
    // resolved `cc -###` tokens; map it to `<SDKROOT>` so the same SDK at
    // a different install path (Xcode vs Command Line Tools, a teammate's
    // machine, a CI runner) keys identically. An explicit `-isysroot`
    // wins over the `SDKROOT` env value (`cc_sdk_root`). Distinct sentinel
    // — never a project root.
    if let Some(sdk) = cc_sdk_root(parsed, sdk_root) {
        let sdk_abs = absolutize_path(cwd, &sdk);
        for root in [sdk_abs.clone(), canonicalize_or_self(&sdk_abs)] {
            let from = root.to_string_lossy().to_string();
            if !from.is_empty() && !maps.iter().any(|m| m.from == from) {
                maps.push(CcPrefixMap {
                    from,
                    to: CC_SDKROOT_SENTINEL.to_string(),
                });
            }
        }
    }

    // Longest `from` first so the most specific prefix wins in the byte
    // normalizer (covers the derived roots, the base dir, and the SDK).
    maps.sort_by_key(|m| std::cmp::Reverse(m.from.len()));
    maps
}

/// Whether cc path normalization is active. `KACHE_CC_PATH_NORMALIZE` set
/// to `0` / `false` / `off` / `no` disables it; default on.
fn cc_path_normalize_enabled() -> bool {
    parse_cc_normalize_toggle(std::env::var("KACHE_CC_PATH_NORMALIZE").ok().as_deref())
}

fn parse_cc_normalize_toggle(value: Option<&str>) -> bool {
    match value {
        Some(v) => !matches!(
            v.trim().to_ascii_lowercase().as_str(),
            "0" | "false" | "off" | "no"
        ),
        None => true,
    }
}

/// The effective `SOURCE_DATE_EPOCH` kache pins on *both* the `-E` key probe
/// and the real compile, so a translation unit that bakes
/// `__DATE__` / `__TIME__` / `__TIMESTAMP__` into its object produces bytes
/// that match the time-stable cache key — no stale-timestamp false hit (#423).
///
/// Resolution (see [`resolve_source_date_epoch`]):
/// - the build's own `SOURCE_DATE_EPOCH` if it exported one (honored as-is, so
///   the key reflects the date the object actually bakes);
/// - otherwise `"0"`, kache's default pin that makes the key time-independent
///   so warm rebuilds hit;
/// - `None` only when the build set nothing *and* the user opted out via
///   `KACHE_CC_SOURCE_DATE_EPOCH=passthrough` — then kache pins nothing and the
///   object bakes wall-clock. The unpinned `-E` probe then produces a
///   time-dependent key, so a stale wall-clock object is very unlikely to be
///   reused (best-effort, not a guarantee: two probes landing in the same
///   second expand identically, so a cross-second cold store can still be hit).
fn effective_source_date_epoch() -> Option<std::ffi::OsString> {
    resolve_source_date_epoch(
        std::env::var_os("SOURCE_DATE_EPOCH"),
        source_date_epoch_passthrough(),
    )
}

/// Pure resolution of the effective `SOURCE_DATE_EPOCH` (env read separately so
/// this stays unit-testable). A build-exported value is honored **verbatim** —
/// the raw bytes, untrimmed — so kache never normalizes a value the compiler
/// would otherwise reject (e.g. `" 123 "`, `""`, non-UTF-8) into a different,
/// accepted one, which would turn a failing compile into a cached success. Only
/// when the build set nothing does kache pin its default `"0"`, unless the
/// caller opted out.
fn resolve_source_date_epoch(
    build_value: Option<std::ffi::OsString>,
    passthrough: bool,
) -> Option<std::ffi::OsString> {
    match build_value {
        Some(v) => Some(v),
        None if passthrough => None,
        None => Some(std::ffi::OsString::from("0")),
    }
}

/// Whether the build opted out of kache's default `SOURCE_DATE_EPOCH=0` pin via
/// `KACHE_CC_SOURCE_DATE_EPOCH=passthrough` (aliases: `wallclock` / `off`), for
/// the rare project that must bake the real wall-clock time into its objects.
/// Ignored when the build exports its own `SOURCE_DATE_EPOCH` (always honored).
fn source_date_epoch_passthrough() -> bool {
    std::env::var("KACHE_CC_SOURCE_DATE_EPOCH")
        .ok()
        .map(|v| {
            let v = v.trim().to_ascii_lowercase();
            v == "passthrough" || v == "wallclock" || v == "off"
        })
        .unwrap_or(false)
}

fn cc_memo_os_bytes(value: &OsStr) -> Vec<u8> {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        value.as_bytes().to_vec()
    }
    #[cfg(windows)]
    {
        use std::os::windows::ffi::OsStrExt;
        value.encode_wide().flat_map(u16::to_le_bytes).collect()
    }
    #[cfg(not(any(unix, windows)))]
    {
        value.to_string_lossy().into_owned().into_bytes()
    }
}

fn fold_cc_memo_field(hasher: &mut blake3::Hasher, label: &[u8], value: &[u8]) {
    hasher.update(&(label.len() as u64).to_le_bytes());
    hasher.update(label);
    hasher.update(&(value.len() as u64).to_le_bytes());
    hasher.update(value);
}

/// Environment variables that cannot change a preprocessor expansion and do
/// change between two otherwise identical invocations.
///
/// The memo key folds the environment wholesale, because compiler-specific
/// include variables are numerous and an extra miss is safer than overlooking
/// one. That stays true — this is a deny list, not an allow list, so anything
/// unrecognised is still keyed and the worst case remains a wasted preprocess.
///
/// Without it the memo is unreachable rather than merely conservative. A
/// shell exports `_`, `PWD` and `OLDPWD` fresh for every command, cargo hands
/// each build script a jobserver on file descriptors it picked this run, and
/// kache's own runtime variables move with the cache directory. Any one of
/// those gives every invocation its own key, so nothing is ever reused.
/// `cwd` is folded separately and explicitly, so dropping `PWD` here loses
/// nothing.
const CC_MEMO_VOLATILE_ENV: &[&str] = &[
    // Shell bookkeeping, rewritten per command.
    "_",
    "OLDPWD",
    "PWD",
    "SHLVL",
    // Build-driver parallelism: `--jobserver-fds=3,5` names this run's fds.
    "CARGO_MAKEFLAGS",
    "MAKEFLAGS",
    "MFLAGS",
    "MAKELEVEL",
    "NUM_JOBS",
];

/// Is this a variable the memo key deliberately ignores? kache's own
/// `KACHE_*` settings are included: they steer the wrapper, never the
/// preprocessor, and they differ between any two cache directories.
fn cc_memo_env_is_volatile(name: &OsStr) -> bool {
    let Some(name) = name.to_str() else {
        return false;
    };
    name.starts_with("KACHE_") || CC_MEMO_VOLATILE_ENV.contains(&name)
}

/// Local identity for a preprocessor invocation. The environment is included
/// apart from [`cc_memo_env_is_volatile`]: compiler-specific include
/// variables are numerous, and an extra miss is safer than overlooking one
/// that changes expansion.
fn cc_preprocess_memo_key(
    parsed: &CcArgs,
    prefix_maps: &[CcPrefixMap],
    compiler_version: &str,
) -> Option<String> {
    let epoch = effective_source_date_epoch()?;
    let cwd = std::env::current_dir().ok()?;
    let compiler_path = super::resolve_program_on_path(&parsed.program)?;
    let compiler_metadata = std::fs::metadata(&compiler_path).ok()?;
    let mut hasher = blake3::Hasher::new();
    // v4: the probe now runs with the compile's prefix maps, and path-bound
    // expansions are never recorded. A v3 record may hold the mapped hash of
    // one of those, which would give another checkout its key (#1004).
    // v5: TUs whose expansion `.incbin`s or `.include`s a file are refused. A
    // v4 record of one would skip the probe that refuses it (#1015).
    fold_cc_memo_field(&mut hasher, b"schema", b"cc-preprocess-memo-v5");
    fold_cc_memo_field(
        &mut hasher,
        b"compiler-program",
        cc_memo_os_bytes(OsStr::new(&parsed.program)).as_slice(),
    );
    fold_cc_memo_field(
        &mut hasher,
        b"compiler-path",
        cc_memo_os_bytes(compiler_path.as_os_str()).as_slice(),
    );
    fold_cc_memo_field(
        &mut hasher,
        b"compiler-size",
        &compiler_metadata.len().to_le_bytes(),
    );
    fold_cc_memo_field(
        &mut hasher,
        b"compiler-mtime",
        &crate::cache_key::metadata_mtime_ns(&compiler_metadata).to_le_bytes(),
    );
    fold_cc_memo_field(
        &mut hasher,
        b"compiler-ctime",
        &crate::cache_key::metadata_ctime_ns(&compiler_metadata).to_le_bytes(),
    );
    fold_cc_memo_field(
        &mut hasher,
        b"compiler-inode",
        &crate::cache_key::metadata_inode(&compiler_metadata).to_le_bytes(),
    );
    fold_cc_memo_field(
        &mut hasher,
        b"compiler-version",
        compiler_version.as_bytes(),
    );
    // The mapped cwd, not the raw one: two checkouts of the same tree differ
    // here and nowhere the expansion can see, so folding the raw path gave
    // every worktree its own memo.
    fold_cc_memo_field(
        &mut hasher,
        b"cwd",
        cc_mapped_path(&cwd, prefix_maps).as_bytes(),
    );
    fold_cc_memo_field(
        &mut hasher,
        b"source-date-epoch",
        cc_memo_os_bytes(&epoch).as_slice(),
    );
    // Likewise the argv: `-I` and the source path carry the checkout root.
    // The maps are folded below, so two trees agree here only when they agree
    // about what the mapping means.
    for arg in build_preprocess_args(parsed) {
        let mapped = apply_cc_prefix_maps_to_bytes(arg.into_bytes(), prefix_maps);
        fold_cc_memo_field(&mut hasher, b"arg", &mapped);
    }
    // Targets only. The sources are the per-checkout roots this whole change
    // exists to keep out; the targets are the sentinels both trees share, and
    // they are what decides whether two mappings mean the same thing.
    for map in prefix_maps {
        fold_cc_memo_field(&mut hasher, b"prefix-to", map.to.as_bytes());
    }

    let mut environment: Vec<(Vec<u8>, Vec<u8>)> = std::env::vars_os()
        .filter(|(name, _)| !cc_memo_env_is_volatile(name))
        .map(|(name, value)| (cc_memo_os_bytes(&name), cc_memo_os_bytes(&value)))
        .collect();
    environment.sort();
    for (name, value) in environment {
        fold_cc_memo_field(&mut hasher, b"env-name", &name);
        fold_cc_memo_field(&mut hasher, b"env-value", &value);
    }
    Some(hasher.finalize().to_hex().to_string())
}

fn cc_prefix_maps_for(parsed: &CcArgs, cwd: &Path) -> Vec<CcPrefixMap> {
    let cwd_abs = absolutize_path(cwd, cwd);
    let Some(source) = parsed.sources.first() else {
        return prefix_maps_from_roots([(cwd_abs, CC_BUILD_SENTINEL)]);
    };
    let source_abs = absolutize_path(cwd, source);
    let source_parent = source_abs
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| source_abs.clone());

    let mut roots: Vec<(PathBuf, &'static str)> = Vec::new();
    push_cwd_source_roots(&mut roots, &cwd_abs, &source_parent);

    let cwd_canon = canonicalize_or_self(&cwd_abs);
    let source_canon = canonicalize_or_self(&source_abs);
    let source_canon_parent = source_canon
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or(source_canon);
    if let Some(common) = common_ancestor(&cwd_canon, &source_canon_parent)
        && stable_cc_common_root(&common, &cwd_canon, &source_canon_parent)
    {
        roots.push((common, CC_ROOT_SENTINEL));
    }

    // Objdir-generated TUs (`Unified_cpp_*`, generated `.cpp`) live in the
    // build dir, so cwd ≈ source-dir and the roots above collapse to a
    // narrow objdir subdir — missing `__FILE__` paths into `dist/include`
    // and the source tree. The `-I` dirs span the repo, so fold them in:
    // the common ancestor of cwd and each include reaches the repo root.
    // `stable_cc_common_root`/`useful_cc_prefix` already drop the out-of-
    // tree ones — a system `-I` gives `/` (0 components) and `$HOME`-rooted
    // toolchain dirs give a 2-component ancestor, both below the ≥3 bound —
    // so only genuine in-tree roots survive. This is what makes
    // cross-checkout cc caching work automatically (no `KACHE_BASE_DIR`).
    for include in &parsed.includes {
        let include_abs = absolutize_path(cwd, include);
        for (a, b) in [
            (&cwd_abs, include_abs.clone()),
            (&cwd_canon, canonicalize_or_self(&include_abs)),
        ] {
            if let Some(common) = common_ancestor(a, &b)
                && stable_cc_common_root(&common, a, &b)
            {
                roots.push((common, CC_ROOT_SENTINEL));
            }
        }
    }

    prefix_maps_from_roots(roots)
}

/// Push the build (cwd) and source-dir roots, choosing the sentinel scheme by
/// TOPOLOGY rather than absolute location, so the same build converges
/// regardless of where its tree lives — the fix for out-of-tree build trees
/// (kunobi-ninja/kache#304, #394).
///
/// - **Nested** (one dir is under the other — the ordinary under-source build,
///   where the common ancestor IS the build or source dir): a single
///   `<CC_ROOT>` at the common ancestor is stable and preserves the
///   build↔source relative structure. Unchanged from before.
/// - **Sibling / out-of-tree** (the common ancestor is a *strict* ancestor of
///   both): the single-root scheme is fragile — whether the common ancestor is
///   judged "useful" depends on absolute properties (its depth, whether it is a
///   temp dir), so the SAME logical build picks `<CC_ROOT>` at one location and
///   split `<CC_BUILD>`/`<CC_SOURCE>` at another, and the cc key diverges.
///   Always use the split sentinels here (location-independent), and still fold
///   the shared root for paths under it (sibling includes) when it is a stable,
///   non-degenerate prefix. Prefix maps apply longest-first, so the split maps
///   (more specific) win for the build/source paths while `<CC_ROOT>` covers the
///   rest.
fn push_cwd_source_roots(
    roots: &mut Vec<(PathBuf, &'static str)>,
    cwd_abs: &Path,
    source_parent: &Path,
) {
    let common = common_ancestor(cwd_abs, source_parent);
    let nested = matches!(&common, Some(c) if c == cwd_abs || c == source_parent);
    if nested {
        if let Some(common) = common {
            roots.push((common, CC_ROOT_SENTINEL));
        }
    } else {
        roots.push((cwd_abs.to_path_buf(), CC_BUILD_SENTINEL));
        // Prefer the shared root over the source file's immediate parent. A
        // `<CC_ROOT>` at the common ancestor already strips the (clone-varying)
        // absolute prefix while PRESERVING the relative path below it
        // (e.g. `security/sandbox/chromium/base/location.cc`). The more-specific
        // `<CC_SOURCE>` at `source_parent` would win under longest-match and
        // collapse that parent directory to a flat sentinel — which gains no
        // cross-clone stability (the relative path is clone-invariant either
        // way) but BREAKS code that `static_assert`s on `__FILE__`, e.g.
        // Chromium's `base/location.cc`
        // (`StrEndsWith(__FILE__, …, "base/location.cc")`), failing the cold
        // Firefox build. Folding `<CC_ROOT>` keeps `__FILE__` ending in
        // `…/base/location.cc` so the assert holds.
        //
        // Gate on the common having a normal component — i.e. anything but a
        // bare filesystem root (`/`, a drive root) that would over-map unrelated
        // absolutes. This is a LOCATION-INDEPENDENT test, so the prefix-map
        // sentinel SET (hashed into the key) does not flip with absolute
        // location and an out-of-tree build still converges across machines / a
        // relocate (kunobi-ninja/kache#304, #394). Fall back to `<CC_SOURCE>`
        // only when there is no usable shared root, so a sibling source's
        // absolute path still cannot leak into the key.
        match common {
            Some(common) if has_normal_component(&common) => {
                roots.push((common, CC_ROOT_SENTINEL));
            }
            _ => {
                roots.push((source_parent.to_path_buf(), CC_SOURCE_SENTINEL));
            }
        }
    }
}

/// Whether `path` has at least one normal component — true for any real
/// directory, false only for a bare filesystem root (`/`) or a drive/UNC root.
/// Folding a bare root to a sentinel would collapse unrelated absolute paths.
fn has_normal_component(path: &Path) -> bool {
    path.components()
        .any(|c| matches!(c, std::path::Component::Normal(_)))
}

fn prefix_maps_from_roots<I>(roots: I) -> Vec<CcPrefixMap>
where
    I: IntoIterator<Item = (PathBuf, &'static str)>,
{
    let mut maps = Vec::new();
    for (root, to) in roots {
        let from = root.to_string_lossy().to_string();
        if from.is_empty() || maps.iter().any(|m: &CcPrefixMap| m.from == from) {
            continue;
        }
        maps.push(CcPrefixMap {
            from,
            to: to.to_string(),
        });
    }
    maps.sort_by_key(|m| std::cmp::Reverse(m.from.len()));
    maps
}

fn absolutize_path(base: &Path, path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        base.join(path)
    }
}

fn canonicalize_or_self(path: &Path) -> PathBuf {
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

fn common_ancestor(a: &Path, b: &Path) -> Option<PathBuf> {
    let mut out = PathBuf::new();
    for (left, right) in a.components().zip(b.components()) {
        if left != right {
            break;
        }
        out.push(left.as_os_str());
    }
    (!out.as_os_str().is_empty()).then_some(out)
}

fn useful_cc_prefix(path: &Path) -> bool {
    path.components()
        .filter(|c| matches!(c, std::path::Component::Normal(_)))
        .count()
        >= 3
}

fn stable_cc_common_root(common: &Path, cwd: &Path, source_parent: &Path) -> bool {
    if common == cwd || common == source_parent {
        return true;
    }
    if common_is_temp_dir(common) {
        return false;
    }
    useful_cc_prefix(common) || common_is_below_temp_dir(common)
}

fn common_is_below_temp_dir(common: &Path) -> bool {
    let temp_dir = canonicalize_or_self(&std::env::temp_dir());
    let common = canonicalize_or_self(common);
    common != temp_dir && common.starts_with(temp_dir)
}

fn common_is_temp_dir(common: &Path) -> bool {
    canonicalize_or_self(common) == canonicalize_or_self(&std::env::temp_dir())
}

/// Substitute build-path prefixes with their targets in a byte buffer (resolved
/// `-###` tokens, preprocessor stdout) for the cache key.
///
/// SINGLE left-to-right pass: at each position the most-specific matching map
/// wins, its target is emitted, and the cursor skips past the source WITHOUT
/// re-scanning the emitted target. This is deliberate now that targets are real
/// absolute paths (`/proc/self/cwd`, `/kache/*`, kunobi-ninja/kache#485): a
/// naive per-map sequential replace could re-match an earlier map's target with
/// a later map's source (e.g. a pathological `KACHE_BASE_DIR=/proc/self`
/// rewriting the `/proc/self/cwd` just written), diverging the key from the
/// compiler's single-application `-ffile-prefix-map`. Single-pass matches the
/// compiler's semantics and is identical to the old behavior for the normal case
/// of non-overlapping absolute source prefixes.
/// One path in the spelling the prefix maps give it, lossily for non-UTF-8.
///
/// The same rewrite the expansion and the resolved tokens already get, so a
/// path recorded here reads the same from any checkout the maps cover.
fn cc_mapped_path(path: &Path, prefix_maps: &[CcPrefixMap]) -> String {
    // Text, not `cc_memo_os_bytes`: that encodes UTF-16 on Windows, and the
    // map sources and targets are UTF-8, so nothing would ever match and
    // every Windows memo missed. The maps are applied to argv strings the
    // same way.
    let text = path.to_string_lossy().into_owned().into_bytes();
    String::from_utf8_lossy(&apply_cc_prefix_maps_to_bytes(text, prefix_maps)).into_owned()
}

/// blake3 of a file's contents with the prefix maps applied.
///
/// The expansion is hashed this way, so an input has to be compared this way
/// too. A `-sys` crate's generated config header names its own build
/// directory: the raw bytes differ between two checkouts, the mapped bytes do
/// not, and the expansion each produces is identical. Comparing raw bytes
/// alone therefore made the memo stricter than the key it feeds. `None` when
/// the file cannot be read, which the caller treats as "cannot reuse".
fn cc_mapped_content_hash(path: &Path, prefix_maps: &[CcPrefixMap]) -> Option<String> {
    let bytes = std::fs::read(path).ok()?;
    let mapped = apply_cc_prefix_maps_to_bytes(bytes, prefix_maps);
    Some(blake3::hash(&mapped).to_hex().to_string())
}

/// Candidate real paths a mapped spelling could name in this invocation.
///
/// The inverse of [`cc_mapped_path`], and inexact by nature: two roots can
/// share one sentinel, so this yields every prefix that could have produced
/// the recorded name, most specific first. Picking wrong is not a
/// correctness problem — the caller compares contents, so a candidate whose
/// bytes differ is a miss and the expansion is recomputed. A mapped path
/// with no matching sentinel yields nothing and the memo is skipped.
fn cc_unmapped_path_candidates(mapped: &str, prefix_maps: &[CcPrefixMap]) -> Vec<PathBuf> {
    let mut maps: Vec<&CcPrefixMap> = prefix_maps
        .iter()
        .filter(|map| !map.from.is_empty() && !map.to.is_empty())
        .collect();
    maps.sort_by_key(|map| std::cmp::Reverse(map.to.len()));

    let mut candidates: Vec<PathBuf> = Vec::new();
    for map in maps {
        if let Some(rest) = mapped.strip_prefix(map.to.as_str()) {
            let candidate = PathBuf::from(format!("{}{rest}", map.from));
            if !candidates.contains(&candidate) {
                candidates.push(candidate);
            }
        }
    }
    // An absolute path outside every mapped root (a system header, the
    // toolchain) was recorded verbatim and needs no inverse.
    if candidates.is_empty() && Path::new(mapped).is_absolute() {
        candidates.push(PathBuf::from(mapped));
    }
    candidates
}

fn apply_cc_prefix_maps_to_bytes(bytes: Vec<u8>, prefix_maps: &[CcPrefixMap]) -> Vec<u8> {
    // Most-specific (longest source) first so it wins at any position where two
    // sources overlap. (`cc_prefix_maps` already sorts this way; re-sort here so
    // callers passing ad-hoc maps get the same precedence.)
    let mut maps: Vec<&CcPrefixMap> = prefix_maps.iter().filter(|m| !m.from.is_empty()).collect();
    maps.sort_by_key(|m| std::cmp::Reverse(m.from.len()));

    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        let matched = maps.iter().find(|m| {
            let from = m.from.as_bytes();
            bytes[i..].starts_with(from)
                && (!is_configured_cc_prefix_map(m)
                    || configured_cc_prefix_starts_path_token(&bytes, i, from))
        });
        if let Some(m) = matched {
            out.extend_from_slice(m.to.as_bytes());
            i += m.from.len();
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    out
}

fn is_configured_cc_prefix_map(map: &CcPrefixMap) -> bool {
    map.to
        .strip_prefix("/kache/base-dir-")
        .is_some_and(|index| !index.is_empty() && index.bytes().all(|byte| byte.is_ascii_digit()))
}

fn configured_cc_prefix_starts_path_token(input: &[u8], start: usize, prefix: &[u8]) -> bool {
    if !cc_windows_absolute_prefix(prefix) && cc_follows_windows_drive_prefix(input, start) {
        return false;
    }
    let before = &input[..start];
    start == 0
        || before.ends_with(b"-I")
        || before.ends_with(b"-L")
        || before.ends_with(b"-F")
        || before.ends_with(b"-B")
        || before.last().is_some_and(|byte| {
            byte.is_ascii_whitespace()
                || matches!(
                    byte,
                    b'=' | b':' | b';' | b',' | b'"' | b'\'' | b'(' | b'[' | b'{' | b'@'
                )
        })
}

fn cc_windows_absolute_prefix(prefix: &[u8]) -> bool {
    (prefix.len() >= 3
        && prefix[0].is_ascii_alphabetic()
        && prefix[1] == b':'
        && matches!(prefix[2], b'/' | b'\\'))
        || prefix.starts_with(b"//")
        || prefix.starts_with(b"\\\\")
}

fn cc_follows_windows_drive_prefix(input: &[u8], start: usize) -> bool {
    if start < 2 || input[start - 1] != b':' || !input[start - 2].is_ascii_alphabetic() {
        return false;
    }
    let lead = &input[..start - 2];
    lead.is_empty()
        || lead.ends_with(b"-I")
        || lead.ends_with(b"-L")
        || lead.ends_with(b"-F")
        || lead.ends_with(b"-B")
        || lead.last().is_some_and(|byte| {
            byte.is_ascii_whitespace()
                || matches!(
                    byte,
                    b'=' | b':' | b';' | b',' | b'"' | b'\'' | b'(' | b'[' | b'{' | b'@'
                )
        })
}

/// The compiler receives the broadest map first and the most specific
/// last, mirroring rustc remap ordering. The byte-normalizer above
/// applies most-specific first.
fn file_prefix_map_args(prefix_maps: &[CcPrefixMap]) -> Vec<String> {
    prefix_maps
        .iter()
        .rev()
        .map(|m| format!("-ffile-prefix-map={}={}", m.from, m.to))
        .collect()
}

/// Compose the final argv for an `execute` invocation: the original
/// args with kache's `appended` flags placed *before* the `--`
/// end-of-options separator if one is present, otherwise at the end.
///
/// The clang / clang-cl driver treats every token after `--` as an
/// input file, not a flag — and cc-rs emits `--` before the source on
/// clang-cl invocations. Appending `-ffile-prefix-map=…` after that
/// separator makes the driver see the flags as extra source files,
/// producing `clang-cl: error: cannot specify '-Fo…' when compiling
/// multiple source files` (#300). Splicing them in ahead of `--` keeps
/// them classified as options. With no `--` present this is a plain
/// append, identical to the prior behaviour.
///
/// Splices before the *first* bare `--` — the only token clang/clang-cl/
/// gcc treat as the end-of-options marker (later `--` are inputs). It
/// matches `rest` literally, so a `--` that is some option's separated
/// value, or one hidden inside an `@response-file`, is not recognised;
/// both are out of scope for the cc-rs `-c` compiles that reach here.
fn compose_cc_args(rest: &[String], appended: Vec<String>) -> Vec<String> {
    if appended.is_empty() {
        return rest.to_vec();
    }
    match rest.iter().position(|a| a == "--") {
        Some(sep) => {
            let mut out = Vec::with_capacity(rest.len() + appended.len());
            out.extend_from_slice(&rest[..sep]);
            out.extend(appended);
            out.extend_from_slice(&rest[sep..]);
            out
        }
        None => {
            let mut out = rest.to_vec();
            out.extend(appended);
            out
        }
    }
}

fn cc_trace_name(parsed: &CcArgs) -> String {
    parsed
        .sources
        .first()
        .and_then(|p| p.file_name())
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| "cc".to_string())
}

/// Digest the shadowing risk for the headers a preprocess actually read.
///
/// The walk below exists because a header appearing in an earlier include
/// directory can shadow one that was read, without changing any recorded
/// fingerprint. It answers that by listing everything that could exist. This
/// answers it by looking only at what could actually shadow: a new file can
/// only take the place of a header we read if it carries the **same relative
/// name** and sits **earlier in the search order** than the directory that
/// provided it.
///
/// So for each header read, resolve which user include directory first
/// provides its relative name and fold that position. A file appearing ahead
/// of it moves the position and therefore the key; a file appearing anywhere
/// else cannot shadow anything and is correctly ignored, where the walk would
/// have invalidated every unit naming that directory.
///
/// Costs one `stat` per candidate directory up to the first that provides the
/// name, rather than a full enumeration, so there is no cap to exceed. A stat
/// that fails for any reason other than absence fails closed, as the walk
/// does for an unreadable directory.
fn digest_cc_include_shadowing(parsed: &CcArgs, read_inputs: &[PathBuf]) -> Result<String> {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let dirs = cc_user_include_dirs(parsed, &cwd);

    // One entry per distinct relative name: the same header read twice, or
    // two units reading it, resolve identically.
    let mut names: Vec<PathBuf> = Vec::new();
    for input in read_inputs {
        let absolute = absolutize_path(&cwd, input);
        // Two spellings could have reached this file, and the search order
        // is checked for both. The path relative to the MOST SPECIFIC user
        // directory containing it, which is what an `#include "sub/h.h"`
        // resolves through; directories nest, so the first match is not
        // necessarily the one that provided it. And the bare file name,
        // which is what an angle include resolves through and the only
        // spelling available for a header read from outside every user
        // directory. Folding both over-detects rather than under-detects:
        // an extra resolution can only cost a miss.
        let mut candidates: Vec<PathBuf> = Vec::new();
        if let Some(relative) = dirs
            .iter()
            .filter_map(|dir| absolute.strip_prefix(dir).ok())
            .min_by_key(|relative| relative.components().count())
        {
            candidates.push(relative.to_path_buf());
        }
        if let Some(file_name) = absolute.file_name() {
            candidates.push(PathBuf::from(file_name));
        }
        for candidate in candidates {
            if !names.contains(&candidate) {
                names.push(candidate);
            }
        }
    }
    names.sort();

    let mut hasher = blake3::Hasher::new();
    for name in &names {
        hasher.update(name.as_os_str().as_encoded_bytes());
        hasher.update(b"\x1f");
        match cc_first_include_dir_providing(&dirs, name)? {
            Some(index) => {
                hasher.update(b"@");
                hasher.update(index.to_string().as_bytes());
            }
            None => {
                hasher.update(b"-");
            }
        }
        hasher.update(b"\n");
    }
    Ok(hasher.finalize().to_hex().to_string())
}

/// Index of the first user include directory that provides `name`, stopping
/// at the first hit. `None` when no directory does, which is itself a fact
/// worth keying: a directory later gaining the name changes it.
fn cc_first_include_dir_providing(dirs: &[PathBuf], name: &Path) -> Result<Option<usize>> {
    for (index, dir) in dirs.iter().enumerate() {
        let candidate = dir.join(name);
        match std::fs::symlink_metadata(&candidate) {
            Ok(_) => return Ok(Some(index)),
            Err(error) if error.kind() == ErrorKind::NotFound => {}
            Err(error) => anyhow::bail!(
                "cc include candidate {} is unreadable ({error})",
                candidate.display()
            ),
        }
    }
    Ok(None)
}

/// Maximum file names walked across every user include dir. A partial
/// listing could miss the shadowing header the digest exists to catch,
/// so overflow is fail-closed passthrough rather than a truncated key.
const CC_INCLUDE_DIR_NAME_CAP: usize = 8192;

const CC_INCLUDE_DIR_NAME_EXTENSIONS: &[&str] = &[
    "h", "hh", "hpp", "hxx", "h++", "cuh", "c", "cc", "cpp", "cxx", "c++", "m", "mm", "i", "ii",
    "inl", "inc", "def", "pch", "gch",
];

fn digest_cc_include_dir_names(parsed: &CcArgs) -> Result<String> {
    digest_cc_include_dir_names_capped(parsed, CC_INCLUDE_DIR_NAME_CAP)
}

fn digest_cc_include_dir_names_capped(parsed: &CcArgs, cap: usize) -> Result<String> {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let exempt = cc_system_include_dirs(parsed, &cwd);
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"include_dir_names.v1\n");
    let mut seen = 0usize;
    for dir in cc_user_include_dirs(parsed, &cwd) {
        if exempt.iter().any(|root| dir.starts_with(root)) {
            continue;
        }
        hasher.update(b"dir\n");
        collect_include_dir_names(&dir, Path::new(""), &mut hasher, &mut seen, cap)?;
        hasher.update(b"enddir\n");
    }
    Ok(hasher.finalize().to_hex().to_string())
}

fn cc_user_include_dirs(parsed: &CcArgs, cwd: &Path) -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    let mut seen = HashSet::new();
    let mut push = |path: PathBuf| {
        let abs = absolutize_path(cwd, &path);
        if seen.insert(abs.clone()) {
            dirs.push(abs);
        }
    };
    if let Some(source) = parsed.sources.first() {
        let parent = source.parent().filter(|p| !p.as_os_str().is_empty());
        push(parent.map_or_else(|| cwd.to_path_buf(), Path::to_path_buf));
    }
    for value in cc_flag_dir_values(&parsed.rest, "-iquote") {
        push(PathBuf::from(value));
    }
    for include in &parsed.includes {
        push(include.clone());
    }
    dirs
}

fn cc_system_include_dirs(parsed: &CcArgs, cwd: &Path) -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    let mut seen = HashSet::new();
    let mut push = |path: PathBuf| {
        let abs = absolutize_path(cwd, &path);
        if seen.insert(abs.clone()) {
            dirs.push(abs);
        }
    };
    for value in cc_flag_dir_values(&parsed.rest, "-isystem") {
        push(PathBuf::from(value));
    }
    for value in cc_flag_dir_values(&parsed.rest, "-isysroot") {
        push(PathBuf::from(value));
        push(PathBuf::from(value).join("usr/include"));
    }
    if let Ok(sdk) = std::env::var("SDKROOT") {
        let path = PathBuf::from(sdk);
        if path.is_dir() {
            push(path.clone());
            push(path.join("usr/include"));
        }
    }
    dirs
}

fn cc_flag_dir_values<'a>(rest: &'a [String], flag: &'a str) -> Vec<&'a str> {
    let mut values = Vec::new();
    let mut args = rest.iter();
    while let Some(arg) = args.next() {
        let Some(suffix) = arg.strip_prefix(flag) else {
            continue;
        };
        if suffix.is_empty() {
            if let Some(value) = args.next() {
                values.push(value.as_str());
            }
        } else if let Some(value) = suffix.strip_prefix('=')
            && !value.is_empty()
        {
            values.push(value);
        }
    }
    values
}

fn collect_include_dir_names(
    dir: &Path,
    rel: &Path,
    hasher: &mut blake3::Hasher,
    seen: &mut usize,
    cap: usize,
) -> Result<()> {
    let entries = match fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(()),
        Err(error) => {
            anyhow::bail!("cc include dir {} is unreadable ({error})", dir.display())
        }
    };

    let mut files = Vec::new();
    let mut subdirs = Vec::new();
    for entry in entries {
        let entry = entry.with_context(|| format!("reading {}", dir.display()))?;
        let file_type = entry
            .file_type()
            .with_context(|| format!("stat {}", entry.path().display()))?;
        let name = entry.file_name();
        if file_type.is_symlink() {
            // Hash the name (it can shadow) but do not recurse; a
            // symlink dir can loop.
            if cc_include_name_counts(&name) {
                files.push(name);
            }
            continue;
        }
        if file_type.is_dir() {
            subdirs.push(name);
            continue;
        }
        if cc_include_name_counts(&name) {
            files.push(name);
        }
    }
    files.sort();
    subdirs.sort();

    for name in files {
        *seen += 1;
        if *seen > cap {
            anyhow::bail!("cc include dir name walk exceeded {cap} entries");
        }
        let path = rel.join(&name);
        hasher.update(path.as_os_str().as_encoded_bytes());
        hasher.update(b"\n");
    }
    for name in subdirs {
        *seen += 1;
        if *seen > cap {
            anyhow::bail!("cc include dir name walk exceeded {cap} entries");
        }
        collect_include_dir_names(&dir.join(&name), &rel.join(&name), hasher, seen, cap)?;
    }
    Ok(())
}

fn cc_include_name_counts(name: &OsStr) -> bool {
    let Some(ext) = Path::new(name).extension() else {
        return true;
    };
    let ext = ext.to_string_lossy();
    CC_INCLUDE_DIR_NAME_EXTENSIONS
        .iter()
        .any(|keep| ext.eq_ignore_ascii_case(keep))
}

struct PendingCcPreprocessMemo {
    memo_key: String,
    preprocessed_hash: String,
    fingerprints: Vec<crate::cache_key::CcPreprocessMemoInput>,
    /// The maps the expansion and the inputs were hashed under. Revalidation
    /// at commit time has to use the same ones.
    prefix_maps: Vec<CcPrefixMap>,
}

#[derive(Default)]
pub struct CcCompiler {
    /// User-declared flags (issue #95) that kache's built-in allow-list
    /// doesn't model but the user opted into caching. A flag here stops
    /// refusing and is folded verbatim into the cache key. Empty in the
    /// common case (and for every existing `CcCompiler::new()` caller).
    extra_allowlist_flags: Vec<String>,
    /// Deterministically ordered `[paths].base_dirs` roots applied to both the
    /// cc key probes and the real compiler invocation.
    base_dirs: Vec<String>,
    pending_preprocess_memo: RefCell<Option<PendingCcPreprocessMemo>>,
    /// The shadowing digest folded into the key, with the read set it was
    /// resolved from, so the publish-time recheck can reproduce it exactly.
    pending_include_dir_digest: RefCell<Option<(String, Option<Vec<PathBuf>>)>>,
    /// The last key bound itself to this checkout's roots. `execute` stores an
    /// object that embeds a raw root only under such a key.
    key_path_bound: Cell<bool>,
}

const C_FAMILY_DRIVERS: [(&str, ToolFamily); 7] = [
    ("clang-cl", ToolFamily::ClangCl),
    ("clang++", ToolFamily::Clang),
    ("clang", ToolFamily::Clang),
    ("gcc", ToolFamily::Gnu),
    ("g++", ToolFamily::Gnu),
    ("c++", ToolFamily::Gnu),
    ("cc", ToolFamily::Gnu),
];

fn is_compiler_version_suffix(suffix: &str) -> bool {
    !suffix.is_empty()
        && suffix.split('.').all(|component| {
            !component.is_empty() && component.bytes().all(|byte| byte.is_ascii_digit())
        })
}

fn strip_compiler_qualifiers(mut name: &str) -> (&str, bool) {
    let mut removed_version = false;
    let mut removed_mingw_flavor = false;
    while let Some((head, suffix)) = name.rsplit_once('-') {
        if !removed_version && is_compiler_version_suffix(suffix) {
            removed_version = true;
            name = head;
        } else if !removed_mingw_flavor && matches!(suffix, "posix" | "win32") {
            removed_mingw_flavor = true;
            name = head;
        } else {
            break;
        }
    }
    (name, removed_mingw_flavor)
}

fn named_tool_family(name: &str) -> Option<ToolFamily> {
    let (base, removed_mingw_flavor) = strip_compiler_qualifiers(name);
    C_FAMILY_DRIVERS.iter().find_map(|(driver, family)| {
        let exact = base == *driver;
        let target_prefixed = base.strip_suffix(driver).is_some_and(|prefix| {
            prefix.strip_suffix('-').is_some_and(|target| {
                !target.is_empty() && target.bytes().any(|byte| byte.is_ascii_alphanumeric())
            })
        });
        if !exact && !target_prefixed {
            return None;
        }
        // `-posix` and `-win32` are MinGW GCC-compatible alternatives, not
        // generic suffixes that should make clang-family tools look compilable.
        if removed_mingw_flavor && *family != ToolFamily::Gnu {
            return None;
        }
        Some(*family)
    })
}

fn is_unresolvable_bare_program(program: &str) -> bool {
    if program.contains('/') {
        return false;
    }
    if program.contains('\\') {
        return false;
    }
    super::resolve_program_on_path(program).is_none()
}

impl CcCompiler {
    #[cfg(test)]
    pub fn new() -> Self {
        Self::default()
    }

    /// Construct with a user-declared cc flag allow-list (issue #95),
    /// typically `config.cc_extra_allowlist_flags`.
    pub fn with_extra_allowlist_flags(extra_allowlist_flags: Vec<String>) -> Self {
        Self {
            extra_allowlist_flags,
            base_dirs: Vec::new(),
            pending_preprocess_memo: RefCell::new(None),
            pending_include_dir_digest: RefCell::new(None),
            key_path_bound: Cell::new(false),
        }
    }

    pub fn with_base_dirs(mut self, base_dirs: Vec<String>) -> Self {
        self.base_dirs = base_dirs;
        self.base_dirs.sort();
        self.base_dirs.dedup();
        self
    }

    /// Publish the dependency snapshot from a full preprocess only after a
    /// successful compile or cache restore revalidated every input.
    pub(crate) fn commit_preprocess_memo(&self, file_hasher: &crate::cache_key::FileHasher<'_>) {
        let Some(pending) = self.pending_preprocess_memo.borrow_mut().take() else {
            return;
        };
        file_hasher.cc_preprocess_memo_record_if_unchanged(
            &pending.memo_key,
            &pending.preprocessed_hash,
            &pending.fingerprints,
            &|path| cc_mapped_content_hash(path, &pending.prefix_maps),
        );
    }

    /// True when user include-dir names still match the digest folded into
    /// the key. A new shadowing header during compile must not be published
    /// under the old key.
    pub(crate) fn include_dir_names_still_match(&self, parsed: &CcArgs) -> bool {
        let pending = self.pending_include_dir_digest.borrow();
        let Some((digest, read_inputs)) = pending.as_ref() else {
            return false;
        };
        // Recompute the way the key did. Resolving against a different set of
        // names than the key used would compare two unrelated digests and
        // refuse every store.
        let now = match read_inputs {
            Some(inputs) => digest_cc_include_shadowing(parsed, inputs),
            None => digest_cc_include_dir_names(parsed),
        };
        now.is_ok_and(|now| now == *digest)
    }

    /// Does this argv invoke a C-family compiler?
    ///
    /// Matches `cc`, `c++`, `gcc`, `g++`, `clang`, `clang++`, their
    /// versioned variants (`gcc-13`, `clang++-17`), and target-prefixed
    /// cross compilers (`arm-linux-gnueabihf-gcc`). Path-prefixed forms
    /// (`/usr/bin/cc`, `C:\path\clang.exe`) and Windows `.exe` suffixes
    /// are accepted.
    ///
    /// Owns its own detection rule; `super::detect_compiler` reaches it
    /// through this module's [`ADAPTER`] descriptor.
    pub fn recognizes(args: &[String]) -> bool {
        if super::is_workspace_wrapper_chain(args) {
            return false;
        }
        let Some(arg0) = args.first() else {
            return false;
        };
        let Some(name) = super::command_basename(arg0) else {
            return false;
        };
        let name = super::strip_windows_exe_suffix(name).to_ascii_lowercase();

        // Cross toolchains conventionally prefix the canonical driver with a
        // target triple. Match exact, versioned, target-prefixed, and supported
        // MinGW alternative names while leaving arbitrary companion suffixes
        // (`gcc-ar`, `gcc-nm`, `clang-format`) rejected.
        if named_tool_family(&name).is_some() {
            return true;
        }

        // zig cc wrappers generated by cargo-zigbuild (commonly used
        // for cross-compilation with glibc version pinning). These wrapper
        // scripts are named `zigcc-{target}.{glibc_ver}-{hash}.sh` and
        // delegate to `cargo-zigbuild zig cc -- ...`. Zig's cc is clang-based
        // (defines `__clang__`), so we treat it as a clang-family compiler.
        // See https://github.com/rust-cross/cargo-zigbuild.
        //
        // NOTE: A better long-term approach is dynamic compiler detection
        // via `-E` probing (as sccache does). That would cover *any*
        // cc-compatible wrapper regardless of its filename, rather than
        // maintaining a name-based allowlist. Tracked in follow-up.
        if name == "zigcc" || name.starts_with("zigcc-") {
            return true;
        }

        // ── Slow path: `-E` probe for unknown binaries ──
        if super::is_kache_subcommand_or_flag(&name) {
            return false;
        }
        if is_unresolvable_bare_program(arg0) {
            return false;
        }
        // A version/info query (e.g. Kani's `kani-compiler -vV`, #656) compiles
        // nothing, so there is nothing to cache — and *running* an unknown
        // program just to sniff its family would add a spurious invocation to a
        // pure passthrough. Leave it unrecognized so it passes through untouched.
        if super::is_version_or_info_query(&args[1..]) {
            return false;
        }

        crate::probe::probe_compiler_family(arg0).is_some()
    }

    /// Does this argv match the `cc` Rust crate's compiler-family
    /// probe shape, `kache -E <file>`?
    ///
    /// The cc crate uses this probe to detect compiler family
    /// (gcc / clang / MSVC) by reading `__VERSION__` from preprocessor
    /// output. It hardcodes `Command::new(program).arg("-E").arg(file)`,
    /// dropping any trailing args from `CC="kache cc"` — so without
    /// explicit passthrough kache would clap-error and the probe
    /// would silently fall back to a default family guess. Today
    /// that's a logged warning; once C/C++ caching lands and family
    /// identifies the cache key, it becomes silent miscaching across
    /// machines.
    ///
    /// Match is intentionally tight (`-E` + at least one more arg).
    /// Other probe shapes (`-?`, `-dumpmachine`, `-dumpversion`) can
    /// land here when their absence becomes a real symptom —
    /// over-broad matching would mask legitimate CLI typos.
    ///
    /// **Not a compiler adapter.** A probe is a non-compiler invocation
    /// pattern that happens to need passthrough. The dispatch in
    /// `run_wrapper_mode` checks this *before* the compiler match.
    pub fn recognizes_family_probe(args: &[String]) -> bool {
        args.len() >= 2 && args[0] == "-E"
    }
}

/// Does `key` name a `CC`/`CXX` compiler variable the `cc` crate reads?
///
/// Mirrors the crate's `getenv_with_target_prefixes("CC"|"CXX")`: the
/// bare name, a `<target>` suffix (`CC_aarch64_pc_windows_msvc`), or a
/// `TARGET_`/`HOST_` prefix. Deliberately excludes neighbours like
/// `CFLAGS`, `CXXFLAGS`, and `CCACHE_*` whose values are not
/// `<wrapper> <compiler>` pairs.
fn is_cc_family_env_key(key: &str) -> bool {
    let base = key
        .strip_prefix("TARGET_")
        .or_else(|| key.strip_prefix("HOST_"))
        .unwrap_or(key);
    base == "CC" || base == "CXX" || base.starts_with("CC_") || base.starts_with("CXX_")
}

/// Is `key` a C++ (`CXX`) compiler variable, as opposed to C (`CC`)?
fn is_cxx_env_key(key: &str) -> bool {
    let base = key
        .strip_prefix("TARGET_")
        .or_else(|| key.strip_prefix("HOST_"))
        .unwrap_or(key);
    base == "CXX" || base.starts_with("CXX_")
}

/// Does `token` (a path or bare name) refer to the kache binary itself?
fn probe_token_is_self(token: &str, self_stem: &str) -> bool {
    super::command_basename(token)
        .map(super::strip_windows_exe_suffix)
        .is_some_and(|name| name.eq_ignore_ascii_case(self_stem))
}

/// Recover the real compiler the `cc` crate dropped from a family probe.
///
/// When `CC="kache <compiler>"` the cc crate mis-parses it — kache is
/// not in the crate's hard-coded known-wrapper allowlist (`ccache`,
/// `sccache`, `distcc`, …), so it treats kache as the *compiler* and
/// `<compiler>` as a leading argument, then drops that argument when it
/// runs the family probe (`Command::new(path).arg("-E").arg(file)`).
/// kache therefore receives `kache -E <file>` with no compiler to
/// forward to.
///
/// The compiler is still recoverable: the very `CC`/`CXX` variable the
/// cc crate read still holds `kache <compiler>` in our environment.
/// Scan those variables, find the one whose first whitespace token is
/// us, and return `<compiler>` so the probe can forward to the real
/// thing — yielding the genuine compiler family instead of a wrong
/// default guess (issue #286: `cc` is absent on Windows MSVC, so the
/// old hard-coded `cc` forward failed and the build fell back to an
/// unsupported GNU family).
///
/// Selection mirrors the cc crate's own `getenv_with_target_prefixes`
/// precedence so kache forwards to the exact variable the crate read
/// when several are kache-wrapped (mozbuild sets a host *and* a target
/// compiler): for a given `<name>` in `CC`, then `CXX`, the order is
/// `<name>_<target>`, `<name>_<target-underscored>`, `TARGET_<name>`,
/// `<name>`, `HOST_<name>`. `target` comes from cargo's `TARGET` env
/// var (set for build scripts). When `target` is `None`, selection
/// falls back to a deterministic order (CC before CXX, then the
/// lexicographically smallest key) so it never depends on environment
/// iteration order.
///
/// `CC` is preferred over `CXX` because the probe file is C and kache
/// cannot tell from `-E <file>` alone whether the cc crate's probe
/// belongs to a C or C++ `Build`. When `CC` and `CXX` are kache-wrapped
/// with *different* compiler families this can mislabel a C++ probe —
/// harmless in practice (the cc crate treats GNU and Clang identically;
/// only MSVC diverges, and a kache-wrapped MSVC `CXX` paired with a
/// non-MSVC `CC` does not occur in real toolchains).
///
/// Returns `None` when no kache-wrapped compiler variable is present.
pub(crate) fn resolve_probe_compiler<I>(
    self_stem: &str,
    target: Option<&str>,
    env_vars: I,
) -> Option<String>
where
    I: IntoIterator<Item = (String, String)>,
{
    // Collect every kache-wrapped CC/CXX variable: key -> real compiler.
    let mut wrapped: HashMap<String, String> = HashMap::new();
    for (key, value) in env_vars {
        if !is_cc_family_env_key(&key) {
            continue;
        }
        let mut tokens = value.split_whitespace();
        let Some(first) = tokens.next() else { continue };
        // The first token must be us; otherwise this is a plain
        // compiler, not a kache-wrapped one.
        if !probe_token_is_self(first, self_stem) {
            continue;
        }
        let Some(real) = tokens.next() else { continue };
        // Guard against a degenerate `CC="kache kache"`.
        if probe_token_is_self(real, self_stem) {
            continue;
        }
        wrapped.entry(key).or_insert_with(|| real.to_string());
    }
    if wrapped.is_empty() {
        return None;
    }

    // cc-crate precedence: most-specific target var first, CC before CXX.
    for name in ["CC", "CXX"] {
        if let Some(t) = target {
            if let Some(c) = wrapped.get(&format!("{name}_{t}")) {
                return Some(c.clone());
            }
            let underscored = t.replace('-', "_");
            if underscored != t
                && let Some(c) = wrapped.get(&format!("{name}_{underscored}"))
            {
                return Some(c.clone());
            }
            if let Some(c) = wrapped.get(&format!("TARGET_{name}")) {
                return Some(c.clone());
            }
        }
        if let Some(c) = wrapped.get(name) {
            return Some(c.clone());
        }
        if let Some(c) = wrapped.get(&format!("HOST_{name}")) {
            return Some(c.clone());
        }
    }

    // No precedence key matched (e.g. only a target-suffixed var for an
    // unknown target): deterministic fallback — CC family before CXX,
    // then the lexicographically smallest key.
    let mut keys: Vec<&String> = wrapped.keys().collect();
    keys.sort_by(|a, b| {
        is_cxx_env_key(a)
            .cmp(&is_cxx_env_key(b))
            .then_with(|| a.cmp(b))
    });
    keys.first().map(|k| wrapped[*k].clone())
}

impl Compiler for CcCompiler {
    type Parsed = CcArgs;

    fn id(&self) -> CompilerId {
        CC_ID
    }

    fn parse(&self, args: &[String]) -> Result<CcArgs> {
        CcArgs::parse(args)
    }

    fn refuse_reasons(&self, parsed: &CcArgs) -> Vec<RefuseReason> {
        // Per-case detection from the parsed shape. The skeleton
        // catch-all is gone — single-source `-c` compiles with no
        // unsafe flags now produce an EMPTY refuse list, which is the
        // signal to the wrapper that this invocation is cacheable.
        parsed.refuse_reasons(&self.extra_allowlist_flags)
    }

    fn cache_key(&self, parsed: &CcArgs, ctx: &KeyCtx<'_, '_>) -> Result<String> {
        // Preconditions (guaranteed by the wrapper checking
        // refuse_reasons first): `-c` mode, exactly one source.
        self.pending_preprocess_memo.borrow_mut().take();
        self.key_path_bound.set(false);
        let mut hasher = blake3::Hasher::new();
        let trace_name = cc_trace_name(parsed);
        let prefix_maps = cc_prefix_maps(parsed, &self.base_dirs);

        hasher.update(b"cc_key_version:");
        hasher.update(crate::cache_key::CACHE_KEY_VERSION.to_string().as_bytes());
        hasher.update(b"\n");
        tracing::trace!(
            target: "kache::cache_key",
            "[key:{}] cc_key_version={}",
            trace_name,
            crate::cache_key::CACHE_KEY_VERSION
        );

        if !self.base_dirs.is_empty() {
            hasher.update(b"configured_base_dirs.v1:");
            hasher.update(self.base_dirs.len().to_string().as_bytes());
            hasher.update(b"\n");
            tracing::trace!(
                target: "kache::cache_key",
                "[key:{}] configured_base_dirs={}",
                trace_name,
                self.base_dirs.len()
            );
        }

        let mut prefix_sentinels: Vec<&str> = Vec::new();
        for map in &prefix_maps {
            if !prefix_sentinels.contains(&map.to.as_str()) {
                prefix_sentinels.push(map.to.as_str());
            }
        }
        prefix_sentinels.sort_unstable();

        // Expansions that spell out a checkout root are hashed raw (see
        // `hash_cc_expansion`). Naming the scheme retires entries stored before
        // it, which mapped those roots to a sentinel and could hand another
        // checkout an object naming this one (kunobi-ninja/kache#1004).
        hasher.update(b"expansion_roots:literal-bound.v1\n");

        hasher.update(b"prefix_maps:");
        for sentinel in prefix_sentinels {
            hasher.update(sentinel.as_bytes());
            hasher.update(b"\x1f");
            tracing::trace!(
                target: "kache::cache_key",
                "[key:{}] cc_prefix_map={}",
                trace_name,
                sentinel
            );
        }
        hasher.update(b"\n");

        // Compiler identity: family name (cc / gcc / clang — affects
        // codegen defaults) + the version string.
        let program_name = Path::new(&parsed.program)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(parsed.program.as_str());
        hasher.update(b"compiler:");
        hasher.update(program_name.as_bytes());
        hasher.update(b"\n");
        tracing::trace!(
            target: "kache::cache_key",
            "[key:{}] compiler={}",
            trace_name,
            program_name
        );
        // Compiler probe, memoized: the version line (`cc --version`,
        // compiler identity) and the resolved invocation (`cc -###`,
        // the driver's fully-expanded `-cc1` line). One probe per build
        // per flag set; the rest of the build reads the record.
        let config_args = parsed.config_args();
        // Per-TU paths to blank from the shared probe record's resolved
        // tokens, so the record is invariant across the build's TUs and
        // parallel builds don't race on whose paths it holds (#keyrace).
        let per_tu_paths = cc_resolved_per_tu_paths(parsed);
        let resolved = crate::probe::probe(
            ctx.cache_dir,
            &crate::probe::CcProber,
            &crate::probe::ProbeRequest {
                compiler: &parsed.program,
                args: &parsed.rest,
                key_args: &config_args,
                per_tu_paths: &per_tu_paths,
                // Sentinel Windows paths only for gnu/clang (objects are
                // remapped via -ffile-prefix-map). clang-cl keeps raw
                // native paths → key stays path-literal (#299/#312).
                windows_aware: parsed.family.dialect() != Dialect::Cl,
            },
        )?;
        if resolved.resolved_tokens.is_none() && cc_flags_need_resolved_invocation(parsed) {
            anyhow::bail!("cc: resolved invocation unavailable for probe-captured flags");
        }
        hasher.update(b"compiler_version:");
        hasher.update(resolved.version_line.as_bytes());
        hasher.update(b"\n");
        tracing::trace!(
            target: "kache::cache_key",
            "[key:{}] compiler_version={}",
            trace_name,
            resolved.version_line
        );

        // Resolved compiler invocation: the `cc -###` `-cc1` line with
        // host-local paths sentinelled. Captures codegen the modeled
        // flags below miss — compiler defaults (`-mrelocation-model`,
        // `-ffp-contract`, the resolved `-target-cpu` and feature set).
        // If `-###` cannot be resolved, we can only proceed when no
        // accepted flag relies on those resolved tokens for safety.
        //
        // Tokens are hashed IN ORDER, and order is significant — that
        // is correct, not an oversight. `cc -###` is deterministic, so
        // the same (compiler, flags, env) always yields the same token
        // order: the key is stable, with no spurious misses. The tokens
        // must NOT be sorted — they interleave flag/value pairs as
        // adjacent elements (`-target-cpu`, `apple-m1`), so sorting the
        // flat list would scramble those pairs. The only cost of
        // order-significance is that two *different* flag invocations
        // that happen to resolve to the same object (same tokens,
        // different order) get different keys — a cache miss, never a
        // miscache. That is the safe direction.
        if let Some(tokens) = &resolved.resolved_tokens {
            hasher.update(b"resolved:");
            for tok in tokens {
                // Resolved `cc -###` tokens carry absolute build paths —
                // `-I` dirs, `-D NAME="/abs/.../foo.ico"` defines, input /
                // `-o` paths — that embed the build directory. Hashing them
                // raw makes the key path-dependent, so two builds of the
                // same TU at different paths (a teammate's checkout, a CI
                // runner, the bench's cross-clone warm phase) miss. Run them
                // through the SAME prefix maps as the preprocessor stdout so
                // the build root collapses to `<CC_ROOT>`/`<CC_BUILD>` and
                // the key is path-portable. Mapping only ever merges keys
                // that differ solely in build path (same object, remapped at
                // compile time via `-ffile-prefix-map`) — never a miscache.
                let mapped = apply_cc_prefix_maps_to_bytes(tok.clone().into_bytes(), &prefix_maps);
                hasher.update(&mapped);
                hasher.update(b"\x1f");
                tracing::trace!(
                    target: "kache::cache_key",
                    "[key:{}] resolved_token={}",
                    trace_name,
                    String::from_utf8_lossy(&mapped)
                );
            }
            hasher.update(b"\n");
        }

        // Target architecture.
        let arch = cc_target_arch(parsed);
        hasher.update(b"arch:");
        hasher.update(arch.as_bytes());
        hasher.update(b"\n");
        tracing::trace!(
            target: "kache::cache_key",
            "[key:{}] arch={}",
            trace_name,
            arch
        );

        // Codegen-affecting flags. These are partly redundant with
        // the preprocessor hash (defines affect macro expansion,
        // -std gates language features) but the redundancy is cheap
        // and defends against e.g. -std affecting codegen without
        // changing the expanded text.
        if let Some(opt) = parsed.optimization {
            hasher.update(b"opt:");
            hasher.update(format!("{opt:?}").as_bytes());
            hasher.update(b"\n");
            tracing::trace!(
                target: "kache::cache_key",
                "[key:{}] opt={opt:?}",
                trace_name
            );
        }
        if let Some(dbg) = parsed.debug_level {
            hasher.update(b"debug:");
            hasher.update(&[dbg]);
            hasher.update(b"\n");
            tracing::trace!(
                target: "kache::cache_key",
                "[key:{}] debug={dbg}",
                trace_name
            );
        }
        // clang-cl debug objects embed per-TU path inputs the rest of
        // the key misses: the source path/filename and output (-Fo) name
        // (both stripped from config_args, so the memoized `-###` tokens
        // can't be trusted for them) and the compilation dir (CWD, not in
        // the key at all). Fold them so distinct objects never share a
        // key — capture, not remap (clang-cl is path-literal; #299/#312).
        if let Some(paths) = cl_debug_path_inputs(parsed) {
            hasher.update(b"cl_debug_paths:");
            for p in &paths {
                hasher.update(p.as_bytes());
                hasher.update(b"\x1f");
                tracing::trace!(
                    target: "kache::cache_key",
                    "[key:{}] cl_debug_path={}",
                    trace_name,
                    p
                );
            }
            hasher.update(b"\n");
        }
        if let Some(std) = &parsed.std {
            hasher.update(b"std:");
            hasher.update(std.as_bytes());
            hasher.update(b"\n");
            tracing::trace!(
                target: "kache::cache_key",
                "[key:{}] std={}",
                trace_name,
                std
            );
        }
        hasher.update(b"pic:");
        hasher.update(&[parsed.pic as u8]);
        hasher.update(b"\n");
        tracing::trace!(
            target: "kache::cache_key",
            "[key:{}] pic={}",
            trace_name,
            parsed.pic
        );

        // Built-in raw-keyed flags have object effects the resolved compiler
        // probe does not expose (notably GNU assembler-only `-Wa` options).
        // Hash their normalized argument bytes in argv order; a length prefix
        // keeps adjacent arguments unambiguous without assuming any character
        // cannot appear in an argv element.
        let raw_flags = cc_raw_flags_for_key(parsed, &prefix_maps);
        if !raw_flags.is_empty() {
            hasher.update(b"cc_raw_flags:");
            for flag in raw_flags {
                hasher.update(&(flag.len() as u64).to_le_bytes());
                hasher.update(&flag);
                tracing::trace!(
                    target: "kache::cache_key",
                    "[key:{}] cc_raw_flag={}",
                    trace_name,
                    String::from_utf8_lossy(&flag)
                );
            }
            hasher.update(b"\n");
        }

        // User-declared cc flags (issue #95). The built-in table doesn't
        // model these; the user opted them into caching via
        // `[cc] extra_allowlist_flags`. kache can't know how each affects
        // codegen, so it folds the flag string *verbatim* — a different
        // flag (or value) is a different string, hence a different key
        // (never a miscache by value). Only flags actually present on the
        // command line are folded (an unused allow-list entry has no
        // codegen effect and must not move the key), sorted + deduped so
        // argv order and repeats don't perturb the key.
        let matched = cc_extra_flags_for_key(parsed, &self.extra_allowlist_flags);
        if !matched.is_empty() {
            hasher.update(b"cc_extra_flags:");
            for flag in matched {
                hasher.update(flag.as_bytes());
                hasher.update(b"\x1f");
                tracing::trace!(
                    target: "kache::cache_key",
                    "[key:{}] cc_extra_flag={}",
                    trace_name,
                    flag
                );
            }
            hasher.update(b"\n");
        }

        // The object bytes do not depend on dep-info flags, but the cached
        // artifact set now can include a `.d` sidecar. Key the dep-info
        // content shape so an object-only entry never satisfies an invocation
        // that expects dependency output, and so flags like `-MD` vs `-MMD`
        // or `-MT` do not share incompatible sidecars.
        // Every field folded here is also emitted to the `kache::cache_key`
        // trace target so `KACHE_E2E_KEYTRACE` can attribute a cross-clone miss
        // to dep-info (these were previously folded but untraced, leaving such
        // divergences invisible in the keytrace diff).
        hasher.update(b"depinfo:");
        if let Some(depinfo) = parsed.depinfo.as_ref().filter(|d| d.emit) {
            hasher.update(b"1\n");
            hasher.update(b"depinfo_include_system:");
            hasher.update(&[depinfo.include_system as u8]);
            hasher.update(b"\n");
            hasher.update(b"depinfo_phony_targets:");
            hasher.update(&[depinfo.phony_targets as u8]);
            hasher.update(b"\n");
            hasher.update(b"depinfo_missing_generated:");
            hasher.update(&[depinfo.missing_generated as u8]);
            hasher.update(b"\n");
            // `depinfo_target` is the make target from `-MT` (else the object
            // file *name*, basename-only). It is hashed raw — keep an eye on it
            // in the trace: a build-path-bearing `-MT` would leak here.
            let depinfo_target: std::borrow::Cow<str> = if let Some(target) = &depinfo.target {
                std::borrow::Cow::Borrowed(target.as_str())
            } else if let Some(object) = parsed.object_output_path()
                && let Some(name) = object.file_name()
            {
                std::borrow::Cow::Owned(name.to_string_lossy().into_owned())
            } else {
                std::borrow::Cow::Borrowed("")
            };
            hasher.update(b"depinfo_target:");
            hasher.update(depinfo_target.as_bytes());
            hasher.update(b"\n");
            tracing::trace!(
                target: "kache::cache_key",
                "[key:{}] depinfo=1 include_system={} phony_targets={} missing_generated={} target={}",
                trace_name,
                depinfo.include_system,
                depinfo.phony_targets,
                depinfo.missing_generated,
                depinfo_target
            );
        } else {
            hasher.update(b"0\n");
            tracing::trace!(
                target: "kache::cache_key",
                "[key:{}] depinfo=0",
                trace_name
            );
        }

        // Preprocessor expansion — the load-bearing input. Captures
        // the source plus every transitively-included header plus
        // macro expansion. `-E -P` strips line markers so header
        // PATHS don't leak (cross-machine portable); SOURCE_DATE_EPOCH
        // pins __DATE__/__TIME__ (stable across builds).
        let memo_key = ctx
            .file_hasher
            .supports_cc_preprocess_memo()
            .then(|| cc_preprocess_memo_key(parsed, &prefix_maps, &resolved.version_line))
            .flatten();
        // The read set comes back with the expansion, from the memo when it
        // answers and from the dependency capture otherwise. It is what makes
        // the shadowing resolution below possible.
        let (pp_hash, read_inputs) = if let Some((memo_hash, satisfied)) =
            memo_key.as_ref().and_then(|key| {
                ctx.file_hasher.cc_preprocess_memo_lookup(
                    key,
                    |name| cc_unmapped_path_candidates(name, &prefix_maps),
                    &|path| cc_mapped_content_hash(path, &prefix_maps),
                )
            }) {
            tracing::trace!(
                target: "kache::cache_key",
                "[key:{}] preprocessed_memo=hit",
                trace_name
            );
            (memo_hash, Some(satisfied))
        } else {
            let preprocessed =
                preprocess_hash(parsed, &prefix_maps, ctx.file_hasher, memo_key.is_some())?;
            self.key_path_bound.set(preprocessed.path_bound);
            let read_inputs = preprocessed.fingerprints.as_ref().map(|inputs| {
                inputs
                    .iter()
                    .map(|input| PathBuf::from(input.local_path()))
                    .collect::<Vec<_>>()
            });
            if let (Some(memo_key), Some(fingerprints)) = (memo_key, preprocessed.fingerprints) {
                self.pending_preprocess_memo
                    .borrow_mut()
                    .replace(PendingCcPreprocessMemo {
                        memo_key,
                        preprocessed_hash: preprocessed.hash.clone(),
                        fingerprints,
                        prefix_maps: prefix_maps.clone(),
                    });
            }
            tracing::trace!(
                target: "kache::cache_key",
                "[key:{}] preprocessed_memo=miss",
                trace_name
            );
            (preprocessed.hash, read_inputs)
        };
        hasher.update(b"preprocessed:");
        hasher.update(pp_hash.as_bytes());
        hasher.update(b"\n");
        tracing::trace!(
            target: "kache::cache_key",
            "[key:{}] preprocessed={}",
            trace_name,
            pp_hash
        );

        // Shadowing. A header appearing in an earlier `-I`/`-iquote` dir (or
        // next to the source) can take the place of one that was read without
        // changing any fingerprint, so the key has to notice it. With the read
        // set in hand this resolves only the names that could actually be
        // shadowed; without it (a compiler whose dependency capture failed)
        // fall back to enumerating the directories, which is what the capped
        // walk has always done.
        let (include_dir_digest, include_dir_mode) = match &read_inputs {
            Some(inputs) => (digest_cc_include_shadowing(parsed, inputs)?, "resolved"),
            None => (digest_cc_include_dir_names(parsed)?, "walked"),
        };
        self.pending_include_dir_digest
            .borrow_mut()
            .replace((include_dir_digest.clone(), read_inputs));
        hasher.update(b"include_dir_names:");
        hasher.update(include_dir_digest.as_bytes());
        hasher.update(b"\n");
        tracing::trace!(
            target: "kache::cache_key",
            "[key:{}] include_dir_names={} mode={}",
            trace_name,
            include_dir_digest,
            include_dir_mode
        );

        let key = hasher.finalize().to_hex().to_string();
        // A cc-rs crate's C sources can carry the same out-of-band inputs as
        // its Rust siblings; the crate dir is the source file's nearest
        // enclosing `Cargo.toml`. Reaching cache_key means refuse_reasons
        // already gated this invocation, so it is exactly one source and
        // unconditionally cacheable — pass `is_primary = true`. The assert
        // pins that precondition so a future caller that bypasses the gate
        // fails loudly instead of silently anchoring extra_inputs to the
        // first of several sources.
        debug_assert_eq!(
            parsed.sources.len(),
            1,
            "cc cache_key expects a single-source compile (refuse_reasons gates the rest)"
        );
        let key = crate::extra_inputs::apply_extra_inputs(
            key,
            parsed.sources.first().map(|p| p.as_path()),
            &trace_name,
            true,
            ctx.file_hasher,
        );
        let key = crate::cache_key::apply_key_env_vars(key, ctx.key_env_vars, &trace_name);
        let key = crate::cache_key::apply_key_salt(key, ctx.key_salt, &trace_name);
        tracing::trace!(
            target: "kache::cache_key",
            "[key:{}] final={}",
            trace_name,
            &key[..16]
        );
        Ok(key)
    }

    fn execute(&self, parsed: &CcArgs) -> Result<CompileResult> {
        // Invoke the underlying compiler with the original argv, plus a
        // set of `-ffile-prefix-map` rules so the object doesn't embed
        // clone-local build/source roots. Spliced in before any `--`
        // separator (see `compose_cc_args`) so the driver still reads
        // them as flags, then last among the flags so they win over any
        // user-supplied map for the same prefix.
        crate::opcounts::record_compiler_run();
        let mut command = Command::new(&parsed.program);
        let prefix_maps = cc_prefix_maps(parsed, &self.base_dirs);
        let args = compose_cc_args(&parsed.rest, file_prefix_map_args(&prefix_maps));
        command.args(&args);
        // Pin the same effective SOURCE_DATE_EPOCH the `-E` key probe used, so a
        // TU baking __DATE__/__TIME__/__TIMESTAMP__ produces an object whose date
        // matches its time-stable cache key. Mirrors the existing __FILE__
        // normalization (we already rewrite paths via -ffile-prefix-map); pinning
        // the date is the same stance. Opt out with
        // KACHE_CC_SOURCE_DATE_EPOCH=passthrough (#423).
        if let Some(epoch) = effective_source_date_epoch() {
            command.env("SOURCE_DATE_EPOCH", epoch);
        }
        let output = command
            .output()
            .with_context(|| format!("executing {}", parsed.program))?;
        let exit_code = output.status.code().unwrap_or(1);

        // Output discovery: on a successful compile the named output is the
        // cacheable artifact. Skip on failure, and skip for the modes that
        // are still refused upstream, where discovery would guess at a file
        // the invocation never wrote. `-E` writing to a named file reaches
        // here now, and its expansion is discovered the same way an object
        // is. Objects retain their basename; dep-info gets a semantic store
        // name because `-MF` permits arbitrary suffixes and restore already
        // takes its real destination from the current invocation
        // (kunobi-ninja/kache#655).
        let discovers_outputs = matches!(parsed.mode, CompileMode::Compile)
            || (parsed.mode == CompileMode::Preprocess && parsed.output.is_some());
        let artifacts = if exit_code == 0 && discovers_outputs {
            discover_cc_output_artifacts(parsed)
        } else {
            ArtifactSet::empty()
        };
        // Safety net for #1004. The key probe catches roots in the expansion.
        // A root that reaches the object some other way would still be stored
        // under a key every checkout shares, so keep the object for this build
        // and store nothing. It only sees roots spelled out as plain bytes.
        let unsafe_to_store =
            cc_unsafe_to_store(artifacts.is_empty(), self.key_path_bound.get(), || {
                parsed
                    .object_output_path()
                    .map(|path| cc_object_embeds_mapped_root(&path, &prefix_maps))
            });
        let artifacts = match unsafe_to_store {
            None => artifacts,
            Some(reason) => {
                tracing::warn!("cc: {} {reason}; not caching it", cc_trace_name(parsed));
                ArtifactSet::empty()
            }
        };

        Ok(CompileResult {
            exit_code,
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            artifacts,
        })
    }

    fn classify_output(&self, _parsed: &CcArgs, name: &str) -> ArtifactKind {
        // Caching is not active; classification only matters once outputs
        // get stored. Delegate to the shared filename-based classifier so
        // when the cc store path lands, the kinds it produces are already
        // consistent with the rustc table for shared extensions (.o, .a,
        // .dylib, etc.).
        classify_by_filename(name)
    }
}

/// Discover a successful C/C++ compile's cacheable outputs while preserving
/// the parsed role of `-MF` instead of trying to recover it from a filename.
fn discover_cc_output_artifacts(parsed: &CcArgs) -> ArtifactSet {
    // Store only lexical regular files. Following a symlink here would let an
    // output such as `/dev/null` or a FIFO enter the blob-ingest path, while a
    // symlink needs compiler-specific replacement semantics on later runs.
    fn is_plain_file(path: &std::path::Path) -> bool {
        std::fs::symlink_metadata(path).is_ok_and(|meta| {
            meta.file_type().is_file() && regular_output_is_independent(path, &meta)
        })
    }

    let Some(object) = parsed
        .object_output_path()
        .filter(|path| is_plain_file(path))
    else {
        return ArtifactSet::empty();
    };
    let object_name = object
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    let mut outputs = vec![Artifact {
        path: object,
        kind: classify_by_filename(&object_name),
        store_name: object_name,
        required: true,
    }];

    if let Some(depinfo) = parsed
        .depinfo_output_path()
        .filter(|path| is_plain_file(path))
    {
        outputs.push(Artifact {
            path: depinfo,
            store_name: CC_DEPINFO_STORE_NAME.to_string(),
            kind: ArtifactKind::DepInfo,
            required: true,
        });
    }

    ArtifactSet::new(outputs)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn s(args: &[&str]) -> Vec<String> {
        args.iter().map(|a| a.to_string()).collect()
    }

    #[test]
    fn cc_flags_dep_info_is_gnu_only() {
        use crate::compiler::flags::{Dialect, FlagClass};
        // The `-MM?D|-M[FTQPG]` gnu dep-info row is tagged Gnu-only.
        // Under Gnu every spelling is inert (NoObjectEffect).
        for flag in ["-MD", "-MMD", "-MT", "-MF", "-MQ", "-MP", "-MG"] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Gnu),
                Some(FlagClass::NoObjectEffect),
                "{flag} should be inert dep-info under Gnu"
            );
        }
        // Under Cl:
        // - `-MD` and `-MT` are CRT-selection flags, classified as
        //   CapturedByProbe by the Layer 2 cl rows. They must NOT refuse.
        for flag in ["-MD", "-MT"] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Cl),
                Some(FlagClass::CapturedByProbe),
                "{flag} should be CapturedByProbe under Cl (CRT selection)"
            );
        }
        // - The rest (`-MMD`, `-MF`, `-MQ`, `-MP`, `-MG`) have no
        //   cl-specific row and still refuse (return None) under Cl.
        for flag in ["-MMD", "-MF", "-MQ", "-MP", "-MG"] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Cl),
                None,
                "{flag} must refuse under Cl (no cl-specific row)"
            );
        }
        // a dialect-less row still classifies under both
        assert_eq!(
            classify_cc_flag("-DFOO", Dialect::Cl),
            Some(FlagClass::PreprocessorCaptured)
        );
    }

    #[test]
    fn clang_cl_flag_classification() {
        use crate::compiler::flags::{Dialect, FlagClass};
        let cl = Dialect::Cl;
        // codegen → CapturedByProbe (keyed via -###).
        // Note: bare -O1/-O2 stay ModeledInKey under Cl — the earlier
        // dialect-agnostic `-O[0-3sz]?` CC_FLAGS row matches them first.
        // The /Onn forms, -Od, and -Ox fall through to the cl regex →
        // CapturedByProbe. Both mechanisms key the level (no collision).
        for f in [
            "-guard:cf,nochecks",
            "-Gy",
            "-Gw",
            "-Oy-",
            "-fms-compatibility-version=19.50",
            "-MD",
            "-MT",
            "/MD",
            "/O2",
        ] {
            assert_eq!(
                classify_cc_flag(f, cl),
                Some(FlagClass::CapturedByProbe),
                "{f}"
            );
        }
        // output + ignored → NoObjectEffect (accepted, not keyed)
        for f in ["-Fofoo.obj", "/Fofoo.obj", "-Zc:inline"] {
            assert_eq!(
                classify_cc_flag(f, cl),
                Some(FlagClass::NoObjectEffect),
                "{f}"
            );
        }
        // standard → ModeledInKey; forced include → PreprocessorCaptured
        assert_eq!(
            classify_cc_flag("-std:c++20", cl),
            Some(FlagClass::ModeledInKey)
        );
        assert_eq!(
            classify_cc_flag("-FIfoo.h", cl),
            Some(FlagClass::PreprocessorCaptured)
        );
        // gnu unaffected: -MD is still inert dep-info under Gnu
        assert_eq!(
            classify_cc_flag("-MD", Dialect::Gnu),
            Some(FlagClass::NoObjectEffect)
        );
    }

    #[test]
    fn parse_records_tool_family() {
        let gnu = CcArgs::parse(&s(&["gcc", "-c", "a.c"])).unwrap();
        assert_eq!(gnu.family, ToolFamily::Gnu);
        let cl = CcArgs::parse(&s(&["clang-cl.exe", "-c", "a.c"])).unwrap();
        assert_eq!(cl.family, ToolFamily::ClangCl);
    }

    #[test]
    fn tool_family_detects_clang_cl_and_dialects() {
        use crate::compiler::flags::Dialect;
        let f = |prog: &str, rest: &[&str]| ToolFamily::detect(prog, &s(rest));

        assert_eq!(f("clang-cl", &[]), ToolFamily::ClangCl);
        assert_eq!(f("clang-cl.exe", &[]), ToolFamily::ClangCl);
        assert_eq!(f(r"C:\VS\bin\clang-cl.EXE", &[]), ToolFamily::ClangCl);
        assert_eq!(f("clang", &["--driver-mode=cl"]), ToolFamily::ClangCl);
        assert_eq!(f("clang", &[]), ToolFamily::Clang);
        assert_eq!(f("clang++-17", &[]), ToolFamily::Clang);
        assert_eq!(f("clang-15", &[]), ToolFamily::Clang);
        assert_eq!(f("aarch64-linux-gnu-clang", &[]), ToolFamily::Clang);
        assert_eq!(
            f("armv7a-linux-androideabi21-clang++-18", &[]),
            ToolFamily::Clang
        );
        assert_eq!(f("clang-cl-17", &[]), ToolFamily::ClangCl);
        assert_eq!(f("x86_64-w64-mingw32-clang-cl", &[]), ToolFamily::ClangCl);
        assert_eq!(f("gcc", &[]), ToolFamily::Gnu);
        assert_eq!(f("arm-linux-gnueabihf-gcc", &[]), ToolFamily::Gnu);
        assert_eq!(f("/usr/bin/cc", &[]), ToolFamily::Gnu);
        assert_eq!(f("g++", &[]), ToolFamily::Gnu);

        assert_eq!(ToolFamily::Gnu.dialect(), Dialect::Gnu);
        assert_eq!(ToolFamily::Clang.dialect(), Dialect::Gnu);
        assert_eq!(ToolFamily::ClangCl.dialect(), Dialect::Cl);
    }

    // ── dialect-aware parser ─────────────────────────────────────

    #[test]
    fn clang_cl_output_and_std_parse() {
        use crate::compiler::flags::Dialect;
        let p = CcArgs::parse(&s(&[
            "clang-cl",
            "-c",
            "-Fobuild\\foo.obj",
            "-std:c++20",
            "foo.c",
        ]))
        .unwrap();
        assert_eq!(p.family.dialect(), Dialect::Cl);
        assert_eq!(p.output.as_ref().unwrap().to_str(), Some("build\\foo.obj"));
        assert_eq!(
            p.object_output_path().unwrap().to_str(),
            Some("build\\foo.obj")
        );
        assert_eq!(p.std.as_deref(), Some("c++20"));
        // /-spellings too
        let q =
            CcArgs::parse(&s(&["clang-cl", "-c", "/Fofoo.obj", "/std:c++17", "foo.c"])).unwrap();
        assert_eq!(q.output.as_ref().unwrap().to_str(), Some("foo.obj"));
        assert_eq!(q.std.as_deref(), Some("c++17"));
    }

    #[test]
    fn parser_skips_gnu_only_rows_under_cl() {
        // -MT is a value-consuming gnu dep row. Under gcc the parser
        // consumes it AND its following token; under clang-cl the gnu row
        // is skipped (there -MT is single-token CRT selection), so the
        // next token is parsed independently rather than swallowed. The
        // value token carries a source extension so a broken skip is
        // observable: if -MT failed to consume it, it would surface as a
        // second source.
        let gnu = CcArgs::parse(&s(&["gcc", "-c", "-MT", "tgt.c", "a.c"])).unwrap();
        assert_eq!(gnu.sources.len(), 1, "-MT should consume tgt.c under gnu");
        assert_eq!(gnu.sources[0].to_str(), Some("a.c"));

        // Under clang-cl the gnu -MT row is skipped, so -MT does NOT
        // consume the following token; a.c is still the source. (If the
        // skip were broken, -MT would swallow a.c → sources empty.)
        let cl = CcArgs::parse(&s(&["clang-cl", "-c", "-MT", "a.c"])).unwrap();
        assert_eq!(cl.sources.len(), 1, "-MT must not consume a.c under cl");
        assert_eq!(cl.sources[0].to_str(), Some("a.c"));
    }

    #[test]
    fn config_args_keeps_crt_flags_under_cl_strips_dep_under_gnu() {
        // Gnu: -MT is per-TU dep-target noise → stripped (with its value).
        let gnu = CcArgs::parse(&s(&["gcc", "-c", "-MT", "tgt", "-DFOO", "a.c"])).unwrap();
        assert!(!gnu.config_args().iter().any(|a| a == "-MT" || a == "tgt"));
        assert!(gnu.config_args().iter().any(|a| a == "-DFOO"));

        // Cl: -MT is CRT selection (CapturedByProbe) → MUST stay in the
        // probe-memo key, or a -MT compile reuses a -MD record (false hit).
        let cl = CcArgs::parse(&s(&["clang-cl", "-c", "-MT", "-DFOO", "a.c"])).unwrap();
        assert!(cl.config_args().iter().any(|a| a == "-MT"));

        // -MD — the spelling that motivated #285 — must likewise stay.
        let cl_md = CcArgs::parse(&s(&["clang-cl", "-c", "-MD", "-DFOO", "a.c"])).unwrap();
        assert!(cl_md.config_args().iter().any(|a| a == "-MD"));
    }

    /// The probe-memo key must carry the separated `--param` VALUE.
    ///
    /// `--param` is `CapturedByProbe` (#580), so its codegen effect is keyed
    /// only through the resolved `cc -###` tokens — and the resolved record is
    /// memoized per `config_args()`. The value rides in a bare token the flag
    /// classifier calls inert, so if `config_args()` dropped it, two compiles
    /// differing only in that value would share one probe record and collide
    /// on a single key: a false hit under gcc, where the parameter really does
    /// change codegen (`--param ssp-buffer-size=4` vs `=32` decides whether an
    /// 8-byte buffer gets a stack canary).
    ///
    /// It survives because it is neither a `drops_value` flag nor a source
    /// file — `.h`/bare tokens are outside `SOURCE_EXTENSIONS`. Pin that, since
    /// it is load-bearing for soundness and not obvious from the row itself.
    #[test]
    fn config_args_keeps_separated_param_value_issue_580() {
        let four =
            CcArgs::parse(&s(&["gcc", "-c", "--param", "ssp-buffer-size=4", "a.c"])).unwrap();
        let cfg = four.config_args();
        assert!(
            cfg.iter().any(|a| a == "--param"),
            "--param must stay in the probe-memo key: {cfg:?}"
        );
        assert!(
            cfg.iter().any(|a| a == "ssp-buffer-size=4"),
            "--param's value must stay in the probe-memo key: {cfg:?}"
        );

        // The whole point: a different value is a different memo key, so the
        // two compiles cannot share one resolved-invocation record.
        let thirty_two =
            CcArgs::parse(&s(&["gcc", "-c", "--param", "ssp-buffer-size=32", "a.c"])).unwrap();
        assert_ne!(
            cfg,
            thirty_two.config_args(),
            "differing --param values must not share a probe-memo key"
        );

        // Same for the forced-include header path, whose value token is inert
        // for the same reason (`.h` is not a source extension).
        let inc = CcArgs::parse(&s(&["gcc", "-c", "--include", "pfx.h", "a.c"])).unwrap();
        let inc_cfg = inc.config_args();
        assert!(
            inc_cfg.iter().any(|a| a == "--include") && inc_cfg.iter().any(|a| a == "pfx.h"),
            "--include and its header must stay in the probe-memo key: {inc_cfg:?}"
        );
        assert_eq!(
            inc.sources.len(),
            1,
            "the forced-include header must not be parsed as a second source: {:?}",
            inc.sources
        );
    }

    #[test]
    fn config_args_strips_clang_cl_output() {
        let p = CcArgs::parse(&s(&["clang-cl", "-c", "-Fofoo.obj", "-guard:cf", "foo.c"])).unwrap();
        let cfg = p.config_args();
        assert!(
            !cfg.iter().any(|a| a.starts_with("-Fo")),
            "-Fo must be stripped from probe-memo key: {cfg:?}"
        );
        assert!(
            cfg.iter().any(|a| a == "-guard:cf"),
            "codegen flag must stay: {cfg:?}"
        );
    }

    #[test]
    fn clang_cl_firefox_style_invocation_is_cacheable() {
        // The flags from issue #285's swgl log — non-debug subset.
        let p = CcArgs::parse(&s(&[
            "clang-cl",
            "-c",
            "foo.c",
            "-Fofoo.obj",
            "-fms-compatibility-version=19.50",
            "-guard:cf,nochecks",
            "-Gy",
            "-Gw",
            "-Oy-",
            "-Zc:inline",
            "-MD",
        ]))
        .unwrap();
        let refuse = p.refuse_reasons(&[]);
        assert!(
            refuse.is_empty(),
            "should be cacheable, refused: {:?}",
            refuse.iter().map(|r| r.description()).collect::<Vec<_>>()
        );
        // As of #312, -Z7 is also cacheable (path inputs are folded into the key).
        let dbg = CcArgs::parse(&s(&["clang-cl", "-c", "foo.c", "-Fofoo.obj", "-Z7"])).unwrap();
        assert!(
            dbg.refuse_reasons(&[]).is_empty(),
            "-Z7 must be cacheable after #312, got: {:?}",
            dbg.refuse_reasons(&[])
                .iter()
                .map(|r| r.description())
                .collect::<Vec<_>>()
        );
        assert!(
            cl_debug_path_inputs(&dbg).is_some(),
            "-Z7 must activate the cl_debug_path_inputs key fold"
        );
    }

    // ── recognize ────────────────────────────────────────────────

    #[test]
    fn recognizes_canonical_command_names() {
        for name in [
            "cc",
            "c++",
            "gcc",
            "g++",
            "clang",
            "clang++",
            "clang-cl",
            "zigcc",
            "/usr/bin/cc",
            "/usr/bin/gcc",
            "/usr/local/bin/clang++",
        ] {
            assert!(
                CcCompiler::recognizes(&s(&[name])),
                "should recognize {name}"
            );
        }
    }

    #[test]
    fn recognizes_windows_exe_command_paths() {
        for name in [
            "clang.exe",
            "clang++.exe",
            "clang-cl.exe",
            "gcc.exe",
            "g++.exe",
            "C:/Users/dev/.mozbuild/clang/bin/clang.exe",
            r"C:\Users\dev\.mozbuild\clang\bin\clang.exe",
            "C:/Users/dev/.mozbuild/clang/bin/clang++.EXE",
        ] {
            assert!(
                CcCompiler::recognizes(&s(&[name])),
                "should recognize Windows compiler path {name}"
            );
        }
    }

    #[test]
    fn adapter_descriptor_uses_cc_recognizer() {
        assert_eq!(ADAPTER.id(), CC_ID);
        assert!(ADAPTER.recognizes(&s(&["cc"])));
        assert!(!ADAPTER.recognizes(&s(&["rustc"])));
    }

    #[test]
    fn recognizes_versioned_variants() {
        for name in [
            "gcc-13",
            "clang-15",
            "g++-12",
            "clang++-17",
            "gcc-13.exe",
            "clang++-17.exe",
        ] {
            assert!(
                CcCompiler::recognizes(&s(&[name])),
                "should recognize versioned {name}"
            );
        }
    }

    #[test]
    fn recognizes_target_prefixed_cross_compilers() {
        for name in [
            "arm-linux-gnueabihf-gcc",
            "aarch64-linux-gnu-g++-13",
            "x86_64-w64-mingw32-clang",
            "riscv64-unknown-elf-clang++-18.1",
            "x86_64-w64-mingw32-clang-cl",
            "x86_64-w64-mingw32-gcc-posix",
            "x86_64-w64-mingw32-gcc-13-posix",
            "x86_64-w64-mingw32-g++-win32",
            "x86_64-w64-mingw32-c++-posix",
            "x86_64-w64-mingw32-cc-win32",
            "/opt/cross/bin/arm-none-eabi-gcc",
            r"C:\toolchains\bin\AARCH64-W64-MINGW32-GCC.EXE",
        ] {
            assert!(
                CcCompiler::recognizes(&s(&[name])),
                "should recognize target-prefixed compiler {name}"
            );
        }
    }

    #[test]
    fn rejects_companion_tools_and_malformed_versions() {
        for name in [
            "gcc-ar",
            "gcc-nm",
            "gcc-ranlib",
            "arm-linux-gnueabihf-gcc-ar",
            "clang-format",
            "clang-tidy",
            "clangd",
            "ccache",
            "gcc-13..1",
            "clang-posix",
        ] {
            assert!(
                !CcCompiler::recognizes(&s(&[name])),
                "should NOT recognize companion tool {name}"
            );
        }
    }

    #[test]
    fn recognizes_unknown_wrapper_via_probe() {
        if cfg!(target_os = "macos") {
            return; // Apple's /usr/bin/cc re-dispatches on argv[0] via xcode-select
        }

        let _lock = crate::config::config_path_lock();
        let temp = tempfile::TempDir::new().unwrap();
        // Find a compiler on the system PATH to copy.
        let compilers = ["cc", "gcc", "clang"];
        let source_compiler = compilers.iter().find_map(|&c| {
            let path = crate::compiler::resolve_program_on_path(c)?;
            if crate::probe::probe_compiler_family(path.to_str()?).is_some() {
                Some(path)
            } else {
                None
            }
        });
        let Some(source_path) = source_compiler else {
            return; // Skip if no GCC/Clang C compiler is installed.
        };

        // Copy or symlink it to an unrecognized name in temp directory.
        let custom_name = if cfg!(windows) {
            "my custom & compiler.cmd"
        } else {
            "my-custom-compiler"
        };
        let dest_path = temp.path().join(custom_name);

        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(&source_path, &dest_path).unwrap();
        }
        #[cfg(windows)]
        {
            std::fs::write(
                &dest_path,
                format!("@echo off\r\n\"{}\" %*", source_path.display()),
            )
            .unwrap();
        }

        // recognizes() should successfully probe and return true!
        let dest_str = dest_path.to_str().unwrap().to_string();
        assert!(CcCompiler::recognizes(std::slice::from_ref(&dest_str)));

        // The same wrapper must be detected when it is found by PATH. This
        // exercises the bare-name guard and the OS's safe argument handling
        // for the Windows `.cmd` name containing spaces and `&`.
        let previous_path = std::env::var_os("PATH");
        let mut path_entries = vec![temp.path().to_path_buf()];
        if let Some(previous) = previous_path.as_deref() {
            path_entries.extend(std::env::split_paths(previous));
        }
        let joined_path = std::env::join_paths(path_entries).unwrap();
        unsafe {
            std::env::set_var("PATH", joined_path);
        }
        let recognized_by_bare_name = CcCompiler::recognizes(&s(&[custom_name]));
        unsafe {
            match previous_path {
                Some(previous) => std::env::set_var("PATH", previous),
                None => std::env::remove_var("PATH"),
            }
        }
        assert!(recognized_by_bare_name);

        // Must also succeed during actual wrapper dispatch when KACHE_ACTIVE is set in wrapper mode
        let recognized_during_dispatch = {
            let prev = std::env::var_os("KACHE_ACTIVE");
            unsafe {
                std::env::set_var("KACHE_ACTIVE", "1");
            }
            struct Guard(Option<std::ffi::OsString>);
            impl Drop for Guard {
                fn drop(&mut self) {
                    unsafe {
                        match self.0.as_ref() {
                            Some(val) => std::env::set_var("KACHE_ACTIVE", val),
                            None => std::env::remove_var("KACHE_ACTIVE"),
                        }
                    }
                }
            }
            let _guard = Guard(prev);
            CcCompiler::recognizes(std::slice::from_ref(&dest_str))
        };
        assert!(
            recognized_during_dispatch,
            "unknown compiler wrapper must be recognized during wrapper dispatch when KACHE_ACTIVE is set"
        );
    }

    #[test]
    fn recognizes_does_not_probe_kache_subcommands() {
        assert!(!CcCompiler::recognizes(&s(&["list"])));
        assert!(!CcCompiler::recognizes(&s(&["gc"])));
        assert!(!CcCompiler::recognizes(&s(&["monitor"])));
        assert!(!CcCompiler::recognizes(&s(&["config"])));
    }

    #[test]
    fn recognizes_checks_path_separators_and_path_resolution() {
        // Bare name not on PATH -> returns false without probing
        assert!(!CcCompiler::recognizes(&s(&[
            "kache_nonexistent_cc_binary_12345"
        ])));

        // Path with separators that does not exist -> returns false
        let nonexistent_path = if cfg!(windows) {
            r"C:\nonexistent\path\to\mycc"
        } else {
            "/nonexistent/path/to/mycc"
        };
        assert!(!CcCompiler::recognizes(&s(&[nonexistent_path])));
    }

    #[test]
    fn recognizes_family_probe_matches_dash_e_with_file_arg() {
        assert!(CcCompiler::recognizes_family_probe(&s(&[
            "-E",
            "/tmp/probe.c"
        ])));
        assert!(CcCompiler::recognizes_family_probe(&s(&[
            "-E",
            "/tmp/detect_compiler_family.c"
        ])));
    }

    #[test]
    fn recognizes_family_probe_rejects_dash_e_alone() {
        assert!(!CcCompiler::recognizes_family_probe(&s(&["-E"])));
    }

    #[test]
    fn recognizes_family_probe_rejects_non_probe_shapes() {
        for argv in [
            vec![],
            s(&["-c", "foo.c"]),
            s(&["--version"]),
            s(&["-dumpmachine"]),
            s(&["report"]),
            s(&["foo.c"]),
        ] {
            assert!(
                !CcCompiler::recognizes_family_probe(&argv),
                "should NOT recognize {argv:?} as cc-probe"
            );
        }
    }

    // ── family-probe compiler recovery (issue #286) ──────────────

    fn env(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    #[test]
    fn probe_compiler_recovers_real_compiler_from_target_cc_var() {
        // The exact shape from issue #286: mozbuild sets the
        // target-prefixed CC var to `kache <clang-cl>`, the cc crate
        // drops clang-cl from the family probe, and kache must recover
        // it from the environment.
        let vars = env(&[(
            "CC_aarch64_pc_windows_msvc",
            "C:/Users/sasch/.cargo/bin/kache.exe C:/Users/sasch/.mozbuild/clang/bin/clang-cl.exe",
        )]);
        assert_eq!(
            resolve_probe_compiler("kache", None, vars),
            Some("C:/Users/sasch/.mozbuild/clang/bin/clang-cl.exe".to_string())
        );
    }

    #[test]
    fn probe_compiler_recovers_from_plain_cc() {
        assert_eq!(
            resolve_probe_compiler("kache", None, env(&[("CC", "kache cc")])),
            Some("cc".to_string())
        );
    }

    #[test]
    fn probe_compiler_recovers_from_cxx_when_no_cc() {
        assert_eq!(
            resolve_probe_compiler("kache", None, env(&[("CXX", "kache clang++")])),
            Some("clang++".to_string())
        );
    }

    #[test]
    fn probe_compiler_prefers_cc_over_cxx() {
        // Both wrap kache; the C variable wins (the probe file is C).
        let vars = env(&[("CXX", "kache clang++"), ("CC", "kache clang")]);
        assert_eq!(
            resolve_probe_compiler("kache", None, vars),
            Some("clang".to_string())
        );
    }

    #[test]
    fn probe_compiler_matches_self_stem_case_insensitively() {
        // Windows path with an upper-case .EXE and mixed-case stem.
        let vars = env(&[("CC", r"C:\bin\KACHE.EXE clang-cl.exe")]);
        assert_eq!(
            resolve_probe_compiler("kache", None, vars),
            Some("clang-cl.exe".to_string())
        );
    }

    #[test]
    fn probe_compiler_none_when_cc_is_not_kache_wrapped() {
        // A plain compiler (no kache wrapper) is not ours to recover.
        assert_eq!(
            resolve_probe_compiler("kache", None, env(&[("CC", "clang -fPIC")])),
            None
        );
    }

    #[test]
    fn probe_compiler_none_when_only_self_present() {
        // `CC=kache` with no trailing compiler (and the RUSTC_WRAPPER
        // shape) leaves nothing to forward to.
        assert_eq!(
            resolve_probe_compiler("kache", None, env(&[("CC", "kache")])),
            None
        );
        assert_eq!(
            resolve_probe_compiler("kache", None, env(&[("CC", "kache kache")])),
            None
        );
    }

    #[test]
    fn probe_compiler_ignores_non_compiler_env_vars() {
        // Flags and ccache-style vars must never be mistaken for a
        // `<wrapper> <compiler>` pair even if they mention kache.
        let vars = env(&[
            ("CFLAGS", "kache -O2"),
            ("CXXFLAGS", "kache -O2"),
            ("CCACHE_DIR", "kache whatever"),
            ("RUSTC_WRAPPER", "kache"),
        ]);
        assert_eq!(resolve_probe_compiler("kache", None, vars), None);
    }

    #[test]
    fn probe_compiler_prefers_target_specific_cc_var() {
        // mozbuild sets both a host and a target compiler. With TARGET
        // known, kache must pick the target-specific var the cc crate
        // actually read — not whichever the environment lists first.
        let vars = env(&[
            ("HOST_CC", "kache gcc"),
            ("CC_aarch64_pc_windows_msvc", "kache clang-cl.exe"),
        ]);
        assert_eq!(
            resolve_probe_compiler("kache", Some("aarch64-pc-windows-msvc"), vars),
            Some("clang-cl.exe".to_string())
        );
    }

    #[test]
    fn probe_compiler_matches_dashed_target_cc_var() {
        // The cc crate also reads the un-underscored `CC_<triple>` form.
        let vars = env(&[("CC_aarch64-pc-windows-msvc", "kache clang-cl.exe")]);
        assert_eq!(
            resolve_probe_compiler("kache", Some("aarch64-pc-windows-msvc"), vars),
            Some("clang-cl.exe".to_string())
        );
    }

    #[test]
    fn probe_compiler_target_specific_beats_bare_cc() {
        let vars = env(&[
            ("CC", "kache gcc"),
            ("CC_x86_64_unknown_linux_gnu", "kache clang"),
        ]);
        assert_eq!(
            resolve_probe_compiler("kache", Some("x86_64-unknown-linux-gnu"), vars),
            Some("clang".to_string())
        );
    }

    #[test]
    fn probe_compiler_deterministic_when_target_unknown() {
        // Two target-suffixed vars and no TARGET to disambiguate: the pick
        // must be stable across environment iteration order, not flaky.
        let a = env(&[("CC_zzz", "kache zzz-cc"), ("CC_aaa", "kache aaa-cc")]);
        let b = env(&[("CC_aaa", "kache aaa-cc"), ("CC_zzz", "kache zzz-cc")]);
        assert_eq!(
            resolve_probe_compiler("kache", None, a),
            Some("aaa-cc".to_string())
        );
        assert_eq!(
            resolve_probe_compiler("kache", None, b),
            Some("aaa-cc".to_string())
        );
    }

    #[test]
    fn recognizes_rejects_non_c_compilers() {
        for name in [
            "rustc",
            "ld",
            "ar",
            "make",
            "cmake",
            "ccache",
            "--crate-name",
        ] {
            assert!(
                !CcCompiler::recognizes(&s(&[name])),
                "should NOT recognize {name}"
            );
        }
        assert!(!CcCompiler::recognizes(&[]));
    }

    // ── parser: program / rest ──────────────────────────────────

    #[test]
    fn parse_splits_program_from_rest() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o"])).unwrap();
        assert_eq!(parsed.program, "cc");
        assert_eq!(parsed.rest, vec!["-c", "foo.c", "-o", "foo.o"]);
    }

    // ── parser: compile mode ────────────────────────────────────

    #[test]
    fn parse_default_mode_is_link() {
        // No `-c`, `-E`, `-S` → default cargo / cc-crate "compile + link" shape.
        let parsed = CcArgs::parse(&s(&["cc", "foo.c", "-o", "foo"])).unwrap();
        assert_eq!(parsed.mode, CompileMode::Link);
    }

    #[test]
    fn parse_dash_c_sets_compile_mode() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o"])).unwrap();
        assert_eq!(parsed.mode, CompileMode::Compile);
    }

    #[test]
    fn parse_slash_c_sets_compile_mode_for_cl_only() {
        // clang-cl accepts the MSVC `/c` spelling; kache must treat it as a
        // compile (not default link mode → passthrough). Box-confirmed gap.
        let cl = CcArgs::parse(&s(&["clang-cl", "/c", "a.c", "-Foa.obj"])).unwrap();
        assert_eq!(cl.mode, CompileMode::Compile, "cl `/c` must set Compile");

        // Dash `-c` still works for cl.
        let cl_dash = CcArgs::parse(&s(&["clang-cl", "-c", "a.c"])).unwrap();
        assert_eq!(cl_dash.mode, CompileMode::Compile);

        // gnu must NOT treat `/c` as a compile marker (it's a path there).
        let gnu = CcArgs::parse(&s(&["gcc", "/c", "a.c"])).unwrap();
        assert_ne!(gnu.mode, CompileMode::Compile, "gnu `/c` is not a flag");
    }

    #[test]
    fn parse_dash_e_sets_preprocess_mode() {
        let parsed = CcArgs::parse(&s(&["cc", "-E", "foo.c"])).unwrap();
        assert_eq!(parsed.mode, CompileMode::Preprocess);
    }

    #[test]
    fn parse_dash_s_sets_assemble_mode() {
        let parsed = CcArgs::parse(&s(&["cc", "-S", "foo.c"])).unwrap();
        assert_eq!(parsed.mode, CompileMode::Assemble);
    }

    // ── parser: output ──────────────────────────────────────────

    #[test]
    fn parse_dash_o_sets_output() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "build/foo.o"])).unwrap();
        assert_eq!(parsed.output, Some(PathBuf::from("build/foo.o")));
    }

    #[test]
    fn parse_no_output_means_compiler_default() {
        // Without `-o`, the compiler picks (e.g., `a.out` for link mode).
        let parsed = CcArgs::parse(&s(&["cc", "foo.c"])).unwrap();
        assert_eq!(parsed.output, None);
    }

    // ── parser: sources ─────────────────────────────────────────

    #[test]
    fn parse_collects_source_files_by_extension() {
        let parsed =
            CcArgs::parse(&s(&["cc", "main.c", "util.c", "-o", "foo", "lib.cpp"])).unwrap();
        assert_eq!(
            parsed.sources,
            vec![
                PathBuf::from("main.c"),
                PathBuf::from("util.c"),
                PathBuf::from("lib.cpp"),
            ]
        );
    }

    #[test]
    fn parse_recognizes_objc_and_assembly_extensions() {
        // Coverage of the long extension list — pin all the obscure
        // ones so a future ergonomic cleanup of SOURCE_EXTENSIONS
        // (e.g. removing the `.M` Objective-C uppercase variant)
        // doesn't silently break parsing.
        for src in &[
            "foo.m", "foo.mm", "foo.M", // Objective-C / C++
            "foo.i", "foo.ii", // pre-preprocessed
            "foo.s", "foo.S", "foo.sx", // assembly
        ] {
            let parsed = CcArgs::parse(&s(&["cc", "-c", src])).unwrap();
            assert_eq!(
                parsed.sources,
                vec![PathBuf::from(src)],
                "expected {src} to be recognized as a source"
            );
        }
    }

    #[test]
    fn parse_ignores_non_source_positional_args() {
        // Positional args without a recognized source extension stay
        // in `rest` (so they're passed through verbatim) but don't
        // count as sources.
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-lpthread"])).unwrap();
        assert_eq!(parsed.sources, vec![PathBuf::from("foo.c")]);
        // Library link flags etc. live in `rest` for re-execution.
        assert!(parsed.rest.contains(&"-lpthread".to_string()));
    }

    // ── parser: includes ────────────────────────────────────────

    #[test]
    fn parse_includes_separate_arg_form() {
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            "foo.c",
            "-I",
            "include",
            "-I",
            "/usr/local/include",
        ]))
        .unwrap();
        assert_eq!(
            parsed.includes,
            vec![
                PathBuf::from("include"),
                PathBuf::from("/usr/local/include"),
            ]
        );
    }

    #[test]
    fn parse_includes_sticky_form() {
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            "foo.c",
            "-Iinclude",
            "-I/usr/local/include",
        ]))
        .unwrap();
        assert_eq!(
            parsed.includes,
            vec![
                PathBuf::from("include"),
                PathBuf::from("/usr/local/include"),
            ]
        );
    }

    // ── parser: defines ─────────────────────────────────────────

    #[test]
    fn parse_defines_with_and_without_values() {
        let parsed = CcArgs::parse(&s(&[
            "cc", "-c", "foo.c", "-DFOO", "-DBAR=42", "-D", "BAZ=qux",
        ]))
        .unwrap();
        assert_eq!(
            parsed.defines,
            vec![
                ("FOO".to_string(), None),
                ("BAR".to_string(), Some("42".to_string())),
                ("BAZ".to_string(), Some("qux".to_string())),
            ]
        );
    }

    // ── parser: optimization / debug / std / pic ────────────────

    #[test]
    fn parse_optimization_levels() {
        for (flag, expected) in [
            ("-O0", OptLevel::O0),
            ("-O1", OptLevel::O1),
            ("-O", OptLevel::O1), // bare -O = -O1
            ("-O2", OptLevel::O2),
            ("-O3", OptLevel::O3),
            ("-Os", OptLevel::Os),
            ("-Oz", OptLevel::Oz),
            ("-Og", OptLevel::Og),
        ] {
            let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", flag])).unwrap();
            assert_eq!(parsed.optimization, Some(expected), "for {flag}");
        }
    }

    #[test]
    fn parse_debug_levels() {
        for (flag, expected) in [
            ("-g", 2u8), // bare -g = compiler default (2)
            ("-g0", 0),
            ("-g1", 1),
            ("-g2", 2),
            ("-g3", 3),
        ] {
            let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", flag])).unwrap();
            assert_eq!(parsed.debug_level, Some(expected), "for {flag}");
        }
    }

    #[test]
    fn parse_std_strips_prefix() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-std=c++17"])).unwrap();
        assert_eq!(parsed.std, Some("c++17".to_string()));
    }

    #[test]
    fn parse_pic_flags() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-fPIC"])).unwrap();
        assert!(parsed.pic);
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-fpic"])).unwrap();
        assert!(parsed.pic);
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c"])).unwrap();
        assert!(!parsed.pic);
    }

    // ── parser: depinfo ─────────────────────────────────────────

    #[test]
    fn parse_depinfo_mmd_excludes_system_headers() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-MMD"])).unwrap();
        let d = parsed.depinfo.expect("dep-info should be set");
        assert!(d.emit);
        assert!(!d.include_system);
        assert_eq!(d.output, None);
        assert_eq!(d.target, None);
    }

    #[test]
    fn parse_depinfo_md_includes_system_headers() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-MD"])).unwrap();
        let d = parsed.depinfo.expect("dep-info should be set");
        assert!(d.emit);
        assert!(d.include_system);
    }

    #[test]
    fn parse_depinfo_mf_sets_output_path() {
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", "foo.c", "-MMD", "-MF", "build/foo.d"])).unwrap();
        let d = parsed.depinfo.expect("dep-info should be set");
        assert_eq!(d.output, Some(PathBuf::from("build/foo.d")));
    }

    #[test]
    fn parse_depinfo_mt_sets_target_name() {
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", "foo.c", "-MMD", "-MT", "build/foo.o"])).unwrap();
        let d = parsed.depinfo.expect("dep-info should be set");
        assert_eq!(d.target, Some("build/foo.o".to_string()));
    }

    #[test]
    fn parse_depinfo_mp_and_mg_shape_flags() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-MMD", "-MP", "-MG"])).unwrap();
        let d = parsed.depinfo.expect("dep-info should be set");
        assert!(d.phony_targets);
        assert!(d.missing_generated);
    }

    #[test]
    fn parse_no_depinfo_flags_means_no_depinfo_struct() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o"])).unwrap();
        assert!(parsed.depinfo.is_none());
    }

    #[test]
    fn depinfo_path_modifiers_alone_do_not_emit_depinfo() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-MF", "deps/foo.d"])).unwrap();
        assert!(parsed.depinfo.is_some());
        assert_eq!(parsed.depinfo_output_path(), None);
        assert_eq!(parsed.depinfo_anchor(), None);
    }

    // ── parser: language override ───────────────────────────────

    #[test]
    fn parse_language_override() {
        let parsed = CcArgs::parse(&s(&["cc", "-x", "c++", "-c", "src"])).unwrap();
        assert_eq!(parsed.language_override, Some("c++".to_string()));
    }

    #[test]
    fn parse_language_override_sticky_form() {
        for (flag, expected) in [
            ("-xc", "c"),
            ("-xc++", "c++"),
            ("-xobjective-c", "objective-c"),
            ("-xobjective-c++", "objective-c++"),
        ] {
            let parsed = CcArgs::parse(&s(&["cc", flag, "-c", "foo.c"])).unwrap();
            assert_eq!(
                parsed.language_override,
                Some(expected.to_string()),
                "for {flag}"
            );
        }
    }

    #[test]
    fn parse_table_driven_value_forms() {
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            "foo.c",
            "-I",
            "include",
            "-Ivendor",
            "-D",
            "FOO=1",
            "-DBAR",
            "-std=c++20",
            "-xobjective-c++",
            "-o",
            "foo.o",
        ]))
        .unwrap();

        assert_eq!(
            parsed.includes,
            vec![PathBuf::from("include"), PathBuf::from("vendor")]
        );
        assert_eq!(
            parsed.defines,
            vec![
                ("FOO".to_string(), Some("1".to_string())),
                ("BAR".to_string(), None),
            ]
        );
        assert_eq!(parsed.std, Some("c++20".to_string()));
        assert_eq!(parsed.language_override, Some("objective-c++".to_string()));
        assert_eq!(parsed.output, Some(PathBuf::from("foo.o")));
    }

    // ── classifier table validation ─────────────────────────────

    /// Every `Matcher::Regex` row in [`CC_FLAGS`] must compile as a
    /// valid anchored regex. CI safety: production lookups assume
    /// pre-validated patterns; a typo in a row should fail here, not
    /// at first use on a developer's machine.
    #[test]
    fn cc_flags_table_regexes_compile() {
        crate::compiler::flags::assert_table_regexes_compile(CC_FLAGS);
    }

    // ── refuse-to-cache: per-case ───────────────────────────────

    fn refuse_descriptions(args: &[&str]) -> Vec<&'static str> {
        refuse_descriptions_with_flags(args, &[])
    }

    fn refuse_descriptions_with_flags(args: &[&str], extra: &[String]) -> Vec<&'static str> {
        let parsed = CcArgs::parse(&s(args)).unwrap();
        parsed
            .refuse_reasons(extra)
            .iter()
            .map(|r| r.description())
            .collect()
    }

    #[test]
    fn refuses_cuda_language_override_in_both_forms() {
        for args in [
            vec!["cc", "-x", "cuda", "-c", "foo.cpp"],
            vec!["cc", "-xcuda", "-c", "foo.cpp"],
        ] {
            let descs = refuse_descriptions(&args);
            assert!(
                descs.iter().any(|d| d.contains("language override")),
                "CUDA language override must refuse, got: {descs:?}"
            );
        }
    }

    #[test]
    fn accepts_all_allowlisted_language_overrides() {
        for language in LANGUAGE_OVERRIDE_ALLOWLIST {
            let descs = refuse_descriptions(&["cc", "-x", language, "-c", "foo.cpp"]);
            assert!(
                descs.is_empty(),
                "allowlisted language {language} should remain cacheable, got: {descs:?}"
            );
        }
    }

    #[test]
    fn refuses_cuda_source_with_dedicated_reason() {
        let descs = refuse_descriptions(&["cc", "-c", "foo.cu"]);
        assert!(
            descs.iter().any(|d| d.contains("CUDA source input")),
            "CUDA source must get its dedicated refusal, got: {descs:?}"
        );
        assert!(
            !descs.iter().any(|d| d.contains("no source file")),
            "CUDA source must not be misreported as missing, got: {descs:?}"
        );
    }

    #[test]
    fn refuses_response_files() {
        let descs = refuse_descriptions(&["cc", "-c", "@flags.rsp"]);
        assert!(
            descs.iter().any(|d| d.contains("response file")),
            "expected response-file refuse, got: {descs:?}"
        );
    }

    #[test]
    fn cl_slash_flag_refuses_but_gnu_treats_it_positional() {
        // Layer 0's most operator-visible invariant, end to end: under
        // clang-cl an unmodeled `/`-flag fails closed (refuse →
        // passthrough); under gcc the same token is an inert positional,
        // so it does not produce an unsupported-flag refusal.
        //
        // Note: `/O2` was previously the unmodeled example but Layer 2
        // now classifies it as CapturedByProbe. Use `/unknown` (genuinely
        // unmodeled) to keep testing the invariant that an unclassified
        // slash flag refuses under Cl but not under Gnu.
        let cl = refuse_descriptions(&["clang-cl", "-c", "/unknown", "a.c"]);
        assert!(
            cl.iter().any(|d| d.contains("unsupported flag")),
            "clang-cl /unknown should refuse as an unsupported flag, got: {cl:?}"
        );
        let gnu = refuse_descriptions(&["gcc", "-c", "/unknown", "a.c"]);
        assert!(
            !gnu.iter().any(|d| d.contains("unsupported flag")),
            "gcc /unknown is an inert positional, not an unsupported flag, got: {gnu:?}"
        );
        // But /O2 itself is now modeled (CapturedByProbe) and must not refuse.
        let cl_o2 = refuse_descriptions(&["clang-cl", "-c", "/O2", "a.c"]);
        assert!(
            !cl_o2.iter().any(|d| d.contains("unsupported flag")),
            "clang-cl /O2 is now CapturedByProbe (Layer 2) and must not refuse, got: {cl_o2:?}"
        );
    }

    #[test]
    fn clang_cl_debug_is_now_cacheable_and_path_keyed() {
        // As of #312 the old "clang-cl debug" refusal is gone. The `-g`
        // form and the native MSVC `/Z7`/`-Z7`/`/Zi` spellings must all
        // cache (empty refuse_reasons) and must be recognised as a debug
        // compile that folds path inputs into the key.
        for flag in ["-g2", "/Z7", "-Z7", "/Zi", "/ZI", "/Zd"] {
            let p = CcArgs::parse(&s(&["clang-cl", "-c", "a.c", "-Foa.obj", flag])).unwrap();
            let descs = p
                .refuse_reasons(&[])
                .iter()
                .map(|r| r.description())
                .collect::<Vec<_>>();
            assert!(
                descs.is_empty(),
                "{flag} must be cacheable now, got: {descs:?}"
            );
            // cl_debug_path_inputs must return Some(…) so the key fold fires.
            assert!(
                cl_debug_path_inputs(&p).is_some(),
                "{flag}: cl_debug_path_inputs must recognise a debug compile"
            );
            assert!(
                p.embeds_codeview_debug(),
                "{flag}: clang-cl debug objects stay machine-local"
            );
        }
        // gcc debug never goes through the cl path-fold path.
        let gnu = CcArgs::parse(&s(&["gcc", "-c", "a.c", "-g2"])).unwrap();
        assert!(
            !gnu.embeds_codeview_debug(),
            "GCC debug objects may publish to a remote"
        );
        assert_eq!(
            cl_debug_path_inputs(&gnu),
            None,
            "gnu debug must not fold cl paths"
        );
    }

    #[test]
    fn clang_cl_debug_compiles_are_no_longer_refused() {
        for f in ["/Z7", "/Zi", "/ZI", "-Z7"] {
            let p = CcArgs::parse(&s(&["clang-cl", "-c", "a.c", "-Foa.obj", f])).unwrap();
            let reasons = p.refuse_reasons(&[]);
            assert!(
                reasons.is_empty(),
                "{f}: clang-cl debug must be cacheable now, got: {reasons:?}"
            );
        }
        // -g form too.
        let g = CcArgs::parse(&s(&["clang-cl", "-c", "a.c", "-Foa.obj", "-g"])).unwrap();
        assert!(
            g.refuse_reasons(&[]).is_empty(),
            "-g clang-cl must be cacheable"
        );
    }

    #[test]
    fn clang_cl_slash_c_compile_is_not_refused() {
        // `/c` must be cacheable end-to-end: the parser sets compile mode AND
        // the unsupported-flag classifier must accept it (ParserHandled).
        // Regression for the box-found gap where `/c` hit "unsupported flag(s): /c".
        let p = CcArgs::parse(&s(&["clang-cl", "/c", "a.c", "-Foa.obj"])).unwrap();
        assert_eq!(p.mode, CompileMode::Compile);
        assert!(
            p.refuse_reasons(&[]).is_empty(),
            "clang-cl /c must not be refused, got: {:?}",
            p.refuse_reasons(&[])
        );
        // And the debug form stays cacheable too.
        let d = CcArgs::parse(&s(&["clang-cl", "/c", "a.c", "-Foa.obj", "/Z7"])).unwrap();
        assert!(
            d.refuse_reasons(&[]).is_empty(),
            "clang-cl /c /Z7 must not be refused"
        );
    }

    #[test]
    fn refuses_multi_arch() {
        // Single -arch is fine; multi -arch produces a fat binary.
        let single = refuse_descriptions(&["cc", "-c", "foo.c", "-arch", "arm64"]);
        assert!(!single.iter().any(|d| d.contains("multi-arch")));

        let multi =
            refuse_descriptions(&["cc", "-c", "foo.c", "-arch", "arm64", "-arch", "x86_64"]);
        assert!(
            multi.iter().any(|d| d.contains("multi-arch")),
            "expected multi-arch refuse, got: {multi:?}"
        );
    }

    #[test]
    fn refuses_coverage_instrumentation() {
        for flag in &["--coverage", "-fprofile-arcs", "-ftest-coverage"] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.c", flag]);
            assert!(
                descs.iter().any(|d| d.contains("coverage")),
                "expected coverage refuse for {flag}, got: {descs:?}"
            );
        }
    }

    #[test]
    fn refuses_split_dwarf() {
        let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-gsplit-dwarf"]);
        assert!(
            descs.iter().any(|d| d.contains("gsplit-dwarf")),
            "expected gsplit-dwarf refuse, got: {descs:?}"
        );
    }

    #[test]
    fn refuses_precompiled_headers() {
        // The `-include foo.pch` form
        let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-include", "stdafx.pch"]);
        assert!(
            descs.iter().any(|d| d.contains("precompiled")),
            "expected PCH refuse, got: {descs:?}"
        );
        // The explicit `-emit-pch` form
        let descs = refuse_descriptions(&["cc", "-c", "foo.h", "-emit-pch"]);
        assert!(
            descs.iter().any(|d| d.contains("precompiled")),
            "expected PCH refuse for -emit-pch, got: {descs:?}"
        );
        // The long spellings model as PreprocessorCaptured (#580), so the
        // PCH refusal has to recognize them too — otherwise a PCH walks
        // straight past the flag classifier.
        for args in [
            vec!["cc", "-c", "foo.c", "--include=stdafx.pch"],
            vec!["cc", "-c", "foo.c", "--include", "stdafx.gch"],
        ] {
            let descs = refuse_descriptions(&args);
            assert!(
                descs.iter().any(|d| d.contains("precompiled")),
                "expected PCH refuse for {args:?}, got: {descs:?}"
            );
        }
    }

    /// aws-lc-sys 0.43 compiles its BoringSSL symbol-prefixing TUs with
    /// `--include=<generated-include>/boringssl_prefix_symbols*.h` and its
    /// jitterentropy TUs with `-fwrapv --param ssp-buffer-size=4`. None of
    /// those classified before #580, so ~62 TUs passed through uncached, the
    /// `.a` diverged per checkout, and the `extern:` content hash re-keyed
    /// the entire rustls/TLS subtree above it.
    #[test]
    fn caches_aws_lc_sys_prefix_symbols_and_jitterentropy_flags_issue_580() {
        let prefix_header = "/cargo/registry/src/index.crates.io-1/aws-lc-sys-0.43.0/\
             generated-include/openssl/boringssl_prefix_symbols.h";
        let joined_include = format!("--include={prefix_header}");
        for args in [
            vec!["cc", "-c", "bcm.c", "-o", "bcm.o", &joined_include],
            vec![
                "cc",
                "-c",
                "bcm.c",
                "-o",
                "bcm.o",
                "--include",
                prefix_header,
            ],
            vec![
                "cc",
                "-c",
                "jitterentropy-base.c",
                "-o",
                "je.o",
                "-fwrapv",
                "--param",
                "ssp-buffer-size=4",
                "-O0",
            ],
            // Joined `--param=`, and the opposite `-fwrapv` polarity, so the
            // missed-polarity passthrough class can't reappear here.
            vec![
                "cc",
                "-c",
                "jitterentropy-base.c",
                "-o",
                "je.o",
                "-fno-wrapv",
                "--param=ssp-buffer-size=4",
                "-O0",
            ],
        ] {
            let descs = refuse_descriptions(&args);
            assert!(
                descs.is_empty(),
                "aws-lc-sys invocation must cache, got: {descs:?} for {args:?}"
            );
        }
    }

    /// aws-lc-sys 0.44 adds `-fsanitize-undefined-strip-path-components=-1`
    /// to the same jitterentropy TUs as #580's `-fwrapv --param` flags once a
    /// compile probe confirms clang support (#840). The option only strips
    /// path components from UBSan check metadata, but that still changes
    /// object bytes, so it is keyed: CapturedByProbe, with Apple clang
    /// forwarding the value verbatim into the resolved `-cc1` tokens.
    #[test]
    fn caches_aws_lc_sys_ubsan_strip_path_components_issue_840() {
        let flag = "-fsanitize-undefined-strip-path-components=-1";
        assert_eq!(
            classify_cc_flag(flag, Dialect::Gnu),
            Some(FlagClass::CapturedByProbe),
            "{flag} must key through the resolved invocation"
        );
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            "jitterentropy-base.c",
            "-o",
            "je.o",
            "-fwrapv",
            "--param",
            "ssp-buffer-size=4",
            flag,
            "-O0",
        ]))
        .unwrap();
        assert!(
            parsed.refuse_reasons(&[]).is_empty(),
            "aws-lc-sys 0.44 jitterentropy invocation must cache: {:?}",
            parsed.refuse_reasons(&[])
        );
        // Probe-captured ⇒ the resolved invocation is required to key; an
        // unresolvable probe refuses rather than under-keys.
        assert!(cc_flags_need_resolved_invocation(&parsed));
    }

    /// The #840 row is exact on the one observed value. Other values — and
    /// the value-less spelling clang rejects outright — stay refused until a
    /// workload needs them, the same evidence-scoping as `-gdwarf-4`.
    #[test]
    fn ubsan_strip_path_components_other_spellings_still_refuse_issue_840() {
        for flag in [
            "-fsanitize-undefined-strip-path-components",
            "-fsanitize-undefined-strip-path-components=0",
            "-fsanitize-undefined-strip-path-components=2",
            "-fsanitize-undefined-strip-path-components=-2",
        ] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Gnu),
                None,
                "{flag} is not modeled and must keep refusing"
            );
        }
    }

    /// Firefox enables Clang's automatic-variable pattern initialization as a
    /// hardening mode (#849). It affects generated code, and Clang preserves
    /// the option verbatim in the resolved `-cc1` invocation, so it must be
    /// accepted as probe-keyed rather than passed through.
    #[test]
    fn caches_trivial_auto_var_init_pattern_issue_849() {
        let flag = "-ftrivial-auto-var-init=pattern";
        assert_eq!(
            classify_cc_flag(flag, Dialect::Gnu),
            Some(FlagClass::CapturedByProbe),
            "{flag} must key through the resolved invocation"
        );
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o", flag, "-O0"])).unwrap();
        assert!(
            parsed.refuse_reasons(&[]).is_empty(),
            "Firefox compile with {flag} must cache: {:?}",
            parsed.refuse_reasons(&[])
        );
        assert!(cc_flags_need_resolved_invocation(&parsed));
    }

    /// The #849 row intentionally covers only the reported mode. Other valid
    /// Clang modes and malformed neighbouring spellings remain conservative
    /// passthroughs instead of being accepted by a broad prefix.
    #[test]
    fn trivial_auto_var_init_other_spellings_still_refuse_issue_849() {
        for flag in [
            "-ftrivial-auto-var-init",
            "-ftrivial-auto-var-init=zero",
            "-ftrivial-auto-var-init=uninitialized",
            "-ftrivial-auto-var-init=patterns",
        ] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Gnu),
                None,
                "{flag} is not modeled and must keep refusing"
            );
        }
    }

    /// `--include=` is modeled by the `=`-anchored prefix precisely so its
    /// unmodeled `--include-*` neighbours keep refusing. Nothing about
    /// forced includes says anything about include *paths* or prefix
    /// mapping, and quietly sweeping them in would be an under-key.
    #[test]
    fn long_include_row_does_not_swallow_neighbouring_options_issue_580() {
        for flag in [
            "--include-directory=/tmp/inc",
            "--include-directory-after=/tmp/inc",
            "--include-with-prefix=/tmp/inc",
            "--include-barrier",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.c", flag]);
            assert!(
                descs.iter().any(|d| d.contains(flag)),
                "{flag} must still refuse as unmodeled, got: {descs:?}"
            );
        }
    }

    #[test]
    fn refuses_modules() {
        for flag in &["-fmodules", "-fcxx-modules"] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.cpp", flag]);
            assert!(
                descs.iter().any(|d| d.contains("modules")),
                "expected modules refuse for {flag}, got: {descs:?}"
            );
        }
    }

    #[test]
    fn refuses_output_to_stdout() {
        let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "-"]);
        assert!(
            descs.iter().any(|d| d.contains("stdout")),
            "expected stdout-output refuse, got: {descs:?}"
        );
    }

    #[test]
    fn refuses_flags_unclassified_in_cc_flags_table() {
        // Flags whose object-file effect kache does not capture in the
        // cache key — i.e. no row in `CC_FLAGS` matches them. Each
        // would miscache → must passthrough. Spans every shape, not
        // just `-f…` / `-m…`: unmodeled optimization / debug variants,
        // cross-targets, profiling.
        for flag in &[
            // unmodeled -f… / -m… codegen flags. (-ffast-math / -fno-finite-math-only
            // / -mrecip= are now CapturedByProbe — modeled from the Firefox bench — so
            // they are deliberately NOT here; these remain genuinely unmodeled.)
            "-fsanitize=address",
            "-fno-pic",
            "-mtune=skylake",
            // unmodeled optimization / debug variants
            "-Ofast",
            "-gdwarf-5",
            "-ggdb",
            "-gline-tables-only",
            // profiling instrumentation
            "-pg",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", flag]);
            assert!(
                descs.iter().any(|d| d.contains("unsupported flag")),
                "expected classifier refuse for {flag}, got: {descs:?}"
            );
        }
    }

    #[test]
    fn cc_flags_table_classifies_known_cache_safe_flags() {
        // Flags kache fully accounts for: modeled codegen (opt / debug
        // / std / pic / arch), preprocessor-captured (defines /
        // includes / sysroot), and no-object-effect (warnings /
        // dep-info / mechanics). None should trip the classifier.
        for flag in &[
            "-O2",
            "-O0",
            "-Og",
            "-g",
            "-g2",
            "-std=c11",
            "-fPIC",
            "-fpic", // modeled codegen
            "-DFOO=1",
            "-Iinclude",
            "-isystem",
            "-include",
            "-nostdinc",
            "-undef", // preprocessor
            "-Wall",
            "-Wextra",
            "-Werror",
            "-Wno-unused",
            "-w",
            "-pedantic", // diagnostics
            "-pipe",
            "-P",
            "-MMD",
            "-MF",
            "-fdiagnostics-color", // mechanics / dep-info / diag
            // fast-math family (CapturedByProbe) — modeled from the LLVM/Firefox
            // benches; each forwards to -cc1 so the resolved-token hash keys it.
            "-ffast-math",
            "-ftrapping-math",
            "-fno-trapping-math",
            "-funsafe-math-optimizations",
            "-freciprocal-math",
            "-fno-signed-zeros",
            "-ffinite-math-only",
            "-fno-finite-math-only",
            "-frounding-math",
            "-fsignaling-nans",
            "-fno-fast-math",
            // frame-pointer + x86 codec ISA flags (Firefox nightly bench)
            "-fomit-frame-pointer",
            "-mavx",
            "-mbmi2",
            "-mf16c",
            "-mssse3",
            "-mfma",
            "-mavx512f",
            "-mavxvnni",
            "-mno-sse3",
            // zstd-sys merge-all-constants knob (#856)
            "-fmerge-all-constants",
            "-fno-merge-all-constants",
            // Firefox / lance 0.20 nightly passthroughs
            "-funroll-loops",
            "-fno-unroll-loops",
            "-fno-stack-protector",
            "-fstack-protector",
            "-fstack-protector-strong",
            "-fno-asynchronous-unwind-tables",
            "-fasynchronous-unwind-tables",
            "--",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", flag]);
            assert!(
                !descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} is cache-safe and must NOT trip the classifier, got: {descs:?}"
            );
        }
    }

    /// Issue #424/#438 — Firefox's Windows clang-cl build passes
    /// `-fansi-escape-codes` as a *bare* driver flag (not `-Xclang`
    /// forwarded). It only forces ANSI color escapes in diagnostics, so it
    /// has no object effect and must classify as `NoObjectEffect` in both
    /// dialects — exactly like its sibling `-fcolor-diagnostics`. (#430's
    /// codegen-knob refactor dropped this row; #438 restores it.)
    #[test]
    fn bare_fansi_escape_codes_is_inert_issue_424() {
        assert_eq!(
            classify_cc_flag("-fansi-escape-codes", Dialect::Gnu),
            Some(FlagClass::NoObjectEffect)
        );
        assert_eq!(
            classify_cc_flag("-fansi-escape-codes", Dialect::Cl),
            Some(FlagClass::NoObjectEffect)
        );
    }

    /// Issue #424/#438 — the remaining Firefox/Windows diagnostics + codegen
    /// knobs surfaced in the bench log (`-fansi-escape-codes` bare alongside
    /// `-ffp-contract=off`) must all classify so the TU caches instead of
    /// passing through as "unsupported flag(s)".
    #[test]
    fn firefox_windows_remaining_flags_are_cacheable_issue_424() {
        let descs = refuse_descriptions(&[
            "clang-cl",
            "-c",
            "-TP",
            "-ffp-contract=off",
            "-fansi-escape-codes",
            "-FoBasePrincipal.obj",
            "caps/BasePrincipal.cpp",
        ]);
        assert!(
            !descs.iter().any(|d| d.contains("unsupported flag")),
            "issue #424 flags must all classify; got: {descs:?}"
        );
    }

    #[test]
    fn codegen_knob_stems_classify_in_both_polarities() {
        // The structural guarantee: every codegen-knob stem classifies in BOTH
        // `-f<stem>` and `-fno-<stem>` forms, so a build passing either polarity
        // never silently passes through. This is what `-ftrapping-math` (#422)
        // and `-fomit-frame-pointer` (#426) violated before the stem list — each
        // had only one polarity modeled. A regression that drops a stem (or
        // reverts to one-polarity rows) fails here, not in a 2-hour nightly.
        for stem in &[
            "omit-frame-pointer",
            "trapping-math",
            "semantic-interposition",
            "math-errno",
            "merge-all-constants",
            "strict-aliasing",
            "function-sections",
            "data-sections",
            "unwind-tables",
            "asynchronous-unwind-tables",
            "unroll-loops",
            "fast-math",
            "finite-math-only",
        ] {
            for flag in [format!("-f{stem}"), format!("-fno-{stem}")] {
                let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", &flag]);
                assert!(
                    !descs.iter().any(|d| d.contains("unsupported flag")),
                    "codegen knob {flag} must classify in both polarities, got: {descs:?}"
                );
            }
        }
        // The polarity matcher must NOT overreach to a non-knob `-f…` flag.
        let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", "-fomit-not-a-knob"]);
        assert!(
            descs.iter().any(|d| d.contains("unsupported flag")),
            "an unknown -f flag must still refuse, got: {descs:?}"
        );
    }

    #[test]
    fn firefox_omit_frame_pointer_no_longer_refuses() {
        // -fomit-frame-pointer on ~every Firefox release TU drove the nightly to
        // 80% passthrough (DEGRADED). It and the codec SIMD combo must classify.
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-O2",
            "-fomit-frame-pointer",
            "-mavx",
            "-mbmi2",
            "-mf16c",
        ]);
        assert!(
            !descs.iter().any(|d| d.contains("unsupported flag")),
            "the Firefox omit-fp + SIMD combo must no longer refuse, got: {descs:?}"
        );
    }

    #[test]
    fn cc_rs_no_omit_leaf_frame_pointer_no_longer_refuses_issue_839() {
        // cc-rs emits `-mno-omit-leaf-frame-pointer` when Rust requests forced
        // frame pointers, and in debug-mode tool setup — every aws-lc-sys TU
        // of a macOS debug build passed through on it (#839). The flag is
        // CapturedByProbe: it must classify clean AND force the resolved
        // invocation (clang `-###` resolves it to `-mframe-pointer=all`,
        // against the default `-mframe-pointer=non-leaf`, so the key
        // separates the two codegen modes; an unresolvable probe refuses
        // fail-closed instead of under-keying).
        let argv = s(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-O0",
            "-fno-omit-frame-pointer",
            "-mno-omit-leaf-frame-pointer",
        ]);
        let parsed = CcArgs::parse(&argv).unwrap();
        assert!(
            parsed.refuse_reasons(&[]).is_empty(),
            "the cc-rs forced-frame-pointer invocation must cache: {:?}",
            parsed.refuse_reasons(&[])
        );
        assert!(
            cc_flags_need_resolved_invocation(&parsed),
            "-mno-omit-leaf-frame-pointer must force the resolved invocation"
        );
        // The related-but-distinct gcc spelling stays unmodeled.
        assert_eq!(
            classify_cc_flag("-momit-leaf-frame-pointer", Dialect::Gnu),
            None,
            "-momit-leaf-frame-pointer is not modeled and must keep refusing"
        );
    }

    /// zstd-sys 2.0.16 adds `-fmerge-all-constants` via `flag_if_supported`
    /// on every translation unit (#856). The flag changes codegen, and Apple
    /// clang preserves the enabled form in the resolved `-cc1` stream, so
    /// both polarities are CapturedByProbe. The disabled form may
    /// canonicalize to the default mode when the probe emits no extra token.
    #[test]
    fn zstd_sys_merge_all_constants_caches_issue_856() {
        for flag in ["-fmerge-all-constants", "-fno-merge-all-constants"] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Gnu),
                Some(FlagClass::CapturedByProbe),
                "{flag} must key through the resolved invocation"
            );
            let parsed =
                CcArgs::parse(&s(&["cc", "-c", "zstd.c", "-o", "zstd.o", flag, "-O0"])).unwrap();
            assert!(
                parsed.refuse_reasons(&[]).is_empty(),
                "zstd-sys compile with {flag} must cache: {:?}",
                parsed.refuse_reasons(&[])
            );
            assert!(
                cc_flags_need_resolved_invocation(&parsed),
                "{flag} must force the resolved invocation"
            );
        }
        // Adjacent gcc spelling stays unmodeled: `-fmerge-constants` is a
        // different knob and must not ride in on the stem list.
        assert_eq!(
            classify_cc_flag("-fmerge-constants", Dialect::Gnu),
            None,
            "-fmerge-constants is a different knob and must keep refusing"
        );
    }

    #[test]
    fn llvm_bench_trapping_math_combo_no_longer_refuses() {
        // The first LLVM bench had a TU carrying `-fno-semantic-interposition
        // -ftrapping-math`; the interposition flag is modeled, but -ftrapping-math
        // kept the TU passing through. Both are now CapturedByProbe, so the combo
        // must classify clean (no unsupported-flag refusal).
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-O2",
            "-fno-semantic-interposition",
            "-ftrapping-math",
        ]);
        assert!(
            !descs.iter().any(|d| d.contains("unsupported flag")),
            "the LLVM -ftrapping-math combo must no longer refuse, got: {descs:?}"
        );
    }

    /// Gecko/Darwin baseline flags (kunobi-ninja/kache#114): codegen
    /// knobs whose effect is captured by clang's `cc -###` resolved
    /// invocation (which the cache key already hashes), so they're
    /// cache-safe even though kache doesn't model them explicitly.
    /// These were the inaugural `FlagClass::CapturedByProbe` rows in
    /// `CC_FLAGS` (#137).
    ///
    /// Each was previously refused as "unsupported flag" and forced
    /// passthrough on Firefox builds — over 4,400 single-source
    /// compiles per build, per the issue's evidence.
    #[test]
    fn classifier_accepts_gecko_darwin_baseline_flags() {
        for flag in &[
            "-mmacosx-version-min=10.15",
            "-mmacosx-version-min=11.0",
            "-pthread",
            "-fstack-protector-strong",
            "-fstrict-flex-arrays=1",
            "-fstrict-flex-arrays=3",
            "-fno-math-errno",
            "-fno-strict-aliasing",
            "-ffp-contract=off",
            "-ffp-contract=on",
            "-fno-omit-frame-pointer",
            "-funwind-tables",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", flag]);
            assert!(
                !descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} should be classified (Gecko/Darwin baseline), got: {descs:?}"
            );
        }
    }

    /// `-fstack-clash-protection` is a pure codegen hardening flag (no
    /// preprocessor or object-path effect), captured by clang's `cc -###`
    /// resolved invocation like the other `-fstack-protector*` knobs.
    /// Firefox enables it by default, so before #245 every C/C++ compile
    /// refused — ~4,842 passthroughs in one build per the issue's evidence.
    #[test]
    fn classifier_accepts_stack_clash_protection() {
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-fstack-clash-protection",
        ]);
        assert!(
            !descs.iter().any(|d| d.contains("unsupported flag")),
            "-fstack-clash-protection should be classified (issue #245), got: {descs:?}"
        );
    }
    // ── #95: user-configurable cc flag allow-list ──────────────────

    fn flags(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn cc_compiler_constructor_keeps_extra_allowlist_flags() {
        let expected = flags(&["-fsome-exotic-flag"]);
        let compiler = CcCompiler::with_extra_allowlist_flags(expected.clone());

        assert_eq!(compiler.extra_allowlist_flags, expected);
    }

    /// A flag the built-in table doesn't model normally refuses, but
    /// listing it in `[cc] extra_allowlist_flags` makes it cacheable.
    #[test]
    fn user_allowed_flag_stops_refusing() {
        let args = &["cc", "-c", "foo.c", "-o", "foo.o", "-fsome-exotic-flag"];

        // Control: unconfigured → still refused.
        let refused = refuse_descriptions(args);
        assert!(
            refused.iter().any(|d| d.contains("unsupported flag")),
            "unconfigured exotic flag should refuse, got: {refused:?}"
        );

        // Configured → accepted (no unsupported-flag refusal).
        let allowed = refuse_descriptions_with_flags(args, &flags(&["-fsome-exotic-flag"]));
        assert!(
            !allowed.iter().any(|d| d.contains("unsupported flag")),
            "allow-listed flag should not refuse, got: {allowed:?}"
        );
    }

    /// The allow-list can only add to the hashable set — it must NOT
    /// override a structural refusal like coverage instrumentation.
    #[test]
    fn user_allowed_flag_cannot_override_structural_refusal() {
        let args = &["cc", "-c", "foo.c", "-o", "foo.o", "--coverage"];
        let descs = refuse_descriptions_with_flags(args, &flags(&["--coverage"]));
        assert!(
            descs.iter().any(|d| d.contains("coverage")),
            "coverage must still refuse even when allow-listed, got: {descs:?}"
        );
    }

    /// Only flags actually present on the command line and unmodeled by
    /// the built-in table are folded into the key (sorted + deduped).
    #[test]
    fn cc_extra_flags_for_key_selects_present_unmodeled_sorted() {
        let extra = flags(&["-fbravo", "-falpha", "-fPIC"]);

        // `-fbravo`/`-falpha` present + unmodeled → folded, sorted.
        // `-fPIC` is modeled by the built-in table → NOT folded here.
        // `-falpha` repeated → deduped. `-fcharlie` not configured → out.
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-fbravo",
            "-falpha",
            "-falpha",
            "-fPIC",
            "-fcharlie",
        ]))
        .unwrap();
        assert_eq!(
            cc_extra_flags_for_key(&parsed, &extra),
            vec!["-falpha", "-fbravo"]
        );

        // A configured-but-absent flag contributes nothing.
        let absent = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o"])).unwrap();
        assert!(cc_extra_flags_for_key(&absent, &extra).is_empty());

        // No config → nothing folded (key byte-identical to today).
        assert!(cc_extra_flags_for_key(&parsed, &[]).is_empty());
    }

    /// A representative Firefox-style C compile: pile the full
    /// Gecko/Darwin baseline onto one `cc -c` invocation and assert
    /// the classifier accepts it. This is the headline contract from
    /// #114: this exact shape should *cache*, not passthrough.
    #[test]
    fn classifier_accepts_realistic_firefox_compile() {
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-O2",
            "-g",
            "-std=gnu11",
            "-mmacosx-version-min=10.15",
            "-pthread",
            "-fno-strict-aliasing",
            "-fno-math-errno",
            "-funwind-tables",
            "-fstack-protector-strong",
            "-fno-omit-frame-pointer",
            "-ffp-contract=off",
            "-fstrict-flex-arrays=1",
            // Mixed with already-allowed flags to confirm no cross-
            // contamination from the additions.
            "-Wall",
            "-Wno-unused-parameter",
            "-DMOZILLA_INTERNAL_API=1",
            "-I/some/include",
        ]);
        assert!(
            descs.is_empty(),
            "realistic Firefox compile should be fully cacheable, got: {descs:?}"
        );
    }

    /// Pin the boundary: variants OUTSIDE the listed set must still
    /// passthrough — we are not opening `-fno-*` / `-fstack-protector*`
    /// as wildcards.
    #[test]
    fn classifier_does_not_overreach_gecko_darwin_family() {
        // Lookalike that isn't the macOS deployment-target flag
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-mmacosx-min-version=10.15",
        ]);
        assert!(
            descs.iter().any(|d| d.contains("unsupported flag")),
            "-mmacosx-min-version=10.15 is NOT on the #114 list and must still refuse, got: {descs:?}"
        );
        // The stack-protector family is now classified (Firefox nightly
        // passed `-fno-stack-protector` through while only `-strong` was listed).
        for flag in &[
            "-fstack-protector",
            "-fstack-protector-all",
            "-fno-stack-protector",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", flag]);
            assert!(
                !descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} is the stack-protector family and must classify, got: {descs:?}"
            );
        }
    }

    /// Firefox debug-info & clang argument-wrapper flags
    /// (kunobi-ninja/kache#117). Each row was previously refused as
    /// "unsupported flag" — 4,275 single-source compiles per Firefox
    /// build, per the issue's evidence.
    #[test]
    fn classifier_accepts_firefox_debug_info_and_wrapper_flags() {
        for flag in &[
            "-gdwarf-4",
            "-gsimple-template-names",
            "-mllvm=-dwarf-linkage-names=Abstract",
            "--start-no-unused-arguments",
            "--end-no-unused-arguments",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", flag]);
            assert!(
                !descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} should be classified (#117 baseline), got: {descs:?}"
            );
        }
    }

    /// cc-rs passes `-gdwarf-2` on every Apple target with debug info
    /// enabled (kunobi-ninja/kache#838). Like `-gdwarf-4` it is
    /// `CapturedByProbe`: the resolved `-###` cc1 line carries
    /// `-dwarf-version=2`, so the probe keys it — and the probe is
    /// REQUIRED (a driver whose `-###` doesn't resolve must fail closed).
    #[test]
    fn classifier_accepts_gdwarf2_issue_838() {
        let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", "-gdwarf-2"]);
        assert!(
            descs.is_empty(),
            "-gdwarf-2 should be classified (#838), got: {descs:?}"
        );
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o", "-gdwarf-2"])).unwrap();
        assert!(
            cc_flags_need_resolved_invocation(&parsed),
            "-gdwarf-2 is probe-keyed and must force the resolved invocation"
        );
    }

    /// ring's Darwin build.rs adds `-gfull` so Apple dead stripping can
    /// see used symbols (kunobi-ninja/kache#857). The flag changes DWARF
    /// sections, so it must be `CapturedByProbe`: the resolved `-###`
    /// tokens (`-debug-info-kind=standalone`, `-dwarf-version=N`) key
    /// it, and a driver whose probe cannot establish the effect must
    /// fail closed rather than under-key.
    #[test]
    fn classifier_accepts_gfull_issue_857() {
        assert_eq!(
            classify_cc_flag("-gfull", Dialect::Gnu),
            Some(FlagClass::CapturedByProbe),
            "-gfull must key through the resolved invocation"
        );
        let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", "-gfull"]);
        assert!(
            descs.is_empty(),
            "-gfull should be classified (#857), got: {descs:?}"
        );
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o", "-gfull"])).unwrap();
        assert!(
            parsed.refuse_reasons(&[]).is_empty(),
            "ring Darwin compile with -gfull must cache: {:?}",
            parsed.refuse_reasons(&[])
        );
        assert!(
            cc_flags_need_resolved_invocation(&parsed),
            "-gfull is probe-keyed and must force the resolved invocation"
        );
    }

    /// The #857 row is exact on the observed Apple spelling. The other
    /// Darwin dead-strip debug mode (`-gused`) and neighbouring `-g*`
    /// lookalikes stay refused until a workload needs them.
    #[test]
    fn gfull_neighbours_still_refuse_issue_857() {
        for flag in ["-gused", "-gfuller", "-gfull-dwarf"] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Gnu),
                None,
                "{flag} is not modeled and must keep refusing"
            );
        }
    }

    /// The argument-wrapper pair must work *together* on one
    /// invocation — that's the canonical clang usage shape
    /// (`--start-no-unused-arguments … <flags> … --end-no-unused-arguments`).
    /// Each flag classifies independently, but the test pins the
    /// realistic usage and guards against a future refactor that
    /// accidentally treats them as a region requiring special pairing.
    #[test]
    fn classifier_accepts_unused_arguments_wrapper_pair() {
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-O2",
            "--start-no-unused-arguments",
            "-Wno-unused-command-line-argument",
            "--end-no-unused-arguments",
        ]);
        assert!(
            descs.is_empty(),
            "wrapped pair should be fully cacheable, got: {descs:?}"
        );
    }

    /// Pin the boundary on #117's additions: adjacent variants must
    /// still passthrough so unsupported codegen flags don't slip in
    /// under the new rows.
    #[test]
    fn classifier_does_not_overreach_117_additions() {
        for flag in &[
            // DWARF version variants beyond the exactly-listed 2 (#838)
            // and 4 (#117)
            "-gdwarf-3",
            "-gdwarf-5",
            "-gdwarf",
            // Other -g* options (already documented as out-of-set)
            "-gline-tables-only",
            // -mllvm wildcards must stay refused. The exact-string row
            // for `-mllvm=-dwarf-linkage-names=Abstract` does NOT open
            // `-mllvm=*` as a prefix; that's deliberate (per the issue's
            // out-of-scope note).
            "-mllvm=-some-other-flag",
            "-mllvm=-inline-threshold=1000",
            // Lookalike wrapper flags
            "--start-no-unused",
            "--no-unused-arguments",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", flag]);
            assert!(
                descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} is NOT on the #117 list and must still refuse, got: {descs:?}"
            );
        }
    }

    /// C++ ABI / RTTI / exception flags (kunobi-ninja/kache#116).
    /// Each row affects the resulting object materially, and clang's
    /// `cc -###` resolved tokens differentiate them — RTTI on vs off,
    /// exceptions on vs off, and `-stdlib=libc++` vs `libstdc++` all
    /// produce distinct keys via the probe.
    #[test]
    fn classifier_accepts_cpp_abi_rtti_exception_flags() {
        for flag in &[
            "-stdlib=libc++",
            "-stdlib=libstdc++",
            "-fno-exceptions",
            "-fexceptions",
            "-fno-rtti",
            "-frtti",
            "-fno-sized-deallocation",
            "-fno-aligned-new",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.cpp", "-o", "foo.o", flag]);
            assert!(
                !descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} should be classified (#116 baseline), got: {descs:?}"
            );
        }
    }

    /// Build-system path-remapping flags must NOT refuse: a build enabling its
    /// own `-f*-prefix-map` (e.g. Firefox `--enable-path-remapping`) otherwise
    /// silently disabled all cc caching. They are `CapturedByProbe`, so the
    /// resolved-token hash keys them (and per-checkout `from` paths normalize
    /// through the cc prefix maps).
    #[test]
    fn classifier_accepts_path_prefix_map_flags() {
        for flag in &[
            "-ffile-prefix-map=/build/clone-a/=/topsrcdir/",
            "-fdebug-prefix-map=/build/clone-a/obj=/topobjdir/",
            "-fmacro-prefix-map=/build/clone-a/=/topsrcdir/",
            "-fdebug-prefix-map=/Applications/Xcode.app/.../SDK=/sysroot/",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.cpp", "-o", "foo.o", flag]);
            assert!(
                !descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} should be classified (path-remap), got: {descs:?}"
            );
        }
    }

    /// Issue #644: aws-lc-sys forwards its debug-prefix map to GNU as rather
    /// than cc1. The exact assembler sub-option is raw-keyed so it caches
    /// without pretending the cc1-only probe captured it.
    #[test]
    fn flag_classification_summary_records_raw_keyed_issue_644() {
        let mut summary = FlagClassificationSummary::default();
        summary.record(Some(FlagClass::RawKeyed));
        assert_eq!(summary.raw_keyed, 1);
    }

    /// Review finding #2: `-Werror` / `-Wno-error` / `-pedantic-errors`
    /// escalate warnings into hard errors — they change whether the compile
    /// SUCCEEDS even though a successful compile's object bytes are
    /// unchanged. Since hits replay success, they must be folded into the
    /// key (RawKeyed), not silently dropped like the diagnostics-only
    /// warning flags.
    #[test]
    fn outcome_gates_are_raw_keyed() {
        for flag in &[
            "-Werror",
            "-Werror=unused-variable",
            "-Wno-error",
            "-Wno-error=unused-variable",
            "-pedantic-errors",
            // Dashed legacy alias for `-Werror=implicit-function-declaration`,
            // still accepted by GCC and clang: same outcome effect, so it must
            // not slip through to the diagnostics-only `-W*` row below it.
            "-Werror-implicit-function-declaration",
            "-Wno-error-implicit-function-declaration",
        ] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Gnu),
                Some(FlagClass::RawKeyed),
                "{flag} is an outcome gate and must be keyed directly"
            );
            let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o", flag])).unwrap();
            assert!(
                parsed.refuse_reasons(&[]).is_empty(),
                "{flag} should be cacheable: {:?}",
                parsed.refuse_reasons(&[])
            );
        }
        // Distinct gate combinations must produce distinct raw-key folds:
        // an entry stored under `-Wno-error=foo` must not serve green to a
        // `-Werror` build that `foo` should have failed.
        let parse = |args: &[&str]| cc_raw_flags_for_key(&CcArgs::parse(&s(args)).unwrap(), &[]);
        let plain = parse(&["cc", "-c", "foo.c", "-o", "foo.o"]);
        let err = parse(&["cc", "-c", "foo.c", "-o", "foo.o", "-Werror"]);
        let no_err = parse(&["cc", "-c", "foo.c", "-o", "foo.o", "-Wno-error=foo"]);
        let both = parse(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-Werror",
            "-Wno-error=foo",
        ]);
        assert_ne!(plain, err, "-Werror must change the keyed flags");
        assert_ne!(err, both, "-Wno-error must distinguish from bare -Werror");
        assert_ne!(no_err, both);
    }

    /// Issue #823: `-mabi=` selects the target ABI, so it must be keyed.
    /// It refused before, which is why a cross-compiled C TU never cached;
    /// it now folds verbatim, and each ABI keys distinctly.
    #[test]
    fn mabi_is_raw_keyed_and_cacheable_issue_823() {
        for flag in &[
            "-mabi=lp64d", // riscv64 hard-float — the issue #823 invocation
            "-mabi=lp64",  // riscv64 soft-float: a different object
            "-mabi=ilp32",
            "-mabi=sysv", // x86-64
            "-mabi=ms",
            "-mabi=aapcs-linux", // arm
            // The rest of the class the `cc` crate injects for cross targets:
            "-mfloat-abi=hard",
            "-mfloat-abi=softfp",
            "-mfloat-abi=soft",
            "-mfpu=vfpv3-d16", // cc-rs armv7-eabihf default
            "-mfpu=neon",
            "-mfpu=vfp",
            "-mfpu=crypto-neon-fp-armv8",
            "-mthumb",
            "-marm",
            "-mcmodel=medany", // riscv firmware/kernel staple
            "-mcmodel=large",
        ] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Gnu),
                Some(FlagClass::RawKeyed),
                "{flag} selects the ABI and must be folded into the key verbatim"
            );
            let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o", flag])).unwrap();
            assert!(
                parsed.refuse_reasons(&[]).is_empty(),
                "{flag} should be cacheable: {:?}",
                parsed.refuse_reasons(&[])
            );
        }
        // Distinct ABIs must fold to distinct raw keys: serving an lp64d
        // object to an lp64 build is a broken binary, not a missed hit.
        let raw = |abi: &str| {
            cc_raw_flags_for_key(
                &CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o", abi])).unwrap(),
                &[],
            )
        };
        let plain = cc_raw_flags_for_key(
            &CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o"])).unwrap(),
            &[],
        );
        assert_ne!(raw("-mabi=lp64d"), raw("-mabi=lp64"));
        assert_ne!(raw("-mabi=sysv"), raw("-mabi=ms"));
        assert_ne!(plain, raw("-mabi=lp64d"), "an ABI gate must move the key");
        assert_ne!(raw("-mfloat-abi=hard"), raw("-mfloat-abi=soft"));
        assert_ne!(raw("-mfpu=neon"), raw("-mfpu=vfpv3-d16"));
        assert_ne!(raw("-mthumb"), raw("-marm"));
        assert_ne!(raw("-mcmodel=medany"), raw("-mcmodel=medlow"));
        // Conflicting occurrences are last-one-wins for the compiler, so the
        // fold must preserve argv ORDER (and duplicates): `-mthumb -marm`
        // ends in ARM state, the reverse in Thumb state.
        let raw2 = |a: &str, b: &str| {
            cc_raw_flags_for_key(
                &CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o", a, b])).unwrap(),
                &[],
            )
        };
        assert_ne!(
            raw2("-mthumb", "-marm"),
            raw2("-marm", "-mthumb"),
            "conflicting ISA-state flags are last-one-wins; order must key"
        );
        assert_ne!(raw("-mthumb"), raw("-mno-thumb"));
    }

    /// The exact `ring` invocation from issue #823. Every flag in it has to
    /// be modeled for the TU to cache at all; `-mabi=lp64d` was the one that
    /// refused, so this pins the whole argv rather than the flag alone.
    #[test]
    fn ring_cross_compile_invocation_is_cacheable_issue_823() {
        let argv = s(&[
            "cc",
            "-O0",
            "-ffunction-sections",
            "-fdata-sections",
            "-fPIC",
            "-g",
            "-gdwarf-4",
            "-fno-omit-frame-pointer",
            "-march=rv64gc",
            "-mabi=lp64d",
            "-I",
            "/cargo/registry/ring-0.17.14/include",
            "-I",
            "/cargo/registry/ring-0.17.14/pregenerated",
            "-Wall",
            "-Wextra",
            "-fvisibility=hidden",
            "-std=c1x",
            "-Wbad-function-cast",
            "-Wcast-align",
            "-Wcast-qual",
            "-Wconversion",
            "-Wmissing-field-initializers",
            "-Wmissing-include-dirs",
            "-Wnested-externs",
            "-Wredundant-decls",
            "-Wshadow",
            "-Wsign-compare",
            "-Wsign-conversion",
            "-Wstrict-prototypes",
            "-Wundef",
            "-Wuninitialized",
            "-g3",
            "-DNDEBUG",
            "-o",
            "/build/out/25ac62e5b3c53843-curve25519.o",
            "-c",
            "/cargo/registry/ring-0.17.14/crypto/curve25519/curve25519.c",
        ]);
        let parsed = CcArgs::parse(&argv).unwrap();
        assert!(
            parsed.refuse_reasons(&[]).is_empty(),
            "the #823 invocation must cache: {:?}",
            parsed.refuse_reasons(&[])
        );
        // `-march=` is probe-captured, so this argv must resolve `-###`
        // before it can key — the ABI fold does not replace that.
        assert!(cc_flags_need_resolved_invocation(&parsed));
    }

    /// The flags the `cc` crate injects on its own for
    /// `armv7-unknown-linux-gnueabihf` (cc-rs `lib.rs`: `-march=armv7-a
    /// -mfpu=vfpv3-d16 -mfloat-abi=hard`), plus `-mthumb` for the thumbv7
    /// variants. No hand-written build file mentions these — refusing any
    /// one of them silently uncaches every arm cross build.
    #[test]
    fn cc_rs_armv7_injected_flags_are_cacheable_issue_823() {
        let argv = s(&[
            "arm-linux-gnueabihf-gcc",
            "-O2",
            "-ffunction-sections",
            "-fdata-sections",
            "-fPIC",
            "-march=armv7-a",
            "-mthumb",
            "-mfpu=vfpv3-d16",
            "-mfloat-abi=hard",
            "-o",
            "/build/out/foo.o",
            "-c",
            "foo.c",
        ]);
        let parsed = CcArgs::parse(&argv).unwrap();
        assert!(
            parsed.refuse_reasons(&[]).is_empty(),
            "the cc-rs armv7 invocation must cache: {:?}",
            parsed.refuse_reasons(&[])
        );
        assert!(cc_flags_need_resolved_invocation(&parsed));
    }

    /// The #823 rows must not widen into the host-relative `-m` knobs.
    /// `-mtune=`/`-mcpu=` accept `native` and `-mfpu=` accepts `auto` —
    /// values whose meaning depends on the host or the toolchain's
    /// configured defaults rather than on the flag text — so they stay
    /// refused until modeled deliberately.
    #[test]
    fn host_relative_m_knobs_still_refuse_issue_823() {
        for flag in &[
            "-mtune=native",
            "-mtune=skylake",
            "-mcpu=native",
            "-mfpu=auto",
        ] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Gnu),
                None,
                "{flag} is not modeled and must keep refusing"
            );
        }
    }

    #[test]
    fn wa_debug_prefix_map_is_raw_keyed_issue_644() {
        for flag in &[
            "-Wa,--debug-prefix-map=/home/runner/.cargo/registry/src/index.crates.io-hash/aws-lc-sys-0.43.0=",
            "-Wa,--debug-prefix-map=/build/aws-lc-sys-0.44.1=/vendor/aws-lc",
        ] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Gnu),
                Some(FlagClass::RawKeyed),
                "{flag} should be keyed directly"
            );
            let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.S", "-o", "foo.o", flag])).unwrap();
            assert!(
                parsed.refuse_reasons(&[]).is_empty(),
                "{flag} should be cacheable: {:?}",
                parsed.refuse_reasons(&[])
            );
            assert!(
                !cc_flags_need_resolved_invocation(&parsed),
                "raw-keyed assembler flags must not depend on a cc1 probe"
            );
        }
    }

    #[test]
    fn wa_debug_prefix_map_normalizes_only_from_issue_644() {
        let maps_a = vec![CcPrefixMap {
            from: "/work/clone-a".to_string(),
            to: CC_ROOT_SENTINEL.to_string(),
        }];
        let maps_b = vec![CcPrefixMap {
            from: "/work/clone-b".to_string(),
            to: CC_ROOT_SENTINEL.to_string(),
        }];
        let parse =
            |flag: &str| CcArgs::parse(&s(&["cc", "-c", "foo.S", "-o", "foo.o", flag])).unwrap();

        let a = cc_raw_flags_for_key(
            &parse("-Wa,--debug-prefix-map=/work/clone-a/vendor/aws-lc="),
            &maps_a,
        );
        let b = cc_raw_flags_for_key(
            &parse("-Wa,--debug-prefix-map=/work/clone-b/vendor/aws-lc="),
            &maps_b,
        );
        assert_eq!(a, b, "relocated OLD paths should normalize identically");
        assert_eq!(
            String::from_utf8(a[0].clone()).unwrap(),
            format!("-Wa,--debug-prefix-map={CC_ROOT_SENTINEL}/vendor/aws-lc=")
        );

        let target_a = cc_raw_flags_for_key(
            &parse("-Wa,--debug-prefix-map=/work/clone-a/vendor/aws-lc=/mapped-a"),
            &maps_a,
        );
        let target_b = cc_raw_flags_for_key(
            &parse("-Wa,--debug-prefix-map=/work/clone-a/vendor/aws-lc=/mapped-b"),
            &maps_a,
        );
        assert_ne!(
            target_a, target_b,
            "NEW is object material and must stay keyed"
        );
        assert!(
            String::from_utf8(target_a[0].clone())
                .unwrap()
                .ends_with("=/mapped-a"),
            "NEW must remain verbatim"
        );

        let ordered = CcArgs::parse(&s(&[
            "cc",
            "-c",
            "foo.S",
            "-o",
            "foo.o",
            "-Wa,--debug-prefix-map=/work/clone-a/vendor/aws-lc=/first",
            "-Wa,--debug-prefix-map=/work/clone-a/vendor/aws-lc=/second",
        ]))
        .unwrap();
        assert_eq!(
            cc_raw_flags_for_key(&ordered, &maps_a),
            vec![
                format!("-Wa,--debug-prefix-map={CC_ROOT_SENTINEL}/vendor/aws-lc=/first")
                    .into_bytes(),
                format!("-Wa,--debug-prefix-map={CC_ROOT_SENTINEL}/vendor/aws-lc=/second")
                    .into_bytes(),
            ],
            "raw-keyed flags must preserve argv order"
        );
    }

    #[test]
    fn wa_debug_prefix_map_does_not_open_other_assembler_flags_issue_644() {
        for flag in &[
            "-Wa,--debug-prefix-map",
            "-Wa,--debug-prefix-map=/from-only",
            "-Wa,--debug-prefix-map-extra=/from=/to",
            "-Wa,--debug-prefix-map=/from=/to,--fatal-warnings",
            "-Wa,--something-else",
        ] {
            assert_eq!(classify_cc_flag(flag, Dialect::Gnu), None, "{flag}");
            let descs = refuse_descriptions(&["cc", "-c", "foo.S", "-o", "foo.o", flag]);
            assert!(
                descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} must remain unsupported, got: {descs:?}"
            );
        }
    }

    /// The raw-keyed classification is load-bearing: two assembler maps that
    /// produce identical preprocessor/probe output must still produce distinct
    /// artifact keys when their object-material NEW values differ.
    #[cfg(unix)]
    #[test]
    fn wa_debug_prefix_map_changes_cache_key_issue_644() {
        use std::fs;

        let temp = tempfile::tempdir().unwrap();
        // A checked-in executable avoids ETXTBSY when another test forks
        // while a runtime-created script is still open for writing.
        let fake_cc =
            Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mock_cc_constant_output.sh");
        let source = temp.path().join("unit.S");
        fs::write(&source, "/* fake compiler ignores this */\n").unwrap();
        let output = temp.path().join("unit.o");

        let compiler = CcCompiler::new();
        let parse = |target: &str| {
            compiler
                .parse(&[
                    fake_cc.to_string_lossy().into_owned(),
                    "-c".to_string(),
                    source.to_string_lossy().into_owned(),
                    "-o".to_string(),
                    output.to_string_lossy().into_owned(),
                    format!("-Wa,--debug-prefix-map=/source={target}"),
                ])
                .unwrap()
        };
        let cache = temp.path().join("cache");
        let file_hasher = crate::cache_key::FileHasher::new();
        let path_normalizer = crate::path_normalizer::PathNormalizer::empty();
        let ctx = KeyCtx {
            file_hasher: &file_hasher,
            path_normalizer: &path_normalizer,
            cache_dir: &cache,
            key_salt: None,
            key_env_vars: &[],
            extra_inputs_digest: None,
        };

        let key_a = compiler.cache_key(&parse("/mapped-a"), &ctx).unwrap();
        let key_b = compiler.cache_key(&parse("/mapped-b"), &ctx).unwrap();
        assert_ne!(key_a, key_b, "different NEW values must not collide");
    }

    /// A realistic Firefox-style C++ compile: pile the full #116
    /// baseline plus already-allowed flags onto one `cc -c` invocation
    /// and assert the classifier accepts it as fully cacheable.
    #[test]
    fn classifier_accepts_realistic_firefox_cpp_compile() {
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.cpp",
            "-o",
            "foo.o",
            "-O2",
            "-g",
            "-std=gnu++17",
            "-stdlib=libc++",
            "-fno-exceptions",
            "-fno-rtti",
            "-fno-sized-deallocation",
            "-fno-aligned-new",
            // Mixed with previously-allowed Gecko/Darwin baseline flags
            // (#114) to confirm no cross-contamination between
            // additions.
            "-mmacosx-version-min=10.15",
            "-fno-strict-aliasing",
            "-fstack-protector-strong",
            "-Wall",
            "-DMOZILLA_INTERNAL_API=1",
        ]);
        assert!(
            descs.is_empty(),
            "realistic Firefox C++ compile should be fully cacheable, got: {descs:?}"
        );
    }

    /// Pin the boundary on #116: adjacent forms / lookalikes must
    /// still refuse so unmodeled codegen flags don't slip past via
    /// the new rows.
    #[test]
    fn classifier_does_not_overreach_116_additions() {
        for flag in &[
            // Sanitizers aren't on #116's list — they remained refused
            // before and must stay refused. (Visibility flags moved to
            // their own cluster, post-#146 — see
            // `classifier_does_not_overreach_visibility_additions`.)
            "-fsanitize=undefined",
            // Aligned-new POSITIVE form not on the list. The negative
            // form (`-fno-aligned-new`) is what Firefox uses; if a
            // workload needs `-faligned-new`, file a follow-up.
            "-faligned-new",
            "-fsized-deallocation",
            // `-stdlib=` lookalike that isn't actually the C++ stdlib
            // selector.
            "-fstdlib=libc++",
            // `-fno-rt*`/`-fno-ex*` near-matches that aren't on the list.
            "-fno-rt",
            "-fno-rttis",
            "-fexception",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.cpp", "-o", "foo.o", flag]);
            assert!(
                descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} is NOT on the #116 list and must still refuse, got: {descs:?}"
            );
        }
    }

    /// ELF symbol-visibility defaults (Firefox bench evidence, post-#146).
    /// Both flags must classify so the warm Firefox build's largest
    /// passthrough bucket (2987 events) becomes cacheable.
    #[test]
    fn classifier_accepts_visibility_flags() {
        for flag in &["-fvisibility=hidden", "-fvisibility-inlines-hidden"] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.cpp", "-o", "foo.o", flag]);
            assert!(
                !descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} should classify (visibility cluster), got: {descs:?}"
            );
        }
    }

    /// Pin the boundary on the visibility cluster: only the two exact
    /// values Firefox uses are accepted. Other `-fvisibility=` modes
    /// and the negative form of `-fvisibility-inlines-hidden` must
    /// still refuse so unmodeled visibility codegen can't slip past.
    #[test]
    fn classifier_does_not_overreach_visibility_additions() {
        for flag in &[
            // Other -fvisibility= values aren't listed (Exact, not Prefix).
            "-fvisibility=default",
            "-fvisibility=protected",
            "-fvisibility=internal",
            // Bare / lookalikes / typos.
            "-fvisibility",
            "-fvisible=hidden",
            // Negative form of the inlines flag — different codegen.
            "-fno-visibility-inlines-hidden",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.cpp", "-o", "foo.o", flag]);
            assert!(
                descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} is NOT on the visibility list and must still refuse, got: {descs:?}"
            );
        }
    }

    /// Target / arch / WASM / ObjC / section flags
    /// (kunobi-ninja/kache#115). Each row affects the resulting object
    /// materially; clang's `cc -###` resolves each into the `-cc1`
    /// token stream so the cache key differentiates per-value.
    #[test]
    fn classifier_accepts_target_arch_objc_flags() {
        for flag in &[
            // Sticky --target= for several real triples Firefox uses
            "--target=arm64-apple-macosx",
            "--target=wasm32-wasi",
            "--target=aarch64-linux-gnu",
            // Separate-arg form
            "-target",
            // -march= family — native + specific microarchs
            "-march=native",
            "-march=armv8-a",
            "-march=armv8.2-a+dotprod",
            "-march=armv8.2-a+i8mm",
            // WASM SIMD
            "-msimd128",
            // x86 width / SIMD feature flags from issue #375
            "-m64",
            "-m32",
            "-msse2",
            "-msse4.1",
            "-msse4.2",
            "-mavx2",
            // Section layout
            "-ffunction-sections",
            "-fdata-sections",
            // Assembler passthrough (specific value, not wildcard)
            "-Wa,--noexecstack",
            // Language override forms
            "-x",
            "-xc",
            "-xc++",
            "-xobjective-c",
            "-xobjective-c++",
            // ObjC codegen modes
            "-fobjc-exceptions",
            "-fobjc-arc",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", flag]);
            assert!(
                !descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} should be classified (#115 baseline), got: {descs:?}"
            );
        }
    }

    /// A realistic Firefox-style cross-compile invocation:
    /// `cc -c foo.c -O2 -g --target=wasm32-wasi -msimd128 …` (the
    /// WASM bundling pipeline) plus previously-allowed flags.
    /// Headline contract from #115's acceptance criteria — "tests
    /// cover wasm target flags".
    #[test]
    fn classifier_accepts_realistic_firefox_wasm_compile() {
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-O2",
            "-g",
            "-std=gnu11",
            "--target=wasm32-wasi",
            "-msimd128",
            "-ffunction-sections",
            "-fdata-sections",
            "-fno-strict-aliasing",
            "-Wa,--noexecstack",
            "-Wall",
            "-DMOZILLA_BUILD=1",
        ]);
        assert!(
            descs.is_empty(),
            "realistic Firefox WASM compile should be fully cacheable, got: {descs:?}"
        );
    }

    /// Realistic ObjC++ Firefox compile — the language override goes
    /// through, the ObjC-specific codegen flags go through. Pins
    /// #115's third acceptance criterion ("ObjC/ObjC++ language mode
    /// flags").
    #[test]
    fn classifier_accepts_realistic_firefox_objc_compile() {
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.mm",
            "-o",
            "foo.o",
            "-O2",
            "-g",
            "-xobjective-c++",
            "-fobjc-arc",
            "-fobjc-exceptions",
            "-fno-exceptions",
            "-fno-rtti",
            "-stdlib=libc++",
            "-mmacosx-version-min=11.0",
            "-march=armv8-a",
        ]);
        assert!(
            descs.is_empty(),
            "realistic Firefox ObjC++ compile should be fully cacheable, got: {descs:?}"
        );
    }

    /// Pin the boundary on #115: adjacent / unmodeled forms must
    /// still refuse so wildcards stay scoped to what #115 actually
    /// covers.
    #[test]
    fn classifier_does_not_overreach_115_additions() {
        for flag in &[
            // `-Wa,*` wildcard is NOT opened — only the specific
            // `--noexecstack` value is. Other assembler passthroughs
            // refuse.
            "-Wa,-mfp",
            "-Wa,--something-else",
            // Other sticky `-x` variants still need explicit rows.
            "-xassembler-with-cpp",
            "-xnone",
            // ObjC variants not on the list
            "-fno-objc-arc",
            "-fobjc-weak",
            // (-fno-function-sections / -fno-data-sections are now modeled via
            // the codegen-knob stem list, both polarities — no longer here.)
            // `-m`-shaped flags that are NOT x86 ISA features — value-takers
            // and tuning knobs the SIMD regex must NOT swallow.
            "-mtune=skylake",
            "-mfpmath=sse",
            // (`-mcmodel=` moved to the modeled #823 class; `-mfpu=auto`
            // resolves inside cc1 so its text is not the object.)
            "-mfpu=auto",
        ] {
            let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", flag]);
            assert!(
                descs.iter().any(|d| d.contains("unsupported flag")),
                "{flag} is NOT on the #115 list and must still refuse, got: {descs:?}"
            );
        }
    }

    #[test]
    fn refuse_reason_names_the_rejected_flags() {
        // The refusal must report *which* flags blocked caching — that
        // visibility is what makes "add support over time" actionable.
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-mtune=skylake",
            "-fsanitize=address",
        ]);
        let detail = descs
            .iter()
            .find(|d| d.contains("unsupported flag"))
            .expect("expected an unsupported-flag refuse reason");
        assert!(
            detail.contains("-mtune=skylake"),
            "reason should name the flag: {detail}"
        );
        assert!(
            detail.contains("-fsanitize=address"),
            "reason should name every rejected flag: {detail}"
        );
    }

    #[test]
    fn classifier_accepts_parser_handled_and_preprocessor_only_flags() {
        for (flag, expected) in [
            ("-c", FlagClass::ParserHandled),
            ("-E", FlagClass::ParserHandled),
            ("-S", FlagClass::ParserHandled),
            ("-P", FlagClass::NoObjectEffect),
            ("-xc", FlagClass::CapturedByProbe),
            ("-xc++", FlagClass::CapturedByProbe),
            ("-xobjective-c", FlagClass::CapturedByProbe),
        ] {
            assert_eq!(
                classify_cc_flag(flag, Dialect::Gnu),
                Some(expected),
                "{flag} should have the expected class"
            );
        }
    }

    #[test]
    fn cc_arg_spec_for_token_filters_by_dialect() {
        // `-MT` is a dep-target parse row tagged Gnu-only (Layer 0). It
        // must resolve under Gnu but NOT under Cl — otherwise a future cl
        // row for an overlapping spelling would be shadowed by the gnu
        // row (the Layer 2 prerequisite).
        assert!(cc_arg_spec_for_token("-MT", Dialect::Gnu).is_some());
        assert!(cc_arg_spec_for_token("-MT", Dialect::Cl).is_none());
        // A dialect-less row (`-o`) resolves under both.
        assert!(cc_arg_spec_for_token("-o", Dialect::Gnu).is_some());
        assert!(cc_arg_spec_for_token("-o", Dialect::Cl).is_some());
    }

    #[test]
    fn arg_analysis_exposes_bucket_and_normalized_value_form() {
        let language = analyze_cc_arg("-xc++", Dialect::Gnu);
        assert_eq!(language.class, Some(FlagClass::CapturedByProbe));
        assert_eq!(language.bucket, CcArgBucket::ProbeKeyed);
        assert_eq!(
            language.normalized,
            vec!["-x".to_string(), "c++".to_string()]
        );
        assert_eq!(language.refusal, None);

        let include = analyze_cc_arg("-Ivendor", Dialect::Gnu);
        assert_eq!(include.class, Some(FlagClass::PreprocessorCaptured));
        assert_eq!(include.bucket, CcArgBucket::Preprocessor);
        assert_eq!(
            include.normalized,
            vec!["-I".to_string(), "vendor".to_string()]
        );

        let unknown = analyze_cc_arg("-funknown", Dialect::Gnu);
        assert_eq!(unknown.class, None);
        assert_eq!(unknown.bucket, CcArgBucket::TooHard);
        assert_eq!(unknown.refusal, Some("cc: unsupported flag"));
    }

    #[test]
    fn unsupported_flag_reason_excludes_classified_mixed_flags() {
        let descs = refuse_descriptions(&[
            "cc",
            "-c",
            "foo.c",
            "-o",
            "foo.o",
            "-P",
            "-xc",
            "-Ofast",
            "-funknown",
        ]);
        let detail = descs
            .iter()
            .find(|d| d.contains("unsupported flag"))
            .expect("expected unsupported flags for the truly unmodeled args");
        assert!(
            detail.contains("-Ofast"),
            "reason should name -Ofast: {detail}"
        );
        assert!(
            detail.contains("-funknown"),
            "reason should name -funknown: {detail}"
        );
        assert!(
            !detail.contains("-P"),
            "reason should not include -P: {detail}"
        );
        assert!(
            !detail.contains("-xc"),
            "reason should not include -xc: {detail}"
        );
    }

    /// Issue #411 — `-TP`/`-TC` (force C++/C source) and `-ffile-reproducible`
    /// classify as `CapturedByProbe`: they affect the object (language mode,
    /// embedded paths) but clang resolves each into a distinct `-cc1` token,
    /// so the resolved-token hash keys them.
    #[test]
    fn force_lang_and_file_reproducible_classify_as_probe_captured_issue_411() {
        assert_eq!(
            classify_cc_flag("-TP", Dialect::Cl),
            Some(FlagClass::CapturedByProbe)
        );
        assert_eq!(
            classify_cc_flag("/TP", Dialect::Cl),
            Some(FlagClass::CapturedByProbe)
        );
        assert_eq!(
            classify_cc_flag("-TC", Dialect::Cl),
            Some(FlagClass::CapturedByProbe)
        );
        assert_eq!(
            classify_cc_flag("-ffile-reproducible", Dialect::Cl),
            Some(FlagClass::CapturedByProbe)
        );
        assert_eq!(
            classify_cc_flag("-ffile-reproducible", Dialect::Gnu),
            Some(FlagClass::CapturedByProbe)
        );
        // `-TP`/`-TC` are clang-cl spellings; under the gnu dialect they are
        // not known flags (gnu uses `-x c++`), so they must refuse there.
        assert_eq!(classify_cc_flag("-TP", Dialect::Gnu), None);
        assert_eq!(classify_cc_flag("-TC", Dialect::Gnu), None);
    }

    /// Issue #411 — the `-Xclang` forwarded-flag classifier accepts the inert
    /// cc1 dep-info / diagnostics flags Firefox forwards, and the bare value
    /// tokens that follow them, but refuses any other forwarded flag so an
    /// `-Xclang`-wrapped codegen flag can't slip past.
    #[test]
    fn xclang_forwarded_classifier_issue_411() {
        let cl = Dialect::Cl;
        assert_eq!(
            classify_xclang_forwarded("-MP", cl),
            Some(FlagClass::NoObjectEffect)
        );
        assert_eq!(
            classify_xclang_forwarded("-dependency-file", cl),
            Some(FlagClass::NoObjectEffect)
        );
        assert_eq!(
            classify_xclang_forwarded("-fansi-escape-codes", cl),
            Some(FlagClass::NoObjectEffect)
        );
        // The dep-target flags that MUST accompany `-dependency-file` (cc1
        // rejects it otherwise). These previously slipped past only because
        // the bare `-MT` token collided with the clang-cl CRT row; the
        // forwarding path must classify them on their own merits.
        assert_eq!(
            classify_xclang_forwarded("-MT", cl),
            Some(FlagClass::NoObjectEffect)
        );
        assert_eq!(
            classify_xclang_forwarded("-MQ", cl),
            Some(FlagClass::NoObjectEffect)
        );
        assert_eq!(
            classify_xclang_forwarded("-sys-header-deps", cl),
            Some(FlagClass::NoObjectEffect)
        );
        // A bare value (e.g. the dependency-file path, itself forwarded as
        // its own `-Xclang <path>`) is inert.
        assert_eq!(
            classify_xclang_forwarded("dom/ipc/Unified_cpp_dom_ipc5.cpp.pp", cl),
            Some(FlagClass::NoObjectEffect)
        );
        // #428: a forwarded flag that matches a modeled CapturedByProbe codegen
        // knob is allowed and keyed via the resolved cc1 probe (the bare operand
        // also forces the probe), so `-Xclang -ffp-contract=off` / `-ffast-math`
        // cache instead of passing through.
        assert_eq!(
            classify_xclang_forwarded("-ffp-contract=off", cl),
            Some(FlagClass::CapturedByProbe)
        );
        assert_eq!(
            classify_xclang_forwarded("-ffast-math", cl),
            Some(FlagClass::CapturedByProbe)
        );
        // An UNMODELED forwarded flag (not in CC_FLAGS) must still refuse —
        // not be swallowed blindly.
        assert_eq!(classify_xclang_forwarded("-mllvm", cl), None);
        assert_eq!(classify_xclang_forwarded("-fnot-a-real-flag", cl), None);
    }

    /// Issue #411 — a full Firefox/Windows clang-cl invocation: `-TP`,
    /// `-ffile-reproducible`, and `-Xclang`-forwarded cc1 dep-info /
    /// diagnostics flags. All must classify so the compile is cacheable
    /// instead of passing through as "unsupported flag(s)".
    #[test]
    fn firefox_windows_clang_cl_compile_is_cacheable_issue_411() {
        let parsed = CcArgs::parse(&s(&[
            "clang-cl",
            "-c",
            "-TP",
            "-ffile-reproducible",
            "-Xclang",
            "-MP",
            "-Xclang",
            "-dependency-file",
            "-Xclang",
            "dom/ipc/Unified_cpp_dom_ipc5.cpp.pp",
            "-Xclang",
            "-MT",
            "-Xclang",
            "Unified_cpp_dom_ipc5.obj",
            "-Xclang",
            "-fansi-escape-codes",
            "-FoUnified_cpp_dom_ipc5.obj",
            "dom/ipc/Unified_cpp_dom_ipc5.cpp",
        ]))
        .unwrap();
        // The dep-file path must not be miscounted as a second source.
        assert_eq!(parsed.sources.len(), 1, "exactly one source TU");
        let descs: Vec<&str> = parsed
            .refuse_reasons(&[])
            .iter()
            .map(|r| r.description())
            .collect();
        assert!(
            !descs.iter().any(|d| d.contains("unsupported flag")),
            "issue #411 flags must all classify; got: {descs:?}"
        );
        // `-TP` / `-ffile-reproducible` are CapturedByProbe, so the resolved
        // `-###` invocation is required to key them safely.
        assert!(
            cc_flags_need_resolved_invocation(&parsed),
            "probe-captured flags must force the resolved invocation"
        );
    }

    /// Issue #428: a `-Xclang`-forwarded flag that matches a modeled
    /// `CapturedByProbe` codegen knob now CACHES — Firefox's Windows clang-cl
    /// build passes `-Xclang -ffp-contract=off` on ~every TU, and the resolved
    /// cc1 probe records the forwarded flag, so the key differentiates it. An
    /// UNMODELED `-Xclang` codegen flag still refuses (the #411 boundary holds
    /// for anything not in `CC_FLAGS` — the relaxation is principled, not blind).
    #[test]
    fn xclang_forwarded_modeled_knob_caches_unmodeled_refuses_issue_428() {
        // Modeled knob via -Xclang: must NOT refuse.
        let ok = refuse_descriptions(&[
            "clang-cl",
            "-c",
            "-Xclang",
            "-ffp-contract=off",
            "-Foa.obj",
            "a.cpp",
        ]);
        assert!(
            !ok.iter().any(|d| d.contains("unsupported flag")),
            "-Xclang -ffp-contract=off must classify (cache), got: {ok:?}"
        );
        // Unmodeled forwarded flag: must still refuse, naming the flag.
        let bad = refuse_descriptions(&[
            "clang-cl",
            "-c",
            "-Xclang",
            "-fnot-a-real-codegen-flag",
            "-Foa.obj",
            "a.cpp",
        ]);
        let detail = bad
            .iter()
            .find(|d| d.contains("unsupported flag"))
            .expect("an UNMODELED -Xclang flag must still refuse");
        assert!(
            detail.contains("-fnot-a-real-codegen-flag"),
            "reason should name the unmodeled forwarded flag: {detail}"
        );
    }

    #[test]
    fn probe_captured_flags_require_resolved_invocation() {
        let needs_probe =
            CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o", "-fno-rtti"])).unwrap();
        assert!(cc_flags_need_resolved_invocation(&needs_probe));

        let modeled_only =
            CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o", "-O2", "-P"])).unwrap();
        assert!(!cc_flags_need_resolved_invocation(&modeled_only));
    }

    // Unix-only: uses `/usr/bin/true` as a stand-in "compiler" that accepts
    // `--version` but emits no `-cc1` line. There is no equivalent always-present
    // no-op binary on Windows (spawning `true` there fails outright), and the
    // guard's logic itself is covered cross-platform by
    // `probe_captured_flags_require_resolved_invocation`.
    #[cfg(unix)]
    #[test]
    fn cache_key_refuses_probe_captured_flags_without_resolved_invocation() {
        // `/usr/bin/true` accepts `--version` but produces no `-###`
        // `-cc1` line. That isolates the resolved-invocation guard
        // before the preprocessor hash runs. Every `CapturedByProbe`
        // shape fails closed here; `-gdwarf-2` pins the #838 row.
        let compiler = CcCompiler::new();
        for flag in ["-fno-rtti", "-gdwarf-2", "-gfull"] {
            let parsed = compiler
                .parse(&s(&["true", "-c", "foo.c", "-o", "foo.o", flag]))
                .unwrap();
            let cache = tempfile::tempdir().unwrap();
            let file_hasher = crate::cache_key::FileHasher::new();
            let path_normalizer = crate::path_normalizer::PathNormalizer::empty();
            let ctx = KeyCtx {
                file_hasher: &file_hasher,
                path_normalizer: &path_normalizer,
                cache_dir: cache.path(),
                key_salt: None,
                key_env_vars: &[],
                extra_inputs_digest: None,
            };

            let err = compiler.cache_key(&parsed, &ctx).unwrap_err().to_string();
            assert!(
                err.contains("resolved invocation unavailable"),
                "expected resolved-invocation refusal for {flag}, got: {err}"
            );
        }
    }

    #[test]
    fn preprocess_mode_refusal_does_not_report_classified_flags_as_unsupported() {
        let descs = refuse_descriptions(&["cc", "-E", "-xc", "-P", "foo.c"]);
        assert!(
            descs.iter().any(|d| d.contains("preprocessor mode")),
            "expected preprocessor-mode refuse, got: {descs:?}"
        );
        assert!(
            !descs.iter().any(|d| d.contains("unsupported flag")),
            "classified preprocess args should not be reported unsupported: {descs:?}"
        );
    }

    #[test]
    fn refuses_preprocess_and_assemble_modes() {
        let preprocess = refuse_descriptions(&["cc", "-E", "foo.c"]);
        assert!(
            preprocess.iter().any(|d| d.contains("preprocessor")),
            "expected preprocessor-mode refuse, got: {preprocess:?}"
        );

        let assemble = refuse_descriptions(&["cc", "-S", "foo.c"]);
        assert!(
            assemble.iter().any(|d| d.contains("assembly")),
            "expected assembly-mode refuse, got: {assemble:?}"
        );
    }

    /// Non-`-c` mode refusals (preprocessor, assembly, link,
    /// output-to-stdout) must NOT carry "unsupported flag(s)" noise.
    /// Mixing them mis-categorizes a correctly-refused non-compile
    /// as a kache classifier gap. Each refusal is `Unsupported` with
    /// "(not yet supported)" in the message — none of these are
    /// conceptually uncacheable, just deferred.
    #[test]
    fn non_compile_refusal_does_not_carry_unsupported_flag_noise() {
        let compiler = CcCompiler::new();

        // Preprocessor mode. Pre-refactor this returned BOTH
        // "unsupported flag(s): -xc -P -E" AND "preprocessor mode
        // (-E)", inflating the "classifier gap" bucket. Post-refactor
        // only the mode refusal fires.
        let parsed = compiler
            .parse(&s(&["cc", "-xc", "-P", "-E", "foo.c"]))
            .unwrap();
        let reasons = compiler.refuse_reasons(&parsed);
        let descs: Vec<_> = reasons.iter().map(|r| r.description()).collect();
        assert!(
            descs.iter().any(|d| d.contains("preprocessor mode")),
            "preprocessor mode must be reported, got: {descs:?}"
        );
        assert!(
            !descs.iter().any(|d| d.contains("unsupported flag")),
            "preprocessor-mode refusal must not carry 'unsupported flag' noise, got: {descs:?}"
        );
        // Must read as a deferral, not a permanent limitation.
        assert!(
            descs.iter().any(|d| d.contains("— not yet")),
            "preprocessor mode message must read as deferral ('— not yet'), got: {descs:?}"
        );

        // Link mode — also `Unsupported` with "— not yet".
        // Same short-circuit: the flag classifier's complaint about
        // `-fuse-ld=lld` would be misleading because the issue is
        // "link mode", not the flag.
        let parsed = compiler
            .parse(&s(&["cc", "foo.o", "-fuse-ld=lld", "-o", "out"]))
            .unwrap();
        let reasons = compiler.refuse_reasons(&parsed);
        let descs: Vec<_> = reasons.iter().map(|r| r.description()).collect();
        assert!(
            descs.iter().any(|d| d.contains("link mode")),
            "link mode must be reported, got: {descs:?}"
        );
        assert!(
            !descs.iter().any(|d| d.contains("unsupported flag")),
            "link-mode refusal must not carry 'unsupported flag' noise, got: {descs:?}"
        );
        assert!(
            reasons
                .iter()
                .any(|r| matches!(r, RefuseReason::Unsupported(d) if d.contains("link mode"))),
            "link mode must classify as Unsupported (roadmap), got: {reasons:?}"
        );
    }

    /// The complement: a real single-source compile with a single
    /// unmodeled flag MUST still report "unsupported flag(s)" — that
    /// case is exactly what the bench's "classifier gap" bucket is
    /// for, and what the next CC_FLAGS row would fix.
    #[test]
    fn compile_mode_unmodeled_flag_still_reports_unsupported_flag() {
        let descs = refuse_descriptions(&["cc", "-c", "foo.c", "-o", "foo.o", "-Ofast"]);
        assert!(
            descs.iter().any(|d| d.contains("unsupported flag")),
            "compile-mode unmodeled flag must still report 'unsupported flag', got: {descs:?}"
        );
    }

    #[test]
    fn refuses_nothing_for_clean_compile_invocation() {
        // The shape we WANT to cache: compile-only, single source,
        // explicit output, common flags. Only the skeleton catch-all
        // should fire (added in Compiler::refuse_reasons, not in
        // CcArgs::refuse_reasons), so the parser-level check is empty.
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            "src/foo.c",
            "-o",
            "build/foo.o",
            "-O2",
            "-g",
            "-fPIC",
            "-Iinclude",
        ]))
        .unwrap();
        assert!(
            parsed.refuse_reasons(&[]).is_empty(),
            "clean compile invocation should have no parser-level refuse reasons; got: {:?}",
            parsed.refuse_reasons(&[])
        );
    }

    // ── Compiler trait: refuse / execute / classify ─────────────

    #[test]
    fn refuse_reasons_empty_for_cacheable_single_source_compile() {
        // The skeleton catch-all is GONE. A single-source `-c`
        // compile with no unsafe flags now produces an EMPTY refuse
        // list — that's the signal to the wrapper that the
        // invocation is cacheable. When this test starts failing,
        // either a new refuse rule landed (intentional) or caching
        // got accidentally disabled (the bug to investigate).
        let compiler = CcCompiler::new();
        let parsed = compiler
            .parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o"]))
            .unwrap();
        assert!(
            compiler.refuse_reasons(&parsed).is_empty(),
            "single-source -c compile must be cacheable, got: {:?}",
            compiler
                .refuse_reasons(&parsed)
                .iter()
                .map(|r| r.description())
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn refuse_reasons_refuses_link_mode() {
        // Link (the default mode — no `-c`) is not cacheable in this
        // phase. Whole-program caching is a separate, harder problem.
        let compiler = CcCompiler::new();
        let parsed = compiler.parse(&s(&["cc", "foo.c", "-o", "foo"])).unwrap();
        let descs: Vec<_> = compiler
            .refuse_reasons(&parsed)
            .iter()
            .map(|r| r.description())
            .collect();
        assert!(
            descs.iter().any(|d| d.contains("link mode")),
            "link invocation must be refused, got: {descs:?}"
        );
    }

    #[test]
    fn refuse_reasons_refuses_multi_source_compile() {
        // `-c a.c b.c` produces two .o files — outside the
        // single-translation-unit cache model. Per-source caching is
        // on the roadmap, message reads as deferral.
        let compiler = CcCompiler::new();
        let parsed = compiler.parse(&s(&["cc", "-c", "a.c", "b.c"])).unwrap();
        let reasons = compiler.refuse_reasons(&parsed);
        let descs: Vec<_> = reasons.iter().map(|r| r.description()).collect();
        assert!(
            descs.iter().any(|d| d.contains("multi-source")),
            "multi-source compile must be refused, got: {descs:?}"
        );
        assert!(
            descs.iter().any(|d| d.contains("— not yet")),
            "multi-source message must read as deferral, got: {descs:?}"
        );
    }

    // ── object_output_path ──────────────────────────────────────

    #[test]
    fn object_output_path_uses_explicit_dash_o() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "src/foo.c", "-o", "build/foo.o"])).unwrap();
        assert_eq!(
            parsed.object_output_path(),
            Some(PathBuf::from("build/foo.o"))
        );
    }

    #[test]
    fn object_output_path_defaults_to_source_stem_dot_o() {
        // Without `-o`, gcc/clang default the object name to the
        // source stem + `.o` in the current directory.
        let parsed = CcArgs::parse(&s(&["cc", "-c", "src/foo.c"])).unwrap();
        assert_eq!(parsed.object_output_path(), Some(PathBuf::from("foo.o")));
    }

    #[test]
    fn object_output_path_defaults_to_obj_for_clang_cl() {
        let cl = CcArgs::parse(&s(&["clang-cl", "-c", "foo.c"])).unwrap();
        assert_eq!(cl.object_output_path().unwrap().to_str(), Some("foo.obj"));
        let gnu = CcArgs::parse(&s(&["gcc", "-c", "foo.c"])).unwrap();
        assert_eq!(gnu.object_output_path().unwrap().to_str(), Some("foo.o"));
    }

    #[test]
    fn depinfo_output_path_uses_mf_or_object_stem() {
        let explicit =
            CcArgs::parse(&s(&["cc", "-c", "foo.c", "-MMD", "-MF", "deps/foo.d"])).unwrap();
        assert_eq!(
            explicit.depinfo_output_path(),
            Some(PathBuf::from("deps/foo.d"))
        );

        let derived = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "obj/foo.o", "-MMD"])).unwrap();
        assert_eq!(
            derived.depinfo_output_path(),
            Some(PathBuf::from("obj/foo.d"))
        );
        assert_eq!(derived.depinfo_anchor(), Some(PathBuf::from("obj")));
    }

    // ── build_preprocess_args ───────────────────────────────────

    /// #1004: the key probe expands `__FILE__` the way the compile will, so a
    /// root left in the expansion really is a literal the object will carry.
    #[test]
    fn key_probe_runs_with_the_compile_prefix_maps() {
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o"])).unwrap();
        let maps = vec![
            CcPrefixMap {
                from: "/w/src".to_string(),
                to: "<CC_SOURCE>".to_string(),
            },
            CcPrefixMap {
                from: "/w".to_string(),
                to: CC_ROOT_SENTINEL.to_string(),
            },
        ];
        let pp = key_preprocess_args(&parsed, &maps);
        let mut expected = build_preprocess_args(&parsed);
        expected.extend(file_prefix_map_args(&maps));
        assert_eq!(pp, expected);
        assert_eq!(
            key_preprocess_args(&parsed, &[]),
            build_preprocess_args(&parsed)
        );

        // The maps go ahead of a `--` separator, as in the real compile, or the
        // driver would read them as extra inputs.
        let separated = CcArgs::parse(&s(&["clang", "-c", "-o", "foo.o", "--", "foo.c"])).unwrap();
        let pp = key_preprocess_args(&separated, &maps);
        let separator = pp.iter().position(|a| a == "--").expect("`--` is kept");
        let first_map = pp
            .iter()
            .position(|a| a.starts_with("-ffile-prefix-map="))
            .expect("maps are passed");
        assert!(first_map < separator, "{pp:?}");
    }

    #[test]
    fn build_preprocess_args_forces_dash_e_dash_p_and_strips_mode() {
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", "foo.o", "-O2", "-Iinc"])).unwrap();
        let pp = build_preprocess_args(&parsed);
        // -E -P prepended.
        assert_eq!(&pp[0], "-E");
        assert_eq!(&pp[1], "-P");
        // -c and -o <arg> stripped (no file redirection of pp output).
        assert!(!pp.iter().any(|a| a == "-c"));
        assert!(!pp.iter().any(|a| a == "-o"));
        assert!(!pp.iter().any(|a| a == "foo.o"));
        // Preprocessing-relevant flags kept.
        assert!(pp.iter().any(|a| a == "-O2"));
        assert!(pp.iter().any(|a| a == "-Iinc"));
        assert!(pp.iter().any(|a| a == "foo.c"));
    }

    #[test]
    fn build_preprocess_args_strips_dep_info_flags() {
        // -MF would redirect dep-info output; -MMD/-MD/-MT are
        // irrelevant to preprocessor *content*. All stripped.
        let parsed = CcArgs::parse(&s(&[
            "cc", "-c", "foo.c", "-MMD", "-MF", "foo.d", "-MT", "foo.o",
        ]))
        .unwrap();
        let pp = build_preprocess_args(&parsed);
        for stripped in &["-MMD", "-MF", "foo.d", "-MT", "foo.o"] {
            assert!(
                !pp.iter().any(|a| a == stripped),
                "{stripped} should be stripped from preprocess args, got {pp:?}"
            );
        }
    }

    #[test]
    fn build_preprocess_args_uses_ep_for_clang_cl() {
        use crate::compiler::flags::Dialect;
        let cl = CcArgs::parse(&s(&["clang-cl", "-c", "a.c", "-DFOO"])).unwrap();
        assert_eq!(cl.family.dialect(), Dialect::Cl);
        let args = build_preprocess_args(&cl);
        assert_eq!(args.first().map(String::as_str), Some("/EP"));
        assert!(!args.iter().any(|a| a == "-E" || a == "-P"));
        assert!(args.iter().any(|a| a == "-DFOO"));
        assert!(args.iter().any(|a| a == "a.c"));
        assert!(!args.iter().any(|a| a == "-c"));
        let gnu = CcArgs::parse(&s(&["gcc", "-c", "a.c"])).unwrap();
        let g = build_preprocess_args(&gnu);
        assert_eq!(&g[..2], &["-E".to_string(), "-P".to_string()]);
    }

    #[test]
    fn preprocess_dep_capture_is_complete_for_both_dialects() {
        let dep = Path::new("memo inputs.d");
        let gnu = CcArgs::parse(&s(&["gcc", "-c", "a.c"])).unwrap();
        let gnu_args = add_preprocess_dep_capture(&gnu, build_preprocess_args(&gnu), dep);
        assert!(gnu_args.windows(2).any(|args| args == ["-MD", "-MF"]));
        assert!(gnu_args.iter().any(|arg| arg == "memo inputs.d"));

        let cl = CcArgs::parse(&s(&["clang-cl", "-c", "a.c"])).unwrap();
        let cl_args = add_preprocess_dep_capture(&cl, build_preprocess_args(&cl), dep);
        assert!(
            cl_args
                .windows(2)
                .any(|args| args == ["-Xclang", "-dependency-file"])
        );
        assert!(
            cl_args
                .windows(2)
                .any(|args| args == ["-Xclang", "-sys-header-deps"]),
            "clang-cl memo dependency capture must include system headers"
        );
    }

    #[test]
    fn preprocess_dependency_parser_handles_make_escapes_and_continuations() {
        let cwd = Path::new("work/project");
        let raw = concat!(
            "__kache_preprocess_memo: src/main.c ab/header.h include/a\\ b.h \\\r\n",
            " include/hash\\#tag.h \\\n",
            " include/cash$$value.h include/single$value.h C:\\sdk\\header.h\n",
        );
        let actual = parse_preprocess_dependencies(raw, cwd).unwrap();
        let mut expected = vec![
            PathBuf::from("C:\\sdk\\header.h"),
            cwd.join("ab/header.h"),
            cwd.join("include/a b.h"),
            cwd.join("include/cash$value.h"),
            cwd.join("include/hash#tag.h"),
            cwd.join("include/single$value.h"),
            cwd.join("src/main.c"),
        ];
        expected.sort();
        assert_eq!(actual, expected);
    }

    #[test]
    fn cc_memo_os_bytes_preserves_distinct_values() {
        assert_ne!(
            cc_memo_os_bytes(OsStr::new("compiler-a")),
            cc_memo_os_bytes(OsStr::new("compiler-b"))
        );
    }

    #[test]
    fn fold_cc_memo_field_changes_and_separates_hashes() {
        let mut first = blake3::Hasher::new();
        fold_cc_memo_field(&mut first, b"arg", b"one");

        let mut second = blake3::Hasher::new();
        fold_cc_memo_field(&mut second, b"arg", b"two");

        assert_ne!(first.finalize(), blake3::Hasher::new().finalize());
        assert_ne!(first.finalize(), second.finalize());
    }

    #[test]
    fn cc_preprocess_memo_key_is_blake3_digest() {
        let compiler = std::env::current_exe()
            .unwrap()
            .to_string_lossy()
            .into_owned();
        let parsed =
            CcArgs::parse(&[compiler, "-c".to_string(), "memo-source.c".to_string()]).unwrap();
        let key = cc_preprocess_memo_key(&parsed, &[], "test compiler version").unwrap();

        assert_eq!(key.len(), 64);
        assert!(
            key.bytes()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
        );
    }

    /// A variable that cannot reach the preprocessor must not give every
    /// invocation its own memo, and one that can must still be keyed.
    /// The mapped-content hash is what decides whether two checkouts share an
    /// expansion, so it has to be a real digest of the mapped bytes: equal
    /// where the maps make the contents equal, different otherwise, and
    /// absent for a file that cannot be read.
    #[test]
    fn cc_mapped_content_hash_digests_the_mapped_bytes() {
        let dir = tempfile::tempdir().unwrap();
        let a = dir.path().join("a.h");
        let b = dir.path().join("b.h");
        std::fs::write(&a, "#define P \"/work/one/out\"\n").unwrap();
        std::fs::write(&b, "#define P \"/work/two/out\"\n").unwrap();

        let maps = vec![
            CcPrefixMap {
                from: "/work/one".to_string(),
                to: "/kache/root".to_string(),
            },
            CcPrefixMap {
                from: "/work/two".to_string(),
                to: "/kache/root".to_string(),
            },
        ];
        let hash_a = cc_mapped_content_hash(&a, &maps).unwrap();
        let hash_b = cc_mapped_content_hash(&b, &maps).unwrap();
        assert_eq!(hash_a.len(), 64, "a blake3 digest, not a placeholder");
        assert_eq!(
            hash_a, hash_b,
            "contents the maps make equal must hash equal"
        );
        // The digest is of the MAPPED bytes, so it is not the raw digest.
        assert_ne!(
            hash_a,
            crate::cache_key::hash_file(&a).unwrap(),
            "mapping must actually change what is hashed"
        );
        // And two files the maps do not reconcile stay apart.
        assert_ne!(
            hash_a,
            cc_mapped_content_hash(&b, &[]).unwrap(),
            "without the maps the two contents differ"
        );
        assert_eq!(
            cc_mapped_content_hash(&dir.path().join("absent.h"), &maps),
            None,
            "an unreadable input cannot be reused"
        );
    }

    /// A recorded name has to come back as the path this checkout uses, and
    /// the memo key must not move when only the checkout root does.
    #[test]
    fn cc_memo_paths_map_out_and_back_across_checkouts() {
        let maps = vec![
            CcPrefixMap {
                from: "/work/clone-a".to_string(),
                to: "/kache/root".to_string(),
            },
            CcPrefixMap {
                from: "/work/clone-a/build".to_string(),
                to: "/kache/build".to_string(),
            },
        ];
        assert_eq!(
            cc_mapped_path(Path::new("/work/clone-a/src/a.h"), &maps),
            "/kache/root/src/a.h"
        );
        // The longer source wins, as it does for the expansion.
        assert_eq!(
            cc_mapped_path(Path::new("/work/clone-a/build/gen.h"), &maps),
            "/kache/build/gen.h"
        );

        let other = vec![
            CcPrefixMap {
                from: "/work/clone-b".to_string(),
                to: "/kache/root".to_string(),
            },
            CcPrefixMap {
                from: "/work/clone-b/build".to_string(),
                to: "/kache/build".to_string(),
            },
        ];
        assert_eq!(
            cc_unmapped_path_candidates("/kache/root/src/a.h", &other),
            vec![PathBuf::from("/work/clone-b/src/a.h")],
            "a name recorded in one checkout resolves into the other"
        );
        assert_eq!(
            cc_unmapped_path_candidates("/kache/build/gen.h", &other),
            vec![PathBuf::from("/work/clone-b/build/gen.h")]
        );

        // Two roots behind one sentinel: both are offered, most specific
        // first, and the caller settles it by content.
        let shared = vec![
            CcPrefixMap {
                from: "/work/one".to_string(),
                to: "/kache/root".to_string(),
            },
            CcPrefixMap {
                from: "/elsewhere/two".to_string(),
                to: "/kache/root".to_string(),
            },
        ];
        assert_eq!(
            cc_unmapped_path_candidates("/kache/root/h.h", &shared),
            vec![
                PathBuf::from("/work/one/h.h"),
                PathBuf::from("/elsewhere/two/h.h")
            ]
        );

        // An unmapped absolute path is its own answer; a relative name that
        // matches no sentinel has none. Absoluteness is what the host says it
        // is, so the path has to be spelled for the host.
        let system_header = if cfg!(windows) {
            r"C:\Program Files\sdk\stdio.h"
        } else {
            "/usr/include/stdio.h"
        };
        assert!(Path::new(system_header).is_absolute());
        assert_eq!(
            cc_unmapped_path_candidates(system_header, &other),
            vec![PathBuf::from(system_header)]
        );
        assert!(cc_unmapped_path_candidates("relative/h.h", &other).is_empty());

        // A half-empty map contributes nothing. Either side empty and the
        // inverse is meaningless: an empty target matches every name and
        // would graft the source onto all of them, an empty source would
        // strip the name down to a relative path. Both must be dropped, so
        // the filter needs both conditions.
        let half_empty = vec![
            CcPrefixMap {
                from: "/work/one".to_string(),
                to: String::new(),
            },
            CcPrefixMap {
                from: String::new(),
                to: "/kache/root".to_string(),
            },
        ];
        // Neither half-empty map may contribute. The sentinel spelling is not
        // absolute on Windows, so assert the shared property: no candidate
        // ever comes from a map with an empty side.
        assert!(
            !cc_unmapped_path_candidates("/kache/root/h.h", &half_empty)
                .iter()
                .any(|candidate| candidate.starts_with("/work/one")),
            "an empty target must not graft its source onto every name"
        );
        assert!(
            cc_unmapped_path_candidates("relative/h.h", &half_empty).is_empty(),
            "an empty source must not strip a name down to a relative path"
        );
    }

    #[test]
    fn cc_preprocess_memo_key_ignores_only_volatile_environment() {
        let _lock = crate::test_support::process_state_test_lock();
        let compiler = std::env::current_exe()
            .unwrap()
            .to_string_lossy()
            .into_owned();
        let parsed =
            CcArgs::parse(&[compiler, "-c".to_string(), "memo-source.c".to_string()]).unwrap();
        let key = || cc_preprocess_memo_key(&parsed, &[], "test compiler version").unwrap();

        let baseline = key();
        for (name, value) in [
            ("_", "/usr/bin/whatever"),
            ("OLDPWD", "/somewhere/else"),
            ("SHLVL", "9"),
            ("CARGO_MAKEFLAGS", "-j --jobserver-fds=7,9"),
            ("NUM_JOBS", "13"),
            ("KACHE_CACHE_DIR", "/tmp/some-other-cache"),
        ] {
            // SAFETY: the process-state lock serialises environment edits.
            unsafe { std::env::set_var(name, value) };
            assert_eq!(
                key(),
                baseline,
                "{name} cannot change an expansion and must not change the memo key"
            );
            unsafe { std::env::remove_var(name) };
        }

        // SAFETY: as above.
        unsafe { std::env::set_var("CPATH", "/opt/extra/include") };
        let with_cpath = key();
        unsafe { std::env::remove_var("CPATH") };
        assert_ne!(
            with_cpath, baseline,
            "an include-path variable changes which headers are found and must be keyed"
        );
    }

    #[test]
    fn cc_prefix_maps_empty_for_clang_cl() {
        let cwd = std::path::Path::new("/work/proj");
        let cl = CcArgs::parse(&s(&["clang-cl", "-c", "/work/proj/a.c"])).unwrap();
        assert!(cc_prefix_maps_cfg(&cl, cwd, None, None, &[]).is_empty());
        let gnu = CcArgs::parse(&s(&["gcc", "-c", "/work/proj/a.c"])).unwrap();
        assert!(!cc_prefix_maps_cfg(&gnu, cwd, None, None, &[]).is_empty());
    }

    /// #299 ("Firefox fails to build sandbox on Windows"): a clang-cl
    /// invocation must reach the real compiler with the EXACT argv kache was
    /// given — zero injected flags. clang-cl rejects `-ffile-prefix-map` as
    /// an unknown argument, so injecting it makes any `-Werror` compile fail.
    /// Firefox's `configure` detects `-ffile-reproducible` with a `-Werror`
    /// probe run through the compiler wrapper; an injected `-ffile-prefix-map`
    /// turned that probe into an error, so `-ffile-reproducible` was reported
    /// unsupported and dropped. Without it, `__FILE__` kept mozbuild's
    /// forward slashes and chromium's `base\location.cc` `static_assert`
    /// failed. clang-cl gets empty prefix maps (#295), so the composed argv
    /// (what `execute` spawns) must be byte-identical to the original `rest`.
    #[test]
    fn clang_cl_invocation_injects_no_flags_issue_299() {
        let cwd = std::path::Path::new("/work/proj");
        let cl = CcArgs::parse(&s(&[
            "clang-cl",
            "-Werror",
            "-ffile-reproducible",
            "-c",
            "/work/proj/a.c",
            "-Foa.obj",
        ]))
        .unwrap();
        let maps = cc_prefix_maps_cfg(&cl, cwd, None, None, &[]);
        assert!(
            maps.is_empty(),
            "clang-cl must get no prefix maps (#295/#299)"
        );
        let composed = compose_cc_args(&cl.rest, file_prefix_map_args(&maps));
        assert_eq!(
            composed, cl.rest,
            "kache must inject nothing into a clang-cl argv, or it poisons \
             `-Werror` compiles/probes (#299); got {composed:?}"
        );
    }

    /// #300: cc-rs emits `--` before the source on clang-cl, and the
    /// clang/clang-cl driver treats everything after `--` as an input
    /// file. Appended `-ffile-prefix-map` flags must therefore be spliced
    /// in *before* the separator, or the driver counts them as extra
    /// source files and fails with "cannot specify '-Fo…' when compiling
    /// multiple source files".
    #[test]
    fn compose_cc_args_splices_appended_flags_before_double_dash() {
        let rest = s(&["-c", "-Fofoo.o", "--", "windows.c"]);
        let appended = s(&["-ffile-prefix-map=/a=<CC_ROOT>"]);
        let out = compose_cc_args(&rest, appended);
        assert_eq!(
            out,
            s(&[
                "-c",
                "-Fofoo.o",
                "-ffile-prefix-map=/a=<CC_ROOT>",
                "--",
                "windows.c"
            ]),
            "appended flags must land before `--`, not after"
        );
    }

    #[test]
    fn compose_cc_args_appends_at_end_without_double_dash() {
        let rest = s(&["-c", "foo.c"]);
        let appended = s(&["-ffile-prefix-map=/a=<CC_ROOT>"]);
        let out = compose_cc_args(&rest, appended);
        assert_eq!(out, s(&["-c", "foo.c", "-ffile-prefix-map=/a=<CC_ROOT>"]));
    }

    #[test]
    fn compose_cc_args_is_identity_when_nothing_appended() {
        let rest = s(&["-c", "-Fofoo.o", "--", "windows.c"]);
        assert_eq!(compose_cc_args(&rest, Vec::new()), rest);
    }

    #[test]
    fn compose_cc_args_splices_before_the_first_double_dash() {
        // Only the first bare `--` is the end-of-options marker; a later
        // `--` is an input. Splicing before the first keeps the injected
        // flags as options regardless of any trailing `--`.
        let rest = s(&["-c", "--", "a.c", "--", "b.c"]);
        let out = compose_cc_args(&rest, s(&["-ffile-prefix-map=/a=<CC_ROOT>"]));
        assert_eq!(
            out,
            s(&[
                "-c",
                "-ffile-prefix-map=/a=<CC_ROOT>",
                "--",
                "a.c",
                "--",
                "b.c"
            ])
        );
    }

    #[test]
    fn compose_cc_args_handles_double_dash_as_first_token() {
        let rest = s(&["--", "a.c"]);
        let out = compose_cc_args(&rest, s(&["-ffile-prefix-map=/a=<CC_ROOT>"]));
        assert_eq!(out, s(&["-ffile-prefix-map=/a=<CC_ROOT>", "--", "a.c"]));
    }

    #[cfg(unix)]
    #[test]
    fn preprocess_hash_bails_on_empty_stdout() {
        // `true` ignores args and prints nothing → empty preprocessor
        // output, which the tripwire refuses. (A legitimately empty TU —
        // all comments / all `#if 0` — also lands here; refusing to cache
        // it is a safe non-cache, the conservative trade-off.)
        let parsed = CcArgs::parse(&s(&["true", "-c", "a.c"])).unwrap();
        let err =
            preprocess_hash(&parsed, &[], &crate::cache_key::FileHasher::new(), false).unwrap_err();
        assert!(err.to_string().contains("no output"), "got: {err}");
    }

    #[test]
    fn execute_returns_error_when_compiler_binary_missing() {
        let compiler = CcCompiler::new();
        let parsed = compiler
            .parse(&["this-binary-does-not-exist-pls-fail-1234567890".to_string()])
            .unwrap();
        let result = compiler.execute(&parsed);
        assert!(
            result.is_err(),
            "execute() must return Err when the compiler binary can't be spawned"
        );
    }

    /// #1004 through the real preprocessor. With the compile's maps on the
    /// probe, `__FILE__` stays portable and memoizable, while a `-D` checkout
    /// path binds the key to its checkout and is never memoized.
    #[cfg(unix)]
    #[test]
    fn real_probe_separates_file_macro_from_literal_roots() {
        // Tests that swap PATH or SDKROOT hold this lock; the macOS `cc` shim
        // exits 72 if it runs while one of them is mid-change.
        let _lock = crate::test_support::process_state_test_lock();
        let probe = |with_literal: bool| {
            let tree = tempfile::TempDir::new().unwrap();
            let root = tree.path().canonicalize().unwrap();
            let src = root.join("src");
            std::fs::create_dir_all(&src).unwrap();
            let source = src.join("x.c");
            std::fs::write(
                &source,
                "const char *f(void) { return __FILE__; }\n\
                 #ifdef DATA\nconst char *d(void) { return DATA; }\n#endif\n",
            )
            .unwrap();
            let mut args = vec![
                "cc".to_string(),
                "-c".to_string(),
                source.to_string_lossy().into_owned(),
                "-o".to_string(),
                root.join("x.o").to_string_lossy().into_owned(),
            ];
            if with_literal {
                args.push(format!("-DDATA=\"{}/data\"", root.display()));
            }
            let parsed = CcArgs::parse(&args).unwrap();
            let maps = cc_prefix_maps_for(&parsed, &root);
            let hasher = crate::cache_key::FileHasher::persistent(&root.join("idx.sqlite"));
            let hashed = preprocess_hash(&parsed, &maps, &hasher, true).unwrap();
            (tree, hashed)
        };

        let (_a, portable_a) = probe(false);
        let (_b, portable_b) = probe(false);
        assert!(!portable_a.path_bound && !portable_b.path_bound);
        assert_eq!(
            portable_a.hash, portable_b.hash,
            "__FILE__ must stay portable"
        );
        assert!(
            portable_a
                .fingerprints
                .as_ref()
                .is_some_and(|inputs| !inputs.is_empty()),
            "dependency capture still works with the maps on the probe"
        );

        let (_c, literal_a) = probe(true);
        let (_d, literal_b) = probe(true);
        assert!(literal_a.path_bound && literal_b.path_bound);
        assert_ne!(literal_a.hash, literal_b.hash);
        assert!(literal_a.fingerprints.is_none(), "never memoized");
    }

    #[test]
    fn cc_prefix_maps_derive_common_source_and_build_root() {
        let root = tempfile::TempDir::new().unwrap();
        let src_dir = root.path().join("dom/canvas");
        let obj_dir = root.path().join("obj-kache-bench/dom/canvas");
        std::fs::create_dir_all(&src_dir).unwrap();
        std::fs::create_dir_all(&obj_dir).unwrap();
        let source = src_dir.join("Unified_cpp_dom_canvas3.cpp");
        std::fs::write(&source, "int x;\n").unwrap();

        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-o",
            "Unified_cpp_dom_canvas3.o",
        ]))
        .unwrap();

        let maps = cc_prefix_maps_for(&parsed, &obj_dir);
        let canonical_root = root
            .path()
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .to_string();
        assert!(
            maps.iter()
                .any(|m| m.from == canonical_root && m.to == CC_ROOT_SENTINEL),
            "expected common root map in {maps:?}"
        );

        let flags = file_prefix_map_args(&maps);
        assert!(
            flags
                .iter()
                .any(|f| f == &format!("-ffile-prefix-map={canonical_root}={CC_ROOT_SENTINEL}")),
            "execute should inject the common-root prefix map, got {flags:?}"
        );
    }

    #[test]
    fn cc_prefix_maps_fall_back_to_distinct_roots_without_common_project_root() {
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", "/opt/kache-src/foo.c", "-o", "foo.o"])).unwrap();
        let maps = cc_prefix_maps_for(&parsed, Path::new("/tmp/kache-build"));

        assert!(
            maps.iter().any(|m| m.to == CC_BUILD_SENTINEL),
            "missing build root map: {maps:?}"
        );
        assert!(
            maps.iter().any(|m| m.to == CC_SOURCE_SENTINEL),
            "missing source root map: {maps:?}"
        );
    }

    #[test]
    fn cc_prefix_maps_keep_shallow_in_tree_relocated_builds_stable() {
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            "/tmp/kache-relocated/src/foo.c",
            "-o",
            "build/foo.o",
        ]))
        .unwrap();
        let maps = cc_prefix_maps_for(&parsed, Path::new("/tmp/kache-relocated"));

        assert!(
            // Compare via `Path` so the separator the platform normalised the
            // build dir to (e.g. `\tmp\kache-relocated` on Windows) still
            // matches the `/`-form fixture.
            maps.iter()
                .any(|m| Path::new(&m.from) == Path::new("/tmp/kache-relocated")
                    && m.to == CC_ROOT_SENTINEL),
            "in-tree shallow relocations should use the same root sentinel, got {maps:?}"
        );
    }

    #[test]
    fn cc_prefix_maps_accept_generated_tempdir_common_root() {
        let root = tempfile::TempDir::new().unwrap();
        let root = root.path();

        assert!(
            stable_cc_common_root(root, &root.join("obj"), &root.join("src")),
            "generated temp project roots should be stable common roots"
        );
        assert!(
            !stable_cc_common_root(&std::env::temp_dir(), &root.join("obj"), &root.join("src")),
            "the temp directory itself is too broad to use as a common root"
        );
    }

    #[test]
    fn cc_prefix_map_targets_are_absolute_distinct_and_carry_no_sentinel() {
        // #485: cc -ffile-prefix-map targets must be absolute, profiler-resolvable
        // paths (no angle-bracket sentinels), and distinct so they never collide
        // in the hashed target set or the byte substitution.
        let all = [
            CC_ROOT_SENTINEL,
            CC_BUILD_SENTINEL,
            CC_SOURCE_SENTINEL,
            CC_BASE_SENTINEL,
            CC_SDKROOT_SENTINEL,
        ];
        for c in all {
            assert!(c.starts_with('/'), "cc target must be absolute: {c}");
            assert!(
                !c.contains('<') && !c.contains('>'),
                "cc target must not be an angle-bracket sentinel: {c}"
            );
        }
        let uniq: std::collections::HashSet<_> = all.iter().collect();
        assert_eq!(uniq.len(), all.len(), "cc targets must be distinct");
        // CC_BUILD is the resolvable cwd spelling on Linux (Bazel trick).
        #[cfg(target_os = "linux")]
        assert_eq!(CC_BUILD_SENTINEL, "/proc/self/cwd");
        #[cfg(not(target_os = "linux"))]
        assert_eq!(CC_BUILD_SENTINEL, "/kache/cc-build");
    }

    #[test]
    fn apply_cc_prefix_maps_does_not_chain_through_targets() {
        // Regression (codex review): a target written by one map must NOT be
        // re-matched by a later map's source. Pathological inputs exercise the
        // class the old sequential replace was vulnerable to.
        let maps = vec![
            CcPrefixMap {
                from: "/work/build".to_string(),
                to: "/proc/self/cwd".to_string(),
            },
            CcPrefixMap {
                from: "/proc/self".to_string(),
                to: "/kache/base-dir".to_string(),
            },
        ];
        let out = apply_cc_prefix_maps_to_bytes(b"X=/work/build/foo.c".to_vec(), &maps);
        assert_eq!(
            String::from_utf8_lossy(&out),
            "X=/proc/self/cwd/foo.c",
            "the /proc/self map must not rewrite the /proc/self/cwd just emitted"
        );
    }

    fn clone_root_maps(clone: &str) -> Vec<CcPrefixMap> {
        vec![CcPrefixMap {
            from: format!("/Users/me/work/{clone}"),
            to: CC_ROOT_SENTINEL.to_string(),
        }]
    }

    /// #1004: a root still spelled out after the probe (a `-D` value, a string
    /// in a generated header) lands in the object verbatim, so two checkouts
    /// must not share the key. The same checkout still does.
    #[test]
    fn expansion_with_a_literal_root_binds_the_key_to_the_checkout() {
        let expansion = |clone: &str| {
            format!(r#"const char *d(void) {{ return "/Users/me/work/{clone}/data"; }}"#)
                .into_bytes()
        };
        let a = hash_cc_expansion(expansion("clone-a"), &clone_root_maps("clone-a"));
        let b = hash_cc_expansion(expansion("clone-b"), &clone_root_maps("clone-b"));
        assert!(a.path_bound && b.path_bound);
        assert_ne!(a.hash, b.hash, "another checkout must not share the key");
        assert_eq!(
            a,
            hash_cc_expansion(expansion("clone-a"), &clone_root_maps("clone-a")),
            "the same checkout keeps its key"
        );
    }

    /// A bound key skips the object scan, so it must separate checkouts even
    /// when the expansion names only a root they share. Here both expansions
    /// spell the same configured base dir and are byte-identical.
    #[test]
    fn bound_expansion_folds_every_root_not_only_the_one_it_names() {
        let maps = |clone: &str| {
            let mut maps = clone_root_maps(clone);
            maps.push(CcPrefixMap {
                from: "/opt/shared".to_string(),
                to: "/kache/base-dir-0".to_string(),
            });
            maps
        };
        let expansion = br#"const char *s = "/opt/shared/data";"#.to_vec();
        let a = hash_cc_expansion(expansion.clone(), &maps("clone-a"));
        let b = hash_cc_expansion(expansion, &maps("clone-b"));
        assert!(a.path_bound && b.path_bound);
        assert_ne!(a.hash, b.hash);
    }

    /// The probe runs with the compile's maps, so `__FILE__` arrives as the
    /// sentinel. Such an expansion stays portable and hashes as it always did.
    #[test]
    fn expansion_without_raw_roots_stays_portable() {
        let expansion = format!(r#"const char *f = "{CC_ROOT_SENTINEL}/src/x.c";"#).into_bytes();
        let a = hash_cc_expansion(expansion.clone(), &clone_root_maps("clone-a"));
        let b = hash_cc_expansion(expansion.clone(), &clone_root_maps("clone-b"));
        assert!(!a.path_bound);
        assert_eq!(a, b);
        assert_eq!(a.hash, blake3::hash(&expansion).to_hex().to_string());
    }

    /// #1004 safety net: a raw root in an object stored under a portable key
    /// would reach every checkout. Only a checkout-bound key may hold one.
    #[test]
    fn store_gate_keeps_raw_roots_out_of_portable_keys() {
        let never = || -> Option<std::io::Result<bool>> { panic!("scanned without a need") };
        assert_eq!(cc_unsafe_to_store(true, false, never), None);
        assert_eq!(cc_unsafe_to_store(false, true, never), None);
        let no_object = cc_unsafe_to_store(false, false, || None).unwrap();
        assert!(no_object.contains("no object"), "{no_object}");
        assert_eq!(cc_unsafe_to_store(false, false, || Some(Ok(false))), None);
        let embeds = cc_unsafe_to_store(false, false, || Some(Ok(true))).unwrap();
        assert!(embeds.contains("embeds a checkout root"), "{embeds}");
        let unreadable =
            cc_unsafe_to_store(false, false, || Some(Err(std::io::Error::other("gone")))).unwrap();
        assert!(
            unreadable.contains("could not be read") && unreadable.contains("gone"),
            "{unreadable}"
        );
    }

    #[test]
    fn object_root_check_reads_the_object() {
        let dir = tempfile::tempdir().unwrap();
        let maps = clone_root_maps("clone-a");
        let dirty = dir.path().join("dirty.o");
        std::fs::write(&dirty, b"\x7fELF\0/Users/me/work/clone-a/data\0").unwrap();
        let clean = dir.path().join("clean.o");
        std::fs::write(&clean, format!("\x7fELF\0{CC_ROOT_SENTINEL}/data\0")).unwrap();
        assert!(cc_object_embeds_mapped_root(&dirty, &maps).unwrap());
        assert!(!cc_object_embeds_mapped_root(&clean, &maps).unwrap());
        assert!(cc_object_embeds_mapped_root(&dir.path().join("missing.o"), &maps).is_err());
    }

    /// #1015: files the assembler reads never reach a depfile, so a TU that
    /// reads one, or defines a macro that could build such a directive, must
    /// not be cached. Look-alikes must not cost C++ TUs.
    #[test]
    fn assembler_file_reads_and_macros_are_refused() {
        let found = |text: &str| cc_assembler_hidden_input(text.as_bytes());
        assert_eq!(found(".incbin \"payload.bin\"\n"), Some(".incbin"));
        assert_eq!(found("\t.INCBIN\t\"payload.bin\""), Some(".incbin"));
        assert_eq!(
            found(r#"__asm__(".incbin \"payload.bin\"\n");"#),
            Some(".incbin")
        );
        assert_eq!(found(".macro blob f\n.incbin \\f\n.endm"), Some(".incbin"));
        assert_eq!(found(".include \"macros.s\""), Some(".include"));
        assert_eq!(found(".include\"macros.s\""), Some(".include"));

        assert_eq!(found("opts.include(\"x\");"), None);
        assert_eq!(found("cfg.include = \"x\";"), None);
        assert_eq!(found(".includes \"x\""), None);
        assert_eq!(found(".incbin_data \"x\""), None);
        assert_eq!(found("int x = 1;"), None);
        assert_eq!(found("end.incbin"), None, "no operand");

        // Macro facilities can assemble a file directive from arguments.
        assert_eq!(
            found(".macro emit op, file\n.\\op \"\\file\"\n.endm\nemit incbin, p.bin"),
            Some(".macro")
        );
        assert_eq!(
            found(".irp op, incbin\n.\\op \"p.bin\"\n.endr"),
            Some(".irp")
        );
        assert_eq!(found("\t.IRPC c, ab\n.endr"), Some(".irpc"));
        assert_eq!(found(r#"__asm__(".macro emit\n.endm\n");"#), Some(".macro"));
        assert_eq!(found(".macros x"), None);
        assert_eq!(found("cfg.macro(x);"), None);
        assert_eq!(found(".endm"), None);

        // `.rept` bodies take `\()`, which splits a directive name in two.
        assert_eq!(
            found(".rept 1\n.inc\\()bin \"p.bin\"\n.endr"),
            Some(".rept")
        );
        assert_eq!(found(".inc\\()bin \"p.bin\""), Some(r"\()"));
        assert_eq!(found(".altmacro\n"), Some(".altmacro"));
        assert_eq!(found(".altmacro_x"), None);

        // The compiler joins and decodes C strings after preprocessing.
        assert_eq!(
            found(r#"__asm__(".inc" "bin \"p.bin\"");"#),
            Some(".incbin")
        );
        assert_eq!(
            found(r#"__asm__(".inc\x62in \"p.bin\"");"#),
            Some(".incbin")
        );
        assert_eq!(found("void f() { asm((text())); }"), Some("asm((...))"));
    }

    /// C23 delimited escapes survive `-E` as written, so only the string
    /// reader can see that `\x{2e}incbin` is `.incbin`.
    #[cfg(unix)]
    #[test]
    fn real_probe_refuses_a_directive_behind_a_delimited_escape() {
        let _lock = crate::test_support::process_state_test_lock();
        let dir = tempfile::TempDir::new().unwrap();
        let source = dir.path().join("delimited.c");
        std::fs::write(
            &source,
            "__asm__(\"\\x{2e}incbin \\\"payload.bin\\\"\\n\");\n",
        )
        .unwrap();
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", source.to_str().unwrap(), "-o", "out.o"])).unwrap();
        let refused = preprocess_hash(&parsed, &[], &crate::cache_key::FileHasher::new(), false)
            .unwrap_err()
            .to_string();
        assert!(refused.contains(".incbin"), "{refused}");
    }

    /// #1015: an `asm` string hides a directive from a plain text search when
    /// it is split across literals or spelled with escapes. Read it the way
    /// the compiler does, without letting quotes in other tokens desync it.
    #[test]
    fn string_literals_are_read_as_the_compiler_reads_them() {
        let text = |src: &str| String::from_utf8(cc_string_literals(src.as_bytes()).text).unwrap();
        assert_eq!(text(r#"x(".inc" "bin \"p\"");"#), "\n.incbin \"p\"");
        assert_eq!(text(r#"".inc\x62in""#), "\n.incbin");
        assert_eq!(text(r#"".inc\142in""#), "\n.incbin");
        assert_eq!(text(r#"".incbin""#), "\n.incbin");
        assert_eq!(text(r#"".inc\U00000062in""#), "\n.incbin");
        assert_eq!(text(r#""a\tb\nc\rd\\e\"""#), "\na\tb\nc d\\e\"");
        assert_eq!(text(r#"u8".in" L"cbin""#), "\n.incbin");
        assert_eq!(text(r#"R"x(.inc\x62in ")x""#), "\n.inc\\x62in \"");
        // A raw delimiter has at most 16 characters and no blank, backslash,
        // parenthesis or quote. Otherwise `R` is a word and a plain string follows.
        assert_eq!(text("R\"abc"), "\nabc");
        assert_eq!(text(r#"R"0123456789abcdef(x)0123456789abcdef""#), "\nx");
        assert_eq!(
            text(r#"R"0123456789abcdefg(x)0123456789abcdefg""#),
            "\n0123456789abcdefg(x)0123456789abcdefg"
        );
        assert_eq!(text(r#"R"a b(x)a b""#), "\na b(x)a b");
        assert_eq!(text(r#"R"a\b(x)a\b""#), "\na (x)a ");
        assert_eq!(text(r#"R"a)(x)a)""#), "\na)(x)a)");
        // A named escape can spell any letter; it is flagged, not decoded.
        let named = cc_string_literals(br#"__asm__(".inc\N{LATIN SMALL LETTER B}in \"p\"");"#);
        assert!(named.named_escape);
        assert_eq!(String::from_utf8(named.text).unwrap(), "\n.incin \"p\"");
        assert!(!cc_string_literals(br#"s = "\\N{x}";"#).named_escape);
        assert!(!cc_string_literals(br#"s = "\N";"#).named_escape);
        assert_eq!(
            cc_assembler_hidden_input(br#"__asm__(".inc\N{LATIN SMALL LETTER B}in \"p\"");"#),
            Some(r"\N{...}")
        );
        assert_eq!(text("\"cut\nx = \"ok\""), "\ncut\nok");
        // Literals separated by code are separate runs.
        assert_eq!(text(r#"f(".inc"); g("bin");"#), "\n.inc\nbin");
        // A quote in a character literal or a number does not open a string.
        assert_eq!(text(r#"char q = '"'; int n = 1'000; s = "ok";"#), "\nok");
        assert_eq!(text(r#"c = '\''; w = L'a'; s = "ok";"#), "\nok");

        // C23 and C++23 delimited escapes.
        assert_eq!(text(r#"".inc\x{62}in""#), "\n.incbin");
        assert_eq!(text(r#"".inc\o{142}in""#), "\n.incbin");
        assert_eq!(text(r#"".inc\u{62}in""#), "\n.incbin");
        assert_eq!(text(r#"".inc\x{62in""#), "\n.incbin", "no closing brace");
        assert_eq!(text(r#""\o""#), "\no");
        assert_eq!(
            cc_assembler_hidden_input(br#"__asm__("\x{2e}incbin \"p\"");"#),
            Some(".incbin")
        );

        // A comment is a blank: literals around it join, and a quote inside
        // it does not open a string. Division is not a comment.
        assert_eq!(text("\"a\" /* \" */ \"b\""), "\nab");
        assert_eq!(text("// \"x\n\"ok\""), "\nok");
        assert_eq!(text("x = 1 / 2; s = \"ok\";"), "\nok");
        assert_eq!(text("/* \"x"), "");
        // `/*/` does not close the comment it opens.
        assert_eq!(text(r#"/*/ "x" */ s = "ok";"#), "\nok");
        // A raw string ends exactly after its delimiter: an adjacent literal
        // still joins it.
        assert_eq!(text(r#"s = R"ab(xyz)ab" "k";"#), "\nxyzk");
        // `R` before a blank is a word, even with `x(` after it.
        assert_eq!(text(r#"R x(y); s = "ok";"#), "\nok");
        // A quote after a digit separates digits only when a digit follows.
        assert_eq!(text(r#"x = 1'"'; s = "ok";"#), "\nok");
        // An escape in a character literal skips exactly two bytes.
        assert_eq!(text(r#"'\'' "ok""#), "\nok");
        // `\u{...}` is a code point, `\x{...}` a byte.
        assert_eq!(cc_string_literals(br#""\u{e9}""#).text, b"\n\xc3\xa9");
        assert_eq!(cc_string_literals(br#""\x{e9}""#).text, b"\n\xe9");
        assert_eq!(
            cc_assembler_hidden_input(b"/* \" */ asm(\".inc\" \"bin \\\"p\\\"\");"),
            Some(".incbin")
        );
    }

    /// Clang accepts a constant expression as the `asm` text, which can build
    /// any directive. Written strings, symbol labels and plain words pass.
    #[test]
    fn asm_with_a_computed_string_is_refused() {
        let computed = |src: &str| cc_string_literals(src.as_bytes()).computed_asm;
        assert!(computed("void f() { asm((s())); }"));
        assert!(computed("__asm__ __volatile__ ( text );"));
        assert!(!computed(r#"asm volatile goto ("jmp %l0" :::: out);"#));
        assert!(!computed(r#"extern int f(void) __asm("_" "f");"#));
        assert!(!computed(r#"__asm__(R"(nop)");"#));
        assert!(!computed(r#"__asm(u8"nop");"#));
        assert!(!computed("int asm = 1; myasm(x);"));
        // A comment inside `asm(...)` is a blank, not the text.
        assert!(computed("asm(/* c */ x);"));
        assert!(!computed(r#"asm(/* c */ "nop");"#));
        assert!(!computed(
            r#"asm(/* why */ "nop"); asm volatile // why
            ("nop");"#
        ));
    }

    /// #1015 through the real preprocessor: assembly and inline `asm` that
    /// `.incbin` a file are refused; assembly that reads nothing is still keyed.
    #[cfg(unix)]
    #[test]
    fn real_probe_refuses_sources_that_incbin_a_file() {
        // Tests that swap PATH or SDKROOT hold this lock; the macOS `cc` shim
        // exits 72 if it runs while one of them is mid-change.
        let _lock = crate::test_support::process_state_test_lock();
        let dir = tempfile::TempDir::new().unwrap();
        let write = |name: &str, text: &str| {
            let path = dir.path().join(name);
            std::fs::write(&path, text).unwrap();
            path.to_string_lossy().into_owned()
        };
        std::fs::write(dir.path().join("payload.bin"), "one").unwrap();
        let probe = |source: String| {
            let parsed = CcArgs::parse(&s(&["cc", "-c", source.as_str(), "-o", "out.o"])).unwrap();
            preprocess_hash(&parsed, &[], &crate::cache_key::FileHasher::new(), false)
        };

        let asm = write(
            "blob.S",
            ".globl payload\npayload:\n.incbin \"payload.bin\"\n",
        );
        let refused = probe(asm).unwrap_err().to_string();
        assert!(refused.contains(".incbin"), "{refused}");

        let inline = write("inline.c", "__asm__(\".incbin \\\"payload.bin\\\"\\n\");\n");
        let refused = probe(inline).unwrap_err().to_string();
        assert!(refused.contains(".incbin"), "{refused}");

        let generated = write(
            "macro.S",
            ".macro emit op, file\n.\\op \"\\file\"\n.endm\nemit incbin, payload.bin\n",
        );
        let refused = probe(generated).unwrap_err().to_string();
        assert!(refused.contains(".macro"), "{refused}");

        let repeated = write("rept.S", ".rept 1\n.inc\\()bin \"payload.bin\"\n.endr\n");
        let refused = probe(repeated).unwrap_err().to_string();
        assert!(refused.contains(".rept"), "{refused}");

        let split = write(
            "split.c",
            "__asm__(\".inc\" \"bin \\\"payload.bin\\\"\\n\");\n",
        );
        let refused = probe(split).unwrap_err().to_string();
        assert!(refused.contains(".incbin"), "{refused}");

        let escaped = write(
            "escaped.c",
            "__asm__(\".inc\\x62in \\\"payload.bin\\\"\\n\");\n",
        );
        let refused = probe(escaped).unwrap_err().to_string();
        assert!(refused.contains(".incbin"), "{refused}");

        let plain = write("plain.S", ".globl answer\nanswer:\n.byte 42\n");
        assert!(probe(plain).is_ok());
    }

    #[test]
    fn object_scan_finds_raw_roots_the_token_mapper_skips() {
        let maps = clone_root_maps("clone-a");
        assert!(bytes_embed_mapped_root(
            b"\0\0/Users/me/work/clone-a/data\0",
            &maps
        ));
        let other = format!("\0{CC_ROOT_SENTINEL}/data\0/Users/me/work/clone-b\0");
        assert!(!bytes_embed_mapped_root(other.as_bytes(), &maps));
        assert!(
            !bytes_embed_mapped_root(b"/Users/me/work/clone-", &maps),
            "a prefix of the root is not the root"
        );

        // A configured base dir maps only at token starts, and NUL is not one.
        // The scan must still see it, or the object would be stored.
        let configured = vec![CcPrefixMap {
            from: "/base".to_string(),
            to: "/kache/base-dir-0".to_string(),
        }];
        let object = b"x\0/base/data\0".to_vec();
        assert_eq!(
            apply_cc_prefix_maps_to_bytes(object.clone(), &configured),
            object
        );
        assert!(bytes_embed_mapped_root(&object, &configured));

        let empty = vec![CcPrefixMap {
            from: String::new(),
            to: CC_ROOT_SENTINEL.to_string(),
        }];
        assert!(!bytes_embed_mapped_root(b"anything", &empty));
    }

    #[test]
    fn cc_prefix_maps_normalize_preprocessor_bytes() {
        let maps = vec![CcPrefixMap {
            from: "/Users/me/work/clone-a".to_string(),
            to: CC_ROOT_SENTINEL.to_string(),
        }];
        let input = br#"assert_fail("/Users/me/work/clone-a/obj/dist/include/fmt/format.h")"#;
        let normalized = apply_cc_prefix_maps_to_bytes(input.to_vec(), &maps);

        assert_eq!(
            std::str::from_utf8(&normalized).unwrap(),
            format!(r#"assert_fail("{CC_ROOT_SENTINEL}/obj/dist/include/fmt/format.h")"#)
        );
    }

    /// Resolved `-###` tokens carry absolute build paths (here a `-D`
    /// define pointing at a branding asset, like Firefox's `FIREFOX_ICO`).
    /// The cc key now normalizes them through the per-build prefix maps, so
    /// the SAME token built at two different paths hashes identically —
    /// the cross-clone / cross-machine portability fix (v12). Previously
    /// the tokens were hashed raw and diverged with the build directory.
    #[test]
    fn resolved_tokens_normalize_identically_across_build_paths() {
        let tok = |clone: &str| {
            format!(r#"FIREFOX_ICO="/Users/me/work/{clone}/browser/branding/firefox.ico""#)
                .into_bytes()
        };
        let maps_for = |clone: &str| {
            vec![CcPrefixMap {
                from: format!("/Users/me/work/{clone}"),
                to: CC_ROOT_SENTINEL.to_string(),
            }]
        };

        let a = apply_cc_prefix_maps_to_bytes(tok("clone-a"), &maps_for("clone-a"));
        let b = apply_cc_prefix_maps_to_bytes(tok("clone-b"), &maps_for("clone-b"));

        assert_eq!(
            a, b,
            "the same resolved token at different build paths must normalize identically"
        );
        assert_eq!(
            std::str::from_utf8(&a).unwrap(),
            format!(r#"FIREFOX_ICO="{CC_ROOT_SENTINEL}/browser/branding/firefox.ico""#)
        );
    }

    /// The objdir cross-checkout fix (v13). An objdir-generated TU compiles
    /// a source that lives IN the build dir, so cwd == source-dir and the
    /// (cwd, source) derivation collapses to a narrow objdir subdir. The
    /// `-I` include dirs span the repo, so folding them in lifts the root
    /// back to the project root — which is what `__FILE__` / preprocessor
    /// paths into `dist/include` and the source tree need to normalize.
    #[test]
    fn cc_prefix_maps_broaden_to_repo_root_via_includes_for_objdir_tus() {
        let root = tempfile::TempDir::new().unwrap();
        let obj_dir = root.path().join("obj-kache-bench/xpcom/components");
        let inc_dir = root.path().join("xpcom/components");
        std::fs::create_dir_all(&obj_dir).unwrap();
        std::fs::create_dir_all(&inc_dir).unwrap();
        // The generated TU lives in the objdir, so cwd ≈ its own dir.
        let source = obj_dir.join("StaticComponents.cpp");
        std::fs::write(&source, "int x;\n").unwrap();

        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            inc_dir.to_str().unwrap(), // in-tree → lifts the root to the repo
            "-I",
            "/usr/include", // out-of-tree → common ancestor is `/` → dropped
            "-o",
            "StaticComponents.o",
        ]))
        .unwrap();

        let maps = cc_prefix_maps_for(&parsed, &obj_dir);
        let canonical_root = root
            .path()
            .canonicalize()
            .unwrap()
            .to_string_lossy()
            .to_string();
        assert!(
            maps.iter()
                .any(|m| m.from == canonical_root && m.to == CC_ROOT_SENTINEL),
            "include-folding must derive the repo root for objdir TUs, got {maps:?}"
        );
        // A system `-I` must never widen the root to the filesystem root.
        assert!(
            !maps.iter().any(|m| m.from == "/"),
            "out-of-tree includes must not add a `/` root, got {maps:?}"
        );
    }

    /// `KACHE_BASE_DIR` (the ccache `CCACHE_BASEDIR` analog) is an explicit
    /// override: whatever path the user names is stripped to `<CC_BASE>`,
    /// independent of the auto-derived roots.
    #[test]
    fn cc_prefix_maps_cfg_maps_explicit_base_dir_to_base_sentinel() {
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", "/work/checkout/src/foo.c", "-o", "foo.o"])).unwrap();
        let cwd = Path::new("/work/checkout");
        // `/work` is the common parent of many checkouts (the canonical
        // CCACHE_BASEDIR shape), above what the auto-derivation would pick.
        let maps = cc_prefix_maps_cfg(&parsed, cwd, Some(Path::new("/work")), None, &[]);
        assert!(
            maps.iter()
                .any(|m| m.from == "/work" && m.to == CC_BASE_SENTINEL),
            "explicit KACHE_BASE_DIR must map to the base sentinel, got {maps:?}"
        );
    }

    #[test]
    fn cc_configured_base_dirs_are_distinct_order_independent_and_longest_first() {
        let dir = tempfile::TempDir::new().unwrap();
        let parent = dir.path().join("container");
        let child = parent.join("work");
        std::fs::create_dir_all(&child).unwrap();
        let source = child.join("src/foo.c");
        std::fs::create_dir_all(source.parent().unwrap()).unwrap();
        std::fs::write(&source, "int x;\n").unwrap();
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", source.to_str().unwrap(), "-o", "foo.o"])).unwrap();
        let parent_cfg = parent.to_string_lossy().into_owned();
        let child_cfg = child.to_string_lossy().into_owned();

        let forward = cc_prefix_maps_cfg(
            &parsed,
            &child,
            None,
            None,
            &[parent_cfg.clone(), child_cfg.clone()],
        );
        let reverse = cc_prefix_maps_cfg(&parsed, &child, None, None, &[child_cfg, parent_cfg]);
        let input = format!("{}/include/generated.h", child.display()).into_bytes();
        let normalized_forward = apply_cc_prefix_maps_to_bytes(input.clone(), &forward);
        let normalized_reverse = apply_cc_prefix_maps_to_bytes(input, &reverse);

        assert_eq!(normalized_forward, normalized_reverse);
        assert_eq!(
            String::from_utf8(normalized_forward).unwrap(),
            format!(
                "{}/include/generated.h",
                crate::path_normalizer::configured_base_dir_target(1)
            )
        );
        assert!(
            forward
                .iter()
                .any(|map| map.to == crate::path_normalizer::configured_base_dir_target(0))
        );
        assert!(
            forward
                .iter()
                .any(|map| map.to == crate::path_normalizer::configured_base_dir_target(1))
        );
    }

    #[test]
    fn cc_configured_base_dir_matches_compiler_raw_prefix_at_path_tokens() {
        let maps = vec![CcPrefixMap {
            from: "/work".to_string(),
            to: crate::path_normalizer::configured_base_dir_target(0),
        }];
        let input = b"/work/src /workspace/src /opt/work/src -I/work/include".to_vec();
        assert_eq!(
            String::from_utf8(apply_cc_prefix_maps_to_bytes(input, &maps)).unwrap(),
            "/kache/base-dir-0/src /kache/base-dir-0space/src /opt/work/src -I/kache/base-dir-0/include"
        );
    }

    #[test]
    fn cc_configured_windows_root_has_portable_variants() {
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", "C:/Build/Root/src/foo.c", "-o", "foo.o"])).unwrap();
        let maps = cc_prefix_maps_cfg(
            &parsed,
            Path::new("C:/Build/Root"),
            None,
            None,
            &["C:/Build/Root".to_string()],
        );
        let target = crate::path_normalizer::configured_base_dir_target(0);
        for variant in [
            "C:/Build/Root",
            r"C:\Build\Root",
            "c:/Build/Root",
            r"c:\Build\Root",
        ] {
            assert!(
                maps.iter()
                    .any(|map| map.from == variant && map.to == target),
                "missing configured Windows variant {variant:?}: {maps:?}"
            );
        }
    }

    #[test]
    fn cc_configured_posix_root_does_not_match_windows_drive_path() {
        let maps = crate::path_normalizer::configured_base_dir_prefix_maps(&["/snap".to_string()])
            .into_iter()
            .map(|(from, to)| CcPrefixMap { from, to })
            .collect::<Vec<_>>();
        assert!(maps.iter().all(|map| map.from != r"\snap"));
        assert_eq!(
            apply_cc_prefix_maps_to_bytes(b"C:/snap/pkg /snap/pkg".to_vec(), &maps),
            b"C:/snap/pkg /kache/base-dir-0/pkg"
        );
    }

    /// kunobi-ninja/kache#304, #394: an out-of-tree (sibling) build must produce
    /// the SAME prefix-map sentinel set regardless of where the tree lives, so
    /// the cc cache key converges across machines / a relocate. Previously a
    /// deep common root got `<CC_ROOT>` while a shallow / temp one did not,
    /// flipping the set (which is hashed into the key) and forcing a miss.
    #[test]
    fn cc_prefix_maps_sentinel_set_is_location_independent_for_out_of_tree() {
        let sentinels = |cwd: &str, src: &str| -> Vec<String> {
            let parsed = CcArgs::parse(&s(&["cc", "-c", src, "-o", "foo.o"])).unwrap();
            let mut set: Vec<String> = cc_prefix_maps_cfg(&parsed, Path::new(cwd), None, None, &[])
                .iter()
                .map(|m| m.to.clone())
                .collect();
            set.sort_unstable();
            set.dedup();
            set
        };
        // Same sibling out-of-tree topology (build dir is a sibling of the
        // source dir), at a deep root vs a shallow / temp-like root.
        let deep = sentinels("/home/user/proj/build", "/home/user/proj/src/foo.c");
        let shallow = sentinels("/tmp/build", "/tmp/src/foo.c");
        assert_eq!(
            deep, shallow,
            "out-of-tree prefix-map sentinel set must not depend on absolute location"
        );
        assert!(
            deep.iter().any(|value| value == CC_ROOT_SENTINEL)
                && deep.iter().any(|value| value == CC_BUILD_SENTINEL),
            "out-of-tree build should fold the build and shared-root sentinels, got {deep:?}"
        );
        // When a usable shared root exists, `<CC_ROOT>` (which preserves the
        // relative path) replaces the flattening `<CC_SOURCE>` — see
        // `cc_prefix_maps_preserve_source_parent_dir_for_out_of_tree`.
        assert!(
            !deep.iter().any(|value| value == CC_SOURCE_SENTINEL),
            "a usable shared root makes <CC_SOURCE> redundant, got {deep:?}"
        );

        // A bare filesystem root as the only common ancestor must NOT be folded
        // — mapping `/` would collapse unrelated absolute paths. With no usable
        // shared root, `<CC_SOURCE>` is the fallback that normalizes the source.
        let rooted = sentinels("/build", "/src/foo.c");
        assert!(
            !rooted.iter().any(|value| value == CC_ROOT_SENTINEL)
                && rooted.iter().any(|value| value == CC_SOURCE_SENTINEL),
            "a bare root must fall back to <CC_SOURCE>, not <CC_ROOT>, got {rooted:?}"
        );
    }

    /// kunobi-ninja/kache: an out-of-tree build's source `__FILE__` must keep
    /// its directory structure under the shared-root sentinel, NOT collapse to a
    /// flat `<CC_SOURCE>/<file>`. Chromium's `base/location.cc` has a
    /// compile-time `static_assert(StrEndsWith(__FILE__, …, "base/location.cc"))`;
    /// flattening the parent dir breaks it and the cold Firefox bench fails to
    /// compile. Regression guard for that fix.
    #[test]
    fn cc_prefix_maps_preserve_source_parent_dir_for_out_of_tree() {
        let src = "/home/user/proj/src/security/sandbox/chromium/base/location.cc";
        let parsed = CcArgs::parse(&s(&["cc", "-c", src, "-o", "location.o"])).unwrap();
        // Sibling out-of-tree build dir (objdir is not under the source dir).
        let maps = cc_prefix_maps_for(&parsed, Path::new("/home/user/proj/obj/security"));

        // `__FILE__` as the compiler emits it is the source path put through the
        // same prefix maps the cache key uses.
        let got = String::from_utf8(apply_cc_prefix_maps_to_bytes(
            src.as_bytes().to_vec(),
            &maps,
        ))
        .unwrap();

        assert!(
            got.ends_with("base/location.cc"),
            "source __FILE__ must keep the base/ parent dir, got {got:?} from {maps:?}"
        );
        assert!(
            !got.contains(CC_SOURCE_SENTINEL),
            "source path must not collapse to a flat <CC_SOURCE>, got {got:?}"
        );
    }

    /// Issue #78: an explicit `-isysroot <sdk>` is mapped to `<SDKROOT>` so
    /// the SDK path that rides in the resolved `cc -###` tokens stops
    /// keying the artifact per-install.
    #[test]
    fn cc_prefix_maps_cfg_maps_explicit_isysroot_to_sdkroot_sentinel() {
        let sdk = "/Applications/Xcode_15.2.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX14.2.sdk";
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-isysroot",
            sdk,
            "-c",
            "/work/checkout/src/foo.c",
            "-o",
            "foo.o",
        ]))
        .unwrap();
        let maps = cc_prefix_maps_cfg(&parsed, Path::new("/work/checkout"), None, None, &[]);
        assert!(
            maps.iter()
                .any(|m| m.from == sdk && m.to == CC_SDKROOT_SENTINEL),
            "explicit -isysroot must map to <SDKROOT>, got {maps:?}"
        );
    }

    /// Issue #78: when there's no `-isysroot`, the `SDKROOT` env value
    /// (threaded in by [`cc_prefix_maps`]) provides the SDK path to strip.
    #[test]
    fn cc_prefix_maps_cfg_maps_sdkroot_env_to_sentinel() {
        let sdk = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk";
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", "/work/checkout/src/foo.c", "-o", "foo.o"])).unwrap();
        let maps = cc_prefix_maps_cfg(
            &parsed,
            Path::new("/work/checkout"),
            None,
            Some(Path::new(sdk)),
            &[],
        );
        assert!(
            maps.iter()
                .any(|m| m.from == sdk && m.to == CC_SDKROOT_SENTINEL),
            "SDKROOT env must map to <SDKROOT>, got {maps:?}"
        );
    }

    /// An explicit `-isysroot` wins over the `SDKROOT` env value (mirrors
    /// clang's own precedence), so only the on-command-line SDK is mapped.
    #[test]
    fn cc_prefix_maps_cfg_isysroot_wins_over_sdkroot_env() {
        let arg_sdk = "/Applications/Xcode_15.2.app/Contents/Developer/.../MacOSX14.2.sdk";
        let env_sdk = "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk";
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-isysroot",
            arg_sdk,
            "-c",
            "/work/checkout/src/foo.c",
            "-o",
            "foo.o",
        ]))
        .unwrap();
        let maps = cc_prefix_maps_cfg(
            &parsed,
            Path::new("/work/checkout"),
            None,
            Some(Path::new(env_sdk)),
            &[],
        );
        assert!(
            maps.iter().any(|m| m.from == arg_sdk),
            "explicit -isysroot must be the SDK that is mapped, got {maps:?}"
        );
        assert!(
            !maps.iter().any(|m| m.from == env_sdk),
            "SDKROOT env must be ignored when -isysroot is explicit, got {maps:?}"
        );
    }

    /// No `-isysroot` and no `SDKROOT` → no `<SDKROOT>` map (the bare
    /// `cc -c` / non-Apple case is left untouched; issue #78 follow-up).
    #[test]
    fn cc_prefix_maps_cfg_no_sdk_adds_no_sdkroot_map() {
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", "/work/checkout/src/foo.c", "-o", "foo.o"])).unwrap();
        let maps = cc_prefix_maps_cfg(&parsed, Path::new("/work/checkout"), None, None, &[]);
        assert!(
            !maps.iter().any(|m| m.to == CC_SDKROOT_SENTINEL),
            "no SDK source means no <SDKROOT> map, got {maps:?}"
        );
    }

    /// The headline portability property: the same TU compiled against the
    /// same SDK *contents* at two different install paths normalizes to the
    /// same key bytes. Drives a resolved-`-###`-shaped token (carrying the
    /// SDK path) through the maps each build would compute and asserts the
    /// results are byte-identical — i.e. the two builds would share a hit.
    #[test]
    fn sdkroot_map_normalizes_resolved_tokens_identically_across_installs() {
        let sdk_a = "/Applications/Xcode_15.2.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX14.2.sdk";
        let sdk_b = "/Library/Developer/CommandLineTools/SDKs/MacOSX14.2.sdk";
        let cwd = Path::new("/work/checkout");

        let parsed_a = CcArgs::parse(&s(&[
            "cc",
            "-isysroot",
            sdk_a,
            "-c",
            "/work/checkout/src/foo.c",
            "-o",
            "foo.o",
        ]))
        .unwrap();
        let parsed_b = CcArgs::parse(&s(&[
            "cc",
            "-isysroot",
            sdk_b,
            "-c",
            "/work/checkout/src/foo.c",
            "-o",
            "foo.o",
        ]))
        .unwrap();

        let maps_a = cc_prefix_maps_cfg(&parsed_a, cwd, None, None, &[]);
        let maps_b = cc_prefix_maps_cfg(&parsed_b, cwd, None, None, &[]);

        // A resolved `-cc1` token as `cc -###` would emit it, per install.
        let token_a = format!("-internal-isystem{sdk_a}/usr/include").into_bytes();
        let token_b = format!("-internal-isystem{sdk_b}/usr/include").into_bytes();

        let norm_a = apply_cc_prefix_maps_to_bytes(token_a, &maps_a);
        let norm_b = apply_cc_prefix_maps_to_bytes(token_b, &maps_b);

        assert_eq!(
            norm_a, norm_b,
            "same SDK contents at different install paths must normalize to the same key bytes"
        );
        assert_eq!(
            String::from_utf8_lossy(&norm_a),
            format!("-internal-isystem{CC_SDKROOT_SENTINEL}/usr/include")
        );
    }

    /// The kill-switch: any explicit off-value disables cc path
    /// normalization; everything else (including unset and empty) leaves it
    /// on — normalization is the default, opt-out only.
    #[test]
    fn parse_cc_normalize_toggle_defaults_on_opts_out_explicitly() {
        for on in [
            None,
            Some("1"),
            Some("yes"),
            Some("on"),
            Some(""),
            Some("garbage"),
        ] {
            assert!(parse_cc_normalize_toggle(on), "{on:?} should keep it on");
        }
        for off in [
            Some("0"),
            Some("false"),
            Some("off"),
            Some("no"),
            Some("  OFF "),
        ] {
            assert!(!parse_cc_normalize_toggle(off), "{off:?} should disable it");
        }
    }

    #[cfg(unix)]
    #[test]
    fn execute_propagates_non_zero_exit_when_compiler_runs_and_fails() {
        let compiler = CcCompiler::new();
        let parsed = compiler.parse(&["false".to_string()]).unwrap();
        let result = compiler
            .execute(&parsed)
            .expect("a failed-but-spawned compiler is Ok(non-zero), not Err");
        assert_ne!(
            result.exit_code, 0,
            "non-zero exit must reach the caller via CompileResult.exit_code"
        );
    }

    /// `execute` with a brief retry on ETXTBSY (kunobi-ninja/kache#673):
    /// tests that write a stand-in compiler script and spawn it immediately
    /// race any concurrent test's fork, which can still hold the script's
    /// write fd open at exec time. The window is microseconds, so a handful
    /// of retries clears it; an error that persists past them is real.
    #[cfg(unix)]
    fn execute_retrying_etxtbsy(compiler: &CcCompiler, parsed: &CcArgs) -> Result<CompileResult> {
        let mut last = compiler.execute(parsed);
        for _ in 0..10 {
            let is_etxtbsy = last.as_ref().err().is_some_and(|e| {
                e.root_cause()
                    .downcast_ref::<std::io::Error>()
                    // 26 == ETXTBSY on both Linux and macOS.
                    .is_some_and(|io| io.raw_os_error() == Some(26))
            });
            if !is_etxtbsy {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
            last = compiler.execute(parsed);
        }
        last
    }

    #[cfg(unix)]
    /// `-E` to a named file is a cacheable single-output compile; `-E` to
    /// stdout still is not, and says so in its own words so the two can be
    /// counted apart in a report.
    #[test]
    fn preprocess_to_a_file_is_cacheable_and_to_stdout_is_not() {
        let to_file = CcArgs::parse(&s(&["cc", "-E", "unit.c", "-o", "unit.i"])).unwrap();
        assert_eq!(to_file.mode, CompileMode::Preprocess);
        assert!(
            to_file.refuse_reasons(&[]).is_empty(),
            "a named output is the artifact: {:?}",
            to_file.refuse_reasons(&[])
        );
        assert_eq!(
            to_file.object_output_path(),
            Some(PathBuf::from("unit.i")),
            "the named output is what restore has to write"
        );

        let to_stdout = CcArgs::parse(&s(&["cc", "-E", "unit.c"])).unwrap();
        let reasons = to_stdout.refuse_reasons(&[]);
        assert!(
            reasons.iter().any(|reason| matches!(
                reason,
                RefuseReason::Unsupported(message) if message.contains("to stdout")
            )),
            "stdout has no file to store: {reasons:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn successful_non_compile_execute_never_discovers_cache_artifacts() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("linker.sh");
        let source = dir.path().join("foo.c");
        let output = dir.path().join("foo.o");
        std::fs::write(&source, "int main(void) { return 0; }\n").unwrap();
        std::fs::write(&script, "#!/bin/sh\nprintf object > \"$3\"\n").unwrap();
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();

        let compiler = CcCompiler::new();
        let parsed = compiler
            .parse(&[
                script.to_string_lossy().into_owned(),
                source.to_string_lossy().into_owned(),
                "-o".to_string(),
                output.to_string_lossy().into_owned(),
            ])
            .unwrap();
        assert_eq!(parsed.mode, CompileMode::Link);

        let result =
            execute_retrying_etxtbsy(&compiler, &parsed).expect("stand-in linker should run");
        assert_eq!(result.exit_code, 0);
        assert!(output.exists(), "stand-in linker should create its output");
        assert!(
            result.artifacts.is_empty(),
            "a successful link must remain passthrough-only even when its output resembles an object"
        );
    }

    #[cfg(unix)]
    #[test]
    fn failed_compile_execute_never_discovers_leftover_artifacts() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("compiler.sh");
        let source = dir.path().join("foo.c");
        let object = dir.path().join("foo.o");
        std::fs::write(&source, "int answer(void) { return 42; }\n").unwrap();
        std::fs::write(&script, "#!/bin/sh\nprintf object > \"$4\"\nexit 1\n").unwrap();
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();

        let compiler = CcCompiler::new();
        let parsed = compiler
            .parse(&[
                script.to_string_lossy().into_owned(),
                source.to_string_lossy().into_owned(),
                "-c".to_string(),
                "-o".to_string(),
                object.to_string_lossy().into_owned(),
            ])
            .unwrap();
        assert_eq!(parsed.mode, CompileMode::Compile);

        let result = execute_retrying_etxtbsy(&compiler, &parsed)
            .expect("failed-but-spawned compiler should return a result");
        assert_ne!(result.exit_code, 0);
        assert!(
            object.exists(),
            "stand-in compiler should leave an object behind before failing"
        );
        assert!(
            result.artifacts.is_empty(),
            "failed compiles must never publish artifacts even when the compiler left outputs"
        );
    }

    #[test]
    fn classify_output_delegates_to_shared_classifier() {
        let compiler = CcCompiler::new();
        let parsed = compiler.parse(&s(&["cc"])).unwrap();
        assert_eq!(
            compiler.classify_output(&parsed, "foo.o"),
            ArtifactKind::Object
        );
        assert_eq!(
            compiler.classify_output(&parsed, "libfoo.dylib"),
            ArtifactKind::DynamicLibrary
        );
        assert_eq!(
            compiler.classify_output(&parsed, "foo.d"),
            ArtifactKind::DepInfo
        );
        assert_eq!(
            compiler.classify_output(&parsed, "foo.o.pp"),
            ArtifactKind::DepInfo
        );
    }

    #[test]
    fn output_discovery_keeps_arbitrary_mf_paths_semantically_depinfo() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("foo.c");
        let object = dir.path().join("foo.o");
        std::fs::write(&source, "int answer(void) { return 42; }\n").unwrap();
        std::fs::write(&object, b"object").unwrap();

        for dep_name in ["foo.d.tmp", "extensionless", "foo.unrelated"] {
            let depinfo = dir.path().join(dep_name);
            std::fs::write(&depinfo, b"foo.o: foo.c\n").unwrap();
            let parsed = CcCompiler::new()
                .parse(&[
                    "cc".to_string(),
                    "-c".to_string(),
                    source.to_string_lossy().into_owned(),
                    "-o".to_string(),
                    object.to_string_lossy().into_owned(),
                    "-MMD".to_string(),
                    "-MF".to_string(),
                    depinfo.to_string_lossy().into_owned(),
                ])
                .unwrap();

            let artifacts = discover_cc_output_artifacts(&parsed);
            assert_eq!(artifacts.outputs().len(), 2);
            assert_eq!(artifacts.outputs()[0].kind, ArtifactKind::Object);
            assert_eq!(artifacts.outputs()[1].path, depinfo);
            assert_eq!(artifacts.outputs()[1].kind, ArtifactKind::DepInfo);
            assert_eq!(artifacts.outputs()[1].store_name, CC_DEPINFO_STORE_NAME);
            assert_eq!(
                classify_by_filename(&artifacts.outputs()[1].store_name),
                ArtifactKind::DepInfo,
                "the semantic store name must survive metadata-only classification"
            );
        }
    }

    // ── existing output path semantics (#645) ─────────────────────

    #[test]
    fn compiler_output_paths_covers_every_multi_source_default_output() {
        let parsed =
            CcArgs::parse(&s(&["cc", "-c", "src/alpha.c", "other/beta.c", "-MMD"])).unwrap();

        assert_eq!(
            parsed.compiler_output_paths(),
            vec![
                PathBuf::from("alpha.o"),
                PathBuf::from("beta.o"),
                PathBuf::from("alpha.d"),
                PathBuf::from("beta.d"),
            ]
        );
    }

    #[test]
    fn compiler_output_paths_ignores_object_shape_outside_compile_mode() {
        let parsed = CcArgs::parse(&s(&["cc", "-E", "foo.c", "-o", "foo.o"])).unwrap();

        assert!(parsed.compiler_output_paths().is_empty());
        assert!(!parsed.requires_compiler_output_semantics());
    }

    #[test]
    fn cc_output_safety_allows_existing_writable_private_regular_file() {
        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("plain.o");
        std::fs::write(&output, b"ordinary compiler output").unwrap();

        let output_str = output.to_string_lossy().into_owned();
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", &output_str])).unwrap();

        assert!(!parsed.requires_compiler_output_semantics());
        assert!(!parsed.refuse_reasons(&[]).iter().any(|reason| {
            reason
                .description()
                .contains("requires compiler write semantics")
        }));
        assert_eq!(
            discover_cc_output_artifacts(&parsed).outputs().len(),
            1,
            "post-compile discovery may ingest an independent regular file"
        );
    }

    #[test]
    fn regular_output_writability_distinguishes_readonly_metadata() {
        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("permissions.o");
        std::fs::write(&output, b"ordinary compiler output").unwrap();

        let writable = std::fs::metadata(&output).unwrap();
        let original_permissions = writable.permissions();
        assert!(regular_output_is_owner_writable(&writable));

        let mut readonly_permissions = original_permissions.clone();
        readonly_permissions.set_readonly(true);
        std::fs::set_permissions(&output, readonly_permissions).unwrap();
        let readonly = std::fs::metadata(&output).unwrap();
        assert!(!regular_output_is_owner_writable(&readonly));

        // Windows refuses to remove a read-only file, so restore the exact
        // original permissions before the temporary directory is dropped.
        std::fs::set_permissions(&output, original_permissions).unwrap();
    }

    /// A user-owned read-only output must reach the selected compiler intact.
    #[cfg(unix)]
    #[test]
    fn cc_output_safety_refuses_readonly_regular_file() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};

        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("readonly.o");
        std::fs::write(&output, b"user-owned").unwrap();
        std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o444)).unwrap();
        let before = std::fs::metadata(&output).unwrap();

        let output_str = output.to_string_lossy().into_owned();
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", &output_str])).unwrap();

        assert!(parsed.requires_compiler_output_semantics());
        assert!(parsed.refuse_reasons(&[]).iter().any(|reason| {
            reason
                .description()
                .contains("requires compiler write semantics")
        }));
        assert_eq!(discover_cc_output_artifacts(&parsed).outputs().len(), 1);
        let after = std::fs::metadata(&output).unwrap();
        assert_eq!((after.dev(), after.ino()), (before.dev(), before.ino()));
        assert_eq!(std::fs::read(&output).unwrap(), b"user-owned");
    }

    #[cfg(unix)]
    #[test]
    fn cc_output_safety_refuses_regular_file_without_owner_write() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("group-writable.o");
        std::fs::write(&output, b"user-owned").unwrap();
        std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o460)).unwrap();

        let output_str = output.to_string_lossy().into_owned();
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", &output_str])).unwrap();

        assert!(parsed.requires_compiler_output_semantics());
        assert_eq!(discover_cc_output_artifacts(&parsed).outputs().len(), 1);
        assert_eq!(std::fs::read(&output).unwrap(), b"user-owned");
    }

    #[cfg(unix)]
    #[test]
    fn cc_output_safety_checks_explicit_depinfo_path() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let object = dir.path().join("foo.o");
        let depinfo = dir.path().join("custom.tmp");
        std::fs::write(&depinfo, b"user-owned depinfo").unwrap();
        std::fs::set_permissions(&depinfo, std::fs::Permissions::from_mode(0o444)).unwrap();

        let object_str = object.to_string_lossy().into_owned();
        let depinfo_str = depinfo.to_string_lossy().into_owned();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            "foo.c",
            "-MMD",
            "-MF",
            &depinfo_str,
            "-o",
            &object_str,
        ]))
        .unwrap();

        assert!(parsed.requires_compiler_output_semantics());
        assert!(parsed.refuse_reasons(&[]).iter().any(|reason| {
            reason
                .description()
                .contains("requires compiler write semantics")
        }));
        assert_eq!(std::fs::read(&depinfo).unwrap(), b"user-owned depinfo");
    }

    /// A compiler may write through or replace a symlink. Cache restore must
    /// not choose those semantics on the selected compiler's behalf.
    #[cfg(unix)]
    #[test]
    fn cc_output_safety_refuses_symlinked_object() {
        use std::fs;
        use std::os::unix::fs::symlink;

        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real.o");
        let output = dir.path().join("link.o");
        fs::write(&target, b"original").unwrap();
        symlink(&target, &output).unwrap();

        let output_str = output.to_string_lossy().into_owned();
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", &output_str])).unwrap();

        assert!(
            parsed.requires_compiler_output_semantics(),
            "an existing output symlink must route through the real compiler"
        );
        assert!(
            fs::symlink_metadata(&output)
                .unwrap()
                .file_type()
                .is_symlink(),
            "classification must leave the -o symlink in place"
        );
        assert_eq!(fs::read(&target).unwrap(), b"original");
    }

    /// Both writable and read-only hardlinks require compiler-native behavior.
    #[cfg(unix)]
    #[test]
    fn cc_output_safety_refuses_all_hardlinks() {
        use std::fs;
        use std::os::unix::fs::{MetadataExt, PermissionsExt};

        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real.o");
        let output = dir.path().join("link.o");
        fs::write(&target, b"original").unwrap();
        fs::hard_link(&target, &output).unwrap();

        let output_str = output.to_string_lossy().into_owned();
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", &output_str])).unwrap();

        assert!(parsed.requires_compiler_output_semantics());
        assert!(parsed.refuse_reasons(&[]).iter().any(|reason| {
            reason
                .description()
                .contains("requires compiler write semantics")
        }));

        let target_meta = fs::metadata(&target).unwrap();
        let output_meta = fs::metadata(&output).unwrap();
        assert_eq!(target_meta.dev(), output_meta.dev());
        assert_eq!(target_meta.ino(), output_meta.ino());
        assert_eq!(target_meta.nlink(), 2);
        assert!(
            discover_cc_output_artifacts(&parsed).is_empty(),
            "writable hardlinked outputs must not enter the blob store"
        );

        fs::set_permissions(&output, fs::Permissions::from_mode(0o444)).unwrap();
        assert!(
            parsed.requires_compiler_output_semantics(),
            "read-only hardlinks are user-owned unless proven otherwise"
        );
        assert!(discover_cc_output_artifacts(&parsed).is_empty());
    }

    #[cfg(windows)]
    #[test]
    fn cc_output_safety_refuses_windows_hardlinks() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("real.obj");
        let output = dir.path().join("link.obj");
        std::fs::write(&target, b"original").unwrap();
        std::fs::hard_link(&target, &output).unwrap();

        let output_str = output.to_string_lossy().into_owned();
        let output_arg = format!("/Fo{output_str}");
        let parsed = CcArgs::parse(&s(&["clang-cl.exe", "/c", "foo.c", &output_arg])).unwrap();
        assert_eq!(
            parsed.object_output_path().as_deref(),
            Some(output.as_path())
        );
        assert!(parsed.requires_compiler_output_semantics());
        assert!(discover_cc_output_artifacts(&parsed).is_empty());

        let mut perms = std::fs::metadata(&output).unwrap().permissions();
        perms.set_readonly(true);
        std::fs::set_permissions(&output, perms).unwrap();
        assert!(parsed.requires_compiler_output_semantics());

        // TempDir cleanup cannot remove a read-only Windows hardlink.
        let mut perms = std::fs::metadata(&output).unwrap().permissions();
        #[allow(clippy::permissions_set_readonly_false)]
        perms.set_readonly(false);
        std::fs::set_permissions(&output, perms).unwrap();
    }

    /// A user-owned non-regular output must never be unlinked by pre-clean or
    /// admitted to blob ingestion. A Unix socket gives the test a disposable
    /// special file without risking a real device node.
    #[cfg(unix)]
    #[test]
    fn cc_output_safety_preserves_and_refuses_non_regular_file() {
        use std::fs;
        use std::os::unix::fs::FileTypeExt;
        use std::os::unix::net::UnixListener;

        let dir = tempfile::tempdir().unwrap();
        let output = dir.path().join("compiler-output.sock");
        let _listener = UnixListener::bind(&output).unwrap();

        let output_str = output.to_string_lossy().into_owned();
        let parsed = CcArgs::parse(&s(&["cc", "-c", "foo.c", "-o", &output_str])).unwrap();

        assert!(parsed.requires_compiler_output_semantics());
        assert!(parsed.refuse_reasons(&[]).iter().any(|reason| {
            reason
                .description()
                .contains("requires compiler write semantics")
        }));

        assert!(
            fs::symlink_metadata(&output)
                .unwrap()
                .file_type()
                .is_socket(),
            "classification must not unlink a non-regular compiler output"
        );
        assert!(
            discover_cc_output_artifacts(&parsed).is_empty(),
            "non-regular compiler outputs must not enter the blob store"
        );
    }

    #[test]
    fn resolve_source_date_epoch_defaults_to_zero() {
        // No build value, no opt-out → kache's default pin makes the key
        // time-independent (warm rebuilds hit).
        assert_eq!(
            resolve_source_date_epoch(None, false).as_deref(),
            Some(std::ffi::OsStr::new("0"))
        );
    }

    #[test]
    fn resolve_source_date_epoch_honors_build_value_verbatim() {
        use std::ffi::OsString;
        // A build that exports SOURCE_DATE_EPOCH is honored VERBATIM (untrimmed),
        // even with the opt-out set, so kache never normalizes a value the
        // compiler would reject into an accepted one (#423). Trimming
        // " 1700000000 " to "1700000000" would turn a build clang rejects into a
        // cached success — that masking is exactly what we must not do.
        assert_eq!(
            resolve_source_date_epoch(Some(OsString::from("1700000000")), false),
            Some(OsString::from("1700000000"))
        );
        assert_eq!(
            resolve_source_date_epoch(Some(OsString::from(" 1700000000 ")), true),
            Some(OsString::from(" 1700000000 ")),
            "a build value is passed through untrimmed and wins over passthrough"
        );
        // An empty build value is honored as set (the compiler gets ""), not
        // silently replaced with "0".
        assert_eq!(
            resolve_source_date_epoch(Some(OsString::from("")), false),
            Some(OsString::from(""))
        );
    }

    #[test]
    fn resolve_source_date_epoch_passthrough_disables_default_pin() {
        // Opt-out with no build value → pin nothing; the unpinned probe yields a
        // time-dependent key, so a wall-clock object is very unlikely to be
        // reused.
        assert_eq!(resolve_source_date_epoch(None, true), None);
    }

    #[cfg(unix)]
    #[test]
    fn execute_pins_source_date_epoch_on_real_compile() {
        // The real compile must export kache's effective SOURCE_DATE_EPOCH so a
        // __DATE__/__TIME__ TU bakes the same date the time-stable key was
        // probed with (no stale-timestamp false hit — #423). Stand-in compiler:
        // a shell that records the SOURCE_DATE_EPOCH it sees into the object.
        use std::fs;

        let dir = tempfile::tempdir().unwrap();
        let obj = dir.path().join("stamp.o");
        let src = dir.path().join("stamp.c");
        fs::write(&src, b"int x;\n").unwrap();
        let obj_str = obj.to_string_lossy().into_owned();
        let src_str = src.to_string_lossy().into_owned();

        // `printf` writes whatever SOURCE_DATE_EPOCH the child process received.
        let script = format!("printf %s \"${{SOURCE_DATE_EPOCH-UNSET}}\" > '{obj_str}'");
        let compiler = CcCompiler::new();
        let parsed = compiler
            .parse(&[
                "sh".to_string(),
                "-c".to_string(),
                script,
                src_str,
                "-c".to_string(),
                "-o".to_string(),
                obj_str.clone(),
            ])
            .unwrap();

        let result = compiler.execute(&parsed).expect("execute must not Err");
        assert_eq!(result.exit_code, 0);
        let baked = fs::read_to_string(&obj).unwrap();
        // Robust against an ambient SOURCE_DATE_EPOCH in the test env: the child
        // must see exactly what the resolver computes (and never "UNSET").
        let expected = effective_source_date_epoch()
            .map(|v| v.to_string_lossy().into_owned())
            .unwrap_or_default();
        assert_eq!(
            baked, expected,
            "real compile must inherit kache's pinned SOURCE_DATE_EPOCH"
        );
        assert_ne!(
            baked, "UNSET",
            "SOURCE_DATE_EPOCH must be set on the compile"
        );
    }

    // ── Layer 4: Firefox-corpus clang-cl flag classification ─────

    #[test]
    fn clang_cl_layer4_flag_classification() {
        use crate::compiler::flags::{Dialect, FlagClass};
        let cl = Dialect::Cl;
        // object-material → CapturedByProbe
        for f in [
            "-EHsc",
            "-EHs-c-",
            "/EHsc",
            "-GR-",
            "/GR-",
            "-GS-",
            "/GS",
            "-Brepro",
            "-utf-8",
            "-Zc:wchar_t",
            "-Zc:forScope-",
        ] {
            assert_eq!(
                classify_cc_flag(f, cl),
                Some(FlagClass::CapturedByProbe),
                "{f}"
            );
        }
        // -Zc:inline stays NoObjectEffect (Layer 2 Exact row matched first)
        assert_eq!(
            classify_cc_flag("-Zc:inline", cl),
            Some(FlagClass::NoObjectEffect)
        );
        // __FILE__-affecting → PreprocessorCaptured
        assert_eq!(
            classify_cc_flag("-FC", cl),
            Some(FlagClass::PreprocessorCaptured)
        );
        // no object effect → NoObjectEffect
        for f in [
            "-nologo",
            "-wd4800",
            "/wd4244",
            "-FS",
            "-Gm-",
            "-external:W0",
        ] {
            assert_eq!(
                classify_cc_flag(f, cl),
                Some(FlagClass::NoObjectEffect),
                "{f}"
            );
        }
        // refused (out of scope) → None
        assert_eq!(classify_cc_flag("-bigobj", cl), None);
        assert_eq!(classify_cc_flag("-showIncludes", cl), None);
    }

    #[test]
    fn clang_cl_full_firefox_invocation_is_cacheable() {
        // Layer 2 + Layer 4 modeled flags (minus -Z7/-bigobj/-showIncludes).
        let p = CcArgs::parse(&s(&[
            "clang-cl",
            "-c",
            "foo.c",
            "-Fofoo.obj",
            "-std:c++20",
            "-fms-compatibility-version=19.50",
            "-guard:cf,nochecks",
            "-Gy",
            "-Gw",
            "-Oy-",
            "-Zc:inline",
            "-Zc:wchar_t",
            "-MD",
            "-EHs-c-",
            "-GR-",
            "-GS-",
            "-nologo",
            "-wd4800",
            "-utf-8",
            "-FS",
            "-external:W0",
            "-Brepro",
            "-FC",
        ]))
        .unwrap();
        let refuse = p.refuse_reasons(&[]);
        assert!(
            refuse.is_empty(),
            "should cache, refused: {:?}",
            refuse.iter().map(|r| r.description()).collect::<Vec<_>>()
        );
        // -bigobj and -showIncludes still refuse.
        let big = CcArgs::parse(&s(&["clang-cl", "-c", "foo.c", "-Fofoo.obj", "-bigobj"])).unwrap();
        assert!(!big.refuse_reasons(&[]).is_empty());
    }

    #[test]
    fn clang_cl_debug_flags_require_the_resolved_probe() {
        // /Z7 etc. are CapturedByProbe: their variant/codegen is only safely
        // keyed via `cc -###`, so the compile must require the probe (bail if
        // absent) — otherwise /ZI and /Z7, which differ, could collide.
        for f in ["/Z7", "/Zi", "/ZI", "/Zd", "-Z7"] {
            let p = CcArgs::parse(&s(&["clang-cl", "-c", "a.c", "-Foa.obj", f])).unwrap();
            assert!(
                cc_flags_need_resolved_invocation(&p),
                "{f}: clang-cl debug must require the -### probe (CapturedByProbe)"
            );
        }
        // A non-debug clang-cl compile with only modeled flags need NOT
        // require the probe (sanity: the assertion above isn't vacuously true).
        let nodebug = CcArgs::parse(&s(&["clang-cl", "-c", "a.c", "-Foa.obj"])).unwrap();
        assert!(
            !cc_flags_need_resolved_invocation(&nodebug),
            "plain clang-cl compile without debug flags must not require the probe"
        );
    }

    /// The per-TU path set handed to the probe must list every spelling a
    /// cc1 line uses for a per-TU file: the path as written (`-o build/u00.o`)
    /// AND the basename (`-main-file-name u00.c`). Missing the basename is
    /// what left the key race half-fixed during development (#keyrace).
    #[test]
    fn cc_resolved_per_tu_paths_includes_full_path_and_basename() {
        let p = CcArgs::parse(&s(&["cc", "-c", "src/u00.c", "-o", "build/u00.o", "-O2"])).unwrap();
        let set: std::collections::HashSet<String> =
            cc_resolved_per_tu_paths(&p).into_iter().collect();
        assert!(set.contains("src/u00.c"), "full source path: {set:?}");
        assert!(set.contains("u00.c"), "source basename: {set:?}");
        assert!(set.contains("build/u00.o"), "full output path: {set:?}");
        assert!(set.contains("u00.o"), "output basename: {set:?}");
        assert!(!set.contains(""), "must never blank an empty token");
    }

    #[test]
    fn cl_debug_path_inputs_folds_source_output_and_dir() {
        let comp = |args: &[&str]| cl_debug_path_inputs(&CcArgs::parse(&s(args)).unwrap());

        // Source filename leaks (H1): foo.c vs bar.c → different components.
        let foo = comp(&["clang-cl", "-c", "foo.c", "-Fofoo.obj", "/Z7"]);
        let bar = comp(&["clang-cl", "-c", "bar.c", "-Fobar.obj", "/Z7"]);
        assert!(foo.is_some() && bar.is_some());
        assert_ne!(
            foo, bar,
            "different source/output must change the component (H1/D3)"
        );

        // Absolute source path leaks (H2).
        let a1 = comp(&["clang-cl", "-c", "C:\\d1\\a.c", "-Foa.obj", "/Z7"]);
        let a2 = comp(&["clang-cl", "-c", "C:\\d2\\a.c", "-Foa.obj", "/Z7"]);
        assert_ne!(
            a1, a2,
            "absolute source path must change the component (H2)"
        );

        // Output name leaks independently (D3): same source, different -Fo.
        let p = comp(&["clang-cl", "-c", "a.c", "-Fopp.obj", "/Z7"]);
        let q = comp(&["clang-cl", "-c", "a.c", "-Foqq.obj", "/Z7"]);
        assert_ne!(p, q, "different -Fo must change the component (D3)");

        // Explicit -fdebug-compilation-dir is used (else current_dir()).
        let explicit = comp(&[
            "clang-cl",
            "-c",
            "a.c",
            "-Foa.obj",
            "/Z7",
            "-fdebug-compilation-dir=C:\\proj\\x",
        ])
        .unwrap();
        assert!(
            explicit.iter().any(|e| e.contains("C:\\proj\\x")),
            "explicit compilation-dir must appear in the component"
        );

        // /Zi, /ZI, -Zi also trigger the fold.
        for f in ["/Zi", "/ZI", "-Zi"] {
            assert!(
                comp(&["clang-cl", "-c", "a.c", "-Foa.obj", f]).is_some(),
                "{f} must fold"
            );
        }

        // Non-debug cl → None (no fold; preserves cross-CWD/name hit-rate).
        assert_eq!(comp(&["clang-cl", "-c", "a.c", "-Foa.obj"]), None);
        // gnu debug → None (gnu normalizes via -ffile-prefix-map, not this path).
        assert_eq!(comp(&["gcc", "-c", "a.c", "-g"]), None);
    }

    #[cfg(unix)]
    fn include_dir_test_compiler(dir: &Path) -> (CcCompiler, PathBuf, PathBuf) {
        use std::fs;

        let fake_cc =
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mock_cc_static.sh");
        let source = dir.join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        (CcCompiler::new(), fake_cc, source)
    }

    #[cfg(unix)]
    fn include_dir_key_ctx(dir: &Path) -> (crate::cache_key::FileHasher<'static>, PathBuf) {
        (crate::cache_key::FileHasher::new(), dir.join("cache"))
    }

    /// The property the whole guard exists for, on the resolution path: a
    /// header appearing in an earlier directory shadows one that was read,
    /// without changing any recorded content, so the key has to move.
    #[test]
    fn include_shadowing_notices_a_header_appearing_ahead_of_the_one_read() {
        let temp = tempfile::tempdir().unwrap();
        let first = temp.path().join("first");
        let second = temp.path().join("second");
        fs::create_dir(&first).unwrap();
        fs::create_dir(&second).unwrap();
        let read = second.join("header.h");
        fs::write(&read, "#define A 1\n").unwrap();
        let source = temp.path().join("unit.c");
        fs::write(&source, "#include \"header.h\"\nint x;\n").unwrap();

        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            first.to_str().unwrap(),
            "-I",
            second.to_str().unwrap(),
        ]))
        .unwrap();
        let inputs = vec![source.clone(), read.clone()];

        let before = digest_cc_include_shadowing(&parsed, &inputs).unwrap();
        fs::write(first.join("header.h"), "#define A 2\n").unwrap();
        let after = digest_cc_include_shadowing(&parsed, &inputs).unwrap();
        assert_ne!(
            before, after,
            "a header ahead of the one that was read must change the key"
        );

        // And removing it again returns to the original resolution.
        fs::remove_file(first.join("header.h")).unwrap();
        assert_eq!(
            digest_cc_include_shadowing(&parsed, &inputs).unwrap(),
            before
        );
    }

    /// The precision the walk did not have. A file that no unit could
    /// include cannot shadow anything, so it must not move the key; the walk
    /// invalidated every unit naming that directory.
    #[test]
    fn include_shadowing_ignores_a_name_that_was_never_read() {
        let temp = tempfile::tempdir().unwrap();
        let include = temp.path().join("inc");
        fs::create_dir(&include).unwrap();
        let read = include.join("header.h");
        fs::write(&read, "int h;\n").unwrap();
        let source = temp.path().join("unit.c");
        fs::write(&source, "#include \"header.h\"\nint x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            include.to_str().unwrap(),
        ]))
        .unwrap();
        let inputs = vec![source.clone(), read.clone()];

        let before = digest_cc_include_shadowing(&parsed, &inputs).unwrap();
        for name in ["unrelated.h", "other.hpp", "header.o", "notes.txt"] {
            fs::write(include.join(name), "x").unwrap();
        }
        assert_eq!(
            digest_cc_include_shadowing(&parsed, &inputs).unwrap(),
            before,
            "names no unit read cannot shadow and must not churn the key"
        );

        // The scale this buys: thousands of unrelated names cost nothing,
        // where the walk refused past its cap.
        let big = temp.path().join("big");
        fs::create_dir(&big).unwrap();
        for i in 0..12_000 {
            fs::write(big.join(format!("h{i}.h")), "x").unwrap();
        }
        let wide = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            include.to_str().unwrap(),
            "-I",
            big.to_str().unwrap(),
        ]))
        .unwrap();
        assert!(
            digest_cc_include_shadowing(&wide, &inputs).is_ok(),
            "a large include tree must resolve rather than refuse"
        );
        assert!(
            digest_cc_include_dir_names(&wide).is_err(),
            "the walk this replaces would have refused the same tree"
        );
    }

    /// A header read from outside any user directory can still be shadowed by
    /// one, since user directories are searched first.
    #[test]
    fn include_shadowing_covers_headers_read_from_outside_the_user_dirs() {
        let temp = tempfile::tempdir().unwrap();
        let user = temp.path().join("user");
        let elsewhere = temp.path().join("elsewhere");
        fs::create_dir(&user).unwrap();
        fs::create_dir(&elsewhere).unwrap();
        let read = elsewhere.join("stdio.h");
        fs::write(&read, "int puts(const char*);\n").unwrap();
        let source = temp.path().join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            user.to_str().unwrap(),
        ]))
        .unwrap();
        let inputs = vec![source.clone(), read.clone()];

        let before = digest_cc_include_shadowing(&parsed, &inputs).unwrap();
        fs::write(user.join("stdio.h"), "int puts(const char*);\n").unwrap();
        assert_ne!(
            digest_cc_include_shadowing(&parsed, &inputs).unwrap(),
            before,
            "a user dir gaining the name of a system header must change the key"
        );
    }

    #[test]
    fn include_dir_digest_changes_when_an_earlier_dir_gains_a_header() {
        let temp = tempfile::tempdir().unwrap();
        let first = temp.path().join("first");
        let second = temp.path().join("second");
        fs::create_dir(&first).unwrap();
        fs::create_dir(&second).unwrap();
        fs::write(second.join("header.h"), "#define A 1\n").unwrap();
        let source = temp.path().join("unit.c");
        fs::write(&source, "#include \"header.h\"\nint x;\n").unwrap();

        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            first.to_str().unwrap(),
            "-I",
            second.to_str().unwrap(),
        ]))
        .unwrap();
        let before = digest_cc_include_dir_names(&parsed).unwrap();
        fs::write(first.join("header.h"), "#define A 2\n").unwrap();
        let after = digest_cc_include_dir_names(&parsed).unwrap();
        assert_ne!(
            before, after,
            "a header appearing in an earlier -I dir must change the name digest"
        );
    }

    #[test]
    fn include_dir_digest_ignores_object_and_dep_files() {
        let temp = tempfile::tempdir().unwrap();
        let include = temp.path().join("inc");
        fs::create_dir(&include).unwrap();
        fs::write(include.join("header.h"), "int h;\n").unwrap();
        let source = temp.path().join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            include.to_str().unwrap(),
        ]))
        .unwrap();
        let before = digest_cc_include_dir_names(&parsed).unwrap();
        fs::write(include.join("header.o"), "obj").unwrap();
        fs::write(include.join("header.obj"), "obj").unwrap();
        fs::write(include.join("header.d"), "deps").unwrap();
        fs::write(include.join("header.pp"), "deps").unwrap();
        fs::write(include.join("libfoo.a"), "ar").unwrap();
        let after = digest_cc_include_dir_names(&parsed).unwrap();
        assert_eq!(
            before, after,
            "sibling compile products must not churn the key"
        );
    }

    #[test]
    fn include_dir_digest_overflow_is_fail_closed() {
        let temp = tempfile::tempdir().unwrap();
        let include = temp.path().join("inc");
        fs::create_dir(&include).unwrap();
        for i in 0..3 {
            fs::write(include.join(format!("h{i}.h")), "int h;\n").unwrap();
        }
        let source = temp.path().join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            include.to_str().unwrap(),
        ]))
        .unwrap();
        let err = digest_cc_include_dir_names_capped(&parsed, 2).unwrap_err();
        assert!(
            err.to_string().contains("exceeded 2"),
            "overflow must fail closed, got {err}"
        );
    }

    #[test]
    fn include_dir_digest_tracks_iquote_dirs() {
        let temp = tempfile::tempdir().unwrap();
        let quote = temp.path().join("quote");
        fs::create_dir(&quote).unwrap();
        let source = temp.path().join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-iquote",
            quote.to_str().unwrap(),
        ]))
        .unwrap();
        let before = digest_cc_include_dir_names(&parsed).unwrap();
        fs::write(quote.join("local.h"), "int q;\n").unwrap();
        let after = digest_cc_include_dir_names(&parsed).unwrap();
        assert_ne!(
            before, after,
            "-iquote dirs must participate in the name digest"
        );
    }

    #[test]
    fn cc_flag_dir_values_reads_separated_and_equals_forms() {
        let rest = [
            "-iquote".to_string(),
            "/q".to_string(),
            "-isystem=/sys".to_string(),
            "-isysroot".to_string(),
            "/sdk".to_string(),
            "-isystem=".to_string(),
        ];
        assert_eq!(cc_flag_dir_values(&rest, "-iquote"), ["/q"]);
        assert_eq!(cc_flag_dir_values(&rest, "-isystem"), ["/sys"]);
        assert_eq!(cc_flag_dir_values(&rest, "-isysroot"), ["/sdk"]);
        assert!(cc_flag_dir_values(&rest, "-idirafter").is_empty());
    }

    #[test]
    fn include_dir_digest_isystem_on_source_dir_is_exempt() {
        let temp = tempfile::tempdir().unwrap();
        let srcdir = temp.path().join("src");
        fs::create_dir(&srcdir).unwrap();
        let source = srcdir.join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-isystem",
            srcdir.to_str().unwrap(),
        ]))
        .unwrap();
        let before = digest_cc_include_dir_names(&parsed).unwrap();
        fs::write(srcdir.join("next_to_source.h"), "int n;\n").unwrap();
        let after = digest_cc_include_dir_names(&parsed).unwrap();
        assert_eq!(
            before, after,
            "-isystem on the source directory must exempt names next to the source"
        );
    }

    #[test]
    fn include_dir_digest_missing_dir_is_empty_not_an_error() {
        let temp = tempfile::tempdir().unwrap();
        let missing = temp.path().join("no-such-inc");
        let source = temp.path().join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            missing.to_str().unwrap(),
        ]))
        .unwrap();
        digest_cc_include_dir_names(&parsed)
            .expect("ENOENT include dir must hash as empty, not fail closed");
    }

    #[test]
    fn include_dir_digest_accepts_a_walk_that_hits_the_cap_exactly() {
        let temp = tempfile::tempdir().unwrap();
        let include = temp.path().join("inc");
        fs::create_dir(&include).unwrap();
        for i in 0..2 {
            fs::write(include.join(format!("h{i}.h")), "int h;\n").unwrap();
        }
        // Source lives in the include dir so the walk is one directory:
        // unit.c + two headers = 3 names.
        let source = include.join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            include.to_str().unwrap(),
        ]))
        .unwrap();
        digest_cc_include_dir_names_capped(&parsed, 3)
            .expect("a walk of exactly `cap` names must succeed");
    }

    #[test]
    fn include_dir_digest_counts_nested_directories_toward_the_cap() {
        let temp = tempfile::tempdir().unwrap();
        let srcdir = temp.path().join("src");
        let include = temp.path().join("inc");
        let nested = include.join("nested");
        fs::create_dir_all(&srcdir).unwrap();
        fs::create_dir_all(&nested).unwrap();
        fs::write(nested.join("h.h"), "int h;\n").unwrap();
        let source = srcdir.join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            include.to_str().unwrap(),
        ]))
        .unwrap();
        // source parent (unit.c) + include subdir + nested header = 3 names.
        // Cap 2 must overflow, including if the subdir increment is mutated
        // to `*=` (which would otherwise stay under the cap).
        let err = digest_cc_include_dir_names_capped(&parsed, 2).unwrap_err();
        assert!(
            err.to_string().contains("exceeded 2"),
            "the nested directory itself must count, got {err}"
        );
    }

    #[test]
    fn include_dir_digest_counts_an_empty_subdir_at_exact_cap() {
        let temp = tempfile::tempdir().unwrap();
        let include = temp.path().join("inc");
        fs::create_dir_all(include.join("empty")).unwrap();
        fs::write(include.join("h.h"), "int h;\n").unwrap();
        let source = include.join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            include.to_str().unwrap(),
        ]))
        .unwrap();
        // unit.c + h.h + empty/ = 3 names. Cap 3 must succeed; `>= cap`
        // on the subdir increment would overflow one too early.
        digest_cc_include_dir_names_capped(&parsed, 3)
            .expect("file + empty subdir at exact cap must succeed");
    }

    #[test]
    fn include_dir_digest_ignores_empty_sdkroot() {
        let _lock = crate::test_support::process_state_test_lock();
        let temp = tempfile::tempdir().unwrap();
        let source = temp.path().join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&["cc", "-c", source.to_str().unwrap()])).unwrap();
        unsafe { std::env::remove_var("SDKROOT") };
        let unset = digest_cc_include_dir_names(&parsed).unwrap();
        unsafe { std::env::set_var("SDKROOT", "") };
        let empty = digest_cc_include_dir_names(&parsed).unwrap();
        unsafe { std::env::remove_var("SDKROOT") };
        assert_eq!(
            unset, empty,
            "empty SDKROOT must not become an include root"
        );
    }

    #[test]
    fn include_dir_digest_exempts_an_existing_sdkroot_directory() {
        let _lock = crate::test_support::process_state_test_lock();
        let temp = tempfile::tempdir().unwrap();
        let sdk = temp.path().join("sdk");
        let srcdir = temp.path().join("src");
        fs::create_dir(&sdk).unwrap();
        fs::create_dir(&srcdir).unwrap();
        let source = srcdir.join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        unsafe { std::env::set_var("SDKROOT", &sdk) };
        let parsed = CcArgs::parse(&s(&["cc", "-c", source.to_str().unwrap()])).unwrap();
        let before = digest_cc_include_dir_names(&parsed).unwrap();
        fs::write(sdk.join("sdk.h"), "int s;\n").unwrap();
        let after = digest_cc_include_dir_names(&parsed).unwrap();
        unsafe { std::env::remove_var("SDKROOT") };
        assert_eq!(
            before, after,
            "headers under SDKROOT must not change the user include-dir digest"
        );
    }

    #[test]
    fn include_dir_names_still_match_is_false_without_a_snapshot() {
        let temp = tempfile::tempdir().unwrap();
        let source = temp.path().join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&["cc", "-c", source.to_str().unwrap()])).unwrap();
        assert!(
            !CcCompiler::new().include_dir_names_still_match(&parsed),
            "no key snapshot means the names must not be treated as matching"
        );
    }

    #[test]
    fn include_dir_digest_skips_isystem_roots() {
        let temp = tempfile::tempdir().unwrap();
        let system = temp.path().join("sys");
        let user = temp.path().join("inc");
        let srcdir = temp.path().join("src");
        fs::create_dir(&system).unwrap();
        fs::create_dir(&user).unwrap();
        fs::create_dir(&srcdir).unwrap();
        fs::write(user.join("user.h"), "int u;\n").unwrap();
        let source = srcdir.join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            user.to_str().unwrap(),
            "-isystem",
            system.to_str().unwrap(),
        ]))
        .unwrap();
        let before = digest_cc_include_dir_names(&parsed).unwrap();
        fs::write(system.join("shadow.h"), "int s;\n").unwrap();
        let after = digest_cc_include_dir_names(&parsed).unwrap();
        assert_eq!(before, after, "-isystem roots must stay exempt");
    }

    /// A directory we cannot stat into is not the same as one that does not
    /// have the header. Only ENOENT means absent; anything else leaves the
    /// resolution unknown, and an unknown shadowing order must refuse rather
    /// than key as if the search had reached the end.
    #[cfg(unix)]
    #[test]
    fn include_dir_resolution_separates_absent_from_unreadable() {
        use std::os::unix::fs::PermissionsExt;
        let temp = tempfile::tempdir().unwrap();
        let first = temp.path().join("first");
        let second = temp.path().join("second");
        fs::create_dir(&first).unwrap();
        fs::create_dir(&second).unwrap();
        fs::write(second.join("shadow.h"), "int s;\n").unwrap();
        let dirs = vec![first.clone(), second.clone()];
        let name = Path::new("shadow.h");

        assert_eq!(
            cc_first_include_dir_providing(&dirs, name).unwrap(),
            Some(1),
            "an empty first dir is genuinely absent, so the search goes on"
        );
        assert_eq!(
            cc_first_include_dir_providing(&dirs, Path::new("nowhere.h")).unwrap(),
            None,
            "no dir providing the name is an answer in itself"
        );

        // The same search, with the first directory unreadable rather than
        // empty, must not silently arrive at the second one.
        fs::set_permissions(&first, fs::Permissions::from_mode(0o000)).unwrap();
        let blocked = cc_first_include_dir_providing(&dirs, name);
        fs::set_permissions(&first, fs::Permissions::from_mode(0o755)).unwrap();
        let err = blocked.expect_err("an unreadable include dir must fail closed");
        assert!(err.to_string().contains("unreadable"), "got {err}");
    }

    #[cfg(unix)]
    #[test]
    fn include_dir_digest_unreadable_dir_is_fail_closed() {
        use std::os::unix::fs::PermissionsExt;
        let temp = tempfile::tempdir().unwrap();
        let include = temp.path().join("inc");
        fs::create_dir(&include).unwrap();
        fs::set_permissions(&include, fs::Permissions::from_mode(0o000)).unwrap();
        let source = temp.path().join("unit.c");
        fs::write(&source, "int x;\n").unwrap();
        let parsed = CcArgs::parse(&s(&[
            "cc",
            "-c",
            source.to_str().unwrap(),
            "-I",
            include.to_str().unwrap(),
        ]))
        .unwrap();
        let err = digest_cc_include_dir_names(&parsed);
        fs::set_permissions(&include, fs::Permissions::from_mode(0o755)).unwrap();
        let err = err.expect_err("unreadable -I dir must fail closed");
        assert!(err.to_string().contains("unreadable"), "got {err}");
    }

    #[cfg(unix)]
    #[test]
    fn shadowing_header_changes_cc_cache_key() {
        let temp = tempfile::tempdir().unwrap();
        let (compiler, fake_cc, source) = include_dir_test_compiler(temp.path());
        let first = temp.path().join("first");
        let second = temp.path().join("second");
        fs::create_dir(&first).unwrap();
        fs::create_dir(&second).unwrap();
        fs::write(second.join("header.h"), "#define A 1\n").unwrap();
        let output = temp.path().join("unit.o");
        let parse = || {
            compiler
                .parse(&[
                    fake_cc.to_string_lossy().into_owned(),
                    "-c".to_string(),
                    source.to_string_lossy().into_owned(),
                    "-o".to_string(),
                    output.to_string_lossy().into_owned(),
                    "-I".to_string(),
                    first.to_string_lossy().into_owned(),
                    "-I".to_string(),
                    second.to_string_lossy().into_owned(),
                ])
                .unwrap()
        };
        let (file_hasher, cache) = include_dir_key_ctx(temp.path());
        let path_normalizer = crate::path_normalizer::PathNormalizer::empty();
        let ctx = KeyCtx {
            file_hasher: &file_hasher,
            path_normalizer: &path_normalizer,
            cache_dir: &cache,
            key_salt: None,
            key_env_vars: &[],
            extra_inputs_digest: None,
        };
        let before = compiler.cache_key(&parse(), &ctx).unwrap();
        fs::write(first.join("header.h"), "#define A 2\n").unwrap();
        let after = compiler.cache_key(&parse(), &ctx).unwrap();
        assert_ne!(
            before, after,
            "a shadowing header must change the cc key even when preprocess output is unchanged"
        );
        assert!(compiler.include_dir_names_still_match(&parse()));
    }
}