Skip to content

Commit

Permalink
refactor rustc_cfg to be more inline with docs/dev/style.md
Browse files Browse the repository at this point in the history
  • Loading branch information
davidbarsky committed Sep 7, 2023
1 parent 5b5bce8 commit 553152e
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 52 deletions.
88 changes: 49 additions & 39 deletions crates/project-model/src/rustc_cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@

use std::process::Command;

use anyhow::Context;
use rustc_hash::FxHashMap;

use crate::{cfg_flag::CfgFlag, utf8_stdout, ManifestPath, Sysroot};

pub(crate) enum Config<'a> {
Cargo(&'a ManifestPath),
Explicit(&'a Sysroot),
Discover,
}

pub(crate) fn get(
cargo_toml: Option<&ManifestPath>,
sysroot: Option<&Sysroot>,
target: Option<&str>,
extra_env: &FxHashMap<String, String>,
config: Config<'_>,
) -> Vec<CfgFlag> {
let _p = profile::span("rustc_cfg::get");
let mut res = Vec::with_capacity(6 * 2 + 1);
Expand All @@ -26,64 +32,68 @@ pub(crate) fn get(
// Add miri cfg, which is useful for mir eval in stdlib
res.push(CfgFlag::Atom("miri".into()));

match get_rust_cfgs(cargo_toml, sysroot, target, extra_env) {
let rustc_cfgs = get_rust_cfgs(target, extra_env, config);

let rustc_cfgs = match rustc_cfgs {
Ok(cfgs) => cfgs,
Err(e) => {
tracing::error!(?e, "failed to get rustc cfgs");
return res;
}
};

let rustc_cfgs =
rustc_cfgs.lines().map(|it| it.parse::<CfgFlag>()).collect::<Result<Vec<_>, _>>();

match rustc_cfgs {
Ok(rustc_cfgs) => {
tracing::debug!(
"rustc cfgs found: {:?}",
rustc_cfgs
.lines()
.map(|it| it.parse::<CfgFlag>().map(|it| it.to_string()))
.collect::<Vec<_>>()
);
res.extend(rustc_cfgs.lines().filter_map(|it| it.parse().ok()));
tracing::debug!(?rustc_cfgs, "rustc cfgs found");
res.extend(rustc_cfgs);
}
Err(e) => {
tracing::error!(?e, "failed to get rustc cfgs")
}
Err(e) => tracing::error!("failed to get rustc cfgs: {e:?}"),
}

res
}

fn get_rust_cfgs(
cargo_toml: Option<&ManifestPath>,
sysroot: Option<&Sysroot>,
target: Option<&str>,
extra_env: &FxHashMap<String, String>,
config: Config<'_>,
) -> anyhow::Result<String> {
if let Some(cargo_toml) = cargo_toml {
let mut cargo_config = Command::new(toolchain::cargo());
cargo_config.envs(extra_env);
cargo_config
.current_dir(cargo_toml.parent())
.args(["rustc", "-Z", "unstable-options", "--print", "cfg"])
.env("RUSTC_BOOTSTRAP", "1");
if let Some(target) = target {
cargo_config.args(["--target", target]);
}
match utf8_stdout(cargo_config) {
Ok(it) => return Ok(it),
Err(e) => tracing::debug!("{e:?}: falling back to querying rustc for cfgs"),
}
}
let mut cmd = match config {
Config::Cargo(cargo_toml) => {
let mut cmd = Command::new(toolchain::cargo());
cmd.envs(extra_env);
cmd.current_dir(cargo_toml.parent())
.args(["rustc", "-Z", "unstable-options", "--print", "cfg"])
.env("RUSTC_BOOTSTRAP", "1");
if let Some(target) = target {
cmd.args(["--target", target]);
}

let rustc = match sysroot {
Some(sysroot) => {
let rustc = sysroot.discover_rustc()?.into();
tracing::debug!(?rustc, "using rustc from sysroot");
rustc
return utf8_stdout(cmd).context("Unable to run `cargo rustc`");
}
Config::Explicit(sysroot) => {
let rustc: std::path::PathBuf = sysroot.discover_rustc()?.into();
tracing::debug!(?rustc, "using explicit rustc from sysroot");
Command::new(rustc)
}
None => {
Config::Discover => {
let rustc = toolchain::rustc();
tracing::debug!(?rustc, "using rustc from env");
rustc
Command::new(rustc)
}
};

// using unstable cargo features failed, fall back to using plain rustc
let mut cmd = Command::new(rustc);
cmd.envs(extra_env);
cmd.args(["--print", "cfg", "-O"]);
if let Some(target) = target {
cmd.args(["--target", target]);
}
utf8_stdout(cmd)

let out = utf8_stdout(cmd).context("Unable to run `rustc`")?;
Ok(out)
}
45 changes: 32 additions & 13 deletions crates/project-model/src/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,10 +280,9 @@ impl ProjectWorkspace {
});

let rustc_cfg = rustc_cfg::get(
Some(&cargo_toml),
None,
config.target.as_deref(),
&config.extra_env,
rustc_cfg::Config::Cargo(cargo_toml),
);

let cfg_overrides = config.cfg_overrides.clone();
Expand Down Expand Up @@ -335,11 +334,18 @@ impl ProjectWorkspace {
}
(None, None) => Err(None),
};
if let Ok(sysroot) = &sysroot {
tracing::info!(src_root = %sysroot.src_root(), root = %sysroot.root(), "Using sysroot");
}
let config = match &sysroot {
Ok(sysroot) => {
tracing::debug!(src_root = %sysroot.src_root(), root = %sysroot.root(), "Using sysroot");
rustc_cfg::Config::Explicit(sysroot)
}
Err(_) => {
tracing::debug!("discovering sysroot");
rustc_cfg::Config::Discover
}
};

let rustc_cfg = rustc_cfg::get(None, sysroot.as_ref().ok(), target, extra_env);
let rustc_cfg = rustc_cfg::get(target, extra_env, config);
ProjectWorkspace::Json { project: project_json, sysroot, rustc_cfg, toolchain }
}

Expand All @@ -361,10 +367,18 @@ impl ProjectWorkspace {
}
None => Err(None),
};
if let Ok(sysroot) = &sysroot {
tracing::info!(src_root = %sysroot.src_root(), root = %sysroot.root(), "Using sysroot");
}
let rustc_cfg = rustc_cfg::get(None, sysroot.as_ref().ok(), None, &Default::default());
let rustc_config = match &sysroot {
Ok(sysroot) => {
tracing::info!(src_root = %sysroot.src_root(), root = %sysroot.root(), "Using sysroot");
rustc_cfg::Config::Explicit(sysroot)
}
Err(_) => {
tracing::info!("discovering sysroot");
rustc_cfg::Config::Discover
}
};

let rustc_cfg = rustc_cfg::get(None, &FxHashMap::default(), rustc_config);
Ok(ProjectWorkspace::DetachedFiles { files: detached_files, sysroot, rustc_cfg })
}

Expand Down Expand Up @@ -758,9 +772,14 @@ fn project_json_to_crate_graph(
let env = env.clone().into_iter().collect();

let target_cfgs = match target.as_deref() {
Some(target) => cfg_cache
.entry(target)
.or_insert_with(|| rustc_cfg::get(None, sysroot, Some(target), extra_env)),
Some(target) => cfg_cache.entry(target).or_insert_with(|| {
let rustc_cfg = match sysroot {
Some(sysroot) => rustc_cfg::Config::Explicit(sysroot),
None => rustc_cfg::Config::Discover,
};

rustc_cfg::get(Some(target), extra_env, rustc_cfg)
}),
None => &rustc_cfg,
};

Expand Down

0 comments on commit 553152e

Please sign in to comment.