mbx-cache-cc 0.10.2

mbx internals: conservative C and C++ action analysis and key construction. No API stability -- use the mbx CLI or mbx-cache-protocol.
Documentation
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
//! Conservative parsing and action-key construction for C and C++ compiles.
//!
//! Cargo build scripts using the `cc` crate compile C and C++ through a
//! gcc-style driver. This adapter models the narrow shape those build scripts
//! produce -- one source, one object, `-c` -- and rejects everything else. As
//! in the rustc adapter, callers should treat [`CcBypassReason`] as a safe
//! cache bypass: run the real compiler and publish nothing.
//!
//! Two properties separate this adapter from a traditional compiler cache.
//! Preprocessor inputs are discovered from a depfile the adapter injects
//! itself, so the key names the headers the compilation actually read; and the
//! directories those headers were searched from contribute a name manifest, so
//! a header that newly *shadows* one of them changes the key even though every
//! previously-read file is byte-identical.
//!
//! Path mappings are shared with the rustc adapter so both agree on which host
//! roots are checkout-specific.
#![deny(missing_docs)]

use mbx_cache_core::{
    CacheDigest, FileDigestCache, PathMapping, PathNormalizationError, canonical_json,
    normalize_mapped_path,
};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use thiserror::Error;

mod depfile;

pub use depfile::{CcDepfile, CcDiscoveredInputs, INCLUDE_MANIFEST_PREFIX, manifest_snapshot};

/// Schema version embedded in canonical cc action descriptors.
pub const ACTION_SCHEMA_VERSION: u8 = 1;
/// Version of the cc argument and input model used to construct keys.
pub const ADAPTER_VERSION: u8 = 1;

/// Maximum discovered inputs, including include-manifest entries.
pub const MAX_PREDICTED_INPUTS: usize = 16 * 1024;
/// Maximum total bytes digested for one action.
pub const MAX_INPUT_BYTES: u64 = 2 * 1024 * 1024 * 1024;
/// Maximum file names summarized across all include manifests.
pub const MAX_MANIFEST_ENTRIES: usize = 16 * 1024;

/// Environment variables whose values enter every cc action key.
///
/// These change the compiler's own behavior without appearing in argv. They
/// are recorded even when unset, so setting one is distinguishable from
/// leaving it unset.
pub const KEYED_ENVIRONMENT: &[&str] = &[
    "IPHONEOS_DEPLOYMENT_TARGET",
    "LANG",
    "LC_ALL",
    "LC_MESSAGES",
    "MACOSX_DEPLOYMENT_TARGET",
    "SDKROOT",
    "SOURCE_DATE_EPOCH",
    "TVOS_DEPLOYMENT_TARGET",
    "WATCHOS_DEPLOYMENT_TARGET",
    "XROS_DEPLOYMENT_TARGET",
];

/// Environment variables that force a bypass when set.
///
/// Each one either injects search paths the argv model cannot see, redirects
/// sub-tool resolution beneath the identity probe, or makes the driver write an
/// output the adapter does not model.
pub const BYPASS_ENVIRONMENT: &[&str] = &[
    "CPATH",
    "COMPILER_PATH",
    "CPLUS_INCLUDE_PATH",
    "C_INCLUDE_PATH",
    "DEPENDENCIES_OUTPUT",
    "GCC_EXEC_PREFIX",
    "OBJC_INCLUDE_PATH",
    "SUNPRO_DEPENDENCIES",
];

/// Absolute roots whose contents are keyed verbatim rather than through a
/// placeholder.
///
/// Files beneath these roots are still digested; keying the path verbatim only
/// declares that the path itself is a machine property rather than a
/// checkout-specific one, which is what makes system headers shareable between
/// worktrees on one machine.
pub const SYSTEM_ROOTS: &[&str] = &[
    "/Applications/Xcode.app",
    "/Library/Developer",
    "/nix/store",
    "/usr/include",
    "/usr/lib",
    "/usr/local/include",
];

const SUPPORTED_F_FLAGS: &[&str] = &[
    "PIC",
    "PIE",
    "asynchronous-unwind-tables",
    "color-diagnostics",
    "data-sections",
    "diagnostics-color",
    "exceptions",
    "function-sections",
    "merge-all-constants",
    "no-asynchronous-unwind-tables",
    "no-builtin",
    "no-common",
    "no-exceptions",
    "no-omit-frame-pointer",
    "no-plt",
    "no-rtti",
    "no-strict-aliasing",
    "omit-frame-pointer",
    "pic",
    "pie",
    "rtti",
    "short-enums",
    "signed-char",
    "stack-protector",
    "stack-protector-all",
    "stack-protector-strong",
    "strict-aliasing",
    "unsigned-char",
    "visibility",
    "visibility-inlines-hidden",
    "wrapv",
];

const SUPPORTED_M_FLAGS: &[&str] = &[
    "32",
    "64",
    "arch",
    "arm",
    "avx",
    "avx2",
    "cpu",
    "float-abi",
    "fma",
    "fpu",
    "iphoneos-version-min",
    "macosx-version-min",
    "no-omit-leaf-frame-pointer",
    "omit-leaf-frame-pointer",
    "sse",
    "sse2",
    "sse3",
    "sse4.1",
    "sse4.2",
    "thumb",
    "tune",
];

const SUPPORTED_O_FLAGS: &[&str] = &[
    "-O", "-O0", "-O1", "-O2", "-O3", "-Ofast", "-Og", "-Os", "-Oz",
];

const SUPPORTED_G_FLAGS: &[&str] = &[
    "-g",
    "-g0",
    "-g1",
    "-g2",
    "-g3",
    "-gdwarf-2",
    "-gdwarf-3",
    "-gdwarf-4",
    "-gdwarf-5",
];

const SUPPORTED_BARE_FLAGS: &[&str] = &[
    "-ansi",
    "-nostdinc",
    "-nostdinc++",
    "-pedantic",
    "-pedantic-errors",
    "-pipe",
    "-pthread",
    "-w",
];

const SEPARATE_PATH_FLAGS: &[&str] = &[
    "-idirafter",
    "-imacros",
    "-include",
    "-iquote",
    "-isysroot",
    "-isystem",
];

const TOOL_PASSTHROUGH_FLAGS: &[&str] = &["-Xassembler", "-Xclang", "-Xlinker", "-Xpreprocessor"];

const COMPILER_QUERY_FLAGS: &[&str] = &[
    "--help",
    "--version",
    "-###",
    // The `cc` crate probes with `-?` to tell an MSVC-style driver from a
    // gcc-style one; neither answer is a compilation.
    "-?",
    "-dumpmachine",
    "-dumpversion",
    "-v",
];

/// Flags that rewrite a path prefix in the compiler's own output.
///
/// The left side is a real path and normalizes like any other; the right side
/// is the text it is replaced with and enters the key verbatim.
const PREFIX_MAP_FLAGS: &[&str] = &[
    "-fdebug-prefix-map",
    "-ffile-prefix-map",
    "-fmacro-prefix-map",
];

impl CcBypassReason {
    /// A stable, low-cardinality name for this reason.
    ///
    /// Many variants carry a path or a flag, so `Display` text cannot be
    /// aggregated; statistics group by this instead.
    pub fn kind(&self) -> &'static str {
        self.into()
    }

    /// A concrete change that can make this invocation cacheable, when one is
    /// available.
    ///
    /// Expected compiler probes and failures that require adapter support
    /// return `None`; callers can still explain those from
    /// [`CcBypassReason::kind`].
    pub fn remediation(&self) -> Option<&'static str> {
        match self {
            Self::UnsupportedEnvironment(_) => Some(
                "Unset the reported environment variable for this build so the compiler invocation describes all of its inputs.",
            ),
            Self::LocalCpuTarget(_) => Some(
                "Replace the reported local-CPU option with an explicit architecture or CPU name.",
            ),
            Self::EmbeddedTimestampMacro(_) => Some(
                "Remove the reported timestamp macro, or keep this compilation uncached if its changing value is intentional.",
            ),
            Self::SearchPathModifiedDuringCompilation(_) => Some(
                "Generate headers before compilation instead of changing an include directory while the compiler is running.",
            ),
            Self::UnknownFlag(_) | Self::ToolPassthrough(_) => Some(
                "Remove the reported compiler option, or upgrade mbx if the option should be modeled.",
            ),
            Self::UnmappedAbsolutePath(_) => Some(
                "Move the input under a mapped project or system root, or keep this compilation uncached.",
            ),
            _ => None,
        }
    }
}

/// Reason a C or C++ invocation cannot safely use the action cache.
///
/// A bypass is an expected conservative outcome, not a compiler error. Match on
/// [`CcBypassReason::kind`] for aggregation rather than on the variants.
#[derive(Debug, Clone, PartialEq, Eq, Error, strum::IntoStaticStr)]
#[strum(serialize_all = "kebab-case")]
#[non_exhaustive]
pub enum CcBypassReason {
    /// An argument cannot be represented in the canonical UTF-8 key.
    #[error("compiler argument {index} is not valid UTF-8")]
    NonUtf8Argument {
        /// Zero-based index in the argument slice.
        index: usize,
    },
    /// The driver was handed an argument file.
    #[error("compiler response file is not modeled by the cache adapter: {0}")]
    ResponseFile(String),
    /// A compiler flag is not modeled by this adapter version.
    #[error("compiler flag is not modeled by the cache adapter: {0}")]
    UnknownFlag(String),
    /// A recognized flag was given without its value.
    #[error("compiler flag {0} is missing its value")]
    MissingValue(String),
    /// The invocation asks the driver about itself rather than compiling.
    #[error("compiler invocation queries the driver instead of compiling")]
    CompilerQuery,
    /// The invocation is not a single-object compile.
    #[error("compiler invocation does not compile with -c")]
    NotACompile,
    /// The invocation emits preprocessed source or assembly.
    #[error("compiler invocation emits a non-object output: {0}")]
    NonObjectOutput(String),
    /// The source arrives on standard input and cannot be rediscovered.
    #[error("compiler invocation reads its source from standard input")]
    StandardInput,
    /// No source file was given.
    #[error("compiler invocation names no source file")]
    MissingInput,
    /// More than one source file was given.
    #[error("compiler invocation names more than one source file")]
    MultipleInputs,
    /// No `-o` was given, so the object name follows driver defaults.
    #[error("compiler invocation names no output file")]
    MissingOutput,
    /// The source language is outside the modeled set.
    #[error("compiler input language is not modeled by the cache adapter: {0}")]
    UnsupportedLanguage(String),
    /// The caller asked for its own dependency output.
    #[error("compiler invocation requests its own dependency output: {0}")]
    CallerDependencyFlags(String),
    /// Precompiled headers are not byte-hermetic key material.
    #[error("precompiled headers are not modeled by the cache adapter: {0}")]
    PrecompiledHeader(String),
    /// Coverage instrumentation writes outputs beside the object.
    #[error("coverage instrumentation is not modeled by the cache adapter: {0}")]
    CoverageInstrumentation(String),
    /// Split debug info writes a `.dwo` beside the object.
    #[error("split debug output is not modeled by the cache adapter: {0}")]
    SplitDebugOutput(String),
    /// Temporary files are preserved beside the object.
    #[error("preserved temporaries are not modeled by the cache adapter: {0}")]
    SaveTemps(String),
    /// An option is smuggled to a sub-tool the adapter cannot model.
    #[error("compiler flag forwards options to another tool: {0}")]
    ToolPassthrough(String),
    /// A compiler plugin makes the output depend on unmodeled code.
    #[error("compiler plugins are not modeled by the cache adapter: {0}")]
    Plugin(String),
    /// An include search directory gained or lost a header while the compiler
    /// ran, so the manifest recorded after it is not what the compilation saw.
    #[error("include search directory changed during the compilation: {0}")]
    SearchPathModifiedDuringCompilation(PathBuf),

    /// The object kept a path the key normalized away.
    ///
    /// Remapping covers what the compiler records itself; a path the source
    /// keeps as a string survives it, and publishing such an object would
    /// share this checkout's directory under a key that says it does not
    /// matter.
    #[error("compilation output records a path its key normalized away: {0}")]
    UnportableOutput(PathBuf),
    /// The object depends on the machine's own CPU rather than on named inputs.
    #[error("compiler flag tunes for the local CPU: {0}")]
    LocalCpuTarget(String),
    /// The driver is not a gcc-style or clang-style compiler.
    #[error("compiler driver is not modeled by the cache adapter: {0}")]
    UnsupportedCompilerDriver(String),
    /// The identity probe could not be run or parsed.
    #[error("could not establish compiler identity: {0}")]
    CompilerIdentityUnavailable(String),
    /// An environment variable outside the modeled set is set.
    #[error("environment variable {0} changes the compilation in an unmodeled way")]
    UnsupportedEnvironment(String),
    /// The shim could not be told which real compiler to run.
    #[error("no real compiler was pinned for the cc shim")]
    RealCompilerUnpinned,
    /// A read file expands a timestamp macro, so the object is not a function
    /// of its inputs.
    #[error("input expands a timestamp macro: {0}")]
    EmbeddedTimestampMacro(PathBuf),
    /// The injected depfile could not be parsed exactly.
    #[error("could not model the compiler depfile: {0}")]
    MalformedDepfile(String),
    /// The injected depfile could not be read.
    #[error("could not read the compiler depfile {path}: {message}")]
    DepfileRead {
        /// Depfile that could not be read.
        path: PathBuf,
        /// Underlying error text.
        message: String,
    },
    /// The action exceeds an input, byte, or manifest bound.
    #[error("compilation reads more inputs than the cache adapter models")]
    TooManyInputs,
    /// An absolute path lies outside every mapped and system root.
    #[error("path is outside every modeled root: {0}")]
    UnmappedAbsolutePath(PathBuf),
    /// A path cannot be represented in the canonical UTF-8 key.
    #[error("path is not valid UTF-8: {0}")]
    NonUtf8Path(PathBuf),
    /// The compiler working directory is not absolute.
    #[error("compiler working directory is not absolute: {0}")]
    RelativeWorkingDirectory(PathBuf),
    /// A configured path mapping root is not absolute.
    #[error("path mapping root is not absolute: {0}")]
    RelativePathMapping(PathBuf),
    /// A configured placeholder is empty, duplicated, or not a bare name.
    #[error("invalid path mapping placeholder: {0}")]
    InvalidPathPlaceholder(String),
    /// A required input never appeared among the discovered inputs.
    #[error("required input is missing from the discovered inputs: {0}")]
    MissingRequiredInput(String),
    /// An input digest is malformed.
    #[error("invalid digest for input: {0}")]
    InvalidInputDigest(String),
    /// One normalized path carries two different digests.
    #[error("conflicting digests for input: {0}")]
    ConflictingInput(String),
    /// An input could not be read.
    #[error("could not read input {path}: {message}")]
    InputRead {
        /// Input that could not be read.
        path: PathBuf,
        /// Underlying error text.
        message: String,
    },
    /// An input changed between discovery and publication.
    #[error("input changed during the compilation: {0}")]
    InputChanged(PathBuf),
    /// An input was written while the compiler ran.
    #[error("input was modified during the compilation: {0}")]
    InputModifiedDuringCompilation(PathBuf),
    /// Discovery and the action disagree about the working directory.
    #[error("discovered inputs use a different working directory")]
    DiscoveryWorkingDirectory,
    /// A prediction uses a schema this adapter version does not model.
    #[error("action prediction is not modeled by this adapter version")]
    UnsupportedPrediction,
    /// A predicted input name cannot be resolved back to a host path.
    #[error("invalid predicted input: {0}")]
    InvalidPredictedInput(String),
    /// Canonical serialization failed.
    #[error("could not serialize the action descriptor: {0}")]
    Serialization(String),
}

impl From<PathNormalizationError> for CcBypassReason {
    fn from(reason: PathNormalizationError) -> Self {
        match reason {
            PathNormalizationError::UnmappedAbsolutePath(path) => Self::UnmappedAbsolutePath(path),
            PathNormalizationError::NonUtf8Path(path) => Self::NonUtf8Path(path),
        }
    }
}

/// Source language a driver invocation compiles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CcLanguage {
    /// C, driven through `CC`.
    C,
    /// C++, driven through `CXX`.
    Cxx,
}

impl CcLanguage {
    /// Shim file stem that selects this language.
    pub fn shim_stem(self) -> &'static str {
        match self {
            Self::C => "mbx-cc",
            Self::Cxx => "mbx-cxx",
        }
    }

    /// Default driver name to fall back to when no real compiler is pinned.
    pub fn default_driver(self) -> &'static str {
        if cfg!(windows) {
            return "cl.exe";
        }
        match self {
            Self::C => "cc",
            Self::Cxx => "c++",
        }
    }
}

/// Compiler family, which decides how the identity is assembled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CcCompilerFamily {
    /// GCC, which compiles objects through an external assembler.
    Gcc,
    /// Upstream LLVM clang.
    Clang,
    /// Apple's clang distribution.
    AppleClang,
    /// Microsoft's `cl.exe` driver.
    #[cfg(windows)]
    Msvc,
}

impl CcCompilerFamily {
    /// Stable name recorded in the action key.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Gcc => "gcc",
            Self::Clang => "clang",
            Self::AppleClang => "apple-clang",
            #[cfg(windows)]
            Self::Msvc => "msvc",
        }
    }

    /// Whether objects are produced through a separate assembler binary whose
    /// version therefore belongs in the identity.
    pub fn uses_external_assembler(self) -> bool {
        matches!(self, Self::Gcc)
    }

    /// Whether this is Microsoft's `cl.exe` driver.
    pub fn is_msvc(self) -> bool {
        #[cfg(windows)]
        {
            matches!(self, Self::Msvc)
        }
        #[cfg(not(windows))]
        {
            false
        }
    }

    /// Classify a driver from its verbose probe output.
    pub fn classify(probe: &str) -> Result<Self, CcBypassReason> {
        #[cfg(windows)]
        if probe.contains("Microsoft (R) C/C++ Optimizing Compiler") {
            return Ok(Self::Msvc);
        }
        if probe.contains("Apple clang version") {
            Ok(Self::AppleClang)
        } else if probe.contains("clang version") {
            Ok(Self::Clang)
        } else if probe.contains("gcc version") {
            Ok(Self::Gcc)
        } else {
            Err(CcBypassReason::UnsupportedCompilerDriver(
                probe.lines().next().unwrap_or_default().into(),
            ))
        }
    }
}

/// Compiler properties that distinguish incompatible objects.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CcCompilerIdentity {
    /// Driver family.
    pub family: CcCompilerFamily,
    /// Complete verbose probe output, verbatim.
    pub version_text: String,
    /// Target triple the driver reports.
    pub target: String,
    /// Resolved assembler and its version, for families that use one.
    ///
    /// GCC assembles through binutils, whose version changes object bytes
    /// without changing anything `gcc -v` prints. Clang assembles internally,
    /// so this is empty there.
    pub assembler: String,
}

/// One file input paired with the digest used in the action key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CcActionInput {
    /// Absolute host path used to read and verify the input, or an
    /// include-manifest pseudo-path.
    pub path: PathBuf,
    /// Digest of the input contents, or of the directory's name manifest.
    pub digest: CacheDigest,
}

/// External information needed to construct a canonical cc action.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CcActionContext {
    /// Identity of the compiler that produces the object.
    pub compiler: CcCompilerIdentity,
    /// Absolute directory in which the compiler runs.
    pub working_dir: PathBuf,
    /// Host roots replaced with stable placeholders in the key.
    pub path_mappings: Vec<PathMapping>,
    /// Environment inputs and their observed values.
    pub environment: BTreeMap<String, Option<String>>,
    /// Complete set of direct and discovered file inputs.
    pub inputs: Vec<CcActionInput>,
}

/// Canonical action descriptor and its content digest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CcAction {
    /// Digest of `bytes`, used as the action-cache key.
    pub digest: CacheDigest,
    /// Canonical serialized action descriptor.
    pub bytes: Vec<u8>,
}

#[derive(Debug, Serialize)]
struct CcCompilerDescriptor {
    assembler: String,
    family: String,
    target: String,
    version_text: String,
}

#[derive(Debug, Serialize)]
struct CcInputDescriptor {
    digest: CacheDigest,
    path: String,
}

#[derive(Debug, Serialize)]
struct CcActionDescriptor {
    version: u8,
    kind: &'static str,
    adapter_version: u8,
    compiler: CcCompilerDescriptor,
    arguments: Vec<String>,
    environment: BTreeMap<String, Option<String>>,
    inputs: Vec<CcInputDescriptor>,
}

#[derive(Debug, Serialize)]
struct CcInvocationDescriptor {
    version: u8,
    kind: &'static str,
    adapter_version: u8,
    compiler: CcCompilerDescriptor,
    arguments: Vec<String>,
    required_inputs: Vec<String>,
}

/// Normalized input names from the last successful execution of one modeled
/// compile.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CcInputPrediction {
    /// Prediction schema version.
    pub version: u8,
    /// Normalized input paths, including include-manifest entries.
    pub inputs: Vec<String>,
    /// Names of environment variables that entered the key.
    pub environment: Vec<String>,
    /// Compiler wall time from the successful invocation that produced this
    /// prediction. Zero means no timing hint was recorded.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub compiler_duration_ns: u64,
    /// Source file name associated with the timing hint.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub source_name: String,
}

fn is_zero(value: &u64) -> bool {
    *value == 0
}

/// One parsed and admitted argument.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Argument {
    /// Keyed verbatim.
    Plain(String),
    /// Keyed with its path normalized.
    Path { flag: String, path: PathBuf },
    /// A prefix rewrite: the source path normalizes, the replacement does not.
    PrefixMap {
        flag: String,
        from: PathBuf,
        to: String,
    },
    /// The source file.
    Source(PathBuf),
}

/// A parsed, admitted C or C++ compile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CcInvocation {
    arguments: Vec<Argument>,
    source: PathBuf,
    output: PathBuf,
    include_dirs: Vec<PathBuf>,
    required_inputs: Vec<PathBuf>,
    language: CcLanguage,
    sysroot: Option<PathBuf>,
}

impl CcInvocation {
    /// Parse a driver command line, admitting only modeled single-object
    /// compiles.
    pub fn parse(arguments: &[OsString]) -> Result<Self, CcBypassReason> {
        Parser::new(arguments).parse()
    }

    /// Parse a command line using the syntax of `family`.
    pub fn parse_for(
        arguments: &[OsString],
        family: CcCompilerFamily,
    ) -> Result<Self, CcBypassReason> {
        if family.is_msvc() {
            MsvcParser::new(arguments).parse()
        } else {
            Self::parse(arguments)
        }
    }

    /// Parse a command line using Microsoft `cl.exe` syntax.
    pub fn parse_msvc(arguments: &[OsString]) -> Result<Self, CcBypassReason> {
        MsvcParser::new(arguments).parse()
    }

    /// Source file this invocation compiles.
    pub fn source(&self) -> &Path {
        &self.source
    }

    /// Object file this invocation produces.
    pub fn output(&self) -> &Path {
        &self.output
    }

    /// Include search directories named on the command line, in order.
    pub fn include_dirs(&self) -> &[PathBuf] {
        &self.include_dirs
    }

    /// Files that must appear among the discovered inputs.
    pub fn required_inputs(&self) -> &[PathBuf] {
        &self.required_inputs
    }

    /// Language the driver compiles.
    pub fn language(&self) -> CcLanguage {
        self.language
    }

    /// Sysroot named on the command line, if any.
    pub fn sysroot(&self) -> Option<&Path> {
        self.sysroot.as_deref()
    }

    /// Short label used for timing statistics.
    pub fn source_name(&self) -> String {
        self.source
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_default()
    }

    /// Arguments to append so the driver writes a dependency list beside the
    /// object.
    ///
    /// `-MD` rather than `-MMD`: system headers are exactly the inputs most
    /// likely to change without any other key component noticing, because the
    /// compiler identity does not cover the C library or the platform SDK.
    pub fn dependency_arguments(&self, depfile: &Path) -> Vec<OsString> {
        vec!["-MD".into(), "-MF".into(), depfile.into()]
    }

    /// Arguments to append so a driver from `family` writes its dependency
    /// list beside the object.
    pub fn dependency_arguments_for(
        &self,
        depfile: &Path,
        family: CcCompilerFamily,
    ) -> Vec<OsString> {
        if family.is_msvc() {
            vec!["/sourceDependencies".into(), depfile.into()]
        } else {
            self.dependency_arguments(depfile)
        }
    }

    /// Arguments to append so `cl.exe` writes `/sourceDependencies` JSON.
    pub fn msvc_dependency_arguments(&self, depfile: &Path) -> Vec<OsString> {
        vec!["/sourceDependencies".into(), depfile.into()]
    }

    /// Digest of the pre-input fingerprint, used to look up a prediction.
    pub fn invocation_digest(
        &self,
        context: &CcActionContext,
    ) -> Result<CacheDigest, CcBypassReason> {
        let builder = ActionBuilder::new(self, context.clone());
        let descriptor = builder.invocation_descriptor()?;
        let bytes = canonical_json(&descriptor)
            .map_err(|error| CcBypassReason::Serialization(error.to_string()))?;
        Ok(CacheDigest::blake3(&bytes))
    }

    /// Build the canonical action for this invocation and its discovered
    /// inputs.
    pub fn action(&self, context: CcActionContext) -> Result<CcAction, CcBypassReason> {
        ActionBuilder::new(self, context).build()
    }

    /// Record the normalized inputs of a successful compile so the next cold
    /// invocation can rebuild the same key before compiling.
    pub fn prediction(
        &self,
        context: &CcActionContext,
        compiler_duration_ns: u64,
    ) -> Result<CcInputPrediction, CcBypassReason> {
        let builder = ActionBuilder::new(self, context.clone());
        let mut inputs = context
            .inputs
            .iter()
            .map(|input| builder.normalize_input_path(&input.path))
            .collect::<Result<Vec<_>, _>>()?;
        inputs.sort();
        inputs.dedup();
        Ok(CcInputPrediction {
            version: 1,
            inputs,
            environment: context.environment.keys().cloned().collect(),
            compiler_duration_ns,
            source_name: self.source_name(),
        })
    }
}

impl CcInputPrediction {
    /// Rehash the predicted paths and recompute include manifests. The caller
    /// still recomputes the full action digest, so changed inputs are misses.
    pub fn discover(
        &self,
        working_dir: &Path,
        path_mappings: &[PathMapping],
        digests: &dyn FileDigestCache,
    ) -> Result<CcDiscoveredInputs, CcBypassReason> {
        if self.version != 1 {
            return Err(CcBypassReason::UnsupportedPrediction);
        }
        if self.inputs.len() > MAX_PREDICTED_INPUTS || self.environment.len() > 4 * 1024 {
            return Err(CcBypassReason::UnsupportedPrediction);
        }
        let mappings = PathMapping::ordered(path_mappings);
        let mut files = BTreeSet::new();
        let mut directories = BTreeSet::new();
        for entry in &self.inputs {
            match entry.strip_prefix(INCLUDE_MANIFEST_PREFIX) {
                Some(directory) => {
                    directories.insert(denormalize_path(directory, &mappings)?);
                }
                None => {
                    files.insert(denormalize_path(entry, &mappings)?);
                }
            }
        }
        CcDiscoveredInputs::collect(working_dir, files, directories, digests)
    }
}

/// Resolve a normalized key path back to a host path.
///
/// Placeholder entries expand through their mapping; a verbatim entry is
/// accepted only when it still lies beneath an admitted system root, so a
/// prediction cannot name an arbitrary absolute path.
fn denormalize_path(value: &str, mappings: &[PathMapping]) -> Result<PathBuf, CcBypassReason> {
    for mapping in mappings {
        let prefix = format!("${{{}}}", mapping.placeholder);
        let suffix = if value == prefix {
            ""
        } else if let Some(suffix) = value.strip_prefix(&format!("{prefix}/")) {
            suffix
        } else {
            continue;
        };
        if !mapping.root.is_absolute() || !safe_suffix(suffix) {
            return Err(CcBypassReason::InvalidPredictedInput(value.into()));
        }
        let mut path = normalize_components(&mapping.root);
        path.extend(suffix.split('/').filter(|component| !component.is_empty()));
        return Ok(path);
    }
    // A verbatim entry names a machine path rather than a placeholder. It is
    // admitted only beneath a system root, and only spelled literally: a
    // traversal component would let a prediction reach outside that root.
    let path = PathBuf::from(value);
    if path.is_absolute() && is_system_path(&path) && normalize_components(&path) == path {
        return Ok(path);
    }
    Err(CcBypassReason::InvalidPredictedInput(value.into()))
}

fn safe_suffix(suffix: &str) -> bool {
    suffix.is_empty()
        || !suffix.split('/').any(|component| {
            component.is_empty() || matches!(component, "." | "..") || component.contains('\\')
        })
}

/// Whether a path lies beneath a root whose location is a machine property.
pub fn is_system_path(path: &Path) -> bool {
    SYSTEM_ROOTS
        .iter()
        .any(|root| path.starts_with(Path::new(root)))
}

fn normalize_components(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
            component => normalized.push(component.as_os_str()),
        }
    }
    normalized
}

/// Read the modeled environment, rejecting variables that change the compile in
/// a way the argv model cannot see.
pub fn environment_inputs<F>(
    lookup: F,
    sysroot: Option<&Path>,
) -> Result<BTreeMap<String, Option<String>>, CcBypassReason>
where
    F: Fn(&str) -> Option<String>,
{
    environment_inputs_for(lookup, sysroot, CcCompilerFamily::Clang)
}

/// Read the modeled environment for a particular compiler family.
pub fn environment_inputs_for<F>(
    lookup: F,
    sysroot: Option<&Path>,
    family: CcCompilerFamily,
) -> Result<BTreeMap<String, Option<String>>, CcBypassReason>
where
    F: Fn(&str) -> Option<String>,
{
    for name in BYPASS_ENVIRONMENT {
        if lookup(name).is_some() {
            return Err(CcBypassReason::UnsupportedEnvironment((*name).into()));
        }
    }
    let mut environment = BTreeMap::new();
    for name in KEYED_ENVIRONMENT {
        // An explicit `-isysroot` on the command line already pins the SDK, and
        // it is what the driver honors, so the variable stops being an input.
        if *name == "SDKROOT" && sysroot.is_some() {
            continue;
        }
        environment.insert((*name).to_string(), lookup(name));
    }
    if family.is_msvc() {
        // INCLUDE changes header resolution without appearing in argv. The
        // toolset and SDK versions make the otherwise machine-local paths
        // meaningful when action records move between hosts.
        for name in [
            "INCLUDE",
            "VCToolsVersion",
            "WindowsSDKVersion",
            "UCRTVersion",
        ] {
            environment.insert(name.into(), lookup(name));
        }
        for name in ["CL", "_CL_"] {
            if lookup(name).is_some() {
                return Err(CcBypassReason::UnsupportedEnvironment(name.into()));
            }
        }
    }
    Ok(environment)
}

struct ActionBuilder<'a> {
    invocation: &'a CcInvocation,
    context: CcActionContext,
    mappings: Vec<PathMapping>,
}

impl<'a> ActionBuilder<'a> {
    fn new(invocation: &'a CcInvocation, mut context: CcActionContext) -> Self {
        context.path_mappings = PathMapping::ordered(&context.path_mappings);
        let mappings = context.path_mappings.clone();
        Self {
            invocation,
            context,
            mappings,
        }
    }

    fn build(self) -> Result<CcAction, CcBypassReason> {
        self.validate_mappings()?;
        let invocation = self.invocation_descriptor()?;

        let mut inputs = BTreeMap::<String, CacheDigest>::new();
        for input in &self.context.inputs {
            input.digest.validate().map_err(|_| {
                CcBypassReason::InvalidInputDigest(input.path.display().to_string())
            })?;
            let path = self.normalize_input_path(&input.path)?;
            if inputs
                .insert(path.clone(), input.digest.clone())
                .is_some_and(|existing| existing != input.digest)
            {
                return Err(CcBypassReason::ConflictingInput(path));
            }
        }
        let required = self
            .invocation
            .required_inputs
            .iter()
            .map(|path| self.normalize_path(path))
            .collect::<Result<BTreeSet<_>, _>>()?;
        if let Some(missing) = required.iter().find(|path| !inputs.contains_key(*path)) {
            return Err(CcBypassReason::MissingRequiredInput(missing.clone()));
        }
        let inputs = inputs
            .into_iter()
            .map(|(path, digest)| CcInputDescriptor { path, digest })
            .collect();
        let descriptor = CcActionDescriptor {
            version: ACTION_SCHEMA_VERSION,
            kind: "cc",
            adapter_version: ADAPTER_VERSION,
            compiler: invocation.compiler,
            arguments: invocation.arguments,
            environment: self.context.environment.clone(),
            inputs,
        };
        let bytes = canonical_json(&descriptor)
            .map_err(|error| CcBypassReason::Serialization(error.to_string()))?;
        let digest = CacheDigest::blake3(&bytes);
        Ok(CcAction { digest, bytes })
    }

    fn invocation_descriptor(&self) -> Result<CcInvocationDescriptor, CcBypassReason> {
        self.validate_mappings()?;
        let arguments = self
            .invocation
            .arguments
            .iter()
            .map(|argument| self.normalize_argument(argument))
            .collect::<Result<Vec<_>, _>>()?;
        let required_inputs = self
            .invocation
            .required_inputs
            .iter()
            .map(|path| self.normalize_path(path))
            .collect::<Result<BTreeSet<_>, _>>()?
            .into_iter()
            .collect();
        Ok(CcInvocationDescriptor {
            version: ACTION_SCHEMA_VERSION,
            kind: "cc",
            adapter_version: ADAPTER_VERSION,
            compiler: self.compiler_descriptor(),
            arguments,
            required_inputs,
        })
    }

    fn compiler_descriptor(&self) -> CcCompilerDescriptor {
        CcCompilerDescriptor {
            assembler: self.context.compiler.assembler.clone(),
            family: self.context.compiler.family.as_str().into(),
            target: self.context.compiler.target.clone(),
            version_text: self.context.compiler.version_text.clone(),
        }
    }

    fn validate_mappings(&self) -> Result<(), CcBypassReason> {
        if !self.context.working_dir.is_absolute() {
            return Err(CcBypassReason::RelativeWorkingDirectory(
                self.context.working_dir.clone(),
            ));
        }
        let mut roots = BTreeSet::new();
        let mut placeholders = BTreeSet::new();
        for mapping in &self.mappings {
            if !mapping.root.is_absolute() {
                return Err(CcBypassReason::RelativePathMapping(mapping.root.clone()));
            }
            if mapping.placeholder.is_empty()
                || !mapping
                    .placeholder
                    .bytes()
                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
                || !roots.insert(normalize_components(&mapping.root))
                || !placeholders.insert(&mapping.placeholder)
            {
                return Err(CcBypassReason::InvalidPathPlaceholder(
                    mapping.placeholder.clone(),
                ));
            }
        }
        Ok(())
    }

    fn normalize_argument(&self, argument: &Argument) -> Result<String, CcBypassReason> {
        match argument {
            Argument::Plain(value) => Ok(value.clone()),
            Argument::Path { flag, path } => Ok(format!("{flag}={}", self.normalize_path(path)?)),
            Argument::PrefixMap { flag, from, to } => {
                Ok(format!("{flag}={}={to}", self.normalize_path(from)?))
            }
            Argument::Source(path) => Ok(self.normalize_path(path)?),
        }
    }

    /// Normalize a path that names a compilation input or search root.
    ///
    /// A path beneath a mapped root becomes a placeholder so equivalent
    /// checkouts agree. A path beneath a system root stays verbatim: its
    /// location is a property of the machine, and its contents are digested
    /// like any other input.
    fn normalize_path(&self, path: &Path) -> Result<String, CcBypassReason> {
        match normalize_mapped_path(path, &self.context.working_dir, &self.mappings) {
            Ok(normalized) => Ok(normalized),
            Err(reason) => {
                let absolute = absolute_path(path, &self.context.working_dir);
                if is_system_path(&absolute) {
                    return absolute
                        .to_str()
                        .map(ToOwned::to_owned)
                        .ok_or_else(|| CcBypassReason::NonUtf8Path(absolute.clone()));
                }
                Err(reason.into())
            }
        }
    }

    fn normalize_input_path(&self, path: &Path) -> Result<String, CcBypassReason> {
        match path.to_str().and_then(|path| {
            path.strip_prefix(INCLUDE_MANIFEST_PREFIX)
                .map(ToOwned::to_owned)
        }) {
            Some(directory) => Ok(format!(
                "{INCLUDE_MANIFEST_PREFIX}{}",
                self.normalize_path(Path::new(&directory))?
            )),
            None => self.normalize_path(path),
        }
    }
}

fn absolute_path(path: &Path, working_dir: &Path) -> PathBuf {
    if path.is_absolute() {
        normalize_components(path)
    } else {
        normalize_components(&working_dir.join(path))
    }
}

struct Parser<'a> {
    arguments: &'a [OsString],
    index: usize,
    parsed: Vec<Argument>,
    source: Option<PathBuf>,
    output: Option<PathBuf>,
    include_dirs: Vec<PathBuf>,
    required_inputs: Vec<PathBuf>,
    sysroot: Option<PathBuf>,
    explicit_language: Option<CcLanguage>,
    compiling: bool,
}

impl<'a> Parser<'a> {
    fn new(arguments: &'a [OsString]) -> Self {
        Self {
            arguments,
            index: 0,
            parsed: Vec::new(),
            source: None,
            output: None,
            include_dirs: Vec::new(),
            required_inputs: Vec::new(),
            sysroot: None,
            explicit_language: None,
            compiling: false,
        }
    }

    fn parse(mut self) -> Result<CcInvocation, CcBypassReason> {
        while self.index < self.arguments.len() {
            let value = self.current()?.to_string();
            self.index += 1;
            if value == "-" {
                return Err(CcBypassReason::StandardInput);
            }
            if let Some(argfile) = value.strip_prefix('@') {
                return Err(CcBypassReason::ResponseFile(argfile.into()));
            }
            if value.starts_with('-') {
                self.parse_flag(&value)?;
            } else {
                self.parse_input(&value)?;
            }
        }

        if !self.compiling {
            return Err(CcBypassReason::NotACompile);
        }
        let source = self.source.clone().ok_or(CcBypassReason::MissingInput)?;
        let output = self.output.clone().ok_or(CcBypassReason::MissingOutput)?;
        let language = self.language(&source)?;
        self.required_inputs.push(source.clone());
        Ok(CcInvocation {
            arguments: self.parsed,
            source,
            output,
            include_dirs: self.include_dirs,
            required_inputs: self.required_inputs,
            language,
            sysroot: self.sysroot,
        })
    }

    fn language(&self, source: &Path) -> Result<CcLanguage, CcBypassReason> {
        if let Some(language) = self.explicit_language {
            return Ok(language);
        }
        let extension = source
            .extension()
            .and_then(|extension| extension.to_str())
            .unwrap_or_default();
        match extension {
            "c" => Ok(CcLanguage::C),
            "cc" | "cpp" | "cxx" | "c++" => Ok(CcLanguage::Cxx),
            _ => Err(CcBypassReason::UnsupportedLanguage(
                source.display().to_string(),
            )),
        }
    }

    fn current(&self) -> Result<&str, CcBypassReason> {
        self.arguments[self.index]
            .to_str()
            .ok_or(CcBypassReason::NonUtf8Argument { index: self.index })
    }

    fn take_value(&mut self, flag: &str, inline: Option<&str>) -> Result<String, CcBypassReason> {
        if let Some(value) = inline
            && !value.is_empty()
        {
            return Ok(value.into());
        }
        if self.index >= self.arguments.len() {
            return Err(CcBypassReason::MissingValue(flag.into()));
        }
        let value = self.current()?.to_string();
        self.index += 1;
        Ok(value)
    }

    fn parse_input(&mut self, value: &str) -> Result<(), CcBypassReason> {
        if self.source.is_some() {
            return Err(CcBypassReason::MultipleInputs);
        }
        let path = PathBuf::from(value);
        // With an explicit `-x`, the driver ignores the extension entirely;
        // without one, the extension is the only thing that decides the
        // language, so an unmodeled extension has to bypass here.
        if self.explicit_language.is_none() {
            let extension = path
                .extension()
                .and_then(|extension| extension.to_str())
                .unwrap_or_default();
            if !matches!(extension, "c" | "cc" | "cpp" | "cxx" | "c++") {
                return Err(CcBypassReason::UnsupportedLanguage(value.into()));
            }
        }
        self.source = Some(path.clone());
        self.parsed.push(Argument::Source(path));
        Ok(())
    }

    fn parse_flag(&mut self, value: &str) -> Result<(), CcBypassReason> {
        if COMPILER_QUERY_FLAGS.contains(&value) || value.starts_with("-print") {
            return Err(CcBypassReason::CompilerQuery);
        }
        if matches!(value, "-E" | "-S") {
            return Err(CcBypassReason::NonObjectOutput(value.into()));
        }
        if value.starts_with("-M") {
            return Err(CcBypassReason::CallerDependencyFlags(value.into()));
        }
        if value.starts_with("-save-temps") {
            return Err(CcBypassReason::SaveTemps(value.into()));
        }
        if value == "--coverage" {
            return Err(CcBypassReason::CoverageInstrumentation(value.into()));
        }
        if TOOL_PASSTHROUGH_FLAGS.contains(&value)
            || value.starts_with("-Wp,")
            || value.starts_with("-Wa,")
            || value.starts_with("-Wl,")
        {
            // The forwarded options are the compilation's real inputs and they
            // are not modeled, so consuming the value would not make this safe.
            return Err(CcBypassReason::ToolPassthrough(value.into()));
        }
        if value.starts_with("-include-pch") || value == "-emit-pch" {
            return Err(CcBypassReason::PrecompiledHeader(value.into()));
        }

        if value == "-c" {
            self.compiling = true;
            self.parsed.push(Argument::Plain(value.into()));
            return Ok(());
        }
        if SUPPORTED_BARE_FLAGS.contains(&value)
            || SUPPORTED_O_FLAGS.contains(&value)
            || SUPPORTED_G_FLAGS.contains(&value)
            || value.starts_with("-std=")
        {
            self.parsed.push(Argument::Plain(value.into()));
            return Ok(());
        }
        if let Some(rest) = value.strip_prefix("-o") {
            let path = self.take_value("-o", Some(rest))?;
            // A repeated `-o` follows the driver: the last one names the file
            // that is produced. Every occurrence still enters the key.
            self.output = Some(PathBuf::from(&path));
            self.parsed.push(Argument::Path {
                flag: "-o".into(),
                path: PathBuf::from(path),
            });
            return Ok(());
        }
        if let Some(rest) = value.strip_prefix("-I") {
            let path = PathBuf::from(self.take_value("-I", Some(rest))?);
            self.include_dirs.push(path.clone());
            self.parsed.push(Argument::Path {
                flag: "-I".into(),
                path,
            });
            return Ok(());
        }
        if SEPARATE_PATH_FLAGS.contains(&value) {
            let path = PathBuf::from(self.take_value(value, None)?);
            match value {
                "-isystem" | "-iquote" | "-idirafter" => self.include_dirs.push(path.clone()),
                "-isysroot" => self.sysroot = Some(path.clone()),
                // `-include` and `-imacros` are deliberately not required
                // inputs. The driver resolves the name through the include
                // chain, so the file need not exist relative to the working
                // directory, and the dependency list names it at whatever path
                // it was actually found at.
                _ => {}
            }
            self.parsed.push(Argument::Path {
                flag: value.into(),
                path,
            });
            return Ok(());
        }
        // `--include=<file>` is the long spelling of `-include <file>`; the
        // `cc` crate emits it for prefixed headers.
        if let Some(rest) = value.strip_prefix("--include=") {
            let path = PathBuf::from(rest);
            self.parsed.push(Argument::Path {
                flag: "-include".into(),
                path,
            });
            return Ok(());
        }
        if let Some((flag, rest)) = PREFIX_MAP_FLAGS.iter().find_map(|flag| {
            value
                .strip_prefix(&format!("{flag}="))
                .map(|rest| (*flag, rest))
        }) {
            let (from, to) = rest.split_once('=').unwrap_or((rest, ""));
            self.parsed.push(Argument::PrefixMap {
                flag: flag.into(),
                from: PathBuf::from(from),
                to: to.into(),
            });
            return Ok(());
        }
        // `--param name=value` tunes the optimizer; its text fully describes it.
        if value == "--param" {
            let parameter = self.take_value("--param", None)?;
            self.parsed
                .push(Argument::Plain(format!("--param={parameter}")));
            return Ok(());
        }
        if let Some(parameter) = value.strip_prefix("--param=") {
            self.parsed
                .push(Argument::Plain(format!("--param={parameter}")));
            return Ok(());
        }
        if let Some(rest) = value.strip_prefix("--sysroot=") {
            let path = PathBuf::from(rest);
            self.sysroot = Some(path.clone());
            self.parsed.push(Argument::Path {
                flag: "--sysroot".into(),
                path,
            });
            return Ok(());
        }
        if let Some(rest) = value
            .strip_prefix("-D")
            .or_else(|| value.strip_prefix("-U"))
        {
            let flag = &value[..2];
            let definition = self.take_value(flag, Some(rest))?;
            self.parsed
                .push(Argument::Plain(format!("{flag}{definition}")));
            return Ok(());
        }
        if let Some(rest) = value.strip_prefix("-x") {
            let language = self.take_value("-x", Some(rest))?;
            self.explicit_language = Some(match language.as_str() {
                "c" => CcLanguage::C,
                "c++" => CcLanguage::Cxx,
                other => return Err(CcBypassReason::UnsupportedLanguage(other.into())),
            });
            self.parsed.push(Argument::Plain(format!("-x{language}")));
            return Ok(());
        }
        if let Some(target) = value.strip_prefix("--target=") {
            self.parsed
                .push(Argument::Plain(format!("--target={target}")));
            return Ok(());
        }
        if value == "-target" {
            let target = self.take_value("-target", None)?;
            self.parsed
                .push(Argument::Plain(format!("--target={target}")));
            return Ok(());
        }
        if value == "-arch" {
            let arch = self.take_value("-arch", None)?;
            self.parsed.push(Argument::Plain(format!("-arch={arch}")));
            return Ok(());
        }
        if let Some(option) = value.strip_prefix("-f") {
            return self.parse_f_flag(value, option);
        }
        if let Some(option) = value.strip_prefix("-m") {
            return self.parse_m_flag(value, option);
        }
        if value.starts_with("-g") {
            // `-gsplit-dwarf` writes a `.dwo` beside the object; every other
            // unlisted `-g` spelling is simply unmodeled.
            return Err(if value.starts_with("-gsplit-dwarf") {
                CcBypassReason::SplitDebugOutput(value.into())
            } else {
                CcBypassReason::UnknownFlag(value.into())
            });
        }
        if value.starts_with("-W") {
            // Warning selection changes only diagnostics, which are replayed
            // from the cache, and the exit status, and only successful
            // compiles are ever published.
            self.parsed.push(Argument::Plain(value.into()));
            return Ok(());
        }
        Err(CcBypassReason::UnknownFlag(value.into()))
    }

    fn parse_f_flag(&mut self, value: &str, option: &str) -> Result<(), CcBypassReason> {
        if option.starts_with("plugin") || option.starts_with("pass-plugin") {
            return Err(CcBypassReason::Plugin(value.into()));
        }
        if option.starts_with("profile-") || option == "test-coverage" {
            return Err(CcBypassReason::CoverageInstrumentation(value.into()));
        }
        let name = option.split_once('=').map_or(option, |(name, _)| name);
        if SUPPORTED_F_FLAGS.binary_search(&name).is_err() {
            return Err(CcBypassReason::UnknownFlag(value.into()));
        }
        self.parsed.push(Argument::Plain(value.into()));
        Ok(())
    }

    fn parse_m_flag(&mut self, value: &str, option: &str) -> Result<(), CcBypassReason> {
        if option == "llvm" {
            return Err(CcBypassReason::ToolPassthrough(value.into()));
        }
        // `-march=native` and its relatives resolve against whatever CPU this
        // machine has. The resulting object is not a function of the key, so
        // another machine could otherwise restore code its processor cannot
        // run.
        if let Some((name, selection)) = option.split_once('=')
            && matches!(name, "arch" | "cpu" | "tune")
            && matches!(selection, "native" | "host")
        {
            return Err(CcBypassReason::LocalCpuTarget(value.into()));
        }
        let name = option.split_once('=').map_or(option, |(name, _)| name);
        if SUPPORTED_M_FLAGS.binary_search(&name).is_err() {
            return Err(CcBypassReason::UnknownFlag(value.into()));
        }
        self.parsed.push(Argument::Plain(value.into()));
        Ok(())
    }
}

/// Conservative parser for the command lines emitted by the `cc` crate for
/// Microsoft's compiler. It intentionally admits only flags whose effects are
/// either present in argv or covered by dependency discovery.
struct MsvcParser<'a> {
    arguments: &'a [OsString],
    index: usize,
    parsed: Vec<Argument>,
    source: Option<PathBuf>,
    output: Option<PathBuf>,
    include_dirs: Vec<PathBuf>,
    required_inputs: Vec<PathBuf>,
    explicit_language: Option<CcLanguage>,
    compiling: bool,
}

impl<'a> MsvcParser<'a> {
    fn new(arguments: &'a [OsString]) -> Self {
        Self {
            arguments,
            index: 0,
            parsed: Vec::new(),
            source: None,
            output: None,
            include_dirs: Vec::new(),
            required_inputs: Vec::new(),
            explicit_language: None,
            compiling: false,
        }
    }

    fn parse(mut self) -> Result<CcInvocation, CcBypassReason> {
        while self.index < self.arguments.len() {
            let value = self.current()?.to_owned();
            self.index += 1;
            if let Some(file) = value.strip_prefix('@') {
                return Err(CcBypassReason::ResponseFile(file.into()));
            }
            if value.starts_with('/') || value.starts_with('-') {
                self.parse_flag(&value)?;
            } else {
                self.add_source(&value)?;
            }
        }
        if !self.compiling {
            return Err(CcBypassReason::NotACompile);
        }
        let source = self.source.clone().ok_or(CcBypassReason::MissingInput)?;
        let output = self.output.clone().ok_or(CcBypassReason::MissingOutput)?;
        let language = self.explicit_language.unwrap_or_else(|| {
            if source
                .extension()
                .and_then(|value| value.to_str())
                .is_some_and(|value| value.eq_ignore_ascii_case("c"))
            {
                CcLanguage::C
            } else {
                CcLanguage::Cxx
            }
        });
        self.required_inputs.push(source.clone());
        Ok(CcInvocation {
            arguments: self.parsed,
            source,
            output,
            include_dirs: self.include_dirs,
            required_inputs: self.required_inputs,
            language,
            sysroot: None,
        })
    }

    fn current(&self) -> Result<&str, CcBypassReason> {
        self.arguments[self.index]
            .to_str()
            .ok_or(CcBypassReason::NonUtf8Argument { index: self.index })
    }

    fn value(&mut self, flag: &str, attached: &str) -> Result<String, CcBypassReason> {
        if !attached.is_empty() {
            return Ok(attached.into());
        }
        if self.index == self.arguments.len() {
            return Err(CcBypassReason::MissingValue(flag.into()));
        }
        let value = self.current()?.to_owned();
        self.index += 1;
        Ok(value)
    }

    fn add_source(&mut self, value: &str) -> Result<(), CcBypassReason> {
        if self.source.is_some() {
            return Err(CcBypassReason::MultipleInputs);
        }
        let path = PathBuf::from(value);
        if self.explicit_language.is_none()
            && !path
                .extension()
                .and_then(|value| value.to_str())
                .is_some_and(|value| {
                    matches!(
                        value.to_ascii_lowercase().as_str(),
                        "c" | "cc" | "cpp" | "cxx"
                    )
                })
        {
            return Err(CcBypassReason::UnsupportedLanguage(value.into()));
        }
        self.source = Some(path.clone());
        self.parsed.push(Argument::Source(path));
        Ok(())
    }

    fn parse_flag(&mut self, value: &str) -> Result<(), CcBypassReason> {
        let option = value.trim_start_matches(['/', '-']);
        let lower = option.to_ascii_lowercase();
        if matches!(lower.as_str(), "?" | "help") {
            return Err(CcBypassReason::CompilerQuery);
        }
        if lower == "showincludes" || lower.starts_with("sourcedependencies") {
            return Err(CcBypassReason::CallerDependencyFlags(value.into()));
        }
        if matches!(lower.as_str(), "e" | "ep" | "p") {
            return Err(CcBypassReason::NonObjectOutput(value.into()));
        }
        if (lower.starts_with("fa") && !lower.starts_with("favor:"))
            || lower.starts_with("fd")
            || lower.starts_with("zi")
        {
            return Err(CcBypassReason::SplitDebugOutput(value.into()));
        }
        if lower.starts_with("yc")
            || lower.starts_with("yu")
            || (lower.starts_with("fp") && !lower.starts_with("fp:"))
        {
            return Err(CcBypassReason::PrecompiledHeader(value.into()));
        }
        if lower == "link" || lower.starts_with("bt+") || lower.starts_with("analyze") {
            return Err(CcBypassReason::ToolPassthrough(value.into()));
        }
        if matches!(lower.as_str(), "ld" | "ldd") {
            return Err(CcBypassReason::NotACompile);
        }
        if lower == "c" {
            self.compiling = true;
            self.parsed.push(Argument::Plain("/c".into()));
            return Ok(());
        }
        for (prefix, canonical) in [("Fo", "/Fo"), ("I", "/I"), ("FI", "/FI")] {
            if let Some(attached) = option.strip_prefix(prefix) {
                let path = PathBuf::from(self.value(canonical, attached)?);
                if prefix == "Fo" {
                    self.output = Some(path.clone());
                } else if prefix == "I" {
                    self.include_dirs.push(path.clone());
                }
                self.parsed.push(Argument::Path {
                    flag: canonical.into(),
                    path,
                });
                return Ok(());
            }
        }
        if lower.starts_with("external:i") {
            let path = PathBuf::from(self.value("/external:I", &option[10..])?);
            self.include_dirs.push(path.clone());
            self.parsed.push(Argument::Path {
                flag: "/external:I".into(),
                path,
            });
            return Ok(());
        }
        if option.starts_with("Tc") || option.starts_with("Tp") {
            let c = option.starts_with("Tc");
            let path = self.value(if c { "/Tc" } else { "/Tp" }, &option[2..])?;
            self.explicit_language = Some(if c { CcLanguage::C } else { CcLanguage::Cxx });
            return self.add_source(&path);
        }
        if lower.starts_with("pathmap:") {
            let rest = &option[8..];
            let (from, to) = rest.split_once('=').unwrap_or((rest, ""));
            self.parsed.push(Argument::PrefixMap {
                flag: "/pathmap".into(),
                from: PathBuf::from(from),
                to: to.into(),
            });
            return Ok(());
        }
        if matches!(option, "D" | "U") {
            let definition = self.value(value, "")?;
            self.parsed
                .push(Argument::Plain(format!("/{option}{definition}")));
            return Ok(());
        }
        // Definitions and the ordinary code-generation/diagnostic switches
        // produced by cc-rs are self-contained text and can be keyed verbatim.
        let definition = option.starts_with('D') || option.starts_with('U');
        let warning = matches!(lower.as_str(), "wall" | "wx" | "wx-")
            || lower
                .strip_prefix('w')
                .is_some_and(|value| value.bytes().all(|byte| byte.is_ascii_digit()))
            || ["wd", "we", "wo"].iter().any(|prefix| {
                lower
                    .strip_prefix(prefix)
                    .is_some_and(|value| value.bytes().all(|byte| byte.is_ascii_digit()))
            });
        let admitted = definition
            || warning
            || lower.starts_with("std:")
            || lower.starts_with("arch:")
            || lower.starts_with("favor:")
            || lower.starts_with("volatile:")
            || lower.starts_with("fp:")
            || lower.starts_with("eh")
            || lower.starts_with('o')
            || lower.starts_with("ob")
            || lower.starts_with("oi")
            || lower.starts_with("ot")
            || lower.starts_with("oy")
            || lower.starts_with("gs")
            || lower.starts_with("gr")
            || lower.starts_with("gy")
            || lower.starts_with("gw")
            || lower.starts_with("gl")
            || lower.starts_with("zc:")
            || lower.starts_with("diagnostics:")
            || matches!(
                lower.as_str(),
                "nologo"
                    | "brepro"
                    | "bigobj"
                    | "utf-8"
                    | "permissive-"
                    | "z7"
                    | "md"
                    | "mdd"
                    | "mt"
                    | "mtd"
            );
        if admitted {
            self.parsed.push(Argument::Plain(value.into()));
            return Ok(());
        }
        Err(CcBypassReason::UnknownFlag(value.into()))
    }
}

#[cfg(test)]
#[path = "cc_cache_tests.rs"]
mod tests;