Auto merge of #17795 - Veykril:library-dep-loading, r=Veykril

feat: Load sysroot library via cargo metadata

See https://github.com/rust-lang/rust/pull/128534, fixes https://github.com/rust-lang/rust-analyzer/issues/7637

Requires a toolchain from 176e54520 2024-08-04 or later to work.
This commit is contained in:
bors 2024-08-05 10:45:47 +00:00
commit 000eed1da8
16 changed files with 156 additions and 212 deletions

View file

@ -43,7 +43,7 @@ pub(crate) fn bind_unused_param(acc: &mut Assists, ctx: &AssistContext<'_>) -> O
acc.add( acc.add(
AssistId("bind_unused_param", AssistKind::QuickFix), AssistId("bind_unused_param", AssistKind::QuickFix),
&format!("Bind as `let _ = {ident_pat};`"), format!("Bind as `let _ = {ident_pat};`"),
param.syntax().text_range(), param.syntax().text_range(),
|builder| { |builder| {
let line_index = ctx.db().line_index(ctx.file_id().into()); let line_index = ctx.db().line_index(ctx.file_id().into());

View file

@ -16,7 +16,7 @@ use ide_db::{
use itertools::Itertools; use itertools::Itertools;
use proc_macro_api::{MacroDylib, ProcMacroServer}; use proc_macro_api::{MacroDylib, ProcMacroServer};
use project_model::{ use project_model::{
CargoConfig, ManifestPath, PackageRoot, ProjectManifest, ProjectWorkspace, ProjectWorkspaceKind, CargoConfig, PackageRoot, ProjectManifest, ProjectWorkspace, ProjectWorkspaceKind,
}; };
use span::Span; use span::Span;
use vfs::{file_set::FileSetConfig, loader::Handle, AbsPath, AbsPathBuf, VfsPath}; use vfs::{file_set::FileSetConfig, loader::Handle, AbsPath, AbsPathBuf, VfsPath};
@ -247,7 +247,7 @@ impl ProjectFolders {
let mut file_set_roots: Vec<VfsPath> = vec![]; let mut file_set_roots: Vec<VfsPath> = vec![];
let mut entries = vec![]; let mut entries = vec![];
if let Some(manifest) = ws.manifest().map(ManifestPath::as_ref) { if let Some(manifest) = ws.manifest().map(|it| it.to_path_buf()) {
file_set_roots.push(VfsPath::from(manifest.to_owned())); file_set_roots.push(VfsPath::from(manifest.to_owned()));
entries.push(manifest.to_owned()); entries.push(manifest.to_owned());
} }

View file

@ -141,6 +141,10 @@ impl AbsPathBuf {
pub fn push<P: AsRef<Utf8Path>>(&mut self, suffix: P) { pub fn push<P: AsRef<Utf8Path>>(&mut self, suffix: P) {
self.0.push(suffix) self.0.push(suffix)
} }
pub fn join(&self, path: impl AsRef<Utf8Path>) -> Self {
Self(self.0.join(path))
}
} }
impl fmt::Display for AbsPathBuf { impl fmt::Display for AbsPathBuf {

View file

@ -73,7 +73,7 @@ impl WorkspaceBuildScripts {
cmd.args(&config.extra_args); cmd.args(&config.extra_args);
cmd.arg("--manifest-path"); cmd.arg("--manifest-path");
cmd.arg(manifest_path.as_ref()); cmd.arg(manifest_path);
if let Some(target_dir) = &config.target_dir { if let Some(target_dir) = &config.target_dir {
cmd.arg("--target-dir").arg(target_dir); cmd.arg("--target-dir").arg(target_dir);

View file

@ -85,8 +85,6 @@ pub struct CargoConfig {
pub target: Option<String>, pub target: Option<String>,
/// Sysroot loading behavior /// Sysroot loading behavior
pub sysroot: Option<RustLibSource>, pub sysroot: Option<RustLibSource>,
/// Whether to invoke `cargo metadata` on the sysroot crate.
pub sysroot_query_metadata: bool,
pub sysroot_src: Option<AbsPathBuf>, pub sysroot_src: Option<AbsPathBuf>,
/// rustc private crate source /// rustc private crate source
pub rustc_source: Option<RustLibSource>, pub rustc_source: Option<RustLibSource>,
@ -259,6 +257,7 @@ impl CargoWorkspace {
current_dir: &AbsPath, current_dir: &AbsPath,
config: &CargoConfig, config: &CargoConfig,
sysroot: &Sysroot, sysroot: &Sysroot,
locked: bool,
progress: &dyn Fn(String), progress: &dyn Fn(String),
) -> anyhow::Result<cargo_metadata::Metadata> { ) -> anyhow::Result<cargo_metadata::Metadata> {
let targets = find_list_of_build_targets(config, cargo_toml, sysroot); let targets = find_list_of_build_targets(config, cargo_toml, sysroot);
@ -312,6 +311,9 @@ impl CargoWorkspace {
// opt into it themselves. // opt into it themselves.
other_options.push("-Zscript".to_owned()); other_options.push("-Zscript".to_owned());
} }
if locked {
other_options.push("--locked".to_owned());
}
meta.other_options(other_options); meta.other_options(other_options);
// FIXME: Fetching metadata is a slow process, as it might require // FIXME: Fetching metadata is a slow process, as it might require

View file

@ -64,6 +64,18 @@ impl AsRef<AbsPath> for ManifestPath {
} }
} }
impl AsRef<std::path::Path> for ManifestPath {
fn as_ref(&self) -> &std::path::Path {
self.file.as_ref()
}
}
impl AsRef<std::ffi::OsStr> for ManifestPath {
fn as_ref(&self) -> &std::ffi::OsStr {
self.file.as_ref()
}
}
impl Borrow<AbsPath> for ManifestPath { impl Borrow<AbsPath> for ManifestPath {
fn borrow(&self) -> &AbsPath { fn borrow(&self) -> &AbsPath {
self.file.borrow() self.file.borrow()

View file

@ -123,32 +123,27 @@ impl Sysroot {
// FIXME: Expose a builder api as loading the sysroot got way too modular and complicated. // FIXME: Expose a builder api as loading the sysroot got way too modular and complicated.
impl Sysroot { impl Sysroot {
/// Attempts to discover the toolchain's sysroot from the given `dir`. /// Attempts to discover the toolchain's sysroot from the given `dir`.
pub fn discover( pub fn discover(dir: &AbsPath, extra_env: &FxHashMap<String, String>) -> Sysroot {
dir: &AbsPath,
extra_env: &FxHashMap<String, String>,
metadata: bool,
) -> Sysroot {
let sysroot_dir = discover_sysroot_dir(dir, extra_env); let sysroot_dir = discover_sysroot_dir(dir, extra_env);
let sysroot_src_dir = sysroot_dir.as_ref().ok().map(|sysroot_dir| { let sysroot_src_dir = sysroot_dir.as_ref().ok().map(|sysroot_dir| {
discover_sysroot_src_dir_or_add_component(sysroot_dir, dir, extra_env) discover_sysroot_src_dir_or_add_component(sysroot_dir, dir, extra_env)
}); });
Sysroot::load_core_check(Some(sysroot_dir), sysroot_src_dir, metadata) Sysroot::load_core_check(Some(sysroot_dir), sysroot_src_dir)
} }
pub fn discover_with_src_override( pub fn discover_with_src_override(
current_dir: &AbsPath, current_dir: &AbsPath,
extra_env: &FxHashMap<String, String>, extra_env: &FxHashMap<String, String>,
sysroot_src_dir: AbsPathBuf, sysroot_src_dir: AbsPathBuf,
metadata: bool,
) -> Sysroot { ) -> Sysroot {
let sysroot_dir = discover_sysroot_dir(current_dir, extra_env); let sysroot_dir = discover_sysroot_dir(current_dir, extra_env);
Sysroot::load_core_check(Some(sysroot_dir), Some(Ok(sysroot_src_dir)), metadata) Sysroot::load_core_check(Some(sysroot_dir), Some(Ok(sysroot_src_dir)))
} }
pub fn discover_sysroot_src_dir(sysroot_dir: AbsPathBuf, metadata: bool) -> Sysroot { pub fn discover_sysroot_src_dir(sysroot_dir: AbsPathBuf) -> Sysroot {
let sysroot_src_dir = discover_sysroot_src_dir(&sysroot_dir) let sysroot_src_dir = discover_sysroot_src_dir(&sysroot_dir)
.ok_or_else(|| format_err!("can't find standard library sources in {sysroot_dir}")); .ok_or_else(|| format_err!("can't find standard library sources in {sysroot_dir}"));
Sysroot::load_core_check(Some(Ok(sysroot_dir)), Some(sysroot_src_dir), metadata) Sysroot::load_core_check(Some(Ok(sysroot_dir)), Some(sysroot_src_dir))
} }
pub fn discover_rustc_src(&self) -> Option<ManifestPath> { pub fn discover_rustc_src(&self) -> Option<ManifestPath> {
@ -191,20 +186,15 @@ impl Sysroot {
}) })
} }
pub fn load( pub fn load(sysroot_dir: Option<AbsPathBuf>, sysroot_src_dir: Option<AbsPathBuf>) -> Sysroot {
sysroot_dir: Option<AbsPathBuf>, Self::load_core_check(sysroot_dir.map(Ok), sysroot_src_dir.map(Ok))
sysroot_src_dir: Option<AbsPathBuf>,
metadata: bool,
) -> Sysroot {
Self::load_core_check(sysroot_dir.map(Ok), sysroot_src_dir.map(Ok), metadata)
} }
fn load_core_check( fn load_core_check(
sysroot_dir: Option<Result<AbsPathBuf, anyhow::Error>>, sysroot_dir: Option<Result<AbsPathBuf, anyhow::Error>>,
sysroot_src_dir: Option<Result<AbsPathBuf, anyhow::Error>>, sysroot_src_dir: Option<Result<AbsPathBuf, anyhow::Error>>,
metadata: bool,
) -> Sysroot { ) -> Sysroot {
let mut sysroot = Self::load_(sysroot_dir, sysroot_src_dir, metadata); let mut sysroot = Self::load_(sysroot_dir, sysroot_src_dir);
if sysroot.error.is_none() { if sysroot.error.is_none() {
if let Some(src_root) = &sysroot.src_root { if let Some(src_root) = &sysroot.src_root {
let has_core = match &sysroot.mode { let has_core = match &sysroot.mode {
@ -230,7 +220,6 @@ impl Sysroot {
fn load_( fn load_(
sysroot_dir: Option<Result<AbsPathBuf, anyhow::Error>>, sysroot_dir: Option<Result<AbsPathBuf, anyhow::Error>>,
sysroot_src_dir: Option<Result<AbsPathBuf, anyhow::Error>>, sysroot_src_dir: Option<Result<AbsPathBuf, anyhow::Error>>,
metadata: bool,
) -> Sysroot { ) -> Sysroot {
let sysroot_dir = match sysroot_dir { let sysroot_dir = match sysroot_dir {
Some(Ok(sysroot_dir)) => Some(sysroot_dir), Some(Ok(sysroot_dir)) => Some(sysroot_dir),
@ -263,119 +252,16 @@ impl Sysroot {
} }
} }
}; };
if metadata { let library_manifest = ManifestPath::try_from(sysroot_src_dir.join("Cargo.toml")).unwrap();
let sysroot: Option<_> = (|| { if fs::metadata(&library_manifest).is_ok() {
let sysroot_cargo_toml = ManifestPath::try_from( if let Some(sysroot) =
AbsPathBuf::try_from(&*format!("{sysroot_src_dir}/sysroot/Cargo.toml")).ok()?, Self::load_library_via_cargo(library_manifest, &sysroot_dir, &sysroot_src_dir)
) {
.ok()?;
let current_dir =
AbsPathBuf::try_from(&*format!("{sysroot_src_dir}/sysroot")).ok()?;
let mut cargo_config = CargoConfig::default();
// the sysroot uses `public-dependency`, so we make cargo think it's a nightly
cargo_config.extra_env.insert(
"__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS".to_owned(),
"nightly".to_owned(),
);
let res = CargoWorkspace::fetch_metadata(
&sysroot_cargo_toml,
&current_dir,
&cargo_config,
&Sysroot::empty(),
&|_| (),
)
.map_err(|e| {
tracing::error!(
"failed to load sysroot `{sysroot_src_dir}/sysroot/Cargo.toml`: {}",
e
);
e
});
if let Err(e) =
std::fs::remove_file(format!("{sysroot_src_dir}/sysroot/Cargo.lock"))
{
tracing::error!(
"failed to remove sysroot `{sysroot_src_dir}/sysroot/Cargo.lock`: {}",
e
)
}
let mut res = res.ok()?;
// Patch out `rustc-std-workspace-*` crates to point to the real crates.
// This is done prior to `CrateGraph` construction to avoid having duplicate `std` targets.
let mut fake_core = None;
let mut fake_alloc = None;
let mut fake_std = None;
let mut real_core = None;
let mut real_alloc = None;
let mut real_std = None;
res.packages.iter().enumerate().for_each(|(idx, package)| {
match package.name.strip_prefix("rustc-std-workspace-") {
Some("core") => fake_core = Some((idx, package.id.clone())),
Some("alloc") => fake_alloc = Some((idx, package.id.clone())),
Some("std") => fake_std = Some((idx, package.id.clone())),
Some(_) => {
tracing::warn!("unknown rustc-std-workspace-* crate: {}", package.name)
}
None => match &*package.name {
"core" => real_core = Some(package.id.clone()),
"alloc" => real_alloc = Some(package.id.clone()),
"std" => real_std = Some(package.id.clone()),
_ => (),
},
}
});
let patches =
[fake_core.zip(real_core), fake_alloc.zip(real_alloc), fake_std.zip(real_std)]
.into_iter()
.flatten();
let resolve = res.resolve.as_mut().expect("metadata executed with deps");
let mut remove_nodes = vec![];
for (idx, node) in resolve.nodes.iter_mut().enumerate() {
// Replace them in the dependency list
node.deps.iter_mut().for_each(|dep| {
if let Some((_, real)) =
patches.clone().find(|((_, fake_id), _)| *fake_id == dep.pkg)
{
dep.pkg = real;
}
});
if patches.clone().any(|((_, fake), _)| fake == node.id) {
remove_nodes.push(idx);
}
}
// Remove the fake ones from the resolve data
remove_nodes.into_iter().rev().for_each(|r| {
resolve.nodes.remove(r);
});
// Remove the fake ones from the packages
patches.map(|((r, _), _)| r).sorted().rev().for_each(|r| {
res.packages.remove(r);
});
res.workspace_members = res
.packages
.iter()
.filter(|&package| RELEVANT_SYSROOT_CRATES.contains(&&*package.name))
.map(|package| package.id.clone())
.collect();
let cargo_workspace = CargoWorkspace::new(res, sysroot_cargo_toml);
Some(Sysroot {
root: sysroot_dir.clone(),
src_root: Some(sysroot_src_dir.clone()),
mode: SysrootMode::Workspace(cargo_workspace),
error: None,
})
})();
if let Some(sysroot) = sysroot {
return sysroot; return sysroot;
} }
} }
tracing::debug!("Stitching sysroot library: {sysroot_src_dir}");
let mut stitched = Stitched { crates: Arena::default() }; let mut stitched = Stitched { crates: Arena::default() };
for path in SYSROOT_CRATES.trim().lines() { for path in SYSROOT_CRATES.trim().lines() {
@ -384,7 +270,7 @@ impl Sysroot {
.into_iter() .into_iter()
.map(|it| sysroot_src_dir.join(it)) .map(|it| sysroot_src_dir.join(it))
.filter_map(|it| ManifestPath::try_from(it).ok()) .filter_map(|it| ManifestPath::try_from(it).ok())
.find(|it| fs::metadata(it.as_ref()).is_ok()); .find(|it| fs::metadata(it).is_ok());
if let Some(root) = root { if let Some(root) = root {
stitched.crates.alloc(SysrootCrateData { stitched.crates.alloc(SysrootCrateData {
@ -425,6 +311,92 @@ impl Sysroot {
error: None, error: None,
} }
} }
fn load_library_via_cargo(
library_manifest: ManifestPath,
sysroot_dir: &Option<AbsPathBuf>,
sysroot_src_dir: &AbsPathBuf,
) -> Option<Sysroot> {
tracing::debug!("Loading library metadata: {library_manifest}");
let mut cargo_config = CargoConfig::default();
// the sysroot uses `public-dependency`, so we make cargo think it's a nightly
cargo_config.extra_env.insert(
"__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS".to_owned(),
"nightly".to_owned(),
);
let mut res = match CargoWorkspace::fetch_metadata(
&library_manifest,
sysroot_src_dir,
&cargo_config,
&Sysroot::empty(),
// Make sure we never attempt to write to the sysroot
true,
&|_| (),
) {
Ok(it) => it,
Err(e) => {
tracing::error!("`cargo metadata` failed on `{library_manifest}` : {e}");
return None;
}
};
// Patch out `rustc-std-workspace-*` crates to point to the real crates.
// This is done prior to `CrateGraph` construction to prevent de-duplication logic from failing.
let patches = {
let mut fake_core = None;
let mut fake_alloc = None;
let mut fake_std = None;
let mut real_core = None;
let mut real_alloc = None;
let mut real_std = None;
res.packages.iter().enumerate().for_each(|(idx, package)| {
match package.name.strip_prefix("rustc-std-workspace-") {
Some("core") => fake_core = Some((idx, package.id.clone())),
Some("alloc") => fake_alloc = Some((idx, package.id.clone())),
Some("std") => fake_std = Some((idx, package.id.clone())),
Some(_) => {
tracing::warn!("unknown rustc-std-workspace-* crate: {}", package.name)
}
None => match &*package.name {
"core" => real_core = Some(package.id.clone()),
"alloc" => real_alloc = Some(package.id.clone()),
"std" => real_std = Some(package.id.clone()),
_ => (),
},
}
});
[fake_core.zip(real_core), fake_alloc.zip(real_alloc), fake_std.zip(real_std)]
.into_iter()
.flatten()
};
let resolve = res.resolve.as_mut().expect("metadata executed with deps");
resolve.nodes.retain_mut(|node| {
// Replace `rustc-std-workspace` crate with the actual one in the dependency list
node.deps.iter_mut().for_each(|dep| {
let real_pkg = patches.clone().find(|((_, fake_id), _)| *fake_id == dep.pkg);
if let Some((_, real)) = real_pkg {
dep.pkg = real;
}
});
// Remove this node if it's a fake one
!patches.clone().any(|((_, fake), _)| fake == node.id)
});
// Remove the fake ones from the package list
patches.map(|((idx, _), _)| idx).sorted().rev().for_each(|idx| {
res.packages.remove(idx);
});
let cargo_workspace = CargoWorkspace::new(res, library_manifest);
Some(Sysroot {
root: sysroot_dir.clone(),
src_root: Some(sysroot_src_dir.clone()),
mode: SysrootMode::Workspace(cargo_workspace),
error: None,
})
}
} }
fn discover_sysroot_dir( fn discover_sysroot_dir(
@ -485,7 +457,7 @@ fn get_rustc_src(sysroot_path: &AbsPath) -> Option<ManifestPath> {
let rustc_src = sysroot_path.join("lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml"); let rustc_src = sysroot_path.join("lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml");
let rustc_src = ManifestPath::try_from(rustc_src).ok()?; let rustc_src = ManifestPath::try_from(rustc_src).ok()?;
tracing::debug!("checking for rustc source code: {rustc_src}"); tracing::debug!("checking for rustc source code: {rustc_src}");
if fs::metadata(rustc_src.as_ref()).is_ok() { if fs::metadata(&rustc_src).is_ok() {
Some(rustc_src) Some(rustc_src)
} else { } else {
None None
@ -531,5 +503,3 @@ test";
const PROC_MACRO_DEPS: &str = " const PROC_MACRO_DEPS: &str = "
std std
core"; core";
const RELEVANT_SYSROOT_CRATES: &[&str] = &["core", "alloc", "std", "test", "proc_macro"];

View file

@ -12,8 +12,8 @@ use span::FileId;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
workspace::ProjectWorkspaceKind, CargoWorkspace, CfgOverrides, ManifestPath, ProjectJson, sysroot::SysrootMode, workspace::ProjectWorkspaceKind, CargoWorkspace, CfgOverrides,
ProjectJsonData, ProjectWorkspace, Sysroot, WorkspaceBuildScripts, ManifestPath, ProjectJson, ProjectJsonData, ProjectWorkspace, Sysroot, WorkspaceBuildScripts,
}; };
fn load_cargo(file: &str) -> (CrateGraph, ProcMacroPaths) { fn load_cargo(file: &str) -> (CrateGraph, ProcMacroPaths) {
@ -146,7 +146,7 @@ fn get_fake_sysroot() -> Sysroot {
// fake sysroot, so we give them both the same path: // fake sysroot, so we give them both the same path:
let sysroot_dir = AbsPathBuf::assert(sysroot_path); let sysroot_dir = AbsPathBuf::assert(sysroot_path);
let sysroot_src_dir = sysroot_dir.clone(); let sysroot_src_dir = sysroot_dir.clone();
Sysroot::load(Some(sysroot_dir), Some(sysroot_src_dir), false) Sysroot::load(Some(sysroot_dir), Some(sysroot_src_dir))
} }
fn rooted_project_json(data: ProjectJsonData) -> ProjectJson { fn rooted_project_json(data: ProjectJsonData) -> ProjectJson {
@ -274,10 +274,9 @@ fn crate_graph_dedup() {
} }
#[test] #[test]
// FIXME Remove the ignore
#[ignore = "requires nightly until the sysroot ships a cargo workspace for library on stable"]
fn smoke_test_real_sysroot_cargo() { fn smoke_test_real_sysroot_cargo() {
if std::env::var("SYSROOT_CARGO_METADATA").is_err() {
return;
}
let file_map = &mut FxHashMap::<AbsPathBuf, FileId>::default(); let file_map = &mut FxHashMap::<AbsPathBuf, FileId>::default();
let meta: Metadata = get_test_json_file("hello-world-metadata.json"); let meta: Metadata = get_test_json_file("hello-world-metadata.json");
let manifest_path = let manifest_path =
@ -286,8 +285,8 @@ fn smoke_test_real_sysroot_cargo() {
let sysroot = Sysroot::discover( let sysroot = Sysroot::discover(
AbsPath::assert(Utf8Path::new(env!("CARGO_MANIFEST_DIR"))), AbsPath::assert(Utf8Path::new(env!("CARGO_MANIFEST_DIR"))),
&Default::default(), &Default::default(),
true,
); );
assert!(matches!(sysroot.mode(), SysrootMode::Workspace(_)));
let project_workspace = ProjectWorkspace { let project_workspace = ProjectWorkspace {
kind: ProjectWorkspaceKind::Cargo { kind: ProjectWorkspaceKind::Cargo {

View file

@ -194,7 +194,7 @@ impl ProjectWorkspace {
) -> anyhow::Result<ProjectWorkspace> { ) -> anyhow::Result<ProjectWorkspace> {
let res = match manifest { let res = match manifest {
ProjectManifest::ProjectJson(project_json) => { ProjectManifest::ProjectJson(project_json) => {
let file = fs::read_to_string(project_json.as_ref()) let file = fs::read_to_string(project_json)
.with_context(|| format!("Failed to read json file {project_json}"))?; .with_context(|| format!("Failed to read json file {project_json}"))?;
let data = serde_json::from_str(&file) let data = serde_json::from_str(&file)
.with_context(|| format!("Failed to deserialize json file {project_json}"))?; .with_context(|| format!("Failed to deserialize json file {project_json}"))?;
@ -213,28 +213,22 @@ impl ProjectWorkspace {
} }
ProjectManifest::CargoToml(cargo_toml) => { ProjectManifest::CargoToml(cargo_toml) => {
let sysroot = match (&config.sysroot, &config.sysroot_src) { let sysroot = match (&config.sysroot, &config.sysroot_src) {
(Some(RustLibSource::Discover), None) => Sysroot::discover( (Some(RustLibSource::Discover), None) => {
cargo_toml.parent(), Sysroot::discover(cargo_toml.parent(), &config.extra_env)
&config.extra_env, }
config.sysroot_query_metadata,
),
(Some(RustLibSource::Discover), Some(sysroot_src)) => { (Some(RustLibSource::Discover), Some(sysroot_src)) => {
Sysroot::discover_with_src_override( Sysroot::discover_with_src_override(
cargo_toml.parent(), cargo_toml.parent(),
&config.extra_env, &config.extra_env,
sysroot_src.clone(), sysroot_src.clone(),
config.sysroot_query_metadata,
) )
} }
(Some(RustLibSource::Path(path)), None) => Sysroot::discover_sysroot_src_dir( (Some(RustLibSource::Path(path)), None) => {
path.clone(), Sysroot::discover_sysroot_src_dir(path.clone())
config.sysroot_query_metadata, }
), (Some(RustLibSource::Path(sysroot)), Some(sysroot_src)) => {
(Some(RustLibSource::Path(sysroot)), Some(sysroot_src)) => Sysroot::load( Sysroot::load(Some(sysroot.clone()), Some(sysroot_src.clone()))
Some(sysroot.clone()), }
Some(sysroot_src.clone()),
config.sysroot_query_metadata,
),
(None, _) => Sysroot::empty(), (None, _) => Sysroot::empty(),
}; };
tracing::info!(workspace = %cargo_toml, src_root = ?sysroot.src_root(), root = ?sysroot.root(), "Using sysroot"); tracing::info!(workspace = %cargo_toml, src_root = ?sysroot.src_root(), root = ?sysroot.root(), "Using sysroot");
@ -260,6 +254,7 @@ impl ProjectWorkspace {
..config.clone() ..config.clone()
}, },
&sysroot, &sysroot,
false,
progress, progress,
) { ) {
Ok(meta) => { Ok(meta) => {
@ -312,7 +307,8 @@ impl ProjectWorkspace {
cargo_toml.parent(), cargo_toml.parent(),
config, config,
&sysroot, &sysroot,
progress, false,
progress,
) )
.with_context(|| { .with_context(|| {
format!( format!(
@ -350,8 +346,7 @@ impl ProjectWorkspace {
extra_env: &FxHashMap<String, String>, extra_env: &FxHashMap<String, String>,
cfg_overrides: &CfgOverrides, cfg_overrides: &CfgOverrides,
) -> ProjectWorkspace { ) -> ProjectWorkspace {
let sysroot = let sysroot = Sysroot::load(project_json.sysroot.clone(), project_json.sysroot_src.clone());
Sysroot::load(project_json.sysroot.clone(), project_json.sysroot_src.clone(), false);
let cfg_config = RustcCfgConfig::Rustc(&sysroot); let cfg_config = RustcCfgConfig::Rustc(&sysroot);
let data_layout_config = RustcDataLayoutConfig::Rustc(&sysroot); let data_layout_config = RustcDataLayoutConfig::Rustc(&sysroot);
let toolchain = match get_toolchain_version( let toolchain = match get_toolchain_version(
@ -386,12 +381,8 @@ impl ProjectWorkspace {
) -> anyhow::Result<ProjectWorkspace> { ) -> anyhow::Result<ProjectWorkspace> {
let dir = detached_file.parent(); let dir = detached_file.parent();
let sysroot = match &config.sysroot { let sysroot = match &config.sysroot {
Some(RustLibSource::Path(path)) => { Some(RustLibSource::Path(path)) => Sysroot::discover_sysroot_src_dir(path.clone()),
Sysroot::discover_sysroot_src_dir(path.clone(), config.sysroot_query_metadata) Some(RustLibSource::Discover) => Sysroot::discover(dir, &config.extra_env),
}
Some(RustLibSource::Discover) => {
Sysroot::discover(dir, &config.extra_env, config.sysroot_query_metadata)
}
None => Sysroot::empty(), None => Sysroot::empty(),
}; };
@ -412,14 +403,14 @@ impl ProjectWorkspace {
); );
let cargo_script = let cargo_script =
CargoWorkspace::fetch_metadata(detached_file, dir, config, &sysroot, &|_| ()).ok().map( CargoWorkspace::fetch_metadata(detached_file, dir, config, &sysroot, false, &|_| ())
|ws| { .ok()
.map(|ws| {
( (
CargoWorkspace::new(ws, detached_file.clone()), CargoWorkspace::new(ws, detached_file.clone()),
WorkspaceBuildScripts::default(), WorkspaceBuildScripts::default(),
) )
}, });
);
let cargo_config_extra_env = cargo_config_env(detached_file, &config.extra_env, &sysroot); let cargo_config_extra_env = cargo_config_env(detached_file, &config.extra_env, &sysroot);
Ok(ProjectWorkspace { Ok(ProjectWorkspace {
@ -651,7 +642,7 @@ impl ProjectWorkspace {
ProjectWorkspaceKind::DetachedFile { file, cargo: cargo_script, .. } => { ProjectWorkspaceKind::DetachedFile { file, cargo: cargo_script, .. } => {
iter::once(PackageRoot { iter::once(PackageRoot {
is_local: true, is_local: true,
include: vec![file.as_ref().to_owned()], include: vec![file.to_path_buf()],
exclude: Vec::new(), exclude: Vec::new(),
}) })
.chain(cargo_script.iter().flat_map(|(cargo, build_scripts)| { .chain(cargo_script.iter().flat_map(|(cargo, build_scripts)| {

View file

@ -64,7 +64,6 @@ impl flags::AnalysisStats {
true => None, true => None,
false => Some(RustLibSource::Discover), false => Some(RustLibSource::Discover),
}, },
sysroot_query_metadata: self.query_sysroot_metadata,
..Default::default() ..Default::default()
}; };
let no_progress = &|_| (); let no_progress = &|_| ();

View file

@ -71,9 +71,6 @@ xflags::xflags! {
optional --with-deps optional --with-deps
/// Don't load sysroot crates (`std`, `core` & friends). /// Don't load sysroot crates (`std`, `core` & friends).
optional --no-sysroot optional --no-sysroot
/// Run cargo metadata on the sysroot to analyze its third-party dependencies.
/// Requires --no-sysroot to not be set.
optional --query-sysroot-metadata
/// Don't run build scripts or load `OUT_DIR` values by running `cargo check` before analysis. /// Don't run build scripts or load `OUT_DIR` values by running `cargo check` before analysis.
optional --disable-build-scripts optional --disable-build-scripts
@ -214,7 +211,6 @@ pub struct AnalysisStats {
pub only: Option<String>, pub only: Option<String>,
pub with_deps: bool, pub with_deps: bool,
pub no_sysroot: bool, pub no_sysroot: bool,
pub query_sysroot_metadata: bool,
pub disable_build_scripts: bool, pub disable_build_scripts: bool,
pub disable_proc_macros: bool, pub disable_proc_macros: bool,
pub skip_lowering: bool, pub skip_lowering: bool,

View file

@ -70,7 +70,7 @@ impl Tester {
let cargo_config = let cargo_config =
CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() }; CargoConfig { sysroot: Some(RustLibSource::Discover), ..Default::default() };
let sysroot = Sysroot::discover(tmp_file.parent().unwrap(), &cargo_config.extra_env, false); let sysroot = Sysroot::discover(tmp_file.parent().unwrap(), &cargo_config.extra_env);
let data_layout = target_data_layout::get( let data_layout = target_data_layout::get(
RustcDataLayoutConfig::Rustc(&sysroot), RustcDataLayoutConfig::Rustc(&sysroot),
None, None,

View file

@ -143,13 +143,6 @@ config_data! {
/// ///
/// This option does not take effect until rust-analyzer is restarted. /// This option does not take effect until rust-analyzer is restarted.
cargo_sysroot: Option<String> = Some("discover".to_owned()), cargo_sysroot: Option<String> = Some("discover".to_owned()),
/// Whether to run cargo metadata on the sysroot library allowing rust-analyzer to analyze
/// third-party dependencies of the standard libraries.
///
/// This will cause `cargo` to create a lockfile in your sysroot directory. rust-analyzer
/// will attempt to clean up afterwards, but nevertheless requires the location to be
/// writable to.
cargo_sysrootQueryMetadata: bool = false,
/// Relative path to the sysroot library sources. If left unset, this will default to /// Relative path to the sysroot library sources. If left unset, this will default to
/// `{cargo.sysroot}/lib/rustlib/src/rust/library`. /// `{cargo.sysroot}/lib/rustlib/src/rust/library`.
/// ///
@ -1839,7 +1832,6 @@ impl Config {
}); });
let sysroot_src = let sysroot_src =
self.cargo_sysrootSrc(None).as_ref().map(|sysroot| self.root_path.join(sysroot)); self.cargo_sysrootSrc(None).as_ref().map(|sysroot| self.root_path.join(sysroot));
let sysroot_query_metadata = self.cargo_sysrootQueryMetadata(None);
CargoConfig { CargoConfig {
all_targets: *self.cargo_allTargets(None), all_targets: *self.cargo_allTargets(None),
@ -1852,7 +1844,6 @@ impl Config {
}, },
target: self.cargo_target(None).clone(), target: self.cargo_target(None).clone(),
sysroot, sysroot,
sysroot_query_metadata: *sysroot_query_metadata,
sysroot_src, sysroot_src,
rustc_source, rustc_source,
cfg_overrides: project_model::CfgOverrides { cfg_overrides: project_model::CfgOverrides {

View file

@ -69,7 +69,7 @@ fn get_fake_sysroot() -> Sysroot {
// fake sysroot, so we give them both the same path: // fake sysroot, so we give them both the same path:
let sysroot_dir = AbsPathBuf::assert_utf8(sysroot_path); let sysroot_dir = AbsPathBuf::assert_utf8(sysroot_path);
let sysroot_src_dir = sysroot_dir.clone(); let sysroot_src_dir = sysroot_dir.clone();
Sysroot::load(Some(sysroot_dir), Some(sysroot_src_dir), false) Sysroot::load(Some(sysroot_dir), Some(sysroot_src_dir))
} }
#[test] #[test]

View file

@ -144,16 +144,6 @@ Unsetting this disables sysroot loading.
This option does not take effect until rust-analyzer is restarted. This option does not take effect until rust-analyzer is restarted.
-- --
[[rust-analyzer.cargo.sysrootQueryMetadata]]rust-analyzer.cargo.sysrootQueryMetadata (default: `false`)::
+
--
Whether to run cargo metadata on the sysroot library allowing rust-analyzer to analyze
third-party dependencies of the standard libraries.
This will cause `cargo` to create a lockfile in your sysroot directory. rust-analyzer
will attempt to clean up afterwards, but nevertheless requires the location to be
writable to.
--
[[rust-analyzer.cargo.sysrootSrc]]rust-analyzer.cargo.sysrootSrc (default: `null`):: [[rust-analyzer.cargo.sysrootSrc]]rust-analyzer.cargo.sysrootSrc (default: `null`)::
+ +
-- --

View file

@ -826,16 +826,6 @@
} }
} }
}, },
{
"title": "cargo",
"properties": {
"rust-analyzer.cargo.sysrootQueryMetadata": {
"markdownDescription": "Whether to run cargo metadata on the sysroot library allowing rust-analyzer to analyze\nthird-party dependencies of the standard libraries.\n\nThis will cause `cargo` to create a lockfile in your sysroot directory. rust-analyzer\nwill attempt to clean up afterwards, but nevertheless requires the location to be\nwritable to.",
"default": false,
"type": "boolean"
}
}
},
{ {
"title": "cargo", "title": "cargo",
"properties": { "properties": {