]> git.lizzy.rs Git - rust.git/blob - crates/ra_project_model/src/lib.rs
Change management of test cfg to better support json projects
[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 = default_cfg_options.clone();
353
354                         let env = Env::default();
355                         let extern_source = ExternSource::default();
356                         let proc_macro = vec![];
357                         let crate_name = CrateName::new(&sysroot[krate].name)
358                             .expect("Sysroot crate names should not contain dashes");
359
360                         let crate_id = crate_graph.add_crate_root(
361                             file_id,
362                             Edition::Edition2018,
363                             Some(crate_name),
364                             cfg_options,
365                             env,
366                             extern_source,
367                             proc_macro,
368                         );
369                         Some((krate, crate_id))
370                     })
371                     .collect();
372
373                 for from in sysroot.crates() {
374                     for &to in sysroot[from].deps.iter() {
375                         let name = &sysroot[to].name;
376                         if let (Some(&from), Some(&to)) =
377                             (sysroot_crates.get(&from), sysroot_crates.get(&to))
378                         {
379                             if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err()
380                             {
381                                 log::error!("cyclic dependency between sysroot crates")
382                             }
383                         }
384                     }
385                 }
386
387                 let libcore = sysroot.core().and_then(|it| sysroot_crates.get(&it).copied());
388                 let liballoc = sysroot.alloc().and_then(|it| sysroot_crates.get(&it).copied());
389                 let libstd = sysroot.std().and_then(|it| sysroot_crates.get(&it).copied());
390                 let libproc_macro =
391                     sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied());
392
393                 let mut pkg_to_lib_crate = FxHashMap::default();
394                 let mut pkg_crates = FxHashMap::default();
395                 // Next, create crates for each package, target pair
396                 for pkg in cargo.packages() {
397                     let mut lib_tgt = None;
398                     for &tgt in cargo[pkg].targets.iter() {
399                         let root = cargo[tgt].root.as_path();
400                         if let Some(file_id) = load(root) {
401                             let edition = cargo[pkg].edition;
402                             let cfg_options = {
403                                 let mut opts = {
404                                     let mut opts = default_cfg_options.clone();
405                                     opts.insert_atom("test".into());
406                                     opts
407                                 };
408
409                                 for feature in cargo[pkg].features.iter() {
410                                     opts.insert_key_value("feature".into(), feature.into());
411                                 }
412                                 for cfg in cargo[pkg].cfgs.iter() {
413                                     match cfg.find('=') {
414                                         Some(split) => opts.insert_key_value(
415                                             cfg[..split].into(),
416                                             cfg[split + 1..].trim_matches('"').into(),
417                                         ),
418                                         None => opts.insert_atom(cfg.into()),
419                                     };
420                                 }
421                                 opts
422                             };
423                             let mut env = Env::default();
424                             let mut extern_source = ExternSource::default();
425                             if let Some(out_dir) = &cargo[pkg].out_dir {
426                                 // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!()
427                                 if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) {
428                                     env.set("OUT_DIR", out_dir);
429                                 }
430                                 if let Some(&extern_source_id) = extern_source_roots.get(out_dir) {
431                                     extern_source.set_extern_path(&out_dir, extern_source_id);
432                                 }
433                             }
434                             let proc_macro = cargo[pkg]
435                                 .proc_macro_dylib_path
436                                 .as_ref()
437                                 .map(|it| proc_macro_client.by_dylib_path(&it))
438                                 .unwrap_or_default();
439
440                             let crate_id = crate_graph.add_crate_root(
441                                 file_id,
442                                 edition,
443                                 Some(CrateName::normalize_dashes(&cargo[pkg].name)),
444                                 cfg_options,
445                                 env,
446                                 extern_source,
447                                 proc_macro.clone(),
448                             );
449                             if cargo[tgt].kind == TargetKind::Lib {
450                                 lib_tgt = Some((crate_id, cargo[tgt].name.clone()));
451                                 pkg_to_lib_crate.insert(pkg, crate_id);
452                             }
453                             if cargo[tgt].is_proc_macro {
454                                 if let Some(proc_macro) = libproc_macro {
455                                     if crate_graph
456                                         .add_dep(
457                                             crate_id,
458                                             CrateName::new("proc_macro").unwrap(),
459                                             proc_macro,
460                                         )
461                                         .is_err()
462                                     {
463                                         log::error!(
464                                             "cyclic dependency on proc_macro for {}",
465                                             &cargo[pkg].name
466                                         )
467                                     }
468                                 }
469                             }
470
471                             pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id);
472                         }
473                     }
474
475                     // Set deps to the core, std and to the lib target of the current package
476                     for &from in pkg_crates.get(&pkg).into_iter().flatten() {
477                         if let Some((to, name)) = lib_tgt.clone() {
478                             if to != from
479                                 && crate_graph
480                                     .add_dep(
481                                         from,
482                                         // For root projects with dashes in their name,
483                                         // cargo metadata does not do any normalization,
484                                         // so we do it ourselves currently
485                                         CrateName::normalize_dashes(&name),
486                                         to,
487                                     )
488                                     .is_err()
489                             {
490                                 {
491                                     log::error!(
492                                         "cyclic dependency between targets of {}",
493                                         &cargo[pkg].name
494                                     )
495                                 }
496                             }
497                         }
498                         // core is added as a dependency before std in order to
499                         // mimic rustcs dependency order
500                         if let Some(core) = libcore {
501                             if crate_graph
502                                 .add_dep(from, CrateName::new("core").unwrap(), core)
503                                 .is_err()
504                             {
505                                 log::error!("cyclic dependency on core for {}", &cargo[pkg].name)
506                             }
507                         }
508                         if let Some(alloc) = liballoc {
509                             if crate_graph
510                                 .add_dep(from, CrateName::new("alloc").unwrap(), alloc)
511                                 .is_err()
512                             {
513                                 log::error!("cyclic dependency on alloc for {}", &cargo[pkg].name)
514                             }
515                         }
516                         if let Some(std) = libstd {
517                             if crate_graph
518                                 .add_dep(from, CrateName::new("std").unwrap(), std)
519                                 .is_err()
520                             {
521                                 log::error!("cyclic dependency on std for {}", &cargo[pkg].name)
522                             }
523                         }
524                     }
525                 }
526
527                 // Now add a dep edge from all targets of upstream to the lib
528                 // target of downstream.
529                 for pkg in cargo.packages() {
530                     for dep in cargo[pkg].dependencies.iter() {
531                         if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
532                             for &from in pkg_crates.get(&pkg).into_iter().flatten() {
533                                 if crate_graph
534                                     .add_dep(from, CrateName::new(&dep.name).unwrap(), to)
535                                     .is_err()
536                                 {
537                                     log::error!(
538                                         "cyclic dependency {} -> {}",
539                                         &cargo[pkg].name,
540                                         &cargo[dep.pkg].name
541                                     )
542                                 }
543                             }
544                         }
545                     }
546                 }
547             }
548         }
549         crate_graph
550     }
551
552     pub fn workspace_root_for(&self, path: &Path) -> Option<&Path> {
553         match self {
554             ProjectWorkspace::Cargo { cargo, .. } => {
555                 Some(cargo.workspace_root()).filter(|root| path.starts_with(root))
556             }
557             ProjectWorkspace::Json { project: JsonProject { roots, .. } } => roots
558                 .iter()
559                 .find(|root| path.starts_with(&root.path))
560                 .map(|root| root.path.as_ref()),
561         }
562     }
563 }
564
565 pub fn get_rustc_cfg_options(target: Option<&String>) -> CfgOptions {
566     let mut cfg_options = CfgOptions::default();
567
568     // Some nightly-only cfgs, which are required for stdlib
569     {
570         cfg_options.insert_atom("target_thread_local".into());
571         for &target_has_atomic in ["8", "16", "32", "64", "cas", "ptr"].iter() {
572             cfg_options.insert_key_value("target_has_atomic".into(), target_has_atomic.into());
573             cfg_options
574                 .insert_key_value("target_has_atomic_load_store".into(), target_has_atomic.into());
575         }
576     }
577
578     let rustc_cfgs = || -> Result<String> {
579         // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here.
580         let mut cmd = Command::new(ra_toolchain::rustc());
581         cmd.args(&["--print", "cfg", "-O"]);
582         if let Some(target) = target {
583             cmd.args(&["--target", target.as_str()]);
584         }
585         let output = output(cmd)?;
586         Ok(String::from_utf8(output.stdout)?)
587     }();
588
589     match rustc_cfgs {
590         Ok(rustc_cfgs) => {
591             for line in rustc_cfgs.lines() {
592                 match line.find('=') {
593                     None => cfg_options.insert_atom(line.into()),
594                     Some(pos) => {
595                         let key = &line[..pos];
596                         let value = line[pos + 1..].trim_matches('"');
597                         cfg_options.insert_key_value(key.into(), value.into());
598                     }
599                 }
600             }
601         }
602         Err(e) => log::error!("failed to get rustc cfgs: {:#}", e),
603     }
604
605     cfg_options
606 }
607
608 fn output(mut cmd: Command) -> Result<Output> {
609     let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?;
610     if !output.status.success() {
611         match String::from_utf8(output.stderr) {
612             Ok(stderr) if !stderr.is_empty() => {
613                 bail!("{:?} failed, {}\nstderr:\n{}", cmd, output.status, stderr)
614             }
615             _ => bail!("{:?} failed, {}", cmd, output.status),
616         }
617     }
618     Ok(output)
619 }