]> git.lizzy.rs Git - rust.git/blob - crates/project_model/src/workspace.rs
Merge #8795
[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         };
152
153         Ok(res)
154     }
155
156     pub fn load_inline(
157         project_json: ProjectJson,
158         target: Option<&str>,
159     ) -> Result<ProjectWorkspace> {
160         let sysroot = match &project_json.sysroot_src {
161             Some(path) => Some(Sysroot::load(path)?),
162             None => None,
163         };
164         let rustc_cfg = rustc_cfg::get(None, target);
165         Ok(ProjectWorkspace::Json { project: project_json, sysroot, rustc_cfg })
166     }
167
168     /// Returns the roots for the current `ProjectWorkspace`
169     /// The return type contains the path and whether or not
170     /// the root is a member of the current workspace
171     pub fn to_roots(&self, build_data: Option<&BuildDataResult>) -> Vec<PackageRoot> {
172         match self {
173             ProjectWorkspace::Json { project, sysroot, rustc_cfg: _ } => project
174                 .crates()
175                 .map(|(_, krate)| PackageRoot {
176                     is_member: krate.is_workspace_member,
177                     include: krate.include.clone(),
178                     exclude: krate.exclude.clone(),
179                 })
180                 .collect::<FxHashSet<_>>()
181                 .into_iter()
182                 .chain(sysroot.as_ref().into_iter().flat_map(|sysroot| {
183                     sysroot.crates().map(move |krate| PackageRoot {
184                         is_member: false,
185                         include: vec![sysroot[krate].root_dir().to_path_buf()],
186                         exclude: Vec::new(),
187                     })
188                 }))
189                 .collect::<Vec<_>>(),
190             ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg: _ } => cargo
191                 .packages()
192                 .map(|pkg| {
193                     let is_member = cargo[pkg].is_member;
194                     let pkg_root = cargo[pkg].root().to_path_buf();
195
196                     let mut include = vec![pkg_root.clone()];
197                     include.extend(
198                         build_data
199                             .and_then(|it| it.get(cargo.workspace_root()))
200                             .and_then(|map| map.get(&cargo[pkg].id))
201                             .and_then(|it| it.out_dir.clone()),
202                     );
203
204                     let mut exclude = vec![pkg_root.join(".git")];
205                     if is_member {
206                         exclude.push(pkg_root.join("target"));
207                     } else {
208                         exclude.push(pkg_root.join("tests"));
209                         exclude.push(pkg_root.join("examples"));
210                         exclude.push(pkg_root.join("benches"));
211                     }
212                     PackageRoot { is_member, include, exclude }
213                 })
214                 .chain(sysroot.crates().map(|krate| PackageRoot {
215                     is_member: false,
216                     include: vec![sysroot[krate].root_dir().to_path_buf()],
217                     exclude: Vec::new(),
218                 }))
219                 .chain(rustc.into_iter().flat_map(|rustc| {
220                     rustc.packages().map(move |krate| PackageRoot {
221                         is_member: false,
222                         include: vec![rustc[krate].root().to_path_buf()],
223                         exclude: Vec::new(),
224                     })
225                 }))
226                 .collect(),
227         }
228     }
229
230     pub fn n_packages(&self) -> usize {
231         match self {
232             ProjectWorkspace::Json { project, .. } => project.n_crates(),
233             ProjectWorkspace::Cargo { cargo, sysroot, rustc, .. } => {
234                 let rustc_package_len = rustc.as_ref().map_or(0, |rc| rc.packages().len());
235                 cargo.packages().len() + sysroot.crates().len() + rustc_package_len
236             }
237         }
238     }
239
240     pub fn to_crate_graph(
241         &self,
242         build_data: Option<&BuildDataResult>,
243         proc_macro_client: Option<&ProcMacroClient>,
244         load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
245     ) -> CrateGraph {
246         let _p = profile::span("ProjectWorkspace::to_crate_graph");
247         let proc_macro_loader = |path: &Path| match proc_macro_client {
248             Some(client) => client.by_dylib_path(path),
249             None => Vec::new(),
250         };
251
252         let mut crate_graph = match self {
253             ProjectWorkspace::Json { project, sysroot, rustc_cfg } => project_json_to_crate_graph(
254                 rustc_cfg.clone(),
255                 &proc_macro_loader,
256                 load,
257                 project,
258                 sysroot,
259             ),
260             ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg } => cargo_to_crate_graph(
261                 rustc_cfg.clone(),
262                 &proc_macro_loader,
263                 load,
264                 cargo,
265                 build_data.and_then(|it| it.get(cargo.workspace_root())),
266                 sysroot,
267                 rustc,
268                 rustc.as_ref().zip(build_data).and_then(|(it, map)| map.get(it.workspace_root())),
269             ),
270         };
271         if crate_graph.patch_cfg_if() {
272             log::debug!("Patched std to depend on cfg-if")
273         } else {
274             log::debug!("Did not patch std to depend on cfg-if")
275         }
276         crate_graph
277     }
278
279     pub fn collect_build_data_configs(&self, collector: &mut BuildDataCollector) {
280         match self {
281             ProjectWorkspace::Cargo { cargo, .. } => {
282                 collector.add_config(&cargo.workspace_root(), cargo.build_data_config().clone());
283             }
284             _ => {}
285         }
286     }
287 }
288
289 fn project_json_to_crate_graph(
290     rustc_cfg: Vec<CfgFlag>,
291     proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>,
292     load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
293     project: &ProjectJson,
294     sysroot: &Option<Sysroot>,
295 ) -> CrateGraph {
296     let mut crate_graph = CrateGraph::default();
297     let sysroot_deps = sysroot
298         .as_ref()
299         .map(|sysroot| sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load));
300
301     let mut cfg_cache: FxHashMap<&str, Vec<CfgFlag>> = FxHashMap::default();
302     let crates: FxHashMap<CrateId, CrateId> = project
303         .crates()
304         .filter_map(|(crate_id, krate)| {
305             let file_path = &krate.root_module;
306             let file_id = load(&file_path)?;
307             Some((crate_id, krate, file_id))
308         })
309         .map(|(crate_id, krate, file_id)| {
310             let env = krate.env.clone().into_iter().collect();
311             let proc_macro = krate.proc_macro_dylib_path.clone().map(|it| proc_macro_loader(&it));
312
313             let target_cfgs = match krate.target.as_deref() {
314                 Some(target) => {
315                     cfg_cache.entry(target).or_insert_with(|| rustc_cfg::get(None, Some(target)))
316                 }
317                 None => &rustc_cfg,
318             };
319
320             let mut cfg_options = CfgOptions::default();
321             cfg_options.extend(target_cfgs.iter().chain(krate.cfg.iter()).cloned());
322             (
323                 crate_id,
324                 crate_graph.add_crate_root(
325                     file_id,
326                     krate.edition,
327                     krate.display_name.clone(),
328                     cfg_options,
329                     env,
330                     proc_macro.unwrap_or_default(),
331                 ),
332             )
333         })
334         .collect();
335
336     for (from, krate) in project.crates() {
337         if let Some(&from) = crates.get(&from) {
338             if let Some((public_deps, _proc_macro)) = &sysroot_deps {
339                 for (name, to) in public_deps.iter() {
340                     add_dep(&mut crate_graph, from, name.clone(), *to)
341                 }
342             }
343
344             for dep in &krate.deps {
345                 if let Some(&to) = crates.get(&dep.crate_id) {
346                     add_dep(&mut crate_graph, from, dep.name.clone(), to)
347                 }
348             }
349         }
350     }
351     crate_graph
352 }
353
354 fn cargo_to_crate_graph(
355     rustc_cfg: Vec<CfgFlag>,
356     proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>,
357     load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
358     cargo: &CargoWorkspace,
359     build_data_map: Option<&WorkspaceBuildData>,
360     sysroot: &Sysroot,
361     rustc: &Option<CargoWorkspace>,
362     rustc_build_data_map: Option<&WorkspaceBuildData>,
363 ) -> CrateGraph {
364     let _p = profile::span("cargo_to_crate_graph");
365     let mut crate_graph = CrateGraph::default();
366     let (public_deps, libproc_macro) =
367         sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load);
368
369     let mut cfg_options = CfgOptions::default();
370     cfg_options.extend(rustc_cfg);
371
372     let mut pkg_to_lib_crate = FxHashMap::default();
373
374     // Add test cfg for non-sysroot crates
375     cfg_options.insert_atom("test".into());
376     cfg_options.insert_atom("debug_assertions".into());
377
378     let mut pkg_crates = FxHashMap::default();
379     // Does any crate signal to rust-analyzer that they need the rustc_private crates?
380     let mut has_private = false;
381     // Next, create crates for each package, target pair
382     for pkg in cargo.packages() {
383         has_private |= cargo[pkg].metadata.rustc_private;
384         let mut lib_tgt = None;
385         for &tgt in cargo[pkg].targets.iter() {
386             if let Some(file_id) = load(&cargo[tgt].root) {
387                 let crate_id = add_target_crate_root(
388                     &mut crate_graph,
389                     &cargo[pkg],
390                     build_data_map.and_then(|it| it.get(&cargo[pkg].id)),
391                     &cfg_options,
392                     proc_macro_loader,
393                     file_id,
394                     &cargo[tgt].name,
395                 );
396                 if cargo[tgt].kind == TargetKind::Lib {
397                     lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
398                     pkg_to_lib_crate.insert(pkg, crate_id);
399                 }
400                 if cargo[tgt].is_proc_macro {
401                     if let Some(proc_macro) = libproc_macro {
402                         add_dep(
403                             &mut crate_graph,
404                             crate_id,
405                             CrateName::new("proc_macro").unwrap(),
406                             proc_macro,
407                         );
408                     }
409                 }
410
411                 pkg_crates.entry(pkg).or_insert_with(Vec::new).push((crate_id, cargo[tgt].kind));
412             }
413         }
414
415         // Set deps to the core, std and to the lib target of the current package
416         for (from, kind) in pkg_crates.get(&pkg).into_iter().flatten() {
417             if let Some((to, name)) = lib_tgt.clone() {
418                 if to != *from && *kind != TargetKind::BuildScript {
419                     // (build script can not depend on its library target)
420
421                     // For root projects with dashes in their name,
422                     // cargo metadata does not do any normalization,
423                     // so we do it ourselves currently
424                     let name = CrateName::normalize_dashes(&name);
425                     add_dep(&mut crate_graph, *from, name, to);
426                 }
427             }
428             for (name, krate) in public_deps.iter() {
429                 add_dep(&mut crate_graph, *from, name.clone(), *krate);
430             }
431         }
432     }
433
434     // Now add a dep edge from all targets of upstream to the lib
435     // target of downstream.
436     for pkg in cargo.packages() {
437         for dep in cargo[pkg].dependencies.iter() {
438             let name = CrateName::new(&dep.name).unwrap();
439             if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
440                 for (from, kind) in pkg_crates.get(&pkg).into_iter().flatten() {
441                     if dep.kind == DepKind::Build && *kind != TargetKind::BuildScript {
442                         // Only build scripts may depend on build dependencies.
443                         continue;
444                     }
445                     if dep.kind != DepKind::Build && *kind == TargetKind::BuildScript {
446                         // Build scripts may only depend on build dependencies.
447                         continue;
448                     }
449
450                     add_dep(&mut crate_graph, *from, name.clone(), to)
451                 }
452             }
453         }
454     }
455
456     if has_private {
457         // If the user provided a path to rustc sources, we add all the rustc_private crates
458         // and create dependencies on them for the crates which opt-in to that
459         if let Some(rustc_workspace) = rustc {
460             handle_rustc_crates(
461                 rustc_workspace,
462                 load,
463                 &mut crate_graph,
464                 rustc_build_data_map,
465                 &cfg_options,
466                 proc_macro_loader,
467                 &mut pkg_to_lib_crate,
468                 &public_deps,
469                 cargo,
470                 &pkg_crates,
471             );
472         }
473     }
474     crate_graph
475 }
476
477 fn handle_rustc_crates(
478     rustc_workspace: &CargoWorkspace,
479     load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
480     crate_graph: &mut CrateGraph,
481     rustc_build_data_map: Option<&WorkspaceBuildData>,
482     cfg_options: &CfgOptions,
483     proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>,
484     pkg_to_lib_crate: &mut FxHashMap<la_arena::Idx<crate::PackageData>, CrateId>,
485     public_deps: &[(CrateName, CrateId)],
486     cargo: &CargoWorkspace,
487     pkg_crates: &FxHashMap<la_arena::Idx<crate::PackageData>, Vec<(CrateId, TargetKind)>>,
488 ) {
489     let mut rustc_pkg_crates = FxHashMap::default();
490     // The root package of the rustc-dev component is rustc_driver, so we match that
491     let root_pkg =
492         rustc_workspace.packages().find(|package| rustc_workspace[*package].name == "rustc_driver");
493     // The rustc workspace might be incomplete (such as if rustc-dev is not
494     // installed for the current toolchain) and `rustcSource` is set to discover.
495     if let Some(root_pkg) = root_pkg {
496         // Iterate through every crate in the dependency subtree of rustc_driver using BFS
497         let mut queue = VecDeque::new();
498         queue.push_back(root_pkg);
499         while let Some(pkg) = queue.pop_front() {
500             // Don't duplicate packages if they are dependended on a diamond pattern
501             // N.B. if this line is ommitted, we try to analyse over 4_800_000 crates
502             // which is not ideal
503             if rustc_pkg_crates.contains_key(&pkg) {
504                 continue;
505             }
506             for dep in &rustc_workspace[pkg].dependencies {
507                 queue.push_back(dep.pkg);
508             }
509             for &tgt in rustc_workspace[pkg].targets.iter() {
510                 if rustc_workspace[tgt].kind != TargetKind::Lib {
511                     continue;
512                 }
513                 if let Some(file_id) = load(&rustc_workspace[tgt].root) {
514                     let crate_id = add_target_crate_root(
515                         crate_graph,
516                         &rustc_workspace[pkg],
517                         rustc_build_data_map.and_then(|it| it.get(&rustc_workspace[pkg].id)),
518                         &cfg_options,
519                         proc_macro_loader,
520                         file_id,
521                         &rustc_workspace[tgt].name,
522                     );
523                     pkg_to_lib_crate.insert(pkg, crate_id);
524                     // Add dependencies on core / std / alloc for this crate
525                     for (name, krate) in public_deps.iter() {
526                         add_dep(crate_graph, crate_id, name.clone(), *krate);
527                     }
528                     rustc_pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
529                 }
530             }
531         }
532     }
533     // Now add a dep edge from all targets of upstream to the lib
534     // target of downstream.
535     for pkg in rustc_pkg_crates.keys().copied() {
536         for dep in rustc_workspace[pkg].dependencies.iter() {
537             let name = CrateName::new(&dep.name).unwrap();
538             if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
539                 for &from in rustc_pkg_crates.get(&pkg).into_iter().flatten() {
540                     add_dep(crate_graph, from, name.clone(), to);
541                 }
542             }
543         }
544     }
545     // Add a dependency on the rustc_private crates for all targets of each package
546     // which opts in
547     for dep in rustc_workspace.packages() {
548         let name = CrateName::normalize_dashes(&rustc_workspace[dep].name);
549
550         if let Some(&to) = pkg_to_lib_crate.get(&dep) {
551             for pkg in cargo.packages() {
552                 let package = &cargo[pkg];
553                 if !package.metadata.rustc_private {
554                     continue;
555                 }
556                 for (from, _) in pkg_crates.get(&pkg).into_iter().flatten() {
557                     // Avoid creating duplicate dependencies
558                     // This avoids the situation where `from` depends on e.g. `arrayvec`, but
559                     // `rust_analyzer` thinks that it should use the one from the `rustcSource`
560                     // instead of the one from `crates.io`
561                     if !crate_graph[*from].dependencies.iter().any(|d| d.name == name) {
562                         add_dep(crate_graph, *from, name.clone(), to);
563                     }
564                 }
565             }
566         }
567     }
568 }
569
570 fn add_target_crate_root(
571     crate_graph: &mut CrateGraph,
572     pkg: &cargo_workspace::PackageData,
573     build_data: Option<&PackageBuildData>,
574     cfg_options: &CfgOptions,
575     proc_macro_loader: &dyn Fn(&Path) -> Vec<ProcMacro>,
576     file_id: FileId,
577     cargo_name: &str,
578 ) -> CrateId {
579     let edition = pkg.edition;
580     let cfg_options = {
581         let mut opts = cfg_options.clone();
582         for feature in pkg.active_features.iter() {
583             opts.insert_key_value("feature".into(), feature.into());
584         }
585         if let Some(cfgs) = build_data.as_ref().map(|it| &it.cfgs) {
586             opts.extend(cfgs.iter().cloned());
587         }
588         opts
589     };
590
591     let mut env = Env::default();
592     if let Some(envs) = build_data.map(|it| &it.envs) {
593         for (k, v) in envs {
594             env.set(k, v.clone());
595         }
596     }
597
598     let proc_macro = build_data
599         .as_ref()
600         .and_then(|it| it.proc_macro_dylib_path.as_ref())
601         .map(|it| proc_macro_loader(&it))
602         .unwrap_or_default();
603
604     let display_name = CrateDisplayName::from_canonical_name(cargo_name.to_string());
605     let crate_id = crate_graph.add_crate_root(
606         file_id,
607         edition,
608         Some(display_name),
609         cfg_options,
610         env,
611         proc_macro,
612     );
613
614     crate_id
615 }
616
617 fn sysroot_to_crate_graph(
618     crate_graph: &mut CrateGraph,
619     sysroot: &Sysroot,
620     rustc_cfg: Vec<CfgFlag>,
621     load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
622 ) -> (Vec<(CrateName, CrateId)>, Option<CrateId>) {
623     let _p = profile::span("sysroot_to_crate_graph");
624     let mut cfg_options = CfgOptions::default();
625     cfg_options.extend(rustc_cfg);
626     let sysroot_crates: FxHashMap<SysrootCrate, CrateId> = sysroot
627         .crates()
628         .filter_map(|krate| {
629             let file_id = load(&sysroot[krate].root)?;
630
631             let env = Env::default();
632             let proc_macro = vec![];
633             let display_name = CrateDisplayName::from_canonical_name(sysroot[krate].name.clone());
634             let crate_id = crate_graph.add_crate_root(
635                 file_id,
636                 Edition::Edition2018,
637                 Some(display_name),
638                 cfg_options.clone(),
639                 env,
640                 proc_macro,
641             );
642             Some((krate, crate_id))
643         })
644         .collect();
645
646     for from in sysroot.crates() {
647         for &to in sysroot[from].deps.iter() {
648             let name = CrateName::new(&sysroot[to].name).unwrap();
649             if let (Some(&from), Some(&to)) = (sysroot_crates.get(&from), sysroot_crates.get(&to)) {
650                 add_dep(crate_graph, from, name, to);
651             }
652         }
653     }
654
655     let public_deps = sysroot
656         .public_deps()
657         .map(|(name, idx)| (CrateName::new(name).unwrap(), sysroot_crates[&idx]))
658         .collect::<Vec<_>>();
659
660     let libproc_macro = sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
661     (public_deps, libproc_macro)
662 }
663
664 fn add_dep(graph: &mut CrateGraph, from: CrateId, name: CrateName, to: CrateId) {
665     if let Err(err) = graph.add_dep(from, name, to) {
666         log::error!("{}", err)
667     }
668 }