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, PathMapping as SharedPathMapping, PathNormalizationError,
33    canonical_json, normalize_mapped_path as normalize_shared_path,
34    normalize_resolved_mapped_path as normalize_resolved_shared_path, resolve_path_mappings,
35};
36use serde::{Deserialize, Deserializer, Serialize, Serializer};
37use std::collections::{BTreeMap, BTreeSet};
38use std::ffi::OsString;
39use std::path::{Component, Path, PathBuf};
40use thiserror::Error;
41
42mod dep_info;
43
44pub use dep_info::{DepInfoCommand, DiscoveredInputs, RustcDepInfo};
45
46/// Schema version embedded in canonical rustc action descriptors.
47pub const ACTION_SCHEMA_VERSION: u8 = 1;
48/// Version of the rustc argument and input model used to construct keys.
49///
50/// Bumped to 2 when the dep-info and diagnostics stored with a result stopped
51/// carrying the publishing checkout's absolute paths. Entries written before
52/// that hold the old spelling, and nothing in them says so, so they are retired
53/// by the key rather than restored into a checkout they do not describe.
54pub const ADAPTER_VERSION: u8 = 2;
55
56impl BypassReason {
57    /// A stable, low-cardinality name for this reason.
58    ///
59    /// Many variants carry a path or a flag, so `Display` text cannot be
60    /// aggregated; statistics group by this instead.
61    pub fn kind(&self) -> &'static str {
62        self.into()
63    }
64
65    /// A concrete change that can make this invocation cacheable, when one is
66    /// available.
67    ///
68    /// Expected probes and failures that require adapter support return
69    /// `None`; callers can still explain those from [`BypassReason::kind`].
70    pub fn remediation(&self) -> Option<&'static str> {
71        match self {
72            Self::Incremental => Some(
73                "Set `MBX_INCREMENTAL=0`; mbx will then disable Cargo incremental state and cache the compilation.",
74            ),
75            Self::UnportableNativeLink(detail) if detail.contains("linker") => Some(
76                "Make the native linker resolvable on `PATH`, or configure a linker mbx can identify for this target.",
77            ),
78            Self::UnportableNativeLink(_) => Some(
79                "Remove the reported `-C` option from the active Cargo profile or `RUSTFLAGS` to make these links cacheable.",
80            ),
81            Self::UnknownFlag(_) | Self::UnknownCodegenOption(_) => Some(
82                "Remove the reported compiler option, or upgrade mbx if the option should be modeled.",
83            ),
84            Self::UnmodeledLinkArgument(_) => Some(
85                "Remove the reported linker argument, or keep these links uncached if the argument is required.",
86            ),
87            Self::UnmappedAbsolutePath(_) => Some(
88                "Move the input under the workspace, target, Cargo, toolchain, or home roots so mbx can give it a portable cache name.",
89            ),
90            _ => None,
91        }
92    }
93}
94
95impl From<PathNormalizationError> for BypassReason {
96    fn from(reason: PathNormalizationError) -> Self {
97        match reason {
98            PathNormalizationError::UnmappedAbsolutePath(path) => Self::UnmappedAbsolutePath(path),
99            PathNormalizationError::NonUtf8Path(path) => Self::NonUtf8Path(path),
100        }
101    }
102}
103
104const SUPPORTED_CODEGEN_OPTIONS: &[&str] = &[
105    "codegen-units",
106    "control-flow-guard",
107    "debug-assertions",
108    "debuginfo",
109    "default-linker-libraries",
110    "embed-bitcode",
111    "extra-filename",
112    "force-frame-pointers",
113    "force-unwind-tables",
114    "instrument-coverage",
115    "link-arg",
116    "link-args",
117    "link-dead-code",
118    "link-self-contained",
119    "lto",
120    "metadata",
121    "no-prepopulate-passes",
122    "opt-level",
123    "overflow-checks",
124    "panic",
125    "prefer-dynamic",
126    "relocation-model",
127    "rpath",
128    "save-temps",
129    "soft-float",
130    "split-debuginfo",
131    "split-dwarf-kind",
132    "strip",
133    "symbol-mangling-version",
134    "target-cpu",
135    "target-feature",
136    "tls-model",
137];
138
139const NATIVE_DIRECTORY_PREDICTION_PREFIX: &str = "@native-directory:";
140const MAX_PREDICTED_INPUTS: usize = 16 * 1024;
141// A compact payload is capped on the wire by the protocol. Bound its expanded
142// form too, so a hostile prefix chain cannot turn a small manifest into an
143// unreasonable allocation while it is being decoded.
144const MAX_DECODED_PREDICTION_BYTES: usize = 16 * 1024 * 1024;
145const MAX_NATIVE_INPUT_BYTES: u64 = 2 * 1024 * 1024 * 1024;
146
147/// Built-in WebAssembly targets whose default linkers and CRT inputs ship in
148/// the Rust toolchain. Custom target specs never enter this list.
149const COMPILER_BUNDLED_WASM_TARGETS: &[&str] = &[
150    "wasm32-unknown-unknown",
151    "wasm32-wasip1",
152    "wasm32-wasip1-threads",
153    "wasm32-wasip2",
154    "wasm32v1-none",
155    "wasm64-unknown-unknown",
156];
157
158#[derive(Debug, Clone, PartialEq, Eq, Error, strum::IntoStaticStr)]
159#[strum(serialize_all = "kebab-case")]
160/// Reason an invocation cannot safely use the action cache.
161///
162/// A bypass is an expected conservative outcome, not necessarily a compiler
163/// error. Variants carry diagnostic context while [`BypassReason::kind`]
164/// provides a stable aggregation key.
165///
166/// This set exists to shrink: every invocation the adapter learns to model
167/// retires a variant, and every construct it learns to reject adds one. Match
168/// on [`BypassReason::kind`] for aggregation rather than on the variants.
169#[non_exhaustive]
170pub enum BypassReason {
171    /// An argument cannot be represented in the canonical UTF-8 key.
172    #[error("rustc argument {index} is not valid UTF-8")]
173    NonUtf8Argument {
174        /// Zero-based index in the argument slice.
175        index: usize,
176    },
177    /// A rustc response file could not be read or parsed exactly.
178    #[error("could not model rustc response file: {0}")]
179    ResponseFile(String),
180    /// A compiler flag is not modeled by this adapter version.
181    #[error("rustc flag is not modeled by the cache adapter: {0}")]
182    UnknownFlag(String),
183    /// A `-C` option is not modeled by this adapter version.
184    #[error("rustc codegen option is not modeled by the cache adapter: {0}")]
185    UnknownCodegenOption(String),
186    /// A recognized flag was not followed by its required value.
187    #[error("rustc flag requires a value: {0}")]
188    MissingValue(String),
189    /// The invocation queries compiler information instead of compiling.
190    #[error("rustc invocation is a compiler query, not a compilation")]
191    CompilerQuery,
192    /// Source would be read from standard input and cannot be rediscovered.
193    #[error("rustc invocation reads source from standard input")]
194    StandardInput,
195    /// No Rust source input was supplied.
196    #[error("rustc invocation has no source input")]
197    MissingInput,
198    /// More than one source input was supplied.
199    #[error("rustc invocation has multiple source inputs")]
200    MultipleInputs,
201    /// Incremental state makes the outputs unsuitable for action caching.
202    #[error("incremental compilation cannot be combined with action caching")]
203    Incremental,
204    /// The requested crate type is outside the supported cacheability tier.
205    #[error("rustc crate type is not cacheable yet: {0}")]
206    UnsupportedCrateType(String),
207    /// The requested emit kind is outside the supported cacheability tier.
208    #[error("rustc output type is not cacheable yet: {0}")]
209    UnsupportedEmit(String),
210    /// The invocation emits no artifact in the supported cacheability tier.
211    #[error("rustc invocation does not emit a cacheable artifact")]
212    NoCacheableOutput,
213    /// The invocation does not emit the dep-info needed for input discovery.
214    #[error("rustc invocation does not emit dependency information")]
215    NoDepInfo,
216    /// Outputs cannot be represented as one cache directory.
217    #[error("rustc output paths do not share one directory")]
218    SplitOutputDirectories,
219    /// An output path does not name a file.
220    #[error("rustc output path has no file name: {0}")]
221    InvalidOutputPath(PathBuf),
222    /// `-o` leaves the name of an implicit emit ambiguous.
223    #[error("rustc -o with an emit that has no explicit path is not modeled: {0}")]
224    ImplicitEmitWithOutputFile(PathBuf),
225    /// Native-library lookup is not modeled as a precise input.
226    #[error("native library lookup is not cacheable yet")]
227    NativeLibrary,
228    /// An output's name does not say whether it is a program or a library.
229    #[error("rustc output name does not distinguish a program from a library: {0}")]
230    AmbiguousOutputName(PathBuf),
231    /// A native link would embed something no other checkout can reproduce.
232    #[error("native link is not reproducible across checkouts: {0}")]
233    UnportableNativeLink(String),
234    /// A linked output was given an argument to pass on to its linker.
235    #[error("rustc link argument is not modeled by the cache adapter: {0}")]
236    UnmodeledLinkArgument(String),
237    /// A library search-path kind is not modeled.
238    #[error("rustc search path kind is not cacheable yet: {0}")]
239    UnsupportedSearchPath(String),
240    /// An extern name does not resolve to a concrete input artifact.
241    #[error("rustc extern does not identify an input artifact: {0}")]
242    UnresolvedExtern(String),
243    /// An absolute path has no stable placeholder mapping.
244    #[error("absolute path has no stable cache mapping: {0}")]
245    UnmappedAbsolutePath(PathBuf),
246    /// A path cannot be represented in a canonical UTF-8 action key.
247    #[error("cache key paths must be valid UTF-8: {0}")]
248    NonUtf8Path(PathBuf),
249    /// The action working directory is not absolute.
250    #[error("cache action working directory must be absolute: {0}")]
251    RelativeWorkingDirectory(PathBuf),
252    /// A path-mapping root is not absolute.
253    #[error("cache path mapping must use an absolute root: {0}")]
254    RelativePathMapping(PathBuf),
255    /// A mapping placeholder is empty or contains unsafe characters.
256    #[error("cache path mapping placeholder is invalid: {0}")]
257    InvalidPathPlaceholder(String),
258    /// An input referenced by compiler arguments is missing from the context.
259    #[error("required compiler input was not provided: {0}")]
260    MissingRequiredInput(String),
261    /// A supplied compiler-input digest is malformed.
262    #[error("compiler input has an invalid digest: {0}")]
263    InvalidInputDigest(String),
264    /// One normalized input path has multiple distinct digests.
265    #[error("compiler input appears more than once with different content: {0}")]
266    ConflictingInput(String),
267    /// rustc dep-info does not follow the supported format.
268    #[error("rustc dep-info is malformed: {0}")]
269    MalformedDepInfo(String),
270    /// A dep-info file could not be read as UTF-8 text.
271    #[error("failed to read rustc dep-info {path}: {message}")]
272    DepInfoRead {
273        /// Dep-info file path.
274        path: PathBuf,
275        /// Underlying I/O or decoding error.
276        message: String,
277    },
278    /// The requested dep-info output path is not absolute.
279    #[error("rustc dep-info output path must be absolute: {0}")]
280    RelativeDepInfoPath(PathBuf),
281    /// A dep-info output path contains a comma and cannot be safely rendered.
282    #[error("rustc dep-info output path cannot contain a comma: {0}")]
283    UnsafeDepInfoPath(PathBuf),
284    /// A discovered compiler input could not be read or was not a file.
285    #[error("failed to read compiler input {path}: {message}")]
286    InputRead {
287        /// Compiler-input path.
288        path: PathBuf,
289        /// Underlying filesystem error.
290        message: String,
291    },
292    /// Input contents changed after they were hashed.
293    #[error("compiler input changed after discovery: {0}")]
294    InputChanged(PathBuf),
295    /// An input's modification time overlaps the compiler execution.
296    #[error("compiler input was modified during compilation: {0}")]
297    InputModifiedDuringCompilation(PathBuf),
298    /// Discovered inputs and the action use different working directories.
299    #[error("discovered inputs were collected from a different working directory")]
300    DiscoveryWorkingDirectory,
301    /// One observed environment input has conflicting values.
302    #[error("compiler environment input has conflicting values: {0}")]
303    ConflictingEnvironment(String),
304    /// Canonical action serialization failed.
305    #[error("failed to serialize the rustc action: {0}")]
306    Serialization(String),
307    /// The stored prediction uses an unsupported version or exceeds limits.
308    #[error("rustc action prediction is unsupported")]
309    UnsupportedPrediction,
310    /// A normalized predicted path cannot be mapped back to the host.
311    #[error("rustc action prediction contains an invalid input path: {0}")]
312    InvalidPredictedInput(String),
313}
314
315#[derive(Debug, Clone, PartialEq, Eq)]
316enum Argument {
317    Plain(String),
318    Path {
319        flag: String,
320        path: PathBuf,
321    },
322    SearchPath {
323        kind: String,
324        path: PathBuf,
325    },
326    Extern {
327        name: String,
328        path: Option<PathBuf>,
329    },
330    Emit(Vec<Emit>),
331    RemapPath {
332        from: PathBuf,
333        to: String,
334    },
335    /// An `-oso_prefix` handed to ld64, whose path strips checkout-specific
336    /// prefixes from the debug map the linker records.
337    OsoPrefix {
338        path: PathBuf,
339        trailing_slash: bool,
340    },
341    /// A `-fuse-ld=<name>` handed to the driver, selecting which linker a
342    /// link invokes. Modeled for native links only, where the linker identity
343    /// probe resolves and pins the linker it names.
344    FuseLd(String),
345}
346
347#[derive(Debug, Clone, PartialEq, Eq)]
348struct Emit {
349    kind: String,
350    path: Option<PathBuf>,
351}
352
353#[derive(Debug, Clone, PartialEq, Eq)]
354/// Parsed, cache-safe model of one `rustc` command line.
355///
356/// Fields are intentionally private so new modeled flags can be added without
357/// exposing the adapter's internal representation.
358pub struct RustcInvocation {
359    arguments: Vec<Argument>,
360    source: PathBuf,
361    required_inputs: Vec<PathBuf>,
362    crate_name: String,
363    extra_filename: String,
364    out_dir: Option<PathBuf>,
365    explicit_output: Option<PathBuf>,
366    emits: Vec<Emit>,
367    target: Option<String>,
368    link_output: LinkOutput,
369}
370
371#[derive(Debug, Clone, Copy, PartialEq, Eq)]
372enum LinkOutput {
373    Library,
374    WasmExecutable,
375    NativeExecutable,
376    NativeProcMacro,
377}
378
379/// What the caller is prepared to model beyond the default tier.
380///
381/// The parser itself stays pure: whether the host can describe its linker
382/// precisely enough to key a native link is the caller's question, and the
383/// answer arrives here rather than being read out of the environment.
384#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
385#[non_exhaustive]
386pub struct ParseOptions {
387    /// Admit natively linked test binaries, executables, and proc macros,
388    /// given a linker identity in the action key. Off by default.
389    pub cache_native_links: bool,
390}
391
392impl ParseOptions {
393    /// Options that admit native links when `enabled`.
394    pub fn caching_native_links(enabled: bool) -> Self {
395        Self {
396            cache_native_links: enabled,
397        }
398    }
399}
400
401/// The cacheable files and dependency manifest produced by a rustc invocation.
402#[derive(Debug, Clone, PartialEq, Eq)]
403pub struct RustcOutputs {
404    /// Common directory containing all modeled outputs.
405    pub directory: PathBuf,
406    /// Cacheable library, metadata, and/or linked program files.
407    pub files: Vec<PathBuf>,
408    /// Dep-info file used for precise input discovery.
409    pub dep_info: PathBuf,
410}
411
412impl RustcInvocation {
413    /// Parse rustc's arguments, excluding the compiler executable supplied as
414    /// the first argument to `RUSTC_WRAPPER`.
415    ///
416    /// Any flag whose cache semantics are not modeled returns a bypass reason
417    /// instead of guessing. A successful parse admits the rlib/rmeta tier,
418    /// every compilation that links nothing at all -- what `cargo check` and
419    /// clippy run, whatever the crate type -- and binaries linked by
420    /// compiler-bundled WebAssembly toolchains.
421    pub fn parse(arguments: &[OsString]) -> Result<Self, BypassReason> {
422        Self::parse_with(arguments, ParseOptions::default())
423    }
424
425    /// Parse as [`RustcInvocation::parse`] does, admitting what `options`
426    /// says the caller can model.
427    pub fn parse_with(arguments: &[OsString], options: ParseOptions) -> Result<Self, BypassReason> {
428        let expanded = expand_response_files(arguments)?;
429        Parser::new(&expanded.arguments, options).parse()
430    }
431
432    /// Whether this invocation links a native artifact, whose key must
433    /// therefore describe the linker that produced it.
434    pub fn links_natively(&self) -> bool {
435        matches!(
436            self.link_output,
437            LinkOutput::NativeExecutable | LinkOutput::NativeProcMacro
438        )
439    }
440
441    /// Linker selected with `-C linker`, if the invocation overrides rustc's
442    /// platform default.
443    pub fn linker_override(&self) -> Option<&Path> {
444        self.arguments.iter().find_map(|argument| {
445            let Argument::Plain(value) = argument else {
446                return None;
447            };
448            value.strip_prefix("--codegen=linker=").map(Path::new)
449        })
450    }
451
452    /// Linker selected with `-C link-arg=-fuse-ld=<name>`, if the invocation
453    /// passes one the adapter models.
454    pub fn fuse_ld(&self) -> Option<&str> {
455        self.arguments.iter().find_map(|argument| {
456            let Argument::FuseLd(selection) = argument else {
457                return None;
458            };
459            Some(selection.as_str())
460        })
461    }
462
463    fn emits_windows_pdb(&self) -> bool {
464        if !cfg!(windows) || !self.links_natively() {
465            return false;
466        }
467        let mut enabled = false;
468        for argument in &self.arguments {
469            let Argument::Plain(value) = argument else {
470                continue;
471            };
472            if value == "-g" {
473                enabled = true;
474            } else if let Some(value) = value.strip_prefix("--codegen=debuginfo=") {
475                enabled = !matches!(value, "0" | "none");
476            }
477        }
478        enabled
479    }
480
481    /// Whether the contents of native search directories cannot reach this
482    /// invocation's outputs.
483    ///
484    /// A library emit never runs a linker, so a `-L native` directory is only
485    /// read for a static library named by `-l` -- and any `-l` already bypasses
486    /// the whole invocation. On Windows every crate downstream of a `cc`-built
487    /// dependency carries the MSVC toolset's `-L native` directories, which sit
488    /// outside every checkout root; treating them as content inputs would leave
489    /// all of those compilations permanently uncacheable. A `#[link]` attribute
490    /// naming a bundled static library could in principle reach through such a
491    /// directory without an `-l` flag, but toolchain directories are
492    /// version-stamped by their path, which the key still carries verbatim.
493    fn native_search_is_inert(&self) -> bool {
494        self.link_output == LinkOutput::Library
495    }
496
497    /// Return the source input passed to rustc.
498    pub fn source(&self) -> &Path {
499        &self.source
500    }
501
502    /// Return the explicitly selected compilation target, if any.
503    pub fn target(&self) -> Option<&str> {
504        self.target.as_deref()
505    }
506
507    /// Return the crate name rustc will assign to this compilation.
508    pub fn crate_name(&self) -> &str {
509        &self.crate_name
510    }
511
512    /// Digest of the inputs this compilation owns: its sources and whatever
513    /// they read, but not the artifacts it merely links against.
514    ///
515    /// This is what separates a crate someone is editing from one sitting
516    /// above it in the graph. Rebuilding a dependency changes the action key of
517    /// every crate that links it, because their keys hash its artifact; it does
518    /// not change this. A caller watching for churn has to watch this instead,
519    /// or a single edited crate would drag its whole dependent cone along.
520    ///
521    /// Host paths enter the digest as they are. This describes one checkout to
522    /// itself rather than to the cache, so there is nothing here to make
523    /// portable.
524    pub fn source_fingerprint(&self, discovered: &DiscoveredInputs) -> CacheDigest {
525        let linked = self
526            .arguments
527            .iter()
528            .filter_map(|argument| match argument {
529                Argument::Extern {
530                    path: Some(path), ..
531                } => Some(path.as_path()),
532                _ => None,
533            })
534            .collect::<BTreeSet<_>>();
535        let owned = discovered
536            .inputs
537            .iter()
538            .filter(|input| !linked.contains(input.path.as_path()))
539            .map(|input| (input.path.as_path(), &input.digest))
540            .collect::<BTreeMap<_, _>>();
541        let mut bytes = Vec::new();
542        for (path, digest) in owned {
543            bytes.extend_from_slice(path.as_os_str().as_encoded_bytes());
544            bytes.push(0);
545            bytes.extend_from_slice(digest.key().as_bytes());
546            bytes.push(0);
547        }
548        CacheDigest::blake3(&bytes)
549    }
550
551    /// Resolve the files produced by this invocation.
552    ///
553    /// The initial cache tier requires one output directory so its artifact can
554    /// be represented by one protocol directory and restored atomically later.
555    pub fn outputs(&self, working_dir: &Path) -> Result<RustcOutputs, BypassReason> {
556        if !working_dir.is_absolute() {
557            return Err(BypassReason::RelativeWorkingDirectory(
558                working_dir.to_path_buf(),
559            ));
560        }
561        let explicit_output = self
562            .explicit_output
563            .as_deref()
564            .map(|path| absolute_path(path, working_dir));
565        let output_directory = explicit_output
566            .as_deref()
567            .and_then(Path::parent)
568            .map(Path::to_path_buf)
569            .or_else(|| {
570                self.out_dir
571                    .as_deref()
572                    .map(|path| absolute_path(path, working_dir))
573            })
574            .unwrap_or_else(|| normalize_components(working_dir));
575        // rustc applies `-o` to every emit that has no path of its own, so the
576        // file names cannot be derived from the crate name here. Cargo always
577        // uses --out-dir instead, so refusing to model this costs nothing.
578        if let Some(output) = &explicit_output
579            && self.emits.iter().any(|emit| {
580                emit.path.is_none()
581                    && matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata")
582            })
583        {
584            return Err(BypassReason::ImplicitEmitWithOutputFile(output.clone()));
585        }
586        let mut files = BTreeSet::new();
587        let mut dep_info = None;
588        for emit in &self.emits {
589            if emit.kind == "dep-info" {
590                let path = emit.path.as_ref().map_or_else(
591                    || {
592                        explicit_output.clone().map_or_else(
593                            || {
594                                output_directory
595                                    .join(format!("{}{}.d", self.crate_name, self.extra_filename))
596                            },
597                            |path| path.with_extension("d"),
598                        )
599                    },
600                    |path| absolute_path(path, working_dir),
601                );
602                if path.file_name().is_none() {
603                    return Err(BypassReason::InvalidOutputPath(path));
604                }
605                dep_info = Some(path);
606                continue;
607            }
608            let (prefix, extension) = match emit.kind.as_str() {
609                "link" => match self.link_output {
610                    LinkOutput::Library => ("lib", "rlib"),
611                    LinkOutput::WasmExecutable => ("", "wasm"),
612                    LinkOutput::NativeExecutable => ("", std::env::consts::EXE_EXTENSION),
613                    LinkOutput::NativeProcMacro => (
614                        std::env::consts::DLL_PREFIX,
615                        std::env::consts::DLL_SUFFIX.trim_start_matches('.'),
616                    ),
617                },
618                "metadata" => ("lib", "rmeta"),
619                _ => continue,
620            };
621            let path = if let Some(path) = &emit.path {
622                absolute_path(path, working_dir)
623            } else {
624                let name = format!("{prefix}{}{}", self.crate_name, self.extra_filename);
625                output_directory.join(if extension.is_empty() {
626                    name
627                } else {
628                    format!("{name}.{extension}")
629                })
630            };
631            if path.file_name().is_none() {
632                return Err(BypassReason::InvalidOutputPath(path));
633            }
634            if path.parent() != Some(output_directory.as_path()) {
635                return Err(BypassReason::SplitOutputDirectories);
636            }
637            // Whether a restored output is a program is read back off its name,
638            // so a program that answers to a library's name would be restored
639            // without the permission that makes it runnable. Nothing cargo
640            // emits looks like this; a hand-built invocation could.
641            let has_library_extension = path
642                .extension()
643                .and_then(|extension| extension.to_str())
644                .is_some_and(|extension| matches!(extension, "rlib" | "rmeta"))
645                || (cfg!(windows)
646                    && path
647                        .file_stem()
648                        .and_then(|stem| Path::new(stem).extension())
649                        .and_then(|extension| extension.to_str())
650                        .is_some_and(|extension| matches!(extension, "rlib" | "rmeta")));
651            if emit.kind == "link"
652                && !matches!(self.link_output, LinkOutput::Library)
653                && has_library_extension
654            {
655                return Err(BypassReason::AmbiguousOutputName(path));
656            }
657            if emit.kind == "link" && self.emits_windows_pdb() {
658                files.insert(path.with_extension("pdb"));
659            }
660            files.insert(path);
661        }
662        let dep_info = dep_info.ok_or(BypassReason::NoDepInfo)?;
663        if dep_info.parent() != Some(output_directory.as_path()) {
664            return Err(BypassReason::SplitOutputDirectories);
665        }
666        Ok(RustcOutputs {
667            directory: output_directory,
668            files: files.into_iter().collect(),
669            dep_info,
670        })
671    }
672
673    /// Build canonical action bytes after precise input discovery has run.
674    ///
675    /// `context.inputs` must contain the source, every explicit extern, and
676    /// every additional source or environment-generated input discovered from
677    /// dep-info.
678    pub fn action(&self, context: ActionContext) -> Result<RustcAction, BypassReason> {
679        self.action_linked_by(context, None)
680    }
681
682    /// Build canonical action bytes for an invocation that links a native
683    /// program.
684    ///
685    /// A `linker` is required whenever [`RustcInvocation::links_natively`]
686    /// holds: the linker, its startup objects, and the platform SDK are inputs
687    /// rustc dep-info does not enumerate, so a key without them would claim
688    /// more than it can support. Passing one for anything else is ignored,
689    /// since nothing else depends on a linker.
690    pub fn action_linked_by(
691        &self,
692        context: ActionContext,
693        linker: Option<LinkerIdentity>,
694    ) -> Result<RustcAction, BypassReason> {
695        ActionBuilder::new(self, context).linked_by(linker).build()
696    }
697
698    /// Fingerprint the modeled invocation before dependency contents are known.
699    pub fn invocation_digest(&self, context: &ActionContext) -> Result<CacheDigest, BypassReason> {
700        let descriptor = ActionBuilder::new(self, context.clone()).invocation_descriptor()?;
701        let bytes = canonical_json(&descriptor)
702            .map_err(|error| BypassReason::Serialization(error.to_string()))?;
703        Ok(CacheDigest::blake3(&bytes))
704    }
705
706    /// Capture normalized dependency paths for a future invocation that has no
707    /// dep-info file yet.
708    pub fn prediction(
709        &self,
710        context: &ActionContext,
711        discovered: &DiscoveredInputs,
712    ) -> Result<RustcInputPrediction, BypassReason> {
713        let builder = ActionBuilder::new(self, context.clone());
714        builder.validate_mappings()?;
715        let mut native_directories = BTreeSet::new();
716        for argument in &self.arguments {
717            if let Argument::SearchPath { kind, path } = argument
718                && kind == "native"
719            {
720                match builder.normalize_path(path) {
721                    Ok(normalized) => {
722                        native_directories.insert(normalized);
723                    }
724                    // Inert and outside every mapped root: the directory
725                    // contributes no content inputs, so the prediction has
726                    // nothing to replay for it. Input discovery skips it the
727                    // same way, which is what keeps the predicted action key
728                    // equal to the one dep-info discovery builds.
729                    Err(BypassReason::UnmappedAbsolutePath(_)) if self.native_search_is_inert() => {
730                    }
731                    Err(error) => return Err(error),
732                }
733            }
734        }
735        // A file beneath a recorded directory is rediscovered by walking that
736        // directory, so naming it as well only makes the payload grow with the
737        // object tree a C dependency leaves in its `OUT_DIR`. `aws-lc-sys`
738        // leaves thousands of files there, which was enough to push the
739        // serialized prediction past the protocol's payload limit and lose the
740        // prediction entirely for the crate that most needed one.
741        let mut inputs = BTreeSet::new();
742        for input in &discovered.inputs {
743            let normalized = builder.normalize_path(&input.path)?;
744            if !under_any_directory(&normalized, &native_directories) {
745                inputs.insert(normalized);
746            }
747        }
748        inputs.extend(
749            native_directories
750                .into_iter()
751                .map(|directory| format!("{NATIVE_DIRECTORY_PREDICTION_PREFIX}{directory}")),
752        );
753        Ok(RustcInputPrediction {
754            version: 4,
755            inputs: inputs.into_iter().collect(),
756            environment: discovered.environment.keys().cloned().collect(),
757            compiler_duration_ns: 0,
758            crate_name: String::new(),
759        })
760    }
761}
762
763impl RustcOutputs {
764    /// The linked executable Cargo will run as a build script, when this is a
765    /// build-script compilation.
766    pub fn build_script_executable(&self, crate_name: &str) -> Option<&Path> {
767        (crate_name == "build_script_build")
768            .then(|| self.files.iter().find(|path| self.is_executable(path)))
769            .flatten()
770            .map(PathBuf::as_path)
771    }
772
773    /// Whether `path` is a linked program whose executable permission is part
774    /// of the declared output contract.
775    /// A program is whatever this invocation emitted that is not a library
776    /// artifact. Every tier the adapter admits distinguishes the two by
777    /// extension -- `rlib` and `rmeta` are the compiler's own, and a linked
778    /// program carries either the target's (`wasm`) or none at all -- so the
779    /// name is enough and no separate list has to be carried alongside.
780    pub fn is_executable(&self, path: &Path) -> bool {
781        self.files.iter().any(|output| output == path)
782            && !matches!(
783                path.extension().and_then(|extension| extension.to_str()),
784                Some("rlib" | "rmeta")
785            )
786    }
787}
788
789#[derive(Debug, Clone, PartialEq, Eq)]
790/// Mapping from a host-specific absolute root to a stable key placeholder.
791pub struct PathMapping {
792    /// Absolute host path to replace.
793    pub root: PathBuf,
794    /// Placeholder name without the surrounding `${...}` syntax.
795    pub placeholder: String,
796}
797
798impl PathMapping {
799    /// Map an absolute host path to a stable cache-key placeholder.
800    pub fn new(root: impl Into<PathBuf>, placeholder: impl Into<String>) -> Self {
801        Self {
802            root: root.into(),
803            placeholder: placeholder.into(),
804        }
805    }
806
807    /// Order mappings deepest root first, which is what normalization needs:
808    /// a target directory inside the workspace has to win over the workspace.
809    pub fn ordered(mappings: &[PathMapping]) -> Vec<PathMapping> {
810        let mut ordered = mappings.to_vec();
811        ordered.sort_by_key(|mapping| std::cmp::Reverse(mapping.root.components().count()));
812        ordered
813    }
814}
815
816fn shared_path_mappings(mappings: &[PathMapping]) -> Vec<SharedPathMapping> {
817    mappings
818        .iter()
819        .map(|mapping| SharedPathMapping::new(&mapping.root, &mapping.placeholder))
820        .collect()
821}
822
823/// Map an absolute path to its cache-key placeholder form.
824///
825/// `mappings` must already be ordered by [`PathMapping::ordered`]. Exposed for
826/// callers that need the placeholder text before an action exists -- notably to
827/// build the `--remap-path-prefix` flag that makes a compilation independent of
828/// a path in its environment.
829pub fn normalize_mapped_path(
830    path: &Path,
831    working_dir: &Path,
832    mappings: &[PathMapping],
833) -> Result<String, BypassReason> {
834    normalize_shared_path(path, working_dir, &shared_path_mappings(mappings)).map_err(Into::into)
835}
836
837#[derive(Debug, Clone, PartialEq, Eq)]
838/// Compiler properties that distinguish incompatible action outputs.
839pub struct CompilerIdentity {
840    /// Toolchain selector or installation identity.
841    pub toolchain: String,
842    /// Complete verbose rustc version string.
843    pub rustc_version: String,
844    /// Compiler host target triple.
845    pub host: String,
846}
847
848/// One file input paired with the digest used in the action key.
849#[derive(Debug, Clone, PartialEq, Eq)]
850pub struct ActionInput {
851    /// Absolute host path used to read and verify the input.
852    pub path: PathBuf,
853    /// Digest of the input contents.
854    pub digest: CacheDigest,
855}
856
857/// External information needed to construct a canonical rustc action.
858#[derive(Debug, Clone, PartialEq, Eq)]
859pub struct ActionContext {
860    /// Identity of the compiler that produces the outputs.
861    pub compiler: CompilerIdentity,
862    /// Absolute directory in which rustc runs.
863    pub working_dir: PathBuf,
864    /// Host roots replaced with stable placeholders in the key.
865    pub path_mappings: Vec<PathMapping>,
866    /// Environment inputs and their observed values.
867    pub environment: BTreeMap<String, Option<String>>,
868    /// Environment inputs whose absolute values the compilation has been made
869    /// independent of, and whose values the key therefore normalizes.
870    ///
871    /// Naming one here is a claim about the compilation, not a preference: the
872    /// caller must both neutralize the value inside it (with
873    /// `--remap-path-prefix`) and confirm no output carries the value anyway.
874    pub portable_environment: BTreeSet<String>,
875    /// Complete set of direct and discovered file inputs.
876    pub inputs: Vec<ActionInput>,
877}
878
879/// What produced a linked native program, beyond the compiler itself.
880///
881/// The fields are identity rather than content wherever a compiler's own
882/// identity is: a driver's version output names its toolchain more cheaply than
883/// hashing a hundred megabytes of it, and matches how rustc is identified. The
884/// CRT objects are hashed, because nothing else pins the libc a link resolves
885/// against. Nothing here is placeholder-mapped -- these paths are host
886/// locations rather than checkout locations, and two hosts that differ should
887/// miss rather than share.
888#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
889#[serde(deny_unknown_fields)]
890pub struct LinkerIdentity {
891    /// Resolved absolute path of the linker driver rustc will invoke.
892    pub driver: String,
893    /// Version output of that driver.
894    pub driver_version: String,
895    /// Version of the linker the driver selects.
896    pub linker_version: String,
897    /// Startup objects and libc the driver resolves, by probe name.
898    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
899    pub crt_objects: BTreeMap<String, CacheDigest>,
900    /// Platform SDK identity, where the platform has one.
901    #[serde(skip_serializing_if = "Option::is_none", default)]
902    pub sdk: Option<String>,
903    /// Deployment target the link was made against, where one applies.
904    #[serde(skip_serializing_if = "Option::is_none", default)]
905    pub deployment_target: Option<String>,
906}
907
908/// Canonical action descriptor and its content digest.
909#[derive(Debug, Clone, PartialEq, Eq)]
910pub struct RustcAction {
911    /// Digest of `bytes`, used as the action-cache key.
912    pub digest: CacheDigest,
913    /// Canonical serialized action descriptor.
914    pub bytes: Vec<u8>,
915}
916
917/// Normalized input names from the last successful execution of one modeled
918/// rustc invocation.
919#[derive(Debug, Clone, PartialEq, Eq)]
920pub struct RustcInputPrediction {
921    /// Prediction schema version.
922    pub version: u8,
923    /// Normalized input paths observed during the successful invocation.
924    pub inputs: Vec<String>,
925    /// Names of environment variables read by the compilation.
926    pub environment: Vec<String>,
927    /// Compiler wall time from the successful invocation that produced this
928    /// prediction. Zero means no timing hint was recorded.
929    pub compiler_duration_ns: u64,
930    /// Crate name associated with the timing hint.
931    pub crate_name: String,
932}
933
934#[derive(Serialize, Deserialize)]
935#[serde(deny_unknown_fields)]
936struct RustcInputPredictionWire {
937    version: u8,
938    inputs: Vec<String>,
939    environment: Vec<String>,
940    #[serde(default, skip_serializing_if = "is_zero")]
941    compiler_duration_ns: u64,
942    #[serde(default, skip_serializing_if = "String::is_empty")]
943    crate_name: String,
944}
945
946impl Serialize for RustcInputPrediction {
947    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
948    where
949        S: Serializer,
950    {
951        RustcInputPredictionWire {
952            version: self.version,
953            inputs: if self.version == 4 {
954                compact_prediction_inputs(&self.inputs)
955            } else {
956                self.inputs.clone()
957            },
958            environment: self.environment.clone(),
959            compiler_duration_ns: self.compiler_duration_ns,
960            crate_name: self.crate_name.clone(),
961        }
962        .serialize(serializer)
963    }
964}
965
966impl<'de> Deserialize<'de> for RustcInputPrediction {
967    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
968    where
969        D: Deserializer<'de>,
970    {
971        let wire = RustcInputPredictionWire::deserialize(deserializer)?;
972        let inputs = if wire.version == 4 {
973            expand_prediction_inputs(&wire.inputs).map_err(serde::de::Error::custom)?
974        } else {
975            wire.inputs
976        };
977        Ok(Self {
978            version: wire.version,
979            inputs,
980            environment: wire.environment,
981            compiler_duration_ns: wire.compiler_duration_ns,
982            crate_name: wire.crate_name,
983        })
984    }
985}
986
987fn compact_prediction_inputs(inputs: &[String]) -> Vec<String> {
988    let mut previous = "";
989    inputs
990        .iter()
991        .map(|input| {
992            let mut shared = previous
993                .bytes()
994                .zip(input.bytes())
995                .take_while(|(left, right)| left == right)
996                .count();
997            while !input.is_char_boundary(shared) {
998                shared -= 1;
999            }
1000            let compact = format!("{shared}:{}", &input[shared..]);
1001            previous = input;
1002            compact
1003        })
1004        .collect()
1005}
1006
1007fn expand_prediction_inputs(inputs: &[String]) -> Result<Vec<String>, &'static str> {
1008    let mut expanded: Vec<String> = Vec::with_capacity(inputs.len());
1009    let mut decoded_bytes = 0_usize;
1010    for input in inputs {
1011        let (shared_text, suffix) = input
1012            .split_once(':')
1013            .ok_or("compact rustc prediction input has no prefix length")?;
1014        let shared: usize = shared_text
1015            .parse()
1016            .map_err(|_| "compact rustc prediction prefix length is invalid")?;
1017        if shared.to_string() != shared_text
1018            || shared > expanded.last().map_or(0, String::len)
1019            || expanded
1020                .last()
1021                .is_some_and(|previous| !previous.is_char_boundary(shared))
1022        {
1023            return Err("compact rustc prediction prefix is not canonical");
1024        }
1025        let mut path = expanded
1026            .last()
1027            .map_or_else(String::new, |previous| previous[..shared].to_string());
1028        path.push_str(suffix);
1029        decoded_bytes = decoded_bytes
1030            .checked_add(path.len())
1031            .ok_or("compact rustc prediction is too large")?;
1032        if decoded_bytes > MAX_DECODED_PREDICTION_BYTES {
1033            return Err("compact rustc prediction is too large");
1034        }
1035        expanded.push(path);
1036    }
1037    Ok(expanded)
1038}
1039
1040fn is_zero(value: &u64) -> bool {
1041    *value == 0
1042}
1043
1044impl RustcInputPrediction {
1045    /// Rehash the predicted paths and read the current environment. The caller
1046    /// still recomputes the full action digest, so changed inputs are misses.
1047    pub fn discover(
1048        &self,
1049        working_dir: &Path,
1050        path_mappings: &[PathMapping],
1051        digests: &dyn FileDigestCache,
1052    ) -> Result<DiscoveredInputs, BypassReason> {
1053        if !matches!(self.version, 2..=4) {
1054            return Err(BypassReason::UnsupportedPrediction);
1055        }
1056        if self.inputs.len() > MAX_PREDICTED_INPUTS || self.environment.len() > 4 * 1024 {
1057            return Err(BypassReason::UnsupportedPrediction);
1058        }
1059        let mut paths = BTreeSet::new();
1060        let admitted_roots = dep_info::native_input_roots(working_dir, path_mappings);
1061        let mut native_bytes = 0_u64;
1062        for path in &self.inputs {
1063            if self.version >= 3
1064                && let Some(path) = path.strip_prefix(NATIVE_DIRECTORY_PREDICTION_PREFIX)
1065            {
1066                let directory = denormalize_path(path, path_mappings)?;
1067                dep_info::collect_native_directory(
1068                    &directory,
1069                    &admitted_roots,
1070                    &mut paths,
1071                    &mut native_bytes,
1072                )?;
1073            } else {
1074                paths.insert(denormalize_path(path, path_mappings)?);
1075            }
1076        }
1077        let environment = self
1078            .environment
1079            .iter()
1080            .map(|name| {
1081                if name.is_empty() || name.contains(['=', '\0']) {
1082                    return Err(BypassReason::UnsupportedPrediction);
1083                }
1084                let value = std::env::var_os(name)
1085                    .map(|value| {
1086                        value
1087                            .into_string()
1088                            .map_err(|_| BypassReason::UnsupportedPrediction)
1089                    })
1090                    .transpose()?;
1091                Ok((name.clone(), value))
1092            })
1093            .collect::<Result<BTreeMap<_, _>, _>>()?;
1094        DiscoveredInputs::from_paths(working_dir, paths, environment, digests)
1095    }
1096}
1097
1098#[derive(Serialize)]
1099struct ActionDescriptor {
1100    version: u8,
1101    kind: &'static str,
1102    adapter_version: u8,
1103    compiler: CompilerDescriptor,
1104    arguments: Vec<String>,
1105    environment: BTreeMap<String, Option<String>>,
1106    inputs: Vec<InputDescriptor>,
1107    /// Omitted entirely unless the invocation links natively, so every key
1108    /// written before this field existed still serializes to the same bytes.
1109    #[serde(skip_serializing_if = "Option::is_none")]
1110    linker: Option<LinkerIdentity>,
1111}
1112
1113#[derive(Serialize)]
1114struct InvocationDescriptor {
1115    version: u8,
1116    kind: &'static str,
1117    adapter_version: u8,
1118    compiler: CompilerDescriptor,
1119    arguments: Vec<String>,
1120    required_inputs: Vec<String>,
1121}
1122
1123#[derive(Serialize)]
1124struct CompilerDescriptor {
1125    toolchain: String,
1126    rustc_version: String,
1127    host: String,
1128}
1129
1130#[derive(Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)]
1131struct InputDescriptor {
1132    path: String,
1133    digest: CacheDigest,
1134}
1135
1136struct Parser<'a> {
1137    arguments: &'a [OsString],
1138    index: usize,
1139    parsed: Vec<Argument>,
1140    source: Option<PathBuf>,
1141    crate_types: Vec<String>,
1142    emits: Vec<Emit>,
1143    required_inputs: Vec<PathBuf>,
1144    test: bool,
1145    crate_name: Option<String>,
1146    extra_filename: String,
1147    out_dir: Option<PathBuf>,
1148    explicit_output: Option<PathBuf>,
1149    target: Option<String>,
1150    options: ParseOptions,
1151}
1152
1153struct ExpandedArguments {
1154    arguments: Vec<OsString>,
1155}
1156
1157#[derive(Default)]
1158struct ResponseExpander {
1159    shell_argfiles: bool,
1160    next_is_unstable_option: bool,
1161    arguments: Vec<OsString>,
1162}
1163
1164impl ResponseExpander {
1165    fn push(&mut self, argument: String) {
1166        if self.next_is_unstable_option {
1167            self.shell_argfiles |= argument == "shell-argfiles";
1168            self.next_is_unstable_option = false;
1169        } else if let Some(option) = argument.strip_prefix("-Z") {
1170            if option.is_empty() {
1171                self.next_is_unstable_option = true;
1172            } else {
1173                self.shell_argfiles |= option == "shell-argfiles";
1174            }
1175        }
1176        self.arguments.push(argument.into());
1177    }
1178}
1179
1180/// Match rustc's argfile expansion: UTF-8, one option per line, no recursive
1181/// expansion, with the nightly shell form enabled only after its `-Z` flag.
1182fn expand_response_files(arguments: &[OsString]) -> Result<ExpandedArguments, BypassReason> {
1183    let mut expanded = ResponseExpander::default();
1184    for (index, argument) in arguments.iter().enumerate() {
1185        let argument = argument
1186            .to_str()
1187            .ok_or(BypassReason::NonUtf8Argument { index })?;
1188        let Some(argfile) = argument.strip_prefix('@') else {
1189            expanded.push(argument.to_string());
1190            continue;
1191        };
1192        let (path, shell) = match argfile.split_once(':') {
1193            Some(("shell", path)) if expanded.shell_argfiles => (path, true),
1194            _ => (argfile, false),
1195        };
1196        let contents = std::fs::read_to_string(path).map_err(|error| {
1197            BypassReason::ResponseFile(format!("{}: {error}", Path::new(path).display()))
1198        })?;
1199        if shell {
1200            let arguments = shlex::split(&contents).ok_or_else(|| {
1201                BypassReason::ResponseFile(format!(
1202                    "invalid shell-style arguments in {}",
1203                    Path::new(path).display()
1204                ))
1205            })?;
1206            for argument in arguments {
1207                expanded.push(argument);
1208            }
1209        } else {
1210            for argument in contents.lines() {
1211                expanded.push(argument.to_string());
1212            }
1213        }
1214    }
1215    Ok(ExpandedArguments {
1216        arguments: expanded.arguments,
1217    })
1218}
1219
1220impl<'a> Parser<'a> {
1221    fn new(arguments: &'a [OsString], options: ParseOptions) -> Self {
1222        Self {
1223            arguments,
1224            options,
1225            index: 0,
1226            parsed: Vec::new(),
1227            source: None,
1228            crate_types: Vec::new(),
1229            emits: Vec::new(),
1230            required_inputs: Vec::new(),
1231            test: false,
1232            crate_name: None,
1233            extra_filename: String::new(),
1234            out_dir: None,
1235            explicit_output: None,
1236            target: None,
1237        }
1238    }
1239
1240    fn parse(mut self) -> Result<RustcInvocation, BypassReason> {
1241        while self.index < self.arguments.len() {
1242            let value = self.current()?.to_string();
1243            self.index += 1;
1244            if let Some(long) = value.strip_prefix("--") {
1245                self.parse_long(long)?;
1246            } else if value.starts_with('-') && value != "-" {
1247                self.parse_short(&value)?;
1248            } else {
1249                self.parse_input(&value)?;
1250            }
1251        }
1252
1253        let source = self.source.clone().ok_or(BypassReason::MissingInput)?;
1254        let link_output = self.classify()?;
1255        let crate_name = self.crate_name.clone().map_or_else(
1256            || {
1257                source
1258                    .file_stem()
1259                    .and_then(|name| name.to_str())
1260                    .map(|name| name.replace('-', "_"))
1261                    .ok_or_else(|| BypassReason::NonUtf8Path(source.clone()))
1262            },
1263            Ok,
1264        )?;
1265        self.required_inputs.push(source.clone());
1266        Ok(RustcInvocation {
1267            arguments: self.parsed,
1268            source,
1269            required_inputs: self.required_inputs,
1270            crate_name,
1271            extra_filename: self.extra_filename,
1272            out_dir: self.out_dir,
1273            explicit_output: self.explicit_output,
1274            emits: self.emits,
1275            target: self.target,
1276            link_output,
1277        })
1278    }
1279
1280    fn current(&self) -> Result<&str, BypassReason> {
1281        self.arguments[self.index]
1282            .to_str()
1283            .ok_or(BypassReason::NonUtf8Argument { index: self.index })
1284    }
1285
1286    fn take_value(&mut self, flag: &str, inline: Option<&str>) -> Result<String, BypassReason> {
1287        if let Some(value) = inline {
1288            if value.is_empty() {
1289                return Err(BypassReason::MissingValue(flag.into()));
1290            }
1291            return Ok(value.into());
1292        }
1293        if self.index >= self.arguments.len() {
1294            return Err(BypassReason::MissingValue(flag.into()));
1295        }
1296        let value = self.current()?.to_string();
1297        self.index += 1;
1298        Ok(value)
1299    }
1300
1301    fn parse_long(&mut self, value: &str) -> Result<(), BypassReason> {
1302        let (flag, inline) = value
1303            .split_once('=')
1304            .map_or((value, None), |(flag, value)| (flag, Some(value)));
1305        let rendered_flag = format!("--{flag}");
1306        match flag {
1307            "help" | "version" | "explain" | "print" => Err(BypassReason::CompilerQuery),
1308            "test" => {
1309                self.test = true;
1310                self.parsed.push(Argument::Plain(rendered_flag));
1311                Ok(())
1312            }
1313            "verbose" => {
1314                self.parsed.push(Argument::Plain(rendered_flag));
1315                Ok(())
1316            }
1317            "crate-name" => {
1318                let value = self.take_value(&rendered_flag, inline)?;
1319                self.crate_name = Some(value.clone());
1320                self.parsed
1321                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1322                Ok(())
1323            }
1324            "cfg" | "check-cfg" | "edition" | "error-format" | "json" | "color"
1325            | "diagnostic-width" | "remap-path-scope" | "allow" | "warn" | "force-warn"
1326            | "deny" | "forbid" | "cap-lints" => {
1327                let value = self.take_value(&rendered_flag, inline)?;
1328                self.parsed
1329                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1330                Ok(())
1331            }
1332            "target" => {
1333                let value = self.take_value(&rendered_flag, inline)?;
1334                self.target = Some(value.clone());
1335                if value.ends_with(".json") || value.contains(['/', '\\']) {
1336                    let path = PathBuf::from(value);
1337                    self.required_inputs.push(path.clone());
1338                    self.parsed.push(Argument::Path {
1339                        flag: rendered_flag,
1340                        path,
1341                    });
1342                } else {
1343                    self.target = Some(value.clone());
1344                    self.parsed
1345                        .push(Argument::Plain(format!("{rendered_flag}={value}")));
1346                }
1347                Ok(())
1348            }
1349            "crate-type" => {
1350                let value = self.take_value(&rendered_flag, inline)?;
1351                self.crate_types
1352                    .extend(value.split(',').map(ToOwned::to_owned));
1353                self.parsed
1354                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1355                Ok(())
1356            }
1357            "emit" => {
1358                let value = self.take_value(&rendered_flag, inline)?;
1359                let emits = parse_emits(&value);
1360                self.emits.extend(emits.clone());
1361                self.parsed.push(Argument::Emit(emits));
1362                Ok(())
1363            }
1364            "out-dir" => {
1365                let path = PathBuf::from(self.take_value(&rendered_flag, inline)?);
1366                self.out_dir = Some(path.clone());
1367                self.parsed.push(Argument::Path {
1368                    flag: rendered_flag,
1369                    path,
1370                });
1371                Ok(())
1372            }
1373            "sysroot" => {
1374                let path = self.take_value(&rendered_flag, inline)?;
1375                self.parsed.push(Argument::Path {
1376                    flag: rendered_flag,
1377                    path: path.into(),
1378                });
1379                Ok(())
1380            }
1381            "extern" => {
1382                let value = self.take_value(&rendered_flag, inline)?;
1383                let (name, path) = value
1384                    .split_once('=')
1385                    .map_or((value.as_str(), None), |(name, path)| {
1386                        (name, Some(PathBuf::from(path)))
1387                    });
1388                if let Some(path) = &path {
1389                    self.required_inputs.push(path.clone());
1390                }
1391                self.parsed.push(Argument::Extern {
1392                    name: name.into(),
1393                    path,
1394                });
1395                Ok(())
1396            }
1397            "remap-path-prefix" => {
1398                let value = self.take_value(&rendered_flag, inline)?;
1399                let Some((from, to)) = value.split_once('=') else {
1400                    return Err(BypassReason::MissingValue(rendered_flag));
1401                };
1402                self.parsed.push(Argument::RemapPath {
1403                    from: from.into(),
1404                    to: to.into(),
1405                });
1406                Ok(())
1407            }
1408            "codegen" => {
1409                let value = self.take_value(&rendered_flag, inline)?;
1410                self.parse_codegen(&value)
1411            }
1412            "jobs-frontend" => {
1413                let value = self.take_value(&rendered_flag, inline)?;
1414                self.parsed
1415                    .push(Argument::Plain(format!("{rendered_flag}={value}")));
1416                Ok(())
1417            }
1418            _ => Err(BypassReason::UnknownFlag(rendered_flag)),
1419        }
1420    }
1421
1422    fn parse_short(&mut self, value: &str) -> Result<(), BypassReason> {
1423        if let Some(attached) = value.strip_prefix("-Z") {
1424            let option = self.take_value("-Z", (!attached.is_empty()).then_some(attached))?;
1425            match option.as_str() {
1426                "shell-argfiles" | "unstable-options" => {
1427                    self.parsed.push(Argument::Plain(format!("-Z{option}")));
1428                    return Ok(());
1429                }
1430                "threads" | "threads=" => {
1431                    return Err(BypassReason::MissingValue("-Zthreads".into()));
1432                }
1433                _ => {}
1434            }
1435            if option.starts_with("threads=") {
1436                self.parsed.push(Argument::Plain(format!("-Z{option}")));
1437                return Ok(());
1438            }
1439            return Err(BypassReason::UnknownFlag(format!("-Z{option}")));
1440        }
1441        match value {
1442            // `-vV` is how cargo and build scripts ask for the verbose
1443            // version, so it is a query rather than a flag left unmodeled.
1444            "-h" | "-V" | "-vV" => return Err(BypassReason::CompilerQuery),
1445            "-g" | "-O" | "-v" => {
1446                self.parsed.push(Argument::Plain(value.into()));
1447                return Ok(());
1448            }
1449            _ => {}
1450        }
1451        for (short, long) in [
1452            ("-A", "--allow"),
1453            ("-W", "--warn"),
1454            ("-D", "--deny"),
1455            ("-F", "--forbid"),
1456        ] {
1457            if let Some(attached) = value.strip_prefix(short) {
1458                let lint = self.take_value(short, (!attached.is_empty()).then_some(attached))?;
1459                self.parsed.push(Argument::Plain(format!("{long}={lint}")));
1460                return Ok(());
1461            }
1462        }
1463        if let Some(attached) = value.strip_prefix("-C") {
1464            let option = self.take_value("-C", (!attached.is_empty()).then_some(attached))?;
1465            return self.parse_codegen(&option);
1466        }
1467        if let Some(attached) = value.strip_prefix("-L") {
1468            let search = self.take_value("-L", (!attached.is_empty()).then_some(attached))?;
1469            let (kind, path) = search
1470                .split_once('=')
1471                .map_or(("all", search.as_str()), |(kind, path)| (kind, path));
1472            if !matches!(kind, "dependency" | "native") {
1473                return Err(BypassReason::UnsupportedSearchPath(kind.into()));
1474            }
1475            self.parsed.push(Argument::SearchPath {
1476                kind: kind.into(),
1477                path: path.into(),
1478            });
1479            return Ok(());
1480        }
1481        if value == "-l" || value.starts_with("-l") {
1482            return Err(BypassReason::NativeLibrary);
1483        }
1484        if let Some(attached) = value.strip_prefix("-o") {
1485            let path = self.take_value("-o", (!attached.is_empty()).then_some(attached))?;
1486            self.explicit_output = Some(path.clone().into());
1487            self.parsed.push(Argument::Path {
1488                flag: "-o".into(),
1489                path: path.into(),
1490            });
1491            return Ok(());
1492        }
1493        Err(BypassReason::UnknownFlag(value.into()))
1494    }
1495
1496    fn parse_codegen(&mut self, value: &str) -> Result<(), BypassReason> {
1497        let name = value.split_once('=').map_or(value, |(name, _)| name);
1498        if name == "incremental" {
1499            return Err(BypassReason::Incremental);
1500        }
1501        if SUPPORTED_CODEGEN_OPTIONS.binary_search(&name).is_err()
1502            && !(cfg!(windows) && name == "linker")
1503        {
1504            return Err(BypassReason::UnknownCodegenOption(name.into()));
1505        }
1506        // `-fuse-ld=<name>` selects the linker the driver invokes. Parsed
1507        // rather than keyed as text so the linker identity probe can pin the
1508        // selected linker; a repeated selection dedups, and a conflicting
1509        // second selection falls through to Plain, which native-link handling
1510        // declines to model. The driver honors the last selection, so a
1511        // conflict is a link whose linker this adapter cannot name.
1512        if name == "link-arg"
1513            && let Some((_, option)) = value.split_once('=')
1514            && let Some(selection) = option.strip_prefix("-fuse-ld=")
1515            && !selection.is_empty()
1516            && !selection.contains(',')
1517            && !self.parsed.iter().any(
1518                |argument| matches!(argument, Argument::FuseLd(existing) if existing != selection),
1519            )
1520        {
1521            if !self.parsed.iter().any(
1522                |argument| matches!(argument, Argument::FuseLd(existing) if existing == selection),
1523            ) {
1524                self.parsed.push(Argument::FuseLd(selection.to_owned()));
1525            }
1526            return Ok(());
1527        }
1528        // `-oso_prefix` names a checkout-specific path, so it is parsed
1529        // rather than keyed as text: the path normalizes like every other
1530        // path in the key, which is what lets two checkouts passing their own
1531        // prefixes agree on one action.
1532        if matches!(name, "link-arg" | "link-args")
1533            && let Some((_, option)) = value.split_once('=')
1534            && let Some(prefix) = option.strip_prefix("-Wl,-oso_prefix,")
1535            && !prefix.trim_end_matches('/').is_empty()
1536            && !prefix.contains(',')
1537        {
1538            let trailing_slash = prefix.ends_with('/');
1539            self.parsed.push(Argument::OsoPrefix {
1540                path: PathBuf::from(prefix.trim_end_matches('/')),
1541                trailing_slash,
1542            });
1543            return Ok(());
1544        }
1545        self.parsed
1546            .push(Argument::Plain(format!("--codegen={value}")));
1547        if name == "extra-filename" {
1548            self.extra_filename = value
1549                .split_once('=')
1550                .map_or(String::new(), |(_, value)| value.to_string());
1551        }
1552        Ok(())
1553    }
1554
1555    fn parse_input(&mut self, value: &str) -> Result<(), BypassReason> {
1556        if value == "-" {
1557            return Err(BypassReason::StandardInput);
1558        }
1559        if self.source.replace(value.into()).is_some() {
1560            return Err(BypassReason::MultipleInputs);
1561        }
1562        Ok(())
1563    }
1564
1565    fn classify(&self) -> Result<LinkOutput, BypassReason> {
1566        // A compilation that emits no `link` produces exactly what an rlib's
1567        // metadata emit does -- dep-info and `lib<name>.rmeta` -- whatever it
1568        // calls its crate type. `cargo check` and clippy compile every binary
1569        // and test target this way, and those were bypassing as an
1570        // unsupported crate type for a linked artifact none of them asked
1571        // for. No linker runs, so nothing downstream needs a linker identity
1572        // to describe, and rustc names the metadata the same way for every
1573        // crate type.
1574        let never_links = !self.emits.iter().any(|emit| emit.kind == "link");
1575        let builds_a_library = !self.test
1576            && !self.crate_types.is_empty()
1577            && self
1578                .crate_types
1579                .iter()
1580                .all(|crate_type| matches!(crate_type.as_str(), "lib" | "rlib"));
1581        let link_output = if never_links || builds_a_library {
1582            LinkOutput::Library
1583        } else if self
1584            .target
1585            .as_deref()
1586            .is_some_and(compiler_bundled_wasm_target)
1587            && ((self.test && self.crate_types.is_empty())
1588                || matches!(self.crate_types.as_slice(), [kind] if kind == "bin" || kind == "cdylib"))
1589        {
1590            if self.parsed.iter().any(|argument| match argument {
1591                Argument::Plain(value) if value == "--codegen=link-self-contained" => false,
1592                Argument::Plain(value) if value.starts_with("--codegen=link-self-contained=") => {
1593                    !matches!(
1594                        value.rsplit_once('=').map(|(_, value)| value),
1595                        Some("y" | "yes" | "on" | "true")
1596                    )
1597                }
1598                _ => false,
1599            }) {
1600                return Err(BypassReason::UnknownCodegenOption(
1601                    "link-self-contained".into(),
1602                ));
1603            }
1604            if self.target.as_deref().is_some_and(|target| target.contains("wasi"))
1605                && self.parsed.iter().any(|argument| {
1606                    matches!(argument, Argument::Plain(value) if value.strip_prefix("--codegen=target-feature=").is_some_and(|features| features.split(',').any(|feature| feature == "-crt-static")))
1607                })
1608            {
1609                return Err(BypassReason::UnknownCodegenOption(
1610                    "target-feature=-crt-static".into(),
1611                ));
1612            }
1613            // These targets use a linker and, where applicable, CRT objects
1614            // and libc shipped in the Rust toolchain. Unlike native linking,
1615            // there are no implicit host inputs outside compiler identity.
1616            LinkOutput::WasmExecutable
1617        } else if self.options.cache_native_links && self.links_a_native_artifact() {
1618            self.check_native_link_is_portable()?;
1619            if matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro") {
1620                LinkOutput::NativeProcMacro
1621            } else {
1622                LinkOutput::NativeExecutable
1623            }
1624        } else if self.test {
1625            return Err(BypassReason::UnsupportedCrateType("test".into()));
1626        } else {
1627            return Err(BypassReason::UnsupportedCrateType(
1628                self.crate_types
1629                    .iter()
1630                    .find(|crate_type| !matches!(crate_type.as_str(), "lib" | "rlib"))
1631                    .cloned()
1632                    .unwrap_or_else(|| "bin".into()),
1633            ));
1634        };
1635        // A link argument is handed to the linker verbatim, and its text is all
1636        // the adapter has to go on. `-Clink-arg=-Tlink.x` names a linker script
1637        // resolved off the search path, `-Clink-arg=-fuse-ld=lld` replaces the
1638        // linker the identity in the key describes, and neither is told apart
1639        // from `/STACK:8000000` by any rule short of knowing the linker's own
1640        // grammar. Where nothing links there is nothing to tell apart: an rlib
1641        // or an rmeta is produced without a linker invocation, so the option is
1642        // inert and the key carries its text like any other codegen option.
1643        if link_output != LinkOutput::Library
1644            && let Some(option) = self.first_link_argument()
1645        {
1646            return Err(BypassReason::UnmodeledLinkArgument(option.to_owned()));
1647        }
1648        // `-fuse-ld` is modeled only for native links, where the linker
1649        // identity probe resolves and pins the linker it names. A wasm or
1650        // other non-native link consuming the selection has no identity that
1651        // describes it, so it declines the action like any other link
1652        // argument. Where nothing links, the selection is inert and the key
1653        // carries its text.
1654        if let Some(selection) = self.parsed.iter().find_map(|argument| {
1655            let Argument::FuseLd(selection) = argument else {
1656                return None;
1657            };
1658            Some(selection.as_str())
1659        }) && !matches!(
1660            link_output,
1661            LinkOutput::Library | LinkOutput::NativeExecutable | LinkOutput::NativeProcMacro
1662        ) {
1663            return Err(BypassReason::UnmodeledLinkArgument(format!(
1664                "link-arg=-fuse-ld={selection}"
1665            )));
1666        }
1667        if self.parsed.iter().any(|argument| {
1668            matches!(argument, Argument::Plain(value) if value.starts_with("--codegen=linker="))
1669        }) && !matches!(
1670            link_output,
1671            LinkOutput::NativeExecutable | LinkOutput::NativeProcMacro
1672        ) {
1673            return Err(BypassReason::UnknownCodegenOption("linker".into()));
1674        }
1675        // `-oso_prefix` is modeled, but only where ld64 is the linker reading
1676        // it: a native macOS link. Any other linker sees an option this
1677        // adapter cannot vouch for, exactly like the arguments above.
1678        if !matches!(
1679            link_output,
1680            LinkOutput::Library | LinkOutput::NativeExecutable | LinkOutput::NativeProcMacro
1681        ) && self
1682            .parsed
1683            .iter()
1684            .any(|argument| matches!(argument, Argument::OsoPrefix { .. }))
1685        {
1686            return Err(BypassReason::UnmodeledLinkArgument(
1687                "link-arg=-Wl,-oso_prefix".into(),
1688            ));
1689        }
1690        if let Some(name) = self.parsed.iter().find_map(|argument| match argument {
1691            Argument::Extern { name, path: None } if name != "proc_macro" => Some(name),
1692            _ => None,
1693        }) {
1694            return Err(BypassReason::UnresolvedExtern(name.clone()));
1695        }
1696        if let Some(emit) = self
1697            .emits
1698            .iter()
1699            .find(|emit| !matches!(emit.kind.as_str(), "dep-info" | "link" | "metadata"))
1700        {
1701            return Err(BypassReason::UnsupportedEmit(emit.kind.clone()));
1702        }
1703        if !self
1704            .emits
1705            .iter()
1706            .any(|emit| matches!(emit.kind.as_str(), "link" | "metadata"))
1707        {
1708            return Err(BypassReason::NoCacheableOutput);
1709        }
1710        Ok(link_output)
1711    }
1712}
1713
1714impl Parser<'_> {
1715    /// The first `-C link-arg` or `-C link-args` option in the invocation,
1716    /// rendered as it appears in the action key.
1717    fn first_link_argument(&self) -> Option<&str> {
1718        self.parsed.iter().find_map(|argument| {
1719            let Argument::Plain(value) = argument else {
1720                return None;
1721            };
1722            let option = value.strip_prefix("--codegen=")?;
1723            let name = option.split_once('=').map_or(option, |(name, _)| name);
1724            matches!(name, "link-arg" | "link-args").then_some(option)
1725        })
1726    }
1727
1728    /// Whether an `-oso_prefix` strips the directory this link's objects live
1729    /// in from the debug map ld64 records.
1730    ///
1731    /// The objects a native link reads -- this unit's own compiled objects
1732    /// and the rlibs it links -- sit in the output directory, so a prefix
1733    /// covering that directory leaves the debug map naming spellings every
1734    /// checkout shares. Toolchain objects stay absolute, as they do in the
1735    /// paths rustc itself embeds on every platform.
1736    fn oso_prefix_covers_outputs(&self) -> bool {
1737        let Some(directory) = self
1738            .out_dir
1739            .as_deref()
1740            .or_else(|| self.explicit_output.as_deref().and_then(Path::parent))
1741        else {
1742            return false;
1743        };
1744        if !directory.is_absolute() {
1745            return false;
1746        }
1747        let directory = normalize_components(directory);
1748        self.parsed.iter().any(|argument| {
1749            let Argument::OsoPrefix { path, .. } = argument else {
1750                return false;
1751            };
1752            path.is_absolute() && directory.starts_with(normalize_components(path))
1753        })
1754    }
1755
1756    /// Whether this invocation links an artifact for the host.
1757    ///
1758    /// An explicit `--target` bypasses even when it spells the host triple:
1759    /// rustc without one links for the host by construction, which is the
1760    /// cheapest description of "the linker this adapter can identify", and
1761    /// cargo omits it for host builds anyway.
1762    fn links_a_native_artifact(&self) -> bool {
1763        self.target.is_none()
1764            // A compilation that emits no linked artifact did not link, so it
1765            // needs no linker to describe it. `cargo check --tests` asks for
1766            // metadata alone, and reading that as a link would send it looking
1767            // for a linker identity and refusing flags no linker ever saw.
1768            && self.emits.iter().any(|emit| emit.kind == "link")
1769            && ((self.test && self.crate_types.is_empty())
1770                || matches!(self.crate_types.as_slice(), [kind] if matches!(kind.as_str(), "bin" | "proc-macro")))
1771    }
1772
1773    /// Reject a native link whose result depends on something the key cannot
1774    /// describe, or that leaves artifacts beside the ones mbx would store.
1775    ///
1776    /// Each check names a value rather than a flag: an option absent from the
1777    /// invocation keeps rustc's default, which the compiler identity already
1778    /// pins, while any other spelling is refused rather than guessed at.
1779    fn check_native_link_is_portable(&self) -> Result<(), BypassReason> {
1780        for argument in &self.parsed {
1781            let Argument::Plain(value) = argument else {
1782                continue;
1783            };
1784            // `-g` is rustc's shorthand for debug info, and arrives as itself
1785            // rather than as a codegen option.
1786            let (name, value) = if value == "-g" {
1787                ("debuginfo", Some("2"))
1788            } else if let Some(option) = value.strip_prefix("--codegen=") {
1789                match option.split_once('=') {
1790                    Some((name, value)) => (name, Some(value)),
1791                    // A codegen flag with no value asks for its enabled form,
1792                    // which is what cargo passes for `-Crpath`. Reading it as
1793                    // "nothing to check" is how these slipped through.
1794                    None => (option, None),
1795                }
1796            } else {
1797                continue;
1798            };
1799            let unportable = match name {
1800                // Packed debug info leaves a .dSYM bundle or .dwp file beside
1801                // the binary, and mbx stores neither. Unpacked is macOS's
1802                // debug-map arrangement -- debug info stays in the objects and
1803                // nothing lands beside the binary -- so the same covering
1804                // `-oso_prefix` that makes the debug map portable covers it.
1805                "split-debuginfo" => match value {
1806                    Some("off") => false,
1807                    Some("unpacked") if cfg!(target_os = "macos") => {
1808                        !self.oso_prefix_covers_outputs()
1809                    }
1810                    _ => true,
1811                },
1812                // ld64 records absolute object paths and their timestamps in
1813                // the binary's debug map, so the same source links to
1814                // different bytes in another checkout -- or the same one
1815                // twice. An `-oso_prefix` covering the output directory
1816                // strips those paths down to spellings every checkout
1817                // shares, which is the same leniency a Linux link already
1818                // gets for the paths rustc itself embeds; what remains
1819                // (object timestamps) only shows up under verification.
1820                "debuginfo" if cfg!(target_os = "macos") => {
1821                    !matches!(value, Some("0" | "none")) && !self.oso_prefix_covers_outputs()
1822                }
1823                // An rpath and a dynamically linked native program embed this
1824                // checkout's absolute target directory. Cargo also passes
1825                // `prefer-dynamic` to proc macros, but their dynamic runtime
1826                // is rustc's own sysroot (already pinned by compiler identity),
1827                // while Cargo's dependencies are linked into the macro. There
1828                // is no checkout rpath to carry; keep rejecting an explicit
1829                // `rpath` independently.
1830                "rpath" => is_enabled(value),
1831                "prefer-dynamic" => {
1832                    is_enabled(value)
1833                        && !matches!(self.crate_types.as_slice(), [kind] if kind == "proc-macro")
1834                }
1835                // The CRT objects a self-contained link uses come from
1836                // somewhere other than where the driver reports.
1837                "link-self-contained" => true,
1838                _ => false,
1839            };
1840            if unportable {
1841                return Err(BypassReason::UnportableNativeLink(match value {
1842                    Some(value) => format!("{name}={value}"),
1843                    None => name.to_owned(),
1844                }));
1845            }
1846        }
1847        Ok(())
1848    }
1849}
1850
1851/// Whether a boolean codegen option is asking for its enabled form. Absent a
1852/// value, rustc reads the flag itself as the request.
1853fn is_enabled(value: Option<&str>) -> bool {
1854    matches!(value, None | Some("y" | "yes" | "on" | "true"))
1855}
1856
1857fn compiler_bundled_wasm_target(target: &str) -> bool {
1858    COMPILER_BUNDLED_WASM_TARGETS.binary_search(&target).is_ok()
1859}
1860
1861fn parse_emits(value: &str) -> Vec<Emit> {
1862    value
1863        .split(',')
1864        .map(|emit| {
1865            let (kind, path) = emit
1866                .split_once('=')
1867                .map_or((emit, None), |(kind, path)| (kind, Some(path.into())));
1868            Emit {
1869                kind: kind.into(),
1870                path,
1871            }
1872        })
1873        .collect()
1874}
1875
1876struct ActionBuilder<'a> {
1877    invocation: &'a RustcInvocation,
1878    context: ActionContext,
1879    mappings: Vec<SharedPathMapping>,
1880    linker: Option<LinkerIdentity>,
1881}
1882
1883impl<'a> ActionBuilder<'a> {
1884    fn new(invocation: &'a RustcInvocation, mut context: ActionContext) -> Self {
1885        context.path_mappings = PathMapping::ordered(&context.path_mappings);
1886        let mappings = resolve_path_mappings(&shared_path_mappings(&context.path_mappings));
1887        Self {
1888            linker: None,
1889            invocation,
1890            mappings,
1891            context,
1892        }
1893    }
1894
1895    fn linked_by(mut self, linker: Option<LinkerIdentity>) -> Self {
1896        self.linker = linker;
1897        self
1898    }
1899
1900    fn build(self) -> Result<RustcAction, BypassReason> {
1901        self.validate_mappings()?;
1902        let invocation = self.invocation_descriptor()?;
1903        let environment = self.environment_descriptor()?;
1904
1905        let mut inputs = BTreeMap::<String, CacheDigest>::new();
1906        for input in &self.context.inputs {
1907            input
1908                .digest
1909                .validate()
1910                .map_err(|_| BypassReason::InvalidInputDigest(input.path.display().to_string()))?;
1911            let path = self.normalize_path(&input.path)?;
1912            if inputs
1913                .insert(path.clone(), input.digest.clone())
1914                .is_some_and(|existing| existing != input.digest)
1915            {
1916                return Err(BypassReason::ConflictingInput(path));
1917            }
1918        }
1919        let required = self
1920            .invocation
1921            .required_inputs
1922            .iter()
1923            .map(|path| self.normalize_path(path))
1924            .collect::<Result<BTreeSet<_>, _>>()?;
1925        if let Some(missing) = required.iter().find(|path| !inputs.contains_key(*path)) {
1926            return Err(BypassReason::MissingRequiredInput(missing.clone()));
1927        }
1928        let inputs = inputs
1929            .into_iter()
1930            .map(|(path, digest)| InputDescriptor { path, digest })
1931            .collect();
1932        // A native link without a linker identity would be keyed as though the
1933        // host did not matter. Refuse rather than publish that claim.
1934        if self.invocation.links_natively() && self.linker.is_none() {
1935            return Err(BypassReason::UnportableNativeLink(
1936                "linker identity is unknown".into(),
1937            ));
1938        }
1939        let descriptor = ActionDescriptor {
1940            version: ACTION_SCHEMA_VERSION,
1941            kind: "rustc",
1942            adapter_version: ADAPTER_VERSION,
1943            compiler: invocation.compiler,
1944            arguments: invocation.arguments,
1945            environment,
1946            inputs,
1947            linker: self.linker.clone(),
1948        };
1949        let bytes = canonical_json(&descriptor)
1950            .map_err(|error| BypassReason::Serialization(error.to_string()))?;
1951        let digest = CacheDigest::blake3(&bytes);
1952        Ok(RustcAction { digest, bytes })
1953    }
1954
1955    fn invocation_descriptor(&self) -> Result<InvocationDescriptor, BypassReason> {
1956        self.validate_mappings()?;
1957        let arguments = self
1958            .invocation
1959            .arguments
1960            .iter()
1961            .map(|argument| self.normalize_argument(argument))
1962            .collect::<Result<Vec<_>, _>>()?;
1963        let required_inputs = self
1964            .invocation
1965            .required_inputs
1966            .iter()
1967            .map(|path| self.normalize_path(path))
1968            .collect::<Result<BTreeSet<_>, _>>()?
1969            .into_iter()
1970            .collect();
1971        Ok(InvocationDescriptor {
1972            version: ACTION_SCHEMA_VERSION,
1973            kind: "rustc",
1974            adapter_version: ADAPTER_VERSION,
1975            compiler: CompilerDescriptor {
1976                toolchain: self.context.compiler.toolchain.clone(),
1977                rustc_version: self.context.compiler.rustc_version.clone(),
1978                host: self.context.compiler.host.clone(),
1979            },
1980            arguments,
1981            required_inputs,
1982        })
1983    }
1984
1985    fn validate_mappings(&self) -> Result<(), BypassReason> {
1986        if !self.context.working_dir.is_absolute() {
1987            return Err(BypassReason::RelativeWorkingDirectory(
1988                self.context.working_dir.clone(),
1989            ));
1990        }
1991        let mut roots = BTreeSet::new();
1992        let mut placeholders = BTreeSet::new();
1993        for mapping in &self.mappings {
1994            if !mapping.root.is_absolute() {
1995                return Err(BypassReason::RelativePathMapping(mapping.root.clone()));
1996            }
1997            if mapping.placeholder.is_empty()
1998                || !mapping
1999                    .placeholder
2000                    .bytes()
2001                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
2002                || !roots.insert(normalize_components(&mapping.root))
2003                || !placeholders.insert(&mapping.placeholder)
2004            {
2005                return Err(BypassReason::InvalidPathPlaceholder(
2006                    mapping.placeholder.clone(),
2007                ));
2008            }
2009        }
2010        Ok(())
2011    }
2012
2013    fn normalize_argument(&self, argument: &Argument) -> Result<String, BypassReason> {
2014        match argument {
2015            Argument::Plain(value) => Ok(value.clone()),
2016            Argument::Path { flag, path } => Ok(format!("{flag}={}", self.normalize_path(path)?)),
2017            Argument::SearchPath { kind, path } => {
2018                let text = match self.normalize_path(path) {
2019                    Ok(text) => text,
2020                    // A native directory outside every mapped root is a host
2021                    // toolchain installation, not a checkout location. Its
2022                    // literal path is the key material: the path is
2023                    // version-stamped on the platforms that pass one (the MSVC
2024                    // toolset, the Windows SDK), so hosts that differ miss,
2025                    // which is the same identity-over-content stance
2026                    // [`LinkerIdentity`] takes.
2027                    Err(BypassReason::UnmappedAbsolutePath(absolute))
2028                        if kind == "native" && self.invocation.native_search_is_inert() =>
2029                    {
2030                        absolute
2031                            .to_str()
2032                            .ok_or(BypassReason::NonUtf8Path(absolute.clone()))?
2033                            .to_string()
2034                    }
2035                    Err(error) => return Err(error),
2036                };
2037                Ok(format!("-L{kind}={text}"))
2038            }
2039            Argument::Extern { name, path } => match path {
2040                Some(path) => Ok(format!("--extern={name}={}", self.normalize_path(path)?)),
2041                None => Ok(format!("--extern={name}")),
2042            },
2043            Argument::Emit(emits) => Ok(format!(
2044                "--emit={}",
2045                emits
2046                    .iter()
2047                    .map(|emit| match &emit.path {
2048                        Some(path) => self
2049                            .normalize_path(path)
2050                            .map(|path| format!("{}={path}", emit.kind)),
2051                        None => Ok(emit.kind.clone()),
2052                    })
2053                    .collect::<Result<Vec<_>, _>>()?
2054                    .join(",")
2055            )),
2056            Argument::RemapPath { from, to } => Ok(format!(
2057                "--remap-path-prefix={}={}",
2058                self.normalize_path(from)?,
2059                to
2060            )),
2061            Argument::OsoPrefix {
2062                path,
2063                trailing_slash,
2064            } => Ok(format!(
2065                "--codegen=link-arg=-Wl,-oso_prefix,{}{}",
2066                self.normalize_path(path)?,
2067                if *trailing_slash { "/" } else { "" }
2068            )),
2069            Argument::FuseLd(selection) => Ok(format!("--codegen=link-arg=-fuse-ld={selection}")),
2070        }
2071    }
2072
2073    /// Environment values enter the key verbatim, because rustc may embed one
2074    /// through `env!`: unlike a path used to locate an input, changing the value
2075    /// changes the artifact.
2076    ///
2077    /// A name in `portable_environment` is the exception the caller has earned.
2078    /// Its value normalizes like any other path, so two checkouts agree on it.
2079    fn environment_descriptor(&self) -> Result<BTreeMap<String, Option<String>>, BypassReason> {
2080        self.context
2081            .environment
2082            .iter()
2083            .map(|(name, value)| {
2084                let value = match value {
2085                    Some(value) if self.context.portable_environment.contains(name) => {
2086                        Some(self.normalize_path(Path::new(value))?)
2087                    }
2088                    value => value.clone(),
2089                };
2090                Ok((name.clone(), value))
2091            })
2092            .collect()
2093    }
2094
2095    fn normalize_path(&self, path: &Path) -> Result<String, BypassReason> {
2096        normalize_resolved_shared_path(path, &self.context.working_dir, &self.mappings)
2097            .map_err(Into::into)
2098    }
2099}
2100
2101/// Whether a normalized path names something strictly beneath one of
2102/// `directories`, which are normalized the same way and so share its `/`
2103/// separator regardless of platform.
2104fn under_any_directory(path: &str, directories: &BTreeSet<String>) -> bool {
2105    directories.iter().any(|directory| {
2106        path.len() > directory.len()
2107            && path.as_bytes()[directory.len()] == b'/'
2108            && path.starts_with(directory)
2109    })
2110}
2111
2112fn denormalize_path(value: &str, mappings: &[PathMapping]) -> Result<PathBuf, BypassReason> {
2113    for mapping in mappings {
2114        let prefix = format!("${{{}}}", mapping.placeholder);
2115        let suffix = if value == prefix {
2116            ""
2117        } else if let Some(suffix) = value.strip_prefix(&format!("{prefix}/")) {
2118            suffix
2119        } else {
2120            continue;
2121        };
2122        if !mapping.root.is_absolute()
2123            || (!suffix.is_empty()
2124                && suffix.split('/').any(|component| {
2125                    component.is_empty()
2126                        || matches!(component, "." | "..")
2127                        || component.contains('\\')
2128                }))
2129        {
2130            return Err(BypassReason::InvalidPredictedInput(value.into()));
2131        }
2132        let mut path = normalize_components(&mapping.root);
2133        path.extend(suffix.split('/').filter(|component| !component.is_empty()));
2134        return Ok(path);
2135    }
2136    Err(BypassReason::InvalidPredictedInput(value.into()))
2137}
2138
2139fn normalize_components(path: &Path) -> PathBuf {
2140    let mut normalized = PathBuf::new();
2141    for component in path.components() {
2142        match component {
2143            Component::CurDir => {}
2144            Component::ParentDir => {
2145                normalized.pop();
2146            }
2147            component => normalized.push(component.as_os_str()),
2148        }
2149    }
2150    normalized
2151}
2152
2153fn absolute_path(path: &Path, working_dir: &Path) -> PathBuf {
2154    if path.is_absolute() {
2155        normalize_components(path)
2156    } else {
2157        normalize_components(&working_dir.join(path))
2158    }
2159}
2160
2161#[cfg(test)]
2162#[path = "rustc_cache_tests.rs"]
2163mod tests;