]> git.lizzy.rs Git - rust.git/blob - crates/ra_project_model/src/lib.rs
Simpify workspace handling
[rust.git] / crates / ra_project_model / src / lib.rs
1 //! FIXME: write short doc here
2
3 mod cargo_workspace;
4 mod json_project;
5 mod sysroot;
6
7 use std::{
8     error::Error,
9     fs::{read_dir, File, ReadDir},
10     io::BufReader,
11     path::{Path, PathBuf},
12     process::Command,
13 };
14
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;
20
21 pub use crate::{
22     cargo_workspace::{CargoConfig, CargoWorkspace, Package, Target, TargetKind},
23     json_project::JsonProject,
24     sysroot::Sysroot,
25 };
26 pub use ra_proc_macro::ProcMacroClient;
27
28 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
29 pub struct CargoTomlNotFoundError {
30     pub searched_at: PathBuf,
31     pub reason: String,
32 }
33
34 impl std::fmt::Display for CargoTomlNotFoundError {
35     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36         write!(
37             fmt,
38             "can't find Cargo.toml at {}, due to {}",
39             self.searched_at.display(),
40             self.reason
41         )
42     }
43 }
44
45 impl Error for CargoTomlNotFoundError {}
46
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 },
53 }
54
55 /// `PackageRoot` describes a package root folder.
56 /// Which may be an external dependency, or a member of
57 /// the current workspace.
58 #[derive(Clone)]
59 pub struct PackageRoot {
60     /// Path to the root folder
61     pub path: PathBuf,
62     /// Is a member of the current workspace
63     pub is_member: bool,
64 }
65 impl PackageRoot {
66     pub fn new_member(path: PathBuf) -> PackageRoot {
67         Self { path, is_member: true }
68     }
69     pub fn new_non_member(path: PathBuf) -> PackageRoot {
70         Self { path, is_member: false }
71     }
72 }
73
74 impl ProjectWorkspace {
75     pub fn discover(path: &Path, cargo_features: &CargoConfig) -> Result<ProjectWorkspace> {
76         ProjectWorkspace::discover_with_sysroot(path, true, cargo_features)
77     }
78
79     pub fn discover_with_sysroot(
80         path: &Path,
81         with_sysroot: bool,
82         cargo_features: &CargoConfig,
83     ) -> Result<ProjectWorkspace> {
84         match find_rust_project_json(path) {
85             Some(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())
92                     })?,
93                 })
94             }
95             None => {
96                 let cargo_toml = find_cargo_toml(path).with_context(|| {
97                     format!("Failed to find Cargo.toml for path {}", path.display())
98                 })?;
99                 let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml, cargo_features)
100                     .with_context(|| {
101                         format!(
102                             "Failed to read Cargo metadata from Cargo.toml file {}",
103                             cargo_toml.display()
104                         )
105                     })?;
106                 let sysroot = if with_sysroot {
107                     Sysroot::discover(&cargo_toml).with_context(|| {
108                         format!(
109                             "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?",
110                             cargo_toml.display()
111                         )
112                     })?
113                 } else {
114                     Sysroot::default()
115                 };
116                 Ok(ProjectWorkspace::Cargo { cargo, sysroot })
117             }
118         }
119     }
120
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> {
125         match self {
126             ProjectWorkspace::Json { project } => {
127                 project.roots.iter().map(|r| PackageRoot::new_member(r.path.clone())).collect()
128             }
129             ProjectWorkspace::Cargo { cargo, sysroot } => cargo
130                 .packages()
131                 .map(|pkg| PackageRoot {
132                     path: cargo[pkg].root().to_path_buf(),
133                     is_member: cargo[pkg].is_member,
134                 })
135                 .chain(sysroot.crates().map(|krate| {
136                     PackageRoot::new_non_member(sysroot[krate].root_dir().to_path_buf())
137                 }))
138                 .collect(),
139         }
140     }
141
142     pub fn out_dirs(&self) -> Vec<PathBuf> {
143         match self {
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());
149                     }
150                 }
151                 out_dirs
152             }
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());
158                     }
159                 }
160                 out_dirs
161             }
162         }
163     }
164
165     pub fn proc_macro_dylib_paths(&self) -> Vec<PathBuf> {
166         match self {
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());
172                     }
173                 }
174                 proc_macro_dylib_paths
175             }
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());
181                     }
182                 }
183                 proc_macro_dylib_paths
184             }
185         }
186     }
187
188     pub fn n_packages(&self) -> usize {
189         match self {
190             ProjectWorkspace::Json { project } => project.crates.len(),
191             ProjectWorkspace::Cargo { cargo, sysroot } => {
192                 cargo.packages().len() + sysroot.crates().len()
193             }
194         }
195     }
196
197     pub fn to_crate_graph(
198         &self,
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>,
203     ) -> CrateGraph {
204         let mut crate_graph = CrateGraph::default();
205         match self {
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,
214                         };
215                         let cfg_options = {
216                             let mut opts = default_cfg_options.clone();
217                             for name in &krate.atom_cfgs {
218                                 opts.insert_atom(name.into());
219                             }
220                             for (key, value) in &krate.key_value_cfgs {
221                                 opts.insert_key_value(key.into(), value.into());
222                             }
223                             opts
224                         };
225
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);
233                             }
234                         }
235                         let proc_macro = krate
236                             .proc_macro_dylib_path
237                             .clone()
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
240                         crates.insert(
241                             crate_id,
242                             crate_graph.add_crate_root(
243                                 file_id,
244                                 edition,
245                                 // FIXME json definitions can store the crate name
246                                 None,
247                                 cfg_options,
248                                 env,
249                                 extern_source,
250                                 proc_macro.unwrap_or_default(),
251                             ),
252                         );
253                     }
254                 }
255
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))
262                         {
263                             if crate_graph
264                                 .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
265                                 .is_err()
266                             {
267                                 log::error!(
268                                     "cyclic dependency {:?} -> {:?}",
269                                     from_crate_id,
270                                     to_crate_id
271                                 );
272                             }
273                         }
274                     }
275                 }
276             }
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
282                         let cfg_options = {
283                             let mut opts = default_cfg_options.clone();
284                             opts.remove_atom("test");
285                             opts
286                         };
287
288                         let env = Env::default();
289                         let extern_source = ExternSource::default();
290                         let proc_macro = vec![];
291
292                         let crate_id = crate_graph.add_crate_root(
293                             file_id,
294                             Edition::Edition2018,
295                             Some(
296                                 CrateName::new(&sysroot[krate].name)
297                                     .expect("Sysroot crate names should not contain dashes"),
298                             ),
299                             cfg_options,
300                             env,
301                             extern_source,
302                             proc_macro,
303                         );
304                         sysroot_crates.insert(krate, crate_id);
305                     }
306                 }
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))
312                         {
313                             if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err()
314                             {
315                                 log::error!("cyclic dependency between sysroot crates")
316                             }
317                         }
318                     }
319                 }
320
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());
324                 let libproc_macro =
325                     sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
326
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;
336                             let cfg_options = {
337                                 let mut opts = default_cfg_options.clone();
338                                 opts.insert_features(cargo[pkg].features.iter().map(Into::into));
339                                 opts
340                             };
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);
348                                 }
349                             }
350                             let proc_macro = cargo[pkg]
351                                 .proc_macro_dylib_path
352                                 .as_ref()
353                                 .map(|it| proc_macro_client.by_dylib_path(&it))
354                                 .unwrap_or_default();
355
356                             let crate_id = crate_graph.add_crate_root(
357                                 file_id,
358                                 edition,
359                                 Some(CrateName::normalize_dashes(&cargo[pkg].name)),
360                                 cfg_options,
361                                 env,
362                                 extern_source,
363                                 proc_macro.clone(),
364                             );
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);
368                             }
369                             if cargo[tgt].is_proc_macro {
370                                 if let Some(proc_macro) = libproc_macro {
371                                     if crate_graph
372                                         .add_dep(
373                                             crate_id,
374                                             CrateName::new("proc_macro").unwrap(),
375                                             proc_macro,
376                                         )
377                                         .is_err()
378                                     {
379                                         log::error!(
380                                             "cyclic dependency on proc_macro for {}",
381                                             &cargo[pkg].name
382                                         )
383                                     }
384                                 }
385                             }
386
387                             pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
388                         }
389                     }
390
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() {
394                             if to != from
395                                 && crate_graph
396                                     .add_dep(
397                                         from,
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),
402                                         to,
403                                     )
404                                     .is_err()
405                             {
406                                 {
407                                     log::error!(
408                                         "cyclic dependency between targets of {}",
409                                         &cargo[pkg].name
410                                     )
411                                 }
412                             }
413                         }
414                         // core is added as a dependency before std in order to
415                         // mimic rustcs dependency order
416                         if let Some(core) = libcore {
417                             if crate_graph
418                                 .add_dep(from, CrateName::new("core").unwrap(), core)
419                                 .is_err()
420                             {
421                                 log::error!("cyclic dependency on core for {}", &cargo[pkg].name)
422                             }
423                         }
424                         if let Some(alloc) = liballoc {
425                             if crate_graph
426                                 .add_dep(from, CrateName::new("alloc").unwrap(), alloc)
427                                 .is_err()
428                             {
429                                 log::error!("cyclic dependency on alloc for {}", &cargo[pkg].name)
430                             }
431                         }
432                         if let Some(std) = libstd {
433                             if crate_graph
434                                 .add_dep(from, CrateName::new("std").unwrap(), std)
435                                 .is_err()
436                             {
437                                 log::error!("cyclic dependency on std for {}", &cargo[pkg].name)
438                             }
439                         }
440                     }
441                 }
442
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() {
449                                 if crate_graph
450                                     .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
451                                     .is_err()
452                                 {
453                                     log::error!(
454                                         "cyclic dependency {} -> {}",
455                                         &cargo[pkg].name,
456                                         &cargo[dep.pkg].name
457                                     )
458                                 }
459                             }
460                         }
461                     }
462                 }
463             }
464         }
465         crate_graph
466     }
467
468     pub fn workspace_root_for(&self, path: &Path) -> Option<&Path> {
469         match self {
470             ProjectWorkspace::Cargo { cargo, .. } => {
471                 Some(cargo.workspace_root()).filter(|root| path.starts_with(root))
472             }
473             ProjectWorkspace::Json { project: JsonProject { roots, .. } } => roots
474                 .iter()
475                 .find(|root| path.starts_with(&root.path))
476                 .map(|root| root.path.as_ref()),
477         }
478     }
479 }
480
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());
484     }
485
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);
491         }
492         curr = path.parent();
493     }
494
495     None
496 }
497
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);
504         }
505         curr = path.parent();
506     }
507
508     None
509 }
510
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)
518         }
519     }
520     valid_canditates
521 }
522
523 fn find_cargo_toml(path: &Path) -> Result<PathBuf> {
524     if path.ends_with("Cargo.toml") {
525         return Ok(path.to_path_buf());
526     }
527
528     if let Some(p) = find_cargo_toml_in_parent_dir(path) {
529         return Ok(p);
530     }
531
532     let entities = match read_dir(path) {
533         Ok(entities) => entities,
534         Err(e) => {
535             return Err(CargoTomlNotFoundError {
536                 searched_at: path.to_path_buf(),
537                 reason: format!("file system error: {}", e),
538             }
539             .into());
540         }
541     };
542
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(),
549         }
550         .into()),
551         _ => Err(CargoTomlNotFoundError {
552             searched_at: path.to_path_buf(),
553             reason: format!(
554                 "multiple equally valid Cargo.toml files found: {:?}",
555                 valid_canditates
556             ),
557         }
558         .into()),
559     }
560 }
561
562 pub fn get_rustc_cfg_options() -> CfgOptions {
563     let mut cfg_options = CfgOptions::default();
564
565     // Some nightly-only cfgs, which are required for stdlib
566     {
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());
570             cfg_options
571                 .insert_key_value("target_has_atomic_load_store".into(), target_has_atomic.into());
572         }
573     }
574
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"])
579             .output()
580             .context("Failed to get output from rustc --print cfg -O")?;
581         if !output.status.success() {
582             bail!(
583                 "rustc --print cfg -O exited with exit code ({})",
584                 output
585                     .status
586                     .code()
587                     .map_or(String::from("no exit code"), |code| format!("{}", code))
588             );
589         }
590         Ok(String::from_utf8(output.stdout)?)
591     })() {
592         Ok(rustc_cfgs) => {
593             for line in rustc_cfgs.lines() {
594                 match line.find('=') {
595                     None => cfg_options.insert_atom(line.into()),
596                     Some(pos) => {
597                         let key = &line[..pos];
598                         let value = line[pos + 1..].trim_matches('"');
599                         cfg_options.insert_key_value(key.into(), value.into());
600                     }
601                 }
602             }
603         }
604         Err(e) => log::error!("failed to get rustc cfgs: {}", e),
605     }
606
607     cfg_options
608 }