kache 1.2.0

Compiler cache for Rust, C/C++ and CUDA, with S3, GCS, shared-filesystem and OCI 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
//! Rustc implementation of the [`Compiler`] trait.
//!
//! Phase 0: a thin facade over the existing free functions in
//! [`crate::args`], [`crate::cache_key`], and [`crate::compile`]. Those
//! functions remain the canonical implementations; the trait simply gives
//! callers a stable shape that other compiler adapters can match.

use anyhow::Result;
use std::borrow::Cow;
use std::path::PathBuf;

use crate::args::RustcArgs;
use crate::cache_key::{KeyOutputs, compute_cache_key_with_outputs};
use crate::compile;
use crate::key_env::KeyEnv;

use super::{
    ArtifactKind, CompileResult, Compiler, CompilerAdapter, CompilerId, KeyCtx, RefuseReason,
    classify_by_filename,
};

pub const RUSTC_ID: CompilerId = CompilerId::new("rustc");
pub const ADAPTER: CompilerAdapter =
    CompilerAdapter::new(RUSTC_ID, "Rust compiler", RustcCompiler::recognizes);

/// Map a rustc `--crate-type` to the [`ArtifactKind`] of the artifact it
/// produces.
///
/// Single source of truth that both [`Compiler::classify_output`] (for
/// extensionless outputs) and [`crate::args::RustcArgs::is_executable_output`]
/// consult. Adding a new crate-type to rustc means adding one arm here;
/// every predicate in the codebase that asks "does this build produce
/// something the OS loads?" then picks up the right answer automatically
/// (via `link_strategy() == Copy`).
///
/// Returns [`ArtifactKind::Other`] for unknown crate-types — callers fall
/// back to safe defaults (immutable handling, no codesign).
pub fn classify_crate_type(crate_type: &str) -> ArtifactKind {
    match crate_type {
        "bin" => ArtifactKind::Executable,
        "dylib" | "cdylib" | "proc-macro" => ArtifactKind::DynamicLibrary,
        "lib" | "rlib" | "staticlib" => ArtifactKind::Library,
        _ => ArtifactKind::Other("unknown-crate-type"),
    }
}

/// Does a crate of this type have Rust metadata to emit?
///
/// rustc writes a real `.rmeta` only for the crate types a downstream crate can
/// link against as a Rust library (`lib` / `rlib` / `dylib` / `proc-macro`). For
/// `bin`, `cdylib`, `staticlib` — and for a `--test` unit, which passes no
/// `--crate-type` at all — an `--emit=metadata` compile still *creates* the
/// `.rmeta` file (cargo expects it) but leaves it **zero bytes**. Verified
/// against rustc 1.97 for every arm below.
///
/// Only used to decide whether an empty `.rmeta` is a legitimate output or a
/// truncated write (`store::zero_byte_is_valid_output`, kunobi-ninja/kache#624),
/// so an unknown crate-type answers `true`: keep the corruption guard rather
/// than exempt something we can't vouch for.
pub fn crate_type_produces_metadata(crate_type: &str) -> bool {
    !matches!(crate_type, "bin" | "cdylib" | "staticlib")
}

#[derive(Default)]
pub struct RustcCompiler {
    base_dirs: Vec<String>,
}

impl RustcCompiler {
    pub fn new() -> Self {
        Self::default()
    }

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

    /// Does this argv invoke rustc (or clippy-driver, which wraps it)?
    ///
    /// Owns its own detection rule; `super::detect_compiler` reaches it
    /// through this module's [`ADAPTER`] descriptor.
    ///
    /// Inspects only `argv[0]`. Path-prefixed forms (`/usr/bin/rustc`,
    /// `C:\…\bin\rustc.exe`) and Windows `.exe` suffixes are accepted —
    /// cargo passes `clippy-driver.exe` here under `cargo clippy` on Windows
    /// (issue #287), which must be recognized as a rustc invocation. Basename
    /// extraction and `.exe` stripping are shared with the cc adapter so both
    /// stay consistent across host platforms.
    pub fn recognizes(args: &[String]) -> bool {
        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);
        name == "rustc" || name.starts_with("rustc") || name == "clippy-driver"
    }

    /// [`Compiler::cache_key`] with the environment and working directory in
    /// `env`, and with what the computation learned besides the key (see
    /// [`KeyOutputs`], returned whether or not the key is). Configured
    /// `key_env_vars`, input predictions and the path normalizer still read
    /// this process, so `env` must describe this process until they move
    /// into the snapshot too.
    pub(crate) fn cache_key_in(
        &self,
        parsed: &RustcArgs,
        ctx: &KeyCtx<'_, '_>,
        env: &KeyEnv,
    ) -> (Result<String>, KeyOutputs) {
        let (key, mut outputs) =
            compute_cache_key_with_outputs(parsed, ctx.file_hasher, ctx.path_normalizer, env);
        // The group `kache explain` names when only declared inputs moved.
        if let (Some(fields), Some(digest)) =
            (outputs.fields.as_mut(), ctx.build_script_inputs_digest)
        {
            fields.insert(
                "build_script_inputs".to_string(),
                digest
                    .get(..crate::cache_key::KEY_FIELD_HEX)
                    .unwrap_or(digest)
                    .to_string(),
            );
        }
        (key.map(|key| finish_key(parsed, ctx, key)), outputs)
    }

    /// Execute a caller-visible compile, forwarding metadata readiness to Cargo.
    pub(crate) fn execute_streaming(&self, parsed: &RustcArgs) -> Result<CompileResult> {
        self.execute_with_metadata_sink(parsed, Some(&mut std::io::stderr()))
    }

    fn execute_with_metadata_sink(
        &self,
        parsed: &RustcArgs,
        metadata_sink: Option<&mut dyn std::io::Write>,
    ) -> Result<CompileResult> {
        self.execute_with_args(
            parsed,
            &parsed.all_args,
            compile::IncrementalMode::Strip,
            None,
            LinkLane::Cache,
            metadata_sink,
            None,
        )
    }

    /// [`Self::execute_streaming`], asking `on_dep_info` once rustc has
    /// written the dep-info whether to carry on. `false` stops rustc there:
    /// nothing has reached Cargo yet, and the result is a failed compile
    /// with no artifacts.
    pub(crate) fn execute_streaming_until_dep_info(
        &self,
        parsed: &RustcArgs,
        on_dep_info: &mut dyn FnMut() -> bool,
    ) -> Result<CompileResult> {
        self.execute_with_args(
            parsed,
            &parsed.all_args,
            compile::IncrementalMode::Strip,
            None,
            LinkLane::Cache,
            Some(&mut std::io::stderr()),
            Some(on_dep_info),
        )
    }

    /// Execute rustc with Kache-owned isolated incremental state while keeping
    /// every other normal compile behavior (path remapping, opcounts,
    /// heartbeat monitoring, diagnostics, and output discovery).
    /// The output is never stored, so a test or binary links as [`LinkLane::Adaptive`] describes.
    pub(crate) fn execute_preserving_incremental(
        &self,
        parsed: &RustcArgs,
        isolated_args: &[String],
    ) -> Result<CompileResult> {
        self.execute_with_args(
            parsed,
            isolated_args,
            compile::IncrementalMode::PreserveIsolated,
            None,
            LinkLane::Adaptive,
            Some(&mut std::io::stderr()),
            None,
        )
    }

    /// Start a cold private incremental compile and pause after dep-info so
    /// the caller can check for a stored artifact before rustc reaches Cargo.
    pub(crate) fn execute_preserving_incremental_until_dep_info(
        &self,
        parsed: &RustcArgs,
        isolated_args: &[String],
        on_dep_info: &mut dyn FnMut() -> bool,
    ) -> Result<CompileResult> {
        self.execute_with_args(
            parsed,
            isolated_args,
            compile::IncrementalMode::PreserveIsolated,
            None,
            LinkLane::Adaptive,
            Some(&mut std::io::stderr()),
            Some(on_dep_info),
        )
    }

    /// Preserve ordinary passthrough path semantics for an executable Kache
    /// had already excluded from artifact caching, while retaining compiler
    /// accounting and heartbeat monitoring.
    pub(crate) fn execute_passthrough_preserving_incremental(
        &self,
        parsed: &RustcArgs,
        isolated_args: &[String],
    ) -> Result<CompileResult> {
        self.execute_with_args(
            parsed,
            isolated_args,
            compile::IncrementalMode::PreserveIsolated,
            Some(true),
            LinkLane::Passthrough,
            Some(&mut std::io::stderr()),
            None,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn execute_with_args(
        &self,
        parsed: &RustcArgs,
        all_args: &[String],
        incremental_mode: compile::IncrementalMode,
        skip_remap_override: Option<bool>,
        lane: LinkLane,
        metadata_sink: Option<&mut dyn std::io::Write>,
        on_dep_info: Option<&mut dyn FnMut() -> bool>,
    ) -> Result<CompileResult> {
        // The invocation and key must use the same path-normalization rules.
        let workspace_root = parsed.path_normalization_root();
        let path_normalizer = crate::path_normalizer::PathNormalizer::from_env(workspace_root)
            .with_target_dir(parsed.target_dir().as_deref())
            .with_base_dirs(&self.base_dirs)
            .with_rust_src_rule(
                crate::cache_key::get_rustc_sysroot(parsed).as_deref(),
                crate::cache_key::get_rustc_commit_hash(&parsed.rustc).as_deref(),
            );
        let skip_remap = skip_remap_override.unwrap_or_else(|| parsed.skip_path_remap());
        let injected: Vec<String> = [
            macos_oso_prefix_flag(parsed, all_args, lane),
            macos_install_name_flag(parsed, all_args, lane),
        ]
        .into_iter()
        .flatten()
        .collect();
        let compiler_args = if injected.is_empty() {
            Cow::Borrowed(all_args)
        } else {
            Cow::Owned([all_args, injected.as_slice()].concat())
        };
        compile::run_rustc(
            &parsed.rustc,
            parsed.inner_rustc.as_deref(),
            compiler_args.as_ref(),
            parsed.has_expanded_argfiles(),
            parsed.output.as_deref(),
            parsed.out_dir.as_deref(),
            parsed.crate_name.as_deref(),
            parsed.extra_filename.as_deref(),
            &parsed.emit,
            skip_remap,
            &path_normalizer,
            incremental_mode,
            metadata_sink,
            on_dep_info,
        )
    }
}

impl Compiler for RustcCompiler {
    type Parsed = RustcArgs;

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

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

    fn refuse_reasons(&self, parsed: &RustcArgs) -> Vec<RefuseReason> {
        let build_script_out_dir = std::env::var_os("OUT_DIR").map(std::path::PathBuf::from);
        rustc_refuse_reasons(parsed, build_script_out_dir.as_deref())
    }

    /// The key for an invocation that ran in this process's environment.
    /// The trait returns only the key, as it does for cc and nvcc; the
    /// wrapper keys rustc through [`RustcCompiler::cache_key_in`].
    fn cache_key(&self, parsed: &RustcArgs, ctx: &KeyCtx<'_, '_>) -> Result<String> {
        self.cache_key_in(parsed, ctx, &KeyEnv::capture()).0
    }

    fn execute(&self, parsed: &RustcArgs) -> Result<CompileResult> {
        self.execute_with_metadata_sink(parsed, None)
    }

    fn classify_output(&self, parsed: &RustcArgs, name: &str) -> ArtifactKind {
        // Delegate to the filename-based classifier for known extensions.
        // Only the extensionless / unrecognized cases need invocation
        // context (to distinguish a bin's primary output from random
        // unrelated files).
        match classify_by_filename(name) {
            ArtifactKind::Other("extensionless") => {
                // No extension: the rustc convention for bin output on
                // Unix. Confirm via crate_types (or `--test`).
                let any_executable_crate_type = parsed
                    .crate_types
                    .iter()
                    .any(|t| matches!(classify_crate_type(t), ArtifactKind::Executable));
                if parsed.is_test || any_executable_crate_type {
                    ArtifactKind::Executable
                } else {
                    ArtifactKind::Other("rustc:unknown")
                }
            }
            ArtifactKind::Other(_) => ArtifactKind::Other("rustc:unknown"),
            kind => kind,
        }
    }
}

/// Fold the configured extra inputs, the build script's declared inputs, key
/// env vars and salt into `key`.
fn finish_key(parsed: &RustcArgs, ctx: &KeyCtx<'_, '_>, key: String) -> String {
    let crate_name = parsed.crate_name.as_deref().unwrap_or("unknown");
    let key = match ctx.extra_inputs_digest {
        Some(digest) => crate::cache_key::fold_labeled(key, "extra_inputs", digest),
        None => key,
    };
    let key = match ctx.build_script_inputs_digest {
        Some(digest) => crate::cache_key::fold_labeled(key, "build_script_inputs", digest),
        None => key,
    };
    let key = crate::cache_key::apply_key_env_vars(key, ctx.key_env_vars, crate_name);
    crate::cache_key::apply_key_salt(key, ctx.key_salt, crate_name)
}

fn rustc_refuse_reasons(
    parsed: &RustcArgs,
    build_script_out_dir: Option<&std::path::Path>,
) -> Vec<RefuseReason> {
    let mut reasons = Vec::new();
    if !parsed.is_primary {
        reasons.push(RefuseReason::NotPrimary);
    }
    if parsed.is_build_script_probe(build_script_out_dir) {
        reasons.push(RefuseReason::Unsupported(
            "rustc build-script probe — not yet",
        ));
    }
    // Expansion is atomic. A missing/non-UTF-8 response file or the unstable
    // shell-style subset keeps its original compact argv and passes through to
    // rustc, which remains the authority for diagnostics and exit status.
    if parsed.argfile_expansion_failed() {
        reasons.push(RefuseReason::Unsupported(
            "rustc response file could not be safely expanded — not yet supported",
        ));
    }
    if parsed.dep_info_output.is_some() {
        reasons.push(RefuseReason::Unsupported(
            "rustc explicit --emit=dep-info=<path> output — not cacheable",
        ));
    }
    // `--pretty`/`--unpretty` (and the `-Z unpretty=…` form) make rustc dump
    // (un)formatted source to stdout *instead* of producing the normal
    // artifacts. The key never reflected these flags, so against a warm cache
    // kache would replay a prior compile's artifacts and skip the requested
    // source dump entirely — the caller gets a binary where it asked for
    // expanded source. Neither cacheable nor keyable; pass through to rustc.
    let wants_source_dump = parsed.all_args.iter().any(|a| {
        a == "--pretty"
            || a == "--unpretty"
            || a.starts_with("--pretty=")
            || a.starts_with("--unpretty=")
    }) || parsed
        .unstable_flags
        .iter()
        .any(|z| z == "unpretty" || z.starts_with("unpretty="));
    if wants_source_dump {
        reasons.push(RefuseReason::Unsupported(
            "rustc --pretty/--unpretty source dump — not cacheable",
        ));
    }
    if let Some(reason) = wasm_link_refusal(parsed) {
        reasons.push(RefuseReason::Unsupported(reason));
    }
    reasons
}

/// Built-in WebAssembly targets whose linker and CRT ship in rustc.
/// Custom target specs never enter this list.
const COMPILER_BUNDLED_WASM_TARGETS: &[&str] = &[
    "wasm32-unknown-unknown",
    "wasm32-wasi",
    "wasm32-wasip1",
    "wasm32-wasip1-threads",
    "wasm32-wasip2",
    "wasm32v1-none",
    "wasm64-unknown-unknown",
];

fn is_compiler_bundled_wasm_target(target: &str) -> bool {
    COMPILER_BUNDLED_WASM_TARGETS.contains(&target)
}

fn is_custom_target_spec(target: &str) -> bool {
    target.contains('/') || target.contains('\\') || target.ends_with(".json")
}

fn is_wasm_triple(target: &str) -> bool {
    target
        .split(['-', '.', '/', '\\'])
        .any(|component| component.starts_with("wasm"))
}

fn link_self_contained_disabled(parsed: &RustcArgs) -> bool {
    match parsed.get_codegen_opt("link-self-contained") {
        None => false,
        Some("y" | "yes" | "on" | "true") => false,
        Some(_) => true,
    }
}

/// Explicit admission for rustc-bundled self-contained WASM links.
///
/// Custom specs, emscripten, and `link-self-contained=no` stay passthrough:
/// those links depend on an external toolchain or CRT that kache does not
/// pin. rlibs and metadata-only emits are unaffected.
fn wasm_link_refusal(parsed: &RustcArgs) -> Option<&'static str> {
    if !parsed.is_executable_output() || !parsed.emits_link() {
        return None;
    }
    let target = parsed.target.as_deref()?;
    if is_custom_target_spec(target) && is_wasm_triple(target) {
        return Some("wasm custom target spec — not yet");
    }
    if is_compiler_bundled_wasm_target(target) {
        if link_self_contained_disabled(parsed) {
            return Some("wasm link-self-contained disabled — not yet");
        }
        return None;
    }
    if is_wasm_triple(target) {
        return Some("wasm target uses an external toolchain — not yet");
    }
    None
}

/// What Kache does with a compile's output, which decides the macOS link flags it adds.
#[derive(Clone, Copy, PartialEq, Eq)]
enum LinkLane {
    /// A passthrough links exactly as an unwrapped rustc would.
    Passthrough,
    /// An output Kache may store gets the checkout-independent `-oso_prefix` and proc-macro install name.
    Cache,
    /// An adaptive incremental output is never stored, so no store-time `.dSYM` stands in for its objects.
    /// A test or binary therefore keeps the absolute `N_OSO` paths an unwrapped rustc writes,
    /// which debuggers and backtraces resolve from any working directory.
    /// Every other output keeps the cache lane's flags.
    /// For a proc macro or dylib that matters, because each dependent's key hashes its bytes.
    Adaptive,
}

/// ld64 `-install_name` for a cached macOS proc-macro link.
///
/// rustc gives a dylib's `LC_ID_DYLIB` its absolute output path, so the same
/// proc macro built fresh in two checkouts differs in that one field, and
/// every dependent that hashes it misses in the second checkout
/// (kunobi-ninja/kache#1009). rustc loads a proc macro by path, never by
/// install name, so a checkout-independent `@rpath` name changes nothing it
/// does. A `dylib` or `cdylib` keeps its name: something may link against it
/// and record that name. The same conditions as `-oso_prefix` apply otherwise.
#[cfg(target_os = "macos")]
fn macos_install_name_flag(
    parsed: &RustcArgs,
    all_args: &[String],
    lane: LinkLane,
) -> Option<String> {
    macos_install_name_flag_inner(parsed, all_args, lane)
}

#[cfg(not(target_os = "macos"))]
fn macos_install_name_flag(
    _parsed: &RustcArgs,
    _all_args: &[String],
    _lane: LinkLane,
) -> Option<String> {
    None
}

#[cfg(any(test, target_os = "macos"))]
fn macos_install_name_flag_inner(
    parsed: &RustcArgs,
    all_args: &[String],
    lane: LinkLane,
) -> Option<String> {
    if lane == LinkLane::Passthrough || !parsed.emits_link() {
        return None;
    }
    if !parsed.crate_types.iter().any(|kind| kind == "proc-macro") {
        return None;
    }
    if all_args.iter().any(|arg| arg.contains("-install_name")) {
        return None;
    }
    if parsed
        .target
        .as_deref()
        .is_some_and(|target| !target.contains("-apple-darwin"))
    {
        return None;
    }
    let crate_name = parsed.crate_name.as_deref()?;
    Some(format!(
        "-Clink-arg=-Wl,-install_name,@rpath/lib{crate_name}.dylib"
    ))
}

/// ld64 `-oso_prefix` for a cached macOS debug link.
///
/// A `-g` Mach-O records absolute object paths in `N_OSO`. Prefixing the
/// output directory makes those paths relative to `--out-dir`, so a restored
/// binary is not checkout-local. An invocation that already carries the flag
/// keeps the caller's spelling. Passthrough compiles skip injection so the
/// binary matches an unwrapped rustc.
/// So does an adaptive test or binary, as [`LinkLane::Adaptive`] explains.
#[cfg(target_os = "macos")]
fn macos_oso_prefix_flag(
    parsed: &RustcArgs,
    all_args: &[String],
    lane: LinkLane,
) -> Option<String> {
    macos_oso_prefix_flag_inner(parsed, all_args, lane)
}

#[cfg(not(target_os = "macos"))]
fn macos_oso_prefix_flag(
    _parsed: &RustcArgs,
    _all_args: &[String],
    _lane: LinkLane,
) -> Option<String> {
    None
}

#[cfg(any(test, target_os = "macos"))]
fn macos_oso_prefix_flag_inner(
    parsed: &RustcArgs,
    all_args: &[String],
    lane: LinkLane,
) -> Option<String> {
    if lane == LinkLane::Passthrough {
        return None;
    }
    if lane == LinkLane::Adaptive && parsed.is_user_facing_executable() {
        return None;
    }
    // Not gated on Rust debuginfo: native objects bundled into an rlib (C or
    // assembly built with `-g`) put `N_OSO` entries in the link either way,
    // and a link with none is unchanged by the flag (kunobi-ninja/kache#1026).
    if !parsed.is_executable_output() || !parsed.emits_link() {
        return None;
    }
    if all_args.iter().any(|arg| arg.contains("-oso_prefix,")) {
        return None;
    }
    if parsed
        .target
        .as_deref()
        .is_some_and(|target| !target.contains("-apple-darwin"))
    {
        return None;
    }
    let root = macos_oso_prefix_root(parsed)?;
    if !root.is_absolute() {
        return None;
    }
    let mut prefix = root.display().to_string();
    if !prefix.ends_with(['/', '\\']) {
        prefix.push('/');
    }
    Some(format!("-Clink-arg=-Wl,-oso_prefix,{prefix}"))
}

/// The directory every OSO path in this link sits under: Cargo's profile
/// directory, `<target>/debug` or `<target>/<triple>/release`.
///
/// Not the output directory. An example links `<profile>/examples/demo` but
/// its rlibs live in `<profile>/deps`, a sibling, so a prefix of the output
/// directory strips nothing from them and the binary keeps the absolute path
/// of the checkout that built it (kunobi-ninja/kache#1010). The profile
/// directory covers `deps`, `examples` and a build script's own directory
/// alike. `-oso_prefix` takes one prefix, so this is the only root that can
/// be stripped; the toolchain's own rlibs keep their paths.
///
/// Falls back to the output directory whenever the invocation is not in
/// Cargo's layout, where widening the prefix would reach outside the build.
#[cfg(any(test, target_os = "macos"))]
use super::platform::cargo_profile_dir;

#[cfg(any(test, target_os = "macos"))]
fn macos_oso_prefix_root(parsed: &RustcArgs) -> Option<PathBuf> {
    let out_dir = parsed.out_dir.as_ref()?;
    Some(cargo_profile_dir(out_dir).unwrap_or_else(|| out_dir.clone()))
}

/// The directory a cached link strips from its `N_OSO` paths through the
/// `-oso_prefix` kache injects, or `None` when this link gets no injected
/// prefix. An archive under it is named relative to that root in the debug
/// map, so the key may use the archive's portable digest.
#[cfg(target_os = "macos")]
pub(crate) fn oso_prefix_root_for_key(parsed: &RustcArgs) -> Option<PathBuf> {
    oso_prefix_root_for_key_inner(parsed)
}

#[cfg(not(target_os = "macos"))]
pub(crate) fn oso_prefix_root_for_key(_parsed: &RustcArgs) -> Option<PathBuf> {
    None
}

#[cfg(any(test, target_os = "macos"))]
fn oso_prefix_root_for_key_inner(parsed: &RustcArgs) -> Option<PathBuf> {
    macos_oso_prefix_flag_inner(parsed, &parsed.all_args, LinkLane::Cache)?;
    macos_oso_prefix_root(parsed)
}

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

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

    fn proc_macro_args(extra: &[&str]) -> RustcArgs {
        let mut argv = vec![
            "rustc",
            "--crate-name",
            "pm",
            "--crate-type",
            "proc-macro",
            "--out-dir",
            "/checkout/target/debug/deps",
            "src/lib.rs",
        ];
        argv.extend_from_slice(extra);
        RustcCompiler::new().parse(&s(&argv)).unwrap()
    }

    #[test]
    fn a_cached_proc_macro_gets_a_checkout_independent_install_name() {
        let parsed = proc_macro_args(&[]);
        assert_eq!(
            macos_install_name_flag_inner(&parsed, &parsed.all_args, LinkLane::Cache).as_deref(),
            Some("-Clink-arg=-Wl,-install_name,@rpath/libpm.dylib")
        );
        let darwin = proc_macro_args(&["--target", "aarch64-apple-darwin"]);
        assert!(
            macos_install_name_flag_inner(&darwin, &darwin.all_args, LinkLane::Cache).is_some()
        );
    }

    #[test]
    fn only_a_cached_proc_macro_link_of_ours_is_renamed() {
        let passthrough = proc_macro_args(&[]);
        assert_eq!(
            macos_install_name_flag_inner(
                &passthrough,
                &passthrough.all_args,
                LinkLane::Passthrough
            ),
            None,
            "a passthrough matches an unwrapped rustc"
        );
        let named = proc_macro_args(&["-C", "link-arg=-Wl,-install_name,@rpath/mine.dylib"]);
        assert_eq!(
            macos_install_name_flag_inner(&named, &named.all_args, LinkLane::Cache),
            None,
            "the caller's own install name stays"
        );
        let linux = proc_macro_args(&["--target", "x86_64-unknown-linux-gnu"]);
        assert_eq!(
            macos_install_name_flag_inner(&linux, &linux.all_args, LinkLane::Cache),
            None
        );
        let metadata = proc_macro_args(&["--emit", "metadata"]);
        assert_eq!(
            macos_install_name_flag_inner(&metadata, &metadata.all_args, LinkLane::Cache),
            None,
            "nothing is linked"
        );
        for kind in ["dylib", "cdylib", "bin", "rlib"] {
            let parsed = RustcCompiler::new()
                .parse(&s(&[
                    "rustc",
                    "--crate-name",
                    "pm",
                    "--crate-type",
                    kind,
                    "--out-dir",
                    "/checkout/target/debug/deps",
                    "src/lib.rs",
                ]))
                .unwrap();
            assert_eq!(
                macos_install_name_flag_inner(&parsed, &parsed.all_args, LinkLane::Cache),
                None,
                "{kind} keeps the name its consumers may record"
            );
        }
    }

    #[test]
    fn recognizes_rustc_and_clippy_driver() {
        assert!(RustcCompiler::recognizes(&s(&["rustc"])));
        assert!(RustcCompiler::recognizes(&s(&["/usr/bin/rustc"])));
        assert!(RustcCompiler::recognizes(&s(&[
            "/home/user/.rustup/toolchains/stable/bin/rustc"
        ])));
        assert!(RustcCompiler::recognizes(&s(&["clippy-driver"])));
        assert!(RustcCompiler::recognizes(&s(&[
            "/path/to/bin/clippy-driver"
        ])));

        // Regression for issue #287: on Windows `cargo clippy` invokes the
        // wrapper as `kache <…>\clippy-driver.exe rustc -vV`. The `.exe`
        // suffix and backslash separators must not defeat detection — this
        // case ran as a clap subcommand before the fix ("unrecognized
        // subcommand"). These assertions hold on every host OS, so the
        // regression is caught without a Windows runner.
        assert!(RustcCompiler::recognizes(&s(&["rustc.exe"])));
        assert!(RustcCompiler::recognizes(&s(&["clippy-driver.exe"])));
        assert!(RustcCompiler::recognizes(&s(&[
            r"C:\Program Files\Rust\bin\rustc.exe"
        ])));
        assert!(RustcCompiler::recognizes(&s(&[
            r"G:\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\bin\clippy-driver.exe"
        ])));
        // Detection is architecture-independent: the binary is named
        // `clippy-driver.exe` / `rustc.exe` identically on ARM64 (aarch64),
        // i686, and the gnu toolchain. The arch substring in the toolchain
        // dir is incidental — only the `.exe` basename matters.
        assert!(RustcCompiler::recognizes(&s(&[
            r"C:\Users\dev\.rustup\toolchains\stable-aarch64-pc-windows-msvc\bin\clippy-driver.exe"
        ])));
        assert!(RustcCompiler::recognizes(&s(&[
            r"C:\.rustup\toolchains\stable-x86_64-pc-windows-gnu\bin\rustc.exe"
        ])));
        // `.exe` matching is case-insensitive (Windows filesystems).
        assert!(RustcCompiler::recognizes(&s(&["clippy-driver.EXE"])));

        assert!(!RustcCompiler::recognizes(&s(&["gcc"])));
        assert!(!RustcCompiler::recognizes(&s(&["--crate-name"])));
        // C-family compilers (incl. their Windows `.exe` forms) belong to the
        // cc adapter, not rustc.
        assert!(!RustcCompiler::recognizes(&s(&["gcc.exe"])));
        assert!(!RustcCompiler::recognizes(&s(&[
            r"C:\msys64\bin\clang.exe"
        ])));
        // Empty argv: there is nothing to recognize.
        assert!(!RustcCompiler::recognizes(&[]));
    }

    #[test]
    fn id_is_rustc() {
        assert_eq!(RustcCompiler::new().id(), RUSTC_ID);
    }

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

    #[test]
    fn refuse_reasons_returns_not_primary_for_query_invocations() {
        // `rustc -vV` is a version query, not a primary compilation
        let parsed = RustcCompiler::new().parse(&s(&["rustc", "-vV"])).unwrap();
        let reasons = RustcCompiler::new().refuse_reasons(&parsed);
        assert!(matches!(reasons.as_slice(), [RefuseReason::NotPrimary]));
    }

    #[test]
    fn refuse_reasons_returns_not_primary_for_source_bearing_print_query() {
        // substrate-wasm-builder probes the wasm artifact name with a real
        // crate/source pair plus `--print=file-names`. It is still a query: rustc
        // prints the name and deliberately emits no dep-info or compile output.
        for print in [
            ["--print", "file-names"].as_slice(),
            ["--print=file-names"].as_slice(),
        ] {
            let mut argv = s(&[
                "rustc",
                "src/lib.rs",
                "--crate-name",
                "dummy_crate",
                "--crate-type",
                "rlib",
            ]);
            argv.extend(print.iter().map(|arg| (*arg).to_string()));
            let parsed = RustcCompiler::new().parse(&argv).unwrap();
            assert!(
                parsed.residual_args.is_empty(),
                "query value leaked into residual args: {print:?} -> {:?}",
                parsed.residual_args
            );
            let reasons = RustcCompiler::new().refuse_reasons(&parsed);
            assert!(
                matches!(reasons.as_slice(), [RefuseReason::NotPrimary]),
                "source-bearing print query was treated as a compile: {print:?} -> {reasons:?}"
            );
        }
    }

    #[test]
    fn refuse_reasons_returns_not_primary_for_source_bearing_info_query() {
        for query in ["-V", "--version", "-h", "--help", "-vV"] {
            let parsed = RustcCompiler::new()
                .parse(&s(&[
                    "rustc",
                    "src/lib.rs",
                    "--crate-name",
                    "dummy_crate",
                    query,
                ]))
                .unwrap();
            let reasons = RustcCompiler::new().refuse_reasons(&parsed);
            assert!(
                matches!(reasons.as_slice(), [RefuseReason::NotPrimary]),
                "source-bearing info query was treated as a compile: {query} -> {reasons:?}"
            );
        }
    }

    #[test]
    fn refuse_reasons_empty_for_primary_compilation() {
        let parsed = RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "src/lib.rs",
                "--crate-name",
                "foo",
                "--crate-type",
                "lib",
            ]))
            .unwrap();
        assert!(parsed.is_primary);
        let reasons = RustcCompiler::new().refuse_reasons(&parsed);
        assert!(reasons.is_empty());
    }

    #[test]
    fn refuse_reasons_accepts_expanded_response_file() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, "pub fn answer() -> u32 { 42 }\n").unwrap();
        let response = dir.path().join("rustc.args");
        std::fs::write(
            &response,
            format!(
                "--crate-name\nfoo\n{}\n--crate-type\nlib\n",
                source.display()
            ),
        )
        .unwrap();

        let parsed = RustcCompiler::new()
            .parse(&["rustc".to_string(), format!("@{}", response.display())])
            .unwrap();
        assert!(parsed.is_primary);
        let reasons = RustcCompiler::new().refuse_reasons(&parsed);
        assert!(reasons.is_empty(), "unexpected refusal: {reasons:?}");
    }

    #[test]
    fn refuse_reasons_refuses_unreadable_response_file() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("missing.args");
        let parsed = RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "--crate-name",
                "foo",
                "src/lib.rs",
                &format!("@{}", missing.display()),
            ]))
            .unwrap();
        let reasons = RustcCompiler::new().refuse_reasons(&parsed);
        assert!(
            reasons.iter().any(|r| matches!(
                r,
                RefuseReason::Unsupported(d) if d.contains("response file")
            )),
            "expected a response-file refusal, got {reasons:?}"
        );
    }

    #[test]
    fn refuse_reasons_refuses_explicit_dep_info_output_path() {
        let parsed = RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "src/lib.rs",
                "--crate-name",
                "foo",
                "--emit=metadata,dep-info=custom/deps.mk",
            ]))
            .unwrap();
        let reasons = RustcCompiler::new().refuse_reasons(&parsed);
        assert!(reasons.iter().any(|reason| matches!(
            reason,
            RefuseReason::Unsupported(detail) if detail.contains("explicit --emit=dep-info")
        )));
    }

    #[test]
    fn refuse_reasons_refuses_unpretty_source_dump() {
        // `--unpretty` / `--pretty` / `-Z unpretty=…` make rustc emit source to
        // stdout instead of artifacts. None of these are folded into the key, so
        // a warm cache would replay the wrong (artifact) output. Must pass through.
        for args in [
            vec![
                "rustc",
                "--crate-name",
                "foo",
                "src/lib.rs",
                "--unpretty=expanded",
            ],
            vec![
                "rustc",
                "--crate-name",
                "foo",
                "src/lib.rs",
                "--pretty",
                "normal",
            ],
            vec![
                "rustc",
                "--crate-name",
                "foo",
                "src/lib.rs",
                "-Z",
                "unpretty=hir",
            ],
        ] {
            let parsed = RustcCompiler::new().parse(&s(&args)).unwrap();
            let reasons = RustcCompiler::new().refuse_reasons(&parsed);
            assert!(
                reasons.iter().any(|r| matches!(
                    r,
                    RefuseReason::Unsupported(d) if d.contains("unpretty")
                )),
                "expected an unpretty refusal for {args:?}, got {reasons:?}"
            );
        }
    }

    #[test]
    fn refuse_reasons_identifies_build_script_probe() {
        let parsed = RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "--edition=2018",
                "--crate-name=thiserror",
                "--crate-type=lib",
                "--emit=dep-info,metadata",
                "--out-dir",
                "/work/proj/target/release/build/thiserror-abc/out/probe",
                "build/probe.rs",
            ]))
            .unwrap();

        let reasons = rustc_refuse_reasons(
            &parsed,
            Some(std::path::Path::new(
                "/work/proj/target/release/build/thiserror-abc/out",
            )),
        );
        assert_eq!(reasons.len(), 1);
        assert_eq!(
            reasons[0].description(),
            "rustc build-script probe — not yet"
        );
    }

    fn lib_args() -> RustcArgs {
        RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "src/lib.rs",
                "--crate-name",
                "foo",
                "--crate-type",
                "lib",
            ]))
            .unwrap()
    }

    fn bin_args() -> RustcArgs {
        RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "src/main.rs",
                "--crate-name",
                "foo",
                "--crate-type",
                "bin",
            ]))
            .unwrap()
    }

    #[test]
    fn classify_output_recognizes_rust_library_artifacts() {
        let c = RustcCompiler::new();
        let args = lib_args();
        assert_eq!(
            c.classify_output(&args, "libfoo-abc123.rlib"),
            ArtifactKind::Library
        );
        assert_eq!(
            c.classify_output(&args, "libfoo-abc123.rmeta"),
            ArtifactKind::Metadata
        );
        assert_eq!(
            c.classify_output(&args, "foo-abc123.d"),
            ArtifactKind::DepInfo
        );
    }

    #[test]
    fn classify_output_recognizes_object_files_including_rcgu() {
        // Regression guard: `.rcgu.o` files must classify as Object so the
        // restore loop never sends them to codesign (kache-fork bug 572f321).
        let c = RustcCompiler::new();
        let args = bin_args();
        assert_eq!(
            c.classify_output(&args, "foo-abc.123.rcgu.o"),
            ArtifactKind::Object
        );
        assert_eq!(c.classify_output(&args, "foo.o"), ArtifactKind::Object);
    }

    #[test]
    fn classify_output_recognizes_dynamic_libraries_per_platform() {
        let c = RustcCompiler::new();
        let args = lib_args();
        assert_eq!(
            c.classify_output(&args, "libfoo.dylib"),
            ArtifactKind::DynamicLibrary
        );
        assert_eq!(
            c.classify_output(&args, "libfoo.so"),
            ArtifactKind::DynamicLibrary
        );
        assert_eq!(
            c.classify_output(&args, "foo.dll"),
            ArtifactKind::DynamicLibrary
        );
    }

    #[test]
    fn classify_output_recognizes_debug_sidecars() {
        let c = RustcCompiler::new();
        let args = bin_args();
        assert_eq!(
            c.classify_output(&args, "foo-abc.dwo"),
            ArtifactKind::DebugSidecar
        );
        assert_eq!(
            c.classify_output(&args, "foo.pdb"),
            ArtifactKind::DebugSidecar
        );
    }

    #[test]
    fn classify_output_treats_extensionless_bin_outputs_as_executable() {
        // A bin crate emits a no-extension file (`my_bin-abc123`); the
        // classifier needs invocation context to recognize it.
        let c = RustcCompiler::new();
        let args = bin_args();
        assert_eq!(
            c.classify_output(&args, "foo-abc123"),
            ArtifactKind::Executable
        );
        assert_eq!(
            c.classify_output(&args, "foo.exe"),
            ArtifactKind::Executable
        );
    }

    #[test]
    fn classify_output_falls_back_to_other_for_unrecognized_in_lib_build() {
        // Same extensionless name in a lib build: no executable context, so
        // we don't blindly call it Executable. Other("...") makes the
        // wrapper take the safe default (Hardlink, no post-processing).
        let c = RustcCompiler::new();
        let args = lib_args();
        match c.classify_output(&args, "mystery-file") {
            ArtifactKind::Other(_) => {}
            other => panic!("expected Other, got {other:?}"),
        }
    }

    #[test]
    fn classify_crate_type_maps_known_rustc_types() {
        // Single source of truth for crate-type → artifact kind. Any
        // predicate in the codebase that asks "does this build produce
        // something the OS loads at runtime?" derives its answer from this
        // mapping (via `link_strategy() == Copy`). Locking the contract.
        assert_eq!(classify_crate_type("bin"), ArtifactKind::Executable);
        assert_eq!(classify_crate_type("dylib"), ArtifactKind::DynamicLibrary);
        assert_eq!(classify_crate_type("cdylib"), ArtifactKind::DynamicLibrary);
        assert_eq!(
            classify_crate_type("proc-macro"),
            ArtifactKind::DynamicLibrary
        );
        assert_eq!(classify_crate_type("lib"), ArtifactKind::Library);
        assert_eq!(classify_crate_type("rlib"), ArtifactKind::Library);
        // staticlib produces .a — a static library, NOT loaded by the OS.
        assert_eq!(classify_crate_type("staticlib"), ArtifactKind::Library);
        // Unknown crate-types fall back to Other, which has Hardlink
        // strategy and is_executable_output() returns false. Conservative
        // default for new rustc crate-types we haven't accounted for yet.
        match classify_crate_type("future-rustc-type-2030") {
            ArtifactKind::Other(_) => {}
            other => panic!("expected Other, got {other:?}"),
        }
    }

    #[test]
    fn crate_type_produces_metadata_splits_rmeta_emitters() {
        // Measured against rustc 1.97: `--emit=metadata` writes a real `.rmeta`
        // for these, so an empty one means a truncated write (#624).
        for ct in ["lib", "rlib", "dylib", "proc-macro"] {
            assert!(crate_type_produces_metadata(ct), "{ct} emits metadata");
        }
        // These create the `.rmeta` cargo expects but leave it zero bytes.
        for ct in ["bin", "cdylib", "staticlib"] {
            assert!(!crate_type_produces_metadata(ct), "{ct} emits no metadata");
        }
        // Unknown crate-type: keep the zero-byte corruption guard.
        assert!(crate_type_produces_metadata("future-rustc-type-2030"));
    }

    #[test]
    fn classify_crate_type_link_strategy_matches_is_executable_output() {
        // Regression guard for the centralization: every crate-type in the
        // is_executable_output set (bin/dylib/cdylib/proc-macro/+test) maps
        // to a kind whose link_strategy is Copy; everything else maps to
        // Hardlink. Adding a new crate-type to classify_crate_type
        // automatically threads through is_executable_output and every
        // caller of it.
        use crate::link::LinkStrategy;
        let executable_types = ["bin", "dylib", "cdylib", "proc-macro"];
        for t in executable_types {
            assert_eq!(
                classify_crate_type(t).link_strategy(),
                LinkStrategy::Copy,
                "{t} should be Copy strategy"
            );
        }
        let library_types = ["lib", "rlib", "staticlib"];
        for t in library_types {
            assert_eq!(
                classify_crate_type(t).link_strategy(),
                LinkStrategy::Hardlink,
                "{t} should be Hardlink strategy"
            );
        }
    }

    fn linked_wasm(target: &str, extra: &[&str]) -> RustcArgs {
        let mut argv = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "widget".to_string(),
            "--crate-type".to_string(),
            "bin".to_string(),
            "--emit".to_string(),
            "link".to_string(),
            "--target".to_string(),
            target.to_string(),
            "src/main.rs".to_string(),
        ];
        argv.extend(extra.iter().map(|s| s.to_string()));
        RustcCompiler::new().parse(&argv).unwrap()
    }

    #[test]
    fn refuse_reasons_admits_native_host_bins() {
        let parsed = RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "--crate-name",
                "app",
                "--crate-type",
                "bin",
                "--emit",
                "link",
                "--target",
                "x86_64-unknown-linux-gnu",
                "src/main.rs",
            ]))
            .unwrap();
        assert!(
            RustcCompiler::new().refuse_reasons(&parsed).is_empty(),
            "a native GNU bin is not a WASM link: {:?}",
            RustcCompiler::new().refuse_reasons(&parsed)
        );
    }

    #[test]
    fn refuse_reasons_treats_path_only_wasm_target_as_custom_spec() {
        let parsed = linked_wasm("/tmp/wasm32-unknown-unknown", &[]);
        let reasons = RustcCompiler::new().refuse_reasons(&parsed);
        assert!(
            reasons.iter().any(|r| matches!(
                r,
                RefuseReason::Unsupported(d) if d.contains("custom target spec")
            )),
            "a path-shaped wasm target must pass through, got {reasons:?}"
        );
    }

    #[test]
    fn custom_target_specs_accept_each_supported_path_shape() {
        assert!(is_custom_target_spec("specs/wasm32-custom"));
        assert!(is_custom_target_spec(r"specs\wasm32-custom"));
        assert!(is_custom_target_spec("wasm32-custom.json"));
        assert!(!is_custom_target_spec("wasm32-unknown-unknown"));
    }

    #[test]
    fn refuse_reasons_admits_compiler_bundled_wasm_links() {
        for target in COMPILER_BUNDLED_WASM_TARGETS {
            let parsed = linked_wasm(target, &[]);
            let reasons = RustcCompiler::new().refuse_reasons(&parsed);
            assert!(
                reasons.is_empty(),
                "{target} should use rustc's bundled linker, got {reasons:?}"
            );
        }

        let yes = linked_wasm("wasm32-wasip1", &["-Clink-self-contained=yes"]);
        assert!(RustcCompiler::new().refuse_reasons(&yes).is_empty());
    }

    #[test]
    fn refuse_reasons_passthroughs_external_wasm_toolchains() {
        for target in ["wasm32-unknown-emscripten", "wasm32-wali-linux-musl"] {
            let parsed = linked_wasm(target, &[]);
            let reasons = RustcCompiler::new().refuse_reasons(&parsed);
            assert!(
                reasons.iter().any(|r| matches!(
                    r,
                    RefuseReason::Unsupported(d) if d.contains("external toolchain")
                )),
                "{target} should pass through, got {reasons:?}"
            );
        }

        let custom = linked_wasm("/tmp/wasm32-unknown-unknown.json", &[]);
        let reasons = RustcCompiler::new().refuse_reasons(&custom);
        assert!(
            reasons.iter().any(|r| matches!(
                r,
                RefuseReason::Unsupported(d) if d.contains("custom target spec")
            )),
            "custom wasm spec should pass through, got {reasons:?}"
        );

        let disabled = linked_wasm("wasm32-unknown-unknown", &["-Clink-self-contained=no"]);
        let reasons = RustcCompiler::new().refuse_reasons(&disabled);
        assert!(
            reasons.iter().any(|r| matches!(
                r,
                RefuseReason::Unsupported(d) if d.contains("link-self-contained")
            )),
            "link-self-contained=no should pass through, got {reasons:?}"
        );
    }

    #[test]
    fn refuse_reasons_does_not_refuse_wasm_rlibs() {
        let parsed = RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "--crate-name",
                "widget",
                "--crate-type",
                "rlib",
                "--target",
                "wasm32-unknown-emscripten",
                "src/lib.rs",
            ]))
            .unwrap();
        assert!(RustcCompiler::new().refuse_reasons(&parsed).is_empty());
    }

    fn debug_bin_args(out_dir: &Path, extra: &[&str]) -> (RustcArgs, Vec<String>) {
        let mut argv = vec![
            "rustc".to_string(),
            "--crate-name".to_string(),
            "foo".to_string(),
            "--crate-type".to_string(),
            "bin".to_string(),
            "-g".to_string(),
            "--out-dir".to_string(),
            out_dir.display().to_string(),
            "src/main.rs".to_string(),
        ];
        argv.extend(extra.iter().map(|s| s.to_string()));
        let parsed = RustcCompiler::new().parse(&argv).unwrap();
        (parsed, argv)
    }

    /// The link-time `-oso_prefix` and the store-time dsymutil cwd must agree,
    /// or every OSO path resolves against the wrong directory and the cached
    /// dSYM comes out empty (kunobi-ninja/kache#1161). Links with the flag
    /// kache actually injects, in each of Cargo's output layouts, with a
    /// dependency object in `deps/` standing in for an rlib member.
    #[test]
    fn macos_dsymutil_resolves_objects_under_the_injected_oso_prefix() {
        use std::process::Command;
        if std::env::consts::OS != "macos" {
            return;
        }
        let cc = |args: &[&std::ffi::OsStr]| {
            let status = Command::new("cc").args(args).status().unwrap();
            assert!(status.success(), "cc {args:?} failed");
        };
        let compile = |dir: &Path, name: &str, body: &str| {
            let source = dir.join(format!("{name}.c"));
            let object = dir.join(format!("{name}.o"));
            std::fs::write(&source, body).unwrap();
            cc(&[
                "-g".as_ref(),
                "-c".as_ref(),
                source.as_os_str(),
                "-o".as_ref(),
                object.as_os_str(),
            ]);
            object
        };

        for layout in ["deps", "examples", "build/foo-0123456789abcdef"] {
            let dir = tempfile::tempdir().unwrap();
            let profile = dir.path().canonicalize().unwrap().join("target/debug");
            let deps = profile.join("deps");
            let out_dir = profile.join(layout);
            std::fs::create_dir_all(&deps).unwrap();
            std::fs::create_dir_all(&out_dir).unwrap();
            let dep = compile(&deps, "depfn", "int depfn(void) { return 1; }\n");
            let main = compile(
                &out_dir,
                "mainfn",
                "int depfn(void);\nint main(void) { return depfn(); }\n",
            );

            let (parsed, argv) = debug_bin_args(&out_dir, &[]);
            let flag = macos_oso_prefix_flag_inner(&parsed, &argv, LinkLane::Cache).unwrap();
            let link_arg = flag.strip_prefix("-Clink-arg=").unwrap();
            let binary = out_dir.join("foo");
            cc(&[
                main.as_os_str(),
                dep.as_os_str(),
                link_arg.as_ref(),
                "-o".as_ref(),
                binary.as_os_str(),
            ]);

            let bundle = out_dir.join("foo.dSYM");
            let output = super::super::platform::debug_bundle_command(&binary, &bundle)
                .unwrap()
                .output()
                .unwrap();
            let stderr = String::from_utf8_lossy(&output.stderr);
            assert!(output.status.success(), "{layout}: {stderr}");
            assert!(
                !stderr.contains("unable to open object file"),
                "{layout}: dsymutil ran outside the OSO prefix root: {stderr}"
            );
            let dump = Command::new("dwarfdump")
                .arg("--debug-info")
                .arg(&bundle)
                .output()
                .unwrap();
            let info = String::from_utf8_lossy(&dump.stdout);
            for unit in ["mainfn.c", "depfn.c"] {
                assert!(info.contains(unit), "{layout}: dSYM lacks {unit}: {info}");
            }
        }
    }

    #[test]
    fn oso_prefix_is_injected_for_cached_macos_debug_links() {
        let dir = tempfile::tempdir().unwrap();
        let profile = dir.path().join("target/debug");
        let out_dir = profile.join("deps");
        std::fs::create_dir_all(&out_dir).unwrap();

        let expected = |root: &Path| format!("-Clink-arg=-Wl,-oso_prefix,{}/", root.display());
        let (parsed, argv) = debug_bin_args(&out_dir, &[]);
        let flag = macos_oso_prefix_flag_inner(&parsed, &argv, LinkLane::Cache).unwrap();
        assert_eq!(flag, expected(&profile));

        // An example links `<profile>/examples/demo` against rlibs in
        // `<profile>/deps`, a sibling: only the profile directory strips both
        // (kunobi-ninja/kache#1010).
        let examples = profile.join("examples");
        std::fs::create_dir_all(&examples).unwrap();
        let (parsed, argv) = debug_bin_args(&examples, &[]);
        assert_eq!(
            macos_oso_prefix_flag_inner(&parsed, &argv, LinkLane::Cache).unwrap(),
            expected(&profile),
            "an example strips the same root as a binary"
        );

        // Cross builds put the profile under the triple.
        let cross_profile = dir.path().join("target/aarch64-apple-darwin/debug");
        let cross_out = cross_profile.join("examples");
        std::fs::create_dir_all(&cross_out).unwrap();
        let (parsed, argv) = debug_bin_args(&cross_out, &["--target", "aarch64-apple-darwin"]);
        assert_eq!(
            macos_oso_prefix_flag_inner(&parsed, &argv, LinkLane::Cache).unwrap(),
            expected(&cross_profile)
        );

        // A build script's own directory is two levels below the profile.
        let build_out = profile.join("build/pkg-abc123");
        std::fs::create_dir_all(&build_out).unwrap();
        let (parsed, argv) = debug_bin_args(&build_out, &[]);
        assert_eq!(
            macos_oso_prefix_flag_inner(&parsed, &argv, LinkLane::Cache).unwrap(),
            expected(&profile)
        );

        // Nothing below the profile directory: its own path is already the
        // root, and widening further would reach outside the build.
        let (parsed, argv) = debug_bin_args(&profile, &[]);
        assert_eq!(
            macos_oso_prefix_flag_inner(&parsed, &argv, LinkLane::Cache).unwrap(),
            expected(&profile)
        );
        assert_eq!(cargo_profile_dir(&profile), None);
        // Only two levels are examined, so a checkout that lives under a
        // directory named `deps` keeps its own output directory.
        let sneaky = dir.path().join("deps/proj/target/debug");
        std::fs::create_dir_all(&sneaky).unwrap();
        assert_eq!(cargo_profile_dir(&sneaky), None);
        assert_eq!(
            cargo_profile_dir(Path::new("/deps")),
            Some(PathBuf::from("/")),
            "a profile directory at the root still yields a root prefix"
        );
        assert_eq!(
            cargo_profile_dir(Path::new("relative/deps")),
            Some(PathBuf::from("relative"))
        );
        let (parsed, argv) = debug_bin_args(Path::new("relative/deps"), &[]);
        assert!(
            macos_oso_prefix_flag_inner(&parsed, &argv, LinkLane::Cache).is_none(),
            "a relative output directory cannot anchor a prefix"
        );

        let already = debug_bin_args(&out_dir, &["-Clink-arg=-Wl,-oso_prefix,/elsewhere/"]);
        assert!(macos_oso_prefix_flag_inner(&already.0, &already.1, LinkLane::Cache).is_none());

        let wasm = debug_bin_args(&out_dir, &["--target", "wasm32-unknown-unknown"]);
        assert!(macos_oso_prefix_flag_inner(&wasm.0, &wasm.1, LinkLane::Cache).is_none());

        let release = RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "--crate-name",
                "foo",
                "--crate-type",
                "bin",
                "--out-dir",
                out_dir.to_str().unwrap(),
                "src/main.rs",
            ]))
            .unwrap();
        assert_eq!(
            macos_oso_prefix_flag_inner(&release, &release.all_args, LinkLane::Cache),
            Some(expected(&profile)),
            "a link without Rust debuginfo can still carry native DWARF from rlibs"
        );
        assert_eq!(
            oso_prefix_root_for_key_inner(&release),
            Some(profile.clone()),
            "so its key treats archives under the profile as prefixed"
        );

        let library = RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "--crate-name",
                "foo",
                "--crate-type",
                "rlib",
                "-g",
                "--out-dir",
                out_dir.to_str().unwrap(),
                "src/lib.rs",
            ]))
            .unwrap();
        assert!(
            macos_oso_prefix_flag_inner(&library, &library.all_args, LinkLane::Cache).is_none(),
            "non-executable outputs must not receive oso_prefix"
        );

        let metadata_only = RustcCompiler::new()
            .parse(&s(&[
                "rustc",
                "--crate-name",
                "foo",
                "--crate-type",
                "bin",
                "-g",
                "--emit",
                "metadata",
                "--out-dir",
                out_dir.to_str().unwrap(),
                "src/main.rs",
            ]))
            .unwrap();
        assert!(
            macos_oso_prefix_flag_inner(&metadata_only, &metadata_only.all_args, LinkLane::Cache)
                .is_none(),
            "non-link outputs must not receive oso_prefix"
        );

        let relative = debug_bin_args(Path::new("target/debug/deps"), &[]);
        assert!(macos_oso_prefix_flag_inner(&relative.0, &relative.1, LinkLane::Cache).is_none());

        let (parsed, argv) = debug_bin_args(&out_dir, &[]);
        assert!(
            macos_oso_prefix_flag_inner(&parsed, &argv, LinkLane::Passthrough).is_none(),
            "passthrough must not rewrite the link"
        );
    }

    /// An adaptive output is never stored, so a test or binary keeps the absolute `N_OSO` paths
    /// that a backtrace resolves from the package directory.
    /// Every other executable output keeps the prefix on that lane; a proc macro's or dylib's dependents hash its bytes.
    #[test]
    fn only_an_adaptive_test_or_binary_links_without_the_oso_prefix() {
        let dir = tempfile::tempdir().unwrap();
        let profile = dir.path().join("target/debug");
        let out_dir = profile.join("deps");
        std::fs::create_dir_all(&out_dir).unwrap();
        let prefixed = Some(format!("-Clink-arg=-Wl,-oso_prefix,{}/", profile.display()));
        let link = |kind: &[&str]| {
            let mut argv = vec!["rustc", "--crate-name", "foo"];
            argv.extend_from_slice(kind);
            argv.extend_from_slice(&["-g", "--out-dir", out_dir.to_str().unwrap(), "src/lib.rs"]);
            RustcCompiler::new().parse(&s(&argv)).unwrap()
        };

        // The last field says whether the adaptive lane keeps the prefix.
        let outputs: [(&str, &[&str], bool); 5] = [
            ("bin", &["--crate-type", "bin"], false),
            ("test harness", &["--test"], false),
            ("proc-macro", &["--crate-type", "proc-macro"], true),
            ("dylib", &["--crate-type", "dylib"], true),
            ("cdylib", &["--crate-type", "cdylib"], true),
        ];
        for (name, kind, adaptive_keeps_prefix) in outputs {
            let parsed = link(kind);
            let flag = |lane| macos_oso_prefix_flag_inner(&parsed, &parsed.all_args, lane);
            assert_eq!(flag(LinkLane::Cache), prefixed, "a cached {name}");
            let adaptive = if adaptive_keeps_prefix {
                prefixed.clone()
            } else {
                None
            };
            assert_eq!(flag(LinkLane::Adaptive), adaptive, "an adaptive {name}");
            assert_eq!(flag(LinkLane::Passthrough), None, "a passthrough {name}");
        }

        let proc_macro = link(&["--crate-type", "proc-macro"]);
        assert_eq!(
            macos_install_name_flag_inner(&proc_macro, &proc_macro.all_args, LinkLane::Adaptive)
                .as_deref(),
            Some("-Clink-arg=-Wl,-install_name,@rpath/libfoo.dylib"),
            "an adaptive proc macro keeps its checkout-independent install name"
        );
    }

    /// The key reads the root only where kache injects the prefix: a debug
    /// link without a prefix of the caller's own.
    #[test]
    fn oso_prefix_root_for_key_follows_the_injected_prefix() {
        let dir = tempfile::tempdir().unwrap();
        let profile = dir.path().join("target/debug");
        let out_dir = profile.join("deps");
        std::fs::create_dir_all(&out_dir).unwrap();

        let (parsed, _) = debug_bin_args(&out_dir, &[]);
        assert_eq!(
            oso_prefix_root_for_key_inner(&parsed),
            Some(profile.clone())
        );
        let host_root = cfg!(target_os = "macos").then_some(profile);
        assert_eq!(oso_prefix_root_for_key(&parsed), host_root);

        let (user_prefix, _) =
            debug_bin_args(&out_dir, &["-Clink-arg=-Wl,-oso_prefix,/elsewhere/"]);
        assert_eq!(oso_prefix_root_for_key_inner(&user_prefix), None);
    }

    /// Through the trait, the key reads this process's environment and
    /// working directory.
    #[test]
    fn the_trait_key_reads_this_process() {
        let _lock = crate::test_support::process_state_test_lock();
        if std::process::Command::new("rustc")
            .arg("--version")
            .output()
            .is_err()
        {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, "pub fn f() {}\n").unwrap();
        let parsed = RustcArgs::parse(&s(&[
            "rustc",
            "--crate-name",
            "k",
            source.to_str().unwrap(),
            "--emit=dep-info,metadata",
        ]))
        .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: dir.path(),
            key_salt: None,
            key_env_vars: &[],
            extra_inputs_digest: None,
            build_script_inputs_digest: None,
        };
        let compiler = RustcCompiler::new();
        let env = KeyEnv::capture();
        let plain =
            crate::cache_key::compute_cache_key(&parsed, &file_hasher, &path_normalizer, &env)
                .unwrap();
        assert_eq!(compiler.cache_key_in(&parsed, &ctx, &env).0.unwrap(), plain);
        assert_eq!(compiler.cache_key(&parsed, &ctx).unwrap(), plain);
        let salted = KeyCtx {
            key_salt: Some("salt"),
            ..ctx
        };
        assert_ne!(
            compiler.cache_key_in(&parsed, &salted, &env).0.unwrap(),
            plain
        );
    }

    /// The declared inputs fold after the extra inputs under their own
    /// label, and a unit without them keeps its key byte for byte.
    #[test]
    fn finish_key_folds_build_script_inputs_under_their_own_label() {
        let parsed = RustcArgs::parse(&s(&["rustc", "--crate-name", "k", "lib.rs"])).unwrap();
        let file_hasher = crate::cache_key::FileHasher::new();
        let path_normalizer = crate::path_normalizer::PathNormalizer::empty();
        let base = KeyCtx {
            file_hasher: &file_hasher,
            path_normalizer: &path_normalizer,
            cache_dir: std::path::Path::new("/cache"),
            key_salt: None,
            key_env_vars: &[],
            extra_inputs_digest: None,
            build_script_inputs_digest: None,
        };
        let key = "0".repeat(64);
        assert_eq!(finish_key(&parsed, &base, key.clone()), key);
        let declared = KeyCtx {
            build_script_inputs_digest: Some("d1"),
            ..base
        };
        let folded = finish_key(&parsed, &declared, key.clone());
        assert_eq!(
            folded,
            crate::cache_key::fold_labeled(key.clone(), "build_script_inputs", "d1")
        );
        let extra = KeyCtx {
            extra_inputs_digest: Some("d1"),
            ..base
        };
        assert_ne!(folded, finish_key(&parsed, &extra, key.clone()));
        let both = KeyCtx {
            extra_inputs_digest: Some("e1"),
            build_script_inputs_digest: Some("d1"),
            ..base
        };
        assert_eq!(
            finish_key(&parsed, &both, key.clone()),
            crate::cache_key::fold_labeled(
                crate::cache_key::fold_labeled(key, "extra_inputs", "e1"),
                "build_script_inputs",
                "d1"
            )
        );
    }

    /// `kache explain` sees the declared inputs as their own key group.
    #[test]
    fn the_declared_inputs_are_a_key_group() {
        let _lock = crate::test_support::process_state_test_lock();
        if std::process::Command::new("rustc")
            .arg("--version")
            .output()
            .is_err()
        {
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("lib.rs");
        std::fs::write(&source, "pub fn f() {}\n").unwrap();
        let parsed = RustcArgs::parse(&s(&[
            "rustc",
            "--crate-name",
            "k",
            source.to_str().unwrap(),
            "--emit=dep-info,metadata",
        ]))
        .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: dir.path(),
            key_salt: None,
            key_env_vars: &[],
            extra_inputs_digest: None,
            build_script_inputs_digest: None,
        };
        let env = KeyEnv::capture();
        let compiler = RustcCompiler::new();
        let (plain, outputs) = compiler.cache_key_in(&parsed, &ctx, &env);
        let fields = outputs.fields.expect("the whole key was hashed");
        assert!(!fields.contains_key("build_script_inputs"));
        let digest = "0123456789abcdef0123456789abcdef";
        let declared = KeyCtx {
            build_script_inputs_digest: Some(digest),
            ..ctx
        };
        let (key, outputs) = compiler.cache_key_in(&parsed, &declared, &env);
        let declared_fields = outputs.fields.expect("the whole key was hashed");
        assert_eq!(
            declared_fields
                .get("build_script_inputs")
                .map(String::as_str),
            Some("0123456789abcdef")
        );
        assert_ne!(key.unwrap(), plain.unwrap());
        let mut others = declared_fields.clone();
        others.remove("build_script_inputs");
        assert_eq!(others, fields, "no other group moves");
    }
}