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