Skip to content

Commit

Permalink
Merge pull request #18785 from Veykril/push-uvsqposqyvmo
Browse files Browse the repository at this point in the history
Cleanup toolchain info fetching
  • Loading branch information
Veykril authored Dec 29, 2024
2 parents 293df4c + 98fde69 commit 90b724a
Show file tree
Hide file tree
Showing 27 changed files with 438 additions and 436 deletions.
4 changes: 4 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@ disallowed-types = [
{ path = "std::collections::HashSet", reason = "use FxHashSet" },
{ path = "std::collections::hash_map::RandomState", reason = "use BuildHasherDefault<FxHasher>"}
]

disallowed-methods = [
{ path = "std::process::Command::new", reason = "use `toolchain::command` instead as it forces the choice of a working directory" },
]
6 changes: 3 additions & 3 deletions 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(), &std::env::current_dir().unwrap()),
None,
&FxHashMap::default(),
)
Expand Down
1 change: 1 addition & 0 deletions crates/ide/src/expand_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ fn _format(
let &crate_id = db.relevant_crates(file_id).iter().next()?;
let edition = db.crate_graph()[crate_id].edition;

#[allow(clippy::disallowed_methods)]
let mut cmd = std::process::Command::new(toolchain::Tool::Rustfmt.path());
cmd.arg("--edition");
cmd.arg(edition.to_string());
Expand Down
1 change: 1 addition & 0 deletions crates/proc-macro-api/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ fn mk_child(
env: impl IntoIterator<Item = (impl AsRef<std::ffi::OsStr>, impl AsRef<std::ffi::OsStr>)>,
null_stderr: bool,
) -> io::Result<Child> {
#[allow(clippy::disallowed_methods)]
let mut cmd = Command::new(path);
cmd.envs(env)
.env("RUST_ANALYZER_INTERNALS_DO_NOT_USE", "this is unstable")
Expand Down
1 change: 1 addition & 0 deletions crates/proc-macro-srv/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ fn main() {
println!("cargo::rustc-check-cfg=cfg(rust_analyzer)");

let rustc = env::var("RUSTC").expect("proc-macro-srv's build script expects RUSTC to be set");
#[allow(clippy::disallowed_methods)]
let output = Command::new(rustc).arg("--version").output().expect("rustc --version must run");
let version_string = std::str::from_utf8(&output.stdout[..])
.expect("rustc --version output must be UTF-8")
Expand Down
2 changes: 2 additions & 0 deletions crates/proc-macro-srv/proc-macro-test/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
//! a specific rustup toolchain: this allows testing against older ABIs (e.g.
//! 1.58) and future ABIs (stage1, nightly)
#![allow(clippy::disallowed_methods)]

use std::{
env,
path::{Path, PathBuf},
Expand Down
14 changes: 6 additions & 8 deletions crates/project-model/src/build_dependencies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,19 +172,18 @@ impl WorkspaceBuildScripts {
}
let res = (|| {
let target_libdir = (|| {
let mut cargo_config = sysroot.tool(Tool::Cargo);
let mut cargo_config = sysroot.tool(Tool::Cargo, current_dir);
cargo_config.envs(extra_env);
cargo_config
.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);
let mut cmd = sysroot.tool(Tool::Rustc, current_dir);
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 Expand Up @@ -390,12 +389,12 @@ impl WorkspaceBuildScripts {
) -> io::Result<Command> {
let mut cmd = match config.run_build_script_command.as_deref() {
Some([program, args @ ..]) => {
let mut cmd = Command::new(program);
let mut cmd = toolchain::command(program, current_dir);
cmd.args(args);
cmd
}
_ => {
let mut cmd = sysroot.tool(Tool::Cargo);
let mut cmd = sysroot.tool(Tool::Cargo, current_dir);

cmd.args(["check", "--quiet", "--workspace", "--message-format=json"]);
cmd.args(&config.extra_args);
Expand Down Expand Up @@ -448,7 +447,6 @@ impl WorkspaceBuildScripts {
}
};

cmd.current_dir(current_dir);
cmd.envs(&config.extra_env);
if config.wrap_rustc_in_build_scripts {
// Setup RUSTC_WRAPPER to point to `rust-analyzer` binary itself. We use
Expand Down
2 changes: 1 addition & 1 deletion crates/project-model/src/cargo_workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ impl CargoWorkspace {
no_deps: bool,
progress: &dyn Fn(String),
) -> anyhow::Result<(cargo_metadata::Metadata, Option<anyhow::Error>)> {
let cargo = sysroot.tool(Tool::Cargo);
let cargo = sysroot.tool(Tool::Cargo, current_dir);
let mut meta = MetadataCommand::new();
meta.cargo_path(cargo.get_program());
cargo.get_envs().for_each(|(var, val)| _ = meta.env(var, val.unwrap_or_default()));
Expand Down
5 changes: 2 additions & 3 deletions crates/project-model/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,18 +74,17 @@ pub(crate) fn cargo_config_env(
extra_env: &FxHashMap<String, String>,
sysroot: &Sysroot,
) -> FxHashMap<String, String> {
let mut cargo_config = sysroot.tool(Tool::Cargo);
let mut cargo_config = sysroot.tool(Tool::Cargo, manifest.parent());
cargo_config.envs(extra_env);
cargo_config
.current_dir(manifest.parent())
.args(["-Z", "unstable-options", "config", "get", "env"])
.env("RUSTC_BOOTSTRAP", "1");
if manifest.is_rust_manifest() {
cargo_config.arg("-Zscript");
}
// 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
26 changes: 21 additions & 5 deletions crates/project-model/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,31 @@
//! procedural macros).
//! * Lowering of concrete model to a [`base_db::CrateGraph`]
pub mod project_json;
pub mod toolchain_info {
pub mod rustc_cfg;
pub mod target_data_layout;
pub mod target_triple;

use std::path::Path;

use crate::{ManifestPath, Sysroot};

#[derive(Copy, Clone)]
pub enum QueryConfig<'a> {
/// Directly invoke `rustc` to query the desired information.
Rustc(&'a Sysroot, &'a Path),
/// 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),
}
}

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 +198,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 crates/project-model/src/rustc_cfg.rs

This file was deleted.

20 changes: 10 additions & 10 deletions crates/project-model/src/sysroot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! but we can't process `.rlib` and need source code instead. The source code
//! is typically installed with `rustup component add rust-src` command.
use std::{env, fs, ops, process::Command};
use std::{env, fs, ops, path::Path, process::Command};

use anyhow::{format_err, Result};
use base_db::CrateName;
Expand Down Expand Up @@ -170,7 +170,7 @@ impl Sysroot {
}

/// Returns a command to run a tool preferring the cargo proxies if the sysroot exists.
pub fn tool(&self, tool: Tool) -> Command {
pub fn tool(&self, tool: Tool, current_dir: impl AsRef<Path>) -> Command {
match self.root() {
Some(root) => {
// special case rustc, we can look that up directly in the sysroot's bin folder
Expand All @@ -179,15 +179,15 @@ impl Sysroot {
if let Some(path) =
probe_for_binary(root.join("bin").join(Tool::Rustc.name()).into())
{
return Command::new(path);
return toolchain::command(path, current_dir);
}
}

let mut cmd = Command::new(tool.prefer_proxy());
let mut cmd = toolchain::command(tool.prefer_proxy(), current_dir);
cmd.env("RUSTUP_TOOLCHAIN", AsRef::<std::path::Path>::as_ref(root));
cmd
}
_ => Command::new(tool.path()),
_ => toolchain::command(tool.path(), current_dir),
}
}

Expand Down Expand Up @@ -436,11 +436,11 @@ fn discover_sysroot_dir(
current_dir: &AbsPath,
extra_env: &FxHashMap<String, String>,
) -> Result<AbsPathBuf> {
let mut rustc = Command::new(Tool::Rustc.path());
let mut rustc = toolchain::command(Tool::Rustc.path(), current_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 @@ -468,11 +468,11 @@ fn discover_sysroot_src_dir_or_add_component(
) -> Result<AbsPathBuf> {
discover_sysroot_src_dir(sysroot_path)
.or_else(|| {
let mut rustup = Command::new(Tool::Rustup.prefer_proxy());
let mut rustup = toolchain::command(Tool::Rustup.prefer_proxy(), current_dir);
rustup.envs(extra_env);
rustup.current_dir(current_dir).args(["component", "add", "rust-src"]);
rustup.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
Loading

0 comments on commit 90b724a

Please sign in to comment.