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