Repository: rust-lang/rust-analyzer
Pull request #18788 (2024-12-29 14:25:17)

Remove `rust-analyzer.cargo.sysrootQueryMetadata` config again
Closes https://github.com/rust-lang/rust-analyzer/issues/18590

Veykril: Ideally the rust-project.json will actually list the sysroot workspace (that is, it provides a stitched one), so that will need some adjustments to the json format.
Veykril: A thought for a follow up to this PR, we should be able to cache the fetched sysroot and re-use it between multiple workspaces.

Patch:
diff --git a/crates/ide-completion/src/context/analysis.rs b/crates/ide-completion/src/context/analysis.rs
index acce62a041..1979755ee5 100644
--- a/crates/ide-completion/src/context/analysis.rs
+++ b/crates/ide-completion/src/context/analysis.rs
@@ -417,15 +417,6 @@ fn analyze(
         derive_ctx,
     } = expansion_result;
 
-    if original_token.kind() != self_token.kind()
-        // FIXME: This check can be removed once we use speculative database forking for completions
-        && !(original_token.kind().is_punct() || original_token.kind().is_trivia())
-        && !(SyntaxKind::is_any_identifier(original_token.kind())
-            && SyntaxKind::is_any_identifier(self_token.kind()))
-    {
-        return None;
-    }
-
     // Overwrite the path kind for derives
     if let Some((original_file, file_with_fake_ident, offset, origin_attr)) = derive_ctx {
         if let Some(ast::NameLike::NameRef(name_ref)) =
diff --git a/crates/project-model/src/cargo_workspace.rs b/crates/project-model/src/cargo_workspace.rs
index c125c141cd..4d906c2aeb 100644
--- a/crates/project-model/src/cargo_workspace.rs
+++ b/crates/project-model/src/cargo_workspace.rs
@@ -15,7 +15,7 @@ use span::Edition;
 use toolchain::Tool;
 
 use crate::{CfgOverrides, InvocationStrategy};
-use crate::{ManifestPath, Sysroot, SysrootQueryMetadata};
+use crate::{ManifestPath, Sysroot};
 
 /// [`CargoWorkspace`] represents the logical structure of, well, a Cargo
 /// workspace. It pretty closely mirrors `cargo metadata` output.
@@ -89,8 +89,6 @@ pub struct CargoConfig {
     pub target: Option<String>,
     /// Sysroot loading behavior
     pub sysroot: Option<RustLibSource>,
-    /// How to query metadata for the sysroot crate.
-    pub sysroot_query_metadata: SysrootQueryMetadata,
     pub sysroot_src: Option<AbsPathBuf>,
     /// rustc private crate source
     pub rustc_source: Option<RustLibSource>,
diff --git a/crates/project-model/src/lib.rs b/crates/project-model/src/lib.rs
index 1913db11fa..f540543825 100644
--- a/crates/project-model/src/lib.rs
+++ b/crates/project-model/src/lib.rs
@@ -259,13 +259,19 @@ fn parse_cfg(s: &str) -> Result<cfg::CfgAtom, String> {
 }
 
 #[derive(Clone, Debug, PartialEq, Eq)]
-pub enum SysrootQueryMetadata {
+pub enum SysrootSourceWorkspaceConfig {
     CargoMetadata(CargoMetadataConfig),
-    None,
+    Stitched,
 }
 
-impl Default for SysrootQueryMetadata {
+impl Default for SysrootSourceWorkspaceConfig {
     fn default() -> Self {
-        SysrootQueryMetadata::CargoMetadata(Default::default())
+        SysrootSourceWorkspaceConfig::default_cargo()
+    }
+}
+
+impl SysrootSourceWorkspaceConfig {
+    pub fn default_cargo() -> Self {
+        SysrootSourceWorkspaceConfig::CargoMetadata(Default::default())
     }
 }
diff --git a/crates/project-model/src/sysroot.rs b/crates/project-model/src/sysroot.rs
index 9d3dc37c58..8f633d24be 100644
--- a/crates/project-model/src/sysroot.rs
+++ b/crates/project-model/src/sysroot.rs
@@ -4,7 +4,12 @@
 //! 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, path::Path, process::Command};
+use std::{
+    env, fs,
+    ops::{self, Not},
+    path::Path,
+    process::Command,
+};
 
 use anyhow::{format_err, Result};
 use base_db::CrateName;
@@ -12,23 +17,24 @@ use itertools::Itertools;
 use la_arena::{Arena, Idx};
 use paths::{AbsPath, AbsPathBuf, Utf8PathBuf};
 use rustc_hash::FxHashMap;
+use stdx::format_to;
 use toolchain::{probe_for_binary, Tool};
 
 use crate::{
     cargo_workspace::CargoMetadataConfig, utf8_stdout, CargoWorkspace, ManifestPath,
-    SysrootQueryMetadata,
+    SysrootSourceWorkspaceConfig,
 };
 
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub struct Sysroot {
     root: Option<AbsPathBuf>,
     src_root: Option<AbsPathBuf>,
-    mode: SysrootMode,
+    workspace: SysrootWorkspace,
     error: Option<String>,
 }
 
 #[derive(Debug, Clone, Eq, PartialEq)]
-pub(crate) enum SysrootMode {
+pub(crate) enum SysrootWorkspace {
     Workspace(CargoWorkspace),
     Stitched(Stitched),
     Empty,
@@ -82,7 +88,7 @@ pub(crate) struct SysrootCrateData {
 
 impl 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/`
@@ -99,10 +105,10 @@ impl Sysroot {
     }
 
     pub fn is_empty(&self) -> bool {
-        match &self.mode {
-            SysrootMode::Workspace(ws) => ws.packages().next().is_none(),
-            SysrootMode::Stitched(stitched) => stitched.crates.is_empty(),
-            SysrootMode::Empty => true,
+        match &self.workspace {
+            SysrootWorkspace::Workspace(ws) => ws.packages().next().is_none(),
+            SysrootWorkspace::Stitched(stitched) => stitched.crates.is_empty(),
+            SysrootWorkspace::Empty => true,
         }
     }
 
@@ -111,64 +117,51 @@ impl Sysroot {
     }
 
     pub fn num_packages(&self) -> usize {
-        match &self.mode {
-            SysrootMode::Workspace(ws) => ws.packages().count(),
-            SysrootMode::Stitched(c) => c.crates().count(),
-            SysrootMode::Empty => 0,
+        match &self.workspace {
+            SysrootWorkspace::Workspace(ws) => ws.packages().count(),
+            SysrootWorkspace::Stitched(c) => c.crates().count(),
+            SysrootWorkspace::Empty => 0,
         }
     }
 
-    pub(crate) fn mode(&self) -> &SysrootMode {
-        &self.mode
+    pub(crate) fn workspace(&self) -> &SysrootWorkspace {
+        &self.workspace
     }
 }
 
-// FIXME: Expose a builder api as loading the sysroot got way too modular and complicated.
 impl Sysroot {
     /// Attempts to discover the toolchain's sysroot from the given `dir`.
-    pub fn discover(
-        dir: &AbsPath,
-        extra_env: &FxHashMap<String, String>,
-        sysroot_query_metadata: &SysrootQueryMetadata,
-    ) -> Sysroot {
+    pub fn discover(dir: &AbsPath, extra_env: &FxHashMap<String, String>) -> Sysroot {
         let sysroot_dir = discover_sysroot_dir(dir, extra_env);
         let sysroot_src_dir = sysroot_dir.as_ref().ok().map(|sysroot_dir| {
             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(
         current_dir: &AbsPath,
         extra_env: &FxHashMap<String, String>,
         sysroot_src_dir: AbsPathBuf,
-        sysroot_query_metadata: &SysrootQueryMetadata,
     ) -> Sysroot {
         let sysroot_dir = discover_sysroot_dir(current_dir, extra_env);
-        Sysroot::load_core_check(
-            Some(sysroot_dir),
-            Some(Ok(sysroot_src_dir)),
-            sysroot_query_metadata,
-        )
+        Sysroot::assemble(Some(sysroot_dir), Some(Ok(sysroot_src_dir)))
     }
 
-    pub fn discover_sysroot_src_dir(
-        sysroot_dir: AbsPathBuf,
-        sysroot_query_metadata: &SysrootQueryMetadata,
-    ) -> Sysroot {
+    pub fn discover_sysroot_src_dir(sysroot_dir: AbsPathBuf) -> Sysroot {
         let sysroot_src_dir = discover_sysroot_src_dir(&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),
-            sysroot_query_metadata,
-        )
+        Sysroot::assemble(Some(Ok(sysroot_dir)), Some(sysroot_src_dir))
     }
 
     pub fn discover_rustc_src(&self) -> Option<ManifestPath> {
         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.
     pub fn tool(&self, tool: Tool, current_dir: impl AsRef<Path>) -> Command {
         match self.root() {
@@ -205,93 +198,51 @@ impl Sysroot {
             })
     }
 
-    pub fn load(
-        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_src_dir: Option<Result<AbsPathBuf, anyhow::Error>>,
-        sysroot_query_metadata: &SysrootQueryMetadata,
-    ) -> Sysroot {
-        let mut sysroot = Self::load_(sysroot_dir, sysroot_src_dir, sysroot_query_metadata);
-        if sysroot.error.is_none() {
-            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_(
+    fn assemble(
         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 {
+        let mut errors = String::new();
+        let root = match sysroot_dir {
             Some(Ok(sysroot_dir)) => Some(sysroot_dir),
             Some(Err(e)) => {
-                return Sysroot {
-                    root: None,
-                    src_root: None,
-                    mode: SysrootMode::Empty,
-                    error: Some(e.to_string()),
-                }
+                format_to!(errors, "{e}\n");
+                None
             }
             None => None,
         };
-        let sysroot_src_dir = match sysroot_src_dir {
-            Some(Ok(sysroot_src_dir)) => sysroot_src_dir,
+        let src_root = match sysroot_src_dir {
+            Some(Ok(sysroot_src_dir)) => Some(sysroot_src_dir),
             Some(Err(e)) => {
-                return Sysroot {
-                    root: sysroot_dir,
-                    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,
-                }
+                format_to!(errors, "{e}\n");
+                None
             }
+            None => None,
         };
-        if let SysrootQueryMetadata::CargoMetadata(cargo_config) = sysroot_query_metadata {
-            let library_manifest =
-                ManifestPath::try_from(sysroot_src_dir.join("Cargo.toml")).unwrap();
+        Sysroot {
+            root,
+            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 let Some(sysroot) = Self::load_library_via_cargo(
-                    library_manifest,
-                    &sysroot_dir,
-                    &sysroot_src_dir,
-                    cargo_config,
-                ) {
-                    return sysroot;
+                if let Some(loaded) =
+                    Self::load_library_via_cargo(library_manifest, src_root, cargo_config)
+                {
+                    *workspace = loaded;
+                    self.load_core_check();
+                    return;
                 }
             }
         }
-        tracing::debug!("Stitching sysroot library: {sysroot_src_dir}");
+        tracing::debug!("Stitching sysroot library: {src_root}");
 
         let mut stitched = Stitched { crates: Arena::default() };
 
@@ -299,7 +250,7 @@ impl Sysroot {
             let name = path.split('/').last().unwrap();
             let root = [format!("{path}/src/lib.rs"), format!("lib{path}/lib.rs")]
                 .into_iter()
-                .map(|it| sysroot_src_dir.join(it))
+                .map(|it| src_root.join(it))
                 .filter_map(|it| ManifestPath::try_from(it).ok())
                 .find(|it| fs::metadata(it).is_ok());
 
@@ -335,20 +286,37 @@ impl Sysroot {
                 }
             }
         }
-        Sysroot {
-            root: sysroot_dir,
-            src_root: Some(sysroot_src_dir),
-            mode: SysrootMode::Stitched(stitched),
-            error: None,
+        *workspace = SysrootWorkspace::Stitched(stitched);
+        self.load_core_check();
+    }
+
+    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(
         library_manifest: ManifestPath,
-        sysroot_dir: &Option<AbsPathBuf>,
         sysroot_src_dir: &AbsPathBuf,
         cargo_config: &CargoMetadataConfig,
-    ) -> Option<Sysroot> {
+    ) -> Option<SysrootWorkspace> {
         tracing::debug!("Loading library metadata: {library_manifest}");
         let mut cargo_config = cargo_config.clone();
         // 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());
-        Some(Sysroot {
-            root: sysroot_dir.clone(),
-            src_root: Some(sysroot_src_dir.clone()),
-            mode: SysrootMode::Workspace(cargo_workspace),
-            error: None,
-        })
+        Some(SysrootWorkspace::Workspace(cargo_workspace))
     }
 }
 
diff --git a/crates/project-model/src/workspace.rs b/crates/project-model/src/workspace.rs
index c10737afed..6dc8e2fa5d 100644
--- a/crates/project-model/src/workspace.rs
+++ b/crates/project-model/src/workspace.rs
@@ -25,10 +25,11 @@ use crate::{
     cargo_workspace::{CargoMetadataConfig, DepKind, PackageData, RustLibSource},
     env::{cargo_config_env, inject_cargo_env, inject_cargo_package_env, inject_rustc_tool_env},
     project_json::{Crate, CrateArrayIdx},
-    sysroot::{SysrootCrate, SysrootMode},
+    sysroot::{SysrootCrate, SysrootWorkspace},
     toolchain_info::{rustc_cfg, target_data_layout, target_triple, QueryConfig},
     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};
 
@@ -213,34 +214,26 @@ impl ProjectWorkspace {
         config: &CargoConfig,
         progress: &dyn Fn(String),
     ) -> Result<ProjectWorkspace, anyhow::Error> {
-        // FIXME: Split sysroot discovery from sysroot loading, as to load the sysroot we
-        // want to pass the analysis target, but to discover the target we need to know the
-        // sysroot location so we know which cargo to use
-        let sysroot = match (&config.sysroot, &config.sysroot_src) {
-            (Some(RustLibSource::Discover), None) => Sysroot::discover(
-                cargo_toml.parent(),
-                &config.extra_env,
-                &config.sysroot_query_metadata,
-            ),
+        let mut sysroot = match (&config.sysroot, &config.sysroot_src) {
+            (Some(RustLibSource::Discover), None) => {
+                Sysroot::discover(cargo_toml.parent(), &config.extra_env)
+            }
             (Some(RustLibSource::Discover), Some(sysroot_src)) => {
                 Sysroot::discover_with_src_override(
                     cargo_toml.parent(),
                     &config.extra_env,
                     sysroot_src.clone(),
-                    &config.sysroot_query_metadata,
                 )
             }
             (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(),
         };
-        tracing::info!(workspace = %cargo_toml, src_root = ?sysroot.src_root(), root = ?sysroot.root(), "Using sysroot");
+
         let rustc_dir = match &config.rustc_source {
             Some(RustLibSource::Path(path)) => ManifestPath::try_from(path.clone())
                 .map_err(|p| Some(format!("rustc source path is not absolute: {p}"))),
@@ -255,6 +248,10 @@ impl ProjectWorkspace {
             &config.extra_env,
         )
         .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| {
             info!(workspace = %cargo_toml, rustc_dir = %rustc_dir, "Using rustc source");
             match CargoWorkspace::fetch_metadata(
@@ -349,11 +346,9 @@ impl ProjectWorkspace {
     }
 
     pub fn load_inline(project_json: ProjectJson, config: &CargoConfig) -> ProjectWorkspace {
-        let sysroot = Sysroot::load(
-            project_json.sysroot.clone(),
-            project_json.sysroot_src.clone(),
-            &config.sysroot_query_metadata,
-        );
+        let mut sysroot =
+            Sysroot::new(project_json.sysroot.clone(), project_json.sysroot_src.clone());
+        sysroot.load_workspace(&SysrootSourceWorkspaceConfig::Stitched);
         let query_config = QueryConfig::Rustc(&sysroot, project_json.path().as_ref());
         let toolchain = match get_toolchain_version(
             project_json.path(),
@@ -387,13 +382,9 @@ impl ProjectWorkspace {
         config: &CargoConfig,
     ) -> anyhow::Result<ProjectWorkspace> {
         let dir = detached_file.parent();
-        let sysroot = match &config.sysroot {
-            Some(RustLibSource::Path(path)) => {
-                Sysroot::discover_sysroot_src_dir(path.clone(), &config.sysroot_query_metadata)
-            }
-            Some(RustLibSource::Discover) => {
-                Sysroot::discover(dir, &config.extra_env, &config.sysroot_query_metadata)
-            }
+        let mut sysroot = match &config.sysroot {
+            Some(RustLibSource::Path(path)) => Sysroot::discover_sysroot_src_dir(path.clone()),
+            Some(RustLibSource::Discover) => Sysroot::discover(dir, &config.extra_env),
             None => Sysroot::empty(),
         };
 
@@ -412,6 +403,10 @@ impl ProjectWorkspace {
             &config.extra_env,
         )
         .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 rustc_cfg = rustc_cfg::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
     pub fn to_roots(&self) -> Vec<PackageRoot> {
         let mk_sysroot = || {
-            let mut r = match self.sysroot.mode() {
-                SysrootMode::Workspace(ws) => ws
+            let mut r = match self.sysroot.workspace() {
+                SysrootWorkspace::Workspace(ws) => ws
                     .packages()
                     .filter_map(|pkg| {
                         if ws[pkg].is_local {
@@ -592,7 +587,7 @@ impl ProjectWorkspace {
                         Some(PackageRoot { is_local: false, include, exclude })
                     })
                     .collect(),
-                SysrootMode::Stitched(_) | SysrootMode::Empty => vec![],
+                SysrootWorkspace::Stitched(_) | SysrootWorkspace::Empty => vec![],
             };
 
             r.push(PackageRoot {
@@ -606,18 +601,18 @@ impl ProjectWorkspace {
             ProjectWorkspaceKind::Json(project) => project
                 .crates()
                 .map(|(_, krate)| {
-                    // FIXME: PackageRoots dont allow specifying files, only directories
-                    let build_file = krate
-                        .build
-                        .as_ref()
-                        .map(|build| self.workspace_root().join(&build.build_file))
-                        .as_deref()
-                        .and_then(AbsPath::parent)
-                        .map(ToOwned::to_owned);
-
+                    let build_files = project
+                        .crates()
+                        .filter_map(|(_, krate)| {
+                            krate.build.as_ref().map(|build| build.build_file.clone())
+                        })
+                        // FIXME: PackageRoots dont allow specifying files, only directories
+                        .filter_map(|build_file| {
+                            self.workspace_root().join(build_file).parent().map(ToOwned::to_owned)
+                        });
                     PackageRoot {
                         is_local: krate.is_workspace_member,
-                        include: krate.include.iter().cloned().chain(build_file).collect(),
+                        include: krate.include.iter().cloned().chain(build_files).collect(),
                         exclude: krate.exclude.clone(),
                     }
                 })
@@ -1416,8 +1411,8 @@ fn sysroot_to_crate_graph(
     load: FileLoader<'_>,
 ) -> (SysrootPublicDeps, Option<CrateId>) {
     let _p = tracing::info_span!("sysroot_to_crate_graph").entered();
-    match sysroot.mode() {
-        SysrootMode::Workspace(cargo) => {
+    match sysroot.workspace() {
+        SysrootWorkspace::Workspace(cargo) => {
             let (mut cg, mut pm) = cargo_to_crate_graph(
                 load,
                 None,
@@ -1492,7 +1487,7 @@ fn sysroot_to_crate_graph(
 
             (SysrootPublicDeps { deps: pub_deps }, libproc_macro)
         }
-        SysrootMode::Stitched(stitched) => {
+        SysrootWorkspace::Stitched(stitched) => {
             let cfg_options = Arc::new({
                 let mut cfg_options = CfgOptions::default();
                 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());
             (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)
     }
 }
+
+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(),
+    }
+}
diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs
index 9b428871c4..afe3455b78 100644
--- a/crates/rust-analyzer/src/cli/analysis_stats.rs
+++ b/crates/rust-analyzer/src/cli/analysis_stats.rs
@@ -33,10 +33,7 @@ use itertools::Itertools;
 use load_cargo::{load_workspace, LoadCargoConfig, ProcMacroServerChoice};
 use oorandom::Rand32;
 use profile::{Bytes, StopWatch};
-use project_model::{
-    CargoConfig, CargoMetadataConfig, CfgOverrides, ProjectManifest, ProjectWorkspace,
-    RustLibSource,
-};
+use project_model::{CargoConfig, CfgOverrides, ProjectManifest, ProjectWorkspace, RustLibSource};
 use rayon::prelude::*;
 use rustc_hash::{FxHashMap, FxHashSet};
 use syntax::{AstNode, SyntaxNode};
@@ -69,12 +66,6 @@ impl flags::AnalysisStats {
                 true => None,
                 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,
             set_test: !self.no_test,
             cfg_overrides: CfgOverrides {
diff --git a/crates/rust-analyzer/src/cli/flags.rs b/crates/rust-analyzer/src/cli/flags.rs
index 920a2a37ef..ff24602144 100644
--- a/crates/rust-analyzer/src/cli/flags.rs
+++ b/crates/rust-analyzer/src/cli/flags.rs
@@ -71,9 +71,6 @@ xflags::xflags! {
             optional --with-deps
             /// Don't load sysroot crates (`std`, `core` & friends).
             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)].
             optional --no-test
 
@@ -238,7 +235,6 @@ pub struct AnalysisStats {
     pub only: Option<String>,
     pub with_deps: bool,
     pub no_sysroot: bool,
-    pub no_query_sysroot_metadata: bool,
     pub no_test: bool,
     pub disable_build_scripts: bool,
     pub disable_proc_macros: bool,
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs
index 64ce124835..67e0a208e8 100644
--- a/crates/rust-analyzer/src/config.rs
+++ b/crates/rust-analyzer/src/config.rs
@@ -21,8 +21,8 @@ use ide_db::{
 use itertools::Itertools;
 use paths::{Utf8Path, Utf8PathBuf};
 use project_model::{
-    CargoConfig, CargoFeatures, CargoMetadataConfig, ProjectJson, ProjectJsonData,
-    ProjectJsonFromCommand, ProjectManifest, RustLibSource,
+    CargoConfig, CargoFeatures, ProjectJson, ProjectJsonData, ProjectJsonFromCommand,
+    ProjectManifest, RustLibSource,
 };
 use rustc_hash::{FxHashMap, FxHashSet};
 use semver::Version;
@@ -595,9 +595,6 @@ config_data! {
         ///
         /// This option does not take effect until rust-analyzer is restarted.
         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
         /// `{cargo.sysroot}/lib/rustlib/src/rust/library`.
         ///
@@ -1941,17 +1938,6 @@ impl Config {
             },
             target: self.cargo_target(source_root).clone(),
             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,
             rustc_source,
             cfg_overrides: project_model::CfgOverrides {
@@ -2674,13 +2660,6 @@ pub enum NumThreads {
     Concrete(usize),
 }
 
-#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
-#[serde(rename_all = "snake_case")]
-pub enum SysrootQueryMetadata {
-    CargoMetadata,
-    None,
-}
-
 macro_rules! _default_val {
     (@verbatim: $s:literal, $ty:ty) => {{
         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! {
             "anyOf": [
                 {
diff --git a/crates/rust-analyzer/src/flycheck.rs b/crates/rust-analyzer/src/flycheck.rs
index ed74d9cf3b..a306302cc0 100644
--- a/crates/rust-analyzer/src/flycheck.rs
+++ b/crates/rust-analyzer/src/flycheck.rs
@@ -233,7 +233,6 @@ struct FlycheckActor {
     /// The receiver side of the channel mentioned above.
     command_receiver: Option<Receiver<CargoCheckMessage>>,
     diagnostics_cleared_for: FxHashSet<Arc<PackageId>>,
-    diagnostics_cleared_for_all: bool,
     diagnostics_received: bool,
 }
 
@@ -265,7 +264,6 @@ impl FlycheckActor {
             command_handle: None,
             command_receiver: None,
             diagnostics_cleared_for: Default::default(),
-            diagnostics_cleared_for_all: false,
             diagnostics_received: false,
         }
     }
@@ -352,7 +350,6 @@ impl FlycheckActor {
                             package_id: None,
                         });
                     }
-                    self.clear_diagnostics_state();
 
                     self.report_progress(Progress::DidFinish(res));
                 }
@@ -398,12 +395,6 @@ impl FlycheckActor {
                                     package_id: Some(package_id.clone()),
                                 });
                             }
-                        } else if !self.diagnostics_cleared_for_all {
-                            self.diagnostics_cleared_for_all = true;
-                            self.send(FlycheckMessage::ClearDiagnostics {
-                                id: self.id,
-                                package_id: None,
-                            });
                         }
                         self.send(FlycheckMessage::AddDiagnostic {
                             id: self.id,
@@ -429,12 +420,7 @@ impl FlycheckActor {
             self.command_receiver.take();
             self.report_progress(Progress::DidCancel);
         }
-        self.clear_diagnostics_state();
-    }
-
-    fn clear_diagnostics_state(&mut self) {
         self.diagnostics_cleared_for.clear();
-        self.diagnostics_cleared_for_all = false;
         self.diagnostics_received = false;
     }
 
diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc
index 205bf0ccb5..2c6ff4fb01 100644
--- a/docs/user/generated_config.adoc
+++ b/docs/user/generated_config.adoc
@@ -135,12 +135,6 @@ Unsetting this disables sysroot loading.
 
 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`)::
 +
 --
diff --git a/editors/code/package.json b/editors/code/package.json
index e1edab4ba2..6ec7032c0b 100644
--- a/editors/code/package.json
+++ b/editors/code/package.json
@@ -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",
                 "properties": {


Test patch:
diff --git a/crates/ide-completion/src/tests/attribute.rs b/crates/ide-completion/src/tests/attribute.rs
index ebf3582057..acafa6518f 100644
--- a/crates/ide-completion/src/tests/attribute.rs
+++ b/crates/ide-completion/src/tests/attribute.rs
@@ -713,28 +713,6 @@ struct Foo;
     );
 }
 
-#[test]
-fn issue_17479() {
-    check(
-        r#"
-//- proc_macros: issue_17479
-fn main() {
-    proc_macros::issue_17479!("te$0");
-}
-"#,
-        expect![""],
-    );
-    check(
-        r#"
-//- proc_macros: issue_17479
-fn main() {
-    proc_macros::issue_17479!("$0");
-}
-"#,
-        expect![""],
-    )
-}
-
 mod cfg {
     use super::*;
 
diff --git a/crates/project-model/src/tests.rs b/crates/project-model/src/tests.rs
index 8bb130433a..681bce3a5a 100644
--- a/crates/project-model/src/tests.rs
+++ b/crates/project-model/src/tests.rs
@@ -12,9 +12,9 @@ use span::FileId;
 use triomphe::Arc;
 
 use crate::{
-    sysroot::SysrootMode, workspace::ProjectWorkspaceKind, CargoWorkspace, CfgOverrides,
-    ManifestPath, ProjectJson, ProjectJsonData, ProjectWorkspace, Sysroot, SysrootQueryMetadata,
-    WorkspaceBuildScripts,
+    sysroot::SysrootWorkspace, workspace::ProjectWorkspaceKind, CargoWorkspace, CfgOverrides,
+    ManifestPath, ProjectJson, ProjectJsonData, ProjectWorkspace, Sysroot,
+    SysrootSourceWorkspaceConfig, WorkspaceBuildScripts,
 };
 
 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:
     let sysroot_dir = AbsPathBuf::assert(sysroot_path);
     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 {
@@ -263,12 +265,12 @@ fn smoke_test_real_sysroot_cargo() {
     let manifest_path =
         ManifestPath::try_from(AbsPathBuf::try_from(meta.workspace_root.clone()).unwrap()).unwrap();
     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"))),
         &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 {
         kind: ProjectWorkspaceKind::Cargo {
             cargo: cargo_workspace,
diff --git a/crates/rust-analyzer/src/cli/rustc_tests.rs b/crates/rust-analyzer/src/cli/rustc_tests.rs
index a4be277da6..6b0ce4db7c 100644
--- a/crates/rust-analyzer/src/cli/rustc_tests.rs
+++ b/crates/rust-analyzer/src/cli/rustc_tests.rs
@@ -13,7 +13,7 @@ use profile::StopWatch;
 use project_model::toolchain_info::{target_data_layout, QueryConfig};
 use project_model::{
     CargoConfig, ManifestPath, ProjectWorkspace, ProjectWorkspaceKind, RustLibSource, Sysroot,
-    SysrootQueryMetadata,
+    SysrootSourceWorkspaceConfig,
 };
 
 use load_cargo::{load_workspace, LoadCargoConfig, ProcMacroServerChoice};
@@ -74,11 +74,8 @@ impl Tester {
             ..Default::default()
         };
 
-        let sysroot = Sysroot::discover(
-            tmp_file.parent().unwrap(),
-            &cargo_config.extra_env,
-            &SysrootQueryMetadata::CargoMetadata(Default::default()),
-        );
+        let mut sysroot = Sysroot::discover(tmp_file.parent().unwrap(), &cargo_config.extra_env);
+        sysroot.load_workspace(&SysrootSourceWorkspaceConfig::default_cargo());
         let data_layout = target_data_layout::get(
             QueryConfig::Rustc(&sysroot, tmp_file.parent().unwrap().as_ref()),
             None,
diff --git a/crates/rust-analyzer/tests/slow-tests/main.rs b/crates/rust-analyzer/tests/slow-tests/main.rs
index ccd2ecdb13..2b3c0a47a2 100644
--- a/crates/rust-analyzer/tests/slow-tests/main.rs
+++ b/crates/rust-analyzer/tests/slow-tests/main.rs
@@ -1082,11 +1082,11 @@ fn resolve_proc_macro() {
         return;
     }
 
-    let sysroot = project_model::Sysroot::discover(
+    let mut sysroot = project_model::Sysroot::discover(
         &AbsPathBuf::assert_utf8(std::env::current_dir().unwrap()),
         &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();
 
diff --git a/crates/test-fixture/src/lib.rs b/crates/test-fixture/src/lib.rs
index 0e72d79687..b40b7757c6 100644
--- a/crates/test-fixture/src/lib.rs
+++ b/crates/test-fixture/src/lib.rs
@@ -376,7 +376,7 @@ impl ChangeFixture {
     }
 }
 
-fn default_test_proc_macros() -> [(String, ProcMacro); 8] {
+fn default_test_proc_macros() -> [(String, ProcMacro); 7] {
     [
         (
             r#"
@@ -483,21 +483,6 @@ pub fn issue_18840(_attr: TokenStream, _item: TokenStream) -> TokenStream {
                 disabled: false,
             },
         ),
-        (
-            r#"
-#[proc_macro]
-pub fn issue_17479(input: TokenStream) -> TokenStream {
-    input
-}
-"#
-            .into(),
-            ProcMacro {
-                name: Symbol::intern("issue_17479"),
-                kind: ProcMacroKind::Bang,
-                expander: sync::Arc::new(Issue17479ProcMacroExpander),
-                disabled: false,
-            },
-        ),
     ]
 }
 
@@ -776,28 +761,3 @@ impl ProcMacroExpander for ShortenProcMacroExpander {
         }
     }
 }
-
-// Reads ident type within string quotes, for issue #17479.
-#[derive(Debug)]
-struct Issue17479ProcMacroExpander;
-impl ProcMacroExpander for Issue17479ProcMacroExpander {
-    fn expand(
-        &self,
-        subtree: &TopSubtree,
-        _: Option<&TopSubtree>,
-        _: &Env,
-        _: Span,
-        _: Span,
-        _: Span,
-        _: Option<String>,
-    ) -> Result<TopSubtree, ProcMacroExpansionError> {
-        let TokenTree::Leaf(Leaf::Literal(lit)) = &subtree.0[1] else {
-            return Err(ProcMacroExpansionError::Panic("incorrect Input".into()));
-        };
-        let symbol = &lit.symbol;
-        let span = lit.span;
-        Ok(quote! { span =>
-            #symbol()
-        })
-    }
-}