Skip to content

Commit 437c3f9

Browse files
authored
Merge pull request #1565 from youknowone/cargo-rerun-selected-crates-only
provide a way to rerun cargo only the selected crates, keep dependencies cached
2 parents cc349e9 + 71cf13c commit 437c3f9

4 files changed

Lines changed: 167 additions & 27 deletions

File tree

‎charon/src/bin/charon-driver/driver.rs‎

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use rustc_interface::interface::Compiler;
1313
use rustc_middle::ty::{InstanceKind, TyCtxt};
1414
use rustc_middle::util::Providers;
1515
use rustc_session::config::{OutputType, OutputTypes};
16-
use rustc_span::ErrorGuaranteed;
16+
use rustc_span::{ErrorGuaranteed, Symbol};
1717
use std::num::NonZero;
1818
use std::sync::atomic::{AtomicBool, Ordering};
1919
use std::{env, fmt};
@@ -102,6 +102,20 @@ fn setup_compiler(
102102
set_mir_options(config);
103103
}
104104

105+
/// Record the current value of `var` (the `selected_crate_var` of the crate being compiled) in the
106+
/// dep-info file. Cargo reruns the crate when that value changes, which `charon cargo` uses to
107+
/// rerun exactly the crates it selects for translation.
108+
fn track_selected_crate_var(config: &mut Config, var: Option<String>) {
109+
if let Some(var) = var {
110+
config.track_state = Some(Box::new(move |sess| {
111+
let value = env::var(&var).ok().map(|value| Symbol::intern(&value));
112+
sess.env_depinfo
113+
.borrow_mut()
114+
.insert((Symbol::intern(&var), value));
115+
}));
116+
}
117+
}
118+
105119
/// Run a couple of rustc queries that don't involve MIR (so that they don't steal it). Returns
106120
/// whether rustc reported errors. This lets us avoid running Charon translation on crates rustc
107121
/// already rejects.
@@ -151,14 +165,6 @@ pub fn run_rustc_driver() -> Result<Option<(TransformCtx, CliOpts)>, CharonFailu
151165
// Retreive the command-line arguments pased to `charon_driver`. The first arg is the path to
152166
// the current executable, we skip it.
153167
let mut compiler_args: Vec<String> = env::args().skip(1).collect();
154-
// We use `RUSTC_WORKSPACE_WRAPPER` to break cargo's caching; that value ends up as our first
155-
// argument.
156-
if compiler_args
157-
.first()
158-
.is_some_and(|arg| arg.starts_with("charon-dont-cache-this-"))
159-
{
160-
compiler_args.remove(0);
161-
}
162168
trace!(
163169
"charon-driver called with args: {}",
164170
compiler_args.iter().format(" ")
@@ -186,6 +192,13 @@ pub fn run_rustc_driver() -> Result<Option<(TransformCtx, CliOpts)>, CharonFailu
186192
let target = arg_value(&compiler_args, "--target");
187193
// Whether this is the crate we want to translate.
188194
let is_selected_crate = !is_workspace_dependency && target.is_some();
195+
// Under cargo, the env var through which `charon cargo` tells cargo whether to rerun this
196+
// target crate.
197+
let selected_crate_var = if env::var("CHARON_USING_CARGO").is_ok() && target.is_some() {
198+
arg_value(&compiler_args, "--crate-name").map(options::selected_crate_var)
199+
} else {
200+
None
201+
};
189202

190203
let mut error_ctx = ErrorCtx::new();
191204

@@ -227,7 +240,8 @@ pub fn run_rustc_driver() -> Result<Option<(TransformCtx, CliOpts)>, CharonFailu
227240
let output = if !is_selected_crate {
228241
trace!("Skipping charon; running compiler normally instead.");
229242
// Run the compiler normally.
230-
run_compiler_with_callbacks(compiler_args, &mut RunCompilerNormallyCallbacks)?;
243+
let mut callback = RunCompilerNormallyCallbacks { selected_crate_var };
244+
run_compiler_with_callbacks(compiler_args, &mut callback)?;
231245
None
232246
} else {
233247
error_ctx.continue_on_failure = !options.abort_on_error;
@@ -244,6 +258,7 @@ pub fn run_rustc_driver() -> Result<Option<(TransformCtx, CliOpts)>, CharonFailu
244258
codegen,
245259
error_ctx: Some(error_ctx),
246260
transform_ctx: None,
261+
selected_crate_var,
247262
};
248263
charon_lib::timing::time("rustc-driver", || {
249264
run_compiler_with_callbacks(compiler_args, &mut callback)
@@ -268,6 +283,8 @@ pub struct CharonCallbacks<'a> {
268283
/// This is to be filled during the extraction; it contains the translated crate. `None` at the
269284
/// start or if we couldn't translate anything.
270285
transform_ctx: Option<TransformCtx>,
286+
/// See [`track_selected_crate_var`].
287+
selected_crate_var: Option<String>,
271288
}
272289
impl<'a> Callbacks for CharonCallbacks<'a> {
273290
fn config(&mut self, config: &mut Config) {
@@ -278,6 +295,7 @@ impl<'a> Callbacks for CharonCallbacks<'a> {
278295
self.emit_artifacts,
279296
self.codegen,
280297
);
298+
track_selected_crate_var(config, self.selected_crate_var.take());
281299
}
282300

283301
/// The MIR is modified in place: borrow-checking requires the "promoted" MIR, which causes the
@@ -314,11 +332,15 @@ impl<'a> Callbacks for CharonCallbacks<'a> {
314332
}
315333

316334
/// Dummy callbacks used to run the compiler normally when we shouldn't be analyzing the crate.
317-
pub struct RunCompilerNormallyCallbacks;
335+
pub struct RunCompilerNormallyCallbacks {
336+
/// See [`track_selected_crate_var`].
337+
selected_crate_var: Option<String>,
338+
}
318339

319340
impl Callbacks for RunCompilerNormallyCallbacks {
320341
fn config(&mut self, config: &mut Config) {
321342
setup_compiler(config, &Default::default(), false, true, true);
343+
track_selected_crate_var(config, self.selected_crate_var.take());
322344
}
323345
}
324346

‎charon/src/bin/charon/main.rs‎

Lines changed: 69 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,14 @@ use charon_lib::{
3434
export::{CrateData, multi_target},
3535
formatter::IntoFormatter,
3636
logger,
37-
options::{CHARON_ARGS, CliOpts, SerializationFormat},
37+
options::{CHARON_ARGS, CliOpts, SerializationFormat, selected_crate_var},
3838
pretty::FmtWithCtx,
3939
utils::{arg_value, arg_values},
4040
};
4141
use clap::Parser;
4242
use cli::{Charon, Cli};
4343
use itertools::Itertools;
44+
use serde::Deserialize;
4445
use std::{env, path::PathBuf, process::ExitStatus};
4546
use toolchain::{CHARON_SYSROOT_VAR, setup_miri_sysroot, toolchain_path, toolchain_version};
4647

@@ -211,16 +212,11 @@ fn translate_multi_target(
211212
Ok(ExitStatus::default())
212213
}
213214

214-
fn translate_with_cargo(options: CliOpts, cargo_args: Vec<String>) -> anyhow::Result<ExitStatus> {
215+
fn translate_with_cargo(
216+
options: CliOpts,
217+
mut cargo_args: Vec<String>,
218+
) -> anyhow::Result<ExitStatus> {
215219
ensure_rustup();
216-
let mut cmd = toolchain::in_toolchain("cargo")?;
217-
cmd.env("RUSTC_WRAPPER", toolchain::driver_path());
218-
// We pass a random value to prevent cargo from considering a charon run cacheable.
219-
cmd.env("RUSTC_WORKSPACE_WRAPPER", fresh_fingerprint());
220-
cmd.env("CHARON_USING_CARGO", "1");
221-
cmd.env_remove("CARGO_PRIMARY_PACKAGE");
222-
cmd.env(CHARON_ARGS, serde_json::to_string(&options).unwrap());
223-
cmd.arg("build");
224220
let target = match arg_values(&cargo_args, "--target").collect_vec().as_slice() {
225221
[target] => target.to_string(),
226222
// We resolve a single sysroot for all the crates we build.
@@ -232,11 +228,28 @@ fn translate_with_cargo(options: CliOpts, cargo_args: Vec<String>) -> anyhow::Re
232228
// Make sure the build target is explicitly set. This is needed to detect which crates
233229
// are proc-macro/build-script in `charon-driver`.
234230
let host = get_rustc_version()?.host;
235-
cmd.arg("--target");
236-
cmd.arg(&host);
231+
cargo_args.push("--target".to_owned());
232+
cargo_args.push(host.clone());
237233
host
238234
}
239235
};
236+
237+
let mut cmd = toolchain::in_toolchain("cargo")?;
238+
cmd.env("RUSTC_WRAPPER", toolchain::driver_path());
239+
cmd.env_remove("RUSTC_WORKSPACE_WRAPPER");
240+
cmd.env("CHARON_USING_CARGO", "1");
241+
cmd.env_remove("CARGO_PRIMARY_PACKAGE");
242+
cmd.env(CHARON_ARGS, serde_json::to_string(&options).unwrap());
243+
// Cargo skips the crates it considers fresh, and charon would emit nothing for a skipped
244+
// crate. `charon-driver` records `selected_crate_var` of each target crate as an env
245+
// dependency, and cargo reruns a crate when the value of such a variable changes. We give a
246+
// fresh value to the variables of the crates this build selects only, so cargo reruns exactly
247+
// them and keeps every dependency cached.
248+
let nonce = fresh_nonce();
249+
for crate_name in selected_crates(&cargo_args)? {
250+
cmd.env(selected_crate_var(&crate_name), &nonce);
251+
}
252+
cmd.arg("build");
240253
if let Some(sysroot) = miri_sysroot(options.sysroot.as_deref(), &target) {
241254
cmd.env(CHARON_SYSROOT_VAR, sysroot);
242255
}
@@ -249,6 +262,47 @@ fn translate_with_cargo(options: CliOpts, cargo_args: Vec<String>) -> anyhow::Re
249262
.expect("failed to wait for cargo?"))
250263
}
251264

265+
/// Returns the names of the crates that `cargo build <build_args>` selects, i.e. the root units of
266+
/// its unit graph.
267+
fn selected_crates(build_args: &[String]) -> anyhow::Result<Vec<String>> {
268+
/// The parts of cargo's `--unit-graph` output we use.
269+
#[derive(Deserialize)]
270+
struct UnitGraph {
271+
units: Vec<Unit>,
272+
roots: Vec<usize>,
273+
}
274+
#[derive(Deserialize)]
275+
struct Unit {
276+
target: UnitTarget,
277+
}
278+
#[derive(Deserialize)]
279+
struct UnitTarget {
280+
name: String,
281+
}
282+
283+
let mut cmd = toolchain::in_toolchain("cargo")?;
284+
cmd.env_remove("RUSTC_WRAPPER");
285+
cmd.env_remove("RUSTC_WORKSPACE_WRAPPER");
286+
cmd.args(["build", "--unit-graph", "-Z", "unstable-options"]);
287+
cmd.args(build_args);
288+
trace!("running {cmd:?}");
289+
let output = cmd.output().context("could not run cargo")?;
290+
if !output.status.success() {
291+
anyhow::bail!(
292+
"`cargo build --unit-graph` failed with {}:\n{}",
293+
output.status,
294+
String::from_utf8_lossy(&output.stderr)
295+
);
296+
}
297+
let graph: UnitGraph = serde_json::from_slice(&output.stdout)
298+
.context("could not parse the output of `cargo build --unit-graph`")?;
299+
Ok(graph
300+
.roots
301+
.into_iter()
302+
.map(|root| graph.units[root].target.name.replace('-', "_"))
303+
.collect())
304+
}
305+
252306
fn translate_without_cargo(mut options: CliOpts) -> anyhow::Result<ExitStatus> {
253307
ensure_rustup();
254308
let mut cmd = toolchain::driver_cmd()?;
@@ -293,12 +347,12 @@ fn get_rustc_version() -> anyhow::Result<rustc_version::VersionMeta> {
293347
Ok(rustc_version)
294348
}
295349

296-
/// A sufficiently unique string used to force cargo to re-run charon each time we call it.
297-
fn fresh_fingerprint() -> String {
350+
/// A sufficiently unique string, different for each charon run.
351+
fn fresh_nonce() -> String {
298352
let nanos = std::time::SystemTime::now()
299353
.duration_since(std::time::UNIX_EPOCH)
300354
.map_or(0, |duration| duration.as_nanos());
301-
format!("charon-dont-cache-this-{}-{nanos}", std::process::id())
355+
format!("{}-{nanos}", std::process::id())
302356
}
303357

304358
fn ensure_rustup() {

‎charon/src/options.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@ use crate::{
1818
/// when calling charon-driver from cargo-charon.
1919
pub const CHARON_ARGS: &str = "CHARON_ARGS";
2020

21+
/// The name of the environment variable that `charon cargo` sets to a fresh value for each crate
22+
/// it selects for translation. `charon-driver` records it as an env dependency of every target
23+
/// crate, so that cargo reruns exactly the selected crates and keeps every other crate cached.
24+
pub fn selected_crate_var(crate_name: &str) -> String {
25+
format!("CHARON_SELECTED_CRATE_{crate_name}")
26+
}
27+
2128
// This structure is used to store the command-line instructions.
2229
// We automatically derive a command-line parser based on this structure.
2330
// Note that the doc comments are used to generate the help message when using

‎charon/tests/cargo.rs‎

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,13 @@ use charon_lib::{ast::FileName, export::CrateData, options::SerializationFormat}
66
use itertools::Itertools;
77
use libtest_mimic::Trial;
88
use regex::Regex;
9-
use std::{error::Error, ffi::OsStr, path::PathBuf, process::Command, sync::LazyLock};
9+
use std::{
10+
error::Error,
11+
ffi::OsStr,
12+
path::{Path, PathBuf},
13+
process::Command,
14+
sync::LazyLock,
15+
};
1016

1117
use util::compare_or_overwrite;
1218
mod util;
@@ -105,6 +111,51 @@ fn perform_test(test_case: &Case) -> anyhow::Result<()> {
105111
Ok(())
106112
}
107113

114+
/// Check that `charon cargo` reruns the selected crate on every run, keeps its dependencies
115+
/// cached, and translates a crate that was previously built only as a dependency.
116+
fn workspace_caching(dir: &Path) -> anyhow::Result<()> {
117+
let tmp = tempfile::tempdir()?;
118+
// A dedicated target dir, so that we don't race the `workspace` test.
119+
let target_dir = tmp.path().join("target");
120+
// Translate `krate` with `charon cargo`; returns the output file and cargo's stderr.
121+
let run = |step: &str, krate: &str| -> anyhow::Result<(PathBuf, String)> {
122+
let dest_file = tmp.path().join(format!("{krate}.llbc"));
123+
let output = Command::cargo_bin("charon")?
124+
.current_dir(dir)
125+
.env("CARGO_TARGET_DIR", &target_dir)
126+
.arg("cargo")
127+
.arg("--dest-file")
128+
.arg(&dest_file)
129+
.args(["--", "-p", krate])
130+
.output()?;
131+
let stderr = String::from_utf8(output.stderr)?;
132+
ensure!(
133+
output.status.success(),
134+
"step {step}: translating `{krate}` failed:\n{stderr}"
135+
);
136+
ensure!(
137+
dest_file.exists(),
138+
"step {step}: `{}` was not written:\n{stderr}",
139+
dest_file.display()
140+
);
141+
Ok((dest_file, stderr))
142+
};
143+
144+
let (crate2_file, stderr) = run("a", "crate2")?;
145+
ensure!(
146+
stderr.contains("Compiling crate1"),
147+
"step a: expected cargo to build `crate1`:\n{stderr}"
148+
);
149+
std::fs::remove_file(&crate2_file)?;
150+
let (_, stderr) = run("b", "crate2")?;
151+
ensure!(
152+
!stderr.contains("Compiling crate1"),
153+
"step b: expected `crate1` to stay cached:\n{stderr}"
154+
);
155+
run("c", "crate1")?;
156+
Ok(())
157+
}
158+
108159
fn main() -> Result<(), Box<dyn Error>> {
109160
let root: PathBuf = PathBuf::from(TESTS_DIR).canonicalize()?;
110161
let mktest = |name: &str,
@@ -209,6 +260,12 @@ fn main() -> Result<(), Box<dyn Error>> {
209260
&["--package=crate2".to_owned()],
210261
Success,
211262
),
263+
{
264+
let dir = root.join("workspace");
265+
Trial::test("workspace-caching", move || {
266+
workspace_caching(&dir).map_err(|err| err.into())
267+
})
268+
},
212269
mktest(
213270
"issue-396-lib-bin",
214271
root.join("issue-396-lib-bin"),

0 commit comments

Comments
 (0)