Skip to main content

mbx_cache_rustc/
lib.rs

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