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