Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass a hash of the modification date for cache control #5

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 84 additions & 1 deletion crates/rustc_plugin/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,26 @@ use crate::CrateFilter;
pub const RUN_ON_ALL_CRATES: &str = "RUSTC_PLUGIN_ALL_TARGETS";
pub const SPECIFIC_CRATE: &str = "SPECIFIC_CRATE";
pub const SPECIFIC_TARGET: &str = "SPECIFIC_TARGET";
pub const CARGO_ENCODED_RUSTFLAGS: &str = "CARGO_ENCODED_RUSTFLAGS";

fn prior_rustflags() -> Result<Vec<String>, std::env::VarError> {
use std::env::{var, VarError};
var(CARGO_ENCODED_RUSTFLAGS)
.map(|flags| flags.split('\x1f').map(str::to_string).collect())
.or_else(|err| {
if matches!(err, VarError::NotPresent) {
var("RUSTFLAGS")
.map(|flags| flags.split_whitespace().map(str::to_string).collect())
} else {
Err(err)
}
})
.or_else(|err| {
matches!(err, VarError::NotPresent)
.then(Vec::new)
.ok_or(err)
})
}

/// The top-level function that should be called in your user-facing binary.
pub fn cli_main<T: RustcPlugin>(plugin: T) {
Expand All @@ -37,12 +57,36 @@ pub fn cli_main<T: RustcPlugin>(plugin: T) {
.expect("current executable path invalid")
.with_file_name(plugin.driver_name().as_ref());

let exec_hash = {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
path
.metadata()
.unwrap()
.modified()
.unwrap()
.hash(&mut hasher);
std::env::current_exe()
.unwrap()
.metadata()
.unwrap()
.modified()
.unwrap()
.hash(&mut hasher);
hasher.finish()
};

if cfg!(windows) {
path.set_extension("exe");
}

let mut prior_rustflags = prior_rustflags().unwrap();

prior_rustflags.push(format!("{}\x1f{exec_hash:x}", crate::EXEC_HASH_ARG));

cmd
.env("RUSTC_WORKSPACE_WRAPPER", path)
.env("RUSTC_WRAPPER", path)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a brief comment that explains why we have to use RUSTC_WRAPPER instead of RUSTC_WORKSPACE_WRAPPER? Just for posterity. Or you can point to this PR.

.env(CARGO_ENCODED_RUSTFLAGS, prior_rustflags.join("\x1f"))
.args(["check", "-vv", "--target-dir"])
.arg(&target_dir);

Expand Down Expand Up @@ -191,3 +235,42 @@ fn only_run_on_file(
target.name
);
}

#[cfg(test)]
mod tests {
use std::ffi::OsStr;

use crate::cli::{prior_rustflags, CARGO_ENCODED_RUSTFLAGS};

fn with_var<K: AsRef<OsStr>, V: AsRef<OsStr>, R>(
k: K,
v: V,
f: impl FnOnce() -> R,
) -> R {
let k_ref = k.as_ref();
std::env::set_var(k_ref, v);
let result = f();
// XXX does not restore any old values (because I'm lazy)
std::env::remove_var(k_ref);
result
}

#[test]
fn rustflags_test() {
with_var("RUSTFLAGS", "space double_space tab end", || {
assert_eq!(
prior_rustflags(),
Ok(vec![
"space".to_string(),
"double_space".to_string(),
"tab".to_string(),
"end".to_string()
]),
"whitespace works"
);
with_var(CARGO_ENCODED_RUSTFLAGS, "override", || {
assert_eq!(prior_rustflags(), Ok(vec!["override".to_string()]))
})
});
}
}
10 changes: 10 additions & 0 deletions crates/rustc_plugin/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,16 @@ pub fn driver_main<T: RustcPlugin>(plugin: T) {
exit(rustc_driver::catch_with_exit_code(move || {
let mut orig_args: Vec<String> = env::args().collect();

let hash_check_arg = orig_args
.iter()
.enumerate()
.find(|elem| elem.1 == crate::EXEC_HASH_ARG)
.map(|t| t.0)
.unwrap();

orig_args.remove(hash_check_arg);
orig_args.remove(hash_check_arg);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it necessary to .remove twice?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh it's because you're deleting both arguments. Maybe orig_args.drain(hash_check_arg .. hash_check_arg + 2) is clearer?


let (have_sys_root_arg, sys_root) = get_sysroot(&orig_args);

if orig_args.iter().any(|a| a == "--version" || a == "-V") {
Expand Down
2 changes: 2 additions & 0 deletions crates/rustc_plugin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
extern crate rustc_driver;
extern crate rustc_interface;

const EXEC_HASH_ARG: &str = "--exec-hash";

#[doc(hidden)]
pub use cargo_metadata::camino::Utf8Path;
pub use cli::cli_main;
Expand Down
41 changes: 35 additions & 6 deletions crates/rustc_plugin/tests/test_example.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,30 @@
use std::{env, fs, path::Path, process::Command, sync::Once};
use std::{
env, fs,
path::Path,
process::{Command, Output},
sync::Once,
};

use anyhow::{ensure, Context, Result};

static SETUP: Once = Once::new();

fn run(dir: &str, f: impl FnOnce(&mut Command)) -> Result<()> {
let output = run_configures(dir, true, f)?;

ensure!(
output.status.success(),
"Process exited with non-zero exit code"
);

Ok(())
}

fn run_configures(
dir: &str,
remove_target: bool,
f: impl FnOnce(&mut Command),
) -> Result<Output> {
let root = env::temp_dir().join("rustc_plugin");

let heredir = Path::new(".").canonicalize()?;
Expand Down Expand Up @@ -42,12 +62,11 @@ fn run(dir: &str, f: impl FnOnce(&mut Command)) -> Result<()> {

f(&mut cmd);

let _ = fs::remove_dir_all(ws.join("target"));

let status = cmd.status().context("Process failed")?;
ensure!(status.success(), "Process exited with non-zero exit code");
if remove_target {
let _ = fs::remove_dir_all(ws.join("target"));
}

Ok(())
cmd.output().context("Process failed")
}

#[test]
Expand All @@ -66,3 +85,13 @@ fn basic_with_arg() -> Result<()> {
fn multi() -> Result<()> {
run("workspaces/multi", |_cmd| {})
}

#[test]
fn caching() -> Result<()> {
let workspace = "workspaces/basic";
let first_run = run_configures(workspace, false, |_| {})?;

let second_run = run_configures(workspace, true, |_| {})?;
ensure!(first_run == second_run);
Ok(())
}
2 changes: 1 addition & 1 deletion crates/rustc_utils/src/mir/places_conflict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ fn place_components_conflict<'tcx>(
// are disjoint
//
// Our invariant is, that at each step of the iteration:
// - If we didn't run out of access to match, our borrow and access are comparable
// - If we didn't run out of access to match, our borrow and access are comparalegal_flow
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think your find/replace was too aggressive :P

// and either equal or disjoint.
// - If we did run out of access, the borrow can access a part of it.

Expand Down