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`.
5 use std::{collections::VecDeque, fmt, fs, path::Path, process::Command};
7 use anyhow::{format_err, Context, Result};
8 use base_db::{CrateDisplayName, CrateGraph, CrateId, CrateName, Edition, Env, FileId, ProcMacro};
9 use cargo_workspace::DepKind;
11 use paths::{AbsPath, AbsPathBuf};
12 use proc_macro_api::ProcMacroClient;
13 use rustc_hash::{FxHashMap, FxHashSet};
16 build_data::{BuildDataResult, PackageBuildData, WorkspaceBuildData},
20 sysroot::SysrootCrate,
21 utf8_stdout, BuildDataCollector, CargoConfig, CargoWorkspace, ProjectJson, ProjectManifest,
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
32 pub include: Vec<AbsPathBuf>,
33 pub exclude: Vec<AbsPathBuf>,
36 #[derive(Clone, Eq, PartialEq)]
37 pub enum ProjectWorkspace {
38 /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`.
40 cargo: CargoWorkspace,
42 rustc: Option<CargoWorkspace>,
43 /// Holds cfg flags for the current target. We get those by running
44 /// `rustc --print cfg`.
46 /// FIXME: make this a per-crate map, as, eg, build.rs might have a
48 rustc_cfg: Vec<CfgFlag>,
50 /// Project workspace was manually specified using a `rust-project.json` file.
51 Json { project: ProjectJson, sysroot: Option<Sysroot>, rustc_cfg: Vec<CfgFlag> },
53 DetachedFiles { files: Vec<AbsPathBuf>, sysroot: Sysroot, rustc_cfg: Vec<CfgFlag> },
56 impl fmt::Debug for ProjectWorkspace {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 // Make sure this isn't too verbose.
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())
66 "n_rustc_compiler_crates",
67 &rustc.as_ref().map_or(0, |rc| rc.packages().len()),
69 .field("n_rustc_cfg", &rustc_cfg.len())
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());
77 debug_struct.field("n_rustc_cfg", &rustc_cfg.len());
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())
90 impl ProjectWorkspace {
92 manifest: ProjectManifest,
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())
101 let data = serde_json::from_str(&file).with_context(|| {
102 format!("Failed to deserialize json file {}", project_json.display())
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())?
108 ProjectManifest::CargoToml(cargo_toml) => {
109 let cargo_version = utf8_stdout({
110 let mut cmd = Command::new(toolchain::cargo());
111 cmd.arg("--version");
115 let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml, config, progress)
118 "Failed to read Cargo metadata from Cargo.toml file {}, {}",
119 cargo_toml.display(),
124 let sysroot = if config.no_sysroot {
127 Sysroot::discover(&cargo_toml).with_context(|| {
129 "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?",
135 let rustc_dir = if let Some(rustc_source) = &config.rustc_source {
136 use cargo_workspace::RustcSource;
138 RustcSource::Path(path) => Some(path.clone()),
139 RustcSource::Discover => Sysroot::discover_rustc(&cargo_toml),
145 let rustc = if let Some(rustc_dir) = rustc_dir {
147 CargoWorkspace::from_cargo_metadata(&rustc_dir, config, progress)
149 format!("Failed to read Cargo metadata for Rust sources")
156 let rustc_cfg = rustc_cfg::get(Some(&cargo_toml), config.target.as_deref());
157 ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg }
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)?),
172 let rustc_cfg = rustc_cfg::get(None, target);
173 Ok(ProjectWorkspace::Json { project: project_json, sysroot, rustc_cfg })
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"))?,
180 let rustc_cfg = rustc_cfg::get(None, None);
181 Ok(ProjectWorkspace::DetachedFiles { files: detached_files, sysroot, rustc_cfg })
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> {
189 ProjectWorkspace::Json { project, sysroot, rustc_cfg: _ } => project
191 .map(|(_, krate)| PackageRoot {
192 is_member: krate.is_workspace_member,
193 include: krate.include.clone(),
194 exclude: krate.exclude.clone(),
196 .collect::<FxHashSet<_>>()
198 .chain(sysroot.as_ref().into_iter().flat_map(|sysroot| {
199 sysroot.crates().map(move |krate| PackageRoot {
201 include: vec![sysroot[krate].root_dir().to_path_buf()],
205 .collect::<Vec<_>>(),
206 ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg: _ } => cargo
209 let is_member = cargo[pkg].is_member;
210 let pkg_root = cargo[pkg].root().to_path_buf();
212 let mut include = vec![pkg_root.clone()];
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()),
220 let mut exclude = vec![pkg_root.join(".git")];
222 exclude.push(pkg_root.join("target"));
224 exclude.push(pkg_root.join("tests"));
225 exclude.push(pkg_root.join("examples"));
226 exclude.push(pkg_root.join("benches"));
228 PackageRoot { is_member, include, exclude }
230 .chain(sysroot.crates().map(|krate| PackageRoot {
232 include: vec![sysroot[krate].root_dir().to_path_buf()],
235 .chain(rustc.into_iter().flat_map(|rustc| {
236 rustc.packages().map(move |krate| PackageRoot {
238 include: vec![rustc[krate].root().to_path_buf()],
243 ProjectWorkspace::DetachedFiles { files, sysroot, .. } => files
245 .map(|detached_file| PackageRoot {
247 include: vec![detached_file.clone()],
250 .chain(sysroot.crates().map(|krate| PackageRoot {
252 include: vec![sysroot[krate].root_dir().to_path_buf()],
259 pub fn n_packages(&self) -> usize {
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
266 ProjectWorkspace::DetachedFiles { sysroot, files, .. } => {
267 sysroot.crates().len() + files.len()
272 pub fn to_crate_graph(
274 build_data: Option<&BuildDataResult>,
275 proc_macro_client: Option<&ProcMacroClient>,
276 load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
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),
284 let mut crate_graph = match self {
285 ProjectWorkspace::Json { project, sysroot, rustc_cfg } => project_json_to_crate_graph(
292 ProjectWorkspace::Cargo { cargo, sysroot, rustc, rustc_cfg } => cargo_to_crate_graph(
297 build_data.and_then(|it| it.get(cargo.workspace_root())),
300 rustc.as_ref().zip(build_data).and_then(|(it, map)| map.get(it.workspace_root())),
302 ProjectWorkspace::DetachedFiles { files, sysroot, rustc_cfg } => {
303 detached_files_to_crate_graph(rustc_cfg.clone(), load, files, sysroot)
306 if crate_graph.patch_cfg_if() {
307 log::debug!("Patched std to depend on cfg-if")
309 log::debug!("Did not patch std to depend on cfg-if")
314 pub fn collect_build_data_configs(&self, collector: &mut BuildDataCollector) {
316 ProjectWorkspace::Cargo { cargo, .. } => {
317 collector.add_config(&cargo.workspace_root(), cargo.build_data_config().clone());
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>,
331 let mut crate_graph = CrateGraph::default();
332 let sysroot_deps = sysroot
334 .map(|sysroot| sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load));
336 let mut cfg_cache: FxHashMap<&str, Vec<CfgFlag>> = FxHashMap::default();
337 let crates: FxHashMap<CrateId, CrateId> = project
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))
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));
348 let target_cfgs = match krate.target.as_deref() {
350 cfg_cache.entry(target).or_insert_with(|| rustc_cfg::get(None, Some(target)))
355 let mut cfg_options = CfgOptions::default();
356 cfg_options.extend(target_cfgs.iter().chain(krate.cfg.iter()).cloned());
359 crate_graph.add_crate_root(
362 krate.display_name.clone(),
365 proc_macro.unwrap_or_default(),
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)
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)
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>,
396 rustc: &Option<CargoWorkspace>,
397 rustc_build_data_map: Option<&WorkspaceBuildData>,
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);
404 let mut cfg_options = CfgOptions::default();
405 cfg_options.extend(rustc_cfg);
407 let mut pkg_to_lib_crate = FxHashMap::default();
409 // Add test cfg for non-sysroot crates
410 cfg_options.insert_atom("test".into());
411 cfg_options.insert_atom("debug_assertions".into());
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(
425 build_data_map.and_then(|it| it.get(&cargo[pkg].id)),
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);
435 if cargo[tgt].is_proc_macro {
436 if let Some(proc_macro) = libproc_macro {
440 CrateName::new("proc_macro").unwrap(),
446 pkg_crates.entry(pkg).or_insert_with(Vec::new).push((crate_id, cargo[tgt].kind));
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)
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);
463 for (name, krate) in public_deps.iter() {
464 add_dep(&mut crate_graph, *from, name.clone(), *krate);
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.
480 if dep.kind != DepKind::Build && *kind == TargetKind::BuildScript {
481 // Build scripts may only depend on build dependencies.
485 add_dep(&mut crate_graph, *from, name.clone(), to)
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 {
499 rustc_build_data_map,
502 &mut pkg_to_lib_crate,
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],
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);
524 let mut cfg_options = CfgOptions::default();
525 cfg_options.extend(rustc_cfg);
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(
531 Edition::Edition2018,
538 for (name, krate) in public_deps.iter() {
539 add_dep(&mut crate_graph, detached_file_crate, name.clone(), *krate);
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)>>,
557 let mut rustc_pkg_crates = FxHashMap::default();
558 // The root package of the rustc-dev component is rustc_driver, so we match that
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) {
574 for dep in &rustc_workspace[pkg].dependencies {
575 queue.push_back(dep.pkg);
577 for &tgt in rustc_workspace[pkg].targets.iter() {
578 if rustc_workspace[tgt].kind != TargetKind::Lib {
581 if let Some(file_id) = load(&rustc_workspace[tgt].root) {
582 let crate_id = add_target_crate_root(
584 &rustc_workspace[pkg],
585 rustc_build_data_map.and_then(|it| it.get(&rustc_workspace[pkg].id)),
589 &rustc_workspace[tgt].name,
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);
596 rustc_pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
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);
613 // Add a dependency on the rustc_private crates for all targets of each package
615 for dep in rustc_workspace.packages() {
616 let name = CrateName::normalize_dashes(&rustc_workspace[dep].name);
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 {
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);
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>,
647 let edition = pkg.edition;
649 let mut opts = cfg_options.clone();
650 for feature in pkg.active_features.iter() {
651 opts.insert_key_value("feature".into(), feature.into());
653 if let Some(cfgs) = build_data.as_ref().map(|it| &it.cfgs) {
654 opts.extend(cfgs.iter().cloned());
659 let mut env = Env::default();
660 if let Some(envs) = build_data.map(|it| &it.envs) {
662 env.set(k, v.clone());
666 let proc_macro = build_data
668 .and_then(|it| it.proc_macro_dylib_path.as_ref())
669 .map(|it| proc_macro_loader(&it))
670 .unwrap_or_default();
672 let display_name = CrateDisplayName::from_canonical_name(cargo_name.to_string());
673 let crate_id = crate_graph.add_crate_root(
685 fn sysroot_to_crate_graph(
686 crate_graph: &mut CrateGraph,
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
696 .filter_map(|krate| {
697 let file_id = load(&sysroot[krate].root)?;
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(
704 Edition::Edition2018,
710 Some((krate, crate_id))
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);
723 let public_deps = sysroot
725 .map(|(name, idx)| (CrateName::new(name).unwrap(), sysroot_crates[&idx]))
726 .collect::<Vec<_>>();
728 let libproc_macro = sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
729 (public_deps, libproc_macro)
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)