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