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