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 impl From<JsonProject> for ProjectWorkspace {
36 fn from(project: JsonProject) -> ProjectWorkspace {
37 ProjectWorkspace::Json { project }
41 /// `PackageRoot` describes a package root folder.
42 /// Which may be an external dependency, or a member of
43 /// the current workspace.
44 #[derive(Debug, Clone)]
45 pub struct PackageRoot {
46 /// Path to the root folder
48 /// Is a member of the current workspace
50 out_dir: Option<PathBuf>,
53 pub fn new_member(path: PathBuf) -> PackageRoot {
54 Self { path, is_member: true, out_dir: None }
56 pub fn new_non_member(path: PathBuf) -> PackageRoot {
57 Self { path, is_member: false, out_dir: None }
59 pub fn path(&self) -> &Path {
62 pub fn out_dir(&self) -> Option<&Path> {
63 self.out_dir.as_deref()
65 pub fn is_member(&self) -> bool {
70 #[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
71 pub enum ProjectManifest {
76 impl ProjectManifest {
77 pub fn from_manifest_file(path: PathBuf) -> Result<ProjectManifest> {
78 if path.ends_with("rust-project.json") {
79 return Ok(ProjectManifest::ProjectJson(path));
81 if path.ends_with("Cargo.toml") {
82 return Ok(ProjectManifest::CargoToml(path));
84 bail!("project root must point to Cargo.toml or rust-project.json: {}", path.display())
87 pub fn discover_single(path: &Path) -> Result<ProjectManifest> {
88 let mut candidates = ProjectManifest::discover(path)?;
89 let res = match candidates.pop() {
90 None => bail!("no projects"),
94 if !candidates.is_empty() {
95 bail!("more than one project")
100 pub fn discover(path: &Path) -> io::Result<Vec<ProjectManifest>> {
101 if let Some(project_json) = find_in_parent_dirs(path, "rust-project.json") {
102 return Ok(vec![ProjectManifest::ProjectJson(project_json)]);
104 return find_cargo_toml(path)
105 .map(|paths| paths.into_iter().map(ProjectManifest::CargoToml).collect());
107 fn find_cargo_toml(path: &Path) -> io::Result<Vec<PathBuf>> {
108 match find_in_parent_dirs(path, "Cargo.toml") {
109 Some(it) => Ok(vec![it]),
110 None => Ok(find_cargo_toml_in_child_dir(read_dir(path)?)),
114 fn find_in_parent_dirs(path: &Path, target_file_name: &str) -> Option<PathBuf> {
115 if path.ends_with(target_file_name) {
116 return Some(path.to_owned());
119 let mut curr = Some(path);
121 while let Some(path) = curr {
122 let candidate = path.join(target_file_name);
123 if candidate.exists() {
124 return Some(candidate);
126 curr = path.parent();
132 fn find_cargo_toml_in_child_dir(entities: ReadDir) -> Vec<PathBuf> {
133 // Only one level down to avoid cycles the easy way and stop a runaway scan with large projects
135 .filter_map(Result::ok)
136 .map(|it| it.path().join("Cargo.toml"))
137 .filter(|it| it.exists())
142 pub fn discover_all(paths: &[impl AsRef<Path>]) -> Vec<ProjectManifest> {
145 .filter_map(|it| ProjectManifest::discover(it.as_ref()).ok())
147 .collect::<FxHashSet<_>>()
149 .collect::<Vec<_>>();
155 impl ProjectWorkspace {
157 manifest: ProjectManifest,
158 cargo_features: &CargoConfig,
160 ) -> Result<ProjectWorkspace> {
161 let res = match manifest {
162 ProjectManifest::ProjectJson(project_json) => {
163 let file = File::open(&project_json).with_context(|| {
164 format!("Failed to open json file {}", project_json.display())
166 let reader = BufReader::new(file);
167 ProjectWorkspace::Json {
168 project: from_reader(reader).with_context(|| {
169 format!("Failed to deserialize json file {}", project_json.display())
173 ProjectManifest::CargoToml(cargo_toml) => {
174 let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml, cargo_features)
177 "Failed to read Cargo metadata from Cargo.toml file {}",
181 let sysroot = if with_sysroot {
182 Sysroot::discover(&cargo_toml).with_context(|| {
184 "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?",
191 ProjectWorkspace::Cargo { cargo, sysroot }
198 /// Returns the roots for the current `ProjectWorkspace`
199 /// The return type contains the path and whether or not
200 /// the root is a member of the current workspace
201 pub fn to_roots(&self) -> Vec<PackageRoot> {
203 ProjectWorkspace::Json { project } => {
204 project.roots.iter().map(|r| PackageRoot::new_member(r.path.clone())).collect()
206 ProjectWorkspace::Cargo { cargo, sysroot } => cargo
208 .map(|pkg| PackageRoot {
209 path: cargo[pkg].root().to_path_buf(),
210 is_member: cargo[pkg].is_member,
211 out_dir: cargo[pkg].out_dir.clone(),
213 .chain(sysroot.crates().map(|krate| {
214 PackageRoot::new_non_member(sysroot[krate].root_dir().to_path_buf())
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 target: Option<&str>,
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 = CfgOptions::default();
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());
280 let mut env = Env::default();
281 let mut extern_source = ExternSource::default();
282 if let Some(out_dir) = &krate.out_dir {
283 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
284 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
285 env.set("OUT_DIR", out_dir);
287 if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
288 extern_source.set_extern_path(&out_dir, extern_source_id);
291 let proc_macro = krate
292 .proc_macro_dylib_path
294 .map(|it| proc_macro_client.by_dylib_path(&it));
295 // FIXME: No crate name in json definition such that we cannot add OUT_DIR to env
297 json_project::CrateId(seq_index),
298 crate_graph.add_crate_root(
301 // FIXME json definitions can store the crate name
306 proc_macro.unwrap_or_default(),
312 for (id, krate) in project.crates.iter().enumerate() {
313 for dep in &krate.deps {
314 let from_crate_id = json_project::CrateId(id);
315 let to_crate_id = dep.krate;
316 if let (Some(&from), Some(&to)) =
317 (crates.get(&from_crate_id), crates.get(&to_crate_id))
320 .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
324 "cyclic dependency {:?} -> {:?}",
333 ProjectWorkspace::Cargo { cargo, sysroot } => {
334 let mut cfg_options = get_rustc_cfg_options(target);
336 let sysroot_crates: FxHashMap<_, _> = sysroot
338 .filter_map(|krate| {
339 let file_id = load(&sysroot[krate].root)?;
341 let env = Env::default();
342 let extern_source = ExternSource::default();
343 let proc_macro = vec![];
344 let crate_name = CrateName::new(&sysroot[krate].name)
345 .expect("Sysroot crate names should not contain dashes");
347 let crate_id = crate_graph.add_crate_root(
349 Edition::Edition2018,
356 Some((krate, crate_id))
360 for from in sysroot.crates() {
361 for &to in sysroot[from].deps.iter() {
362 let name = &sysroot[to].name;
363 if let (Some(&from), Some(&to)) =
364 (sysroot_crates.get(&from), sysroot_crates.get(&to))
366 if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err()
368 log::error!("cyclic dependency between sysroot crates")
374 let libcore = sysroot.core().and_then(|it| sysroot_crates.get(&it).copied());
375 let liballoc = sysroot.alloc().and_then(|it| sysroot_crates.get(&it).copied());
376 let libstd = sysroot.std().and_then(|it| sysroot_crates.get(&it).copied());
378 sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
380 let mut pkg_to_lib_crate = FxHashMap::default();
381 let mut pkg_crates = FxHashMap::default();
383 // Add test cfg for non-sysroot crates
384 cfg_options.insert_atom("test".into());
386 // Next, create crates for each package, target pair
387 for pkg in cargo.packages() {
388 let mut lib_tgt = None;
389 for &tgt in cargo[pkg].targets.iter() {
390 let root = cargo[tgt].root.as_path();
391 if let Some(file_id) = load(root) {
392 let edition = cargo[pkg].edition;
394 let mut opts = cfg_options.clone();
395 for feature in cargo[pkg].features.iter() {
396 opts.insert_key_value("feature".into(), feature.into());
398 for cfg in cargo[pkg].cfgs.iter() {
399 match cfg.find('=') {
400 Some(split) => opts.insert_key_value(
402 cfg[split + 1..].trim_matches('"').into(),
404 None => opts.insert_atom(cfg.into()),
409 let mut env = Env::default();
410 let mut extern_source = ExternSource::default();
411 if let Some(out_dir) = &cargo[pkg].out_dir {
412 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
413 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
414 env.set("OUT_DIR", out_dir);
416 if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
417 extern_source.set_extern_path(&out_dir, extern_source_id);
420 let proc_macro = cargo[pkg]
421 .proc_macro_dylib_path
423 .map(|it| proc_macro_client.by_dylib_path(&it))
424 .unwrap_or_default();
426 let crate_id = crate_graph.add_crate_root(
429 Some(CrateName::normalize_dashes(&cargo[pkg].name)),
435 if cargo[tgt].kind == TargetKind::Lib {
436 lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
437 pkg_to_lib_crate.insert(pkg, crate_id);
439 if cargo[tgt].is_proc_macro {
440 if let Some(proc_macro) = libproc_macro {
444 CrateName::new("proc_macro").unwrap(),
450 "cyclic dependency on proc_macro for {}",
457 pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
461 // Set deps to the core, std and to the lib target of the current package
462 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
463 if let Some((to, name)) = lib_tgt.clone() {
468 // For root projects with dashes in their name,
469 // cargo metadata does not do any normalization,
470 // so we do it ourselves currently
471 CrateName::normalize_dashes(&name),
478 "cyclic dependency between targets of {}",
484 // core is added as a dependency before std in order to
485 // mimic rustcs dependency order
486 if let Some(core) = libcore {
488 .add_dep(from, CrateName::new("core").unwrap(), core)
491 log::error!("cyclic dependency on core for {}", &cargo[pkg].name)
494 if let Some(alloc) = liballoc {
496 .add_dep(from, CrateName::new("alloc").unwrap(), alloc)
499 log::error!("cyclic dependency on alloc for {}", &cargo[pkg].name)
502 if let Some(std) = libstd {
504 .add_dep(from, CrateName::new("std").unwrap(), std)
507 log::error!("cyclic dependency on std for {}", &cargo[pkg].name)
513 // Now add a dep edge from all targets of upstream to the lib
514 // target of downstream.
515 for pkg in cargo.packages() {
516 for dep in cargo[pkg].dependencies.iter() {
517 if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
518 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
520 .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
524 "cyclic dependency {} -> {}",
538 pub fn workspace_root_for(&self, path: &Path) -> Option<&Path> {
540 ProjectWorkspace::Cargo { cargo, .. } => {
541 Some(cargo.workspace_root()).filter(|root| path.starts_with(root))
543 ProjectWorkspace::Json { project: JsonProject { roots, .. } } => roots
545 .find(|root| path.starts_with(&root.path))
546 .map(|root| root.path.as_ref()),
551 fn get_rustc_cfg_options(target: Option<&str>) -> CfgOptions {
552 let mut cfg_options = CfgOptions::default();
554 // Some nightly-only cfgs, which are required for stdlib
556 cfg_options.insert_atom("target_thread_local".into());
557 for &target_has_atomic in ["8", "16", "32", "64", "cas", "ptr"].iter() {
558 cfg_options.insert_key_value("target_has_atomic".into(), target_has_atomic.into());
560 .insert_key_value("target_has_atomic_load_store".into(), target_has_atomic.into());
564 let rustc_cfgs = || -> Result<String> {
565 // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
566 let mut cmd = Command::new(ra_toolchain::rustc());
567 cmd.args(&["--print", "cfg", "-O"]);
568 if let Some(target) = target {
569 cmd.args(&["--target", target]);
571 let output = output(cmd)?;
572 Ok(String::from_utf8(output.stdout)?)
577 for line in rustc_cfgs.lines() {
578 match line.find('=') {
579 None => cfg_options.insert_atom(line.into()),
581 let key = &line[..pos];
582 let value = line[pos + 1..].trim_matches('"');
583 cfg_options.insert_key_value(key.into(), value.into());
588 Err(e) => log::error!("failed to get rustc cfgs: {:#}", e),
591 cfg_options.insert_atom("debug_assertions".into());
596 fn output(mut cmd: Command) -> Result<Output> {
597 let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?;
598 if !output.status.success() {
599 match String::from_utf8(output.stderr) {
600 Ok(stderr) if !stderr.is_empty() => {
601 bail!("{:?} failed, {}\nstderr:\n{}", cmd, output.status, stderr)
603 _ => bail!("{:?} failed, {}", cmd, output.status),