Skip to main content

project_model/
workspace.rs

1//! Handles lowering of build-system specific workspace information (`cargo
2//! metadata` or `rust-project.json`) into representation stored in the salsa
3//! database -- `CrateGraph`.
4
5use std::thread::Builder;
6use std::{collections::VecDeque, fmt, fs, iter, ops::Deref, sync, thread};
7
8use anyhow::Context;
9use base_db::{
10    CrateBuilderId, CrateDisplayName, CrateGraphBuilder, CrateName, CrateOrigin,
11    CrateWorkspaceData, DependencyBuilder, Env, LangCrateOrigin, ProcMacroLoadingError,
12    ProcMacroPaths, target::TargetLoadResult,
13};
14use cfg::{CfgAtom, CfgDiff, CfgOptions};
15use intern::{Symbol, sym};
16use paths::{AbsPath, AbsPathBuf, Utf8Path, Utf8PathBuf};
17use rustc_hash::{FxHashMap, FxHashSet};
18use semver::Version;
19use span::{Edition, FileId};
20use toolchain::Tool;
21use tracing::instrument;
22use tracing::{debug, error, info};
23use triomphe::Arc;
24
25use crate::{
26    CargoConfig, CargoWorkspace, CfgOverrides, InvocationStrategy, ManifestPath, Package,
27    ProjectJson, ProjectManifest, RustSourceWorkspaceConfig, Sysroot, TargetData, TargetKind,
28    WorkspaceBuildScripts,
29    build_dependencies::{BuildScriptOutput, ProcMacroDylibPath},
30    cargo_config_file::CargoConfigFile,
31    cargo_workspace::{
32        CargoMetadataConfig, CargoMetadataKind, DepKind, FetchMetadata, PackageData, RustLibSource,
33    },
34    env::{cargo_config_env, inject_cargo_env, inject_cargo_package_env, inject_rustc_tool_env},
35    project_json::{Crate, CrateArrayIdx},
36    sysroot::RustLibSrcWorkspace,
37    toolchain_info::{QueryConfig, rustc_cfg, target_data, target_tuple, version},
38    utf8_stdout,
39};
40
41pub type FileLoader<'a> = &'a mut dyn for<'b> FnMut(&'b AbsPath) -> Option<FileId>;
42
43/// `PackageRoot` describes a package root folder.
44/// Which may be an external dependency, or a member of
45/// the current workspace.
46#[derive(Debug, Clone, Eq, PartialEq, Hash)]
47pub struct PackageRoot {
48    /// Is from the local filesystem and may be edited
49    pub is_local: bool,
50    /// Directories to include
51    pub include: Vec<AbsPathBuf>,
52    /// Directories to exclude
53    pub exclude: Vec<AbsPathBuf>,
54}
55
56#[derive(Clone)]
57pub struct ProjectWorkspace {
58    pub kind: ProjectWorkspaceKind,
59    /// The sysroot loaded for this workspace.
60    pub sysroot: Sysroot,
61    /// Holds cfg flags for the current target. We get those by running
62    /// `rustc --print cfg`.
63    // FIXME: make this a per-crate map, as, eg, build.rs might have a
64    // different target.
65    pub rustc_cfg: Vec<CfgAtom>,
66    /// The toolchain version used by this workspace.
67    pub toolchain: Option<Version>,
68    /// The target data layout queried for workspace.
69    pub target: TargetLoadResult,
70    /// A set of cfg overrides for this workspace.
71    pub cfg_overrides: CfgOverrides,
72    /// Additional includes to add for the VFS.
73    pub extra_includes: Vec<AbsPathBuf>,
74    /// Set `cfg(test)` for local crates
75    pub set_test: bool,
76}
77
78#[derive(Clone)]
79#[allow(clippy::large_enum_variant)]
80pub enum ProjectWorkspaceKind {
81    /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`.
82    Cargo {
83        /// The workspace as returned by `cargo metadata`.
84        cargo: CargoWorkspace,
85        /// Additional `cargo metadata` error. (only populated if retried fetching via `--no-deps` succeeded).
86        error: Option<Arc<anyhow::Error>>,
87        /// The build script results for the workspace.
88        build_scripts: WorkspaceBuildScripts,
89        /// The rustc workspace loaded for this workspace. An `Err(None)` means loading has been
90        /// disabled or was otherwise not requested.
91        rustc: Result<Box<(CargoWorkspace, WorkspaceBuildScripts)>, Option<String>>,
92    },
93    /// Project workspace was specified using a `rust-project.json` file.
94    Json(ProjectJson),
95    // FIXME: The primary limitation of this approach is that the set of detached files needs to be fixed at the beginning.
96    // That's not the end user experience we should strive for.
97    // Ideally, you should be able to just open a random detached file in existing cargo projects, and get the basic features working.
98    // That needs some changes on the salsa-level though.
99    // In particular, we should split the unified CrateGraph (which currently has maximal durability) into proper crate graph, and a set of ad hoc roots (with minimal durability).
100    // Then, we need to hide the graph behind the queries such that most queries look only at the proper crate graph, and fall back to ad hoc roots only if there's no results.
101    // After this, we should be able to tweak the logic in reload.rs to add newly opened files, which don't belong to any existing crates, to the set of the detached files.
102    // //
103    /// Project with a set of disjoint files, not belonging to any particular workspace.
104    /// Backed by basic sysroot crates for basic completion and highlighting.
105    DetachedFile {
106        /// The file in question.
107        file: ManifestPath,
108        /// Is this file a cargo script file?
109        cargo: Option<(CargoWorkspace, WorkspaceBuildScripts, Option<Arc<anyhow::Error>>)>,
110    },
111}
112
113impl fmt::Debug for ProjectWorkspace {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        // Make sure this isn't too verbose.
116        let Self {
117            kind,
118            sysroot,
119            rustc_cfg,
120            toolchain,
121            target: target_layout,
122            cfg_overrides,
123            extra_includes,
124            set_test,
125        } = self;
126        match kind {
127            ProjectWorkspaceKind::Cargo { cargo, error: _, build_scripts, rustc } => f
128                .debug_struct("Cargo")
129                .field("root", &cargo.workspace_root().file_name())
130                .field("n_packages", &cargo.packages().len())
131                .field("n_sysroot_crates", &sysroot.num_packages())
132                .field(
133                    "n_rustc_compiler_crates",
134                    &rustc.as_ref().map(|a| a.as_ref()).map_or(0, |(rc, _)| rc.packages().len()),
135                )
136                .field("n_rustc_cfg", &rustc_cfg.len())
137                .field("n_cfg_overrides", &cfg_overrides.len())
138                .field("n_extra_includes", &extra_includes.len())
139                .field("toolchain", &toolchain)
140                .field("data_layout", &target_layout)
141                .field("set_test", set_test)
142                .field("build_scripts", &build_scripts.error().unwrap_or("ok"))
143                .finish(),
144            ProjectWorkspaceKind::Json(project) => {
145                let mut debug_struct = f.debug_struct("Json");
146                debug_struct
147                    .field("n_crates", &project.n_crates())
148                    .field("n_sysroot_crates", &sysroot.num_packages())
149                    .field("n_rustc_cfg", &rustc_cfg.len())
150                    .field("toolchain", &toolchain)
151                    .field("data_layout", &target_layout)
152                    .field("n_cfg_overrides", &cfg_overrides.len())
153                    .field("n_extra_includes", &extra_includes.len())
154                    .field("set_test", set_test);
155
156                debug_struct.finish()
157            }
158            ProjectWorkspaceKind::DetachedFile { file, cargo: cargo_script } => f
159                .debug_struct("DetachedFiles")
160                .field("file", &file)
161                .field("cargo_script", &cargo_script.is_some())
162                .field("n_sysroot_crates", &sysroot.num_packages())
163                .field("n_rustc_cfg", &rustc_cfg.len())
164                .field("toolchain", &toolchain)
165                .field("data_layout", &target_layout)
166                .field("n_cfg_overrides", &cfg_overrides.len())
167                .field("n_extra_includes", &extra_includes.len())
168                .field("set_test", set_test)
169                .finish(),
170        }
171    }
172}
173
174impl ProjectWorkspace {
175    pub fn load(
176        manifest: ProjectManifest,
177        config: &CargoConfig,
178        progress: &(dyn Fn(String) + Sync),
179    ) -> anyhow::Result<ProjectWorkspace> {
180        ProjectWorkspace::load_inner(&manifest, config, progress)
181            .with_context(|| format!("Failed to load the project at {manifest}"))
182    }
183
184    fn load_inner(
185        manifest: &ProjectManifest,
186        config: &CargoConfig,
187        progress: &(dyn Fn(String) + Sync),
188    ) -> anyhow::Result<ProjectWorkspace> {
189        let res = match manifest {
190            ProjectManifest::ProjectJson(project_json) => {
191                let file = fs::read_to_string(project_json)
192                    .with_context(|| format!("Failed to read json file {project_json}"))?;
193                let data = serde_json::from_str(&file)
194                    .with_context(|| format!("Failed to deserialize json file {project_json}"))?;
195                let project_location = project_json.parent().to_path_buf();
196                let project_json: ProjectJson =
197                    ProjectJson::new(Some(project_json.clone()), &project_location, data);
198                ProjectWorkspace::load_inline(project_json, config, progress)
199            }
200            ProjectManifest::CargoScript(rust_file) => {
201                ProjectWorkspace::load_detached_file(rust_file, config)?
202            }
203            ProjectManifest::CargoToml(cargo_toml) => {
204                ProjectWorkspace::load_cargo(cargo_toml, config, progress)?
205            }
206        };
207
208        Ok(res)
209    }
210
211    fn load_cargo(
212        cargo_toml: &ManifestPath,
213        config: &CargoConfig,
214        progress: &(dyn Fn(String) + Sync),
215    ) -> Result<ProjectWorkspace, anyhow::Error> {
216        progress("discovering sysroot".to_owned());
217        let CargoConfig {
218            features,
219            rustc_source,
220            extra_args,
221            metadata_extra_args,
222            config_path,
223            extra_env,
224            set_test,
225            cfg_overrides,
226            extra_includes,
227            sysroot,
228            sysroot_src,
229            target,
230            no_deps,
231            ..
232        } = config;
233        let workspace_dir = cargo_toml.parent();
234        let mut sysroot = match (sysroot, sysroot_src) {
235            (Some(RustLibSource::Discover), None) => Sysroot::discover(workspace_dir, extra_env),
236            (Some(RustLibSource::Discover), Some(sysroot_src)) => {
237                Sysroot::discover_with_src_override(workspace_dir, extra_env, sysroot_src.clone())
238            }
239            (Some(RustLibSource::Path(path)), None) => {
240                Sysroot::discover_rust_lib_src_dir(path.clone())
241            }
242            (Some(RustLibSource::Path(sysroot)), Some(sysroot_src)) => {
243                Sysroot::new(Some(sysroot.clone()), Some(sysroot_src.clone()))
244            }
245            (None, _) => Sysroot::empty(),
246        };
247
248        // Resolve the Cargo.toml to the workspace root as we base the `target` dir off of it.
249        let mut cmd = sysroot.tool(Tool::Cargo, workspace_dir, extra_env);
250        cmd.args(["locate-project", "--workspace", "--manifest-path", cargo_toml.as_str()]);
251        let cargo_toml = &match utf8_stdout(&mut cmd) {
252            Ok(output) => {
253                #[derive(serde_derive::Deserialize)]
254                struct Root {
255                    root: Utf8PathBuf,
256                }
257                match serde_json::from_str::<Root>(&output) {
258                    Ok(object) => ManifestPath::try_from(AbsPathBuf::assert(object.root))
259                        .expect("manifest path should be absolute"),
260                    Err(e) => {
261                        tracing::error!(%e, %cargo_toml, "failed fetching cargo workspace root");
262                        cargo_toml.clone()
263                    }
264                }
265            }
266            Err(e) => {
267                tracing::error!(%e, %cargo_toml, "failed fetching cargo workspace root");
268                cargo_toml.clone()
269            }
270        };
271        let workspace_dir = cargo_toml.parent();
272
273        tracing::info!(workspace = %cargo_toml, src_root = ?sysroot.rust_lib_src_root(), root = ?sysroot.root(), "Using sysroot");
274        progress("querying project metadata".to_owned());
275        let config_file =
276            CargoConfigFile::load(cargo_toml, extra_env, &sysroot, config_path.as_deref());
277        let config_file_ = config_file.clone();
278        let toolchain_config = QueryConfig::Cargo(&sysroot, cargo_toml, &config_file_);
279        let targets =
280            target_tuple::get(toolchain_config, target.as_deref(), extra_env).unwrap_or_default();
281        let toolchain = version::get(toolchain_config, extra_env)
282            .inspect_err(|e| {
283                tracing::error!(%e,
284                    "failed fetching toolchain version for {cargo_toml:?} workspace"
285                )
286            })
287            .ok()
288            .flatten();
289
290        let fetch_metadata = FetchMetadata::new(
291            cargo_toml,
292            workspace_dir,
293            &CargoMetadataConfig {
294                features: features.clone(),
295                targets: targets.clone(),
296                extra_args: extra_args.clone(),
297                metadata_extra_args: metadata_extra_args.clone(),
298                config_path: config_path.clone(),
299                extra_env: extra_env.clone(),
300                toolchain_version: toolchain.clone(),
301                kind: CargoMetadataKind::Workspace,
302            },
303            &sysroot,
304            *no_deps,
305        );
306
307        // We spawn a bunch of processes to query various information about the workspace's
308        // toolchain and sysroot
309        // We can speed up loading a bit by spawning all of these processes in parallel (especially
310        // on systems were process spawning is delayed)
311        let join = thread::scope(|s| {
312            let rustc_cfg = Builder::new()
313                .name("ProjectWorkspace::rustc_cfg".to_owned())
314                .spawn_scoped(s, || {
315                    rustc_cfg::get(toolchain_config, targets.first().map(Deref::deref), extra_env)
316                })
317                .expect("failed to spawn thread");
318            let target_data = Builder::new()
319                .name("ProjectWorkspace::target_data".to_owned())
320                .spawn_scoped(s, || {
321                    target_data::get(
322                        toolchain_config,
323                        targets.first().map(Deref::deref),
324                        extra_env,
325                        toolchain.as_ref(),
326                    )
327                    .inspect_err(|e| {
328                        tracing::error!(%e,
329                            "failed fetching data layout for \
330                            {cargo_toml:?} workspace"
331                        )
332                    })
333                })
334                .expect("failed to spawn thread");
335
336            let rustc_dir = Builder::new()
337                .name("ProjectWorkspace::rustc_dir".to_owned())
338                .spawn_scoped(s, || {
339                    let rustc_dir = match rustc_source {
340                        Some(RustLibSource::Path(path)) => ManifestPath::try_from(path.clone())
341                            .map_err(|p| Some(format!("rustc source path is not absolute: {p}"))),
342                        Some(RustLibSource::Discover) => {
343                            sysroot.discover_rustc_src().ok_or_else(|| {
344                                Some("Failed to discover rustc source for sysroot.".to_owned())
345                            })
346                        }
347                        None => Err(None),
348                    };
349                    rustc_dir.and_then(|rustc_dir| {
350                    info!(workspace = %cargo_toml, rustc_dir = %rustc_dir, "Using rustc source");
351                    match FetchMetadata::new(
352                        &rustc_dir,
353                        workspace_dir,
354                        &CargoMetadataConfig {
355                            features: crate::CargoFeatures::default(),
356                            targets: targets.clone(),
357                            extra_args: extra_args.clone(),
358                            metadata_extra_args: metadata_extra_args.clone(),
359                            config_path: config_path.clone(),
360                            extra_env: extra_env.clone(),
361                            toolchain_version: toolchain.clone(),
362                            kind: CargoMetadataKind::Rustc
363                        },
364                        &sysroot,
365                        *no_deps,
366                    ).exec(true, progress) {
367                        Ok((meta, _error)) => {
368                            let workspace = CargoWorkspace::new(
369                                meta,
370                                cargo_toml.clone(),
371                                Env::default(),
372                                false,
373                            );
374                            let build_scripts = WorkspaceBuildScripts::rustc_crates(
375                                &workspace,
376                                workspace_dir,
377                                extra_env,
378                                &sysroot,
379                            );
380                            Ok(Box::new((workspace, build_scripts)))
381                        }
382                        Err(e) => {
383                            tracing::error!(
384                                %e,
385                                "Failed to read Cargo metadata from rustc source \
386                                at {rustc_dir}",
387                            );
388                            Err(Some(format!(
389                                "Failed to read Cargo metadata from rustc source \
390                                at {rustc_dir}: {e}"
391                            )))
392                        }
393                    }
394                })
395                })
396                .expect("failed to spawn thread");
397
398            let cargo_metadata = Builder::new()
399                .name("ProjectWorkspace::cargo_metadata".to_owned())
400                .spawn_scoped(s, || fetch_metadata.exec(false, progress))
401                .expect("failed to spawn thread");
402            let loaded_sysroot = Builder::new()
403                .name("ProjectWorkspace::loaded_sysroot".to_owned())
404                .spawn_scoped(s, || {
405                    sysroot.load_workspace(
406                        &RustSourceWorkspaceConfig::CargoMetadata(sysroot_metadata_config(
407                            config,
408                            workspace_dir,
409                            &targets,
410                            toolchain.clone(),
411                        )),
412                        config.no_deps,
413                        progress,
414                    )
415                })
416                .expect("failed to spawn thread");
417            let cargo_env = Builder::new()
418                .name("ProjectWorkspace::cargo_env".to_owned())
419                .spawn_scoped(s, move || cargo_config_env(&config_file, &config.extra_env))
420                .expect("failed to spawn thread");
421            thread::Result::Ok((
422                rustc_cfg.join()?,
423                target_data.join()?,
424                rustc_dir.join()?,
425                loaded_sysroot.join()?,
426                cargo_metadata.join()?,
427                cargo_env.join()?,
428            ))
429        });
430
431        let (rustc_cfg, data_layout, mut rustc, loaded_sysroot, cargo_metadata, mut cargo_env) =
432            match join {
433                Ok(it) => it,
434                Err(e) => std::panic::resume_unwind(e),
435            };
436
437        for (key, value) in config.extra_env.iter() {
438            if let Some(value) = value {
439                cargo_env.insert(key.clone(), value.clone());
440            }
441        }
442
443        let (meta, error) = cargo_metadata.with_context(|| {
444            format!(
445                "Failed to read Cargo metadata from Cargo.toml file {cargo_toml}, {toolchain:?}",
446            )
447        })?;
448        let cargo = CargoWorkspace::new(meta, cargo_toml.clone(), cargo_env, false);
449        if let Some(loaded_sysroot) = loaded_sysroot {
450            tracing::info!(src_root = ?sysroot.rust_lib_src_root(), root = %loaded_sysroot, "Loaded sysroot");
451            sysroot.set_workspace(loaded_sysroot);
452        }
453
454        if !cargo.requires_rustc_private()
455            && let Err(e) = &mut rustc
456        {
457            // We don't need the rustc sources here,
458            // so just discard the error.
459            _ = e.take();
460        }
461
462        Ok(ProjectWorkspace {
463            kind: ProjectWorkspaceKind::Cargo {
464                cargo,
465                build_scripts: WorkspaceBuildScripts::default(),
466                rustc,
467                error: error.map(Arc::new),
468            },
469            sysroot,
470            rustc_cfg,
471            cfg_overrides: cfg_overrides.clone(),
472            toolchain,
473            target: data_layout.map_err(|it| it.to_string().into()),
474            extra_includes: extra_includes.clone(),
475            set_test: *set_test,
476        })
477    }
478
479    pub fn load_inline(
480        mut project_json: ProjectJson,
481        config: &CargoConfig,
482        progress: &(dyn Fn(String) + Sync),
483    ) -> ProjectWorkspace {
484        progress("discovering sysroot".to_owned());
485        let mut sysroot =
486            Sysroot::new(project_json.sysroot.clone(), project_json.sysroot_src.clone());
487
488        tracing::info!(workspace = %project_json.manifest_or_root(), src_root = ?sysroot.rust_lib_src_root(), root = ?sysroot.root(), "Using sysroot");
489        progress("querying project metadata".to_owned());
490        let sysroot_project = project_json.sysroot_project.take();
491        let query_config = QueryConfig::Rustc(&sysroot, project_json.path().as_ref());
492        let targets = target_tuple::get(query_config, config.target.as_deref(), &config.extra_env)
493            .unwrap_or_default();
494        let toolchain = version::get(query_config, &config.extra_env).ok().flatten();
495
496        // We spawn a bunch of processes to query various information about the workspace's
497        // toolchain and sysroot
498        // We can speed up loading a bit by spawning all of these processes in parallel (especially
499        // on systems were process spawning is delayed)
500        let join = thread::scope(|s| {
501            let rustc_cfg = s.spawn(|| {
502                rustc_cfg::get(query_config, targets.first().map(Deref::deref), &config.extra_env)
503            });
504            let data_layout = s.spawn(|| {
505                target_data::get(
506                    query_config,
507                    targets.first().map(Deref::deref),
508                    &config.extra_env,
509                    toolchain.as_ref(),
510                )
511            });
512            let loaded_sysroot = s.spawn(|| {
513                if let Some(sysroot_project) = sysroot_project {
514                    sysroot.load_workspace(
515                        &RustSourceWorkspaceConfig::Json(*sysroot_project),
516                        config.no_deps,
517                        progress,
518                    )
519                } else {
520                    sysroot.load_workspace(
521                        &RustSourceWorkspaceConfig::CargoMetadata(sysroot_metadata_config(
522                            config,
523                            project_json.project_root(),
524                            &targets,
525                            toolchain.clone(),
526                        )),
527                        config.no_deps,
528                        progress,
529                    )
530                }
531            });
532
533            thread::Result::Ok((rustc_cfg.join()?, data_layout.join()?, loaded_sysroot.join()?))
534        });
535
536        let (rustc_cfg, target_data, loaded_sysroot) = match join {
537            Ok(it) => it,
538            Err(e) => std::panic::resume_unwind(e),
539        };
540
541        if let Some(loaded_sysroot) = loaded_sysroot {
542            sysroot.set_workspace(loaded_sysroot);
543        }
544
545        ProjectWorkspace {
546            kind: ProjectWorkspaceKind::Json(project_json),
547            sysroot,
548            rustc_cfg,
549            toolchain,
550            target: target_data.map_err(|it| it.to_string().into()),
551            cfg_overrides: config.cfg_overrides.clone(),
552            extra_includes: config.extra_includes.clone(),
553            set_test: config.set_test,
554        }
555    }
556
557    pub fn load_detached_file(
558        detached_file: &ManifestPath,
559        config: &CargoConfig,
560    ) -> anyhow::Result<ProjectWorkspace> {
561        let dir = detached_file.parent();
562        let mut sysroot = match &config.sysroot {
563            Some(RustLibSource::Path(path)) => Sysroot::discover_rust_lib_src_dir(path.clone()),
564            Some(RustLibSource::Discover) => Sysroot::discover(dir, &config.extra_env),
565            None => Sysroot::empty(),
566        };
567
568        let config_file = CargoConfigFile::load(
569            detached_file,
570            &config.extra_env,
571            &sysroot,
572            config.config_path.as_deref(),
573        );
574        let query_config = QueryConfig::Cargo(&sysroot, detached_file, &config_file);
575        let toolchain = version::get(query_config, &config.extra_env).ok().flatten();
576        let targets = target_tuple::get(query_config, config.target.as_deref(), &config.extra_env)
577            .unwrap_or_default();
578        let rustc_cfg = rustc_cfg::get(query_config, None, &config.extra_env);
579        let target_data =
580            target_data::get(query_config, None, &config.extra_env, toolchain.as_ref());
581
582        let loaded_sysroot = sysroot.load_workspace(
583            &RustSourceWorkspaceConfig::CargoMetadata(sysroot_metadata_config(
584                config,
585                dir,
586                &targets,
587                toolchain.clone(),
588            )),
589            config.no_deps,
590            &|_| (),
591        );
592        if let Some(loaded_sysroot) = loaded_sysroot {
593            sysroot.set_workspace(loaded_sysroot);
594        }
595
596        let fetch_metadata = FetchMetadata::new(
597            detached_file,
598            dir,
599            &CargoMetadataConfig {
600                features: config.features.clone(),
601                targets,
602                extra_args: config.extra_args.clone(),
603                metadata_extra_args: config.metadata_extra_args.clone(),
604                config_path: config.config_path.clone(),
605                extra_env: config.extra_env.clone(),
606                toolchain_version: toolchain.clone(),
607                kind: CargoMetadataKind::DetachedFile,
608            },
609            &sysroot,
610            config.no_deps,
611        );
612        let cargo_script = fetch_metadata.exec(false, &|_| ()).ok().map(|(ws, error)| {
613            let cargo_config_extra_env = cargo_config_env(&config_file, &config.extra_env);
614            (
615                CargoWorkspace::new(ws, detached_file.clone(), cargo_config_extra_env, false),
616                WorkspaceBuildScripts::default(),
617                error.map(Arc::new),
618            )
619        });
620
621        Ok(ProjectWorkspace {
622            kind: ProjectWorkspaceKind::DetachedFile {
623                file: detached_file.to_owned(),
624                cargo: cargo_script,
625            },
626            sysroot,
627            rustc_cfg,
628            toolchain,
629            target: target_data.map_err(|it| it.to_string().into()),
630            cfg_overrides: config.cfg_overrides.clone(),
631            extra_includes: config.extra_includes.clone(),
632            set_test: config.set_test,
633        })
634    }
635
636    pub fn load_detached_files(
637        detached_files: Vec<ManifestPath>,
638        config: &CargoConfig,
639    ) -> Vec<anyhow::Result<ProjectWorkspace>> {
640        detached_files.into_iter().map(|file| Self::load_detached_file(&file, config)).collect()
641    }
642
643    /// Runs the build scripts for this [`ProjectWorkspace`].
644    pub fn run_build_scripts(
645        &self,
646        config: &CargoConfig,
647        progress: &dyn Fn(String),
648    ) -> anyhow::Result<WorkspaceBuildScripts> {
649        match &self.kind {
650            ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _, None)), .. }
651            | ProjectWorkspaceKind::Cargo { cargo, error: None, .. } => {
652                WorkspaceBuildScripts::run_for_workspace(
653                    config,
654                    cargo,
655                    progress,
656                    &self.sysroot,
657                    self.toolchain.as_ref(),
658                )
659                .with_context(|| {
660                    format!("Failed to run build scripts for {}", cargo.workspace_root())
661                })
662            }
663            _ => Ok(WorkspaceBuildScripts::default()),
664        }
665    }
666
667    /// Runs the build scripts for the given [`ProjectWorkspace`]s. Depending on the invocation
668    /// strategy this may run a single build process for all project workspaces.
669    pub fn run_all_build_scripts(
670        workspaces: &[ProjectWorkspace],
671        config: &CargoConfig,
672        progress: &dyn Fn(String),
673        working_directory: &AbsPathBuf,
674    ) -> Vec<anyhow::Result<WorkspaceBuildScripts>> {
675        if matches!(config.invocation_strategy, InvocationStrategy::PerWorkspace)
676            || config.run_build_script_command.is_none()
677        {
678            return workspaces.iter().map(|it| it.run_build_scripts(config, progress)).collect();
679        }
680
681        let cargo_ws: Vec<_> = workspaces
682            .iter()
683            .filter_map(|it| match &it.kind {
684                ProjectWorkspaceKind::Cargo { cargo, .. } => Some(cargo),
685                _ => None,
686            })
687            .collect();
688        let outputs = &mut match WorkspaceBuildScripts::run_once(
689            config,
690            &cargo_ws,
691            progress,
692            working_directory,
693        ) {
694            Ok(it) => Ok(it.into_iter()),
695            // io::Error is not Clone?
696            Err(e) => Err(sync::Arc::new(e)),
697        };
698
699        workspaces
700            .iter()
701            .map(|it| match &it.kind {
702                ProjectWorkspaceKind::Cargo { cargo, .. } => match outputs {
703                    Ok(outputs) => Ok(outputs.next().unwrap()),
704                    Err(e) => Err(e.clone()).with_context(|| {
705                        format!("Failed to run build scripts for {}", cargo.workspace_root())
706                    }),
707                },
708                _ => Ok(WorkspaceBuildScripts::default()),
709            })
710            .collect()
711    }
712
713    pub fn set_build_scripts(&mut self, bs: WorkspaceBuildScripts) {
714        match &mut self.kind {
715            ProjectWorkspaceKind::Cargo { build_scripts, .. }
716            | ProjectWorkspaceKind::DetachedFile { cargo: Some((_, build_scripts, _)), .. } => {
717                *build_scripts = bs
718            }
719            _ => assert_eq!(bs, WorkspaceBuildScripts::default()),
720        }
721    }
722
723    pub fn manifest_or_root(&self) -> &AbsPath {
724        match &self.kind {
725            ProjectWorkspaceKind::Cargo { cargo, .. } => cargo.manifest_path(),
726            ProjectWorkspaceKind::Json(project) => project.manifest_or_root(),
727            ProjectWorkspaceKind::DetachedFile { file, .. } => file,
728        }
729    }
730
731    pub fn workspace_root(&self) -> &AbsPath {
732        match &self.kind {
733            ProjectWorkspaceKind::Cargo { cargo, .. } => cargo.workspace_root(),
734            ProjectWorkspaceKind::Json(project) => project.project_root(),
735            ProjectWorkspaceKind::DetachedFile { file, .. } => file.parent(),
736        }
737    }
738
739    pub fn manifest(&self) -> Option<&ManifestPath> {
740        match &self.kind {
741            ProjectWorkspaceKind::Cargo { cargo, .. } => Some(cargo.manifest_path()),
742            ProjectWorkspaceKind::Json(project) => project.manifest(),
743            ProjectWorkspaceKind::DetachedFile { cargo, .. } => {
744                Some(cargo.as_ref()?.0.manifest_path())
745            }
746        }
747    }
748
749    pub fn buildfiles(&self) -> Vec<AbsPathBuf> {
750        match &self.kind {
751            ProjectWorkspaceKind::Json(project) => project
752                .crates()
753                .filter_map(|(_, krate)| krate.build.as_ref().map(|build| build.build_file.clone()))
754                .map(|build_file| self.workspace_root().join(build_file))
755                .collect(),
756            _ => vec![],
757        }
758    }
759
760    pub fn find_sysroot_proc_macro_srv(&self) -> Option<anyhow::Result<AbsPathBuf>> {
761        self.sysroot.discover_proc_macro_srv()
762    }
763
764    /// Returns the roots for the current `ProjectWorkspace`
765    /// The return type contains the path and whether or not
766    /// the root is a member of the current workspace
767    pub fn to_roots(&self) -> Vec<PackageRoot> {
768        let mk_sysroot = || {
769            let mut r = match self.sysroot.workspace() {
770                RustLibSrcWorkspace::Workspace { ws, .. } => ws
771                    .packages()
772                    .filter_map(|pkg| {
773                        if ws[pkg].is_local {
774                            // the local ones are included in the main `PackageRoot` below
775                            return None;
776                        }
777                        let pkg_root = ws[pkg].manifest.parent().to_path_buf();
778
779                        let include = vec![pkg_root.clone()];
780
781                        let exclude = vec![
782                            pkg_root.join(".git"),
783                            pkg_root.join("target"),
784                            pkg_root.join("tests"),
785                            pkg_root.join("examples"),
786                            pkg_root.join("benches"),
787                        ];
788                        Some(PackageRoot { is_local: false, include, exclude })
789                    })
790                    .collect(),
791                RustLibSrcWorkspace::Json(project_json) => project_json
792                    .crates()
793                    .map(|(_, krate)| PackageRoot {
794                        is_local: krate.is_workspace_member,
795                        include: krate.include.clone(),
796                        exclude: krate.exclude.clone(),
797                    })
798                    .collect(),
799                RustLibSrcWorkspace::Stitched(_) => vec![],
800                RustLibSrcWorkspace::Empty => vec![],
801            };
802
803            r.push(PackageRoot {
804                is_local: false,
805                include: self
806                    .sysroot
807                    .rust_lib_src_root()
808                    .map(|it| it.to_path_buf())
809                    .into_iter()
810                    .collect(),
811                exclude: Vec::new(),
812            });
813            r
814        };
815        match &self.kind {
816            ProjectWorkspaceKind::Json(project) => project
817                .crates()
818                .map(|(_, krate)| PackageRoot {
819                    is_local: krate.is_workspace_member,
820                    include: krate
821                        .include
822                        .iter()
823                        .cloned()
824                        .chain(self.extra_includes.iter().cloned())
825                        .collect(),
826                    exclude: krate.exclude.clone(),
827                })
828                .collect::<FxHashSet<_>>()
829                .into_iter()
830                .chain(mk_sysroot())
831                .collect::<Vec<_>>(),
832            ProjectWorkspaceKind::Cargo { cargo, rustc, build_scripts, error: _ } => {
833                cargo
834                    .packages()
835                    .map(|pkg| {
836                        let is_local = cargo[pkg].is_local;
837                        let is_member = cargo[pkg].is_member;
838                        let pkg_root = cargo[pkg].manifest.parent().to_path_buf();
839
840                        let mut include = vec![pkg_root.clone()];
841                        let out_dir =
842                            build_scripts.get_output(pkg).and_then(|it| it.out_dir.clone());
843                        include.extend(out_dir);
844
845                        // In case target's path is manually set in Cargo.toml to be
846                        // outside the package root, add its parent as an extra include.
847                        // An example of this situation would look like this:
848                        //
849                        // ```toml
850                        // [lib]
851                        // path = "../../src/lib.rs"
852                        // ```
853                        //
854                        // or
855                        //
856                        // ```toml
857                        // [[bin]]
858                        // path = "../bin_folder/main.rs"
859                        // ```
860                        let extra_targets = cargo[pkg]
861                            .targets
862                            .iter()
863                            .filter_map(|&tgt| cargo[tgt].root.parent())
864                            .map(|tgt| tgt.normalize().to_path_buf())
865                            .filter(|path| !path.starts_with(&pkg_root));
866                        include.extend(extra_targets);
867
868                        let mut exclude = vec![pkg_root.join(".git")];
869                        if is_local {
870                            include.extend(self.extra_includes.iter().cloned());
871                            exclude.push(pkg_root.join("target"));
872                        }
873                        if !is_member {
874                            // For non-workspace-members, we only resolve library targets,
875                            // so none of these need to be loaded into the VFS.
876                            exclude.push(pkg_root.join("tests"));
877                            exclude.push(pkg_root.join("examples"));
878                            exclude.push(pkg_root.join("benches"));
879                        }
880                        include.sort();
881                        include.dedup();
882                        PackageRoot { is_local, include, exclude }
883                    })
884                    .chain(mk_sysroot())
885                    .chain(rustc.iter().map(|a| a.as_ref()).flat_map(|(rustc, _)| {
886                        rustc.packages().map(move |krate| {
887                            let krate = &rustc[krate];
888                            let include = if krate.name == "rustc_proc_macro" {
889                                // rustc_proc_macro sets its root to ../../library/proc_macro, so we need to include both the manifest
890                                // and the root separately.
891                                vec![
892                                    krate.manifest.parent().to_path_buf(),
893                                    rustc[krate.targets[0]]
894                                        .root
895                                        .parent()
896                                        .unwrap()
897                                        .parent()
898                                        .unwrap()
899                                        .to_path_buf(),
900                                ]
901                            } else {
902                                vec![krate.manifest.parent().to_path_buf()]
903                            };
904                            PackageRoot { is_local: false, include, exclude: Vec::new() }
905                        })
906                    }))
907                    .collect()
908            }
909            ProjectWorkspaceKind::DetachedFile { file, cargo: cargo_script, .. } => {
910                iter::once(PackageRoot {
911                    is_local: true,
912                    include: vec![file.to_path_buf()],
913                    exclude: Vec::new(),
914                })
915                .chain(cargo_script.iter().flat_map(|(cargo, build_scripts, _)| {
916                    cargo.packages().map(|pkg| {
917                        let is_local = cargo[pkg].is_local;
918                        let is_member = cargo[pkg].is_member;
919                        let pkg_root = cargo[pkg].manifest.parent().to_path_buf();
920
921                        let mut include = vec![pkg_root.clone()];
922                        let out_dir =
923                            build_scripts.get_output(pkg).and_then(|it| it.out_dir.clone());
924                        include.extend(out_dir);
925
926                        // In case target's path is manually set in Cargo.toml to be
927                        // outside the package root, add its parent as an extra include.
928                        // An example of this situation would look like this:
929                        //
930                        // ```toml
931                        // [lib]
932                        // path = "../../src/lib.rs"
933                        // ```
934                        //
935                        // or
936                        //
937                        // ```toml
938                        // [[bin]]
939                        // path = "../bin_folder/main.rs"
940                        // ```
941                        let extra_targets = cargo[pkg]
942                            .targets
943                            .iter()
944                            .filter_map(|&tgt| cargo[tgt].root.parent())
945                            .map(|tgt| tgt.normalize().to_path_buf())
946                            .filter(|path| !path.starts_with(&pkg_root));
947                        include.extend(extra_targets);
948
949                        let mut exclude = vec![pkg_root.join(".git")];
950                        if is_local {
951                            include.extend(self.extra_includes.iter().cloned());
952
953                            exclude.push(pkg_root.join("target"));
954                        }
955                        if !is_member {
956                            // For non-workspace-members, we only resolve library targets,
957                            // so none of these need to be loaded into the VFS.
958                            exclude.push(pkg_root.join("tests"));
959                            exclude.push(pkg_root.join("examples"));
960                            exclude.push(pkg_root.join("benches"));
961                        }
962                        include.sort();
963                        include.dedup();
964                        PackageRoot { is_local, include, exclude }
965                    })
966                }))
967                .chain(mk_sysroot())
968                .collect()
969            }
970        }
971    }
972
973    pub fn n_packages(&self) -> usize {
974        let sysroot_package_len = self.sysroot.num_packages();
975        match &self.kind {
976            ProjectWorkspaceKind::Json(project) => sysroot_package_len + project.n_crates(),
977            ProjectWorkspaceKind::Cargo { cargo, rustc, .. } => {
978                let rustc_package_len =
979                    rustc.as_ref().map(|a| a.as_ref()).map_or(0, |(it, _)| it.packages().len());
980                cargo.packages().len() + sysroot_package_len + rustc_package_len
981            }
982            ProjectWorkspaceKind::DetachedFile { cargo: cargo_script, .. } => {
983                sysroot_package_len
984                    + cargo_script.as_ref().map_or(1, |(cargo, _, _)| cargo.packages().len())
985            }
986        }
987    }
988
989    pub fn to_crate_graph(
990        &self,
991        load: FileLoader<'_>,
992        extra_env: &FxHashMap<String, Option<String>>,
993    ) -> (CrateGraphBuilder, ProcMacroPaths) {
994        let _p = tracing::info_span!("ProjectWorkspace::to_crate_graph").entered();
995
996        let Self { kind, sysroot, cfg_overrides, rustc_cfg, .. } = self;
997        let crate_ws_data = Arc::new(CrateWorkspaceData {
998            toolchain: self.toolchain.clone(),
999            target: self.target.clone(),
1000        });
1001        let (crate_graph, proc_macros) = match kind {
1002            ProjectWorkspaceKind::Json(project) => project_json_to_crate_graph(
1003                rustc_cfg.clone(),
1004                load,
1005                project,
1006                sysroot,
1007                extra_env,
1008                cfg_overrides,
1009                self.set_test,
1010                false,
1011                crate_ws_data,
1012            ),
1013            ProjectWorkspaceKind::Cargo { cargo, rustc, build_scripts, error: _ } => {
1014                cargo_to_crate_graph(
1015                    load,
1016                    rustc.as_ref().map(|a| a.as_ref()).ok(),
1017                    cargo,
1018                    sysroot,
1019                    rustc_cfg.clone(),
1020                    cfg_overrides,
1021                    build_scripts,
1022                    self.set_test,
1023                    crate_ws_data,
1024                )
1025            }
1026            ProjectWorkspaceKind::DetachedFile { file, cargo: cargo_script, .. } => {
1027                if let Some((cargo, build_scripts, _)) = cargo_script {
1028                    cargo_to_crate_graph(
1029                        &mut |path| load(path),
1030                        None,
1031                        cargo,
1032                        sysroot,
1033                        rustc_cfg.clone(),
1034                        cfg_overrides,
1035                        build_scripts,
1036                        self.set_test,
1037                        crate_ws_data,
1038                    )
1039                } else {
1040                    detached_file_to_crate_graph(
1041                        rustc_cfg.clone(),
1042                        load,
1043                        file,
1044                        sysroot,
1045                        cfg_overrides,
1046                        self.set_test,
1047                        crate_ws_data,
1048                    )
1049                }
1050            }
1051        };
1052
1053        (crate_graph, proc_macros)
1054    }
1055
1056    pub fn eq_ignore_build_data(&self, other: &Self) -> bool {
1057        let Self {
1058            kind, sysroot, rustc_cfg, toolchain, target: target_layout, cfg_overrides, ..
1059        } = self;
1060        let Self {
1061            kind: o_kind,
1062            sysroot: o_sysroot,
1063            rustc_cfg: o_rustc_cfg,
1064            toolchain: o_toolchain,
1065            target: o_target_layout,
1066            cfg_overrides: o_cfg_overrides,
1067            ..
1068        } = other;
1069        (match (kind, o_kind) {
1070            (
1071                ProjectWorkspaceKind::Cargo { cargo, rustc, build_scripts: _, error: _ },
1072                ProjectWorkspaceKind::Cargo {
1073                    cargo: o_cargo,
1074                    rustc: o_rustc,
1075                    build_scripts: _,
1076                    error: _,
1077                },
1078            ) => cargo == o_cargo && rustc == o_rustc,
1079            (ProjectWorkspaceKind::Json(project), ProjectWorkspaceKind::Json(o_project)) => {
1080                project == o_project
1081            }
1082            (
1083                ProjectWorkspaceKind::DetachedFile { file, cargo: Some((cargo_script, _, _)) },
1084                ProjectWorkspaceKind::DetachedFile {
1085                    file: o_file,
1086                    cargo: Some((o_cargo_script, _, _)),
1087                },
1088            ) => file == o_file && cargo_script == o_cargo_script,
1089            _ => return false,
1090        }) && sysroot == o_sysroot
1091            && rustc_cfg == o_rustc_cfg
1092            && toolchain == o_toolchain
1093            && target_layout == o_target_layout
1094            && cfg_overrides == o_cfg_overrides
1095    }
1096
1097    /// Returns `true` if the project workspace is [`Json`].
1098    ///
1099    /// [`Json`]: ProjectWorkspaceKind::Json
1100    #[must_use]
1101    pub fn is_json(&self) -> bool {
1102        matches!(self.kind, ProjectWorkspaceKind::Json { .. })
1103    }
1104}
1105
1106#[instrument(skip_all)]
1107fn project_json_to_crate_graph(
1108    rustc_cfg: Vec<CfgAtom>,
1109    load: FileLoader<'_>,
1110    project: &ProjectJson,
1111    sysroot: &Sysroot,
1112    extra_env: &FxHashMap<String, Option<String>>,
1113    override_cfg: &CfgOverrides,
1114    set_test: bool,
1115    is_sysroot: bool,
1116    crate_ws_data: Arc<CrateWorkspaceData>,
1117) -> (CrateGraphBuilder, ProcMacroPaths) {
1118    let mut res = (CrateGraphBuilder::default(), ProcMacroPaths::default());
1119    let (crate_graph, proc_macros) = &mut res;
1120    let (public_deps, libproc_macro) = sysroot_to_crate_graph(
1121        crate_graph,
1122        sysroot,
1123        rustc_cfg.clone(),
1124        load,
1125        // FIXME: This looks incorrect but I don't think this matters.
1126        crate_ws_data.clone(),
1127    );
1128
1129    let mut cfg_cache: FxHashMap<&str, Vec<CfgAtom>> = FxHashMap::default();
1130    let project_root = Arc::new(project.project_root().to_path_buf());
1131
1132    let idx_to_crate_id: FxHashMap<CrateArrayIdx, _> = project
1133        .crates()
1134        .filter_map(|(idx, krate)| Some((idx, krate, load(&krate.root_module)?)))
1135        .map(
1136            |(
1137                idx,
1138                Crate {
1139                    display_name,
1140                    edition,
1141                    version,
1142                    cfg,
1143                    target,
1144                    env,
1145                    crate_attrs,
1146                    proc_macro_dylib_path,
1147                    is_proc_macro,
1148                    repository,
1149                    is_workspace_member,
1150                    proc_macro_cwd,
1151                    ..
1152                },
1153                file_id,
1154            )| {
1155                let mut env = env.clone().into_iter().collect::<Env>();
1156                // Override existing env vars with those from `extra_env`
1157                env.extend(
1158                    extra_env
1159                        .iter()
1160                        .filter_map(|(k, v)| v.as_ref().map(|v| (k.clone(), v.clone()))),
1161                );
1162
1163                let target_cfgs = match target.as_deref() {
1164                    Some(target) => cfg_cache.entry(target).or_insert_with(|| {
1165                        rustc_cfg::get(
1166                            QueryConfig::Rustc(sysroot, project.project_root().as_ref()),
1167                            Some(target),
1168                            extra_env,
1169                        )
1170                    }),
1171                    None => &rustc_cfg,
1172                };
1173
1174                let cfg_options = {
1175                    let mut cfg_options: CfgOptions =
1176                        target_cfgs.iter().chain(cfg.iter()).cloned().collect();
1177
1178                    if *is_workspace_member {
1179                        if set_test && !is_sysroot {
1180                            // Add test cfg for local crates
1181                            cfg_options.insert_atom(sym::test);
1182                        }
1183                        cfg_options.insert_atom(sym::rust_analyzer);
1184                    }
1185
1186                    override_cfg.apply(
1187                        &mut cfg_options,
1188                        display_name
1189                            .as_ref()
1190                            .map(|it| it.canonical_name().as_str())
1191                            .unwrap_or_default(),
1192                    );
1193                    cfg_options
1194                };
1195
1196                let crate_graph_crate_id = crate_graph.add_crate_root(
1197                    file_id,
1198                    *edition,
1199                    display_name.clone(),
1200                    version.clone(),
1201                    cfg_options,
1202                    None,
1203                    env,
1204                    if let Some(name) = display_name.clone() {
1205                        if is_sysroot {
1206                            CrateOrigin::Lang(LangCrateOrigin::from(name.canonical_name().as_str()))
1207                        } else {
1208                            CrateOrigin::Local {
1209                                repo: repository.clone(),
1210                                name: Some(name.canonical_name().to_owned()),
1211                            }
1212                        }
1213                    } else if is_sysroot {
1214                        CrateOrigin::Lang(LangCrateOrigin::Dependency)
1215                    } else {
1216                        CrateOrigin::Local { repo: None, name: None }
1217                    },
1218                    crate_attrs.clone(),
1219                    TargetKind::Lib { is_proc_macro: *is_proc_macro },
1220                    match proc_macro_cwd {
1221                        Some(path) => Arc::new(path.clone()),
1222                        None => project_root.clone(),
1223                    },
1224                    crate_ws_data.clone(),
1225                );
1226                debug!(
1227                    ?crate_graph_crate_id,
1228                    crate = display_name.as_ref().map(|name| name.canonical_name().as_str()),
1229                    "added root to crate graph"
1230                );
1231                if *is_proc_macro && let Some(path) = proc_macro_dylib_path.clone() {
1232                    let node = Ok((
1233                        display_name
1234                            .as_ref()
1235                            .map(|it| it.canonical_name().as_str().to_owned())
1236                            .unwrap_or_else(|| format!("crate{}", idx.0)),
1237                        path,
1238                    ));
1239                    proc_macros.insert(crate_graph_crate_id, node);
1240                }
1241                (idx, crate_graph_crate_id)
1242            },
1243        )
1244        .collect();
1245
1246    debug!(map = ?idx_to_crate_id);
1247    for (from_idx, krate) in project.crates() {
1248        if let Some(&from) = idx_to_crate_id.get(&from_idx) {
1249            public_deps.add_to_crate_graph(crate_graph, from);
1250            if let Some(proc_macro) = libproc_macro {
1251                add_proc_macro_dep(crate_graph, from, proc_macro, krate.is_proc_macro);
1252            }
1253
1254            for dep in &krate.deps {
1255                if let Some(&to) = idx_to_crate_id.get(&dep.krate) {
1256                    add_dep(crate_graph, from, dep.name.clone(), to);
1257                }
1258            }
1259        }
1260    }
1261    res
1262}
1263
1264fn cargo_to_crate_graph(
1265    load: FileLoader<'_>,
1266    rustc: Option<&(CargoWorkspace, WorkspaceBuildScripts)>,
1267    cargo: &CargoWorkspace,
1268    sysroot: &Sysroot,
1269    rustc_cfg: Vec<CfgAtom>,
1270    override_cfg: &CfgOverrides,
1271    build_scripts: &WorkspaceBuildScripts,
1272    set_test: bool,
1273    crate_ws_data: Arc<CrateWorkspaceData>,
1274) -> (CrateGraphBuilder, ProcMacroPaths) {
1275    let _p = tracing::info_span!("cargo_to_crate_graph").entered();
1276    let mut res = (CrateGraphBuilder::default(), ProcMacroPaths::default());
1277    let (crate_graph, proc_macros) = &mut res;
1278    let (public_deps, libproc_macro) = sysroot_to_crate_graph(
1279        crate_graph,
1280        sysroot,
1281        rustc_cfg.clone(),
1282        load,
1283        crate_ws_data.clone(),
1284    );
1285    let cargo_path = sysroot.tool_path(Tool::Cargo, cargo.workspace_root(), cargo.env());
1286
1287    let cfg_options = CfgOptions::from_iter(rustc_cfg);
1288
1289    // Mapping of a package to its library target
1290    let mut pkg_to_lib_crate = FxHashMap::default();
1291    let mut pkg_crates = FxHashMap::default();
1292    let workspace_proc_macro_cwd = Arc::new(cargo.workspace_root().to_path_buf());
1293
1294    // Next, create crates for each package, target pair
1295    for pkg in cargo.packages() {
1296        let cfg_options = {
1297            let mut cfg_options = cfg_options.clone();
1298
1299            if cargo[pkg].is_local {
1300                if set_test && !cargo.is_sysroot() {
1301                    // Add test cfg for local crates
1302                    cfg_options.insert_atom(sym::test);
1303                }
1304                cfg_options.insert_atom(sym::rust_analyzer);
1305            }
1306
1307            override_cfg.apply(&mut cfg_options, &cargo[pkg].name);
1308            cfg_options
1309        };
1310
1311        let mut lib_tgt = None;
1312        for &tgt in cargo[pkg].targets.iter() {
1313            let pkg_data = &cargo[pkg];
1314            if !matches!(cargo[tgt].kind, TargetKind::Lib { .. })
1315                && (!pkg_data.is_member || cargo.is_sysroot())
1316            {
1317                // For non-workspace-members, Cargo does not resolve dev-dependencies, so we don't
1318                // add any targets except the library target, since those will not work correctly if
1319                // they use dev-dependencies.
1320                // In fact, they can break quite badly if multiple client workspaces get merged:
1321                // https://github.com/rust-lang/rust-analyzer/issues/11300
1322                continue;
1323            }
1324            let &TargetData { ref name, kind, ref root, .. } = &cargo[tgt];
1325
1326            let Some(file_id) = load(root) else { continue };
1327
1328            let build_data = build_scripts.get_output(pkg);
1329            let crate_id = add_target_crate_root(
1330                crate_graph,
1331                proc_macros,
1332                cargo,
1333                pkg_data,
1334                build_data.zip(Some(build_scripts.error().is_some())),
1335                cfg_options.clone(),
1336                file_id,
1337                name,
1338                kind,
1339                if pkg_data.is_local {
1340                    if cargo.is_sysroot() {
1341                        CrateOrigin::Lang(LangCrateOrigin::from(&*pkg_data.name))
1342                    } else {
1343                        CrateOrigin::Local {
1344                            repo: pkg_data.repository.clone(),
1345                            name: Some(Symbol::intern(&pkg_data.name)),
1346                        }
1347                    }
1348                } else if cargo.is_sysroot() {
1349                    CrateOrigin::Lang(LangCrateOrigin::Dependency)
1350                } else {
1351                    CrateOrigin::Library {
1352                        repo: pkg_data.repository.clone(),
1353                        name: Symbol::intern(&pkg_data.name),
1354                    }
1355                },
1356                crate_ws_data.clone(),
1357                if pkg_data.is_member {
1358                    workspace_proc_macro_cwd.clone()
1359                } else {
1360                    Arc::new(pkg_data.manifest.parent().to_path_buf())
1361                },
1362                &cargo_path,
1363            );
1364            if let TargetKind::Lib { .. } = kind {
1365                lib_tgt = Some((crate_id, name.clone()));
1366                pkg_to_lib_crate.insert(pkg, crate_id);
1367            }
1368            // Even crates that don't set proc-macro = true are allowed to depend on proc_macro
1369            // (just none of the APIs work when called outside of a proc macro).
1370            if let Some(proc_macro) = libproc_macro {
1371                add_proc_macro_dep(
1372                    crate_graph,
1373                    crate_id,
1374                    proc_macro,
1375                    matches!(kind, TargetKind::Lib { is_proc_macro: true }),
1376                );
1377            }
1378
1379            pkg_crates.entry(pkg).or_insert_with(Vec::new).push((crate_id, kind));
1380        }
1381
1382        // Set deps to the core, std and to the lib target of the current package
1383        for &(from, kind) in pkg_crates.get(&pkg).into_iter().flatten() {
1384            // Add sysroot deps first so that a lib target named `core` etc. can overwrite them.
1385            public_deps.add_to_crate_graph(crate_graph, from);
1386
1387            // Add dep edge of all targets to the package's lib target
1388            if let Some((to, name)) = lib_tgt.clone()
1389                && to != from
1390                && kind != TargetKind::BuildScript
1391            {
1392                // (build script can not depend on its library target)
1393
1394                // For root projects with dashes in their name,
1395                // cargo metadata does not do any normalization,
1396                // so we do it ourselves currently
1397                let name = CrateName::normalize_dashes(&name);
1398                add_dep(crate_graph, from, name, to);
1399            }
1400        }
1401    }
1402
1403    let mut delayed_dev_deps = vec![];
1404
1405    // Now add a dep edge from all targets of upstream to the lib
1406    // target of downstream.
1407    for pkg in cargo.packages() {
1408        for dep in &cargo[pkg].dependencies {
1409            let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) else { continue };
1410            let Some(targets) = pkg_crates.get(&pkg) else { continue };
1411
1412            let name = CrateName::new(&dep.name).unwrap();
1413            for &(from, kind) in targets {
1414                // Build scripts may only depend on build dependencies.
1415                if (dep.kind == DepKind::Build) != (kind == TargetKind::BuildScript) {
1416                    continue;
1417                }
1418
1419                // If the dependency is a dev-dependency with both crates being member libraries of
1420                // the workspace we delay adding the edge. The reason can be read up on in
1421                // https://github.com/rust-lang/rust-analyzer/issues/14167
1422                // but in short, such an edge is able to cause some form of cycle in the crate graph
1423                // for normal dependencies. If we do run into a cycle like this, we want to prefer
1424                // the non dev-dependency edge, and so the easiest way to do that is by adding the
1425                // dev-dependency edges last.
1426                if dep.kind == DepKind::Dev
1427                    && matches!(kind, TargetKind::Lib { .. })
1428                    && cargo[dep.pkg].is_member
1429                    && cargo[pkg].is_member
1430                {
1431                    delayed_dev_deps.push((from, name.clone(), to));
1432                    continue;
1433                }
1434
1435                add_dep(crate_graph, from, name.clone(), to)
1436            }
1437        }
1438    }
1439
1440    for (from, name, to) in delayed_dev_deps {
1441        add_dep(crate_graph, from, name, to);
1442    }
1443
1444    if cargo.requires_rustc_private() {
1445        // If the user provided a path to rustc sources, we add all the rustc_private crates
1446        // and create dependencies on them for the crates which opt-in to that
1447        if let Some((rustc_workspace, rustc_build_scripts)) = rustc {
1448            handle_rustc_crates(
1449                crate_graph,
1450                proc_macros,
1451                &mut pkg_to_lib_crate,
1452                load,
1453                rustc_workspace,
1454                cargo,
1455                &public_deps,
1456                libproc_macro,
1457                &pkg_crates,
1458                &cfg_options,
1459                override_cfg,
1460                // FIXME: Remove this once rustc switched over to rust-project.json
1461                if rustc_workspace.workspace_root() == cargo.workspace_root() {
1462                    // the rustc workspace does not use the installed toolchain's proc-macro server
1463                    // so we need to make sure we don't use the pre compiled proc-macros there either
1464                    build_scripts
1465                } else {
1466                    rustc_build_scripts
1467                },
1468                // FIXME: This looks incorrect but I don't think this causes problems.
1469                crate_ws_data,
1470                &cargo_path,
1471            );
1472        }
1473    }
1474    res
1475}
1476
1477fn detached_file_to_crate_graph(
1478    rustc_cfg: Vec<CfgAtom>,
1479    load: FileLoader<'_>,
1480    detached_file: &ManifestPath,
1481    sysroot: &Sysroot,
1482    override_cfg: &CfgOverrides,
1483    set_test: bool,
1484    crate_ws_data: Arc<CrateWorkspaceData>,
1485) -> (CrateGraphBuilder, ProcMacroPaths) {
1486    let _p = tracing::info_span!("detached_file_to_crate_graph").entered();
1487    let mut crate_graph = CrateGraphBuilder::default();
1488    let (public_deps, _libproc_macro) = sysroot_to_crate_graph(
1489        &mut crate_graph,
1490        sysroot,
1491        rustc_cfg.clone(),
1492        load,
1493        // FIXME: This looks incorrect but I don't think this causes problems.
1494        crate_ws_data.clone(),
1495    );
1496
1497    let mut cfg_options = CfgOptions::from_iter(rustc_cfg);
1498    if set_test {
1499        cfg_options.insert_atom(sym::test);
1500    }
1501    cfg_options.insert_atom(sym::rust_analyzer);
1502    override_cfg.apply(&mut cfg_options, "");
1503    let cfg_options = cfg_options;
1504
1505    let file_id = match load(detached_file) {
1506        Some(file_id) => file_id,
1507        None => {
1508            error!("Failed to load detached file {:?}", detached_file);
1509            return (crate_graph, FxHashMap::default());
1510        }
1511    };
1512    let display_name = detached_file.file_stem().map(CrateDisplayName::from_canonical_name);
1513    let detached_file_crate = crate_graph.add_crate_root(
1514        file_id,
1515        Edition::CURRENT,
1516        display_name.clone(),
1517        None,
1518        cfg_options,
1519        None,
1520        Env::default(),
1521        CrateOrigin::Local {
1522            repo: None,
1523            name: display_name.map(|n| n.canonical_name().to_owned()),
1524        },
1525        Vec::new(),
1526        TargetKind::Lib { is_proc_macro: false },
1527        Arc::new(detached_file.parent().to_path_buf()),
1528        crate_ws_data,
1529    );
1530
1531    public_deps.add_to_crate_graph(&mut crate_graph, detached_file_crate);
1532    (crate_graph, FxHashMap::default())
1533}
1534
1535// FIXME: There shouldn't really be a need for duplicating all of this?
1536fn handle_rustc_crates(
1537    crate_graph: &mut CrateGraphBuilder,
1538    proc_macros: &mut ProcMacroPaths,
1539    pkg_to_lib_crate: &mut FxHashMap<Package, CrateBuilderId>,
1540    load: FileLoader<'_>,
1541    rustc_workspace: &CargoWorkspace,
1542    cargo: &CargoWorkspace,
1543    public_deps: &SysrootPublicDeps,
1544    libproc_macro: Option<CrateBuilderId>,
1545    pkg_crates: &FxHashMap<Package, Vec<(CrateBuilderId, TargetKind)>>,
1546    cfg_options: &CfgOptions,
1547    override_cfg: &CfgOverrides,
1548    build_scripts: &WorkspaceBuildScripts,
1549    crate_ws_data: Arc<CrateWorkspaceData>,
1550    cargo_path: &Utf8Path,
1551) {
1552    let mut rustc_pkg_crates = FxHashMap::default();
1553    // The root package of the rustc-dev component is rustc_driver, so we match that
1554    let root_pkg =
1555        rustc_workspace.packages().find(|&package| rustc_workspace[package].name == "rustc_driver");
1556    let workspace_proc_macro_cwd = Arc::new(cargo.workspace_root().to_path_buf());
1557    // The rustc workspace might be incomplete (such as if rustc-dev is not
1558    // installed for the current toolchain) and `rustc_source` is set to discover.
1559    if let Some(root_pkg) = root_pkg {
1560        // Iterate through every crate in the dependency subtree of rustc_driver using BFS
1561        let mut queue = VecDeque::new();
1562        queue.push_back(root_pkg);
1563        while let Some(pkg) = queue.pop_front() {
1564            // Don't duplicate packages if they are dependent on a diamond pattern
1565            // N.B. if this line is omitted, we try to analyze over 4_800_000 crates
1566            // which is not ideal
1567            if rustc_pkg_crates.contains_key(&pkg) {
1568                continue;
1569            }
1570            let pkg_data = &rustc_workspace[pkg];
1571            for dep in &pkg_data.dependencies {
1572                queue.push_back(dep.pkg);
1573            }
1574
1575            let mut cfg_options = cfg_options.clone();
1576            override_cfg.apply(&mut cfg_options, &pkg_data.name);
1577
1578            for &tgt in pkg_data.targets.iter() {
1579                let kind @ TargetKind::Lib { is_proc_macro } = rustc_workspace[tgt].kind else {
1580                    continue;
1581                };
1582                let pkg_crates = &mut rustc_pkg_crates.entry(pkg).or_insert_with(Vec::new);
1583                if let Some(file_id) = load(&rustc_workspace[tgt].root) {
1584                    let crate_id = add_target_crate_root(
1585                        crate_graph,
1586                        proc_macros,
1587                        rustc_workspace,
1588                        pkg_data,
1589                        build_scripts.get_output(pkg).zip(Some(build_scripts.error().is_some())),
1590                        cfg_options.clone(),
1591                        file_id,
1592                        &rustc_workspace[tgt].name,
1593                        kind,
1594                        CrateOrigin::Rustc { name: Symbol::intern(&pkg_data.name) },
1595                        crate_ws_data.clone(),
1596                        if pkg_data.is_member {
1597                            workspace_proc_macro_cwd.clone()
1598                        } else {
1599                            Arc::new(pkg_data.manifest.parent().to_path_buf())
1600                        },
1601                        cargo_path,
1602                    );
1603                    pkg_to_lib_crate.insert(pkg, crate_id);
1604                    // Add dependencies on core / std / alloc for this crate
1605                    public_deps.add_to_crate_graph(crate_graph, crate_id);
1606                    if let Some(proc_macro) = libproc_macro {
1607                        add_proc_macro_dep(crate_graph, crate_id, proc_macro, is_proc_macro);
1608                    }
1609                    pkg_crates.push(crate_id);
1610                }
1611            }
1612        }
1613    }
1614    // Now add a dep edge from all targets of upstream to the lib
1615    // target of downstream.
1616    for pkg in rustc_pkg_crates.keys().copied() {
1617        for dep in rustc_workspace[pkg].dependencies.iter() {
1618            let name = CrateName::new(&dep.name).unwrap();
1619            if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
1620                for &from in rustc_pkg_crates.get(&pkg).into_iter().flatten() {
1621                    add_dep(crate_graph, from, name.clone(), to);
1622                }
1623            }
1624        }
1625    }
1626    // Add a dependency on the rustc_private crates for all targets of each package
1627    // which opts in
1628    for dep in rustc_workspace.packages() {
1629        let name = CrateName::normalize_dashes(&rustc_workspace[dep].name);
1630
1631        if let Some(&to) = pkg_to_lib_crate.get(&dep) {
1632            for pkg in cargo.packages() {
1633                let package = &cargo[pkg];
1634                if !package.metadata.rustc_private {
1635                    continue;
1636                }
1637                for (from, _) in pkg_crates.get(&pkg).into_iter().flatten() {
1638                    // Avoid creating duplicate dependencies
1639                    // This avoids the situation where `from` depends on e.g. `arrayvec`, but
1640                    // `rust_analyzer` thinks that it should use the one from the `rustc_source`
1641                    // instead of the one from `crates.io`
1642                    if !crate_graph[*from].basic.dependencies.iter().any(|d| d.name == name) {
1643                        add_dep(crate_graph, *from, name.clone(), to);
1644                    }
1645                }
1646            }
1647        }
1648    }
1649}
1650
1651fn add_target_crate_root(
1652    crate_graph: &mut CrateGraphBuilder,
1653    proc_macros: &mut ProcMacroPaths,
1654    cargo: &CargoWorkspace,
1655    pkg: &PackageData,
1656    build_data: Option<(&BuildScriptOutput, bool)>,
1657    cfg_options: CfgOptions,
1658    file_id: FileId,
1659    cargo_crate_name: &str,
1660    kind: TargetKind,
1661    origin: CrateOrigin,
1662    crate_ws_data: Arc<CrateWorkspaceData>,
1663    proc_macro_cwd: Arc<AbsPathBuf>,
1664    cargo_path: &Utf8Path,
1665) -> CrateBuilderId {
1666    let edition = pkg.edition;
1667    let potential_cfg_options = if pkg.features.is_empty() {
1668        None
1669    } else {
1670        let mut potential_cfg_options = cfg_options.clone();
1671        potential_cfg_options.extend(
1672            pkg.features
1673                .iter()
1674                .map(|feat| CfgAtom::KeyValue { key: sym::feature, value: Symbol::intern(feat.0) }),
1675        );
1676        Some(potential_cfg_options)
1677    };
1678    let cfg_options = {
1679        let mut opts = cfg_options;
1680        for feature in pkg.active_features.iter() {
1681            opts.insert_key_value(sym::feature, Symbol::intern(feature));
1682        }
1683        if let Some(cfgs) = build_data.map(|(it, _)| &it.cfgs) {
1684            opts.extend(cfgs.iter().cloned());
1685        }
1686        opts
1687    };
1688
1689    let mut env = cargo.env().clone();
1690    inject_cargo_package_env(&mut env, pkg);
1691    inject_cargo_env(&mut env, cargo_path);
1692    inject_rustc_tool_env(&mut env, cargo_crate_name, kind);
1693
1694    if let Some(envs) = build_data.map(|(it, _)| &it.envs) {
1695        env.extend_from_other(envs);
1696    }
1697    let crate_id = crate_graph.add_crate_root(
1698        file_id,
1699        edition,
1700        Some(CrateDisplayName::from_canonical_name(cargo_crate_name)),
1701        Some(pkg.version.to_string()),
1702        cfg_options,
1703        potential_cfg_options,
1704        env,
1705        origin,
1706        Vec::new(),
1707        kind,
1708        proc_macro_cwd,
1709        crate_ws_data,
1710    );
1711    if let TargetKind::Lib { is_proc_macro: true } = kind {
1712        let proc_macro = match build_data {
1713            Some((BuildScriptOutput { proc_macro_dylib_path, .. }, has_errors)) => {
1714                match proc_macro_dylib_path {
1715                    ProcMacroDylibPath::Path(path) => {
1716                        Ok((cargo_crate_name.to_owned(), path.clone()))
1717                    }
1718                    ProcMacroDylibPath::NotBuilt => Err(ProcMacroLoadingError::NotYetBuilt),
1719                    ProcMacroDylibPath::NotProcMacro | ProcMacroDylibPath::DylibNotFound
1720                        if has_errors =>
1721                    {
1722                        Err(ProcMacroLoadingError::FailedToBuild)
1723                    }
1724                    ProcMacroDylibPath::NotProcMacro => {
1725                        Err(ProcMacroLoadingError::ExpectedProcMacroArtifact)
1726                    }
1727                    ProcMacroDylibPath::DylibNotFound => {
1728                        Err(ProcMacroLoadingError::MissingDylibPath)
1729                    }
1730                }
1731            }
1732            None => Err(ProcMacroLoadingError::NotYetBuilt),
1733        };
1734        proc_macros.insert(crate_id, proc_macro);
1735    }
1736
1737    crate_id
1738}
1739
1740#[derive(Default, Debug)]
1741struct SysrootPublicDeps {
1742    deps: Vec<(CrateName, CrateBuilderId, bool)>,
1743}
1744
1745impl SysrootPublicDeps {
1746    /// Makes `from` depend on the public sysroot crates.
1747    fn add_to_crate_graph(&self, crate_graph: &mut CrateGraphBuilder, from: CrateBuilderId) {
1748        for (name, krate, prelude) in &self.deps {
1749            add_dep_with_prelude(crate_graph, from, name.clone(), *krate, *prelude, true);
1750        }
1751    }
1752}
1753
1754fn extend_crate_graph_with_sysroot(
1755    crate_graph: &mut CrateGraphBuilder,
1756    mut sysroot_crate_graph: CrateGraphBuilder,
1757    mut sysroot_proc_macros: ProcMacroPaths,
1758) -> (SysrootPublicDeps, Option<CrateBuilderId>) {
1759    let mut pub_deps = vec![];
1760    let mut libproc_macro = None;
1761    for cid in sysroot_crate_graph.iter() {
1762        if let CrateOrigin::Lang(lang_crate) = sysroot_crate_graph[cid].basic.origin {
1763            match lang_crate {
1764                LangCrateOrigin::Test
1765                | LangCrateOrigin::Alloc
1766                | LangCrateOrigin::Core
1767                | LangCrateOrigin::Std => pub_deps.push((
1768                    CrateName::normalize_dashes(&lang_crate.to_string()),
1769                    cid,
1770                    !matches!(lang_crate, LangCrateOrigin::Test | LangCrateOrigin::Alloc),
1771                )),
1772                LangCrateOrigin::ProcMacro => libproc_macro = Some(cid),
1773                LangCrateOrigin::Other | LangCrateOrigin::Dependency => (),
1774            }
1775        }
1776    }
1777
1778    let mut marker_set = vec![];
1779    for &(_, cid, _) in pub_deps.iter() {
1780        marker_set.extend(sysroot_crate_graph.transitive_deps(cid));
1781    }
1782    if let Some(cid) = libproc_macro {
1783        marker_set.extend(sysroot_crate_graph.transitive_deps(cid));
1784    }
1785
1786    marker_set.sort();
1787    marker_set.dedup();
1788
1789    // Remove all crates except the ones we are interested in to keep the sysroot graph small.
1790    let removed_mapping = sysroot_crate_graph.remove_crates_except(&marker_set);
1791    sysroot_proc_macros = sysroot_proc_macros
1792        .into_iter()
1793        .filter_map(|(k, v)| Some((removed_mapping[k.into_raw().into_u32() as usize]?, v)))
1794        .collect();
1795    let mapping = crate_graph.extend(sysroot_crate_graph, &mut sysroot_proc_macros);
1796
1797    // Map the id through the removal mapping first, then through the crate graph extension mapping.
1798    pub_deps.iter_mut().for_each(|(_, cid, _)| {
1799        *cid = mapping[&removed_mapping[cid.into_raw().into_u32() as usize].unwrap()]
1800    });
1801    if let Some(libproc_macro) = &mut libproc_macro {
1802        *libproc_macro =
1803            mapping[&removed_mapping[libproc_macro.into_raw().into_u32() as usize].unwrap()];
1804    }
1805
1806    (SysrootPublicDeps { deps: pub_deps }, libproc_macro)
1807}
1808
1809fn sysroot_to_crate_graph(
1810    crate_graph: &mut CrateGraphBuilder,
1811    sysroot: &Sysroot,
1812    rustc_cfg: Vec<CfgAtom>,
1813    load: FileLoader<'_>,
1814    crate_ws_data: Arc<CrateWorkspaceData>,
1815) -> (SysrootPublicDeps, Option<CrateBuilderId>) {
1816    let _p = tracing::info_span!("sysroot_to_crate_graph").entered();
1817    match sysroot.workspace() {
1818        RustLibSrcWorkspace::Workspace { ws: cargo, .. } => {
1819            let (sysroot_cg, sysroot_pm) = cargo_to_crate_graph(
1820                load,
1821                None,
1822                cargo,
1823                &Sysroot::empty(),
1824                rustc_cfg,
1825                &CfgOverrides {
1826                    global: CfgDiff::new(
1827                        vec![
1828                            CfgAtom::Flag(sym::debug_assertions),
1829                            CfgAtom::Flag(sym::miri),
1830                            CfgAtom::Flag(sym::bootstrap),
1831                        ],
1832                        vec![CfgAtom::Flag(sym::test)],
1833                    ),
1834                    ..Default::default()
1835                },
1836                &WorkspaceBuildScripts::default(),
1837                false,
1838                crate_ws_data,
1839            );
1840
1841            extend_crate_graph_with_sysroot(crate_graph, sysroot_cg, sysroot_pm)
1842        }
1843        RustLibSrcWorkspace::Json(project_json) => {
1844            let (sysroot_cg, sysroot_pm) = project_json_to_crate_graph(
1845                rustc_cfg,
1846                load,
1847                project_json,
1848                &Sysroot::empty(),
1849                &FxHashMap::default(),
1850                &CfgOverrides {
1851                    global: CfgDiff::new(
1852                        vec![CfgAtom::Flag(sym::debug_assertions), CfgAtom::Flag(sym::miri)],
1853                        vec![],
1854                    ),
1855                    ..Default::default()
1856                },
1857                false,
1858                true,
1859                crate_ws_data,
1860            );
1861
1862            extend_crate_graph_with_sysroot(crate_graph, sysroot_cg, sysroot_pm)
1863        }
1864        RustLibSrcWorkspace::Stitched(stitched) => {
1865            let cfg_options = {
1866                let mut cfg_options = CfgOptions::default();
1867                cfg_options.extend(rustc_cfg);
1868                cfg_options.insert_atom(sym::debug_assertions);
1869                cfg_options.insert_atom(sym::miri);
1870                cfg_options
1871            };
1872            let sysroot_crates: FxHashMap<
1873                crate::sysroot::stitched::RustLibSrcCrate,
1874                CrateBuilderId,
1875            > = stitched
1876                .crates()
1877                .filter_map(|krate| {
1878                    let file_id = load(&stitched[krate].root)?;
1879
1880                    let display_name = CrateDisplayName::from_canonical_name(&stitched[krate].name);
1881                    let crate_id = crate_graph.add_crate_root(
1882                        file_id,
1883                        stitched.edition,
1884                        Some(display_name),
1885                        None,
1886                        cfg_options.clone(),
1887                        None,
1888                        Env::default(),
1889                        CrateOrigin::Lang(LangCrateOrigin::from(&*stitched[krate].name)),
1890                        Vec::new(),
1891                        TargetKind::Lib { is_proc_macro: false },
1892                        Arc::new(stitched[krate].root.parent().to_path_buf()),
1893                        crate_ws_data.clone(),
1894                    );
1895                    Some((krate, crate_id))
1896                })
1897                .collect();
1898
1899            for from in stitched.crates() {
1900                for &to in stitched[from].deps.iter() {
1901                    let name = CrateName::new(&stitched[to].name).unwrap();
1902                    if let (Some(&from), Some(&to)) =
1903                        (sysroot_crates.get(&from), sysroot_crates.get(&to))
1904                    {
1905                        add_dep(crate_graph, from, name, to);
1906                    }
1907                }
1908            }
1909
1910            let public_deps = SysrootPublicDeps {
1911                deps: stitched
1912                    .public_deps()
1913                    .filter_map(|(name, idx, prelude)| {
1914                        Some((name, *sysroot_crates.get(&idx)?, prelude))
1915                    })
1916                    .collect::<Vec<_>>(),
1917            };
1918
1919            let libproc_macro =
1920                stitched.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
1921            (public_deps, libproc_macro)
1922        }
1923        RustLibSrcWorkspace::Empty => (SysrootPublicDeps { deps: vec![] }, None),
1924    }
1925}
1926
1927fn add_dep(
1928    graph: &mut CrateGraphBuilder,
1929    from: CrateBuilderId,
1930    name: CrateName,
1931    to: CrateBuilderId,
1932) {
1933    add_dep_inner(graph, from, DependencyBuilder::new(name, to))
1934}
1935
1936fn add_dep_with_prelude(
1937    graph: &mut CrateGraphBuilder,
1938    from: CrateBuilderId,
1939    name: CrateName,
1940    to: CrateBuilderId,
1941    prelude: bool,
1942    sysroot: bool,
1943) {
1944    add_dep_inner(graph, from, DependencyBuilder::with_prelude(name, to, prelude, sysroot))
1945}
1946
1947fn add_proc_macro_dep(
1948    crate_graph: &mut CrateGraphBuilder,
1949    from: CrateBuilderId,
1950    to: CrateBuilderId,
1951    prelude: bool,
1952) {
1953    add_dep_with_prelude(
1954        crate_graph,
1955        from,
1956        CrateName::new("proc_macro").unwrap(),
1957        to,
1958        prelude,
1959        true,
1960    );
1961}
1962
1963fn add_dep_inner(graph: &mut CrateGraphBuilder, from: CrateBuilderId, dep: DependencyBuilder) {
1964    if let Err(err) = graph.add_dep(from, dep) {
1965        tracing::warn!("{}", err)
1966    }
1967}
1968
1969fn sysroot_metadata_config(
1970    config: &CargoConfig,
1971    workspace_root: &AbsPath,
1972    targets: &[String],
1973    toolchain_version: Option<Version>,
1974) -> CargoMetadataConfig {
1975    // If the target is a JSON path, prefix it with workspace root directory.
1976    // Since `cargo metadata` command for sysroot is run inside sysroots dir, it may fail to
1977    // locate the target file if it is given as a relative path.
1978    let targets = targets
1979        .iter()
1980        .map(|target| {
1981            if target.ends_with(".json") {
1982                // If `target` is an absolute path, this will replace the whole path.
1983                workspace_root.join(target).to_string()
1984            } else {
1985                target.to_owned()
1986            }
1987        })
1988        .collect();
1989
1990    CargoMetadataConfig {
1991        features: Default::default(),
1992        targets,
1993        // NOTE: Not passing extra_args / metadata_extra_args / config_path here is very
1994        // intentional. The sysroot config has nothing to do with the workspace's config, so it's
1995        // very unlikely to do the right thing (e.g. it'd could try to use vendored dependencies in
1996        // the project's config for libstd or what not).
1997        extra_args: Default::default(),
1998        metadata_extra_args: Default::default(),
1999        config_path: Default::default(),
2000        // FIXME: Passing extra_env is somewhat dubious here, for the same reason we don't pass
2001        // extra_args.
2002        extra_env: config.extra_env.clone(),
2003        toolchain_version,
2004        kind: CargoMetadataKind::Sysroot,
2005    }
2006}