Skip to content

Commit

Permalink
Cleanup toolchain info fetching
Browse files Browse the repository at this point in the history
  • Loading branch information
Veykril committed Dec 29, 2024
1 parent 47f497d commit d5f7e78
Show file tree
Hide file tree
Showing 13 changed files with 197 additions and 230 deletions.
6 changes: 3 additions & 3 deletions src/tools/rust-analyzer/crates/hir-ty/src/layout/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use chalk_ir::{AdtId, TyKind};
use either::Either;
use hir_def::db::DefDatabase;
use project_model::{target_data_layout::RustcDataLayoutConfig, Sysroot};
use project_model::{toolchain_info::QueryConfig, Sysroot};
use rustc_hash::FxHashMap;
use syntax::ToSmolStr;
use test_fixture::WithFixture;
Expand All @@ -17,8 +17,8 @@ use crate::{
mod closure;

fn current_machine_data_layout() -> String {
project_model::target_data_layout::get(
RustcDataLayoutConfig::Rustc(&Sysroot::empty()),
project_model::toolchain_info::target_data_layout::get(
QueryConfig::Rustc(&Sysroot::empty()),
None,
&FxHashMap::default(),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,13 +178,13 @@ impl WorkspaceBuildScripts {
.current_dir(current_dir)
.args(["rustc", "-Z", "unstable-options", "--print", "target-libdir"])
.env("RUSTC_BOOTSTRAP", "1");
if let Ok(it) = utf8_stdout(cargo_config) {
if let Ok(it) = utf8_stdout(&mut cargo_config) {
return Ok(it);
}
let mut cmd = sysroot.tool(Tool::Rustc);
cmd.envs(extra_env);
cmd.args(["--print", "target-libdir"]);
utf8_stdout(cmd)
utf8_stdout(&mut cmd)
})()?;

let target_libdir = AbsPathBuf::try_from(Utf8PathBuf::from(target_libdir))
Expand Down
2 changes: 1 addition & 1 deletion src/tools/rust-analyzer/crates/project-model/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ pub(crate) fn cargo_config_env(
}
// if successful we receive `env.key.value = "value" per entry
tracing::debug!("Discovering cargo config env by {:?}", cargo_config);
utf8_stdout(cargo_config)
utf8_stdout(&mut cargo_config)
.map(parse_output_cargo_config_env)
.inspect(|env| {
tracing::debug!("Discovered cargo config env: {:?}", env);
Expand Down
9 changes: 4 additions & 5 deletions src/tools/rust-analyzer/crates/project-model/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,14 @@
//! procedural macros).
//! * Lowering of concrete model to a [`base_db::CrateGraph`]
pub mod project_json;
pub mod toolchain_info;

mod build_dependencies;
mod cargo_workspace;
mod env;
mod manifest_path;
pub mod project_json;
mod rustc_cfg;
mod sysroot;
pub mod target_data_layout;
mod target_triple;
mod workspace;

#[cfg(test)]
Expand Down Expand Up @@ -182,7 +181,7 @@ impl fmt::Display for ProjectManifest {
}
}

fn utf8_stdout(mut cmd: Command) -> anyhow::Result<String> {
fn utf8_stdout(cmd: &mut Command) -> anyhow::Result<String> {
let output = cmd.output().with_context(|| format!("{cmd:?} failed"))?;
if !output.status.success() {
match String::from_utf8(output.stderr) {
Expand Down
99 changes: 0 additions & 99 deletions src/tools/rust-analyzer/crates/project-model/src/rustc_cfg.rs

This file was deleted.

4 changes: 2 additions & 2 deletions src/tools/rust-analyzer/crates/project-model/src/sysroot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ fn discover_sysroot_dir(
rustc.envs(extra_env);
rustc.current_dir(current_dir).args(["--print", "sysroot"]);
tracing::debug!("Discovering sysroot by {:?}", rustc);
let stdout = utf8_stdout(rustc)?;
let stdout = utf8_stdout(&mut rustc)?;
Ok(AbsPathBuf::assert(Utf8PathBuf::from(stdout)))
}

Expand Down Expand Up @@ -472,7 +472,7 @@ fn discover_sysroot_src_dir_or_add_component(
rustup.envs(extra_env);
rustup.current_dir(current_dir).args(["component", "add", "rust-src"]);
tracing::info!("adding rust-src component by {:?}", rustup);
utf8_stdout(rustup).ok()?;
utf8_stdout(&mut rustup).ok()?;
get_rust_src(sysroot_path)
})
.ok_or_else(|| {
Expand Down

This file was deleted.

13 changes: 13 additions & 0 deletions src/tools/rust-analyzer/crates/project-model/src/toolchain_info.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
pub mod rustc_cfg;
pub mod target_data_layout;
pub mod target_triple;

use crate::{ManifestPath, Sysroot};

pub enum QueryConfig<'a> {
/// Directly invoke `rustc` to query the desired information.
Rustc(&'a Sysroot),
/// Attempt to use cargo to query the desired information, honoring cargo configurations.
/// If this fails, falls back to invoking `rustc` directly.
Cargo(&'a Sysroot, &'a ManifestPath),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
//! Get the built-in cfg flags for the to be compile platform.
use anyhow::Context;
use cfg::CfgAtom;
use rustc_hash::FxHashMap;
use toolchain::Tool;

use crate::{toolchain_info::QueryConfig, utf8_stdout};

/// Uses `rustc --print cfg` to fetch the builtin cfgs.
pub fn get(
config: QueryConfig<'_>,
target: Option<&str>,
extra_env: &FxHashMap<String, String>,
) -> Vec<CfgAtom> {
let _p = tracing::info_span!("rustc_cfg::get").entered();

let rustc_cfgs = rustc_print_cfg(target, extra_env, config);
let rustc_cfgs = match rustc_cfgs {
Ok(cfgs) => cfgs,
Err(e) => {
tracing::error!(?e, "failed to get rustc cfgs");
return vec![];
}
};

let rustc_cfgs = rustc_cfgs.lines().map(crate::parse_cfg).collect::<Result<Vec<_>, _>>();
match rustc_cfgs {
Ok(rustc_cfgs) => {
tracing::debug!(?rustc_cfgs, "rustc cfgs found");
rustc_cfgs
}
Err(e) => {
tracing::error!(?e, "failed to parse rustc cfgs");
vec![]
}
}
}

fn rustc_print_cfg(
target: Option<&str>,
extra_env: &FxHashMap<String, String>,
config: QueryConfig<'_>,
) -> anyhow::Result<String> {
const RUSTC_ARGS: [&str; 3] = ["--print", "cfg", "-O"];
let sysroot = match config {
QueryConfig::Cargo(sysroot, cargo_toml) => {
let mut cmd = sysroot.tool(Tool::Cargo);
cmd.envs(extra_env);
cmd.current_dir(cargo_toml.parent()).env("RUSTC_BOOTSTRAP", "1");
cmd.args(["rustc", "-Z", "unstable-options"]).args(RUSTC_ARGS);
if let Some(target) = target {
cmd.args(["--target", target]);
}

match utf8_stdout(&mut cmd) {
Ok(it) => return Ok(it),
Err(e) => {
tracing::warn!(
%e,
"failed to run `{cmd:?}`, falling back to invoking rustc directly"
);
sysroot
}
}
}
QueryConfig::Rustc(sysroot) => sysroot,
};

let mut cmd = sysroot.tool(Tool::Rustc);
cmd.envs(extra_env);
cmd.args(RUSTC_ARGS);
if let Some(target) = target {
cmd.args(["--target", target]);
}

utf8_stdout(&mut cmd).with_context(|| format!("unable to fetch cfgs via `{cmd:?}`"))
}
Loading

0 comments on commit d5f7e78

Please sign in to comment.