]> git.lizzy.rs Git - rust.git/blob - crates/project_model/src/workspace.rs
5fd6487106810108aa1b357189f0446e35cd12d6
[rust.git] / crates / project_model / src / 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
5 use std::{collections::VecDeque, fmt, fs, path::Path, process::Command};
6
7 use anyhow::{Context, Result};
8 use base_db::{CrateDisplayName, CrateGraph, CrateId, CrateName, Edition, Env, FileId, ProcMacro};
9 use cargo_workspace::DepKind;
10 use cfg::CfgOptions;
11 use paths::{AbsPath, AbsPathBuf};
12 use proc_macro_api::ProcMacroClient;
13 use rustc_hash::{FxHashMap, FxHashSet};
14
15 use crate::{
16     build_data::{BuildDataResult, PackageBuildData, WorkspaceBuildData},
17     cargo_workspace,
18     cfg_flag::CfgFlag,
19     rustc_cfg,
20     sysroot::SysrootCrate,
21     utf8_stdout, BuildDataCollector, CargoConfig, CargoWorkspace, ProjectJson, ProjectManifest,
22     Sysroot, TargetKind,
23 };
24
25 /// `PackageRoot` describes a package root folder.
26 /// Which may be an external dependency, or a member of
27 /// the current workspace.
28 #[derive(Debug, Clone, Eq, PartialEq, Hash)]
29 pub struct PackageRoot {
30     /// Is a member of the current workspace
31     pub is_member: bool,
32     pub include: Vec<AbsPathBuf>,
33     pub exclude: Vec<AbsPathBuf>,
34 }
35
36 #[derive(Clone, Eq, PartialEq)]
37 pub enum ProjectWorkspace {
38     /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`.
39     Cargo {
40         cargo: CargoWorkspace,
41         sysroot: Sysroot,
42         rustc: Option<CargoWorkspace>,
43         /// Holds cfg flags for the current target. We get those by running
44         /// `rustc --print cfg`.
45         ///
46         /// FIXME: make this a per-crate map, as, eg, build.rs might have a
47         /// different target.
48         rustc_cfg: Vec<CfgFlag>,
49     },
50     /// Project workspace was manually specified using a `rust-project.json` file.
51     Json { project: ProjectJson, sysroot: Option<Sysroot>, rustc_cfg: Vec<CfgFlag> },
52 }
53
54 impl fmt::Debug for ProjectWorkspace {
55     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56         // Make sure this isn't too verbose.
57         match self {
58             ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg } => f
59                 .debug_struct("Cargo")
60                 .field("root", &cargo.workspace_root().file_name())
61                 .field("n_packages", &cargo.packages().len())
62                 .field("n_sysroot_crates", &sysroot.crates().len())
63                 .field(
64                     "n_rustc_compiler_crates",
65                     &rustc.as_ref().map_or(0, |rc| rc.packages().len()),
66                 )
67                 .field("n_rustc_cfg", &rustc_cfg.len())
68                 .finish(),
69             ProjectWorkspace::Json { project, sysroot, rustc_cfg } => {
70                 let mut debug_struct = f.debug_struct("Json");
71                 debug_struct.field("n_crates", &project.n_crates());
72                 if let Some(sysroot) = sysroot {
73                     debug_struct.field("n_sysroot_crates", &sysroot.crates().len());
74                 }
75                 debug_struct.field("n_rustc_cfg", &rustc_cfg.len());
76                 debug_struct.finish()
77             }
78         }
79     }
80 }
81
82 impl ProjectWorkspace {
83     pub fn load(
84         manifest: ProjectManifest,
85         config: &CargoConfig,
86         progress: &dyn Fn(String),
87     ) -> Result<ProjectWorkspace> {
88         let res = match manifest {
89             ProjectManifest::ProjectJson(project_json) => {
90                 let file = fs::read_to_string(&project_json).with_context(|| {
91                     format!("Failed to read json file {}", project_json.display())
92                 })?;
93                 let data = serde_json::from_str(&file).with_context(|| {
94                     format!("Failed to deserialize json file {}", project_json.display())
95                 })?;
96                 let project_location = project_json.parent().unwrap().to_path_buf();
97                 let project_json = ProjectJson::new(&project_location, data);
98                 ProjectWorkspace::load_inline(project_json, config.target.as_deref())?
99             }
100             ProjectManifest::CargoToml(cargo_toml) => {
101                 let cargo_version = utf8_stdout({
102                     let mut cmd = Command::new(toolchain::cargo());
103                     cmd.arg("--version");
104                     cmd
105                 })?;
106
107                 let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml, config, progress)
108                     .with_context(|| {
109                         format!(
110                             "Failed to read Cargo metadata from Cargo.toml file {}, {}",
111                             cargo_toml.display(),
112                             cargo_version
113                         )
114                     })?;
115
116                 let sysroot = if config.no_sysroot {
117                     Sysroot::default()
118                 } else {
119                     Sysroot::discover(&cargo_toml).with_context(|| {
120                         format!(
121                             "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?",
122                             cargo_toml.display()
123                         )
124                     })?
125                 };
126
127                 let rustc_dir = if let Some(rustc_source) = &config.rustc_source {
128                     use cargo_workspace::RustcSource;
129                     match rustc_source {
130                         RustcSource::Path(path) => Some(path.clone()),
131                         RustcSource::Discover => Sysroot::discover_rustc(&cargo_toml),
132                     }
133                 } else {
134                     None
135                 };
136
137                 let rustc = if let Some(rustc_dir) = rustc_dir {
138                     Some(
139                         CargoWorkspace::from_cargo_metadata(&rustc_dir, config, progress)
140                             .with_context(|| {
141                                 format!("Failed to read Cargo metadata for Rust sources")
142                             })?,
143                     )
144                 } else {
145                     None
146                 };
147
148                 let rustc_cfg = rustc_cfg::get(Some(&cargo_toml), config.target.as_deref());
149                 ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg }
150             }
151             ProjectManifest::DetachedFile(_) => {
152                 todo!("TODO kb")
153             }
154         };
155
156         Ok(res)
157     }
158
159     pub fn load_inline(
160         project_json: ProjectJson,
161         target: Option<&str>,
162     ) -> Result<ProjectWorkspace> {
163         let sysroot = match &project_json.sysroot_src {
164             Some(path) => Some(Sysroot::load(path)?),
165             None => None,
166         };
167         let rustc_cfg = rustc_cfg::get(None, target);
168         Ok(ProjectWorkspace::Json { project: project_json, sysroot, rustc_cfg })
169     }
170
171     /// Returns the roots for the current `ProjectWorkspace`
172     /// The return type contains the path and whether or not
173     /// the root is a member of the current workspace
174     pub fn to_roots(&self, build_data: Option<&BuildDataResult>) -> Vec<PackageRoot> {
175         match self {
176             ProjectWorkspace::Json { project, sysroot, rustc_cfg: _ } => project
177                 .crates()
178                 .map(|(_, krate)| PackageRoot {
179                     is_member: krate.is_workspace_member,
180                     include: krate.include.clone(),
181                     exclude: krate.exclude.clone(),
182                 })
183                 .collect::<FxHashSet<_>>()
184                 .into_iter()
185                 .chain(sysroot.as_ref().into_iter().flat_map(|sysroot| {
186                     sysroot.crates().map(move |krate| PackageRoot {
187                         is_member: false,
188                         include: vec![sysroot[krate].root_dir().to_path_buf()],
189                         exclude: Vec::new(),
190                     })
191                 }))
192                 .collect::<Vec<_>>(),
193             ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg: _ } => cargo
194                 .packages()
195                 .map(|pkg| {
196                     let is_member = cargo[pkg].is_member;
197                     let pkg_root = cargo[pkg].root().to_path_buf();
198
199                     let mut include = vec![pkg_root.clone()];
200                     include.extend(
201                         build_data
202                             .and_then(|it| it.get(cargo.workspace_root()))
203                             .and_then(|map| map.get(&cargo[pkg].id))
204                             .and_then(|it| it.out_dir.clone()),
205                     );
206
207                     let mut exclude = vec![pkg_root.join(".git")];
208                     if is_member {
209                         exclude.push(pkg_root.join("target"));
210                     } else {
211                         exclude.push(pkg_root.join("tests"));
212                         exclude.push(pkg_root.join("examples"));
213                         exclude.push(pkg_root.join("benches"));
214                     }
215                     PackageRoot { is_member, include, exclude }
216                 })
217                 .chain(sysroot.crates().map(|krate| PackageRoot {
218                     is_member: false,
219                     include: vec![sysroot[krate].root_dir().to_path_buf()],
220                     exclude: Vec::new(),
221                 }))
222                 .chain(rustc.into_iter().flat_map(|rustc| {
223                     rustc.packages().map(move |krate| PackageRoot {
224                         is_member: false,
225                         include: vec![rustc[krate].root().to_path_buf()],
226                         exclude: Vec::new(),
227                     })
228                 }))
229                 .collect(),
230         }
231     }
232
233     pub fn n_packages(&self) -> usize {
234         match self {
235             ProjectWorkspace::Json { project, .. } => project.n_crates(),
236             ProjectWorkspace::Cargo { cargo, sysroot, rustc, .. } => {
237                 let rustc_package_len = rustc.as_ref().map_or(0, |rc| rc.packages().len());
238                 cargo.packages().len() + sysroot.crates().len() + rustc_package_len
239             }
240         }
241     }
242
243     pub fn to_crate_graph(
244         &self,
245         build_data: Option<&BuildDataResult>,
246         proc_macro_client: Option<&ProcMacroClient>,
247         load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
248     ) -> CrateGraph {
249         let _p = profile::span("ProjectWorkspace::to_crate_graph");
250         let proc_macro_loader = |path: &Path| match proc_macro_client {
251             Some(client) => client.by_dylib_path(path),
252             None => Vec::new(),
253         };
254
255         let mut crate_graph = match self {
256             ProjectWorkspace::Json { project, sysroot, rustc_cfg } => project_json_to_crate_graph(
257                 rustc_cfg.clone(),
258                 &proc_macro_loader,
259                 load,
260                 project,
261                 sysroot,
262             ),
263             ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg } => cargo_to_crate_graph(
264                 rustc_cfg.clone(),
265                 &proc_macro_loader,
266                 load,
267                 cargo,
268                 build_data.and_then(|it| it.get(cargo.workspace_root())),
269                 sysroot,
270                 rustc,
271                 rustc.as_ref().zip(build_data).and_then(|(it, map)| map.get(it.workspace_root())),
272             ),
273         };
274         if crate_graph.patch_cfg_if() {
275             log::debug!("Patched std to depend on cfg-if")
276         } else {
277             log::debug!("Did not patch std to depend on cfg-if")
278         }
279         crate_graph
280     }
281
282     pub fn collect_build_data_configs(&self, collector: &mut BuildDataCollector) {
283         match self {
284             ProjectWorkspace::Cargo { cargo, .. } => {
285                 collector.add_config(&cargo.workspace_root(), cargo.build_data_config().clone());
286             }
287             _ => {}
288         }
289     }
290 }
291
292 fn project_json_to_crate_graph(
293     rustc_cfg: Vec<CfgFlag>,
294     proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>,
295     load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
296     project: &ProjectJson,
297     sysroot: &Option<Sysroot>,
298 ) -> CrateGraph {
299     let mut crate_graph = CrateGraph::default();
300     let sysroot_deps = sysroot
301         .as_ref()
302         .map(|sysroot| sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load));
303
304     let mut cfg_cache: FxHashMap<&str, Vec<CfgFlag>> = FxHashMap::default();
305     let crates: FxHashMap<CrateId, CrateId> = project
306         .crates()
307         .filter_map(|(crate_id, krate)| {
308             let file_path = &krate.root_module;
309             let file_id = load(&file_path)?;
310             Some((crate_id, krate, file_id))
311         })
312         .map(|(crate_id, krate, file_id)| {
313             let env = krate.env.clone().into_iter().collect();
314             let proc_macro = krate.proc_macro_dylib_path.clone().map(|it| proc_macro_loader(&it));
315
316             let target_cfgs = match krate.target.as_deref() {
317                 Some(target) => {
318                     cfg_cache.entry(target).or_insert_with(|| rustc_cfg::get(None, Some(target)))
319                 }
320                 None => &rustc_cfg,
321             };
322
323             let mut cfg_options = CfgOptions::default();
324             cfg_options.extend(target_cfgs.iter().chain(krate.cfg.iter()).cloned());
325             (
326                 crate_id,
327                 crate_graph.add_crate_root(
328                     file_id,
329                     krate.edition,
330                     krate.display_name.clone(),
331                     cfg_options,
332                     env,
333                     proc_macro.unwrap_or_default(),
334                 ),
335             )
336         })
337         .collect();
338
339     for (from, krate) in project.crates() {
340         if let Some(&from) = crates.get(&from) {
341             if let Some((public_deps, _proc_macro)) = &sysroot_deps {
342                 for (name, to) in public_deps.iter() {
343                     add_dep(&mut crate_graph, from, name.clone(), *to)
344                 }
345             }
346
347             for dep in &krate.deps {
348                 if let Some(&to) = crates.get(&dep.crate_id) {
349                     add_dep(&mut crate_graph, from, dep.name.clone(), to)
350                 }
351             }
352         }
353     }
354     crate_graph
355 }
356
357 fn cargo_to_crate_graph(
358     rustc_cfg: Vec<CfgFlag>,
359     proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>,
360     load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
361     cargo: &CargoWorkspace,
362     build_data_map: Option<&WorkspaceBuildData>,
363     sysroot: &Sysroot,
364     rustc: &Option<CargoWorkspace>,
365     rustc_build_data_map: Option<&WorkspaceBuildData>,
366 ) -> CrateGraph {
367     let _p = profile::span("cargo_to_crate_graph");
368     let mut crate_graph = CrateGraph::default();
369     let (public_deps, libproc_macro) =
370         sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load);
371
372     let mut cfg_options = CfgOptions::default();
373     cfg_options.extend(rustc_cfg);
374
375     let mut pkg_to_lib_crate = FxHashMap::default();
376
377     // Add test cfg for non-sysroot crates
378     cfg_options.insert_atom("test".into());
379     cfg_options.insert_atom("debug_assertions".into());
380
381     let mut pkg_crates = FxHashMap::default();
382     // Does any crate signal to rust-analyzer that they need the rustc_private crates?
383     let mut has_private = false;
384     // Next, create crates for each package, target pair
385     for pkg in cargo.packages() {
386         has_private |= cargo[pkg].metadata.rustc_private;
387         let mut lib_tgt = None;
388         for &tgt in cargo[pkg].targets.iter() {
389             if let Some(file_id) = load(&cargo[tgt].root) {
390                 let crate_id = add_target_crate_root(
391                     &mut crate_graph,
392                     &cargo[pkg],
393                     build_data_map.and_then(|it| it.get(&cargo[pkg].id)),
394                     &cfg_options,
395                     proc_macro_loader,
396                     file_id,
397                     &cargo[tgt].name,
398                 );
399                 if cargo[tgt].kind == TargetKind::Lib {
400                     lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
401                     pkg_to_lib_crate.insert(pkg, crate_id);
402                 }
403                 if cargo[tgt].is_proc_macro {
404                     if let Some(proc_macro) = libproc_macro {
405                         add_dep(
406                             &mut crate_graph,
407                             crate_id,
408                             CrateName::new("proc_macro").unwrap(),
409                             proc_macro,
410                         );
411                     }
412                 }
413
414                 pkg_crates.entry(pkg).or_insert_with(Vec::new).push((crate_id, cargo[tgt].kind));
415             }
416         }
417
418         // Set deps to the core, std and to the lib target of the current package
419         for (from, kind) in pkg_crates.get(&pkg).into_iter().flatten() {
420             if let Some((to, name)) = lib_tgt.clone() {
421                 if to != *from && *kind != TargetKind::BuildScript {
422                     // (build script can not depend on its library target)
423
424                     // For root projects with dashes in their name,
425                     // cargo metadata does not do any normalization,
426                     // so we do it ourselves currently
427                     let name = CrateName::normalize_dashes(&name);
428                     add_dep(&mut crate_graph, *from, name, to);
429                 }
430             }
431             for (name, krate) in public_deps.iter() {
432                 add_dep(&mut crate_graph, *from, name.clone(), *krate);
433             }
434         }
435     }
436
437     // Now add a dep edge from all targets of upstream to the lib
438     // target of downstream.
439     for pkg in cargo.packages() {
440         for dep in cargo[pkg].dependencies.iter() {
441             let name = CrateName::new(&dep.name).unwrap();
442             if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
443                 for (from, kind) in pkg_crates.get(&pkg).into_iter().flatten() {
444                     if dep.kind == DepKind::Build && *kind != TargetKind::BuildScript {
445                         // Only build scripts may depend on build dependencies.
446                         continue;
447                     }
448                     if dep.kind != DepKind::Build && *kind == TargetKind::BuildScript {
449                         // Build scripts may only depend on build dependencies.
450                         continue;
451                     }
452
453                     add_dep(&mut crate_graph, *from, name.clone(), to)
454                 }
455             }
456         }
457     }
458
459     if has_private {
460         // If the user provided a path to rustc sources, we add all the rustc_private crates
461         // and create dependencies on them for the crates which opt-in to that
462         if let Some(rustc_workspace) = rustc {
463             handle_rustc_crates(
464                 rustc_workspace,
465                 load,
466                 &mut crate_graph,
467                 rustc_build_data_map,
468                 &cfg_options,
469                 proc_macro_loader,
470                 &mut pkg_to_lib_crate,
471                 &public_deps,
472                 cargo,
473                 &pkg_crates,
474             );
475         }
476     }
477     crate_graph
478 }
479
480 fn handle_rustc_crates(
481     rustc_workspace: &CargoWorkspace,
482     load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
483     crate_graph: &mut CrateGraph,
484     rustc_build_data_map: Option<&WorkspaceBuildData>,
485     cfg_options: &CfgOptions,
486     proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>,
487     pkg_to_lib_crate: &mut FxHashMap<la_arena::Idx<crate::PackageData>, CrateId>,
488     public_deps: &[(CrateName, CrateId)],
489     cargo: &CargoWorkspace,
490     pkg_crates: &FxHashMap<la_arena::Idx<crate::PackageData>, Vec<(CrateId, TargetKind)>>,
491 ) {
492     let mut rustc_pkg_crates = FxHashMap::default();
493     // The root package of the rustc-dev component is rustc_driver, so we match that
494     let root_pkg =
495         rustc_workspace.packages().find(|package| rustc_workspace[*package].name == "rustc_driver");
496     // The rustc workspace might be incomplete (such as if rustc-dev is not
497     // installed for the current toolchain) and `rustcSource` is set to discover.
498     if let Some(root_pkg) = root_pkg {
499         // Iterate through every crate in the dependency subtree of rustc_driver using BFS
500         let mut queue = VecDeque::new();
501         queue.push_back(root_pkg);
502         while let Some(pkg) = queue.pop_front() {
503             // Don't duplicate packages if they are dependended on a diamond pattern
504             // N.B. if this line is ommitted, we try to analyse over 4_800_000 crates
505             // which is not ideal
506             if rustc_pkg_crates.contains_key(&pkg) {
507                 continue;
508             }
509             for dep in &rustc_workspace[pkg].dependencies {
510                 queue.push_back(dep.pkg);
511             }
512             for &tgt in rustc_workspace[pkg].targets.iter() {
513                 if rustc_workspace[tgt].kind != TargetKind::Lib {
514                     continue;
515                 }
516                 if let Some(file_id) = load(&rustc_workspace[tgt].root) {
517                     let crate_id = add_target_crate_root(
518                         crate_graph,
519                         &rustc_workspace[pkg],
520                         rustc_build_data_map.and_then(|it| it.get(&rustc_workspace[pkg].id)),
521                         &cfg_options,
522                         proc_macro_loader,
523                         file_id,
524                         &rustc_workspace[tgt].name,
525                     );
526                     pkg_to_lib_crate.insert(pkg, crate_id);
527                     // Add dependencies on core / std / alloc for this crate
528                     for (name, krate) in public_deps.iter() {
529                         add_dep(crate_graph, crate_id, name.clone(), *krate);
530                     }
531                     rustc_pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
532                 }
533             }
534         }
535     }
536     // Now add a dep edge from all targets of upstream to the lib
537     // target of downstream.
538     for pkg in rustc_pkg_crates.keys().copied() {
539         for dep in rustc_workspace[pkg].dependencies.iter() {
540             let name = CrateName::new(&dep.name).unwrap();
541             if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
542                 for &from in rustc_pkg_crates.get(&pkg).into_iter().flatten() {
543                     add_dep(crate_graph, from, name.clone(), to);
544                 }
545             }
546         }
547     }
548     // Add a dependency on the rustc_private crates for all targets of each package
549     // which opts in
550     for dep in rustc_workspace.packages() {
551         let name = CrateName::normalize_dashes(&rustc_workspace[dep].name);
552
553         if let Some(&to) = pkg_to_lib_crate.get(&dep) {
554             for pkg in cargo.packages() {
555                 let package = &cargo[pkg];
556                 if !package.metadata.rustc_private {
557                     continue;
558                 }
559                 for (from, _) in pkg_crates.get(&pkg).into_iter().flatten() {
560                     // Avoid creating duplicate dependencies
561                     // This avoids the situation where `from` depends on e.g. `arrayvec`, but
562                     // `rust_analyzer` thinks that it should use the one from the `rustcSource`
563                     // instead of the one from `crates.io`
564                     if !crate_graph[*from].dependencies.iter().any(|d| d.name == name) {
565                         add_dep(crate_graph, *from, name.clone(), to);
566                     }
567                 }
568             }
569         }
570     }
571 }
572
573 fn add_target_crate_root(
574     crate_graph: &mut CrateGraph,
575     pkg: &cargo_workspace::PackageData,
576     build_data: Option<&PackageBuildData>,
577     cfg_options: &CfgOptions,
578     proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>,
579     file_id: FileId,
580     cargo_name: &str,
581 ) -> CrateId {
582     let edition = pkg.edition;
583     let cfg_options = {
584         let mut opts = cfg_options.clone();
585         for feature in pkg.active_features.iter() {
586             opts.insert_key_value("feature".into(), feature.into());
587         }
588         if let Some(cfgs) = build_data.as_ref().map(|it| &it.cfgs) {
589             opts.extend(cfgs.iter().cloned());
590         }
591         opts
592     };
593
594     let mut env = Env::default();
595     if let Some(envs) = build_data.map(|it| &it.envs) {
596         for (k, v) in envs {
597             env.set(k, v.clone());
598         }
599     }
600
601     let proc_macro = build_data
602         .as_ref()
603         .and_then(|it| it.proc_macro_dylib_path.as_ref())
604         .map(|it| proc_macro_loader(&it))
605         .unwrap_or_default();
606
607     let display_name = CrateDisplayName::from_canonical_name(cargo_name.to_string());
608     let crate_id = crate_graph.add_crate_root(
609         file_id,
610         edition,
611         Some(display_name),
612         cfg_options,
613         env,
614         proc_macro,
615     );
616
617     crate_id
618 }
619
620 fn sysroot_to_crate_graph(
621     crate_graph: &mut CrateGraph,
622     sysroot: &Sysroot,
623     rustc_cfg: Vec<CfgFlag>,
624     load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
625 ) -> (Vec<(CrateName, CrateId)>, Option<CrateId>) {
626     let _p = profile::span("sysroot_to_crate_graph");
627     let mut cfg_options = CfgOptions::default();
628     cfg_options.extend(rustc_cfg);
629     let sysroot_crates: FxHashMap<SysrootCrate, CrateId> = sysroot
630         .crates()
631         .filter_map(|krate| {
632             let file_id = load(&sysroot[krate].root)?;
633
634             let env = Env::default();
635             let proc_macro = vec![];
636             let display_name = CrateDisplayName::from_canonical_name(sysroot[krate].name.clone());
637             let crate_id = crate_graph.add_crate_root(
638                 file_id,
639                 Edition::Edition2018,
640                 Some(display_name),
641                 cfg_options.clone(),
642                 env,
643                 proc_macro,
644             );
645             Some((krate, crate_id))
646         })
647         .collect();
648
649     for from in sysroot.crates() {
650         for &to in sysroot[from].deps.iter() {
651             let name = CrateName::new(&sysroot[to].name).unwrap();
652             if let (Some(&from), Some(&to)) = (sysroot_crates.get(&from), sysroot_crates.get(&to)) {
653                 add_dep(crate_graph, from, name, to);
654             }
655         }
656     }
657
658     let public_deps = sysroot
659         .public_deps()
660         .map(|(name, idx)| (CrateName::new(name).unwrap(), sysroot_crates[&idx]))
661         .collect::<Vec<_>>();
662
663     let libproc_macro = sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
664     (public_deps, libproc_macro)
665 }
666
667 fn add_dep(graph: &mut CrateGraph, from: CrateId, name: CrateName, to: CrateId) {
668     if let Err(err) = graph.add_dep(from, name, to) {
669         log::error!("{}", err)
670     }
671 }