Skip to main content

mbx_cache_rustc/
lib.rs

1//! Conservative parsing and action-key construction for `rustc` invocations.
2//!
3//! The adapter deliberately rejects any compiler option whose effect on the
4//! action key is unknown. Callers should treat [`BypassReason`] as a safe cache
5//! bypass, run the real compiler, and avoid publishing an action result.
6//!
7//! A typical integration parses an invocation, discovers precise inputs from
8//! rustc dep-info with [`RustcInvocation::discover_inputs`], adds them to an
9//! [`ActionContext`], and finally calls [`RustcInvocation::action`]. Path
10//! mappings make workspace-local absolute paths stable across machines.
11//!
12//! ```
13//! use mbx_cache_rustc::{PathMapping, normalize_mapped_path};
14//! use std::path::Path;
15//!
16//! let mappings = PathMapping::ordered(&[
17//!     PathMapping::new("/work/project", "workspace"),
18//! ]);
19//! assert_eq!(
20//!     normalize_mapped_path(
21//!         Path::new("src/lib.rs"),
22//!         Path::new("/work/project"),
23//!         &mappings,
24//!     )?,
25//!     "${workspace}/src/lib.rs",
26//! );
27//! # Ok::<(), mbx_cache_rustc::BypassReason>(())
28//! ```
29#![deny(missing_docs)]
30
31use mbx_cache_core::{
32    CacheDigest, FileDigestCache, PathAliases, PathMapping as SharedPathMapping,
33    PathNormalizationError, canonical_json, normalize_mapped_path as normalize_shared_path,
34    normalize_resolved_mapped_path_with as normalize_resolved_shared_path_with,
35    resolve_path_mappings,
36};
37use serde::{Deserialize, Deserializer, Serialize, Serializer};
38use std::collections::{BTreeMap, BTreeSet};
39use std::ffi::OsString;
40use std::path::{Component, Path, PathBuf};
41use thiserror::Error;
42
43mod dep_info;
44
45const NIX_STORE_ROOT: &str = "/nix/store";
46
47pub use dep_info::{DepInfoCommand, DiscoveredInputs, RustcDepInfo};
48
49/// Schema version embedded in canonical rustc action descriptors.
50pub const ACTION_SCHEMA_VERSION: u8 = 1;
51/// Version of the rustc argument and input model used to construct keys.
52///
53/// Bumped to 2 when the dep-info and diagnostics stored with a result stopped
54/// carrying the publishing checkout's absolute paths. Entries written before
55/// that hold the old spelling, and nothing in them says so, so they are retired
56/// by the key rather than restored into a checkout they do not describe.
57pub const ADAPTER_VERSION: u8 = 2;
58
59impl BypassReason {
60    /// A stable, low-cardinality name for this reason.
61    ///
62    /// Many variants carry a path or a flag, so `Display` text cannot be
63    /// aggregated; statistics group by this instead.
64    pub fn kind(&self) -> &'static str {
65        self.into()
66    }
67
68    /// A concrete change that can make this invocation cacheable, when one is
69    /// available.
70    ///
71    /// Expected probes and failures that require adapter support return
72    /// `None`; callers can still explain those from [`BypassReason::kind`].
73    pub fn remediation(&self) -> Option<&'static str> {
74        match self {
75            Self::Incremental => Some(
76                "Set `MBX_INCREMENTAL=0`; mbx will then disable Cargo incremental state and cache the compilation.",
77            ),
78            Self::UnportableNativeLink(detail) if detail.contains("linker") => Some(
79                "Make the native linker resolvable on `PATH`, or configure a linker mbx can identify for this target.",
80            ),
81            Self::UnportableNativeLink(_) => Some(
82                "Remove the reported `-C` option from the active Cargo profile or `RUSTFLAGS` to make these links cacheable.",
83            ),
84            Self::UnknownFlag(_) | Self::UnknownCodegenOption(_) => Some(
85                "Remove the reported compiler option, or upgrade mbx if the option should be modeled.",
86            ),
87            Self::UnmodeledLinkArgument(_) => Some(
88                "Remove the reported linker argument, or keep these links uncached if the argument is required.",
89            ),
90            Self::UnmappedAbsolutePath(_) => Some(
91                "Move the input under the workspace, target, Cargo, toolchain, or home roots so mbx can give it a portable cache name.",
92            ),
93            Self::BuildScriptInputOverlapsOutputs(_) => Some(
94                "Keep compiler output directories outside watched trees, or narrow `rerun-if-changed` to source and asset paths.",
95            ),
96            _ => None,
97        }
98    }
99}
100
101impl From<PathNormalizationError> for BypassReason {
102    fn from(reason: PathNormalizationError) -> Self {
103        match reason {
104            PathNormalizationError::UnmappedAbsolutePath(path) => Self::UnmappedAbsolutePath(path),
105            PathNormalizationError::NonUtf8Path(path) => Self::NonUtf8Path(path),
106        }
107    }
108}
109
110/// Code-generation options that a Cargo profile sets on every unit it builds.
111/// Options Cargo varies from unit to unit within one profile, such as `lto`
112/// and `embed-bitcode`, would split a profile into groups that each wait for
113/// their own first hit, so they are left out. The group keeps these in the
114/// invocation's order, because a later spelling of one option wins.
115const PREFETCH_GROUP_CODEGEN_OPTIONS: &[&str] = &[
116    "debug-assertions",
117    "debuginfo",
118    "opt-level",
119    "overflow-checks",
120    "panic",
121];
122
123/// Hex digits kept from a prefetch group's digest. A group only has to tell
124/// the few profiles of one workspace apart, and every prediction carries it.
125const PREFETCH_GROUP_LEN: usize = 16;
126
127/// The rustc prediction schema this release records.
128pub const PREDICTION_VERSION: u8 = 6;
129
130const SUPPORTED_CODEGEN_OPTIONS: &[&str] = &[
131    "codegen-units",
132    "control-flow-guard",
133    "debug-assertions",
134    "debuginfo",
135    "default-linker-libraries",
136    "embed-bitcode",
137    "extra-filename",
138    "force-frame-pointers",
139    "force-unwind-tables",
140    "instrument-coverage",
141    "link-arg",
142    "link-args",
143    "link-dead-code",
144    "link-self-contained",
145    "linker-plugin-lto",
146    "lto",
147    "metadata",
148    "no-prepopulate-passes",
149    "opt-level",
150    "overflow-checks",
151    "panic",
152    "prefer-dynamic",
153    "relocation-model",
154    "rpath",
155    "save-temps",
156    "soft-float",
157    "split-debuginfo",
158    "split-dwarf-kind",
159    "strip",
160    "symbol-mangling-version",
161    "target-cpu",
162    "target-feature",
163    "tls-model",
164    // Only lets rustc link crates whose target modifiers differ, without
165    // refusing or warning; it does not change the code generated.
166    "unsafe-allow-abi-mismatch",
167];
168
169const NATIVE_DIRECTORY_PREDICTION_PREFIX: &str = "@native-directory:";
170const MAX_PREDICTED_INPUTS: usize = 16 * 1024;
171// A compact payload is capped on the wire by the protocol. Bound its expanded
172// form too, so a hostile prefix chain cannot turn a small manifest into an
173// unreasonable allocation while it is being decoded.
174const MAX_DECODED_PREDICTION_BYTES: usize = 16 * 1024 * 1024;
175const MAX_NATIVE_INPUT_BYTES: u64 = 2 * 1024 * 1024 * 1024;
176
177/// Built-in WebAssembly targets whose default linkers and CRT inputs ship in
178/// the Rust toolchain. Custom target specs never enter this list.
179const COMPILER_BUNDLED_WASM_TARGETS: &[&str] = &[
180    "wasm32-unknown-unknown",
181    "wasm32-wasip1",
182    "wasm32-wasip1-threads",
183    "wasm32-wasip2",
184    "wasm32v1-none",
185    "wasm64-unknown-unknown",
186];
187
188#[derive(Debug, Clone, PartialEq, Eq, Error, strum::IntoStaticStr)]
189#[strum(serialize_all = "kebab-case")]
190/// Reason an invocation cannot safely use the action cache.
191///
192/// A bypass is an expected conservative outcome, not necessarily a compiler
193/// error. Variants carry diagnostic context while [`BypassReason::kind`]
194/// provides a stable aggregation key.
195///
196/// This set exists to shrink: every invocation the adapter learns to model
197/// retires a variant, and every construct it learns to reject adds one. Match
198/// on [`BypassReason::kind`] for aggregation rather than on the variants.
199#[non_exhaustive]
200pub enum BypassReason {
201    /// An argument cannot be represented in the canonical UTF-8 key.
202    #[error("rustc argument {index} is not valid UTF-8")]
203    NonUtf8Argument {
204        /// Zero-based index in the argument slice.
205        index: usize,
206    },
207    /// A rustc response file could not be read or parsed exactly.
208    #[error("could not model rustc response file: {0}")]
209    ResponseFile(String),
210    /// A compiler flag is not modeled by this adapter version.
211    #[error("rustc flag is not modeled by the cache adapter: {0}")]
212    UnknownFlag(String),
213    /// A `-C` option is not modeled by this adapter version.
214    #[error("rustc codegen option is not modeled by the cache adapter: {0}")]
215    UnknownCodegenOption(String),
216    /// A recognized flag was not followed by its required value.
217    #[error("rustc flag requires a value: {0}")]
218    MissingValue(String),
219    /// The invocation queries compiler information instead of compiling.
220    #[error("rustc invocation is a compiler query, not a compilation")]
221    CompilerQuery,
222    /// Source would be read from standard input and cannot be rediscovered.
223    #[error("rustc invocation reads source from standard input")]
224    StandardInput,
225    /// No Rust source input was supplied.
226    #[error("rustc invocation has no source input")]
227    MissingInput,
228    /// More than one source input was supplied.
229    #[error("rustc invocation has multiple source inputs")]
230    MultipleInputs,
231    /// Incremental state makes the outputs unsuitable for action caching.
232    #[error("incremental compilation cannot be combined with action caching")]
233    Incremental,
234    /// The requested crate type is outside the supported cacheability tier.
235    #[error("rustc crate type is not cacheable yet: {0}")]
236    UnsupportedCrateType(String),
237    /// The requested emit kind is outside the supported cacheability tier.
238    #[error("rustc output type is not cacheable yet: {0}")]
239    UnsupportedEmit(String),
240    /// The invocation emits no artifact in the supported cacheability tier.
241    #[error("rustc invocation does not emit a cacheable artifact")]
242    NoCacheableOutput,
243    /// The invocation does not emit the dep-info needed for input discovery.
244    #[error("rustc invocation does not emit dependency information")]
245    NoDepInfo,
246    /// Outputs cannot be represented as one cache directory.
247    #[error("rustc output paths do not share one directory")]
248    SplitOutputDirectories,
249    /// An output path does not name a file.
250    #[error("rustc output path has no file name: {0}")]
251    InvalidOutputPath(PathBuf),
252    /// `-o` leaves the name of an implicit emit ambiguous.
253    #[error("rustc -o with an emit that has no explicit path is not modeled: {0}")]
254    ImplicitEmitWithOutputFile(PathBuf),
255    /// A linked output hands its native libraries to a linker whose search
256    /// is not modeled; only a library emit can name what rustc reads.
257    #[error("native library on a linked output is not cacheable yet: {0}")]
258    NativeLibrary(String),
259    /// A static library named by `-l` is not in any directory rustc would
260    /// read it from, so there is no archive to hash.
261    #[error("native static library was not found on any search path: {0}")]
262    MissingNativeLibrary(String),
263    /// A custom target specification chooses its own static-library file
264    /// names, so the archive rustc would read cannot be named without it.
265    #[error("static library file names are not known for a custom target: {0}")]
266    CustomTargetNativeLibrary(String),
267    /// An output's name does not say whether it is a program or a library.
268    #[error("rustc output name does not distinguish a program from a library: {0}")]
269    AmbiguousOutputName(PathBuf),
270    /// A native link would embed something no other checkout can reproduce.
271    #[error("native link is not reproducible across checkouts: {0}")]
272    UnportableNativeLink(String),
273    /// A linked output was given an argument to pass on to its linker.
274    #[error("rustc link argument is not modeled by the cache adapter: {0}")]
275    UnmodeledLinkArgument(String),
276    /// A library search-path kind is not modeled.
277    #[error("rustc search path kind is not cacheable yet: {0}")]
278    UnsupportedSearchPath(String),
279    /// An extern name does not resolve to a concrete input artifact.
280    #[error("rustc extern does not identify an input artifact: {0}")]
281    UnresolvedExtern(String),
282    /// An absolute path has no stable placeholder mapping.
283    #[error("absolute path has no stable cache mapping: {0}")]
284    UnmappedAbsolutePath(PathBuf),
285    /// A path cannot be represented in a canonical UTF-8 action key.
286    #[error("cache key paths must be valid UTF-8: {0}")]
287    NonUtf8Path(PathBuf),
288    /// The action working directory is not absolute.
289    #[error("cache action working directory must be absolute: {0}")]
290    RelativeWorkingDirectory(PathBuf),
291    /// A path-mapping root is not absolute.
292    #[error("cache path mapping must use an absolute root: {0}")]
293    RelativePathMapping(PathBuf),
294    /// A mapping placeholder is empty or contains unsafe characters.
295    #[error("cache path mapping placeholder is invalid: {0}")]
296    InvalidPathPlaceholder(String),
297    /// An input referenced by compiler arguments is missing from the context.
298    #[error("required compiler input was not provided: {0}")]
299    MissingRequiredInput(String),
300    /// A supplied compiler-input digest is malformed.
301    #[error("compiler input has an invalid digest: {0}")]
302    InvalidInputDigest(String),
303    /// One normalized input path has multiple distinct digests.
304    #[error("compiler input appears more than once with different content: {0}")]
305    ConflictingInput(String),
306    /// rustc dep-info does not follow the supported format.
307    #[error("rustc dep-info is malformed: {0}")]
308    MalformedDepInfo(String),
309    /// A dep-info file could not be read as UTF-8 text.
310    #[error("failed to read rustc dep-info {path}: {message}")]
311    DepInfoRead {
312        /// Dep-info file path.
313        path: PathBuf,
314        /// Underlying I/O or decoding error.
315        message: String,
316    },
317    /// The requested dep-info output path is not absolute.
318    #[error("rustc dep-info output path must be absolute: {0}")]
319    RelativeDepInfoPath(PathBuf),
320    /// A dep-info output path contains a comma and cannot be safely rendered.
321    #[error("rustc dep-info output path cannot contain a comma: {0}")]
322    UnsafeDepInfoPath(PathBuf),
323    /// A discovered compiler input could not be read or was not a file.
324    #[error("failed to read compiler input {path}: {message}")]
325    InputRead {
326        /// Compiler-input path.
327        path: PathBuf,
328        /// Underlying filesystem error.
329        message: String,
330    },
331    /// A declared build-script input includes files the compiler writes.
332    #[error("declared build-script input overlaps compiler outputs: {0}")]
333    BuildScriptInputOverlapsOutputs(PathBuf),
334    /// Cargo has not yet written the build script's recorded declarations.
335    ///
336    /// A build script that runs `$RUSTC` as a probe does so before it exits,
337    /// and Cargo writes its output record only afterwards.
338    #[error("Cargo has not recorded the build script's declarations yet: {0}")]
339    BuildScriptDeclarationsPending(PathBuf),
340    /// A build script's watched paths or environment changed after discovery.
341    /// The path identifies Cargo's recorded declarations, not a changed input.
342    #[error("build-script inputs changed during compilation (declarations: {0})")]
343    BuildScriptInputsChanged(PathBuf),
344    /// Input contents changed after they were hashed.
345    #[error("compiler input changed after discovery: {0}")]
346    InputChanged(PathBuf),
347    /// An input's modification time overlaps the compiler execution.
348    #[error("compiler input was modified during compilation: {0}")]
349    InputModifiedDuringCompilation(PathBuf),
350    /// An input's metadata-change token moved while the compiler ran, but
351    /// not its length, modification time or file object: a metadata write
352    /// that does not prove new contents, so the result is kept uncached.
353    #[error("compiler input metadata changed during compilation: {0}")]
354    InputMetadataChangedDuringCompilation(PathBuf),
355    /// Discovered inputs and the action use different working directories.
356    #[error("discovered inputs were collected from a different working directory")]
357    DiscoveryWorkingDirectory,
358    /// One observed environment input has conflicting values.
359    #[error("compiler environment input has conflicting values: {0}")]
360    ConflictingEnvironment(String),
361    /// Canonical action serialization failed.
362    #[error("failed to serialize the rustc action: {0}")]
363    Serialization(String),
364    /// The stored prediction uses an unsupported version or exceeds limits.
365    #[error("rustc action prediction is unsupported")]
366    UnsupportedPrediction,
367    /// A normalized predicted path cannot be mapped back to the host.
368    #[error("rustc action prediction contains an invalid input path: {0}")]
369    InvalidPredictedInput(String),
370}
371
372/// Whether a `-L` kind makes rustc look for native libraries. A bare `-L path`,
373/// which is what an untyped `cargo:rustc-link-search` produces, is `all`: it
374/// searches for crates and native libraries alike, so it is held to the same
375/// rules as `native`.
376fn searches_native(kind: &str) -> bool {
377    matches!(kind, "native" | "all")
378}
379
380#[derive(Debug, Clone, PartialEq, Eq)]
381enum Argument {
382    Plain(String),
383    Path {
384        flag: String,
385        path: PathBuf,
386    },
387    SearchPath {
388        kind: String,
389        path: PathBuf,
390    },
391    Extern {
392        name: String,
393        path: Option<PathBuf>,
394    },
395    Emit(Vec<Emit>),
396    RemapPath {
397        from: PathBuf,
398        to: String,
399    },
400    /// A single @rpath filename used as a macOS proc macro install name.
401    InstallName(String),
402    /// An `-oso_prefix` handed to ld64, whose path strips checkout-specific
403    /// prefixes from the debug map the linker records.
404    OsoPrefix {
405        path: PathBuf,
406        trailing_slash: bool,
407    },
408    /// A `-fuse-ld=<name>` handed to the driver, selecting which linker a
409    /// link invokes. Modeled for native links only, where the linker identity
410    /// probe resolves and pins the linker it names.
411    FuseLd(String),
412    /// A `-Wl,-rpath,<absolute dir>` handed to ld64, which records the
413    /// directory as an `LC_RPATH` load command and never searches it while
414    /// linking. The text is therefore the whole input and is keyed as written.
415    Rpath(String),
416}
417
418#[derive(Debug, Clone, PartialEq, Eq)]
419struct Emit {
420    kind: String,
421    path: Option<PathBuf>,
422}
423
424#[derive(Debug, Clone, PartialEq, Eq)]
425/// Parsed, cache-safe model of one `rustc` command line.
426///
427/// Fields are intentionally private so new modeled flags can be added without
428/// exposing the adapter's internal representation.
429pub struct RustcInvocation {
430    arguments: Vec<Argument>,
431    source: PathBuf,
432    required_inputs: Vec<PathBuf>,
433    crate_name: String,
434    extra_filename: String,
435    out_dir: Option<PathBuf>,
436    explicit_output: Option<PathBuf>,
437    emits: Vec<Emit>,
438    target: Option<String>,
439    link_output: LinkOutput,
440}
441
442#[derive(Debug, Clone, Copy, PartialEq, Eq)]
443enum LinkOutput {
444    Library,
445    WasmExecutable,
446    NativeExecutable,
447    NativeProcMacro,
448    /// A `cdylib` linked for the host. Admitted on Linux only: an ELF shared
449    /// object names neither its own path nor an import library beside it,
450    /// where a Mach-O dylib records its output path as its install name and
451    /// a Windows DLL leaves an import library and export file next to it.
452    NativeSharedLibrary,
453}
454
455/// What the caller is prepared to model beyond the default tier.
456///
457/// The parser itself stays pure: whether the host can describe its linker
458/// precisely enough to key a native link is the caller's question, and the
459/// answer arrives here rather than being read out of the environment.
460#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
461#[non_exhaustive]
462pub struct ParseOptions {
463    /// Admit natively linked test binaries, executables, and proc macros,
464    /// given a linker identity in the action key. Off by default.
465    pub cache_native_links: bool,
466    /// rustc may resolve this invocation's bare `--target NAME` to a custom
467    /// specification: a `NAME.json` under `RUST_TARGET_PATH` or a
468    /// `lib/rustlib/NAME/target.json` in the sysroot exists. Such a target
469    /// chooses its own static-library file names, which the parser cannot
470    /// know, so `-l static` bypasses.
471    pub custom_target_search: bool,
472}
473
474impl ParseOptions {
475    /// Options that admit native links when `enabled`.
476    pub fn caching_native_links(enabled: bool) -> Self {
477        Self {
478            cache_native_links: enabled,
479            ..Self::default()
480        }
481    }
482
483    /// Options that also say whether rustc could resolve a bare target name
484    /// to a custom specification.
485    pub fn with_custom_target_search(mut self, enabled: bool) -> Self {
486        self.custom_target_search = enabled;
487        self
488    }
489}
490
491/// The cacheable files and dependency manifest produced by a rustc invocation.
492#[derive(Debug, Clone, PartialEq, Eq)]
493pub struct RustcOutputs {
494    /// Common directory containing all modeled outputs.
495    pub directory: PathBuf,
496    /// Cacheable library, metadata, and/or linked program files.
497    pub files: Vec<PathBuf>,
498    /// Dep-info file used for precise input discovery.
499    pub dep_info: PathBuf,
500}
501
502impl RustcInvocation {
503    /// Parse rustc's arguments, excluding the compiler executable supplied as
504    /// the first argument to `RUSTC_WRAPPER`.
505    ///
506    /// Any flag whose cache semantics are not modeled returns a bypass reason
507    /// instead of guessing. A successful parse admits the rlib/rmeta tier,
508    /// every compilation that links nothing at all -- what `cargo check` and
509    /// clippy run, whatever the crate type -- and binaries linked by
510    /// compiler-bundled WebAssembly toolchains.
511    pub fn parse(arguments: &[OsString]) -> Result<Self, BypassReason> {
512        Self::parse_with(arguments, ParseOptions::default())
513    }
514
515    /// The command line with `@argfile` response files expanded, as the
516    /// parser sees it. A caller that scans the arguments before parsing, for a
517    /// `--target` a response file may carry, reads this rather than the raw
518    /// list.
519    pub fn expand_arguments(arguments: &[OsString]) -> Result<Vec<OsString>, BypassReason> {
520        Ok(expand_response_files(arguments)?.arguments)
521    }
522
523    /// Parse as [`RustcInvocation::parse`] does, admitting what `options`
524    /// says the caller can model.
525    pub fn parse_with(arguments: &[OsString], options: ParseOptions) -> Result<Self, BypassReason> {
526        let expanded = expand_response_files(arguments)?;
527        Parser::new(&expanded.arguments, options).parse()
528    }
529
530    /// Whether this invocation links a native artifact, whose key must
531    /// therefore describe the linker that produced it.
532    pub fn links_natively(&self) -> bool {
533        matches!(
534            self.link_output,
535            LinkOutput::NativeExecutable
536                | LinkOutput::NativeProcMacro
537                | LinkOutput::NativeSharedLibrary
538        )
539    }
540
541    /// Stable Mach-O identity for a cached macOS proc macro. The compiler loads
542    /// these by filename; embedding the checkout's output path only makes the
543    /// bytes (and dependent action keys) vary between otherwise identical builds.
544    pub fn portable_install_name(&self, outputs: &RustcOutputs) -> Option<String> {
545        if !cfg!(target_os = "macos")
546            || self.link_output != LinkOutput::NativeProcMacro
547            || self
548                .arguments
549                .iter()
550                .any(|arg| matches!(arg, Argument::InstallName(_)))
551        {
552            return None;
553        }
554        let file = outputs
555            .files
556            .iter()
557            .find(|path| path.extension().is_some_and(|ext| ext == "dylib"))?;
558        let name = file.file_name()?.to_str()?;
559        if !safe_install_name(name) {
560            return None;
561        }
562        Some(format!("-Clink-arg=-Wl,-install_name,@rpath/{name}"))
563    }
564
565    /// Linker selected with `-C linker`, if the invocation overrides rustc's
566    /// platform default.
567    pub fn linker_override(&self) -> Option<&Path> {
568        self.arguments.iter().find_map(|argument| {
569            let Argument::Plain(value) = argument else {
570                return None;
571            };
572            value.strip_prefix("--codegen=linker=").map(Path::new)
573        })
574    }
575
576    /// Linker selected with `-C link-arg=-fuse-ld=<name>`, if the invocation
577    /// passes one the adapter models.
578    pub fn fuse_ld(&self) -> Option<&str> {
579        self.arguments.iter().find_map(|argument| {
580            let Argument::FuseLd(selection) = argument else {
581                return None;
582            };
583            Some(selection.as_str())
584        })
585    }
586
587    fn emits_windows_pdb(&self) -> bool {
588        if !cfg!(windows) || !self.links_natively() {
589            return false;
590        }
591        let mut enabled = false;
592        for argument in &self.arguments {
593            let Argument::Plain(value) = argument else {
594                continue;
595            };
596            if value == "-g" {
597                enabled = true;
598            } else if let Some(value) = value.strip_prefix("--codegen=debuginfo=") {
599                enabled = !matches!(value, "0" | "none");
600            }
601        }
602        enabled
603    }
604
605    /// Native directories explicitly searched by this invocation. Callers can
606    /// map external installations so their contents participate in discovery
607    /// and prediction, rather than treating their paths as immutable inputs.
608    pub fn native_search_paths(&self) -> impl Iterator<Item = &Path> {
609        self.arguments.iter().filter_map(|argument| match argument {
610            Argument::SearchPath { kind, path } if searches_native(kind) => Some(path.as_path()),
611            _ => None,
612        })
613    }
614
615    /// Return the source input passed to rustc.
616    pub fn source(&self) -> &Path {
617        &self.source
618    }
619
620    /// Absolute files named directly by the invocation that rustc must read.
621    ///
622    /// This includes the source, explicit extern artifacts, and custom target
623    /// specifications. Callers can snapshot these before rustc starts even
624    /// though the complete input set is only known from dep-info afterwards.
625    pub fn required_inputs_in(&self, working_dir: &Path) -> Vec<PathBuf> {
626        self.required_inputs
627            .iter()
628            .map(|path| absolute_path(path, working_dir))
629            .collect()
630    }
631
632    /// Return the explicitly selected compilation target, if any.
633    pub fn target(&self) -> Option<&str> {
634        self.target.as_deref()
635    }
636
637    /// Name the build settings this compilation shares with the rest of its
638    /// profile: the target and the profile's code-generation options.
639    ///
640    /// A dev and a release build of one workspace record their predictions in
641    /// one manifest, so that `build`, `test`, and Clippy runs can share them.
642    /// Prefetching every prediction there makes a release build download the
643    /// dev build's outputs, and the reverse. The group lets a build prefetch
644    /// only the predictions recorded with settings it is actually compiling
645    /// with. Build scripts and procedural macros get their own group within a
646    /// profile, because Cargo compiles them with the build-override settings;
647    /// the first of them to hit prefetches the rest.
648    ///
649    /// `-O` is read as `opt-level=3`, as current compilers define it. Cargo
650    /// spells the level out, so this only matters for hand-written
651    /// invocations, and a compiler that reads `-O` differently merely groups
652    /// them apart.
653    ///
654    /// The group selects what to download ahead of time, never what to
655    /// restore: action keys do not depend on it.
656    pub fn prefetch_group(&self) -> String {
657        let mut material = vec![format!("target={}", self.target.as_deref().unwrap_or(""))];
658        for argument in &self.arguments {
659            let Argument::Plain(value) = argument else {
660                continue;
661            };
662            let option = match value.as_str() {
663                "-O" => "opt-level=3",
664                "-g" => "debuginfo=2",
665                value => match value.strip_prefix("--codegen=") {
666                    Some(option) => option,
667                    None => continue,
668                },
669            };
670            let name = option.split_once('=').map_or(option, |(name, _)| name);
671            if PREFETCH_GROUP_CODEGEN_OPTIONS.contains(&name) {
672                material.push(option.to_string());
673            }
674        }
675        let digest = CacheDigest::blake3(
676            format!("rustc-prefetch-group-v1\0{}", material.join("\0")).as_bytes(),
677        );
678        digest.hash[..PREFETCH_GROUP_LEN].to_string()
679    }
680
681    /// Return the crate name rustc will assign to this compilation.
682    pub fn crate_name(&self) -> &str {
683        &self.crate_name
684    }
685
686    /// Whether rustc records a virtual directory in place of the working
687    /// directory (`-Zremap-cwd-prefix`).
688    ///
689    /// rustc checks incremental state against its options, the working
690    /// directory included, and ignores state recorded anywhere else. Under this
691    /// flag, with the paths under the working directory named relative to it,
692    /// every checkout presents the same options, so one checkout's state is as
693    /// good as another's.
694    pub fn remaps_working_directory(&self) -> bool {
695        self.arguments.iter().any(|argument| {
696            matches!(argument, Argument::Plain(flag) if flag.starts_with("-Zremap-cwd-prefix="))
697        })
698    }
699
700    /// Digest of the inputs this compilation owns: its sources and whatever
701    /// they read, but not the artifacts it merely links against.
702    ///
703    /// This is what separates a crate someone is editing from one sitting
704    /// above it in the graph. Rebuilding a dependency changes the action key of
705    /// every crate that links it, because their keys hash its artifact; it does
706    /// not change this. A caller watching for churn has to watch this instead,
707    /// or a single edited crate would drag its whole dependent cone along.
708    ///
709    /// Host paths enter the digest as they are. This describes one checkout to
710    /// itself rather than to the cache, so there is nothing here to make
711    /// portable.
712    pub fn source_fingerprint(&self, discovered: &DiscoveredInputs) -> CacheDigest {
713        let linked = self
714            .arguments
715            .iter()
716            .filter_map(|argument| match argument {
717                Argument::Extern {
718                    path: Some(path), ..
719                } => Some(path.as_path()),
720                _ => None,
721            })
722            .collect::<BTreeSet<_>>();
723        let owned = discovered
724            .inputs
725            .iter()
726            .filter(|input| {
727                !linked.contains(input.path.as_path()) && !discovered.is_native_only(&input.path)
728            })
729            .map(|input| (input.path.as_path(), &input.digest))
730            .collect::<BTreeMap<_, _>>();
731        let mut bytes = Vec::new();
732        for (path, digest) in owned {
733            bytes.extend_from_slice(path.as_os_str().as_encoded_bytes());
734            bytes.push(0);
735            bytes.extend_from_slice(digest.key().as_bytes());
736            bytes.push(0);
737        }
738        CacheDigest::blake3(&bytes)
739    }
740
741    /// Resolve the files produced by this invocation.
742    ///
743    /// The initial cache tier requires one output directory so its artifact can
744    /// be represented by one protocol directory and restored atomically later.
745    pub fn outputs(&self, working_dir: &Path) -> Result<RustcOutputs, BypassReason> {
746        if !working_dir.is_absolute() {
747            return Err(BypassReason::RelativeWorkingDirectory(
748                working_dir.to_path_buf(),
749            ));
750        }
751        let explicit_output = self
752            .explicit_output
753            .as_deref()
754            .map(|path| absolute_path(path, working_dir));
755        let output_directory = explicit_output
756            .as_deref()
757            .and_then(Path::parent)
758            .map(Path::to_path_buf)
759            .or_else(|| {
760                self.out_dir
761                    .as_deref()
762                    .map(|path| absolute_path(path, working_dir))
763            })
764            .unwrap_or_else(|| normalize_components(working_dir));
765        // rustc applies `-o` to every emit that has no path of its own, so the
766        // file names cannot be derived from the crate name here. Cargo always
767        // uses --out-dir instead, so refusing to model this costs nothing.
768        if let Some(output) = &explicit_output
769            && self.emits.iter().any(|emit| {
770                emit.path.is_none()
771                    && matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata")
772            })
773        {
774            return Err(BypassReason::ImplicitEmitWithOutputFile(output.clone()));
775        }
776        let mut files = BTreeSet::new();
777        let mut dep_info = None;
778        for emit in &self.emits {
779            if emit.kind == "dep-info" {
780                let path = emit.path.as_ref().map_or_else(
781                    || {
782                        explicit_output.clone().map_or_else(
783                            || {
784                                output_directory
785                                    .join(format!("{}{}.d", self.crate_name, self.extra_filename))
786                            },
787                            |path| path.with_extension("d"),
788                        )
789                    },
790                    |path| absolute_path(path, working_dir),
791                );
792                if path.file_name().is_none() {
793                    return Err(BypassReason::InvalidOutputPath(path));
794                }
795                dep_info = Some(path);
796                continue;
797            }
798            let (prefix, extension) = match emit.kind.as_str() {
799                "link" => match self.link_output {
800                    LinkOutput::Library => ("lib", "rlib"),
801                    LinkOutput::WasmExecutable => ("", "wasm"),
802                    LinkOutput::NativeExecutable => ("", std::env::consts::EXE_EXTENSION),
803                    LinkOutput::NativeProcMacro | LinkOutput::NativeSharedLibrary => (
804                        std::env::consts::DLL_PREFIX,
805                        std::env::consts::DLL_SUFFIX.trim_start_matches('.'),
806                    ),
807                },
808                "metadata" => ("lib", "rmeta"),
809                _ => continue,
810            };
811            let path = if let Some(path) = &emit.path {
812                absolute_path(path, working_dir)
813            } else {
814                let name = format!("{prefix}{}{}", self.crate_name, self.extra_filename);
815                output_directory.join(if extension.is_empty() {
816                    name
817                } else {
818                    format!("{name}.{extension}")
819                })
820            };
821            if path.file_name().is_none() {
822                return Err(BypassReason::InvalidOutputPath(path));
823            }
824            if path.parent() != Some(output_directory.as_path()) {
825                return Err(BypassReason::SplitOutputDirectories);
826            }
827            // Whether a restored output is a program is read back off its name,
828            // so a program that answers to a library's name would be restored
829            // without the permission that makes it runnable. Nothing cargo
830            // emits looks like this; a hand-built invocation could.
831            let has_library_extension = path
832                .extension()
833                .and_then(|extension| extension.to_str())
834                .is_some_and(|extension| matches!(extension, "rlib" | "rmeta"))
835                || (cfg!(windows)
836                    && path
837                        .file_stem()
838                        .and_then(|stem| Path::new(stem).extension())
839                        .and_then(|extension| extension.to_str())
840                        .is_some_and(|extension| matches!(extension, "rlib" | "rmeta")));
841            if emit.kind == "link"
842                && !matches!(self.link_output, LinkOutput::Library)
843                && has_library_extension
844            {
845                return Err(BypassReason::AmbiguousOutputName(path));
846            }
847            if emit.kind == "link" && self.emits_windows_pdb() {
848                files.insert(path.with_extension("pdb"));
849            }
850            files.insert(path);
851        }
852        let dep_info = dep_info.ok_or(BypassReason::NoDepInfo)?;
853        if dep_info.parent() != Some(output_directory.as_path()) {
854            return Err(BypassReason::SplitOutputDirectories);
855        }
856        Ok(RustcOutputs {
857            directory: output_directory,
858            files: files.into_iter().collect(),
859            dep_info,
860        })
861    }
862
863    /// Build canonical action bytes after precise input discovery has run.
864    ///
865    /// `context.inputs` must contain the source, every explicit extern, and
866    /// every additional source or environment-generated input discovered from
867    /// dep-info.
868    pub fn action(&self, context: ActionContext) -> Result<RustcAction, BypassReason> {
869        self.action_linked_by(context, None)
870    }
871
872    /// Build canonical action bytes for an invocation that links a native
873    /// program.
874    ///
875    /// A `linker` is required whenever [`RustcInvocation::links_natively`]
876    /// holds: the linker, its startup objects, and the platform SDK are inputs
877    /// rustc dep-info does not enumerate, so a key without them would claim
878    /// more than it can support. Passing one for anything else is ignored,
879    /// since nothing else depends on a linker.
880    pub fn action_linked_by(
881        &self,
882        context: ActionContext,
883        linker: Option<LinkerIdentity>,
884    ) -> Result<RustcAction, BypassReason> {
885        self.action_with_incremental_state(context, linker, None)
886    }
887
888    /// Build canonical action bytes for a compilation whose result carries
889    /// the incremental state it finished with.
890    ///
891    /// Such a result holds more than the compiler's outputs, so it must not
892    /// share a key with a result that does not: `incremental_state` names the
893    /// state generation the attached session belongs to, and becomes part of
894    /// the key. `None` builds exactly the key [`Self::action_linked_by`]
895    /// builds, byte for byte.
896    pub fn action_with_incremental_state(
897        &self,
898        context: ActionContext,
899        linker: Option<LinkerIdentity>,
900        incremental_state: Option<String>,
901    ) -> Result<RustcAction, BypassReason> {
902        ActionBuilder::new(self, context)
903            .linked_by(linker)
904            .carrying_incremental_state(incremental_state)
905            .build()
906    }
907
908    /// Fingerprint the modeled invocation before dependency contents are known.
909    pub fn invocation_digest(&self, context: &ActionContext) -> Result<CacheDigest, BypassReason> {
910        let descriptor = ActionBuilder::new(self, context.clone()).invocation_descriptor()?;
911        let bytes = canonical_json(&descriptor)
912            .map_err(|error| BypassReason::Serialization(error.to_string()))?;
913        Ok(CacheDigest::blake3(&bytes))
914    }
915
916    /// Capture normalized dependency paths for a future invocation that has no
917    /// dep-info file yet.
918    pub fn prediction(
919        &self,
920        context: &ActionContext,
921        discovered: &DiscoveredInputs,
922    ) -> Result<RustcInputPrediction, BypassReason> {
923        let builder = ActionBuilder::new(self, context.clone());
924        builder.validate_mappings()?;
925        let mut native_directories = BTreeSet::new();
926        for argument in &self.arguments {
927            if let Argument::SearchPath { kind, path } = argument
928                && searches_native(kind)
929            {
930                native_directories.insert(builder.normalize_path(path)?);
931            }
932        }
933        // A file beneath a recorded directory is rediscovered by walking that
934        // directory, so naming it as well only makes the payload grow with the
935        // object tree a C dependency leaves in its `OUT_DIR`. `aws-lc-sys`
936        // leaves thousands of files there, which was enough to push the
937        // serialized prediction past the protocol's payload limit and lose the
938        // prediction entirely for the crate that most needed one.
939        //
940        // A file dep-info itself names stays, even beneath a recorded
941        // directory. It is a source of the crate, and rediscovery can only tell
942        // it from the objects around it if the prediction says which it is.
943        // There are few of those; the thousands of objects are not named.
944        let mut inputs = BTreeSet::new();
945        for input in &discovered.inputs {
946            let normalized = builder.normalize_file_path(&input.path)?;
947            if !under_any_directory(&normalized, &native_directories)
948                || !discovered.is_native_only(&input.path)
949            {
950                inputs.insert(normalized);
951            }
952        }
953        inputs.extend(
954            native_directories
955                .into_iter()
956                .map(|directory| format!("{NATIVE_DIRECTORY_PREDICTION_PREFIX}{directory}")),
957        );
958        Ok(RustcInputPrediction {
959            version: PREDICTION_VERSION,
960            inputs: inputs.into_iter().collect(),
961            environment: discovered.environment.keys().cloned().collect(),
962            compiler_duration_ns: 0,
963            compiler_cpu_ns: 0,
964            crate_name: String::new(),
965            prefetch_group: self.prefetch_group(),
966        })
967    }
968}
969
970/// Whether a crate name has the form Cargo gives every build script.
971///
972/// The name alone is not proof: see [`RustcOutputs::build_script_executable`].
973pub fn is_build_script_crate_name(crate_name: &str) -> bool {
974    crate_name
975        .strip_prefix("build_script_")
976        .is_some_and(|stem| !stem.is_empty())
977}
978
979impl RustcOutputs {
980    /// The linked executable Cargo will run as a build script, when this is a
981    /// build-script compilation.
982    ///
983    /// Cargo names a build script's crate `build_script_` plus the stem of its
984    /// source: `build_script_build` for `build.rs`, `build_script_main` for
985    /// `build = "builder/main.rs"`. A `[[bin]]` target can take the same name,
986    /// and Cargo's output directory does not tell them apart, so the caller
987    /// has to confirm from Cargo's environment that this is a build script:
988    /// Cargo sets `CARGO_BIN_NAME` for binary targets and never for one.
989    pub fn build_script_executable(&self, crate_name: &str) -> Option<&Path> {
990        is_build_script_crate_name(crate_name)
991            .then(|| self.files.iter().find(|path| self.is_executable(path)))
992            .flatten()
993            .map(PathBuf::as_path)
994    }
995
996    /// Whether `path` is a linked program whose executable permission is part
997    /// of the declared output contract.
998    /// A program is whatever this invocation emitted that is not a library
999    /// artifact. Every tier the adapter admits distinguishes the two by
1000    /// extension -- `rlib` and `rmeta` are the compiler's own, and a linked
1001    /// program carries either the target's (`wasm`) or none at all -- so the
1002    /// name is enough and no separate list has to be carried alongside.
1003    pub fn is_executable(&self, path: &Path) -> bool {
1004        self.files.iter().any(|output| output == path)
1005            && !matches!(
1006                path.extension().and_then(|extension| extension.to_str()),
1007                Some("rlib" | "rmeta")
1008            )
1009    }
1010}
1011
1012#[derive(Debug, Clone, PartialEq, Eq)]
1013/// Mapping from a host-specific absolute root to a stable key placeholder.
1014pub struct PathMapping {
1015    /// Absolute host path to replace.
1016    pub root: PathBuf,
1017    /// Placeholder name without the surrounding `${...}` syntax.
1018    pub placeholder: String,
1019}
1020
1021impl PathMapping {
1022    /// Map an absolute host path to a stable cache-key placeholder.
1023    pub fn new(root: impl Into<PathBuf>, placeholder: impl Into<String>) -> Self {
1024        Self {
1025            root: root.into(),
1026            placeholder: placeholder.into(),
1027        }
1028    }
1029
1030    /// Order mappings deepest root first, which is what normalization needs:
1031    /// a target directory inside the workspace has to win over the workspace.
1032    pub fn ordered(mappings: &[PathMapping]) -> Vec<PathMapping> {
1033        let mut ordered = mappings.to_vec();
1034        ordered.sort_by_key(|mapping| std::cmp::Reverse(mapping.root.components().count()));
1035        ordered
1036    }
1037}
1038
1039fn shared_path_mappings(mappings: &[PathMapping]) -> Vec<SharedPathMapping> {
1040    mappings
1041        .iter()
1042        .map(|mapping| SharedPathMapping::new(&mapping.root, &mapping.placeholder))
1043        .collect()
1044}
1045
1046/// Map an absolute path to its cache-key placeholder form.
1047///
1048/// `mappings` must already be ordered by [`PathMapping::ordered`]. Exposed for
1049/// callers that need the placeholder text before an action exists -- notably to
1050/// build the `--remap-path-prefix` flag that makes a compilation independent of
1051/// a path in its environment.
1052pub fn normalize_mapped_path(
1053    path: &Path,
1054    working_dir: &Path,
1055    mappings: &[PathMapping],
1056) -> Result<String, BypassReason> {
1057    normalize_shared_path(path, working_dir, &shared_path_mappings(mappings)).map_err(Into::into)
1058}
1059
1060/// Key an input path using the configured mappings or its literal Nix store path.
1061pub fn normalize_input_path(
1062    path: &Path,
1063    working_dir: &Path,
1064    mappings: &[PathMapping],
1065) -> Result<String, BypassReason> {
1066    normalize_mapped_path(path, working_dir, mappings)
1067        .or_else(|reason| key_nix_store_path(path, working_dir, reason))
1068}
1069
1070#[derive(Debug, Clone, PartialEq, Eq)]
1071/// Compiler properties that distinguish incompatible action outputs.
1072pub struct CompilerIdentity {
1073    /// Toolchain selector or installation identity.
1074    pub toolchain: String,
1075    /// Complete verbose rustc version string.
1076    pub rustc_version: String,
1077    /// Compiler host target triple.
1078    pub host: String,
1079    /// Identity of a compiler driver layered over rustc, when one is in use.
1080    pub driver: Option<String>,
1081}
1082
1083/// One file input paired with the digest used in the action key.
1084#[derive(Debug, Clone, PartialEq, Eq)]
1085pub struct ActionInput {
1086    /// Absolute host path used to read and verify the input.
1087    pub path: PathBuf,
1088    /// Digest of the input contents.
1089    pub digest: CacheDigest,
1090}
1091
1092/// External information needed to construct a canonical rustc action.
1093#[derive(Debug, Clone, PartialEq, Eq)]
1094pub struct ActionContext {
1095    /// Identity of the compiler that produces the outputs.
1096    pub compiler: CompilerIdentity,
1097    /// Absolute directory in which rustc runs.
1098    pub working_dir: PathBuf,
1099    /// Host roots replaced with stable placeholders in the key.
1100    pub path_mappings: Vec<PathMapping>,
1101    /// Environment inputs and their observed values.
1102    pub environment: BTreeMap<String, Option<String>>,
1103    /// Environment inputs whose absolute values the compilation has been made
1104    /// independent of, and whose values the key therefore normalizes.
1105    ///
1106    /// Naming one here is a claim about the compilation, not a preference: the
1107    /// caller must both neutralize the value inside it (with
1108    /// `--remap-path-prefix`) and confirm no output carries the value anyway.
1109    pub portable_environment: BTreeSet<String>,
1110    /// Complete set of direct and discovered file inputs.
1111    pub inputs: Vec<ActionInput>,
1112}
1113
1114/// What produced a linked native program, beyond the compiler itself.
1115///
1116/// The fields are identity rather than content wherever a compiler's own
1117/// identity is: a driver's version output names its toolchain more cheaply than
1118/// hashing a hundred megabytes of it, and matches how rustc is identified. The
1119/// CRT objects are hashed, because nothing else pins the libc a link resolves
1120/// against. Nothing here is placeholder-mapped -- these paths are host
1121/// locations rather than checkout locations, and two hosts that differ should
1122/// miss rather than share.
1123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1124#[serde(deny_unknown_fields)]
1125pub struct LinkerIdentity {
1126    /// Resolved absolute path of the linker driver rustc will invoke.
1127    pub driver: String,
1128    /// Version output of that driver.
1129    pub driver_version: String,
1130    /// Version of the linker the driver selects.
1131    pub linker_version: String,
1132    /// Startup objects and libc the driver resolves, by probe name.
1133    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
1134    pub crt_objects: BTreeMap<String, CacheDigest>,
1135    /// Platform SDK identity, where the platform has one.
1136    #[serde(skip_serializing_if = "Option::is_none", default)]
1137    pub sdk: Option<String>,
1138    /// Deployment target the link was made against, where one applies.
1139    #[serde(skip_serializing_if = "Option::is_none", default)]
1140    pub deployment_target: Option<String>,
1141}
1142
1143/// Canonical action descriptor and its content digest.
1144#[derive(Debug, Clone, PartialEq, Eq)]
1145pub struct RustcAction {
1146    /// Digest of `bytes`, used as the action-cache key.
1147    pub digest: CacheDigest,
1148    /// Canonical serialized action descriptor.
1149    pub bytes: Vec<u8>,
1150}
1151
1152/// Normalized input names from the last successful execution of one modeled
1153/// rustc invocation.
1154#[derive(Debug, Clone, PartialEq, Eq)]
1155pub struct RustcInputPrediction {
1156    /// Prediction schema version.
1157    pub version: u8,
1158    /// Normalized input paths observed during the successful invocation.
1159    pub inputs: Vec<String>,
1160    /// Names of environment variables read by the compilation.
1161    pub environment: Vec<String>,
1162    /// Compiler wall time from the successful invocation that produced this
1163    /// prediction. Zero means no timing hint was recorded.
1164    pub compiler_duration_ns: u64,
1165    /// User and system CPU time of that invocation's compiler process tree.
1166    /// Zero means it was not measured. Recorded from version 6.
1167    pub compiler_cpu_ns: u64,
1168    /// Crate name associated with the timing hint.
1169    pub crate_name: String,
1170    /// Build settings group from [`RustcInvocation::prefetch_group`], which
1171    /// selects the predictions a build prefetches together. Recorded from
1172    /// version 5; empty before it.
1173    pub prefetch_group: String,
1174}
1175
1176#[derive(Serialize, Deserialize)]
1177#[serde(deny_unknown_fields)]
1178struct RustcInputPredictionWire {
1179    version: u8,
1180    inputs: Vec<String>,
1181    environment: Vec<String>,
1182    #[serde(default, skip_serializing_if = "is_zero")]
1183    compiler_duration_ns: u64,
1184    #[serde(default, skip_serializing_if = "is_zero")]
1185    compiler_cpu_ns: u64,
1186    #[serde(default, skip_serializing_if = "String::is_empty")]
1187    crate_name: String,
1188    #[serde(default, skip_serializing_if = "String::is_empty")]
1189    prefetch_group: String,
1190}
1191
1192impl Serialize for RustcInputPrediction {
1193    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1194    where
1195        S: Serializer,
1196    {
1197        RustcInputPredictionWire {
1198            version: self.version,
1199            inputs: if self.version >= 4 {
1200                mbx_cache_core::prefix_coding::compact_paths(&self.inputs)
1201            } else {
1202                self.inputs.clone()
1203            },
1204            environment: self.environment.clone(),
1205            compiler_duration_ns: self.compiler_duration_ns,
1206            compiler_cpu_ns: self.compiler_cpu_ns,
1207            crate_name: self.crate_name.clone(),
1208            prefetch_group: self.prefetch_group.clone(),
1209        }
1210        .serialize(serializer)
1211    }
1212}
1213
1214impl<'de> Deserialize<'de> for RustcInputPrediction {
1215    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1216    where
1217        D: Deserializer<'de>,
1218    {
1219        let wire = RustcInputPredictionWire::deserialize(deserializer)?;
1220        let group_is_valid = if wire.version >= 5 {
1221            wire.prefetch_group.len() == PREFETCH_GROUP_LEN
1222                && wire
1223                    .prefetch_group
1224                    .bytes()
1225                    .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
1226        } else {
1227            wire.prefetch_group.is_empty()
1228        };
1229        if !group_is_valid {
1230            return Err(serde::de::Error::custom(
1231                "rustc prediction prefetch group is invalid for its version",
1232            ));
1233        }
1234        if wire.version < 6 && wire.compiler_cpu_ns != 0 {
1235            return Err(serde::de::Error::custom(
1236                "rustc prediction CPU time is invalid for its version",
1237            ));
1238        }
1239        let inputs = if wire.version >= 4 {
1240            mbx_cache_core::prefix_coding::expand_paths(&wire.inputs, MAX_DECODED_PREDICTION_BYTES)
1241                .map_err(serde::de::Error::custom)?
1242        } else {
1243            wire.inputs
1244        };
1245        Ok(Self {
1246            version: wire.version,
1247            inputs,
1248            environment: wire.environment,
1249            compiler_duration_ns: wire.compiler_duration_ns,
1250            compiler_cpu_ns: wire.compiler_cpu_ns,
1251            crate_name: wire.crate_name,
1252            prefetch_group: wire.prefetch_group,
1253        })
1254    }
1255}
1256
1257fn is_zero(value: &u64) -> bool {
1258    *value == 0
1259}
1260
1261impl RustcInputPrediction {
1262    /// This prediction re-recorded at the current version with `group`, when
1263    /// it was restored from an older version whose inputs mean the same thing
1264    /// at the current one. Versions 3 and 4 differ from it only in how inputs
1265    /// are encoded on the wire. Version 2 read every input as a plain path, so
1266    /// it converts unless an input carries the native-directory prefix that
1267    /// version 3 gave a meaning. Anything else gets `None`.
1268    pub fn with_prefetch_group(&self, group: String) -> Option<Self> {
1269        let converts = match self.version {
1270            3 | 4 => true,
1271            2 => !self
1272                .inputs
1273                .iter()
1274                .any(|input| input.starts_with(NATIVE_DIRECTORY_PREDICTION_PREFIX)),
1275            _ => false,
1276        };
1277        converts.then(|| Self {
1278            version: PREDICTION_VERSION,
1279            prefetch_group: group,
1280            ..self.clone()
1281        })
1282    }
1283
1284    /// Rehash the predicted paths and read the current environment. The caller
1285    /// still recomputes the full action digest, so changed inputs are misses.
1286    pub fn discover(
1287        &self,
1288        working_dir: &Path,
1289        path_mappings: &[PathMapping],
1290        digests: &dyn FileDigestCache,
1291    ) -> Result<DiscoveredInputs, BypassReason> {
1292        self.discover_with_store(working_dir, path_mappings, digests, NIX_STORE_ROOT)
1293    }
1294
1295    fn discover_with_store(
1296        &self,
1297        working_dir: &Path,
1298        path_mappings: &[PathMapping],
1299        digests: &dyn FileDigestCache,
1300        store_root: &str,
1301    ) -> Result<DiscoveredInputs, BypassReason> {
1302        if !matches!(self.version, 2..=PREDICTION_VERSION) {
1303            return Err(BypassReason::UnsupportedPrediction);
1304        }
1305        if self.inputs.len() > MAX_PREDICTED_INPUTS || self.environment.len() > 4 * 1024 {
1306            return Err(BypassReason::UnsupportedPrediction);
1307        }
1308        let mut paths = BTreeSet::new();
1309        let mut named = BTreeSet::new();
1310        let admitted_roots = dep_info::native_input_roots(working_dir, path_mappings);
1311        let mut native_bytes = 0_u64;
1312        let mut counted = BTreeSet::new();
1313        let mut native_walk = dep_info::NativeWalk::default();
1314        for path in &self.inputs {
1315            if self.version >= 3
1316                && let Some(path) = path.strip_prefix(NATIVE_DIRECTORY_PREDICTION_PREFIX)
1317            {
1318                let directory = denormalize_path(path, path_mappings, store_root)?;
1319                native_walk.extend(dep_info::collect_native_directory(
1320                    &directory,
1321                    &admitted_roots,
1322                    &mut paths,
1323                    &mut native_bytes,
1324                    &mut counted,
1325                )?);
1326            } else {
1327                let path = denormalize_path(path, path_mappings, store_root)?;
1328                named.insert(path.clone());
1329                paths.insert(path);
1330            }
1331        }
1332        let native_only = paths.difference(&named).cloned().collect();
1333        let environment = self
1334            .environment
1335            .iter()
1336            .map(|name| {
1337                if name.is_empty() || name.contains(['=', '\0']) {
1338                    return Err(BypassReason::UnsupportedPrediction);
1339                }
1340                let value = std::env::var_os(name)
1341                    .map(|value| {
1342                        value
1343                            .into_string()
1344                            .map_err(|_| BypassReason::UnsupportedPrediction)
1345                    })
1346                    .transpose()?;
1347                Ok((name.clone(), value))
1348            })
1349            .collect::<Result<BTreeMap<_, _>, _>>()?;
1350        Ok(
1351            DiscoveredInputs::from_paths(working_dir, paths, environment, digests)?
1352                .with_native_only(native_only)
1353                .with_native_walk(native_walk),
1354        )
1355    }
1356}
1357
1358#[derive(Serialize)]
1359struct ActionDescriptor {
1360    version: u8,
1361    kind: &'static str,
1362    adapter_version: u8,
1363    compiler: CompilerDescriptor,
1364    arguments: Vec<String>,
1365    environment: BTreeMap<String, Option<String>>,
1366    inputs: Vec<InputDescriptor>,
1367    /// Omitted entirely unless the invocation links natively, so every key
1368    /// written before this field existed still serializes to the same bytes.
1369    #[serde(skip_serializing_if = "Option::is_none")]
1370    linker: Option<LinkerIdentity>,
1371    /// The state generation of the incremental session a result under this
1372    /// key carries. Omitted when the result carries none, which keeps every
1373    /// other key's bytes as they were before this field existed.
1374    #[serde(skip_serializing_if = "Option::is_none")]
1375    incremental_state: Option<String>,
1376}
1377
1378#[derive(Serialize)]
1379struct InvocationDescriptor {
1380    version: u8,
1381    kind: &'static str,
1382    adapter_version: u8,
1383    compiler: CompilerDescriptor,
1384    arguments: Vec<String>,
1385    required_inputs: Vec<String>,
1386}
1387
1388#[derive(Serialize)]
1389struct CompilerDescriptor {
1390    toolchain: String,
1391    rustc_version: String,
1392    host: String,
1393    #[serde(skip_serializing_if = "Option::is_none")]
1394    driver: Option<String>,
1395}
1396
1397#[derive(Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)]
1398struct InputDescriptor {
1399    path: String,
1400    digest: CacheDigest,
1401}
1402
1403/// The static-library file names a built-in target uses.
1404#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1405enum StaticLibraryNaming {
1406    /// `NAME.lib`, then the Unix spelling as a fallback.
1407    Msvc,
1408    /// `libNAME.a`.
1409    Unix,
1410}
1411
1412struct Parser<'a> {
1413    arguments: &'a [OsString],
1414    index: usize,
1415    parsed: Vec<Argument>,
1416    source: Option<PathBuf>,
1417    crate_types: Vec<String>,
1418    emits: Vec<Emit>,
1419    required_inputs: Vec<PathBuf>,
1420    native_libraries: Vec<String>,
1421    test: bool,
1422    crate_name: Option<String>,
1423    extra_filename: String,
1424    out_dir: Option<PathBuf>,
1425    explicit_output: Option<PathBuf>,
1426    target: Option<String>,
1427    sysroot_backend: Option<String>,
1428    options: ParseOptions,
1429}
1430
1431struct ExpandedArguments {
1432    arguments: Vec<OsString>,
1433}
1434
1435#[derive(Default)]
1436struct ResponseExpander {
1437    shell_argfiles: bool,
1438    next_is_unstable_option: bool,
1439    arguments: Vec<OsString>,
1440}
1441
1442impl ResponseExpander {
1443    fn push(&mut self, argument: String) {
1444        if self.next_is_unstable_option {
1445            self.shell_argfiles |= argument == "shell-argfiles";
1446            self.next_is_unstable_option = false;
1447        } else if let Some(option) = argument.strip_prefix("-Z") {
1448            if option.is_empty() {
1449                self.next_is_unstable_option = true;
1450            } else {
1451                self.shell_argfiles |= option == "shell-argfiles";
1452            }
1453        }
1454        self.arguments.push(argument.into());
1455    }
1456}
1457
1458/// Match rustc's argfile expansion: UTF-8, one option per line, no recursive
1459/// expansion, with the nightly shell form enabled only after its `-Z` flag.
1460fn expand_response_files(arguments: &[OsString]) -> Result<ExpandedArguments, BypassReason> {
1461    let mut expanded = ResponseExpander::default();
1462    for (index, argument) in arguments.iter().enumerate() {
1463        let argument = argument
1464            .to_str()
1465            .ok_or(BypassReason::NonUtf8Argument { index })?;
1466        let Some(argfile) = argument.strip_prefix('@') else {
1467            expanded.push(argument.to_string());
1468            continue;
1469        };
1470        let (path, shell) = match argfile.split_once(':') {
1471            Some(("shell", path)) if expanded.shell_argfiles => (path, true),
1472            _ => (argfile, false),
1473        };
1474        let contents = std::fs::read_to_string(path).map_err(|error| {
1475            BypassReason::ResponseFile(format!("{}: {error}", Path::new(path).display()))
1476        })?;
1477        if shell {
1478            let arguments = shlex::split(&contents).ok_or_else(|| {
1479                BypassReason::ResponseFile(format!(
1480                    "invalid shell-style arguments in {}",
1481                    Path::new(path).display()
1482                ))
1483            })?;
1484            for argument in arguments {
1485                expanded.push(argument);
1486            }
1487        } else {
1488            for argument in contents.lines() {
1489                expanded.push(argument.to_string());
1490            }
1491        }
1492    }
1493    Ok(ExpandedArguments {
1494        arguments: expanded.arguments,
1495    })
1496}
1497
1498impl<'a> Parser<'a> {
1499    fn new(arguments: &'a [OsString], options: ParseOptions) -> Self {
1500        Self {
1501            arguments,
1502            options,
1503            index: 0,
1504            parsed: Vec::new(),
1505            source: None,
1506            crate_types: Vec::new(),
1507            emits: Vec::new(),
1508            required_inputs: Vec::new(),
1509            native_libraries: Vec::new(),
1510            test: false,
1511            crate_name: None,
1512            extra_filename: String::new(),
1513            out_dir: None,
1514            explicit_output: None,
1515            target: None,
1516            sysroot_backend: None,
1517        }
1518    }
1519
1520    fn parse(mut self) -> Result<RustcInvocation, BypassReason> {
1521        while self.index < self.arguments.len() {
1522            let value = self.current()?.to_string();
1523            self.index += 1;
1524            if let Some(long) = value.strip_prefix("--") {
1525                self.parse_long(long)?;
1526            } else if value.starts_with('-') && value != "-" {
1527                self.parse_short(&value)?;
1528            } else {
1529                self.parse_input(&value)?;
1530            }
1531        }
1532
1533        // rustc searches an explicit sysroot for the backend first, and only the compiler's own is hashed.
1534        if let Some(backend) = self.sysroot_backend.take()
1535            && self.parsed.iter().any(
1536                |argument| matches!(argument, Argument::Path { flag, .. } if flag == "--sysroot"),
1537            )
1538        {
1539            return Err(BypassReason::UnknownFlag(backend));
1540        }
1541        let source = self.source.clone().ok_or(BypassReason::MissingInput)?;
1542        let link_output = self.classify()?;
1543        self.require_native_libraries(link_output)?;
1544        let crate_name = self.crate_name.clone().map_or_else(
1545            || {
1546                source
1547                    .file_stem()
1548                    .and_then(|name| name.to_str())
1549                    .map(|name| name.replace('-', "_"))
1550                    .ok_or_else(|| BypassReason::NonUtf8Path(source.clone()))
1551            },
1552            Ok,
1553        )?;
1554        self.required_inputs.push(source.clone());
1555        self.drop_unobservable_diagnostic_width();
1556        Ok(RustcInvocation {
1557            arguments: self.parsed,
1558            source,
1559            required_inputs: self.required_inputs,
1560            crate_name,
1561            extra_filename: self.extra_filename,
1562            out_dir: self.out_dir,
1563            explicit_output: self.explicit_output,
1564            emits: self.emits,
1565            target: self.target,
1566            link_output,
1567        })
1568    }
1569
1570    fn current(&self) -> Result<&str, BypassReason> {
1571        self.arguments[self.index]
1572            .to_str()
1573            .ok_or(BypassReason::NonUtf8Argument { index: self.index })
1574    }
1575
1576    fn take_value(&mut self, flag: &str, inline: Option<&str>) -> Result<String, BypassReason> {
1577        if let Some(value) = inline {
1578            if value.is_empty() {
1579                return Err(BypassReason::MissingValue(flag.into()));
1580            }
1581            return Ok(value.into());
1582        }
1583        if self.index >= self.arguments.len() {
1584            return Err(BypassReason::MissingValue(flag.into()));
1585        }
1586        let value = self.current()?.to_string();
1587        self.index += 1;
1588        Ok(value)
1589    }
1590
1591    /// Cargo passes `--diagnostic-width` only when stderr is a terminal, with
1592    /// the terminal's width as the value, so keying it splits the cache by how
1593    /// a build was launched. The width only wraps rendered diagnostics and
1594    /// never changes the artifacts, so it is left out of the key for every
1595    /// crate. Diagnostics replayed from a cached entry keep the wrapping of
1596    /// the build that produced them.
1597    ///
1598    /// rustc rejects a repeated flag and a non-numeric value, so only a single
1599    /// well-formed width is dropped; anything else stays keyed and cannot
1600    /// share an entry with a build that rustc would accept.
1601    fn drop_unobservable_diagnostic_width(&mut self) {
1602        fn widths(argument: &Argument) -> Option<&str> {
1603            match argument {
1604                Argument::Plain(value) => value.strip_prefix("--diagnostic-width="),
1605                _ => None,
1606            }
1607        }
1608        let mut found = self.parsed.iter().filter_map(widths);
1609        let valid = matches!(
1610            (found.next(), found.next()),
1611            (Some(width), None) if width.parse::<usize>().is_ok()
1612        );
1613        if valid {
1614            self.parsed.retain(|argument| widths(argument).is_none());
1615        }
1616    }
1617
1618    fn parse_long(&mut self, value: &str) -> Result<(), BypassReason> {
1619        let (flag, inline) = value
1620            .split_once('=')
1621            .map_or((value, None), |(flag, value)| (flag, Some(value)));
1622        let rendered_flag = format!("--{flag}");
1623        match flag {
1624            "help" | "version" | "explain" | "print" => Err(BypassReason::CompilerQuery),
1625            "test" => {
1626                self.test = true;
1627                self.parsed.push(Argument::Plain(rendered_flag));
1628                Ok(())
1629            }
1630            "verbose" => {
1631                self.parsed.push(Argument::Plain(rendered_flag));
1632                Ok(())
1633            }
1634            "crate-name" => {
1635                let value = self.take_value(&rendered_flag, inline)?;
1636                self.crate_name = Some(value.clone());
1637                self.parsed
1638                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1639                Ok(())
1640            }
1641            "cfg" | "check-cfg" | "edition" | "error-format" | "json" | "color"
1642            | "diagnostic-width" | "remap-path-scope" | "allow" | "warn" | "force-warn"
1643            | "deny" | "forbid" | "cap-lints" => {
1644                let value = self.take_value(&rendered_flag, inline)?;
1645                self.parsed
1646                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1647                Ok(())
1648            }
1649            "target" => {
1650                let value = self.take_value(&rendered_flag, inline)?;
1651                // rustc reads the first `--target`, as getopts does; a later
1652                // one is still keyed as an argument but does not decide the
1653                // target, so it is not read and not a required input either.
1654                let effective = self.target.is_none();
1655                if effective {
1656                    self.target = Some(value.clone());
1657                }
1658                if value.ends_with(".json") || value.contains(['/', '\\']) {
1659                    let path = PathBuf::from(value);
1660                    if effective {
1661                        self.required_inputs.push(path.clone());
1662                    }
1663                    self.parsed.push(Argument::Path {
1664                        flag: rendered_flag,
1665                        path,
1666                    });
1667                } else {
1668                    self.parsed
1669                        .push(Argument::Plain(format!("{rendered_flag}={value}")));
1670                }
1671                Ok(())
1672            }
1673            "crate-type" => {
1674                let value = self.take_value(&rendered_flag, inline)?;
1675                self.crate_types
1676                    .extend(value.split(',').map(ToOwned::to_owned));
1677                self.parsed
1678                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1679                Ok(())
1680            }
1681            "emit" => {
1682                let value = self.take_value(&rendered_flag, inline)?;
1683                let emits = parse_emits(&value);
1684                self.emits.extend(emits.clone());
1685                self.parsed.push(Argument::Emit(emits));
1686                Ok(())
1687            }
1688            "out-dir" => {
1689                let path = PathBuf::from(self.take_value(&rendered_flag, inline)?);
1690                self.out_dir = Some(path.clone());
1691                self.parsed.push(Argument::Path {
1692                    flag: rendered_flag,
1693                    path,
1694                });
1695                Ok(())
1696            }
1697            "sysroot" => {
1698                let path = self.take_value(&rendered_flag, inline)?;
1699                self.parsed.push(Argument::Path {
1700                    flag: rendered_flag,
1701                    path: path.into(),
1702                });
1703                Ok(())
1704            }
1705            "extern" => {
1706                let value = self.take_value(&rendered_flag, inline)?;
1707                let (name, path) = value
1708                    .split_once('=')
1709                    .map_or((value.as_str(), None), |(name, path)| {
1710                        (name, Some(PathBuf::from(path)))
1711                    });
1712                if let Some(path) = &path {
1713                    self.required_inputs.push(path.clone());
1714                }
1715                self.parsed.push(Argument::Extern {
1716                    name: name.into(),
1717                    path,
1718                });
1719                Ok(())
1720            }
1721            "remap-path-prefix" => {
1722                let value = self.take_value(&rendered_flag, inline)?;
1723                let Some((from, to)) = value.split_once('=') else {
1724                    return Err(BypassReason::MissingValue(rendered_flag));
1725                };
1726                self.parsed.push(Argument::RemapPath {
1727                    from: from.into(),
1728                    to: to.into(),
1729                });
1730                Ok(())
1731            }
1732            "codegen" => {
1733                let value = self.take_value(&rendered_flag, inline)?;
1734                self.parse_codegen(&value)
1735            }
1736            "jobs-frontend" => {
1737                let value = self.take_value(&rendered_flag, inline)?;
1738                self.parsed
1739                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1740                Ok(())
1741            }
1742            _ => Err(BypassReason::UnknownFlag(rendered_flag)),
1743        }
1744    }
1745
1746    fn parse_short(&mut self, value: &str) -> Result<(), BypassReason> {
1747        if let Some(attached) = value.strip_prefix("-Z") {
1748            let option = self.take_value("-Z", (!attached.is_empty()).then_some(attached))?;
1749            match option.as_str() {
1750                // Cargo passes `force-unstable-if-unmarked` to every standard
1751                // library unit under `-Zbuild-std`. It changes the stability
1752                // recorded in the crate's metadata, so it stays in the key.
1753                "embed-metadata=no"
1754                | "embed-metadata=yes"
1755                | "force-unstable-if-unmarked"
1756                | "shell-argfiles"
1757                | "unstable-options" => {
1758                    self.parsed.push(Argument::Plain(format!("-Z{option}")));
1759                    return Ok(());
1760                }
1761                // Selects a distinct unwind-table encoding. Preserve the
1762                // exact value in the action key; reject other spellings.
1763                "use-sync-unwind=yes" | "use-sync-unwind=no" => {
1764                    self.parsed.push(Argument::Plain(format!("-Z{option}")));
1765                    return Ok(());
1766                }
1767                "threads" | "threads=" => {
1768                    return Err(BypassReason::MissingValue("-Zthreads".into()));
1769                }
1770                "remap-cwd-prefix" | "remap-cwd-prefix=" => {
1771                    return Err(BypassReason::MissingValue("-Zremap-cwd-prefix".into()));
1772                }
1773                _ => {}
1774            }
1775            // Replaces the working directory in every path rustc records, and
1776            // in the options its incremental state is checked against. The
1777            // value is the virtual directory written in the working
1778            // directory's place, kept verbatim like `--remap-path-prefix`'s
1779            // destination.
1780            if option.starts_with("remap-cwd-prefix=") {
1781                self.parsed.push(Argument::Plain(format!("-Z{option}")));
1782                return Ok(());
1783            }
1784            if option == "share-generics" {
1785                return Err(BypassReason::MissingValue("-Zshare-generics".into()));
1786            }
1787            if let Some(value) = option.strip_prefix("share-generics=") {
1788                if matches!(
1789                    value,
1790                    "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1791                ) {
1792                    self.parsed.push(Argument::Plain(format!("-Z{option}")));
1793                    return Ok(());
1794                }
1795                return Err(if value.is_empty() {
1796                    BypassReason::MissingValue("-Zshare-generics".into())
1797                } else {
1798                    BypassReason::UnknownFlag(format!("-Z{option}"))
1799                });
1800            }
1801            // These change what rustc encodes into the rmeta: the MIR of
1802            // every item, or the optimized MIR. Keep the exact spelling in
1803            // the key; reject values rustc would not accept.
1804            if option == "always-encode-mir" {
1805                self.parsed.push(Argument::Plain(format!("-Z{option}")));
1806                return Ok(());
1807            }
1808            if let Some(level) = option.strip_prefix("mir-opt-level=") {
1809                if matches!(level, "0" | "1" | "2" | "3" | "4") {
1810                    self.parsed.push(Argument::Plain(format!("-Z{option}")));
1811                    return Ok(());
1812                }
1813                return Err(if level.is_empty() {
1814                    BypassReason::MissingValue("-Zmir-opt-level".into())
1815                } else {
1816                    BypassReason::UnknownFlag(format!("-Z{option}"))
1817                });
1818            }
1819            if option == "mir-opt-level" {
1820                return Err(BypassReason::MissingValue("-Zmir-opt-level".into()));
1821            }
1822            // `ub-checks` sets `cfg(ub_checks)`, so it changes the code as
1823            // well as the MIR.
1824            let (name, value) = option
1825                .split_once('=')
1826                .map_or((option.as_str(), None), |(name, value)| (name, Some(value)));
1827            if matches!(name, "inline-mir" | "ub-checks") {
1828                return match value {
1829                    Some("y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false") => {
1830                        self.parsed.push(Argument::Plain(format!("-Z{option}")));
1831                        Ok(())
1832                    }
1833                    None | Some("") => Err(BypassReason::MissingValue(format!("-Z{name}"))),
1834                    Some(_) => Err(BypassReason::UnknownFlag(format!("-Z{option}"))),
1835                };
1836            }
1837            // A later entry for the same pass wins, and so does a later flag,
1838            // so the list is kept verbatim and in order.
1839            if name == "mir-enable-passes" {
1840                return match value {
1841                    Some(list)
1842                        if list
1843                            .split(',')
1844                            .all(|entry| entry.len() > 1 && entry.starts_with(['+', '-'])) =>
1845                    {
1846                        self.parsed.push(Argument::Plain(format!("-Z{option}")));
1847                        Ok(())
1848                    }
1849                    None | Some("") => Err(BypassReason::MissingValue(format!("-Z{name}"))),
1850                    Some(_) => Err(BypassReason::UnknownFlag(format!("-Z{option}"))),
1851                };
1852            }
1853            if option.starts_with("threads=") {
1854                self.parsed.push(Argument::Plain(format!("-Z{option}")));
1855                return Ok(());
1856            }
1857            // rustc loads a value containing a `.` as a library path, which the key doesn't hash.
1858            if let Some(backend) = option.strip_prefix("codegen-backend=")
1859                && !backend.is_empty()
1860                && !backend.contains(['.', '/', '\\'])
1861            {
1862                self.sysroot_backend = Some(format!("-Z{option}"));
1863                self.parsed.push(Argument::Plain(format!("-Z{option}")));
1864                return Ok(());
1865            }
1866            return Err(BypassReason::UnknownFlag(format!("-Z{option}")));
1867        }
1868        match value {
1869            // `-vV` is how cargo and build scripts ask for the verbose
1870            // version, so it is a query rather than a flag left unmodeled.
1871            "-h" | "-V" | "-vV" => return Err(BypassReason::CompilerQuery),
1872            "-g" | "-O" | "-v" => {
1873                self.parsed.push(Argument::Plain(value.into()));
1874                return Ok(());
1875            }
1876            _ => {}
1877        }
1878        for (short, long) in [
1879            ("-A", "--allow"),
1880            ("-W", "--warn"),
1881            ("-D", "--deny"),
1882            ("-F", "--forbid"),
1883        ] {
1884            if let Some(attached) = value.strip_prefix(short) {
1885                let lint = self.take_value(short, (!attached.is_empty()).then_some(attached))?;
1886                self.parsed.push(Argument::Plain(format!("{long}={lint}")));
1887                return Ok(());
1888            }
1889        }
1890        if let Some(attached) = value.strip_prefix("-C") {
1891            let option = self.take_value("-C", (!attached.is_empty()).then_some(attached))?;
1892            return self.parse_codegen(&option);
1893        }
1894        if let Some(attached) = value.strip_prefix("-L") {
1895            let search = self.take_value("-L", (!attached.is_empty()).then_some(attached))?;
1896            let (kind, path) = search
1897                .split_once('=')
1898                .map_or(("all", search.as_str()), |(kind, path)| (kind, path));
1899            if kind != "dependency" && !searches_native(kind) {
1900                return Err(BypassReason::UnsupportedSearchPath(kind.into()));
1901            }
1902            self.parsed.push(Argument::SearchPath {
1903                kind: kind.into(),
1904                path: path.into(),
1905            });
1906            return Ok(());
1907        }
1908        if let Some(attached) = value.strip_prefix("-l") {
1909            let library = self.take_value("-l", (!attached.is_empty()).then_some(attached))?;
1910            self.parsed.push(Argument::Plain(format!("-l{library}")));
1911            self.native_libraries.push(library);
1912            return Ok(());
1913        }
1914        if let Some(attached) = value.strip_prefix("-o") {
1915            let path = self.take_value("-o", (!attached.is_empty()).then_some(attached))?;
1916            self.explicit_output = Some(path.clone().into());
1917            self.parsed.push(Argument::Path {
1918                flag: "-o".into(),
1919                path: path.into(),
1920            });
1921            return Ok(());
1922        }
1923        Err(BypassReason::UnknownFlag(value.into()))
1924    }
1925
1926    fn parse_codegen(&mut self, value: &str) -> Result<(), BypassReason> {
1927        let name = value.split_once('=').map_or(value, |(name, _)| name);
1928        if name == "incremental" {
1929            return Err(BypassReason::Incremental);
1930        }
1931        if name == "profile-use" {
1932            let Some((_, profile)) = value.split_once('=') else {
1933                return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1934            };
1935            if profile.is_empty() {
1936                return Err(BypassReason::MissingValue("-Cprofile-use".into()));
1937            }
1938            let path = PathBuf::from(profile);
1939            self.required_inputs.push(path.clone());
1940            self.parsed.push(Argument::Path {
1941                flag: "-Cprofile-use".into(),
1942                path,
1943            });
1944            return Ok(());
1945        }
1946        if SUPPORTED_CODEGEN_OPTIONS.binary_search(&name).is_err()
1947            && !matches!(name, "linker" | "linker-flavor")
1948        {
1949            return Err(BypassReason::UnknownCodegenOption(name.into()));
1950        }
1951        // Cargo compiles every dependency of an LTO build with this flag, so
1952        // the rlibs carry bitcode for the final link to optimize across. The
1953        // switch is keyed as text like any other option. A value naming the
1954        // linker plugin is a host file the key does not describe, so that
1955        // spelling still bypasses.
1956        if name == "linker-plugin-lto"
1957            && let Some((_, selection)) = value.split_once('=')
1958            && !matches!(
1959                selection,
1960                "" | "y" | "yes" | "on" | "true" | "n" | "no" | "off" | "false"
1961            )
1962        {
1963            return Err(BypassReason::UnknownCodegenOption(format!(
1964                "linker-plugin-lto={selection}"
1965            )));
1966        }
1967        // `-fuse-ld=<name>` selects the linker the driver invokes. Parsed
1968        // rather than keyed as text so the linker identity probe can pin the
1969        // selected linker; a repeated selection dedups, and a conflicting
1970        // second selection falls through to Plain, which native-link handling
1971        // declines to model. The driver honors the last selection, so a
1972        // conflict is a link whose linker this adapter cannot name.
1973        if name == "link-arg"
1974            && let Some((_, option)) = value.split_once('=')
1975            && let Some(selection) = option.strip_prefix("-fuse-ld=")
1976            && !selection.is_empty()
1977            && !selection.contains(',')
1978            && !self.parsed.iter().any(
1979                |argument| matches!(argument, Argument::FuseLd(existing) if existing != selection),
1980            )
1981        {
1982            if !self.parsed.iter().any(
1983                |argument| matches!(argument, Argument::FuseLd(existing) if existing == selection),
1984            ) {
1985                self.parsed.push(Argument::FuseLd(selection.to_owned()));
1986            }
1987            return Ok(());
1988        }
1989        // Only a single filename under @rpath is modeled. Other spellings,
1990        // combined linker options, and explicit absolute names still bypass.
1991        if name == "link-arg"
1992            && let Some(option) = value.strip_prefix("link-arg=-Wl,-install_name,@rpath/")
1993            && safe_install_name(option)
1994        {
1995            self.parsed.push(Argument::InstallName(option.to_owned()));
1996            return Ok(());
1997        }
1998        // An absolute rpath is only recorded in the output. Relative and
1999        // `@`-prefixed entries, and several options in one argument, stay
2000        // unmodeled text.
2001        if name == "link-arg"
2002            && let Some(directory) = value.strip_prefix("link-arg=-Wl,-rpath,")
2003            && directory.starts_with('/')
2004            && !directory.contains(',')
2005        {
2006            self.parsed.push(Argument::Rpath(directory.to_owned()));
2007            return Ok(());
2008        }
2009        // `-oso_prefix` names a checkout-specific path, so it is parsed
2010        // rather than keyed as text: the path normalizes like every other
2011        // path in the key, which is what lets two checkouts passing their own
2012        // prefixes agree on one action.
2013        if matches!(name, "link-arg" | "link-args")
2014            && let Some((_, option)) = value.split_once('=')
2015            && let Some(prefix) = option.strip_prefix("-Wl,-oso_prefix,")
2016            && !prefix.trim_end_matches('/').is_empty()
2017            && !prefix.contains(',')
2018        {
2019            let trailing_slash = prefix.ends_with('/');
2020            self.parsed.push(Argument::OsoPrefix {
2021                path: PathBuf::from(prefix.trim_end_matches('/')),
2022                trailing_slash,
2023            });
2024            return Ok(());
2025        }
2026        self.parsed
2027            .push(Argument::Plain(format!("--codegen={value}")));
2028        if name == "extra-filename" {
2029            self.extra_filename = value
2030                .split_once('=')
2031                .map_or(String::new(), |(_, value)| value.to_string());
2032        }
2033        Ok(())
2034    }
2035
2036    /// Model what rustc reads for each `-l`, now that the emit is known.
2037    ///
2038    /// A library emit runs no linker. For `dylib`, `framework`, `link-arg`,
2039    /// and an unspecified kind, rustc only records the name in the crate's
2040    /// metadata, so the flag text already in the key is the whole input. A
2041    /// `static` library is different: rustc opens the archive and bundles its
2042    /// members into the rlib, so the archive's content decides the output. It
2043    /// is found the way rustc finds it and named as a required input, keyed
2044    /// by content exactly like an `--extern` artifact. With `-bundle` rustc
2045    /// records the name for a downstream link instead of reading the archive,
2046    /// so that flag is text like the name-only kinds.
2047    ///
2048    /// A linked output hands every `-l` to its linker, whose search is not
2049    /// modeled here, so those still bypass whatever the kind.
2050    fn require_native_libraries(&mut self, link_output: LinkOutput) -> Result<(), BypassReason> {
2051        for library in std::mem::take(&mut self.native_libraries) {
2052            if link_output != LinkOutput::Library {
2053                return Err(BypassReason::NativeLibrary(library));
2054            }
2055            // `-l [KIND[:MODIFIERS]=]NAME[:RENAME]`. Without a kind the
2056            // library is rustc's "unspecified" kind: it is handed to the
2057            // linker of whatever finally links, and an rlib only records the
2058            // name. rustc bundles into an rlib only what `-l static` names
2059            // (`link_rlib` takes `NativeLibKind::Static` with bundling on),
2060            // so a `libNAME.a` that later appears beside a plain `-l NAME`
2061            // changes that final link, not this compilation.
2062            let Some((kind, name)) = library.split_once('=') else {
2063                continue;
2064            };
2065            let (kind, modifiers) = kind.split_once(':').unwrap_or((kind, ""));
2066            match kind {
2067                "static" => {}
2068                "dylib" | "framework" | "link-arg" => continue,
2069                _ => return Err(BypassReason::UnknownFlag(format!("-l{library}"))),
2070            }
2071            // A rename links RENAME in place of the NAME a `#[link]` attribute
2072            // gave, so RENAME is the archive on disk.
2073            let name = name.split_once(':').map_or(name, |(_, renamed)| renamed);
2074            let (mut verbatim, mut bundle) = (false, true);
2075            for modifier in modifiers.split(',') {
2076                match modifier {
2077                    "+verbatim" => verbatim = true,
2078                    "-verbatim" => verbatim = false,
2079                    "+bundle" => bundle = true,
2080                    "-bundle" => bundle = false,
2081                    _ => {}
2082                }
2083            }
2084            if !bundle {
2085                continue;
2086            }
2087            let archive = self
2088                .find_native_static_library(name, verbatim)
2089                .map_err(|()| BypassReason::CustomTargetNativeLibrary(library.clone()))?
2090                .ok_or_else(|| BypassReason::MissingNativeLibrary(library.clone()))?;
2091            self.required_inputs.push(archive);
2092        }
2093        Ok(())
2094    }
2095
2096    /// Resolve a static library the way rustc does: the first `-L native`
2097    /// directory, in command-line order, holding the target's file name for
2098    /// it. rustc would also search a plain `-L` directory, but that kind
2099    /// already bypasses as unsupported before it gets here. Targets with
2100    /// MSVC-style libraries (Windows MSVC and UEFI) accept `NAME.lib` before
2101    /// falling back to the `libNAME.a` every built-in target otherwise uses;
2102    /// `+verbatim` names the file literally. A custom target specification
2103    /// sets its own prefix and suffix, which are not read here, so it is an
2104    /// `Err` rather than a guess that could hash a different archive than
2105    /// rustc bundles. A relative search directory resolves against the
2106    /// process working directory, as it does for rustc.
2107    fn find_native_static_library(
2108        &self,
2109        name: &str,
2110        verbatim: bool,
2111    ) -> Result<Option<PathBuf>, ()> {
2112        let file_names = if verbatim {
2113            vec![name.to_owned()]
2114        } else {
2115            match self.static_library_naming() {
2116                Some(StaticLibraryNaming::Msvc) => {
2117                    vec![format!("{name}.lib"), format!("lib{name}.a")]
2118                }
2119                Some(StaticLibraryNaming::Unix) => vec![format!("lib{name}.a")],
2120                None => return Err(()),
2121            }
2122        };
2123        Ok(self
2124            .parsed
2125            .iter()
2126            .filter_map(|argument| match argument {
2127                Argument::SearchPath { kind, path } if searches_native(kind) => Some(path),
2128                _ => None,
2129            })
2130            .flat_map(|directory| {
2131                file_names
2132                    .iter()
2133                    .map(move |file_name| directory.join(file_name))
2134            })
2135            .find(|candidate| candidate.is_file()))
2136    }
2137
2138    /// How the target names a static library, or `None` for a custom target
2139    /// specification, whose names only the specification knows.
2140    ///
2141    /// A bare name is a built-in target unless a specification file for it
2142    /// exists where rustc would look, under `RUST_TARGET_PATH` or in the
2143    /// sysroot, which the caller reports through
2144    /// [`ParseOptions::custom_target_search`].
2145    fn static_library_naming(&self) -> Option<StaticLibraryNaming> {
2146        let Some(target) = self.target.as_deref() else {
2147            return Some(if cfg!(any(target_env = "msvc", target_os = "uefi")) {
2148                StaticLibraryNaming::Msvc
2149            } else {
2150                StaticLibraryNaming::Unix
2151            });
2152        };
2153        if target.ends_with(".json")
2154            || target.contains(['/', '\\'])
2155            || self.options.custom_target_search
2156        {
2157            return None;
2158        }
2159        // rustc's `is_like_msvc` targets: `*-windows-msvc`, `*-win7-windows-msvc`,
2160        // and the UEFI targets, which borrow the MSVC toolchain's conventions.
2161        Some(if target.contains("msvc") || target.ends_with("-uefi") {
2162            StaticLibraryNaming::Msvc
2163        } else {
2164            StaticLibraryNaming::Unix
2165        })
2166    }
2167
2168    fn parse_input(&mut self, value: &str) -> Result<(), BypassReason> {
2169        if value == "-" {
2170            return Err(BypassReason::StandardInput);
2171        }
2172        if self.source.replace(value.into()).is_some() {
2173            return Err(BypassReason::MultipleInputs);
2174        }
2175        Ok(())
2176    }
2177
2178    fn classify(&self) -> Result<LinkOutput, BypassReason> {
2179        // A compilation that emits no `link` produces exactly what an rlib's
2180        // metadata emit does -- dep-info and `lib<name>.rmeta` -- whatever it
2181        // calls its crate type. `cargo check` and clippy compile every binary
2182        // and test target this way, and those were bypassing as an
2183        // unsupported crate type for a linked artifact none of them asked
2184        // for. No linker runs, so nothing downstream needs a linker identity
2185        // to describe, and rustc names the metadata the same way for every
2186        // crate type.
2187        let never_links = !self.emits.iter().any(|emit| emit.kind == "link");
2188        let builds_a_library = !self.test
2189            && !self.crate_types.is_empty()
2190            && self
2191                .crate_types
2192                .iter()
2193                .all(|crate_type| matches!(crate_type.as_str(), "lib" | "rlib"));
2194        let link_output = if never_links || builds_a_library {
2195            LinkOutput::Library
2196        } else if self
2197            .target
2198            .as_deref()
2199            .is_some_and(compiler_bundled_wasm_target)
2200            && ((self.test && self.crate_types.is_empty())
2201                || matches!(self.crate_types.as_slice(), [kind] if kind == "bin" || kind == "cdylib"))
2202        {
2203            if self.parsed.iter().any(|argument| match argument {
2204                Argument::Plain(value) if value == "--codegen=link-self-contained" => false,
2205                Argument::Plain(value) if value.starts_with("--codegen=link-self-contained=") => {
2206                    !matches!(
2207                        value.rsplit_once('=').map(|(_, value)| value),
2208                        Some("y" | "yes" | "on" | "true")
2209                    )
2210                }
2211                _ => false,
2212            }) {
2213                return Err(BypassReason::UnknownCodegenOption(
2214                    "link-self-contained".into(),
2215                ));
2216            }
2217            if self.target.as_deref().is_some_and(|target| target.contains("wasi"))
2218                && self.parsed.iter().any(|argument| {
2219                    matches!(argument, Argument::Plain(value) if value.strip_prefix("--codegen=target-feature=").is_some_and(|features| features.split(',').any(|feature| feature == "-crt-static")))
2220                })
2221            {
2222                return Err(BypassReason::UnknownCodegenOption(
2223                    "target-feature=-crt-static".into(),
2224                ));
2225            }
2226            // These targets use a linker and, where applicable, CRT objects
2227            // and libc shipped in the Rust toolchain. Unlike native linking,
2228            // there are no implicit host inputs outside compiler identity.
2229            LinkOutput::WasmExecutable
2230        } else if self.options.cache_native_links && self.links_a_native_artifact() {
2231            self.check_native_link_is_portable()?;
2232            if matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro") {
2233                LinkOutput::NativeProcMacro
2234            } else if matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib") {
2235                LinkOutput::NativeSharedLibrary
2236            } else {
2237                LinkOutput::NativeExecutable
2238            }
2239        } else if self.test {
2240            return Err(BypassReason::UnsupportedCrateType("test".into()));
2241        } else {
2242            return Err(BypassReason::UnsupportedCrateType(
2243                self.crate_types
2244                    .iter()
2245                    .find(|crate_type| !matches!(crate_type.as_str(), "lib" | "rlib"))
2246                    .cloned()
2247                    .unwrap_or_else(|| "bin".into()),
2248            ));
2249        };
2250        // A link argument is handed to the linker verbatim, and its text is all
2251        // the adapter has to go on. `-Clink-arg=-Tlink.x` names a linker script
2252        // resolved off the search path, `-Clink-arg=-fuse-ld=lld` replaces the
2253        // linker the identity in the key describes, and neither is told apart
2254        // from `/STACK:8000000` by any rule short of knowing the linker's own
2255        // grammar. Where nothing links there is nothing to tell apart: an rlib
2256        // or an rmeta is produced without a linker invocation, so the option is
2257        // inert and the key carries its text like any other codegen option.
2258        if link_output != LinkOutput::Library
2259            && let Some(option) = self.first_link_argument(link_output)
2260        {
2261            return Err(BypassReason::UnmodeledLinkArgument(option.to_owned()));
2262        }
2263        if self
2264            .parsed
2265            .iter()
2266            .any(|arg| matches!(arg, Argument::InstallName(_)))
2267            && !(cfg!(target_os = "macos") && link_output == LinkOutput::NativeProcMacro)
2268        {
2269            return Err(BypassReason::UnmodeledLinkArgument(
2270                "link-arg=-Wl,-install_name".into(),
2271            ));
2272        }
2273        // ld64 never searches an rpath directory while linking, so the
2274        // argument is modeled only for a native macOS link. GNU ld searches
2275        // it for a shared object's own dependencies, which the key cannot see.
2276        if self
2277            .parsed
2278            .iter()
2279            .any(|argument| matches!(argument, Argument::Rpath(_)))
2280            && !(link_output == LinkOutput::Library
2281                || cfg!(target_os = "macos")
2282                    && matches!(
2283                        link_output,
2284                        LinkOutput::NativeExecutable
2285                            | LinkOutput::NativeProcMacro
2286                            | LinkOutput::NativeSharedLibrary
2287                    ))
2288        {
2289            return Err(BypassReason::UnmodeledLinkArgument(
2290                "link-arg=-Wl,-rpath".into(),
2291            ));
2292        }
2293        // `-fuse-ld` is modeled only for native links, where the linker
2294        // identity probe resolves and pins the linker it names. A wasm or
2295        // other non-native link consuming the selection has no identity that
2296        // describes it, so it declines the action like any other link
2297        // argument. Where nothing links, the selection is inert and the key
2298        // carries its text.
2299        if let Some(selection) = self.parsed.iter().find_map(|argument| {
2300            let Argument::FuseLd(selection) = argument else {
2301                return None;
2302            };
2303            Some(selection.as_str())
2304        }) && !matches!(
2305            link_output,
2306            LinkOutput::Library
2307                | LinkOutput::NativeExecutable
2308                | LinkOutput::NativeProcMacro
2309                | LinkOutput::NativeSharedLibrary
2310        ) {
2311            return Err(BypassReason::UnmodeledLinkArgument(format!(
2312                "link-arg=-fuse-ld={selection}"
2313            )));
2314        }
2315        if self.parsed.iter().any(|argument| {
2316            matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker="))
2317        }) && !matches!(
2318            link_output,
2319            LinkOutput::Library
2320                | LinkOutput::NativeExecutable
2321                | LinkOutput::NativeProcMacro
2322                | LinkOutput::NativeSharedLibrary
2323        ) {
2324            return Err(BypassReason::UnknownCodegenOption("linker".into()));
2325        }
2326        // `-Clinker-flavor` tells rustc how to drive the linker, which no
2327        // identity probe describes, so every real link declines it. An rlib or
2328        // a metadata-only compilation never reaches the linker, so the value
2329        // is inert there and the key carries its text.
2330        if link_output != LinkOutput::Library
2331            && self.parsed.iter().any(|argument| {
2332                matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker-flavor="))
2333            })
2334        {
2335            return Err(BypassReason::UnknownCodegenOption("linker-flavor".into()));
2336        }
2337        // `-oso_prefix` is modeled, but only where ld64 is the linker reading
2338        // it: a native macOS link. Any other linker sees an option this
2339        // adapter cannot vouch for, exactly like the arguments above.
2340        if !matches!(
2341            link_output,
2342            LinkOutput::Library
2343                | LinkOutput::NativeExecutable
2344                | LinkOutput::NativeProcMacro
2345                | LinkOutput::NativeSharedLibrary
2346        ) && self
2347            .parsed
2348            .iter()
2349            .any(|argument| matches!(argument, Argument::OsoPrefix { .. }))
2350        {
2351            return Err(BypassReason::UnmodeledLinkArgument(
2352                "link-arg=-Wl,-oso_prefix".into(),
2353            ));
2354        }
2355        if let Some(name) = self.parsed.iter().find_map(|argument| match argument {
2356            Argument::Extern { name, path: None } if name != "proc_macro" => Some(name),
2357            _ => None,
2358        }) {
2359            return Err(BypassReason::UnresolvedExtern(name.clone()));
2360        }
2361        if let Some(emit) = self
2362            .emits
2363            .iter()
2364            .find(|emit| !matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata"))
2365        {
2366            return Err(BypassReason::UnsupportedEmit(emit.kind.clone()));
2367        }
2368        if !self
2369            .emits
2370            .iter()
2371            .any(|emit| matches!(emit.kind.as_str(), "link" | "metadata"))
2372        {
2373            return Err(BypassReason::NoCacheableOutput);
2374        }
2375        Ok(link_output)
2376    }
2377}
2378
2379impl Parser<'_> {
2380    /// The first `-C link-arg` or `-C link-args` option in the invocation,
2381    /// rendered as it appears in the action key.
2382    fn first_link_argument(&self, link_output: LinkOutput) -> Option<&str> {
2383        self.parsed.iter().find_map(|argument| {
2384            let Argument::Plain(value) = argument else {
2385                return None;
2386            };
2387            let option = value.strip_prefix("--codegen=")?;
2388            let (name, value) = option.split_once('=').unwrap_or((option, ""));
2389            (matches!(name, "link-arg" | "link-args")
2390                && !(name == "link-arg" && elf_keyword_is_modeled(link_output, value))
2391                && !msvc_options_are_modeled(link_output, name, value))
2392            .then_some(option)
2393        })
2394    }
2395
2396    /// Whether an `-oso_prefix` strips the directory this link's objects live
2397    /// in from the debug map ld64 records.
2398    ///
2399    /// The objects a native link reads -- this unit's own compiled objects
2400    /// and the rlibs it links -- sit in the output directory, so a prefix
2401    /// covering that directory leaves the debug map naming spellings every
2402    /// checkout shares. Toolchain objects stay absolute, as they do in the
2403    /// paths rustc itself embeds on every platform.
2404    fn oso_prefix_covers_outputs(&self) -> bool {
2405        let Some(directory) = self
2406            .out_dir
2407            .as_deref()
2408            .or_else(|| self.explicit_output.as_deref().and_then(Path::parent))
2409        else {
2410            return false;
2411        };
2412        if !directory.is_absolute() {
2413            return false;
2414        }
2415        let directory = normalize_components(directory);
2416        self.parsed.iter().any(|argument| {
2417            let Argument::OsoPrefix { path, .. } = argument else {
2418                return false;
2419            };
2420            path.is_absolute()
2421                && (directory.starts_with(normalize_components(path))
2422                    || std::fs::canonicalize(&directory)
2423                        .ok()
2424                        .zip(std::fs::canonicalize(path).ok())
2425                        .is_some_and(|(directory, prefix)| directory.starts_with(prefix)))
2426        })
2427    }
2428
2429    /// Whether this invocation links an artifact for the host.
2430    ///
2431    /// An explicit `--target` bypasses even when it spells the host triple:
2432    /// rustc without one links for the host by construction, which is the
2433    /// cheapest description of "the linker this adapter can identify", and
2434    /// cargo omits it for host builds anyway.
2435    fn links_a_native_artifact(&self) -> bool {
2436        self.target.is_none()
2437            // A compilation that emits no linked artifact did not link, so it
2438            // needs no linker to describe it. `cargo check --tests` asks for
2439            // metadata alone, and reading that as a link would send it looking
2440            // for a linker identity and refusing flags no linker ever saw.
2441            && self.emits.iter().any(|emit| emit.kind == "link")
2442            && ((self.test && self.crate_types.is_empty())
2443                || matches!(self.crate_types.as_slice(), [kind] if matches!(kind.as_str(), "bin" | "proc-macro"))
2444                || (cfg!(target_os = "linux")
2445                    && matches!(self.crate_types.as_slice(), [kind] if kind == "cdylib")))
2446    }
2447
2448    /// Reject a native link whose result depends on something the key cannot
2449    /// describe, or that leaves artifacts beside the ones mbx would store.
2450    ///
2451    /// Each check names a value rather than a flag: an option absent from the
2452    /// invocation keeps rustc's default, which the compiler identity already
2453    /// pins, while any other spelling is refused rather than guessed at.
2454    fn check_native_link_is_portable(&self) -> Result<(), BypassReason> {
2455        for argument in &self.parsed {
2456            let Argument::Plain(value) = argument else {
2457                continue;
2458            };
2459            // `-g` is rustc's shorthand for debug info, and arrives as itself
2460            // rather than as a codegen option.
2461            let (name, value) = if value == "-g" {
2462                ("debuginfo", Some("2"))
2463            } else if let Some(option) = value.strip_prefix("--codegen=") {
2464                match option.split_once('=') {
2465                    Some((name, value)) => (name, Some(value)),
2466                    // A codegen flag with no value asks for its enabled form,
2467                    // which is what cargo passes for `-Crpath`. Reading it as
2468                    // "nothing to check" is how these slipped through.
2469                    None => (option, None),
2470                }
2471            } else {
2472                continue;
2473            };
2474            let unportable = match name {
2475                // Packed debug info leaves a .dSYM bundle or .dwp file beside
2476                // the binary, and mbx stores neither. Unpacked is macOS's
2477                // debug-map arrangement -- debug info stays in the objects and
2478                // nothing lands beside the binary -- so the same covering
2479                // `-oso_prefix` that makes the debug map portable covers it.
2480                "split-debuginfo" => match value {
2481                    Some("off") => false,
2482                    Some("unpacked") if cfg!(target_os = "macos") => {
2483                        !self.oso_prefix_covers_outputs()
2484                    }
2485                    _ => true,
2486                },
2487                // ld64 records absolute object paths and their timestamps in
2488                // the binary's debug map, so the same source links to
2489                // different bytes in another checkout -- or the same one
2490                // twice. An `-oso_prefix` covering the output directory
2491                // strips those paths down to spellings every checkout
2492                // shares, which is the same leniency a Linux link already
2493                // gets for the paths rustc itself embeds; what remains
2494                // (object timestamps) only shows up under verification.
2495                "debuginfo" if cfg!(target_os = "macos") => {
2496                    !matches!(value, Some("0" | "none")) && !self.oso_prefix_covers_outputs()
2497                }
2498                // An rpath and a dynamically linked native program embed this
2499                // checkout's absolute target directory. Cargo also passes
2500                // `prefer-dynamic` to proc macros, but their dynamic runtime
2501                // is rustc's own sysroot (already pinned by compiler identity),
2502                // while Cargo's dependencies are linked into the macro. There
2503                // is no checkout rpath to carry; keep rejecting an explicit
2504                // `rpath` independently.
2505                "rpath" => is_enabled(value),
2506                "prefer-dynamic" => {
2507                    is_enabled(value)
2508                        && !matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro")
2509                }
2510                // The CRT objects a self-contained link uses come from
2511                // somewhere other than where the driver reports.
2512                "link-self-contained" => true,
2513                _ => false,
2514            };
2515            if unportable {
2516                return Err(BypassReason::UnportableNativeLink(match value {
2517                    Some(value) => format!("{name}={value}"),
2518                    None => name.to_owned(),
2519                }));
2520            }
2521        }
2522        Ok(())
2523    }
2524}
2525
2526fn safe_install_name(name: &str) -> bool {
2527    !name.is_empty()
2528        && name
2529            .bytes()
2530            .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
2531}
2532
2533/// Whether a boolean codegen option is asking for its enabled form. Absent a
2534/// value, rustc reads the flag itself as the request.
2535fn is_enabled(value: Option<&str>) -> bool {
2536    matches!(value, None | Some("y" | "yes" | "on" | "true"))
2537}
2538
2539/// Whether `-Wl,-z,KEYWORD` is a native Linux link option the key can carry
2540/// as text.
2541///
2542/// A link argument is refused because its text cannot say whether it names a
2543/// file. These keywords are the exception: each sets a flag or a dynamic
2544/// section entry in the ELF output and reads nothing, in every linker the
2545/// identity probe resolves (GNU ld, gold, lld, and mold all spell them the
2546/// same). napi-build passes `-z nodelete` to every Node-API addon, so without
2547/// it no such addon caches.
2548fn elf_keyword_is_modeled(link_output: LinkOutput, value: &str) -> bool {
2549    cfg!(target_os = "linux")
2550        && matches!(
2551            link_output,
2552            LinkOutput::NativeExecutable
2553                | LinkOutput::NativeProcMacro
2554                | LinkOutput::NativeSharedLibrary
2555        )
2556        && value.strip_prefix("-Wl,-z,").is_some_and(|keyword| {
2557            matches!(
2558                keyword,
2559                "defs"
2560                    | "lazy"
2561                    | "nodelete"
2562                    | "nodlopen"
2563                    | "noexecstack"
2564                    | "norelro"
2565                    | "now"
2566                    | "origin"
2567                    | "relro"
2568            )
2569        })
2570}
2571
2572/// `-C link-arg` / `-C link-args` values that `link.exe` and `lld-link` read
2573/// as a plain switch or number and never as a file name.
2574///
2575/// `-C link-arg=/STACK:8000000` is how projects raise the main thread's stack
2576/// for Windows, usually through a `rustflags` entry in `.cargo/config.toml`
2577/// that reaches every proc macro, build script, and binary the workspace
2578/// builds. Refusing it leaves each of those linking on every build, and a MSVC
2579/// link is not reproducible (the PE header and PDB carry a timestamp and a
2580/// GUID), so each fresh proc-macro DLL hashes differently and every crate
2581/// compiled against it misses too.
2582///
2583/// Only spellings whose grammar is closed are listed: a number after
2584/// `/STACK:`, and `/Brepro`, which makes the link reproducible. Anything else
2585/// (`/DEF:`, `/MANIFESTINPUT:`, `/LIBPATH:`, a bare file name) can name a file
2586/// the key never hashes, so it still bypasses.
2587fn msvc_options_are_modeled(link_output: LinkOutput, name: &str, value: &str) -> bool {
2588    cfg!(target_env = "msvc")
2589        && matches!(
2590            link_output,
2591            LinkOutput::NativeExecutable
2592                | LinkOutput::NativeProcMacro
2593                | LinkOutput::NativeSharedLibrary
2594        )
2595        && match name {
2596            "link-arg" => msvc_option_reads_no_file(value),
2597            // The plural spelling is a whitespace-separated list, each entry
2598            // of which has to qualify.
2599            "link-args" => {
2600                let mut options = value.split_ascii_whitespace().peekable();
2601                options.peek().is_some() && options.all(msvc_option_reads_no_file)
2602            }
2603            _ => false,
2604        }
2605}
2606
2607/// One MSVC linker option from the closed list in [`msvc_options_are_modeled`].
2608/// The linker takes `-` for `/` and ignores the case of option names, and so
2609/// does this.
2610fn msvc_option_reads_no_file(option: &str) -> bool {
2611    let Some(option) = option.strip_prefix(['/', '-']) else {
2612        return false;
2613    };
2614    if option.eq_ignore_ascii_case("brepro") {
2615        return true;
2616    }
2617    let Some((name, sizes)) = option.split_once(':') else {
2618        return false;
2619    };
2620    // `/STACK:reserve[,commit]`. Sizes are decimal or `0x` hexadecimal, and
2621    // nothing else, so a value cannot smuggle in a path.
2622    let is_size = |size: &str| match size.strip_prefix("0x").or_else(|| size.strip_prefix("0X")) {
2623        Some(hex) => !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit()),
2624        None => !size.is_empty() && size.bytes().all(|byte| byte.is_ascii_digit()),
2625    };
2626    name.eq_ignore_ascii_case("stack")
2627        && sizes.split(',').count() <= 2
2628        && sizes.split(',').all(is_size)
2629}
2630
2631fn compiler_bundled_wasm_target(target: &str) -> bool {
2632    COMPILER_BUNDLED_WASM_TARGETS.binary_search(&target).is_ok()
2633}
2634
2635fn parse_emits(value: &str) -> Vec<Emit> {
2636    value
2637        .split(',')
2638        .map(|emit| {
2639            let (kind, path) = emit
2640                .split_once('=')
2641                .map_or((emit, None), |(kind, path)| (kind, Some(path.into())));
2642            Emit {
2643                kind: kind.into(),
2644                path,
2645            }
2646        })
2647        .collect()
2648}
2649
2650struct ActionBuilder<'a> {
2651    invocation: &'a RustcInvocation,
2652    store_root: &'a str,
2653    context: ActionContext,
2654    mappings: Vec<SharedPathMapping>,
2655    /// The directories resolved while building this one action. Its inputs
2656    /// share a few parents, and resolving each once is what keeps a crate
2657    /// with hundreds of them from paying a `realpath` walk per input.
2658    aliases: PathAliases,
2659    linker: Option<LinkerIdentity>,
2660    incremental_state: Option<String>,
2661}
2662
2663impl<'a> ActionBuilder<'a> {
2664    fn new(invocation: &'a RustcInvocation, mut context: ActionContext) -> Self {
2665        context.path_mappings = PathMapping::ordered(&context.path_mappings);
2666        let mappings = resolve_path_mappings(&shared_path_mappings(&context.path_mappings));
2667        Self {
2668            linker: None,
2669            incremental_state: None,
2670            invocation,
2671            store_root: NIX_STORE_ROOT,
2672            mappings,
2673            aliases: PathAliases::default(),
2674            context,
2675        }
2676    }
2677
2678    fn linked_by(mut self, linker: Option<LinkerIdentity>) -> Self {
2679        self.linker = linker;
2680        self
2681    }
2682
2683    fn carrying_incremental_state(mut self, generation: Option<String>) -> Self {
2684        self.incremental_state = generation;
2685        self
2686    }
2687
2688    fn build(self) -> Result<RustcAction, BypassReason> {
2689        self.validate_mappings()?;
2690        let invocation = self.invocation_descriptor()?;
2691        let environment = self.environment_descriptor()?;
2692
2693        let mut inputs = BTreeMap::<String, CacheDigest>::new();
2694        for input in &self.context.inputs {
2695            input
2696                .digest
2697                .validate()
2698                .map_err(|_| BypassReason::InvalidInputDigest(input.path.display().to_string()))?;
2699            let path = self.normalize_input_path(&input.path)?;
2700            if inputs
2701                .insert(path.clone(), input.digest.clone())
2702                .is_some_and(|existing| existing != input.digest)
2703            {
2704                return Err(BypassReason::ConflictingInput(path));
2705            }
2706        }
2707        let required = self
2708            .invocation
2709            .required_inputs
2710            .iter()
2711            .map(|path| self.normalize_input_path(path))
2712            .collect::<Result<BTreeSet<_>, _>>()?;
2713        if let Some(missing) = required.iter().find(|path| !inputs.contains_key(*path)) {
2714            return Err(BypassReason::MissingRequiredInput(missing.clone()));
2715        }
2716        let inputs = inputs
2717            .into_iter()
2718            .map(|(path, digest)| InputDescriptor { path, digest })
2719            .collect();
2720        // A native link without a linker identity would be keyed as though the
2721        // host did not matter. Refuse rather than publish that claim.
2722        if self.invocation.links_natively() && self.linker.is_none() {
2723            return Err(BypassReason::UnportableNativeLink(
2724                "linker identity is unknown".into(),
2725            ));
2726        }
2727        let descriptor = ActionDescriptor {
2728            version: ACTION_SCHEMA_VERSION,
2729            kind: "rustc",
2730            adapter_version: ADAPTER_VERSION,
2731            compiler: invocation.compiler,
2732            arguments: invocation.arguments,
2733            environment,
2734            inputs,
2735            linker: self.linker.clone(),
2736            incremental_state: self.incremental_state.clone(),
2737        };
2738        let bytes = canonical_json(&descriptor)
2739            .map_err(|error| BypassReason::Serialization(error.to_string()))?;
2740        let digest = CacheDigest::blake3(&bytes);
2741        Ok(RustcAction { digest, bytes })
2742    }
2743
2744    fn invocation_descriptor(&self) -> Result<InvocationDescriptor, BypassReason> {
2745        self.validate_mappings()?;
2746        let arguments = self
2747            .invocation
2748            .arguments
2749            .iter()
2750            .map(|argument| self.normalize_argument(argument))
2751            .collect::<Result<Vec<_>, _>>()?;
2752        let required_inputs = self
2753            .invocation
2754            .required_inputs
2755            .iter()
2756            .map(|path| self.normalize_file_path(path))
2757            .collect::<Result<BTreeSet<_>, _>>()?
2758            .into_iter()
2759            .collect();
2760        Ok(InvocationDescriptor {
2761            version: ACTION_SCHEMA_VERSION,
2762            kind: "rustc",
2763            adapter_version: ADAPTER_VERSION,
2764            compiler: CompilerDescriptor {
2765                toolchain: self.context.compiler.toolchain.clone(),
2766                rustc_version: self.context.compiler.rustc_version.clone(),
2767                host: self.context.compiler.host.clone(),
2768                driver: self.context.compiler.driver.clone(),
2769            },
2770            arguments,
2771            required_inputs,
2772        })
2773    }
2774
2775    fn validate_mappings(&self) -> Result<(), BypassReason> {
2776        if !self.context.working_dir.is_absolute() {
2777            return Err(BypassReason::RelativeWorkingDirectory(
2778                self.context.working_dir.clone(),
2779            ));
2780        }
2781        let mut roots = BTreeSet::new();
2782        let mut placeholders = BTreeSet::new();
2783        for mapping in &self.mappings {
2784            if !mapping.root.is_absolute() {
2785                return Err(BypassReason::RelativePathMapping(mapping.root.clone()));
2786            }
2787            if mapping.placeholder.is_empty()
2788                || !mapping
2789                    .placeholder
2790                    .bytes()
2791                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
2792                || !roots.insert(normalize_components(&mapping.root))
2793                || !placeholders.insert(&mapping.placeholder)
2794            {
2795                return Err(BypassReason::InvalidPathPlaceholder(
2796                    mapping.placeholder.clone(),
2797                ));
2798            }
2799        }
2800        Ok(())
2801    }
2802
2803    fn normalize_argument(&self, argument: &Argument) -> Result<String, BypassReason> {
2804        match argument {
2805            Argument::Plain(value) => Ok(value.clone()),
2806            Argument::Path { flag, path } if flag == "--sysroot" => {
2807                Ok(format!("{flag}={}", self.normalize_sysroot_path(path)?))
2808            }
2809            Argument::Path { flag, path } => Ok(format!("{flag}={}", self.normalize_path(path)?)),
2810            Argument::SearchPath { kind, path } => {
2811                let text = self.normalize_path(path)?;
2812                Ok(format!("-L{kind}={text}"))
2813            }
2814            Argument::Extern { name, path } => match path {
2815                Some(path) => Ok(format!(
2816                    "--extern={name}={}",
2817                    self.normalize_file_path(path)?
2818                )),
2819                None => Ok(format!("--extern={name}")),
2820            },
2821            Argument::Emit(emits) => Ok(format!(
2822                "--emit={}",
2823                emits
2824                    .iter()
2825                    .map(|emit| match &emit.path {
2826                        Some(path) => self
2827                            .normalize_path(path)
2828                            .map(|path| format!("{}={path}", emit.kind)),
2829                        None => Ok(emit.kind.clone()),
2830                    })
2831                    .collect::<Result<Vec<_>, _>>()?
2832                    .join(",")
2833            )),
2834            Argument::RemapPath { from, to } => Ok(format!(
2835                "--remap-path-prefix={}={}",
2836                self.normalize_path(from)?,
2837                to
2838            )),
2839            Argument::InstallName(name) => Ok(format!(
2840                "--codegen=link-arg=-Wl,-install_name,@rpath/{name}"
2841            )),
2842            Argument::OsoPrefix {
2843                path,
2844                trailing_slash,
2845            } => Ok(format!(
2846                "--codegen=link-arg=-Wl,-oso_prefix,{}{}",
2847                self.normalize_path(path)?,
2848                if *trailing_slash { "/" } else { "" }
2849            )),
2850            Argument::FuseLd(selection) => Ok(format!("--codegen=link-arg=-fuse-ld={selection}")),
2851            // Keyed as written: the directory is only recorded in the output.
2852            Argument::Rpath(directory) => Ok(format!("--codegen=link-arg=-Wl,-rpath,{directory}")),
2853        }
2854    }
2855
2856    /// Environment values enter the key verbatim, because rustc may embed one
2857    /// through `env!`: unlike a path used to locate an input, changing the value
2858    /// changes the artifact.
2859    ///
2860    /// A name in `portable_environment` is the exception the caller has earned.
2861    /// Its value normalizes like any other path, so two checkouts agree on it.
2862    fn environment_descriptor(&self) -> Result<BTreeMap<String, Option<String>>, BypassReason> {
2863        self.context
2864            .environment
2865            .iter()
2866            .map(|(name, value)| {
2867                let value = match value {
2868                    Some(value) if self.context.portable_environment.contains(name) => {
2869                        Some(self.normalize_path(Path::new(value))?)
2870                    }
2871                    value => value.clone(),
2872                };
2873                Ok((name.clone(), value))
2874            })
2875            .collect()
2876    }
2877
2878    fn normalize_input_path(&self, path: &Path) -> Result<String, BypassReason> {
2879        let absolute = normalize_components(&self.context.working_dir.join(path));
2880        for directory in self.invocation.native_search_paths() {
2881            let directory = normalize_components(&self.context.working_dir.join(directory));
2882            if let Ok(relative) = absolute.strip_prefix(&directory) {
2883                // Preserve the searched filename. Resolving a symlink here
2884                // would collapse libssl.dylib into its versioned referent, so
2885                // retargeting that link between two existing files could leave
2886                // the input map unchanged. Discovery rejects directory links
2887                // inside the tree and hashes regular-file links by content.
2888                let suffix = relative
2889                    .components()
2890                    .map(|component| {
2891                        component
2892                            .as_os_str()
2893                            .to_str()
2894                            .ok_or_else(|| BypassReason::NonUtf8Path(path.to_path_buf()))
2895                    })
2896                    .collect::<Result<Vec<_>, _>>()?
2897                    .join("/");
2898                if !suffix.is_empty() {
2899                    return Ok(format!("{}/{}", self.normalize_path(&directory)?, suffix));
2900                }
2901            }
2902        }
2903        self.normalize_file_path(path)
2904    }
2905
2906    fn normalize_sysroot_path(&self, path: &Path) -> Result<String, BypassReason> {
2907        let absolute = self.context.working_dir.join(path);
2908        if !absolute.starts_with(self.store_root) {
2909            return self.normalize_path(path);
2910        }
2911        // Dep-info omits implicit libraries from the sysroot. Its literal
2912        // path can identify them only when the directory stays in the store.
2913        if let Some(value) = absolute.to_str()
2914            && resolve_nix_store_path(value, self.store_root).is_some_and(|path| path.is_dir())
2915        {
2916            return Ok(value.to_owned());
2917        }
2918        Err(BypassReason::UnmappedAbsolutePath(absolute))
2919    }
2920
2921    fn normalize_file_path(&self, path: &Path) -> Result<String, BypassReason> {
2922        self.normalize_path(path)
2923            .or_else(|reason| key_nix_store_path(path, &self.context.working_dir, reason))
2924    }
2925
2926    fn normalize_path(&self, path: &Path) -> Result<String, BypassReason> {
2927        normalize_resolved_shared_path_with(
2928            &self.aliases,
2929            path,
2930            &self.context.working_dir,
2931            &self.mappings,
2932        )
2933        .map_err(Into::into)
2934    }
2935}
2936
2937/// Whether a normalized path names something strictly beneath one of
2938/// `directories`, which are normalized the same way and so share its `/`
2939/// separator regardless of platform.
2940fn under_any_directory(path: &str, directories: &BTreeSet<String>) -> bool {
2941    directories.iter().any(|directory| {
2942        path.len() > directory.len()
2943            && path.as_bytes()[directory.len()] == b'/'
2944            && path.starts_with(directory)
2945    })
2946}
2947
2948fn denormalize_path(
2949    value: &str,
2950    mappings: &[PathMapping],
2951    store_root: &str,
2952) -> Result<PathBuf, BypassReason> {
2953    for mapping in mappings {
2954        let prefix = format!("${{{}}}", mapping.placeholder);
2955        let suffix = if value == prefix {
2956            ""
2957        } else if let Some(suffix) = value.strip_prefix(&format!("{prefix}/")) {
2958            suffix
2959        } else {
2960            continue;
2961        };
2962        if !mapping.root.is_absolute()
2963            || (!suffix.is_empty()
2964                && suffix.split('/').any(|component| {
2965                    component.is_empty()
2966                        || matches!(component, "." | "..")
2967                        || component.contains('\\')
2968                }))
2969        {
2970            return Err(BypassReason::InvalidPredictedInput(value.into()));
2971        }
2972        let mut path = normalize_components(&mapping.root);
2973        path.extend(suffix.split('/').filter(|component| !component.is_empty()));
2974        return Ok(path);
2975    }
2976    // Predictions can come from a shared cache. Check the symlink target as
2977    // well as the spelling before allowing the caller to read the file.
2978    if resolve_nix_store_path(value, store_root).is_some() {
2979        return Ok(PathBuf::from(value));
2980    }
2981    Err(BypassReason::InvalidPredictedInput(value.into()))
2982}
2983
2984fn resolve_nix_store_path(value: &str, store_root: &str) -> Option<PathBuf> {
2985    let resolved = nix_store_path(value, store_root)?.canonicalize().ok()?;
2986    nix_store_path(resolved.to_str()?, store_root)?;
2987    Some(resolved)
2988}
2989
2990fn nix_store_path<'a>(value: &'a str, store_root: &str) -> Option<&'a Path> {
2991    let path = Path::new(value);
2992    if !path.is_absolute() {
2993        return None;
2994    }
2995    let suffix = value.strip_prefix(store_root)?.strip_prefix('/')?;
2996    (!suffix.split('/').any(|component| {
2997        component.is_empty() || matches!(component, "." | "..") || component.contains('\0')
2998    }))
2999    .then_some(path)
3000}
3001
3002fn key_nix_store_path(
3003    path: &Path,
3004    working_dir: &Path,
3005    reason: BypassReason,
3006) -> Result<String, BypassReason> {
3007    if matches!(reason, BypassReason::UnmappedAbsolutePath(_)) {
3008        let absolute = working_dir.join(path);
3009        if let Some(value) = absolute.to_str()
3010            && nix_store_path(value, NIX_STORE_ROOT).is_some()
3011        {
3012            return Ok(value.to_owned());
3013        }
3014    }
3015    Err(reason)
3016}
3017
3018fn normalize_components(path: &Path) -> PathBuf {
3019    let mut normalized = PathBuf::new();
3020    for component in path.components() {
3021        match component {
3022            Component::CurDir => {}
3023            Component::ParentDir => {
3024                normalized.pop();
3025            }
3026            component => normalized.push(component.as_os_str()),
3027        }
3028    }
3029    normalized
3030}
3031
3032fn absolute_path(path: &Path, working_dir: &Path) -> PathBuf {
3033    if path.is_absolute() {
3034        normalize_components(path)
3035    } else {
3036        normalize_components(&working_dir.join(path))
3037    }
3038}
3039
3040#[cfg(test)]
3041#[path = "rustc_cache_tests.rs"]
3042mod tests;