]> git.lizzy.rs Git - rust.git/blob - crates/ra_project_model/src/lib.rs
Migrate to privacy as per review commets
[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     path: PathBuf,
62     /// Is a member of the current workspace
63     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     pub fn path(&self) -> &Path {
73         &self.path
74     }
75     pub fn is_member(&self) -> bool {
76         self.is_member
77     }
78 }
79
80 impl ProjectWorkspace {
81     pub fn discover(path: &Path, cargo_features: &CargoConfig) -> Result<ProjectWorkspace> {
82         ProjectWorkspace::discover_with_sysroot(path, true, cargo_features)
83     }
84
85     pub fn discover_with_sysroot(
86         path: &Path,
87         with_sysroot: bool,
88         cargo_features: &CargoConfig,
89     ) -> Result<ProjectWorkspace> {
90         match find_rust_project_json(path) {
91             Some(json_path) => {
92                 let file = File::open(&json_path)
93                     .with_context(|| format!("Failed to open json file {}", json_path.display()))?;
94                 let reader = BufReader::new(file);
95                 Ok(ProjectWorkspace::Json {
96                     project: from_reader(reader).with_context(|| {
97                         format!("Failed to deserialize json file {}", json_path.display())
98                     })?,
99                 })
100             }
101             None => {
102                 let cargo_toml = find_cargo_toml(path).with_context(|| {
103                     format!("Failed to find Cargo.toml for path {}", path.display())
104                 })?;
105                 let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml, cargo_features)
106                     .with_context(|| {
107                         format!(
108                             "Failed to read Cargo metadata from Cargo.toml file {}",
109                             cargo_toml.display()
110                         )
111                     })?;
112                 let sysroot = if with_sysroot {
113                     Sysroot::discover(&cargo_toml).with_context(|| {
114                         format!(
115                             "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?",
116                             cargo_toml.display()
117                         )
118                     })?
119                 } else {
120                     Sysroot::default()
121                 };
122                 Ok(ProjectWorkspace::Cargo { cargo, sysroot })
123             }
124         }
125     }
126
127     /// Returns the roots for the current `ProjectWorkspace`
128     /// The return type contains the path and whether or not
129     /// the root is a member of the current workspace
130     pub fn to_roots(&self) -> Vec<PackageRoot> {
131         match self {
132             ProjectWorkspace::Json { project } => {
133                 project.roots.iter().map(|r| PackageRoot::new_member(r.path.clone())).collect()
134             }
135             ProjectWorkspace::Cargo { cargo, sysroot } => cargo
136                 .packages()
137                 .map(|pkg| PackageRoot {
138                     path: cargo[pkg].root().to_path_buf(),
139                     is_member: cargo[pkg].is_member,
140                 })
141                 .chain(sysroot.crates().map(|krate| {
142                     PackageRoot::new_non_member(sysroot[krate].root_dir().to_path_buf())
143                 }))
144                 .collect(),
145         }
146     }
147
148     pub fn out_dirs(&self) -> Vec<PathBuf> {
149         match self {
150             ProjectWorkspace::Json { project } => {
151                 project.crates.iter().filter_map(|krate| krate.out_dir.as_ref()).cloned().collect()
152             }
153             ProjectWorkspace::Cargo { cargo, sysroot: _ } => {
154                 cargo.packages().filter_map(|pkg| cargo[pkg].out_dir.as_ref()).cloned().collect()
155             }
156         }
157     }
158
159     pub fn proc_macro_dylib_paths(&self) -> Vec<PathBuf> {
160         match self {
161             ProjectWorkspace::Json { project } => project
162                 .crates
163                 .iter()
164                 .filter_map(|krate| krate.proc_macro_dylib_path.as_ref())
165                 .cloned()
166                 .collect(),
167             ProjectWorkspace::Cargo { cargo, sysroot: _sysroot } => cargo
168                 .packages()
169                 .filter_map(|pkg| cargo[pkg].proc_macro_dylib_path.as_ref())
170                 .cloned()
171                 .collect(),
172         }
173     }
174
175     pub fn n_packages(&self) -> usize {
176         match self {
177             ProjectWorkspace::Json { project } => project.crates.len(),
178             ProjectWorkspace::Cargo { cargo, sysroot } => {
179                 cargo.packages().len() + sysroot.crates().len()
180             }
181         }
182     }
183
184     pub fn to_crate_graph(
185         &self,
186         default_cfg_options: &CfgOptions,
187         extern_source_roots: &FxHashMap<PathBuf, ExternSourceId>,
188         proc_macro_client: &ProcMacroClient,
189         load: &mut dyn FnMut(&Path) -> Option<FileId>,
190     ) -> CrateGraph {
191         let mut crate_graph = CrateGraph::default();
192         match self {
193             ProjectWorkspace::Json { project } => {
194                 let crates: FxHashMap<_, _> = project
195                     .crates
196                     .iter()
197                     .enumerate()
198                     .filter_map(|(seq_index, krate)| {
199                         let file_id = load(&krate.root_module)?;
200                         let edition = match krate.edition {
201                             json_project::Edition::Edition2015 => Edition::Edition2015,
202                             json_project::Edition::Edition2018 => Edition::Edition2018,
203                         };
204                         let cfg_options = {
205                             let mut opts = default_cfg_options.clone();
206                             for name in &krate.atom_cfgs {
207                                 opts.insert_atom(name.into());
208                             }
209                             for (key, value) in &krate.key_value_cfgs {
210                                 opts.insert_key_value(key.into(), value.into());
211                             }
212                             opts
213                         };
214
215                         let mut env = Env::default();
216                         let mut extern_source = ExternSource::default();
217                         if let Some(out_dir) = &krate.out_dir {
218                             // FIXME: We probably mangle non UTF-8 paths here, figure out a better solution
219                             env.set("OUT_DIR", out_dir.to_string_lossy().to_string());
220                             if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
221                                 extern_source.set_extern_path(&out_dir, extern_source_id);
222                             }
223                         }
224                         let proc_macro = krate
225                             .proc_macro_dylib_path
226                             .clone()
227                             .map(|it| proc_macro_client.by_dylib_path(&it));
228                         // FIXME: No crate name in json definition such that we cannot add OUT_DIR to env
229                         Some((
230                             json_project::CrateId(seq_index),
231                             crate_graph.add_crate_root(
232                                 file_id,
233                                 edition,
234                                 // FIXME json definitions can store the crate name
235                                 None,
236                                 cfg_options,
237                                 env,
238                                 extern_source,
239                                 proc_macro.unwrap_or_default(),
240                             ),
241                         ))
242                     })
243                     .collect();
244
245                 for (id, krate) in project.crates.iter().enumerate() {
246                     for dep in &krate.deps {
247                         let from_crate_id = json_project::CrateId(id);
248                         let to_crate_id = dep.krate;
249                         if let (Some(&from), Some(&to)) =
250                             (crates.get(&from_crate_id), crates.get(&to_crate_id))
251                         {
252                             if crate_graph
253                                 .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
254                                 .is_err()
255                             {
256                                 log::error!(
257                                     "cyclic dependency {:?} -> {:?}",
258                                     from_crate_id,
259                                     to_crate_id
260                                 );
261                             }
262                         }
263                     }
264                 }
265             }
266             ProjectWorkspace::Cargo { cargo, sysroot } => {
267                 let sysroot_crates: FxHashMap<_, _> = sysroot
268                     .crates()
269                     .filter_map(|krate| {
270                         let file_id = load(&sysroot[krate].root)?;
271
272                         // Crates from sysroot have `cfg(test)` disabled
273                         let cfg_options = {
274                             let mut opts = default_cfg_options.clone();
275                             opts.remove_atom("test");
276                             opts
277                         };
278
279                         let env = Env::default();
280                         let extern_source = ExternSource::default();
281                         let proc_macro = vec![];
282                         let crate_name = CrateName::new(&sysroot[krate].name)
283                             .expect("Sysroot crate names should not contain dashes");
284
285                         let crate_id = crate_graph.add_crate_root(
286                             file_id,
287                             Edition::Edition2018,
288                             Some(crate_name),
289                             cfg_options,
290                             env,
291                             extern_source,
292                             proc_macro,
293                         );
294                         Some((krate, crate_id))
295                     })
296                     .collect();
297
298                 for from in sysroot.crates() {
299                     for &to in sysroot[from].deps.iter() {
300                         let name = &sysroot[to].name;
301                         if let (Some(&from), Some(&to)) =
302                             (sysroot_crates.get(&from), sysroot_crates.get(&to))
303                         {
304                             if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err()
305                             {
306                                 log::error!("cyclic dependency between sysroot crates")
307                             }
308                         }
309                     }
310                 }
311
312                 let libcore = sysroot.core().and_then(|it| sysroot_crates.get(&it).copied());
313                 let liballoc = sysroot.alloc().and_then(|it| sysroot_crates.get(&it).copied());
314                 let libstd = sysroot.std().and_then(|it| sysroot_crates.get(&it).copied());
315                 let libproc_macro =
316                     sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
317
318                 let mut pkg_to_lib_crate = FxHashMap::default();
319                 let mut pkg_crates = FxHashMap::default();
320                 // Next, create crates for each package, target pair
321                 for pkg in cargo.packages() {
322                     let mut lib_tgt = None;
323                     for &tgt in cargo[pkg].targets.iter() {
324                         let root = cargo[tgt].root.as_path();
325                         if let Some(file_id) = load(root) {
326                             let edition = cargo[pkg].edition;
327                             let cfg_options = {
328                                 let mut opts = default_cfg_options.clone();
329                                 opts.insert_features(cargo[pkg].features.iter().map(Into::into));
330                                 opts
331                             };
332                             let mut env = Env::default();
333                             let mut extern_source = ExternSource::default();
334                             if let Some(out_dir) = &cargo[pkg].out_dir {
335                                 // FIXME: We probably mangle non UTF-8 paths here, figure out a better solution
336                                 env.set("OUT_DIR", out_dir.to_string_lossy().to_string());
337                                 if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
338                                     extern_source.set_extern_path(&out_dir, extern_source_id);
339                                 }
340                             }
341                             let proc_macro = cargo[pkg]
342                                 .proc_macro_dylib_path
343                                 .as_ref()
344                                 .map(|it| proc_macro_client.by_dylib_path(&it))
345                                 .unwrap_or_default();
346
347                             let crate_id = crate_graph.add_crate_root(
348                                 file_id,
349                                 edition,
350                                 Some(CrateName::normalize_dashes(&cargo[pkg].name)),
351                                 cfg_options,
352                                 env,
353                                 extern_source,
354                                 proc_macro.clone(),
355                             );
356                             if cargo[tgt].kind == TargetKind::Lib {
357                                 lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
358                                 pkg_to_lib_crate.insert(pkg, crate_id);
359                             }
360                             if cargo[tgt].is_proc_macro {
361                                 if let Some(proc_macro) = libproc_macro {
362                                     if crate_graph
363                                         .add_dep(
364                                             crate_id,
365                                             CrateName::new("proc_macro").unwrap(),
366                                             proc_macro,
367                                         )
368                                         .is_err()
369                                     {
370                                         log::error!(
371                                             "cyclic dependency on proc_macro for {}",
372                                             &cargo[pkg].name
373                                         )
374                                     }
375                                 }
376                             }
377
378                             pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
379                         }
380                     }
381
382                     // Set deps to the core, std and to the lib target of the current package
383                     for &from in pkg_crates.get(&pkg).into_iter().flatten() {
384                         if let Some((to, name)) = lib_tgt.clone() {
385                             if to != from
386                                 && crate_graph
387                                     .add_dep(
388                                         from,
389                                         // For root projects with dashes in their name,
390                                         // cargo metadata does not do any normalization,
391                                         // so we do it ourselves currently
392                                         CrateName::normalize_dashes(&name),
393                                         to,
394                                     )
395                                     .is_err()
396                             {
397                                 {
398                                     log::error!(
399                                         "cyclic dependency between targets of {}",
400                                         &cargo[pkg].name
401                                     )
402                                 }
403                             }
404                         }
405                         // core is added as a dependency before std in order to
406                         // mimic rustcs dependency order
407                         if let Some(core) = libcore {
408                             if crate_graph
409                                 .add_dep(from, CrateName::new("core").unwrap(), core)
410                                 .is_err()
411                             {
412                                 log::error!("cyclic dependency on core for {}", &cargo[pkg].name)
413                             }
414                         }
415                         if let Some(alloc) = liballoc {
416                             if crate_graph
417                                 .add_dep(from, CrateName::new("alloc").unwrap(), alloc)
418                                 .is_err()
419                             {
420                                 log::error!("cyclic dependency on alloc for {}", &cargo[pkg].name)
421                             }
422                         }
423                         if let Some(std) = libstd {
424                             if crate_graph
425                                 .add_dep(from, CrateName::new("std").unwrap(), std)
426                                 .is_err()
427                             {
428                                 log::error!("cyclic dependency on std for {}", &cargo[pkg].name)
429                             }
430                         }
431                     }
432                 }
433
434                 // Now add a dep edge from all targets of upstream to the lib
435                 // target of downstream.
436                 for pkg in cargo.packages() {
437                     for dep in cargo[pkg].dependencies.iter() {
438                         if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
439                             for &from in pkg_crates.get(&pkg).into_iter().flatten() {
440                                 if crate_graph
441                                     .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
442                                     .is_err()
443                                 {
444                                     log::error!(
445                                         "cyclic dependency {} -> {}",
446                                         &cargo[pkg].name,
447                                         &cargo[dep.pkg].name
448                                     )
449                                 }
450                             }
451                         }
452                     }
453                 }
454             }
455         }
456         crate_graph
457     }
458
459     pub fn workspace_root_for(&self, path: &Path) -> Option<&Path> {
460         match self {
461             ProjectWorkspace::Cargo { cargo, .. } => {
462                 Some(cargo.workspace_root()).filter(|root| path.starts_with(root))
463             }
464             ProjectWorkspace::Json { project: JsonProject { roots, .. } } => roots
465                 .iter()
466                 .find(|root| path.starts_with(&root.path))
467                 .map(|root| root.path.as_ref()),
468         }
469     }
470 }
471
472 fn find_rust_project_json(path: &Path) -> Option<PathBuf> {
473     if path.ends_with("rust-project.json") {
474         return Some(path.to_path_buf());
475     }
476
477     let mut curr = Some(path);
478     while let Some(path) = curr {
479         let candidate = path.join("rust-project.json");
480         if candidate.exists() {
481             return Some(candidate);
482         }
483         curr = path.parent();
484     }
485
486     None
487 }
488
489 fn find_cargo_toml_in_parent_dir(path: &Path) -> Option<PathBuf> {
490     let mut curr = Some(path);
491     while let Some(path) = curr {
492         let candidate = path.join("Cargo.toml");
493         if candidate.exists() {
494             return Some(candidate);
495         }
496         curr = path.parent();
497     }
498
499     None
500 }
501
502 fn find_cargo_toml_in_child_dir(entities: ReadDir) -> Vec<PathBuf> {
503     // Only one level down to avoid cycles the easy way and stop a runaway scan with large projects
504     let mut valid_canditates = vec![];
505     for entity in entities.filter_map(Result::ok) {
506         let candidate = entity.path().join("Cargo.toml");
507         if candidate.exists() {
508             valid_canditates.push(candidate)
509         }
510     }
511     valid_canditates
512 }
513
514 fn find_cargo_toml(path: &Path) -> Result<PathBuf> {
515     if path.ends_with("Cargo.toml") {
516         return Ok(path.to_path_buf());
517     }
518
519     if let Some(p) = find_cargo_toml_in_parent_dir(path) {
520         return Ok(p);
521     }
522
523     let entities = match read_dir(path) {
524         Ok(entities) => entities,
525         Err(e) => {
526             return Err(CargoTomlNotFoundError {
527                 searched_at: path.to_path_buf(),
528                 reason: format!("file system error: {}", e),
529             }
530             .into());
531         }
532     };
533
534     let mut valid_canditates = find_cargo_toml_in_child_dir(entities);
535     match valid_canditates.len() {
536         1 => Ok(valid_canditates.remove(0)),
537         0 => Err(CargoTomlNotFoundError {
538             searched_at: path.to_path_buf(),
539             reason: "no Cargo.toml file found".to_string(),
540         }
541         .into()),
542         _ => Err(CargoTomlNotFoundError {
543             searched_at: path.to_path_buf(),
544             reason: format!(
545                 "multiple equally valid Cargo.toml files found: {:?}",
546                 valid_canditates
547             ),
548         }
549         .into()),
550     }
551 }
552
553 pub fn get_rustc_cfg_options() -> CfgOptions {
554     let mut cfg_options = CfgOptions::default();
555
556     // Some nightly-only cfgs, which are required for stdlib
557     {
558         cfg_options.insert_atom("target_thread_local".into());
559         for &target_has_atomic in ["8", "16", "32", "64", "cas", "ptr"].iter() {
560             cfg_options.insert_key_value("target_has_atomic".into(), target_has_atomic.into());
561             cfg_options
562                 .insert_key_value("target_has_atomic_load_store".into(), target_has_atomic.into());
563         }
564     }
565
566     match (|| -> Result<String> {
567         // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
568         let output = Command::new("rustc")
569             .args(&["--print", "cfg", "-O"])
570             .output()
571             .context("Failed to get output from rustc --print cfg -O")?;
572         if !output.status.success() {
573             bail!(
574                 "rustc --print cfg -O exited with exit code ({})",
575                 output
576                     .status
577                     .code()
578                     .map_or(String::from("no exit code"), |code| format!("{}", code))
579             );
580         }
581         Ok(String::from_utf8(output.stdout)?)
582     })() {
583         Ok(rustc_cfgs) => {
584             for line in rustc_cfgs.lines() {
585                 match line.find('=') {
586                     None => cfg_options.insert_atom(line.into()),
587                     Some(pos) => {
588                         let key = &line[..pos];
589                         let value = line[pos + 1..].trim_matches('"');
590                         cfg_options.insert_key_value(key.into(), value.into());
591                     }
592                 }
593             }
594         }
595         Err(e) => log::error!("failed to get rustc cfgs: {}", e),
596     }
597
598     cfg_options
599 }