1 //! FIXME: write short doc here
9 fs::{read_dir, File, ReadDir},
11 path::{Path, PathBuf},
15 use anyhow::{bail, Context, Result};
16 use ra_cfg::CfgOptions;
17 use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId};
18 use rustc_hash::FxHashMap;
19 use serde_json::from_reader;
22 cargo_workspace::{CargoConfig, CargoWorkspace, Package, Target, TargetKind},
23 json_project::JsonProject,
26 pub use ra_proc_macro::ProcMacroClient;
28 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
29 pub struct CargoTomlNotFoundError {
30 pub searched_at: PathBuf,
34 impl std::fmt::Display for CargoTomlNotFoundError {
35 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 "can't find Cargo.toml at {}, due to {}",
39 self.searched_at.display(),
45 impl Error for CargoTomlNotFoundError {}
47 #[derive(Debug, Clone)]
48 pub enum ProjectWorkspace {
49 /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`.
50 Cargo { cargo: CargoWorkspace, sysroot: Sysroot },
51 /// Project workspace was manually specified using a `rust-project.json` file.
52 Json { project: JsonProject },
55 /// `PackageRoot` describes a package root folder.
56 /// Which may be an external dependency, or a member of
57 /// the current workspace.
59 pub struct PackageRoot {
60 /// Path to the root folder
62 /// Is a member of the current workspace
66 pub fn new_member(path: PathBuf) -> PackageRoot {
67 Self { path, is_member: true }
69 pub fn new_non_member(path: PathBuf) -> PackageRoot {
70 Self { path, is_member: false }
74 impl ProjectWorkspace {
75 pub fn discover(path: &Path, cargo_features: &CargoConfig) -> Result<ProjectWorkspace> {
76 ProjectWorkspace::discover_with_sysroot(path, true, cargo_features)
79 pub fn discover_with_sysroot(
82 cargo_features: &CargoConfig,
83 ) -> Result<ProjectWorkspace> {
84 match find_rust_project_json(path) {
86 let file = File::open(&json_path)
87 .with_context(|| format!("Failed to open json file {}", json_path.display()))?;
88 let reader = BufReader::new(file);
89 Ok(ProjectWorkspace::Json {
90 project: from_reader(reader).with_context(|| {
91 format!("Failed to deserialize json file {}", json_path.display())
96 let cargo_toml = find_cargo_toml(path).with_context(|| {
97 format!("Failed to find Cargo.toml for path {}", path.display())
99 let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml, cargo_features)
102 "Failed to read Cargo metadata from Cargo.toml file {}",
106 let sysroot = if with_sysroot {
107 Sysroot::discover(&cargo_toml).with_context(|| {
109 "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?",
116 Ok(ProjectWorkspace::Cargo { cargo, sysroot })
121 /// Returns the roots for the current `ProjectWorkspace`
122 /// The return type contains the path and whether or not
123 /// the root is a member of the current workspace
124 pub fn to_roots(&self) -> Vec<PackageRoot> {
126 ProjectWorkspace::Json { project } => {
127 project.roots.iter().map(|r| PackageRoot::new_member(r.path.clone())).collect()
129 ProjectWorkspace::Cargo { cargo, sysroot } => cargo
131 .map(|pkg| PackageRoot {
132 path: cargo[pkg].root().to_path_buf(),
133 is_member: cargo[pkg].is_member,
135 .chain(sysroot.crates().map(|krate| {
136 PackageRoot::new_non_member(sysroot[krate].root_dir().to_path_buf())
142 pub fn out_dirs(&self) -> Vec<PathBuf> {
144 ProjectWorkspace::Json { project } => {
145 let mut out_dirs = Vec::with_capacity(project.crates.len());
146 for krate in &project.crates {
147 if let Some(out_dir) = &krate.out_dir {
148 out_dirs.push(out_dir.to_path_buf());
153 ProjectWorkspace::Cargo { cargo, sysroot: _sysroot } => {
154 let mut out_dirs = Vec::with_capacity(cargo.packages().len());
155 for pkg in cargo.packages() {
156 if let Some(out_dir) = &cargo[pkg].out_dir {
157 out_dirs.push(out_dir.to_path_buf());
165 pub fn proc_macro_dylib_paths(&self) -> Vec<PathBuf> {
167 ProjectWorkspace::Json { project } => {
168 let mut proc_macro_dylib_paths = Vec::with_capacity(project.crates.len());
169 for krate in &project.crates {
170 if let Some(out_dir) = &krate.proc_macro_dylib_path {
171 proc_macro_dylib_paths.push(out_dir.to_path_buf());
174 proc_macro_dylib_paths
176 ProjectWorkspace::Cargo { cargo, sysroot: _sysroot } => {
177 let mut proc_macro_dylib_paths = Vec::with_capacity(cargo.packages().len());
178 for pkg in cargo.packages() {
179 if let Some(dylib_path) = &cargo[pkg].proc_macro_dylib_path {
180 proc_macro_dylib_paths.push(dylib_path.to_path_buf());
183 proc_macro_dylib_paths
188 pub fn n_packages(&self) -> usize {
190 ProjectWorkspace::Json { project } => project.crates.len(),
191 ProjectWorkspace::Cargo { cargo, sysroot } => {
192 cargo.packages().len() + sysroot.crates().len()
197 pub fn to_crate_graph(
199 default_cfg_options: &CfgOptions,
200 extern_source_roots: &FxHashMap<PathBuf, ExternSourceId>,
201 proc_macro_client: &ProcMacroClient,
202 load: &mut dyn FnMut(&Path) -> Option<FileId>,
204 let mut crate_graph = CrateGraph::default();
206 ProjectWorkspace::Json { project } => {
207 let mut crates = FxHashMap::default();
208 for (id, krate) in project.crates.iter().enumerate() {
209 let crate_id = json_project::CrateId(id);
210 if let Some(file_id) = load(&krate.root_module) {
211 let edition = match krate.edition {
212 json_project::Edition::Edition2015 => Edition::Edition2015,
213 json_project::Edition::Edition2018 => Edition::Edition2018,
216 let mut opts = default_cfg_options.clone();
217 for name in &krate.atom_cfgs {
218 opts.insert_atom(name.into());
220 for (key, value) in &krate.key_value_cfgs {
221 opts.insert_key_value(key.into(), value.into());
226 let mut env = Env::default();
227 let mut extern_source = ExternSource::default();
228 if let Some(out_dir) = &krate.out_dir {
229 // FIXME: We probably mangle non UTF-8 paths here, figure out a better solution
230 env.set("OUT_DIR", out_dir.to_string_lossy().to_string());
231 if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
232 extern_source.set_extern_path(&out_dir, extern_source_id);
235 let proc_macro = krate
236 .proc_macro_dylib_path
238 .map(|it| proc_macro_client.by_dylib_path(&it));
239 // FIXME: No crate name in json definition such that we cannot add OUT_DIR to env
242 crate_graph.add_crate_root(
245 // FIXME json definitions can store the crate name
250 proc_macro.unwrap_or_default(),
256 for (id, krate) in project.crates.iter().enumerate() {
257 for dep in &krate.deps {
258 let from_crate_id = json_project::CrateId(id);
259 let to_crate_id = dep.krate;
260 if let (Some(&from), Some(&to)) =
261 (crates.get(&from_crate_id), crates.get(&to_crate_id))
264 .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
268 "cyclic dependency {:?} -> {:?}",
277 ProjectWorkspace::Cargo { cargo, sysroot } => {
278 let mut sysroot_crates = FxHashMap::default();
279 for krate in sysroot.crates() {
280 if let Some(file_id) = load(&sysroot[krate].root) {
281 // Crates from sysroot have `cfg(test)` disabled
283 let mut opts = default_cfg_options.clone();
284 opts.remove_atom("test");
288 let env = Env::default();
289 let extern_source = ExternSource::default();
290 let proc_macro = vec![];
292 let crate_id = crate_graph.add_crate_root(
294 Edition::Edition2018,
296 CrateName::new(&sysroot[krate].name)
297 .expect("Sysroot crate names should not contain dashes"),
304 sysroot_crates.insert(krate, crate_id);
307 for from in sysroot.crates() {
308 for &to in sysroot[from].deps.iter() {
309 let name = &sysroot[to].name;
310 if let (Some(&from), Some(&to)) =
311 (sysroot_crates.get(&from), sysroot_crates.get(&to))
313 if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err()
315 log::error!("cyclic dependency between sysroot crates")
321 let libcore = sysroot.core().and_then(|it| sysroot_crates.get(&it).copied());
322 let liballoc = sysroot.alloc().and_then(|it| sysroot_crates.get(&it).copied());
323 let libstd = sysroot.std().and_then(|it| sysroot_crates.get(&it).copied());
325 sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
327 let mut pkg_to_lib_crate = FxHashMap::default();
328 let mut pkg_crates = FxHashMap::default();
329 // Next, create crates for each package, target pair
330 for pkg in cargo.packages() {
331 let mut lib_tgt = None;
332 for &tgt in cargo[pkg].targets.iter() {
333 let root = cargo[tgt].root.as_path();
334 if let Some(file_id) = load(root) {
335 let edition = cargo[pkg].edition;
337 let mut opts = default_cfg_options.clone();
338 opts.insert_features(cargo[pkg].features.iter().map(Into::into));
341 let mut env = Env::default();
342 let mut extern_source = ExternSource::default();
343 if let Some(out_dir) = &cargo[pkg].out_dir {
344 // FIXME: We probably mangle non UTF-8 paths here, figure out a better solution
345 env.set("OUT_DIR", out_dir.to_string_lossy().to_string());
346 if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
347 extern_source.set_extern_path(&out_dir, extern_source_id);
350 let proc_macro = cargo[pkg]
351 .proc_macro_dylib_path
353 .map(|it| proc_macro_client.by_dylib_path(&it))
354 .unwrap_or_default();
356 let crate_id = crate_graph.add_crate_root(
359 Some(CrateName::normalize_dashes(&cargo[pkg].name)),
365 if cargo[tgt].kind == TargetKind::Lib {
366 lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
367 pkg_to_lib_crate.insert(pkg, crate_id);
369 if cargo[tgt].is_proc_macro {
370 if let Some(proc_macro) = libproc_macro {
374 CrateName::new("proc_macro").unwrap(),
380 "cyclic dependency on proc_macro for {}",
387 pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
391 // Set deps to the core, std and to the lib target of the current package
392 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
393 if let Some((to, name)) = lib_tgt.clone() {
398 // For root projects with dashes in their name,
399 // cargo metadata does not do any normalization,
400 // so we do it ourselves currently
401 CrateName::normalize_dashes(&name),
408 "cyclic dependency between targets of {}",
414 // core is added as a dependency before std in order to
415 // mimic rustcs dependency order
416 if let Some(core) = libcore {
418 .add_dep(from, CrateName::new("core").unwrap(), core)
421 log::error!("cyclic dependency on core for {}", &cargo[pkg].name)
424 if let Some(alloc) = liballoc {
426 .add_dep(from, CrateName::new("alloc").unwrap(), alloc)
429 log::error!("cyclic dependency on alloc for {}", &cargo[pkg].name)
432 if let Some(std) = libstd {
434 .add_dep(from, CrateName::new("std").unwrap(), std)
437 log::error!("cyclic dependency on std for {}", &cargo[pkg].name)
443 // Now add a dep edge from all targets of upstream to the lib
444 // target of downstream.
445 for pkg in cargo.packages() {
446 for dep in cargo[pkg].dependencies.iter() {
447 if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
448 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
450 .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
454 "cyclic dependency {} -> {}",
468 pub fn workspace_root_for(&self, path: &Path) -> Option<&Path> {
470 ProjectWorkspace::Cargo { cargo, .. } => {
471 Some(cargo.workspace_root()).filter(|root| path.starts_with(root))
473 ProjectWorkspace::Json { project: JsonProject { roots, .. } } => roots
475 .find(|root| path.starts_with(&root.path))
476 .map(|root| root.path.as_ref()),
481 fn find_rust_project_json(path: &Path) -> Option<PathBuf> {
482 if path.ends_with("rust-project.json") {
483 return Some(path.to_path_buf());
486 let mut curr = Some(path);
487 while let Some(path) = curr {
488 let candidate = path.join("rust-project.json");
489 if candidate.exists() {
490 return Some(candidate);
492 curr = path.parent();
498 fn find_cargo_toml_in_parent_dir(path: &Path) -> Option<PathBuf> {
499 let mut curr = Some(path);
500 while let Some(path) = curr {
501 let candidate = path.join("Cargo.toml");
502 if candidate.exists() {
503 return Some(candidate);
505 curr = path.parent();
511 fn find_cargo_toml_in_child_dir(entities: ReadDir) -> Vec<PathBuf> {
512 // Only one level down to avoid cycles the easy way and stop a runaway scan with large projects
513 let mut valid_canditates = vec![];
514 for entity in entities.filter_map(Result::ok) {
515 let candidate = entity.path().join("Cargo.toml");
516 if candidate.exists() {
517 valid_canditates.push(candidate)
523 fn find_cargo_toml(path: &Path) -> Result<PathBuf> {
524 if path.ends_with("Cargo.toml") {
525 return Ok(path.to_path_buf());
528 if let Some(p) = find_cargo_toml_in_parent_dir(path) {
532 let entities = match read_dir(path) {
533 Ok(entities) => entities,
535 return Err(CargoTomlNotFoundError {
536 searched_at: path.to_path_buf(),
537 reason: format!("file system error: {}", e),
543 let mut valid_canditates = find_cargo_toml_in_child_dir(entities);
544 match valid_canditates.len() {
545 1 => Ok(valid_canditates.remove(0)),
546 0 => Err(CargoTomlNotFoundError {
547 searched_at: path.to_path_buf(),
548 reason: "no Cargo.toml file found".to_string(),
551 _ => Err(CargoTomlNotFoundError {
552 searched_at: path.to_path_buf(),
554 "multiple equally valid Cargo.toml files found: {:?}",
562 pub fn get_rustc_cfg_options() -> CfgOptions {
563 let mut cfg_options = CfgOptions::default();
565 // Some nightly-only cfgs, which are required for stdlib
567 cfg_options.insert_atom("target_thread_local".into());
568 for &target_has_atomic in ["8", "16", "32", "64", "cas", "ptr"].iter() {
569 cfg_options.insert_key_value("target_has_atomic".into(), target_has_atomic.into());
571 .insert_key_value("target_has_atomic_load_store".into(), target_has_atomic.into());
575 match (|| -> Result<String> {
576 // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
577 let output = Command::new("rustc")
578 .args(&["--print", "cfg", "-O"])
580 .context("Failed to get output from rustc --print cfg -O")?;
581 if !output.status.success() {
583 "rustc --print cfg -O exited with exit code ({})",
587 .map_or(String::from("no exit code"), |code| format!("{}", code))
590 Ok(String::from_utf8(output.stdout)?)
593 for line in rustc_cfgs.lines() {
594 match line.find('=') {
595 None => cfg_options.insert_atom(line.into()),
597 let key = &line[..pos];
598 let value = line[pos + 1..].trim_matches('"');
599 cfg_options.insert_key_value(key.into(), value.into());
604 Err(e) => log::error!("failed to get rustc cfgs: {}", e),