Remove rust-analyzer.cargo.sysrootQueryMetadata config again

This commit is contained in:
Lukas Wirth 2024-12-29 15:24:52 +01:00
parent 4a03036744
commit f1c0d176f3
12 changed files with 159 additions and 252 deletions

View file

@ -15,7 +15,7 @@ use span::Edition;
use toolchain::Tool; use toolchain::Tool;
use crate::{CfgOverrides, InvocationStrategy}; use crate::{CfgOverrides, InvocationStrategy};
use crate::{ManifestPath, Sysroot, SysrootQueryMetadata}; use crate::{ManifestPath, Sysroot};
/// [`CargoWorkspace`] represents the logical structure of, well, a Cargo /// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
/// workspace. It pretty closely mirrors `cargo metadata` output. /// workspace. It pretty closely mirrors `cargo metadata` output.
@ -89,8 +89,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>,
/// How to query metadata for the sysroot crate.
pub sysroot_query_metadata: SysrootQueryMetadata,
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>,

View file

@ -259,13 +259,19 @@ fn parse_cfg(s: &str) -> Result<cfg::CfgAtom, String> {
} }
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub enum SysrootQueryMetadata { pub enum SysrootSourceWorkspaceConfig {
CargoMetadata(CargoMetadataConfig), CargoMetadata(CargoMetadataConfig),
None, Stitched,
} }
impl Default for SysrootQueryMetadata { impl Default for SysrootSourceWorkspaceConfig {
fn default() -> Self { fn default() -> Self {
SysrootQueryMetadata::CargoMetadata(Default::default()) SysrootSourceWorkspaceConfig::default_cargo()
}
}
impl SysrootSourceWorkspaceConfig {
pub fn default_cargo() -> Self {
SysrootSourceWorkspaceConfig::CargoMetadata(Default::default())
} }
} }

View file

@ -4,7 +4,12 @@
//! but we can't process `.rlib` and need source code instead. The source code //! but we can't process `.rlib` and need source code instead. The source code
//! is typically installed with `rustup component add rust-src` command. //! is typically installed with `rustup component add rust-src` command.
use std::{env, fs, ops, path::Path, process::Command}; use std::{
env, fs,
ops::{self, Not},
path::Path,
process::Command,
};
use anyhow::{format_err, Result}; use anyhow::{format_err, Result};
use base_db::CrateName; use base_db::CrateName;
@ -12,23 +17,24 @@ use itertools::Itertools;
use la_arena::{Arena, Idx}; use la_arena::{Arena, Idx};
use paths::{AbsPath, AbsPathBuf, Utf8PathBuf}; use paths::{AbsPath, AbsPathBuf, Utf8PathBuf};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use stdx::format_to;
use toolchain::{probe_for_binary, Tool}; use toolchain::{probe_for_binary, Tool};
use crate::{ use crate::{
cargo_workspace::CargoMetadataConfig, utf8_stdout, CargoWorkspace, ManifestPath, cargo_workspace::CargoMetadataConfig, utf8_stdout, CargoWorkspace, ManifestPath,
SysrootQueryMetadata, SysrootSourceWorkspaceConfig,
}; };
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sysroot { pub struct Sysroot {
root: Option<AbsPathBuf>, root: Option<AbsPathBuf>,
src_root: Option<AbsPathBuf>, src_root: Option<AbsPathBuf>,
mode: SysrootMode, workspace: SysrootWorkspace,
error: Option<String>, error: Option<String>,
} }
#[derive(Debug, Clone, Eq, PartialEq)] #[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) enum SysrootMode { pub(crate) enum SysrootWorkspace {
Workspace(CargoWorkspace), Workspace(CargoWorkspace),
Stitched(Stitched), Stitched(Stitched),
Empty, Empty,
@ -82,7 +88,7 @@ pub(crate) struct SysrootCrateData {
impl Sysroot { impl Sysroot {
pub const fn empty() -> Sysroot { pub const fn empty() -> Sysroot {
Sysroot { root: None, src_root: None, mode: SysrootMode::Empty, error: None } Sysroot { root: None, src_root: None, workspace: SysrootWorkspace::Empty, error: None }
} }
/// Returns sysroot "root" directory, where `bin/`, `etc/`, `lib/`, `libexec/` /// Returns sysroot "root" directory, where `bin/`, `etc/`, `lib/`, `libexec/`
@ -99,10 +105,10 @@ impl Sysroot {
} }
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
match &self.mode { match &self.workspace {
SysrootMode::Workspace(ws) => ws.packages().next().is_none(), SysrootWorkspace::Workspace(ws) => ws.packages().next().is_none(),
SysrootMode::Stitched(stitched) => stitched.crates.is_empty(), SysrootWorkspace::Stitched(stitched) => stitched.crates.is_empty(),
SysrootMode::Empty => true, SysrootWorkspace::Empty => true,
} }
} }
@ -111,64 +117,51 @@ impl Sysroot {
} }
pub fn num_packages(&self) -> usize { pub fn num_packages(&self) -> usize {
match &self.mode { match &self.workspace {
SysrootMode::Workspace(ws) => ws.packages().count(), SysrootWorkspace::Workspace(ws) => ws.packages().count(),
SysrootMode::Stitched(c) => c.crates().count(), SysrootWorkspace::Stitched(c) => c.crates().count(),
SysrootMode::Empty => 0, SysrootWorkspace::Empty => 0,
} }
} }
pub(crate) fn mode(&self) -> &SysrootMode { pub(crate) fn workspace(&self) -> &SysrootWorkspace {
&self.mode &self.workspace
} }
} }
// 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>,
sysroot_query_metadata: &SysrootQueryMetadata,
) -> 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, sysroot_query_metadata) Sysroot::assemble(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,
sysroot_query_metadata: &SysrootQueryMetadata,
) -> 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( Sysroot::assemble(Some(sysroot_dir), Some(Ok(sysroot_src_dir)))
Some(sysroot_dir),
Some(Ok(sysroot_src_dir)),
sysroot_query_metadata,
)
} }
pub fn discover_sysroot_src_dir( pub fn discover_sysroot_src_dir(sysroot_dir: AbsPathBuf) -> Sysroot {
sysroot_dir: AbsPathBuf,
sysroot_query_metadata: &SysrootQueryMetadata,
) -> 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( Sysroot::assemble(Some(Ok(sysroot_dir)), Some(sysroot_src_dir))
Some(Ok(sysroot_dir)),
Some(sysroot_src_dir),
sysroot_query_metadata,
)
} }
pub fn discover_rustc_src(&self) -> Option<ManifestPath> { pub fn discover_rustc_src(&self) -> Option<ManifestPath> {
get_rustc_src(self.root()?) get_rustc_src(self.root()?)
} }
pub fn new(sysroot_dir: Option<AbsPathBuf>, sysroot_src_dir: Option<AbsPathBuf>) -> Sysroot {
Self::assemble(sysroot_dir.map(Ok), sysroot_src_dir.map(Ok))
}
/// Returns a command to run a tool preferring the cargo proxies if the sysroot exists. /// Returns a command to run a tool preferring the cargo proxies if the sysroot exists.
pub fn tool(&self, tool: Tool, current_dir: impl AsRef<Path>) -> Command { pub fn tool(&self, tool: Tool, current_dir: impl AsRef<Path>) -> Command {
match self.root() { match self.root() {
@ -205,93 +198,51 @@ impl Sysroot {
}) })
} }
pub fn load( fn assemble(
sysroot_dir: Option<AbsPathBuf>,
sysroot_src_dir: Option<AbsPathBuf>,
sysroot_query_metadata: &SysrootQueryMetadata,
) -> Sysroot {
Self::load_core_check(sysroot_dir.map(Ok), sysroot_src_dir.map(Ok), sysroot_query_metadata)
}
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>>,
sysroot_query_metadata: &SysrootQueryMetadata,
) -> Sysroot { ) -> Sysroot {
let mut sysroot = Self::load_(sysroot_dir, sysroot_src_dir, sysroot_query_metadata); let mut errors = String::new();
if sysroot.error.is_none() { let root = match sysroot_dir {
if let Some(src_root) = &sysroot.src_root {
let has_core = match &sysroot.mode {
SysrootMode::Workspace(ws) => ws.packages().any(|p| ws[p].name == "core"),
SysrootMode::Stitched(stitched) => stitched.by_name("core").is_some(),
SysrootMode::Empty => true,
};
if !has_core {
let var_note = if env::var_os("RUST_SRC_PATH").is_some() {
" (env var `RUST_SRC_PATH` is set and may be incorrect, try unsetting it)"
} else {
", try running `rustup component add rust-src` to possibly fix this"
};
sysroot.error = Some(format!(
"sysroot at `{src_root}` is missing a `core` library{var_note}",
));
}
}
}
sysroot
}
fn load_(
sysroot_dir: Option<Result<AbsPathBuf, anyhow::Error>>,
sysroot_src_dir: Option<Result<AbsPathBuf, anyhow::Error>>,
sysroot_query_metadata: &SysrootQueryMetadata,
) -> Sysroot {
let sysroot_dir = match sysroot_dir {
Some(Ok(sysroot_dir)) => Some(sysroot_dir), Some(Ok(sysroot_dir)) => Some(sysroot_dir),
Some(Err(e)) => { Some(Err(e)) => {
return Sysroot { format_to!(errors, "{e}\n");
root: None, None
src_root: None,
mode: SysrootMode::Empty,
error: Some(e.to_string()),
}
} }
None => None, None => None,
}; };
let sysroot_src_dir = match sysroot_src_dir { let src_root = match sysroot_src_dir {
Some(Ok(sysroot_src_dir)) => sysroot_src_dir, Some(Ok(sysroot_src_dir)) => Some(sysroot_src_dir),
Some(Err(e)) => { Some(Err(e)) => {
return Sysroot { format_to!(errors, "{e}\n");
root: sysroot_dir, None
src_root: None,
mode: SysrootMode::Empty,
error: Some(e.to_string()),
}
}
None => {
return Sysroot {
root: sysroot_dir,
src_root: None,
mode: SysrootMode::Empty,
error: None,
}
} }
None => None,
}; };
if let SysrootQueryMetadata::CargoMetadata(cargo_config) = sysroot_query_metadata { Sysroot {
let library_manifest = root,
ManifestPath::try_from(sysroot_src_dir.join("Cargo.toml")).unwrap(); src_root,
workspace: SysrootWorkspace::Empty,
error: errors.is_empty().not().then_some(errors),
}
}
pub fn load_workspace(&mut self, sysroot_source_config: &SysrootSourceWorkspaceConfig) {
assert!(matches!(self.workspace, SysrootWorkspace::Empty), "workspace already loaded");
let Self { root: _, src_root: Some(src_root), workspace, error: _ } = self else { return };
if let SysrootSourceWorkspaceConfig::CargoMetadata(cargo_config) = sysroot_source_config {
let library_manifest = ManifestPath::try_from(src_root.join("Cargo.toml")).unwrap();
if fs::metadata(&library_manifest).is_ok() { if fs::metadata(&library_manifest).is_ok() {
if let Some(sysroot) = Self::load_library_via_cargo( if let Some(loaded) =
library_manifest, Self::load_library_via_cargo(library_manifest, src_root, cargo_config)
&sysroot_dir, {
&sysroot_src_dir, *workspace = loaded;
cargo_config, self.load_core_check();
) { return;
return sysroot;
} }
} }
} }
tracing::debug!("Stitching sysroot library: {sysroot_src_dir}"); tracing::debug!("Stitching sysroot library: {src_root}");
let mut stitched = Stitched { crates: Arena::default() }; let mut stitched = Stitched { crates: Arena::default() };
@ -299,7 +250,7 @@ impl Sysroot {
let name = path.split('/').last().unwrap(); let name = path.split('/').last().unwrap();
let root = [format!("{path}/src/lib.rs"), format!("lib{path}/lib.rs")] let root = [format!("{path}/src/lib.rs"), format!("lib{path}/lib.rs")]
.into_iter() .into_iter()
.map(|it| sysroot_src_dir.join(it)) .map(|it| src_root.join(it))
.filter_map(|it| ManifestPath::try_from(it).ok()) .filter_map(|it| ManifestPath::try_from(it).ok())
.find(|it| fs::metadata(it).is_ok()); .find(|it| fs::metadata(it).is_ok());
@ -335,20 +286,37 @@ impl Sysroot {
} }
} }
} }
Sysroot { *workspace = SysrootWorkspace::Stitched(stitched);
root: sysroot_dir, self.load_core_check();
src_root: Some(sysroot_src_dir), }
mode: SysrootMode::Stitched(stitched),
error: None, fn load_core_check(&mut self) {
if self.error.is_none() {
if let Some(src_root) = &self.src_root {
let has_core = match &self.workspace {
SysrootWorkspace::Workspace(ws) => ws.packages().any(|p| ws[p].name == "core"),
SysrootWorkspace::Stitched(stitched) => stitched.by_name("core").is_some(),
SysrootWorkspace::Empty => true,
};
if !has_core {
let var_note = if env::var_os("RUST_SRC_PATH").is_some() {
" (env var `RUST_SRC_PATH` is set and may be incorrect, try unsetting it)"
} else {
", try running `rustup component add rust-src` to possibly fix this"
};
self.error = Some(format!(
"sysroot at `{src_root}` is missing a `core` library{var_note}",
));
}
}
} }
} }
fn load_library_via_cargo( fn load_library_via_cargo(
library_manifest: ManifestPath, library_manifest: ManifestPath,
sysroot_dir: &Option<AbsPathBuf>,
sysroot_src_dir: &AbsPathBuf, sysroot_src_dir: &AbsPathBuf,
cargo_config: &CargoMetadataConfig, cargo_config: &CargoMetadataConfig,
) -> Option<Sysroot> { ) -> Option<SysrootWorkspace> {
tracing::debug!("Loading library metadata: {library_manifest}"); tracing::debug!("Loading library metadata: {library_manifest}");
let mut cargo_config = cargo_config.clone(); let mut cargo_config = cargo_config.clone();
// the sysroot uses `public-dependency`, so we make cargo think it's a nightly // the sysroot uses `public-dependency`, so we make cargo think it's a nightly
@ -423,12 +391,7 @@ impl Sysroot {
}); });
let cargo_workspace = CargoWorkspace::new(res, library_manifest, Default::default()); let cargo_workspace = CargoWorkspace::new(res, library_manifest, Default::default());
Some(Sysroot { Some(SysrootWorkspace::Workspace(cargo_workspace))
root: sysroot_dir.clone(),
src_root: Some(sysroot_src_dir.clone()),
mode: SysrootMode::Workspace(cargo_workspace),
error: None,
})
} }
} }

View file

@ -12,9 +12,9 @@ use span::FileId;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
sysroot::SysrootMode, workspace::ProjectWorkspaceKind, CargoWorkspace, CfgOverrides, sysroot::SysrootWorkspace, workspace::ProjectWorkspaceKind, CargoWorkspace, CfgOverrides,
ManifestPath, ProjectJson, ProjectJsonData, ProjectWorkspace, Sysroot, SysrootQueryMetadata, ManifestPath, ProjectJson, ProjectJsonData, ProjectWorkspace, Sysroot,
WorkspaceBuildScripts, SysrootSourceWorkspaceConfig, WorkspaceBuildScripts,
}; };
fn load_cargo(file: &str) -> (CrateGraph, ProcMacroPaths) { fn load_cargo(file: &str) -> (CrateGraph, ProcMacroPaths) {
@ -122,7 +122,9 @@ 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), &SysrootQueryMetadata::default()) let mut sysroot = Sysroot::new(Some(sysroot_dir), Some(sysroot_src_dir));
sysroot.load_workspace(&SysrootSourceWorkspaceConfig::default_cargo());
sysroot
} }
fn rooted_project_json(data: ProjectJsonData) -> ProjectJson { fn rooted_project_json(data: ProjectJsonData) -> ProjectJson {
@ -263,12 +265,12 @@ fn smoke_test_real_sysroot_cargo() {
let manifest_path = let manifest_path =
ManifestPath::try_from(AbsPathBuf::try_from(meta.workspace_root.clone()).unwrap()).unwrap(); ManifestPath::try_from(AbsPathBuf::try_from(meta.workspace_root.clone()).unwrap()).unwrap();
let cargo_workspace = CargoWorkspace::new(meta, manifest_path, Default::default()); let cargo_workspace = CargoWorkspace::new(meta, manifest_path, Default::default());
let sysroot = Sysroot::discover( let mut sysroot = Sysroot::discover(
AbsPath::assert(Utf8Path::new(env!("CARGO_MANIFEST_DIR"))), AbsPath::assert(Utf8Path::new(env!("CARGO_MANIFEST_DIR"))),
&Default::default(), &Default::default(),
&SysrootQueryMetadata::default(),
); );
assert!(matches!(sysroot.mode(), SysrootMode::Workspace(_))); sysroot.load_workspace(&SysrootSourceWorkspaceConfig::default_cargo());
assert!(matches!(sysroot.workspace(), SysrootWorkspace::Workspace(_)));
let project_workspace = ProjectWorkspace { let project_workspace = ProjectWorkspace {
kind: ProjectWorkspaceKind::Cargo { kind: ProjectWorkspaceKind::Cargo {
cargo: cargo_workspace, cargo: cargo_workspace,

View file

@ -25,10 +25,11 @@ use crate::{
cargo_workspace::{CargoMetadataConfig, DepKind, PackageData, RustLibSource}, cargo_workspace::{CargoMetadataConfig, DepKind, PackageData, RustLibSource},
env::{cargo_config_env, inject_cargo_env, inject_cargo_package_env, inject_rustc_tool_env}, env::{cargo_config_env, inject_cargo_env, inject_cargo_package_env, inject_rustc_tool_env},
project_json::{Crate, CrateArrayIdx}, project_json::{Crate, CrateArrayIdx},
sysroot::{SysrootCrate, SysrootMode}, sysroot::{SysrootCrate, SysrootWorkspace},
toolchain_info::{rustc_cfg, target_data_layout, target_triple, QueryConfig}, toolchain_info::{rustc_cfg, target_data_layout, target_triple, QueryConfig},
utf8_stdout, CargoConfig, CargoWorkspace, CfgOverrides, InvocationStrategy, ManifestPath, utf8_stdout, CargoConfig, CargoWorkspace, CfgOverrides, InvocationStrategy, ManifestPath,
Package, ProjectJson, ProjectManifest, Sysroot, TargetData, TargetKind, WorkspaceBuildScripts, Package, ProjectJson, ProjectManifest, Sysroot, SysrootSourceWorkspaceConfig, TargetData,
TargetKind, WorkspaceBuildScripts,
}; };
use tracing::{debug, error, info}; use tracing::{debug, error, info};
@ -213,34 +214,26 @@ impl ProjectWorkspace {
config: &CargoConfig, config: &CargoConfig,
progress: &dyn Fn(String), progress: &dyn Fn(String),
) -> Result<ProjectWorkspace, anyhow::Error> { ) -> Result<ProjectWorkspace, anyhow::Error> {
// FIXME: Split sysroot discovery from sysroot loading, as to load the sysroot we let mut sysroot = match (&config.sysroot, &config.sysroot_src) {
// want to pass the analysis target, but to discover the target we need to know the (Some(RustLibSource::Discover), None) => {
// sysroot location so we know which cargo to use Sysroot::discover(cargo_toml.parent(), &config.extra_env)
let sysroot = match (&config.sysroot, &config.sysroot_src) { }
(Some(RustLibSource::Discover), None) => Sysroot::discover(
cargo_toml.parent(),
&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) => { (Some(RustLibSource::Path(path)), None) => {
Sysroot::discover_sysroot_src_dir(path.clone(), &config.sysroot_query_metadata) Sysroot::discover_sysroot_src_dir(path.clone())
}
(Some(RustLibSource::Path(sysroot)), Some(sysroot_src)) => {
Sysroot::new(Some(sysroot.clone()), Some(sysroot_src.clone()))
} }
(Some(RustLibSource::Path(sysroot)), Some(sysroot_src)) => Sysroot::load(
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");
let rustc_dir = match &config.rustc_source { let rustc_dir = match &config.rustc_source {
Some(RustLibSource::Path(path)) => ManifestPath::try_from(path.clone()) Some(RustLibSource::Path(path)) => ManifestPath::try_from(path.clone())
.map_err(|p| Some(format!("rustc source path is not absolute: {p}"))), .map_err(|p| Some(format!("rustc source path is not absolute: {p}"))),
@ -255,6 +248,10 @@ impl ProjectWorkspace {
&config.extra_env, &config.extra_env,
) )
.unwrap_or_default(); .unwrap_or_default();
sysroot.load_workspace(&SysrootSourceWorkspaceConfig::CargoMetadata(
sysroot_metadata_config(&config.extra_env, &targets),
));
tracing::info!(workspace = %cargo_toml, src_root = ?sysroot.src_root(), root = ?sysroot.root(), "Using sysroot");
let rustc = rustc_dir.and_then(|rustc_dir| { let rustc = rustc_dir.and_then(|rustc_dir| {
info!(workspace = %cargo_toml, rustc_dir = %rustc_dir, "Using rustc source"); info!(workspace = %cargo_toml, rustc_dir = %rustc_dir, "Using rustc source");
match CargoWorkspace::fetch_metadata( match CargoWorkspace::fetch_metadata(
@ -349,11 +346,9 @@ impl ProjectWorkspace {
} }
pub fn load_inline(project_json: ProjectJson, config: &CargoConfig) -> ProjectWorkspace { pub fn load_inline(project_json: ProjectJson, config: &CargoConfig) -> ProjectWorkspace {
let sysroot = Sysroot::load( let mut sysroot =
project_json.sysroot.clone(), Sysroot::new(project_json.sysroot.clone(), project_json.sysroot_src.clone());
project_json.sysroot_src.clone(), sysroot.load_workspace(&SysrootSourceWorkspaceConfig::Stitched);
&config.sysroot_query_metadata,
);
let query_config = QueryConfig::Rustc(&sysroot, project_json.path().as_ref()); let query_config = QueryConfig::Rustc(&sysroot, project_json.path().as_ref());
let toolchain = match get_toolchain_version( let toolchain = match get_toolchain_version(
project_json.path(), project_json.path(),
@ -387,13 +382,9 @@ impl ProjectWorkspace {
config: &CargoConfig, config: &CargoConfig,
) -> anyhow::Result<ProjectWorkspace> { ) -> anyhow::Result<ProjectWorkspace> {
let dir = detached_file.parent(); let dir = detached_file.parent();
let sysroot = match &config.sysroot { let mut 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,6 +403,10 @@ impl ProjectWorkspace {
&config.extra_env, &config.extra_env,
) )
.unwrap_or_default(); .unwrap_or_default();
sysroot.load_workspace(&SysrootSourceWorkspaceConfig::CargoMetadata(
sysroot_metadata_config(&config.extra_env, &targets),
));
let query_config = QueryConfig::Rustc(&sysroot, dir.as_ref()); let query_config = QueryConfig::Rustc(&sysroot, dir.as_ref());
let rustc_cfg = rustc_cfg::get(query_config, None, &config.extra_env); let rustc_cfg = rustc_cfg::get(query_config, None, &config.extra_env);
let data_layout = target_data_layout::get(query_config, None, &config.extra_env); let data_layout = target_data_layout::get(query_config, None, &config.extra_env);
@ -570,8 +565,8 @@ impl ProjectWorkspace {
/// the root is a member of the current workspace /// the root is a member of the current workspace
pub fn to_roots(&self) -> Vec<PackageRoot> { pub fn to_roots(&self) -> Vec<PackageRoot> {
let mk_sysroot = || { let mk_sysroot = || {
let mut r = match self.sysroot.mode() { let mut r = match self.sysroot.workspace() {
SysrootMode::Workspace(ws) => ws SysrootWorkspace::Workspace(ws) => ws
.packages() .packages()
.filter_map(|pkg| { .filter_map(|pkg| {
if ws[pkg].is_local { if ws[pkg].is_local {
@ -592,7 +587,7 @@ impl ProjectWorkspace {
Some(PackageRoot { is_local: false, include, exclude }) Some(PackageRoot { is_local: false, include, exclude })
}) })
.collect(), .collect(),
SysrootMode::Stitched(_) | SysrootMode::Empty => vec![], SysrootWorkspace::Stitched(_) | SysrootWorkspace::Empty => vec![],
}; };
r.push(PackageRoot { r.push(PackageRoot {
@ -1416,8 +1411,8 @@ fn sysroot_to_crate_graph(
load: FileLoader<'_>, load: FileLoader<'_>,
) -> (SysrootPublicDeps, Option<CrateId>) { ) -> (SysrootPublicDeps, Option<CrateId>) {
let _p = tracing::info_span!("sysroot_to_crate_graph").entered(); let _p = tracing::info_span!("sysroot_to_crate_graph").entered();
match sysroot.mode() { match sysroot.workspace() {
SysrootMode::Workspace(cargo) => { SysrootWorkspace::Workspace(cargo) => {
let (mut cg, mut pm) = cargo_to_crate_graph( let (mut cg, mut pm) = cargo_to_crate_graph(
load, load,
None, None,
@ -1492,7 +1487,7 @@ fn sysroot_to_crate_graph(
(SysrootPublicDeps { deps: pub_deps }, libproc_macro) (SysrootPublicDeps { deps: pub_deps }, libproc_macro)
} }
SysrootMode::Stitched(stitched) => { SysrootWorkspace::Stitched(stitched) => {
let cfg_options = Arc::new({ let cfg_options = Arc::new({
let mut cfg_options = CfgOptions::default(); let mut cfg_options = CfgOptions::default();
cfg_options.extend(rustc_cfg); cfg_options.extend(rustc_cfg);
@ -1545,7 +1540,7 @@ fn sysroot_to_crate_graph(
stitched.proc_macro().and_then(|it| sysroot_crates.get(&it).copied()); stitched.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
(public_deps, libproc_macro) (public_deps, libproc_macro)
} }
SysrootMode::Empty => (SysrootPublicDeps { deps: vec![] }, None), SysrootWorkspace::Empty => (SysrootPublicDeps { deps: vec![] }, None),
} }
} }
@ -1580,3 +1575,15 @@ fn add_dep_inner(graph: &mut CrateGraph, from: CrateId, dep: Dependency) {
tracing::warn!("{}", err) tracing::warn!("{}", err)
} }
} }
fn sysroot_metadata_config(
extra_env: &FxHashMap<String, String>,
targets: &[String],
) -> CargoMetadataConfig {
CargoMetadataConfig {
features: Default::default(),
targets: targets.to_vec(),
extra_args: Default::default(),
extra_env: extra_env.clone(),
}
}

View file

@ -33,10 +33,7 @@ use itertools::Itertools;
use load_cargo::{load_workspace, LoadCargoConfig, ProcMacroServerChoice}; use load_cargo::{load_workspace, LoadCargoConfig, ProcMacroServerChoice};
use oorandom::Rand32; use oorandom::Rand32;
use profile::{Bytes, StopWatch}; use profile::{Bytes, StopWatch};
use project_model::{ use project_model::{CargoConfig, CfgOverrides, ProjectManifest, ProjectWorkspace, RustLibSource};
CargoConfig, CargoMetadataConfig, CfgOverrides, ProjectManifest, ProjectWorkspace,
RustLibSource,
};
use rayon::prelude::*; use rayon::prelude::*;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use syntax::{AstNode, SyntaxNode}; use syntax::{AstNode, SyntaxNode};
@ -69,12 +66,6 @@ impl flags::AnalysisStats {
true => None, true => None,
false => Some(RustLibSource::Discover), false => Some(RustLibSource::Discover),
}, },
sysroot_query_metadata: match self.no_query_sysroot_metadata {
true => project_model::SysrootQueryMetadata::None,
false => project_model::SysrootQueryMetadata::CargoMetadata(
CargoMetadataConfig::default(),
),
},
all_targets: true, all_targets: true,
set_test: !self.no_test, set_test: !self.no_test,
cfg_overrides: CfgOverrides { cfg_overrides: CfgOverrides {

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
/// Don't run cargo metadata on the sysroot to analyze its third-party dependencies.
/// Requires --no-sysroot to not be set.
optional --no-query-sysroot-metadata
/// Don't set #[cfg(test)]. /// Don't set #[cfg(test)].
optional --no-test optional --no-test
@ -238,7 +235,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 no_query_sysroot_metadata: bool,
pub no_test: bool, pub no_test: bool,
pub disable_build_scripts: bool, pub disable_build_scripts: bool,
pub disable_proc_macros: bool, pub disable_proc_macros: bool,

View file

@ -13,7 +13,7 @@ use profile::StopWatch;
use project_model::toolchain_info::{target_data_layout, QueryConfig}; use project_model::toolchain_info::{target_data_layout, QueryConfig};
use project_model::{ use project_model::{
CargoConfig, ManifestPath, ProjectWorkspace, ProjectWorkspaceKind, RustLibSource, Sysroot, CargoConfig, ManifestPath, ProjectWorkspace, ProjectWorkspaceKind, RustLibSource, Sysroot,
SysrootQueryMetadata, SysrootSourceWorkspaceConfig,
}; };
use load_cargo::{load_workspace, LoadCargoConfig, ProcMacroServerChoice}; use load_cargo::{load_workspace, LoadCargoConfig, ProcMacroServerChoice};
@ -74,11 +74,8 @@ impl Tester {
..Default::default() ..Default::default()
}; };
let sysroot = Sysroot::discover( let mut sysroot = Sysroot::discover(tmp_file.parent().unwrap(), &cargo_config.extra_env);
tmp_file.parent().unwrap(), sysroot.load_workspace(&SysrootSourceWorkspaceConfig::default_cargo());
&cargo_config.extra_env,
&SysrootQueryMetadata::CargoMetadata(Default::default()),
);
let data_layout = target_data_layout::get( let data_layout = target_data_layout::get(
QueryConfig::Rustc(&sysroot, tmp_file.parent().unwrap().as_ref()), QueryConfig::Rustc(&sysroot, tmp_file.parent().unwrap().as_ref()),
None, None,

View file

@ -21,8 +21,8 @@ use ide_db::{
use itertools::Itertools; use itertools::Itertools;
use paths::{Utf8Path, Utf8PathBuf}; use paths::{Utf8Path, Utf8PathBuf};
use project_model::{ use project_model::{
CargoConfig, CargoFeatures, CargoMetadataConfig, ProjectJson, ProjectJsonData, CargoConfig, CargoFeatures, ProjectJson, ProjectJsonData, ProjectJsonFromCommand,
ProjectJsonFromCommand, ProjectManifest, RustLibSource, ProjectManifest, RustLibSource,
}; };
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use semver::Version; use semver::Version;
@ -595,9 +595,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()),
/// How to query metadata for the sysroot crate. Using cargo metadata allows rust-analyzer
/// to analyze third-party dependencies of the standard libraries.
cargo_sysrootQueryMetadata: SysrootQueryMetadata = SysrootQueryMetadata::CargoMetadata,
/// 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`.
/// ///
@ -1941,17 +1938,6 @@ impl Config {
}, },
target: self.cargo_target(source_root).clone(), target: self.cargo_target(source_root).clone(),
sysroot, sysroot,
sysroot_query_metadata: match self.cargo_sysrootQueryMetadata(None) {
SysrootQueryMetadata::CargoMetadata => {
project_model::SysrootQueryMetadata::CargoMetadata(CargoMetadataConfig {
features: Default::default(),
targets: self.cargo_target(source_root).clone().into_iter().collect(),
extra_args: Default::default(),
extra_env: Default::default(),
})
}
SysrootQueryMetadata::None => project_model::SysrootQueryMetadata::None,
},
sysroot_src, sysroot_src,
rustc_source, rustc_source,
cfg_overrides: project_model::CfgOverrides { cfg_overrides: project_model::CfgOverrides {
@ -2674,13 +2660,6 @@ pub enum NumThreads {
Concrete(usize), Concrete(usize),
} }
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SysrootQueryMetadata {
CargoMetadata,
None,
}
macro_rules! _default_val { macro_rules! _default_val {
(@verbatim: $s:literal, $ty:ty) => {{ (@verbatim: $s:literal, $ty:ty) => {{
let default_: $ty = serde_json::from_str(&$s).unwrap(); let default_: $ty = serde_json::from_str(&$s).unwrap();
@ -3532,14 +3511,6 @@ fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json
} }
] ]
}, },
"SysrootQueryMetadata" => set! {
"type": "string",
"enum": ["none", "cargo_metadata"],
"enumDescriptions": [
"Do not query sysroot metadata, always use stitched sysroot.",
"Use `cargo metadata` to query sysroot metadata."
],
},
"Option<MaxSubstitutionLength>" => set! { "Option<MaxSubstitutionLength>" => set! {
"anyOf": [ "anyOf": [
{ {

View file

@ -1082,11 +1082,11 @@ fn resolve_proc_macro() {
return; return;
} }
let sysroot = project_model::Sysroot::discover( let mut sysroot = project_model::Sysroot::discover(
&AbsPathBuf::assert_utf8(std::env::current_dir().unwrap()), &AbsPathBuf::assert_utf8(std::env::current_dir().unwrap()),
&Default::default(), &Default::default(),
&project_model::SysrootQueryMetadata::default(),
); );
sysroot.load_workspace(&project_model::SysrootSourceWorkspaceConfig::default_cargo());
let proc_macro_server_path = sysroot.discover_proc_macro_srv().unwrap(); let proc_macro_server_path = sysroot.discover_proc_macro_srv().unwrap();

View file

@ -135,12 +135,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: `"cargo_metadata"`)::
+
--
How to query metadata for the sysroot crate. Using cargo metadata allows rust-analyzer
to analyze third-party dependencies of the standard libraries.
--
[[rust-analyzer.cargo.sysrootSrc]]rust-analyzer.cargo.sysrootSrc (default: `null`):: [[rust-analyzer.cargo.sysrootSrc]]rust-analyzer.cargo.sysrootSrc (default: `null`)::
+ +
-- --

View file

@ -871,24 +871,6 @@
} }
} }
}, },
{
"title": "cargo",
"properties": {
"rust-analyzer.cargo.sysrootQueryMetadata": {
"markdownDescription": "How to query metadata for the sysroot crate. Using cargo metadata allows rust-analyzer\nto analyze third-party dependencies of the standard libraries.",
"default": "cargo_metadata",
"type": "string",
"enum": [
"none",
"cargo_metadata"
],
"enumDescriptions": [
"Do not query sysroot metadata, always use stitched sysroot.",
"Use `cargo metadata` to query sysroot metadata."
]
}
}
},
{ {
"title": "cargo", "title": "cargo",
"properties": { "properties": {