Skip to main content

hydroplane_auto/
lib.rs

1//! Build-time MIR analysis for hydroplane `#[kernel]`s. A downstream crate's `build.rs` calls
2//! [`build_script`], which runs the nightly StableMIR driver over a nested build, writes one
3//! metrics line per kernel, and points `HYDRO_ANALYSIS` at it for the macro's [`analysis`] lookups.
4
5pub mod analysis;
6
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10/// Pinned nightly whose `rustc_public` (StableMIR) API the driver is written against. Bump in
11/// lockstep with `driver/main.rs`.
12const TOOLCHAIN: &str = "nightly-2026-06-27";
13
14/// The driver ships as source and is compiled at build time: a crate doing `extern crate
15/// rustc_driver` must be the final linked artifact, so it can't be a library dependency.
16const DRIVER_MAIN: &str = include_str!("../driver/main.rs");
17const DRIVER_CARGO: &str = "\
18[package]
19name = \"hydro-analyze\"
20version = \"0.0.0\"
21edition = \"2021\"
22
23[workspace]
24
25[[bin]]
26name = \"hydro-analyze\"
27path = \"main.rs\"
28";
29const DRIVER_TOOLCHAIN: &str = "\
30[toolchain]
31channel = \"nightly-2026-06-27\"
32components = [\"rustc-dev\", \"llvm-tools\"]
33";
34
35/// Call from a downstream crate's `build.rs` (`fn main() { hydroplane_auto::build_script(); }`).
36///
37/// Runs the MIR analysis of *that* crate's kernels — release + Unix only — and, on success, emits
38/// `cargo:rustc-env=HYDRO_ANALYSIS=<path>#<hash>` so the `#[kernel]` macro can bake per-kernel
39/// decisions. On a debug build, a non-Unix host, or with `KANALYZE_DISABLE` set, it no-ops and the
40/// macro keeps its defaults.
41pub fn build_script() {
42    // The nested analysis build re-enters this script; bail so it neither recurses nor sets
43    // `HYDRO_ANALYSIS` (the nested compile must use macro defaults).
44    if std::env::var_os("HYDRO_ANALYZE_INNER").is_some() {
45        return;
46    }
47
48    let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
49    let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
50    let crate_name = std::env::var("CARGO_PKG_NAME").unwrap().replace('-', "_");
51    let metrics = out_dir.join("hydro_analysis.txt");
52
53    println!("cargo::rerun-if-changed=src");
54    println!("cargo::rerun-if-env-changed=KANALYZE_DISABLE");
55
56    if let Some(reason) = skip_reason() {
57        println!("cargo::warning=hydroplane MIR analysis skipped: {reason}; kernels use macro defaults");
58        return;
59    }
60    if !toolchain_installed() {
61        println!(
62            "cargo::warning=hydroplane MIR analysis skipped: toolchain {TOOLCHAIN} not installed; \
63             kernels use macro defaults. To enable per-kernel tuning, run: \
64             rustup toolchain install --profile minimal {TOOLCHAIN} -c rustc-dev,llvm-tools"
65        );
66        return;
67    }
68
69    let driver = build_driver(&out_dir);
70    run_nested_analysis(&manifest, &out_dir, &driver, &metrics, &crate_name);
71
72    if !metrics.exists() {
73        println!("cargo::warning=hydroplane MIR analysis produced no metrics; kernels use defaults");
74        return;
75    }
76    // The hash makes the env value change when the metrics change, forcing the macro to re-expand.
77    let hash = content_hash(&metrics);
78    println!("cargo::rustc-env=HYDRO_ANALYSIS={}#{hash}", metrics.display());
79    println!("cargo::warning=hydroplane MIR analysis applied ({})", metrics.display());
80}
81
82fn skip_reason() -> Option<String> {
83    if std::env::var_os("KANALYZE_DISABLE").is_some() {
84        return Some("KANALYZE_DISABLE set".into());
85    }
86    if std::env::var("PROFILE").as_deref() != Ok("release") {
87        return Some("debug build (analysis runs only for --release)".into());
88    }
89    if !cfg!(unix) {
90        return Some(format!("only wired up for Unix, not {}", std::env::consts::OS));
91    }
92    None
93}
94
95/// Write the embedded driver source to `out_dir/hydro-driver` and build it (prefer-dynamic + rpath
96/// into the nightly runtime, so it links and later loads `librustc_driver`). Returns the binary path.
97fn build_driver(out_dir: &Path) -> PathBuf {
98    let dir = out_dir.join("hydro-driver");
99    std::fs::create_dir_all(&dir).expect("create driver dir");
100    std::fs::write(dir.join("main.rs"), DRIVER_MAIN).expect("write driver main.rs");
101    std::fs::write(dir.join("Cargo.toml"), DRIVER_CARGO).expect("write driver Cargo.toml");
102    std::fs::write(dir.join("rust-toolchain.toml"), DRIVER_TOOLCHAIN).expect("write driver toolchain");
103
104    let sysroot = rustc_out(&["--print", "sysroot"]).expect("nightly sysroot");
105    let host = host_triple();
106    let rustflags = [
107        "-Cprefer-dynamic".to_string(),
108        format!("-Clink-arg=-Wl,-rpath,{sysroot}/lib"),
109        format!("-Clink-arg=-Wl,-rpath,{sysroot}/lib/rustlib/{host}/lib"),
110    ]
111    .join("\u{1f}");
112
113    let target_dir = out_dir.join("driver-target");
114    let status = clean_cargo()
115        .arg(format!("+{TOOLCHAIN}"))
116        .args(["build", "--quiet", "--manifest-path"])
117        .arg(dir.join("Cargo.toml"))
118        .arg("--target-dir")
119        .arg(&target_dir)
120        .env("CARGO_ENCODED_RUSTFLAGS", rustflags)
121        .status()
122        .expect("failed to build the hydro-analyze driver");
123    assert!(status.success(), "building hydro-analyze failed: {status}");
124    target_dir.join("debug").join("hydro-analyze")
125}
126
127/// Nested `cargo +nightly build` of the downstream crate with the driver as the rustc wrapper. Cargo
128/// rebuilds it and its deps under nightly (so the driver's in-process rustc can read their metadata)
129/// into a throwaway target dir; the wrapper writes the metrics for the crate named `crate_name`.
130fn run_nested_analysis(manifest: &Path, out_dir: &Path, driver: &Path, metrics: &Path, crate_name: &str) {
131    let status = clean_cargo()
132        .arg(format!("+{TOOLCHAIN}"))
133        .args(["build", "--quiet", "--release", "--manifest-path"])
134        .arg(manifest.join("Cargo.toml"))
135        .args(["--no-default-features", "--features", &active_features()])
136        .arg("--target-dir")
137        .arg(out_dir.join("analysis-target"))
138        .env("RUSTC_WORKSPACE_WRAPPER", driver)
139        .env("HYDRO_ANALYZE_INNER", "1")
140        .env("HYDRO_ANALYZE_CRATE", crate_name)
141        .env("HYDRO_ANALYSIS_OUT", metrics)
142        .env("CARGO_ENCODED_RUSTFLAGS", "--cfg\u{1f}hp_analyze")
143        .status()
144        .expect("failed to run the nested analysis build");
145    if !status.success() {
146        println!("cargo::warning=hydroplane analysis build exited with {status}");
147    }
148}
149
150/// The features the outer build enabled, so the analysis sees the same kernels: cargo exposes
151/// each as `CARGO_FEATURE_<NAME>` (upper-cased, `-` as `_`), which maps back unambiguously for
152/// the usual lower-case feature names.
153fn active_features() -> String {
154    let mut names: Vec<String> = std::env::vars()
155        .filter_map(|(k, _)| k.strip_prefix("CARGO_FEATURE_").map(|f| f.to_lowercase()))
156        .collect();
157    names.sort();
158    names.join(",")
159}
160
161/// A cargo command with the outer toolchain's rustc overrides scrubbed, so the nested `+nightly` isn't
162/// forced back to the wrong compiler.
163fn clean_cargo() -> Command {
164    let mut c = Command::new("cargo");
165    c.env_remove("RUSTC")
166        .env_remove("RUSTC_WRAPPER")
167        .env_remove("RUSTC_WORKSPACE_WRAPPER")
168        .env_remove("RUSTUP_TOOLCHAIN")
169        .env_remove("CARGO_ENCODED_RUSTFLAGS")
170        .env_remove("CARGO_BUILD_RUSTFLAGS")
171        .env_remove("RUSTFLAGS");
172    c
173}
174
175/// Whether the pinned nightly (with `rustc-dev`) is present. Never installs it: a build script
176/// must not touch the network or mutate rustup state, so the analysis only skips with a pointer
177/// to the install command.
178fn toolchain_installed() -> bool {
179    Command::new("rustup")
180        .args(["component", "list", "--toolchain", TOOLCHAIN, "--installed"])
181        .output()
182        .map(|o| {
183            o.status.success()
184                && String::from_utf8_lossy(&o.stdout).lines().any(|l| l.starts_with("rustc-dev"))
185        })
186        .unwrap_or(false)
187}
188
189fn host_triple() -> String {
190    rustc_out(&["-vV"])
191        .expect("rustc -vV")
192        .lines()
193        .find_map(|l| l.strip_prefix("host: ").map(str::to_string))
194        .expect("no host line")
195}
196
197fn rustc_out(args: &[&str]) -> Option<String> {
198    let out = Command::new("rustc").arg(format!("+{TOOLCHAIN}")).args(args).output().ok()?;
199    out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
200}
201
202fn content_hash(path: &Path) -> u64 {
203    let bytes = std::fs::read(path).unwrap_or_default();
204    // FNV-1a, enough to change the env value when metrics change.
205    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
206    for b in bytes {
207        h ^= b as u64;
208        h = h.wrapping_mul(0x0000_0100_0000_01b3);
209    }
210    h
211}