1 //! FIXME: write short doc here
8 fs::{read_dir, File, ReadDir},
10 path::{Path, PathBuf},
11 process::{Command, Output},
14 use anyhow::{bail, Context, Result};
15 use ra_cfg::CfgOptions;
16 use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId};
17 use rustc_hash::{FxHashMap, FxHashSet};
18 use serde_json::from_reader;
21 cargo_workspace::{CargoConfig, CargoWorkspace, Package, Target, TargetKind},
22 json_project::JsonProject,
25 pub use ra_proc_macro::ProcMacroClient;
27 #[derive(Debug, Clone)]
28 pub enum ProjectWorkspace {
29 /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`.
30 Cargo { cargo: CargoWorkspace, sysroot: Sysroot },
31 /// Project workspace was manually specified using a `rust-project.json` file.
32 Json { project: JsonProject },
35 /// `PackageRoot` describes a package root folder.
36 /// Which may be an external dependency, or a member of
37 /// the current workspace.
38 #[derive(Debug, Clone)]
39 pub struct PackageRoot {
40 /// Path to the root folder
42 /// Is a member of the current workspace
46 pub fn new_member(path: PathBuf) -> PackageRoot {
47 Self { path, is_member: true }
49 pub fn new_non_member(path: PathBuf) -> PackageRoot {
50 Self { path, is_member: false }
52 pub fn path(&self) -> &Path {
55 pub fn is_member(&self) -> bool {
60 #[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
61 pub enum ProjectManifest {
66 impl ProjectManifest {
67 pub fn from_manifest_file(path: PathBuf) -> Result<ProjectManifest> {
68 if path.ends_with("rust-project.json") {
69 return Ok(ProjectManifest::ProjectJson(path));
71 if path.ends_with("Cargo.toml") {
72 return Ok(ProjectManifest::CargoToml(path));
74 bail!("project root must point to Cargo.toml or rust-project.json: {}", path.display())
77 pub fn discover_single(path: &Path) -> Result<ProjectManifest> {
78 let mut candidates = ProjectManifest::discover(path)?;
79 let res = match candidates.pop() {
80 None => bail!("no projects"),
84 if !candidates.is_empty() {
85 bail!("more than one project")
90 pub fn discover(path: &Path) -> io::Result<Vec<ProjectManifest>> {
91 if let Some(project_json) = find_in_parent_dirs(path, "rust-project.json") {
92 return Ok(vec![ProjectManifest::ProjectJson(project_json)]);
94 return find_cargo_toml(path)
95 .map(|paths| paths.into_iter().map(ProjectManifest::CargoToml).collect());
97 fn find_cargo_toml(path: &Path) -> io::Result<Vec<PathBuf>> {
98 match find_in_parent_dirs(path, "Cargo.toml") {
99 Some(it) => Ok(vec![it]),
100 None => Ok(find_cargo_toml_in_child_dir(read_dir(path)?)),
104 fn find_in_parent_dirs(path: &Path, target_file_name: &str) -> Option<PathBuf> {
105 if path.ends_with(target_file_name) {
106 return Some(path.to_owned());
109 let mut curr = Some(path);
111 while let Some(path) = curr {
112 let candidate = path.join(target_file_name);
113 if candidate.exists() {
114 return Some(candidate);
116 curr = path.parent();
122 fn find_cargo_toml_in_child_dir(entities: ReadDir) -> Vec<PathBuf> {
123 // Only one level down to avoid cycles the easy way and stop a runaway scan with large projects
125 .filter_map(Result::ok)
126 .map(|it| it.path().join("Cargo.toml"))
127 .filter(|it| it.exists())
132 pub fn discover_all(paths: &[impl AsRef<Path>]) -> Vec<ProjectManifest> {
135 .filter_map(|it| ProjectManifest::discover(it.as_ref()).ok())
137 .collect::<FxHashSet<_>>()
139 .collect::<Vec<_>>();
145 impl ProjectWorkspace {
147 root: ProjectManifest,
148 cargo_features: &CargoConfig,
150 ) -> Result<ProjectWorkspace> {
151 let res = match root {
152 ProjectManifest::ProjectJson(project_json) => {
153 let file = File::open(&project_json).with_context(|| {
154 format!("Failed to open json file {}", project_json.display())
156 let reader = BufReader::new(file);
157 ProjectWorkspace::Json {
158 project: from_reader(reader).with_context(|| {
159 format!("Failed to deserialize json file {}", project_json.display())
163 ProjectManifest::CargoToml(cargo_toml) => {
164 let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml, cargo_features)
167 "Failed to read Cargo metadata from Cargo.toml file {}",
171 let sysroot = if with_sysroot {
172 Sysroot::discover(&cargo_toml).with_context(|| {
174 "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?",
181 ProjectWorkspace::Cargo { cargo, sysroot }
188 /// Returns the roots for the current `ProjectWorkspace`
189 /// The return type contains the path and whether or not
190 /// the root is a member of the current workspace
191 pub fn to_roots(&self) -> Vec<PackageRoot> {
193 ProjectWorkspace::Json { project } => {
194 project.roots.iter().map(|r| PackageRoot::new_member(r.path.clone())).collect()
196 ProjectWorkspace::Cargo { cargo, sysroot } => cargo
198 .map(|pkg| PackageRoot {
199 path: cargo[pkg].root().to_path_buf(),
200 is_member: cargo[pkg].is_member,
202 .chain(sysroot.crates().map(|krate| {
203 PackageRoot::new_non_member(sysroot[krate].root_dir().to_path_buf())
209 pub fn out_dirs(&self) -> Vec<PathBuf> {
211 ProjectWorkspace::Json { project } => {
212 project.crates.iter().filter_map(|krate| krate.out_dir.as_ref()).cloned().collect()
214 ProjectWorkspace::Cargo { cargo, sysroot: _ } => {
215 cargo.packages().filter_map(|pkg| cargo[pkg].out_dir.as_ref()).cloned().collect()
220 pub fn proc_macro_dylib_paths(&self) -> Vec<PathBuf> {
222 ProjectWorkspace::Json { project } => project
225 .filter_map(|krate| krate.proc_macro_dylib_path.as_ref())
228 ProjectWorkspace::Cargo { cargo, sysroot: _sysroot } => cargo
230 .filter_map(|pkg| cargo[pkg].proc_macro_dylib_path.as_ref())
236 pub fn n_packages(&self) -> usize {
238 ProjectWorkspace::Json { project } => project.crates.len(),
239 ProjectWorkspace::Cargo { cargo, sysroot } => {
240 cargo.packages().len() + sysroot.crates().len()
245 pub fn to_crate_graph(
247 default_cfg_options: &CfgOptions,
248 extern_source_roots: &FxHashMap<PathBuf, ExternSourceId>,
249 proc_macro_client: &ProcMacroClient,
250 load: &mut dyn FnMut(&Path) -> Option<FileId>,
252 let mut crate_graph = CrateGraph::default();
254 ProjectWorkspace::Json { project } => {
255 let crates: FxHashMap<_, _> = project
259 .filter_map(|(seq_index, krate)| {
260 let file_id = load(&krate.root_module)?;
261 let edition = match krate.edition {
262 json_project::Edition::Edition2015 => Edition::Edition2015,
263 json_project::Edition::Edition2018 => Edition::Edition2018,
266 let mut opts = default_cfg_options.clone();
267 for cfg in &krate.cfg {
268 match cfg.find('=') {
269 None => opts.insert_atom(cfg.into()),
271 let key = &cfg[..pos];
272 let value = cfg[pos + 1..].trim_matches('"');
273 opts.insert_key_value(key.into(), value.into());
277 for name in &krate.atom_cfgs {
278 opts.insert_atom(name.into());
280 for (key, value) in &krate.key_value_cfgs {
281 opts.insert_key_value(key.into(), value.into());
286 let mut env = Env::default();
287 let mut extern_source = ExternSource::default();
288 if let Some(out_dir) = &krate.out_dir {
289 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
290 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
291 env.set("OUT_DIR", out_dir);
293 if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
294 extern_source.set_extern_path(&out_dir, extern_source_id);
297 let proc_macro = krate
298 .proc_macro_dylib_path
300 .map(|it| proc_macro_client.by_dylib_path(&it));
301 // FIXME: No crate name in json definition such that we cannot add OUT_DIR to env
303 json_project::CrateId(seq_index),
304 crate_graph.add_crate_root(
307 // FIXME json definitions can store the crate name
312 proc_macro.unwrap_or_default(),
318 for (id, krate) in project.crates.iter().enumerate() {
319 for dep in &krate.deps {
320 let from_crate_id = json_project::CrateId(id);
321 let to_crate_id = dep.krate;
322 if let (Some(&from), Some(&to)) =
323 (crates.get(&from_crate_id), crates.get(&to_crate_id))
326 .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
330 "cyclic dependency {:?} -> {:?}",
339 ProjectWorkspace::Cargo { cargo, sysroot } => {
340 let sysroot_crates: FxHashMap<_, _> = sysroot
342 .filter_map(|krate| {
343 let file_id = load(&sysroot[krate].root)?;
345 // Crates from sysroot have `cfg(test)` disabled
347 let mut opts = default_cfg_options.clone();
348 opts.remove_atom("test");
352 let env = Env::default();
353 let extern_source = ExternSource::default();
354 let proc_macro = vec![];
355 let crate_name = CrateName::new(&sysroot[krate].name)
356 .expect("Sysroot crate names should not contain dashes");
358 let crate_id = crate_graph.add_crate_root(
360 Edition::Edition2018,
367 Some((krate, crate_id))
371 for from in sysroot.crates() {
372 for &to in sysroot[from].deps.iter() {
373 let name = &sysroot[to].name;
374 if let (Some(&from), Some(&to)) =
375 (sysroot_crates.get(&from), sysroot_crates.get(&to))
377 if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err()
379 log::error!("cyclic dependency between sysroot crates")
385 let libcore = sysroot.core().and_then(|it| sysroot_crates.get(&it).copied());
386 let liballoc = sysroot.alloc().and_then(|it| sysroot_crates.get(&it).copied());
387 let libstd = sysroot.std().and_then(|it| sysroot_crates.get(&it).copied());
389 sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
391 let mut pkg_to_lib_crate = FxHashMap::default();
392 let mut pkg_crates = FxHashMap::default();
393 // Next, create crates for each package, target pair
394 for pkg in cargo.packages() {
395 let mut lib_tgt = None;
396 for &tgt in cargo[pkg].targets.iter() {
397 let root = cargo[tgt].root.as_path();
398 if let Some(file_id) = load(root) {
399 let edition = cargo[pkg].edition;
401 let mut opts = default_cfg_options.clone();
402 for feature in cargo[pkg].features.iter() {
403 opts.insert_key_value("feature".into(), feature.into());
405 for cfg in cargo[pkg].cfgs.iter() {
406 match cfg.find('=') {
407 Some(split) => opts.insert_key_value(
409 cfg[split + 1..].trim_matches('"').into(),
411 None => opts.insert_atom(cfg.into()),
416 let mut env = Env::default();
417 let mut extern_source = ExternSource::default();
418 if let Some(out_dir) = &cargo[pkg].out_dir {
419 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
420 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
421 env.set("OUT_DIR", out_dir);
423 if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
424 extern_source.set_extern_path(&out_dir, extern_source_id);
427 let proc_macro = cargo[pkg]
428 .proc_macro_dylib_path
430 .map(|it| proc_macro_client.by_dylib_path(&it))
431 .unwrap_or_default();
433 let crate_id = crate_graph.add_crate_root(
436 Some(CrateName::normalize_dashes(&cargo[pkg].name)),
442 if cargo[tgt].kind == TargetKind::Lib {
443 lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
444 pkg_to_lib_crate.insert(pkg, crate_id);
446 if cargo[tgt].is_proc_macro {
447 if let Some(proc_macro) = libproc_macro {
451 CrateName::new("proc_macro").unwrap(),
457 "cyclic dependency on proc_macro for {}",
464 pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
468 // Set deps to the core, std and to the lib target of the current package
469 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
470 if let Some((to, name)) = lib_tgt.clone() {
475 // For root projects with dashes in their name,
476 // cargo metadata does not do any normalization,
477 // so we do it ourselves currently
478 CrateName::normalize_dashes(&name),
485 "cyclic dependency between targets of {}",
491 // core is added as a dependency before std in order to
492 // mimic rustcs dependency order
493 if let Some(core) = libcore {
495 .add_dep(from, CrateName::new("core").unwrap(), core)
498 log::error!("cyclic dependency on core for {}", &cargo[pkg].name)
501 if let Some(alloc) = liballoc {
503 .add_dep(from, CrateName::new("alloc").unwrap(), alloc)
506 log::error!("cyclic dependency on alloc for {}", &cargo[pkg].name)
509 if let Some(std) = libstd {
511 .add_dep(from, CrateName::new("std").unwrap(), std)
514 log::error!("cyclic dependency on std for {}", &cargo[pkg].name)
520 // Now add a dep edge from all targets of upstream to the lib
521 // target of downstream.
522 for pkg in cargo.packages() {
523 for dep in cargo[pkg].dependencies.iter() {
524 if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
525 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
527 .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
531 "cyclic dependency {} -> {}",
545 pub fn workspace_root_for(&self, path: &Path) -> Option<&Path> {
547 ProjectWorkspace::Cargo { cargo, .. } => {
548 Some(cargo.workspace_root()).filter(|root| path.starts_with(root))
550 ProjectWorkspace::Json { project: JsonProject { roots, .. } } => roots
552 .find(|root| path.starts_with(&root.path))
553 .map(|root| root.path.as_ref()),
558 pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions {
559 let mut cfg_options = CfgOptions::default();
561 // Some nightly-only cfgs, which are required for stdlib
563 cfg_options.insert_atom("target_thread_local".into());
564 for &target_has_atomic in ["8", "16", "32", "64", "cas", "ptr"].iter() {
565 cfg_options.insert_key_value("target_has_atomic".into(), target_has_atomic.into());
567 .insert_key_value("target_has_atomic_load_store".into(), target_has_atomic.into());
571 let rustc_cfgs = || -> Result<String> {
572 // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
573 let mut cmd = Command::new(ra_toolchain::rustc());
574 cmd.args(&["--print", "cfg", "-O"]);
575 if let Some(target) = target {
576 cmd.args(&["--target", target.as_str()]);
578 let output = output(cmd)?;
579 Ok(String::from_utf8(output.stdout)?)
584 for line in rustc_cfgs.lines() {
585 match line.find('=') {
586 None => cfg_options.insert_atom(line.into()),
588 let key = &line[..pos];
589 let value = line[pos + 1..].trim_matches('"');
590 cfg_options.insert_key_value(key.into(), value.into());
595 Err(e) => log::error!("failed to get rustc cfgs: {:#}", e),
601 fn output(mut cmd: Command) -> Result<Output> {
602 let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?;
603 if !output.status.success() {
604 match String::from_utf8(output.stderr) {
605 Ok(stderr) if !stderr.is_empty() => {
606 bail!("{:?} failed, {}\nstderr:\n{}", cmd, output.status, stderr)
608 _ => bail!("{:?} failed, {}", cmd, output.status),